"""Exercise the unmodified baseline with disposable Mesh-shaped records.""" from contextlib import closing from pathlib import Path import selectors import signal import sqlite3 import subprocess import sys import tempfile SCHEMA = """ CREATE TABLE records ( account TEXT NOT NULL, collection TEXT NOT NULL, id INTEGER NOT NULL, version INTEGER NOT NULL, payload BLOB NOT NULL, PRIMARY KEY (account, collection, id) ); CREATE TABLE changes ( seq INTEGER PRIMARY KEY AUTOINCREMENT, account TEXT NOT NULL, id INTEGER NOT NULL, version INTEGER NOT NULL ); CREATE INDEX changes_cursor ON changes (account, seq); CREATE TRIGGER record_insert AFTER INSERT ON records BEGIN INSERT INTO changes(account, id, version) VALUES(NEW.account, NEW.id, NEW.version); END; CREATE TRIGGER record_update AFTER UPDATE ON records BEGIN INSERT INTO changes(account, id, version) VALUES(NEW.account, NEW.id, NEW.version); END; INSERT INTO records VALUES ('fixture', 'files', 0, 1, X'0001ff'); """ def run_sql(command, db, sql, *, check=True): return subprocess.run([*command, db, sql], check=check, text=True, capture_output=True, timeout=20) def query(command, db, sql): return run_sql(command, db, sql).stdout.strip() def expect(actual, expected): if actual != expected: raise AssertionError(f"expected {expected!r}, got {actual!r}") def insert_records(first, last, size): return f""" WITH RECURSIVE ids(n) AS (VALUES({first}) UNION ALL SELECT n+1 FROM ids WHERE n<{last}) INSERT INTO records SELECT 'fixture', 'files', n, 1, zeroblob({size}) FROM ids; """ def send_and_wait(writer, sql): writer.stdin.write(sql + "\nSELECT 'ready';\n") writer.stdin.flush() with selectors.DefaultSelector() as selector: selector.register(writer.stdout, selectors.EVENT_READ) if not selector.select(timeout=20): raise AssertionError("writer did not reach the crash point") expect(writer.stdout.readline().strip(), "ready") def check_journal(command, directory, mode, suffix): db = directory / f"{mode}.db" with closing(sqlite3.connect(db)) as legacy: legacy.executescript(SCHEMA) expect(query(command, db, "SELECT hex(payload) FROM records WHERE id=0;"), "0001FF") expect(query(command, db, f"PRAGMA journal_mode={mode};").upper(), mode) query(command, db, f""" PRAGMA synchronous=FULL; BEGIN IMMEDIATE; {insert_records(1, 4000, 96)} INSERT INTO records SELECT account, collection, id, 2, X'00ff00' FROM records WHERE id BETWEEN 1 AND 64 ON CONFLICT (account, collection, id) DO UPDATE SET version=excluded.version, payload=excluded.payload; COMMIT; BEGIN IMMEDIATE; UPDATE records SET version=3 WHERE id=0; DELETE FROM records WHERE id=1; ROLLBACK; """) expect(query(command, db, """ SELECT group_concat(id || ':' || version, ',') FROM ( SELECT id, version FROM changes WHERE account='fixture' AND seq>4061 ORDER BY seq LIMIT 5 ); """), "61:2,62:2,63:2,64:2") expect(query(command, db, "SELECT version FROM records WHERE id IN (0,1) ORDER BY id;"), "1\n2") # The child commits one batch and then spills a second batch to disk before # it is killed with an open transaction. No clean SQLite close can run. with subprocess.Popen(["stdbuf", "-oL", *command, db], text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as writer: try: send_and_wait(writer, f""" .output /dev/null PRAGMA synchronous=FULL; PRAGMA wal_autocheckpoint=0; PRAGMA cache_size=8; PRAGMA cache_spill=ON; .output stdout BEGIN IMMEDIATE; {insert_records(4001, 4008, 256)} COMMIT; """) journal = Path(str(db) + suffix) committed_size = journal.stat().st_size if mode == "WAL" else 0 send_and_wait(writer, f""" BEGIN IMMEDIATE; UPDATE records SET version=4, payload=zeroblob(2048) WHERE id BETWEEN 0 AND 200; {insert_records(4009, 4256, 2048)} """) if journal.stat().st_size <= max(committed_size, 32): raise AssertionError(f"{mode} writer failed to spill uncommitted journal data") if mode == "WAL": expect(query(command, db, "SELECT count(*) FROM records;"), "4009") blocked = run_sql(command, db, "BEGIN IMMEDIATE; COMMIT;", check=False) if blocked.returncode == 0 or "database is locked" not in blocked.stderr: raise AssertionError(f"{mode} admitted a concurrent writer: {blocked}") finally: if writer.poll() is None: writer.kill() _, stderr = writer.communicate(timeout=10) if stderr: print(f"{mode} writer: {stderr.strip()}", file=sys.stderr) expect(writer.returncode, -signal.SIGKILL) # First recovery happens through the other SQLite build. It must see the # committed generation, then the fork must read a write from that build. with closing(sqlite3.connect(db)) as legacy, legacy: expect(legacy.execute("PRAGMA integrity_check").fetchall(), [("ok",)]) expect(legacy.execute("SELECT count(*), max(id) FROM records").fetchone(), (4009, 4008)) expect(legacy.execute("SELECT count(*) FROM changes").fetchone(), (4073,)) expect(legacy.execute("SELECT version, payload FROM records WHERE id=0").fetchone(), (1, b"\x00\x01\xff")) legacy.execute("UPDATE records SET payload=? WHERE id=0", (b"\xff\x00",)) expect(query(command, db, "SELECT hex(payload) FROM records WHERE id=0;"), "FF00") expect(query(command, db, "PRAGMA integrity_check;"), "ok") print(f"{mode}: 4,000 inserts, indexed cursor, upsert, rollback, locking, SIGKILL recovery") def main(): shell, manifest, build = map(Path, sys.argv[1:]) command = [shell.resolve(), "-batch", "-bail", "-init", "/dev/null"] source = query(command, ":memory:", "SELECT sqlite_source_id();") expect(source.split()[-1], manifest.read_text().strip()) expect(query(command, ":memory:", """ CREATE VIRTUAL TABLE search USING fts5(body); INSERT INTO search VALUES ('synthetic encrypted record metadata'); SELECT count(*) FROM search WHERE search MATCH 'metadata'; """), "1") with tempfile.TemporaryDirectory(prefix="compatibility-", dir=build) as directory: check_journal(command, Path(directory), "DELETE", "-journal") check_journal(command, Path(directory), "WAL", "-wal") print(f"SQLite {source} exchanged data with SQLite {sqlite3.sqlite_version}") if __name__ == "__main__": main()