"""Render the NEW (unbundled v3) confuser trie and compare to the OLD one. The canonical renderer (distractor_generation_2/visualize.py) builds a trie over each row's `calls` name-sequence, colouring the real prefix BLUE and confuser look-alikes ORANGE. We reuse it, but feed it our v3 split dataset so you can see how unbundling reshaped the trie: OLD: 795 confusers, each a single long mega-turn -> deep root->leaf paths. NEW: each split confuser becomes T1 (real prefix -> confuser node F, the preserved divergence) plus re-rooted tail turns (own short paths from ROOT). Result: shallower, wider trie that mirrors real tau2 turn shapes. Outputs (into this folder): trie_v3.txt, trie_v3.svg, trie_v3.png Run: python -u temp/story_remediation/unbundle/visualize_v3.py """ from __future__ import annotations import json, sys from pathlib import Path HERE = Path(__file__).resolve().parent ROOT = HERE.parents[2] sys.path.insert(0, str(ROOT)) from models.trie import Trie # noqa: E402 from distractor_generation_2.visualize import ( # noqa: E402 _load_seqs, _load_names, _text_tree, _render_image) N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" V3 = HERE / "out" / "trajectories_all_v3.jsonl" REAL_APIS = ROOT / "data" / "tau-2" / "processed" / "apis.jsonl" def seqs_from(path: Path): out = [] for line in path.read_text(encoding="utf-8").splitlines(): if not line.strip(): continue e = json.loads(line) s = [c["name"] for c in e.get("calls", []) if c.get("name")] if s: out.append(s) return out def build(seqs): t = Trie() for s in seqs: t.insert(list(s)) return t def stats(trie, classify): lines, st, cls = _text_tree(trie.root, classify, 1) root_branch = sum(1 for c in trie.root.children.values()) depths = [] def walk(node, d): if not node.children: depths.append(d); return for c in node.children.values(): walk(c, d + 1) walk(trie.root, 0) return dict(nodes=st["nodes"], max_depth=st["max_depth"], root_branch=root_branch, leaves=len(depths), mean_leaf_depth=sum(depths) / max(len(depths), 1)), lines def main(): try: sys.stdout.reconfigure(encoding="utf-8", errors="replace") except Exception: pass real_names = _load_names(REAL_APIS) conf_names = _load_names(N100 / "apis.jsonl") def classify(name: str) -> str: if name in conf_names: return "confuser" if name in real_names: return "real" return "?" old_seqs = seqs_from(N100 / "trajectories.jsonl") new_seqs = seqs_from(V3) old_trie = build(old_seqs) new_trie = build(new_seqs) old_st, _ = stats(old_trie, classify) new_st, new_lines = stats(new_trie, classify) print("=" * 74) print("CONFUSER TRIE — OLD (single mega-turn) vs NEW (unbundled v3)") print("=" * 74) print(f"{'metric':22s}{'OLD':>12s}{'NEW':>12s}") for k in ("nodes", "max_depth", "root_branch", "leaves", "mean_leaf_depth"): ov, nv = old_st[k], new_st[k] of = f"{ov:.2f}" if isinstance(ov, float) else str(ov) nf = f"{nv:.2f}" if isinstance(nv, float) else str(nv) print(f"{k:22s}{of:>12s}{nf:>12s}") print(f"{'trajectories(rows)':22s}{len(old_seqs):>12d}{len(new_seqs):>12d}") header = [ "NEW UNBUNDLED CONFUSER TRIE (v3) — built over the split dataset", "=" * 72, f"rows: {len(new_seqs)} nodes: {new_st['nodes']} max depth: {new_st['max_depth']} " f"root branches: {new_st['root_branch']} mean leaf depth: {new_st['mean_leaf_depth']:.2f}", "Legend: [real] BLUE = real prefix the confuser anchors to; " "[confuser] ORANGE = retail look-alike (the divergence node F).", "=" * 72, "", ] (HERE / "trie_v3.txt").write_text("\n".join(header + new_lines), encoding="utf-8") print(f"\ntext tree -> {(HERE/'trie_v3.txt').relative_to(ROOT)} ({len(new_lines)} lines)") png = _render_image(new_trie.root, classify, HERE / "trie_v3", 1, "png") svg = _render_image(new_trie.root, classify, HERE / "trie_v3", 1, "svg") if png: print(f"PNG -> {png}") if svg: print(f"SVG -> {svg}") if __name__ == "__main__": main()