Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions pkgs/cold-store-reaper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,20 @@ 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.

If urllib still cannot deliver the object whole, the download falls
back to **one `curl` attempt** (curl does its own SigV4 signing via
`--aws-sigv4` and reads the proxy from the environment). Why: through
this sandbox's egress proxy, small responses truncate only
intermittently — retries absorb those — but multi-megabyte responses
truncate _systematically_ (live: every attempt cut at exactly
409,600 bytes), and curl is immune; the Supabase backup tooling
established the same replay-with-curl precedent, and the reaper
already shells out to a CLI for compression (`zstd`). The curl body
gets the same byte-count verification (the listing's size, or a HEAD
Content-Length when the caller has none), credentials are scrubbed
from any error text, and a missing or failing curl surfaces as a
named `ColdStoreError`, never a traceback.

### Eviction

```sh
Expand Down Expand Up @@ -289,17 +303,19 @@ API-driven deploy procedure.
| 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` |
| curl binary (S3 download fallback) | `curl` on PATH, or `$COLD_STORE_CURL` |

## 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), a stubbed D1 REST endpoint, and a
fake S3 endpoint (SigV4 capture, paginated listings, a truncate-once
download mode) run in threads:
fake S3 endpoint (SigV4 capture, paginated listings, truncate-once
and truncate-always download modes) run in threads:

```sh
python3 -m unittest discover -s pkgs/cold-store-reaper/tests -v
```

Requirements: Python 3.12, the `zstd` CLI. Everything else is stdlib.
Requirements: Python 3.12, the `zstd` CLI, and `curl` (runtime only,
for the S3 download fallback). Everything else is stdlib.
130 changes: 123 additions & 7 deletions pkgs/cold-store-reaper/cold_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
"""cold-store reaper v1: archive files into Google Drive as immutable,
content-addressed bundles of concatenated per-object zstd frames.

Stdlib only. Compression/decompression is delegated to the `zstd` CLI.
Stdlib only. Compression/decompression is delegated to the `zstd` CLI,
and S3 downloads that urllib cannot deliver whole fall back to the
`curl` CLI (see s3_get_object).

Identity model (see README.md): the OAuth app holds ONLY the drive.file
scope, so it can see nothing but files/folders it creates itself. On first
Expand Down Expand Up @@ -75,6 +77,10 @@
DEFAULT_R2_BUCKET = "supabase-backups"
R2_SIGNING_REGION = "auto" # R2 is region-agnostic; SigV4 still needs one
S3_GET_ATTEMPTS = 3
# The curl fallback for S3 downloads (s3_get_object) is a last resort
# for objects urllib cannot deliver whole; it gets one attempt and a
# generous timeout — the objects it exists for are the large ones.
S3_CURL_TIMEOUT_SECONDS = 900
# Transport-level retries inside the S3 layer (LIST/GET/DELETE are all
# idempotent). Through some egress proxies, urllib responses are
# intermittently truncated mid-body or the connection drops outright;
Expand Down Expand Up @@ -107,6 +113,17 @@ def s3_error_message(body: bytes) -> str:
return text[:200] if text else "no error detail in response body"


def _scrub_secrets(text: str, *values: str) -> str:
"""Replace credential values in text destined for an error
message. The curl fallback passes credentials in argv (visible in
the local process list, like any CLI); they must still never land
in logs or error text."""
for v in values:
if v:
text = text.replace(v, "***")
return text


def _header_value(headers: dict, name: str):
for k, v in headers.items():
if k.lower() == name.lower():
Expand Down Expand Up @@ -260,6 +277,7 @@ def __init__(
zstd=None,
d1_base=None,
s3_base=None,
curl=None,
):
self.home = Path(home)
self.credentials_path = self.home / "credentials.json"
Expand Down Expand Up @@ -287,6 +305,9 @@ def __init__(
if not Path(candidate).exists():
candidate = "zstd" # fall back to PATH lookup
self.zstd = candidate
# curl is the S3 download fallback of last resort
# (s3_get_object); PATH lookup unless overridden, like zstd.
self.curl = curl or os.environ.get("COLD_STORE_CURL") or "curl"
self._access_token = None
# Injectable so tests can zero it: transport-retry backoff for
# the S3 layer (see _s3_request).
Expand Down Expand Up @@ -1424,12 +1445,25 @@ def s3_list_objects(self, bucket: str) -> list[dict]:
if not truncated:
return out

def s3_get_object(self, bucket: str, key: str) -> bytes:
def s3_get_object(
self, bucket: str, key: str, expected_size: int | None = None
) -> 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."""
retries the whole GET, up to S3_GET_ATTEMPTS attempts.

