Skip to content

feat(cold-store-reaper): v4 — R2 S3 client, backup-supabase, eviction - #971

Merged
dezren39 merged 3 commits into
mainfrom
cold-store-reaper-v4
Oct 26, 2026
Merged

dezren39 merged 3 commits into
mainfrom
cold-store-reaper-v4

Conversation

@dezren39

@dezren39 dezren39 commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

What

Reaper v4 wires the supabase-backups R2 bucket into the reaper in both directions: filing its newest dump into the Drive cold store, and evicting bucket objects the cold store provably holds.

S3 client (stdlib only, in cold_store.py)

  • SigV4-signed ListObjectsV2 (continuation-token pagination), GET, DELETE against the account R2 host; COLD_STORE_R2_HOST / COLD_STORE_S3_BASE overrides mirror the existing endpoint-override pattern.
  • Credentials only from R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY (operator materializes from Bitwarden); clear error when absent.
  • GET verifies the received byte count against Content-Length and retries the whole GET up to 3 attempts on truncation / IncompleteRead — a truncated read was observed live through this sandbox's egress proxy.

backup-supabase

Lists the bucket, picks the newest backup object by LastModified (manifest.json excluded — it's the backup system's index, not a dump), downloads it byte-verified, and files it through the existing put-backup machinery as db supabase. Point-in-time semantics like backup-d1: unchanged content is filed again, and the content sha256 is printed so duplication is visible.

Eviction (trial bucket)

  • evict-scan (dry-run, never deletes): one verdict per object. Evictable requires ALL of: content hash known (content-addressed 64-hex filename stem), manifest state cold, membership in a verified bundle, LastModified at least --min-age-days old (default 14), and not among the --keep-newest newest bucket objects (default 3). Other verdicts: hash-unknown / not-in-manifest / bundle-unverified / too-young / kept-newest. Age is checked before position (a young object always carries one of the newest stamps).
  • evict recomputes the scan; without the literal --apply it prints the scan and exits non-zero. With --apply, each evictable object is re-verified against the manifest at deletion time, then S3-deleted, marked evicted, and ledgered (direction='trash', kind='evict', ref=<R2 key>). One object's failure never aborts the rest.

Nightly script

scripts/nightly-backup.sh gains a guarded step 2: backup-supabase runs between backup-d1 and prune only when both R2 credentials are set; otherwise a one-line skip notice (not an error). Header env docs updated; shellcheck/shfmt clean. The existing nightly-backup cron does not materialize R2 credentials today, so the step skips there until the cron body is updated (separate operator action).

Schema — needs a call-out

objects.state is not free text: the pre-v4 CHECK is ('hot','staging','cold','rehydrating','gone'), so 'evicted' required a change. Following the v1.1 ledger 'trash' precedent: schema v1.2 adds 'evicted' to the CHECK, local manifests are migrated in place on first open (table rebuild preserving FK-referencing member rows, covered by a test), and the README documents that the D1 copy needs the same one-line CHECK change before evicted rows can sync — until then sync-manifest fails on the objects statement with D1's own error text. The ledger was deliberately NOT changed (direction stays 'trash', kind 'evict').

Tests

Offline, no real R2/Google/Cloudflare calls, no real credentials: a fake S3 HTTP layer in the existing fake-server style (SigV4 capture, 2-object list pages, truncate-once GET mode, DELETE recording). 40 tests pass (30 prior + 10 new), 1 pre-existing skip (worker decoder, node deps absent):

  • SigV4 header shape + empty-payload hash; list pagination follows continuation tokens; missing-credentials error.
  • backup-supabase files the newest non-manifest object; the filed copy is byte-whole despite a truncated first GET (retry verified); manifest-only bucket errors.
  • Evict-scan verdict matrix hits every reason; scan deletes nothing.
  • evict without --apply exits 1 and deletes nothing; evict --apply deletes only fully verified evictable objects, writes the trash/evict ledger rows, sets state evicted.
  • An object flipped non-cold between scan and apply is skipped by the deletion-time re-verification.
  • Pre-v4 manifest migration admits 'evicted' and preserves member rows.

README documents the S3 env, backup-supabase, the eviction policy + safety rails, the nightly change, and notes the turso/ backup folder exists with no filing command yet (no Turso export source wired — none invented).


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

Muse Sweep added 3 commits October 26, 2026 13:57
…/apply

Minimal stdlib SigV4 S3 client for the supabase-backups trial bucket:
paginated ListObjectsV2, byte-count-verified GET with whole-GET retry
on truncation, DELETE. Credentials come from R2_ACCESS_KEY_ID /
R2_SECRET_ACCESS_KEY in the environment only; host overridable via
COLD_STORE_R2_HOST, endpoint via COLD_STORE_S3_BASE (tests).

backup-supabase files the newest backup object (manifest.json
excluded) into db-backups/supabase/ through put-backup, reporting the
content sha256.

evict-scan prints a verdict per object — evictable only when the
content hash is known, the manifest has it cold in a verified bundle,
it is at least --min-age-days old, and it is not among the
--keep-newest newest; evict requires --apply and re-verifies every
candidate against the manifest at deletion time before S3 DELETE,
then marks the object 'evicted' with a ledger row (direction
'trash', kind 'evict').

