#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Native SQLite lock-bypass experiment. Only fresh temporary databases are used.""" import argparse import hashlib import itertools import json import os from pathlib import Path import platform import sqlite3 import subprocess import sys import tempfile from datetime import datetime, timezone MODES = ("delete", "truncate", "persist", "wal") LAYOUTS = ("same-table", "separate-tables") ACTIONS = ("none", "raw-main-close", "raw-main-held", "raw-other-close", "sqlite-managed-close", "separate-process-read", "raw-hardlink-close") SELECTS = { "same-table": "SELECT id,v FROM t ORDER BY id", "separate-tables": "SELECT 1,v FROM a UNION ALL SELECT 2,v FROM b ORDER BY 1", } UPDATES = { "same-table": ("UPDATE t SET v=1 WHERE id=1", "UPDATE t SET v=10 WHERE id=2"), "separate-tables": ("UPDATE a SET v=1", "UPDATE b SET v=10"), } PEER = """ import json, os, sqlite3, sys from pathlib import Path path, mode, layout, operation = sys.argv[1:] selects = { "same-table": "SELECT id,v FROM t ORDER BY id", "separate-tables": "SELECT 1,v FROM a UNION ALL SELECT 2,v FROM b ORDER BY 1", } updates = { "same-table": "UPDATE t SET v=10 WHERE id=2", "separate-tables": "UPDATE b SET v=10", } r = {"version": sqlite3.sqlite_version, "begin": False, "commit": False} if operation == "read": f = os.open(path, os.O_RDONLY) try: r["header_hex"] = os.read(f,16).hex() finally: os.close(f) else: c = sqlite3.connect(Path(path).as_uri()+"?vfs=unix", uri=True, timeout=0, isolation_level=None) stage = "configure" try: r["mode"] = c.execute("PRAGMA journal_mode="+mode).fetchone()[0] c.execute("PRAGMA synchronous=FULL") stage = "begin" c.execute("BEGIN IMMEDIATE"); r["begin"] = True if operation == "probe": c.execute("ROLLBACK") else: stage = "update"; c.execute(updates[layout]) stage = "commit"; c.execute("COMMIT"); r["commit"] = True stage = "readback"; r["readback"] = c.execute(selects[layout]).fetchall() except sqlite3.Error as e: r["error"] = {"stage": stage, "name": e.sqlite_errorname, "code": e.sqlite_errorcode, "message": str(e)} finally: c.close() print(json.dumps(r)) """ def require(condition, message): if not condition: raise RuntimeError(message) def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def peer(path, mode, layout, operation): result = subprocess.run( [sys.executable, "-c", PEER, str(path), mode, layout, operation], check=True, capture_output=True, text=True, timeout=15, close_fds=True, ) require(not result.stderr, "Unexpected peer stderr: " + result.stderr) value = json.loads(result.stdout) require(value["version"] == sqlite3.sqlite_version, "Mixed SQLite builds") if operation != "read": require(value.get("mode") == mode, "Peer journal mode unavailable") return value def sql_outcome(connection, sql): try: connection.execute(sql) return {"ok": True} except sqlite3.Error as error: return {"ok": False, "name": error.sqlite_errorname, "code": error.sqlite_errorcode, "message": str(error)} def observe_case(mode, layout, action, repetition): require(mode in MODES and layout in LAYOUTS and action in ACTIONS, "Unknown experiment parameter") with tempfile.TemporaryDirectory(prefix="hesela-sqlite-lock-bypass-") as td: root = Path(td) path = root / "fixture.db" other = root / "unrelated" other.write_bytes(b"unrelated inode") # No raw database open/close is performed outside the selected intervention. c = sqlite3.connect(Path(path).as_uri()+"?vfs=unix", uri=True, timeout=0, isolation_level=None) held = None try: c.execute("PRAGMA page_size=4096") selected_mode = c.execute("PRAGMA journal_mode="+mode).fetchone()[0] require(selected_mode == mode, "Requested journal mode unavailable") c.execute("PRAGMA synchronous=FULL") c.execute("PRAGMA cache_spill=OFF") c.execute("PRAGMA wal_autocheckpoint=0") if layout == "same-table": c.execute("CREATE TABLE t(id INTEGER PRIMARY KEY,v INTEGER NOT NULL)") c.executemany("INSERT INTO t VALUES(?,0)", [(1,), (2,)]) else: for table in ("a", "b"): c.execute("CREATE TABLE "+table+"(v INTEGER NOT NULL)") c.execute("INSERT INTO "+table+" VALUES(0)") roots = c.execute( "SELECT name,rootpage FROM sqlite_schema WHERE type='table' ORDER BY name" ).fetchall() fixture = { "page_size": c.execute("PRAGMA page_size").fetchone()[0], "page_count": c.execute("PRAGMA page_count").fetchone()[0], "table_roots": roots, "synchronous": c.execute("PRAGMA synchronous").fetchone()[0], "cache_spill": c.execute("PRAGMA cache_spill").fetchone()[0], "locking_mode": c.execute("PRAGMA locking_mode").fetchone()[0], } require(fixture["page_count"] == (2 if layout == "same-table" else 3), "Unexpected fixture geometry") require(fixture["synchronous"] == 2 and fixture["cache_spill"] == 0, "Unexpected persistence/cache configuration") c.execute("BEGIN IMMEDIATE") c.execute(UPDATES[layout][0]) before = peer(path, mode, layout, "probe") require(not before["begin"] and before.get("error", {}).get("name") == "SQLITE_BUSY", "Pre-intervention writer was not blocked") intervention = {"action": action} if action.startswith("raw-"): target = other if action == "raw-other-close" else path if action == "raw-hardlink-close": target = root / "raw-alias" os.link(path, target) held = os.open(target, os.O_RDONLY) st = os.fstat(held) dbst = path.stat() intervention["same_inode"] = (st.st_dev, st.st_ino) == (dbst.st_dev, dbst.st_ino) intervention["header_hex"] = os.read(held, 16).hex() if action != "raw-main-held": os.close(held) held = None intervention["closed_before_peer"] = held is None elif action == "sqlite-managed-close": managed = sqlite3.connect(Path(path).as_uri()+"?vfs=unix", uri=True, timeout=0, isolation_level=None) try: intervention["readback"] = managed.execute(SELECTS[layout]).fetchall() finally: managed.close() elif action == "separate-process-read": intervention["reader"] = peer(path, mode, layout, "read") active_after_action = c.in_transaction after = peer(path, mode, layout, "write") parent_commit = sql_outcome(c, "COMMIT") parent_after_commit = c.in_transaction finally: c.close() if held is not None: os.close(held) final = sqlite3.connect(Path(path).as_uri()+"?vfs=unix", uri=True, timeout=0, isolation_level=None) try: values = final.execute(SELECTS[layout]).fetchall() integrity = [r[0] for r in final.execute("PRAGMA integrity_check")] finally: final.close() row = { "mode": mode, "layout": layout, "action": action, "repetition": repetition, "fixture": fixture, "before": before, "intervention": intervention, "parent_active_after_action": active_after_action, "peer": after, "parent_commit": parent_commit, "parent_active_after_commit": parent_after_commit, "final_rows": values, "integrity_check": integrity, "database_sha256_after_close": digest(path), } row["acknowledged_peer_value_missing"] = ( after["commit"] and dict(values).get(2) != 10 ) row["both_commits_ok"] = after["commit"] and parent_commit["ok"] return row def environment(): with sqlite3.connect(":memory:") as c: result = { "python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "vfs": "unix", "sqlite_source_id": c.execute("SELECT sqlite_source_id()").fetchone()[0], "compile_options": sorted(r[0] for r in c.execute("PRAGMA compile_options")), "kernel": platform.release(), "architecture": platform.machine(), } libraries = sorted({line.split()[-1] for line in Path("/proc/self/maps").read_text().splitlines() if "libsqlite3" in line and line.split()[-1].startswith("/")}) require(len(libraries) == 1, "Expected exactly one mapped SQLite library") result["sqlite_library_sha256"] = digest(libraries[0]) result["sqlite_library_basename"] = Path(libraries[0]).name result["temporary_filesystem"] = subprocess.check_output( ["stat", "-f", "-c", "%T", tempfile.gettempdir()], text=True ).strip() return result def summarize(rows): groups = [] for mode, layout, action in itertools.product(MODES, LAYOUTS, ACTIONS): selected = [r for r in rows if (r["mode"], r["layout"], r["action"]) == (mode, layout, action)] groups.append({ "mode": mode, "layout": layout, "action": action, "cases": len(selected), "peer_commits": sum(r["peer"]["commit"] for r in selected), "missing_acknowledged_peer_values": sum(r["acknowledged_peer_value_missing"] for r in selected), "both_commits_ok": sum(r["both_commits_ok"] for r in selected), "integrity_ok": sum(r["integrity_check"] == ["ok"] for r in selected), }) return groups def observe(repetitions=2): require(platform.system() == "Linux", "This runner requires Linux") require(type(repetitions) is int and 1 <= repetitions <= 5, "Use 1-5 repetitions") env = environment() rows = [observe_case(mode, layout, action, repeat) for repeat in range(1, repetitions+1) for mode, layout, action in itertools.product(MODES, LAYOUTS, ACTIONS)] return { "schema_version": 1, "generated_at": datetime.now(timezone.utc).isoformat(), "kind": "controlled-native-observation", "license": "CC0-1.0", "runner_sha256": digest(__file__), "environment": env, "repetitions": repetitions, "rows": rows, "summary": summarize(rows), } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--repetitions", type=int, default=2) args = parser.parse_args() # Refuse accidental replacement of a retained observation. require(not args.output.exists(), "Output already exists") data = observe(args.repetitions) with args.output.open("x", encoding="utf-8") as handle: json.dump(data, handle, indent=2, sort_keys=True) handle.write("\n") print(json.dumps({"sqlite": data["environment"]["sqlite"], "cases": len(data["rows"]), "missing_acknowledged_peer_values": sum(r["acknowledged_peer_value_missing"] for r in data["rows"]), "both_commits_ok_with_loss": sum(r["both_commits_ok"] and r["acknowledged_peer_value_missing"] for r in data["rows"])})) if __name__ == "__main__": main()