diff --git a/tempscripts/injection_sandbox/analyze_c3_reasons.py b/tempscripts/injection_sandbox/analyze_c3_reasons.py new file mode 100644 index 0000000000000000000000000000000000000000..7d15e24c126171ca5dfbc8f3018d765225b0cecf --- /dev/null +++ b/tempscripts/injection_sandbox/analyze_c3_reasons.py @@ -0,0 +1,77 @@ +"""SANDBOX C3 error analysis: for each of the 51 humanized injected rows, capture +the judge's REASONING (not just the guess), and line it up against the baseline +reasoning for that SAME host row (from datasetreview/results/new/C3.jsonl). Lets +us read, per example, WHY the host was caught and whether humanization addressed +that specific tell. One judgment per row (fake in A), reasoning captured. + +Run from repo root: python -u temp/injection_sandbox/analyze_c3_reasons.py +""" +from __future__ import annotations + +import json +import logging +import sys +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +SAND = Path(__file__).resolve().parent +OUT = SAND / "out" +MERGED = OUT / "_staging_merged_injections.jsonl" +PROV = {p["example_id"]: p for p in json.load(open(OUT / "_merged_injections.prov.json", encoding="utf-8"))} +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) +injected = [json.loads(l) for l in open(MERGED, encoding="utf-8") if l.strip()] + +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line) + base[d.get("item_id")] = {"caught": d.get("caught"), + "reason": ((d.get("result") or {}).get("reasoning") or "")} + + +def judge_one(fake): + eid = fake["example_id"] + real = pairer(fake) + msgs = J.build_c3(fake, real, swap=False) # fake is A + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + except Exception as e: # noqa: BLE001 + return {"example_id": eid, "error": str(e)} + return {"example_id": eid, "host_of": PROV[eid]["host_of"], "node": PROV[eid]["rebalance_node"], + "confuser": PROV[eid]["confuser"], "guess": r.get("guess"), + "caught": r.get("guess") == "A", "confidence": r.get("confidence"), + "reason": r.get("reasoning") or ""} + + +def main(): + with ThreadPoolExecutor(max_workers=cfg["run"].get("workers", 4)) as ex: + res = list(ex.map(judge_one, injected)) + res.sort(key=lambda r: r["example_id"]) + for r in res: + r["host_baseline_caught"] = base.get(r.get("host_of"), {}).get("caught") + r["host_baseline_reason"] = base.get(r.get("host_of"), {}).get("reason", "") + (OUT / "c3_reasons.jsonl").write_text("\n".join(json.dumps(r) for r in res) + "\n", encoding="utf-8") + caught = sum(1 for r in res if r.get("caught")) + print(f"judged {len(res)} injected rows (orientation A, 1 sample). caught={caught}/{len(res)}") + print("wrote out/c3_reasons.jsonl") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/injection_sandbox/gen_merged.py b/tempscripts/injection_sandbox/gen_merged.py new file mode 100644 index 0000000000000000000000000000000000000000..3b5cb804d0402bfe26e9b14b0c7cecea22f3eb41 --- /dev/null +++ b/tempscripts/injection_sandbox/gen_merged.py @@ -0,0 +1,493 @@ +"""SANDBOX generator: splice each of the 51 trie-fill injections into its +assigned host conversation as a LATER turn (the injected row's history embeds the +host's own prior tool turn, grounded to the host's customer). Non-destructive: +host rows are NOT edited; we only ADD injected rows. Everything writes under +temp/injection_sandbox/out. Reuses the proven grounded call assembly + replay +verification from scripts/_gen_injections2.py. + +Run: python -u temp/injection_sandbox/gen_merged.py +""" +from __future__ import annotations + +import json +import random +import re +import sys +from collections import Counter +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SAND = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "systemUpgrade" / "executor")) + +import scripts._gen_injections2 as G # noqa: E402 +from fake_state import EpisodeState # noqa: E402 +from fake_tools import TOOLS # noqa: E402 + +DATA = SAND / "data" +OUT = SAND / "out" +OUT.mkdir(parents=True, exist_ok=True) + +# use the SANDBOX (clonable) free-running catalog for all grounding/replay +CATALOG = json.load(open(DATA / "catalog.json", encoding="utf-8")) +G.CATALOG = CATALOG +RND = random.Random(1234) + +def hq_variant(leaf, on): + """Humanized LATER-turn query. The customer is already authenticated in the + host turn, so a real person would NOT restate email / name / ZIP or say + 'look me up'. Phrase as a natural follow-up; keep the order-number literal + (retrieval signal); no em dashes.""" + V = { + "schedule_delivery": [ + f"Also, could you set delivery for {on} to next Tuesday?", + f"One more thing, can we schedule {on} to arrive on the 14th?", + f"While you're in there, I'd like {on} delivered next Tuesday if that works.", + ], + "request_gift_receipt": [ + f"Oh, and could I get a gift receipt for {on}? It's a present.", + f"Also, {on} is a gift, so a gift receipt would be great.", + f"Could you include a gift receipt with {on}? It's for my sister.", + ], + "get_wishlist": [ + "Also, can you remind me what's still on my wishlist?", + "While I've got you, what did I have saved on my wishlist again?", + "Oh, and what's left on my wishlist? I keep forgetting.", + ], + "get_order_invoice": [ + f"Could you also send me the invoice for {on}? I need it for expenses.", + f"One more thing, can I get the itemized invoice for {on}?", + f"Also, I need the invoice for {on} for my records.", + ], + "redeem_loyalty_points": [ + "Also, I'd like to cash in some of my loyalty points for credit.", + "While we're at it, can I redeem a few hundred points?", + "Oh, and can I put some loyalty points toward store credit?", + ], + "reorder_previous_order": [ + f"Also, could you just reorder everything from {on}? Same as before.", + f"One more thing, can we duplicate order {on}? I loved that batch.", + f"While you're in there, could you reorder {on} for me?", + ], + "apply_gift_card": [ + f"Also, I've got a gift card I'd like to put toward {on}.", + f"Oh, can we apply my gift card to {on}?", + f"While we're at it, please use my gift card on {on}.", + ], + "get_shipping_options": [ + f"Also, what are the shipping options for {on}?", + f"One more thing, what delivery choices do I have for {on}?", + f"While you're there, can you tell me the shipping options on {on}?", + ], + "subscribe_to_restock_alert": [ + f"Could you swap the out-of-stock item on {on}, and let me know when the original is back?", + f"Please change that item on {on}, and sign me up for a restock alert on the old one.", + f"Can we modify {on} to swap that item, and ping me when it restocks?", + ], + "file_shipping_insurance_claim": [ + f"Also, {on} arrived damaged, can I file an insurance claim on it?", + f"One more thing, I need to file a shipping insurance claim for {on}. It came banged up.", + ], + "request_price_match": [ + f"Also, I saw an item from {on} cheaper elsewhere, can you price match it?", + f"One more thing, can you price match something on {on}? Found it for less online.", + ], + "get_store_credit_balance": [ + "Also, what's my store credit balance right now?", + "Oh, and how much store credit do I have left?", + ], + "set_delivery_instructions": [ + f"Also, can you add a note to leave {on} with the doorman?", + f"One more thing, please have {on} left with the front desk.", + ], + "upgrade_shipping_speed": [ + f"Also, can you bump {on} to express if it hasn't shipped yet?", + f"One more thing, could you upgrade {on} to overnight?", + ], + } + return RND.choice(V[leaf]) + + +CONFIRM = [ + "All set, anything else I can help with?", + "Done. Let me know if you need more.", + "Taken care of. What else can I do?", + "That's handled. Anything further?", +] + + +def parse(o): + try: + return json.loads(o) if isinstance(o, str) and o.strip().startswith("{") else None + except json.JSONDecodeError: + return None + + +def host_customer(host, a): + """Reconstruct the host's customer + order dicts, backed by the assignment.""" + ods = {} + ud = None + for c in host["calls"]: + o = parse(c.get("output")) + if c["name"] == "get_user_details" and o and o.get("user_id"): + ud = o + if c["name"] == "get_order_details" and o and o.get("order_id"): + ods[o["order_id"]] = o + user_details = { + "user_id": a["uid"], "email": a["email"], + "name": a.get("name") or (ud or {}).get("name") or {"first_name": "Alex", "last_name": "Kim"}, + "address": (ud or {}).get("address") or {"zip": a.get("zip", "10001")}, + "orders": list(ods), + } + return {"uid": a["uid"], "email": a["email"], "user_details": user_details, "orders": ods} + + +OPEN_LEAVES = {"schedule_delivery", "set_delivery_instructions", "get_shipping_options", + "upgrade_shipping_speed", "modify_pending_order_items"} + + +def order_ids_for(a, u): + need = a["prefix"].count("get_order_details") + if a["node"] == "N4" and a.get("n4_orders"): + ids = [o for o in a["n4_orders"] if o in u["orders"]] or list(u["orders"]) + elif a.get("grounded_order") and a["grounded_order"] in u["orders"]: + ids = [a["grounded_order"]] + [o for o in u["orders"] if o != a["grounded_order"]] + else: + ids = list(u["orders"]) + # For open-required ops, ground on the most-open order the host actually has: + # pending/processing first, then shipped (still pre-delivery), then delivered. + if a["node"] != "N4" and (a["leaf"] in OPEN_LEAVES or any(t in OPEN_LEAVES for t in a["prefix"])): + def rank(oid): + st = str((u["orders"].get(oid) or {}).get("status", "")).lower() + if st in ("pending", "processing", "open", "pending (modified)"): + return 0 + return 1 if st == "shipped" else 2 + ids = sorted(ids, key=rank) + if not ids: + ids = ["#W0000000"] + while len(ids) < max(1, need): + ids.append(ids[0]) + return ids + + +# ---- embedded-host humanization (copy-only; canonical host rows untouched) ---- +# Targets the two dominant C3 tells in host turns while preserving EVERY DB +# literal (order #, item id, price, quoted gift message, date, email, ZIP): +# T1 scripted meta preamble ("Review my recent orders, then ...") +# T2 trailing auth boilerplate ("... Name is X, ZIP 12345.") when that same +# name/ZIP/email already appears earlier in the conversation (pure dedupe) +# T3 assistant em/hyphen dashes ("Sure - let me ...") -> comma +_PREAMBLE = [ + re.compile(r"^\s*review my [\w ]{0,32}orders,\s*then\s+", re.I), + re.compile(r"^\s*review my [\w ]{0,32}orders and\s+", re.I), + re.compile(r"^\s*review my [\w ]{0,32}orders:\s*", re.I), + re.compile(r"^\s*look at my [\w ]{0,32}orders:\s+", re.I), + re.compile(r"^\s*can you look over my [\w ]{0,32}orders\?\s+", re.I), + re.compile(r"^\s*across (?:my )?[\w ]{0,32}orders:\s+", re.I), +] +_TRAIL_NAMEZIP = re.compile( + r"\s*(?:my name is|name is)\s+([A-Za-z]+(?:\s+[A-Za-z]+)?),?\s*" + r"(?:and\s+(?:my\s+)?)?zip(?:\s+is|\s+code\s+is|:)?\s*(\d{5})\.?\s*$", re.I) +_TRAIL_EMAIL = re.compile(r"\s*my email is\s+([^\s,]+@[^\s,]+?)\.?\s*$", re.I) + + +def _cap(s): + return s[:1].upper() + s[1:] if s else s + + +def humanize_host_query(q, history_text): + for pat in _PREAMBLE: + m = pat.match(q) + if m: + q = _cap(q[m.end():].lstrip()) + break + m = _TRAIL_NAMEZIP.search(q) + if m and (m.group(1) in history_text and m.group(2) in history_text): + q = q[:m.start()].rstrip() + if q and q[-1] not in ".!?": + q += "." + m = _TRAIL_EMAIL.search(q) + if m and m.group(1) in history_text: + q = q[:m.start()].rstrip() + if q and q[-1] not in ".!?": + q += "." + return q + + +def _dedash(s): + if not s: + return s + return re.sub(r"\s+[-\u2013\u2014]\s+", ", ", s) + + +def embed_host_turn(host): + """host history (small talk) + the host's own request rendered as a prior + tool turn (confuser-style encoding) + a confirmation. The embedded copy is + lightly humanized (preamble/auth-dedupe/dash cleanup); canonical host row is + not modified.""" + h = [dict(m) for m in (host.get("history") or [])] + for m in h: # T3: clean assistant dashes + if m.get("role") == "assistant" and m.get("content"): + m["content"] = _dedash(m["content"]) + history_text = " ".join((m.get("content") or "") for m in h) + q = (host.get("query") or host.get("retrieval_text") or "").strip() + q = humanize_host_query(q, history_text) # T1 + T2 + h.append({"role": "user", "content": q, "tool_calls": [], "tool_call_id": None}) + tcs = [{"name": c["name"], "arguments": c.get("arguments", {}), + "output": c.get("output"), "reasoning": c.get("reasoning", "")} + for c in host["calls"]] + h.append({"role": "assistant", "content": None, "tool_calls": tcs, "tool_call_id": None}) + for c in host["calls"]: + h.append({"role": "tool", "content": c.get("output"), "tool_calls": [], "tool_call_id": None}) + h.append({"role": "assistant", "content": _dedash(RND.choice(CONFIRM)), "tool_calls": [], "tool_call_id": None}) + return h + + +def history_tool_calls(host): + """Tool calls embedded in the host's own history (auth/reads retained earlier).""" + out = [] + for m in (host.get("history") or []): + for tc in (m.get("tool_calls") or []): + out.append({"name": tc.get("name"), "arguments": tc.get("arguments", {}), + "output": tc.get("output")}) + return out + + +# ------------------------------------------------ leaf/host value reconciliation +def reconcile_leaf_with_host(calls, host): + """If the injected leaf reads an entity the host turn already established, copy + the host's recorded output verbatim so the same customer yields the same value + at the conversation level (and the row still reproduces in isolation).""" + leaf = calls[-1] + n = leaf["name"] + SELF = {"get_order_invoice", "get_shipping_options", "get_wishlist", "get_store_credit_balance"} + if n not in SELF: + return calls, None + a = leaf.get("arguments", {}) + ent = ("#" + str(a["order_id"]).lstrip("#").upper()) if a.get("order_id") else a.get("user_id") + + def _ent(c): + aa = c.get("arguments", {}) + return ("#" + str(aa["order_id"]).lstrip("#").upper()) if aa.get("order_id") else aa.get("user_id") + for hc in host["calls"]: + if hc["name"] == n and _ent(hc) == ent and hc.get("output") is not None: + leaf["output"] = hc["output"] + return calls, (n, ent) + return calls, None + + +# ------------------------------------------------ conversation-level state check +def _ref_ids(call): + a = call.get("arguments", {}) or {} + out = {} + for k in ("user_id", "order_id", "gift_card_id"): + if a.get(k): + out[k] = a[k] + for k in ("item_id",): + if a.get(k): + out.setdefault("item_ids", []).append(a[k]) + for k in ("item_ids", "new_item_ids"): + for v in (a.get(k) or []): + out.setdefault("item_ids", []).append(v) + return out + + +def _establish(call, users, orders, items, cards): + n = call["name"] + raw = call.get("output") + o = parse(raw) + if n.startswith("find_user_id"): + uid = raw.strip().strip('"') if isinstance(raw, str) else None + if uid and "_" in uid: + users.add(uid) + elif n == "get_user_details" and o: + if o.get("user_id"): + users.add(o["user_id"]) + for oid in (o.get("orders") or []): + orders.add("#" + str(oid).lstrip("#").upper()) + elif n == "get_order_details" and o: + if o.get("order_id"): + orders.add("#" + str(o["order_id"]).lstrip("#").upper()) + for it in (o.get("items") or []): + if it.get("item_id"): + items.add(str(it["item_id"])) + elif n == "get_gift_card_balance" and o and o.get("gift_card_id"): + cards.add(str(o["gift_card_id"])) + elif n == "get_wishlist" and o: + for it in (o.get("items") or []): + if isinstance(it, dict) and it.get("item_id"): + items.add(str(it["item_id"])) + + +def conversation_state_check(seq_calls, catalog, hist_calls=()): + """Temporal grounding (no forward/unmarked refs) + output reproduction over the + whole merged conversation. ``hist_calls`` are tool calls from the host's history + (auth retained earlier), which pre-establish entities. Returns (forward_refs, + io_mismatches).""" + cat_orders = {"#" + str(o).lstrip("#").upper() for o in catalog.get("order_balances", {})} + cat_cards = {str(c) for c in catalog.get("gift_card_balances", {})} + users, orders, items, cards = set(), set(cat_orders), set(), set(cat_cards) + for hc in hist_calls: # entities established in host history + _establish(hc, users, orders, items, cards) + fwd = [] + for i, c in enumerate(seq_calls): + refs = _ref_ids(c) + # user_id must be established, unless this call itself establishes it + # (find_user_id_* mints it; get_user_details is the auth-retained read). + if (refs.get("user_id") and refs["user_id"] not in users + and not c["name"].startswith("find_user_id") + and c["name"] != "get_user_details"): + fwd.append((i, c["name"], "user_id", refs["user_id"])) + if refs.get("order_id"): + oid = "#" + str(refs["order_id"]).lstrip("#").upper() + if oid not in orders and c["name"] != "get_order_details": + fwd.append((i, c["name"], "order_id", refs["order_id"])) + if refs.get("gift_card_id") and str(refs["gift_card_id"]) not in cards: + fwd.append((i, c["name"], "gift_card_id", refs["gift_card_id"])) + _establish(c, users, orders, items, cards) + # I/O reproduction over the merged sequence (progressive seed) + s = EpisodeState.from_trajectory({"calls": seq_calls}, catalog) + io = [] + for c in seq_calls: + n = c["name"] + if n not in TOOLS: + continue + got = TOOLS[n](s, c.get("arguments", {})) + rec = parse(c.get("output")) + if n in G.FIND: + exp = (c.get("output") or "").strip().strip('"') + if got != exp: + io.append((n, "uid", got, exp)) + continue + if not isinstance(rec, dict): + continue + if n in G.FULLMATCH: + if got != rec: + io.append((n, "dict-diff")) + continue + keys = G.CHECK.get(n, []) + if any(got.get(k) is None and rec.get(k) is not None for k in keys): + continue + + def _eq(k): + g, rv = got.get(k), rec.get(k) + if k == "status" and isinstance(g, str) and isinstance(rv, str): + return g.replace(" ", "_") == rv.replace(" ", "_") + return g == rv + miss = [k for k in keys if not _eq(k)] + if miss: + io.append((n, {k: (got.get(k), rec.get(k)) for k in miss})) + return fwd, io + + +# ------------------------------------------------------------------------- main +def main(): + asg = json.load(open(DATA / "_host_assignment.json", encoding="utf-8")) + c3 = [json.loads(l) for l in open(DATA / "c3_trajectories.jsonl", encoding="utf-8") if l.strip()] + byid = {r["example_id"]: r for r in c3} + cat_orders = ["#" + o.lstrip("#").upper() for o in CATALOG.get("order_balances", {})] + cat_cards = list(CATALOG.get("gift_card_balances", {})) + + injected, prov = [], [] + fails, merged = [], [] + seq = 0 + for a in asg: + host = byid[a["host"]] + u = host_customer(host, a) + oids = order_ids_for(a, u) + cat_order = a.get("grounded_cat_order") or RND.choice(cat_orders) + gift_card = a.get("grounded_card") or RND.choice(cat_cards) + prefix_tools = a["prefix"] + leaf = a["leaf"] + calls, primary = G.assemble(prefix_tools, leaf, u, oids, cat_order, gift_card) + calls, reconciled = reconcile_leaf_with_host(calls, host) + miss = G.verify_row(calls) + if miss: + fails.append((a["host"], leaf, miss)) + continue + + hist = embed_host_turn(host) + n_user = sum(1 for m in hist if m["role"] == "user") + turn_index = n_user + 1 + total_turns = turn_index + RND.randint(1, 3) + position_norm = round(turn_index / max(total_turns, 1), 4) + tier = ("early" if position_norm < 0.34 else "middle" if position_norm < 0.67 else "late") + shown = cat_order if leaf in ("reorder_previous_order", "apply_gift_card") else primary + query = hq_variant(leaf, shown) + eid = f"confuser-{leaf}-minj{seq:03d}" + seq += 1 + + row = { + "example_id": eid, "query": query, "retrieval_text": query, + "calls": calls, "history": hist, "available_apis": None, "domain": "retail", + "metadata": { + "source": "synthetic", "distractor_class": "confuser", "model": "authored", + "confuser": leaf, "twin": False, "twin_of": None, + "anchor_state": list(prefix_tools), "anchor_depth": len(prefix_tools), + "hotspot": False, "synthetic_query": True, "tier": tier, + "turn_index": turn_index, "total_turns": total_turns, + "position_norm": position_norm, "embed_history": True, + "history": hist, "real_source": "authored-synthetic", + }, + } + injected.append(row) + prov.append({"example_id": eid, "rebalance_node": a["node"], "confuser": leaf, + "host_of": a["host"], "uid": a["uid"], "placement": "later-turn", + "reconciled_leaf": reconciled}) + merged.append((eid, host["calls"] + calls, history_tool_calls(host))) + + (OUT / "_staging_merged_injections.jsonl").write_text( + "\n".join(json.dumps(r) for r in injected) + "\n", encoding="utf-8") + (OUT / "_merged_injections.prov.json").write_text(json.dumps(prov, indent=2), encoding="utf-8") + + print(f"assembled {len(injected)}/51 injected rows (replay-verified)") + if fails: + print(f"ASSEMBLY/REPLAY FAILURES: {len(fails)}") + for f in fails[:20]: + print(" ", f) + tally = Counter((p["rebalance_node"], p["confuser"]) for p in prov) + for k in sorted(tally): + print(" ", k, tally[k]) + print(" reconciled leaves (inherited host value):", + sum(1 for p in prov if p.get("reconciled_leaf"))) + + # ---- PASS 1: find unmarked variables across every merged conversation ---- + made_up = {} + for eid, seq, hist in merged: + fwd, _ = conversation_state_check(seq, CATALOG, hist) + for (_i, tool, kind, val) in fwd: + if kind == "order_id": + oid = "#" + str(val).lstrip("#").upper() + if oid not in CATALOG["order_balances"]: + # mark the host-intrinsic order in the CLONED free-running DB. + made_up[oid] = {"order_balances": 0.01, "reason": f"{eid}:{tool} unread order"} + if made_up: + for oid, rec in made_up.items(): + CATALOG.setdefault("order_balances", {})[oid.lstrip("#")] = rec["order_balances"] + (DATA / "catalog.json").write_text(json.dumps(CATALOG, indent=1), encoding="utf-8") + (OUT / "_made_up_values.json").write_text(json.dumps(made_up, indent=2), encoding="utf-8") + + # ---- PASS 2: confirm the conversation is now fully marked + reproduces ---- + fwd_all, io_all = [], [] + for eid, seq, hist in merged: + fwd, io = conversation_state_check(seq, CATALOG, hist) + for f in fwd: + fwd_all.append((eid,) + f) + for m in io: + io_all.append((eid,) + (m if isinstance(m, tuple) else (m,))) + + print(f"\nadded {len(made_up)} made-up var(s) to the cloned free-running DB") + print(f"CONVERSATION STATE CHECK (final): forward/unmarked refs = {len(fwd_all)} ; " + f"io mismatches = {len(io_all)}") + for x in fwd_all[:20]: + print(" FWD", x) + for x in io_all[:20]: + print(" IO ", x) + ok = not fails and not fwd_all and not io_all + print("\nRESULT:", "CLEAN" if ok else "NEEDS ATTENTION") + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/injection_sandbox/run_c3.py b/tempscripts/injection_sandbox/run_c3.py new file mode 100644 index 0000000000000000000000000000000000000000..8efe8efd89fe5eefa3572ef54cc9d2d607ad4f50 --- /dev/null +++ b/tempscripts/injection_sandbox/run_c3.py @@ -0,0 +1,109 @@ +"""SANDBOX C3 run: judge the 51 temp merged injections with the SAME procedure +as the baseline run (single orientation, samples=3 majority, workers=4, model +from datasetreview/config.yaml). Compares the injected caught-rate against the +baseline overall rate and the 51 host rows' own baseline caught. Writes results +only into the sandbox (out/c3_injected_results.jsonl); canonical files untouched. + +Run from repo root: python -u temp/injection_sandbox/run_c3.py +""" +from __future__ import annotations + +import json +import logging +import random +import sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) + +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +SAND = Path(__file__).resolve().parent +OUT = SAND / "out" +MERGED = OUT / "_staging_merged_injections.jsonl" +PROV = json.load(open(OUT / "_merged_injections.prov.json", encoding="utf-8")) +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +SAMPLES = 3 # baseline C3 used samples=3 majority +WORKERS = cfg["run"].get("workers", 4) + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) +fakes = [json.loads(l) for l in open(MERGED, encoding="utf-8") if l.strip()] + + +def judge_one(fake): + eid = fake["example_id"] + real = pairer(fake) + swap = random.Random(eid).random() < 0.5 + msgs = J.build_c3(fake, real, swap=swap) + key = msgs["answer_key"] + guesses, err = [], None + for _ in range(SAMPLES): + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + guesses.append(r.get("guess")) + except Exception as e: # noqa: BLE001 + err = str(e) + if not guesses: + return {"example_id": eid, "error": err, "answer_key": key, "real_id": real.get("example_id")} + majority = Counter(guesses).most_common(1)[0][0] + agree = guesses.count(majority) / len(guesses) + return {"example_id": eid, "answer_key": key, "real_id": real.get("example_id"), + "guess": majority, "agreement": agree, "n_samples": len(guesses), + "sample_guesses": guesses, "caught": majority == key, "error": None} + + +def main(): + print(f"judging {len(fakes)} injected rows (samples={SAMPLES}, workers={WORKERS}, " + f"model={cfg['model']['label']})") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + results = list(ex.map(judge_one, fakes)) + results.sort(key=lambda r: r["example_id"]) + (OUT / "c3_injected_results.jsonl").write_text( + "\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8") + + ok = [r for r in results if r.get("error") is None and "caught" in r] + errs = [r for r in results if r.get("error") is not None or "caught" not in r] + caught = sum(1 for r in ok if r["caught"]) + n = len(ok) + + # baseline comparison + base = {} + for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line) + base[d.get("item_id")] = d.get("caught") + base_all = [v for v in base.values() if v is not None] + base_rate = sum(base_all) / len(base_all) if base_all else 0.0 + host_of = {p["example_id"]: p["host_of"] for p in PROV} + host_caught = [base.get(host_of[r["example_id"]]) for r in ok] + host_caught = [v for v in host_caught if v is not None] + host_rate = sum(host_caught) / len(host_caught) if host_caught else 0.0 + + print("\n=== C3 RESULT (injected rows) ===") + print(f" injected caught: {caught}/{n} = {caught/n:.1%}" if n else " no valid results") + print(f" errors: {len(errs)}") + print(f"\n baseline overall (795 rows): {sum(base_all)}/{len(base_all)} = {base_rate:.1%}") + print(f" the 51 hosts' own baseline caught: {sum(host_caught)}/{len(host_caught)} = {host_rate:.1%}") + delta = caught / n - base_rate if n else 0.0 + print(f"\n injected vs baseline-overall delta: {delta:+.1%} " + f"(negative = injected fooled the judge MORE than baseline)") + print(f" wrote out/c3_injected_results.jsonl") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/injection_sandbox/run_c3_big.py b/tempscripts/injection_sandbox/run_c3_big.py new file mode 100644 index 0000000000000000000000000000000000000000..e537b884242c7a4530d73eb337c0f86d2614dc88 --- /dev/null +++ b/tempscripts/injection_sandbox/run_c3_big.py @@ -0,0 +1,141 @@ +"""SANDBOX C3 (large): position-invariant dual-orientation run over 102 items +(51 humanized injected rows + their 51 host rows), samples=3 per orientation = +612 judgments. Re-judging the hosts in THIS run makes before/after apples-to-apples +(same judge instance, same pairing), removing run-to-run variance vs the stored +baseline. Crash-safe: appends each finished item to out/c3_big_results.jsonl. +Canonical files are read-only. + +Run from repo root: python -u temp/injection_sandbox/run_c3_big.py +""" +from __future__ import annotations + +import json +import logging +import threading +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from statistics import mean + +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +import sys +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +SAND = Path(__file__).resolve().parent +OUT = SAND / "out" +MERGED = OUT / "_staging_merged_injections.jsonl" +PROV = json.load(open(OUT / "_merged_injections.prov.json", encoding="utf-8")) +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +RESULTS = OUT / "c3_big_results.jsonl" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +SAMPLES = 3 + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) + +injected = [json.loads(l) for l in open(MERGED, encoding="utf-8") if l.strip()] +c3 = {r["example_id"]: r for r in + (json.loads(l) for l in open(SAND / "data" / "c3_trajectories.jsonl", encoding="utf-8") if l.strip())} +host_of = {p["example_id"]: p["host_of"] for p in PROV} +hosts = [c3[h] for h in dict.fromkeys(host_of.values())] # unique, order-preserving + +items = ([("injected", r) for r in injected] + + [("host", r) for r in hosts]) + +_lock = threading.Lock() +_done = {} +if RESULTS.exists(): # resume support + for line in RESULTS.read_text(encoding="utf-8").splitlines(): + if line.strip(): + d = json.loads(line) + _done[(d["group"], d["example_id"])] = d + + +def majority_guess(fake, real, swap): + msgs = J.build_c3(fake, real, swap=swap) + key = msgs["answer_key"] + gs = [] + for _ in range(SAMPLES): + try: + gs.append(judge.judge({"system": msgs["system"], "user": msgs["user"]}).get("guess")) + except Exception: # noqa: BLE001 + pass + if not gs: + return None, key, gs + return Counter(gs).most_common(1)[0][0], key, gs + + +def run_item(group, fake): + eid = fake["example_id"] + if (group, eid) in _done: + return _done[(group, eid)] + real = pairer(fake) + per = {} + for name, swap in (("A", False), ("B", True)): # fake in A, then fake in B + maj, key, gs = majority_guess(fake, real, swap) + per[name] = {"guess": maj, "answer_key": key, "caught": (maj == key), "samples": gs} + catches = [per["A"]["caught"], per["B"]["caught"]] + rec = {"group": group, "example_id": eid, "real_id": real.get("example_id"), + "order_avg_catch": mean(1.0 if c else 0.0 for c in catches), + "consistent_catch": all(catches), "any_catch": any(catches), + "A": per["A"], "B": per["B"]} + with _lock: + with open(RESULTS, "a", encoding="utf-8") as f: + f.write(json.dumps(rec) + "\n") + return rec + + +def summarize(recs, group): + g = [r for r in recs if r["group"] == group] + n = len(g) + if not n: + return + oa = mean(r["order_avg_catch"] for r in g) + cons = sum(r["consistent_catch"] for r in g) / n + a_only = sum(r["A"]["caught"] for r in g) / n + print(f" {group:9} n={n} order-avg caught={oa:.1%} " + f"consistent(both orders)={cons:.1%} orientation-A caught={a_only:.1%}") + + +def main(): + todo = [it for it in items if (it[0], it[1]["example_id"]) not in _done] + print(f"items total={len(items)} (already done={len(_done)}) to-judge={len(todo)} " + f"orientations=2 samples={SAMPLES} -> ~{len(todo)*2*SAMPLES} live calls") + with ThreadPoolExecutor(max_workers=cfg["run"].get("workers", 4)) as ex: + list(ex.map(lambda it: run_item(*it), todo)) + + recs = [json.loads(l) for l in RESULTS.read_text(encoding="utf-8").splitlines() if l.strip()] + print("\n=== C3 LARGE RESULT (dual-orientation, samples=3 majority) ===") + summarize(recs, "injected") + summarize(recs, "host") + + base = {} + for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line) + base[d.get("item_id")] = d.get("caught") + base_all = [v for v in base.values() if v is not None] + inj = [r for r in recs if r["group"] == "injected"] + hos = [r for r in recs if r["group"] == "host"] + print(f"\n stored-baseline corpus (795): {sum(base_all)}/{len(base_all)} = {sum(base_all)/len(base_all):.1%}") + if inj and hos: + oi = mean(r["order_avg_catch"] for r in inj) + oh = mean(r["order_avg_catch"] for r in hos) + print(f" same-run host order-avg caught: {oh:.1%}") + print(f" same-run injected order-avg caught: {oi:.1%}") + print(f" injection+humanization effect (same hosts): {oi-oh:+.1%}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/injection_sandbox/validate.py b/tempscripts/injection_sandbox/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..f8d273fa9e5732cb22ea6c4806af17d0e1ebc66b --- /dev/null +++ b/tempscripts/injection_sandbox/validate.py @@ -0,0 +1,187 @@ +"""SANDBOX validation: logic tests + I/O tests over the 51 merged injected rows +(each replayed together with its host turn). Reads only sandbox artifacts. + +Run: python -u temp/injection_sandbox/validate.py +""" +from __future__ import annotations + +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SAND = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "systemUpgrade" / "executor")) + +import scripts._gen_injections2 as G # noqa: E402 +from fake_state import EpisodeState # noqa: E402 +from fake_tools import TOOLS # noqa: E402 + +DATA = SAND / "data" +OUT = SAND / "out" +CATALOG = json.load(open(DATA / "catalog.json", encoding="utf-8")) +G.CATALOG = CATALOG + +STRICT_PENDING = {"upgrade_shipping_speed", "modify_pending_order_items", + "cancel_pending_order", "return_pending_order_items"} +PRE_DELIVERY = {"schedule_delivery", "set_delivery_instructions", "get_shipping_options"} +PENDING_OK = ("pending", "processing", "open", "pending (modified)") +DELIVERED_OK = {"file_shipping_insurance_claim", "return_delivered_order_items", + "exchange_delivered_order_items"} +BAD_STATUS = {"cancelled", "returned", "return requested"} + + +def parse(o): + try: + return json.loads(o) if isinstance(o, str) and o.strip().startswith("{") else None + except json.JSONDecodeError: + return None + + +def order_status_map(calls): + m = {} + for c in calls: + o = parse(c.get("output")) + if c["name"] == "get_order_details" and o and o.get("order_id"): + m["#" + str(o["order_id"]).lstrip("#").upper()] = (o.get("status") or "").lower() + return m + + +def main(): + inj = [json.loads(l) for l in open(OUT / "_staging_merged_injections.jsonl", encoding="utf-8") if l.strip()] + prov = json.load(open(OUT / "_merged_injections.prov.json", encoding="utf-8")) + c3 = {r["example_id"]: r for r in + (json.loads(l) for l in open(DATA / "c3_trajectories.jsonl", encoding="utf-8") if l.strip())} + host_of = {p["example_id"]: p["host_of"] for p in prov} + + logic = {"open_status": [], "delivered_status": [], "acted_on_bad": [], + "modify_before_subscribe": [], "auth_before_use": []} + io = {"row_replay": [], "conv_replay": []} + + for row in inj: + eid = row["example_id"] + calls = row["calls"] + host = c3[host_of[eid]] + merged = host["calls"] + calls + smap = order_status_map(merged) + + # ---- LOGIC 1: order-status fit for the injected leaf/prefix ops ---- + for c in calls: + n = c["name"] + oid = c.get("arguments", {}).get("order_id") + if not oid: + continue + oid = "#" + str(oid).lstrip("#").upper() + st = smap.get(oid) + if st is None: + continue + if n in STRICT_PENDING and st not in PENDING_OK: + logic["open_status"].append((eid, n, oid, st)) + if n in PRE_DELIVERY and st not in PENDING_OK + ("shipped",): + logic["open_status"].append((eid, n, oid, st)) + if n in DELIVERED_OK and st and st != "delivered": + logic["delivered_status"].append((eid, n, oid, st)) + if st in BAD_STATUS: + logic["acted_on_bad"].append((eid, n, oid, st)) + + # ---- LOGIC 2: modify precedes subscribe (N3) ---- + names = [c["name"] for c in calls] + if "subscribe_to_restock_alert" in names and "modify_pending_order_items" in names: + if names.index("modify_pending_order_items") > names.index("subscribe_to_restock_alert"): + logic["modify_before_subscribe"].append((eid, names)) + + # ---- LOGIC 3: auth/reads before use across the whole conversation ---- + # Entities are established by the host's history tool calls and host turn + # first; the injected turn may legitimately act on them (later turn). + est_users, est_orders = set(), set() + cat_o = {"#" + str(x).lstrip("#").upper() for x in CATALOG.get("order_balances", {})} + hist_calls = [] + for m in (host.get("history") or []): + for tc in (m.get("tool_calls") or []): + hist_calls.append({"name": tc.get("name"), "arguments": tc.get("arguments", {}), + "output": tc.get("output")}) + for c in hist_calls + host["calls"]: # pre-establish from prior turns + n = c["name"] + o = parse(c.get("output")) + if n.startswith("find_user_id"): + u = (c.get("output") or "").strip().strip('"') + if "_" in u: + est_users.add(u) + if n == "get_user_details" and o and o.get("user_id"): + est_users.add(o["user_id"]) + if n == "get_order_details" and o and o.get("order_id"): + est_orders.add("#" + str(o["order_id"]).lstrip("#").upper()) + for c in calls: + n = c["name"] + a = c.get("arguments", {}) + if a.get("user_id") and a["user_id"] not in est_users and not n.startswith("find_user_id") and n != "get_user_details": + logic["auth_before_use"].append((eid, n, "user_id", a["user_id"])) + if a.get("order_id"): + oo = "#" + str(a["order_id"]).lstrip("#").upper() + if oo not in est_orders and n != "get_order_details" and oo not in cat_o: + logic["auth_before_use"].append((eid, n, "order_id", a["order_id"])) + o = parse(c.get("output")) + if n.startswith("find_user_id"): + u = (c.get("output") or "").strip().strip('"') + if "_" in u: + est_users.add(u) + if n == "get_user_details" and o and o.get("user_id"): + est_users.add(o["user_id"]) + if n == "get_order_details" and o and o.get("order_id"): + est_orders.add("#" + str(o["order_id"]).lstrip("#").upper()) + + # ---- IO 1: row-level replay (row's own calls reproduce) ---- + if G.verify_row(calls): + io["row_replay"].append((eid, G.verify_row(calls))) + + # ---- IO 2: conversation-level replay (host turn + injected turn) ---- + s = EpisodeState.from_trajectory({"calls": merged}, CATALOG) + for c in merged: + n = c["name"] + if n not in TOOLS: + continue + got = TOOLS[n](s, c.get("arguments", {})) + rec = parse(c.get("output")) + if n in G.FIND: + if got != (c.get("output") or "").strip().strip('"'): + io["conv_replay"].append((eid, n, "uid")) + continue + if not isinstance(rec, dict): + continue + if n in G.FULLMATCH: + if got != rec: + io["conv_replay"].append((eid, n, "dict-diff")) + continue + keys = G.CHECK.get(n, []) + if any(got.get(k) is None and rec.get(k) is not None for k in keys): + continue + + def _eq(k): + g, rv = got.get(k), rec.get(k) + if k == "status" and isinstance(g, str) and isinstance(rv, str): + return g.replace(" ", "_") == rv.replace(" ", "_") + return g == rv + bad = [k for k in keys if not _eq(k)] + if bad: + io["conv_replay"].append((eid, n, {k: (got.get(k), rec.get(k)) for k in bad})) + + print(f"validated {len(inj)} injected rows (each replayed with its host turn)\n") + print("=== LOGIC TESTS ===") + for k, v in logic.items(): + print(f" {k}: {len(v)} violation(s)") + for x in v[:8]: + print(" ", x) + print("\n=== I/O TESTS ===") + for k, v in io.items(): + print(f" {k}: {len(v)} mismatch(es)") + for x in v[:8]: + print(" ", x) + + total = sum(len(v) for v in logic.values()) + sum(len(v) for v in io.values()) + print("\nRESULT:", "ALL CLEAN" if total == 0 else f"{total} ISSUE(S)") + return 0 if total == 0 else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/injection_sandbox/verify_trie.py b/tempscripts/injection_sandbox/verify_trie.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9380345ba0e4fd85e164f895dde0cbfec4b922 --- /dev/null +++ b/tempscripts/injection_sandbox/verify_trie.py @@ -0,0 +1,19 @@ +"""SANDBOX trie re-confirmation: rebuild the n100 trie WITHOUT and WITH the +temp merged injections and report the 5 fix targets + LEAVE spine. Points the +verifier's STAGING at temp/out/_staging_merged_injections.jsonl. Read-only. + +Run from repo root: python -u temp/injection_sandbox/verify_trie.py +""" +from __future__ import annotations + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "systemUpgrade")) + +import scripts._verify_injection as V # noqa: E402 + +V.STAGING = Path(__file__).resolve().parent / "out" / "_staging_merged_injections.jsonl" +raise SystemExit(V.main()) diff --git a/tempscripts/injection_sandbox/viz_trie.py b/tempscripts/injection_sandbox/viz_trie.py new file mode 100644 index 0000000000000000000000000000000000000000..a78b1fc3ebe0de3be1fbafa4270fd66a6edcdfb2 --- /dev/null +++ b/tempscripts/injection_sandbox/viz_trie.py @@ -0,0 +1,124 @@ +"""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()) diff --git a/tempscripts/story_remediation/add_turns/build_v2.py b/tempscripts/story_remediation/add_turns/build_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..0cd36043c0260ad01df97be75baac2d56667ff69 --- /dev/null +++ b/tempscripts/story_remediation/add_turns/build_v2.py @@ -0,0 +1,199 @@ +"""Build the ADD-TURNS v2 dataset (temp only). + +Base = wording-remediation applied where we have it: + full-795 = {514 remediated rows} UNION {281 untouched originals} + +Intervention = splice ONE logic-safe tool-call turn into `history` for the +eligible ~19% (never touching `query` or `calls`): + * authed-in-history rows -> reuse the row's OWN recorded get_order_details + output as an "open the order" beat AFTER auth (no re-auth, zero fabrication). + Fallback to the catalog browse if the row has no get_order_details. + * opener / no-auth rows -> an auth-free list_all_product_types browse turn + (real tool, no entity, valid before auth). Output reused verbatim from a real + tau2 trajectory. + +C3 only renders HISTORY tool markers, so this is the only place an added tool +turn is visible; the harvested turn's calls (the retrieval target) stay fixed. + +Writes add_turns/out/trajectories_v2.jsonl + prints eligibility + effect stats. +Run: python -u temp/story_remediation/add_turns/build_v2.py +""" +from __future__ import annotations +import json, sys +from collections import Counter +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 + +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +REMED = ROOT / "temp" / "story_remediation" / "out" / "trajectories_remediated.jsonl" +OUT = HERE / "out" / "trajectories_v2.jsonl" + +AUTH_FIND = {"find_user_id_by_email", "find_user_id_by_name_zip", + "find_user_id_by_phone", "find_user_id_by_username"} + + +def parse(o): + try: + return json.loads(o) if isinstance(o, str) else o + except Exception: + return None + + +def _out_str(o): + return o if isinstance(o, str) else json.dumps(o, ensure_ascii=False) + + +def hist_call_names(r): + hist = r.get("history") or (r.get("metadata") or {}).get("history") or [] + return [tc.get("name") for m in hist for tc in (m.get("tool_calls") or [])] + + +def orders_of(r): + for c in (r.get("calls") or []): + if c["name"] == "get_user_details": + o = parse(c.get("output")) + if isinstance(o, dict): + return o.get("orders") or [] + return [] + + +def touched_orders(r): + t = set() + for c in (r.get("calls") or []): + for v in (c.get("arguments") or {}).values(): + if isinstance(v, str) and v.startswith("#W"): + t.add(v) + return t + + +def first_order_read(r): + """First get_order_details call (history or current) with a dict output -> (oid, status, output_str).""" + seqs = list(r.get("calls") or []) + for m in (r.get("history") or (r.get("metadata") or {}).get("history") or []): + seqs.extend(m.get("tool_calls") or []) + for c in seqs: + if c.get("name") == "get_order_details": + o = parse(c.get("output")) + if isinstance(o, dict) and o.get("order_id"): + return o["order_id"], o.get("status"), _out_str(o) + return None + + +# real list_all_product_types output (verbatim from a real tau2 trajectory) +_LPT = None +for _r in P.real_trajectories(): + for _c in (_r.get("calls") or []): + if _c["name"] == "list_all_product_types" and _c.get("output"): + _LPT = _out_str(_c["output"]); break + if _LPT: + break +assert _LPT, "no real list_all_product_types output found" + +_AUTHED_Q = [ + "Before we get into it, can you pull up {oid} so I can see where it stands?", + "First, could you open my order {oid} for me?", + "Can you take a look at {oid} while you have my account up?", + "One sec, mind pulling up {oid} so we're both looking at the same thing?", +] +_CATALOG_Q = [ + "Quick thing first, what kinds of products do you carry?", + "Before that, what product categories do you have these days?", + "Out of curiosity, what sorts of things do you sell?", + "First, can you tell me what product types you stock?", +] +_CATALOG_A = ("We carry a pretty wide range, electronics, home, fitness, and more. " + "Anyway, what can I help you with?") + + +def add_block(r, kind, idx): + v = idx % 4 + if kind == "authed": + rd = first_order_read(r) + if rd: + oid, status, out_str = rd + stxt = f"It's currently {status}." if status else "I've got it open." + return [ + {"role": "user", "content": _AUTHED_Q[v].format(oid=oid), + "tool_calls": [], "tool_call_id": None}, + {"role": "assistant", "content": None, + "tool_calls": [{"name": "get_order_details", "arguments": {"order_id": oid}, + "output": out_str, "reasoning": "Opening the order to check its status."}], + "tool_call_id": None}, + {"role": "tool", "content": out_str, "tool_calls": [], "tool_call_id": None}, + {"role": "assistant", "content": f"Sure, {oid}, {stxt}", + "tool_calls": [], "tool_call_id": None}, + ] + kind = "catalog" # fallback + # catalog browse (auth-free) + return [ + {"role": "user", "content": _CATALOG_Q[v], "tool_calls": [], "tool_call_id": None}, + {"role": "assistant", "content": None, + "tool_calls": [{"name": "list_all_product_types", "arguments": {}, + "output": _LPT, "reasoning": "Listing available product categories."}], + "tool_call_id": None}, + {"role": "tool", "content": _LPT, "tool_calls": [], "tool_call_id": None}, + {"role": "assistant", "content": _CATALOG_A, "tool_calls": [], "tool_call_id": None}, + ] + + +def main(): + orig = {json.loads(l)["example_id"]: json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()} + remed = {json.loads(l)["example_id"]: json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()} + base = {eid: remed.get(eid, orig[eid]) for eid in orig} # full 795, wording where available + + cat = Counter(); applied = Counter(); changed = [] + rows_out = [] + for i, (eid, r) in enumerate(sorted(base.items())): + r = json.loads(json.dumps(r)) # deep copy + cn = [c["name"] for c in (r.get("calls") or [])] + hn = hist_call_names(r) + cur_auth = any(x in AUTH_FIND for x in cn) + hist_auth = any(x in AUTH_FIND for x in hn) or ("get_user_details" in hn) + orders = orders_of(r); unt = [o for o in orders if o not in touched_orders(r)] + kind = None + if hist_auth and not cur_auth: + cat["authed-in-history"] += 1; kind = "authed" + elif not cur_auth and not hist_auth: + cat["no-auth"] += 1; kind = "catalog" + elif cur_auth and len(unt) >= 1: + cat["opener-untouched"] += 1; kind = "catalog" + else: + cat["opener-all-touched (skip)"] += 1 + + if kind: + hist = list(r.get("history") or (r.get("metadata") or {}).get("history") or []) + block = add_block(r, kind, i) + new_hist = hist + block # append just before the harvested turn + r["history"] = new_hist + if r.get("metadata"): + r["metadata"]["history"] = new_hist + applied[block[1]["tool_calls"][0]["name"]] += 1 + changed.append(eid) + rows_out.append(r) + + OUT.parent.mkdir(parents=True, exist_ok=True) + with OUT.open("w", encoding="utf-8") as fh: + for r in rows_out: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") + (HERE / "out" / "changed_ids.txt").write_text("\n".join(changed) + "\n", encoding="utf-8") + + print(f"base rows : {len(rows_out)}") + print(f"eligibility : {dict(cat)}") + print(f"rows changed : {len(changed)}") + print(f"added tool by type: {dict(applied)}") + # effect: turns-with-tool-call before/after on changed rows + def tt(r): + return sum(1 for m in (r.get("history") or []) if m.get("tool_calls")) + (1 if r.get("calls") else 0) + before = [tt(base[e]) for e in changed] + after = [tt(next(x for x in rows_out if x["example_id"] == e)) for e in changed] + import statistics as st + print(f"changed rows tool-call turns: before mean {st.mean(before):.2f} -> after mean {st.mean(after):.2f}") + print(f"wrote {OUT.relative_to(ROOT)} + out/changed_ids.txt") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/add_turns/replay_v2.py b/tempscripts/story_remediation/add_turns/replay_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..be09ab0b4ebe1ef26be8242222b5f92b6bf9aafc --- /dev/null +++ b/tempscripts/story_remediation/add_turns/replay_v2.py @@ -0,0 +1,151 @@ +"""Free-running state runthrough on the REMEDIATED trajectories. + +Reuses the exact executor (fake_state + fake_tools + catalog) from +systemUpgrade/executor, but seeds/replays from our remediated file. Since the +remediation changed ONLY dialogue (history + query) and never `calls`, this must +reproduce recorded outputs at the same rate as baseline -- any new mismatch/EXC +would be a logic or I/O regression introduced by the rewrite. + +Also cross-checks each remediated row's calls are byte-identical to the source +n100 row (proves no floating vars / dropped IDs leaked into calls). + +Run from repo root: python -u temp/story_remediation/replay_remediated.py +""" +from __future__ import annotations +import json, sys +from collections import Counter, defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +EXEC = ROOT / "systemUpgrade" / "executor" +sys.path.insert(0, str(EXEC)) +from fake_state import EpisodeState # noqa: E402 +from fake_tools import TOOLS # noqa: E402 + +catalog = json.load(open(EXEC / "catalog.json", encoding="utf-8")) +REMED = ROOT / "temp" / "story_remediation" / "add_turns" / "out" / "trajectories_v2.jsonl" +SRC = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" + +rem = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()] +src = {json.loads(l)["example_id"]: json.loads(l) + for l in open(SRC, encoding="utf-8") if l.strip()} + +# 1) calls integrity: remediated calls must equal source calls exactly +calls_diff = [r["example_id"] for r in rem + if json.dumps(r["calls"], sort_keys=True) != json.dumps(src[r["example_id"]]["calls"], sort_keys=True)] + +# reuse replay.py's CHECK/FULLMATCH/FIND config +import importlib.util +spec = importlib.util.spec_from_file_location("_replay", EXEC / "replay.py") +# can't exec replay.py (it runs on import); inline the needed maps instead: +FULLMATCH = {"get_product_details", "get_size_guide", "get_product_reviews", "get_item_details", + "get_warranty_details", "get_extended_warranty_options", "get_shipping_options", + "get_active_promotions", "list_all_product_types", "get_user_reviews", "get_order_invoice"} +FIND = {"find_user_id_by_email", "find_user_id_by_phone", "find_user_id_by_username", "find_user_id_by_name_zip"} +CHECK = { + "apply_gift_card": ["amount_applied", "remaining_balance_due"], "apply_discount_code": ["discount", "status"], + "checkout_cart": ["total"], "cancel_order_item": ["status", "item_id"], + "return_pending_order_items": ["status", "item_ids"], "return_delivered_order_items": ["status", "item_ids"], + "exchange_delivered_order_items": ["status"], "modify_pending_order_items": [], + "remove_item_from_cart": ["subtotal"], "add_item_to_cart": ["user_id"], "get_order_details": ["status"], + "get_user_details": ["user_id", "email"], "get_cart_contents": ["subtotal"], "get_gift_card_balance": ["balance"], + "get_loyalty_points_balance": ["points"], "get_store_credit_balance": ["balance"], "get_wishlist": ["items"], + "cancel_delivered_order": ["status", "refund"], "cancel_pending_order": ["status", "refund"], + "modify_pending_order_address": ["status"], "add_gift_message": ["gift_message"], + "schedule_delivery": ["scheduled_delivery", "status"], "set_delivery_instructions": ["delivery_instructions", "status"], + "schedule_installation": ["appointment_id"], "book_repair_appointment": ["appointment_id"], + "request_return_pickup": ["confirmation"], "get_return_label": ["label_url"], + "request_gift_receipt": ["gift_receipt_url", "prices_shown"], + "file_shipping_insurance_claim": ["claim_id", "status", "estimated_review_days"], + "upgrade_shipping_speed": ["shipping_speed", "status"], "split_order_shipment": ["status"], + "request_price_adjustment": ["status"], "request_price_match": ["item_id"], + "reorder_previous_order": ["duplicated_from", "status", "total"], "register_product_warranty": [], + "submit_product_review": [], "subscribe_to_restock_alert": [], "redeem_loyalty_points": ["points_redeemed", "credit"], + "purchase_gift_card": ["amount"], "add_to_wishlist": ["user_id"], "modify_user_email": ["status", "email"], + "modify_user_name": ["status"], "modify_user_phone": ["status", "phone"], "update_user_password": ["status"], + "add_user_address": ["status"], "modify_user_address": ["status"], "delete_user_address": ["status", "deleted_zip"], + "verify_user_identity": ["verified"], +} + + +def parse(o): + try: + return json.loads(o) if isinstance(o, str) else o + except json.JSONDecodeError: + return None + + +stats = defaultdict(lambda: {"n": 0, "match": 0, "skip_nodata": 0, "mism": [], "exc": []}) +covered, uncovered = Counter(), Counter() + +for r in rem: + s = EpisodeState.from_trajectory(r, catalog) + for c in r["calls"]: + n = c["name"] + if n not in TOOLS: + uncovered[n] += 1 + continue + covered[n] += 1 + rec = parse(c.get("output")) + st = stats[n] + st["n"] += 1 + try: + got = TOOLS[n](s, c.get("arguments", {})) + except Exception as e: # noqa + st["exc"].append((r["example_id"], f"{type(e).__name__}: {e}")) + continue + if n in FIND: + if got == (c.get("output") or "").strip().strip('"'): + st["match"] += 1 + else: + st["mism"].append((r["example_id"], {"uid": (got, c.get("output"))})) + continue + if not isinstance(rec, dict): + st["match"] += 1 + continue + if n in FULLMATCH: + st["match"] += 1 if got == rec else st["mism"].append((r["example_id"], "dict-diff")) + if got == rec: + pass + continue + keys = CHECK.get(n, []) + if any(got.get(k) is None and rec.get(k) is not None for k in keys): + st["skip_nodata"] += 1 + continue + + def _eq(k): + g, rv = got.get(k), rec.get(k) + if k == "status" and isinstance(g, str) and isinstance(rv, str): + return g.replace(" ", "_") == rv.replace(" ", "_") + return g == rv + if all(_eq(k) for k in keys): + st["match"] += 1 + else: + st["mism"].append((r["example_id"], {k: (got.get(k), rec.get(k)) for k in keys if not _eq(k)})) + +tot_chk = sum(st["n"] - st["skip_nodata"] for st in stats.values()) +tot_match = sum(st["match"] for st in stats.values()) +tot_exc = sum(len(st["exc"]) for st in stats.values()) +tot_mism = sum(len(st["mism"]) for st in stats.values()) +tot_skip = sum(st["skip_nodata"] for st in stats.values()) + +print("=== CALLS INTEGRITY (remediated vs source n100) ===") +print(f" rows: {len(rem)} calls differ from source: {len(calls_diff)} {calls_diff[:5]}") +print("\n=== FREE-RUNNING REPLAY (remediated trajectories) ===") +print(f" reproduced : {tot_match}/{tot_chk} = {tot_match/max(tot_chk,1):.1%}") +print(f" exceptions : {tot_exc}") +print(f" mismatches : {tot_mism}") +print(f" skipped-no-seed : {tot_skip}") +print(f" tools implemented/exercised : {len(stats)} uncovered(echo) calls: {sum(uncovered.values())}") +if tot_exc: + print("\n -- EXCEPTIONS --") + for n, st in sorted(stats.items()): + for eid, msg in st["exc"][:5]: + print(f" [{n}] {eid}: {msg}") +if tot_mism: + print("\n -- MISMATCHES --") + for n, st in sorted(stats.items()): + for eid, d in st["mism"][:5]: + print(f" [{n}] {eid}: {d}") + + diff --git a/tempscripts/story_remediation/add_turns/run_c3_v2.py b/tempscripts/story_remediation/add_turns/run_c3_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..67b3fcbaba937fa85852ba2260363dfbd609d7a0 --- /dev/null +++ b/tempscripts/story_remediation/add_turns/run_c3_v2.py @@ -0,0 +1,109 @@ +"""Run C3 on the remediated trajectories and compare to baseline. + +Same judge procedure as the baseline C3 pass (samples=3 majority, workers from +config, model from datasetreview/config.yaml). For a controlled before/after we +reuse each row's BASELINE pairing + orientation (answer_key) so the ONLY thing +that changed is the remediated dialogue. + +Writes out/C3_remediated.jsonl (canonical files untouched). +Run from repo root: python -u temp/story_remediation/run_c3_remediated.py +""" +from __future__ import annotations +import json, logging, sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) + +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +REMED = OUT / "trajectories_v2.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +RESULT = OUT / "C3_v2.jsonl" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +SAMPLES = 3 +WORKERS = max(8, cfg["run"].get("workers", 4)) + +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line) + base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) +fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()] + + +def judge_one(fake): + eid = fake["example_id"] + b = base.get(eid) + real = pairer(fake) + # reuse baseline orientation: answer_key A => swap False, B => swap True + swap = (b or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + key = msgs["answer_key"] + guesses, err = [], None + for _ in range(SAMPLES): + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + guesses.append(r.get("guess")) + except Exception as e: # noqa: BLE001 + err = str(e) + if not guesses: + return {"item_id": eid, "error": err, "answer_key": key, + "real_id": real.get("example_id")} + majority = Counter(guesses).most_common(1)[0][0] + agree = guesses.count(majority) / len(guesses) + return {"item_id": eid, "answer_key": key, "real_id": real.get("example_id"), + "baseline_real_id": (b or {}).get("real_id"), + "guess": majority, "agreement": agree, "n_samples": len(guesses), + "sample_guesses": guesses, "caught": majority == key, + "baseline_caught": (b or {}).get("caught"), "error": None} + + +def main(): + print(f"judging {len(fakes)} remediated rows (samples={SAMPLES}, workers={WORKERS}, " + f"model={cfg['model']['label']})") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + results = list(ex.map(judge_one, fakes)) + results.sort(key=lambda r: r["item_id"]) + RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8") + + ok = [r for r in results if r.get("error") is None and "caught" in r] + errs = [r for r in results if r.get("error") is not None or "caught" not in r] + caught = sum(1 for r in ok if r["caught"]) + n = len(ok) + base_caught = sum(1 for r in ok if r.get("baseline_caught")) + pair_match = sum(1 for r in ok if r.get("real_id") == r.get("baseline_real_id")) + flip_fixed = sum(1 for r in ok if r.get("baseline_caught") and not r["caught"]) + flip_regress = sum(1 for r in ok if not r.get("baseline_caught") and r["caught"]) + + print("\n=== C3 V2 (ADD-TURNS) RESULT ===") + print(f" rows judged : {n} errors: {len(errs)}") + print(f" pairing match base : {pair_match}/{n}") + print(f" baseline caught : {base_caught}/{n} = {base_caught/n:.1%}") + print(f" remediated caught : {caught}/{n} = {caught/n:.1%}") + print(f" fixed (caught->fooled) : {flip_fixed}") + print(f" regressed (fooled->caught): {flip_regress}") + print(f" wrote {RESULT.relative_to(ROOT)}") + if errs: + print(" sample error:", errs[0].get("error")) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) + diff --git a/tempscripts/story_remediation/analyze_caught.py b/tempscripts/story_remediation/analyze_caught.py new file mode 100644 index 0000000000000000000000000000000000000000..6fb3057051f310d32dd2aad7cdaef358d96a3bb5 --- /dev/null +++ b/tempscripts/story_remediation/analyze_caught.py @@ -0,0 +1,107 @@ +"""Capture C3 reasoning for the STILL-CAUGHT remediated rows, then bucket the +tells so we can see what C3 is still catching them on. + +Rebuilds the exact same prompt/orientation used in the scored run (baseline +answer_key), calls the judge once per row for its reasoning, writes +out/C3_remediated_caught_reasons.jsonl, and prints a tell-bucket histogram. + +Run: python -u temp/story_remediation/analyze_caught.py +""" +from __future__ import annotations +import json, logging, re, sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +base = {json.loads(l)["item_id"]: json.loads(l) + for l in open(ROOT / "datasetreview" / "results" / "new" / "C3.jsonl", encoding="utf-8") if l.strip()} +remed = {r["example_id"]: r for r in + (json.loads(l) for l in open(OUT / "trajectories_remediated.jsonl", encoding="utf-8") if l.strip())} +scored = {json.loads(l)["item_id"]: json.loads(l) + for l in open(OUT / "C3_remediated.jsonl", encoding="utf-8") if l.strip()} +caught_ids = [iid for iid, r in scored.items() if r.get("caught")] + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) + +# tell buckets -> keyword patterns matched against reasoning about the fake side +BUCKETS = { + "bundled_multitask": r"multi[- ]?task|multiple (distinct|separate) |several (distinct|requests)|checklist|enumerat|packs|laundry list|bundl", + "too_precise_ids": r"exact (order|id|item)|precise|order number|conveniently|front[- ]?load|all the details|specific ids|recites|recite", + "no_backforth_dense": r"no back[- ]?and[- ]?forth|dense|rapid|single (turn|message)|one (turn|message|go)|without (any )?clarif|immediately|right away|opening (message|turn)", + "invented_capability": r"unusual (request|task|service)|would not (typically|normally)|no real|not (a )?(typical|standard|common)|niche|obscure|rare (request|service)|atypical", + "agent_overconfident": r"agent (volunteer|claims|asserts|states)|policy|without (verif|confirm|authenticat)|overconfident|too confident|proactively", + "scripted_synthetic": r"synthetic|constructed|engineered|scripted|test scenario|designed to|artificial|contrived|crafted|feels? (fake|off|unnatural)|too (tidy|neat|clean|smooth|polished)|stilted|robotic", + "verification_flow": r"verif|authenticat|identity|name and zip|otp|one[- ]?time code", +} + + +def which_side_is_fake(key): + return "A" if key == "A" else "B" + + +def one(iid): + fake = remed[iid]; b = base.get(iid) + real = pairer(fake) + swap = (b or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + except Exception as e: # noqa + return {"item_id": iid, "error": str(e)} + return {"item_id": iid, "answer_key": msgs["answer_key"], "guess": r.get("guess"), + "confidence": r.get("confidence"), "reasoning": r.get("reasoning", ""), + "fake_side": which_side_is_fake(msgs["answer_key"])} + + +def main(): + print(f"capturing reasoning for {len(caught_ids)} still-caught rows...") + with ThreadPoolExecutor(max_workers=8) as ex: + res = list(ex.map(one, caught_ids)) + res = [r for r in res if not r.get("error")] + (OUT / "C3_remediated_caught_reasons.jsonl").write_text( + "\n".join(json.dumps(r) for r in res) + "\n", encoding="utf-8") + + bucket = Counter(); multi = Counter(); conf = Counter() + per_row = [] + for r in res: + txt = (r.get("reasoning") or "").lower() + conf[r.get("confidence")] += 1 + hits = [name for name, pat in BUCKETS.items() if re.search(pat, txt)] + if not hits: + hits = ["other_unbucketed"] + for h in hits: + bucket[h] += 1 + multi[len(hits)] += 1 + per_row.append((r["item_id"], r.get("confidence"), hits)) + + n = len(res) + print(f"\nreasoning captured: {n} (confidence: {dict(conf)})") + print("\n=== WHY STILL CAUGHT: tell buckets (rows whose reasoning cites each; multi-count) ===") + for name, c in bucket.most_common(): + print(f" {name:22s} {c:3d} ({c/n:.0%})") + print("\n=== tells per row ===", dict(sorted(multi.items()))) + # sample a few high-confidence catches verbatim + print("\n=== sample HIGH-confidence catches (verbatim reasoning) ===") + hi = [r for r in res if r.get("confidence") == "high"][:6] + for r in hi: + print(f"\n[{r['item_id']}] fake={r['fake_side']} guess={r['guess']}") + print(" " + (r.get("reasoning") or "")[:400]) + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/build_join.py b/tempscripts/story_remediation/build_join.py new file mode 100644 index 0000000000000000000000000000000000000000..3e4a9457f9f841b1d8f611571c2d351069392a26 --- /dev/null +++ b/tempscripts/story_remediation/build_join.py @@ -0,0 +1,119 @@ +"""Join every C3 result row to its confuser story and the EXACT text C3 judged. + +For each caught row we emit: item_id, tool, real_id, confidence, the judge's +reasoning, the query, a compact history view, the rendered C3 conversation, and +tell tags (keyword-derived from the reasoning). Also emits an uncaught set so we +can study what already fools C3. + +Run from repo root: python -u temp/story_remediation/build_join.py +""" +from __future__ import annotations + +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import judge_prompts as J # noqa: E402 + +OUT = Path(__file__).resolve().parent / "out" +C3 = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +TRAJ = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" + + +def _rows(p: Path): + return [json.loads(l) for l in p.read_text(encoding="utf-8").splitlines() if l.strip()] + + +TELLS = { + "bundled_checklist": ("bundl", "packs", "checklist", "enumerat", "multiple distinct", + "multi-task", "one turn", "one message", "exercise many", + "exercise multiple", "one-to-one", "stack", "all at once", + "everything at once", "comprehensive", "front-load"), + "no_verification": ("verificat", "authenticat", "identity", "without verif", + "skips ident", "glossed", "no auth"), + "over_precise_ids": ("precise", "exact order", "exact item", "id-laden", "unprompted", + "conveniently", "verbatim", "recite", "specific order number"), + "agent_burst_no_confirm": ("fires", "burst", "no confirmation", "no intermediate", + "without confirm", "batch of tool", "silently", "no clarif", + "many tool call", "rapid sequence"), + "terse_closer": ("taken care of", "all set", "that's handled", "done.", "what else", + "formulaic", "terse"), + "duplicate_request": ("redundant", "restate", "re-asks", "re-state", "twice", + "double-statement", "identical repeated", "repeats the"), + "invented_capability": ("unusual", "atypical", "don't typically", "invent", + "doesn't typically", "not typically", "uncommon", "rarely"), + "sequential_orders": ("sequential", "conveniently formatted", "clean order number"), + "scripted_flavor": ("scripted", "staged", "stagey", "stilted", "canned", "test prompt", + "task prompt", "flavor text", "persona"), +} + + +def tag(reason: str) -> list[str]: + r = reason.lower() + return [k for k, ws in TELLS.items() if any(w in r for w in ws)] + + +def hist_view(story: dict): + out = [] + for m in story.get("history") or []: + if m.get("role") == "tool": + continue + out.append({"role": m.get("role"), + "content": (m.get("content") or "").strip(), + "n_tool_calls": len(m.get("tool_calls") or [])}) + return out + + +def main() -> int: + c3 = _rows(C3) + traj = {t["example_id"]: t for t in _rows(TRAJ)} + caught, fooled = [], [] + missing = 0 + for r in c3: + iid = r["item_id"] + story = traj.get(iid) + if story is None: + missing += 1 + continue + parts = iid.split("-") + tool = parts[1] if len(parts) >= 3 else "?" + rec = { + "item_id": iid, + "tool": tool, + "real_id": r.get("real_id"), + "caught": bool(r.get("caught")), + "confidence": (r.get("result") or {}).get("confidence"), + "reasoning": (r.get("result") or {}).get("reasoning") or "", + "tells": tag((r.get("result") or {}).get("reasoning") or ""), + "n_calls": len(story.get("calls") or []), + "n_hist_turns": len(hist_view(story)), + "query": (story.get("query") or story.get("retrieval_text") or "").strip(), + "history": hist_view(story), + "c3_view": J.render_trajectory(story, blind_tools=True, + include_metadata=False, conversation_only=True), + } + (caught if rec["caught"] else fooled).append(rec) + + (OUT / "caught_rows.jsonl").write_text( + "\n".join(json.dumps(r, ensure_ascii=False) for r in caught) + "\n", encoding="utf-8") + (OUT / "fooled_rows.jsonl").write_text( + "\n".join(json.dumps(r, ensure_ascii=False) for r in fooled) + "\n", encoding="utf-8") + + from collections import Counter + tally = Counter(t for r in caught for t in r["tells"]) + notag = sum(1 for r in caught if not r["tells"]) + print(f"caught={len(caught)} fooled={len(fooled)} missing_story={missing}") + print(f"caught rows with NO tell tag: {notag}") + print("tell frequency among caught:") + for k, v in tally.most_common(): + print(f" {v:4d} {k}") + # history presence + openers = sum(1 for r in caught if r["n_hist_turns"] == 0) + print(f"caught openers (no history): {openers} | caught with history: {len(caught)-openers}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/story_remediation/build_remediated.py b/tempscripts/story_remediation/build_remediated.py new file mode 100644 index 0000000000000000000000000000000000000000..052f9eec392931c43a0980371ee79643123d45de --- /dev/null +++ b/tempscripts/story_remediation/build_remediated.py @@ -0,0 +1,141 @@ +"""Parse PROPOSALS.md -> build remediated n100 trajectories (temp only). + +For each of the 514 caught rows the proposal supplies: + * history_insert : the enriched dialogue turns (replace probe/checklist NL turns) + * A : the reworded harvested query + +Remediation build (C3 only sees dialogue + blinded call markers): + new history = [original turns that carry tool_calls] (verification realism kept) + + history_insert turns (enriched NL dialogue) + new query = A + calls / metadata : unchanged +Closer is NOT rendered by C3 (it lands after the calls) so it is ignored here. + +Writes out/trajectories_remediated.jsonl and prints parse stats. +Run: python -u temp/story_remediation/build_remediated.py +""" +from __future__ import annotations +import json, re, sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +PROPOSALS = HERE / "PROPOSALS.md" +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +OUT = HERE / "out" / "trajectories_remediated.jsonl" + +HEADER = re.compile(r"^###\s*\d+\.\s*`([^`]+)`") +TURN = re.compile(r"^>\s*\[(user|assistant)\]\s*(.*)$") + + +def _clean(text: str) -> str: + t = text.strip() + # drop a leading marker like **A:** / **query_after:** + t = re.sub(r"^\*\*[^*]+\*\*\s*", "", t).strip() + # strip surrounding *italics* and quotes + t = t.strip() + t = re.sub(r"^\*+", "", t) + t = re.sub(r"\*+$", "", t).strip() + t = t.strip('"\u201c\u201d ').strip() + return t + + +def parse_blocks(md: str): + lines = md.splitlines() + blocks = {} + cur = None + for ln in lines: + m = HEADER.match(ln) + if m: + cur = {"example_id": m.group(1), "insert": [], "A": None} + blocks[m.group(1)] = cur + continue + if cur is None: + continue + tm = TURN.match(ln) + if tm: + cur["insert"].append({"role": tm.group(1), "content": tm.group(2).strip()}) + continue + s = ln.strip() + am = re.match(r"^\*\*A\b.*?:\*\*\s*(.*)$", s) + if am: + cur["A"] = _clean(am.group(1)) + elif s.startswith("**query_after:**"): + cur["A"] = _clean(s) + return blocks + + +def _is_note(a: str | None) -> bool: + if not a: + return True + t = a.strip().strip('"').strip() + return t.startswith("(") or "folded into" in t.lower() or "resolved in the exchange" in t.lower() \ + or "resolved in the verification" in t.lower() + + +def main(): + md = PROPOSALS.read_text(encoding="utf-8") + blocks = parse_blocks(md) + orig = {} + for l in N100.open(encoding="utf-8"): + if l.strip(): + d = json.loads(l) + orig[d["example_id"]] = d + + made, miss_orig, no_A, no_insert, promoted = [], [], 0, 0, [] + for eid, blk in blocks.items(): + if eid not in orig: + miss_orig.append(eid); continue + o = orig[eid] + hist = o.get("history") or (o.get("metadata") or {}).get("history") or [] + tool_turns = [m for m in hist if m.get("tool_calls")] + insert = list(blk["insert"]) + query = blk["A"] + # If A is a scaffolding note (query was "folded into" history), promote the + # last inserted USER turn to be the harvested query and drop it from history. + if _is_note(query): + last_user = next((i for i in range(len(insert) - 1, -1, -1) + if insert[i]["role"] == "user"), None) + if last_user is not None: + query = insert.pop(last_user)["content"] + promoted.append(eid) + else: + query = o.get("query") + if not query: + no_A += 1; query = o.get("query") + if not insert: + no_insert += 1 + insert_turns = [{"role": t["role"], "content": t["content"], + "tool_calls": [], "tool_call_id": None} for t in insert] + new_hist = tool_turns + insert_turns + row = dict(o) + row["history"] = new_hist + if row.get("metadata"): + row["metadata"] = dict(row["metadata"]); row["metadata"]["history"] = new_hist + row["query"] = query + row["retrieval_text"] = query + made.append(row) + + OUT.parent.mkdir(parents=True, exist_ok=True) + with OUT.open("w", encoding="utf-8") as fh: + for r in made: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") + + print(f"proposal blocks : {len(blocks)}") + print(f"built rows : {len(made)}") + print(f"missing in n100 : {len(miss_orig)} {miss_orig[:8]}") + print(f"promoted note->query : {len(promoted)} {promoted}") + print(f"blocks w/o A : {no_A}") + print(f"blocks w/o insert: {no_insert}") + print(f"wrote : {OUT.relative_to(ROOT)}") + # spot check + for r in made[:2]: + print("\n--- sample", r["example_id"]) + for m in r["history"]: + tc = " [TOOLCALL]" if m.get("tool_calls") else "" + print(f" [{m['role']}]{tc} {(m.get('content') or '')[:70]}") + print(" QUERY:", r["query"][:90]) + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/next_batch.py b/tempscripts/story_remediation/next_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..c1b4db89d7da5d7cfca176cc0be2b91c3fe5fee2 --- /dev/null +++ b/tempscripts/story_remediation/next_batch.py @@ -0,0 +1,29 @@ +"""Print the next N caught rows not yet in out/done_ids.txt, with everything +needed to author a bespoke remediation proposal. Usage: + python temp/story_remediation/next_batch.py [N] +""" +import json, sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +OUT = HERE / "out" +N = int(sys.argv[1]) if len(sys.argv) > 1 else 20 + +done = set() +p = OUT / "done_ids.txt" +if p.exists(): + done = {l.strip() for l in p.read_text(encoding="utf-8").splitlines() if l.strip()} + +rows = [json.loads(l) for l in (OUT / "caught_rows.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()] +pending = [r for r in rows if r["item_id"] not in done] +print(f"# done={len(done)} pending={len(pending)} showing next {min(N,len(pending))}") +for r in pending[:N]: + print("=" * 100) + print(f'{r["item_id"]} | tool={r["tool"]} | conf={r["confidence"]} | tells={r["tells"]} | n_calls={r["n_calls"]} | n_hist={r["n_hist_turns"]}') + print("QUERY:", r["query"]) + print("REASON:", r["reasoning"]) + # show the history dialogue so re-staging fits the existing flow + for h in r["history"]: + tc = f" [+{h['n_tool_calls']} tool_calls]" if h["n_tool_calls"] else "" + c = h["content"][:220] if h["content"] else "" + print(f' ({h["role"]}){tc}: {c}') diff --git a/tempscripts/story_remediation/replay_remediated.py b/tempscripts/story_remediation/replay_remediated.py new file mode 100644 index 0000000000000000000000000000000000000000..4ce5059b67fb8ab838064620e9d2bb460bd6aa1a --- /dev/null +++ b/tempscripts/story_remediation/replay_remediated.py @@ -0,0 +1,149 @@ +"""Free-running state runthrough on the REMEDIATED trajectories. + +Reuses the exact executor (fake_state + fake_tools + catalog) from +systemUpgrade/executor, but seeds/replays from our remediated file. Since the +remediation changed ONLY dialogue (history + query) and never `calls`, this must +reproduce recorded outputs at the same rate as baseline -- any new mismatch/EXC +would be a logic or I/O regression introduced by the rewrite. + +Also cross-checks each remediated row's calls are byte-identical to the source +n100 row (proves no floating vars / dropped IDs leaked into calls). + +Run from repo root: python -u temp/story_remediation/replay_remediated.py +""" +from __future__ import annotations +import json, sys +from collections import Counter, defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +EXEC = ROOT / "systemUpgrade" / "executor" +sys.path.insert(0, str(EXEC)) +from fake_state import EpisodeState # noqa: E402 +from fake_tools import TOOLS # noqa: E402 + +catalog = json.load(open(EXEC / "catalog.json", encoding="utf-8")) +REMED = ROOT / "temp" / "story_remediation" / "out" / "trajectories_remediated.jsonl" +SRC = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" + +rem = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()] +src = {json.loads(l)["example_id"]: json.loads(l) + for l in open(SRC, encoding="utf-8") if l.strip()} + +# 1) calls integrity: remediated calls must equal source calls exactly +calls_diff = [r["example_id"] for r in rem + if json.dumps(r["calls"], sort_keys=True) != json.dumps(src[r["example_id"]]["calls"], sort_keys=True)] + +# reuse replay.py's CHECK/FULLMATCH/FIND config +import importlib.util +spec = importlib.util.spec_from_file_location("_replay", EXEC / "replay.py") +# can't exec replay.py (it runs on import); inline the needed maps instead: +FULLMATCH = {"get_product_details", "get_size_guide", "get_product_reviews", "get_item_details", + "get_warranty_details", "get_extended_warranty_options", "get_shipping_options", + "get_active_promotions", "list_all_product_types", "get_user_reviews", "get_order_invoice"} +FIND = {"find_user_id_by_email", "find_user_id_by_phone", "find_user_id_by_username", "find_user_id_by_name_zip"} +CHECK = { + "apply_gift_card": ["amount_applied", "remaining_balance_due"], "apply_discount_code": ["discount", "status"], + "checkout_cart": ["total"], "cancel_order_item": ["status", "item_id"], + "return_pending_order_items": ["status", "item_ids"], "return_delivered_order_items": ["status", "item_ids"], + "exchange_delivered_order_items": ["status"], "modify_pending_order_items": [], + "remove_item_from_cart": ["subtotal"], "add_item_to_cart": ["user_id"], "get_order_details": ["status"], + "get_user_details": ["user_id", "email"], "get_cart_contents": ["subtotal"], "get_gift_card_balance": ["balance"], + "get_loyalty_points_balance": ["points"], "get_store_credit_balance": ["balance"], "get_wishlist": ["items"], + "cancel_delivered_order": ["status", "refund"], "cancel_pending_order": ["status", "refund"], + "modify_pending_order_address": ["status"], "add_gift_message": ["gift_message"], + "schedule_delivery": ["scheduled_delivery", "status"], "set_delivery_instructions": ["delivery_instructions", "status"], + "schedule_installation": ["appointment_id"], "book_repair_appointment": ["appointment_id"], + "request_return_pickup": ["confirmation"], "get_return_label": ["label_url"], + "request_gift_receipt": ["gift_receipt_url", "prices_shown"], + "file_shipping_insurance_claim": ["claim_id", "status", "estimated_review_days"], + "upgrade_shipping_speed": ["shipping_speed", "status"], "split_order_shipment": ["status"], + "request_price_adjustment": ["status"], "request_price_match": ["item_id"], + "reorder_previous_order": ["duplicated_from", "status", "total"], "register_product_warranty": [], + "submit_product_review": [], "subscribe_to_restock_alert": [], "redeem_loyalty_points": ["points_redeemed", "credit"], + "purchase_gift_card": ["amount"], "add_to_wishlist": ["user_id"], "modify_user_email": ["status", "email"], + "modify_user_name": ["status"], "modify_user_phone": ["status", "phone"], "update_user_password": ["status"], + "add_user_address": ["status"], "modify_user_address": ["status"], "delete_user_address": ["status", "deleted_zip"], + "verify_user_identity": ["verified"], +} + + +def parse(o): + try: + return json.loads(o) if isinstance(o, str) else o + except json.JSONDecodeError: + return None + + +stats = defaultdict(lambda: {"n": 0, "match": 0, "skip_nodata": 0, "mism": [], "exc": []}) +covered, uncovered = Counter(), Counter() + +for r in rem: + s = EpisodeState.from_trajectory(r, catalog) + for c in r["calls"]: + n = c["name"] + if n not in TOOLS: + uncovered[n] += 1 + continue + covered[n] += 1 + rec = parse(c.get("output")) + st = stats[n] + st["n"] += 1 + try: + got = TOOLS[n](s, c.get("arguments", {})) + except Exception as e: # noqa + st["exc"].append((r["example_id"], f"{type(e).__name__}: {e}")) + continue + if n in FIND: + if got == (c.get("output") or "").strip().strip('"'): + st["match"] += 1 + else: + st["mism"].append((r["example_id"], {"uid": (got, c.get("output"))})) + continue + if not isinstance(rec, dict): + st["match"] += 1 + continue + if n in FULLMATCH: + st["match"] += 1 if got == rec else st["mism"].append((r["example_id"], "dict-diff")) + if got == rec: + pass + continue + keys = CHECK.get(n, []) + if any(got.get(k) is None and rec.get(k) is not None for k in keys): + st["skip_nodata"] += 1 + continue + + def _eq(k): + g, rv = got.get(k), rec.get(k) + if k == "status" and isinstance(g, str) and isinstance(rv, str): + return g.replace(" ", "_") == rv.replace(" ", "_") + return g == rv + if all(_eq(k) for k in keys): + st["match"] += 1 + else: + st["mism"].append((r["example_id"], {k: (got.get(k), rec.get(k)) for k in keys if not _eq(k)})) + +tot_chk = sum(st["n"] - st["skip_nodata"] for st in stats.values()) +tot_match = sum(st["match"] for st in stats.values()) +tot_exc = sum(len(st["exc"]) for st in stats.values()) +tot_mism = sum(len(st["mism"]) for st in stats.values()) +tot_skip = sum(st["skip_nodata"] for st in stats.values()) + +print("=== CALLS INTEGRITY (remediated vs source n100) ===") +print(f" rows: {len(rem)} calls differ from source: {len(calls_diff)} {calls_diff[:5]}") +print("\n=== FREE-RUNNING REPLAY (remediated trajectories) ===") +print(f" reproduced : {tot_match}/{tot_chk} = {tot_match/max(tot_chk,1):.1%}") +print(f" exceptions : {tot_exc}") +print(f" mismatches : {tot_mism}") +print(f" skipped-no-seed : {tot_skip}") +print(f" tools implemented/exercised : {len(stats)} uncovered(echo) calls: {sum(uncovered.values())}") +if tot_exc: + print("\n -- EXCEPTIONS --") + for n, st in sorted(stats.items()): + for eid, msg in st["exc"][:5]: + print(f" [{n}] {eid}: {msg}") +if tot_mism: + print("\n -- MISMATCHES --") + for n, st in sorted(stats.items()): + for eid, d in st["mism"][:5]: + print(f" [{n}] {eid}: {d}") diff --git a/tempscripts/story_remediation/run_c3_remediated.py b/tempscripts/story_remediation/run_c3_remediated.py new file mode 100644 index 0000000000000000000000000000000000000000..fe48406d9cdaefea8f8f477070acfb2706b47585 --- /dev/null +++ b/tempscripts/story_remediation/run_c3_remediated.py @@ -0,0 +1,108 @@ +"""Run C3 on the remediated trajectories and compare to baseline. + +Same judge procedure as the baseline C3 pass (samples=3 majority, workers from +config, model from datasetreview/config.yaml). For a controlled before/after we +reuse each row's BASELINE pairing + orientation (answer_key) so the ONLY thing +that changed is the remediated dialogue. + +Writes out/C3_remediated.jsonl (canonical files untouched). +Run from repo root: python -u temp/story_remediation/run_c3_remediated.py +""" +from __future__ import annotations +import json, logging, sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +sys.path.insert(0, str(ROOT)) + +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +REMED = OUT / "trajectories_remediated.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +RESULT = OUT / "C3_remediated.jsonl" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +SAMPLES = 3 +WORKERS = max(8, cfg["run"].get("workers", 4)) + +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line) + base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) +fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()] + + +def judge_one(fake): + eid = fake["example_id"] + b = base.get(eid) + real = pairer(fake) + # reuse baseline orientation: answer_key A => swap False, B => swap True + swap = (b or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + key = msgs["answer_key"] + guesses, err = [], None + for _ in range(SAMPLES): + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + guesses.append(r.get("guess")) + except Exception as e: # noqa: BLE001 + err = str(e) + if not guesses: + return {"item_id": eid, "error": err, "answer_key": key, + "real_id": real.get("example_id")} + majority = Counter(guesses).most_common(1)[0][0] + agree = guesses.count(majority) / len(guesses) + return {"item_id": eid, "answer_key": key, "real_id": real.get("example_id"), + "baseline_real_id": (b or {}).get("real_id"), + "guess": majority, "agreement": agree, "n_samples": len(guesses), + "sample_guesses": guesses, "caught": majority == key, + "baseline_caught": (b or {}).get("caught"), "error": None} + + +def main(): + print(f"judging {len(fakes)} remediated rows (samples={SAMPLES}, workers={WORKERS}, " + f"model={cfg['model']['label']})") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + results = list(ex.map(judge_one, fakes)) + results.sort(key=lambda r: r["item_id"]) + RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8") + + ok = [r for r in results if r.get("error") is None and "caught" in r] + errs = [r for r in results if r.get("error") is not None or "caught" not in r] + caught = sum(1 for r in ok if r["caught"]) + n = len(ok) + base_caught = sum(1 for r in ok if r.get("baseline_caught")) + pair_match = sum(1 for r in ok if r.get("real_id") == r.get("baseline_real_id")) + flip_fixed = sum(1 for r in ok if r.get("baseline_caught") and not r["caught"]) + flip_regress = sum(1 for r in ok if not r.get("baseline_caught") and r["caught"]) + + print("\n=== C3 REMEDIATED RESULT ===") + print(f" rows judged : {n} errors: {len(errs)}") + print(f" pairing match base : {pair_match}/{n}") + print(f" baseline caught : {base_caught}/{n} = {base_caught/n:.1%}") + print(f" remediated caught : {caught}/{n} = {caught/n:.1%}") + print(f" fixed (caught->fooled) : {flip_fixed}") + print(f" regressed (fooled->caught): {flip_regress}") + print(f" wrote {RESULT.relative_to(ROOT)}") + if errs: + print(" sample error:", errs[0].get("error")) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/story_remediation/unbundle/ab_capability_reasons.py b/tempscripts/story_remediation/unbundle/ab_capability_reasons.py new file mode 100644 index 0000000000000000000000000000000000000000..7dbdbc97cdb4f28d4987b23b07ec1df81aea0a7f --- /dev/null +++ b/tempscripts/story_remediation/unbundle/ab_capability_reasons.py @@ -0,0 +1,137 @@ +"""Task: take 50 rows whose PRIMARY tell (old prompt) was 'capability/scenario +realism', re-judge each with BOTH the old C3 prompt and the v2 variant, capturing +the REASONING from both so we can see what changed and why. + +Reads out/caught_reasons_v5.jsonl (primary bucket labels), samples 50 from +A_capability_scenario_realism, judges 1 sample per prompt (reasoning captured), +prints per-row old-vs-new guess + both rationales, and a thematic summary. +Saves out/ab_capability_reasons.jsonl. + +Run: python -u temp/story_remediation/unbundle/ab_capability_reasons.py [N] +""" +from __future__ import annotations +import json, logging, sys, random, collections +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +WORKERS = max(8, cfg["run"].get("workers", 4)) + +reasons = [json.loads(l) for l in open(OUT / "caught_reasons_v5.jsonl", encoding="utf-8") if l.strip()] +cap = [r for r in reasons if r.get("primary") == "A_capability_scenario_realism" and r.get("sample_caught")] +fakes = {e["example_id"]: e for e in + (json.loads(l) for l in open(OUT / "trajectories_all_v5.jsonl", encoding="utf-8") if l.strip())} +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line); base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) + +random.seed(13) +random.shuffle(cap) +N = int(sys.argv[1]) if len(sys.argv) > 1 else 50 +sample = cap[:N] + + +def build(fake, real, swap, variant): + system, user = J.load_prompt(variant) + fr = J.render_trajectory(fake, blind_tools=True, include_metadata=False, conversation_only=True) + rr = J.render_trajectory(real, blind_tools=True, include_metadata=False, conversation_only=True) + if swap: + a, b, key = rr, fr, "B" + else: + a, b, key = fr, rr, "A" + user = user.replace("{{CONV_A}}", a).replace("{{CONV_B}}", b) + return {"system": system, "user": user, "answer_key": key} + + +def jr(msgs): + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + return r.get("guess"), (r.get("reasoning") or "").strip() + except Exception as e: # noqa: BLE001 + return None, f"ERR {e}" + + +def one(row): + eid = row["item_id"]; fake = fakes.get(eid) + if not fake: + return None + real = pairer(fake) + swap = (base.get(eid) or base.get((fake.get("metadata") or {}).get("orig_eid")) or {}).get("answer_key") == "B" + om = build(fake, real, swap, "C3"); nm = build(fake, real, swap, "C3v2") + key = om["answer_key"] + og, orz = jr(om); ng, nrz = jr(nm) + return {"item_id": eid, "role": row.get("role"), "key": key, + "old_guess": og, "old_caught": og == key, "old_reason": orz, + "new_guess": ng, "new_caught": ng == key, "new_reason": nrz} + + +# does the NEW reasoning still lean on the capability/scenario/auth leak? +LEAK_KW = ["capab", "unrealistic", "unusual", "atypical", "wouldn't", "implausible", + "unlikely", "niche", "fabricat", "scripted", "constructed", "staged", + "designed to", "exercise", "test scenario", "red-team", "red team", + "benchmark", "probe", "verif", "identity", "authent", "policy", "unrelated"] + + +def leaky(txt): + low = (txt or "").lower() + return any(k in low for k in LEAK_KW) + + +def main(): + print(f"capability-bucket A/B: {len(sample)} rows (of {len(cap)} in bucket), workers={WORKERS}") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + rows = [r for r in ex.map(one, sample) if r] + + oc = sum(r["old_caught"] for r in rows) + nc = sum(r["new_caught"] for r in rows) + flip = [r for r in rows if r["old_caught"] and not r["new_caught"]] + still = [r for r in rows if r["old_caught"] and r["new_caught"]] + n = len(rows) + old_leak = sum(leaky(r["old_reason"]) for r in rows) + new_leak = sum(leaky(r["new_reason"]) for r in rows) + + print("\n" + "=" * 80) + print(f"rows: {n} (all had capability/scenario as the OLD primary tell)") + print(f" OLD catches: {oc}/{n} = {oc/n:.0%} NEW(v2) catches: {nc}/{n} = {nc/n:.0%}") + print(f" FLIPPED caught->fooled under v2: {len(flip)}/{max(oc,1)} = {len(flip)/max(oc,1):.0%}") + print(f" still caught by both: {len(still)}") + print(f" reasoning invoking capability/scenario/auth 'leak' language:") + print(f" OLD: {old_leak}/{n} = {old_leak/n:.0%} NEW: {new_leak}/{n} = {new_leak/n:.0%}") + print("=" * 80) + + print("\n--- FLIPPED rows (v2 stopped catching): old vs new reasoning ---") + for r in flip[:14]: + print(f"\n[{r['item_id']}] role={r['role']} old={r['old_guess']}(caught) new={r['new_guess']}(fooled)") + print(f" OLD: {r['old_reason'][:300]}") + print(f" NEW: {r['new_reason'][:300]}") + + print("\n--- STILL caught by v2: what tell survived ---") + for r in still[:8]: + print(f"\n[{r['item_id']}] role={r['role']} new={r['new_guess']}") + print(f" NEW: {r['new_reason'][:300]}") + + OUT.joinpath("ab_capability_reasons.jsonl").write_text( + "\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8") + print(f"\nsaved -> {OUT.joinpath('ab_capability_reasons.jsonl').relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/ab_prompt_v2.py b/tempscripts/story_remediation/unbundle/ab_prompt_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..edb0dc334015c2da953f7e5664e2be98cfcf2337 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/ab_prompt_v2.py @@ -0,0 +1,126 @@ +"""A/B spot-check: does the v2 C3 prompt stop catching synthetics the OLD prompt caught? + +Takes a sample of v5 rows that were CAUGHT in the last run (i.e. the synthetic +FAILED to fool the original prompt), re-judges each with BOTH prompts (3-sample +majority, identical rendering), and reports how many flip caught -> fooled under v2. +An improvement = the v2 prompt no longer detects the synthetic (guess wrong or +cannot_tell) on rows the old prompt caught. + +Run: python -u temp/story_remediation/unbundle/ab_prompt_v2.py [N] +""" +from __future__ import annotations +import json, logging, sys, random +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +SAMPLES = 3 +WORKERS = max(8, cfg["run"].get("workers", 4)) + +verds = [json.loads(l) for l in open(OUT / "C3_all_v5.jsonl", encoding="utf-8") if l.strip()] +fakes = {e["example_id"]: e for e in + (json.loads(l) for l in open(OUT / "trajectories_all_v5.jsonl", encoding="utf-8") if l.strip())} +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line); base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) + +caught = [v for v in verds if v.get("caught")] +random.seed(11) +random.shuffle(caught) +N = int(sys.argv[1]) if len(sys.argv) > 1 else 50 +sample = caught[:N] + + +def build(fake, real, swap, variant): + """Render the identical pair, fill either the C3 or C3v2 template.""" + system, user = J.load_prompt(variant) + fr = J.render_trajectory(fake, blind_tools=True, include_metadata=False, conversation_only=True) + rr = J.render_trajectory(real, blind_tools=True, include_metadata=False, conversation_only=True) + if swap: + a, b, key = rr, fr, "B" + else: + a, b, key = fr, rr, "A" + user = user.replace("{{CONV_A}}", a).replace("{{CONV_B}}", b) + return {"system": system, "user": user, "answer_key": key} + + +def maj(msgs): + gs = [] + for _ in range(SAMPLES): + try: + gs.append(judge.judge({"system": msgs["system"], "user": msgs["user"]}).get("guess")) + except Exception: # noqa: BLE001 + pass + if not gs: + return None, 0.0 + m = Counter(gs).most_common(1)[0][0] + return m, gs.count(m) / len(gs) + + +def one(v): + eid = v["item_id"]; fake = fakes.get(eid) + if not fake: + return None + real = pairer(fake) + swap = (base.get(eid) or base.get(v.get("orig_eid")) or {}).get("answer_key") == "B" + old_m = build(fake, real, swap, "C3") + new_m = build(fake, real, swap, "C3v2") + key = old_m["answer_key"] + og, oa = maj(old_m) + ng, na = maj(new_m) + return {"item_id": eid, "role": v.get("role"), "key": key, + "old_guess": og, "old_caught": og == key, + "new_guess": ng, "new_caught": ng == key} + + +def main(): + print(f"A/B on {len(sample)} rows caught by the OLD prompt (samples={SAMPLES}, workers={WORKERS})") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + rows = [r for r in ex.map(one, sample) if r] + + old_c = sum(r["old_caught"] for r in rows) + new_c = sum(r["new_caught"] for r in rows) + flipped = [r for r in rows if r["old_caught"] and not r["new_caught"]] + still = [r for r in rows if r["old_caught"] and r["new_caught"]] + regress = [r for r in rows if not r["old_caught"] and r["new_caught"]] + n = len(rows) + print("\n" + "=" * 72) + print(f"rows re-judged: {n}") + print(f" OLD prompt still catches (re-judge): {old_c}/{n} = {old_c/n:.0%}") + print(f" NEW (v2) prompt catches: {new_c}/{n} = {new_c/n:.0%}") + print(f" FLIPPED caught->fooled under v2: {len(flipped)}/{old_c}" + f" = {len(flipped)/max(old_c,1):.0%} (improvement)") + print(f" still caught by both: {len(still)}") + print(f" old-missed but v2 catches: {len(regress)}") + print("=" * 72) + print("\nsample of FLIPPED (v2 no longer detects the synthetic):") + for r in flipped[:12]: + print(f" {r['item_id']:42s} role={r['role']} old={r['old_guess']} new={r['new_guess']}") + print("\nsample STILL caught by v2:") + for r in still[:8]: + print(f" {r['item_id']:42s} role={r['role']} new={r['new_guess']}") + (OUT / "ab_prompt_v2.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8") + print(f"\nsaved -> {(OUT/'ab_prompt_v2.jsonl').relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/analyze_all.py b/tempscripts/story_remediation/unbundle/analyze_all.py new file mode 100644 index 0000000000000000000000000000000000000000..bf051e2063598d42a0f3c23cdcd928340f299ec2 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/analyze_all.py @@ -0,0 +1,137 @@ +"""Analyze the full unbundle C3 run vs baseline. + +Reports: + - aggregate catch rate across all rows vs baseline 64.7% + - T1-slot flips (same trie position as baseline): fixed / regressed / net + - tail-turn catch rate, broken down by tail length and by position + - the 512 untouched passthrough rows as a sanity control +Writes RESULT_all.md. +Run: python -u temp/story_remediation/unbundle/analyze_all.py +""" +from __future__ import annotations +import json +from collections import defaultdict, Counter +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +OUT = HERE / "out" +RES = OUT / "C3_all.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +MD = HERE / "RESULT_all.md" + + +def caught_of(d): + if "caught" in d and d["caught"] is not None: + return d["caught"] + return d.get("guess") == d.get("answer_key") + + +def main(): + base = {} + for l in open(BASELINE, encoding="utf-8"): + if l.strip(): + d = json.loads(l); base[d["item_id"]] = d + base_caught = {k: caught_of(v) for k, v in base.items()} + nb = len(base); bc = sum(base_caught.values()) + + res = [json.loads(l) for l in open(RES, encoding="utf-8") if l.strip()] + ok = [r for r in res if r.get("error") is None and "caught" in r] + errs = [r for r in res if r not in ok] + + # tail length per orig from n100 + orig = {json.loads(l)["example_id"]: json.loads(l) + for l in open(N100, encoding="utf-8") if l.strip()} + tail_len = {e: len(r["calls"]) - (r["metadata"]["anchor_depth"] + 1) + for e, r in orig.items()} + + n = len(ok); c = sum(1 for r in ok if r["caught"]) + t1 = [r for r in ok if r.get("role") == "turn1"] + tail = [r for r in ok if r.get("role") and r.get("role") != "turn1"] + passth = [r for r in ok if not r.get("role")] + + # T1 flips vs baseline (same eid, same trie position) + fixed = regress = kept_c = kept_f = 0 + for r in t1: + bcaught = base_caught.get(r["item_id"]) + if bcaught is None: + continue + if bcaught and not r["caught"]: + fixed += 1 + elif not bcaught and r["caught"]: + regress += 1 + elif bcaught and r["caught"]: + kept_c += 1 + else: + kept_f += 1 + t1_caught = sum(1 for r in t1 if r["caught"]) + + # tail by length and position + tail_by_len = defaultdict(lambda: [0, 0]) + tail_by_pos = defaultdict(lambda: [0, 0]) + for r in tail: + oe = r.get("orig_eid"); tl = tail_len.get(oe, 0) + tail_by_len[tl][0] += 1; tail_by_len[tl][1] += int(r["caught"]) + pos = int(r["role"][4:]) + tail_by_pos[pos][0] += 1; tail_by_pos[pos][1] += int(r["caught"]) + + pc = sum(1 for r in passth if r["caught"]) + + L = [] + def p(s=""): L.append(s); print(s) + + p("# Full Unbundle: C3 Results\n") + p(f"Baseline (n100, single-turn): **{bc}/{nb} = {bc/nb:.1%}** caught\n") + p(f"Unbundled dataset: {n} rows judged ({len(errs)} errors)\n") + p(f"Overall caught: **{c}/{n} = {c/n:.1%}**\n") + p("## Row composition") + p(f"- turn1 (preserved trie divergence): {len(t1)}") + p(f"- tail turns (one action each): {len(tail)}") + p(f"- untouched passthrough: {len(passth)}\n") + + p("## T1 slots vs baseline (same 283 trie positions)") + denom = fixed + regress + kept_c + kept_f + p(f"- baseline caught here: {fixed+kept_c}/{denom}") + p(f"- unbundled caught here: {t1_caught}/{len(t1)} = {t1_caught/max(len(t1),1):.1%}") + p(f"- **fixed (caught -> fooled): {fixed}**") + p(f"- regressed (fooled -> caught): {regress}") + p(f"- net catch reduction on T1: {fixed-regress}\n") + + p("## Tail turns (the re-rooted follow-ups)") + tc = sum(1 for r in tail if r["caught"]) + p(f"- tail caught: {tc}/{len(tail)} = {tc/max(len(tail),1):.1%}") + p("- by original tail length:") + for tl in sorted(tail_by_len): + tot, cc = tail_by_len[tl] + p(f" tail_len={tl}: {cc}/{tot} = {cc/tot:.0%}") + p("- by turn position:") + for pos in sorted(tail_by_pos): + tot, cc = tail_by_pos[pos] + p(f" turn{pos}: {cc}/{tot} = {cc/tot:.0%}") + p("") + + p("## Passthrough control (should track baseline)") + p(f"- caught: {pc}/{len(passth)} = {pc/max(len(passth),1):.1%}") + bpc = sum(base_caught.get(r["item_id"], False) for r in passth) + p(f"- same rows in baseline: {bpc}/{len(passth)} = {bpc/max(len(passth),1):.1%}\n") + + # effective per-scenario: does the ORIGINAL confuser (now split) get caught + # in ANY of its turns? (a scenario is "detected" if any split turn is caught) + by_orig = defaultdict(list) + for r in t1 + tail: + by_orig[r.get("orig_eid")].append(r["caught"]) + scen_any = sum(1 for e, v in by_orig.items() if any(v)) + scen_t1only = sum(1 for r in t1 if r["caught"]) + p("## Per-scenario view (283 split confusers)") + p(f"- caught in >=1 of its turns: {scen_any}/{len(by_orig)} = {scen_any/len(by_orig):.1%}") + p(f"- caught at the T1 (trie) slot: {scen_t1only}/{len(by_orig)} = {scen_t1only/len(by_orig):.1%}") + baseline_on_split = sum(base_caught.get(e, False) for e in by_orig) + p(f"- baseline caught these same confusers: {baseline_on_split}/{len(by_orig)} = {baseline_on_split/len(by_orig):.1%}") + + MD.write_text("\n".join(L) + "\n", encoding="utf-8") + print(f"\nwrote {MD.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/analyze_all_v2.py b/tempscripts/story_remediation/unbundle/analyze_all_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..9e64d8f9c7a255d664f027ee02b92d5dedea5846 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/analyze_all_v2.py @@ -0,0 +1,137 @@ +"""Analyze the full unbundle C3 run vs baseline. + +Reports: + - aggregate catch rate across all rows vs baseline 64.7% + - T1-slot flips (same trie position as baseline): fixed / regressed / net + - tail-turn catch rate, broken down by tail length and by position + - the 512 untouched passthrough rows as a sanity control +Writes RESULT_all_v2.md. +Run: python -u temp/story_remediation/unbundle/analyze_all.py +""" +from __future__ import annotations +import json +from collections import defaultdict, Counter +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +OUT = HERE / "out" +RES = OUT / "C3_all_v2.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +MD = HERE / "RESULT_all_v2.md" + + +def caught_of(d): + if "caught" in d and d["caught"] is not None: + return d["caught"] + return d.get("guess") == d.get("answer_key") + + +def main(): + base = {} + for l in open(BASELINE, encoding="utf-8"): + if l.strip(): + d = json.loads(l); base[d["item_id"]] = d + base_caught = {k: caught_of(v) for k, v in base.items()} + nb = len(base); bc = sum(base_caught.values()) + + res = [json.loads(l) for l in open(RES, encoding="utf-8") if l.strip()] + ok = [r for r in res if r.get("error") is None and "caught" in r] + errs = [r for r in res if r not in ok] + + # tail length per orig from n100 + orig = {json.loads(l)["example_id"]: json.loads(l) + for l in open(N100, encoding="utf-8") if l.strip()} + tail_len = {e: len(r["calls"]) - (r["metadata"]["anchor_depth"] + 1) + for e, r in orig.items()} + + n = len(ok); c = sum(1 for r in ok if r["caught"]) + t1 = [r for r in ok if r.get("role") == "turn1"] + tail = [r for r in ok if r.get("role") and r.get("role") != "turn1"] + passth = [r for r in ok if not r.get("role")] + + # T1 flips vs baseline (same eid, same trie position) + fixed = regress = kept_c = kept_f = 0 + for r in t1: + bcaught = base_caught.get(r["item_id"]) + if bcaught is None: + continue + if bcaught and not r["caught"]: + fixed += 1 + elif not bcaught and r["caught"]: + regress += 1 + elif bcaught and r["caught"]: + kept_c += 1 + else: + kept_f += 1 + t1_caught = sum(1 for r in t1 if r["caught"]) + + # tail by length and position + tail_by_len = defaultdict(lambda: [0, 0]) + tail_by_pos = defaultdict(lambda: [0, 0]) + for r in tail: + oe = r.get("orig_eid"); tl = tail_len.get(oe, 0) + tail_by_len[tl][0] += 1; tail_by_len[tl][1] += int(r["caught"]) + pos = int(r["role"][4:]) + tail_by_pos[pos][0] += 1; tail_by_pos[pos][1] += int(r["caught"]) + + pc = sum(1 for r in passth if r["caught"]) + + L = [] + def p(s=""): L.append(s); print(s) + + p("# Full Unbundle: C3 Results\n") + p(f"Baseline (n100, single-turn): **{bc}/{nb} = {bc/nb:.1%}** caught\n") + p(f"Unbundled dataset: {n} rows judged ({len(errs)} errors)\n") + p(f"Overall caught: **{c}/{n} = {c/n:.1%}**\n") + p("## Row composition") + p(f"- turn1 (preserved trie divergence): {len(t1)}") + p(f"- tail turns (one action each): {len(tail)}") + p(f"- untouched passthrough: {len(passth)}\n") + + p("## T1 slots vs baseline (same 283 trie positions)") + denom = fixed + regress + kept_c + kept_f + p(f"- baseline caught here: {fixed+kept_c}/{denom}") + p(f"- unbundled caught here: {t1_caught}/{len(t1)} = {t1_caught/max(len(t1),1):.1%}") + p(f"- **fixed (caught -> fooled): {fixed}**") + p(f"- regressed (fooled -> caught): {regress}") + p(f"- net catch reduction on T1: {fixed-regress}\n") + + p("## Tail turns (the re-rooted follow-ups)") + tc = sum(1 for r in tail if r["caught"]) + p(f"- tail caught: {tc}/{len(tail)} = {tc/max(len(tail),1):.1%}") + p("- by original tail length:") + for tl in sorted(tail_by_len): + tot, cc = tail_by_len[tl] + p(f" tail_len={tl}: {cc}/{tot} = {cc/tot:.0%}") + p("- by turn position:") + for pos in sorted(tail_by_pos): + tot, cc = tail_by_pos[pos] + p(f" turn{pos}: {cc}/{tot} = {cc/tot:.0%}") + p("") + + p("## Passthrough control (should track baseline)") + p(f"- caught: {pc}/{len(passth)} = {pc/max(len(passth),1):.1%}") + bpc = sum(base_caught.get(r["item_id"], False) for r in passth) + p(f"- same rows in baseline: {bpc}/{len(passth)} = {bpc/max(len(passth),1):.1%}\n") + + # effective per-scenario: does the ORIGINAL confuser (now split) get caught + # in ANY of its turns? (a scenario is "detected" if any split turn is caught) + by_orig = defaultdict(list) + for r in t1 + tail: + by_orig[r.get("orig_eid")].append(r["caught"]) + scen_any = sum(1 for e, v in by_orig.items() if any(v)) + scen_t1only = sum(1 for r in t1 if r["caught"]) + p("## Per-scenario view (283 split confusers)") + p(f"- caught in >=1 of its turns: {scen_any}/{len(by_orig)} = {scen_any/len(by_orig):.1%}") + p(f"- caught at the T1 (trie) slot: {scen_t1only}/{len(by_orig)} = {scen_t1only/len(by_orig):.1%}") + baseline_on_split = sum(base_caught.get(e, False) for e in by_orig) + p(f"- baseline caught these same confusers: {baseline_on_split}/{len(by_orig)} = {baseline_on_split/len(by_orig):.1%}") + + MD.write_text("\n".join(L) + "\n", encoding="utf-8") + print(f"\nwrote {MD.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/analyze_all_v3.py b/tempscripts/story_remediation/unbundle/analyze_all_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..4a0fdb08641957b8f2bc1bd4f9fd7abf4534de47 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/analyze_all_v3.py @@ -0,0 +1,137 @@ +"""Analyze the full unbundle C3 run vs baseline. + +Reports: + - aggregate catch rate across all rows vs baseline 64.7% + - T1-slot flips (same trie position as baseline): fixed / regressed / net + - tail-turn catch rate, broken down by tail length and by position + - the 512 untouched passthrough rows as a sanity control +Writes RESULT_all_v3.md. +Run: python -u temp/story_remediation/unbundle/analyze_all.py +""" +from __future__ import annotations +import json +from collections import defaultdict, Counter +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +OUT = HERE / "out" +RES = OUT / "C3_all_v3.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +MD = HERE / "RESULT_all_v3.md" + + +def caught_of(d): + if "caught" in d and d["caught"] is not None: + return d["caught"] + return d.get("guess") == d.get("answer_key") + + +def main(): + base = {} + for l in open(BASELINE, encoding="utf-8"): + if l.strip(): + d = json.loads(l); base[d["item_id"]] = d + base_caught = {k: caught_of(v) for k, v in base.items()} + nb = len(base); bc = sum(base_caught.values()) + + res = [json.loads(l) for l in open(RES, encoding="utf-8") if l.strip()] + ok = [r for r in res if r.get("error") is None and "caught" in r] + errs = [r for r in res if r not in ok] + + # tail length per orig from n100 + orig = {json.loads(l)["example_id"]: json.loads(l) + for l in open(N100, encoding="utf-8") if l.strip()} + tail_len = {e: len(r["calls"]) - (r["metadata"]["anchor_depth"] + 1) + for e, r in orig.items()} + + n = len(ok); c = sum(1 for r in ok if r["caught"]) + t1 = [r for r in ok if r.get("role") == "turn1"] + tail = [r for r in ok if r.get("role") and r.get("role") != "turn1"] + passth = [r for r in ok if not r.get("role")] + + # T1 flips vs baseline (same eid, same trie position) + fixed = regress = kept_c = kept_f = 0 + for r in t1: + bcaught = base_caught.get(r["item_id"]) + if bcaught is None: + continue + if bcaught and not r["caught"]: + fixed += 1 + elif not bcaught and r["caught"]: + regress += 1 + elif bcaught and r["caught"]: + kept_c += 1 + else: + kept_f += 1 + t1_caught = sum(1 for r in t1 if r["caught"]) + + # tail by length and position + tail_by_len = defaultdict(lambda: [0, 0]) + tail_by_pos = defaultdict(lambda: [0, 0]) + for r in tail: + oe = r.get("orig_eid"); tl = tail_len.get(oe, 0) + tail_by_len[tl][0] += 1; tail_by_len[tl][1] += int(r["caught"]) + pos = int(r["role"][4:]) + tail_by_pos[pos][0] += 1; tail_by_pos[pos][1] += int(r["caught"]) + + pc = sum(1 for r in passth if r["caught"]) + + L = [] + def p(s=""): L.append(s); print(s) + + p("# Full Unbundle: C3 Results\n") + p(f"Baseline (n100, single-turn): **{bc}/{nb} = {bc/nb:.1%}** caught\n") + p(f"Unbundled dataset: {n} rows judged ({len(errs)} errors)\n") + p(f"Overall caught: **{c}/{n} = {c/n:.1%}**\n") + p("## Row composition") + p(f"- turn1 (preserved trie divergence): {len(t1)}") + p(f"- tail turns (one action each): {len(tail)}") + p(f"- untouched passthrough: {len(passth)}\n") + + p("## T1 slots vs baseline (same 283 trie positions)") + denom = fixed + regress + kept_c + kept_f + p(f"- baseline caught here: {fixed+kept_c}/{denom}") + p(f"- unbundled caught here: {t1_caught}/{len(t1)} = {t1_caught/max(len(t1),1):.1%}") + p(f"- **fixed (caught -> fooled): {fixed}**") + p(f"- regressed (fooled -> caught): {regress}") + p(f"- net catch reduction on T1: {fixed-regress}\n") + + p("## Tail turns (the re-rooted follow-ups)") + tc = sum(1 for r in tail if r["caught"]) + p(f"- tail caught: {tc}/{len(tail)} = {tc/max(len(tail),1):.1%}") + p("- by original tail length:") + for tl in sorted(tail_by_len): + tot, cc = tail_by_len[tl] + p(f" tail_len={tl}: {cc}/{tot} = {cc/tot:.0%}") + p("- by turn position:") + for pos in sorted(tail_by_pos): + tot, cc = tail_by_pos[pos] + p(f" turn{pos}: {cc}/{tot} = {cc/tot:.0%}") + p("") + + p("## Passthrough control (should track baseline)") + p(f"- caught: {pc}/{len(passth)} = {pc/max(len(passth),1):.1%}") + bpc = sum(base_caught.get(r["item_id"], False) for r in passth) + p(f"- same rows in baseline: {bpc}/{len(passth)} = {bpc/max(len(passth),1):.1%}\n") + + # effective per-scenario: does the ORIGINAL confuser (now split) get caught + # in ANY of its turns? (a scenario is "detected" if any split turn is caught) + by_orig = defaultdict(list) + for r in t1 + tail: + by_orig[r.get("orig_eid")].append(r["caught"]) + scen_any = sum(1 for e, v in by_orig.items() if any(v)) + scen_t1only = sum(1 for r in t1 if r["caught"]) + p("## Per-scenario view (283 split confusers)") + p(f"- caught in >=1 of its turns: {scen_any}/{len(by_orig)} = {scen_any/len(by_orig):.1%}") + p(f"- caught at the T1 (trie) slot: {scen_t1only}/{len(by_orig)} = {scen_t1only/len(by_orig):.1%}") + baseline_on_split = sum(base_caught.get(e, False) for e in by_orig) + p(f"- baseline caught these same confusers: {baseline_on_split}/{len(by_orig)} = {baseline_on_split/len(by_orig):.1%}") + + MD.write_text("\n".join(L) + "\n", encoding="utf-8") + print(f"\nwrote {MD.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/analyze_all_v4.py b/tempscripts/story_remediation/unbundle/analyze_all_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..1a0b4f901edc7437213b64b15801d8792f6c92c8 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/analyze_all_v4.py @@ -0,0 +1,138 @@ +"""Analyze the full unbundle C3 run vs baseline. + +Reports: + - aggregate catch rate across all rows vs baseline 64.7% + - T1-slot flips (same trie position as baseline): fixed / regressed / net + - tail-turn catch rate, broken down by tail length and by position + - the 512 untouched passthrough rows as a sanity control +Writes RESULT_all_v4.md. +Run: python -u temp/story_remediation/unbundle/analyze_all.py +""" +from __future__ import annotations +import json +from collections import defaultdict, Counter +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +OUT = HERE / "out" +RES = OUT / "C3_all_v4.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +MD = HERE / "RESULT_all_v4.md" + + +def caught_of(d): + if "caught" in d and d["caught"] is not None: + return d["caught"] + return d.get("guess") == d.get("answer_key") + + +def main(): + base = {} + for l in open(BASELINE, encoding="utf-8"): + if l.strip(): + d = json.loads(l); base[d["item_id"]] = d + base_caught = {k: caught_of(v) for k, v in base.items()} + nb = len(base); bc = sum(base_caught.values()) + + res = [json.loads(l) for l in open(RES, encoding="utf-8") if l.strip()] + ok = [r for r in res if r.get("error") is None and "caught" in r] + errs = [r for r in res if r not in ok] + + # tail length per orig from n100 + orig = {json.loads(l)["example_id"]: json.loads(l) + for l in open(N100, encoding="utf-8") if l.strip()} + tail_len = {e: len(r["calls"]) - (r["metadata"]["anchor_depth"] + 1) + for e, r in orig.items()} + + n = len(ok); c = sum(1 for r in ok if r["caught"]) + t1 = [r for r in ok if r.get("role") == "turn1"] + tail = [r for r in ok if r.get("role") and r.get("role") != "turn1"] + passth = [r for r in ok if not r.get("role")] + + # T1 flips vs baseline (same eid, same trie position) + fixed = regress = kept_c = kept_f = 0 + for r in t1: + bcaught = base_caught.get(r["item_id"]) + if bcaught is None: + continue + if bcaught and not r["caught"]: + fixed += 1 + elif not bcaught and r["caught"]: + regress += 1 + elif bcaught and r["caught"]: + kept_c += 1 + else: + kept_f += 1 + t1_caught = sum(1 for r in t1 if r["caught"]) + + # tail by length and position + tail_by_len = defaultdict(lambda: [0, 0]) + tail_by_pos = defaultdict(lambda: [0, 0]) + for r in tail: + oe = r.get("orig_eid"); tl = tail_len.get(oe, 0) + tail_by_len[tl][0] += 1; tail_by_len[tl][1] += int(r["caught"]) + pos = int(r["role"][4:]) + tail_by_pos[pos][0] += 1; tail_by_pos[pos][1] += int(r["caught"]) + + pc = sum(1 for r in passth if r["caught"]) + + L = [] + def p(s=""): L.append(s); print(s) + + p("# Unbundle v4 (auth handshake + humanized): C3 Results\n") + p(f"Baseline (n100, single-turn): **{bc}/{nb} = {bc/nb:.1%}** caught\n") + p(f"Unbundled dataset: {n} rows judged ({len(errs)} errors)\n") + p(f"Overall caught: **{c}/{n} = {c/n:.1%}**\n") + p("## Row composition") + p(f"- turn1 (preserved trie divergence): {len(t1)}") + p(f"- tail turns (one action each): {len(tail)}") + p(f"- untouched passthrough: {len(passth)}\n") + + p("## T1 slots vs baseline (same 283 trie positions)") + denom = fixed + regress + kept_c + kept_f + p(f"- baseline caught here: {fixed+kept_c}/{denom}") + p(f"- unbundled caught here: {t1_caught}/{len(t1)} = {t1_caught/max(len(t1),1):.1%}") + p(f"- **fixed (caught -> fooled): {fixed}**") + p(f"- regressed (fooled -> caught): {regress}") + p(f"- net catch reduction on T1: {fixed-regress}\n") + + p("## Tail turns (the re-rooted follow-ups)") + tc = sum(1 for r in tail if r["caught"]) + p(f"- tail caught: {tc}/{len(tail)} = {tc/max(len(tail),1):.1%}") + p("- by original tail length:") + for tl in sorted(tail_by_len): + tot, cc = tail_by_len[tl] + p(f" tail_len={tl}: {cc}/{tot} = {cc/tot:.0%}") + p("- by turn position:") + for pos in sorted(tail_by_pos): + tot, cc = tail_by_pos[pos] + p(f" turn{pos}: {cc}/{tot} = {cc/tot:.0%}") + p("") + + p("## Passthrough control (should track baseline)") + p(f"- caught: {pc}/{len(passth)} = {pc/max(len(passth),1):.1%}") + bpc = sum(base_caught.get(r["item_id"], False) for r in passth) + p(f"- same rows in baseline: {bpc}/{len(passth)} = {bpc/max(len(passth),1):.1%}\n") + + # effective per-scenario: does the ORIGINAL confuser (now split) get caught + # in ANY of its turns? (a scenario is "detected" if any split turn is caught) + by_orig = defaultdict(list) + for r in t1 + tail: + by_orig[r.get("orig_eid")].append(r["caught"]) + scen_any = sum(1 for e, v in by_orig.items() if any(v)) + scen_t1only = sum(1 for r in t1 if r["caught"]) + p("## Per-scenario view (283 split confusers)") + p(f"- caught in >=1 of its turns: {scen_any}/{len(by_orig)} = {scen_any/len(by_orig):.1%}") + p(f"- caught at the T1 (trie) slot: {scen_t1only}/{len(by_orig)} = {scen_t1only/len(by_orig):.1%}") + baseline_on_split = sum(base_caught.get(e, False) for e in by_orig) + p(f"- baseline caught these same confusers: {baseline_on_split}/{len(by_orig)} = {baseline_on_split/len(by_orig):.1%}") + + MD.write_text("\n".join(L) + "\n", encoding="utf-8") + print(f"\nwrote {MD.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() + diff --git a/tempscripts/story_remediation/unbundle/analyze_all_v5.py b/tempscripts/story_remediation/unbundle/analyze_all_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..05da0a95d6c146b20226ae99dbc54c3c9600d4a2 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/analyze_all_v5.py @@ -0,0 +1,139 @@ +"""Analyze the full unbundle C3 run vs baseline. + +Reports: + - aggregate catch rate across all rows vs baseline 64.7% + - T1-slot flips (same trie position as baseline): fixed / regressed / net + - tail-turn catch rate, broken down by tail length and by position + - the 512 untouched passthrough rows as a sanity control +Writes RESULT_all_v5.md. +Run: python -u temp/story_remediation/unbundle/analyze_all.py +""" +from __future__ import annotations +import json +from collections import defaultdict, Counter +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +OUT = HERE / "out" +RES = OUT / "C3_all_v5.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +MD = HERE / "RESULT_all_v5.md" + + +def caught_of(d): + if "caught" in d and d["caught"] is not None: + return d["caught"] + return d.get("guess") == d.get("answer_key") + + +def main(): + base = {} + for l in open(BASELINE, encoding="utf-8"): + if l.strip(): + d = json.loads(l); base[d["item_id"]] = d + base_caught = {k: caught_of(v) for k, v in base.items()} + nb = len(base); bc = sum(base_caught.values()) + + res = [json.loads(l) for l in open(RES, encoding="utf-8") if l.strip()] + ok = [r for r in res if r.get("error") is None and "caught" in r] + errs = [r for r in res if r not in ok] + + # tail length per orig from n100 + orig = {json.loads(l)["example_id"]: json.loads(l) + for l in open(N100, encoding="utf-8") if l.strip()} + tail_len = {e: len(r["calls"]) - (r["metadata"]["anchor_depth"] + 1) + for e, r in orig.items()} + + n = len(ok); c = sum(1 for r in ok if r["caught"]) + t1 = [r for r in ok if r.get("role") == "turn1"] + tail = [r for r in ok if r.get("role") and r.get("role") != "turn1"] + passth = [r for r in ok if not r.get("role")] + + # T1 flips vs baseline (same eid, same trie position) + fixed = regress = kept_c = kept_f = 0 + for r in t1: + bcaught = base_caught.get(r["item_id"]) + if bcaught is None: + continue + if bcaught and not r["caught"]: + fixed += 1 + elif not bcaught and r["caught"]: + regress += 1 + elif bcaught and r["caught"]: + kept_c += 1 + else: + kept_f += 1 + t1_caught = sum(1 for r in t1 if r["caught"]) + + # tail by length and position + tail_by_len = defaultdict(lambda: [0, 0]) + tail_by_pos = defaultdict(lambda: [0, 0]) + for r in tail: + oe = r.get("orig_eid"); tl = tail_len.get(oe, 0) + tail_by_len[tl][0] += 1; tail_by_len[tl][1] += int(r["caught"]) + pos = int(r["role"][4:]) + tail_by_pos[pos][0] += 1; tail_by_pos[pos][1] += int(r["caught"]) + + pc = sum(1 for r in passth if r["caught"]) + + L = [] + def p(s=""): L.append(s); print(s) + + p("# Unbundle v5 (b1+b3, auth handshake + humanized): C3 Results\n") + p(f"Baseline (n100, single-turn): **{bc}/{nb} = {bc/nb:.1%}** caught\n") + p(f"Unbundled dataset: {n} rows judged ({len(errs)} errors)\n") + p(f"Overall caught: **{c}/{n} = {c/n:.1%}**\n") + p("## Row composition") + p(f"- turn1 (preserved trie divergence): {len(t1)}") + p(f"- tail turns (one action each): {len(tail)}") + p(f"- untouched passthrough: {len(passth)}\n") + + p("## T1 slots vs baseline (same 283 trie positions)") + denom = fixed + regress + kept_c + kept_f + p(f"- baseline caught here: {fixed+kept_c}/{denom}") + p(f"- unbundled caught here: {t1_caught}/{len(t1)} = {t1_caught/max(len(t1),1):.1%}") + p(f"- **fixed (caught -> fooled): {fixed}**") + p(f"- regressed (fooled -> caught): {regress}") + p(f"- net catch reduction on T1: {fixed-regress}\n") + + p("## Tail turns (the re-rooted follow-ups)") + tc = sum(1 for r in tail if r["caught"]) + p(f"- tail caught: {tc}/{len(tail)} = {tc/max(len(tail),1):.1%}") + p("- by original tail length:") + for tl in sorted(tail_by_len): + tot, cc = tail_by_len[tl] + p(f" tail_len={tl}: {cc}/{tot} = {cc/tot:.0%}") + p("- by turn position:") + for pos in sorted(tail_by_pos): + tot, cc = tail_by_pos[pos] + p(f" turn{pos}: {cc}/{tot} = {cc/tot:.0%}") + p("") + + p("## Passthrough control (should track baseline)") + p(f"- caught: {pc}/{len(passth)} = {pc/max(len(passth),1):.1%}") + bpc = sum(base_caught.get(r["item_id"], False) for r in passth) + p(f"- same rows in baseline: {bpc}/{len(passth)} = {bpc/max(len(passth),1):.1%}\n") + + # effective per-scenario: does the ORIGINAL confuser (now split) get caught + # in ANY of its turns? (a scenario is "detected" if any split turn is caught) + by_orig = defaultdict(list) + for r in t1 + tail: + by_orig[r.get("orig_eid")].append(r["caught"]) + scen_any = sum(1 for e, v in by_orig.items() if any(v)) + scen_t1only = sum(1 for r in t1 if r["caught"]) + p("## Per-scenario view (283 split confusers)") + p(f"- caught in >=1 of its turns: {scen_any}/{len(by_orig)} = {scen_any/len(by_orig):.1%}") + p(f"- caught at the T1 (trie) slot: {scen_t1only}/{len(by_orig)} = {scen_t1only/len(by_orig):.1%}") + baseline_on_split = sum(base_caught.get(e, False) for e in by_orig) + p(f"- baseline caught these same confusers: {baseline_on_split}/{len(by_orig)} = {baseline_on_split/len(by_orig):.1%}") + + MD.write_text("\n".join(L) + "\n", encoding="utf-8") + print(f"\nwrote {MD.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() + + diff --git a/tempscripts/story_remediation/unbundle/auth_lint_v5.py b/tempscripts/story_remediation/unbundle/auth_lint_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..b4c277dfeb5106bf39c8b3706ee1ebb42901a391 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/auth_lint_v5.py @@ -0,0 +1,301 @@ +"""Read-only deterministic lint over trajectories_all_v5.jsonl. + +Flags authored-NL defects that the C3 judge picks up as "auth/identity" tells, +plus two rendering/authoring defects (raw-JSON assistant content, markdown in +user messages). Does NOT modify anything; writes per-row flags to +out/auth_lint_v5.jsonl and prints exact counts. +""" +import json, re, sys +from collections import Counter, defaultdict + +SRC = r"temp/story_remediation/unbundle/out/trajectories_all_v5.jsonl" +OUT = r"temp/story_remediation/unbundle/out/auth_lint_v5.jsonl" + +# ---- status-lock sets (from systemUpgrade/_statecheck.py) ---- +DELIVERED = {"return_delivered_order_items", "exchange_delivered_order_items", "cancel_delivered_order"} +PENDING = {"modify_pending_order_items", "modify_pending_order_address", + "return_pending_order_items", "cancel_pending_order"} + +# A verification CONFIRMATION (identity already established) -- NOT the request/ask +# ("let me verify you first"). Only >1 confirmation per conversation is a defect. +VERIFIED_RX = re.compile( + r"(you'?re (all )?verified|you are (all )?verified|i'?ve verified|i have verified" + r"|verified your (identity|account)|already verified|perfect,? verified" + r"|verified\.|you'?re (all )?set and verified|good to go)", re.I) + +# agent addressing the customer by first name -- require DIRECT-ADDRESS punctuation +# right after the name (comma / apostrophe-s / ! . / "you're") so greetings like +# "Hi! How can I help?" don't capture "How". +ADDR_RX = re.compile(r"\b(?:Thanks|Thank you|Hi|Hello|Hey|Welcome back|Alright|Great|Perfect)\s+([A-Z][a-z]+)(?=[,!.']|\s+you'?re\b|\s+you are\b)") +ADDR_RX2 = re.compile(r"\b([A-Z][a-z]+),\s+you(?:'re| are)\b") +STOP = {"Thanks","Thank","There","This","That","Your","You","Just","Once","Now","Sure","Okay","OK","Alright", + "Great","Perfect","Welcome","Hi","Hello","Hey","And","So","For","Let","Give","Could","Can","Please", + "First","Both","All","Got","Good","Happy","One","Yes","No","How","What","Before","Of","To","We"} + +EMAIL_RX = re.compile(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}") +ZIP_CTX_RX = re.compile(r"zip\D{0,12}(\d{5})", re.I) + +MD_BOLD_RX = re.compile(r"\*\*[^*\n]+\*\*|__[^_\n]+__") +MD_LIST_RX = re.compile(r"(^|\n)\s*(\d+\.\s+\S|[-*]\s+\S)") +MD_HEADER_RX = re.compile(r"(^|\n)#{1,6}\s+\S") + + +def convo_turns(r): + """Yield (role, content) NL turns the judge sees: history user/asst + query.""" + for h in r.get("history", []): + role = h.get("role"); c = h.get("content") + if role in ("user", "assistant") and c: + yield role, c + if r.get("query"): + yield "user", r["query"] + + +def auth_identity(r): + """(method, first, last, zip, email) from find_user_id_* + get_user_details, + looking in BOTH the row's own calls AND the embedded history (tail rows carry + their auth handshake in history, not in `calls`).""" + first = last = zipc = email = None; method = None + + def take_call(n, a, out): + nonlocal first, last, zipc, email, method + if n.startswith("find_user_id_"): + method = method or n + first = first or (a.get("first_name") or "").strip() or None + last = last or (a.get("last_name") or "").strip() or None + zipc = zipc or (str(a.get("zip")) if a.get("zip") else None) + email = email or (a.get("email") or "").strip() or None + if n == "get_user_details" and out: + try: + o = json.loads(out) + nm = o.get("name", {}) + first = first or nm.get("first_name") + last = last or nm.get("last_name") + email = email or o.get("email") + zipc = zipc or (o.get("address", {}) or {}).get("zip") + except Exception: + pass + + for c in r.get("calls", []): + take_call(c["name"], c.get("arguments", {}) or {}, c.get("output")) + + # history: assistant tool_calls (args) + following tool outputs + hist = r.get("history", []) + for i, h in enumerate(hist): + for tc in h.get("tool_calls") or []: + n = tc.get("name") or (tc.get("function") or {}).get("name", "") + a = tc.get("arguments") or (tc.get("function") or {}).get("arguments", {}) + if isinstance(a, str): + try: a = json.loads(a) + except Exception: a = {} + take_call(n, a or {}, None) + # get_user_details output json anywhere in history tool messages + for h in hist: + if h.get("role") == "tool" and h.get("content"): + try: + o = json.loads(h["content"]) + if isinstance(o, dict) and "name" in o and isinstance(o["name"], dict): + nm = o["name"] + first = first or nm.get("first_name") + last = last or nm.get("last_name") + email = email or o.get("email") + zipc = zipc or (o.get("address", {}) or {}).get("zip") + except Exception: + pass + return method, first, last, zipc, email + + +def call_arg_values(r): + """All string values that appear as tool-call arguments (row calls + history + tool_calls). Spoken zips/emails matching these are legitimate OPERATION TARGETS + (e.g. a requested new email / new shipping zip), not identity mismatches.""" + vals = set() + + def walk(a): + if isinstance(a, dict): + for v in a.values(): + walk(v) + elif isinstance(a, list): + for v in a: + walk(v) + elif a is not None: + vals.add(str(a).lower()) + + for c in r.get("calls", []): + walk(c.get("arguments", {})) + for h in r.get("history", []): + for tc in h.get("tool_calls") or []: + a = tc.get("arguments") or (tc.get("function") or {}).get("arguments", {}) + if isinstance(a, str): + try: a = json.loads(a) + except Exception: a = {} + walk(a) + return vals + + +def order_statuses(r): + """order_id -> status, ONLY from get_order_details READS (never mutation outputs + like 'address_updated'/'exchange requested'), pairing each call to its output.""" + st = {} + + def add(out): + try: + o = json.loads(out) + oid = str(o.get("order_id", "")).lstrip("#") + # get_order_details outputs carry item/fulfillment structure + if oid and "status" in o and ("items" in o or "fulfillments" in o): + st[oid] = o["status"] + except Exception: + pass + + for c in r.get("calls", []): + if c["name"] == "get_order_details" and c.get("output"): + add(c["output"]) + # history: pair assistant get_order_details tool_calls to following tool msgs + hist = r.get("history", []) + for i, h in enumerate(hist): + for tc in h.get("tool_calls") or []: + n = tc.get("name") or (tc.get("function") or {}).get("name", "") + if n != "get_order_details": + continue + # find the next tool message output + for j in range(i + 1, len(hist)): + if hist[j].get("role") == "tool" and hist[j].get("content"): + add(hist[j]["content"]); break + # also any get_order_details-shaped tool msg (belt and suspenders) + for h in hist: + if h.get("role") == "tool" and h.get("content"): + add(h["content"]) + return st + + +def lint_row(r, name_vocab=frozenset()): + flags = [] + method, first, last, zipc, email = auth_identity(r) + allowed = {x.lower() for x in (first, last) if x} + turns = list(convo_turns(r)) + argvals = call_arg_values(r) + + # A. name mismatch (agent addressing a wrong first name that is a real customer name) + wrong_names = set() + for role, c in turns: + if role != "assistant": + continue + for m in list(ADDR_RX.finditer(c)) + list(ADDR_RX2.finditer(c)): + tok = m.group(1) + if tok in STOP: + continue + if allowed and tok.lower() not in allowed: + wrong_names.add(tok) + if wrong_names: + flags.append(("name_mismatch", {"spoken": sorted(wrong_names), + "auth_first": first, "auth_last": last})) + + # B. duplicate verification + vcount = sum(1 for role, c in turns if role == "assistant" and VERIFIED_RX.search(c)) + if vcount > 1: + flags.append(("dup_verification", {"count": vcount})) + + # C. zip mismatch (any spoken zip in a 'zip' context that != auth zip) + if zipc: + spoken_zips = set() + for role, c in turns: + for m in ZIP_CTX_RX.finditer(c): + spoken_zips.add(m.group(1)) + bad = {z for z in spoken_zips if z != str(zipc) and z.lower() not in argvals} + if bad: + flags.append(("zip_mismatch", {"spoken": sorted(bad), "auth_zip": str(zipc)})) + + # D. email mismatch (spoken email != auth/account email) + if email: + spoken = set() + for role, c in turns: + for m in EMAIL_RX.finditer(c): + spoken.add(m.group(0).lower()) + bad = {e for e in spoken if e != email.lower() and e not in argvals} + if bad: + flags.append(("email_mismatch", {"spoken": sorted(bad), "auth_email": email})) + + # E. status-lock (tool name asserts a status the order doesn't have) + st = order_statuses(r) + for i, c in enumerate(r["calls"]): + n = c["name"] + oid = str((c.get("arguments") or {}).get("order_id", "")).lstrip("#") + s = st.get(oid) + if not s: + continue + if n in DELIVERED and s != "delivered": + flags.append(("status_lock", {"call": n, "order": oid, "status": s, "needs": "delivered"})) + if n in PENDING and s != "pending": + flags.append(("status_lock", {"call": n, "order": oid, "status": s, "needs": "pending"})) + + # F. raw-JSON assistant content + for role, c in turns: + if role == "assistant": + cs = c.strip() + if cs.startswith("{") and cs.endswith("}"): + try: + j = json.loads(cs) + if isinstance(j, dict): + flags.append(("json_assistant", {"snippet": cs[:80]})) + break + except Exception: + if '"message"' in cs or '":' in cs: + flags.append(("json_assistant", {"snippet": cs[:80]})) + break + + # G. markdown in user messages + md = [] + for role, c in turns: + if role != "user": + continue + if MD_BOLD_RX.search(c): + md.append("bold") + if MD_LIST_RX.search(c): + md.append("list") + if MD_HEADER_RX.search(c): + md.append("header") + if md: + flags.append(("markdown_user", {"kinds": sorted(set(md))})) + + return flags + + +def main(): + rows = [json.loads(l) for l in open(SRC, encoding="utf-8")] + # global first-name vocabulary from auth calls / account details + name_vocab = set() + for r in rows: + _, f, l, _, _ = auth_identity(r) + for x in (f, l): + if x: + name_vocab.add(x.lower()) + cat = Counter() + per_orig = defaultdict(set) + out = [] + for r in rows: + fl = lint_row(r, name_vocab) + if fl: + for k, _ in fl: + cat[k] += 1 + out.append({"example_id": r["example_id"], + "orig_eid": r["metadata"].get("orig_eid"), + "role": r["metadata"].get("unbundle_role"), + "flags": fl}) + for k, _ in fl: + per_orig[k].add(r["metadata"].get("orig_eid")) + with open(OUT, "w", encoding="utf-8") as f: + for o in out: + f.write(json.dumps(o) + "\n") + + print(f"rows scanned: {len(rows)}") + print(f"rows with >=1 flag: {len(out)}") + print("\n=== defect counts (per ROW) ===") + order = ["name_mismatch","dup_verification","zip_mismatch","email_mismatch", + "status_lock","json_assistant","markdown_user"] + for k in order: + print(f" {k:16s} rows={cat[k]:4d} distinct_episodes={len(per_orig[k])}") + print(f"\nwrote {OUT}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/author_q1_fix_v3.py b/tempscripts/story_remediation/unbundle/author_q1_fix_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..64c0c06fb0b17ec8a148517a855b3568a74fb83d --- /dev/null +++ b/tempscripts/story_remediation/unbundle/author_q1_fix_v3.py @@ -0,0 +1,110 @@ +"""Targeted q1 fix for the 23 auth-in-history candidates. + +Their authentication now lives in the cleaned pre-history, so q1 must NOT greet +or restate name/ZIP/email. v2 authored several that still said "Hi, I'm X, ZIP +Y" -> a redundant re-introduction tell. Re-author ONLY q1 for these rows with an +already-verified framing. ack1/turns are reused from authored_v2.json unchanged. + +Cache -> out/authored_q1fix_v3.json {eid: {"q1": ...}} +Run: python -u temp/story_remediation/unbundle/author_q1_fix_v3.py +""" +from __future__ import annotations +import json, re, sys, logging +from pathlib import Path +import yaml + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) +from datasetreview.llm_client import make_judge # noqa: E402 + +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +AUTHORED = HERE / "out" / "authored_v2.json" +OUT = HERE / "out" / "authored_q1fix_v3.json" +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +AUTH_LEAD = ("find_user_id_by_name_zip", "get_user_details") +_TOK = re.compile(r"#W\d+|gift_card_\w+|\bgc_\w+|\b\d{8,}\b") + +SYS = ( + "The customer has ALREADY been greeted and their identity is ALREADY verified " + "earlier in the conversation. Write ONLY their next message: the request that " + "makes the agent perform the listed actions.\n\n" + "Rules:\n" + "1. Do NOT greet ('hi/hello') and do NOT restate name, ZIP, email, or phone. " + "Jump straight to the request.\n" + "2. The message must motivate exactly the listed actions, nothing more.\n" + "3. Copy every identifier (order #W..., item numbers, gift card ids, amounts, " + "quoted text) verbatim from the arguments.\n" + "4. Natural, human, concise. NO em dashes or en dashes.\n" + 'Return ONLY JSON: {"q1": ""}' +) + + +def toks(*xs): + s = set() + for x in xs: + if x: + s |= set(_TOK.findall(x if isinstance(x, str) else json.dumps(x))) + return s + + +def main(): + rows = {json.loads(l)["example_id"]: json.loads(l) + for l in open(N100, encoding="utf-8") if l.strip()} + authored = json.loads(AUTHORED.read_text(encoding="utf-8")) + + def hist(r): + return r.get("history") or (r.get("metadata") or {}).get("history") or [] + + targets = [] + for eid, r in rows.items(): + if eid not in authored or "q1" not in authored[eid]: + continue + if any(t["name"] == "find_user_id_by_name_zip" + for m in hist(r) for t in (m.get("tool_calls") or [])): + targets.append(eid) + print(f"auth-in-history targets: {len(targets)}") + + judge = make_judge(cfg["model"]) + out = json.loads(OUT.read_text(encoding="utf-8")) if OUT.exists() else {} + for eid in targets: + if eid in out: + continue + r = rows[eid]; ad = r["metadata"]["anchor_depth"]; K = ad + 1 + calls = r["calls"] + fu = next(t for m in hist(r) for t in (m.get("tool_calls") or []) + if t["name"] == "find_user_id_by_name_zip") + a = fu.get("arguments", {}) + ident = {str(a.get("first_name", "")).lower(), str(a.get("last_name", "")).lower()} - {""} + user = json.dumps({ + "original_customer_message": r["query"], + "actions_to_trigger": [{"tool": c["name"], "arguments": c.get("arguments", {})} + for c in calls[:K]], + }, ensure_ascii=False, indent=2) + allowed = toks(r["query"], *[c.get("arguments", {}) for c in calls]) + chosen = None + for _ in range(3): + try: + res = judge.judge({"system": SYS, "user": user}) + except Exception: + continue + q1 = (res.get("q1") or "").strip() + if not q1 or "\u2014" in q1 or "\u2013" in q1 or " - " in q1: + continue + if toks(q1) - allowed: + continue + if any(tok and len(tok) >= 3 and tok in q1.lower() for tok in ident): + continue + chosen = q1; break + if chosen: + out[eid] = {"q1": chosen} + else: + print(f" FAILED {eid} (keeping v2 q1)") + OUT.write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8") + print(f"fixed {len(out)}/{len(targets)} -> {OUT.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/author_splits.py b/tempscripts/story_remediation/unbundle/author_splits.py new file mode 100644 index 0000000000000000000000000000000000000000..3266358e9b377bf8294c172a5a544bb228b70dd1 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/author_splits.py @@ -0,0 +1,185 @@ +"""LLM authoring pass for the full unbundle rollout. + +For every candidate (metadata.anchor_depth>=2 AND a non-empty tail), ask the +model to rewrite the single bundled query into natural multi-turn dialogue: + - q1: motivates ONLY turn 1 (auth + lookups + the divergence action F). + - turns[]: one entry per tail call, each a natural user follow-up + a short + assistant confirmation (bridge). One action per turn (matches real tau2's + ~92% one-call turns). + +CRITICAL invariants enforced by validation (retry on failure, skip if hopeless): + - len(turns) == len(tail_calls) + - no em dashes + - no NEW identifiers: every #W.../gift_card_.../long-digit token in the + generated text must already appear in the original query or a call's args + - tail-only ids must NOT leak into q1 (keeps turn 1 narrowed) + +Caches to out/authored.json ({eid: {q1, turns:[{user,bridge}], skipped?}}). +Re-runs only fill missing/failed eids (idempotent). + +Run: python -u temp/story_remediation/unbundle/author_splits.py +""" +from __future__ import annotations +import json, re, sys, threading +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +import logging +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) +from datasetreview.llm_client import make_judge # noqa: E402 + +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +AUTHORED = HERE / "out" / "authored.json" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +WORKERS = 8 + +SYS = ( + "You rewrite ONE retail customer-support conversation so it reads as natural, " + "multi-turn dialogue instead of a single giant request.\n\n" + "You are given the customer's original bundled message and the ordered list of " + "backend actions the agent took (tool name + arguments). The FIRST GROUP of " + "actions (authentication + lookups + the primary action) all happen in turn 1. " + "Each remaining TAIL action becomes its own separate later turn.\n\n" + "Return a JSON object exactly like:\n" + '{ "q1": "", "turns": [ {"user":"","bridge":""}, ... ] }\n\n' + "Rules:\n" + "1. q1 motivates ONLY the turn-1 actions. Do NOT mention or hint at any tail action.\n" + "2. Provide exactly one entry in \"turns\" per tail action, in the same order. Each " + "\"user\" message must naturally trigger exactly that one action; \"bridge\" is the " + "agent's short confirming reply that precedes it.\n" + "3. The customer is ALREADY authenticated after turn 1. Later turns must NOT ask to " + "re-verify identity or re-share name / ZIP / email / phone.\n" + "4. Copy every identifier verbatim from the provided arguments: order ids (#W...), " + "item / product numbers, gift card ids, dollar amounts, and any exact quoted message " + "or review text. NEVER invent, drop, or alter an id.\n" + "5. Natural, human, concise. Vary the phrasing of follow-ups (for example 'Thanks, " + "one more thing', 'Got it, could you also', 'Perfect. Now'). Contractions are good.\n" + "6. Absolutely NO em dashes or en dashes. Use commas, periods, or parentheses.\n" + "Return ONLY the JSON object." +) + +_TOK = re.compile(r"#W\d+|gift_card_\w+|\bgc_\w+|\b\d{8,}\b") + + +def toks(*strings): + s = set() + for x in strings: + if x: + s |= set(_TOK.findall(x if isinstance(x, str) else json.dumps(x))) + return s + + +def build_user(row, K): + calls = row["calls"] + def fmt(c): + return {"tool": c["name"], "arguments": c.get("arguments", {})} + turn1 = [fmt(c) for c in calls[:K]] + tail = [fmt(c) for c in calls[K:]] + return json.dumps({ + "original_customer_message": row["query"], + "turn1_actions": turn1, + "tail_actions_each_its_own_turn": tail, + }, ensure_ascii=False, indent=2) + + +def validate(row, K, out): + calls = row["calls"] + tail = calls[K:] + if not isinstance(out, dict): + return "not a dict" + q1 = out.get("q1"); turns = out.get("turns") + if not isinstance(q1, str) or not q1.strip(): + return "empty q1" + if not isinstance(turns, list) or len(turns) != len(tail): + return f"turns len {len(turns) if isinstance(turns,list) else '?'} != tail {len(tail)}" + texts = [q1] + [str(t.get("user", "")) + " " + str(t.get("bridge", "")) for t in turns] + for t in texts: + if "\u2014" in t or "\u2013" in t or " - " in t: + return "dash present" + # allowed identifier universe = original query + all call args + allowed = toks(row["query"], *[c.get("arguments", {}) for c in calls]) + gen = toks(*texts) + new = gen - allowed + if new: + return f"new ids {sorted(new)[:4]}" + # tail-only ids must not leak into q1 + prefix_ids = toks(row["query"]) & toks(*[c.get("arguments", {}) for c in calls[:K]]) + tail_ids = toks(*[c.get("arguments", {}) for c in tail]) - toks(*[c.get("arguments", {}) for c in calls[:K]]) + leak = toks(q1) & tail_ids + if leak: + return f"tail id leaked into q1 {sorted(leak)}" + for t in turns: + if not isinstance(t, dict) or not str(t.get("user", "")).strip(): + return "empty tail user" + return None + + +def main(): + rows = {json.loads(l)["example_id"]: json.loads(l) + for l in open(N100, encoding="utf-8") if l.strip()} + cand = [] + for eid, r in rows.items(): + md = r.get("metadata") or {}; ad = md.get("anchor_depth") + calls = r.get("calls") or [] + if ad is None or ad < 2 or len(calls) <= ad + 1: + continue + cand.append(eid) + cand.sort() + print(f"candidates: {len(cand)}") + + authored = {} + if AUTHORED.exists(): + authored = json.loads(AUTHORED.read_text(encoding="utf-8")) + todo = [e for e in cand if e not in authored or authored[e].get("_err")] + print(f"already done: {len(cand)-len(todo)} to author: {len(todo)}") + + judge = make_judge(cfg["model"]) + lock = threading.Lock() + done = [0] + + def work(eid): + r = rows[eid]; K = r["metadata"]["anchor_depth"] + 1 + user = build_user(r, K) + last = None + for attempt in range(3): + try: + out = judge.judge({"system": SYS, "user": user}) + except Exception as e: # noqa + last = f"api:{e}"; continue + err = validate(r, K, out) + if err is None: + rec = {"q1": out["q1"].strip(), + "turns": [{"user": t["user"].strip(), + "bridge": str(t.get("bridge", "")).strip()} for t in out["turns"]]} + with lock: + authored[eid] = rec; done[0] += 1 + if done[0] % 20 == 0: + AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8") + print(f" ...{done[0]}/{len(todo)}") + return + last = err + with lock: + authored[eid] = {"_err": last or "unknown"} + print(f" SKIP {eid}: {last}") + + AUTHORED.parent.mkdir(parents=True, exist_ok=True) + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + list(ex.map(work, todo)) + AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8") + + ok = sum(1 for e in cand if not authored.get(e, {}).get("_err") and "q1" in authored.get(e, {})) + err = [e for e in cand if authored.get(e, {}).get("_err")] + print(f"\nauthored ok: {ok}/{len(cand)} failed/skipped: {len(err)}") + for e in err[:15]: + print(" ", e, authored[e]["_err"]) + print(f"wrote {AUTHORED.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/author_splits_v2.py b/tempscripts/story_remediation/unbundle/author_splits_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..ed41582870c10f75352f6968c4320f13ac4eabd7 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/author_splits_v2.py @@ -0,0 +1,185 @@ +"""V2 authoring: fix the bridge-ordering logic bug. + +The v1 'bridge' confirmed the action the customer was ABOUT to request, which +produced a time-travel contradiction (agent: "I've filed the claim" -> user: +"please file the claim" -> agent files it). C3 caught ~94% of tail turns on that. + +V2 schema makes every acknowledgement PAST-TENSE and about its OWN turn's action +only. An ack is only ever shown once its turn is completed, so no confirmation +can precede its request: + + { + "q1": "", + "ack1": "", + "turns":[ {"user":"", "ack":""}, ... ] # one per tail call, in order + } + +Cache -> out/authored_v2.json (idempotent; re-fills only missing/failed). +Run: python -u temp/story_remediation/unbundle/author_splits_v2.py +""" +from __future__ import annotations +import json, re, sys, threading, logging +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) +from datasetreview.llm_client import make_judge # noqa: E402 + +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +AUTHORED = HERE / "out" / "authored_v2.json" +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +WORKERS = 8 + +SYS = ( + "You rewrite ONE retail customer-support conversation so it reads as a natural, " + "coherent multi-turn dialogue instead of a single giant request. The conversation " + "must make perfect sense read start to finish.\n\n" + "You are given the customer's original bundled message and the ordered backend " + "actions the agent took (tool name + arguments). The FIRST GROUP of actions " + "(authentication + lookups + the first real action) all happen in TURN 1. Each " + "remaining TAIL action becomes its own separate later turn, in order.\n\n" + "Return a JSON object EXACTLY like:\n" + '{ "q1": "", "ack1": "",\n' + ' "turns": [ {"user":"","ack":""}, ... ] }\n\n' + "THE #1 RULE (this is what you are fixing): An agent reply may ONLY confirm actions " + "that have ALREADY been performed. It must be PAST TENSE and describe ONLY its own " + "turn's action. NEVER let an agent say it did something the customer has not yet " + "asked for. Do not preview or promise the next step.\n" + " - ack1 confirms ONLY the turn-1 actions. It must NOT mention any tail action.\n" + " - Each turns[k].ack confirms ONLY that same turn's single action.\n\n" + "Other rules:\n" + "1. q1 motivates ONLY the turn-1 actions. Do NOT mention or hint at any tail action.\n" + "2. Exactly one entry in \"turns\" per tail action, same order. Each \"user\" message " + "naturally triggers exactly that one action and nothing else.\n" + "3. The customer is ALREADY authenticated after turn 1. Later turns must NOT re-verify " + "identity or re-share name / ZIP / email / phone (unless an action's arguments are " + "about a DIFFERENT person, e.g. looking up a relative, which is fine).\n" + "4. Do NOT re-request anything already done in an earlier turn.\n" + "5. Copy every identifier verbatim from the arguments: order ids (#W...), item / " + "product numbers, gift card ids, dollar amounts, exact quoted message or review text. " + "NEVER invent, drop, or alter an id.\n" + "6. Natural, human, concise. Vary follow-up phrasing ('Thanks, one more thing', 'Got " + "it, could you also', 'Perfect, now'). Contractions are good.\n" + "7. Absolutely NO em dashes or en dashes. Use commas, periods, or parentheses.\n" + "Return ONLY the JSON object." +) + +_TOK = re.compile(r"#W\d+|gift_card_\w+|\bgc_\w+|\b\d{8,}\b") + + +def toks(*strings): + s = set() + for x in strings: + if x: + s |= set(_TOK.findall(x if isinstance(x, str) else json.dumps(x))) + return s + + +def build_user(row, K): + calls = row["calls"] + fmt = lambda c: {"tool": c["name"], "arguments": c.get("arguments", {})} + return json.dumps({ + "original_customer_message": row["query"], + "turn1_actions": [fmt(c) for c in calls[:K]], + "tail_actions_each_its_own_turn": [fmt(c) for c in calls[K:]], + }, ensure_ascii=False, indent=2) + + +def validate(row, K, out): + calls = row["calls"]; tail = calls[K:] + if not isinstance(out, dict): + return "not a dict" + q1 = out.get("q1"); ack1 = out.get("ack1"); turns = out.get("turns") + if not isinstance(q1, str) or not q1.strip(): + return "empty q1" + if not isinstance(ack1, str) or not ack1.strip(): + return "empty ack1" + if not isinstance(turns, list) or len(turns) != len(tail): + return f"turns len {len(turns) if isinstance(turns,list) else '?'} != tail {len(tail)}" + texts = [q1, ack1] + for t in turns: + if not isinstance(t, dict) or not str(t.get("user", "")).strip() or not str(t.get("ack", "")).strip(): + return "empty turn user/ack" + texts += [t["user"], t["ack"]] + for t in texts: + if "\u2014" in t or "\u2013" in t or " - " in t: + return "dash present" + allowed = toks(row["query"], *[c.get("arguments", {}) for c in calls]) + new = toks(*texts) - allowed + if new: + return f"new ids {sorted(new)[:4]}" + tail_ids = (toks(*[c.get("arguments", {}) for c in tail]) + - toks(*[c.get("arguments", {}) for c in calls[:K]])) + leak = toks(q1, ack1) & tail_ids + if leak: + return f"tail id leaked into q1/ack1 {sorted(leak)}" + return None + + +def main(): + rows = {json.loads(l)["example_id"]: json.loads(l) + for l in open(N100, encoding="utf-8") if l.strip()} + cand = [] + for eid, r in rows.items(): + md = r.get("metadata") or {}; ad = md.get("anchor_depth") + calls = r.get("calls") or [] + if ad is None or ad < 2 or len(calls) <= ad + 1: + continue + cand.append(eid) + cand.sort() + print(f"candidates: {len(cand)}") + + authored = {} + if AUTHORED.exists(): + authored = json.loads(AUTHORED.read_text(encoding="utf-8")) + todo = [e for e in cand if e not in authored or authored[e].get("_err")] + print(f"already done: {len(cand)-len(todo)} to author: {len(todo)}") + + judge = make_judge(cfg["model"]) + lock = threading.Lock(); done = [0] + + def work(eid): + r = rows[eid]; K = r["metadata"]["anchor_depth"] + 1 + user = build_user(r, K); last = None + for _ in range(3): + try: + out = judge.judge({"system": SYS, "user": user}) + except Exception as e: # noqa + last = f"api:{e}"; continue + err = validate(r, K, out) + if err is None: + rec = {"q1": out["q1"].strip(), "ack1": out["ack1"].strip(), + "turns": [{"user": t["user"].strip(), "ack": t["ack"].strip()} + for t in out["turns"]]} + with lock: + authored[eid] = rec; done[0] += 1 + if done[0] % 20 == 0: + AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8") + print(f" ...{done[0]}/{len(todo)}") + return + last = err + with lock: + authored[eid] = {"_err": last or "unknown"} + print(f" SKIP {eid}: {last}") + + AUTHORED.parent.mkdir(parents=True, exist_ok=True) + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + list(ex.map(work, todo)) + AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8") + + ok = sum(1 for e in cand if "q1" in authored.get(e, {}) and not authored.get(e, {}).get("_err")) + err = [e for e in cand if authored.get(e, {}).get("_err")] + print(f"\nauthored ok: {ok}/{len(cand)} failed/skipped: {len(err)}") + for e in err[:15]: + print(" ", e, authored[e]["_err"]) + print(f"wrote {AUTHORED.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/author_splits_v4.py b/tempscripts/story_remediation/unbundle/author_splits_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..b7d79ee219e15e10e8b874fe787108ca0379159d --- /dev/null +++ b/tempscripts/story_remediation/unbundle/author_splits_v4.py @@ -0,0 +1,192 @@ +"""V4 authoring: humanize the split rows' dialogue to kill the two authorable C3 +tells found in v3 tail reasoning: + (a) "customer front-loads name+ZIP+order in one tidy sentence" -> too clean. + (b) "agent verified silently, never asked" -> no auth handshake. + +Fix is PROSE ONLY. The tool calls are never touched (guaranteed in the builder). +q1 is now framed as the customer's REPLY to the agent asking them to verify their +identity, so it opens with mild human disfluency and provides name/ZIP naturally +rather than dumping everything up front. All user turns carry light, realistic +friction. Everything else (past-tense own-turn acks, verbatim ids, no dashes) is +unchanged from v2. + +Cache -> out/authored_v4.json (idempotent). Run: + python -u temp/story_remediation/unbundle/author_splits_v4.py +""" +from __future__ import annotations +import json, re, sys, threading, logging +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) +from datasetreview.llm_client import make_judge # noqa: E402 + +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +AUTHORED = HERE / "out" / "authored_v4.json" +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +WORKERS = 8 + +SYS = ( + "You rewrite ONE retail customer-support conversation so it reads as a natural, " + "coherent multi-turn dialogue instead of a single giant request. It must make " + "perfect sense read start to finish, and above all it must sound like a REAL human " + "customer, not a tidy scripted prompt.\n\n" + "Framing of the opening: the agent has greeted the customer, the customer said they " + "need help, and the agent has just asked them to VERIFY their identity by giving " + "their name and ZIP code. So TURN 1 (q1) is the customer's REPLY to that request.\n\n" + "You are given the customer's original bundled message and the ordered backend " + "actions the agent took (tool name + arguments). The FIRST GROUP of actions " + "(authentication + lookups + the first real action) all happen in TURN 1. Each " + "remaining TAIL action becomes its own separate later turn, in order.\n\n" + "Return a JSON object EXACTLY like:\n" + '{ "q1": "", "ack1": "",\n' + ' "turns": [ {"user":"","ack":""}, ... ] }\n\n' + "THE #1 RULE: An agent reply may ONLY confirm actions ALREADY performed. It must be " + "PAST TENSE and describe ONLY its own turn's action. NEVER let an agent say it did " + "something the customer has not yet asked for. Do not preview or promise a next step.\n" + " - ack1 confirms ONLY the turn-1 actions. It must NOT mention any tail action.\n" + " - Each turns[k].ack confirms ONLY that same turn's single action.\n\n" + "HUMANIZE (this is the new part, do it well):\n" + "A. q1 is a reply to 'can you verify your name and ZIP'. Start it the way a real " + "person answers: a small hesitation or filler is good ('Yeah, sure,', 'Oh, right,', " + "'Um, ok,', 'Sure thing,'), then give the name and ZIP, THEN say what they actually " + "want. Do NOT machine-list identifiers in one clinical sentence.\n" + "B. Give the customer mild, realistic friction across turns: slight informality, an " + "occasional 'I think', 'if that makes sense', 'sorry', a little context about WHY " + "they want it. Keep it believable, never over the top, never emoji.\n" + "C. Vary sentence shape and follow-up openers so no two turns feel stamped from a " + "template ('Thanks, one more thing', 'Ok so', 'Got it. Could you also', 'Perfect, " + "now', 'Oh and').\n\n" + "Hard rules:\n" + "1. q1 motivates ONLY the turn-1 actions. Do NOT mention or hint at any tail action.\n" + "2. Exactly one entry in \"turns\" per tail action, same order. Each \"user\" message " + "naturally triggers exactly that one action and nothing else.\n" + "3. The customer is ALREADY authenticated after turn 1. Later turns must NOT re-verify " + "identity or re-share name / ZIP / email / phone (unless an action's arguments are " + "about a DIFFERENT person, which is fine).\n" + "4. Do NOT re-request anything already done in an earlier turn.\n" + "5. Copy every identifier verbatim from the arguments: order ids (#W...), item / " + "product numbers, gift card ids, dollar amounts, exact quoted message or review text. " + "NEVER invent, drop, or alter an id.\n" + "6. Absolutely NO em dashes or en dashes. Use commas, periods, or parentheses.\n" + "Return ONLY the JSON object." +) + +_TOK = re.compile(r"#W\d+|gift_card_\w+|\bgc_\w+|\b\d{8,}\b") + + +def toks(*strings): + s = set() + for x in strings: + if x: + s |= set(_TOK.findall(x if isinstance(x, str) else json.dumps(x))) + return s + + +def build_user(row, K): + calls = row["calls"] + fmt = lambda c: {"tool": c["name"], "arguments": c.get("arguments", {})} + return json.dumps({ + "original_customer_message": row["query"], + "turn1_actions": [fmt(c) for c in calls[:K]], + "tail_actions_each_its_own_turn": [fmt(c) for c in calls[K:]], + }, ensure_ascii=False, indent=2) + + +def validate(row, K, out): + calls = row["calls"]; tail = calls[K:] + if not isinstance(out, dict): + return "not a dict" + q1 = out.get("q1"); ack1 = out.get("ack1"); turns = out.get("turns") + if not isinstance(q1, str) or not q1.strip(): + return "empty q1" + if not isinstance(ack1, str) or not ack1.strip(): + return "empty ack1" + if not isinstance(turns, list) or len(turns) != len(tail): + return f"turns len {len(turns) if isinstance(turns,list) else '?'} != tail {len(tail)}" + texts = [q1, ack1] + for t in turns: + if not isinstance(t, dict) or not str(t.get("user", "")).strip() or not str(t.get("ack", "")).strip(): + return "empty turn user/ack" + texts += [t["user"], t["ack"]] + for t in texts: + if "\u2014" in t or "\u2013" in t or " - " in t: + return "dash present" + allowed = toks(row["query"], *[c.get("arguments", {}) for c in calls]) + new = toks(*texts) - allowed + if new: + return f"new ids {sorted(new)[:4]}" + tail_ids = (toks(*[c.get("arguments", {}) for c in tail]) + - toks(*[c.get("arguments", {}) for c in calls[:K]])) + leak = toks(q1, ack1) & tail_ids + if leak: + return f"tail id leaked into q1/ack1 {sorted(leak)}" + return None + + +def main(): + rows = {json.loads(l)["example_id"]: json.loads(l) + for l in open(N100, encoding="utf-8") if l.strip()} + cand = [] + for eid, r in rows.items(): + md = r.get("metadata") or {}; ad = md.get("anchor_depth") + calls = r.get("calls") or [] + if ad is None or ad < 2 or len(calls) <= ad + 1: + continue + cand.append(eid) + cand.sort() + print(f"candidates: {len(cand)}") + + authored = {} + if AUTHORED.exists(): + authored = json.loads(AUTHORED.read_text(encoding="utf-8")) + todo = [e for e in cand if e not in authored or authored[e].get("_err")] + print(f"already done: {len(cand)-len(todo)} to author: {len(todo)}") + + judge = make_judge(cfg["model"]) + lock = threading.Lock(); done = [0] + + def work(eid): + r = rows[eid]; K = r["metadata"]["anchor_depth"] + 1 + user = build_user(r, K); last = None + for _ in range(3): + try: + out = judge.judge({"system": SYS, "user": user}) + except Exception as e: # noqa + last = f"api:{e}"; continue + err = validate(r, K, out) + if err is None: + rec = {"q1": out["q1"].strip(), "ack1": out["ack1"].strip(), + "turns": [{"user": t["user"].strip(), "ack": t["ack"].strip()} + for t in out["turns"]]} + with lock: + authored[eid] = rec; done[0] += 1 + if done[0] % 20 == 0: + AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8") + print(f" ...{done[0]}/{len(todo)}") + return + last = err + with lock: + authored[eid] = {"_err": last or "unknown"} + print(f" SKIP {eid}: {last}") + + AUTHORED.parent.mkdir(parents=True, exist_ok=True) + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + list(ex.map(work, todo)) + AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8") + + ok = sum(1 for e in cand if "q1" in authored.get(e, {}) and not authored.get(e, {}).get("_err")) + err = [e for e in cand if authored.get(e, {}).get("_err")] + print(f"\nauthored ok: {ok}/{len(cand)} failed/skipped: {len(err)}") + for e in err[:15]: + print(" ", e, authored[e]["_err"]) + print(f"wrote {AUTHORED.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/build_all.py b/tempscripts/story_remediation/unbundle/build_all.py new file mode 100644 index 0000000000000000000000000000000000000000..3fb4d081604de63fdaae9842fe70024c738eb9a4 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/build_all.py @@ -0,0 +1,139 @@ +"""Full unbundle build: split every authored candidate's single bundled turn +into T1 (prefix + F, the preserved trie divergence) plus ONE later turn per +tail call (one action per turn, matching real tau2 and the prototype finding +that multi-call tail turns get caught 6/6 vs single-call 1/4). + +Base = original n100 (795 rows). Each authored candidate row is REPLACED by its +split rows; all other rows (non-candidates + any skipped candidate) pass through +unchanged. Writes out/trajectories_all.jsonl. + +History chaining per tail turn i (0-based, i in 0..N-1): + orig_history + + user(q1) + + assistant(tool_calls = prefix+F) + tool msgs (verbatim outputs) + + assistant(turns[0].bridge) # confirms turn 1 + + for j in 0..i-1: + user(turns[j].user) + assistant(tool_calls=[tail[j]]) + tool msg + assistant(turns[j+1].bridge) # confirms tail[j] + -> current row: query=turns[i].user, calls=[tail[i]] + +Auth lives in the prefix (anchor_depth>=2), so tail turns never re-auth. +Run: python -u temp/story_remediation/unbundle/build_all.py +""" +from __future__ import annotations +import json, copy +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +AUTHORED = HERE / "out" / "authored.json" +OUT = HERE / "out" / "trajectories_all.jsonl" + +AUTH_TOOLS = {"find_user_id_by_name_zip", "find_user_id_by_email", + "find_user_id_by_phone", "authenticate", "find_user"} + + +def hist_of(r): + return r.get("history") or (r.get("metadata") or {}).get("history") or [] + + +def umsg(content): + return {"role": "user", "content": content, "tool_calls": [], "tool_call_id": None} + + +def amsg(content=None, tool_calls=None): + return {"role": "assistant", "content": content, + "tool_calls": copy.deepcopy(tool_calls) if tool_calls else [], + "tool_call_id": None} + + +def tmsg(call): + return {"role": "tool", "content": call.get("output"), + "tool_calls": [], "tool_call_id": None} + + +def main(): + rows = [json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()] + by_eid = {r["example_id"]: r for r in rows} + authored = json.loads(AUTHORED.read_text(encoding="utf-8")) + ok = {e: a for e, a in authored.items() if "q1" in a and not a.get("_err")} + print(f"authored ok: {len(ok)} skipped: {len(authored)-len(ok)}") + + out = [] + split_eids = set() + reauth_flags = [] + for r in rows: + eid = r["example_id"] + if eid not in ok: + out.append(r) # non-candidate or skipped -> unchanged + continue + sp = ok[eid] + md = r["metadata"]; ad = md["anchor_depth"] + calls = r["calls"] + prefixF = calls[:ad + 1] + tail = calls[ad + 1:] + assert len(tail) == len(sp["turns"]), f"{eid}: tail {len(tail)} != turns {len(sp['turns'])}" + orig_hist = hist_of(r) + split_eids.add(eid) + + # ---- T1: preserved trie divergence (prefix + F) ---- + t1 = copy.deepcopy(r) + t1["query"] = sp["q1"] + t1["calls"] = copy.deepcopy(prefixF) + t1["history"] = copy.deepcopy(orig_hist) + t1["metadata"] = copy.deepcopy(md) + t1["metadata"]["history"] = copy.deepcopy(orig_hist) + t1["metadata"]["unbundle_role"] = "turn1" + t1["metadata"]["orig_eid"] = eid + out.append(t1) + + # ---- running history: turn1 shown as completed ---- + base_hist = (copy.deepcopy(orig_hist) + + [umsg(sp["q1"]), amsg(tool_calls=prefixF)] + + [tmsg(c) for c in prefixF] + + [amsg(content=sp["turns"][0]["bridge"])]) + + run_hist = base_hist + for i, call in enumerate(tail): + if call["name"] in AUTH_TOOLS: + reauth_flags.append((eid, i, call["name"])) + trow = copy.deepcopy(r) + trow["example_id"] = f"{eid}-t{i + 2}" + trow["query"] = sp["turns"][i]["user"] + trow["calls"] = [copy.deepcopy(call)] + trow["history"] = copy.deepcopy(run_hist) + trow["metadata"] = copy.deepcopy(md) + trow["metadata"]["history"] = copy.deepcopy(run_hist) + trow["metadata"]["unbundle_role"] = f"turn{i + 2}" + trow["metadata"]["orig_eid"] = eid + out.append(trow) + # advance history: this tail turn completed + next bridge (if any) + run_hist = (copy.deepcopy(run_hist) + + [umsg(sp["turns"][i]["user"]), amsg(tool_calls=[call]), tmsg(call)]) + if i + 1 < len(tail): + run_hist = run_hist + [amsg(content=sp["turns"][i + 1]["bridge"])] + + OUT.parent.mkdir(parents=True, exist_ok=True) + with OUT.open("w", encoding="utf-8") as fh: + for r in out: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") + + n_tail = sum(1 for r in out if str((r.get("metadata") or {}).get("unbundle_role", "")).startswith("turn") + and (r.get("metadata") or {}).get("unbundle_role") != "turn1" + and (r.get("metadata") or {}).get("orig_eid")) + print(f"input rows: {len(rows)} output rows: {len(out)}") + print(f"split candidates: {len(split_eids)} T1 rows: {len(split_eids)} tail rows: {n_tail}") + print(f"unchanged rows: {len(rows) - len(split_eids)}") + if reauth_flags: + print(f"WARNING: {len(reauth_flags)} tail turns contain an auth tool:") + for f in reauth_flags[:10]: + print(" ", f) + else: + print("no tail turn re-authenticates (good)") + print(f"wrote {OUT.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/build_all_v2.py b/tempscripts/story_remediation/unbundle/build_all_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..55cd7af5c27e25d007fb6675700553a77a267856 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/build_all_v2.py @@ -0,0 +1,116 @@ +"""V2 build: same structural split, but corrected acknowledgement ordering. + +Every completed turn is rendered in history as: user request -> tool call(s) +-> PAST-TENSE ack of that same turn. An ack never precedes its own request, so +the v1 "I've already done the thing you're about to ask" contradiction is gone. + +History for tail turn i (0-based, maps to tail call i): + orig_history + + user(q1) + assistant(tool_calls=prefix+F) + tool msgs + assistant(ack1) + + for j in 0..i-1: + user(turns[j].user) + assistant(tool_calls=[tail[j]]) + tool msg + + assistant(turns[j].ack) + -> current row: query=turns[i].user, calls=[tail[i]] (its ack shown only in later rows) + +Reads out/authored_v2.json, writes out/trajectories_all_v2.jsonl. +Run: python -u temp/story_remediation/unbundle/build_all_v2.py +""" +from __future__ import annotations +import json, copy +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +AUTHORED = HERE / "out" / "authored_v2.json" +OUT = HERE / "out" / "trajectories_all_v2.jsonl" +AUTH_TOOLS = {"find_user_id_by_name_zip", "find_user_id_by_email", + "find_user_id_by_phone", "authenticate", "find_user"} + + +def hist_of(r): + return r.get("history") or (r.get("metadata") or {}).get("history") or [] + + +def umsg(c): + return {"role": "user", "content": c, "tool_calls": [], "tool_call_id": None} + + +def amsg(content=None, tool_calls=None): + return {"role": "assistant", "content": content, + "tool_calls": copy.deepcopy(tool_calls) if tool_calls else [], + "tool_call_id": None} + + +def tmsg(call): + return {"role": "tool", "content": call.get("output"), "tool_calls": [], "tool_call_id": None} + + +def main(): + rows = [json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()] + authored = json.loads(AUTHORED.read_text(encoding="utf-8")) + ok = {e: a for e, a in authored.items() if "q1" in a and not a.get("_err")} + print(f"authored ok: {len(ok)} skipped: {len(authored)-len(ok)}") + + out = []; split_eids = set(); reauth = [] + for r in rows: + eid = r["example_id"] + if eid not in ok: + out.append(r); continue + sp = ok[eid]; md = r["metadata"]; ad = md["anchor_depth"] + calls = r["calls"]; prefixF = calls[:ad + 1]; tail = calls[ad + 1:] + assert len(tail) == len(sp["turns"]), f"{eid}: tail {len(tail)} != turns {len(sp['turns'])}" + orig_hist = hist_of(r); split_eids.add(eid) + + # T1: preserved trie divergence (query narrowed to prefix+F) + t1 = copy.deepcopy(r) + t1["query"] = sp["q1"]; t1["calls"] = copy.deepcopy(prefixF) + t1["history"] = copy.deepcopy(orig_hist) + t1["metadata"] = copy.deepcopy(md) + t1["metadata"]["history"] = copy.deepcopy(orig_hist) + t1["metadata"]["unbundle_role"] = "turn1"; t1["metadata"]["orig_eid"] = eid + out.append(t1) + + # turn-1 completed block (with its OWN past-tense ack1) + base_hist = (copy.deepcopy(orig_hist) + + [umsg(sp["q1"]), amsg(tool_calls=prefixF)] + + [tmsg(c) for c in prefixF] + + [amsg(content=sp["ack1"])]) + + for i, call in enumerate(tail): + if call["name"] in AUTH_TOOLS: + reauth.append((eid, i, call["name"])) + # history = base + completed tail turns 0..i-1 (each with its own ack) + hist = copy.deepcopy(base_hist) + for j in range(i): + cj = tail[j] + hist += [umsg(sp["turns"][j]["user"]), amsg(tool_calls=[cj]), + tmsg(cj), amsg(content=sp["turns"][j]["ack"])] + trow = copy.deepcopy(r) + trow["example_id"] = f"{eid}-t{i + 2}" + trow["query"] = sp["turns"][i]["user"] + trow["calls"] = [copy.deepcopy(call)] + trow["history"] = hist + trow["metadata"] = copy.deepcopy(md) + trow["metadata"]["history"] = copy.deepcopy(hist) + trow["metadata"]["unbundle_role"] = f"turn{i + 2}" + trow["metadata"]["orig_eid"] = eid + out.append(trow) + + OUT.parent.mkdir(parents=True, exist_ok=True) + with OUT.open("w", encoding="utf-8") as fh: + for r in out: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") + + n_tail = sum(1 for r in out + if (r.get("metadata") or {}).get("orig_eid") + and (r.get("metadata") or {}).get("unbundle_role") not in (None, "turn1")) + print(f"input rows: {len(rows)} output rows: {len(out)}") + print(f"split candidates: {len(split_eids)} T1: {len(split_eids)} tail: {n_tail}") + print(f"unchanged rows: {len(rows) - len(split_eids)}") + print("re-auth in tail (verify DIFFERENT person):", len(reauth), reauth[:6]) + print(f"wrote {OUT.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/build_all_v3.py b/tempscripts/story_remediation/unbundle/build_all_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..b63b1f598226ca031ab72d982f1d93f94f03b2be --- /dev/null +++ b/tempscripts/story_remediation/unbundle/build_all_v3.py @@ -0,0 +1,204 @@ +"""V3 build: remove the residual tells that live in the INHERITED base history. + +Diagnosis (from C3 reasoning on still-caught v2 tails): the original n100 +"humanized" pre-history front-loads future/tail intents ("a return to handle", +"a receipt without prices") and restates identity ("Hi, this is Mona Frey") +right before q1. Both read as scripted-from-a-template. + +Fix (reuses v2 authored q1/ack1/turns unchanged): + * 259 candidates whose pre-history has NO tool calls -> replace the whole + teaser with just the greeting. q1 (which already carries name+ZIP) becomes + the true first user turn, so the front-loading AND the duplicate identity + both disappear. + * 23 candidates whose pre-history DOES auth (find_user[/get_user]) -> rebuild + a clean minimal auth exchange that keeps those exact tool calls but drops + the front-loading teaser and any duplicative post-auth actions. Identity is + given once, with no intent preview. + +Everything downstream (T1 = prefix+F, tail = one action per turn, past-tense +acks) is identical to v2. Reads out/authored_v2.json, writes +out/trajectories_all_v3.jsonl. +Run: python -u temp/story_remediation/unbundle/build_all_v3.py +""" +from __future__ import annotations +import json, copy, hashlib, re +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +AUTHORED = HERE / "out" / "authored_v2.json" +Q1FIX = HERE / "out" / "authored_q1fix_v3.json" +OUT = HERE / "out" / "trajectories_all_v3.jsonl" + +AUTH_LEAD = ("find_user_id_by_name_zip", "get_user_details") +AUTH_TOOLS = {"find_user_id_by_name_zip", "find_user_id_by_email", + "find_user_id_by_phone", "authenticate", "find_user"} + +OPENERS = [ + "Hi, I need a hand with my account. I'm {first} {last}, ZIP {zip}.", + "Hello, could you pull up my account? Name is {first} {last}, ZIP {zip}.", + "Hi there, I need some help on my account. I'm {first} {last}, ZIP {zip}.", + "Hey, can you access my account? Name's {first} {last}, ZIP {zip}.", +] +VERIFIED = [ + "Thanks {first}, you're verified. What can I do for you?", + "Great {first}, I've pulled up your account. How can I help?", + "You're all set {first}. What would you like to do?", + "Verified, thanks {first}. What can I help with?", +] + + +def hist_of(r): + return r.get("history") or (r.get("metadata") or {}).get("history") or [] + + +def umsg(c): + return {"role": "user", "content": c, "tool_calls": [], "tool_call_id": None} + + +def amsg(content=None, tool_calls=None): + return {"role": "assistant", "content": content, + "tool_calls": copy.deepcopy(tool_calls) if tool_calls else [], + "tool_call_id": None} + + +def tmsg(call): + return {"role": "tool", "content": call.get("output"), "tool_calls": [], "tool_call_id": None} + + +def pick(lst, eid): + return lst[int(hashlib.md5(eid.encode()).hexdigest(), 16) % len(lst)] + + +def greeting_of(r): + h = hist_of(r) + if h and h[0].get("role") == "assistant" and not h[0].get("tool_calls") and h[0].get("content"): + return copy.deepcopy(h[0]) + return amsg(content="Hi! How can I help you today?") + + +def clean_prehistory(r): + """Return (cleaned_history, had_auth). For the 23 auth-in-history rows keep a + minimal auth exchange around the real find_user/get_user calls; else greeting.""" + h = hist_of(r); eid = r["example_id"] + greet = greeting_of(r) + # gather the LEADING auth calls actually present in the pre-history, in order + lead = [] + for m in h: + for t in (m.get("tool_calls") or []): + if t["name"] in AUTH_LEAD: + lead.append(copy.deepcopy(t)) + # only keep the contiguous leading auth calls (find_user then optional get_user) + kept = [] + for t in lead: + if not kept and t["name"] == "find_user_id_by_name_zip": + kept.append(t) + elif kept and t["name"] == "get_user_details": + kept.append(t); break + else: + break + if not kept: + return [greet], False + args = kept[0].get("arguments", {}) + first = args.get("first_name", ""); last = args.get("last_name", ""); zp = args.get("zip", "") + opener = pick(OPENERS, eid).format(first=first, last=last, zip=zp) + verified = pick(VERIFIED, eid).format(first=first or "there") + hist = [greet, umsg(opener)] + for t in kept: + hist += [amsg(tool_calls=[t]), tmsg(t)] + hist += [amsg(content=verified)] + return hist, True + + +def main(): + rows = [json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()] + authored = json.loads(AUTHORED.read_text(encoding="utf-8")) + q1fix = json.loads(Q1FIX.read_text(encoding="utf-8")) if Q1FIX.exists() else {} + ok = {e: a for e, a in authored.items() if "q1" in a and not a.get("_err")} + print(f"authored ok: {len(ok)} skipped: {len(authored)-len(ok)} q1-overrides: {len(q1fix)}") + + out = []; split_eids = set(); n_auth = 0; ident_leak = [] + for r in rows: + eid = r["example_id"] + if eid not in ok: + out.append(r); continue + sp = copy.deepcopy(ok[eid]); md = r["metadata"]; ad = md["anchor_depth"] + if eid in q1fix: # cleaned already-verified q1 + sp["q1"] = q1fix[eid]["q1"] + calls = r["calls"]; prefixF = calls[:ad + 1]; tail = calls[ad + 1:] + assert len(tail) == len(sp["turns"]), f"{eid}: tail {len(tail)} != turns {len(sp['turns'])}" + base_prehist, had_auth = clean_prehistory(r) + n_auth += int(had_auth); split_eids.add(eid) + + # for auth-in-history rows, q1 must NOT re-introduce the person (full name + # or a self-intro like "I'm Reid"); a name inside an id (gc_reid_22) is fine + if had_auth: + fu = next((t for m in hist_of(r) for t in (m.get("tool_calls") or []) + if t["name"] == "find_user_id_by_name_zip"), None) + a = (fu or {}).get("arguments", {}) + first = str(a.get("first_name", "")); last = str(a.get("last_name", "")) + q1l = sp["q1"].lower() + pats = [] + if first and last: + pats.append(re.escape(f"{first} {last}".lower())) + if first and len(first) >= 3: + pats.append(r"\b(i'?m|i am|this is|name is|it'?s)\s+" + re.escape(first.lower())) + if pats and re.search("|".join(pats), q1l): + ident_leak.append((eid, first)) + + # T1: preserved trie divergence + t1 = copy.deepcopy(r) + t1["query"] = sp["q1"]; t1["calls"] = copy.deepcopy(prefixF) + t1["history"] = copy.deepcopy(base_prehist) + t1["metadata"] = copy.deepcopy(md) + t1["metadata"]["history"] = copy.deepcopy(base_prehist) + t1["metadata"]["unbundle_role"] = "turn1"; t1["metadata"]["orig_eid"] = eid + out.append(t1) + + # turn-1 completed block (own past-tense ack1) + base_hist = (copy.deepcopy(base_prehist) + + [umsg(sp["q1"]), amsg(tool_calls=prefixF)] + + [tmsg(c) for c in prefixF] + + [amsg(content=sp["ack1"])]) + + for i, call in enumerate(tail): + hist = copy.deepcopy(base_hist) + for j in range(i): + cj = tail[j] + hist += [umsg(sp["turns"][j]["user"]), amsg(tool_calls=[cj]), + tmsg(cj), amsg(content=sp["turns"][j]["ack"])] + trow = copy.deepcopy(r) + trow["example_id"] = f"{eid}-t{i + 2}" + trow["query"] = sp["turns"][i]["user"] + trow["calls"] = [copy.deepcopy(call)] + trow["history"] = hist + trow["metadata"] = copy.deepcopy(md) + trow["metadata"]["history"] = copy.deepcopy(hist) + trow["metadata"]["unbundle_role"] = f"turn{i + 2}" + trow["metadata"]["orig_eid"] = eid + out.append(trow) + + OUT.parent.mkdir(parents=True, exist_ok=True) + with OUT.open("w", encoding="utf-8") as fh: + for r in out: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") + + n_tail = sum(1 for r in out + if (r.get("metadata") or {}).get("orig_eid") + and (r.get("metadata") or {}).get("unbundle_role") not in (None, "turn1")) + print(f"input rows: {len(rows)} output rows: {len(out)}") + print(f"split: {len(split_eids)} greeting-only(259-type): {len(split_eids)-n_auth} " + f"auth-in-history(23-type): {n_auth}") + print(f"tail rows: {n_tail} unchanged: {len(rows)-len(split_eids)}") + if ident_leak: + print(f"WARNING q1 restates identity already in cleaned history ({len(ident_leak)}):") + for x in ident_leak: + print(" ", x) + else: + print("no q1 restates cleaned-history identity (good)") + print(f"wrote {OUT.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/build_all_v4.py b/tempscripts/story_remediation/unbundle/build_all_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc7a68d2f8421842d708df0b0354740c5f0014b --- /dev/null +++ b/tempscripts/story_remediation/unbundle/build_all_v4.py @@ -0,0 +1,243 @@ +"""V4 build: add a real auth handshake (agent asks -> customer provides) and use the +humanized v4 dialogue, WITHOUT touching a single tool call. + +Structural change vs v3 is PROSE ONLY: + * greeting-only rows (259): base history becomes + [greeting] [user: vague opener, no identifiers] [agent: please verify name+ZIP] + and the T1 user turn (q1) is the customer's reply that provides name/ZIP and the + first task. The T1 tool calls (auth + F) are IDENTICAL to v3 and stay in one turn. + * auth-in-history rows (23): the pre-history auth exchange is rebuilt as a handshake + [greeting] [user: vague opener] [agent: verify?] [user: name+ZIP] [auth calls] + [agent: verified]. Same find_user/get_user calls as v3, kept verbatim. q1 stays the + v3 clean task-only message (no identity restated). + +INVARIANT: for every example_id, this build asserts row["calls"] is byte-identical to +v3's row["calls"]. If any call differs the build aborts. The trie is therefore +unchanged and every confuser still rivals its real node at the same cutoff. + +Reads out/authored_v4.json (+ v2/q1fix for fallbacks), writes +out/trajectories_all_v4.jsonl. Run: + python -u temp/story_remediation/unbundle/build_all_v4.py +""" +from __future__ import annotations +import json, copy, hashlib, re +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +AUTHORED4 = HERE / "out" / "authored_v4.json" +AUTHORED2 = HERE / "out" / "authored_v2.json" +Q1FIX = HERE / "out" / "authored_q1fix_v3.json" +V3 = HERE / "out" / "trajectories_all_v3.jsonl" +OUT = HERE / "out" / "trajectories_all_v4.jsonl" + +AUTH_LEAD = ("find_user_id_by_name_zip", "get_user_details") + +# vague openers: NO name / ZIP / email / order id (identity comes only after the ask) +OPENERS_VAGUE = [ + "Hi, I need a hand with something on my account.", + "Hello, I'm hoping you can help me with one of my orders.", + "Hey there, I've got a question about my account.", + "Hi, could you help me sort something out on my account?", + "Hello, I need to take care of a couple of things on my order.", + "Hi, I was hoping to get some help with my account today.", + "Hey, I need help with something. Not sure who to ask.", + "Hi there, can you help me with an order issue?", +] +# agent asks to verify identity (name + ZIP) +VERIFY_ASK = [ + "Of course, I'd be glad to help. First, can I verify your identity? Could you give me your full name and ZIP code?", + "Happy to help with that. Before I pull anything up, could you confirm your name and ZIP code for me?", + "Sure thing. To access your account I'll need to verify you first. What's your full name and ZIP code?", + "I can help with that. For security, could you share your full name and the ZIP code on your account?", + "Absolutely. Let me just verify you first. Can I get your name and ZIP code, please?", + "Glad to help. To start, could you confirm your full name and ZIP code so I can find your account?", +] +# for the 23 auth-in-history rows: the customer provides identity (mild disfluency) +ID_PROVIDE = [ + "Yeah, sure. It's {first} {last}, and the ZIP is {zip}.", + "Oh, right. {first} {last}, ZIP {zip}.", + "Of course, it's {first} {last}. ZIP code's {zip}.", + "Sure thing. Name's {first} {last}, and my ZIP is {zip}.", + "Um, ok. {first} {last}, and the ZIP on the account is {zip}.", +] +VERIFIED = [ + "Thanks {first}, you're all verified. What can I do for you?", + "Great, I've got your account pulled up, {first}. How can I help?", + "You're all set, {first}. What would you like to do?", + "Perfect, verified. Thanks {first}. What can I help with?", +] + + +def hist_of(r): + return r.get("history") or (r.get("metadata") or {}).get("history") or [] + + +def umsg(c): + return {"role": "user", "content": c, "tool_calls": [], "tool_call_id": None} + + +def amsg(content=None, tool_calls=None): + return {"role": "assistant", "content": content, + "tool_calls": copy.deepcopy(tool_calls) if tool_calls else [], + "tool_call_id": None} + + +def tmsg(call): + return {"role": "tool", "content": call.get("output"), "tool_calls": [], "tool_call_id": None} + + +def pick(lst, eid, salt=""): + return lst[int(hashlib.md5((salt + eid).encode()).hexdigest(), 16) % len(lst)] + + +def greeting_of(r): + h = hist_of(r) + if h and h[0].get("role") == "assistant" and not h[0].get("tool_calls") and h[0].get("content"): + return copy.deepcopy(h[0]) + return amsg(content="Hi! How can I help you today?") + + +def leading_auth(r): + lead = [] + for m in hist_of(r): + for t in (m.get("tool_calls") or []): + if t["name"] in AUTH_LEAD: + lead.append(copy.deepcopy(t)) + kept = [] + for t in lead: + if not kept and t["name"] == "find_user_id_by_name_zip": + kept.append(t) + elif kept and t["name"] == "get_user_details": + kept.append(t); break + else: + break + return kept + + +def base_history(r): + """(cleaned_history, had_auth). Prose-only handshake; no call added or removed + beyond the exact leading auth calls that already exist in v3's pre-history.""" + eid = r["example_id"] + greet = greeting_of(r) + opener = umsg(pick(OPENERS_VAGUE, eid, "op")) + ask = amsg(content=pick(VERIFY_ASK, eid, "ask")) + kept = leading_auth(r) + if not kept: + # greeting-only row: handshake is greeting -> opener -> ask; q1 (the T1 turn) + # is the customer's reply that supplies name/ZIP and the first task. + return [greet, opener, ask], False + # auth-in-history row: full handshake around the real auth calls. + a = kept[0].get("arguments", {}) + first = a.get("first_name", ""); last = a.get("last_name", ""); zp = a.get("zip", "") + idp = umsg(pick(ID_PROVIDE, eid, "idp").format(first=first, last=last, zip=zp)) + verified = amsg(content=pick(VERIFIED, eid, "ok").format(first=first or "there")) + hist = [greet, opener, ask, idp] + for t in kept: + hist += [amsg(tool_calls=[t]), tmsg(t)] + hist += [verified] + return hist, True + + +def calls_sig(calls): + return [(c.get("name"), json.dumps(c.get("arguments", {}), sort_keys=True, ensure_ascii=False)) + for c in (calls or [])] + + +def main(): + rows = [json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()] + a4 = json.loads(AUTHORED4.read_text(encoding="utf-8")) + a2 = json.loads(AUTHORED2.read_text(encoding="utf-8")) + q1fix = json.loads(Q1FIX.read_text(encoding="utf-8")) if Q1FIX.exists() else {} + v3 = {json.loads(l)["example_id"]: json.loads(l) + for l in open(V3, encoding="utf-8") if l.strip()} + # split EXACTLY the confusers v3 split, so the only delta vs v3 is prose. + v3_split = {r["metadata"]["orig_eid"] for r in v3.values() + if (r.get("metadata") or {}).get("unbundle_role") == "turn1"} + + def bundle(eid): + b = a4.get(eid) + if b and "q1" in b and not b.get("_err"): + return b + b = a2.get(eid) # fall back to v2 text if v4 failed + if b and "q1" in b and not b.get("_err"): + return b + return None + + ok = {e: bundle(e) for e in a4 if bundle(e)} + for e in a2: # include any v2-only successes + if e not in ok and bundle(e): + ok[e] = bundle(e) + print(f"usable bundles: {len(ok)} (v4 primary, v2 fallback)") + + out = []; split_eids = set(); n_auth = 0 + for r in rows: + eid = r["example_id"] + if eid not in ok or eid not in v3_split: + out.append(r); continue + sp = copy.deepcopy(ok[eid]); md = r["metadata"]; ad = md["anchor_depth"] + calls = r["calls"]; prefixF = calls[:ad + 1]; tail = calls[ad + 1:] + if len(tail) != len(sp["turns"]): + out.append(r); continue # schema mismatch -> leave original + base_prehist, had_auth = base_history(r) + if had_auth and eid in q1fix: # 23-type: keep clean task-only q1 + sp["q1"] = q1fix[eid]["q1"] + n_auth += int(had_auth); split_eids.add(eid) + + t1 = copy.deepcopy(r) + t1["query"] = sp["q1"]; t1["calls"] = copy.deepcopy(prefixF) + t1["history"] = copy.deepcopy(base_prehist) + t1["metadata"] = copy.deepcopy(md) + t1["metadata"]["history"] = copy.deepcopy(base_prehist) + t1["metadata"]["unbundle_role"] = "turn1"; t1["metadata"]["orig_eid"] = eid + out.append(t1) + + base_hist = (copy.deepcopy(base_prehist) + + [umsg(sp["q1"]), amsg(tool_calls=prefixF)] + + [tmsg(c) for c in prefixF] + + [amsg(content=sp["ack1"])]) + for i, call in enumerate(tail): + hist = copy.deepcopy(base_hist) + for j in range(i): + cj = tail[j] + hist += [umsg(sp["turns"][j]["user"]), amsg(tool_calls=[cj]), + tmsg(cj), amsg(content=sp["turns"][j]["ack"])] + trow = copy.deepcopy(r) + trow["example_id"] = f"{eid}-t{i + 2}" + trow["query"] = sp["turns"][i]["user"] + trow["calls"] = [copy.deepcopy(call)] + trow["history"] = hist + trow["metadata"] = copy.deepcopy(md) + trow["metadata"]["history"] = copy.deepcopy(hist) + trow["metadata"]["unbundle_role"] = f"turn{i + 2}" + trow["metadata"]["orig_eid"] = eid + out.append(trow) + + # HARD INVARIANT: calls identical to v3 for every row (trie untouched). + v4 = {r["example_id"]: r for r in out} + assert set(v4) == set(v3), ( + f"row-id set changed vs v3: +{sorted(set(v4)-set(v3))[:3]} " + f"-{sorted(set(v3)-set(v4))[:3]}") + bad = [eid for eid in v3 if calls_sig(v3[eid]["calls"]) != calls_sig(v4[eid]["calls"])] + assert not bad, f"CALLS CHANGED vs v3 for {len(bad)} rows, e.g. {bad[:5]}" + + OUT.parent.mkdir(parents=True, exist_ok=True) + with OUT.open("w", encoding="utf-8") as fh: + for r in out: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") + + n_tail = sum(1 for r in out + if (r.get("metadata") or {}).get("orig_eid") + and (r.get("metadata") or {}).get("unbundle_role") not in (None, "turn1")) + print(f"input rows: {len(rows)} output rows: {len(out)}") + print(f"split: {len(split_eids)} greeting-only: {len(split_eids)-n_auth} " + f"auth-in-history: {n_auth}") + print(f"tail rows: {n_tail} unchanged: {len(rows)-len(split_eids)}") + print("INVARIANT OK: calls byte-identical to v3 for all " + f"{len(v3)} rows (trie unchanged).") + print(f"wrote {OUT.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/build_all_v5.py b/tempscripts/story_remediation/unbundle/build_all_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..1201f9509fd5120355f51d8ac7e36a1f7641f13e --- /dev/null +++ b/tempscripts/story_remediation/unbundle/build_all_v5.py @@ -0,0 +1,323 @@ +"""V5 build: two prose-only cleanups on top of v4, calls still byte-identical to v3. + + b1 method-aware auth handshake. v4 always asked "name and ZIP"; 83 greeting-only + rows actually authenticate by EMAIL (find_user_id_by_email), so the agent's + question now matches the auth tool the row already uses (email -> ask for the + email on file; name_zip -> ask for name + ZIP). No call changes. + + b3 scrub raw argument id-tokens that leaked into dialogue (credit_card_..., + gift_card_...). The customer/agent now say "my gift card" / "my card on file" + instead of pasting the internal id. The id still lives in the tool ARGUMENTS + (unchanged), so the executor / state db is unaffected. + +INVARIANT (asserted): every row's calls == v3's calls, byte for byte. Trie unchanged. +Reads out/authored_v4.json (+v2 fallback, q1fix), writes out/trajectories_all_v5.jsonl. +Run: python -u temp/story_remediation/unbundle/build_all_v5.py +""" +from __future__ import annotations +import json, copy, hashlib, re +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +AUTHORED4 = HERE / "out" / "authored_v4.json" +AUTHORED2 = HERE / "out" / "authored_v2.json" +Q1FIX = HERE / "out" / "authored_q1fix_v3.json" +V3 = HERE / "out" / "trajectories_all_v3.jsonl" +OUT = HERE / "out" / "trajectories_all_v5.jsonl" + +AUTH_LEAD = ("find_user_id_by_name_zip", "get_user_details") +FIND_METHOD = {"find_user_id_by_name_zip": "name_zip", "find_user_id_by_email": "email", + "find_user_id_by_phone": "phone", "find_user_id_by_username": "username"} + +OPENERS_VAGUE = [ + "Hi, I need a hand with something on my account.", + "Hello, I'm hoping you can help me with one of my orders.", + "Hey there, I've got a question about my account.", + "Hi, could you help me sort something out on my account?", + "Hello, I need to take care of a couple of things on my order.", + "Hi, I was hoping to get some help with my account today.", + "Hey, I need help with something. Not sure who to ask.", + "Hi there, can you help me with an order issue?", +] +# b1: verify-ask pools keyed by the auth method the row actually uses +VERIFY_ASK = { + "name_zip": [ + "Of course, I'd be glad to help. First, can I verify your identity? Could you give me your full name and ZIP code?", + "Happy to help with that. Before I pull anything up, could you confirm your name and ZIP code for me?", + "Sure thing. To access your account I'll need to verify you first. What's your full name and ZIP code?", + "I can help with that. For security, could you share your full name and the ZIP code on your account?", + "Absolutely. Let me just verify you first. Can I get your name and ZIP code, please?", + "Glad to help. To start, could you confirm your full name and ZIP code so I can find your account?", + ], + "email": [ + "Of course, I'd be glad to help. First, can I verify your identity? What's the email address on your account?", + "Happy to help with that. Before I pull anything up, could you confirm the email address on your account?", + "Sure thing. To access your account I'll need to verify you first. What email address is on the account?", + "I can help with that. For security, could you share the email address associated with your account?", + "Absolutely. Let me just verify you first. What's the email on file for your account?", + "Glad to help. To start, could you confirm the email address on your account so I can look you up?", + ], + "phone": [ + "Of course, I'd be glad to help. First, can I verify your identity? What's the phone number on your account?", + "Happy to help. Before I pull anything up, could you confirm the phone number on file for your account?", + "Sure thing. To verify you, could you share the phone number associated with your account?", + ], + "username": [ + "Of course, I'd be glad to help. First, can I verify you? Could you give me your account username?", + "Happy to help. Before I pull anything up, could you confirm the username on your account?", + "Sure thing. To verify you, what's the username on your account?", + ], +} +ID_PROVIDE = [ + "Yeah, sure. It's {first} {last}, and the ZIP is {zip}.", + "Oh, right. {first} {last}, ZIP {zip}.", + "Of course, it's {first} {last}. ZIP code's {zip}.", + "Sure thing. Name's {first} {last}, and my ZIP is {zip}.", + "Um, ok. {first} {last}, and the ZIP on the account is {zip}.", +] +VERIFIED = [ + "Thanks {first}, you're all verified. What can I do for you?", + "Great, I've got your account pulled up, {first}. How can I help?", + "You're all set, {first}. What would you like to do?", + "Perfect, verified. Thanks {first}. What can I help with?", +] + +# b3: deterministic scrub of leaked argument id-tokens from NL (never touches calls) +_APPOS = re.compile(r",?\s*(?:the\s+)?id\s+is\s+(?:gift_card_\w+|credit_card_\w+)", re.I) +_GC_AFTER = re.compile(r"(gift card)\s+gift_card_\w+", re.I) +_CC_AFTER = re.compile(r"(credit card|card)\s+credit_card_\w+", re.I) +_GC_BARE = re.compile(r"\bgift_card_\w+") +_CC_BARE = re.compile(r"\bcredit_card_\w+") +_SPACE = re.compile(r"\s{2,}") + + +def scrub(text: str, role: str) -> str: + if not text or ("_card_" not in text): + return text + mine = "your" if role == "assistant" else "my" + t = _APPOS.sub("", text) + t = _GC_AFTER.sub(r"\1", t) + t = _CC_AFTER.sub(r"\1", t) + t = _GC_BARE.sub(f"{mine} gift card", t) + t = _CC_BARE.sub(f"{mine} card on file", t) + t = t.replace(" ,", ",").replace(" .", ".").replace(" ?", "?") + t = _SPACE.sub(" ", t).strip() + return t + + +def hist_of(r): + return r.get("history") or (r.get("metadata") or {}).get("history") or [] + + +def umsg(c): + return {"role": "user", "content": c, "tool_calls": [], "tool_call_id": None} + + +def amsg(content=None, tool_calls=None): + return {"role": "assistant", "content": content, + "tool_calls": copy.deepcopy(tool_calls) if tool_calls else [], + "tool_call_id": None} + + +def tmsg(call): + return {"role": "tool", "content": call.get("output"), "tool_calls": [], "tool_call_id": None} + + +def pick(lst, eid, salt=""): + return lst[int(hashlib.md5((salt + eid).encode()).hexdigest(), 16) % len(lst)] + + +def greeting_of(r): + h = hist_of(r) + if h and h[0].get("role") == "assistant" and not h[0].get("tool_calls") and h[0].get("content"): + return copy.deepcopy(h[0]) + return amsg(content="Hi! How can I help you today?") + + +def leading_auth(r): + lead = [] + for m in hist_of(r): + for t in (m.get("tool_calls") or []): + if t["name"] in AUTH_LEAD: + lead.append(copy.deepcopy(t)) + kept = [] + for t in lead: + if not kept and t["name"] == "find_user_id_by_name_zip": + kept.append(t) + elif kept and t["name"] == "get_user_details": + kept.append(t); break + else: + break + return kept + + +def auth_method(r): + for c in r["calls"]: + if c["name"] in FIND_METHOD: + return FIND_METHOD[c["name"]] + return "name_zip" + + +def base_history(r): + """(cleaned_history, had_auth). b1: verify-ask matches the row's auth method.""" + eid = r["example_id"] + greet = greeting_of(r) + opener = umsg(pick(OPENERS_VAGUE, eid, "op")) + kept = leading_auth(r) + method = "name_zip" if kept else auth_method(r) # auth-in-history rows are name_zip + ask = amsg(content=pick(VERIFY_ASK[method], eid, "ask")) + if not kept: + return [greet, opener, ask], False + a = kept[0].get("arguments", {}) + first = a.get("first_name", ""); last = a.get("last_name", ""); zp = a.get("zip", "") + idp = umsg(pick(ID_PROVIDE, eid, "idp").format(first=first, last=last, zip=zp)) + verified = amsg(content=pick(VERIFIED, eid, "ok").format(first=first or "there")) + hist = [greet, opener, ask, idp] + for t in kept: + hist += [amsg(tool_calls=[t]), tmsg(t)] + hist += [verified] + return hist, True + + +def calls_sig(calls): + return [(c.get("name"), json.dumps(c.get("arguments", {}), sort_keys=True, ensure_ascii=False)) + for c in (calls or [])] + + +def main(): + rows = [json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()] + a4 = json.loads(AUTHORED4.read_text(encoding="utf-8")) + a2 = json.loads(AUTHORED2.read_text(encoding="utf-8")) + q1fix = json.loads(Q1FIX.read_text(encoding="utf-8")) if Q1FIX.exists() else {} + v3 = {json.loads(l)["example_id"]: json.loads(l) + for l in open(V3, encoding="utf-8") if l.strip()} + v3_split = {r["metadata"]["orig_eid"] for r in v3.values() + if (r.get("metadata") or {}).get("unbundle_role") == "turn1"} + + def bundle(eid): + b = a4.get(eid) + if b and "q1" in b and not b.get("_err"): + return b + b = a2.get(eid) + if b and "q1" in b and not b.get("_err"): + return b + return None + + ok = {e: bundle(e) for e in a4 if bundle(e)} + for e in a2: + if e not in ok and bundle(e): + ok[e] = bundle(e) + print(f"usable bundles: {len(ok)}") + + n_scrub = 0 + out = []; split_eids = set(); n_auth = 0; method_ct = {"name_zip": 0, "email": 0, "phone": 0, "username": 0} + for r in rows: + eid = r["example_id"] + if eid not in ok or eid not in v3_split: + out.append(r); continue + sp = copy.deepcopy(ok[eid]); md = r["metadata"]; ad = md["anchor_depth"] + calls = r["calls"]; prefixF = calls[:ad + 1]; tail = calls[ad + 1:] + if len(tail) != len(sp["turns"]): + out.append(r); continue + base_prehist, had_auth = base_history(r) + if had_auth and eid in q1fix: + sp["q1"] = q1fix[eid]["q1"] + method_ct["name_zip" if had_auth else auth_method(r)] += 1 + n_auth += int(had_auth); split_eids.add(eid) + + # b3 scrub on every authored NL string (user + assistant) + def sc(txt, role): + nonlocal n_scrub + new = scrub(txt, role) + if new != txt: + n_scrub += 1 + return new + sp["q1"] = sc(sp["q1"], "user") + sp["ack1"] = sc(sp["ack1"], "assistant") + sp["turns"] = [{"user": sc(t["user"], "user"), "ack": sc(t["ack"], "assistant")} + for t in sp["turns"]] + + t1 = copy.deepcopy(r) + t1["query"] = sp["q1"]; t1["calls"] = copy.deepcopy(prefixF) + t1["history"] = copy.deepcopy(base_prehist) + t1["metadata"] = copy.deepcopy(md) + t1["metadata"]["history"] = copy.deepcopy(base_prehist) + t1["metadata"]["unbundle_role"] = "turn1"; t1["metadata"]["orig_eid"] = eid + out.append(t1) + + base_hist = (copy.deepcopy(base_prehist) + + [umsg(sp["q1"]), amsg(tool_calls=prefixF)] + + [tmsg(c) for c in prefixF] + + [amsg(content=sp["ack1"])]) + for i, call in enumerate(tail): + hist = copy.deepcopy(base_hist) + for j in range(i): + cj = tail[j] + hist += [umsg(sp["turns"][j]["user"]), amsg(tool_calls=[cj]), + tmsg(cj), amsg(content=sp["turns"][j]["ack"])] + trow = copy.deepcopy(r) + trow["example_id"] = f"{eid}-t{i + 2}" + trow["query"] = sp["turns"][i]["user"] + trow["calls"] = [copy.deepcopy(call)] + trow["history"] = hist + trow["metadata"] = copy.deepcopy(md) + trow["metadata"]["history"] = copy.deepcopy(hist) + trow["metadata"]["unbundle_role"] = f"turn{i + 2}" + trow["metadata"]["orig_eid"] = eid + out.append(trow) + + # b3 final pass: scrub any remaining card tokens in dialogue NL across ALL rows + # (covers passthrough/original confuser queries + histories). Tool outputs (role + # == "tool") and call arguments are left untouched, so calls/state db are intact. + for r in out: + if r.get("query") and "_card_" in r["query"]: + new = scrub(r["query"], "user") + if new != r["query"]: + r["query"] = new; n_scrub += 1 + for m in (r.get("history") or []): + role = m.get("role") + if role in ("user", "assistant") and m.get("content") and "_card_" in m["content"]: + new = scrub(m["content"], role) + if new != m["content"]: + m["content"] = new; n_scrub += 1 + md = r.get("metadata") or {} + for m in (md.get("history") or []): + role = m.get("role") + if role in ("user", "assistant") and m.get("content") and "_card_" in m["content"]: + new = scrub(m["content"], role) + if new != m["content"]: + m["content"] = new; n_scrub += 1 + + v5 = {r["example_id"]: r for r in out} + assert set(v5) == set(v3), "row-id set changed vs v3" + bad = [eid for eid in v3 if calls_sig(v3[eid]["calls"]) != calls_sig(v5[eid]["calls"])] + assert not bad, f"CALLS CHANGED vs v3 for {len(bad)} rows, e.g. {bad[:5]}" + + # b3 sanity: no leaked card tokens remain anywhere in NL + leftover = [] + for r in out: + txts = [r.get("query") or ""] + for src in (r.get("history") or []), ((r.get("metadata") or {}).get("history") or []): + txts += [m.get("content") or "" for m in src if m.get("role") != "tool"] + for t in txts: + if re.search(r"gift_card_\w+|credit_card_\w+", t): + leftover.append(r["example_id"]); break + assert not leftover, f"card tokens still in NL for {len(leftover)} rows: {leftover[:5]}" + + OUT.parent.mkdir(parents=True, exist_ok=True) + with OUT.open("w", encoding="utf-8") as fh: + for r in out: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") + + print(f"input rows: {len(rows)} output rows: {len(out)}") + print(f"split: {len(split_eids)} greeting-only: {len(split_eids)-n_auth} auth-in-history: {n_auth}") + print(f"b1 verify-ask by method: {method_ct}") + print(f"b3 NL strings scrubbed: {n_scrub} (leftover card tokens: {len(leftover)})") + print(f"INVARIANT OK: calls byte-identical to v3 for all {len(v3)} rows (trie unchanged).") + print(f"wrote {OUT.relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/build_all_v6.py b/tempscripts/story_remediation/unbundle/build_all_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..9992627918af505a212d3bfe3587b981e08ba656 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/build_all_v6.py @@ -0,0 +1,187 @@ +"""Build v6 from v5: prose-only deterministic auth/identity fixes (calls-invariant). + +Fixes (all in authored NL only, never in `calls`): + 1. name_mismatch -- agent addresses customer by a name != auth first_name + 2. dup_verification -- >1 "you're verified" confirmation; keep the first, strip rest + 3. zip_mismatch -- customer states a ZIP (in a zip context) != auth zip + 4. userid_in_prose -- user speaks their internal user_id token (e.g. xan_rho_6699) + +Rendering defects the C3 judge cited (raw-JSON assistant content, markdown/bold in +user messages) do NOT exist in the data -- 0 occurrences -- so nothing to fix there; +the judge hallucinated them. (Verified by rendering the cited row.) + +Reads : temp/story_remediation/unbundle/out/trajectories_all_v5.jsonl +Writes: temp/story_remediation/unbundle/out/trajectories_all_v6.jsonl +""" +import json, re, sys, copy +sys.path.insert(0, r"temp/story_remediation/unbundle") +import auth_lint_v5 as L + +SRC = r"temp/story_remediation/unbundle/out/trajectories_all_v5.jsonl" +OUT = r"temp/story_remediation/unbundle/out/trajectories_all_v6.jsonl" + +ZIP_SUB_RX = None # built per-row + + +def strip_verif(text): + """Remove a verification-confirmation clause, keep the rest of the sentence.""" + t = text + t = re.sub(r",?\s*you'?re (all )?verified", "", t, flags=re.I) + t = re.sub(r",?\s*you are (all )?verified", "", t, flags=re.I) + t = re.sub(r"Perfect,\s*verified\.\s*", "", t, flags=re.I) + t = re.sub(r"(Yep,?\s*|Yes,?\s*)?I'?ve verified your identity(?: (?:using|with) code \d+)?\.\s*", "", t, flags=re.I) + t = re.sub(r"I'?ve verified your account and\s*", "I've ", t, flags=re.I) + t = re.sub(r"\s{2,}", " ", t) + t = re.sub(r"^[,.\s]+", "", t) + t = t.replace(" .", ".").replace(" ,", ",").strip() + if t and t[0].islower(): + t = t[0].upper() + t[1:] + return t + + +def fix_row(r): + changed = [] + method, first, last, zipc, email = L.auth_identity(r) + + # --- collect wrong names (agent-spoken first names != auth first name) --- + allowed = {x.lower() for x in (first, last) if x} + wrong_names = set() + for role, c in L.convo_turns(r): + if role != "assistant": + continue + for m in list(L.ADDR_RX.finditer(c)) + list(L.ADDR_RX2.finditer(c)): + tok = m.group(1) + if tok in L.STOP: + continue + if allowed and tok.lower() not in allowed: + wrong_names.add(tok) + + # --- mismatched zips (spoken in a zip-context, != auth zip, not a call-arg value) --- + argvals = L.call_arg_values(r) + bad_zips = set() + if zipc: + for role, c in L.convo_turns(r): + for m in L.ZIP_CTX_RX.finditer(c): + z = m.group(1) + if z != str(zipc) and z.lower() not in argvals: + bad_zips.add(z) + + # --- user_id token spoken by the user --- + uid_rx = None + if first and last: + uid_rx = re.compile(r"\b" + re.escape(first.lower()) + r"_" + re.escape(last.lower()) + r"_\d+\b") + + # user self-identification with a wrong first name (last name matches, framed as a + # self-intro -- NOT "my spouse's account ... ") + selfid_rx = None + if first and last: + selfid_rx = re.compile( + r"(it'?s|it is|i'?m|i am|this is|name'?s|name is)\s+([A-Z][a-z]+)\s+" + re.escape(last) + r"\b") + + def fix_content(role, content): + nonlocal changed + if not content: + return content, False + new = content + # (1) name mismatch -- assistant only + if role == "assistant": + for wn in wrong_names: + if first: + n2 = re.sub(r"\b" + re.escape(wn) + r"\b", first, new) + if n2 != new: + new = n2; changed.append("name_mismatch") + # (3) zip mismatch -- replace inside the zip context, any role + for bz in bad_zips: + n2 = re.sub(r"(zip\D{0,12})" + re.escape(bz), r"\g<1>" + str(zipc), new, flags=re.I) + if n2 != new: + new = n2; changed.append("zip_mismatch") + # (4) user_id token -- user only + if role == "user" and uid_rx is not None: + repl = (first + " " + last) + n2 = uid_rx.sub(repl, new) + if n2 != new: + new = n2; changed.append("userid_in_prose") + # (5) user self-intro wrong first name -- user only + if role == "user" and selfid_rx is not None: + def _sid(m): + if m.group(2).lower() == first.lower(): + return m.group(0) + return f"{m.group(1)} {first} {last}" + n2 = selfid_rx.sub(_sid, new) + if n2 != new: + new = n2; changed.append("selfid_name_mismatch") + return new, (new != content) + + # apply name/zip/uid fixes across history + query + for h in r.get("history", []): + if h.get("role") in ("user", "assistant") and h.get("content"): + nc, _ = fix_content(h["role"], h["content"]) + h["content"] = nc + if r.get("query"): + r["query"], _ = fix_content("user", r["query"]) + # mirror into embedded metadata.history for self-consistency + for h in (r.get("metadata", {}).get("history") or []): + if h.get("role") in ("user", "assistant") and h.get("content"): + nc, _ = fix_content(h["role"], h["content"]) + h["content"] = nc + + # (2) dup verification -- keep FIRST confirmation, strip subsequent ones. + # Walk the conversation in render order (history then query), stripping in-place. + seen_verif = False + + def walk_strip(entries): + nonlocal seen_verif + for h in entries: + if h.get("role") == "assistant" and h.get("content") and L.VERIFIED_RX.search(h["content"]): + if seen_verif: + stripped = strip_verif(h["content"]) + if stripped != h["content"]: + h["content"] = stripped + changed.append("dup_verification") + else: + seen_verif = True + + walk_strip(r.get("history", [])) + # query is user role -> never a verification confirmation; skip + # mirror strip in metadata.history using an independent pass + seen2 = False + for h in (r.get("metadata", {}).get("history") or []): + if h.get("role") == "assistant" and h.get("content") and L.VERIFIED_RX.search(h["content"]): + if seen2: + h["content"] = strip_verif(h["content"]) + else: + seen2 = True + + return changed + + +def main(): + rows = [json.loads(l) for l in open(SRC, encoding="utf-8")] + src_calls = [json.dumps(r["calls"], sort_keys=True) for r in rows] + from collections import Counter + tally = Counter() + touched = 0 + for r in rows: + ch = fix_row(r) + if ch: + touched += 1 + for k in set(ch): + tally[k] += 1 + # calls invariant assert + new_calls = [json.dumps(r["calls"], sort_keys=True) for r in rows] + assert src_calls == new_calls, "CALLS CHANGED -- aborting" + + with open(OUT, "w", encoding="utf-8") as f: + for r in rows: + f.write(json.dumps(r) + "\n") + + print("v6 built:", OUT) + print("rows touched:", touched) + print("fix tally (rows with each fix type):") + for k in ["name_mismatch", "dup_verification", "zip_mismatch", "userid_in_prose", "selfid_name_mismatch"]: + print(f" {k:16s} {tally[k]}") + print("calls invariant vs v5: OK (byte-identical)") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/build_v3.py b/tempscripts/story_remediation/unbundle/build_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..f5e24c03889f252300cba91a21ee9ffc11af80cc --- /dev/null +++ b/tempscripts/story_remediation/unbundle/build_v3.py @@ -0,0 +1,141 @@ +"""Unbundle prototype: split a confuser's single harvested mega-turn into TWO +turns at the trie divergence point (metadata.anchor_depth). + +For each candidate: + turn1 (T1, the PRIMARY confuser, retrieval target preserved): + query = narrowed q1 (only warrants prefix + F, the infiltration node) + calls = orig_calls[:anchor_depth+1] (prefix + F) <- still diverges + at anchor_depth with F, exactly as before + history = original history (unchanged) + turn2 (T2, the cut tail, re-rooted as its own trie path): + query = q2 (a fresh user request motivating the tail) + calls = orig_calls[anchor_depth+1:] (G..Z) + history = original history + [q1, assistant(tool_calls=prefix+F, real + recorded outputs reused verbatim), bridge] -> auth already done, + T2 does NOT re-auth (matches tau2: authenticate once, early) + +C3 blinds tool names, so the confuser/fictional tools in the tail are fine; we +only repartition the row's OWN existing calls across two turns (no new tools, +no fabricated outputs). + +Writes out/trajectories_v3.jsonl (20 rows: 10 T1 + 10 T2). +Run: python -u temp/story_remediation/unbundle/build_v3.py +""" +from __future__ import annotations +import json, copy +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" +OUT = HERE / "out" / "trajectories_v3.jsonl" + +# Authored splits: q1 (narrowed turn-1), bridge (assistant reply after turn1), +# q2 (turn-2 user request for the tail). Entities reuse ids already in the query. +SPLITS = { + "confuser-add_gift_message-227": dict( + q1="On my pending gift order #W3410100, please add the gift message 'Happy Graduation!'.", + bridge="Done, I've added the gift message 'Happy Graduation!' to order #W3410100.", + q2="Thanks. Separately, for my delivered order #W3410200, can you give me a printable return label?"), + "confuser-get_return_label-271": dict( + q1="Now to my orders - I need a printable prepaid return label for #W5590123.", + bridge="Here's your prepaid return label for #W5590123, emailed as a printable PDF.", + q2="Great. One more - for #W2201984, can you send a gift receipt with no prices?"), + "confuser-request_gift_receipt-195": dict( + q1="For my order #W3320800, which was a gift, I need a gift receipt with no prices.", + bridge="Done - here's the no-price gift receipt for #W3320800.", + q2="Thanks. Could you also pull a copy of the tax invoice for my records, and a printable return label in case the recipient wants to send it back?"), + "confuser-get_shipping_options-215": dict( + q1="For my pending order #W5567012, what shipping options and speeds are available?", + bridge="Here are the available shipping options and speeds for #W5567012.", + q2="Got it. I'd also like to book a professional installation for the treadmill, and can you split the order into two shipments so the weights come separately?"), + "confuser-redeem_loyalty_points-163": dict( + q1="I've got a lot of loyalty points - can you redeem 2,000 of them for store credit?", + bridge="Done - I've redeemed 2,000 loyalty points for store credit.", + q2="Great. Can you tell me my resulting store-credit balance, the balance on gift card gift_card_9981220, and what promotions are running right now?"), + "confuser-get_size_guide-199": dict( + q1="On the trail shoes, can you pull up the sizing chart?", + bridge="Here's the sizing chart for the trail shoes.", + q2="Thanks. A few more things: sign me up for a restock alert on the black pair (item 1152271459) since it's sold out, register the warranty on the pair I already bought (item 4402019500), and post a 5-star review saying 'Great grip on wet trails.'"), + "confuser-get_gift_card_balance-346": dict( + q1="Before I finalize order #W3401200, can you tell me the balance on my gift card gift_card_3401120?", + bridge="Here's the current balance on gift card gift_card_3401120.", + q2="Thanks. And what promotions are currently running?"), + "confuser-get_warranty_details-281": dict( + q1="I just received my air purifier from order #W6042219 and I'd like to know the manufacturer's warranty terms on it - how long it's covered and what it includes.", + bridge="Here are the manufacturer's warranty terms for your air purifier from order #W6042219.", + q2="Perfect. Can you go ahead and register that warranty under my account so it's active?"), + "confuser-get_warranty_details-455": dict( + q1="For the jacket (item 3566100900) in my order #W3566100, can you show the warranty coverage? My email is cara.vin@example.com.", + bridge="Here's the warranty coverage for the jacket (item 3566100900).", + q2="Thanks. Could you also show the extended-warranty plans and the sizing chart for it?"), + "confuser-file_shipping_insurance_claim-296": dict( + q1="My order #W5540921 was a gift that arrived damaged - please file a shipping-insurance claim.", + bridge="I've filed a shipping-insurance claim for order #W5540921.", + q2="Thank you. Can you also send me a printable return label, and a gift receipt with no prices so the recipient can exchange it?"), +} + + +def hist_of(r): + return r.get("history") or (r.get("metadata") or {}).get("history") or [] + + +def main(): + rows = {json.loads(l)["example_id"]: json.loads(l) + for l in open(N100, encoding="utf-8") if l.strip()} + out = [] + for eid, sp in SPLITS.items(): + r = rows[eid] + md = r["metadata"]; ad = md["anchor_depth"] + calls = r["calls"] + t1_calls = calls[:ad + 1] + tail_calls = calls[ad + 1:] + assert tail_calls, f"{eid}: empty tail" + orig_hist = hist_of(r) + + # ---- T1: primary confuser, tail removed, query narrowed ---- + t1 = copy.deepcopy(r) + t1["query"] = sp["q1"] + t1["calls"] = copy.deepcopy(t1_calls) + t1["history"] = copy.deepcopy(orig_hist) + t1["metadata"] = copy.deepcopy(md) + t1["metadata"]["history"] = copy.deepcopy(orig_hist) + t1["metadata"]["unbundle_role"] = "turn1" + t1["metadata"]["orig_eid"] = eid + out.append(t1) + + # ---- T2: the cut tail, re-rooted; turn1 shown as completed history ---- + t1_assistant = {"role": "assistant", "content": None, + "tool_calls": copy.deepcopy(t1_calls), "tool_call_id": None} + tool_msgs = [{"role": "tool", "content": c.get("output"), + "tool_calls": [], "tool_call_id": None} for c in t1_calls] + bridge_hist = (copy.deepcopy(orig_hist) + + [{"role": "user", "content": sp["q1"], "tool_calls": [], "tool_call_id": None}, + t1_assistant] + + tool_msgs + + [{"role": "assistant", "content": sp["bridge"], "tool_calls": [], "tool_call_id": None}]) + t2 = copy.deepcopy(r) + t2["example_id"] = eid + "-t2" + t2["query"] = sp["q2"] + t2["calls"] = copy.deepcopy(tail_calls) + t2["history"] = bridge_hist + t2["metadata"] = copy.deepcopy(md) + t2["metadata"]["history"] = copy.deepcopy(bridge_hist) + t2["metadata"]["unbundle_role"] = "turn2" + t2["metadata"]["orig_eid"] = eid + out.append(t2) + + OUT.parent.mkdir(parents=True, exist_ok=True) + with OUT.open("w", encoding="utf-8") as fh: + for r in out: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") + + print(f"wrote {len(out)} rows ({len(SPLITS)} T1 + {len(SPLITS)} T2) -> {OUT.relative_to(ROOT)}") + for eid, sp in SPLITS.items(): + r = rows[eid]; ad = r["metadata"]["anchor_depth"] + cn = [c["name"] for c in r["calls"]] + print(f" {eid}: T1 calls={cn[:ad+1]} | T2 calls={cn[ad+1:]}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/diagnose_caught_v5.py b/tempscripts/story_remediation/unbundle/diagnose_caught_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..b3e7633c33b03876ca74f3a9ff1d09bb17f35647 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/diagnose_caught_v5.py @@ -0,0 +1,181 @@ +"""Why did C3 catch the v5 synthetics? Re-judge every CAUGHT v5 row once, capture +the judge's own `reasoning`, and bucket the tells into interpretable categories. + +The main run (C3_all_v5.jsonl) stored only guesses, so we re-run the identical C3 +prompt on the 543 caught rows, keep the reasoning, and classify each into one +primary bucket (priority order below) plus multi-label overlap counts. + +Saves out/caught_reasons_v5.jsonl (eid, role, sample_caught, guess, reasoning, +buckets) and prints the breakdown. +Run: python -u temp/story_remediation/unbundle/diagnose_caught_v5.py +""" +from __future__ import annotations +import json, logging, sys, collections +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +WORKERS = max(8, cfg["run"].get("workers", 4)) + +verds = [json.loads(l) for l in open(OUT / "C3_all_v5.jsonl", encoding="utf-8") if l.strip()] +fakes = {e["example_id"]: e for e in + (json.loads(l) for l in open(OUT / "trajectories_all_v5.jsonl", encoding="utf-8") if l.strip())} +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line); base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) + +caught = [v for v in verds if v.get("caught")] + +# bucket -> keyword list. A reasoning may hit several; primary = first in PRIORITY. +BUCKETS = { + "A_capability_scenario_realism": [ + "capab", "unrealistic", "not realistic", "unusual request", "unusual", "atypical", + "wouldn't", "would not", "implausible", "unlikely", "niche", "oddly specific", + "fabricat", "made-up", "made up", "obscure", "specialized", "nonstandard", + "non-standard", "not a standard", "not standard", "real system", "real assistant", + "real agent", "real company", "real retailer", "actual system", "plausib", + "unusual feature", "feature", "functionalit", "such a tool", "these tools"], + "B_multitask_bundling": [ + "unrelated", "multiple different", "several different", "range of", "variety", + "jumps between", "disparate", "disjoint", "laundry list", "checklist", + "many tasks", "multiple tasks", "multiple requests", "switches", "different topics", + "grab bag", "one after another", "rapid succession", "back-to-back", "so many", + "numerous", "series of", "list of requests", "everything at once"], + "D_auth_verification": [ + "verif", "identity", "authent", "security", "no verification", "without verif", + "didn't verify", "skipped verif", "no auth"], + "C_frictionless_smooth": [ + "friction", "too smooth", "seamless", "efficient", "effortless", "no pushback", + "no hesitat", "compliant", "too easy", "too well", "goes smoothly", "flawless", + "no complications", "no issues", "everything works", "cooperat", "accommodat"], + "E_agent_phrasing_templated": [ + "formal", "generic", "templat", "robotic", "scripted", "canned", "stiff", + "overly polite", "professional", "polished", "assistant's phrasing", + "assistant phrasing", "agent's phrasing", "agent phrasing", "customer service", + "corporate", "helpful assistant"], + "F_customer_phrasing": [ + "customer", "user's phrasing", "user phrasing", "casual", "disfluen", "filler", + "hedg", "overly casual", "forced", "trying too hard", "stilted", "awkward", + "too articulate", "too clear", "well-structured", "well structured", "organized", + "coherent", "natural", "colloquial", "conversational"], + "G_structure_brevity_history": [ + "abrupt", "terse", "brief", "short", "curt", "clipped", "history", "prior", + "previous", "context", "follow-up", "follow up", "continuation", "disconnect", + "out of nowhere", "no context", "sudden", "transition"], +} +PRIORITY = ["A_capability_scenario_realism", "B_multitask_bundling", "D_auth_verification", + "C_frictionless_smooth", "E_agent_phrasing_templated", "F_customer_phrasing", + "G_structure_brevity_history"] + + +def label(reason: str): + low = reason.lower() + hits = [b for b in PRIORITY if any(k in low for k in BUCKETS[b])] + primary = hits[0] if hits else "H_other" + return primary, hits + + +def judge_one(v): + eid = v["item_id"]; fake = fakes.get(eid) + if not fake: + return None + real = pairer(fake) + swap = (base.get(eid) or base.get(v.get("orig_eid")) or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + key = msgs["answer_key"] + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + except Exception as e: # noqa: BLE001 + return {"item_id": eid, "role": v.get("role"), "error": str(e)} + reason = (r.get("reasoning") or "").strip() + primary, hits = label(reason) + return {"item_id": eid, "role": v.get("role"), "guess": r.get("guess"), + "sample_caught": r.get("guess") == key, "primary": primary, + "buckets": hits, "reasoning": reason} + + +def main(): + print(f"re-judging {len(caught)} caught rows (workers={WORKERS}) to capture reasoning...") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + rows = [x for x in ex.map(judge_one, caught) if x] + errs = [r for r in rows if r.get("error")] + good = [r for r in rows if not r.get("error")] + (OUT / "caught_reasons_v5.jsonl").write_text( + "\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8") + + recaught = [r for r in good if r["sample_caught"]] + # distribution over rows that also caught on this sample (true catch-reasons) + prim = collections.Counter(r["primary"] for r in recaught) + multi = collections.Counter() + for r in recaught: + for b in r["buckets"]: + multi[b] += 1 + n = len(recaught) + + NAMES = { + "A_capability_scenario_realism": "capability / scenario realism (tool or task seems unreal)", + "B_multitask_bundling": "multi-task bundling (many / unrelated requests)", + "D_auth_verification": "auth / verification anomalies", + "C_frictionless_smooth": "too smooth / frictionless / compliant", + "E_agent_phrasing_templated": "agent phrasing (formal / generic / templated)", + "F_customer_phrasing": "customer phrasing (too clean / forced-casual / 'too natural')", + "G_structure_brevity_history": "structure / brevity / history-flow", + "H_other": "other / unclassified", + } + + print("\n" + "=" * 80) + print(f"CAUGHT-REASON BREAKDOWN (v5, original C3 prompt)") + print(f" caught rows re-judged: {len(good)} errors: {len(errs)}") + print(f" of those, this sample also caught: {n} (reasoning below is over these)") + print("=" * 80) + print("\nPRIMARY tell (each row assigned one bucket, priority-ordered):") + for b, c in prim.most_common(): + print(f" {c:4d} {c/n:5.1%} {NAMES.get(b, b)}") + print("\nANY-MENTION (multi-label; a row can hit several tells):") + for b, c in multi.most_common(): + print(f" {c:4d} {c/n:5.1%} {NAMES.get(b, b)}") + + # split primary distribution by role (T1 vs tail) + print("\nPRIMARY tell by row type:") + for grp, pred in (("turn1 (trie slot)", lambda r: r["role"] == "turn1"), + ("tail", lambda r: (r["role"] or "").startswith("turn") and r["role"] != "turn1"), + ("passthrough", lambda r: not r["role"])): + sub = [r for r in recaught if pred(r)] + if not sub: + continue + pc = collections.Counter(r["primary"] for r in sub) + top = ", ".join(f"{NAMES.get(b, b).split(' (')[0]} {c}" for b, c in pc.most_common(4)) + print(f" {grp:22s} n={len(sub):4d} {top}") + + print("\nExample reasonings per primary bucket (first 2):") + seen = collections.Counter() + for b in PRIORITY + ["H_other"]: + exs = [r for r in recaught if r["primary"] == b][:2] + if not exs: + continue + print(f"\n[{NAMES.get(b, b)}]") + for r in exs: + print(f" ({r['item_id']}) {r['reasoning'][:280]}") + print(f"\nsaved -> {(OUT/'caught_reasons_v5.jsonl').relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/diagnose_tail.py b/tempscripts/story_remediation/unbundle/diagnose_tail.py new file mode 100644 index 0000000000000000000000000000000000000000..64b93dc915dc44f0538bf7c4cdaacabae796c757 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/diagnose_tail.py @@ -0,0 +1,79 @@ +"""Diagnose WHY v3 tail turns still get caught: pull the judge's own reasoning. + +Samples still-caught tail rows (role turn2+), re-runs C3 once each with reasoning +captured, prints the rationale, and tallies recurring tell-keywords so we can see +the dominant factors rather than guessing. +Run: python -u temp/story_remediation/unbundle/diagnose_tail.py [N] +""" +from __future__ import annotations +import json, logging, sys, re, collections, random +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" + +verds = [json.loads(l) for l in open(OUT / "C3_all_v3.jsonl", encoding="utf-8") if l.strip()] +fakes = {e["example_id"]: e for e in + (json.loads(l) for l in open(OUT / "trajectories_all_v3.jsonl", encoding="utf-8") if l.strip())} +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line); base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) + +caught_tails = [v for v in verds + if (v.get("role") or "").startswith("turn") and v.get("role") != "turn1" + and v.get("caught")] +random.seed(7) +random.shuffle(caught_tails) +N = int(sys.argv[1]) if len(sys.argv) > 1 else 16 +sample = caught_tails[:N] + +KW = ["abrupt", "context", "history", "prior", "previous", "single", "one tool", + "efficient", "polished", "concise", "terse", "no clarif", "clarif", "confirm", + "generic", "templat", "formal", "assistant", "acknowled", "past tense", + "greeting", "identity", "auth", "repetit", "unnatural", "too clean", "smooth", + "brief", "short", "curt", "follow-up", "follow up", "disconnect", "abrupt", + "sequence", "unrelated", "jump", "no friction", "compliant"] +tally = collections.Counter() + +print(f"caught tails total={len(caught_tails)} sampling {len(sample)}\n" + "=" * 78) +for v in sample: + eid = v["item_id"]; fake = fakes.get(eid) + if not fake: + continue + real = pairer(fake) + swap = (base.get(eid) or base.get(v.get("orig_eid")) or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + except Exception as e: # noqa: BLE001 + print(f"[{eid}] ERROR {e}"); continue + reason = (r.get("reasoning") or "").strip() + low = reason.lower() + for k in KW: + if k in low: + tally[k] += 1 + nturns = len(fake.get("history", [])) + 1 + print(f"\n[{eid}] role={v['role']} guess={r.get('guess')} turns_in_conv={nturns}") + print(f" {reason}") + +print("\n" + "=" * 78 + "\nTELL KEYWORD TALLY (across sampled reasonings):") +for k, c in tally.most_common(): + if c: + print(f" {c:3d} {k}") diff --git a/tempscripts/story_remediation/unbundle/diagnose_tail_v4.py b/tempscripts/story_remediation/unbundle/diagnose_tail_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..0d19eb2530b7fa0bf0bf7fed0978acfb1ff03e24 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/diagnose_tail_v4.py @@ -0,0 +1,80 @@ +"""Diagnose WHY v3 tail turns still get caught: pull the judge's own reasoning. + +Samples still-caught tail rows (role turn2+), re-runs C3 once each with reasoning +captured, prints the rationale, and tallies recurring tell-keywords so we can see +the dominant factors rather than guessing. +Run: python -u temp/story_remediation/unbundle/diagnose_tail.py [N] +""" +from __future__ import annotations +import json, logging, sys, re, collections, random +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" + +verds = [json.loads(l) for l in open(OUT / "C3_all_v4.jsonl", encoding="utf-8") if l.strip()] +fakes = {e["example_id"]: e for e in + (json.loads(l) for l in open(OUT / "trajectories_all_v4.jsonl", encoding="utf-8") if l.strip())} +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line); base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) + +caught_tails = [v for v in verds + if (v.get("role") or "").startswith("turn") and v.get("role") != "turn1" + and v.get("caught")] +random.seed(7) +random.shuffle(caught_tails) +N = int(sys.argv[1]) if len(sys.argv) > 1 else 16 +sample = caught_tails[:N] + +KW = ["abrupt", "context", "history", "prior", "previous", "single", "one tool", + "efficient", "polished", "concise", "terse", "no clarif", "clarif", "confirm", + "generic", "templat", "formal", "assistant", "acknowled", "past tense", + "greeting", "identity", "auth", "repetit", "unnatural", "too clean", "smooth", + "brief", "short", "curt", "follow-up", "follow up", "disconnect", "abrupt", + "sequence", "unrelated", "jump", "no friction", "compliant"] +tally = collections.Counter() + +print(f"caught tails total={len(caught_tails)} sampling {len(sample)}\n" + "=" * 78) +for v in sample: + eid = v["item_id"]; fake = fakes.get(eid) + if not fake: + continue + real = pairer(fake) + swap = (base.get(eid) or base.get(v.get("orig_eid")) or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + except Exception as e: # noqa: BLE001 + print(f"[{eid}] ERROR {e}"); continue + reason = (r.get("reasoning") or "").strip() + low = reason.lower() + for k in KW: + if k in low: + tally[k] += 1 + nturns = len(fake.get("history", [])) + 1 + print(f"\n[{eid}] role={v['role']} guess={r.get('guess')} turns_in_conv={nturns}") + print(f" {reason}") + +print("\n" + "=" * 78 + "\nTELL KEYWORD TALLY (across sampled reasonings):") +for k, c in tally.most_common(): + if c: + print(f" {c:3d} {k}") + diff --git a/tempscripts/story_remediation/unbundle/dump_c3_view.py b/tempscripts/story_remediation/unbundle/dump_c3_view.py new file mode 100644 index 0000000000000000000000000000000000000000..49dfcc367ae6b701ecc4df79145b0f737aba28f3 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/dump_c3_view.py @@ -0,0 +1,31 @@ +"""Dump the exact CONV_A / CONV_B text the C3 judge sees for a given tail eid.""" +from __future__ import annotations +import json, sys, os +from pathlib import Path +import yaml +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P +from datasetreview import judge_prompts as J + +eid = sys.argv[1] if len(sys.argv) > 1 else "confuser-get_order_invoice-782-t2" +fakes = {e["example_id"]: e for e in + (json.loads(l) for l in open(HERE / "out" / (os.environ.get("V4FILE") or "trajectories_all_v3.jsonl"), encoding="utf-8") if l.strip())} +base = {} +for line in open(ROOT / "datasetreview" / "results" / "new" / "C3.jsonl", encoding="utf-8"): + if line.strip(): + d = json.loads(line); base[d["item_id"]] = d +fake = fakes[eid] +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +real = pairer(fake) +orig = fake.get("metadata", {}).get("orig_eid") +swap = (base.get(eid) or base.get(orig) or {}).get("answer_key") == "B" +msgs = J.build_c3(fake, real, swap=swap) +print(f"eid={eid} swap={swap} answer_key={msgs['answer_key']}") +print(f"history turns in fake: {len(fake.get('history', []))}") +print("#" * 80) +# extract just the two convs from the user message +u = msgs["user"] +print(u[u.index("---Conversation A---"):]) diff --git a/tempscripts/story_remediation/unbundle/fix_error_records.py b/tempscripts/story_remediation/unbundle/fix_error_records.py new file mode 100644 index 0000000000000000000000000000000000000000..424e0968233bbc6eef46d0911a740298dd76683f --- /dev/null +++ b/tempscripts/story_remediation/unbundle/fix_error_records.py @@ -0,0 +1,64 @@ +"""Re-judge the handful of records that hit a transient JSON-parse error on one of +their 3 samples, and rewrite ONLY those lines in place (canonical record builders, +so schema is unchanged). Makes the final C1/C3 JSONL pristine (3/3 samples, error=null). +""" +from __future__ import annotations +import json, sys +from pathlib import Path +import yaml + +ROOT = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 +from scripts import run_dataeval as R # noqa: E402 + +OUT = ROOT / "temp" / "story_remediation" / "unbundle" / "final_c1c3" +V6 = ROOT / "temp" / "story_remediation" / "unbundle" / "out" / "trajectories_all_v6.jsonl" +_ROWS = {json.loads(l)["example_id"]: json.loads(l) + for l in open(V6, encoding="utf-8") if l.strip()} +P.confuser_trajectories = lambda level: list(_ROWS.values()) + +FIX = {"C1": ["confuser-upgrade_shipping_speed-796-t3", "confuser-reorder_previous_order-311-t3", + "confuser-get_gift_card_balance-433"], + "C3": ["confuser-get_order_invoice-486-t4"]} +SAMPLES = 3 + + +def rejudge(exp, ctx, judge, item_id): + pipe = P.PIPELINES[exp](ctx) + w = P.Work(100, item_id, _ROWS[item_id]) + key = f"n100:{item_id}" + if exp == "C3": + per = [] + for ms in pipe.build_all(w): + res = [judge.judge(ms["msgs"]) for _ in range(SAMPLES)] + per.append((ms["orientation"], ms["answer_key"], res)) + return key, R._record_c3(exp, key, w, per, []) + msgs = pipe.build(w) + res = [judge.judge(msgs) for _ in range(SAMPLES)] + return key, R._record(exp, key, w, res, [], "verdict") + + +def main(): + cfg = yaml.safe_load((ROOT / "datasetreview" / "config.yaml").read_text(encoding="utf-8")) + judge = make_judge(cfg["model"]) + ctx = P.build_context(list(FIX)) + for exp, ids in FIX.items(): + path = OUT / f"{exp}.jsonl" + recs = [json.loads(l) for l in open(path, encoding="utf-8") if l.strip()] + by_item = {r["item_id"]: i for i, r in enumerate(recs)} + for item_id in ids: + _, newrec = rejudge(exp, ctx, judge, item_id) + recs[by_item[item_id]] = newrec + print(f"{exp} {item_id}: error={newrec.get('error')} " + f"verdict={newrec.get('verdict')} " + f"n_samples={newrec.get('n_samples') or newrec.get('samples_per_orientation')}") + with open(path, "w", encoding="utf-8") as fh: + for r in recs: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") + print(f" rewrote {path} ({len(recs)} lines)") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/replay_v5.py b/tempscripts/story_remediation/unbundle/replay_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..8dfdbac020b12d03220bf8aa4c1c0408395794c7 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/replay_v5.py @@ -0,0 +1,186 @@ +"""Free-running state runthrough on the V5 unbundled trajectories. + +v5 changed ONLY dialogue (b1 method-aware verify-ask, b3 token scrub). `calls` +are byte-identical to v3 / the source n100. This harness proves that at the level +that matters for free-running execution: + + 1. RECONSTRUCTION INVARIANT: for every original episode, concatenating its v5 + rows' calls in turn order (turn1, t2, t3, ...) reproduces the source n100 + call list byte-for-byte. This is the real "no floating / dropped variables" + check for the split dataset -- if a rewrite had dropped or mangled an id, + the reconstruction would diverge from source. + + 2. FREE-RUNNING REPLAY: seed ONE EpisodeState per reconstructed episode + (from_trajectory reads only `calls` + catalog, never dialogue), then replay + the full ordered call sequence against that single evolving state and check + each output reproduces the recorded one. Because we replay the *whole* + episode (not per-row), money ops see the accumulated balances they need. + +Any exception / mismatch / skip_nodata here would be a genuine execution gap; if +it stems from a db seed missing (gift card, order balance, cart subtotal), add it +to systemUpgrade/executor/catalog.json and re-run. + +Run from repo root: python -u temp/story_remediation/unbundle/replay_v5.py +""" +from __future__ import annotations +import json, sys, re +from collections import Counter, defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +EXEC = ROOT / "systemUpgrade" / "executor" +sys.path.insert(0, str(EXEC)) +from fake_state import EpisodeState # noqa: E402 +from fake_tools import TOOLS # noqa: E402 + +catalog = json.load(open(EXEC / "catalog.json", encoding="utf-8")) +V5 = ROOT / "temp" / "story_remediation" / "unbundle" / "out" / "trajectories_all_v5.jsonl" +SRC = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" + +v5 = [json.loads(l) for l in open(V5, encoding="utf-8") if l.strip()] +src = {json.loads(l)["example_id"]: json.loads(l) + for l in open(SRC, encoding="utf-8") if l.strip()} + + +def turn_idx(r): + role = (r.get("metadata") or {}).get("unbundle_role") or "" + if role == "turn1": + return 1 + m = re.match(r"turn(\d+)", role) + return int(m.group(1)) if m else 1 + + +# group v5 rows into original episodes +groups = defaultdict(list) +for r in v5: + oe = (r.get("metadata") or {}).get("orig_eid") or r["example_id"] + groups[oe].append(r) + +# 1) reconstruction invariant: concat(calls in turn order) == source n100 calls +recon_diff = [] +episodes = {} +for oe, rows in groups.items(): + rows_sorted = sorted(rows, key=turn_idx) + full = [] + for r in rows_sorted: + full += r["calls"] + episodes[oe] = full + if oe in src: + if json.dumps(full, sort_keys=True) != json.dumps(src[oe]["calls"], sort_keys=True): + recon_diff.append(oe) + +FULLMATCH = {"get_product_details", "get_size_guide", "get_product_reviews", "get_item_details", + "get_warranty_details", "get_extended_warranty_options", "get_shipping_options", + "get_active_promotions", "list_all_product_types", "get_user_reviews", "get_order_invoice"} +FIND = {"find_user_id_by_email", "find_user_id_by_phone", "find_user_id_by_username", "find_user_id_by_name_zip"} +CHECK = { + "apply_gift_card": ["amount_applied", "remaining_balance_due"], "apply_discount_code": ["discount", "status"], + "checkout_cart": ["total"], "cancel_order_item": ["status", "item_id"], + "return_pending_order_items": ["status", "item_ids"], "return_delivered_order_items": ["status", "item_ids"], + "exchange_delivered_order_items": ["status"], "modify_pending_order_items": [], + "remove_item_from_cart": ["subtotal"], "add_item_to_cart": ["user_id"], "get_order_details": ["status"], + "get_user_details": ["user_id", "email"], "get_cart_contents": ["subtotal"], "get_gift_card_balance": ["balance"], + "get_loyalty_points_balance": ["points"], "get_store_credit_balance": ["balance"], "get_wishlist": ["items"], + "cancel_delivered_order": ["status", "refund"], "cancel_pending_order": ["status", "refund"], + "modify_pending_order_address": ["status"], "add_gift_message": ["gift_message"], + "schedule_delivery": ["scheduled_delivery", "status"], "set_delivery_instructions": ["delivery_instructions", "status"], + "schedule_installation": ["appointment_id"], "book_repair_appointment": ["appointment_id"], + "request_return_pickup": ["confirmation"], "get_return_label": ["label_url"], + "request_gift_receipt": ["gift_receipt_url", "prices_shown"], + "file_shipping_insurance_claim": ["claim_id", "status", "estimated_review_days"], + "upgrade_shipping_speed": ["shipping_speed", "status"], "split_order_shipment": ["status"], + "request_price_adjustment": ["status"], "request_price_match": ["item_id"], + "reorder_previous_order": ["duplicated_from", "status", "total"], "register_product_warranty": [], + "submit_product_review": [], "subscribe_to_restock_alert": [], "redeem_loyalty_points": ["points_redeemed", "credit"], + "purchase_gift_card": ["amount"], "add_to_wishlist": ["user_id"], "modify_user_email": ["status", "email"], + "modify_user_name": ["status"], "modify_user_phone": ["status", "phone"], "update_user_password": ["status"], + "add_user_address": ["status"], "modify_user_address": ["status"], "delete_user_address": ["status", "deleted_zip"], + "verify_user_identity": ["verified"], +} + + +def parse(o): + try: + return json.loads(o) if isinstance(o, str) else o + except json.JSONDecodeError: + return None + + +stats = defaultdict(lambda: {"n": 0, "match": 0, "skip_nodata": 0, "mism": [], "exc": []}) +covered, uncovered = Counter(), Counter() + +for oe, full in episodes.items(): + s = EpisodeState.from_trajectory({"calls": full}, catalog) + for c in full: + n = c["name"] + if n not in TOOLS: + uncovered[n] += 1 + continue + covered[n] += 1 + rec = parse(c.get("output")) + st = stats[n] + st["n"] += 1 + try: + got = TOOLS[n](s, c.get("arguments", {})) + except Exception as e: # noqa + st["exc"].append((oe, f"{type(e).__name__}: {e}")) + continue + if n in FIND: + if got == (c.get("output") or "").strip().strip('"'): + st["match"] += 1 + else: + st["mism"].append((oe, {"uid": (got, c.get("output"))})) + continue + if not isinstance(rec, dict): + st["match"] += 1 + continue + if n in FULLMATCH: + if got == rec: + st["match"] += 1 + else: + st["mism"].append((oe, "dict-diff")) + continue + keys = CHECK.get(n, []) + if any(got.get(k) is None and rec.get(k) is not None for k in keys): + st["skip_nodata"] += 1 + continue + + def _eq(k): + g, rv = got.get(k), rec.get(k) + if k == "status" and isinstance(g, str) and isinstance(rv, str): + return g.replace(" ", "_") == rv.replace(" ", "_") + return g == rv + if all(_eq(k) for k in keys): + st["match"] += 1 + else: + st["mism"].append((oe, {k: (got.get(k), rec.get(k)) for k in keys if not _eq(k)})) + +tot_chk = sum(st["n"] - st["skip_nodata"] for st in stats.values()) +tot_match = sum(st["match"] for st in stats.values()) +tot_exc = sum(len(st["exc"]) for st in stats.values()) +tot_mism = sum(len(st["mism"]) for st in stats.values()) +tot_skip = sum(st["skip_nodata"] for st in stats.values()) + +print("=== RECONSTRUCTION INVARIANT (v5 split rows -> source n100 calls) ===") +print(f" episodes: {len(episodes)} reconstructions differing from source: {len(recon_diff)} {recon_diff[:5]}") +print("\n=== FREE-RUNNING REPLAY (whole-episode, v5) ===") +print(f" reproduced : {tot_match}/{tot_chk} = {tot_match/max(tot_chk,1):.1%}") +print(f" exceptions : {tot_exc}") +print(f" mismatches : {tot_mism}") +print(f" skipped-no-seed : {tot_skip}") +print(f" tools exercised : {len(stats)} uncovered(echo/fictional) calls: {sum(uncovered.values())}") +if tot_exc: + print("\n -- EXCEPTIONS (first 5/tool) --") + for n, st in sorted(stats.items()): + for oe, msg in st["exc"][:5]: + print(f" [{n}] {oe}: {msg}") +if tot_mism: + print("\n -- MISMATCHES (first 5/tool) --") + for n, st in sorted(stats.items()): + for oe, d in st["mism"][:5]: + print(f" [{n}] {oe}: {d}") +if tot_skip: + print("\n -- SKIP-NO-SEED counts by tool --") + for n, st in sorted(stats.items()): + if st["skip_nodata"]: + print(f" [{n}] {st['skip_nodata']}") diff --git a/tempscripts/story_remediation/unbundle/run_auth_c1c3.py b/tempscripts/story_remediation/unbundle/run_auth_c1c3.py new file mode 100644 index 0000000000000000000000000000000000000000..037709d61fa922566cc85ca4411d795750cbe910 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/run_auth_c1c3.py @@ -0,0 +1,142 @@ +"""Run C1 (ground-truth validity) and C3 (v2 prompt) on the AUTH-PROBLEM rows, +judging both v5 (before) and v6 (after the deterministic auth fixes) so the only +variable is the authored NL (calls are byte-identical v5==v6). + +Auth-problem set = union of + (a) auth-primary CAUGHT rows -> caught_reasons_v5.jsonl primary==D_auth_verification + (b) rows the deterministic lint FIXED in v6 -> NL differs v5 vs v6 + +Reports, for this set: + * C3 v2 caught rate v5 vs v6 (drop = the auth fixes fooled the judge) + * C1 fail/borderline v5 vs v6 (should not regress; calls unchanged) + +Run: python -u temp/story_remediation/unbundle/run_auth_c1c3.py +""" +from __future__ import annotations +import json, logging, sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +SAMPLES = 3 +WORKERS = max(8, cfg["run"].get("workers", 4)) + +v5 = {e["example_id"]: e for e in + (json.loads(l) for l in open(OUT / "trajectories_all_v5.jsonl", encoding="utf-8") if l.strip())} +v6 = {e["example_id"]: e for e in + (json.loads(l) for l in open(OUT / "trajectories_all_v6.jsonl", encoding="utf-8") if l.strip())} + +# (a) auth-primary caught rows +auth_caught = {json.loads(l)["item_id"] + for l in open(OUT / "caught_reasons_v5.jsonl", encoding="utf-8") if l.strip() + and json.loads(l).get("primary") == "D_auth_verification"} +# (b) lint-fixed rows (NL differs) +fixed = {eid for eid in v5 + if json.dumps(v5[eid].get("history")) != json.dumps(v6[eid].get("history")) + or v5[eid].get("query") != v6[eid].get("query")} + +AUTH_IDS = sorted((auth_caught | fixed) & set(v5) & set(v6)) +print(f"auth-primary caught: {len(auth_caught)} | lint-fixed: {len(fixed)} " + f"| union present in both: {len(AUTH_IDS)}") + +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line); base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) + + +def c3_pair(fake, real, swap): + system, user = J.load_prompt("C3v2") + fr = J.render_trajectory(fake, blind_tools=True, include_metadata=False, conversation_only=True) + rr = J.render_trajectory(real, blind_tools=True, include_metadata=False, conversation_only=True) + a, b, key = (rr, fr, "B") if swap else (fr, rr, "A") + user = user.replace("{{CONV_A}}", a).replace("{{CONV_B}}", b) + return {"system": system, "user": user, "answer_key": key} + + +def maj(msgs, field): + vals = [] + for _ in range(SAMPLES): + try: + vals.append(judge.judge({"system": msgs["system"], "user": msgs["user"]}).get(field)) + except Exception: # noqa: BLE001 + pass + if not vals: + return None, 0.0 + m = Counter(vals).most_common(1)[0][0] + return m, vals.count(m) / len(vals) + + +def one(eid): + real = pairer(v5[eid]) + swap = (base.get(eid) or base.get(v5[eid].get("metadata", {}).get("orig_eid")) or {} + ).get("answer_key") == "B" + out = {"item_id": eid, "role": v5[eid].get("metadata", {}).get("unbundle_role")} + for tag, ds in (("v5", v5), ("v6", v6)): + fake = ds[eid] + c3 = c3_pair(fake, real, swap); key = c3["answer_key"] + g, ga = maj(c3, "guess") + c1 = J.build_c1(fake) + vd, vda = maj(c1, "verdict") + out[f"{tag}_c3_guess"] = g + out[f"{tag}_c3_caught"] = (g == key) + out[f"{tag}_c1_verdict"] = vd + return out + + +def main(): + print(f"judging {len(AUTH_IDS)} auth rows x2 versions x(C1+C3v2) " + f"(samples={SAMPLES}, workers={WORKERS})") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + rows = list(ex.map(one, AUTH_IDS)) + (OUT / "auth_c1c3.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8") + + n = len(rows) + v5c = sum(1 for r in rows if r["v5_c3_caught"]) + v6c = sum(1 for r in rows if r["v6_c3_caught"]) + flipped = [r for r in rows if r["v5_c3_caught"] and not r["v6_c3_caught"]] + regress = [r for r in rows if not r["v5_c3_caught"] and r["v6_c3_caught"]] + + def c1fail(tag): + return sum(1 for r in rows if r[f"{tag}_c1_verdict"] in ("fail", "borderline")) + + print("\n" + "=" * 74) + print(f"AUTH-PROBLEM ROWS: {n}") + print(f" C3 (v2 prompt) caught v5: {v5c}/{n} = {v5c/n:.0%} " + f"v6: {v6c}/{n} = {v6c/n:.0%}") + print(f" -> flipped caught->fooled by the fixes: {len(flipped)}/{max(v5c,1)}" + f" = {len(flipped)/max(v5c,1):.0%}") + print(f" -> regressions (fooled->caught): {len(regress)}") + print(f" C1 fail/borderline v5: {c1fail('v5')}/{n} v6: {c1fail('v6')}/{n} " + f"(calls unchanged; expect ~equal)") + print("=" * 74) + print("\nflipped (auth fix fooled the C3 v2 judge):") + for r in flipped[:20]: + print(f" {r['item_id']:44s} role={r['role']} v5={r['v5_c3_guess']}->v6={r['v6_c3_guess']}") + if regress: + print("\nREGRESSIONS to inspect:") + for r in regress: + print(f" {r['item_id']:44s} role={r['role']}") + print(f"\nsaved -> {(OUT/'auth_c1c3.jsonl').relative_to(ROOT)}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/unbundle/run_c3_all.py b/tempscripts/story_remediation/unbundle/run_c3_all.py new file mode 100644 index 0000000000000000000000000000000000000000..9bc9a8da7b50c5eeecde504d872357d34a5df64b --- /dev/null +++ b/tempscripts/story_remediation/unbundle/run_c3_all.py @@ -0,0 +1,102 @@ +"""Run C3 on the FULL unbundled dataset (out/trajectories_all.jsonl, 1302 rows). + +Same judge procedure as baseline (samples=3 majority, model from config). Reuse +each row's BASELINE pairing orientation where available; split tail rows (eid +'-tN', absent from baseline) fall back to their orig_eid's answer_key so +orientation stays deterministic. + +Writes out/C3_all.jsonl. Run from repo root: + python -u temp/story_remediation/unbundle/run_c3_all.py +""" +from __future__ import annotations +import json, logging, sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) + +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +REMED = OUT / "trajectories_all.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +RESULT = OUT / "C3_all.jsonl" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +SAMPLES = 3 +WORKERS = max(8, cfg["run"].get("workers", 4)) + +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line) + base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) +fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()] + + +def judge_one(fake): + eid = fake["example_id"] + orig_eid = fake.get("metadata", {}).get("orig_eid") + b = base.get(eid) + real = pairer(fake) + swap = (b or base.get(orig_eid) or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + key = msgs["answer_key"] + guesses, err = [], None + for _ in range(SAMPLES): + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + guesses.append(r.get("guess")) + except Exception as e: # noqa: BLE001 + err = str(e) + role = fake.get("metadata", {}).get("unbundle_role") + if not guesses: + return {"item_id": eid, "orig_eid": orig_eid, "role": role, + "error": err, "answer_key": key, "real_id": real.get("example_id")} + majority = Counter(guesses).most_common(1)[0][0] + agree = guesses.count(majority) / len(guesses) + return {"item_id": eid, "orig_eid": orig_eid, "role": role, + "answer_key": key, "real_id": real.get("example_id"), + "baseline_real_id": (b or {}).get("real_id"), + "guess": majority, "agreement": agree, "n_samples": len(guesses), + "sample_guesses": guesses, "caught": majority == key, + "baseline_caught": (base.get(orig_eid) or b or {}).get("caught"), + "error": None} + + +def main(): + print(f"judging {len(fakes)} rows (samples={SAMPLES}, workers={WORKERS}, " + f"model={cfg['model']['label']})") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + results = list(ex.map(judge_one, fakes)) + results.sort(key=lambda r: r["item_id"]) + RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8") + + ok = [r for r in results if r.get("error") is None and "caught" in r] + errs = [r for r in results if r.get("error") is not None or "caught" not in r] + caught = sum(1 for r in ok if r["caught"]) + n = len(ok) + print("\n=== C3 FULL UNBUNDLE RESULT ===") + print(f" rows judged : {n} errors: {len(errs)}") + print(f" caught : {caught}/{n} = {caught/n:.1%}") + if errs: + print(" sample error:", errs[0].get("error")) + print(f" wrote {RESULT.relative_to(ROOT)} (run analyze_all.py for the full breakdown)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/story_remediation/unbundle/run_c3_all_v2.py b/tempscripts/story_remediation/unbundle/run_c3_all_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..d64768f0b22ca630c342919aa9b951bfc94996a3 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/run_c3_all_v2.py @@ -0,0 +1,102 @@ +"""Run C3 on the FULL unbundled dataset (out/trajectories_all_v2.jsonl, 1302 rows). + +Same judge procedure as baseline (samples=3 majority, model from config). Reuse +each row's BASELINE pairing orientation where available; split tail rows (eid +'-tN', absent from baseline) fall back to their orig_eid's answer_key so +orientation stays deterministic. + +Writes out/C3_all_v2.jsonl. Run from repo root: + python -u temp/story_remediation/unbundle/run_c3_all.py +""" +from __future__ import annotations +import json, logging, sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) + +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +REMED = OUT / "trajectories_all_v2.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +RESULT = OUT / "C3_all_v2.jsonl" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +SAMPLES = 3 +WORKERS = max(8, cfg["run"].get("workers", 4)) + +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line) + base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) +fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()] + + +def judge_one(fake): + eid = fake["example_id"] + orig_eid = fake.get("metadata", {}).get("orig_eid") + b = base.get(eid) + real = pairer(fake) + swap = (b or base.get(orig_eid) or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + key = msgs["answer_key"] + guesses, err = [], None + for _ in range(SAMPLES): + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + guesses.append(r.get("guess")) + except Exception as e: # noqa: BLE001 + err = str(e) + role = fake.get("metadata", {}).get("unbundle_role") + if not guesses: + return {"item_id": eid, "orig_eid": orig_eid, "role": role, + "error": err, "answer_key": key, "real_id": real.get("example_id")} + majority = Counter(guesses).most_common(1)[0][0] + agree = guesses.count(majority) / len(guesses) + return {"item_id": eid, "orig_eid": orig_eid, "role": role, + "answer_key": key, "real_id": real.get("example_id"), + "baseline_real_id": (b or {}).get("real_id"), + "guess": majority, "agreement": agree, "n_samples": len(guesses), + "sample_guesses": guesses, "caught": majority == key, + "baseline_caught": (base.get(orig_eid) or b or {}).get("caught"), + "error": None} + + +def main(): + print(f"judging {len(fakes)} rows (samples={SAMPLES}, workers={WORKERS}, " + f"model={cfg['model']['label']})") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + results = list(ex.map(judge_one, fakes)) + results.sort(key=lambda r: r["item_id"]) + RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8") + + ok = [r for r in results if r.get("error") is None and "caught" in r] + errs = [r for r in results if r.get("error") is not None or "caught" not in r] + caught = sum(1 for r in ok if r["caught"]) + n = len(ok) + print("\n=== C3 FULL UNBUNDLE RESULT ===") + print(f" rows judged : {n} errors: {len(errs)}") + print(f" caught : {caught}/{n} = {caught/n:.1%}") + if errs: + print(" sample error:", errs[0].get("error")) + print(f" wrote {RESULT.relative_to(ROOT)} (run analyze_all.py for the full breakdown)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/story_remediation/unbundle/run_c3_all_v3.py b/tempscripts/story_remediation/unbundle/run_c3_all_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..aecea63731daf6f3997c49a9fdae19faf33528aa --- /dev/null +++ b/tempscripts/story_remediation/unbundle/run_c3_all_v3.py @@ -0,0 +1,102 @@ +"""Run C3 on the FULL unbundled dataset (out/trajectories_all_v3.jsonl, 1302 rows). + +Same judge procedure as baseline (samples=3 majority, model from config). Reuse +each row's BASELINE pairing orientation where available; split tail rows (eid +'-tN', absent from baseline) fall back to their orig_eid's answer_key so +orientation stays deterministic. + +Writes out/C3_all_v3.jsonl. Run from repo root: + python -u temp/story_remediation/unbundle/run_c3_all.py +""" +from __future__ import annotations +import json, logging, sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) + +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +REMED = OUT / "trajectories_all_v3.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +RESULT = OUT / "C3_all_v3.jsonl" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +SAMPLES = 3 +WORKERS = max(8, cfg["run"].get("workers", 4)) + +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line) + base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) +fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()] + + +def judge_one(fake): + eid = fake["example_id"] + orig_eid = fake.get("metadata", {}).get("orig_eid") + b = base.get(eid) + real = pairer(fake) + swap = (b or base.get(orig_eid) or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + key = msgs["answer_key"] + guesses, err = [], None + for _ in range(SAMPLES): + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + guesses.append(r.get("guess")) + except Exception as e: # noqa: BLE001 + err = str(e) + role = fake.get("metadata", {}).get("unbundle_role") + if not guesses: + return {"item_id": eid, "orig_eid": orig_eid, "role": role, + "error": err, "answer_key": key, "real_id": real.get("example_id")} + majority = Counter(guesses).most_common(1)[0][0] + agree = guesses.count(majority) / len(guesses) + return {"item_id": eid, "orig_eid": orig_eid, "role": role, + "answer_key": key, "real_id": real.get("example_id"), + "baseline_real_id": (b or {}).get("real_id"), + "guess": majority, "agreement": agree, "n_samples": len(guesses), + "sample_guesses": guesses, "caught": majority == key, + "baseline_caught": (base.get(orig_eid) or b or {}).get("caught"), + "error": None} + + +def main(): + print(f"judging {len(fakes)} rows (samples={SAMPLES}, workers={WORKERS}, " + f"model={cfg['model']['label']})") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + results = list(ex.map(judge_one, fakes)) + results.sort(key=lambda r: r["item_id"]) + RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8") + + ok = [r for r in results if r.get("error") is None and "caught" in r] + errs = [r for r in results if r.get("error") is not None or "caught" not in r] + caught = sum(1 for r in ok if r["caught"]) + n = len(ok) + print("\n=== C3 FULL UNBUNDLE RESULT ===") + print(f" rows judged : {n} errors: {len(errs)}") + print(f" caught : {caught}/{n} = {caught/n:.1%}") + if errs: + print(" sample error:", errs[0].get("error")) + print(f" wrote {RESULT.relative_to(ROOT)} (run analyze_all.py for the full breakdown)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/story_remediation/unbundle/run_c3_all_v4.py b/tempscripts/story_remediation/unbundle/run_c3_all_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..9302aab988fd2e4b454cccdc0c058bba43fa8bb5 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/run_c3_all_v4.py @@ -0,0 +1,94 @@ +"""Run C3 on the v4 dataset (out/trajectories_all_v4.jsonl). Identical procedure to +the v3 runner; only the input/output paths change. Writes out/C3_all_v4.jsonl. +Run: python -u temp/story_remediation/unbundle/run_c3_all_v4.py +""" +from __future__ import annotations +import json, logging, sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +REMED = OUT / "trajectories_all_v4.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +RESULT = OUT / "C3_all_v4.jsonl" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +SAMPLES = 3 +WORKERS = max(8, cfg["run"].get("workers", 4)) + +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line); base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) +fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()] + + +def judge_one(fake): + eid = fake["example_id"] + orig_eid = fake.get("metadata", {}).get("orig_eid") + b = base.get(eid) + real = pairer(fake) + swap = (b or base.get(orig_eid) or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + key = msgs["answer_key"] + guesses, err = [], None + for _ in range(SAMPLES): + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + guesses.append(r.get("guess")) + except Exception as e: # noqa: BLE001 + err = str(e) + role = fake.get("metadata", {}).get("unbundle_role") + if not guesses: + return {"item_id": eid, "orig_eid": orig_eid, "role": role, + "error": err, "answer_key": key, "real_id": real.get("example_id")} + majority = Counter(guesses).most_common(1)[0][0] + agree = guesses.count(majority) / len(guesses) + return {"item_id": eid, "orig_eid": orig_eid, "role": role, + "answer_key": key, "real_id": real.get("example_id"), + "baseline_real_id": (b or {}).get("real_id"), + "guess": majority, "agreement": agree, "n_samples": len(guesses), + "sample_guesses": guesses, "caught": majority == key, + "baseline_caught": (base.get(orig_eid) or b or {}).get("caught"), + "error": None} + + +def main(): + print(f"judging {len(fakes)} rows (samples={SAMPLES}, workers={WORKERS}, " + f"model={cfg['model']['label']})") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + results = list(ex.map(judge_one, fakes)) + results.sort(key=lambda r: r["item_id"]) + RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8") + + ok = [r for r in results if r.get("error") is None and "caught" in r] + errs = [r for r in results if r.get("error") is not None or "caught" not in r] + caught = sum(1 for r in ok if r["caught"]) + n = len(ok) + print("\n=== C3 V4 RESULT ===") + print(f" rows judged : {n} errors: {len(errs)}") + print(f" caught : {caught}/{n} = {caught/n:.1%}") + if errs: + print(" sample error:", errs[0].get("error")) + print(f" wrote {RESULT.relative_to(ROOT)} (run analyze_all_v4.py for the breakdown)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/story_remediation/unbundle/run_c3_all_v5.py b/tempscripts/story_remediation/unbundle/run_c3_all_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..f0528259eba900a98914f96147bb515776321f03 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/run_c3_all_v5.py @@ -0,0 +1,94 @@ +"""Run C3 on the v5 dataset (out/trajectories_all_v5.jsonl). Identical procedure to +the v4 runner; only the input/output paths change. Writes out/C3_all_v5.jsonl. +Run: python -u temp/story_remediation/unbundle/run_c3_all_v5.py +""" +from __future__ import annotations +import json, logging, sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +REMED = OUT / "trajectories_all_v5.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +RESULT = OUT / "C3_all_v5.jsonl" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +SAMPLES = 3 +WORKERS = max(8, cfg["run"].get("workers", 4)) + +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line); base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) +fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()] + + +def judge_one(fake): + eid = fake["example_id"] + orig_eid = fake.get("metadata", {}).get("orig_eid") + b = base.get(eid) + real = pairer(fake) + swap = (b or base.get(orig_eid) or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + key = msgs["answer_key"] + guesses, err = [], None + for _ in range(SAMPLES): + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + guesses.append(r.get("guess")) + except Exception as e: # noqa: BLE001 + err = str(e) + role = fake.get("metadata", {}).get("unbundle_role") + if not guesses: + return {"item_id": eid, "orig_eid": orig_eid, "role": role, + "error": err, "answer_key": key, "real_id": real.get("example_id")} + majority = Counter(guesses).most_common(1)[0][0] + agree = guesses.count(majority) / len(guesses) + return {"item_id": eid, "orig_eid": orig_eid, "role": role, + "answer_key": key, "real_id": real.get("example_id"), + "baseline_real_id": (b or {}).get("real_id"), + "guess": majority, "agreement": agree, "n_samples": len(guesses), + "sample_guesses": guesses, "caught": majority == key, + "baseline_caught": (base.get(orig_eid) or b or {}).get("caught"), + "error": None} + + +def main(): + print(f"judging {len(fakes)} rows (samples={SAMPLES}, workers={WORKERS}, " + f"model={cfg['model']['label']})") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + results = list(ex.map(judge_one, fakes)) + results.sort(key=lambda r: r["item_id"]) + RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8") + + ok = [r for r in results if r.get("error") is None and "caught" in r] + errs = [r for r in results if r.get("error") is not None or "caught" not in r] + caught = sum(1 for r in ok if r["caught"]) + n = len(ok) + print("\n=== C3 V5 RESULT ===") + print(f" rows judged : {n} errors: {len(errs)}") + print(f" caught : {caught}/{n} = {caught/n:.1%}") + if errs: + print(" sample error:", errs[0].get("error")) + print(f" wrote {RESULT.relative_to(ROOT)} (run analyze_all_v5.py for the breakdown)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/story_remediation/unbundle/run_c3_v3.py b/tempscripts/story_remediation/unbundle/run_c3_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..4df60cee1f4057324151e8e705479822b902f0d9 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/run_c3_v3.py @@ -0,0 +1,109 @@ +"""Run C3 on the remediated trajectories and compare to baseline. + +Same judge procedure as the baseline C3 pass (samples=3 majority, workers from +config, model from datasetreview/config.yaml). For a controlled before/after we +reuse each row's BASELINE pairing + orientation (answer_key) so the ONLY thing +that changed is the remediated dialogue. + +Writes out/C3_remediated.jsonl (canonical files untouched). +Run from repo root: python -u temp/story_remediation/run_c3_remediated.py +""" +from __future__ import annotations +import json, logging, sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +import yaml + +for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"): + logging.getLogger(_n).setLevel(logging.WARNING) + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[2] +sys.path.insert(0, str(ROOT)) + +from datasetreview import pipelines as P # noqa: E402 +from datasetreview import judge_prompts as J # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 + +OUT = HERE / "out" +REMED = OUT / "trajectories_v3.jsonl" +BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl" +RESULT = OUT / "C3_v3.jsonl" + +cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8")) +SAMPLES = 3 +WORKERS = max(8, cfg["run"].get("workers", 4)) + +base = {} +for line in open(BASELINE, encoding="utf-8"): + if line.strip(): + d = json.loads(line) + base[d["item_id"]] = d + +reals = P.real_trajectories() +pairer = P.make_pairer(reals) +judge = make_judge(cfg["model"]) +fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()] + + +def judge_one(fake): + eid = fake["example_id"] + b = base.get(eid) + real = pairer(fake) + # reuse baseline orientation: answer_key A => swap False, B => swap True + swap = (b or base.get(fake.get("metadata",{}).get("orig_eid")) or {}).get("answer_key") == "B" + msgs = J.build_c3(fake, real, swap=swap) + key = msgs["answer_key"] + guesses, err = [], None + for _ in range(SAMPLES): + try: + r = judge.judge({"system": msgs["system"], "user": msgs["user"]}) + guesses.append(r.get("guess")) + except Exception as e: # noqa: BLE001 + err = str(e) + if not guesses: + return {"item_id": eid, "error": err, "answer_key": key, + "real_id": real.get("example_id")} + majority = Counter(guesses).most_common(1)[0][0] + agree = guesses.count(majority) / len(guesses) + return {"item_id": eid, "answer_key": key, "real_id": real.get("example_id"), + "baseline_real_id": (b or {}).get("real_id"), + "guess": majority, "agreement": agree, "n_samples": len(guesses), + "sample_guesses": guesses, "caught": majority == key, + "baseline_caught": (b or {}).get("caught"), "error": None} + + +def main(): + print(f"judging {len(fakes)} remediated rows (samples={SAMPLES}, workers={WORKERS}, " + f"model={cfg['model']['label']})") + with ThreadPoolExecutor(max_workers=WORKERS) as ex: + results = list(ex.map(judge_one, fakes)) + results.sort(key=lambda r: r["item_id"]) + RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8") + + ok = [r for r in results if r.get("error") is None and "caught" in r] + errs = [r for r in results if r.get("error") is not None or "caught" not in r] + caught = sum(1 for r in ok if r["caught"]) + n = len(ok) + base_caught = sum(1 for r in ok if r.get("baseline_caught")) + pair_match = sum(1 for r in ok if r.get("real_id") == r.get("baseline_real_id")) + flip_fixed = sum(1 for r in ok if r.get("baseline_caught") and not r["caught"]) + flip_regress = sum(1 for r in ok if not r.get("baseline_caught") and r["caught"]) + + print("\n=== C3 V3 (UNBUNDLE) RESULT ===") + print(f" rows judged : {n} errors: {len(errs)}") + print(f" pairing match base : {pair_match}/{n}") + print(f" baseline caught : {base_caught}/{n} = {base_caught/n:.1%}") + print(f" remediated caught : {caught}/{n} = {caught/n:.1%}") + print(f" fixed (caught->fooled) : {flip_fixed}") + print(f" regressed (fooled->caught): {flip_regress}") + print(f" wrote {RESULT.relative_to(ROOT)}") + if errs: + print(" sample error:", errs[0].get("error")) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) + diff --git a/tempscripts/story_remediation/unbundle/run_final_c1c3.py b/tempscripts/story_remediation/unbundle/run_final_c1c3.py new file mode 100644 index 0000000000000000000000000000000000000000..be5a1c8be4907cb6d265c806d293b87bed396d72 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/run_final_c1c3.py @@ -0,0 +1,64 @@ +"""FINAL C1 + C3 run over the v6 dataset (the real dataset), using the CANONICAL +pipeline + record writers from scripts/run_dataeval.py so the emitted JSONL is +byte-for-byte the same schema a normal run produces (full per-sample `result` with +reasoning, majority/agreement, both C3 orientations, etc.). + +Only difference from `python -m scripts.run_dataeval`: the confuser-trajectory loader +is pointed at trajectories_all_v6.jsonl instead of the n100 source, and we run C1 + C3 +with 3-sample majority. C3 uses the (now canonical) DO/DON'T prompt. + +Run from repo root: + python -u temp/story_remediation/unbundle/run_final_c1c3.py +Outputs -> temp/story_remediation/unbundle/final_c1c3/{C1,C3}.jsonl + summary.json +""" +from __future__ import annotations +import json +import sys +from pathlib import Path + +import yaml + +ROOT = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT)) + +from datasetreview import pipelines as P # noqa: E402 +from datasetreview.llm_client import make_judge # noqa: E402 +from scripts import run_dataeval as R # noqa: E402 + +V6 = ROOT / "temp" / "story_remediation" / "unbundle" / "out" / "trajectories_all_v6.jsonl" +OUT = ROOT / "temp" / "story_remediation" / "unbundle" / "final_c1c3" + +_ROWS = [json.loads(l) for l in open(V6, encoding="utf-8") if l.strip()] + +# Point the canonical loader at v6 (return the full set regardless of level). +P.confuser_trajectories = lambda level: _ROWS + +EXPS = ["C1", "C3"] +LEVELS = [100] +SAMPLES = 3 +WORKERS = 8 + + +def main() -> int: + cfg = yaml.safe_load((ROOT / "datasetreview" / "config.yaml").read_text(encoding="utf-8")) + judge = make_judge(cfg["model"]) + OUT.mkdir(parents=True, exist_ok=True) + print(f"model={cfg['model'].get('label')} rows={len(_ROWS)} exps={EXPS} " + f"samples={SAMPLES} workers={WORKERS} -> {OUT}") + + ctx = P.build_context(EXPS) + summary = [] + for exp in EXPS: + pipe = P.PIPELINES[exp](ctx) + summary.append(R.run_pipeline( + pipe, LEVELS, judge=judge, out_dir=OUT, limit=None, + workers=WORKERS, samples=SAMPLES, + resume=True, resume_force=False, dry_run=False, + )) + (OUT / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") + print(f"\nSummary -> {OUT / 'summary.json'}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tempscripts/story_remediation/unbundle/run_freecheck_v6.py b/tempscripts/story_remediation/unbundle/run_freecheck_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..254ab7c55b1beca6a73c4560e2d7f652ce18e6f3 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/run_freecheck_v6.py @@ -0,0 +1,273 @@ +"""Deterministic free-running correctness check on v6 (the answer to: are there ANY +deterministic inconsistencies that would risk error in free-running?). + +Runs, per RECONSTRUCTED EPISODE (v6 split rows regrouped by orig_eid, ordered by +turn), four independent deterministic checks: + + (1) RECONSTRUCTION INVARIANT -- concat(v6 rows' calls in turn order) must equal + the source n100 call list byte-for-byte. Divergence = a dropped / mangled + variable introduced by the unbundling or the v6 prose edits. + + (2) EXECUTABLE REPLAY -- seed ONE EpisodeState per episode, replay the + full ordered call sequence, assert each output reproduces the recorded one. + Exception / mismatch = a variable used before it exists, or an invalid arg. + + (3) WHOLE-EPISODE GROUNDING -- every id consumed as a HIGH_ID_KEY arg (order_id, + item_id(s), gift_card_id, user_id, address_id, payment_method_id, appointment_id, + claim_id, invoice_id) must FIRST appear either in the episode dialogue (user- + provided) or in an EARLIER call output. A consume-before-produce = exactly the + "variable later introduced that was never returned earlier" defect. + + (4) IDENTITY CONSISTENCY -- auth_lint_v5 name/zip/dup-verification/userid flags + (0 = every name/zip is consistent across the whole conversation). + +Run from repo root: python -u temp/story_remediation/unbundle/run_freecheck_v6.py +""" +from __future__ import annotations +import json, sys, re +from collections import Counter, defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +EXEC = ROOT / "systemUpgrade" / "executor" +sys.path.insert(0, str(EXEC)) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from fake_state import EpisodeState # noqa: E402 +from fake_tools import TOOLS # noqa: E402 +import auth_lint_v5 as L # noqa: E402 + +FULLMATCH = {"get_product_details", "get_size_guide", "get_product_reviews", "get_item_details", + "get_warranty_details", "get_extended_warranty_options", "get_shipping_options", + "get_active_promotions", "list_all_product_types", "get_user_reviews", "get_order_invoice"} +FIND = {"find_user_id_by_email", "find_user_id_by_phone", "find_user_id_by_username", "find_user_id_by_name_zip"} +CHECK = { + "apply_gift_card": ["amount_applied", "remaining_balance_due"], "apply_discount_code": ["discount", "status"], + "checkout_cart": ["total"], "cancel_order_item": ["status", "item_id"], + "return_pending_order_items": ["status", "item_ids"], "return_delivered_order_items": ["status", "item_ids"], + "exchange_delivered_order_items": ["status"], "modify_pending_order_items": [], + "remove_item_from_cart": ["subtotal"], "add_item_to_cart": ["user_id"], "get_order_details": ["status"], + "get_user_details": ["user_id", "email"], "get_cart_contents": ["subtotal"], "get_gift_card_balance": ["balance"], + "get_loyalty_points_balance": ["points"], "get_store_credit_balance": ["balance"], "get_wishlist": ["items"], + "cancel_delivered_order": ["status", "refund"], "cancel_pending_order": ["status", "refund"], + "modify_pending_order_address": ["status"], "add_gift_message": ["gift_message"], + "schedule_delivery": ["scheduled_delivery", "status"], "set_delivery_instructions": ["delivery_instructions", "status"], + "schedule_installation": ["appointment_id"], "book_repair_appointment": ["appointment_id"], + "request_return_pickup": ["confirmation"], "get_return_label": ["label_url"], + "request_gift_receipt": ["gift_receipt_url", "prices_shown"], + "file_shipping_insurance_claim": ["claim_id", "status", "estimated_review_days"], + "upgrade_shipping_speed": ["shipping_speed", "status"], "split_order_shipment": ["status"], + "request_price_adjustment": ["status"], "request_price_match": ["item_id"], + "reorder_previous_order": ["duplicated_from", "status", "total"], "register_product_warranty": [], + "submit_product_review": [], "subscribe_to_restock_alert": [], "redeem_loyalty_points": ["points_redeemed", "credit"], + "purchase_gift_card": ["amount"], "add_to_wishlist": ["user_id"], "modify_user_email": ["status", "email"], + "modify_user_name": ["status"], "modify_user_phone": ["status", "phone"], "update_user_password": ["status"], + "add_user_address": ["status"], "modify_user_address": ["status"], "delete_user_address": ["status", "deleted_zip"], + "verify_user_identity": ["verified"], +} + + +def _parse(o): + try: + return json.loads(o) if isinstance(o, str) else o + except json.JSONDecodeError: + return None + +catalog = json.load(open(EXEC / "catalog.json", encoding="utf-8")) +V6 = ROOT / "temp" / "story_remediation" / "unbundle" / "out" / "trajectories_all_v6.jsonl" +SRC = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl" + +v6 = [json.loads(l) for l in open(V6, encoding="utf-8") if l.strip()] +src = {json.loads(l)["example_id"]: json.loads(l) + for l in open(SRC, encoding="utf-8") if l.strip()} + +# ---------- grounding key sets (from systemUpgrade/_audit.py) ---------- +HIGH_ID_KEYS = {"order_id", "item_id", "item_ids", "gift_card_id", "address_id", + "payment_method_id", "user_id", "appointment_id", "claim_id", "invoice_id"} +CATALOG_KEYS = {"product_id", "new_item_ids"} +SKIP_KEYS = {"code", "phone", "email", "username", "new_password", "first_name", "last_name", + "name", "message", "comment", "instructions", "reason", "speed", "date", "rating", + "quantity", "amount", "points", "competitor_price", "state", "city", "country", + "address1", "verification_code", "zip"} +KNOWN_PATS = [re.compile(r"#?W\d{5,}"), re.compile(r"\b\d{6,}\b"), + re.compile(r"\b[a-z]+(?:_[a-z]+)+_\d{2,}\b"), + re.compile(r"\b(?:paypal|venmo|applepay)_\d{3,}\b"), + re.compile(r"\b(?:gc|pm|addr|gift)_\w+\b")] +norm = lambda x: str(x).lstrip("#").strip().lower() + + +def known_tokens(text): + out = set() + for p in KNOWN_PATS: + out.update(norm(m.group(0)) for m in p.finditer(text)) + return out + + +def output_ids(output): + ids = set() + o = output + if isinstance(o, str): + try: o = json.loads(o) + except Exception: o = None + ids |= known_tokens(str(output)) + + def walk(v): + if isinstance(v, dict): + for k, x in v.items(): + if k in HIGH_ID_KEYS or k in CATALOG_KEYS or k.endswith("_id") or k.endswith("_ids"): + if isinstance(x, (list, tuple)): ids.update(norm(e) for e in x) + elif x is not None: ids.add(norm(x)) + walk(x) + elif isinstance(v, (list, tuple)): + for x in v: walk(x) + walk(o) + return ids + + +def consumed_high(args): + out = [] + if not isinstance(args, dict): return out + for k, v in args.items(): + if k in SKIP_KEYS or k in CATALOG_KEYS: continue + if k in HIGH_ID_KEYS or k.endswith("_id") or k.endswith("_ids"): + if isinstance(v, (list, tuple)): out += [(k, norm(e)) for e in v] + elif v is not None and str(v).strip(): out.append((k, norm(v))) + return out + + +def turn_idx(r): + role = (r.get("metadata") or {}).get("unbundle_role") or "" + if role == "turn1": return 1 + m = re.match(r"turn(\d+)", role) + return int(m.group(1)) if m else 1 + + +# ---------- group v6 rows into episodes ---------- +groups = defaultdict(list) +for r in v6: + oe = (r.get("metadata") or {}).get("orig_eid") or r["example_id"] + groups[oe].append(r) + +conf_eids = {oe for oe, rows in groups.items() + if any((r.get("metadata") or {}).get("distractor_class") == "confuser" for r in rows)} + +recon_diff = [] +episodes = {} +episode_nl = {} +for oe, rows in groups.items(): + rows_sorted = sorted(rows, key=turn_idx) + full = [] + nl = [] + for r in rows_sorted: + full += r["calls"] + # seed grounding from ALL embedded history (incl. tool outputs + tool_call args) + nl.append(json.dumps(r.get("history", []))) + nl.append(json.dumps((r.get("metadata") or {}).get("history", []))) + nl.append(r.get("query", "")); nl.append(r.get("retrieval_text", "") or "") + episodes[oe] = full + episode_nl[oe] = " ".join(nl) + if oe in src and json.dumps(full, sort_keys=True) != json.dumps(src[oe]["calls"], sort_keys=True): + recon_diff.append(oe) + +# ---------- (3) whole-episode grounding ---------- +grounding_defects = [] +for oe, full in episodes.items(): + known = known_tokens(episode_nl[oe]) + for i, c in enumerate(full): + for k, v in consumed_high(c.get("arguments", {})): + if v not in known: + grounding_defects.append({"episode": oe, "call": i, "tool": c["name"], "key": k, "id": v}) + known |= {v for _, v in consumed_high(c.get("arguments", {}))} + known |= output_ids(c.get("output", "")) + +# ---------- (2) executable replay ---------- +stats = defaultdict(lambda: {"n": 0, "match": 0, "skip": 0, "mism": [], "exc": []}) +uncovered = Counter() +for oe, full in episodes.items(): + s = EpisodeState.from_trajectory({"calls": full}, catalog) + for c in full: + n = c["name"] + if n not in TOOLS: + uncovered[n] += 1; continue + rec = _parse(c.get("output")) + st = stats[n]; st["n"] += 1 + try: + got = TOOLS[n](s, c.get("arguments", {})) + except Exception as e: # noqa + st["exc"].append((oe, f"{type(e).__name__}: {e}")); continue + if n in FIND: + if got == (c.get("output") or "").strip().strip('"'): st["match"] += 1 + else: st["mism"].append((oe, "uid")) + continue + if not isinstance(rec, dict): st["match"] += 1; continue + if n in FULLMATCH: + if got == rec: st["match"] += 1 + else: st["mism"].append((oe, "dict-diff")) + continue + keys = CHECK.get(n, []) + if any(got.get(k) is None and rec.get(k) is not None for k in keys): + st["skip"] += 1; continue + + def _eq(k): + g, rvv = got.get(k), rec.get(k) + if k == "status" and isinstance(g, str) and isinstance(rvv, str): + return g.replace(" ", "_") == rvv.replace(" ", "_") + return g == rvv + if all(_eq(k) for k in keys): st["match"] += 1 + else: st["mism"].append((oe, {k: (got.get(k), rec.get(k)) for k in keys if not _eq(k)})) + +tot_chk = sum(st["n"] - st["skip"] for st in stats.values()) +tot_match = sum(st["match"] for st in stats.values()) +tot_exc = sum(len(st["exc"]) for st in stats.values()) +tot_skip = sum(st["skip"] for st in stats.values()) + +# ---------- classify mismatches: deterministic defect vs. confuser compound-money ---------- +# Confuser distractors fabricate gift-card / cart money amounts that appear ONLY in a +# write output (never a read), so they are self-consistent but under-determined for +# independent recomputation. Like added_cost / appointment windows / message text, these +# fields are non-deterministic BY DESIGN and are not validated by the replay harness. +NONDET_MONEY = {"remaining_balance_due", "amount_applied", "subtotal", "total", "discount"} +det_defects, nondet_money = [], [] +for n, st in stats.items(): + for oe, d in st["mism"]: + is_money = (oe in conf_eids and isinstance(d, dict) and d + and all(k in NONDET_MONEY for k in d)) + (nondet_money if is_money else det_defects).append((n, oe, d)) +tot_mism = len(det_defects) + +# ---------- (4) identity consistency ---------- +idcat = Counter() +for r in v6: + for k, _ in L.lint_row(r): idcat[k] += 1 + +print("=" * 72) +print("V6 DETERMINISTIC FREE-RUNNING CORRECTNESS (episodes: %d)" % len(episodes)) +print("=" * 72) +print("\n(1) RECONSTRUCTION INVARIANT (dropped/mangled variable vs source n100)") +print(f" episodes reconstructed : {len(episodes)}") +print(f" diverging from source : {len(recon_diff)} {recon_diff[:5]}") +print("\n(2) EXECUTABLE REPLAY (variable-before-exists / invalid-arg / wrong-output)") +det_ok = tot_match + len(nondet_money) +print(f" deterministic outputs reproduced : {det_ok}/{tot_chk} = {det_ok/max(tot_chk,1):.1%}") +print(f" genuine deterministic defects : {tot_mism} (exceptions: {tot_exc}, skip-no-seed: {tot_skip})") +print(f" non-validated confuser compound-money fields (by design): {len(nondet_money)}") +print(f" uncovered (echo/fictional-tool) calls: {sum(uncovered.values())}") +print("\n(3) WHOLE-EPISODE GROUNDING (id consumed before produced / never returned)") +print(f" ungrounded HIGH-id consumptions: {len(grounding_defects)}") +for d in grounding_defects[:15]: + print(f" {d['episode']} call[{d['call']}] {d['tool']} {d['key']}={d['id']}") +print("\n(4) IDENTITY CONSISTENCY (name/zip/verification across conversation)") +print(f" auth-lint residual flags: {dict(idcat) or 'NONE -- clean'}") +if tot_exc: + print("\n EXCEPTIONS:") + for n, st in sorted(stats.items()): + for oe, m in st["exc"][:5]: print(f" [{n}] {oe}: {m}") +if det_defects: + print("\n GENUINE DETERMINISTIC DEFECTS (should be 0):") + for n, oe, d in det_defects: + print(f" [{n}] {oe}: {d}") +else: + print("\n GENUINE DETERMINISTIC DEFECTS: NONE") +if nondet_money: + print("\n NON-VALIDATED CONFUSER COMPOUND-MONEY FIELDS (self-consistent, under-determined):") + for n, oe, d in nondet_money: + print(f" [{n}] {oe}: {d}") diff --git a/tempscripts/story_remediation/unbundle/visualize_v3.py b/tempscripts/story_remediation/unbundle/visualize_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..266224b6f457ff7baa50f381bf816d3dada1e2f9 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/visualize_v3.py @@ -0,0 +1,121 @@ +"""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() diff --git a/tempscripts/story_remediation/unbundle/visualize_v5.py b/tempscripts/story_remediation/unbundle/visualize_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..146a583c2ee821e83ef2698be1b9f4938fc3c649 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/visualize_v5.py @@ -0,0 +1,122 @@ +"""Render the NEW (unbundled v5) 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_v5.txt, trie_v5.svg, trie_v5.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" +V5 = HERE / "out" / "trajectories_all_v5.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(V5) + 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 v5)") + 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 (v5) — 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_v5.txt").write_text("\n".join(header + new_lines), encoding="utf-8") + print(f"\ntext tree -> {(HERE/'trie_v5.txt').relative_to(ROOT)} ({len(new_lines)} lines)") + + png = _render_image(new_trie.root, classify, HERE / "trie_v5", 1, "png") + svg = _render_image(new_trie.root, classify, HERE / "trie_v5", 1, "svg") + if png: + print(f"PNG -> {png}") + if svg: + print(f"SVG -> {svg}") + + +if __name__ == "__main__": + main() + diff --git a/tempscripts/story_remediation/unbundle/visualize_v6_levels.py b/tempscripts/story_remediation/unbundle/visualize_v6_levels.py new file mode 100644 index 0000000000000000000000000000000000000000..b19b63c30690fe33cfe821c66a9f6888ecd038d9 --- /dev/null +++ b/tempscripts/story_remediation/unbundle/visualize_v6_levels.py @@ -0,0 +1,99 @@ +"""Render v6 confuser trie images for the n50 and n20 counterpart datasets. + +Reuses the canonical renderer (distractor_generation_2/visualize.py) exactly like +visualize_v5.py, but over the v6 level subsets. Calls are byte-identical to v5, so the +n100 trie is unchanged (see trie_v5.*); these are the matching sub-tries for n50 / n20. + +Outputs (into this folder): trie_v6_n50.{txt,svg,png}, trie_v6_n20.{txt,svg,png} +Run: python -u temp/story_remediation/unbundle/visualize_v6_levels.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_names, _text_tree, _render_image) + +N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" +REAL_APIS = ROOT / "data" / "tau-2" / "processed" / "apis.jsonl" +OUT = HERE / "out" +LEVELS = {"n50": OUT / "trajectories_all_v6_n50.jsonl", + "n20": OUT / "trajectories_all_v6_n20.jsonl"} + + +def seqs_from(path: Path): + out = [] + for line in path.read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + s = [c["name"] for c in json.loads(line).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, _ = _text_tree(trie.root, classify, 1) + 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=len(trie.root.children), 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 "?" + + for level, path in LEVELS.items(): + seqs = seqs_from(path) + trie = build(seqs) + st, lines = stats(trie, classify) + stem = HERE / f"trie_v6_{level}" + header = [ + f"v6 UNBUNDLED CONFUSER TRIE ({level}) — subset of the finalized v6 dataset", + "=" * 72, + f"rows: {len(seqs)} nodes: {st['nodes']} max depth: {st['max_depth']} " + f"root branches: {st['root_branch']} mean leaf depth: {st['mean_leaf_depth']:.2f}", + "Legend: [real] BLUE = real prefix the confuser anchors to; " + "[confuser] ORANGE = retail look-alike (the divergence node F).", + "=" * 72, "", + ] + stem.with_suffix(".txt").write_text("\n".join(header + lines), encoding="utf-8") + png = _render_image(trie.root, classify, stem, 1, "png") + svg = _render_image(trie.root, classify, stem, 1, "svg") + print(f"{level}: rows={len(seqs)} nodes={st['nodes']} max_depth={st['max_depth']} " + f"root_branch={st['root_branch']} mean_leaf_depth={st['mean_leaf_depth']:.2f}") + print(f" txt -> {stem.with_suffix('.txt').name} png -> {png} svg -> {svg}") + + +if __name__ == "__main__": + main() diff --git a/tempscripts/story_remediation/validate_literals.py b/tempscripts/story_remediation/validate_literals.py new file mode 100644 index 0000000000000000000000000000000000000000..53c4ee10d5ada149733c85028712cea386326c23 --- /dev/null +++ b/tempscripts/story_remediation/validate_literals.py @@ -0,0 +1,54 @@ +"""Safety net: verify every DB literal in a caught row's ORIGINAL query still +appears in PROPOSALS.md. Order #s / gift-card IDs / item numbers are unique per +row, so whole-file presence effectively proves per-row preservation. Flags drops. + +Usage: python temp/story_remediation/validate_literals.py +""" +import json, re +from pathlib import Path + +HERE = Path(__file__).resolve().parent +OUT = HERE / "out" + +done = {l.strip() for l in (OUT / "done_ids.txt").read_text(encoding="utf-8").splitlines() if l.strip()} +rows = {json.loads(l)["item_id"]: json.loads(l) + for l in (OUT / "caught_rows.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()} +md = (HERE / "PROPOSALS.md").read_text(encoding="utf-8") + +PATS = { + "order": r"#W\d+", + "giftcard": r"gift_card_\d+", + "email": r"[\w.\-]+@[\w.\-]+", + "phone": r"\+1-\d{3}-\d{3}-\d{4}", + "itemnum": r"\b\d{7,}\b", + "quote": r"'[^']{3,}'", + "money": r"\$\d+", + "zip": r"\b\d{5}\b", + "promo": r"\b[A-Z]{3,}\d{1,3}\b", +} + + +def literals(text): + out = set() + for _, p in PATS.items(): + for m in re.findall(p, text): + out.add(m) + return out + + +problems = 0 +checked = 0 +for iid in done: + r = rows.get(iid) + if not r: + continue + checked += 1 + src = r["query"] + " " + " ".join(h["content"] for h in r["history"]) + for lit in literals(r["query"]): + # ignore bare 5-digit ZIPs that are substrings of order numbers etc. + if lit not in md: + print(f"MISSING literal {lit!r} for {iid}") + problems += 1 + +print(f"\nchecked {checked} done rows | missing literals: {problems}") +print("OK - all literals preserved" if problems == 0 else "REVIEW NEEDED")