From 008e662c6c7454557f1fdcff48f51966e60794ac Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Mon, 26 Oct 2026 01:21:21 +0000 Subject: [PATCH 1/2] fix(cold-store-reaper): size D1 sync batches by bound parameters, surface D1 error text D1 allows at most 100 bound parameters per query, but sync-manifest batched a flat 50 rows per statement: objects has 8 columns, so the statement carried 112 params at just 14 rows and D1 rejected it (HTTP 400). Batch size is now computed per table from its column count: batch_rows = max(1, 90 // ncols), so rows x columns stays within a 90-parameter budget under the hard limit for every table. Also include the D1 API's own errors[0].message in the HTTP-failure message, so a failed sync is diagnosable from the CLI output alone. --- pkgs/cold-store-reaper/cold_store.py | 47 +++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/pkgs/cold-store-reaper/cold_store.py b/pkgs/cold-store-reaper/cold_store.py index bf11eb081e..592c97fda3 100755 --- a/pkgs/cold-store-reaper/cold_store.py +++ b/pkgs/cold-store-reaper/cold_store.py @@ -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. @@ -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] = [] @@ -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) @@ -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): From 36dd14bcd12c69fab29c33662fac2c12756e1da6 Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Mon, 26 Oct 2026 01:24:07 +0000 Subject: [PATCH 2/2] test(cold-store-reaper): regression for D1 sync parameter limit Seed 30 extra objects (31 total) so the old flat 50-row batch would emit one 248-parameter statement; assert every statement stays at or under D1's 100 bound parameters, that per-table arrived row counts match the local manifest exactly, and that objects splits into 3 statements at the 90 // 8 = 11-row batch. Verified failing on the pre-fix code with '248 not less than or equal to 100'. Also assert the HTTP-error message now carries the D1 API's own error text ('fake failure' from the stub), not just the status. --- .../tests/test_cold_store.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/pkgs/cold-store-reaper/tests/test_cold_store.py b/pkgs/cold-store-reaper/tests/test_cold_store.py index b1c4ccdb4a..115959fd3d 100644 --- a/pkgs/cold-store-reaper/tests/test_cold_store.py +++ b/pkgs/cold-store-reaper/tests/test_cold_store.py @@ -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):