If urllib ultimately cannot deliver the object whole, fall
back to ONE curl attempt (_s3_get_via_curl): small responses
truncate intermittently and retries absorb them, but
multi-megabyte responses truncate systematically through this
proxy (every attempt cut at the same byte count), while curl
is immune — the same reason the Supabase backup tooling
replays downloads with curl. `expected_size`, when the caller
knows it (backup-supabase has it from the listing), is the
byte count the curl body is verified against.
"""
problem = "no attempt made"
for _attempt in range(S3_GET_ATTEMPTS):
try:
Expand All @@ -1443,9 +1477,91 @@ def s3_get_object(self, bucket: str, key: str) -> bytes:
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}"
)
try:
return self._s3_get_via_curl(bucket, key, expected_size=expected_size)
except ColdStoreError as e:
raise ColdStoreError(
f"S3 GET {bucket}/{key} failed after {S3_GET_ATTEMPTS} "
f"urllib attempts ({problem}); {e}"
) from None

def _s3_get_via_curl(
self, bucket: str, key: str, expected_size: int | None = None
) -> bytes:
"""One curl download of one object, byte-count verified.

The expected size is the caller's when given, else a urllib
HEAD's Content-Length (HEAD has no body for the proxy to
truncate). A body whose length cannot be established is not
accepted: an unverifiable download is exactly what this path
exists to avoid. Errors are detail-only — the caller
(s3_get_object) names the operation, bucket and key.
"""
access, secret = self._r2_credentials()
if expected_size is None:
try:
status, headers, _body = self._s3_request("HEAD", bucket, key=key)
if status == 200:
length = _header_value(headers, "Content-Length")
if length is not None:
expected_size = int(length)
except ColdStoreError:
pass # no size from HEAD either; handled below
if expected_size is None:
raise ColdStoreError(
"curl fallback could not determine the object's size "
"(no caller size, no HEAD Content-Length); refusing "
"an unverifiable download"
)
path = "/" + urllib.parse.quote(bucket, safe="")
path += "/" + urllib.parse.quote(key, safe="/")
body = self._curl_fetch(self.s3_base + path, access, secret)
if len(body) != expected_size:
raise ColdStoreError(
f"curl fallback delivered {len(body)} of {expected_size} "
"bytes (truncated)"
)
return body

def _curl_fetch(self, url: str, access: str, secret: str) -> bytes:
"""GET `url` with curl, which does its own SigV4 signing
(--aws-sigv4) and reads the proxy from the environment itself.
Credentials travel in argv — the local process list sees them,
as with any credentialed CLI — but they are scrubbed from every
error this raises, and nothing here is logged.
"""
argv = [
self.curl,
"-sS",
"--fail",
"--aws-sigv4",
"aws:amz:auto:s3",
"--user",
f"{access}:{secret}",
url,
]
try:
proc = subprocess.run(
argv, capture_output=True, timeout=S3_CURL_TIMEOUT_SECONDS
)
except FileNotFoundError:
raise ColdStoreError(
f"curl binary not found (looked for {self.curl!r}) — "
"the S3 curl fallback needs curl on PATH"
) from None
except subprocess.TimeoutExpired:
raise ColdStoreError(
f"curl fallback timed out after {S3_CURL_TIMEOUT_SECONDS}s"
) from None
if proc.returncode != 0:
detail = _scrub_secrets(
proc.stderr.decode("utf-8", "replace").strip()[:200], access, secret
)
raise ColdStoreError(
f"curl fallback failed (exit {proc.returncode}): "
f"{detail or 'no error output'}"
)
return proc.stdout

def s3_delete_object(self, bucket: str, key: str) -> None:
status, _h, resp = self._s3_request("DELETE", bucket, key=key)
Expand All @@ -1472,7 +1588,7 @@ def backup_supabase(self, bucket: str = DEFAULT_R2_BUCKET) -> dict:
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"])
data = self.s3_get_object(bucket, newest["key"], expected_size=newest["size"])
staging = self.home / "staging"
staging.mkdir(parents=True, exist_ok=True)
path = staging / newest["key"].rsplit("/", 1)[-1]
Expand Down
124 changes: 122 additions & 2 deletions pkgs/cold-store-reaper/tests/test_cold_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,9 @@ class FakeS3:
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.
case the real client must retry. A key in `truncate_always` gets
that response every time — the systematic large-object truncation
that only the curl fallback survives.
"""

BUCKET = "supabase-backups"
Expand All @@ -515,6 +517,7 @@ def __init__(self):
self.deleted = [] # keys, in DELETE order
self.requests = [] # {"method", "path", "query", "headers"}
self.truncate_once = set()
self.truncate_always = set()
self._truncated = set()
self.page_size = 2
# Transport-failure injection for LIST requests: a queue of
Expand Down Expand Up @@ -624,7 +627,9 @@ def do_GET(self):
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:
if key in fake.truncate_always or (
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")
Expand All @@ -635,6 +640,21 @@ def do_GET(self):
return
self._send(200, body, ctype="application/octet-stream")

def do_HEAD(self):
parsed = self._record()
rest = parsed.path.lstrip("/").split("/", 1)
key = urllib.parse.unquote(rest[1]) if len(rest) > 1 else ""
obj = fake.objects.get(key)
if obj is None:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(len(obj["body"])))
self.end_headers()

def do_DELETE(self):
parsed = self._record()
rest = parsed.path.lstrip("/").split("/", 1)
Expand Down Expand Up @@ -1244,6 +1264,106 @@ def test_no_backup_objects_errors(self):
self.store.backup_supabase()


class TestS3CurlFallback(S3TestBase):
"""The curl fallback in s3_get_object: multi-megabyte R2
responses truncate SYSTEMATICALLY through the sandbox egress
proxy (live: every urllib attempt cut at exactly 409,600 bytes),
which no amount of urllib retrying survives — so once urllib is
exhausted, one curl attempt (stubbed here at the _curl_fetch
transport seam; no network, no real curl) delivers the object,
byte-count verified like the urllib path."""

BODY = b"large backup payload " * 500

def _persistent_truncation(self, body=None):
"""The newest bucket object, truncated on every urllib GET."""
body = self.BODY if body is None else body
key = self.key_for(hashlib.sha256(body).hexdigest())
self.s3.put(key, body, "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")
self.s3.truncate_always.add(key)
return key

def _stub_curl(self, body):
"""Patch the store's curl transport; return the call log. Each
entry records how many urllib GETs of `key` had happened when
curl was invoked, proving the fallback fires only after
urllib exhaustion, never alongside it."""
calls = []

def fake_fetch(url, access, secret):
calls.append(
{
"url": url,
"access": access,
"secret": secret,
"get_requests": {
k: len(self.s3.get_requests(k)) for k in self.s3.objects
},
}
)
return body

return mock.patch.object(self.store, "_curl_fetch", fake_fetch), calls

def test_fallback_after_urllib_exhaustion_files_backup(self):
key = self._persistent_truncation()
patcher, calls = self._stub_curl(self.BODY)
with patcher:
result = self.store.backup_supabase()
# exactly one curl attempt, and only after urllib was fully
# exhausted: S3_GET_ATTEMPTS outer loops, each burning
# S3_TRANSPORT_ATTEMPTS transport attempts on the object GET
self.assertEqual(len(calls), 1)
self.assertEqual(
calls[0]["get_requests"][key],
cold_store.S3_GET_ATTEMPTS * cold_store.S3_TRANSPORT_ATTEMPTS,
)
self.assertTrue(calls[0]["url"].endswith("/" + key))
self.assertEqual(calls[0]["access"], "test-access-key")
# the fallback body was byte-verified and filed whole
self.assertEqual(result["source_key"], key)
self.assertEqual(result["sha256"], hashlib.sha256(self.BODY).hexdigest())
self.assertEqual(self.fake.files[result["drive_file_id"]], self.BODY)

def test_short_curl_body_named_error_nothing_filed(self):
key = self._persistent_truncation()
files_before = dict(self.fake.files)
patcher, calls = self._stub_curl(self.BODY[:100])
with patcher:
with self.assertRaises(cold_store.ColdStoreError) as ctx:
self.store.backup_supabase()
self.assertEqual(len(calls), 1)
message = str(ctx.exception)
self.assertIn("supabase-backups", message)
self.assertIn(key, message)
self.assertIn("curl fallback delivered 100 of", message)
self.assertNotIn("test-secret-key", message)
self.assertEqual(self.fake.files, files_before)

def test_curl_never_invoked_on_urllib_happy_path(self):
body = b"small backup " * 20
key = self.key_for(hashlib.sha256(body).hexdigest())
self.s3.put(key, body, "2026-10-21T02:00:00.000Z")
patcher, calls = self._stub_curl(body)
with patcher:
result = self.store.backup_supabase()
self.assertEqual(calls, [])
self.assertEqual(result["sha256"], hashlib.sha256(body).hexdigest())

def test_fallback_sizes_via_head_when_caller_gives_none(self):
key = self._persistent_truncation()
patcher, calls = self._stub_curl(self.BODY)
with patcher:
data = self.store.s3_get_object("supabase-backups", key)
self.assertEqual(data, self.BODY)
self.assertEqual(len(calls), 1)
head_requests = [r for r in self.s3.requests if r["method"] == "HEAD"]
self.assertEqual(len(head_requests), 1)
self.assertTrue(head_requests[0]["path"].endswith("/" + key))


class EvictTestBase(S3TestBase):
"""One bucket holding every eviction verdict at once.

Expand Down
Loading