Skip to content

feat(runtime): make backup retention something an operator invokes - #389

Merged
prisis merged 10 commits into
alphafrom
feat/backup-prune-verb
Aug 9, 2026
Merged

prisis merged 10 commits into
alphafrom
feat/backup-prune-verb

Conversation

@prisis

@prisis prisis commented Aug 9, 2026 •

Copy link
Copy Markdown
Member

Behaviour change, first

The scheduled backup no longer deletes anything. backupRetain is the
retention window and nothing more. lunora backup prune is now the only thing
in Lunora that removes a backup.

A deployment relying on the cron to prune will grow until somebody prunes it —
so every scheduled run that has snapshots past the window says so and names the
command:

[lunora] backup retention: 3 snapshot(s) past the newest 14 — run `lunora backup prune` to remove them: backups/…

That trade is the point. An R2 delete has no undo, the thing deleted is the
backup, and a config mistake surfaces when someone reaches for a snapshot that
is not there. Swapping "unexpected deletion" for "unbounded storage nobody
mentioned" would not have been an improvement, which is why the report is not
optional.

What finishes WS4

Plan 313 §4.4 asked for retention that is explicit, with no silent deletion of
anything
; WS4 for "prune as its own verb so it is never implicit". The verb
alone would have changed nothing while the schedule still deleted on its own —
so both halves are here.

lunora backup retention   # what would go (reads; deletes nothing)
lunora backup prune       # delete it — prints, asks, then removes
lunora backup prune --yes # for scripts

POST /_lunora/admin/backup/prune, admin-gated, runs the same
selectStaleBackups the preview and the cron's report use. Three consumers, one
selection — a prediction, a confirmation and the record of what happened cannot
disagree.

Safety

  • Confirms by default. Prints the list, then asks. Uses the CLI's existing
    promptYesNo / isInteractive from @lunora/config; no second prompt
    mechanism.
  • Refuses without a TTY unless --yes. A prune that deletes because it ran
    in a pipeline where nobody could answer is the failure this workstream exists
    to prevent, so a script says --yes and means it.
  • Refuses with no window. No backupRetain → BACKUP_RETENTION_NOT_CONFIGURED,
    nothing deleted. A default is deliberately not invented — that would be the
    implicit deletion this replaces.
  • Reports what was actually deleted, not what was predicted: the worker
    re-runs the selection when it deletes, and a snapshot written between the two
    calls would push one more past the window.

Tests

  • The WS4 regression: a cron fire deletes nothing — over a bucket seeded
    with a legacy sidecar, another deployment's cron expression, and an
    operator-written snapshot — and store.delete is never called. Verified
    non-vacuous by putting the prune back on the cron: three tests fail.
  • Parity, extended rather than duplicated: the harness from feat(runtime): preview what backup retention would delete #388 now runs
    preview → prune and asserts the deleted set, the worker's reported set, and
    the predicted set are all equal. I deleted a second parity test I had written
    before noticing it was the same assertion.
  • CLI: no-TTY refuses with only a GET issued; --yes issues GET then
    POST; an empty window and a missing window each refuse without a POST.

Merge note

Branched from alpha and merged #387 (retention log) and #388 (preview)
in, per instruction — both are still open and all three touch pruneBackups.
The merge conflict resolution is its own commit, so the behaviour change reads
separately from the reconciliation.

One consequence worth naming: #387's log said what retention deleted. Since
retention no longer deletes, that record now belongs to the prune —
[lunora] backup prune kept the newest N and deleted M: … — and its test asserts
it after a prune rather than after a cron fire. The intent is intact; the caller
moved.

STOP conditions

Neither triggered. pruneBackups had exactly one caller (runScheduledBackup) —
no second caller, no test helper apps depend on — and the confirmation fits the
existing prompt helper.

🤖 Generated with Claude Code

https://claude.ai/code/session_011sk9BLaUZDkPVAZ1sKhuDP

