#!/usr/bin/env python3 """Observe VACUUM horizons in a private disposable cluster; no external DSN.""" import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import queue import shlex import subprocess import tempfile import threading import time CASES = ("none", "repeatable_begin_only", "read_committed_read", "repeatable_read", "read_committed_xid") BLOCKING = {"repeatable_read", "read_committed_xid"} PHASES = ("inserted", "vacuum_with_holder", "holder_released", "vacuum_after_release") QUERY = "SELECT id FROM public.coverage ORDER BY id" SETTINGS = ("SET enable_seqscan=off; SET enable_bitmapscan=off; " "SET enable_indexscan=on; SET enable_indexonlyscan=on; " "SET max_parallel_workers_per_gather=0; SET jit=off; ") ENV = {k: v for k, v in os.environ.items() if not k.startswith("PG") and k not in {"LD_PRELOAD", "LD_LIBRARY_PATH"}} ENV.update(LC_ALL="C", LANG="C", PYTHONDONTWRITEBYTECODE="1") def require(condition, message): if not condition: raise ValueError(message) def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() class Holder: def __init__(self, args, transcript, case): self.events, self.case = transcript, case self.output = queue.Queue() self.errors = [] self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, env={**ENV, "PGAPPNAME": "hesela_horizon_holder"}) def read_stdout(): for line in self.proc.stdout: self.output.put(line.rstrip("\n")) self.output.put(None) def read_stderr(): self.errors.extend(self.proc.stderr.readlines()) self.readers = [threading.Thread(target=read_stdout, daemon=True), threading.Thread(target=read_stderr, daemon=True)] for reader in self.readers: reader.start() self.execute("") def execute(self, sql): marker = "HESELA_END_" + str(len(self.events)) self.proc.stdin.write(sql + "\n\\echo " + marker + "\n") self.proc.stdin.flush() lines = [] deadline = time.monotonic() + 15 while True: line = self.output.get(timeout=max(0.001, deadline - time.monotonic())) if line == marker: break if line is None: raise RuntimeError("Holder exited: " + "".join(self.errors)) lines.append(line) output = "\n".join(lines) self.events.append(dict(session="holder", case=self.case, sql=sql, stdout=output)) return output def close(self): if self.proc.poll() is None: try: self.proc.stdin.write("\\q\n") self.proc.stdin.flush() self.proc.wait(timeout=10) except (BrokenPipeError, subprocess.TimeoutExpired): self.proc.kill() self.proc.wait(timeout=10) for reader in self.readers: reader.join(timeout=2) for pipe in (self.proc.stdin, self.proc.stdout, self.proc.stderr): pipe.close() self.events.append(dict(session="holder_exit", case=self.case, returncode=self.proc.returncode, stderr="".join(self.errors).strip())) def verify(result): require(type(result.get("schemaVersion")) is int and result["schemaVersion"] == 1, "schema") require(result["probeSha256"] == digest(__file__), "runner hash") require([c["case"] for c in result["cases"]] == list(CASES), "case order") require(result["environment"]["autovacuum"] == "off", "autovacuum") for event in result["transcript"]: if "returncode" in event: require(type(event["returncode"]) is int and event["returncode"] == 0, "command failed") for case in result["cases"]: name = case["case"] holder = case["holder"] if name == "none": require(holder is None, "unexpected holder") else: require(holder["state"] == "idle in transaction", "holder not idle") require((holder["backend_xmin"] is not None) == (name == "repeatable_read"), "xmin scope") require((holder["backend_xid"] is not None) == (name == "read_committed_xid"), "xid scope") require("coverage" not in holder["relations"], "holder touched target") require([s["phase"] for s in case["stages"]] == list(PHASES), "phase order") for stage in case["stages"]: plan = stage["explain"][0]["Plan"] require(plan["Node Type"] == "Index Only Scan", "plan") require(plan["Relation Name"] == "coverage" and plan["Index Name"] == "coverage_pkey", "relation") require(type(plan["Actual Rows"]) is int and plan["Actual Rows"] == 256, "rows") require(type(plan["Actual Loops"]) is int and plan["Actual Loops"] == 1, "loops") require(stage["keys"] == list(range(1, 257)) and all(type(x) is int for x in stage["keys"]), "keys") require(stage["vmBefore"] == stage["vmAfter"], "VM drift") fetches = plan["Heap Fetches"] pages, visible = stage["heapPages"], stage["vmBefore"]["all_visible"] require(type(fetches) is int and fetches >= 0, "fetch type") require(type(pages) is int and pages > 0 and type(visible) is int, "page type") require(0 <= visible <= pages, "page bounds") blocked = stage["phase"] == "inserted" or ( name in BLOCKING and stage["phase"] in {"vacuum_with_holder", "holder_released"}) require((visible == 0 and fetches > 0) if blocked else (visible == pages and fetches == 0), "visibility transition") expected = None if name == "none" else (0 if name == "repeatable_read" else 256) require(case["holderLateCount"] == expected, "holder view") return True def run_probe(bindir, client): events = [] current_case = None def command(args, sql=None): proc = subprocess.run([str(x) for x in args], text=True, capture_output=True, timeout=60, env=ENV) event = dict(session="observer", case=current_case, program=Path(args[0]).name, returncode=proc.returncode, stdout=proc.stdout.strip(), stderr=proc.stderr.strip()) if sql is not None: event["sql"] = sql events.append(event) require(proc.returncode == 0, repr(event)) return event["stdout"] with tempfile.TemporaryDirectory(prefix="hesela-pg-horizon-") as tmp: root = Path(tmp) data, sock = root / "data", root / "socket" sock.mkdir(mode=0o700) conn = ["-h", str(sock), "-p", "55443", "-U", "hesela_lab", "-d", "postgres"] psql = [str(client / "psql"), "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", *conn] options = shlex.join(["-k", str(sock), "-p", "55443", "-h", "", "-c", "unix_socket_permissions=0700", "-c", "autovacuum=off", "-c", "shared_buffers=16MB", "-c", "max_connections=10", "-c", "statement_timeout=10000", "-c", "lock_timeout=5000", "-c", "idle_in_transaction_session_timeout=60000"]) command([bindir / "initdb", "-D", data, "--username=hesela_lab", "--auth-local=trust", "--auth-host=reject", "--no-locale", "-E", "UTF8", "--data-checksums"]) started = False holder = None try: command([bindir / "pg_ctl", "-D", data, "-l", root / "server.log", "-o", options, "-w", "start"]) started = True def sql(statement): return command([*psql, "-c", statement], sql=statement) def vm(): return json.loads(sql("SELECT row_to_json(v) FROM " "pg_visibility_map_summary('public.coverage') v;")) sql("CREATE EXTENSION pg_visibility; CREATE TABLE public.anchor(id int); " "INSERT INTO public.anchor VALUES (1);") environment = json.loads(sql("SELECT json_build_object('version',version()," "'server_version_num',current_setting('server_version_num')," "'block_size',current_setting('block_size')," "'data_checksums',current_setting('data_checksums')," "'autovacuum',current_setting('autovacuum'));")) cases = [] for name in CASES: current_case = name sql("CREATE TABLE public.coverage(id integer PRIMARY KEY, payload text NOT NULL) " "WITH (fillfactor=70);") if name != "none": holder = Holder(psql, events, name) isolation = "REPEATABLE READ" if name.startswith("repeatable") else "READ COMMITTED" holder.execute("BEGIN ISOLATION LEVEL " + isolation + ";") if name in {"repeatable_read", "read_committed_read"}: require(holder.execute("SELECT count(*) FROM public.anchor;") == "1", "anchor") elif name == "read_committed_xid": holder.execute("SELECT pg_current_xact_id();") holder_state = None if holder: for attempt in range(50): holder_state = json.loads(sql("SELECT row_to_json(s) FROM (" "SELECT state, backend_xid::text, backend_xmin::text, " "ARRAY(SELECT DISTINCT c.relname FROM pg_locks l JOIN pg_class c " "ON c.oid=l.relation JOIN pg_namespace n ON n.oid=c.relnamespace " "WHERE l.pid=a.pid AND n.nspname='public' ORDER BY c.relname) AS relations " "FROM pg_stat_activity a WHERE application_name='hesela_horizon_holder') s;")) if holder_state["state"] == "idle in transaction": break time.sleep(0.02) require(holder_state["state"] == "idle in transaction", "holder readiness") sql("INSERT INTO public.coverage SELECT i, repeat('x',64) FROM generate_series(1,256) i;") stages = [] late_count = None for phase in PHASES: if phase.startswith("vacuum_"): sql("VACUUM (ANALYZE, VERBOSE) public.coverage;") elif phase == "holder_released" and holder: late_count = int(holder.execute("SELECT count(*) FROM public.coverage;")) holder.execute("COMMIT;") holder.close() holder = None before = vm() plan = json.loads(sql(SETTINGS + "EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, FORMAT JSON) " + QUERY + ";")) after = vm() keys = [int(x) for x in sql(SETTINGS + QUERY + ";").splitlines()] pages = int(sql("SELECT pg_relation_size('public.coverage') / " "current_setting('block_size')::integer;")) stages.append(dict(phase=phase, vmBefore=before, vmAfter=after, explain=plan, keys=keys, heapPages=pages)) cases.append(dict(case=name, holder=holder_state, holderLateCount=late_count, stages=stages)) sql("DROP TABLE public.coverage;") result = dict(schemaVersion=1, generatedAt=datetime.now(timezone.utc).isoformat(), platform=platform.platform(), environment=environment, cases=cases, query=QUERY, plannerSettings=SETTINGS, probeSha256=digest(__file__), binarySha256={n: digest(p) for n, p in ( ("postgres", bindir / "postgres"), ("initdb", bindir / "initdb"), ("pg_ctl", bindir / "pg_ctl"), ("psql", client / "psql"))}, transcript=events) finally: if holder: holder.close() if started: command([bindir / "pg_ctl", "-D", data, "-m", "fast", "-w", "stop"]) verify(result) return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--bindir", type=Path, default=Path("/usr/lib/postgresql/16/bin")) parser.add_argument("--client-bin", type=Path, default=Path("/usr/lib/postgresql/16/bin")) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() require(not args.output.exists(), "Refusing to overwrite a record") result = run_probe(args.bindir.resolve(), args.client_bin.resolve()) with args.output.open("x") as stream: json.dump(result, stream, indent=2) stream.write("\n") print(json.dumps([dict(case=c["case"], xmin=c["holder"] and c["holder"]["backend_xmin"], xid=c["holder"] and c["holder"]["backend_xid"], visible=[s["vmBefore"]["all_visible"] for s in c["stages"]], pages=[s["heapPages"] for s in c["stages"]], fetches=[s["explain"][0]["Plan"]["Heap Fetches"] for s in c["stages"]]) for c in result["cases"]])) if __name__ == "__main__": main()