#!/usr/bin/env python3 """Check internal consistency and the recorded protocol, without running SQL.""" import argparse import json from pathlib import Path from probe import CASES, PHASES, QUERY, SETTINGS, require, verify def check(record): verify(record) events = record["transcript"] require(record["query"] == QUERY and record["plannerSettings"] == SETTINGS, "query metadata") for event in events: require(event.get("session") in {"observer", "holder", "holder_exit"}, "session") require(event.get("case") in {None, *CASES}, "event case") if event["session"] in {"observer", "holder_exit"}: require(type(event.get("returncode")) is int and event["returncode"] == 0, "missing or failed command status") if event["session"] == "observer": require(event.get("program") in {"initdb", "pg_ctl", "psql"}, "program") environment = [e for e in events if e.get("sql", "").startswith( "SELECT json_build_object('version',version(),")] require(len(environment) == 1 and json.loads(environment[0]["stdout"]) == record["environment"], "environment binding") programs = [e["program"] for e in events if "program" in e] require(programs[0:2] == ["initdb", "pg_ctl"] and programs[-1] == "pg_ctl", "lifecycle") require(programs.count("initdb") == 1 and programs.count("pg_ctl") == 2, "lifecycle count") for case in record["cases"]: name = case["case"] trace = [e for e in events if e.get("case") == name] sql_events = [e for e in trace if e.get("program") == "psql"] position = {id(e): i for i, e in enumerate(trace)} holders = [e for e in trace if e["session"] == "holder"] exits = [e for e in trace if e["session"] == "holder_exit"] if name == "none": require(not holders and not exits, "no-holder control") else: isolation = "REPEATABLE READ" if name.startswith("repeatable") else "READ COMMITTED" expected = ["", "BEGIN ISOLATION LEVEL " + isolation + ";"] if name in {"repeatable_read", "read_committed_read"}: expected += ["SELECT count(*) FROM public.anchor;"] elif name == "read_committed_xid": expected += ["SELECT pg_current_xact_id();"] expected += ["SELECT count(*) FROM public.coverage;", "COMMIT;"] require([e["sql"] for e in holders] == expected, "holder SQL protocol") require(len(exits) == 1 and exits[0]["returncode"] == 0, "holder exit") require(type(case["holderLateCount"]) is int, "holder count type") require(int(holders[-2]["stdout"]) == case["holderLateCount"], "holder count binding") plans = [e for e in sql_events if "EXPLAIN (ANALYZE" in e["sql"]] maps = [e for e in sql_events if "pg_visibility_map_summary" in e["sql"]] keys = [e for e in sql_events if e["sql"] == SETTINGS + QUERY + ";"] pages = [e for e in sql_events if e["sql"].startswith("SELECT pg_relation_size")] vacuums = [e for e in sql_events if e["sql"].startswith("VACUUM")] statuses = [e for e in sql_events if "pg_stat_activity a" in e["sql"]] require(len(plans) == len(keys) == len(pages) == 4 and len(maps) == 8, "capture coverage") require(len(vacuums) == 2, "VACUUM count") vm_sql = ("SELECT row_to_json(v) FROM " "pg_visibility_map_summary('public.coverage') v;") page_sql = ("SELECT pg_relation_size('public.coverage') / " "current_setting('block_size')::integer;") create_sql = ("CREATE TABLE public.coverage(id integer PRIMARY KEY, payload text NOT NULL) " "WITH (fillfactor=70);") insert_sql = ("INSERT INTO public.coverage SELECT i, repeat('x',64) " "FROM generate_series(1,256) i;") vacuum_sql = "VACUUM (ANALYZE, VERBOSE) public.coverage;" stage_sql = [vm_sql, SETTINGS + "EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, FORMAT JSON) " + QUERY + ";", vm_sql, SETTINGS + QUERY + ";", page_sql] expected_sql = [create_sql, insert_sql, *stage_sql, vacuum_sql, *stage_sql, *stage_sql, vacuum_sql, *stage_sql, "DROP TABLE public.coverage;"] require([e["sql"] for e in sql_events if e not in statuses] == expected_sql, "observer SQL protocol") insertion = next(e for e in sql_events if e["sql"] == insert_sql) if holders: require(position[id(holders[-3])] < position[id(insertion)], "holder setup order") require(all(position[id(holders[-3])] < position[id(e)] < position[id(insertion)] for e in statuses), "holder status order") if name != "none": require(statuses and json.loads(statuses[-1]["stdout"]) == case["holder"], "holder binding") expected_relations = ["anchor"] if name in {"repeatable_read", "read_committed_read"} else [] require(case["holder"]["relations"] == expected_relations, "initial relation locks") else: require(not statuses, "unexpected holder status") for i, stage in enumerate(case["stages"]): require(plans[i]["sql"] == SETTINGS + "EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, FORMAT JSON) " + QUERY + ";", "query") require(json.loads(plans[i]["stdout"]) == stage["explain"], "plan binding") require(json.loads(maps[2*i]["stdout"]) == stage["vmBefore"], "before binding") require(json.loads(maps[2*i+1]["stdout"]) == stage["vmAfter"], "after binding") require([int(k) for k in keys[i]["stdout"].splitlines()] == stage["keys"], "key binding") require(int(pages[i]["stdout"]) == stage["heapPages"], "page binding") indices = [position[id(e)] for e in (maps[2*i], plans[i], maps[2*i+1], keys[i], pages[i])] require(indices == sorted(indices) and len(set(indices)) == 5, "capture order") # Position checks use identity because repeated SQL outputs can be equal. position = {id(e): i for i, e in enumerate(trace)} require(position[id(plans[0])] < position[id(vacuums[0])] < position[id(plans[1])], "first VACUUM order") require(position[id(plans[2])] < position[id(vacuums[1])] < position[id(plans[3])], "second VACUUM order") if holders: require(position[id(plans[1])] < position[id(holders[-2])] < position[id(holders[-1])] < position[id(exits[0])] < position[id(plans[2])], "release order") return True def summary(record): check(record) return [dict(case=c["case"], holderXmin=c["holder"] and c["holder"]["backend_xmin"], holderXid=c["holder"] and c["holder"]["backend_xid"], holderLateCount=c["holderLateCount"], stages=[ dict(phase=s["phase"], allVisible=s["vmBefore"]["all_visible"], heapPages=s["heapPages"], heapFetches=s["explain"][0]["Plan"]["Heap Fetches"]) for s in c["stages"]]) for c in record["cases"]] if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("records", nargs="+", type=Path) args = parser.parse_args() for path in args.records: result = summary(json.loads(path.read_text())) print(json.dumps(dict(file=path.name, cases=result)))