Summary by CodeRabbit

  • New Features

    • Added backup retention to preview snapshots outside the configured retention window.
    • Added backup prune to explicitly delete eligible snapshots and related backup data.
    • Pruning requires confirmation or the --yes option and reports deleted items.
    • Scheduled backups now report retention candidates without deleting them automatically.
  • Documentation

    • Clarified retention eligibility, scheduled backup behavior, confirmation requirements, and configuration guidance.
    • Added guidance for unconfigured retention settings and legacy backup handling.

prisis and others added 8 commits August 9, 2026 10:11
Retention is opt-in and its deletes are irreversible, but a successful
prune left no trace - only the failure path logged. Both retention
defects found in review, pruning an operator's snapshots and then
another deployment's, were silent successes that had to be
reconstructed from a missing file.

It now names the count and the keys, capped so a first run on an old
bucket does not print a line nobody can read, and stays quiet when it
deletes nothing. This is a forensic record, not an approval gate - that
is plan 313's WS4, still open.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011sk9BLaUZDkPVAZ1sKhuDP
`backupRetain` deletes on every cron run, R2 deletes have no undo, and the
thing deleted is a backup — so the only way to learn what a retention setting
does on a real bucket was to let it run and read what was gone. That is a poor
trade for a subsystem where both defects found in review were silent data loss,
and it is worse than it sounds because eligibility turns on a metadata marker
that legacy sidecars lack: on any pre-existing bucket, retention may own far
fewer snapshots than the bucket holds, and nothing said so.

`GET /_lunora/admin/backup/retention` answers "what would go next", and
`lunora backup retention` prints it. The worker has to be the one to answer —
it is the only party that knows its own `backupCron` and `backupRetain`, and
the marker is not visible in a plain listing.

The selection is shared, not re-derived. `pruneBackups` already computed its
set before deleting; that computation is now `selectStaleBackups`, which both
the prune and the preview call. A preview that can disagree with the prune is
worse than no preview, and this subsystem has twice shown what happens when one
rule gets written in two places. The test seeds one bucket with every case that
makes eligibility subtle — a legacy sidecar, another deployment's cron, an
operator's own snapshot — then runs the preview and a real cron fire against
identical bucket state and asserts the sets match. Diverging only the preview
fails it; perturbing the shared function moves both and is caught elsewhere.

Nothing here deletes. The route reads, the verb reads, and a test asserts the
bucket is byte-for-byte unchanged after a preview. Retention itself stays on
the cron — this adds no second deleter.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011sk9BLaUZDkPVAZ1sKhuDP
Plan 313's §4.4 amendment said WS4 was wholly open; half of it is now done.
The preview closes the "see it coming" half; what remains is the deletion
becoming a step an operator invokes rather than a side effect of a backup
succeeding.

The docs say to run the preview after changing `backupRetain` and on any bucket
that predates the marker — the case where the answer is least deducible from
the config.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011sk9BLaUZDkPVAZ1sKhuDP
…feat/backup-prune-verb

# Conflicts:
#	packages/runtime/__tests__/scheduled-backup.test.ts
#	packages/runtime/src/scheduled-backup.ts
BREAKING CHANGE: the scheduled backup no longer deletes. `backupRetain` is the
retention window and nothing more; `lunora backup prune` is now the only thing
that removes a backup. A deployment that relied on the cron pruning will grow
until somebody prunes it — every run that has snapshots past the window says so
and names the command.

Plan 313 §4.4 asked for retention that is explicit, with no silent deletion of
anything, and WS4 for "prune as its own verb so it is never implicit". What
shipped kept deleting inside every cron run. That is the half that makes the
decision true: a verb that deletes changes nothing while the schedule still
deletes on its own.

`lunora backup prune` prints what will go, asks, and then removes it —
`POST /_lunora/admin/backup/prune`, admin-gated, running the same
`selectStaleBackups` the preview and the cron's report use. Three consumers, one
selection, so a prediction, a confirmation and the record of what happened
cannot disagree. Without a TTY it refuses rather than assuming: a prune that
deletes because it happened to run in a pipeline is the failure this workstream
exists to prevent, so a script passes `--yes` and means it. With no
`backupRetain` it refuses too — there is no window, so nothing is past it, and
inventing a default would be the implicit deletion this replaces.

