#!/usr/bin/env python3 """Observe SQLite journal lifecycle on disposable data; NOT a power-loss test.""" import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import sqlite3 import subprocess import sys import tempfile ROWS = 256 PAYLOAD_BYTES = 2048 MAGIC = "d9d505f920a163d7" CASES = (("DELETE", True), ("TRUNCATE", True), ("PERSIST", True), ("DELETE", False), ("PERSIST", False)) LIMITS = [ "Deterministic synthetic workload, actual local observations; not fleet data.", "os._exit terminates the writer without SQLite close or rollback; the OS and its caches remain alive.", "No power loss, kernel crash, torn sector, I/O fault injection or device flush verification.", "Single database only: no ATTACH, super-journal or cross-file atomicity experiment.", "One installed SQLite build and filesystem; no failure probability or performance estimate.", "Eight-byte journal prefix is an observation, not a complete hot-journal validator.", ] def require(condition, message): if not condition: raise RuntimeError(message) def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def journal_state(database): journal = Path(str(database) + "-journal") if not journal.exists(): return {"exists": False, "sizeBytes": 0, "prefixHex": None} with journal.open("rb") as stream: prefix = stream.read(8).hex() return {"exists": True, "sizeBytes": journal.stat().st_size, "prefixHex": prefix} def writer(database, mode, commit): require(mode in {"DELETE", "TRUNCATE", "PERSIST"}, "Unsupported journal mode") connection = sqlite3.connect(database) actual_mode = connection.execute("PRAGMA journal_mode=" + mode).fetchone()[0] connection.execute("PRAGMA synchronous=FULL") connection.execute("PRAGMA cache_size=8") connection.execute("PRAGMA cache_spill=ON") settings = { "journalMode": actual_mode, "synchronous": connection.execute("PRAGMA synchronous").fetchone()[0], "pageSizeBytes": connection.execute("PRAGMA page_size").fetchone()[0], "cacheSizePages": connection.execute("PRAGMA cache_size").fetchone()[0], "cacheSpill": connection.execute("PRAGMA cache_spill").fetchone()[0], } connection.execute("BEGIN IMMEDIATE") connection.execute("UPDATE sample SET payload=?", ("B" * PAYLOAD_BYTES,)) if commit: connection.commit() print(json.dumps(settings), flush=True) # Deliberately bypass connection cleanup in BOTH outcomes; keep the OS running. os._exit(0 if commit else 23) def observe_case(root, mode, commit): database = root / "sample.db" connection = sqlite3.connect(database) connection.execute("PRAGMA page_size=4096") connection.execute("PRAGMA journal_mode=DELETE") connection.execute("PRAGMA synchronous=FULL") connection.execute("CREATE TABLE sample (id INTEGER PRIMARY KEY, payload TEXT NOT NULL)") connection.executemany("INSERT INTO sample VALUES (?, ?)", ((i, "A" * PAYLOAD_BYTES) for i in range(1, ROWS + 1))) connection.commit() connection.close() initial_hash = digest(database) process = subprocess.run( [sys.executable, str(Path(__file__).resolve()), "--writer", str(database), mode, "commit" if commit else "abandon"], capture_output=True, text=True, timeout=30, check=False) require(process.returncode == (0 if commit else 23), "Unexpected writer exit: " + process.stderr) settings = json.loads(process.stdout) require(settings["journalMode"] == mode.lower(), "Requested mode was not applied") before_read = journal_state(database) changed = digest(database) != initial_hash updated_bytes_present = (b"B" * PAYLOAD_BYTES) in database.read_bytes() # The child has exited. No other connection is open when SQLite performs recovery. connection = sqlite3.connect(database) rows = connection.execute("SELECT id, payload FROM sample ORDER BY id").fetchall() expected = [(i, ("B" if commit else "A") * PAYLOAD_BYTES) for i in range(1, ROWS + 1)] matches = rows == expected integrity = connection.execute("PRAGMA integrity_check").fetchall() recovery_mode = connection.execute("PRAGMA journal_mode").fetchone()[0] connection.close() after_read = journal_state(database) require(matches, "Recovered contents differ from the complete expected row set") require(integrity == [("ok",)], "SQLite integrity_check failed") if not commit: require(changed and updated_bytes_present, "No database spill observed; recovery demonstration is inconclusive") require(before_read["sizeBytes"] > 512 and before_read["prefixHex"] == MAGIC, "No initialized recovery journal observed; demonstration is inconclusive") require(after_read["prefixHex"] != MAGIC, "Journal remains active after recovery") elif mode == "DELETE": require(not before_read["exists"], "DELETE commit left a journal") elif mode == "TRUNCATE": require(before_read["exists"] and before_read["sizeBytes"] == 0, "TRUNCATE commit did not leave an empty journal") else: require(before_read["sizeBytes"] > 512 and before_read["prefixHex"] == "00" * 8, "PERSIST commit did not leave a zeroed journal header") return { "case": mode.lower() + ("-committed" if commit else "-uncommitted-exit"), "writerCommitted": commit, "writerExitCode": process.returncode, "settings": settings, "databaseBytesChangedBeforeRead": changed, "updatedPayloadBytesPresentBeforeRead": updated_bytes_present, "recoveryConnectionJournalMode": recovery_mode, "journalBeforeRecoveryRead": before_read, "journalAfterRecoveryRead": after_read, "rowCount": len(rows), "rowPayloadBytes": PAYLOAD_BYTES, "visiblePayload": "B" if commit else "A", "allRowsMatchOracle": matches, "integrityCheck": integrity[0][0], } def run_observations(work_root=None): observations = [] with tempfile.TemporaryDirectory(prefix="hesela-sqlite-", dir=work_root) as temp: root = Path(temp) filesystem = subprocess.run( ["stat", "-f", "-c", "%T", str(root)], capture_output=True, text=True, timeout=10, check=True).stdout.strip() if sys.platform.startswith("linux") else "unmeasured" for index, (mode, commit) in enumerate(CASES): case_root = root / str(index) case_root.mkdir() observations.append(observe_case(case_root, mode, commit)) connection = sqlite3.connect(":memory:") source_id = connection.execute("SELECT sqlite_source_id()").fetchone()[0] options = [row[0] for row in connection.execute("PRAGMA compile_options")] connection.close() return { "schemaVersion": 1, "kind": "measured-software-behavior", "generatedAt": datetime.now(timezone.utc).isoformat(), "title": "SQLite rollback-journal lifecycle: process-exit observations", "scriptSha256": digest(__file__), "environment": {"python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "sqliteSourceId": source_id, "sqliteCompileOptions": options, "os": platform.system(), "kernel": platform.release(), "architecture": platform.machine(), "statfsTypeLabel": filesystem}, "workload": {"rowsPerCase": ROWS, "payloadBytesPerRow": PAYLOAD_BYTES, "initialPayload": "A", "updatedPayload": "B", "randomness": "none", "independentDatabasePerCase": True}, "caseCount": len(observations), "observations": observations, "limits": LIMITS, "sources": ["https://sqlite.org/atomiccommit.html", "https://sqlite.org/lockingv3.html", "https://sqlite.org/pragma.html#pragma_journal_mode"], "reproduce": "python3 sqlite-journal-observation.py --work-root . --output result.json", } if __name__ == "__main__": if len(sys.argv) == 5 and sys.argv[1] == "--writer": writer(sys.argv[2], sys.argv[3], sys.argv[4] == "commit") parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--work-root", type=Path, help="Existing directory for disposable test databases") parser.add_argument("--output", type=Path, help="New JSON result path; existing files are not overwritten") args = parser.parse_args() result = run_observations(args.work_root) serialized = json.dumps(result, indent=2) + "\n" if args.output: with args.output.open("x", encoding="utf-8") as output: output.write(serialized) else: print(serialized, end="")