#!/usr/bin/env python3 """Fault injection: how many conversational nodes does the assurance ceiling need? For every configuration (a subset of the eight nodes) and every fault of the catalogue (``lgphysstratum/faults.py``) a probe set of the corpus is run in memory with the very same node code the orchestrator runs. A run is *activated* when the injected fault really changed a node. Each activated run is then measured against the honest result of the same item, and ends in one of: raised : the fault pushed the shown assurance above the honest ceiling -- an invariant violation, and the only outcome this topology is not allowed to produce lowered : the answer stayed what the gold asked but the confidence dropped: another node compensated by withdrawing certainty, which is the designed reaction masked : the gold still holds at the same assurance, because the fault changed nothing that the referee reads abstained : the layer withdrew the answer entirely (assurance zero) while the gold expected one caught : an answer was shown that the gold does not accept, but the session pointed at its own gap: a claim fell to the referee of its node, or the assurance sits below the honest one because the configuration itself lost a node silent_error : a wrong answer presented with confidence while nothing in the session said so Usage: python tools/ablation.py [--probe N] [--all] [--out results/ablation.json] """ import argparse import json import sys import time from pathlib import Path from typing import Any, Dict, List, Tuple ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from lgphysstratum import agents, corpus, faults, pipeline # noqa: E402 FULL = list(agents.ORDER) OUT = ROOT / "results" / "ablation.json" CONFIGS: Dict[str, List[str]] = { "S1 reader_a": ["reader_a"], "S2 +reader_b": ["reader_a", "reader_b"], "S3 +equivalence": ["reader_a", "reader_b", "equivalence"], "S4 +coverage": ["reader_a", "reader_b", "equivalence", "coverage"], "S5 +invoker": ["reader_a", "reader_b", "equivalence", "coverage", "invoker"], "S6 +boundary": FULL[:6], "S7 +adversary": FULL[:7], "S8 full topology": FULL, } for _node in FULL: CONFIGS["S8 minus %s" % _node] = [node for node in FULL if node != _node] def single_faults(active: List[str]) -> List[Tuple[str, ...]]: # Not every node has a fault to commit: the invoker reads nothing and proves nothing. return [("%s:%s" % (node, kind),) for node in active for kind in faults.CATALOG.get(node, [])] def multi_faults() -> List[Tuple[str, ...]]: """The pairs that matter here: both readers wrong in the same way, and certainty forced on top of a reading that no longer holds. The physics reader faults are the three that a physics sentence makes possible -- a shifted number, a pair of units that no longer convert, a symbol that fell out of a formula -- so the pairs below are the same mistakes on both channels.""" out: List[Tuple[str, ...]] = [ ("reader_a:same_units", "reader_b:same_units"), ("reader_a:shift_number", "reader_b:shift_number"), ("reader_a:drop_symbol", "reader_b:drop_symbol"), ("equivalence:rubber_stamp", "coverage:rubber_stamp"), ("boundary:tamper_physics", "arbiter:force_assurance"), ("reader_a:shift_number", "equivalence:rubber_stamp"), ("reader_a:drop_symbol", "arbiter:force_assurance"), ("boundary:tamper_physics", "adversary:rubber_stamp", "arbiter:force_assurance"), ] return [spec for spec in out if all(part.split(":")[0] in faults.CATALOG for part in spec)] def honest(item: Dict[str, Any]) -> Dict[str, Any]: """The baseline the injected runs are measured against: no fault, full topology.""" faults.configure([]) result = pipeline.ask(item["question"], item["lang"], active=FULL) grade = corpus.grade(item, result) return {"ok": bool(grade["ok"]), "assurance": int(result["final"].get("assurance", 0)), "state": str(result["final"].get("state", "NONE")), "problems": grade["problems"]} def flagged(result: Dict[str, Any]) -> bool: """Did the session itself point at the problem: a claim that did not survive its own referee.""" final = result.get("final") or {} if final.get("detected"): return True return any(record["claimed"] != record["referee"] for record in result.get("records") or []) def classify(base: Dict[str, Any], item: Dict[str, Any], result: Dict[str, Any]) -> str: """What an injected fault ended up doing to what the layer shows. ``raised`` is the violation the tool exists to look for. ``silent_error`` is the narrower thing it is supposed to prevent: a wrong answer was shown, and nothing in the session said so. When an envelope claim fell to its referee, or the assurance sits below the honest one because the topology itself was weakened, the run is ``caught``: the layer still answered, but it pointed at its own gap. """ shown = int(result["final"].get("assurance", 0)) grade = corpus.grade(item, result) if shown > base["assurance"]: return "raised" if grade["ok"]: return "lowered" if shown < base["assurance"] else "masked" if shown == 0: return "abstained" return "caught" if (flagged(result) or shown < base["assurance"]) else "silent_error" def run_cell(items: List[Dict[str, Any]], active: List[str], spec: Tuple[str, ...], base: Dict[str, Dict[str, Any]], config: str = "") -> Dict[str, Any]: tally = {"runs": 0, "activated": 0, "raised": 0, "lowered": 0, "masked": 0, "caught": 0, "abstained": 0, "silent_error": 0, "details": []} for item in items: # The session itself has to carry the fault: asking for it beforehand is not enough, because # a session configures the faults it was given and leaves the others off. result = pipeline.ask(item["question"], item["lang"], active=active, fault_spec=list(spec)) tally["runs"] += 1 if not faults.FIRED: continue tally["activated"] += 1 label = classify(base[item["id"]], item, result) tally[label] += 1 if label in ("raised", "silent_error", "caught"): grade = corpus.grade(item, result) tally["details"].append({"id": item["id"], "config": config, "fault": list(spec), "label": label, "honest": base[item["id"]]["assurance"], "shown": int(result["final"].get("assurance", 0)), "flagged": flagged(result), "problems": grade["problems"]}) return tally def probe_set(items: List[Dict[str, Any]], count: int) -> List[Dict[str, Any]]: """Spread the probe across the languages instead of taking the first N of one variety.""" if count >= len(items): return list(items) by_lang: Dict[str, List[Dict[str, Any]]] = {} for item in items: by_lang.setdefault(item["lang"], []).append(item) picked: List[Dict[str, Any]] = [] rank = 0 while len(picked) < count: added = False for lang in sorted(by_lang): pool = by_lang[lang] if rank < len(pool) and len(picked) < count: picked.append(pool[rank]) added = True if not added: break rank += 1 return picked def main(argv: List[str] = None) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--probe", type=int, default=12, help="how many corpus items to run per cell") parser.add_argument("--all", action="store_true", help="run the whole corpus in every cell") parser.add_argument("--out", default=str(OUT), help="where to write the JSON report") args = parser.parse_args(argv) items = corpus.load() probes = items if args.all else probe_set(items, max(1, args.probe)) print("probe set: %d items over %s" % (len(probes), ", ".join(sorted({i["lang"] for i in probes})))) base = {} for item in probes: base[item["id"]] = honest(item) print("honest %-9s %-12s assurance %d %s" % (item["id"], base[item["id"]]["state"], base[item["id"]]["assurance"], "" if base[item["id"]]["ok"] else base[item["id"]]["problems"])) report: Dict[str, Any] = {"probe": [item["id"] for item in probes], "cells": {}} started = time.time() for name in sorted(CONFIGS): active = CONFIGS[name] specs = single_faults(active) if name == "S8 full topology": specs.extend(multi_faults()) for spec in specs: cell = run_cell(probes, active, spec, base, config=name) key = "%s | %s" % (name, ",".join(spec)) report["cells"][key] = cell print("%-52s runs %2d activated %2d raised %d silent %d caught %d abstained %d " "lowered %d masked %d" % (key, cell["runs"], cell["activated"], cell["raised"], cell["silent_error"], cell["caught"], cell["abstained"], cell["lowered"], cell["masked"])) totals = {"runs": 0, "activated": 0, "raised": 0, "lowered": 0, "masked": 0, "caught": 0, "abstained": 0, "silent_error": 0} for cell in report["cells"].values(): for key in totals: totals[key] += cell[key] report["totals"] = totals report["seconds"] = round(time.time() - started, 1) report["violations"] = [detail for cell in report["cells"].values() for detail in cell["details"]] destination = Path(args.out) destination.parent.mkdir(parents=True, exist_ok=True) destination.write_text(json.dumps(report, indent=1, sort_keys=True) + "\n", encoding="utf-8") print("") print("cells %d, activated %d, raised %d, silent errors %d, caught %d, abstained %d, lowered %d, " "masked %d" % (len(report["cells"]), totals["activated"], totals["raised"], totals["silent_error"], totals["caught"], totals["abstained"], totals["lowered"], totals["masked"])) print("wrote %s in %.1f seconds" % (destination, report["seconds"])) return 1 if totals["raised"] else 0 if __name__ == "__main__": raise SystemExit(main())