The cron keeps the selection call, minus the delete. Reporting is not decoration:
swapping "unexpected deletion" for "unbounded storage nobody mentioned" would not
be an improvement.

The regression test that matters is that a cron fire deletes nothing, over a
bucket seeded with a legacy sidecar, another deployment's cron, and an
operator's snapshot. The parity harness from the preview now runs preview →
prune and asserts the deleted set equals the predicted one exactly.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011sk9BLaUZDkPVAZ1sKhuDP
An operator upgrading needs to know the scheduled backup stopped deleting and
what to run instead — the docs are the only place they will learn it. All three
surfaces say it: the concepts page leads with a warning, `@lunora/runtime`
explains the trade and the cost, and the CLI reference names `prune` as the only
command that removes a backup.

Plan 313 closes WS4. §4.4's amendment comes out: it recorded a deviation that no
longer exists, and the decision now reads as originally written.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011sk9BLaUZDkPVAZ1sKhuDP
@netlify

netlify Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for lunorash ready!

Name Link
🔨 Latest commit 430617c
🔍 Latest deploy log https://app.netlify.com/projects/lunorash/deploys/6a7857b27ff15f0008352ce8
😎 Deploy Preview https://deploy-preview-389--lunorash.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions

github-actions Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Thank you for following the naming conventions! 🙏

@github-actions

github-actions Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Thank you for confirming the Contributor License Agreement! 🙏

@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Scheduled backups now report stale snapshots without deleting them. New worker endpoints and CLI commands preview and explicitly prune eligible backups. Pruning requires confirmation or --yes. Runtime types, error handling, and documentation describe the retention workflow.

Changes

Backup retention workflow

Layer / File(s) Summary
Retention selection and pruning
packages/runtime/src/scheduled-backup.ts, packages/runtime/src/index.ts
Retention selection is non-destructive. Explicit pruning deletes confirmed snapshots and sidecars with bounded concurrency and structured results.
Worker retention endpoints
packages/runtime/src/backup-admin-routes.ts, packages/runtime/src/create-worker.ts, packages/runtime/src/index.ts
The worker exposes authenticated GET and POST routes for retention preview and pruning. The routes validate storage, methods, request bodies, and response caching.
CLI retention and prune commands
packages/cli/src/commands/backup/handler.ts, packages/cli/src/commands/backup/index.ts, packages/errors/src/catalog.ts
The CLI adds retention and prune, supports confirmation and --yes, reports results, and handles missing retention configuration.
Retention behavior documentation
packages/runtime/docs/index.mdx, apps/docs/src/content/docs/concepts/backups.mdx, packages/cli/docs/index.mdx
Documentation describes scheduled retention, eligibility, preview behavior, confirmation, and explicit pruning.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Operator
  participant LunoraCLI
  participant Worker
  participant BackupRuntime
  participant BackupStore
  Operator->>LunoraCLI: run backup retention
  LunoraCLI->>Worker: GET retention preview
  Worker->>BackupRuntime: previewBackupRetention
  BackupRuntime->>BackupStore: inspect eligible snapshots
  BackupStore-->>BackupRuntime: stale candidates
  BackupRuntime-->>Worker: retention preview
  Worker-->>LunoraCLI: preview response
  LunoraCLI-->>Operator: show snapshots to prune
  Operator->>LunoraCLI: confirm backup prune
  LunoraCLI->>Worker: POST confirmed keys
  Worker->>BackupRuntime: runBackupPrune
  BackupRuntime->>BackupStore: delete snapshots and sidecars
  BackupStore-->>BackupRuntime: deletion results
  BackupRuntime-->>Worker: prune result
  Worker-->>LunoraCLI: deletion results
  LunoraCLI-->>Operator: report prune result
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the behavior, safety model, commands, endpoints, and tests, but omits the template's Linked issues, Checklist, Notes, and required CLA sections. Add the missing template sections, complete the checklist, document linked issues or state none, and include the exact CLA confirmation line when required.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: backup retention is now invoked by an operator instead of scheduled automatically.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/backup-prune-verb

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (2)
packages/cli/src/commands/backup/handler.ts (1)

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

