#!/usr/bin/env python3 """Linux C-API experiment using only private temporary databases. CC0-1.0.""" import argparse import ctypes as C import datetime import hashlib import itertools import json import os from pathlib import Path import platform import select import signal import subprocess import sys import tempfile HERE = Path(__file__).resolve().parent RDONLY, NOTLS, MAP_FULL = 0x20000, 0x200000, -30792 MODES = ("live", "reset_live", "clean_exit", "killed_reaped", "killed_unreaped") VALUE_BYTES = 16384 FOLLOWUP = 64 def require(condition, message): if not condition: raise ValueError(message) def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def payload(key, generation): token = f"key={key};generation={generation};".encode("ascii") return (token * (VALUE_BYTES // len(token) + 1))[:VALUE_BYTES] class Val(C.Structure): _fields_ = [("size", C.c_size_t), ("data", C.c_void_p)] class Info(C.Structure): _fields_ = [("mapaddr", C.c_void_p), ("mapsize", C.c_size_t), ("last_pgno", C.c_size_t), ("last_txnid", C.c_size_t), ("maxreaders", C.c_uint), ("numreaders", C.c_uint)] class Stat(C.Structure): _fields_ = [("psize", C.c_uint), ("depth", C.c_uint), ("branch", C.c_size_t), ("leaf", C.c_size_t), ("overflow", C.c_size_t), ("entries", C.c_size_t)] CALLBACK = C.CFUNCTYPE(C.c_int, C.c_char_p, C.c_void_p) class DB: def __init__(self, library, path, map_bytes): self.lib = C.CDLL(str(library)) p, pp, ui = C.c_void_p, C.POINTER(C.c_void_p), C.c_uint specs = { "mdb_env_create": ([pp], C.c_int), "mdb_env_set_mapsize": ([p, C.c_size_t], C.c_int), "mdb_env_set_maxreaders": ([p, ui], C.c_int), "mdb_env_open": ([p, C.c_char_p, ui, ui], C.c_int), "mdb_env_close": ([p], None), "mdb_txn_begin": ([p, p, ui, pp], C.c_int), "mdb_txn_abort": ([p], None), "mdb_txn_reset": ([p], None), "mdb_txn_commit": ([p], C.c_int), "mdb_dbi_open": ([p, C.c_char_p, ui, C.POINTER(ui)], C.c_int), "mdb_put": ([p, ui, C.POINTER(Val), C.POINTER(Val), ui], C.c_int), "mdb_get": ([p, ui, C.POINTER(Val), C.POINTER(Val)], C.c_int), "mdb_stat": ([p, ui, C.POINTER(Stat)], C.c_int), "mdb_env_info": ([p, C.POINTER(Info)], C.c_int), "mdb_env_stat": ([p, C.POINTER(Stat)], C.c_int), "mdb_reader_check": ([p, C.POINTER(C.c_int)], C.c_int), "mdb_reader_list": ([p, CALLBACK, p], C.c_int), "mdb_version": ([C.POINTER(C.c_int)] * 3, C.c_char_p), } for name, (args, result) in specs.items(): fn = getattr(self.lib, name) fn.argtypes, fn.restype = args, result self.env = p() self.ok(self.lib.mdb_env_create(C.byref(self.env))) self.ok(self.lib.mdb_env_set_mapsize(self.env, map_bytes)) self.ok(self.lib.mdb_env_set_maxreaders(self.env, 16)) self.ok(self.lib.mdb_env_open(self.env, os.fsencode(path), NOTLS, 0o600)) txn = self.begin(True) self.dbi = ui() try: self.ok(self.lib.mdb_dbi_open(txn, None, 0, C.byref(self.dbi))) finally: self.lib.mdb_txn_abort(txn) @staticmethod def ok(rc): require(rc == 0, f"unexpected LMDB status {rc}") def begin(self, readonly=False): txn = C.c_void_p() self.ok(self.lib.mdb_txn_begin(self.env, None, RDONLY if readonly else 0, C.byref(txn))) return txn def put(self, txn, key, generation): kb = C.create_string_buffer(f"key-{key}".encode()) vb = C.create_string_buffer(payload(key, generation)) k = Val(len(kb.value), C.cast(kb, C.c_void_p)) v = Val(VALUE_BYTES, C.cast(vb, C.c_void_p)) return self.lib.mdb_put(txn, self.dbi, C.byref(k), C.byref(v), 0) def write(self, key, generation): txn = self.begin() rc = self.put(txn, key, generation) if rc: self.lib.mdb_txn_abort(txn) return rc return self.lib.mdb_txn_commit(txn) def seed(self): txn = self.begin() try: for key in range(8): self.ok(self.put(txn, key, 0)) except BaseException: self.lib.mdb_txn_abort(txn) raise self.ok(self.lib.mdb_txn_commit(txn)) def verify(self, expected, txn=None): own = txn is None txn = self.begin(True) if own else txn digest = hashlib.sha256() try: stat = Stat() self.ok(self.lib.mdb_stat(txn, self.dbi, C.byref(stat))) require(stat.entries == 8, "key count changed") for key, generation in enumerate(expected): kb = C.create_string_buffer(f"key-{key}".encode()) k, v = Val(len(kb.value), C.cast(kb, C.c_void_p)), Val() self.ok(self.lib.mdb_get(txn, self.dbi, C.byref(k), C.byref(v))) require(v.size == VALUE_BYTES, "value length changed") actual = C.string_at(v.data, v.size) require(actual == payload(key, generation), "payload bytes changed") digest.update(actual) return digest.hexdigest() finally: if own: self.lib.mdb_txn_abort(txn) def state(self, child_pid): info, stat = Info(), Stat() self.ok(self.lib.mdb_env_info(self.env, C.byref(info))) self.ok(self.lib.mdb_env_stat(self.env, C.byref(stat))) lines = [] @CALLBACK def collect(message, _): lines.append(message.decode()) return 0 self.ok(self.lib.mdb_reader_list(self.env, collect, None)) slots = [] for line in lines: fields = line.split() if len(fields) == 3 and fields[0].isdigit(): pid = int(fields[0]) require(pid in (child_pid, os.getpid()), "unexpected reader owner") slots.append({"owner": "child" if pid == child_pid else "parent", "txnid": None if fields[2] == "-" else int(fields[2])}) return {"slots": slots, "reader_high_water": info.numreaders, "extent_bytes": (info.last_pgno + 1) * stat.psize, "page_bytes": stat.psize, "map_bytes": info.mapsize, "last_txnid": info.last_txnid} def check(self): dead = C.c_int(-1) rc = self.lib.mdb_reader_check(self.env, C.byref(dead)) self.ok(rc) return {"rc": rc, "cleared_slots": dead.value} def close(self): if self.env: self.lib.mdb_env_close(self.env) self.env = None def reply(value): print(json.dumps(value), flush=True) def worker(library, path, map_bytes, readers): signal.signal(signal.SIGALRM, lambda *_: os._exit(124)) signal.alarm(60) db = DB(library, path, map_bytes) txns = [db.begin(True) for _ in range(readers)] try: reply({"ready": True, "digests": [db.verify([0] * 8, t) for t in txns]}) for line in sys.stdin: command = json.loads(line) if command == "verify": reply({"digests": [db.verify([0] * 8, t) for t in txns]}) elif command == "reset": for txn in txns: db.lib.mdb_txn_reset(txn) reply({"reset": len(txns)}) elif command == "exit": for txn in txns: db.lib.mdb_txn_abort(txn) txns.clear() db.close() reply({"closed": True}) return else: raise ValueError("unknown worker command") finally: for txn in txns: db.lib.mdb_txn_abort(txn) db.close() def receive(proc): ready, _, _ = select.select([proc.stdout], [], [], 20) require(bool(ready), "worker handshake timed out") line = proc.stdout.readline() require(bool(line), "worker exited without a reply") return json.loads(line) def exchange(proc, command): proc.stdin.write(json.dumps(command) + "\n") proc.stdin.flush() return receive(proc) def process_present(pid): try: os.kill(pid, 0) return True except ProcessLookupError: return False def run_case(library, mode, map_bytes, readers, repetition, directory): path = Path(directory) / "db" path.mkdir() db = DB(library, path, map_bytes) proc = None try: db.seed() proc = subprocess.Popen( [sys.executable, "-B", str(Path(__file__).resolve()), "--worker", str(library), str(path), str(map_bytes), str(readers)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1) ready = receive(proc) require(ready.get("ready") is True, "reader not ready") expected = [0] * 8 committed = 0 def update(): nonlocal committed key = committed % 8 rc = db.write(key, committed + 1) if rc == 0: expected[key] = committed + 1 committed += 1 return rc for _ in range(256): pressure_rc = update() if pressure_rc: break require(pressure_rc == MAP_FULL, "fixture did not exhaust map") pressure_commits = committed old = exchange(proc, "verify") require(old["digests"] == ready["digests"], "old snapshots changed") before_action = db.state(proc.pid) wait_receipt = None if mode == "reset_live": require(exchange(proc, "reset") == {"reset": readers}, "reset failed") elif mode == "clean_exit": require(exchange(proc, "exit") == {"closed": True}, "close failed") require(proc.wait(timeout=20) == 0, "clean child failed") elif mode.startswith("killed"): proc.send_signal(signal.SIGKILL) if mode == "killed_unreaped": # Observe termination without reaping; never call poll here. receipt = os.waitid(os.P_PID, proc.pid, os.WEXITED | os.WNOWAIT) require(receipt.si_code == os.CLD_KILLED and receipt.si_status == signal.SIGKILL, "unexpected child exit") wait_receipt = {"code": "CLD_KILLED", "signal": "SIGKILL", "reaped_before_check": False} else: require(proc.wait(timeout=20) == -signal.SIGKILL, "kill not observed") wait_receipt = {"code": "CLD_KILLED", "signal": "SIGKILL", "reaped_before_check": True} present = process_present(proc.pid) after_action = db.state(proc.pid) before_check_rc = update() before_check = db.state(proc.pid) cleanup = db.check() after_check = db.state(proc.pid) after_check_rc = update() if mode == "live": require(exchange(proc, "verify")["digests"] == ready["digests"], "cleanup damaged live snapshot") if mode in ("live", "reset_live"): require(exchange(proc, "exit") == {"closed": True}, "close failed") require(proc.wait(timeout=20) == 0, "child cleanup failed") elif mode == "killed_unreaped": require(proc.wait(timeout=20) == -signal.SIGKILL, "reap failed") followup = [] for _ in range(FOLLOWUP): followup.append(update()) require(all(rc == 0 for rc in followup), "writes did not resume") final_state = db.state(proc.pid) final_digest = db.verify(expected) db.close() db = DB(library, path, map_bytes) reopened_digest = db.verify(expected) require(reopened_digest == final_digest, "reopen changed values") db.close() stderr = proc.stderr.read() require(not stderr, "worker emitted stderr: " + stderr) return {"mode": mode, "map_bytes": map_bytes, "readers": readers, "repetition": repetition, "pressure_commits": pressure_commits, "pressure_rc": pressure_rc, "before_action": before_action, "old_digests": old["digests"], "after_action": after_action, "pid_present_after_action": present, "wait": wait_receipt, "before_check_rc": before_check_rc, "before_check": before_check, "cleanup": cleanup, "after_check": after_check, "after_check_rc": after_check_rc, "followup_rcs": followup, "final_state": final_state, "final_generations": expected, "total_commits": committed, "final_digest": final_digest, "reopened_digest": reopened_digest, "database_sha256": sha(path / "data.mdb")} finally: if proc is not None: if proc.poll() is None: proc.kill() proc.wait(timeout=20) for stream in (proc.stdin, proc.stdout, proc.stderr): stream.close() db.close() def build(source, destination): lock = json.loads((HERE / "source-lock.json").read_text()) for name, digest in lock["files"].items(): require(sha(source / name) == digest, "source hash mismatch: " + name) library = destination / "liblmdb.so" command = ["cc", "-std=c11", "-O2", "-fPIC", "-shared", "-pthread", "-I", str(source), str(source / "mdb.c"), str(source / "midl.c"), "-o", str(library)] subprocess.run(command, check=True, capture_output=True, text=True, timeout=60) return library, lock def main(): if len(sys.argv) > 1 and sys.argv[1] == "--worker": worker(Path(sys.argv[2]), Path(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5])) return parser = argparse.ArgumentParser() parser.add_argument("--lmdb", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() require(platform.system() == "Linux", "Linux is required") require(not args.output.exists(), "output already exists") rows = [] with tempfile.TemporaryDirectory(prefix="hesela-lmdb-dead-") as temp: base = Path(temp) library, lock = build(args.lmdb.resolve(), base) for mode, size, readers, repetition in itertools.product( MODES, (1048576, 2097152), (1, 3), (1, 2)): with tempfile.TemporaryDirectory(dir=base) as directory: rows.append(run_case(library, mode, size, readers, repetition, directory)) result = {"schema_version": 1, "generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "source": lock, "runner_sha256": sha(__file__), "environment": {"platform": platform.platform(), "python": platform.python_version(), "compiler": subprocess.check_output( ["cc", "--version"], text=True).splitlines()[0], "temp_filesystem": subprocess.check_output( ["stat", "-f", "-c", "%T", temp], text=True).strip(), "flags": ["MDB_NOTLS"], "build_flags": ["-std=c11", "-O2", "-fPIC", "-shared", "-pthread"]}, "cases": rows} from validate import validate validate(result) with args.output.open("x") as output: json.dump(result, output, indent=2) output.write("\n") print(f"Validated {len(rows)} native cases: {args.output}") if __name__ == "__main__": main()