"""Actual SQLite on owned temporary files, two connections, controlled interleavings.""" import argparse import json import os import platform import sqlite3 import tempfile from pathlib import Path def query(conn, sql, params=(), fetch=False): cur = conn.execute(sql, params) try: rows = cur.fetchall() if fetch else None return rows if fetch else cur.rowcount finally: cur.close() def observe(c, events, rule): parent = Path(tempfile.gettempdir()).resolve() handle, name = tempfile.mkstemp(prefix='ct-free-stock-', suffix='.sqlite3', dir=parent) os.close(handle) path = Path(name).resolve() assert path.parent == parent and path.name.startswith('ct-free-stock-') conns = {} result = None try: conns['A'] = sqlite3.connect(path, autocommit=True) conns['B'] = sqlite3.connect(path, autocommit=True) query(conns['A'], 'CREATE TABLE stock(id INTEGER PRIMARY KEY, available INTEGER NOT NULL CHECK(available>=0))') query(conns['A'], 'INSERT INTO stock VALUES(1, ?)', (c['initial'],)) reads, confirmed, quantities, frames = dict(A=None, B=None), dict(A=None, B=None), dict(A=c['a'], B=c['b']), [] current = lambda: query(conns['A'], 'SELECT available FROM stock WHERE id=1', fetch=True)[0][0] for event in events: actor, operation = event[0], 'read' if event[1] == 'R' else 'confirm' before = current() decision, affected = None, None if operation == 'read': reads[actor] = query(conns[actor], 'SELECT available FROM stock WHERE id=1', fetch=True)[0][0] else: qty = quantities[actor] if rule == 'snapshot': affected = query(conns[actor], 'UPDATE stock SET available=? WHERE id=1', (reads[actor]-qty,)) if reads[actor] >= qty else 0 else: affected = query(conns[actor], 'UPDATE stock SET available=available-? WHERE id=1 AND available>=?', (qty, qty)) confirmed[actor] = affected == 1 decision = 'accepted' if confirmed[actor] else 'rejected' available = current() units = sum(quantities[a] for a in confirmed if confirmed[a]) frames.append(dict(step=len(frames)+1, event=event, actor=actor, operation=operation, requested=quantities[actor], seen=reads[actor], available_before=before, available_after=available, decision=decision, affected=affected, reads=dict(reads), confirmed=dict(confirmed), confirmed_units=units)) assert not any(conn.in_transaction for conn in conns.values()) excess = max(0, units-c['initial']) difference = available+units-c['initial'] outcome = 'over' if excess else 'mismatch' if difference else 'consistent' result = dict(initial=c['initial'], a=c['a'], b=c['b'], rule=rule, events=events, frames=frames, available=available, confirmed=confirmed, confirmed_units=units, excess=excess, difference=difference, outcome=outcome) finally: for conn in conns.values(): conn.close() # Only exact owned files, no recursive directory deletion. owned = [path] + [path.with_name(path.name + suffix) for suffix in ['-journal', '-wal', '-shm']] for candidate in owned: assert candidate.parent == parent and candidate.name.startswith(path.name) candidate.unlink(missing_ok=True) assert not any(candidate.exists() for candidate in owned) return dict(result=result, temporary_files_removed=True) def main(): parser = argparse.ArgumentParser() parser.add_argument('--check', type=Path) args = parser.parse_args() cfg = json.loads(Path(__file__).with_name('cases.json').read_text(encoding='utf-8')) records = [] for c in cfg['cases']: for order in cfg['orders']: for rule in ['snapshot', 'guard']: records.append(dict(configuration=dict(case=c['id'], order=order['id'], rule=rule), **observe(c, order['events'], rule))) transfer = [dict(configuration=t, **observe(t['case'], t['events'], t['rule'])) for t in cfg['transfer']] output = dict(python_version=platform.python_version(), sqlite_version=sqlite3.sqlite_version, method='Actual SQL queries and updates through two connections to a new temporary SQLite file per configuration, autocommit=True, controlled serial statement interleavings; no threads/parallel write benchmark. Owned temporary files removed after each case.', main=records, transfer=transfer) data = (json.dumps(output, ensure_ascii=False, indent=2) + '\n').encode('utf-8') if args.check: if args.check.read_bytes() != data: raise SystemExit('Different bytes') print('Identical bytes') else: import sys sys.stdout.buffer.write(data) if __name__ == '__main__': main()