Skip to content

feat: automate snapshot creation and scheduling#4938

Open
HarshitVerma109 wants to merge 2 commits into
OWASP:feature/community-snapshotsfrom
HarshitVerma109:feature/automate-snapshots
Open

feat: automate snapshot creation and scheduling#4938
HarshitVerma109 wants to merge 2 commits into
OWASP:feature/community-snapshotsfrom
HarshitVerma109:feature/automate-snapshots

Conversation

@HarshitVerma109

Copy link
Copy Markdown
Collaborator

Proposed change

Resolves #4744

This PR fully automates the OWASP snapshot lifecycle so we no longer have to create them manually through the admin panel. It safely calculates the correct date ranges, prevents duplicate entries, and schedules the entire pipeline to run completely on its own every Monday morning.

Checklist

  • Required: I followed the contributing workflow
  • Required: I verified that my code works as intended and resolves the issue as described
  • Required: I ran make check-test locally: all warnings addressed, tests passed
  • I used AI for code, documentation, tests, or communication related to this PR

@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Summary by CodeRabbit

  • New Features
    • Added an owasp-create-snapshot management command to generate OWASP snapshots on a weekly or monthly cadence (default: weekly) with duplicate detection to prevent re-creation.
    • Introduced scheduled automation to run snapshot creation and subsequent processing via a new ECS task, including configurable CPU/memory sizing.
  • Tests
    • Added unit tests for weekly/monthly date ranges, key/title generation, snapshot creation, and duplicate-skip behavior.
  • Documentation
    • Updated the tasks module documentation with the new create-snapshot task and optional CPU/memory inputs.

Walkthrough

Adds a snapshot creation command, a Makefile target, unit tests for the command flow, and Terraform changes that schedule the task in ECS.

Changes

Snapshot Creation Automation

Layer / File(s) Summary
owasp_create_snapshot management command
backend/apps/owasp/management/commands/owasp_create_snapshot.py
New Command class implements add_arguments, handle, calculate_date_range, generate_key, and generate_title. It computes weekly or monthly UTC windows, skips duplicate keys, and creates a PENDING Snapshot record.
Makefile owasp-create-snapshot
backend/apps/owasp/Makefile
Adds SNAPSHOT_FREQUENCY ?= weekly and an owasp-create-snapshot target that invokes the management command through exec-backend-command with --frequency $(SNAPSHOT_FREQUENCY).
Unit tests for Command, date helpers, key/title generation
backend/tests/unit/apps/owasp/management/commands/owasp_create_snapshot_test.py
Tests weekly and monthly handle() paths, duplicate detection, calculate_date_range(), generate_key(), and generate_title() with mocked time and known inputs.
Terraform ECS scheduled task and variables
infrastructure/modules/tasks/main.tf, infrastructure/modules/tasks/variables.tf, infrastructure/modules/tasks/README.md
Adds local.create_snapshot_schedule_expression, the owasp_create_snapshot_task ECS module, CPU/memory inputs for the task, and matching module/input documentation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: automating snapshot creation and scheduling.
Description check ✅ Passed The description matches the changeset and accurately summarizes the snapshot automation work.
Linked Issues check ✅ Passed The changes add the command, duplicate prevention, Makefile target, scheduling, and tests required by #4744.
Out of Scope Changes check ✅ Passed The changes stay focused on snapshot automation, related tests, docs, and scheduling infrastructure.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added docs Improvements or additions to documentation backend backend-tests makefile infrastructure labels Jun 16, 2026
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 16, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 6 files

Confidence score: 2/5

  • In backend/apps/owasp/management/commands/owasp_create_snapshot.py, the command references Snapshot.Frequency, which is missing on the model, so running the command will raise an AttributeError immediately and block snapshot creation—replace this with the correct model enum/field reference and run the command path before merging.
  • In backend/apps/owasp/management/commands/owasp_create_snapshot.py, key is checked for duplicates but not passed into Snapshot.objects.create(), so saved rows can get a different generated key and weekly duplicate prevention fails—pass the checked key into create (or align duplicate logic with generated keys) and add a regression test for weekly dedupe before merging.

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/apps/owasp/management/commands/owasp_create_snapshot.py
Comment thread backend/apps/owasp/management/commands/owasp_create_snapshot.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/apps/owasp/management/commands/owasp_create_snapshot.py (1)

111-128: ⚠️ Potential issue | 🟠 Major

Remove or correct the misleading comment about mirroring save() logic.

The comment at line 115 claims the generate_key() method "mirrors the logic in the Snapshot model's save() method," but this is inaccurate. The Snapshot model's save() method only generates monthly keys using now().strftime("%Y-%m") and does not implement the weekly ISO calendar logic that generate_key() provides. Update or remove the misleading comment to reflect the actual implementation difference, and consider whether the save() method should also support the weekly frequency format to ensure consistency across key generation paths.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/apps/owasp/management/commands/owasp_create_snapshot.py` around lines
111 - 128, The comment in the generate_key() method at line 115 claims it
mirrors the logic in the Snapshot model's save() method, but this is inaccurate
since the save() method only generates monthly keys using strftime("%Y-%m") and
does not implement the weekly ISO calendar logic that generate_key() provides.
Remove or correct this misleading comment to accurately reflect that
generate_key() is a separate implementation that supports both weekly and
monthly frequency formats, which differs from what the save() method currently
does.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@backend/apps/owasp/management/commands/owasp_create_snapshot.py`:
- Around line 111-128: The comment in the generate_key() method at line 115
claims it mirrors the logic in the Snapshot model's save() method, but this is
inaccurate since the save() method only generates monthly keys using
strftime("%Y-%m") and does not implement the weekly ISO calendar logic that
generate_key() provides. Remove or correct this misleading comment to accurately
reflect that generate_key() is a separate implementation that supports both
weekly and monthly frequency formats, which differs from what the save() method
currently does.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b6649067-6fe6-44fe-991e-4723c5847c00

📥 Commits

Reviewing files that changed from the base of the PR and between 31ce1c0 and 15f3d5a.

📒 Files selected for processing (2)
  • backend/apps/owasp/management/commands/owasp_create_snapshot.py
  • backend/tests/unit/apps/owasp/management/commands/owasp_create_snapshot_test.py

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 16, 2026
cubic-dev-ai[bot]
cubic-dev-ai Bot previously approved these changes Jun 16, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Re-trigger cubic

@HarshitVerma109 HarshitVerma109 added the gsoc2026:harshitverma109 harshitverma109 GSoC 2026 related work label Jun 17, 2026
Comment thread backend/apps/owasp/management/commands/owasp_create_snapshot.py Outdated
Comment thread backend/apps/owasp/management/commands/owasp_create_snapshot.py Outdated
cubic-dev-ai[bot]
cubic-dev-ai Bot previously approved these changes Jun 26, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Re-trigger cubic

@codecov

codecov Bot commented Jun 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.87234% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 98.82%. Comparing base (0479503) to head (c1581e0).
⚠️ Report is 1 commits behind head on feature/community-snapshots.

Files with missing lines Patch % Lines
...owasp/management/commands/owasp_create_snapshot.py 97.87% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@                       Coverage Diff                       @@
##           feature/community-snapshots    #4938      +/-   ##
===============================================================
- Coverage                        98.82%   98.82%   -0.01%     
===============================================================
  Files                              541      542       +1     
  Lines                            17289    17336      +47     
  Branches                          2496     2500       +4     
===============================================================
+ Hits                             17086    17132      +46     
- Misses                              88       89       +1     
  Partials                           115      115              
Flag Coverage Δ
backend 99.41% <97.87%> (-0.01%) ⬇️
frontend 97.20% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...owasp/management/commands/owasp_create_snapshot.py 97.87% <97.87%> (ø)

Continue to review full report in Codecov by Harness.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 5a15194...c1581e0. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@HarshitVerma109 HarshitVerma109 requested a review from arkid15r June 26, 2026 02:54
@HarshitVerma109

Copy link
Copy Markdown
Collaborator Author

Hi @Arkadii, could you please review and merge this PR when you have a moment?

Signed-off-by: Harsh <harshit1092004@gmail.com>
@HarshitVerma109 HarshitVerma109 force-pushed the feature/automate-snapshots branch from 9949320 to 3cf5c1d Compare June 26, 2026 15:06

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (2)
backend/apps/owasp/management/commands/owasp_create_snapshot.py (1)

28-28: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reuse the Frequency enum values instead of enumerating choices.

Snapshot.Frequency.values already exposes the full set of valid values; listing members manually duplicates the source of truth and can drift if a frequency is added.

♻️ Suggested change
-            choices=[Snapshot.Frequency.WEEKLY, Snapshot.Frequency.MONTHLY],
+            choices=Snapshot.Frequency.values,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/apps/owasp/management/commands/owasp_create_snapshot.py` at line 28,
The `owasp_create_snapshot.py` command is hardcoding the `choices` for
`Snapshot.Frequency` instead of using the enum’s source of truth. Update the
argument definition in the snapshot command to use `Snapshot.Frequency.values`
directly so the valid frequencies stay in sync with the enum, and keep the
change localized to the snapshot creation command logic that references
`Snapshot.Frequency`.
backend/tests/unit/apps/owasp/management/commands/owasp_create_snapshot_test.py (1)

