"""Run pg_archivecleanup only in dry-run mode against disposable synthetic files.""" import argparse import hashlib import json import os import platform import subprocess import tempfile from datetime import datetime, timezone from pathlib import Path CUTOFF = "000000020000000000000010" LOW = [f"{timeline:08X}000000000000000F" for timeline in (1, 2, 3)] FILES = [f"{timeline:08X}00000000{segment:08X}" for timeline in (1, 2, 3) for segment in (15, 16, 17)] FILES += [f"0000000200000000{segment:08X}{suffix}" for suffix in (".partial", ".00000020.backup", ".gz") for segment in (15, 16, 17)] FILES += ["00000002000000000000000F.00000020.backup.gz", "00000001.history", "00000001.history.gz", "00000002000000000000000f", "unrelated_file"] PAYLOAD = b"HESELA synthetic filename fixture. Not valid WAL.\n" def sha(data): return hashlib.sha256(data).hexdigest() def inventory(folder): return {p.name: {"bytes": p.stat().st_size, "sha256": sha(p.read_bytes())} for p in sorted(folder.iterdir())} def scenarios(): groups = [ ("default", [], LOW + ["00000002000000000000000F.partial"]), ("extension", ["-x", ".gz"], LOW + ["00000002000000000000000F.partial", "00000002000000000000000F.gz"]), ] for name, options, expected in groups: for suffix in ("", ".partial", ".00000020.backup"): yield {"name": name + (suffix or "-plain"), "options": options, "cutoff": CUTOFF + suffix, "expected": sorted(expected), "exit": 0} yield {"name": "compressed-cutoff", "options": ["-x", ".gz"], "cutoff": CUTOFF + ".gz", "expected": sorted(groups[1][2]), "exit": 0} yield {"name": "invalid-cutoff", "options": [], "cutoff": "not-a-wal-name", "expected": [], "exit": 2} yield {"name": "unsupported-backup-history-option", "options": ["-b"], "cutoff": CUTOFF, "expected": [], "exit": 2} yield {"name": "unsupported-long-dry-run-option", "options": ["--dry-run"], "cutoff": CUTOFF, "expected": [], "exit": 2} def run_probe(binary): binary = Path(binary).resolve(strict=True) version = subprocess.check_output([str(binary), "--version"], text=True).strip() if not version.startswith("pg_archivecleanup (PostgreSQL) 16.15"): raise ValueError("This recorded protocol requires PostgreSQL 16.15") cases = [] with tempfile.TemporaryDirectory(prefix="hesela-pg-cleanup-") as temp: folder = Path(temp) for name in FILES: (folder / name).write_bytes(PAYLOAD) before = inventory(folder) for case in scenarios(): args = [str(binary), "-n", *case["options"], str(folder), case["cutoff"]] completed = subprocess.run(args, capture_output=True, text=True, timeout=10, env={**os.environ, "LC_ALL": "C", "PG_COLOR": "never"}) output_paths = completed.stdout.splitlines() if any(Path(p).parent != folder for p in output_paths): raise RuntimeError("Unexpected path in native output") actual = sorted(Path(p).name for p in output_paths) after = inventory(folder) if before != after: raise RuntimeError("Dry-run changed fixture files") if completed.returncode != case["exit"] or actual != case["expected"]: raise RuntimeError(json.dumps({"case": case, "returncode": completed.returncode, "actual": actual, "stderr": completed.stderr})) cases.append({**case, "command": ["pg_archivecleanup", "-n", *case["options"], "", case["cutoff"]], "exitCode": completed.returncode, "listed": actual, "stdout": completed.stdout.replace(str(folder), ""), "stderr": completed.stderr.replace(str(folder), "").replace(str(binary), "pg_archivecleanup"), "after": after, "unchanged": True}) return {"schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "scope": "Native filename selection only; synthetic files, not valid WAL; no restore.", "version": version, "binarySha256": sha(binary.read_bytes()), "platform": platform.platform(), "python": platform.python_version(), "probeSha256": sha(Path(__file__).read_bytes()), "fixture": before, "cases": cases, "passed": True} if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--binary", required=True, help="Path to PostgreSQL 16.15 pg_archivecleanup") parser.add_argument("--output", required=True, type=Path) args = parser.parse_args() result = run_probe(args.binary) args.output.write_text(json.dumps(result, indent=2) + "\n") print(json.dumps({"passed": result["passed"], "cases": len(result["cases"]), "files": len(result["fixture"]), "version": result["version"]}))