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 | 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 2242836dec..2a4d30b51e 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 @@ -50,17 +51,62 @@ 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 + +# 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__ # ------------------------------------------------------------ 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) @@ -73,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) @@ -214,6 +258,255 @@ 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 _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 + 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) + 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. + + 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 _is_constraint_def(d): + 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 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. + + 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: + return [c.strip().strip('"`[]') for c in m.group(1).split(",")] + for d in defs: + d = d.strip() + 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): + 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. @@ -221,16 +514,25 @@ 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) + 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). @@ -241,11 +543,20 @@ 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) + ");") + counts[name] += 1 + 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(";") + ";") @@ -262,7 +573,7 @@ def build_dump(client, exported_at): ) + ");" ) - return "\n".join(lines) + "\n", counts + return "\n".join(lines) + "\n", counts, splits # ------------------------------------------------------------- Cloudflare @@ -304,34 +615,73 @@ 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. + + 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( + 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", - {"action": "init", "etag": digest}, + {"action": "ingest", "etag": digest, "filename": filename}, ) - 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}" - ) - for _attempt in range(60): + 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/bin/restore_drill.py b/infra/fleet-queue-backup/bin/restore_drill.py index 560a1b2b75..d4d8ec0d49 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): @@ -64,26 +68,93 @@ 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_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 + ] + 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 * FROM "{table}" LIMIT {fq_common.PAGE_ROWS} 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(d1_value(row[c]) for c in columns) - if len(rows) < fq_common.PAGE_ROWS: + 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 += fq_common.PAGE_ROWS + offset += READ_PAGE raise RuntimeError( f"{table}: D1 pagination exceeded {fq_common.MAX_PAGES} pages; " "refusing to page unboundedly" @@ -107,15 +178,20 @@ 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}"') 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/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..7be655e280 --- /dev/null +++ b/infra/fleet-queue-backup/tests/test_d1_import.py @@ -0,0 +1,137 @@ +#!/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._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), + 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) + + + 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() 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() 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_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() diff --git a/infra/fleet-queue-backup/tests/test_restore_drill.py b/infra/fleet-queue-backup/tests/test_restore_drill.py index 41049edfc5..f5a58a524c 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,14 +116,121 @@ 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 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:") + 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 = fq_common.build_dump( + dump, _counts, _splits = fq_common.build_dump( SqliteLibsqlAdapter(source), "2026-11-22T00:00:00Z" ) 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 +252,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(), 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() 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..9efba7e077 --- /dev/null +++ b/infra/fleet-queue-backup/tests/test_table_columns.py @@ -0,0 +1,78 @@ +#!/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)" +) +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, " + '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_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), + ["worker_id", "key", "value", "updated_at"], + ) + self.assertEqual( + fq_common._pk_columns(CHECKPOINTS), ["worker_id", "key"] + ) + + +if __name__ == "__main__": + unittest.main()