diff --git a/pkgs/cold-store-reaper/README.md b/pkgs/cold-store-reaper/README.md index 1fd00d39bc..41b4057a2f 100644 --- a/pkgs/cold-store-reaper/README.md +++ b/pkgs/cold-store-reaper/README.md @@ -79,6 +79,9 @@ cold-store status # counts, cold bytes, last cold-store sync-manifest # push the local manifest into D1 cold-store sync-manifest --dry-run # ... or just print the statement counts cold-store backup-d1 # export the D1 manifest DB into db-backups/d1/ +cold-store backup-supabase # file the newest Supabase dump from R2 into db-backups/supabase/ +cold-store evict-scan # dry-run: which R2 objects are safe to evict? (never deletes) +cold-store evict --apply # delete the evictable ones (each re-verified first) cold-store prune-backups # retention plan (dry-run) cold-store prune-backups --apply # ... and trash the excess cold-store get-backup d1 ./restored.sql # download one backup in full @@ -99,9 +102,15 @@ cold-store list-backups # all DBs, newest fir cold-store list-backups --db turso cold-store backup-d1 # export the D1 manifest DB itself # (REST query API) and file it under d1/ +cold-store backup-supabase # file the newest R2 Supabase dump + # under supabase/ (see "R2" below) cold-store get-backup d1 d1-<...>-cold-store-manifest-export.sql ./restored.sql ``` +The `turso/` folder exists (created by `ensure-folders` like the +others) but has **no filing command yet**: there is no Turso export +source wired into the reaper, so nothing files there until one exists. + ### Retention (design section 5) `prune-backups [--db ] [--apply]` enforces **30 daily / 12 weekly / @@ -140,9 +149,13 @@ pipefail`, no secrets stored or echoed — credentials arrive via the environment only): - `scripts/nightly-backup.sh` — the nightly run: `backup-d1`, then + `backup-supabase` (only when both R2 credentials are set; a skip + notice is printed otherwise — never an error), then `prune-backups --apply`, then `sync-manifest`, then `status`. Any failing step aborts the run non-zero. Requires `CLOUDFLARE_API_TOKEN` - in the environment (materialize from Bitwarden into the cron env). + in the environment (materialize from Bitwarden into the cron env); + `R2_ACCESS_KEY_ID` / `R2_SECRET_ACCESS_KEY` are optional (they gate + the Supabase step). - `scripts/restore-drill.sh` — the quarterly restore drill (design section 8): picks 3 pseudo-random cold objects from the local manifest, fetches each through the rehydrator Worker and verifies its @@ -159,6 +172,80 @@ environment only): and a final verdict; exits non-zero on any failure. Requires `REHYDRATOR_API_KEY` and `CLOUDFLARE_API_TOKEN` in the environment. +## R2: Supabase filings and the eviction trial + +The `supabase-backups` R2 bucket is wired in both directions: the +nightly job files its newest dump into Drive, and the reaper can evict +bucket objects the cold store provably holds. Access is a minimal +stdlib S3 client (SigV4) at the account's R2 host, with bucket-scoped +credentials from the environment only — materialize from Bitwarden, +never store: + +```sh +R2_ACCESS_KEY_ID= \ +R2_SECRET_ACCESS_KEY= \ + cold-store backup-supabase +``` + +The host defaults to the account's `*.r2.cloudflarestorage.com` +endpoint (override with `COLD_STORE_R2_HOST`; tests stub the whole +base with `COLD_STORE_S3_BASE`). + +### backup-supabase + +Lists the bucket (paginated ListObjectsV2), picks the **newest backup +object by LastModified** — `pg/muse-dev/manifest.json` excluded; it is +the backup system's own index, not a dump — downloads it, and files it +via `put-backup` as a `supabase` backup. The download is verified +against the response's Content-Length, and a truncated body (observed +live through this sandbox's egress proxy) retries the whole GET, up +to 3 attempts. Filing is point-in-time, like `backup-d1`: unchanged +content is filed again, and the command prints the content sha256 so +the duplication is visible rather than silent. + +### Eviction + +```sh +cold-store evict-scan # verdicts only, never deletes +cold-store evict-scan --min-age-days 30 --keep-newest 5 +cold-store evict --apply # delete the evictable, re-verified +``` + +`evict-scan` prints one verdict per bucket object (`manifest.json` +excluded). An object is **evictable** only if _all_ of these hold: + +- **(a) hash known** — the key is content-addressed + (`.api.jsonl.zst`), so the manifest can be consulted at all; +- **(b) cold in a verified bundle** — the manifest has the object + `state='cold'` and a member of a bundle whose state is `verified` + (Drive upload MD5-checked at ingest); +- **(c) old enough** — LastModified at least `--min-age-days` ago + (default 14); +- **(d) not protected** — not among the `--keep-newest` newest objects + in the bucket (default 3). + +Every other object gets the first failing reason: `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 LastModified stamps, so position-first would mask the +age verdict). The scan is a pure read: it never deletes. + +`evict` recomputes the scan and, without `--apply`, prints it and +exits non-zero — deletion requires the literal flag. With `--apply`, +each evictable object is **re-verified against the manifest at +deletion time** (the scan may be stale; nothing is deleted on a stale +verdict), then deleted via S3, marked `state='evicted'` in the +manifest, and recorded in the ledger (`direction='trash'`, +`kind='evict'`, `ref=`). One object's failure is reported and +does not abort the rest. + +The `'evicted'` state is a schema v1.2 extension (see `schema.sql`): +local manifests are migrated in place on first open, but the **D1 +copy of the schema 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 same caveat the +v1.1 `'trash'` direction had). + ## Manifest sync → D1 The local SQLite manifest is the reaper's working copy; the hosted copy @@ -193,20 +280,23 @@ API-driven deploy procedure. ## Configuration -| Knob | Default | -| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Home dir | `$COLD_STORE_HOME` or `~/.config/cold-store` (or `--home`) | -| Bundle target size (design constant) | 8 GiB (`pack` packs what it is given) | -| Upload chunk size | 8 MiB | -| Endpoints | Google; overridable via `COLD_STORE_TOKEN_URL`, `COLD_STORE_DRIVE_BASE`, `COLD_STORE_UPLOAD_BASE` (used by tests) | -| D1 sync | `CLOUDFLARE_API_TOKEN` from env only; account/db via `COLD_STORE_CF_ACCOUNT_ID` / `COLD_STORE_CF_D1_DATABASE_ID` or `state.json`; base via `COLD_STORE_D1_BASE` | -| zstd binary | `/usr/local/bin/zstd`, or `$COLD_STORE_ZSTD` | +| Knob | Default | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Home dir | `$COLD_STORE_HOME` or `~/.config/cold-store` (or `--home`) | +| Bundle target size (design constant) | 8 GiB (`pack` packs what it is given) | +| Upload chunk size | 8 MiB | +| Endpoints | Google; overridable via `COLD_STORE_TOKEN_URL`, `COLD_STORE_DRIVE_BASE`, `COLD_STORE_UPLOAD_BASE` (used by tests) | +| D1 sync | `CLOUDFLARE_API_TOKEN` from env only; account/db via `COLD_STORE_CF_ACCOUNT_ID` / `COLD_STORE_CF_D1_DATABASE_ID` or `state.json`; base via `COLD_STORE_D1_BASE` | +| R2 (S3) | `R2_ACCESS_KEY_ID` / `R2_SECRET_ACCESS_KEY` from env only; host via `COLD_STORE_R2_HOST`, whole base via `COLD_STORE_S3_BASE` (tests); default bucket `supabase-backups` | +| zstd binary | `/usr/local/bin/zstd`, or `$COLD_STORE_ZSTD` | ## Tests Stdlib `unittest`, no network, no credentials — a fake Drive HTTP server (token endpoint, folder create/list, resumable upload sessions with 308 -resume, `files.get`, Range downloads) runs in a thread: +resume, `files.get`, Range downloads), a stubbed D1 REST endpoint, and a +fake S3 endpoint (SigV4 capture, paginated listings, a truncate-once +download mode) run in threads: ```sh python3 -m unittest discover -s pkgs/cold-store-reaper/tests -v diff --git a/pkgs/cold-store-reaper/cold_store.py b/pkgs/cold-store-reaper/cold_store.py index 69e51d7b5e..e1369f80a8 100755 --- a/pkgs/cold-store-reaper/cold_store.py +++ b/pkgs/cold-store-reaper/cold_store.py @@ -18,6 +18,8 @@ import argparse import hashlib +import hmac +import http.client import json import mimetypes import os @@ -28,6 +30,7 @@ import urllib.error import urllib.parse import urllib.request +import xml.etree.ElementTree as ET from datetime import datetime, timedelta, timezone from pathlib import Path @@ -63,6 +66,86 @@ D1_SYNC_PARAM_BUDGET = 90 +# R2 (DESIGN.md sections 4-5): the supabase-backups bucket is both a +# nightly filing source (backup-supabase) and the first eviction trial +# bucket. Access is the S3 API at the account's R2 host, with +# bucket-scoped credentials from the environment only. +DEFAULT_R2_HOST = "234b866b99ce2b142d7963d8d139cbfa.r2.cloudflarestorage.com" +DEFAULT_R2_BUCKET = "supabase-backups" +R2_SIGNING_REGION = "auto" # R2 is region-agnostic; SigV4 still needs one +S3_GET_ATTEMPTS = 3 + + +def s3_error_message(body: bytes) -> str: + """Best-effort extraction from an S3 XML error body.""" + m = re.search(rb"([^<]+)", body or b"") + if m: + return m.group(1).decode("utf-8", "replace") + text = (body or b"").decode("utf-8", "replace").strip() + return text[:200] if text else "no error detail in response body" + + +def _header_value(headers: dict, name: str): + for k, v in headers.items(): + if k.lower() == name.lower(): + return v + return None + + +def _xml_local(tag: str) -> str: + return tag.rsplit("}", 1)[-1] + + +def _parse_s3_list_page(body: bytes): + """One ListObjectsV2 page -> (objects, is_truncated, next_token). + + Namespace-agnostic (S3 replies carry a default xmlns; a stub may + omit it). Each object is {key, size, last_modified}; last_modified + is an aware datetime, or None when absent/unparseable — callers + treat None as oldest, never as 'now'. + """ + root = ET.fromstring(body) + objects = [] + truncated = False + token = None + for child in root: + name = _xml_local(child.tag) + if name == "IsTruncated": + truncated = (child.text or "").strip().lower() == "true" + elif name == "NextContinuationToken": + token = child.text + elif name == "Contents": + fields = {_xml_local(c.tag): c.text for c in child} + stamp = None + raw = fields.get("LastModified") + if raw: + try: + stamp = datetime.fromisoformat(raw.replace("Z", "+00:00")) + except ValueError: + stamp = None + objects.append( + { + "key": fields.get("Key") or "", + "size": int(fields.get("Size") or 0), + "last_modified": stamp, + } + ) + return objects, truncated, token + + +def content_hash_from_key(key: str) -> str | None: + """The content sha256 a content-addressed R2 key carries, or None. + + Trial-bucket keys look like pg/muse-dev/2026/10/.api.jsonl.zst: + the basename's first dot-segment is the hash when it is 64-hex — + the same hash the manifest keys objects by. + """ + stem = key.rsplit("/", 1)[-1].split(".", 1)[0] + if re.fullmatch(r"[0-9a-f]{64}", stem): + return stem + return None + + def d1_sync_batch_rows(ncols: int) -> int: """Rows per sync statement for a table with ncols columns.""" return max(1, D1_SYNC_PARAM_BUDGET // ncols) @@ -154,6 +237,7 @@ def __init__( upload_base=None, zstd=None, d1_base=None, + s3_base=None, ): self.home = Path(home) self.credentials_path = self.home / "credentials.json" @@ -172,6 +256,11 @@ def __init__( self.d1_base = ( d1_base or os.environ.get("COLD_STORE_D1_BASE", DEFAULT_D1_BASE) ).rstrip("/") + self.s3_base = ( + s3_base + or os.environ.get("COLD_STORE_S3_BASE") + or ("https://" + os.environ.get("COLD_STORE_R2_HOST", DEFAULT_R2_HOST)) + ).rstrip("/") candidate = zstd or os.environ.get("COLD_STORE_ZSTD") or "/usr/local/bin/zstd" if not Path(candidate).exists(): candidate = "zstd" # fall back to PATH lookup @@ -238,6 +327,7 @@ def db(self) -> sqlite3.Connection: conn.executescript(SCHEMA_PATH.read_text()) conn.commit() self._migrate_ledger_trash(conn) + self._migrate_objects_evicted(conn) return conn @staticmethod @@ -267,6 +357,42 @@ def _migrate_ledger_trash(conn) -> None: conn.execute(index.group(0)) conn.commit() + @staticmethod + def _migrate_objects_evicted(conn) -> None: + """Let pre-v4 manifests record the 'evicted' object state: + rebuild objects with the current schema.sql CHECK if its CHECK + predates 'evicted'. members references objects by name, so the + new table is built under a scratch name, copied into, and + renamed over the dropped original — with foreign keys off, + because dropping a referenced parent would otherwise fail. + No-op for fresh or already-migrated databases.""" + row = conn.execute( + "SELECT sql FROM sqlite_master WHERE type='table' AND name='objects'" + ).fetchone() + if row is None or "'evicted'" in (row["sql"] or ""): + return + text = SCHEMA_PATH.read_text() + create = re.search(r"CREATE TABLE IF NOT EXISTS objects \(.*?\);", text, re.S) + index = re.search(r"CREATE INDEX IF NOT EXISTS idx_objects_state[^;]*;", text) + if create is None or index is None: + raise ColdStoreError("schema.sql is missing the objects definition") + cols = [r["name"] for r in conn.execute("PRAGMA table_info(objects)")] + collist = ", ".join(cols) + if conn.in_transaction: + conn.commit() + conn.execute("PRAGMA foreign_keys = OFF") + try: + conn.execute(create.group(0).replace("objects", "objects_new", 1)) + conn.execute( + f"INSERT INTO objects_new ({collist}) SELECT {collist} FROM objects" + ) + conn.execute("DROP TABLE objects") + conn.execute("ALTER TABLE objects_new RENAME TO objects") + conn.execute(index.group(0)) + conn.commit() + finally: + conn.execute("PRAGMA foreign_keys = ON") + @staticmethod def _schema_missing(conn) -> bool: row = conn.execute( @@ -1142,6 +1268,285 @@ def backup_d1(self) -> dict: result["rows"] = total return result + # ------------------------------------------------------------------- s3 + @staticmethod + def _r2_credentials() -> tuple[str, str]: + access = os.environ.get("R2_ACCESS_KEY_ID") + secret = os.environ.get("R2_SECRET_ACCESS_KEY") + if not access or not secret: + raise ColdStoreError( + "R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY are not set — " + "materialize them from Bitwarden (cloudflare.r2-backups-*) " + "into the environment first (they are never stored)" + ) + return access, secret + + def _s3_signed_headers(self, method: str, path: str, query: str) -> dict: + """SigV4 headers for one R2 request (payload is always empty: + the client only lists, downloads and deletes).""" + access, secret = self._r2_credentials() + host = urllib.parse.urlparse(self.s3_base).netloc + now = datetime.now(timezone.utc) + amz_date = now.strftime("%Y%m%dT%H%M%SZ") + date_stamp = now.strftime("%Y%m%d") + payload_hash = hashlib.sha256(b"").hexdigest() + signed = "host;x-amz-content-sha256;x-amz-date" + canonical_headers = ( + f"host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n" + ) + canonical_request = "\n".join( + [method, path, query, canonical_headers, signed, payload_hash] + ) + scope = f"{date_stamp}/{R2_SIGNING_REGION}/s3/aws4_request" + string_to_sign = "\n".join( + [ + "AWS4-HMAC-SHA256", + amz_date, + scope, + hashlib.sha256(canonical_request.encode()).hexdigest(), + ] + ) + + def _hmac(key, msg): + return hmac.new(key, msg.encode(), hashlib.sha256).digest() + + k_signing = _hmac( + _hmac( + _hmac(_hmac(("AWS4" + secret).encode(), date_stamp), R2_SIGNING_REGION), + "s3", + ), + "aws4_request", + ) + signature = hmac.new( + k_signing, string_to_sign.encode(), hashlib.sha256 + ).hexdigest() + return { + "Authorization": ( + f"AWS4-HMAC-SHA256 Credential={access}/{scope}, " + f"SignedHeaders={signed}, Signature={signature}" + ), + "x-amz-content-sha256": payload_hash, + "x-amz-date": amz_date, + } + + def _s3_request(self, method, bucket, key=None, query=None): + """One signed S3 request; returns (status, headers, body).""" + path = "/" + urllib.parse.quote(bucket, safe="") + if key is not None: + path += "/" + urllib.parse.quote(key, safe="/") + canonical_query = urllib.parse.urlencode( + sorted((query or {}).items()), quote_via=urllib.parse.quote + ) + url = self.s3_base + path + if canonical_query: + url += "?" + canonical_query + headers = self._s3_signed_headers(method, path, canonical_query) + return http_request(method, url, headers=headers) + + @staticmethod + def _s3_check(status: int, body: bytes, what: str) -> None: + if status >= 300: + raise ColdStoreError( + f"S3 {what} failed (HTTP {status}): {s3_error_message(body)}" + ) + + def s3_list_objects(self, bucket: str) -> list[dict]: + """Every object in the bucket, following ListObjectsV2 + continuation tokens until the listing is complete.""" + out: list[dict] = [] + token = None + while True: + query = {"list-type": "2"} + if token: + query["continuation-token"] = token + status, _h, resp = self._s3_request("GET", bucket, query=query) + self._s3_check(status, resp, f"list of {bucket}") + page, truncated, token = _parse_s3_list_page(resp) + out.extend(page) + if not truncated: + return out + + def s3_get_object(self, bucket: str, key: str) -> bytes: + """Download one object, verifying the received byte count + against Content-Length. A truncated body — seen live through + this sandbox's egress proxy, where urllib surfaces it as an + http.client.IncompleteRead (an HTTPException) or a short read — + retries the whole GET, up to S3_GET_ATTEMPTS attempts.""" + problem = "no attempt made" + for _attempt in range(S3_GET_ATTEMPTS): + try: + status, headers, resp = self._s3_request("GET", bucket, key=key) + except (http.client.HTTPException, ColdStoreError) as e: + problem = str(e) + continue + self._s3_check(status, resp, f"GET {bucket}/{key}") + expected = _header_value(headers, "Content-Length") + if expected is not None and len(resp) != int(expected): + problem = f"truncated body: got {len(resp)} of {expected} bytes" + continue + return resp + raise ColdStoreError( + f"S3 GET {bucket}/{key} failed after {S3_GET_ATTEMPTS} attempts: {problem}" + ) + + def s3_delete_object(self, bucket: str, key: str) -> None: + status, _h, resp = self._s3_request("DELETE", bucket, key=key) + self._s3_check(status, resp, f"DELETE {bucket}/{key}") + + # ---------------------------------------------------------- backup from R2 + def backup_supabase(self, bucket: str = DEFAULT_R2_BUCKET) -> dict: + """File the newest Supabase backup object from R2 as a supabase + backup (DESIGN section 5), via the put-backup machinery. + + 'Newest' is by S3 LastModified among the bucket's backup + objects; manifest.json is excluded — it is the backup system's + own index, not a dump. The download is byte-count verified + (s3_get_object). Filing is point-in-time, exactly like + backup-d1: unchanged content is filed again, and the content + sha256 is reported so the duplication is visible. + """ + epoch = datetime.min.replace(tzinfo=timezone.utc) + objects = [ + o + for o in self.s3_list_objects(bucket) + if o["key"].rsplit("/", 1)[-1] != "manifest.json" + ] + if not objects: + raise ColdStoreError(f"no backup objects found in R2 bucket {bucket}") + newest = max(objects, key=lambda o: (o["last_modified"] or epoch, o["key"])) + data = self.s3_get_object(bucket, newest["key"]) + staging = self.home / "staging" + staging.mkdir(parents=True, exist_ok=True) + path = staging / newest["key"].rsplit("/", 1)[-1] + path.write_bytes(data) + result = self.put_backup("supabase", str(path)) + result["sha256"] = hashlib.sha256(data).hexdigest() + result["source_bucket"] = bucket + result["source_key"] = newest["key"] + return result + + # --------------------------------------------------------------- eviction + def _object_cold_verified(self, conn, obj_hash: str): + """(manifest state or None, member of a verified bundle?) — + the two manifest facts every eviction decision rests on.""" + row = conn.execute( + "SELECT state FROM objects WHERE hash = ?", (obj_hash,) + ).fetchone() + if row is None: + return None, False + member = conn.execute( + "SELECT 1 AS x FROM members m JOIN bundles b" + " ON b.bundle_id = m.bundle_id" + " WHERE m.object_hash = ? AND b.state = 'verified' LIMIT 1", + (obj_hash,), + ).fetchone() + return row["state"], member is not None + + def evict_scan( + self, + bucket: str = DEFAULT_R2_BUCKET, + min_age_days: int = 14, + keep_newest: int = 3, + ) -> list[dict]: + """One verdict per R2 object (manifest.json excluded): may it + be evicted from R2 because the cold store already holds it? + + An object is 'evictable' only if ALL hold: (a) its content hash + is known (content-addressed key), (b) the manifest has it + 'cold' in a verified bundle, (c) its LastModified is at least + min_age_days old, (d) it is not among the keep_newest newest + objects in the bucket. Anything else gets the first failing + reason, checked in this order: hash-unknown / not-in-manifest / + bundle-unverified / too-young / kept-newest. (Age is checked + before position: a young object always has one of the newest + LastModified stamps, so position-first would mask the age + verdict entirely.) The scan never deletes. + """ + epoch = datetime.min.replace(tzinfo=timezone.utc) + objects = [ + o + for o in self.s3_list_objects(bucket) + if o["key"].rsplit("/", 1)[-1] != "manifest.json" + ] + newest_first = sorted( + objects, + key=lambda o: (o["last_modified"] or epoch, o["key"]), + reverse=True, + ) + protected = {o["key"] for o in newest_first[: max(keep_newest, 0)]} + now = datetime.now(timezone.utc) + min_age = timedelta(days=min_age_days) + conn = self.db() + scan = [] + for obj in newest_first: + entry = {**obj, "hash": content_hash_from_key(obj["key"])} + if entry["hash"] is None: + entry["verdict"] = "hash-unknown" + else: + state, verified = self._object_cold_verified(conn, entry["hash"]) + if state != "cold": + entry["verdict"] = "not-in-manifest" + entry["detail"] = ( + "no manifest row" + if state is None + else f"manifest state is {state!r}, not 'cold'" + ) + elif not verified: + entry["verdict"] = "bundle-unverified" + elif ( + obj["last_modified"] is None or now - obj["last_modified"] < min_age + ): + entry["verdict"] = "too-young" + elif obj["key"] in protected: + entry["verdict"] = "kept-newest" + else: + entry["verdict"] = "evictable" + scan.append(entry) + conn.close() + return scan + + def evict_apply(self, bucket: str, scan: list[dict]) -> list[dict]: + """Delete a scan's evictable objects from R2, one by one. + + Each candidate is RE-VERIFIED against the manifest at deletion + time (state 'cold' in a verified bundle) — the scan may be + stale, and nothing is ever deleted on a stale verdict. After a + successful DELETE, the object's manifest state becomes + 'evicted' and one ledger row is written (direction 'trash', + kind 'evict', ref = R2 key). One object's failure is recorded + in its outcome and does not abort the rest. + """ + outcomes = [] + conn = self.db() + for entry in scan: + if entry["verdict"] != "evictable": + continue + key = entry["key"] + try: + state, verified = self._object_cold_verified(conn, entry["hash"]) + if state != "cold" or not verified: + outcomes.append( + { + "key": key, + "outcome": "skipped", + "detail": "re-verify failed at deletion time " + f"(state={state!r}, verified bundle={verified})", + } + ) + continue + self.s3_delete_object(bucket, key) + with conn: + conn.execute( + "UPDATE objects SET state='evicted' WHERE hash=?", + (entry["hash"],), + ) + self.ledger_add(conn, "trash", entry["size"], "evict", key) + outcomes.append({"key": key, "outcome": "evicted", "detail": ""}) + except ColdStoreError as e: + outcomes.append({"key": key, "outcome": "failed", "detail": str(e)}) + conn.close() + return outcomes + # ---------------------------------------------------------------- status def status_data(self) -> dict: conn = self.db() @@ -1200,6 +1605,26 @@ def _human(n: int) -> str: return f"{n} bytes ({n / 1e9:.2f} GB)" +def _print_evict_scan(scan: list[dict]) -> None: + counts: dict[str, int] = {} + for entry in scan: + counts[entry["verdict"]] = counts.get(entry["verdict"], 0) + 1 + stamp = ( + entry["last_modified"].strftime("%Y-%m-%dT%H:%M:%SZ") + if entry["last_modified"] + else "unknown-time" + ) + line = ( + f"{entry['key']}: {entry['verdict']} " + f"({_human(entry['size'])}, last modified {stamp})" + ) + if entry.get("detail"): + line += f" — {entry['detail']}" + print(line) + summary = ", ".join(f"{k} {v}" for k, v in sorted(counts.items())) + print(f"summary: {len(scan)} object(s) scanned: {summary or 'none'}") + + def main(argv=None) -> int: parser = argparse.ArgumentParser( prog="cold-store", description=__doc__.splitlines()[0] @@ -1273,6 +1698,30 @@ def main(argv=None) -> int: "backup-d1", help="export the D1 cold-store-manifest database and file it as a d1 backup", ) + p_backup_sb = sub.add_parser( + "backup-supabase", + help="file the newest Supabase backup object from R2 into db-backups/supabase/", + ) + p_backup_sb.add_argument("--bucket", default=DEFAULT_R2_BUCKET) + p_evict_scan = sub.add_parser( + "evict-scan", + help="dry-run: verdict per R2 object — evictable only if cold in a verified bundle, old enough, and not among the newest kept (never deletes)", + ) + p_evict_scan.add_argument("--bucket", default=DEFAULT_R2_BUCKET) + p_evict_scan.add_argument("--min-age-days", type=int, default=14) + p_evict_scan.add_argument("--keep-newest", type=int, default=3) + p_evict = sub.add_parser( + "evict", + help="delete evictable objects from R2 (requires --apply; each is re-verified against the manifest at deletion time)", + ) + p_evict.add_argument("--bucket", default=DEFAULT_R2_BUCKET) + p_evict.add_argument("--min-age-days", type=int, default=14) + p_evict.add_argument("--keep-newest", type=int, default=3) + p_evict.add_argument( + "--apply", + action="store_true", + help="actually delete (without it, prints the scan and exits non-zero)", + ) args = parser.parse_args(argv) store = build_store(args) try: @@ -1387,6 +1836,36 @@ def main(argv=None) -> int: f"uploaded to Drive as {result['drive_file_id']} " f"({result['rows']} row(s) across {len(result['tables'])} table(s))" ) + elif args.cmd == "backup-supabase": + result = store.backup_supabase(args.bucket) + print( + f"backup {result['name']}: {_human(result['bytes'])}, " + f"sha256 {result['sha256']}, " + f"uploaded to Drive as {result['drive_file_id']} " + f"(from r2://{result['source_bucket']}/{result['source_key']})" + ) + elif args.cmd == "evict-scan": + scan = store.evict_scan(args.bucket, args.min_age_days, args.keep_newest) + _print_evict_scan(scan) + elif args.cmd == "evict": + scan = store.evict_scan(args.bucket, args.min_age_days, args.keep_newest) + _print_evict_scan(scan) + if not args.apply: + raise ColdStoreError( + "evict deletes objects from R2 — the scan above is a " + "dry run; re-run with --apply to delete the evictable " + "objects" + ) + outcomes = store.evict_apply(args.bucket, scan) + for o in outcomes: + line = f"{o['outcome']}: {o['key']}" + if o["detail"]: + line += f" — {o['detail']}" + print(line) + done = sum(1 for o in outcomes if o["outcome"] == "evicted") + print( + f"evict: {done} object(s) evicted, {len(outcomes) - done} not evicted" + ) except ColdStoreError as e: print(f"error: {e}", file=sys.stderr) return 1 diff --git a/pkgs/cold-store-reaper/schema.sql b/pkgs/cold-store-reaper/schema.sql index 9d657731e2..ef61287e58 100644 --- a/pkgs/cold-store-reaper/schema.sql +++ b/pkgs/cold-store-reaper/schema.sql @@ -1,5 +1,9 @@ -- Cold-store manifest schema v1 (2026-10-25) -- Canonical index for the Drive cold store. Drive holds bundles; this DB is the system. +-- v1.2 (reaper v4): objects.state gains 'evicted' — still cold in Drive, but +-- deleted from R2 by `cold-store evict`. The D1 copy of this schema needs the +-- same one-line CHECK change before evicted rows can sync; sync-manifest +-- surfaces D1's own error text until then. CREATE TABLE IF NOT EXISTS objects ( hash TEXT PRIMARY KEY, -- sha256 hex of object content size INTEGER NOT NULL, @@ -9,7 +13,7 @@ CREATE TABLE IF NOT EXISTS objects ( first_seen TEXT NOT NULL DEFAULT (datetime('now')), last_seen_hot TEXT, -- last time it was present in R2 state TEXT NOT NULL DEFAULT 'hot' - CHECK (state IN ('hot','staging','cold','rehydrating','gone')) + CHECK (state IN ('hot','staging','cold','rehydrating','gone','evicted')) ); CREATE INDEX IF NOT EXISTS idx_objects_state ON objects(state); diff --git a/pkgs/cold-store-reaper/scripts/nightly-backup.sh b/pkgs/cold-store-reaper/scripts/nightly-backup.sh index 0b340be7dd..4ab171ec4b 100755 --- a/pkgs/cold-store-reaper/scripts/nightly-backup.sh +++ b/pkgs/cold-store-reaper/scripts/nightly-backup.sh @@ -6,12 +6,17 @@ # Steps, in order: # 1. cold-store backup-d1 export the D1 cold-store-manifest # database and file it in db-backups/d1/ -# 2. cold-store prune-backups --apply +# 2. cold-store backup-supabase file the newest Supabase backup object +# from R2 in db-backups/supabase/ — +# only when the R2 credentials below +# are set; skipped (not an error) +# otherwise +# 3. cold-store prune-backups --apply # enforce 30 daily / 12 weekly / # 12 monthly retention across all DBs -# 3. cold-store sync-manifest push the local manifest (including +# 4. cold-store sync-manifest push the local manifest (including # tonight's ledger rows) to D1 -# 4. cold-store status one-screen summary (head) +# 5. cold-store status one-screen summary (head) # # Environment — the operator/cron supplies these; the script itself # stores nothing and echoes no secret values: @@ -19,6 +24,12 @@ # (cloudflare.api-token-day-to-day) into the # cron environment; backup-d1 and sync-manifest # read it from the environment only. +# R2_ACCESS_KEY_ID optional. Bucket-scoped S3 credentials for the +# R2_SECRET_ACCESS_KEY supabase-backups bucket (Bitwarden: +# cloudflare.r2-backups-access-key-id / +# cloudflare.r2-backups-secret-access-key). +# When either is unset, step 2 is skipped with +# a one-line notice instead of failing the run. # COLD_STORE_HOME optional; the reaper home (default # ~/.config/cold-store). That directory's # credentials.json holds the Drive grant. @@ -32,6 +43,11 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" COLD_STORE="${SCRIPT_DIR}/../cold-store" "${COLD_STORE}" backup-d1 +if [[ -n ${R2_ACCESS_KEY_ID:-} && -n ${R2_SECRET_ACCESS_KEY:-} ]]; then + "${COLD_STORE}" backup-supabase +else + echo "nightly-backup: R2 credentials not set — skipping backup-supabase" +fi "${COLD_STORE}" prune-backups --apply "${COLD_STORE}" sync-manifest "${COLD_STORE}" status | head -n 20 diff --git a/pkgs/cold-store-reaper/tests/test_cold_store.py b/pkgs/cold-store-reaper/tests/test_cold_store.py index ddc3dda67b..9549758a15 100644 --- a/pkgs/cold-store-reaper/tests/test_cold_store.py +++ b/pkgs/cold-store-reaper/tests/test_cold_store.py @@ -5,7 +5,9 @@ or: python3 pkgs/cold-store-reaper/tests/test_cold_store.py """ +import contextlib import hashlib +import io import json import os import re @@ -18,7 +20,7 @@ import threading import unittest import urllib.parse -from datetime import date, timedelta +from datetime import date, datetime, timedelta, timezone from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from unittest import mock @@ -495,6 +497,178 @@ def do_POST(self): return Handler +# -------------------------------------------------------------------- fake S3 +class FakeS3: + """In-memory state for the fake R2 S3 endpoint. + + Listings are served in pages of `page_size` objects no matter what + the client asks for, so pagination is always exercised. A key in + `truncate_once` gets one response whose body stops halfway while + its Content-Length promises the whole object — the truncated-read + case the real client must retry. + """ + + BUCKET = "supabase-backups" + + def __init__(self): + self.objects = {} # key -> {"body": bytes, "last_modified": str} + self.deleted = [] # keys, in DELETE order + self.requests = [] # {"method", "path", "query", "headers"} + self.truncate_once = set() + self._truncated = set() + self.page_size = 2 + + def put(self, key, body: bytes, last_modified: str): + self.objects[key] = {"body": body, "last_modified": last_modified} + + def get_requests(self, key): + return [ + r + for r in self.requests + if r["method"] == "GET" and r["path"].endswith("/" + key) + ] + + +def make_s3_handler(fake: FakeS3): + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): # silence + pass + + def _record(self): + parsed = urllib.parse.urlparse(self.path) + fake.requests.append( + { + "method": self.command, + "path": parsed.path, + "query": urllib.parse.parse_qs(parsed.query), + "headers": {k.lower(): v for k, v in self.headers.items()}, + } + ) + return parsed + + def _send(self, code, body=b"", ctype="application/xml"): + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + if body: + self.wfile.write(body) + + def _error(self, code, message): + body = ( + '' + f"NoSuchKey{message}" + ).encode() + self._send(code, body) + + def do_GET(self): + parsed = self._record() + qs = urllib.parse.parse_qs(parsed.query) + rest = parsed.path.lstrip("/").split("/", 1) + if len(rest) == 1: # bucket root: ListObjectsV2 + start = int(qs.get("continuation-token", ["0"])[0]) + keys = sorted(fake.objects) + page = keys[start : start + fake.page_size] + truncated = start + fake.page_size < len(keys) + contents = "".join( + f"{k}" + f"{fake.objects[k]['last_modified']}" + f"{len(fake.objects[k]['body'])}" + for k in page + ) + token = ( + f"{start + fake.page_size}" + "" + if truncated + else "" + ) + body = ( + '' + '' + f"{FakeS3.BUCKET}" + f"{str(truncated).lower()}" + f"{contents}{token}" + ).encode() + self._send(200, body) + return + key = urllib.parse.unquote(rest[1]) + obj = fake.objects.get(key) + if obj is None: + self._error(404, "The specified key does not exist.") + return + body = obj["body"] + if key in fake.truncate_once and key not in fake._truncated: + fake._truncated.add(key) + self.send_response(200) + self.send_header("Content-Type", "application/octet-stream") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body[: len(body) // 2]) + self.close_connection = True + return + self._send(200, body, ctype="application/octet-stream") + + def do_DELETE(self): + parsed = self._record() + rest = parsed.path.lstrip("/").split("/", 1) + key = urllib.parse.unquote(rest[1]) + if key not in fake.objects: + self._error(404, "The specified key does not exist.") + return + del fake.objects[key] + fake.deleted.append(key) + self._send(204) + + return Handler + + +class S3TestBase(ColdStoreTestBase): + """ColdStoreTestBase plus a fake S3 endpoint wired into the store, + with dummy R2 credentials in the environment (values are fake; the + real ones are operator-supplied from Bitwarden, never stored).""" + + R2_ENV = { + "R2_ACCESS_KEY_ID": "test-access-key", + "R2_SECRET_ACCESS_KEY": "test-secret-key", + } + + def setUp(self): + super().setUp() + self.s3 = FakeS3() + self.s3_server = ThreadingHTTPServer(("127.0.0.1", 0), make_s3_handler(self.s3)) + self.s3_thread = threading.Thread( + target=self.s3_server.serve_forever, daemon=True + ) + self.s3_thread.start() + self.s3_base_url = f"http://127.0.0.1:{self.s3_server.server_address[1]}" + self.store.s3_base = self.s3_base_url + self._r2_env = mock.patch.dict(os.environ, self.R2_ENV) + self._r2_env.start() + + def tearDown(self): + self._r2_env.stop() + self.s3_server.shutdown() + self.s3_server.server_close() + super().tearDown() + + @staticmethod + def key_for(obj_hash): + return f"pg/muse-dev/2026/10/{obj_hash}.api.jsonl.zst" + + def make_cold(self, contents: dict) -> dict: + """Pack {name: bytes} into one bundle and upload it against the + fake Drive: every object ends up cold in a verified bundle. + Returns {name: sha256}.""" + files = [str(self.write_src(name, data)) for name, data in contents.items()] + packed = self.store.pack(files) + self.store.upload(packed["bundle_id"]) + return { + name: hashlib.sha256(data).hexdigest() for name, data in contents.items() + } + + class TestBackups(ColdStoreTestBase): def test_ensure_folders_creates_backup_subfolders_once(self): first = self.store.ensure_folders() @@ -901,6 +1075,301 @@ def test_backup_d1_requires_token(self): self.store.backup_d1() +class TestS3Client(S3TestBase): + def test_sigv4_header_shape(self): + self.s3.put("pg/muse-dev/manifest.json", b"{}", "2026-10-01T00:00:00.000Z") + self.store.s3_list_objects("supabase-backups") + req = self.s3.requests[0] + auth = req["headers"]["authorization"] + self.assertIsNotNone( + re.fullmatch( + r"AWS4-HMAC-SHA256 Credential=test-access-key/\d{8}" + r"/auto/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256" + r";x-amz-date, Signature=[0-9a-f]{64}", + auth, + ), + auth, + ) + # GET signs the empty-payload hash + self.assertEqual( + req["headers"]["x-amz-content-sha256"], hashlib.sha256(b"").hexdigest() + ) + self.assertRegex(req["headers"]["x-amz-date"], r"^\d{8}T\d{6}Z$") + self.assertEqual(req["query"]["list-type"], ["2"]) + + def test_list_pagination(self): + for i in range(5): + self.s3.put(f"pg/muse-dev/k{i}.bin", b"x", "2026-10-01T00:00:00.000Z") + objects = self.store.s3_list_objects("supabase-backups") + self.assertEqual([o["key"] for o in objects], sorted(self.s3.objects)) + list_calls = [r for r in self.s3.requests if r["path"] == "/supabase-backups"] + self.assertEqual(len(list_calls), 3) # fake pages are 2, 2, 1 + self.assertNotIn("continuation-token", list_calls[0]["query"]) + self.assertEqual(list_calls[1]["query"]["continuation-token"], ["2"]) + self.assertEqual(list_calls[2]["query"]["continuation-token"], ["4"]) + for o in objects: + self.assertEqual(o["size"], 1) + self.assertIsNotNone(o["last_modified"]) + + def test_missing_credentials_error(self): + env = { + k: v + for k, v in os.environ.items() + if k not in ("R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY") + } + with mock.patch.dict(os.environ, env, clear=True): + with self.assertRaises(cold_store.ColdStoreError) as ctx: + self.store.s3_list_objects("supabase-backups") + self.assertIn("R2_ACCESS_KEY_ID", str(ctx.exception)) + + +class TestBackupSupabase(S3TestBase): + def test_files_newest_non_manifest_with_truncation_retry(self): + older = b"older backup " * 40 + newest = b"newest backup payload " * 60 + old_key = self.key_for(hashlib.sha256(older).hexdigest()) + new_key = self.key_for(hashlib.sha256(newest).hexdigest()) + self.s3.put(old_key, older, "2026-10-20T02:00:00.000Z") + self.s3.put(new_key, newest, "2026-10-21T02:00:00.000Z") + # the bucket manifest is newer still — and is never a dump filing + self.s3.put("pg/muse-dev/manifest.json", b"{}", "2026-10-22T02:00:00.000Z") + # the first GET of the newest object arrives truncated (the + # live proxy failure mode); the client must retry the whole GET + self.s3.truncate_once.add(new_key) + result = self.store.backup_supabase() + self.assertEqual(result["source_key"], new_key) + self.assertRegex( + result["name"], + r"^supabase-\d{8}T\d{6}Z-" + re.escape(new_key.rsplit("/", 1)[-1]) + r"$", + ) + self.assertEqual(result["sha256"], hashlib.sha256(newest).hexdigest()) + folders = self.store.ensure_folders() + meta = self.fake.file_meta[result["drive_file_id"]] + self.assertEqual(meta["parents"], [folders["db-backups/supabase"]]) + # byte-count verification did its job: the filed copy is the + # whole object, not the truncated first response + self.assertEqual(self.fake.files[result["drive_file_id"]], newest) + self.assertGreaterEqual(len(self.s3.get_requests(new_key)), 2) + + def test_no_backup_objects_errors(self): + self.s3.put("pg/muse-dev/manifest.json", b"{}", "2026-10-22T02:00:00.000Z") + with self.assertRaises(cold_store.ColdStoreError): + self.store.backup_supabase() + + +class EvictTestBase(S3TestBase): + """One bucket holding every eviction verdict at once. + + LastModified order (newest first): young (now-1d), oldtimer + (2026-06), evict2, evict1, unknown, not-in-manifest, unverified — + with keep_newest=2 the protected pair is {young, oldtimer}; age is + checked before position, so young reports too-young and oldtimer + (old enough on its own) is the isolated kept-newest case. + """ + + def setUp(self): + super().setUp() + self.h = self.make_cold( + { + "young.bin": b"young object " * 30, + "oldtimer.bin": b"oldtimer object " * 30, + "evict1.bin": b"evict me one " * 30, + "evict2.bin": b"evict me two " * 30, + } + ) + self.keys = { + "young": self.key_for(self.h["young.bin"]), + "oldtimer": self.key_for(self.h["oldtimer.bin"]), + "evict1": self.key_for(self.h["evict1.bin"]), + "evict2": self.key_for(self.h["evict2.bin"]), + "unverified": self.key_for("d" * 64), + "not-in-manifest": self.key_for("e" * 64), + "unknown": "pg/muse-dev/2026/01/random-file.bin", + "manifest": "pg/muse-dev/manifest.json", + } + # a cold object whose only bundle was never verified + conn = self.store.db() + with conn: + conn.execute( + "INSERT INTO objects (hash, size, state) VALUES (?, ?, 'cold')", + ("d" * 64, 123), + ) + conn.execute( + "INSERT INTO bundles (bundle_id, sha256, bytes, state)" + " VALUES ('b_unverified00', ?, 123, 'sealed')", + ("f" * 64,), + ) + conn.execute( + "INSERT INTO members (bundle_id, object_hash, offset, length)" + " VALUES ('b_unverified00', ?, 0, 10)", + ("d" * 64,), + ) + conn.close() + young_lm = (datetime.now(timezone.utc) - timedelta(days=1)).strftime( + "%Y-%m-%dT%H:%M:%SZ" + ) + self.s3.put(self.keys["manifest"], b"{}", "2026-10-25T00:00:00.000Z") + self.s3.put(self.keys["young"], b"y", young_lm) + self.s3.put(self.keys["oldtimer"], b"o", "2026-06-01T00:00:00.000Z") + self.s3.put(self.keys["evict1"], b"1", "2026-01-05T00:00:00.000Z") + self.s3.put(self.keys["evict2"], b"2", "2026-01-06T00:00:00.000Z") + self.s3.put(self.keys["unverified"], b"u", "2026-01-02T00:00:00.000Z") + self.s3.put(self.keys["not-in-manifest"], b"n", "2026-01-03T00:00:00.000Z") + self.s3.put(self.keys["unknown"], b"?", "2026-01-04T00:00:00.000Z") + + def scan_by_key(self, **kwargs): + kwargs.setdefault("min_age_days", 14) + kwargs.setdefault("keep_newest", 2) + return {e["key"]: e for e in self.store.evict_scan(**kwargs)} + + +class TestEvictScan(EvictTestBase): + def test_verdict_matrix(self): + scan = self.scan_by_key() + self.assertEqual(len(scan), 7) # manifest.json is excluded + self.assertNotIn(self.keys["manifest"], scan) + self.assertEqual(scan[self.keys["young"]]["verdict"], "too-young") + self.assertEqual(scan[self.keys["oldtimer"]]["verdict"], "kept-newest") + self.assertEqual(scan[self.keys["evict1"]]["verdict"], "evictable") + self.assertEqual(scan[self.keys["evict2"]]["verdict"], "evictable") + self.assertEqual(scan[self.keys["unverified"]]["verdict"], "bundle-unverified") + self.assertEqual( + scan[self.keys["not-in-manifest"]]["verdict"], "not-in-manifest" + ) + self.assertEqual(scan[self.keys["unknown"]]["verdict"], "hash-unknown") + # a scan is a dry run: nothing deleted, nothing mutated + self.assertEqual(self.s3.deleted, []) + self.assertIn(self.keys["evict1"], self.s3.objects) + + +class TestEvictApply(EvictTestBase): + def test_apply_deletes_only_evictable_and_records(self): + scan = self.store.evict_scan(min_age_days=14, keep_newest=2) + outcomes = self.store.evict_apply("supabase-backups", scan) + self.assertEqual( + {o["key"] for o in outcomes if o["outcome"] == "evicted"}, + {self.keys["evict1"], self.keys["evict2"]}, + ) + self.assertEqual( + sorted(self.s3.deleted), + sorted([self.keys["evict1"], self.keys["evict2"]]), + ) + for name in ("young", "oldtimer", "unverified", "not-in-manifest", "unknown"): + self.assertIn(self.keys[name], self.s3.objects) + conn = self.store.db() + states = { + r["hash"]: r["state"] + for r in conn.execute("SELECT hash, state FROM objects") + } + rows = conn.execute( + "SELECT * FROM transfer_ledger WHERE kind='evict'" + ).fetchall() + conn.close() + self.assertEqual(states[self.h["evict1.bin"]], "evicted") + self.assertEqual(states[self.h["evict2.bin"]], "evicted") + self.assertEqual(states[self.h["young.bin"]], "cold") + self.assertEqual(len(rows), 2) + self.assertEqual( + {r["ref"] for r in rows}, {self.keys["evict1"], self.keys["evict2"]} + ) + for r in rows: + self.assertEqual(r["direction"], "trash") + + def test_apply_reverifies_and_skips_changed_object(self): + scan = self.store.evict_scan(min_age_days=14, keep_newest=2) + # between scan and apply the object stops being cold — the + # deletion-time re-verification must refuse to delete it + conn = self.store.db() + with conn: + conn.execute( + "UPDATE objects SET state='hot' WHERE hash=?", + (self.h["evict1.bin"],), + ) + conn.close() + outcomes = { + o["key"]: o for o in self.store.evict_apply("supabase-backups", scan) + } + self.assertEqual(outcomes[self.keys["evict1"]]["outcome"], "skipped") + self.assertEqual(outcomes[self.keys["evict2"]]["outcome"], "evicted") + self.assertEqual(self.s3.deleted, [self.keys["evict2"]]) + self.assertIn(self.keys["evict1"], self.s3.objects) + + def test_cli_refuses_without_apply(self): + env = dict(self.R2_ENV) + env["COLD_STORE_S3_BASE"] = self.s3_base_url + out, err = io.StringIO(), io.StringIO() + with mock.patch.dict(os.environ, env): + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + rc = cold_store.main( + [ + "--home", + str(self.home), + "evict", + "--bucket", + "supabase-backups", + "--min-age-days", + "14", + "--keep-newest", + "2", + ] + ) + self.assertEqual(rc, 1) + self.assertIn("--apply", err.getvalue()) + self.assertIn("evictable", out.getvalue()) # the scan still printed + self.assertEqual(self.s3.deleted, []) + + +class TestObjectsEvictedMigration(ColdStoreTestBase): + def test_pre_v4_manifest_gains_evicted_state(self): + # Rebuild a manifest exactly as a pre-v4 home has it (objects + # CHECK without 'evicted'), with a cold object in a verified + # bundle, then open it via a store: the migration must admit + # 'evicted' and preserve the member row that references the + # rebuilt table. + legacy_home = Path(self.tmp.name) / "legacy-home-v4" + legacy_home.mkdir() + legacy_schema = cold_store.SCHEMA_PATH.read_text().replace(",'evicted')", ")") + self.assertIn( + "CHECK (state IN ('hot','staging','cold','rehydrating','gone'))", + legacy_schema, + ) + conn = sqlite3.connect(legacy_home / "manifest.sqlite") + conn.executescript(legacy_schema) + conn.execute( + "INSERT INTO objects (hash, size, state) VALUES (?, 10, 'cold')", + ("a" * 64,), + ) + conn.execute( + "INSERT INTO bundles (bundle_id, sha256, bytes, state)" + " VALUES ('b_legacy', ?, 10, 'verified')", + ("b" * 64,), + ) + conn.execute( + "INSERT INTO members (bundle_id, object_hash, offset, length)" + " VALUES ('b_legacy', ?, 0, 10)", + ("a" * 64,), + ) + conn.commit() + conn.close() + base = self.store.drive_base.rsplit("/drive/v3", 1)[0] + legacy = ColdStore( + legacy_home, + token_url=base + "/token", + drive_base=self.store.drive_base, + upload_base=base, + ) + conn = legacy.db() + with conn: + conn.execute("UPDATE objects SET state='evicted' WHERE hash=?", ("a" * 64,)) + row = conn.execute( + "SELECT state FROM objects WHERE hash=?", ("a" * 64,) + ).fetchone() + members = conn.execute("SELECT count(*) n FROM members").fetchone() + conn.close() + self.assertEqual(row["state"], "evicted") + self.assertEqual(members["n"], 1) + + class TestDrillCompare(ColdStoreTestBase): """restore-drill.sh's backup-vs-live check (scripts/drill_compare.py).