#!/usr/bin/env python3 """Exercise SQLite's native backup API on disposable, constructed databases.""" import argparse import ctypes import ctypes.util import hashlib import json from pathlib import Path import platform import sqlite3 import tempfile from datetime import datetime, timezone OK, BUSY, DONE = 0, 5, 101 MODES = ("no-step", "partial", "busy", "complete") ROWS = 64 PAYLOAD_BYTES = 4096 PARTIAL_PAGES = 8 def require(condition, message): if not condition: raise RuntimeError(message) def digest_rows(rows): return hashlib.sha256(json.dumps(rows, separators=(",", ":")).encode()).hexdigest() def expected_rows(generation): return [(i, generation, (f"g{generation}-row{i:03d}-" * 512)[:PAYLOAD_BYTES]) for i in range(ROWS)] def seed(path, generation): db = sqlite3.connect(path) try: db.execute("PRAGMA page_size=4096") require(db.execute("PRAGMA journal_mode=DELETE").fetchone()[0] == "delete", "DELETE journal mode required for the lock control") db.execute("PRAGMA synchronous=FULL") db.execute("CREATE TABLE records(id INTEGER PRIMARY KEY, generation INTEGER, payload TEXT)") db.executemany("INSERT INTO records VALUES(?,?,?)", expected_rows(generation)) db.commit() require(db.execute("PRAGMA page_count").fetchone()[0] > 1, "Need a multi-page database") finally: db.close() def inspect(path): db = sqlite3.connect(path.as_uri() + "?mode=ro", uri=True) try: rows = db.execute("SELECT id,generation,payload FROM records ORDER BY id").fetchall() return { "rows": rows, "integrity": [r[0] for r in db.execute("PRAGMA integrity_check")], "page_count": db.execute("PRAGMA page_count").fetchone()[0], "source_id": db.execute("SELECT sqlite_source_id()").fetchone()[0], } finally: db.close() class Native: def __init__(self): self.library = ctypes.util.find_library("sqlite3") require(self.library, "A system SQLite shared library is required") self.lib = ctypes.CDLL(self.library) ptr, integer, string = ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p signatures = { "sqlite3_open_v2": ([string, ctypes.POINTER(ptr), integer, string], integer), "sqlite3_close": ([ptr], integer), "sqlite3_exec": ([ptr, string, ptr, ptr, ptr], integer), "sqlite3_prepare_v2": ([ptr, string, integer, ctypes.POINTER(ptr), ptr], integer), "sqlite3_step": ([ptr], integer), "sqlite3_column_int": ([ptr, integer], integer), "sqlite3_finalize": ([ptr], integer), "sqlite3_errmsg": ([ptr], string), "sqlite3_libversion": ([], string), "sqlite3_sourceid": ([], string), "sqlite3_backup_init": ([ptr, string, ptr, string], ptr), "sqlite3_backup_step": ([ptr, integer], integer), "sqlite3_backup_remaining": ([ptr], integer), "sqlite3_backup_pagecount": ([ptr], integer), "sqlite3_backup_finish": ([ptr], integer), } for name, (args, result) in signatures.items(): function = getattr(self.lib, name) function.argtypes = args function.restype = result def open(self, path, readonly=False): handle = ctypes.c_void_p() rc = self.lib.sqlite3_open_v2(str(path).encode(), ctypes.byref(handle), 1 if readonly else 2, None) if rc != OK: detail = self.lib.sqlite3_errmsg(handle).decode() if handle else "no handle" if handle: self.lib.sqlite3_close(handle) raise RuntimeError(f"Open failed ({rc}): {detail}") return handle def scalar(self, handle, sql): statement = ctypes.c_void_p() rc = self.lib.sqlite3_prepare_v2(handle, sql.encode(), -1, ctypes.byref(statement), None) require(rc == OK, "Native scalar prepare failed") try: require(self.lib.sqlite3_step(statement) == 100, "Expected one native result row") value = self.lib.sqlite3_column_int(statement, 0) require(self.lib.sqlite3_step(statement) == DONE, "Unexpected extra result") return value finally: require(self.lib.sqlite3_finalize(statement) == OK, "Native finalize failed") def configure(self, handle): require(self.lib.sqlite3_exec(handle, b"PRAGMA synchronous=FULL", None, None, None) == OK, "Could not set native synchronous mode") require(self.scalar(handle, "PRAGMA synchronous") == 2, "Native FULL mode not active") require(self.scalar(handle, "PRAGMA page_size") == 4096, "Native page-size mismatch") def close(self, handle): require(self.lib.sqlite3_close(handle) == OK, "Native close failed") def validate_case(case): mode = case["mode"] require(mode in MODES, "Unknown mode") require(case["finish_rc"] == (BUSY if mode == "busy" else OK), "Unexpected finish result") require(case["integrity_check"] == ["ok"], "Destination integrity failed") require(case["row_count"] == ROWS, "Unexpected row count") require(case["source_unchanged"], "Source changed") expected_steps = {"no-step": [], "partial": [OK], "busy": [BUSY], "complete": [DONE]} require([s["rc"] for s in case["steps"]] == expected_steps[mode], "Unexpected step result") complete = mode == "complete" require(case["observed_done"] == complete, "Completion evidence mismatch") require(case["matches_source"] == complete, "Destination/source mismatch") require(case["matches_old_destination"] == (not complete), "Rollback mismatch") require(case["accepted_as_completed_copy"] == complete, "Acceptance mismatch") if mode in ("partial", "complete"): step = case["steps"][0] require(step["page_count"] == case["source_pages_before"], "Page count mismatch") expected_remaining = step["page_count"] - PARTIAL_PAGES if mode == "partial" else 0 require(step["remaining"] == expected_remaining, "Remaining-page mismatch") require(step["page_count"] > PARTIAL_PAGES, "Source must exceed the partial copy") def run_case(native, mode): require(mode in MODES, "Unknown mode") with tempfile.TemporaryDirectory(prefix="hesela-backup-completion-") as tmp: root = Path(tmp) source, target = root / "source.db", root / "target.db" seed(source, 2) seed(target, 1) before_source, before_target = inspect(source), inspect(target) require(before_source["rows"] == expected_rows(2), "Source fixture mismatch") require(before_target["rows"] == expected_rows(1), "Target fixture mismatch") require(before_source["source_id"] == native.lib.sqlite3_sourceid().decode(), "Python and native SQLite must use the same build") source_db = native.open(source, readonly=True) target_db = None locker = None steps = [] try: target_db = native.open(target) native.configure(source_db) native.configure(target_db) if mode == "busy": locker = sqlite3.connect(source, timeout=0) locker.execute("BEGIN EXCLUSIVE") backup = native.lib.sqlite3_backup_init(target_db, b"main", source_db, b"main") require(backup, "backup_init failed") # Do not use the destination connection while the backup handle is active. try: if mode != "no-step": rc = native.lib.sqlite3_backup_step(backup, PARTIAL_PAGES if mode == "partial" else -1) steps.append({ "rc": rc, "remaining": native.lib.sqlite3_backup_remaining(backup) if rc in (OK, DONE) else None, "page_count": native.lib.sqlite3_backup_pagecount(backup) if rc in (OK, DONE) else None, }) finally: finish_rc = native.lib.sqlite3_backup_finish(backup) finally: if locker is not None: locker.rollback() locker.close() try: if target_db is not None: native.close(target_db) finally: native.close(source_db) after = inspect(target) source_after = inspect(source) done = any(step["rc"] == DONE for step in steps) matches_source = after["rows"] == before_source["rows"] case = { "mode": mode, "steps": steps, "finish_rc": finish_rc, "observed_done": done, "source_pages_before": before_source["page_count"], "row_count": len(after["rows"]), "integrity_check": after["integrity"], "source_unchanged": source_after["rows"] == before_source["rows"], "matches_source": matches_source, "matches_old_destination": after["rows"] == before_target["rows"], "accepted_as_completed_copy": done and finish_rc == OK and matches_source, "source_rows_sha256": digest_rows(before_source["rows"]), "old_destination_rows_sha256": digest_rows(before_target["rows"]), "reopened_destination_rows_sha256": digest_rows(after["rows"]), } validate_case(case) return case def run(): native = Native() return { "schema_version": 1, "title": "SQLite backup cleanup versus copy completion", "generated_at": datetime.now(timezone.utc).isoformat(), "experiment_type": "Executed native API experiment on constructed data", "environment": { "sqlite_version": native.lib.sqlite3_libversion().decode(), "sqlite_source_id": native.lib.sqlite3_sourceid().decode(), "shared_library": native.library, "python_version": platform.python_version(), "platform": platform.platform(), "script_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), }, "method": { "rows_per_database": ROWS, "payload_bytes_per_row": PAYLOAD_BYTES, "page_size_bytes": 4096, "partial_pages_requested": PARTIAL_PAGES, "journal_mode": "DELETE", "synchronous": "FULL; set and checked on native source and destination before backup_init", "source_generation": 2, "initial_destination_generation": 1, "copy_scope": "main database only", "seed": None, "randomness": "None: deterministic, distinct fixtures of equal row count", "native_calls": "ctypes calls sqlite3_backup_init/step/finish directly; not Connection.backup", "verification": "Close both native handles; reopen read-only; compare every ordered row and run integrity_check", "hash_encoding": "SHA256 of UTF-8 JSON ordered row arrays using separators comma and colon", "lock_control": "Separate source connection holds BEGIN EXCLUSIVE; no busy handler; abandon after SQLITE_BUSY", }, "sources": [ "https://www.sqlite.org/c3ref/backup_finish.html", "https://www.sqlite.org/backup.html", "https://github.com/sqlite/sqlite/blob/version-3.45.1/src/backup.c", "https://www.sqlite.org/pragma.html#pragma_integrity_check", ], "limits": [ "Four deterministic cases on the recorded SQLite build; not a fleet sample or failure rate.", "The abandoned BUSY case expects finish=BUSY, as observed and source-checked for SQLite 3.45.1; this differs from the API prose.", "Controlled abandonment, not process crash, power loss or I/O error injection.", "No concurrent source changes, throughput measurements or whole-application recovery.", "Existing destination in DELETE mode; no WAL destination, attached-database set or wrapper API tested.", "Successful logical verification is not a durability or source-freshness guarantee.", ], "cases": [run_case(native, mode) for mode in MODES], } if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, help="Write the generated JSON receipt here") args = parser.parse_args() result = json.dumps(run(), indent=2) + "\n" if args.output: args.output.write_text(result) else: print(result, end="")