#!/usr/bin/env python3 """Observe SQLite backup progress, writer identity and source-view tradeoffs. Only private synthetic databases are created; no database-path input is accepted. Native binding and fixture helpers adapted from Hesela sqlite-backup-completion.py. """ import argparse import ctypes as C import ctypes.util import hashlib import json from pathlib import Path import platform import sys import tempfile from datetime import datetime, timezone OK, DONE = 0, 101 ROWS = 64 CALLBACK = C.CFUNCTYPE(C.c_int, C.c_void_p, C.c_int, C.POINTER(C.c_char_p), C.POINTER(C.c_char_p)) def require(condition, message): if not condition: raise RuntimeError(message) class SQLite: def __init__(self): self.library = ctypes.util.find_library("sqlite3") require(self.library, "System SQLite shared library not found") self.lib = C.CDLL(self.library) signatures = { "open_v2": ([C.c_char_p, C.POINTER(C.c_void_p), C.c_int, C.c_char_p], C.c_int), "close": ([C.c_void_p], C.c_int), "exec": ([C.c_void_p, C.c_char_p, CALLBACK, C.c_void_p, C.POINTER(C.c_void_p)], C.c_int), "free": ([C.c_void_p], None), "errcode": ([C.c_void_p], C.c_int), "backup_init": ([C.c_void_p, C.c_char_p, C.c_void_p, C.c_char_p], C.c_void_p), "backup_step": ([C.c_void_p, C.c_int], C.c_int), "backup_remaining": ([C.c_void_p], C.c_int), "backup_pagecount": ([C.c_void_p], C.c_int), "backup_finish": ([C.c_void_p], C.c_int), "libversion": ([], C.c_char_p), "sourceid": ([], C.c_char_p), "compileoption_get": ([C.c_int], C.c_char_p), } for name, (args, result) in signatures.items(): fn = getattr(self.lib, "sqlite3_" + name) fn.argtypes, fn.restype = args, result setattr(self, name, fn) def connect(self, path, readonly=False): db = C.c_void_p() rc = self.open_v2(str(path).encode(), C.byref(db), 1 if readonly else 6, None) if rc != OK: if db.value: self.close(db) raise RuntimeError(f"sqlite3_open_v2 returned {rc}") return db def query(self, db, sql): rows, errors = [], [] @CALLBACK def collect(_context, count, values, _names): try: rows.append([values[i].decode() if values[i] is not None else None for i in range(count)]) return 0 except Exception as error: errors.append(str(error)) return 1 error = C.c_void_p() rc = self.exec(db, sql.encode(), collect, None, C.byref(error)) message = C.string_at(error).decode() if error.value else "" if error.value: self.free(error) require(rc == OK and not errors, f"sqlite3_exec returned {rc}: {message} {errors}") return rows def disconnect(self, db): require(self.close(db) == OK, "sqlite3_close failed") def environment(self): options, i = [], 0 while (option := self.compileoption_get(i)) is not None: options.append(option.decode()) i += 1 return { "sqlite": self.libversion().decode(), "sourceId": self.sourceid().decode(), "sharedLibrary": self.library, "compileOptions": options, "python": platform.python_version(), "system": platform.system(), "machine": platform.machine(), "binding": "ctypes calls to sqlite3_backup_* C API", } def payload(generation, row): return f"generation={generation};id={row:03d};" + str(generation) * 8192 def seed(api, db, generation, mode): api.query(db, "PRAGMA page_size=4096") actual_mode = api.query(db, f"PRAGMA journal_mode={mode}")[0][0] require(actual_mode == mode.lower(), "Journal mode was not applied") api.query(db, "PRAGMA synchronous=FULL; PRAGMA wal_autocheckpoint=0") api.query(db, "CREATE TABLE sample(id INTEGER PRIMARY KEY, generation INTEGER, payload TEXT)") api.query(db, "BEGIN") for row in range(ROWS): api.query(db, f"INSERT INTO sample VALUES({row},{generation},'{payload(generation, row)}')") api.query(db, "COMMIT") return { "journalMode": actual_mode, "pageSize": int(api.query(db, "PRAGMA page_size")[0][0]), "synchronous": int(api.query(db, "PRAGMA synchronous")[0][0]), "walAutocheckpoint": int(api.query(db, "PRAGMA wal_autocheckpoint")[0][0]), } def inspect(api, db, generation): rows = api.query(db, "SELECT id,generation,payload FROM sample ORDER BY id") expected = [[str(i), str(generation), payload(generation, i)] for i in range(ROWS)] require(rows == expected, "Reopened destination differs from all expected row values") checks = [r[0] for r in api.query(db, "PRAGMA integrity_check")] require(checks == ["ok"], "integrity_check did not return exactly ok") return { "rows": len(rows), "generation": generation, "allRowsMatchExpected": True, "logicalRowsSha256": hashlib.sha256(json.dumps(rows, separators=(",", ":")).encode()).hexdigest(), "integrityCheck": checks, } WRITES = 6 INITIAL_PAGES = 8 STEP_PAGES = 2 SCHEDULES = (("DELETE", "idle"), ("DELETE", "external"), ("DELETE", "same-handle"), ("WAL", "idle"), ("WAL", "external"), ("WAL", "same-handle"), ("WAL", "pinned")) def run_case(api, root, mode, schedule): source = destination = writer = backup = None source_path, destination_path = root / "source.db", root / "destination.db" try: source = api.connect(source_path) destination = api.connect(destination_path) settings = seed(api, source, 10, mode) destination_settings = seed(api, destination, 0, "DELETE") writer = api.connect(source_path) api.query(writer, "PRAGMA synchronous=FULL; PRAGMA wal_autocheckpoint=0") if schedule == "pinned": api.query(source, "BEGIN") inspect(api, source, 10) pages = int(api.query(source, "PRAGMA page_count")[0][0]) require(pages > INITIAL_PAGES + WRITES * STEP_PAGES, "Fixture too small") backup = api.backup_init(destination, b"main", source, b"main") require(backup, "backup_init failed") def counters(): return {"remaining": api.backup_remaining(backup), "page_count": api.backup_pagecount(backup)} def step(requested): rc = api.backup_step(backup, requested) require(rc in (OK, DONE), f"Unexpected step result {rc}") return {"requested_pages": requested, "rc": rc, **counters()} initial = step(INITIAL_PAGES) require(initial["rc"] == OK, "Initial copy completed unexpectedly") events = [] generation = 10 for index in range(WRITES): before = counters() if schedule != "idle": generation += 1 owner = source if schedule == "same-handle" else writer api.query(owner, "BEGIN IMMEDIATE") for row in range(ROWS): api.query(owner, f"UPDATE sample SET generation={generation}, " f"payload='{payload(generation, row)}' WHERE id={row}") api.query(owner, "COMMIT") after_commit = counters() events.append({"index": index + 1, "committed_generation": generation, "before_commit": before, "after_commit": after_commit, "step": step(STEP_PAGES)}) # Quiesce this designed writer and drain the existing backup object. drain = [] for _ in range(pages + 1): event = step(STEP_PAGES) drain.append(event) if event["rc"] == DONE: break require(drain[-1]["rc"] == DONE and drain[-1]["remaining"] == 0, "Quiescent drain did not complete within bound") finish = api.backup_finish(backup) backup = None require(finish == OK, "Backup finish failed") api.disconnect(destination) destination = None if schedule == "pinned": api.query(source, "ROLLBACK") current = inspect(api, writer, generation) for db in (source, writer): api.disconnect(db) source = writer = None expected = 10 if schedule == "pinned" else generation destination = api.connect(destination_path, readonly=True) restored = inspect(api, destination, expected) return {"mode": mode, "schedule": schedule, "settings": settings, "destination_settings": destination_settings, "source_pages": pages, "initial": initial, "interleaved_events": events, "drain": drain, "finish_rc": finish, "source_after": current, "destination_after": restored, "source_file_sha256_after_close": hashlib.sha256(source_path.read_bytes()).hexdigest(), "destination_file_sha256_after_finish": hashlib.sha256(destination_path.read_bytes()).hexdigest()} finally: if backup: api.backup_finish(backup) for db in (destination, writer, source): if db: api.disconnect(db) def validate_case(case): n = case["source_pages"] require(case["initial"]["remaining"] == n - INITIAL_PAGES, "Initial counter mismatch") for i, event in enumerate(case["interleaved_events"], 1): require(event["before_commit"] == event["after_commit"], "Counters changed without a step") expected = n - STEP_PAGES if case["schedule"] == "external" else n - INITIAL_PAGES - i * STEP_PAGES require(event["step"]["rc"] == OK and event["step"]["remaining"] == expected, f"Unexpected progress trace: {case['mode']} {case['schedule']} round {i}") require(event["step"]["page_count"] == n, "Fixed-size fixture changed page count") require(case["drain"][-1]["rc"] == DONE, "Missing completion") require(case["finish_rc"] == OK, "Cleanup failed") latest = 10 if case["schedule"] == "idle" else WRITES + 10 copied = 10 if case["schedule"] == "pinned" else latest require(case["source_after"]["generation"] == latest, "Wrong source oracle") require(case["destination_after"]["generation"] == copied, "Wrong restored oracle") require(case["destination_after"]["allRowsMatchExpected"], "Rows did not match") def experiment(work_root, repeats=3): require(1 <= repeats <= 10, "repeats must be between 1 and 10") api = SQLite() runs = [] with tempfile.TemporaryDirectory(prefix="hesela-backup-progress-", dir=work_root) as temporary: root = Path(temporary) fs = __import__("subprocess").check_output( ["stat", "-f", "-c", "%T", str(root)], text=True).strip() for repetition in range(repeats): cases = [] for mode, schedule in SCHEDULES: case_root = root / f"{repetition}-{mode}-{schedule}" case_root.mkdir() case = run_case(api, case_root, mode, schedule) validate_case(case) cases.append(case) runs.append({"repetition": repetition + 1, "cases": cases}) return { "schemaVersion": 1, "kind": "constructed-software-observation", "generatedAt": datetime.now(timezone.utc).isoformat(), "environment": {**api.environment(), "kernel": platform.release(), "filesystem_label": fs}, "scriptSha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "method": {"repeats": repeats, "cases_per_repeat": len(SCHEDULES), "rows": ROWS, "initial_pages_requested": INITIAL_PAGES, "pages_per_step": STEP_PAGES, "write_rounds": WRITES, "writer": "Ordered single-thread interleaving; no sleeps or overlapping API calls", "oracle": "All IDs, generations and complete payloads; destination reopened read-only", "sql_update": "UPDATE sample SET generation=g, payload=payload(g,id) for every row, one transaction per round", "data_origin": "Deterministic synthetic fixture, not a production dataset"}, "runs": runs, "limitations": [ "One installed SQLite build; repetitions check repeatability, not a failure rate.", "No infinite execution was observed; six write rounds only, then a quiescent drain.", "No timing, physical I/O, growth, external process, shared-cache or crash measurement.", "Pinned-read case uses WAL only; no rollback-mode pinned-writer result is implied.", "The snapshot control is not a recovery-point guarantee or a deployment recommendation." ], "sources": ["https://www.sqlite.org/backup.html", "https://www.sqlite.org/c3ref/backup_finish.html", "https://www.sqlite.org/isolation.html", "https://github.com/sqlite/sqlite/blob/version-3.45.1/src/backup.c"] } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--work-root", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--repeats", type=int, default=3, choices=range(1, 11)) args = parser.parse_args() with args.output.open("x", encoding="utf-8") as stream: result = experiment(args.work_root, args.repeats) json.dump(result, stream, indent=2) stream.write("\n") print(f"Recorded {len(result['runs']) * len(SCHEDULES)} native schedules") if __name__ == "__main__": main()