Schema v1.2: objects.state CHECK gains 'evicted' (it was CHECK-
constrained, not free text), with an in-place migration in db() on
the v1.1 pattern; the D1 copy needs the same CHECK change before
evicted rows can sync.

nightly-backup.sh gains a guarded backup-supabase step between
backup-d1 and prune: it runs only when both R2 credentials are set
and prints a skip notice otherwise.
…ckup-supabase, eviction)

Stubbed S3 HTTP layer in the fake-server style: paginated listings
(2-object pages), DELETE recording, and a truncate-once mode that
answers a GET with a short body under a full Content-Length.

New coverage: SigV4 Authorization header shape + empty-payload hash;
list pagination follows continuation tokens; missing R2 credentials
error clearly; backup-supabase files the newest non-manifest object
and the filed copy is whole despite a truncated first GET; the
evict-scan verdict matrix hits every reason (evictable, too-young,
kept-newest, not-in-manifest, bundle-unverified, hash-unknown);
evict without --apply exits 1 and deletes nothing; evict --apply
deletes only fully verified evictable objects, writes ledger rows
(direction trash, kind evict) and marks objects evicted; an object
flipped non-cold between scan and apply is skipped by the
deletion-time re-verification; the pre-v4 objects CHECK migration
admits 'evicted' and preserves referencing member rows.

40 tests pass (30 prior + 10 new), 1 pre-existing skip.
Document the S3 env (R2 keys from Bitwarden, host overrides),
backup-supabase (newest non-manifest dump, byte-verified download,
point-in-time filing with the sha256 printed), the eviction policy
(never delete unverified: hash known, cold in a verified bundle, age
floor, keep-newest; explicit --apply; deletion-time re-verification;
ledger trash/evict; state evicted) with the schema v1.2 / D1 CHECK
caveat, the nightly script's guarded Supabase step, and a note that
the turso/ backup folder exists but has no filing command yet
because no Turso export source is wired.
@dezren39
dezren39 requested a review from a team as a code owner October 26, 2026 14:05
@coderabbitai

coderabbitai Bot commented Oct 26, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 10 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5bd8667c-16e9-4401-aa6c-d2c5b8f1a611
Commits

Reviewing files that changed from the base of the PR and between 9b09762 and b83e9dd.

Files selected for processing: 5
  • pkgs/cold-store-reaper/README.md
  • pkgs/cold-store-reaper/cold_store.py
  • pkgs/cold-store-reaper/schema.sql
  • pkgs/cold-store-reaper/scripts/nightly-backup.sh
  • pkgs/cold-store-reaper/tests/test_cold_store.py
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T14:10:55.507249Z b83e9dd PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@dezren39
dezren39 merged commit e95356c into main Oct 26, 2026
4 checks passed
@dezren39
dezren39 deleted the cold-store-reaper-v4 branch October 26, 2026 14:10

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b83e9ddd0b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1420 to +1422
path = staging / newest["key"].rsplit("/", 1)[-1]
path.write_bytes(data)
result = self.put_backup("supabase", str(path))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Remove staged Supabase dumps after successful filing

When the nightly backup changes content, its content-addressed basename changes, so this code leaves another complete dump in the local staging directory after every successful upload. There is no staging cleanup elsewhere in the repository, and prune-backups only trashes Drive files. Consequently, normal nightly operation grows local disk usage without bound and eventually prevents further backups. Remove the staged download after filing, or use a temporary file with cleanup.

Useful? React with 👍 / 👎.

Comment on lines +1540 to +1541
"UPDATE objects SET state='evicted' WHERE hash=?",
(entry["hash"],),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include evicted objects in the restore drill

After this state transition, the object is excluded from the quarterly restore drill: scripts/restore-drill.sh:64 selects only objects with state='cold'. Thus the drill stops checking precisely the objects whose R2 copies have been deleted and whose recovery now depends on Drive; if all cold objects are evicted, it instead fails with “no cold objects” despite having a valid archive. Update the drill's selection to include the new evicted state.

Useful? React with 👍 / 👎.

Comment on lines +1526 to +1527
state, verified = self._object_cold_verified(conn, entry["hash"])
if state != "cold" or not verified:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Allow eviction of additional keys with the same content hash

If two old R2 keys contain the same content hash, both can pass evict_scan, but deleting the first changes their shared object row to evicted. This check then skips the second key, and all subsequent scans classify it as not-in-manifest, leaving it permanently in R2 despite its verified cold copy. This also affects identical content stored in different buckets. Track source-key eviction separately, or allow already-evicted content with a verified bundle to satisfy the cold-copy checks.

Useful? React with 👍 / 👎.

Comment on lines +1865 to +1868
done = sum(1 for o in outcomes if o["outcome"] == "evicted")
print(
f"evict: {done} object(s) evicted, {len(outcomes) - done} not evicted"
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Return a nonzero exit status when eviction fails

When an S3 DELETE fails, evict_apply catches the error and returns a failed outcome, but this CLI branch only prints the outcomes and then reaches return 0. Reproducing a DELETE access-denied error therefore reports zero objects evicted while still exiting successfully. Shell callers and job monitoring cannot detect failed eviction or trigger failure handling. Continue processing the remaining objects as intended, but return a nonzero status after reporting any failed outcomes.

Useful? React with 👍 / 👎.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant