"""Observa o planner em dois clusters PostgreSQL 17 descartáveis, sem conexões TCP.""" import argparse from contextlib import contextmanager from datetime import datetime, timezone import json import os from pathlib import Path import signal import subprocess import tempfile import time HERE = Path(__file__).resolve().parent ROLE = "sample006" PORT = "5432" # Identifica o socket no diretório privado. O postmaster não escuta TCP. EXPECTED = {"rare": (20, 210000), "common": (19980, 199800000)} PHASES = [ ("before_index", None), ("after_index", "CREATE INDEX events_kind_idx ON events USING btree (kind)"), ("after_analyze", "ANALYZE events"), ] class Cluster: def __init__(self, bin_dir, root): self.bin = bin_dir self.data = root / "data" self.socket = root / "socket" self.socket.mkdir(mode=0o700) self.log = root / "postgres.log" self.env = {k: v for k, v in os.environ.items() if not k.startswith("PG")} self.process = None def execute(self, name, args, **kwargs): return subprocess.run([self.bin / name, *args], env=self.env, check=True, capture_output=True, text=True, timeout=30, **kwargs).stdout.strip() def sql(self, query): return self.execute("psql", ["-X", "-w", "-qAt", "-v", "ON_ERROR_STOP=1", "-h", self.socket, "-p", PORT, "-U", ROLE, "-d", "postgres"], input=query) def query_json(self, query): return json.loads(self.sql(query)) def start(self): self.execute("initdb", ["--no-locale", "--encoding=UTF8", "--auth-local=trust", "--auth-host=reject", "-U", ROLE, "-D", self.data]) with self.log.open("wb") as log: self.process = subprocess.Popen( [self.bin / "postgres", "-D", self.data, "-k", self.socket, "-p", PORT, "-c", "listen_addresses=", "-c", "unix_socket_permissions=0700"], env=self.env, stdout=log, stderr=subprocess.STDOUT) deadline = time.monotonic() + 15 while time.monotonic() < deadline: if self.process.poll() is not None: raise RuntimeError(self.log.read_text()[-2000:]) try: if self.sql("SELECT 1") == "1": return except subprocess.CalledProcessError: time.sleep(0.05) raise TimeoutError("O cluster temporário não ficou pronto") def stop(self): process = self.process if process is None or process.poll() is not None: return process.send_signal(signal.SIGINT) # Fast shutdown: fecha também backends ativos. try: process.wait(10) except subprocess.TimeoutExpired: process.send_signal(signal.SIGQUIT) try: process.wait(10) except subprocess.TimeoutExpired: process.kill() process.wait() if process.returncode: raise RuntimeError(f"Falha ao encerrar postmaster: {process.returncode}") def snapshot(db): return db.query_json(""" SELECT json_build_object( 'stats_present', EXISTS (SELECT 1 FROM pg_stats WHERE schemaname='public' AND tablename='events' AND attname='kind'), 'btree_present', to_regclass('public.events_kind_idx') IS NOT NULL, 'frequencies', (SELECT row_to_json(s) FROM ( SELECT most_common_vals::text AS values, most_common_freqs::text AS frequencies FROM pg_stats WHERE schemaname='public' AND tablename='events' AND attname='kind' ) s) )""") def observe(db, value): # Os únicos valores aceitos nas consultas são constantes do fixture. if value not in EXPECTED: raise ValueError(value) query = f"SELECT id, detail FROM events WHERE kind = '{value}'" plan = db.query_json("EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, FORMAT JSON) " + query)[0] rows, checksum = json.loads(db.sql( "SELECT json_build_array(count(*), sum(id)) FROM (" + query + ") AS selected")) if (rows, checksum) != EXPECTED[value] or plan["Plan"]["Actual Rows"] != rows: raise AssertionError("Cardinalidade ou soma de IDs incorreta") return {"predicate":value, "query":query, "rows":rows, "sum_ids":checksum, "explain":plan} def sample(db): identity = db.query_json(""" SELECT json_build_object( 'data', current_setting('data_directory'), 'socket', current_setting('unix_socket_directories'), 'listen_addresses', current_setting('listen_addresses'), 'unix_client', inet_client_addr() IS NULL, 'system_id', system_identifier::text, 'version', current_setting('server_version'), 'version_num', current_setting('server_version_num')::int, 'empty_fixture', to_regclass('public.events') IS NULL ) FROM pg_control_system()""") if not (Path(identity.pop("data")).samefile(db.data) and Path(identity.pop("socket")).samefile(db.socket) and identity["listen_addresses"] == "" and identity["unix_client"] and identity["empty_fixture"] and identity["version_num"] // 10000 == 17): raise RuntimeError("Identidade do cluster temporário não conferida") settings = db.query_json(""" SELECT json_object_agg(name,setting) FROM pg_settings WHERE name IN ('enable_seqscan','enable_indexscan','enable_bitmapscan','enable_indexonlyscan', 'default_statistics_target','random_page_cost','seq_page_cost','shared_buffers','block_size', 'max_parallel_workers_per_gather')""") if any(v != "on" for k,v in settings.items() if k.startswith("enable_")): raise RuntimeError("Método de scan desabilitado") db.sql((HERE / "fixture.sql").read_text()) phases = [] for name, statement in PHASES: if statement: db.sql(statement) state = snapshot(db) if (state["btree_present"], state["stats_present"]) != (name != "before_index", name == "after_analyze"): raise AssertionError(f"Estado inesperado na fase {name}") phases.append({"phase":name, "catalog":state, "queries":[observe(db, value) for value in ("common","rare")]}) return {"cluster":identity, "settings":settings, "phases":phases} @contextmanager def isolated_cluster(binaries): # /tmp mantém o caminho do socket curto, inclusive em macOS. with tempfile.TemporaryDirectory(dir="/tmp", prefix="kv-pg006-") as directory: base = Path(directory) db = Cluster(binaries, base) try: db.start() yield db finally: db.stop() if (db.socket / (".s.PGSQL."+PORT)).exists() or (db.data / "postmaster.pid").exists(): raise RuntimeError("O socket ou PID temporário permaneceu ativo") def one_run(binaries): with isolated_cluster(binaries) as db: result = sample(db) if db.data.parent.exists(): raise RuntimeError("Cluster temporário não removido") result["cleanup"] = {"postmaster_stopped": True, "private_directory_removed": True} return result def plan_shape(node): return [node["Node Type"],node.get("Index Name"),node["Plan Rows"],node["Actual Rows"], [plan_shape(child) for child in node.get("Plans", [])]] def failure_probe(binaries): # Exercita o mesmo finally quando uma consulta do laboratório falha. with_error = False try: with isolated_cluster(binaries) as db: db.sql("SELECT 1/0") except subprocess.CalledProcessError as error: if "division by zero" not in error.stderr: raise with_error = True if not with_error or db.data.parent.exists() or db.process.poll() is None: raise RuntimeError("O teste de limpeza após erro falhou") return {"error":"division by zero", "postmaster_stopped":True, "private_directory_removed":True} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--bin-dir", type=Path, default=Path("/opt/homebrew/opt/postgresql@17/bin")) args = parser.parse_args() runs = [one_run(args.bin_dir.resolve()) for _ in range(2)] signatures = [[plan_shape(q["explain"]["Plan"]) for p in run["phases"] for q in p["queries"]] for run in runs] if runs[0]["cluster"]["system_id"] == runs[1]["cluster"]["system_id"] or signatures[0] != signatures[1]: raise AssertionError("Os clusters ou a repetição do plano exigem investigação") result = {"tested_utc":datetime.now(timezone.utc).isoformat(timespec="seconds"), "fixture_rows":20000, "same_plan_shapes_and_cardinalities":True, "error_cleanup_probe":failure_probe(args.bin_dir.resolve()), "runs":runs} with tempfile.NamedTemporaryFile("w", dir=HERE, suffix=".tmp", delete=False) as out: json.dump(result, out, ensure_ascii=False, indent=2) out.write("\n") Path(out.name).replace(HERE / "evidence.json") for phase in runs[0]["phases"]: for query in phase["queries"]: p = query["explain"]["Plan"] print(phase["phase"], query["predicate"], p["Node Type"], p["Plan Rows"], p["Actual Rows"], p["Shared Hit Blocks"], p["Shared Read Blocks"]) if __name__ == "__main__": main()