#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Bounded native Watchman observations; only new disposable fixtures are touched.""" import argparse import contextlib import datetime import hashlib import json import os from pathlib import Path import platform import subprocess import tempfile import time SCENARIOS = ("quiet", "continuous", "reset-default", "reset-empty", "clock-before-apply", "named-query-retry") INITIAL = {"keep.dat", "gone.dat"} CHANGED = {"keep.dat", "added.dat"} def require(condition, message): if not condition: raise RuntimeError(message) def delta(names, response): result = set(names) for entry in response["files"]: if entry["exists"]: result.add(entry["name"]) else: result.discard(entry["name"]) return result def snapshot(response): return {entry["name"] for entry in response["files"] if entry["exists"]} def query_options(since=None, empty=False): # An expression filters the single since/all generator. A suffix generator # alongside since would UNION candidates and invalidate the delta control. options = {"expression": ["suffix", "dat"], "fields": ["name", "exists", "new"], "sync_timeout": 5000} if since is not None: options["since"] = since if empty: options["empty_on_fresh_instance"] = True return options class Server: def __init__(self, binary, parent): self.binary = str(binary) self.temp = tempfile.TemporaryDirectory(prefix="hwc-", dir=parent) self.base = Path(self.temp.name) self.socket = self.base / "s" require(len(str(self.socket).encode()) < 100, "Choose a shorter scratch path") self.transcript = [] self.process = None def request(self, request, record=True): command = [self.binary, "--sockname=" + str(self.socket), "--logfile=" + str(self.base / "watchman.log"), "--statefile=" + str(self.base / "state"), "--pidfile=" + str(self.base / "pid"), "--no-spawn", "--no-local", "--output-encoding=json", "--no-pretty", "-j"] result = subprocess.run(command, input=json.dumps(request), text=True, capture_output=True, timeout=12) require(result.returncode == 0, result.stderr or result.stdout) response = json.loads(result.stdout) require("error" not in response, str(response)) if record: self.transcript.append({"request": request, "response": response, "exit_code": result.returncode, "stderr": result.stderr}) return response def __enter__(self): self.output = (self.base / "process.log").open("w") self.env = dict(os.environ) config = self.base / "global.json" config.write_text("{}\n") self.env["WATCHMAN_CONFIG_FILE"] = str(config) command = [self.binary, "--foreground", "--no-save-state", "--sockname=" + str(self.socket), "--logfile=" + str(self.base / "watchman.log"), "--statefile=" + str(self.base / "state"), "--pidfile=" + str(self.base / "pid")] self.process = subprocess.Popen(command, stdout=self.output, stderr=subprocess.STDOUT, env=self.env) deadline = time.monotonic() + 10 while time.monotonic() < deadline: if self.process.poll() is not None: break try: self.version = self.request(["version"], record=False)["version"] return self except (RuntimeError, ValueError) as error: self.start_error = str(error) time.sleep(0.02) detail = (self.base / "process.log").read_text() detail += (self.base / "watchman.log").read_text() if (self.base / "watchman.log").exists() else "" detail += getattr(self, "start_error", "") self.close() raise RuntimeError("Private Watchman server did not start: " + detail) def close(self): if self.process is not None: if self.process.poll() is None: with contextlib.suppress(Exception): self.request(["shutdown-server"], record=False) try: self.process.wait(timeout=5) except subprocess.TimeoutExpired: self.process.terminate() try: self.process.wait(timeout=5) except subprocess.TimeoutExpired: self.process.kill() self.process.wait(timeout=5) if hasattr(self, "output"): self.output.close() self.temp.cleanup() def __exit__(self, *_): self.close() def observe(server, parent, scenario, repetition): with tempfile.TemporaryDirectory(prefix="hw-root-", dir=parent) as directory: root = Path(directory) (root / ".watchmanconfig").write_text("{}\n") for name in INITIAL: (root / name).write_bytes(name.encode("ascii") + b"\n") start = len(server.transcript) watch = server.request(["watch", str(root)]) require(watch.get("watcher") == "inotify", "This probe requires Linux inotify") try: cursor = "n:hesela" if scenario == "named-query-retry" else None baseline = server.request(["query", str(root), query_options(cursor)]) require(snapshot(baseline) == INITIAL, "Baseline incomplete") cursor = cursor or baseline["clock"] if scenario.startswith("reset"): server.request(["watch-del", str(root)]) if scenario != "quiet": (root / "gone.dat").unlink() (root / "added.dat").write_bytes(b"added.dat\n") if scenario.startswith("reset"): server.request(["watch", str(root)]) first = server.request(["query", str(root), query_options(cursor, scenario == "reset-empty")]) retry = None if scenario in ("clock-before-apply", "named-query-retry"): retry_cursor = first["clock"] if scenario == "clock-before-apply" else cursor retry = server.request(["query", str(root), query_options(retry_cursor)]) naive = delta(INITIAL, retry) recovered = server.request(["query", str(root), query_options(baseline["clock"])]) safe = delta(INITIAL, recovered) elif scenario == "reset-empty": naive = delta(INITIAL, first) recovered = server.request(["query", str(root), query_options()]) safe = snapshot(recovered) elif scenario == "reset-default": naive = delta(INITIAL, first) recovered = first safe = snapshot(first) else: naive = delta(INITIAL, first) recovered = first safe = naive expected = INITIAL if scenario == "quiet" else CHANGED actual = {p.name for p in root.iterdir() if p.suffix == ".dat"} require(actual == expected, "Fixture oracle mismatch") require(safe == expected, "Recovery control failed") require(first["is_fresh_instance"] == scenario.startswith("reset"), "Unexpected continuity flag") if scenario in ("quiet", "reset-empty"): require(first["files"] == [], "Expected empty first query") if retry is not None: require(retry["files"] == [] and retry["is_fresh_instance"] is False, "Expected empty non-fresh retry") expected_naive = { "quiet": INITIAL, "continuous": CHANGED, "reset-default": INITIAL | CHANGED, "reset-empty": INITIAL, "clock-before-apply": INITIAL, "named-query-retry": INITIAL, }[scenario] require(naive == expected_naive, "Unexpected naive consumer result") info = json.loads(subprocess.check_output( ["findmnt", "-J", "-T", str(root), "-o", "FSTYPE"], text=True)) row = { "scenario": scenario, "repetition": repetition, "filesystem": info["filesystems"][0]["fstype"], "watcher": watch["watcher"], "fresh": first["is_fresh_instance"], "returned": sorted(first["files"], key=lambda x: x["name"]), "retry": retry, "naive_names": sorted(naive), "oracle_names": sorted(actual), "recovered_names": sorted(safe), "stale_names": sorted(naive - actual), "missing_names": sorted(actual - naive), "transcript": server.transcript[start:], } # Preserve opaque clocks and results while removing random path labels. return json.loads(json.dumps(row).replace(str(root), "")) finally: server.request(["watch-del", str(root)], record=False) def summarize(rows): result = [] for scenario in SCENARIOS: group = [row for row in rows if row["scenario"] == scenario] result.append({"scenario": scenario, "executions": len(group), "fresh": sorted({row["fresh"] for row in group}), "returned_counts": sorted({len(row["returned"]) for row in group}), "stale_counts": sorted({len(row["stale_names"]) for row in group}), "missing_counts": sorted({len(row["missing_names"]) for row in group}), "recovery_passes": sum(row["oracle_names"] == row["recovered_names"] for row in group)}) return result def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--binary", type=Path, required=True) parser.add_argument("--directory", type=Path, action="append", required=True) parser.add_argument("--repetitions", type=int, default=3) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() require(1 <= args.repetitions <= 20, "Repetitions must be 1..20") require(not args.output.exists(), "Output exists; choose a new filename") binary = args.binary.resolve(strict=True) rows = [] versions = set() for parent in args.directory: parent = parent.resolve(strict=True) with Server(binary, parent) as server: versions.add(server.version) for repetition in range(1, args.repetitions + 1): for scenario in SCENARIOS: rows.append(observe(server, parent, scenario, repetition)) result = { "schema_version": 1, "generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "kind": "controlled software observations and client-state counterexamples", "environment": {"watchman_versions": sorted(versions), "kernel": platform.release(), "python": platform.python_version(), "libc": platform.libc_ver(), "platform": platform.machine(), "binary_sha256": hashlib.sha256(binary.read_bytes()).hexdigest(), "probe_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}, "scope": {"query": query_options(), "initial_names": sorted(INITIAL), "mutated_names": sorted(CHANGED), "repetitions": args.repetitions, "limitations": "One host; name membership, not file-content backup. No overflow, aging-out, recrawl, concurrent writer, process crash or power failure was injected. Root reset used watch-del/watch only on private fixtures. Client discard/early cursor advance is deliberate."}, "summary": summarize(rows), "cases": rows, } with args.output.open("x") as handle: json.dump(result, handle, indent=2) handle.write("\n") print(json.dumps({"executions": len(rows), "summary": result["summary"]}, indent=2)) if __name__ == "__main__": main()