Rename or re-document pitrFetch now that it serves three subcommands.

resolveBackupAdminRequest reads options.pitrFetch for retention and prune. The option is documented on Line 79 as "Injectable fetch for the pitr admin endpoint". The name and the doc comment no longer describe the use. Rename it to something neutral such as adminFetch, or update the doc comment to name all three subcommands.

♻️ Minimal doc-only fix
-    /** Injectable fetch for the `pitr` admin endpoint (plain JSON, not the streaming export fetch). */
+    /** Injectable fetch for the worker-answered admin endpoints (`pitr`, `retention`, `prune`) — plain JSON, not the streaming export fetch. */
     pitrFetch?: FetchLike;
🤖 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 `@packages/cli/src/commands/backup/handler.ts` at line 454, Update the option
documentation for pitrFetch to describe its use by all three backup-admin
subcommands, including retention and prune, or rename the option to a neutral
name such as adminFetch and update every reference including
resolveBackupAdminRequest. Keep the injectable fetch fallback behavior
unchanged.
packages/cli/src/commands/backup/index.ts (1)

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

Name retention and prune in the command description.

The argument description on Line 4 lists all six subcommands. This description still enumerates only create | list | restore plus pitr. prune is the only command that deletes a backup, so it is worth naming in the line that lunora backup --help prints first.

♻️ Proposed wording
-    description: "Managed snapshot backups (create | list | restore) to a directory or an R2 bucket, plus native point-in-time recovery (pitr)",
+    description:
+        "Managed snapshot backups (create | list | restore) to a directory or an R2 bucket, retention preview and pruning (retention | prune), plus native point-in-time recovery (pitr)",
🤖 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 `@packages/cli/src/commands/backup/index.ts` at line 5, Update the backup
command’s top-level description to explicitly name the retention and prune
subcommands alongside the existing create, list, restore, and pitr entries, so
`lunora backup --help` reflects all supported operations.
🤖 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 `@apps/docs/src/content/docs/concepts/backups.mdx`:
- Around line 152-156: Update apps/docs/src/content/docs/concepts/backups.mdx at
lines 152-156 and the related Line 172 text so scheduled runs report snapshots
past the retention window instead of pruning them. Update
packages/runtime/docs/index.mdx at lines 240-241 to describe failures from the
retention report that runScheduledBackup catches and logs as a warning, not a
scheduled prune.

In `@packages/cli/src/commands/backup/handler.ts`:
- Around line 665-666: Update the unknown-subcommand error message in the backup
command handler to include the newly supported prune and retention subcommands,
matching the values accepted by isBackupSubcommand while preserving the existing
message format.
- Around line 596-616: Update the prune result handling around the deleted array
and preview.wouldDelete to explicitly notify the operator when the actual
deleted keys differ from the confirmed preview list. Preserve the existing
actual-deletion success and key output, and make the notice clearly identify
that the worker deleted a different set than was confirmed.

In `@packages/runtime/src/scheduled-backup.ts`:
- Around line 178-189: Bound the delete fan-out in the stale-backup cleanup
around the stale map and MAX_PRUNE_PAGES by introducing a fixed batch-size cap
such as MAX_CONCURRENT_PRUNE_DELETES and processing stale manifest keys in
sequential batches, while retaining Promise.all within each batch and the
snapshot-then-sidecar delete order. Optionally cap selection per run if needed
to keep the total invocation within the platform subrequest budget.

---

