"""SANDBOX trie visualization: build the n100 execution trie over canonical train + test + synthetic + the 51 temp merged injections, and emit into the sandbox out/ folder: - trie_after.txt full highlighted text tree - trie_targets.txt focused before/after view of the 5 fix-target nodes - trie_after.png/.svg rendered image (if Graphviz is installed) Read-only w.r.t. canonical data. Run from repo root: python -u temp/injection_sandbox/viz_trie.py """ from __future__ import annotations import json import sys from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "systemUpgrade")) from pipeline import load_examples # noqa: E402 from trie.builder import build_trie # noqa: E402 from scripts.visualize_distractor_trie import _render_image # noqa: E402 SAND = Path(__file__).resolve().parent OUT = SAND / "out" EXP = ROOT / "data" / "tau-2" / "processed_distractor_exp2" N100 = EXP / "n100" MERGED = OUT / "_staging_merged_injections.jsonl" TARGETS = { "N1": ["find_user_id_by_email"], "N2": ["find_user_id_by_email", "get_user_details"], "N3": ["modify_pending_order_items"], "N4": ["find_user_id_by_name_zip", "get_user_details", "get_order_details", "get_order_details", "get_order_details", "get_order_details"], "N5": ["find_user_id_by_name_zip", "get_order_details"], } manifest = json.loads((N100 / "apis.manifest.json").read_text(encoding="utf-8")) REAL, CONF, DUMMY = set(manifest.get("real", [])), set(manifest.get("confuser", [])), set(manifest.get("dummy", [])) def cls(name): return "REAL" if name in REAL else "conf" if name in CONF else "dummy" if name in DUMMY else "?" def build(with_merged): ex = load_examples(EXP / "train.jsonl") + load_examples(EXP / "test.jsonl") ex += load_examples(N100 / "synthetic_trajectories.jsonl") if with_merged: ex += load_examples(MERGED) return build_trie(ex) def target_view(trie): lines = [] for name, path in TARGETS.items(): node = trie.traverse(tuple(path)) lines.append(f"\n{name} {' > '.join(path)}") if node is None or node.total_child_count() == 0: lines.append(" (absent)") continue probs = node.transition_probs() for nm in sorted(node.children, key=lambda n: -probs[n]): tag = cls(nm) mark = ">>" if tag == "REAL" else " " lines.append(f" {mark} [{tag:5}] {nm:32} p={probs[nm]:.3f} count={node.children[nm].count}") return lines def main(): before, after = build(False), build(True) # focused before/after target view tv = ["FIX-TARGET NODES (before vs after temp injection)", "=" * 70] tv.append("\n--- BEFORE ---") tv += target_view(before) tv.append("\n\n--- AFTER (with 51 merged injections) ---") tv += target_view(after) (OUT / "trie_targets.txt").write_text("\n".join(tv), encoding="utf-8") # full highlighted text tree (after) lines, node_cls, stats = [], Counter(), {"nodes": 0, "max_depth": 0} def render(node, depth): for child in sorted(node.children.values(), key=lambda c: (-c.count, c.api_name)): c = cls(child.api_name) node_cls[c] += 1 stats["nodes"] += 1 stats["max_depth"] = max(stats["max_depth"], depth + 1) ind = " " * depth if c == "REAL": lines.append(f"{ind}>> REAL {child.api_name} (count={child.count})") else: lines.append(f"{ind} [{c:5}] {child.api_name} (count={child.count})") render(child, depth + 1) render(after.root, 0) header = [ "EXP2 EXECUTION TRIE (train + test + synthetic + 51 temp injections)", "=" * 70, f"trajectories: before={before.root.count} after={after.root.count} " f"(+{after.root.count - before.root.count})", f"trie nodes: {stats['nodes']} max depth: {stats['max_depth']}", "nodes by class: " + " ".join(f"{k}={node_cls[k]}" for k in ("REAL", "conf", "dummy", "?")), "Legend: '>> REAL' = real tau2 API; [conf] = confuser; [dummy] = off-domain", "=" * 70, "", ] (OUT / "trie_after.txt").write_text("\n".join(header + lines), encoding="utf-8") img = _render_image(after.root, cls, OUT / "trie_after", fmt="png") _render_image(after.root, cls, OUT / "trie_after", fmt="svg") print(f"trajectories before={before.root.count} after={after.root.count} (+{after.root.count-before.root.count})") print("wrote:", (OUT / 'trie_targets.txt').name, ",", (OUT / 'trie_after.txt').name, ("," + Path(img).name if img else "(no image: Graphviz not installed)")) return 0 if __name__ == "__main__": raise SystemExit(main())