75-81: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assertion will need frequency="monthly" once the command bug is fixed.

This assert_called_once_with(...) omits frequency, matching the current (incorrect) behavior flagged in owasp_create_snapshot.py lines 62-68. Update it to include frequency="monthly" (and frequency="weekly" in the weekly test) when applying that fix.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/tests/unit/apps/owasp/management/commands/owasp_create_snapshot_test.py`
around lines 75 - 81, The snapshot creation test is asserting the current buggy
behavior and is missing the expected frequency argument. Update the
`assert_called_once_with` in `owasp_create_snapshot_test` to include the
`frequency` field that the fixed `owasp_create_snapshot` command should pass
through, using `frequency="monthly"` for this monthly case and
`frequency="weekly"` in the weekly test, so the test matches the corrected
`Snapshot.objects.create` call.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/apps/owasp/management/commands/owasp_create_snapshot.py`:
- Around line 62-68: The snapshot creation in owasp_create_snapshot is missing
the frequency value, so records created by Snapshot.objects.create end up with
the default weekly frequency even when the command runs with monthly. Update the
command’s snapshot creation logic to pass the current frequency into
Snapshot.objects.create, and adjust the related test
test_handle_creates_snapshot_monthly so it expects frequency to be set rather
than omitted.

---

Duplicate comments:
In `@backend/apps/owasp/management/commands/owasp_create_snapshot.py`:
- Line 28: The `owasp_create_snapshot.py` command is hardcoding the `choices`
for `Snapshot.Frequency` instead of using the enum’s source of truth. Update the
argument definition in the snapshot command to use `Snapshot.Frequency.values`
directly so the valid frequencies stay in sync with the enum, and keep the
change localized to the snapshot creation command logic that references
`Snapshot.Frequency`.

In
`@backend/tests/unit/apps/owasp/management/commands/owasp_create_snapshot_test.py`:
- Around line 75-81: The snapshot creation test is asserting the current buggy
behavior and is missing the expected frequency argument. Update the
`assert_called_once_with` in `owasp_create_snapshot_test` to include the
`frequency` field that the fixed `owasp_create_snapshot` command should pass
through, using `frequency="monthly"` for this monthly case and
`frequency="weekly"` in the weekly test, so the test matches the corrected
`Snapshot.objects.create` call.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: a5ac54fb-0bfa-4cd6-8681-719a4bab4c8d