Nitpick comments:
In `@packages/cli/src/commands/backup/handler.ts`:
- Line 454: Update the option documentation for pitrFetch to describe its use by
all three backup-admin subcommands, including retention and prune, or rename the
option to a neutral name such as adminFetch and update every reference including
resolveBackupAdminRequest. Keep the injectable fetch fallback behavior
unchanged.

In `@packages/cli/src/commands/backup/index.ts`:
- Line 5: Update the backup command’s top-level description to explicitly name
the retention and prune subcommands alongside the existing create, list,
restore, and pitr entries, so `lunora backup --help` reflects all supported
operations.
🪄 Autofix

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: CHILL

Plan: Pro Plus

Run ID: 4ede1461-336a-40c7-b163-0e74c01ecf32

📥 Commits

Reviewing files that changed from the base of the PR and between 2dc73bf and 9154d5c.

⛔ Files ignored due to path filters (6)
  • api-snapshots/errors.api.md is excluded by none and included by none
  • api-snapshots/lunora.api.md is excluded by none and included by none
  • api-snapshots/runtime.api.md is excluded by none and included by none
  • packages/cli/__tests__/commands/backup.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/runtime/__tests__/scheduled-backup.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • plans/313-r2-backup-tier.md is excluded by none and included by none
📒 Files selected for processing (9)
  • apps/docs/src/content/docs/concepts/backups.mdx
  • packages/cli/docs/index.mdx
  • packages/cli/src/commands/backup/handler.ts
  • packages/cli/src/commands/backup/index.ts
  • packages/errors/src/catalog.ts
  • packages/runtime/docs/index.mdx
  • packages/runtime/src/create-worker.ts
  • packages/runtime/src/index.ts
  • packages/runtime/src/scheduled-backup.ts

Comment on lines +596 to +616
const response = await request.fetchImpl(`${request.baseUrl}${PRUNE_ENDPOINT_PATH}`, {
headers: { authorization: `Bearer ${request.token}` },
method: "POST",
});

if (!response.ok) {
await readAndLogBody(response, options.logger);

return { code: 1, preview };
}

// Report what actually went, not what was predicted: the worker re-runs the
// selection when it deletes, and a snapshot written between the two calls
// would push one more past the window.
const { deleted } = (await response.json()) as { deleted: string[] };

options.logger.success(`deleted ${deleted.length.toString()} backup(s)`);

