From 1464829fd52af7c0d6a7157a5bf877a68731b3e9 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 20:53:38 -0600 Subject: [PATCH 01/12] fix(fleet-queue-backup): follow the live D1 import contract (ingest + bookmark poll) (#8584) The first live export run (2026-11-22) reached the D1 import step and was rejected: the live API requires the four-step flow init -> upload -> ingest -> poll, with poll identified by the current_bookmark the ingest step returns. import_sql skipped ingest and polled with the filename, which the API rejects with "current_bookmark => Required". The hermetic suite never exercised D1Client.import_sql, so the drift was invisible until the live run. Also: poll completion is the result status reaching complete (a result error aborts), and the poll bound grows to 360 x 5s = 30 min, sized to a full-store import of ~600k statements. New tests/test_d1_import.py fakes the documented contract and pins the step order and poll payload. And the export service gains TimeoutStartSec=2h: the user manager default (90s) would kill every scheduled run -- the first live run's read phase alone took ~24 minutes. --- infra/fleet-queue-backup/bin/fq_common.py | 33 +++-- .../systemd/fleet-queue-backup-export.service | 6 + .../tests/test_d1_import.py | 117 ++++++++++++++++++ 3 files changed, 149 insertions(+), 7 deletions(-) create mode 100644 infra/fleet-queue-backup/tests/test_d1_import.py diff --git a/infra/fleet-queue-backup/bin/fq_common.py b/infra/fleet-queue-backup/bin/fq_common.py index 2242836dec..cb71d45c9a 100755 --- a/infra/fleet-queue-backup/bin/fq_common.py +++ b/infra/fleet-queue-backup/bin/fq_common.py @@ -304,7 +304,15 @@ def query(self, db_id, sql, params=()): return result[0].get("results") or [] def import_sql(self, db_id, sql_text): - """Import SQL text via the D1 import API (init -> upload -> poll).""" + """Import SQL text via the D1 import API (init -> upload -> ingest -> poll). + + The poll step identifies the import by the current_bookmark + the ingest step returns (its at_bookmark); polling with the + filename instead is rejected by the live API with + "current_bookmark => Required" (seen on the first live run, + 2026-11-22, #8584). Completion is the result status reaching + "complete"; a result error aborts. + """ digest = hashlib.md5(sql_text.encode()).hexdigest() init = self._call( "POST", @@ -315,23 +323,34 @@ def import_sql(self, db_id, sql_text): req = urllib.request.Request(upload_url, data=sql_text.encode(), method="PUT") try: with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT_SECONDS) as resp: - etag = resp.headers.get("etag", "").strip('"') + etag = resp.headers.get("etag", "").strip("\"") except (urllib.error.URLError, TimeoutError, OSError) as exc: raise RuntimeError(f"D1 import upload failed: {exc}") from exc if etag != digest: raise RuntimeError( f"D1 import upload etag mismatch: sent {digest}, got {etag}" ) - for _attempt in range(60): + ingest = self._call( + "POST", + f"/accounts/{self.account}/d1/database/{db_id}/import", + {"action": "ingest", "etag": digest, "filename": filename}, + ) + bookmark = ingest.get("at_bookmark") + if not bookmark: + raise RuntimeError(f"D1 import ingest returned no at_bookmark: {ingest}") + # A full-store import executes ~600k statements server-side; + # the poll bound (360 x 5s = 30 min) is sized to that, not to + # the hermetic fixtures. + for _attempt in range(360): poll = self._call( "POST", f"/accounts/{self.account}/d1/database/{db_id}/import", - {"action": "poll", "filename": filename}, + {"action": "poll", "current_bookmark": bookmark}, ) - if poll.get("success"): - return poll if poll.get("error"): - raise RuntimeError(f"D1 import failed: {poll['error']}") + raise RuntimeError(f"D1 import failed: {poll["error"]}") + if poll.get("status") == "complete": + return poll time.sleep(5) raise RuntimeError("D1 import did not complete within the poll bound") diff --git a/infra/fleet-queue-backup/systemd/fleet-queue-backup-export.service b/infra/fleet-queue-backup/systemd/fleet-queue-backup-export.service index ebccd1d7d4..d2805096ae 100644 --- a/infra/fleet-queue-backup/systemd/fleet-queue-backup-export.service +++ b/infra/fleet-queue-backup/systemd/fleet-queue-backup-export.service @@ -5,4 +5,10 @@ Wants=network-online.target [Service] Type=oneshot +# A full export reads the whole queue store over the libsql HTTP API +# before the D1 import begins; the first live run's read phase alone +# took ~24 minutes (2026-11-22, #8584). The user manager's default +# start timeout (90s) would kill every scheduled run, so the bound is +# set from the measured cycle with headroom for import + verify. +TimeoutStartSec=2h ExecStart=/usr/bin/env bash __FQ_DIR__/systemd/run-export.sh diff --git a/infra/fleet-queue-backup/tests/test_d1_import.py b/infra/fleet-queue-backup/tests/test_d1_import.py new file mode 100644 index 0000000000..95181857fa --- /dev/null +++ b/infra/fleet-queue-backup/tests/test_d1_import.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""The D1 import flow must follow the live four-step contract. + +Oracle: a fake Cloudflare API. fq_common.http_json is replaced with a +recorder that answers init/ingest/poll per the documented contract +(developers.cloudflare.com, D1 database import method): init takes +{action, etag} and returns upload_url + filename; ingest takes +{action, etag, filename} and returns at_bookmark; poll takes +{action, current_bookmark} and completes when the result status is +"complete". The upload PUT is faked at urllib.request.urlopen and +answers with the md5 etag of the bytes it received. + +An earlier revision of import_sql skipped the ingest step and polled +with the filename; the live API rejects that with +"current_bookmark => Required" (first live run, 2026-11-22, #8584). +These tests pin the step order and the poll payload so the drift is +caught hermetically next time. + +Run: python3 -I infra/fleet-queue-backup/tests/test_d1_import.py +""" + +import hashlib +import os +import sys +import unittest +from unittest import mock + +BIN = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "bin")) +sys.path.insert(0, BIN) + +import fq_common + + +class FakeUploadResponse: + def __init__(self, etag): + self.headers = {"etag": etag} + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +class ImportFlowTest(unittest.TestCase): + def setUp(self): + self.calls = [] + self.poll_count = 0 + self.sql = "CREATE TABLE t (x);\nINSERT INTO t VALUES (1);\n" + self.digest = hashlib.md5(self.sql.encode()).hexdigest() + + def fake_http_json(method, url, token, payload=None, timeout=None): + self.calls.append((method, url, payload)) + action = payload["action"] + if action == "init": + self.assertEqual(payload, {"action": "init", "etag": self.digest}) + return {"success": True, "result": { + "upload_url": "https://upload.example/put", + "filename": "import.sql"}} + if action == "ingest": + self.assertEqual(payload, { + "action": "ingest", "etag": self.digest, + "filename": "import.sql"}) + return {"success": True, "result": {"at_bookmark": "bm-1"}} + if action == "poll": + self.assertEqual(payload, { + "action": "poll", "current_bookmark": "bm-1"}) + self.poll_count += 1 + if self.poll_count < 2: + return {"success": True, "result": {"status": "running"}} + return {"success": True, "result": { + "status": "complete", "result": {"num_queries": 2}}} + raise AssertionError("unexpected action " + action) + + def fake_urlopen(req, timeout=None): + self.assertEqual(req.full_url, "https://upload.example/put") + return FakeUploadResponse(hashlib.md5(req.data).hexdigest()) + + self._patches = [ + mock.patch.object(fq_common, "http_json", fake_http_json), + mock.patch.object(fq_common.urllib.request, "urlopen", fake_urlopen), + mock.patch.object(fq_common.time, "sleep", lambda _s: None), + ] + for p in self._patches: + p.start() + + def tearDown(self): + for p in self._patches: + p.stop() + + def test_import_follows_init_upload_ingest_poll(self): + client = fq_common.D1Client("token", "acct") + result = client.import_sql("db-id", self.sql) + self.assertEqual(result["status"], "complete") + actions = [c[2]["action"] for c in self.calls] + self.assertEqual(actions, ["init", "ingest", "poll", "poll"]) + + def test_import_error_aborts(self): + def failing_http_json(method, url, token, payload=None, timeout=None): + action = payload["action"] + if action == "init": + return {"success": True, "result": { + "upload_url": "https://upload.example/put", + "filename": "import.sql"}} + if action == "ingest": + return {"success": True, "result": {"at_bookmark": "bm-1"}} + return {"success": True, "result": { + "status": "error", "error": "near line 1: no such table"}} + + with mock.patch.object(fq_common, "http_json", failing_http_json): + client = fq_common.D1Client("token", "acct") + with self.assertRaises(RuntimeError): + client.import_sql("db-id", self.sql) + + +if __name__ == "__main__": + unittest.main() From 74aa3dddf597fa2202b6b40c328e53febd7bfb25 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 21:29:43 -0600 Subject: [PATCH 02/12] fix(fleet-queue-backup): retry the D1 import upload with a long timeout (#8584) Second live run (2026-11-22): the ingest fix worked, but the single PUT of the ~1 GB dump died with "The write operation timed out" under the 120s JSON-API socket timeout. The upload now uses UPLOAD_TIMEOUT_SECONDS=3600, and a transport failure re-runs init + upload up to 3 attempts -- the dump is already built, so an upload retry never re-reads the source store. API-level errors are still not retried. New hermetic test: a flaky first upload re-inits and completes. --- infra/fleet-queue-backup/bin/fq_common.py | 55 ++++++++++++++----- .../tests/test_d1_import.py | 20 +++++++ 2 files changed, 60 insertions(+), 15 deletions(-) diff --git a/infra/fleet-queue-backup/bin/fq_common.py b/infra/fleet-queue-backup/bin/fq_common.py index cb71d45c9a..1123126ca9 100755 --- a/infra/fleet-queue-backup/bin/fq_common.py +++ b/infra/fleet-queue-backup/bin/fq_common.py @@ -50,6 +50,11 @@ HTTP_TIMEOUT_SECONDS = 120 +# The D1 import upload PUTs the whole dump in one request (~1 GB for +# the live queue store); it gets a far longer socket timeout than the +# JSON API calls above it. +UPLOAD_TIMEOUT_SECONDS = 3600 + def _shape(value): return type(value).__name__ @@ -312,24 +317,44 @@ def import_sql(self, db_id, sql_text): "current_bookmark => Required" (seen on the first live run, 2026-11-22, #8584). Completion is the result status reaching "complete"; a result error aborts. + + The upload is a single PUT of the whole dump (~1 GB for the + live queue store), so it gets its own long timeout, and a + transport failure re-runs init + upload (the dump is already + built; an upload retry never re-reads the source). API-level + errors are not retried: they do not heal. """ digest = hashlib.md5(sql_text.encode()).hexdigest() - init = self._call( - "POST", - f"/accounts/{self.account}/d1/database/{db_id}/import", - {"action": "init", "etag": digest}, - ) - upload_url, filename = init["upload_url"], init["filename"] - req = urllib.request.Request(upload_url, data=sql_text.encode(), method="PUT") - try: - with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT_SECONDS) as resp: - etag = resp.headers.get("etag", "").strip("\"") - except (urllib.error.URLError, TimeoutError, OSError) as exc: - raise RuntimeError(f"D1 import upload failed: {exc}") from exc - if etag != digest: - raise RuntimeError( - f"D1 import upload etag mismatch: sent {digest}, got {etag}" + filename = None + for attempt in range(3): + init = self._call( + "POST", + f"/accounts/{self.account}/d1/database/{db_id}/import", + {"action": "init", "etag": digest}, ) + upload_url, filename = init["upload_url"], init["filename"] + req = urllib.request.Request( + upload_url, data=sql_text.encode(), method="PUT" + ) + try: + with urllib.request.urlopen( + req, timeout=UPLOAD_TIMEOUT_SECONDS + ) as resp: + etag = resp.headers.get("etag", "").strip('"') + except (urllib.error.URLError, TimeoutError, OSError) as exc: + if attempt == 2: + raise RuntimeError( + f"D1 import upload failed after 3 attempts: {exc}" + ) from exc + time.sleep(5) + continue + if etag == digest: + break + if attempt == 2: + raise RuntimeError( + f"D1 import upload etag mismatch: sent {digest}, got {etag}" + ) + time.sleep(5) ingest = self._call( "POST", f"/accounts/{self.account}/d1/database/{db_id}/import", diff --git a/infra/fleet-queue-backup/tests/test_d1_import.py b/infra/fleet-queue-backup/tests/test_d1_import.py index 95181857fa..7be655e280 100644 --- a/infra/fleet-queue-backup/tests/test_d1_import.py +++ b/infra/fleet-queue-backup/tests/test_d1_import.py @@ -76,6 +76,8 @@ def fake_urlopen(req, timeout=None): self.assertEqual(req.full_url, "https://upload.example/put") return FakeUploadResponse(hashlib.md5(req.data).hexdigest()) + self._good_urlopen = fake_urlopen + self._patches = [ mock.patch.object(fq_common, "http_json", fake_http_json), mock.patch.object(fq_common.urllib.request, "urlopen", fake_urlopen), @@ -113,5 +115,23 @@ def failing_http_json(method, url, token, payload=None, timeout=None): client.import_sql("db-id", self.sql) + def test_upload_failure_reinits_and_retries(self): + attempts = {"n": 0} + + def flaky_urlopen(req, timeout=None): + attempts["n"] += 1 + if attempts["n"] == 1: + raise fq_common.urllib.error.URLError( + "write operation timed out") + return self._good_urlopen(req, timeout=timeout) + + with mock.patch.object( + fq_common.urllib.request, "urlopen", flaky_urlopen): + client = fq_common.D1Client("token", "acct") + result = client.import_sql("db-id", self.sql) + self.assertEqual(result["status"], "complete") + actions = [c[2]["action"] for c in self.calls] + self.assertEqual(actions, ["init", "init", "ingest", "poll", "poll"]) + if __name__ == "__main__": unittest.main() From 5d09a5fa264c891281672dd5ded06cef86c64904 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 22:38:26 -0600 Subject: [PATCH 03/12] docs(registry): fleet-queue-backup-export.timer is installed (#8584) The live half ran 2026-11-22: units installed on the laptop via systemd/install-units.sh from the #12791 fix branch checkout, timer enabled and armed (first elapse Mon 2026-11-23 02:25 CST). The installed units run the repo scripts from ~/code-8584-turso-d1 until #12791 merges and that checkout is refreshed to main. --- doc/fleet-schedule-registry.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index 0dec803a0e..14fd1911ad 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -359,7 +359,7 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `git-maintenance@daily.timer` | `OnCalendar=Tue..Sun *-*-* 00:56:00` | `git-maintenance@daily.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `git-maintenance@hourly.timer` | `OnCalendar=*-*-* 01..23:56:00` | `git-maintenance@hourly.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `git-maintenance@weekly.timer` | `OnCalendar=Mon *-*-* 00:56:00` | `git-maintenance@weekly.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | -| `fleet-queue-backup-export.timer` (repo-shipped, not yet installed) | `OnCalendar=*-*-* 02:15:00` + `RandomizedDelaySec=30m` | `fleet-queue-backup-export.service` | laptop (user systemd; code#8584) | not recorded | Disable if a scheduled export cannot verify its read-back counts; repair the cause (credentials, D1, schema) and rerun before re-enabling | 2026-11-22 | 2026-11-22 | +| `fleet-queue-backup-export.timer` (installed on the laptop 2026-11-22, #8584 live half) | `OnCalendar=*-*-* 02:15:00` + `RandomizedDelaySec=30m` | `fleet-queue-backup-export.service` | laptop (user systemd; code#8584) | not recorded | Disable if a scheduled export cannot verify its read-back counts; repair the cause (credentials, D1, schema) and rerun before re-enabling | 2026-11-22 | 2026-11-22 | | `github-backup-drain.timer` | `OnCalendar=*-*-* *:00/5:00,OnBootUSec=3min` | `github-backup-drain.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `github-backup-fetch.timer` | `OnCalendar=*-*-* 00:00:00` | `github-backup-fetch.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `github-backup-r2.timer` (repo-shipped, not yet installed) | `OnCalendar=*-*-* 01:30:00` + `RandomizedDelaySec=30m` | `github-backup-r2.service` | laptop (user systemd; code#8584) | not recorded | Disable if any scheduled run cannot verify every planned R2 object; repair credentials or target and rerun before re-enabling | 2026-11-22 | 2026-11-22 | From 84eeef31500ba314ec0f7f7e393fb2298c7bc42a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 23:23:25 -0600 Subject: [PATCH 04/12] fix(fleet-queue-backup): split rows over the D1 statement limit (#8584) Third live-run finding: the first import with the ingest fix reached ingestion and failed with SQLITE_TOOBIG. D1 caps one statement at 100,000 bytes (D1 import docs, Statement too long section); exactly one live row renders over it: tasks id=12835 at 151,914 bytes (progress is 74,153 chars). build_dump now chunks the largest TEXT/BLOB cells of an oversized row: chunk 1 rides the INSERT, the rest are appended by UPDATE ... SET col = col || chunk statements keyed on the primary key with a running-length guard (BLOB appends CAST back, since SQLite || always yields TEXT). Every split is recorded and the exporter verifies the reassembled lengths in D1 after import. Rehearsed on the real row: 3 statements, max 90,000 bytes, rebuilt row identical to the source. New hermetic suite tests/test_statement_split.py (sqlite3 oracle, byte-exact rebuild incl. a no-PK table); full suite green. --- infra/fleet-queue-backup/bin/export_to_d1.py | 12 +- infra/fleet-queue-backup/bin/fq_common.py | 212 +++++++++++++++++- .../tests/test_fq_common.py | 4 +- .../tests/test_restore_drill.py | 2 +- .../tests/test_statement_split.py | 120 ++++++++++ 5 files changed, 340 insertions(+), 10 deletions(-) create mode 100644 infra/fleet-queue-backup/tests/test_statement_split.py diff --git a/infra/fleet-queue-backup/bin/export_to_d1.py b/infra/fleet-queue-backup/bin/export_to_d1.py index faafecc281..09c4582d19 100755 --- a/infra/fleet-queue-backup/bin/export_to_d1.py +++ b/infra/fleet-queue-backup/bin/export_to_d1.py @@ -41,7 +41,7 @@ def export(source_url, d1_name, create): _require_env("CLOUDFLARE_API_TOKEN"), _require_env("CLOUDFLARE_ACCOUNT_ID") ) exported_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - dump, counts = fq_common.build_dump(source, exported_at) + dump, counts, splits = fq_common.build_dump(source, exported_at) db = d1.find_database(d1_name) if db is None: if not create: @@ -52,6 +52,16 @@ def export(source_url, d1_name, create): db = d1.create_database(d1_name) db_id = db["uuid"] d1.import_sql(db_id, dump) + for table, col, where, expected in splits: + rows = d1.query( + db_id, + f'SELECT length("{col}") AS n FROM "{table}" WHERE {where}', + ) + if len(rows) != 1 or rows[0].get("n") != expected: + raise RuntimeError( + f"split-row verification failed for {table}.{col}: " + f"expected one row of length {expected}, got {rows}" + ) meta = d1.read_meta(db_id) if meta is None: raise RuntimeError("D1 copy has no export meta after import; import is suspect") diff --git a/infra/fleet-queue-backup/bin/fq_common.py b/infra/fleet-queue-backup/bin/fq_common.py index 1123126ca9..6018a8964c 100755 --- a/infra/fleet-queue-backup/bin/fq_common.py +++ b/infra/fleet-queue-backup/bin/fq_common.py @@ -28,6 +28,7 @@ import hashlib import json import os +import re import time import urllib.request @@ -55,6 +56,19 @@ # JSON API calls above it. UPLOAD_TIMEOUT_SECONDS = 3600 +# D1 caps one SQL statement at 100,000 bytes, and the import API +# enforces it: a larger statement fails the whole import with +# SQLITE_TOOBIG (seen live on the first #8584 export; the D1 import +# docs' "Statement too long" section names the same limit). A row +# whose quote()-rendered INSERT exceeds the cap is split instead: +# its largest TEXT/BLOB cells are chunked, chunk 1 riding the INSERT +# and the rest appended by UPDATE ... SET col = col || '' +# statements keyed on the table's primary key, each statement under +# the cap. build_dump records every split so the exporter can verify +# the reassembled lengths in D1 after the import. +MAX_IMPORT_STATEMENT_BYTES = 90_000 +SPLIT_CHUNK_BYTES = 40_000 + def _shape(value): return type(value).__name__ @@ -219,6 +233,182 @@ def read_table_quoted(client, table, ncols): ) +def _decode_literal(literal): + """Inverse of SQLite quote() for TEXT and BLOB literals. + + Returns ("text", str) or ("blob", bytes); (None, None) for anything + else (numbers, NULL) -- those are never split candidates. + """ + if len(literal) >= 2 and literal.startswith("'") and literal.endswith("'"): + return "text", literal[1:-1].replace("''", "'") + if len(literal) >= 3 and literal.startswith("X'") and literal.endswith("'"): + return "blob", bytes.fromhex(literal[2:-1]) + return None, None + + +def _render_literal(kind, value): + if kind == "text": + return "'" + value.replace("'", "''") + "'" + return "X'" + value.hex().upper() + "'" + + +def _value_chunks(kind, value, first_budget=None): + """Chunk a decoded TEXT/BLOB value: the first chunk is at most + `first_budget` bytes (default SPLIT_CHUNK_BYTES), later chunks at + most SPLIT_CHUNK_BYTES; sizes are UTF-8 bytes for text and a UTF-8 + sequence is never split.""" + limit = first_budget or SPLIT_CHUNK_BYTES + if kind == "text": + chunks, current, size = [], "", 0 + for ch in value: + n = len(ch.encode("utf-8")) + if current and size + n > limit: + chunks.append(current) + current, size = "", 0 + limit = SPLIT_CHUNK_BYTES + current += ch + size += n + if current or not chunks: + chunks.append(current) + return chunks + chunks = [value[:limit]] + rest = value[limit:] + chunks.extend( + rest[i : i + SPLIT_CHUNK_BYTES] + for i in range(0, len(rest), SPLIT_CHUNK_BYTES) + ) + return [c for c in chunks if c] or [b""] + + +def _pk_columns(create_sql): + """Primary-key column names from a CREATE TABLE statement, or None. + + Handles the two shapes the queue schema uses: a table-level + PRIMARY KEY (a, b) definition and an inline column PRIMARY KEY. + The parenthesised body is split into top-level definitions first, + so a single-line CREATE cannot confuse the match. + """ + start = create_sql.find("(") + if start < 0: + return None + depth, end = 0, None + for i in range(start, len(create_sql)): + if create_sql[i] == "(": + depth += 1 + elif create_sql[i] == ")": + depth -= 1 + if depth == 0: + end = i + break + if end is None: + return None + defs, depth, cur = [], 0, "" + for ch in create_sql[start + 1 : end]: + if ch == "(": + depth += 1 + elif ch == ")": + depth -= 1 + if ch == "," and depth == 0: + defs.append(cur) + cur = "" + else: + cur += ch + if cur.strip(): + defs.append(cur) + for d in defs: + m = re.match(r"\s*PRIMARY\s+KEY\s*\(([^)]*)\)", d, re.IGNORECASE) + if m: + return [c.strip().strip('"`[]') for c in m.group(1).split(",")] + for d in defs: + d = d.strip() + if d.upper().startswith( + ("PRIMARY", "FOREIGN", "UNIQUE", "CHECK", "CONSTRAINT") + ): + continue + m = re.match(r'"?([A-Za-z_][A-Za-z0-9_]*)"?\s+', d) + if m and re.search(r"\bPRIMARY\s+KEY\b", d, re.IGNORECASE): + return [m.group(1)] + return None + + +def _split_row_insert(table, colnames, row, pk_cols, splits): + """Render one oversized row as an INSERT plus UPDATE appends. + + The largest splittable (TEXT/BLOB) cells are chunked until the + INSERT fits under MAX_IMPORT_STATEMENT_BYTES; the remaining chunks + are appended by UPDATEs keyed on the primary key (or, when the + table declares none, on every unsplit column) with a running-length + guard, so a mis-keyed UPDATE matches nothing instead of corrupting + a row. Every split is recorded in `splits` as (table, column, + where_sql, expected_length) for post-import verification. A row + that cannot be split safely raises: a loud failure beats a silently + wrong backup copy. + """ + cells = list(row) + key_idx = [colnames.index(c) for c in pk_cols] if pk_cols else None + split_cells = {} + while True: + stmt = f'INSERT INTO "{table}" VALUES (' + ", ".join(cells) + ");" + if len(stmt.encode("utf-8")) <= MAX_IMPORT_STATEMENT_BYTES: + break + candidates = [ + i + for i in range(len(cells)) + if i not in split_cells + and i not in (key_idx or []) + and _decode_literal(cells[i])[0] is not None + ] + if not candidates: + raise RuntimeError( + f"{table}: row exceeds the D1 statement limit and has no " + "splittable cell left; refusing to emit it" + ) + target = max(candidates, key=lambda i: len(cells[i].encode("utf-8"))) + kind, value = _decode_literal(cells[target]) + byte_len = len(value.encode("utf-8")) if kind == "text" else len(value) + overflow = len(stmt.encode("utf-8")) - MAX_IMPORT_STATEMENT_BYTES + first_budget = max(1024, byte_len - overflow) + chunks = _value_chunks(kind, value, first_budget) + if len(chunks) < 2: + raise RuntimeError( + f"{table}: oversized cell did not split into chunks" + ) + split_cells[target] = (kind, value, chunks) + cells[target] = _render_literal(kind, chunks[0]) + if key_idx is None: + key_idx = [i for i in range(len(cells)) if i not in split_cells] + if not key_idx: + raise RuntimeError( + f"{table}: oversized row has no column left to key its " + "UPDATE appends on; refusing to emit it" + ) + where = " AND ".join(f'"{colnames[i]}" IS {row[i]}' for i in key_idx) + out = [stmt] + for target, (kind, value, chunks) in split_cells.items(): + col = colnames[target] + done = len(chunks[0]) + for chunk in chunks[1:]: + # SQLite's || always yields TEXT, so a BLOB cell's appends + # CAST back to BLOB to keep the rebuilt value's storage + # class (and bytes) identical to the source. + expr = f'"{col}" || {_render_literal(kind, chunk)}' + if kind == "blob": + expr = f"CAST({expr} AS BLOB)" + update = ( + f'UPDATE "{table}" SET "{col}" = {expr} ' + f'WHERE {where} AND length("{col}") = {done};' + ) + if len(update.encode("utf-8")) > MAX_IMPORT_STATEMENT_BYTES: + raise RuntimeError( + f"{table}: UPDATE append for column {col} exceeds the " + "D1 statement limit; refusing to emit it" + ) + out.append(update) + done += len(chunk) + splits.append((table, col, where, len(value))) + return out + + def build_dump(client, exported_at): """A complete, re-importable SQL dump of the store as D1-safe text. @@ -226,7 +416,9 @@ def build_dump(client, exported_at): quote()), then indexes/views/triggers, then the meta table holding the export timestamp and the per-table row counts the restore drill and the freshness readout verify against. Returns - (dump_text, counts). + (dump_text, counts, splits), where splits records each row that + had to be chunked for the D1 statement limit (see + _split_row_insert), for post-import verification. """ schema = read_schema(client) counts = table_counts(client, schema) @@ -246,11 +438,19 @@ def build_dump(client, exported_at): lines.append(f'DROP TABLE IF EXISTS "{name}";') for _name, sql in tables: lines.append(sql.rstrip().rstrip(";") + ";") - for name, _sql in tables: - _c, _probe = client.execute(f'SELECT * FROM "{name}" LIMIT 0') - ncols = len(_c) + splits = [] + for name, sql in tables: + colnames, _probe = client.execute(f'SELECT * FROM "{name}" LIMIT 0') + ncols = len(colnames) + pk_cols = _pk_columns(sql) for row in read_table_quoted(client, name, ncols): - lines.append(f'INSERT INTO "{name}" VALUES (' + ", ".join(row) + ");") + stmt = f'INSERT INTO "{name}" VALUES (' + ", ".join(row) + ");" + if len(stmt.encode("utf-8")) <= MAX_IMPORT_STATEMENT_BYTES: + lines.append(stmt) + else: + lines.extend( + _split_row_insert(name, colnames, row, pk_cols, splits) + ) for kind, _name, _t, sql in schema: if kind in ("index", "view", "trigger"): lines.append(sql.rstrip().rstrip(";") + ";") @@ -267,7 +467,7 @@ def build_dump(client, exported_at): ) + ");" ) - return "\n".join(lines) + "\n", counts + return "\n".join(lines) + "\n", counts, splits # ------------------------------------------------------------- Cloudflare diff --git a/infra/fleet-queue-backup/tests/test_fq_common.py b/infra/fleet-queue-backup/tests/test_fq_common.py index 1e9051f931..9a8316aaa4 100644 --- a/infra/fleet-queue-backup/tests/test_fq_common.py +++ b/infra/fleet-queue-backup/tests/test_fq_common.py @@ -67,7 +67,7 @@ def make_source(): class TestBuildDump(unittest.TestCase): def test_dump_rebuilds_source_exactly(self): conn, task_rows = make_source() - dump, counts = fq_common.build_dump( + dump, counts, _splits = fq_common.build_dump( SqliteLibsqlAdapter(conn), "2026-11-22T00:00:00Z" ) self.assertEqual(counts, {"tasks": 3, "notes": 3}) @@ -94,7 +94,7 @@ def test_dump_rebuilds_source_exactly(self): def test_dump_is_reimportable(self): conn, _rows = make_source() adapter = SqliteLibsqlAdapter(conn) - dump, _counts = fq_common.build_dump(adapter, "2026-11-22T00:00:00Z") + dump, _counts, _splits = fq_common.build_dump(adapter, "2026-11-22T00:00:00Z") # A second export over the rebuilt copy renders the same rows: # DROP+CREATE makes the dump idempotent against a live target. rebuilt = sqlite3.connect(":memory:") diff --git a/infra/fleet-queue-backup/tests/test_restore_drill.py b/infra/fleet-queue-backup/tests/test_restore_drill.py index 41049edfc5..280cb87deb 100644 --- a/infra/fleet-queue-backup/tests/test_restore_drill.py +++ b/infra/fleet-queue-backup/tests/test_restore_drill.py @@ -110,7 +110,7 @@ def test_unknown_shape_fails(self): class TestRestore(unittest.TestCase): def test_restore_rebuilds_target_from_copy(self): source = make_source() - dump, _counts = fq_common.build_dump( + dump, _counts, _splits = fq_common.build_dump( SqliteLibsqlAdapter(source), "2026-11-22T00:00:00Z" ) copy = sqlite3.connect(":memory:") diff --git a/infra/fleet-queue-backup/tests/test_statement_split.py b/infra/fleet-queue-backup/tests/test_statement_split.py new file mode 100644 index 0000000000..e1d449ec82 --- /dev/null +++ b/infra/fleet-queue-backup/tests/test_statement_split.py @@ -0,0 +1,120 @@ +#!/usr/bin/env python3 +"""Oversized rows: D1's import rejects any statement over 100,000 +bytes (SQLITE_TOOBIG, seen live on the first #8584 export attempt). +A row whose quote()-rendered INSERT exceeds the exporter's cap is +split -- its largest cells chunked across an INSERT plus keyed UPDATE +appends -- and the rebuilt values must equal the source byte-for-byte, +with every emitted statement under the cap and every split recorded +for the exporter's post-import verification. + +Oracle: Python's sqlite3 module, same adapter idiom as +test_fq_common.py. Run: python3 -I infra/fleet-queue-backup/tests/test_statement_split.py +""" + +import os +import sqlite3 +import sys +import unittest + +BIN = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "bin")) +sys.path.insert(0, BIN) +sys.path.insert(0, os.path.dirname(__file__)) + +import fq_common +from test_fq_common import SqliteLibsqlAdapter + + +def statements(dump): + """Split a dump into statements on top-level semicolons (a ';' + inside a quoted literal does not split; '' is an escaped quote).""" + out, buf, i, in_str = [], [], 0, False + while i < len(dump): + ch = dump[i] + buf.append(ch) + if in_str: + if ch == "'": + if i + 1 < len(dump) and dump[i + 1] == "'": + buf.append("'") + i += 1 + else: + in_str = False + elif ch == "'": + in_str = True + elif ch == ";": + out.append("".join(buf)) + buf = [] + i += 1 + tail = "".join(buf).strip() + if tail: + out.append(tail) + return out + + +class TestStatementSplit(unittest.TestCase): + def test_oversized_text_and_blob_row_rebuilds_exactly(self): + big_text = "data 'quoted' and \"dq\" ✓ line\n" * 5000 # ~165K chars + big_blob = bytes(range(256)) * 700 # 179,200 bytes + conn = sqlite3.connect(":memory:") + conn.execute( + "CREATE TABLE wide (id INTEGER PRIMARY KEY, note TEXT, data BLOB)" + ) + conn.executemany( + "INSERT INTO wide VALUES (?,?,?)", + [(1, big_text, big_blob), (2, "small", b"\x00\xff")], + ) + conn.commit() + dump, counts, splits = fq_common.build_dump( + SqliteLibsqlAdapter(conn), "2026-11-22T00:00:00Z" + ) + self.assertEqual(counts, {"wide": 2}) + for stmt in statements(dump): + self.assertLessEqual( + len(stmt.encode("utf-8")), + fq_common.MAX_IMPORT_STATEMENT_BYTES, + stmt[:60], + ) + rebuilt = sqlite3.connect(":memory:") + rebuilt.executescript(dump) + self.assertEqual( + rebuilt.execute("SELECT * FROM wide ORDER BY id").fetchall(), + [(1, big_text, big_blob), (2, "small", b"\x00\xff")], + ) + recorded = {(t, c): (w, n) for t, c, w, n in splits} + self.assertEqual(set(recorded), {("wide", "note"), ("wide", "data")}) + self.assertEqual(recorded[("wide", "note")][1], len(big_text)) + self.assertEqual(recorded[("wide", "data")][1], len(big_blob)) + self.assertIn('"id" IS 1', recorded[("wide", "note")][0]) + + def test_oversized_row_without_pk_keys_appends_on_other_columns(self): + big_text = "z" * 150_000 + conn = sqlite3.connect(":memory:") + conn.execute("CREATE TABLE nopk (a TEXT, b TEXT)") + conn.executemany( + "INSERT INTO nopk VALUES (?,?)", [("k1", big_text), ("k2", "tiny")] + ) + conn.commit() + dump, _counts, splits = fq_common.build_dump( + SqliteLibsqlAdapter(conn), "2026-11-22T00:00:00Z" + ) + rebuilt = sqlite3.connect(":memory:") + rebuilt.executescript(dump) + self.assertEqual( + rebuilt.execute("SELECT * FROM nopk ORDER BY a").fetchall(), + [("k1", big_text), ("k2", "tiny")], + ) + self.assertEqual(len(splits), 1) + self.assertEqual(splits[0][3], len(big_text)) + + def test_normal_rows_record_no_splits(self): + conn = sqlite3.connect(":memory:") + conn.execute("CREATE TABLE plain (id INTEGER PRIMARY KEY, v TEXT)") + conn.execute("INSERT INTO plain VALUES (1, 'x')") + conn.commit() + _dump, _counts, splits = fq_common.build_dump( + SqliteLibsqlAdapter(conn), "2026-11-22T00:00:00Z" + ) + self.assertEqual(splits, []) + + +if __name__ == "__main__": + unittest.main() From 12fb94f9bd70e857cbe8653c213d247632638b52 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 23:48:57 -0600 Subject: [PATCH 05/12] fix(fleet-queue-backup): count emitted rows, not a separate COUNT pass (#8584) Fourth live-run finding: run 4 imported cleanly (the statement split verified live) but the read-back check failed -- D1 held MORE rows than the recorded counts (events +142, tasks +1, checkpoints +3, mirror PRs +10). The counts came from a COUNT(*) pass taken before the ~21-minute row read of a live store; rows written in between land in the dump but not in the counts. build_dump now counts the rows it actually emits, so the meta, the read-back check and the restore drill all describe the same artifact: the copy as written. New hermetic test tests/test_emitted_counts.py simulates a mid-export write. Full suite green (5 files). --- infra/fleet-queue-backup/bin/fq_common.py | 14 +++- .../tests/test_emitted_counts.py | 71 +++++++++++++++++++ 2 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 infra/fleet-queue-backup/tests/test_emitted_counts.py diff --git a/infra/fleet-queue-backup/bin/fq_common.py b/infra/fleet-queue-backup/bin/fq_common.py index 6018a8964c..d9b936c26a 100755 --- a/infra/fleet-queue-backup/bin/fq_common.py +++ b/infra/fleet-queue-backup/bin/fq_common.py @@ -421,13 +421,20 @@ def build_dump(client, exported_at): _split_row_insert), for post-import verification. """ schema = read_schema(client) - counts = table_counts(client, schema) + tables = [(name, sql) for kind, name, _t, sql in schema if kind == "table"] + # Counts are taken from the rows actually emitted below, never from + # a separate COUNT(*) pass: on the live store the two reads smear + # (rows land between them), which made the exporter's read-back + # check fail on a faithful copy and left the meta describing no + # copy that ever existed (live run 4, #8584). Emitted counts make + # the meta, the read-back check and the restore drill all describe + # the same artifact. + counts = {name: 0 for name, _sql in tables} lines = [ "-- fleet-queue-backup export (#8584)", f"-- exported_at: {exported_at}", - f"-- source tables: {len(counts)}", + f"-- source tables: {len(tables)}", ] - tables = [(name, sql) for kind, name, _t, sql in schema if kind == "table"] # Drop every object the dump recreates, dependents first, so the # dump is idempotent against a target already holding a copy # (re-import is the scheduled refresh path, not an error). @@ -444,6 +451,7 @@ def build_dump(client, exported_at): ncols = len(colnames) pk_cols = _pk_columns(sql) for row in read_table_quoted(client, name, ncols): + counts[name] += 1 stmt = f'INSERT INTO "{name}" VALUES (' + ", ".join(row) + ");" if len(stmt.encode("utf-8")) <= MAX_IMPORT_STATEMENT_BYTES: lines.append(stmt) diff --git a/infra/fleet-queue-backup/tests/test_emitted_counts.py b/infra/fleet-queue-backup/tests/test_emitted_counts.py new file mode 100644 index 0000000000..dc1922b9ae --- /dev/null +++ b/infra/fleet-queue-backup/tests/test_emitted_counts.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Emitted-row counts (#8584 live run 4): build_dump's counts must +describe the dump itself, so a row that lands in the source while the +export is reading (the normal case on the live queue store) is counted +-- the meta, the D1 read-back check and the restore drill then all +describe the same copy. With a separate COUNT(*) pass the counts +described the store as of dump start and the read-back check failed +on a faithful copy. + +Oracle: Python's sqlite3 module, same adapter idiom as +test_fq_common.py. Run: python3 -I infra/fleet-queue-backup/tests/test_emitted_counts.py +""" + +import os +import sqlite3 +import sys +import unittest + +BIN = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "bin")) +sys.path.insert(0, BIN) +sys.path.insert(0, os.path.dirname(__file__)) + +import fq_common +from test_fq_common import SqliteLibsqlAdapter + + +class DriftAdapter(SqliteLibsqlAdapter): + """Inserts one extra tasks row the first time the dump probes the + table -- a write landing mid-export, as the live store does.""" + + def __init__(self, conn): + super().__init__(conn) + self.drifted = False + + def execute(self, sql, args=()): + if not self.drifted and "LIMIT 0" in sql and '"tasks"' in sql: + self.drifted = True + self.conn.execute( + "INSERT INTO tasks VALUES (99, 'late', '', NULL, 0.0, NULL)" + ) + self.conn.commit() + return super().execute(sql, args) + + +class TestEmittedCounts(unittest.TestCase): + def test_counts_describe_the_dump_not_the_count_pass(self): + conn = sqlite3.connect(":memory:") + conn.executescript( + """ + CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT, body TEXT, + payload BLOB, score REAL, parent INTEGER); + """ + ) + conn.executemany( + "INSERT INTO tasks VALUES (?,?,?,?,?,?)", + [(1, "a", "", None, 0.0, None), (2, "b", "", None, 0.0, None)], + ) + conn.commit() + dump, counts, _splits = fq_common.build_dump( + DriftAdapter(conn), "2026-11-22T00:00:00Z" + ) + self.assertEqual(counts, {"tasks": 3}) + rebuilt = sqlite3.connect(":memory:") + rebuilt.executescript(dump) + self.assertEqual( + rebuilt.execute("SELECT count(*) FROM tasks").fetchone()[0], 3 + ) + + +if __name__ == "__main__": + unittest.main() From 7f7ea60c25a6bd266d4e7811211682c7595af918 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 00:24:05 -0600 Subject: [PATCH 06/12] fix(fleet-queue-backup): drill reads columns from CREATE TABLE, not PRAGMA (#8584) Fifth live-run finding: the restore drill failed immediately -- the D1 query API refuses PRAGMA statements (HTTP 400, code 7500, not authorized: SQLITE_AUTH), and the drill read column order via PRAGMA table_info. It already fetches every CREATE TABLE, so column order is now parsed from that text (fq_common.table_columns, sharing the definition splitter with _pk_columns). New test pins both live schema shapes (inline PK; table-level PK with a quoted column). Full suite green (6 files). --- infra/fleet-queue-backup/bin/fq_common.py | 50 +++++++++++++++--- infra/fleet-queue-backup/bin/restore_drill.py | 20 ++++---- .../tests/test_table_columns.py | 51 +++++++++++++++++++ 3 files changed, 104 insertions(+), 17 deletions(-) create mode 100644 infra/fleet-queue-backup/tests/test_table_columns.py diff --git a/infra/fleet-queue-backup/bin/fq_common.py b/infra/fleet-queue-backup/bin/fq_common.py index d9b936c26a..0fb6e82906 100755 --- a/infra/fleet-queue-backup/bin/fq_common.py +++ b/infra/fleet-queue-backup/bin/fq_common.py @@ -280,14 +280,9 @@ def _value_chunks(kind, value, first_budget=None): return [c for c in chunks if c] or [b""] -def _pk_columns(create_sql): - """Primary-key column names from a CREATE TABLE statement, or None. - - Handles the two shapes the queue schema uses: a table-level - PRIMARY KEY (a, b) definition and an inline column PRIMARY KEY. - The parenthesised body is split into top-level definitions first, - so a single-line CREATE cannot confuse the match. - """ +def _create_defs(create_sql): + """The top-level definitions inside a CREATE TABLE's parentheses, + split on top-level commas, or None if the parens do not parse.""" start = create_sql.find("(") if start < 0: return None @@ -315,6 +310,45 @@ def _pk_columns(create_sql): cur += ch if cur.strip(): defs.append(cur) + return defs + + +def table_columns(create_sql): + """Column names of a CREATE TABLE, in definition order. + + Constraint definitions (PRIMARY KEY / FOREIGN KEY / UNIQUE / + CHECK / CONSTRAINT) are not columns and are skipped. The D1 query + API refuses PRAGMA statements (SQLITE_AUTH), so the restore drill + gets column order from the CREATE text it already fetched rather + than from PRAGMA table_info. + """ + cols = [] + for d in _create_defs(create_sql) or []: + d = d.strip() + if d.upper().startswith( + ("PRIMARY", "FOREIGN", "UNIQUE", "CHECK", "CONSTRAINT") + ): + continue + m = re.match( + r'^(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s', + d, + ) + if m: + cols.append(next(g for g in m.groups() if g is not None)) + return cols + + +def _pk_columns(create_sql): + """Primary-key column names from a CREATE TABLE statement, or None. + + Handles the two shapes the queue schema uses: a table-level + PRIMARY KEY (a, b) definition and an inline column PRIMARY KEY. + The parenthesised body is split into top-level definitions first, + so a single-line CREATE cannot confuse the match. + """ + defs = _create_defs(create_sql) + if defs is None: + return None for d in defs: m = re.match(r"\s*PRIMARY\s+KEY\s*\(([^)]*)\)", d, re.IGNORECASE) if m: diff --git a/infra/fleet-queue-backup/bin/restore_drill.py b/infra/fleet-queue-backup/bin/restore_drill.py index 560a1b2b75..e94e8a6cf5 100755 --- a/infra/fleet-queue-backup/bin/restore_drill.py +++ b/infra/fleet-queue-backup/bin/restore_drill.py @@ -64,15 +64,17 @@ def d1_schema(d1, db_id): ) -def d1_columns(d1, db_id, table): - """Column names in table order, from PRAGMA table_info — the - drill never trusts JSON object key order for column position.""" - rows = d1.query(db_id, f'PRAGMA table_info("{table}")') - return [r["name"] for r in sorted(rows, key=lambda r: r["cid"])] +def d1_columns(create_sql): + """Column names in table order, parsed from the CREATE TABLE -- + the drill never trusts JSON object key order for column position, + and the D1 query API refuses PRAGMA statements (SQLITE_AUTH, seen + live on the first drill run, #8584), so PRAGMA table_info cannot + be the source.""" + return fq_common.table_columns(create_sql) -def d1_read_table(d1, db_id, table): - columns = d1_columns(d1, db_id, table) +def d1_read_table(d1, db_id, table, create_sql): + columns = d1_columns(create_sql) offset = 0 for _page in range(fq_common.MAX_PAGES): rows = d1.query( @@ -112,10 +114,10 @@ def restore(d1_name, target_url): target.execute(f'DROP TABLE IF EXISTS "{name}"') for _name, sql in tables: target.execute(sql.rstrip().rstrip(";")) - for name, _sql in tables: + for name, sql in tables: batch = [] placeholders = None - for row in d1_read_table(d1, db_id, name): + for row in d1_read_table(d1, db_id, name, sql): if placeholders is None: placeholders = ", ".join("?" for _ in row) batch.append((f'INSERT INTO "{name}" VALUES ({placeholders})', row)) diff --git a/infra/fleet-queue-backup/tests/test_table_columns.py b/infra/fleet-queue-backup/tests/test_table_columns.py new file mode 100644 index 0000000000..dcb7495d62 --- /dev/null +++ b/infra/fleet-queue-backup/tests/test_table_columns.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""table_columns (#8584 live drill finding): the D1 query API refuses +PRAGMA, so the restore drill parses column order from CREATE TABLE +text. The two schemas below are verbatim from the live queue store -- +an inline PRIMARY KEY shape and a table-level PRIMARY KEY shape with +a quoted column name. + +Run: python3 -I infra/fleet-queue-backup/tests/test_table_columns.py +""" + +import os +import sys +import unittest + +BIN = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "bin")) +sys.path.insert(0, BIN) + +import fq_common + +EVENTS = ( + "CREATE TABLE events (id INTEGER PRIMARY KEY AUTOINCREMENT, " + "worker_id TEXT, task_id INTEGER, kind TEXT NOT NULL, " + "detail TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL)" +) +CHECKPOINTS = ( + 'CREATE TABLE checkpoints (worker_id TEXT NOT NULL, "key" TEXT NOT NULL, ' + "value TEXT NOT NULL DEFAULT '{}', updated_at TEXT NOT NULL, " + 'PRIMARY KEY (worker_id, "key"))' +) + + +class TestTableColumns(unittest.TestCase): + def test_inline_pk_schema(self): + self.assertEqual( + fq_common.table_columns(EVENTS), + ["id", "worker_id", "task_id", "kind", "detail", "created_at"], + ) + self.assertEqual(fq_common._pk_columns(EVENTS), ["id"]) + + def test_table_level_pk_schema_with_quoted_column(self): + self.assertEqual( + fq_common.table_columns(CHECKPOINTS), + ["worker_id", "key", "value", "updated_at"], + ) + self.assertEqual( + fq_common._pk_columns(CHECKPOINTS), ["worker_id", "key"] + ) + + +if __name__ == "__main__": + unittest.main() From 9b388d5ef6d7b30d6f1024cf2df183bcbffd2b4b Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 00:34:06 -0600 Subject: [PATCH 07/12] fix(fleet-queue-backup): drill skips D1-internal _cf_KV (#8584) Sixth live-run finding: the restore drill failed on its first table -- D1 keeps a _cf_KV table in every database, it sorts first in the copy schema, and the query API prohibits reading it (access to _cf_KV.key is prohibited: SQLITE_AUTH). It is not part of the backup; restore() now filters it out of the copy schema before dropping/creating/restoring. The drill test copy grows a _cf_KV fixture and asserts the target never sees it. Full suite green (6 files). --- infra/fleet-queue-backup/bin/restore_drill.py | 5 +++++ infra/fleet-queue-backup/tests/test_restore_drill.py | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/infra/fleet-queue-backup/bin/restore_drill.py b/infra/fleet-queue-backup/bin/restore_drill.py index e94e8a6cf5..9518c38dff 100755 --- a/infra/fleet-queue-backup/bin/restore_drill.py +++ b/infra/fleet-queue-backup/bin/restore_drill.py @@ -109,6 +109,11 @@ def restore(d1_name, target_url): schema = [ (r["type"], r["name"], r["tbl_name"], r["sql"]) for r in d1_schema(d1, db_id) ] + # D1 keeps its own _cf_KV table in every database: it is not part + # of the backup, the query API prohibits reading it ("access to + # _cf_KV.key is prohibited: SQLITE_AUTH", seen live on the first + # drill run, #8584), and the target must not recreate it. + schema = [entry for entry in schema if entry[1] != "_cf_KV"] tables = [(name, sql) for kind, name, _t, sql in schema if kind == "table"] for name, _sql in tables: target.execute(f'DROP TABLE IF EXISTS "{name}"') diff --git a/infra/fleet-queue-backup/tests/test_restore_drill.py b/infra/fleet-queue-backup/tests/test_restore_drill.py index 280cb87deb..5856e785ae 100644 --- a/infra/fleet-queue-backup/tests/test_restore_drill.py +++ b/infra/fleet-queue-backup/tests/test_restore_drill.py @@ -115,6 +115,10 @@ def test_restore_rebuilds_target_from_copy(self): ) copy = sqlite3.connect(":memory:") copy.executescript(dump) + # D1 adds its own _cf_KV table to every database; the drill + # must skip it (the live API prohibits even reading it). + copy.execute("CREATE TABLE _cf_KV (key TEXT PRIMARY KEY, value BLOB)") + copy.execute("INSERT INTO _cf_KV VALUES ('k', X'00')") target_conn = sqlite3.connect(":memory:") target = SqliteLibsqlAdapter(target_conn) @@ -136,6 +140,12 @@ def test_restore_rebuilds_target_from_copy(self): del os.environ[name] self.assertEqual(result["tables"], 2) self.assertEqual(result["rows"], 5) + self.assertEqual( + target_conn.execute( + "SELECT count(*) FROM sqlite_master WHERE name='_cf_KV'" + ).fetchone()[0], + 0, + ) for table in ("tasks", "notes"): self.assertEqual( target_conn.execute(f"SELECT * FROM {table} ORDER BY 1, 2").fetchall(), From a1156398bd3b13c5ae5766d077279d40cb9e4650 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 00:37:40 -0600 Subject: [PATCH 08/12] fix(fleet-queue-backup): constraint-keyword skip is a first-token test (#8584) Seventh live-run finding: the drill supplied 35 values for the 36-column tasks table -- table_columns skipped the check_outcome column because its name starts with CHECK and the constraint skip was a prefix test. Both schema parsers now share _is_constraint_def, which tests the definition first token only. Regression test embeds the verbatim live tasks schema (36 columns). Full suite green (6 files). --- infra/fleet-queue-backup/bin/fq_common.py | 21 ++++++++++----- .../tests/test_table_columns.py | 27 +++++++++++++++++++ 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/infra/fleet-queue-backup/bin/fq_common.py b/infra/fleet-queue-backup/bin/fq_common.py index 0fb6e82906..c48f07cf69 100755 --- a/infra/fleet-queue-backup/bin/fq_common.py +++ b/infra/fleet-queue-backup/bin/fq_common.py @@ -313,6 +313,19 @@ def _create_defs(create_sql): return defs +def _is_constraint_def(d): + """True when a CREATE TABLE definition is a constraint clause + rather than a column: its first token is exactly PRIMARY, FOREIGN, + UNIQUE, CHECK or CONSTRAINT. A first-token test, not a prefix + test -- the live tasks table has a column named check_outcome, + which a prefix test on CHECK silently swallowed (#8584).""" + parts = d.strip().split(None, 1) + if not parts: + return False + token = parts[0].strip('"`[]').upper() + return token in ("PRIMARY", "FOREIGN", "UNIQUE", "CHECK", "CONSTRAINT") + + def table_columns(create_sql): """Column names of a CREATE TABLE, in definition order. @@ -325,9 +338,7 @@ def table_columns(create_sql): cols = [] for d in _create_defs(create_sql) or []: d = d.strip() - if d.upper().startswith( - ("PRIMARY", "FOREIGN", "UNIQUE", "CHECK", "CONSTRAINT") - ): + if _is_constraint_def(d): continue m = re.match( r'^(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s', @@ -355,9 +366,7 @@ def _pk_columns(create_sql): return [c.strip().strip('"`[]') for c in m.group(1).split(",")] for d in defs: d = d.strip() - if d.upper().startswith( - ("PRIMARY", "FOREIGN", "UNIQUE", "CHECK", "CONSTRAINT") - ): + if _is_constraint_def(d): continue m = re.match(r'"?([A-Za-z_][A-Za-z0-9_]*)"?\s+', d) if m and re.search(r"\bPRIMARY\s+KEY\b", d, re.IGNORECASE): diff --git a/infra/fleet-queue-backup/tests/test_table_columns.py b/infra/fleet-queue-backup/tests/test_table_columns.py index dcb7495d62..9efba7e077 100644 --- a/infra/fleet-queue-backup/tests/test_table_columns.py +++ b/infra/fleet-queue-backup/tests/test_table_columns.py @@ -22,6 +22,26 @@ "worker_id TEXT, task_id INTEGER, kind TEXT NOT NULL, " "detail TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL)" ) +TASKS = ( + "CREATE TABLE tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, " + "queue TEXT NOT NULL, title TEXT, body TEXT, " + "payload TEXT NOT NULL DEFAULT '{}', dedupe_key TEXT, " + "priority INTEGER, status TEXT NOT NULL DEFAULT 'queued', " + "not_before TEXT, worker_id TEXT, claimed_at TEXT, " + "lease_until TEXT, lane_id TEXT, " + "attempts INTEGER NOT NULL DEFAULT 0, " + "max_attempts INTEGER NOT NULL DEFAULT 4, " + "progress TEXT NOT NULL DEFAULT '{}', " + "result TEXT NOT NULL DEFAULT '{}', last_error TEXT, " + "park_kind TEXT, wait_kind TEXT, ready_condition TEXT, " + "last_checked_at TEXT, check_outcome TEXT, " + "created_at TEXT NOT NULL, updated_at TEXT NOT NULL, " + "completed_at TEXT, platform TEXT, claim_provider TEXT, " + "claim_model TEXT, claim_variant TEXT, blocked_deps TEXT, " + "dep_next_recheck_at TEXT, dep_blocked_until TEXT, " + "dep_recheck_seconds INTEGER, claim_session_id TEXT, " + "required_budget_minutes INTEGER)" +) CHECKPOINTS = ( 'CREATE TABLE checkpoints (worker_id TEXT NOT NULL, "key" TEXT NOT NULL, ' "value TEXT NOT NULL DEFAULT '{}', updated_at TEXT NOT NULL, " @@ -37,6 +57,13 @@ def test_inline_pk_schema(self): ) self.assertEqual(fq_common._pk_columns(EVENTS), ["id"]) + def test_column_named_like_a_constraint_keyword(self): + cols = fq_common.table_columns(TASKS) + self.assertEqual(len(cols), 36) + self.assertIn("check_outcome", cols) + self.assertEqual(cols[-1], "required_budget_minutes") + self.assertEqual(fq_common._pk_columns(TASKS), ["id"]) + def test_table_level_pk_schema_with_quoted_column(self): self.assertEqual( fq_common.table_columns(CHECKPOINTS), From 3602ff5d1715522012d152150fb7325adfa3c130 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 00:45:19 -0600 Subject: [PATCH 09/12] perf(fleet-queue-backup): drill reads/writes 1000 rows per request (#8584) Eighth live-run finding: the restore drill ran at ~3 rows/s. Measured on the laptop-to-Turso path: one D1 page read (500 tasks rows) 5.3s, one 100-row pipeline write 3.4s -- per-request latency dominates, so requests are the scarce resource. The drill now reads 1000 rows per D1 page and writes 1000 rows per pipeline batch; the exporter page size is untouched. Full suite green (6 files). --- infra/fleet-queue-backup/bin/restore_drill.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/infra/fleet-queue-backup/bin/restore_drill.py b/infra/fleet-queue-backup/bin/restore_drill.py index 9518c38dff..8f2740555c 100755 --- a/infra/fleet-queue-backup/bin/restore_drill.py +++ b/infra/fleet-queue-backup/bin/restore_drill.py @@ -30,7 +30,11 @@ import fq_common -BATCH = 100 +# Rows per D1 read page and per pipeline write batch. Sized for the +# measured per-request latency of the laptop-to-Turso path (seconds +# per request, #8584): at 100 the restore ran at ~3 rows/s. +READ_PAGE = 1000 +BATCH = 1000 def _require_env(name): @@ -79,13 +83,13 @@ def d1_read_table(d1, db_id, table, create_sql): for _page in range(fq_common.MAX_PAGES): rows = d1.query( db_id, - f'SELECT * FROM "{table}" LIMIT {fq_common.PAGE_ROWS} OFFSET {offset}', + f'SELECT * FROM "{table}" LIMIT {READ_PAGE} OFFSET {offset}', ) for row in rows: yield tuple(d1_value(row[c]) for c in columns) - if len(rows) < fq_common.PAGE_ROWS: + if len(rows) < READ_PAGE: return - offset += fq_common.PAGE_ROWS + offset += READ_PAGE raise RuntimeError( f"{table}: D1 pagination exceeded {fq_common.MAX_PAGES} pages; " "refusing to page unboundedly" From 400c2c74f5529b77c5df76f339ed0124e3abc6e9 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 01:09:21 -0600 Subject: [PATCH 10/12] fix(fleet-queue-backup): drill reads INTEGER columns as CAST AS TEXT (#8584) Ninth live-run finding: the drill died writing the autoincrement sequence tables -- they hold i64::MAX, and the D1 query API serializes numbers through JavaScript doubles, so it came back as 9223372036854776000 and the target rejected it as out of range (D1 documents this int64 precision limitation). The D1 copy itself is exact; only the API read is lossy. The drill now CASTs INTEGER-affinity columns to TEXT in its SELECT and decodes exactly (int, then float, then the string itself). A scan of the live store confirms the seq tables are the only >2^53 integers. The drill test fake now emulates the API rounding, and a round-trip test pins i64::MAX. Full suite green (6 files). --- infra/fleet-queue-backup/bin/fq_common.py | 30 ++++++++ infra/fleet-queue-backup/bin/restore_drill.py | 37 +++++++++- .../tests/test_restore_drill.py | 68 ++++++++++++++++++- 3 files changed, 132 insertions(+), 3 deletions(-) diff --git a/infra/fleet-queue-backup/bin/fq_common.py b/infra/fleet-queue-backup/bin/fq_common.py index c48f07cf69..9cc676d05d 100755 --- a/infra/fleet-queue-backup/bin/fq_common.py +++ b/infra/fleet-queue-backup/bin/fq_common.py @@ -349,6 +349,36 @@ def table_columns(create_sql): return cols +def table_column_types(create_sql): + """Column name -> declared type (uppercased) for a CREATE TABLE. + + The declared type is the text after the column name up to the + first constraint keyword or '(' -- e.g. "INTEGER", "TEXT", + "DOUBLE PRECISION", "UNSIGNED BIG INT", or "" for a typeless + column. + """ + types = {} + for d in _create_defs(create_sql) or []: + d = d.strip() + if _is_constraint_def(d): + continue + m = re.match( + r'^(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s+(.*)$', + d, + re.DOTALL, + ) + if m: + name = next(g for g in m.groups()[:4] if g is not None) + raw = re.split( + r"\(|\bPRIMARY\b|\bNOT\b|\bNULL\b|\bDEFAULT\b|\bCHECK\b" + r"|\bREFERENCES\b|\bUNIQUE\b|\bCOLLATE\b|\bGENERATED\b", + m.group(5), + flags=re.IGNORECASE, + )[0] + types[name] = raw.strip().upper() + return types + + def _pk_columns(create_sql): """Primary-key column names from a CREATE TABLE statement, or None. diff --git a/infra/fleet-queue-backup/bin/restore_drill.py b/infra/fleet-queue-backup/bin/restore_drill.py index 8f2740555c..8957382ec7 100755 --- a/infra/fleet-queue-backup/bin/restore_drill.py +++ b/infra/fleet-queue-backup/bin/restore_drill.py @@ -77,16 +77,49 @@ def d1_columns(create_sql): return fq_common.table_columns(create_sql) +def d1_integer_value(value): + """Decode an INTEGER-affinity column read back as CAST AS TEXT. + + The D1 query API serializes numbers through JavaScript doubles, + so an int64 beyond 2^53 arrives rounded: the source's + autoincrement sequence tables hold i64::MAX, which came back as + 9223372036854776000 and the target rejected it as out of range + (live drill run, #8584). CAST AS TEXT returns the exact decimal. + Decode int first, then float (a REAL stored in an INTEGER + column), then the string itself (a non-numeric value, which + column affinity leaves stored as text). + """ + if value is None or isinstance(value, int): + return value + try: + return int(value) + except (TypeError, ValueError): + pass + try: + return float(value) + except (TypeError, ValueError): + return value + + def d1_read_table(d1, db_id, table, create_sql): columns = d1_columns(create_sql) + types = fq_common.table_column_types(create_sql) + select = ", ".join( + f'CAST("{c}" AS TEXT) AS "{c}"' if "INT" in types.get(c, "") else f'"{c}"' + for c in columns + ) + decoders = [ + d1_integer_value if "INT" in types.get(c, "") else d1_value + for c in columns + ] offset = 0 for _page in range(fq_common.MAX_PAGES): rows = d1.query( db_id, - f'SELECT * FROM "{table}" LIMIT {READ_PAGE} OFFSET {offset}', + f'SELECT {select} FROM "{table}" LIMIT {READ_PAGE} OFFSET {offset}', ) for row in rows: - yield tuple(d1_value(row[c]) for c in columns) + yield tuple(decode(row[c]) for decode, c in zip(decoders, columns)) if len(rows) < READ_PAGE: return offset += READ_PAGE diff --git a/infra/fleet-queue-backup/tests/test_restore_drill.py b/infra/fleet-queue-backup/tests/test_restore_drill.py index 5856e785ae..a1883c6735 100644 --- a/infra/fleet-queue-backup/tests/test_restore_drill.py +++ b/infra/fleet-queue-backup/tests/test_restore_drill.py @@ -61,7 +61,16 @@ def query(self, db_id, sql, params=()): for row in cur.fetchall(): record = {} for col, value in zip(cols, row): - record[col] = list(value) if isinstance(value, bytes) else value + if isinstance(value, bytes): + value = list(value) + elif isinstance(value, int) and abs(value) > 2**53: + # The real D1 API serializes numbers through + # JavaScript doubles and rounds int64s beyond + # 2^53 (its documented known limitation); emulate + # that loss so the drill's exact-read path is what + # gets tested. + value = int(float(value)) + record[col] = value out.append(record) return out @@ -107,7 +116,64 @@ def test_unknown_shape_fails(self): restore_drill.d1_value({"surprise": True}) +class TestD1IntegerValue(unittest.TestCase): + def test_exact_int64(self): + self.assertEqual( + restore_drill.d1_integer_value("9223372036854775807"), + 9223372036854775807, + ) + + def test_small_values(self): + self.assertEqual(restore_drill.d1_integer_value("42"), 42) + self.assertEqual(restore_drill.d1_integer_value(7), 7) + self.assertIsNone(restore_drill.d1_integer_value(None)) + + def test_real_in_integer_column(self): + self.assertEqual(restore_drill.d1_integer_value("1.5"), 1.5) + + def test_non_numeric_text_passes_through(self): + self.assertEqual(restore_drill.d1_integer_value("abc"), "abc") + + class TestRestore(unittest.TestCase): + def test_restore_round_trips_int64_max(self): + source = sqlite3.connect(":memory:") + source.execute( + "CREATE TABLE seq (name TEXT PRIMARY KEY, max INTEGER)" + ) + source.executemany( + "INSERT INTO seq VALUES (?,?)", + [("tasks", 9223372036854775807), ("events", 21500)], + ) + source.commit() + dump, _counts, _splits = fq_common.build_dump( + SqliteLibsqlAdapter(source), "2026-11-22T00:00:00Z" + ) + copy = sqlite3.connect(":memory:") + copy.executescript(dump) + target_conn = sqlite3.connect(":memory:") + target = SqliteLibsqlAdapter(target_conn) + restore_drill.fq_common.D1Client = lambda token, account: FakeD1(copy) + restore_drill.fq_common.LibsqlClient = lambda url, token: target + os.environ["CLOUDFLARE_API_TOKEN"] = "test" + os.environ["CLOUDFLARE_ACCOUNT_ID"] = "test" + os.environ["TURSO_TARGET_TOKEN"] = "test" + try: + restore_drill.restore( + fq_common.DEFAULT_D1_NAME, "https://scratch.invalid" + ) + finally: + for name in ( + "CLOUDFLARE_API_TOKEN", + "CLOUDFLARE_ACCOUNT_ID", + "TURSO_TARGET_TOKEN", + ): + del os.environ[name] + self.assertEqual( + target_conn.execute("SELECT * FROM seq ORDER BY name").fetchall(), + [("events", 21500), ("tasks", 9223372036854775807)], + ) + def test_restore_rebuilds_target_from_copy(self): source = make_source() dump, _counts, _splits = fq_common.build_dump( From b9fa0dfe2f7ed5de00df8ba39df84c9c07d81401 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 01:41:06 -0600 Subject: [PATCH 11/12] perf(fleet-queue-backup): keyset paging for INT-PK tables in the drill (#8584) Tenth live-run finding: at ~25 rows/s on events, OFFSET paging both projected to hours and degrades linearly with depth (each page scans the offset on D1, risking the 30s query cap mid-restore). Tables with a single INTEGER primary key -- all the big ones -- now page by WHERE pk > last ORDER BY CAST(pk AS INTEGER): the CAST in the ORDER BY matters, because the select list aliases CAST(pk AS TEXT) AS pk and ORDER BY would otherwise resolve the text alias and lose rows between pages (the new hermetic test caught exactly that: 1701 of 2600 rows). Other tables keep OFFSET. Full suite green (6 files). --- infra/fleet-queue-backup/bin/restore_drill.py | 42 +++++++++++++++-- .../tests/test_restore_drill.py | 46 +++++++++++++++++++ 2 files changed, 83 insertions(+), 5 deletions(-) diff --git a/infra/fleet-queue-backup/bin/restore_drill.py b/infra/fleet-queue-backup/bin/restore_drill.py index 8957382ec7..d4d8ec0d49 100755 --- a/infra/fleet-queue-backup/bin/restore_drill.py +++ b/infra/fleet-queue-backup/bin/restore_drill.py @@ -112,14 +112,46 @@ def d1_read_table(d1, db_id, table, create_sql): d1_integer_value if "INT" in types.get(c, "") else d1_value for c in columns ] + pk_cols = fq_common._pk_columns(create_sql) + keyset = ( + pk_cols[0] + if pk_cols + and len(pk_cols) == 1 + and "INT" in types.get(pk_cols[0], "") + else None + ) offset = 0 + last_key = None for _page in range(fq_common.MAX_PAGES): - rows = d1.query( - db_id, - f'SELECT {select} FROM "{table}" LIMIT {READ_PAGE} OFFSET {offset}', - ) + # ORDER BY must name the CAST, not "{keyset}": the select list + # aliases CAST("{keyset}" AS TEXT) AS "{keyset}", and ORDER BY + # resolves the alias first -- text ordering ('1', '10', '100', + # ...) silently loses rows between pages (hermetic keyset test + # caught this: 1701 of 2600 rows restored). + if keyset is not None and last_key is not None: + sql = ( + f'SELECT {select} FROM "{table}" ' + f'WHERE "{keyset}" > {last_key} ' + f'ORDER BY CAST("{keyset}" AS INTEGER) LIMIT {READ_PAGE}' + ) + elif keyset is not None: + sql = ( + f'SELECT {select} FROM "{table}" ' + f'ORDER BY CAST("{keyset}" AS INTEGER) LIMIT {READ_PAGE}' + ) + else: + sql = ( + f'SELECT {select} FROM "{table}" ' + f"LIMIT {READ_PAGE} OFFSET {offset}" + ) + rows = d1.query(db_id, sql) for row in rows: - yield tuple(decode(row[c]) for decode, c in zip(decoders, columns)) + values = tuple( + decode(row[c]) for decode, c in zip(decoders, columns) + ) + if keyset is not None: + last_key = values[columns.index(keyset)] + yield values if len(rows) < READ_PAGE: return offset += READ_PAGE diff --git a/infra/fleet-queue-backup/tests/test_restore_drill.py b/infra/fleet-queue-backup/tests/test_restore_drill.py index a1883c6735..f5a58a524c 100644 --- a/infra/fleet-queue-backup/tests/test_restore_drill.py +++ b/infra/fleet-queue-backup/tests/test_restore_drill.py @@ -135,6 +135,52 @@ def test_non_numeric_text_passes_through(self): self.assertEqual(restore_drill.d1_integer_value("abc"), "abc") +class TestKeysetPaging(unittest.TestCase): + def test_int_pk_table_pages_by_key(self): + source = sqlite3.connect(":memory:") + source.execute( + "CREATE TABLE big (id INTEGER PRIMARY KEY, v TEXT)" + ) + source.executemany( + "INSERT INTO big VALUES (?,?)", + [(i, "row-%d" % i) for i in range(1, 2601)], + ) + source.commit() + dump, _counts, _splits = fq_common.build_dump( + SqliteLibsqlAdapter(source), "2026-11-22T00:00:00Z" + ) + copy = sqlite3.connect(":memory:") + copy.executescript(dump) + target_conn = sqlite3.connect(":memory:") + target = SqliteLibsqlAdapter(target_conn) + restore_drill.fq_common.D1Client = lambda token, account: FakeD1(copy) + restore_drill.fq_common.LibsqlClient = lambda url, token: target + os.environ["CLOUDFLARE_API_TOKEN"] = "test" + os.environ["CLOUDFLARE_ACCOUNT_ID"] = "test" + os.environ["TURSO_TARGET_TOKEN"] = "test" + try: + result = restore_drill.restore( + fq_common.DEFAULT_D1_NAME, "https://scratch.invalid" + ) + finally: + for name in ( + "CLOUDFLARE_API_TOKEN", + "CLOUDFLARE_ACCOUNT_ID", + "TURSO_TARGET_TOKEN", + ): + del os.environ[name] + self.assertEqual(result["rows"], 2600) + self.assertEqual( + target_conn.execute("SELECT count(*) FROM big").fetchone()[0], 2600 + ) + self.assertEqual( + target_conn.execute( + "SELECT v FROM big WHERE id = 2600" + ).fetchone()[0], + "row-2600", + ) + + class TestRestore(unittest.TestCase): def test_restore_round_trips_int64_max(self): source = sqlite3.connect(":memory:") From b41daae7d33e6efd718b3b4f002f4611cadd2c80 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 02:34:35 -0600 Subject: [PATCH 12/12] fix(fleet-queue-backup): retry transport failures in http_json (#8584) Eleventh live-run finding: the restore drill died at events=32,000 on a single connection reset (Errno 104) -- the shared HTTP helper treated every transport failure as fatal, the same gap the export read path had shown earlier. http_json now retries transport failures (5 attempts, exponential backoff) and never retries HTTP errors, which do not heal. Retrying a write whose first attempt may have landed is safe for these tools: primary keys reject duplicates loudly and both sides verify final counts. New suite tests/test_http_retry.py. Full suite green (7 files). --- infra/fleet-queue-backup/bin/fq_common.py | 33 +++++++- .../tests/test_http_retry.py | 84 +++++++++++++++++++ 2 files changed, 113 insertions(+), 4 deletions(-) create mode 100644 infra/fleet-queue-backup/tests/test_http_retry.py diff --git a/infra/fleet-queue-backup/bin/fq_common.py b/infra/fleet-queue-backup/bin/fq_common.py index 9cc676d05d..2a4d30b51e 100755 --- a/infra/fleet-queue-backup/bin/fq_common.py +++ b/infra/fleet-queue-backup/bin/fq_common.py @@ -75,11 +75,38 @@ def _shape(value): # ------------------------------------------------------------ HTTP core +TRANSPORT_ATTEMPTS = 5 + + def http_json(method, url, token, payload=None, timeout=HTTP_TIMEOUT_SECONDS): + """One JSON HTTP call; returns the parsed body. + + HTTP failures raise RuntimeError (see _http_json_once). Transport + failures (connection reset, timeout, DNS) are retried with + backoff first: over the fleet's paths a single reset hours into + a restore must not be fatal (live drill run, #8584). Retrying a + write whose first attempt may have landed is safe here -- primary + keys reject duplicates loudly, and both the export and the drill + verify final counts and fail loudly rather than pass a wrong + copy. + """ + last_exc = None + for attempt in range(TRANSPORT_ATTEMPTS): + try: + return _http_json_once(method, url, token, payload, timeout) + except (urllib.error.URLError, TimeoutError, OSError) as exc: + last_exc = exc + if attempt + 1 < TRANSPORT_ATTEMPTS: + time.sleep(min(30, 2 ** (attempt + 1))) + raise RuntimeError(f"{method} {url} failed: {last_exc}") from last_exc + + +def _http_json_once(method, url, token, payload=None, timeout=HTTP_TIMEOUT_SECONDS): """One JSON HTTP call with a bearer token; returns the parsed body. - Raises RuntimeError naming the endpoint (never the token) on any - transport or HTTP failure. + One attempt. HTTP failures raise RuntimeError naming the + endpoint (never the token); transport failures propagate raw so + http_json can retry them. """ data = None if payload is None else json.dumps(payload).encode() req = urllib.request.Request(url, data=data, method=method) @@ -92,8 +119,6 @@ def http_json(method, url, token, payload=None, timeout=HTTP_TIMEOUT_SECONDS): except urllib.error.HTTPError as exc: detail = exc.read().decode(errors="replace")[:300] raise RuntimeError(f"{method} {url} -> HTTP {exc.code}: {detail}") from exc - except (urllib.error.URLError, TimeoutError, OSError) as exc: - raise RuntimeError(f"{method} {url} failed: {exc}") from exc # ------------------------------------------------------- libsql (Turso) diff --git a/infra/fleet-queue-backup/tests/test_http_retry.py b/infra/fleet-queue-backup/tests/test_http_retry.py new file mode 100644 index 0000000000..377917a980 --- /dev/null +++ b/infra/fleet-queue-backup/tests/test_http_retry.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""http_json transport retry (#8584): a connection reset must not be +fatal to a multi-hour export or restore; an HTTP error must not be +retried (the API answered; it does not heal). + +Run: python3 -I infra/fleet-queue-backup/tests/test_http_retry.py +""" + +import io +import json +import os +import sys +import unittest +import urllib.error +import urllib.request + +BIN = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "bin")) +sys.path.insert(0, BIN) + +import fq_common + + +class FakeResponse: + def __init__(self, body): + self._body = body + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self): + return self._body + + +class TestHttpRetry(unittest.TestCase): + def setUp(self): + self.calls = 0 + self._real_urlopen = urllib.request.urlopen + self._real_sleep = fq_common.time.sleep + fq_common.time.sleep = lambda _s: None + + def tearDown(self): + urllib.request.urlopen = self._real_urlopen + fq_common.time.sleep = self._real_sleep + + def test_transport_failures_are_retried(self): + def flaky(req, timeout=None): + self.calls += 1 + if self.calls < 3: + raise urllib.error.URLError("connection reset by peer") + return FakeResponse(json.dumps({"ok": True}).encode()) + + urllib.request.urlopen = flaky + out = fq_common.http_json("GET", "https://example.invalid/x", "tok") + self.assertEqual(out, {"ok": True}) + self.assertEqual(self.calls, 3) + + def test_http_errors_are_not_retried(self): + def broken(req, timeout=None): + self.calls += 1 + raise urllib.error.HTTPError( + req.full_url, 400, "bad", {}, io.BytesIO(b'{"e":1}') + ) + + urllib.request.urlopen = broken + with self.assertRaises(RuntimeError): + fq_common.http_json("GET", "https://example.invalid/x", "tok") + self.assertEqual(self.calls, 1) + + def test_transport_failure_eventually_raises(self): + def dead(req, timeout=None): + self.calls += 1 + raise urllib.error.URLError("unreachable") + + urllib.request.urlopen = dead + with self.assertRaises(RuntimeError): + fq_common.http_json("GET", "https://example.invalid/x", "tok") + self.assertEqual(self.calls, fq_common.TRANSPORT_ATTEMPTS) + + +if __name__ == "__main__": + unittest.main()