#!/usr/bin/env python3 """Observe SQLite page placement in private, generated fixtures; not a benchmark.""" import argparse from collections import Counter from contextlib import closing from datetime import datetime, timezone import hashlib import json from pathlib import Path import platform import sqlite3 import tempfile ROWS = 512 PAGE_SIZES = (512, 1024, 4096) ORDERS = ("ascending", "permuted") OBJECTS = ("sample", "sample_token", "clustered") SCHEMA = [ "CREATE TABLE sample(id INTEGER PRIMARY KEY, token TEXT NOT NULL, body TEXT NOT NULL)", "CREATE INDEX sample_token ON sample(token)", "CREATE TABLE clustered(token TEXT PRIMARY KEY, id INTEGER NOT NULL, body TEXT NOT NULL) WITHOUT ROWID", ] STAT_SQL = ("SELECT name,path,pageno,pagetype,ncell,payload,unused,pgsize FROM dbstat " "WHERE name IN ('sample','sample_token','clustered') ORDER BY name,path") READ_SQL = { "sample": "SELECT id,token,body FROM sample NOT INDEXED ORDER BY id", "sample_token": "SELECT id,token,body FROM sample INDEXED BY sample_token ORDER BY id", "clustered": "SELECT id,token,body FROM clustered ORDER BY id", } def require(condition, message): if not condition: raise ValueError(message) def digest(data): return hashlib.sha256(data).hexdigest() def row_digest(rows): return digest(json.dumps(rows, separators=(",", ":"), ensure_ascii=True).encode()) def expected_rows(): return [(i, format(i, "032x"), format(i, "024x")) for i in range(1, ROWS + 1)] def validate(case): require(type(case["pageSize"]) is int and case["pageSize"] in PAGE_SIZES, "page size") require(case["order"] in ORDERS, "insertion order") require(type(case["repeat"]) is int and case["repeat"] in (1, 2), "repeat") require(case["integrityCheck"] == ["ok"], "integrity check") require(case["databaseSha256Before"] == case["databaseSha256After"], "read-only file changed") wanted_digest = row_digest(expected_rows()) require(set(case["objects"]) == set(OBJECTS), "object set") for name, obj in case["objects"].items(): require(type(obj["rowCount"]) is int and obj["rowCount"] == ROWS, "row count") require(obj["rowsSha256"] == wanted_digest, "complete row oracle") pages = obj["pages"] require(bool(pages), "missing pages") require(len({p["pageno"] for p in pages}) == len(pages), "duplicate page") kinds = Counter(p["pagetype"] for p in pages) require(set(kinds) == {"internal", "leaf"}, "require internal and leaf, no overflow") totals = {} for kind in ("internal", "leaf"): subset = [page for page in pages if page["pagetype"] == kind] totals[kind] = {key: sum(page[key] for page in subset) for key in ("ncell", "payload")} totals[kind]["pages"] = len(subset) require(obj["totals"] == totals, "aggregate mismatch") for page in pages: for key in ("pageno", "ncell", "payload", "unused", "pgsize", "headerType", "headerCells"): require(type(page[key]) is int and page[key] >= 0, "noninteger page field") require(page["pgsize"] == case["pageSize"], "reported page size") expected_type = (5 if page["pagetype"] == "internal" else 13) if name == "sample" else (2 if page["pagetype"] == "internal" else 10) require(page["headerType"] == expected_type, "file header page type") require(page["headerCells"] == page["ncell"], "file header cell count") depths = {page["path"].count("/") - 1 for page in pages if page["pagetype"] == "leaf"} require(len(depths) == 1 and min(depths) >= 1, "unbalanced or unsplit tree") if name == "sample": require(totals["internal"]["payload"] == 0, "table interior has payload") require(totals["leaf"]["ncell"] == ROWS, "table leaf record count") else: require(totals["internal"]["payload"] > 0, "index interior lacks payload") require(totals["internal"]["ncell"] > 0, "index interior lacks cells") require(totals["internal"]["ncell"] + totals["leaf"]["ncell"] == ROWS, "index total record count") require(totals["leaf"]["ncell"] < ROWS, "index leaf-only count") def observe(root, page_size, order, repeat): path = root / "fixture.db" rows = expected_rows() insertion = rows if order == "ascending" else sorted(rows, key=lambda row: (row[0] * 73) % ROWS) with closing(sqlite3.connect(path)) as db, db: db.execute("PRAGMA page_size=" + str(page_size)) db.execute("PRAGMA journal_mode=DELETE") for sql in SCHEMA: db.execute(sql) db.executemany("INSERT INTO sample VALUES(?,?,?)", insertion) db.executemany("INSERT INTO clustered(token,id,body) VALUES(?,?,?)", [(t, i, b) for i, t, b in insertion]) raw = path.read_bytes() before = digest(raw) case = {"pageSize": page_size, "order": order, "repeat": repeat, "databaseSha256Before": before, "databaseBytes": len(raw), "objects": {}} with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as db: case["integrityCheck"] = [r[0] for r in db.execute("PRAGMA integrity_check")] cursor = db.execute(STAT_SQL) columns = [c[0] for c in cursor.description] pages = [dict(zip(columns, row)) for row in cursor] for name in OBJECTS: selected = [page for page in pages if page["name"] == name] for page in selected: offset = (page["pageno"] - 1) * page_size + (100 if page["pageno"] == 1 else 0) page["headerType"] = raw[offset] page["headerCells"] = int.from_bytes(raw[offset + 3:offset + 5], "big") actual = db.execute(READ_SQL[name]).fetchall() require(actual == rows, "readback differs from explicit rows") totals = {} for kind in ("internal", "leaf"): group = [page for page in selected if page["pagetype"] == kind] totals[kind] = {key: sum(page[key] for page in group) for key in ("ncell", "payload")} totals[kind]["pages"] = len(group) case["objects"][name] = {"rowCount": len(actual), "rowsSha256": row_digest(actual), "pages": selected, "totals": totals} case["databaseSha256After"] = digest(path.read_bytes()) validate(case) return case def run(): with closing(sqlite3.connect(":memory:")) as db: environment = { "python": platform.python_version(), "sqlite": sqlite3.sqlite_version, "sqliteSourceId": db.execute("SELECT sqlite_source_id()").fetchone()[0], "compileOptions": [row[0] for row in db.execute("PRAGMA compile_options")], "platform": platform.platform(), } db.execute("SELECT count(*) FROM dbstat").fetchone() cases = [] for page_size in PAGE_SIZES: for order in ORDERS: for repeat in (1, 2): with tempfile.TemporaryDirectory(prefix="hesela-btree-") as folder: cases.append(observe(Path(folder), page_size, order, repeat)) return { "evidenceType": "controlled-software-observation", "generatedAt": datetime.now(timezone.utc).isoformat(), "environment": environment, "method": { "rowsPerObject": ROWS, "pageSizesBytes": PAGE_SIZES, "orders": ORDERS, "repetitions": 2, "schema": SCHEMA, "dbstatSql": STAT_SQL, "readSql": READ_SQL, "insertionRule": "ascending ids or ids sorted by (id * 73) % 512; index exists before insertion", "rowRule": "id in 1..512; token=format(id, '032x'); body=format(id, '024x')", "units": "ncell counts cells; payload counts bytes of record payload on that page", }, "limits": [ "Generated fixtures, not sampled incidents or a performance benchmark.", "dbstat requires SQLITE_ENABLE_DBSTAT_VTAB and omits freelist, pointer-map and lock pages.", "No overflow pages in these small-record fixtures; this is checked, not assumed.", "Exact page packing depends on version, schema, page size and insertion history.", "No concurrent writer, crash, durability, device-read or sanitization measurement.", "Header checks inspect page type and cell count, not complete independent record decoding.", ], "codeSha256": digest(Path(__file__).read_bytes()), "cases": cases, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() if args.output.exists(): parser.error("output already exists; choose a new path") result = run() with args.output.open("x", encoding="utf-8") as out: json.dump(result, out, indent=2) out.write("\n") print(f"Validated {len(result['cases'])} private fixtures; output: {args.output}") if __name__ == "__main__": main()