for (const key of deleted) {
options.logger.info(` ${key.slice(0, -MANIFEST_SUFFIX_LENGTH)}`);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Warn the operator when the prune deletes something the confirmation did not list.

The confirmation at Line 587 names preview.wouldDelete.length. The POST at Line 596 sends no selection, so the worker re-runs selectStaleBackups and deletes whatever is past the window at that moment. The comment on Line 607 states this. The operator therefore confirms one list and the command can delete a superset of it.

Reporting the actual keys is the right base behavior. Add an explicit notice when the two lists differ, so a divergence is visible rather than inferred by comparing two blocks of output.

🛡️ Proposed divergence notice
     const { deleted } = (await response.json()) as { deleted: string[] };
 
+    // The worker re-ran the selection, so this can differ from what was
+    // confirmed. Say so rather than leaving the operator to diff two lists.
+    const confirmed = new Set(preview.wouldDelete);
+    const unconfirmed = deleted.filter((key) => !confirmed.has(key));
+
+    if (unconfirmed.length > 0) {
+        options.logger.warn(
+            `${unconfirmed.length.toString()} snapshot(s) were deleted that the preview did not list — a newer snapshot landed between the preview and the prune`,
+        );
+    }
+
     options.logger.success(`deleted ${deleted.length.toString()} backup(s)`);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const response = await request.fetchImpl(`${request.baseUrl}${PRUNE_ENDPOINT_PATH}`, {
headers: { authorization: `Bearer ${request.token}` },
method: "POST",
});
if (!response.ok) {
await readAndLogBody(response, options.logger);
return { code: 1, preview };
}
// Report what actually went, not what was predicted: the worker re-runs the
// selection when it deletes, and a snapshot written between the two calls
// would push one more past the window.
const { deleted } = (await response.json()) as { deleted: string[] };
options.logger.success(`deleted ${deleted.length.toString()} backup(s)`);
for (const key of deleted) {
options.logger.info(` ${key.slice(0, -MANIFEST_SUFFIX_LENGTH)}`);
}
const response = await request.fetchImpl(`${request.baseUrl}${PRUNE_ENDPOINT_PATH}`, {
headers: { authorization: `Bearer ${request.token}` },
method: "POST",
});
if (!response.ok) {
await readAndLogBody(response, options.logger);
return { code: 1, preview };
}
// Report what actually went, not what was predicted: the worker re-runs the
// selection when it deletes, and a snapshot written between the two calls
// would push one more past the window.
const { deleted } = (await response.json()) as { deleted: string[] };
// The worker re-ran the selection, so this can differ from what was
// confirmed. Say so rather than leaving the operator to diff two lists.
const confirmed = new Set(preview.wouldDelete);
const unconfirmed = deleted.filter((key) => !confirmed.has(key));
if (unconfirmed.length > 0) {
options.logger.warn(
`${unconfirmed.length.toString()} snapshot(s) were deleted that the preview did not list — a newer snapshot landed between the preview and the prune`,
);
}
options.logger.success(`deleted ${deleted.length.toString()} backup(s)`);
for (const key of deleted) {
options.logger.info(` ${key.slice(0, -MANIFEST_SUFFIX_LENGTH)}`);
}
🤖 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 `@packages/cli/src/commands/backup/handler.ts` around lines 596 - 616, Update
the prune result handling around the deleted array and preview.wouldDelete to
explicitly notify the operator when the actual deleted keys differ from the
confirmed preview list. Preserve the existing actual-deletion success and key
output, and make the notice clearly identify that the worker deleted a different
set than was confirmed.

@codecov-commenter

codecov-commenter commented Aug 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.70056% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.10%. Comparing base (95d33d6) to head (430617c).
⚠️ Report is 77 commits behind head on alpha.

Files with missing lines Patch % Lines
packages/cli/src/commands/backup/handler.ts 83.83% 13 Missing and 3 partials ⚠️
packages/runtime/src/scheduled-backup.ts 94.91% 2 Missing and 1 partial ⚠️
packages/runtime/src/backup-admin-routes.ts 94.44% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            alpha     #389      +/-   ##
==========================================
+ Coverage   87.09%   87.10%   +0.01%     
==========================================
  Files        1172     1178       +6     
  Lines       63383    63748     +365     
  Branches    15447    15749     +302     
==========================================
+ Hits        55202    55527     +325     
- Misses       7654     7695      +41     
+ Partials      527      526       -1     
Files with missing lines Coverage Δ
packages/cli/src/commands/backup/index.ts 25.00% <ø> (ø)
packages/errors/src/catalog.ts 98.50% <ø> (ø)
packages/runtime/src/create-worker.ts 87.91% <100.00%> (-0.31%) ⬇️
packages/runtime/src/index.ts 100.00% <ø> (ø)
packages/runtime/src/backup-admin-routes.ts 94.44% <94.44%> (ø)
packages/runtime/src/scheduled-backup.ts 95.61% <94.91%> (ø)
packages/cli/src/commands/backup/handler.ts 85.23% <83.83%> (-1.84%) ⬇️

... and 9 files with indirect coverage changes

🚀 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.

@codspeed

codspeed Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 21.14%

⚡ 1 improved benchmark
❌ 3 regressed benchmarks
✅ 249 untouched benchmarks
⏩ 10 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ token bucket, unsharded 134.1 µs 268 µs -49.97%
❌ batched: one IN-list UNION-ALL probe across all tables (locateTablesByIds) 1.4 ms 1.8 ms -21.26%
❌ flat 3 primitives (the notify.send attribute shape) 55.6 µs 62.5 µs -11.07%
⚡ baseline (Object.keys + toInternal + path spread per field) 72 µs 65.2 µs +10.4%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing feat/backup-prune-verb (430617c) with alpha (52fe8f8)2

Open in CodSpeed

Footnotes

  1. 10 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

  2. No successful run was found on alpha (9431669) during the generation of this report, so 52fe8f8 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

prisis and others added 2 commits August 9, 2026 12:30
BREAKING CHANGE: `POST /_lunora/admin/backup/prune` now requires a `confirm`
array of the sidecar keys to remove. A prune with no body deletes nothing.

The POST carried no body, so the confirmed list and the deleted list were two
computations separated by however long a human takes to read a prompt. A cron
fire inside that window writes a newer snapshot and pushes one more past the
window — probed with three snapshots and `backupRetain: 2`, the preview showed
one and the prune deleted two, the second having been displayed as KEPT. The
docs promised "what retention predicts is what prune removes", and the thing
that cost was irreversible.

The server still decides eligibility — it re-runs the selection, so naming a
key grants nothing — but it deletes the intersection with what was confirmed.
Snapshots that became eligible in between are reported, not removed.

`backupRetain: NaN` deleted every eligible snapshot: `NaN <= 0` is false so it
slipped both guards, and `slice(NaN)` is `slice(0)`. Reachable from
`Number(env.BACKUP_RETAIN)` with the variable unset. Both guards are now
`Number.isInteger`.

A partial failure destroyed backups and left no record: `Promise.all` rejected
on the first failing delete, so the log the record exists to produce never ran
and the route answered with a bare 500. Now `allSettled`, per-window, with
`{ deleted, failed, ignored, remaining }` returned so the CLI can report every
way the run differed from the plan. Deletes are capped per run — a daily cron
kept two years leaves ~700 past a 14-day window, and 1432 concurrent R2 calls
would exhaust the subrequest budget partway through.

Also: the two routes move to `backup-admin-routes.ts` like the other eleven
clusters; the runtime's record names the snapshot rather than its sidecar, so
the prediction, the confirmation and the record are one string.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011sk9BLaUZDkPVAZ1sKhuDP
The plan said "§4.4 now reads as originally written" while §4.4 still carried
the amendment saying retention deletes inside the cron run, and Status plus the
WS4 row still said the prune was open — so the next agent reads Status and
re-implements a verb that exists. The earlier edit had never landed: the script
that wrote it aborted before writing the file.

Three comments asserting what the code no longer does: a failed *prune* that is
now a failed retention report, a scheduled run that "prunes older snapshots"
twenty lines under a callout saying it never deletes, and a selection docblock
naming two callers when there are three.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011sk9BLaUZDkPVAZ1sKhuDP

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
packages/runtime/docs/index.mdx (1)

222-225: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Describe the confirmed intersection, not identical results.

prune re-evaluates eligibility. It deletes only confirmed keys that remain eligible. A deletion failure or the per-run cap can also leave eligible snapshots behind. The current text promises that preview and prune have identical results.

Proposed fix
-Both commands answer from the worker, because the worker is the only party that
-knows its own `backupCron` and `backupRetain`, and because eligibility depends
-on a marker that is not visible in a plain object listing. They share one
-selection, so what `retention` predicts is what `prune` removes.
+Both commands answer from the worker, because the worker is the only party that
+knows its own `backupCron` and `backupRetain`, and because eligibility depends
+on a marker that is not visible in a plain object listing. They share the same
+eligibility rules. `prune` deletes only previewed keys that the operator
+confirms and that remain eligible when the request runs.
🤖 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 `@packages/runtime/docs/index.mdx` around lines 222 - 225, Update the
documentation paragraph describing retention and prune to state that they share
the same selection criteria and confirmed eligible intersection, rather than
promising identical results. Mention that prune re-evaluates eligibility and may
leave eligible snapshots due to deletion failures or the per-run cap.
🤖 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 `@packages/cli/src/commands/backup/handler.ts`:
- Around line 332-335: Replace the obsolete pitrFetch guidance with adminFetch
in both error messages: packages/cli/src/commands/backup/handler.ts lines
332-335 and 481-485. Update each message while preserving the existing fetch
validation and Node version guidance.

---

Outside diff comments:
In `@packages/runtime/docs/index.mdx`:
- Around line 222-225: Update the documentation paragraph describing retention
and prune to state that they share the same selection criteria and confirmed
eligible intersection, rather than promising identical results. Mention that
prune re-evaluates eligibility and may leave eligible snapshots due to deletion
failures or the per-run cap.
🪄 Autofix

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: CHILL

Plan: Pro Plus

Run ID: 70dacd67-f4d6-4012-918c-a13640f5e7f4

📥 Commits

Reviewing files that changed from the base of the PR and between 9154d5c and 430617c.

⛔ Files ignored due to path filters (5)
  • api-snapshots/lunora.api.md is excluded by none and included by none
  • api-snapshots/runtime.api.md is excluded by none and included by none
  • packages/cli/__tests__/commands/backup.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • packages/runtime/__tests__/scheduled-backup.test.ts is excluded by !**/__tests__/**, !**/*.test.ts and included by packages/**
  • plans/313-r2-backup-tier.md is excluded by none and included by none
📒 Files selected for processing (7)
  • apps/docs/src/content/docs/concepts/backups.mdx
  • packages/cli/src/commands/backup/handler.ts
  • packages/runtime/docs/index.mdx
  • packages/runtime/src/backup-admin-routes.ts
  • packages/runtime/src/create-worker.ts
  • packages/runtime/src/index.ts
  • packages/runtime/src/scheduled-backup.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/docs/src/content/docs/concepts/backups.mdx
  • packages/runtime/src/scheduled-backup.ts

Comment on lines +332 to 335
const fetchImpl: FetchLike = options.adminFetch ?? (globalThis as unknown as { fetch: FetchLike }).fetch;

if (typeof fetchImpl !== "function") {
throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Replace obsolete pitrFetch guidance with adminFetch.

BackupCommandOptions exposes adminFetch. Both request paths resolve options.adminFetch. The current errors instruct the caller to pass an option that no longer exists.

  • packages/cli/src/commands/backup/handler.ts#L332-L335: change pass pitrFetch to pass adminFetch.
  • packages/cli/src/commands/backup/handler.ts#L481-L485: change pass pitrFetch to pass adminFetch.
📍 Affects 1 file
  • packages/cli/src/commands/backup/handler.ts#L332-L335 (this comment)
  • packages/cli/src/commands/backup/handler.ts#L481-L485
🤖 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 `@packages/cli/src/commands/backup/handler.ts` around lines 332 - 335, Replace
the obsolete pitrFetch guidance with adminFetch in both error messages:
packages/cli/src/commands/backup/handler.ts lines 332-335 and 481-485. Update
each message while preserving the existing fetch validation and Node version
guidance.

@prisis
prisis merged commit 01dc8bf into alpha Aug 9, 2026
46 of 47 checks passed
@prisis
prisis deleted the feat/backup-prune-verb branch August 9, 2026 12:09
prisis added a commit that referenced this pull request Aug 9, 2026
Both halves shipped - the object-storage destination in #375, and in
#389 the part that made the plan's own decision true: the scheduled
backup no longer deletes, prune is the only thing that removes a
backup, and retention previews what it would take.

The row keeps what git alone would not tell you. Six review rounds, and
every defect after the first was in the remediation rather than the
original work, all of one shape - a claim about a second party's
behaviour never checked against the second party.


Claude-Session: https://claude.ai/code/session_011sk9BLaUZDkPVAZ1sKhuDP

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using our GitHub Discussions tab for questions.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Sep 8, 2026

This branch was previously deployed

1 inactive deployment
benchmarks — 430617c1 Deployed Aug 9, 2026 by prisis via Benchmarks #1608
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants