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
47 changes: 39 additions & 8 deletions pkgs/cold-store-reaper/cold_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,34 @@
DEFAULT_CF_ACCOUNT_ID = "234b866b99ce2b142d7963d8d139cbfa"
DEFAULT_CF_D1_DATABASE_ID = "15d5f460-835c-4f24-b229-222908a5b30c"
MANIFEST_TABLES = ("objects", "bundles", "members", "transfer_ledger", "meta")
D1_SYNC_BATCH_ROWS = 50
# D1 allows at most 100 bound parameters per query. A sync statement batches
# whole rows, so it costs rows x columns parameters: a flat row batch (50
# rows x 8 columns for objects = 400 params) is rejected once a table grows.
# Batch size is therefore computed per table from its column count against
# a 90-parameter budget, keeping headroom under the hard limit.
D1_MAX_PARAMS_PER_QUERY = 100
D1_SYNC_PARAM_BUDGET = 90


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)


def d1_error_message(resp: bytes) -> str:
"""Best-effort extraction of the D1 API's own error text from a
response body, so a sync failure is diagnosable from the CLI output
alone instead of just an HTTP status."""
try:
payload = json.loads(resp) if resp else {}
except (ValueError, TypeError):
payload = {}
errors = payload.get("errors") or []
if errors and errors[0].get("message"):
return str(errors[0]["message"])
text = (resp or b"").decode("utf-8", "replace").strip()
return text[:200] if text else "no error detail in response body"


# Design constant: bundles are sealed at this size in the full reaper;
# `pack` packs exactly what it is given regardless of size.
Expand Down Expand Up @@ -742,9 +769,11 @@ def build_sync_statements(self) -> tuple[list[dict], dict]:
"""Read the local manifest and build batched D1 upsert statements.

Returns (statements, per-table {"rows": n, "statements": m}). Each
statement carries at most D1_SYNC_BATCH_ROWS row-groups so a re-sync
is a handful of HTTP calls, and every statement is an idempotent
upsert keyed by the table's primary key from schema.sql.
table's batch is sized by d1_sync_batch_rows(len(cols)) so a
statement's bound parameters (rows x columns) stay within
D1_SYNC_PARAM_BUDGET, under D1's per-query limit. Every statement
is an idempotent upsert keyed by the table's primary key from
schema.sql, so a re-sync is a handful of HTTP calls.
"""
conn = self.db()
statements: list[dict] = []
Expand All @@ -755,9 +784,10 @@ def build_sync_statements(self) -> tuple[list[dict], dict]:
rows = conn.execute(
f"SELECT {', '.join(cols)} FROM {table} ORDER BY {order}"
).fetchall()
batch_rows = d1_sync_batch_rows(len(cols))
table_statements = 0
for i in range(0, len(rows), D1_SYNC_BATCH_ROWS):
chunk = rows[i : i + D1_SYNC_BATCH_ROWS]
for i in range(0, len(rows), batch_rows):
chunk = rows[i : i + batch_rows]
params: list = []
for row in chunk:
params.extend(row[c] for c in cols)
Expand Down Expand Up @@ -816,8 +846,9 @@ def sync_manifest(self, dry_run: bool = False) -> dict:
)
if status != 200:
raise ColdStoreError(
f"D1 sync failed (HTTP {status}) on table {stmt['table']} — "
"statements already sent are idempotent upserts, re-run to resume"
f"D1 sync failed (HTTP {status}) on table {stmt['table']}: "
f"{d1_error_message(resp)} — statements already sent are "
"idempotent upserts, re-run to resume"
)
payload = json.loads(resp) if resp else {}
if payload and not payload.get("success", True):
Expand Down
43 changes: 43 additions & 0 deletions pkgs/cold-store-reaper/tests/test_cold_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,12 +558,55 @@ def test_sync_posts_idempotent_upserts(self):
self.assertEqual(len(req["params"]) % col_counts[table], 0)
self.assertGreater(len(req["params"]), 0)

def test_sync_many_objects_stays_under_d1_param_limit(self):
# Regression: D1 allows at most 100 bound parameters per query,
# and the old flat 50-row batch put 50 x 8 = 400 params into one
# objects statement (already 112 params at 14 rows), which D1
# rejected with HTTP 400. Seed enough objects that the old
# batching would blow the limit, then assert every statement
# stays under it and every row of every table arrives.
conn = self.store.db()
for i in range(30):
digest = hashlib.sha256(f"seed-object-{i}".encode()).hexdigest()
conn.execute(
"INSERT INTO objects (hash, size, state) VALUES (?, ?, 'cold')",
(digest, 1000 + i),
)
conn.commit()
conn.close()
expected = self._row_counts()
# 13 objects x 8 columns = 104 params: the old batching already
# breaks below this seed size.
self.assertGreater(expected["objects"], 12)
with mock.patch.dict(os.environ, {"CLOUDFLARE_API_TOKEN": "fake-cf-token"}):
result = self.store.sync_manifest()
col_counts = {
"objects": 8,
"bundles": 10,
"members": 4,
"transfer_ledger": 6,
"meta": 2,
}
arrived = {t: 0 for t in cold_store.MANIFEST_TABLES}
for req in self.d1.requests:
# D1's hard per-query limit is 100 bound parameters.
self.assertLessEqual(len(req["params"]), 100)
table = re.match(r"INSERT INTO (\w+)", req["sql"]).group(1)
self.assertEqual(len(req["params"]) % col_counts[table], 0)
arrived[table] += len(req["params"]) // col_counts[table]
self.assertEqual(arrived, expected)
self.assertEqual(result["rows"], sum(expected.values()))
# objects batch is 90 // 8 = 11 rows, so 31 rows take 3 statements.
self.assertEqual(result["tables"]["objects"]["statements"], 3)

def test_sync_http_error_is_clear(self):
self.d1.fail = True
with mock.patch.dict(os.environ, {"CLOUDFLARE_API_TOKEN": "fake-cf-token"}):
with self.assertRaises(cold_store.ColdStoreError) as ctx:
self.store.sync_manifest()
self.assertIn("HTTP 500", str(ctx.exception))
# The D1 API's own error text rides along, not just the status.
self.assertIn("fake failure", str(ctx.exception))

def test_sync_requires_token(self):
with mock.patch.dict(os.environ, self._env_without_token(), clear=True):
Expand Down
Loading