📥 Commits

Reviewing files that changed from the base of the PR and between 9949320 and 3cf5c1d.

📒 Files selected for processing (6)
  • backend/apps/owasp/Makefile
  • backend/apps/owasp/management/commands/owasp_create_snapshot.py
  • backend/tests/unit/apps/owasp/management/commands/owasp_create_snapshot_test.py
  • infrastructure/modules/tasks/README.md
  • infrastructure/modules/tasks/main.tf
  • infrastructure/modules/tasks/variables.tf

Comment thread backend/apps/owasp/management/commands/owasp_create_snapshot.py
Signed-off-by: Harsh <harshit1092004@gmail.com>
@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/apps/owasp/management/commands/owasp_create_snapshot.py (1)

53-69: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Make duplicate handling atomic.

Lines 55-69 still do a check-then-create sequence. Two overlapping runs can both pass .exists(), and the loser will fail on the unique Snapshot.key constraint instead of behaving idempotently. Please switch this to get_or_create(..., defaults=...) or catch IntegrityError and treat it as “already exists”.

Suggested change
-        if Snapshot.objects.filter(key=key).exists():
-            self.stdout.write(
-                self.style.WARNING(f"Snapshot with key '{key}' already exists, skipping creation")
-            )
-            logger.info("Snapshot with key '%s' already exists, skipping", key)
-            return
-
-        snapshot = Snapshot.objects.create(
-            key=key,
-            frequency=frequency,
-            start_at=start_at,
-            end_at=end_at,
-            title=self.generate_title(start_at, frequency),
-            status=Snapshot.Status.PENDING,
-        )
+        snapshot, created = Snapshot.objects.get_or_create(
+            key=key,
+            defaults={
+                "frequency": frequency,
+                "start_at": start_at,
+                "end_at": end_at,
+                "title": self.generate_title(start_at, frequency),
+                "status": Snapshot.Status.PENDING,
+            },
+        )
+        if not created:
+            self.stdout.write(
+                self.style.WARNING(f"Snapshot with key '{key}' already exists, skipping creation")
+            )
+            logger.info("Snapshot with key '%s' already exists, skipping", key)
+            return
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/apps/owasp/management/commands/owasp_create_snapshot.py` around lines
53 - 69, The duplicate snapshot handling in the snapshot creation command is
still doing a non-atomic exists-then-create check, which can race under
overlapping runs. Update the logic in the management command method that builds
the Snapshot (using generate_key, generate_title, and Snapshot.objects.create)
to use an atomic get_or_create with defaults, or catch IntegrityError around the
create and treat that case as already existing. Keep the existing skip/log
behavior for the duplicate path so repeated runs remain idempotent.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@backend/apps/owasp/management/commands/owasp_create_snapshot.py`:
- Around line 53-69: The duplicate snapshot handling in the snapshot creation
command is still doing a non-atomic exists-then-create check, which can race
under overlapping runs. Update the logic in the management command method that
builds the Snapshot (using generate_key, generate_title, and
Snapshot.objects.create) to use an atomic get_or_create with defaults, or catch
IntegrityError around the create and treat that case as already existing. Keep
the existing skip/log behavior for the duplicate path so repeated runs remain
idempotent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ff6ac96a-5841-46d1-be5d-f56e9006dcb9

📥 Commits

Reviewing files that changed from the base of the PR and between 3cf5c1d and c1581e0.

📒 Files selected for processing (2)
  • backend/apps/owasp/management/commands/owasp_create_snapshot.py
  • backend/tests/unit/apps/owasp/management/commands/owasp_create_snapshot_test.py

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Re-trigger cubic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend backend-tests docs Improvements or additions to documentation gsoc2026:harshitverma109 harshitverma109 GSoC 2026 related work infrastructure makefile

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants