temp build/analysis scripts (54 py files) backup before prune
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tempscripts/injection_sandbox/analyze_c3_reasons.py +77 -0
- tempscripts/injection_sandbox/gen_merged.py +493 -0
- tempscripts/injection_sandbox/run_c3.py +109 -0
- tempscripts/injection_sandbox/run_c3_big.py +141 -0
- tempscripts/injection_sandbox/validate.py +187 -0
- tempscripts/injection_sandbox/verify_trie.py +19 -0
- tempscripts/injection_sandbox/viz_trie.py +124 -0
- tempscripts/story_remediation/add_turns/build_v2.py +199 -0
- tempscripts/story_remediation/add_turns/replay_v2.py +151 -0
- tempscripts/story_remediation/add_turns/run_c3_v2.py +109 -0
- tempscripts/story_remediation/analyze_caught.py +107 -0
- tempscripts/story_remediation/build_join.py +119 -0
- tempscripts/story_remediation/build_remediated.py +141 -0
- tempscripts/story_remediation/next_batch.py +29 -0
- tempscripts/story_remediation/replay_remediated.py +149 -0
- tempscripts/story_remediation/run_c3_remediated.py +108 -0
- tempscripts/story_remediation/unbundle/ab_capability_reasons.py +137 -0
- tempscripts/story_remediation/unbundle/ab_prompt_v2.py +126 -0
- tempscripts/story_remediation/unbundle/analyze_all.py +137 -0
- tempscripts/story_remediation/unbundle/analyze_all_v2.py +137 -0
- tempscripts/story_remediation/unbundle/analyze_all_v3.py +137 -0
- tempscripts/story_remediation/unbundle/analyze_all_v4.py +138 -0
- tempscripts/story_remediation/unbundle/analyze_all_v5.py +139 -0
- tempscripts/story_remediation/unbundle/auth_lint_v5.py +301 -0
- tempscripts/story_remediation/unbundle/author_q1_fix_v3.py +110 -0
- tempscripts/story_remediation/unbundle/author_splits.py +185 -0
- tempscripts/story_remediation/unbundle/author_splits_v2.py +185 -0
- tempscripts/story_remediation/unbundle/author_splits_v4.py +192 -0
- tempscripts/story_remediation/unbundle/build_all.py +139 -0
- tempscripts/story_remediation/unbundle/build_all_v2.py +116 -0
- tempscripts/story_remediation/unbundle/build_all_v3.py +204 -0
- tempscripts/story_remediation/unbundle/build_all_v4.py +243 -0
- tempscripts/story_remediation/unbundle/build_all_v5.py +323 -0
- tempscripts/story_remediation/unbundle/build_all_v6.py +187 -0
- tempscripts/story_remediation/unbundle/build_v3.py +141 -0
- tempscripts/story_remediation/unbundle/diagnose_caught_v5.py +181 -0
- tempscripts/story_remediation/unbundle/diagnose_tail.py +79 -0
- tempscripts/story_remediation/unbundle/diagnose_tail_v4.py +80 -0
- tempscripts/story_remediation/unbundle/dump_c3_view.py +31 -0
- tempscripts/story_remediation/unbundle/fix_error_records.py +64 -0
- tempscripts/story_remediation/unbundle/replay_v5.py +186 -0
- tempscripts/story_remediation/unbundle/run_auth_c1c3.py +142 -0
- tempscripts/story_remediation/unbundle/run_c3_all.py +102 -0
- tempscripts/story_remediation/unbundle/run_c3_all_v2.py +102 -0
- tempscripts/story_remediation/unbundle/run_c3_all_v3.py +102 -0
- tempscripts/story_remediation/unbundle/run_c3_all_v4.py +94 -0
- tempscripts/story_remediation/unbundle/run_c3_all_v5.py +94 -0
- tempscripts/story_remediation/unbundle/run_c3_v3.py +109 -0
- tempscripts/story_remediation/unbundle/run_final_c1c3.py +64 -0
- tempscripts/story_remediation/unbundle/run_freecheck_v6.py +273 -0
tempscripts/injection_sandbox/analyze_c3_reasons.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SANDBOX C3 error analysis: for each of the 51 humanized injected rows, capture
|
| 2 |
+
the judge's REASONING (not just the guess), and line it up against the baseline
|
| 3 |
+
reasoning for that SAME host row (from datasetreview/results/new/C3.jsonl). Lets
|
| 4 |
+
us read, per example, WHY the host was caught and whether humanization addressed
|
| 5 |
+
that specific tell. One judgment per row (fake in A), reasoning captured.
|
| 6 |
+
|
| 7 |
+
Run from repo root: python -u temp/injection_sandbox/analyze_c3_reasons.py
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import logging
|
| 13 |
+
import sys
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import yaml
|
| 18 |
+
|
| 19 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 20 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 21 |
+
|
| 22 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 25 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 26 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 27 |
+
|
| 28 |
+
SAND = Path(__file__).resolve().parent
|
| 29 |
+
OUT = SAND / "out"
|
| 30 |
+
MERGED = OUT / "_staging_merged_injections.jsonl"
|
| 31 |
+
PROV = {p["example_id"]: p for p in json.load(open(OUT / "_merged_injections.prov.json", encoding="utf-8"))}
|
| 32 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 33 |
+
|
| 34 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 35 |
+
reals = P.real_trajectories()
|
| 36 |
+
pairer = P.make_pairer(reals)
|
| 37 |
+
judge = make_judge(cfg["model"])
|
| 38 |
+
injected = [json.loads(l) for l in open(MERGED, encoding="utf-8") if l.strip()]
|
| 39 |
+
|
| 40 |
+
base = {}
|
| 41 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 42 |
+
if line.strip():
|
| 43 |
+
d = json.loads(line)
|
| 44 |
+
base[d.get("item_id")] = {"caught": d.get("caught"),
|
| 45 |
+
"reason": ((d.get("result") or {}).get("reasoning") or "")}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def judge_one(fake):
|
| 49 |
+
eid = fake["example_id"]
|
| 50 |
+
real = pairer(fake)
|
| 51 |
+
msgs = J.build_c3(fake, real, swap=False) # fake is A
|
| 52 |
+
try:
|
| 53 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 54 |
+
except Exception as e: # noqa: BLE001
|
| 55 |
+
return {"example_id": eid, "error": str(e)}
|
| 56 |
+
return {"example_id": eid, "host_of": PROV[eid]["host_of"], "node": PROV[eid]["rebalance_node"],
|
| 57 |
+
"confuser": PROV[eid]["confuser"], "guess": r.get("guess"),
|
| 58 |
+
"caught": r.get("guess") == "A", "confidence": r.get("confidence"),
|
| 59 |
+
"reason": r.get("reasoning") or ""}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def main():
|
| 63 |
+
with ThreadPoolExecutor(max_workers=cfg["run"].get("workers", 4)) as ex:
|
| 64 |
+
res = list(ex.map(judge_one, injected))
|
| 65 |
+
res.sort(key=lambda r: r["example_id"])
|
| 66 |
+
for r in res:
|
| 67 |
+
r["host_baseline_caught"] = base.get(r.get("host_of"), {}).get("caught")
|
| 68 |
+
r["host_baseline_reason"] = base.get(r.get("host_of"), {}).get("reason", "")
|
| 69 |
+
(OUT / "c3_reasons.jsonl").write_text("\n".join(json.dumps(r) for r in res) + "\n", encoding="utf-8")
|
| 70 |
+
caught = sum(1 for r in res if r.get("caught"))
|
| 71 |
+
print(f"judged {len(res)} injected rows (orientation A, 1 sample). caught={caught}/{len(res)}")
|
| 72 |
+
print("wrote out/c3_reasons.jsonl")
|
| 73 |
+
return 0
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
raise SystemExit(main())
|
tempscripts/injection_sandbox/gen_merged.py
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SANDBOX generator: splice each of the 51 trie-fill injections into its
|
| 2 |
+
assigned host conversation as a LATER turn (the injected row's history embeds the
|
| 3 |
+
host's own prior tool turn, grounded to the host's customer). Non-destructive:
|
| 4 |
+
host rows are NOT edited; we only ADD injected rows. Everything writes under
|
| 5 |
+
temp/injection_sandbox/out. Reuses the proven grounded call assembly + replay
|
| 6 |
+
verification from scripts/_gen_injections2.py.
|
| 7 |
+
|
| 8 |
+
Run: python -u temp/injection_sandbox/gen_merged.py
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import random
|
| 14 |
+
import re
|
| 15 |
+
import sys
|
| 16 |
+
from collections import Counter
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 20 |
+
SAND = Path(__file__).resolve().parent
|
| 21 |
+
sys.path.insert(0, str(ROOT))
|
| 22 |
+
sys.path.insert(0, str(ROOT / "systemUpgrade" / "executor"))
|
| 23 |
+
|
| 24 |
+
import scripts._gen_injections2 as G # noqa: E402
|
| 25 |
+
from fake_state import EpisodeState # noqa: E402
|
| 26 |
+
from fake_tools import TOOLS # noqa: E402
|
| 27 |
+
|
| 28 |
+
DATA = SAND / "data"
|
| 29 |
+
OUT = SAND / "out"
|
| 30 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 31 |
+
|
| 32 |
+
# use the SANDBOX (clonable) free-running catalog for all grounding/replay
|
| 33 |
+
CATALOG = json.load(open(DATA / "catalog.json", encoding="utf-8"))
|
| 34 |
+
G.CATALOG = CATALOG
|
| 35 |
+
RND = random.Random(1234)
|
| 36 |
+
|
| 37 |
+
def hq_variant(leaf, on):
|
| 38 |
+
"""Humanized LATER-turn query. The customer is already authenticated in the
|
| 39 |
+
host turn, so a real person would NOT restate email / name / ZIP or say
|
| 40 |
+
'look me up'. Phrase as a natural follow-up; keep the order-number literal
|
| 41 |
+
(retrieval signal); no em dashes."""
|
| 42 |
+
V = {
|
| 43 |
+
"schedule_delivery": [
|
| 44 |
+
f"Also, could you set delivery for {on} to next Tuesday?",
|
| 45 |
+
f"One more thing, can we schedule {on} to arrive on the 14th?",
|
| 46 |
+
f"While you're in there, I'd like {on} delivered next Tuesday if that works.",
|
| 47 |
+
],
|
| 48 |
+
"request_gift_receipt": [
|
| 49 |
+
f"Oh, and could I get a gift receipt for {on}? It's a present.",
|
| 50 |
+
f"Also, {on} is a gift, so a gift receipt would be great.",
|
| 51 |
+
f"Could you include a gift receipt with {on}? It's for my sister.",
|
| 52 |
+
],
|
| 53 |
+
"get_wishlist": [
|
| 54 |
+
"Also, can you remind me what's still on my wishlist?",
|
| 55 |
+
"While I've got you, what did I have saved on my wishlist again?",
|
| 56 |
+
"Oh, and what's left on my wishlist? I keep forgetting.",
|
| 57 |
+
],
|
| 58 |
+
"get_order_invoice": [
|
| 59 |
+
f"Could you also send me the invoice for {on}? I need it for expenses.",
|
| 60 |
+
f"One more thing, can I get the itemized invoice for {on}?",
|
| 61 |
+
f"Also, I need the invoice for {on} for my records.",
|
| 62 |
+
],
|
| 63 |
+
"redeem_loyalty_points": [
|
| 64 |
+
"Also, I'd like to cash in some of my loyalty points for credit.",
|
| 65 |
+
"While we're at it, can I redeem a few hundred points?",
|
| 66 |
+
"Oh, and can I put some loyalty points toward store credit?",
|
| 67 |
+
],
|
| 68 |
+
"reorder_previous_order": [
|
| 69 |
+
f"Also, could you just reorder everything from {on}? Same as before.",
|
| 70 |
+
f"One more thing, can we duplicate order {on}? I loved that batch.",
|
| 71 |
+
f"While you're in there, could you reorder {on} for me?",
|
| 72 |
+
],
|
| 73 |
+
"apply_gift_card": [
|
| 74 |
+
f"Also, I've got a gift card I'd like to put toward {on}.",
|
| 75 |
+
f"Oh, can we apply my gift card to {on}?",
|
| 76 |
+
f"While we're at it, please use my gift card on {on}.",
|
| 77 |
+
],
|
| 78 |
+
"get_shipping_options": [
|
| 79 |
+
f"Also, what are the shipping options for {on}?",
|
| 80 |
+
f"One more thing, what delivery choices do I have for {on}?",
|
| 81 |
+
f"While you're there, can you tell me the shipping options on {on}?",
|
| 82 |
+
],
|
| 83 |
+
"subscribe_to_restock_alert": [
|
| 84 |
+
f"Could you swap the out-of-stock item on {on}, and let me know when the original is back?",
|
| 85 |
+
f"Please change that item on {on}, and sign me up for a restock alert on the old one.",
|
| 86 |
+
f"Can we modify {on} to swap that item, and ping me when it restocks?",
|
| 87 |
+
],
|
| 88 |
+
"file_shipping_insurance_claim": [
|
| 89 |
+
f"Also, {on} arrived damaged, can I file an insurance claim on it?",
|
| 90 |
+
f"One more thing, I need to file a shipping insurance claim for {on}. It came banged up.",
|
| 91 |
+
],
|
| 92 |
+
"request_price_match": [
|
| 93 |
+
f"Also, I saw an item from {on} cheaper elsewhere, can you price match it?",
|
| 94 |
+
f"One more thing, can you price match something on {on}? Found it for less online.",
|
| 95 |
+
],
|
| 96 |
+
"get_store_credit_balance": [
|
| 97 |
+
"Also, what's my store credit balance right now?",
|
| 98 |
+
"Oh, and how much store credit do I have left?",
|
| 99 |
+
],
|
| 100 |
+
"set_delivery_instructions": [
|
| 101 |
+
f"Also, can you add a note to leave {on} with the doorman?",
|
| 102 |
+
f"One more thing, please have {on} left with the front desk.",
|
| 103 |
+
],
|
| 104 |
+
"upgrade_shipping_speed": [
|
| 105 |
+
f"Also, can you bump {on} to express if it hasn't shipped yet?",
|
| 106 |
+
f"One more thing, could you upgrade {on} to overnight?",
|
| 107 |
+
],
|
| 108 |
+
}
|
| 109 |
+
return RND.choice(V[leaf])
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
CONFIRM = [
|
| 113 |
+
"All set, anything else I can help with?",
|
| 114 |
+
"Done. Let me know if you need more.",
|
| 115 |
+
"Taken care of. What else can I do?",
|
| 116 |
+
"That's handled. Anything further?",
|
| 117 |
+
]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def parse(o):
|
| 121 |
+
try:
|
| 122 |
+
return json.loads(o) if isinstance(o, str) and o.strip().startswith("{") else None
|
| 123 |
+
except json.JSONDecodeError:
|
| 124 |
+
return None
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def host_customer(host, a):
|
| 128 |
+
"""Reconstruct the host's customer + order dicts, backed by the assignment."""
|
| 129 |
+
ods = {}
|
| 130 |
+
ud = None
|
| 131 |
+
for c in host["calls"]:
|
| 132 |
+
o = parse(c.get("output"))
|
| 133 |
+
if c["name"] == "get_user_details" and o and o.get("user_id"):
|
| 134 |
+
ud = o
|
| 135 |
+
if c["name"] == "get_order_details" and o and o.get("order_id"):
|
| 136 |
+
ods[o["order_id"]] = o
|
| 137 |
+
user_details = {
|
| 138 |
+
"user_id": a["uid"], "email": a["email"],
|
| 139 |
+
"name": a.get("name") or (ud or {}).get("name") or {"first_name": "Alex", "last_name": "Kim"},
|
| 140 |
+
"address": (ud or {}).get("address") or {"zip": a.get("zip", "10001")},
|
| 141 |
+
"orders": list(ods),
|
| 142 |
+
}
|
| 143 |
+
return {"uid": a["uid"], "email": a["email"], "user_details": user_details, "orders": ods}
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
OPEN_LEAVES = {"schedule_delivery", "set_delivery_instructions", "get_shipping_options",
|
| 147 |
+
"upgrade_shipping_speed", "modify_pending_order_items"}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def order_ids_for(a, u):
|
| 151 |
+
need = a["prefix"].count("get_order_details")
|
| 152 |
+
if a["node"] == "N4" and a.get("n4_orders"):
|
| 153 |
+
ids = [o for o in a["n4_orders"] if o in u["orders"]] or list(u["orders"])
|
| 154 |
+
elif a.get("grounded_order") and a["grounded_order"] in u["orders"]:
|
| 155 |
+
ids = [a["grounded_order"]] + [o for o in u["orders"] if o != a["grounded_order"]]
|
| 156 |
+
else:
|
| 157 |
+
ids = list(u["orders"])
|
| 158 |
+
# For open-required ops, ground on the most-open order the host actually has:
|
| 159 |
+
# pending/processing first, then shipped (still pre-delivery), then delivered.
|
| 160 |
+
if a["node"] != "N4" and (a["leaf"] in OPEN_LEAVES or any(t in OPEN_LEAVES for t in a["prefix"])):
|
| 161 |
+
def rank(oid):
|
| 162 |
+
st = str((u["orders"].get(oid) or {}).get("status", "")).lower()
|
| 163 |
+
if st in ("pending", "processing", "open", "pending (modified)"):
|
| 164 |
+
return 0
|
| 165 |
+
return 1 if st == "shipped" else 2
|
| 166 |
+
ids = sorted(ids, key=rank)
|
| 167 |
+
if not ids:
|
| 168 |
+
ids = ["#W0000000"]
|
| 169 |
+
while len(ids) < max(1, need):
|
| 170 |
+
ids.append(ids[0])
|
| 171 |
+
return ids
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# ---- embedded-host humanization (copy-only; canonical host rows untouched) ----
|
| 175 |
+
# Targets the two dominant C3 tells in host turns while preserving EVERY DB
|
| 176 |
+
# literal (order #, item id, price, quoted gift message, date, email, ZIP):
|
| 177 |
+
# T1 scripted meta preamble ("Review my recent orders, then ...")
|
| 178 |
+
# T2 trailing auth boilerplate ("... Name is X, ZIP 12345.") when that same
|
| 179 |
+
# name/ZIP/email already appears earlier in the conversation (pure dedupe)
|
| 180 |
+
# T3 assistant em/hyphen dashes ("Sure - let me ...") -> comma
|
| 181 |
+
_PREAMBLE = [
|
| 182 |
+
re.compile(r"^\s*review my [\w ]{0,32}orders,\s*then\s+", re.I),
|
| 183 |
+
re.compile(r"^\s*review my [\w ]{0,32}orders and\s+", re.I),
|
| 184 |
+
re.compile(r"^\s*review my [\w ]{0,32}orders:\s*", re.I),
|
| 185 |
+
re.compile(r"^\s*look at my [\w ]{0,32}orders:\s+", re.I),
|
| 186 |
+
re.compile(r"^\s*can you look over my [\w ]{0,32}orders\?\s+", re.I),
|
| 187 |
+
re.compile(r"^\s*across (?:my )?[\w ]{0,32}orders:\s+", re.I),
|
| 188 |
+
]
|
| 189 |
+
_TRAIL_NAMEZIP = re.compile(
|
| 190 |
+
r"\s*(?:my name is|name is)\s+([A-Za-z]+(?:\s+[A-Za-z]+)?),?\s*"
|
| 191 |
+
r"(?:and\s+(?:my\s+)?)?zip(?:\s+is|\s+code\s+is|:)?\s*(\d{5})\.?\s*$", re.I)
|
| 192 |
+
_TRAIL_EMAIL = re.compile(r"\s*my email is\s+([^\s,]+@[^\s,]+?)\.?\s*$", re.I)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _cap(s):
|
| 196 |
+
return s[:1].upper() + s[1:] if s else s
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def humanize_host_query(q, history_text):
|
| 200 |
+
for pat in _PREAMBLE:
|
| 201 |
+
m = pat.match(q)
|
| 202 |
+
if m:
|
| 203 |
+
q = _cap(q[m.end():].lstrip())
|
| 204 |
+
break
|
| 205 |
+
m = _TRAIL_NAMEZIP.search(q)
|
| 206 |
+
if m and (m.group(1) in history_text and m.group(2) in history_text):
|
| 207 |
+
q = q[:m.start()].rstrip()
|
| 208 |
+
if q and q[-1] not in ".!?":
|
| 209 |
+
q += "."
|
| 210 |
+
m = _TRAIL_EMAIL.search(q)
|
| 211 |
+
if m and m.group(1) in history_text:
|
| 212 |
+
q = q[:m.start()].rstrip()
|
| 213 |
+
if q and q[-1] not in ".!?":
|
| 214 |
+
q += "."
|
| 215 |
+
return q
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _dedash(s):
|
| 219 |
+
if not s:
|
| 220 |
+
return s
|
| 221 |
+
return re.sub(r"\s+[-\u2013\u2014]\s+", ", ", s)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def embed_host_turn(host):
|
| 225 |
+
"""host history (small talk) + the host's own request rendered as a prior
|
| 226 |
+
tool turn (confuser-style encoding) + a confirmation. The embedded copy is
|
| 227 |
+
lightly humanized (preamble/auth-dedupe/dash cleanup); canonical host row is
|
| 228 |
+
not modified."""
|
| 229 |
+
h = [dict(m) for m in (host.get("history") or [])]
|
| 230 |
+
for m in h: # T3: clean assistant dashes
|
| 231 |
+
if m.get("role") == "assistant" and m.get("content"):
|
| 232 |
+
m["content"] = _dedash(m["content"])
|
| 233 |
+
history_text = " ".join((m.get("content") or "") for m in h)
|
| 234 |
+
q = (host.get("query") or host.get("retrieval_text") or "").strip()
|
| 235 |
+
q = humanize_host_query(q, history_text) # T1 + T2
|
| 236 |
+
h.append({"role": "user", "content": q, "tool_calls": [], "tool_call_id": None})
|
| 237 |
+
tcs = [{"name": c["name"], "arguments": c.get("arguments", {}),
|
| 238 |
+
"output": c.get("output"), "reasoning": c.get("reasoning", "")}
|
| 239 |
+
for c in host["calls"]]
|
| 240 |
+
h.append({"role": "assistant", "content": None, "tool_calls": tcs, "tool_call_id": None})
|
| 241 |
+
for c in host["calls"]:
|
| 242 |
+
h.append({"role": "tool", "content": c.get("output"), "tool_calls": [], "tool_call_id": None})
|
| 243 |
+
h.append({"role": "assistant", "content": _dedash(RND.choice(CONFIRM)), "tool_calls": [], "tool_call_id": None})
|
| 244 |
+
return h
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def history_tool_calls(host):
|
| 248 |
+
"""Tool calls embedded in the host's own history (auth/reads retained earlier)."""
|
| 249 |
+
out = []
|
| 250 |
+
for m in (host.get("history") or []):
|
| 251 |
+
for tc in (m.get("tool_calls") or []):
|
| 252 |
+
out.append({"name": tc.get("name"), "arguments": tc.get("arguments", {}),
|
| 253 |
+
"output": tc.get("output")})
|
| 254 |
+
return out
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
# ------------------------------------------------ leaf/host value reconciliation
|
| 258 |
+
def reconcile_leaf_with_host(calls, host):
|
| 259 |
+
"""If the injected leaf reads an entity the host turn already established, copy
|
| 260 |
+
the host's recorded output verbatim so the same customer yields the same value
|
| 261 |
+
at the conversation level (and the row still reproduces in isolation)."""
|
| 262 |
+
leaf = calls[-1]
|
| 263 |
+
n = leaf["name"]
|
| 264 |
+
SELF = {"get_order_invoice", "get_shipping_options", "get_wishlist", "get_store_credit_balance"}
|
| 265 |
+
if n not in SELF:
|
| 266 |
+
return calls, None
|
| 267 |
+
a = leaf.get("arguments", {})
|
| 268 |
+
ent = ("#" + str(a["order_id"]).lstrip("#").upper()) if a.get("order_id") else a.get("user_id")
|
| 269 |
+
|
| 270 |
+
def _ent(c):
|
| 271 |
+
aa = c.get("arguments", {})
|
| 272 |
+
return ("#" + str(aa["order_id"]).lstrip("#").upper()) if aa.get("order_id") else aa.get("user_id")
|
| 273 |
+
for hc in host["calls"]:
|
| 274 |
+
if hc["name"] == n and _ent(hc) == ent and hc.get("output") is not None:
|
| 275 |
+
leaf["output"] = hc["output"]
|
| 276 |
+
return calls, (n, ent)
|
| 277 |
+
return calls, None
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
# ------------------------------------------------ conversation-level state check
|
| 281 |
+
def _ref_ids(call):
|
| 282 |
+
a = call.get("arguments", {}) or {}
|
| 283 |
+
out = {}
|
| 284 |
+
for k in ("user_id", "order_id", "gift_card_id"):
|
| 285 |
+
if a.get(k):
|
| 286 |
+
out[k] = a[k]
|
| 287 |
+
for k in ("item_id",):
|
| 288 |
+
if a.get(k):
|
| 289 |
+
out.setdefault("item_ids", []).append(a[k])
|
| 290 |
+
for k in ("item_ids", "new_item_ids"):
|
| 291 |
+
for v in (a.get(k) or []):
|
| 292 |
+
out.setdefault("item_ids", []).append(v)
|
| 293 |
+
return out
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _establish(call, users, orders, items, cards):
|
| 297 |
+
n = call["name"]
|
| 298 |
+
raw = call.get("output")
|
| 299 |
+
o = parse(raw)
|
| 300 |
+
if n.startswith("find_user_id"):
|
| 301 |
+
uid = raw.strip().strip('"') if isinstance(raw, str) else None
|
| 302 |
+
if uid and "_" in uid:
|
| 303 |
+
users.add(uid)
|
| 304 |
+
elif n == "get_user_details" and o:
|
| 305 |
+
if o.get("user_id"):
|
| 306 |
+
users.add(o["user_id"])
|
| 307 |
+
for oid in (o.get("orders") or []):
|
| 308 |
+
orders.add("#" + str(oid).lstrip("#").upper())
|
| 309 |
+
elif n == "get_order_details" and o:
|
| 310 |
+
if o.get("order_id"):
|
| 311 |
+
orders.add("#" + str(o["order_id"]).lstrip("#").upper())
|
| 312 |
+
for it in (o.get("items") or []):
|
| 313 |
+
if it.get("item_id"):
|
| 314 |
+
items.add(str(it["item_id"]))
|
| 315 |
+
elif n == "get_gift_card_balance" and o and o.get("gift_card_id"):
|
| 316 |
+
cards.add(str(o["gift_card_id"]))
|
| 317 |
+
elif n == "get_wishlist" and o:
|
| 318 |
+
for it in (o.get("items") or []):
|
| 319 |
+
if isinstance(it, dict) and it.get("item_id"):
|
| 320 |
+
items.add(str(it["item_id"]))
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def conversation_state_check(seq_calls, catalog, hist_calls=()):
|
| 324 |
+
"""Temporal grounding (no forward/unmarked refs) + output reproduction over the
|
| 325 |
+
whole merged conversation. ``hist_calls`` are tool calls from the host's history
|
| 326 |
+
(auth retained earlier), which pre-establish entities. Returns (forward_refs,
|
| 327 |
+
io_mismatches)."""
|
| 328 |
+
cat_orders = {"#" + str(o).lstrip("#").upper() for o in catalog.get("order_balances", {})}
|
| 329 |
+
cat_cards = {str(c) for c in catalog.get("gift_card_balances", {})}
|
| 330 |
+
users, orders, items, cards = set(), set(cat_orders), set(), set(cat_cards)
|
| 331 |
+
for hc in hist_calls: # entities established in host history
|
| 332 |
+
_establish(hc, users, orders, items, cards)
|
| 333 |
+
fwd = []
|
| 334 |
+
for i, c in enumerate(seq_calls):
|
| 335 |
+
refs = _ref_ids(c)
|
| 336 |
+
# user_id must be established, unless this call itself establishes it
|
| 337 |
+
# (find_user_id_* mints it; get_user_details is the auth-retained read).
|
| 338 |
+
if (refs.get("user_id") and refs["user_id"] not in users
|
| 339 |
+
and not c["name"].startswith("find_user_id")
|
| 340 |
+
and c["name"] != "get_user_details"):
|
| 341 |
+
fwd.append((i, c["name"], "user_id", refs["user_id"]))
|
| 342 |
+
if refs.get("order_id"):
|
| 343 |
+
oid = "#" + str(refs["order_id"]).lstrip("#").upper()
|
| 344 |
+
if oid not in orders and c["name"] != "get_order_details":
|
| 345 |
+
fwd.append((i, c["name"], "order_id", refs["order_id"]))
|
| 346 |
+
if refs.get("gift_card_id") and str(refs["gift_card_id"]) not in cards:
|
| 347 |
+
fwd.append((i, c["name"], "gift_card_id", refs["gift_card_id"]))
|
| 348 |
+
_establish(c, users, orders, items, cards)
|
| 349 |
+
# I/O reproduction over the merged sequence (progressive seed)
|
| 350 |
+
s = EpisodeState.from_trajectory({"calls": seq_calls}, catalog)
|
| 351 |
+
io = []
|
| 352 |
+
for c in seq_calls:
|
| 353 |
+
n = c["name"]
|
| 354 |
+
if n not in TOOLS:
|
| 355 |
+
continue
|
| 356 |
+
got = TOOLS[n](s, c.get("arguments", {}))
|
| 357 |
+
rec = parse(c.get("output"))
|
| 358 |
+
if n in G.FIND:
|
| 359 |
+
exp = (c.get("output") or "").strip().strip('"')
|
| 360 |
+
if got != exp:
|
| 361 |
+
io.append((n, "uid", got, exp))
|
| 362 |
+
continue
|
| 363 |
+
if not isinstance(rec, dict):
|
| 364 |
+
continue
|
| 365 |
+
if n in G.FULLMATCH:
|
| 366 |
+
if got != rec:
|
| 367 |
+
io.append((n, "dict-diff"))
|
| 368 |
+
continue
|
| 369 |
+
keys = G.CHECK.get(n, [])
|
| 370 |
+
if any(got.get(k) is None and rec.get(k) is not None for k in keys):
|
| 371 |
+
continue
|
| 372 |
+
|
| 373 |
+
def _eq(k):
|
| 374 |
+
g, rv = got.get(k), rec.get(k)
|
| 375 |
+
if k == "status" and isinstance(g, str) and isinstance(rv, str):
|
| 376 |
+
return g.replace(" ", "_") == rv.replace(" ", "_")
|
| 377 |
+
return g == rv
|
| 378 |
+
miss = [k for k in keys if not _eq(k)]
|
| 379 |
+
if miss:
|
| 380 |
+
io.append((n, {k: (got.get(k), rec.get(k)) for k in miss}))
|
| 381 |
+
return fwd, io
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
# ------------------------------------------------------------------------- main
|
| 385 |
+
def main():
|
| 386 |
+
asg = json.load(open(DATA / "_host_assignment.json", encoding="utf-8"))
|
| 387 |
+
c3 = [json.loads(l) for l in open(DATA / "c3_trajectories.jsonl", encoding="utf-8") if l.strip()]
|
| 388 |
+
byid = {r["example_id"]: r for r in c3}
|
| 389 |
+
cat_orders = ["#" + o.lstrip("#").upper() for o in CATALOG.get("order_balances", {})]
|
| 390 |
+
cat_cards = list(CATALOG.get("gift_card_balances", {}))
|
| 391 |
+
|
| 392 |
+
injected, prov = [], []
|
| 393 |
+
fails, merged = [], []
|
| 394 |
+
seq = 0
|
| 395 |
+
for a in asg:
|
| 396 |
+
host = byid[a["host"]]
|
| 397 |
+
u = host_customer(host, a)
|
| 398 |
+
oids = order_ids_for(a, u)
|
| 399 |
+
cat_order = a.get("grounded_cat_order") or RND.choice(cat_orders)
|
| 400 |
+
gift_card = a.get("grounded_card") or RND.choice(cat_cards)
|
| 401 |
+
prefix_tools = a["prefix"]
|
| 402 |
+
leaf = a["leaf"]
|
| 403 |
+
calls, primary = G.assemble(prefix_tools, leaf, u, oids, cat_order, gift_card)
|
| 404 |
+
calls, reconciled = reconcile_leaf_with_host(calls, host)
|
| 405 |
+
miss = G.verify_row(calls)
|
| 406 |
+
if miss:
|
| 407 |
+
fails.append((a["host"], leaf, miss))
|
| 408 |
+
continue
|
| 409 |
+
|
| 410 |
+
hist = embed_host_turn(host)
|
| 411 |
+
n_user = sum(1 for m in hist if m["role"] == "user")
|
| 412 |
+
turn_index = n_user + 1
|
| 413 |
+
total_turns = turn_index + RND.randint(1, 3)
|
| 414 |
+
position_norm = round(turn_index / max(total_turns, 1), 4)
|
| 415 |
+
tier = ("early" if position_norm < 0.34 else "middle" if position_norm < 0.67 else "late")
|
| 416 |
+
shown = cat_order if leaf in ("reorder_previous_order", "apply_gift_card") else primary
|
| 417 |
+
query = hq_variant(leaf, shown)
|
| 418 |
+
eid = f"confuser-{leaf}-minj{seq:03d}"
|
| 419 |
+
seq += 1
|
| 420 |
+
|
| 421 |
+
row = {
|
| 422 |
+
"example_id": eid, "query": query, "retrieval_text": query,
|
| 423 |
+
"calls": calls, "history": hist, "available_apis": None, "domain": "retail",
|
| 424 |
+
"metadata": {
|
| 425 |
+
"source": "synthetic", "distractor_class": "confuser", "model": "authored",
|
| 426 |
+
"confuser": leaf, "twin": False, "twin_of": None,
|
| 427 |
+
"anchor_state": list(prefix_tools), "anchor_depth": len(prefix_tools),
|
| 428 |
+
"hotspot": False, "synthetic_query": True, "tier": tier,
|
| 429 |
+
"turn_index": turn_index, "total_turns": total_turns,
|
| 430 |
+
"position_norm": position_norm, "embed_history": True,
|
| 431 |
+
"history": hist, "real_source": "authored-synthetic",
|
| 432 |
+
},
|
| 433 |
+
}
|
| 434 |
+
injected.append(row)
|
| 435 |
+
prov.append({"example_id": eid, "rebalance_node": a["node"], "confuser": leaf,
|
| 436 |
+
"host_of": a["host"], "uid": a["uid"], "placement": "later-turn",
|
| 437 |
+
"reconciled_leaf": reconciled})
|
| 438 |
+
merged.append((eid, host["calls"] + calls, history_tool_calls(host)))
|
| 439 |
+
|
| 440 |
+
(OUT / "_staging_merged_injections.jsonl").write_text(
|
| 441 |
+
"\n".join(json.dumps(r) for r in injected) + "\n", encoding="utf-8")
|
| 442 |
+
(OUT / "_merged_injections.prov.json").write_text(json.dumps(prov, indent=2), encoding="utf-8")
|
| 443 |
+
|
| 444 |
+
print(f"assembled {len(injected)}/51 injected rows (replay-verified)")
|
| 445 |
+
if fails:
|
| 446 |
+
print(f"ASSEMBLY/REPLAY FAILURES: {len(fails)}")
|
| 447 |
+
for f in fails[:20]:
|
| 448 |
+
print(" ", f)
|
| 449 |
+
tally = Counter((p["rebalance_node"], p["confuser"]) for p in prov)
|
| 450 |
+
for k in sorted(tally):
|
| 451 |
+
print(" ", k, tally[k])
|
| 452 |
+
print(" reconciled leaves (inherited host value):",
|
| 453 |
+
sum(1 for p in prov if p.get("reconciled_leaf")))
|
| 454 |
+
|
| 455 |
+
# ---- PASS 1: find unmarked variables across every merged conversation ----
|
| 456 |
+
made_up = {}
|
| 457 |
+
for eid, seq, hist in merged:
|
| 458 |
+
fwd, _ = conversation_state_check(seq, CATALOG, hist)
|
| 459 |
+
for (_i, tool, kind, val) in fwd:
|
| 460 |
+
if kind == "order_id":
|
| 461 |
+
oid = "#" + str(val).lstrip("#").upper()
|
| 462 |
+
if oid not in CATALOG["order_balances"]:
|
| 463 |
+
# mark the host-intrinsic order in the CLONED free-running DB.
|
| 464 |
+
made_up[oid] = {"order_balances": 0.01, "reason": f"{eid}:{tool} unread order"}
|
| 465 |
+
if made_up:
|
| 466 |
+
for oid, rec in made_up.items():
|
| 467 |
+
CATALOG.setdefault("order_balances", {})[oid.lstrip("#")] = rec["order_balances"]
|
| 468 |
+
(DATA / "catalog.json").write_text(json.dumps(CATALOG, indent=1), encoding="utf-8")
|
| 469 |
+
(OUT / "_made_up_values.json").write_text(json.dumps(made_up, indent=2), encoding="utf-8")
|
| 470 |
+
|
| 471 |
+
# ---- PASS 2: confirm the conversation is now fully marked + reproduces ----
|
| 472 |
+
fwd_all, io_all = [], []
|
| 473 |
+
for eid, seq, hist in merged:
|
| 474 |
+
fwd, io = conversation_state_check(seq, CATALOG, hist)
|
| 475 |
+
for f in fwd:
|
| 476 |
+
fwd_all.append((eid,) + f)
|
| 477 |
+
for m in io:
|
| 478 |
+
io_all.append((eid,) + (m if isinstance(m, tuple) else (m,)))
|
| 479 |
+
|
| 480 |
+
print(f"\nadded {len(made_up)} made-up var(s) to the cloned free-running DB")
|
| 481 |
+
print(f"CONVERSATION STATE CHECK (final): forward/unmarked refs = {len(fwd_all)} ; "
|
| 482 |
+
f"io mismatches = {len(io_all)}")
|
| 483 |
+
for x in fwd_all[:20]:
|
| 484 |
+
print(" FWD", x)
|
| 485 |
+
for x in io_all[:20]:
|
| 486 |
+
print(" IO ", x)
|
| 487 |
+
ok = not fails and not fwd_all and not io_all
|
| 488 |
+
print("\nRESULT:", "CLEAN" if ok else "NEEDS ATTENTION")
|
| 489 |
+
return 0 if ok else 1
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
if __name__ == "__main__":
|
| 493 |
+
raise SystemExit(main())
|
tempscripts/injection_sandbox/run_c3.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SANDBOX C3 run: judge the 51 temp merged injections with the SAME procedure
|
| 2 |
+
as the baseline run (single orientation, samples=3 majority, workers=4, model
|
| 3 |
+
from datasetreview/config.yaml). Compares the injected caught-rate against the
|
| 4 |
+
baseline overall rate and the 51 host rows' own baseline caught. Writes results
|
| 5 |
+
only into the sandbox (out/c3_injected_results.jsonl); canonical files untouched.
|
| 6 |
+
|
| 7 |
+
Run from repo root: python -u temp/injection_sandbox/run_c3.py
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import logging
|
| 13 |
+
import random
|
| 14 |
+
import sys
|
| 15 |
+
from collections import Counter
|
| 16 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import yaml
|
| 20 |
+
|
| 21 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 22 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 23 |
+
|
| 24 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 25 |
+
sys.path.insert(0, str(ROOT))
|
| 26 |
+
|
| 27 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 28 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 29 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 30 |
+
|
| 31 |
+
SAND = Path(__file__).resolve().parent
|
| 32 |
+
OUT = SAND / "out"
|
| 33 |
+
MERGED = OUT / "_staging_merged_injections.jsonl"
|
| 34 |
+
PROV = json.load(open(OUT / "_merged_injections.prov.json", encoding="utf-8"))
|
| 35 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 36 |
+
|
| 37 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 38 |
+
SAMPLES = 3 # baseline C3 used samples=3 majority
|
| 39 |
+
WORKERS = cfg["run"].get("workers", 4)
|
| 40 |
+
|
| 41 |
+
reals = P.real_trajectories()
|
| 42 |
+
pairer = P.make_pairer(reals)
|
| 43 |
+
judge = make_judge(cfg["model"])
|
| 44 |
+
fakes = [json.loads(l) for l in open(MERGED, encoding="utf-8") if l.strip()]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def judge_one(fake):
|
| 48 |
+
eid = fake["example_id"]
|
| 49 |
+
real = pairer(fake)
|
| 50 |
+
swap = random.Random(eid).random() < 0.5
|
| 51 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 52 |
+
key = msgs["answer_key"]
|
| 53 |
+
guesses, err = [], None
|
| 54 |
+
for _ in range(SAMPLES):
|
| 55 |
+
try:
|
| 56 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 57 |
+
guesses.append(r.get("guess"))
|
| 58 |
+
except Exception as e: # noqa: BLE001
|
| 59 |
+
err = str(e)
|
| 60 |
+
if not guesses:
|
| 61 |
+
return {"example_id": eid, "error": err, "answer_key": key, "real_id": real.get("example_id")}
|
| 62 |
+
majority = Counter(guesses).most_common(1)[0][0]
|
| 63 |
+
agree = guesses.count(majority) / len(guesses)
|
| 64 |
+
return {"example_id": eid, "answer_key": key, "real_id": real.get("example_id"),
|
| 65 |
+
"guess": majority, "agreement": agree, "n_samples": len(guesses),
|
| 66 |
+
"sample_guesses": guesses, "caught": majority == key, "error": None}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main():
|
| 70 |
+
print(f"judging {len(fakes)} injected rows (samples={SAMPLES}, workers={WORKERS}, "
|
| 71 |
+
f"model={cfg['model']['label']})")
|
| 72 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 73 |
+
results = list(ex.map(judge_one, fakes))
|
| 74 |
+
results.sort(key=lambda r: r["example_id"])
|
| 75 |
+
(OUT / "c3_injected_results.jsonl").write_text(
|
| 76 |
+
"\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8")
|
| 77 |
+
|
| 78 |
+
ok = [r for r in results if r.get("error") is None and "caught" in r]
|
| 79 |
+
errs = [r for r in results if r.get("error") is not None or "caught" not in r]
|
| 80 |
+
caught = sum(1 for r in ok if r["caught"])
|
| 81 |
+
n = len(ok)
|
| 82 |
+
|
| 83 |
+
# baseline comparison
|
| 84 |
+
base = {}
|
| 85 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 86 |
+
if line.strip():
|
| 87 |
+
d = json.loads(line)
|
| 88 |
+
base[d.get("item_id")] = d.get("caught")
|
| 89 |
+
base_all = [v for v in base.values() if v is not None]
|
| 90 |
+
base_rate = sum(base_all) / len(base_all) if base_all else 0.0
|
| 91 |
+
host_of = {p["example_id"]: p["host_of"] for p in PROV}
|
| 92 |
+
host_caught = [base.get(host_of[r["example_id"]]) for r in ok]
|
| 93 |
+
host_caught = [v for v in host_caught if v is not None]
|
| 94 |
+
host_rate = sum(host_caught) / len(host_caught) if host_caught else 0.0
|
| 95 |
+
|
| 96 |
+
print("\n=== C3 RESULT (injected rows) ===")
|
| 97 |
+
print(f" injected caught: {caught}/{n} = {caught/n:.1%}" if n else " no valid results")
|
| 98 |
+
print(f" errors: {len(errs)}")
|
| 99 |
+
print(f"\n baseline overall (795 rows): {sum(base_all)}/{len(base_all)} = {base_rate:.1%}")
|
| 100 |
+
print(f" the 51 hosts' own baseline caught: {sum(host_caught)}/{len(host_caught)} = {host_rate:.1%}")
|
| 101 |
+
delta = caught / n - base_rate if n else 0.0
|
| 102 |
+
print(f"\n injected vs baseline-overall delta: {delta:+.1%} "
|
| 103 |
+
f"(negative = injected fooled the judge MORE than baseline)")
|
| 104 |
+
print(f" wrote out/c3_injected_results.jsonl")
|
| 105 |
+
return 0
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
raise SystemExit(main())
|
tempscripts/injection_sandbox/run_c3_big.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SANDBOX C3 (large): position-invariant dual-orientation run over 102 items
|
| 2 |
+
(51 humanized injected rows + their 51 host rows), samples=3 per orientation =
|
| 3 |
+
612 judgments. Re-judging the hosts in THIS run makes before/after apples-to-apples
|
| 4 |
+
(same judge instance, same pairing), removing run-to-run variance vs the stored
|
| 5 |
+
baseline. Crash-safe: appends each finished item to out/c3_big_results.jsonl.
|
| 6 |
+
Canonical files are read-only.
|
| 7 |
+
|
| 8 |
+
Run from repo root: python -u temp/injection_sandbox/run_c3_big.py
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import logging
|
| 14 |
+
import threading
|
| 15 |
+
from collections import Counter
|
| 16 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from statistics import mean
|
| 19 |
+
|
| 20 |
+
import yaml
|
| 21 |
+
|
| 22 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 23 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 24 |
+
|
| 25 |
+
import sys
|
| 26 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 27 |
+
sys.path.insert(0, str(ROOT))
|
| 28 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 29 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 30 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 31 |
+
|
| 32 |
+
SAND = Path(__file__).resolve().parent
|
| 33 |
+
OUT = SAND / "out"
|
| 34 |
+
MERGED = OUT / "_staging_merged_injections.jsonl"
|
| 35 |
+
PROV = json.load(open(OUT / "_merged_injections.prov.json", encoding="utf-8"))
|
| 36 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 37 |
+
RESULTS = OUT / "c3_big_results.jsonl"
|
| 38 |
+
|
| 39 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 40 |
+
SAMPLES = 3
|
| 41 |
+
|
| 42 |
+
reals = P.real_trajectories()
|
| 43 |
+
pairer = P.make_pairer(reals)
|
| 44 |
+
judge = make_judge(cfg["model"])
|
| 45 |
+
|
| 46 |
+
injected = [json.loads(l) for l in open(MERGED, encoding="utf-8") if l.strip()]
|
| 47 |
+
c3 = {r["example_id"]: r for r in
|
| 48 |
+
(json.loads(l) for l in open(SAND / "data" / "c3_trajectories.jsonl", encoding="utf-8") if l.strip())}
|
| 49 |
+
host_of = {p["example_id"]: p["host_of"] for p in PROV}
|
| 50 |
+
hosts = [c3[h] for h in dict.fromkeys(host_of.values())] # unique, order-preserving
|
| 51 |
+
|
| 52 |
+
items = ([("injected", r) for r in injected]
|
| 53 |
+
+ [("host", r) for r in hosts])
|
| 54 |
+
|
| 55 |
+
_lock = threading.Lock()
|
| 56 |
+
_done = {}
|
| 57 |
+
if RESULTS.exists(): # resume support
|
| 58 |
+
for line in RESULTS.read_text(encoding="utf-8").splitlines():
|
| 59 |
+
if line.strip():
|
| 60 |
+
d = json.loads(line)
|
| 61 |
+
_done[(d["group"], d["example_id"])] = d
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def majority_guess(fake, real, swap):
|
| 65 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 66 |
+
key = msgs["answer_key"]
|
| 67 |
+
gs = []
|
| 68 |
+
for _ in range(SAMPLES):
|
| 69 |
+
try:
|
| 70 |
+
gs.append(judge.judge({"system": msgs["system"], "user": msgs["user"]}).get("guess"))
|
| 71 |
+
except Exception: # noqa: BLE001
|
| 72 |
+
pass
|
| 73 |
+
if not gs:
|
| 74 |
+
return None, key, gs
|
| 75 |
+
return Counter(gs).most_common(1)[0][0], key, gs
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def run_item(group, fake):
|
| 79 |
+
eid = fake["example_id"]
|
| 80 |
+
if (group, eid) in _done:
|
| 81 |
+
return _done[(group, eid)]
|
| 82 |
+
real = pairer(fake)
|
| 83 |
+
per = {}
|
| 84 |
+
for name, swap in (("A", False), ("B", True)): # fake in A, then fake in B
|
| 85 |
+
maj, key, gs = majority_guess(fake, real, swap)
|
| 86 |
+
per[name] = {"guess": maj, "answer_key": key, "caught": (maj == key), "samples": gs}
|
| 87 |
+
catches = [per["A"]["caught"], per["B"]["caught"]]
|
| 88 |
+
rec = {"group": group, "example_id": eid, "real_id": real.get("example_id"),
|
| 89 |
+
"order_avg_catch": mean(1.0 if c else 0.0 for c in catches),
|
| 90 |
+
"consistent_catch": all(catches), "any_catch": any(catches),
|
| 91 |
+
"A": per["A"], "B": per["B"]}
|
| 92 |
+
with _lock:
|
| 93 |
+
with open(RESULTS, "a", encoding="utf-8") as f:
|
| 94 |
+
f.write(json.dumps(rec) + "\n")
|
| 95 |
+
return rec
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def summarize(recs, group):
|
| 99 |
+
g = [r for r in recs if r["group"] == group]
|
| 100 |
+
n = len(g)
|
| 101 |
+
if not n:
|
| 102 |
+
return
|
| 103 |
+
oa = mean(r["order_avg_catch"] for r in g)
|
| 104 |
+
cons = sum(r["consistent_catch"] for r in g) / n
|
| 105 |
+
a_only = sum(r["A"]["caught"] for r in g) / n
|
| 106 |
+
print(f" {group:9} n={n} order-avg caught={oa:.1%} "
|
| 107 |
+
f"consistent(both orders)={cons:.1%} orientation-A caught={a_only:.1%}")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def main():
|
| 111 |
+
todo = [it for it in items if (it[0], it[1]["example_id"]) not in _done]
|
| 112 |
+
print(f"items total={len(items)} (already done={len(_done)}) to-judge={len(todo)} "
|
| 113 |
+
f"orientations=2 samples={SAMPLES} -> ~{len(todo)*2*SAMPLES} live calls")
|
| 114 |
+
with ThreadPoolExecutor(max_workers=cfg["run"].get("workers", 4)) as ex:
|
| 115 |
+
list(ex.map(lambda it: run_item(*it), todo))
|
| 116 |
+
|
| 117 |
+
recs = [json.loads(l) for l in RESULTS.read_text(encoding="utf-8").splitlines() if l.strip()]
|
| 118 |
+
print("\n=== C3 LARGE RESULT (dual-orientation, samples=3 majority) ===")
|
| 119 |
+
summarize(recs, "injected")
|
| 120 |
+
summarize(recs, "host")
|
| 121 |
+
|
| 122 |
+
base = {}
|
| 123 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 124 |
+
if line.strip():
|
| 125 |
+
d = json.loads(line)
|
| 126 |
+
base[d.get("item_id")] = d.get("caught")
|
| 127 |
+
base_all = [v for v in base.values() if v is not None]
|
| 128 |
+
inj = [r for r in recs if r["group"] == "injected"]
|
| 129 |
+
hos = [r for r in recs if r["group"] == "host"]
|
| 130 |
+
print(f"\n stored-baseline corpus (795): {sum(base_all)}/{len(base_all)} = {sum(base_all)/len(base_all):.1%}")
|
| 131 |
+
if inj and hos:
|
| 132 |
+
oi = mean(r["order_avg_catch"] for r in inj)
|
| 133 |
+
oh = mean(r["order_avg_catch"] for r in hos)
|
| 134 |
+
print(f" same-run host order-avg caught: {oh:.1%}")
|
| 135 |
+
print(f" same-run injected order-avg caught: {oi:.1%}")
|
| 136 |
+
print(f" injection+humanization effect (same hosts): {oi-oh:+.1%}")
|
| 137 |
+
return 0
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
raise SystemExit(main())
|
tempscripts/injection_sandbox/validate.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SANDBOX validation: logic tests + I/O tests over the 51 merged injected rows
|
| 2 |
+
(each replayed together with its host turn). Reads only sandbox artifacts.
|
| 3 |
+
|
| 4 |
+
Run: python -u temp/injection_sandbox/validate.py
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 13 |
+
SAND = Path(__file__).resolve().parent
|
| 14 |
+
sys.path.insert(0, str(ROOT))
|
| 15 |
+
sys.path.insert(0, str(ROOT / "systemUpgrade" / "executor"))
|
| 16 |
+
|
| 17 |
+
import scripts._gen_injections2 as G # noqa: E402
|
| 18 |
+
from fake_state import EpisodeState # noqa: E402
|
| 19 |
+
from fake_tools import TOOLS # noqa: E402
|
| 20 |
+
|
| 21 |
+
DATA = SAND / "data"
|
| 22 |
+
OUT = SAND / "out"
|
| 23 |
+
CATALOG = json.load(open(DATA / "catalog.json", encoding="utf-8"))
|
| 24 |
+
G.CATALOG = CATALOG
|
| 25 |
+
|
| 26 |
+
STRICT_PENDING = {"upgrade_shipping_speed", "modify_pending_order_items",
|
| 27 |
+
"cancel_pending_order", "return_pending_order_items"}
|
| 28 |
+
PRE_DELIVERY = {"schedule_delivery", "set_delivery_instructions", "get_shipping_options"}
|
| 29 |
+
PENDING_OK = ("pending", "processing", "open", "pending (modified)")
|
| 30 |
+
DELIVERED_OK = {"file_shipping_insurance_claim", "return_delivered_order_items",
|
| 31 |
+
"exchange_delivered_order_items"}
|
| 32 |
+
BAD_STATUS = {"cancelled", "returned", "return requested"}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def parse(o):
|
| 36 |
+
try:
|
| 37 |
+
return json.loads(o) if isinstance(o, str) and o.strip().startswith("{") else None
|
| 38 |
+
except json.JSONDecodeError:
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def order_status_map(calls):
|
| 43 |
+
m = {}
|
| 44 |
+
for c in calls:
|
| 45 |
+
o = parse(c.get("output"))
|
| 46 |
+
if c["name"] == "get_order_details" and o and o.get("order_id"):
|
| 47 |
+
m["#" + str(o["order_id"]).lstrip("#").upper()] = (o.get("status") or "").lower()
|
| 48 |
+
return m
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def main():
|
| 52 |
+
inj = [json.loads(l) for l in open(OUT / "_staging_merged_injections.jsonl", encoding="utf-8") if l.strip()]
|
| 53 |
+
prov = json.load(open(OUT / "_merged_injections.prov.json", encoding="utf-8"))
|
| 54 |
+
c3 = {r["example_id"]: r for r in
|
| 55 |
+
(json.loads(l) for l in open(DATA / "c3_trajectories.jsonl", encoding="utf-8") if l.strip())}
|
| 56 |
+
host_of = {p["example_id"]: p["host_of"] for p in prov}
|
| 57 |
+
|
| 58 |
+
logic = {"open_status": [], "delivered_status": [], "acted_on_bad": [],
|
| 59 |
+
"modify_before_subscribe": [], "auth_before_use": []}
|
| 60 |
+
io = {"row_replay": [], "conv_replay": []}
|
| 61 |
+
|
| 62 |
+
for row in inj:
|
| 63 |
+
eid = row["example_id"]
|
| 64 |
+
calls = row["calls"]
|
| 65 |
+
host = c3[host_of[eid]]
|
| 66 |
+
merged = host["calls"] + calls
|
| 67 |
+
smap = order_status_map(merged)
|
| 68 |
+
|
| 69 |
+
# ---- LOGIC 1: order-status fit for the injected leaf/prefix ops ----
|
| 70 |
+
for c in calls:
|
| 71 |
+
n = c["name"]
|
| 72 |
+
oid = c.get("arguments", {}).get("order_id")
|
| 73 |
+
if not oid:
|
| 74 |
+
continue
|
| 75 |
+
oid = "#" + str(oid).lstrip("#").upper()
|
| 76 |
+
st = smap.get(oid)
|
| 77 |
+
if st is None:
|
| 78 |
+
continue
|
| 79 |
+
if n in STRICT_PENDING and st not in PENDING_OK:
|
| 80 |
+
logic["open_status"].append((eid, n, oid, st))
|
| 81 |
+
if n in PRE_DELIVERY and st not in PENDING_OK + ("shipped",):
|
| 82 |
+
logic["open_status"].append((eid, n, oid, st))
|
| 83 |
+
if n in DELIVERED_OK and st and st != "delivered":
|
| 84 |
+
logic["delivered_status"].append((eid, n, oid, st))
|
| 85 |
+
if st in BAD_STATUS:
|
| 86 |
+
logic["acted_on_bad"].append((eid, n, oid, st))
|
| 87 |
+
|
| 88 |
+
# ---- LOGIC 2: modify precedes subscribe (N3) ----
|
| 89 |
+
names = [c["name"] for c in calls]
|
| 90 |
+
if "subscribe_to_restock_alert" in names and "modify_pending_order_items" in names:
|
| 91 |
+
if names.index("modify_pending_order_items") > names.index("subscribe_to_restock_alert"):
|
| 92 |
+
logic["modify_before_subscribe"].append((eid, names))
|
| 93 |
+
|
| 94 |
+
# ---- LOGIC 3: auth/reads before use across the whole conversation ----
|
| 95 |
+
# Entities are established by the host's history tool calls and host turn
|
| 96 |
+
# first; the injected turn may legitimately act on them (later turn).
|
| 97 |
+
est_users, est_orders = set(), set()
|
| 98 |
+
cat_o = {"#" + str(x).lstrip("#").upper() for x in CATALOG.get("order_balances", {})}
|
| 99 |
+
hist_calls = []
|
| 100 |
+
for m in (host.get("history") or []):
|
| 101 |
+
for tc in (m.get("tool_calls") or []):
|
| 102 |
+
hist_calls.append({"name": tc.get("name"), "arguments": tc.get("arguments", {}),
|
| 103 |
+
"output": tc.get("output")})
|
| 104 |
+
for c in hist_calls + host["calls"]: # pre-establish from prior turns
|
| 105 |
+
n = c["name"]
|
| 106 |
+
o = parse(c.get("output"))
|
| 107 |
+
if n.startswith("find_user_id"):
|
| 108 |
+
u = (c.get("output") or "").strip().strip('"')
|
| 109 |
+
if "_" in u:
|
| 110 |
+
est_users.add(u)
|
| 111 |
+
if n == "get_user_details" and o and o.get("user_id"):
|
| 112 |
+
est_users.add(o["user_id"])
|
| 113 |
+
if n == "get_order_details" and o and o.get("order_id"):
|
| 114 |
+
est_orders.add("#" + str(o["order_id"]).lstrip("#").upper())
|
| 115 |
+
for c in calls:
|
| 116 |
+
n = c["name"]
|
| 117 |
+
a = c.get("arguments", {})
|
| 118 |
+
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":
|
| 119 |
+
logic["auth_before_use"].append((eid, n, "user_id", a["user_id"]))
|
| 120 |
+
if a.get("order_id"):
|
| 121 |
+
oo = "#" + str(a["order_id"]).lstrip("#").upper()
|
| 122 |
+
if oo not in est_orders and n != "get_order_details" and oo not in cat_o:
|
| 123 |
+
logic["auth_before_use"].append((eid, n, "order_id", a["order_id"]))
|
| 124 |
+
o = parse(c.get("output"))
|
| 125 |
+
if n.startswith("find_user_id"):
|
| 126 |
+
u = (c.get("output") or "").strip().strip('"')
|
| 127 |
+
if "_" in u:
|
| 128 |
+
est_users.add(u)
|
| 129 |
+
if n == "get_user_details" and o and o.get("user_id"):
|
| 130 |
+
est_users.add(o["user_id"])
|
| 131 |
+
if n == "get_order_details" and o and o.get("order_id"):
|
| 132 |
+
est_orders.add("#" + str(o["order_id"]).lstrip("#").upper())
|
| 133 |
+
|
| 134 |
+
# ---- IO 1: row-level replay (row's own calls reproduce) ----
|
| 135 |
+
if G.verify_row(calls):
|
| 136 |
+
io["row_replay"].append((eid, G.verify_row(calls)))
|
| 137 |
+
|
| 138 |
+
# ---- IO 2: conversation-level replay (host turn + injected turn) ----
|
| 139 |
+
s = EpisodeState.from_trajectory({"calls": merged}, CATALOG)
|
| 140 |
+
for c in merged:
|
| 141 |
+
n = c["name"]
|
| 142 |
+
if n not in TOOLS:
|
| 143 |
+
continue
|
| 144 |
+
got = TOOLS[n](s, c.get("arguments", {}))
|
| 145 |
+
rec = parse(c.get("output"))
|
| 146 |
+
if n in G.FIND:
|
| 147 |
+
if got != (c.get("output") or "").strip().strip('"'):
|
| 148 |
+
io["conv_replay"].append((eid, n, "uid"))
|
| 149 |
+
continue
|
| 150 |
+
if not isinstance(rec, dict):
|
| 151 |
+
continue
|
| 152 |
+
if n in G.FULLMATCH:
|
| 153 |
+
if got != rec:
|
| 154 |
+
io["conv_replay"].append((eid, n, "dict-diff"))
|
| 155 |
+
continue
|
| 156 |
+
keys = G.CHECK.get(n, [])
|
| 157 |
+
if any(got.get(k) is None and rec.get(k) is not None for k in keys):
|
| 158 |
+
continue
|
| 159 |
+
|
| 160 |
+
def _eq(k):
|
| 161 |
+
g, rv = got.get(k), rec.get(k)
|
| 162 |
+
if k == "status" and isinstance(g, str) and isinstance(rv, str):
|
| 163 |
+
return g.replace(" ", "_") == rv.replace(" ", "_")
|
| 164 |
+
return g == rv
|
| 165 |
+
bad = [k for k in keys if not _eq(k)]
|
| 166 |
+
if bad:
|
| 167 |
+
io["conv_replay"].append((eid, n, {k: (got.get(k), rec.get(k)) for k in bad}))
|
| 168 |
+
|
| 169 |
+
print(f"validated {len(inj)} injected rows (each replayed with its host turn)\n")
|
| 170 |
+
print("=== LOGIC TESTS ===")
|
| 171 |
+
for k, v in logic.items():
|
| 172 |
+
print(f" {k}: {len(v)} violation(s)")
|
| 173 |
+
for x in v[:8]:
|
| 174 |
+
print(" ", x)
|
| 175 |
+
print("\n=== I/O TESTS ===")
|
| 176 |
+
for k, v in io.items():
|
| 177 |
+
print(f" {k}: {len(v)} mismatch(es)")
|
| 178 |
+
for x in v[:8]:
|
| 179 |
+
print(" ", x)
|
| 180 |
+
|
| 181 |
+
total = sum(len(v) for v in logic.values()) + sum(len(v) for v in io.values())
|
| 182 |
+
print("\nRESULT:", "ALL CLEAN" if total == 0 else f"{total} ISSUE(S)")
|
| 183 |
+
return 0 if total == 0 else 1
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
if __name__ == "__main__":
|
| 187 |
+
raise SystemExit(main())
|
tempscripts/injection_sandbox/verify_trie.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SANDBOX trie re-confirmation: rebuild the n100 trie WITHOUT and WITH the
|
| 2 |
+
temp merged injections and report the 5 fix targets + LEAVE spine. Points the
|
| 3 |
+
verifier's STAGING at temp/out/_staging_merged_injections.jsonl. Read-only.
|
| 4 |
+
|
| 5 |
+
Run from repo root: python -u temp/injection_sandbox/verify_trie.py
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import sys
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 13 |
+
sys.path.insert(0, str(ROOT))
|
| 14 |
+
sys.path.insert(0, str(ROOT / "systemUpgrade"))
|
| 15 |
+
|
| 16 |
+
import scripts._verify_injection as V # noqa: E402
|
| 17 |
+
|
| 18 |
+
V.STAGING = Path(__file__).resolve().parent / "out" / "_staging_merged_injections.jsonl"
|
| 19 |
+
raise SystemExit(V.main())
|
tempscripts/injection_sandbox/viz_trie.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SANDBOX trie visualization: build the n100 execution trie over canonical
|
| 2 |
+
train + test + synthetic + the 51 temp merged injections, and emit into the
|
| 3 |
+
sandbox out/ folder:
|
| 4 |
+
- trie_after.txt full highlighted text tree
|
| 5 |
+
- trie_targets.txt focused before/after view of the 5 fix-target nodes
|
| 6 |
+
- trie_after.png/.svg rendered image (if Graphviz is installed)
|
| 7 |
+
Read-only w.r.t. canonical data.
|
| 8 |
+
|
| 9 |
+
Run from repo root: python -u temp/injection_sandbox/viz_trie.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import sys
|
| 15 |
+
from collections import Counter
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 19 |
+
sys.path.insert(0, str(ROOT))
|
| 20 |
+
sys.path.insert(0, str(ROOT / "systemUpgrade"))
|
| 21 |
+
|
| 22 |
+
from pipeline import load_examples # noqa: E402
|
| 23 |
+
from trie.builder import build_trie # noqa: E402
|
| 24 |
+
from scripts.visualize_distractor_trie import _render_image # noqa: E402
|
| 25 |
+
|
| 26 |
+
SAND = Path(__file__).resolve().parent
|
| 27 |
+
OUT = SAND / "out"
|
| 28 |
+
EXP = ROOT / "data" / "tau-2" / "processed_distractor_exp2"
|
| 29 |
+
N100 = EXP / "n100"
|
| 30 |
+
MERGED = OUT / "_staging_merged_injections.jsonl"
|
| 31 |
+
|
| 32 |
+
TARGETS = {
|
| 33 |
+
"N1": ["find_user_id_by_email"],
|
| 34 |
+
"N2": ["find_user_id_by_email", "get_user_details"],
|
| 35 |
+
"N3": ["modify_pending_order_items"],
|
| 36 |
+
"N4": ["find_user_id_by_name_zip", "get_user_details",
|
| 37 |
+
"get_order_details", "get_order_details",
|
| 38 |
+
"get_order_details", "get_order_details"],
|
| 39 |
+
"N5": ["find_user_id_by_name_zip", "get_order_details"],
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
manifest = json.loads((N100 / "apis.manifest.json").read_text(encoding="utf-8"))
|
| 43 |
+
REAL, CONF, DUMMY = set(manifest.get("real", [])), set(manifest.get("confuser", [])), set(manifest.get("dummy", []))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def cls(name):
|
| 47 |
+
return "REAL" if name in REAL else "conf" if name in CONF else "dummy" if name in DUMMY else "?"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def build(with_merged):
|
| 51 |
+
ex = load_examples(EXP / "train.jsonl") + load_examples(EXP / "test.jsonl")
|
| 52 |
+
ex += load_examples(N100 / "synthetic_trajectories.jsonl")
|
| 53 |
+
if with_merged:
|
| 54 |
+
ex += load_examples(MERGED)
|
| 55 |
+
return build_trie(ex)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def target_view(trie):
|
| 59 |
+
lines = []
|
| 60 |
+
for name, path in TARGETS.items():
|
| 61 |
+
node = trie.traverse(tuple(path))
|
| 62 |
+
lines.append(f"\n{name} {' > '.join(path)}")
|
| 63 |
+
if node is None or node.total_child_count() == 0:
|
| 64 |
+
lines.append(" (absent)")
|
| 65 |
+
continue
|
| 66 |
+
probs = node.transition_probs()
|
| 67 |
+
for nm in sorted(node.children, key=lambda n: -probs[n]):
|
| 68 |
+
tag = cls(nm)
|
| 69 |
+
mark = ">>" if tag == "REAL" else " "
|
| 70 |
+
lines.append(f" {mark} [{tag:5}] {nm:32} p={probs[nm]:.3f} count={node.children[nm].count}")
|
| 71 |
+
return lines
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def main():
|
| 75 |
+
before, after = build(False), build(True)
|
| 76 |
+
|
| 77 |
+
# focused before/after target view
|
| 78 |
+
tv = ["FIX-TARGET NODES (before vs after temp injection)", "=" * 70]
|
| 79 |
+
tv.append("\n--- BEFORE ---")
|
| 80 |
+
tv += target_view(before)
|
| 81 |
+
tv.append("\n\n--- AFTER (with 51 merged injections) ---")
|
| 82 |
+
tv += target_view(after)
|
| 83 |
+
(OUT / "trie_targets.txt").write_text("\n".join(tv), encoding="utf-8")
|
| 84 |
+
|
| 85 |
+
# full highlighted text tree (after)
|
| 86 |
+
lines, node_cls, stats = [], Counter(), {"nodes": 0, "max_depth": 0}
|
| 87 |
+
|
| 88 |
+
def render(node, depth):
|
| 89 |
+
for child in sorted(node.children.values(), key=lambda c: (-c.count, c.api_name)):
|
| 90 |
+
c = cls(child.api_name)
|
| 91 |
+
node_cls[c] += 1
|
| 92 |
+
stats["nodes"] += 1
|
| 93 |
+
stats["max_depth"] = max(stats["max_depth"], depth + 1)
|
| 94 |
+
ind = " " * depth
|
| 95 |
+
if c == "REAL":
|
| 96 |
+
lines.append(f"{ind}>> REAL {child.api_name} (count={child.count})")
|
| 97 |
+
else:
|
| 98 |
+
lines.append(f"{ind} [{c:5}] {child.api_name} (count={child.count})")
|
| 99 |
+
render(child, depth + 1)
|
| 100 |
+
|
| 101 |
+
render(after.root, 0)
|
| 102 |
+
header = [
|
| 103 |
+
"EXP2 EXECUTION TRIE (train + test + synthetic + 51 temp injections)",
|
| 104 |
+
"=" * 70,
|
| 105 |
+
f"trajectories: before={before.root.count} after={after.root.count} "
|
| 106 |
+
f"(+{after.root.count - before.root.count})",
|
| 107 |
+
f"trie nodes: {stats['nodes']} max depth: {stats['max_depth']}",
|
| 108 |
+
"nodes by class: " + " ".join(f"{k}={node_cls[k]}" for k in ("REAL", "conf", "dummy", "?")),
|
| 109 |
+
"Legend: '>> REAL' = real tau2 API; [conf] = confuser; [dummy] = off-domain",
|
| 110 |
+
"=" * 70, "",
|
| 111 |
+
]
|
| 112 |
+
(OUT / "trie_after.txt").write_text("\n".join(header + lines), encoding="utf-8")
|
| 113 |
+
|
| 114 |
+
img = _render_image(after.root, cls, OUT / "trie_after", fmt="png")
|
| 115 |
+
_render_image(after.root, cls, OUT / "trie_after", fmt="svg")
|
| 116 |
+
|
| 117 |
+
print(f"trajectories before={before.root.count} after={after.root.count} (+{after.root.count-before.root.count})")
|
| 118 |
+
print("wrote:", (OUT / 'trie_targets.txt').name, ",", (OUT / 'trie_after.txt').name,
|
| 119 |
+
("," + Path(img).name if img else "(no image: Graphviz not installed)"))
|
| 120 |
+
return 0
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
if __name__ == "__main__":
|
| 124 |
+
raise SystemExit(main())
|
tempscripts/story_remediation/add_turns/build_v2.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build the ADD-TURNS v2 dataset (temp only).
|
| 2 |
+
|
| 3 |
+
Base = wording-remediation applied where we have it:
|
| 4 |
+
full-795 = {514 remediated rows} UNION {281 untouched originals}
|
| 5 |
+
|
| 6 |
+
Intervention = splice ONE logic-safe tool-call turn into `history` for the
|
| 7 |
+
eligible ~19% (never touching `query` or `calls`):
|
| 8 |
+
* authed-in-history rows -> reuse the row's OWN recorded get_order_details
|
| 9 |
+
output as an "open the order" beat AFTER auth (no re-auth, zero fabrication).
|
| 10 |
+
Fallback to the catalog browse if the row has no get_order_details.
|
| 11 |
+
* opener / no-auth rows -> an auth-free list_all_product_types browse turn
|
| 12 |
+
(real tool, no entity, valid before auth). Output reused verbatim from a real
|
| 13 |
+
tau2 trajectory.
|
| 14 |
+
|
| 15 |
+
C3 only renders HISTORY tool markers, so this is the only place an added tool
|
| 16 |
+
turn is visible; the harvested turn's calls (the retrieval target) stay fixed.
|
| 17 |
+
|
| 18 |
+
Writes add_turns/out/trajectories_v2.jsonl + prints eligibility + effect stats.
|
| 19 |
+
Run: python -u temp/story_remediation/add_turns/build_v2.py
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
import json, sys
|
| 23 |
+
from collections import Counter
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
HERE = Path(__file__).resolve().parent
|
| 27 |
+
ROOT = HERE.parents[2]
|
| 28 |
+
sys.path.insert(0, str(ROOT))
|
| 29 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 30 |
+
|
| 31 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 32 |
+
REMED = ROOT / "temp" / "story_remediation" / "out" / "trajectories_remediated.jsonl"
|
| 33 |
+
OUT = HERE / "out" / "trajectories_v2.jsonl"
|
| 34 |
+
|
| 35 |
+
AUTH_FIND = {"find_user_id_by_email", "find_user_id_by_name_zip",
|
| 36 |
+
"find_user_id_by_phone", "find_user_id_by_username"}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def parse(o):
|
| 40 |
+
try:
|
| 41 |
+
return json.loads(o) if isinstance(o, str) else o
|
| 42 |
+
except Exception:
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _out_str(o):
|
| 47 |
+
return o if isinstance(o, str) else json.dumps(o, ensure_ascii=False)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def hist_call_names(r):
|
| 51 |
+
hist = r.get("history") or (r.get("metadata") or {}).get("history") or []
|
| 52 |
+
return [tc.get("name") for m in hist for tc in (m.get("tool_calls") or [])]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def orders_of(r):
|
| 56 |
+
for c in (r.get("calls") or []):
|
| 57 |
+
if c["name"] == "get_user_details":
|
| 58 |
+
o = parse(c.get("output"))
|
| 59 |
+
if isinstance(o, dict):
|
| 60 |
+
return o.get("orders") or []
|
| 61 |
+
return []
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def touched_orders(r):
|
| 65 |
+
t = set()
|
| 66 |
+
for c in (r.get("calls") or []):
|
| 67 |
+
for v in (c.get("arguments") or {}).values():
|
| 68 |
+
if isinstance(v, str) and v.startswith("#W"):
|
| 69 |
+
t.add(v)
|
| 70 |
+
return t
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def first_order_read(r):
|
| 74 |
+
"""First get_order_details call (history or current) with a dict output -> (oid, status, output_str)."""
|
| 75 |
+
seqs = list(r.get("calls") or [])
|
| 76 |
+
for m in (r.get("history") or (r.get("metadata") or {}).get("history") or []):
|
| 77 |
+
seqs.extend(m.get("tool_calls") or [])
|
| 78 |
+
for c in seqs:
|
| 79 |
+
if c.get("name") == "get_order_details":
|
| 80 |
+
o = parse(c.get("output"))
|
| 81 |
+
if isinstance(o, dict) and o.get("order_id"):
|
| 82 |
+
return o["order_id"], o.get("status"), _out_str(o)
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# real list_all_product_types output (verbatim from a real tau2 trajectory)
|
| 87 |
+
_LPT = None
|
| 88 |
+
for _r in P.real_trajectories():
|
| 89 |
+
for _c in (_r.get("calls") or []):
|
| 90 |
+
if _c["name"] == "list_all_product_types" and _c.get("output"):
|
| 91 |
+
_LPT = _out_str(_c["output"]); break
|
| 92 |
+
if _LPT:
|
| 93 |
+
break
|
| 94 |
+
assert _LPT, "no real list_all_product_types output found"
|
| 95 |
+
|
| 96 |
+
_AUTHED_Q = [
|
| 97 |
+
"Before we get into it, can you pull up {oid} so I can see where it stands?",
|
| 98 |
+
"First, could you open my order {oid} for me?",
|
| 99 |
+
"Can you take a look at {oid} while you have my account up?",
|
| 100 |
+
"One sec, mind pulling up {oid} so we're both looking at the same thing?",
|
| 101 |
+
]
|
| 102 |
+
_CATALOG_Q = [
|
| 103 |
+
"Quick thing first, what kinds of products do you carry?",
|
| 104 |
+
"Before that, what product categories do you have these days?",
|
| 105 |
+
"Out of curiosity, what sorts of things do you sell?",
|
| 106 |
+
"First, can you tell me what product types you stock?",
|
| 107 |
+
]
|
| 108 |
+
_CATALOG_A = ("We carry a pretty wide range, electronics, home, fitness, and more. "
|
| 109 |
+
"Anyway, what can I help you with?")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def add_block(r, kind, idx):
|
| 113 |
+
v = idx % 4
|
| 114 |
+
if kind == "authed":
|
| 115 |
+
rd = first_order_read(r)
|
| 116 |
+
if rd:
|
| 117 |
+
oid, status, out_str = rd
|
| 118 |
+
stxt = f"It's currently {status}." if status else "I've got it open."
|
| 119 |
+
return [
|
| 120 |
+
{"role": "user", "content": _AUTHED_Q[v].format(oid=oid),
|
| 121 |
+
"tool_calls": [], "tool_call_id": None},
|
| 122 |
+
{"role": "assistant", "content": None,
|
| 123 |
+
"tool_calls": [{"name": "get_order_details", "arguments": {"order_id": oid},
|
| 124 |
+
"output": out_str, "reasoning": "Opening the order to check its status."}],
|
| 125 |
+
"tool_call_id": None},
|
| 126 |
+
{"role": "tool", "content": out_str, "tool_calls": [], "tool_call_id": None},
|
| 127 |
+
{"role": "assistant", "content": f"Sure, {oid}, {stxt}",
|
| 128 |
+
"tool_calls": [], "tool_call_id": None},
|
| 129 |
+
]
|
| 130 |
+
kind = "catalog" # fallback
|
| 131 |
+
# catalog browse (auth-free)
|
| 132 |
+
return [
|
| 133 |
+
{"role": "user", "content": _CATALOG_Q[v], "tool_calls": [], "tool_call_id": None},
|
| 134 |
+
{"role": "assistant", "content": None,
|
| 135 |
+
"tool_calls": [{"name": "list_all_product_types", "arguments": {},
|
| 136 |
+
"output": _LPT, "reasoning": "Listing available product categories."}],
|
| 137 |
+
"tool_call_id": None},
|
| 138 |
+
{"role": "tool", "content": _LPT, "tool_calls": [], "tool_call_id": None},
|
| 139 |
+
{"role": "assistant", "content": _CATALOG_A, "tool_calls": [], "tool_call_id": None},
|
| 140 |
+
]
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def main():
|
| 144 |
+
orig = {json.loads(l)["example_id"]: json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()}
|
| 145 |
+
remed = {json.loads(l)["example_id"]: json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()}
|
| 146 |
+
base = {eid: remed.get(eid, orig[eid]) for eid in orig} # full 795, wording where available
|
| 147 |
+
|
| 148 |
+
cat = Counter(); applied = Counter(); changed = []
|
| 149 |
+
rows_out = []
|
| 150 |
+
for i, (eid, r) in enumerate(sorted(base.items())):
|
| 151 |
+
r = json.loads(json.dumps(r)) # deep copy
|
| 152 |
+
cn = [c["name"] for c in (r.get("calls") or [])]
|
| 153 |
+
hn = hist_call_names(r)
|
| 154 |
+
cur_auth = any(x in AUTH_FIND for x in cn)
|
| 155 |
+
hist_auth = any(x in AUTH_FIND for x in hn) or ("get_user_details" in hn)
|
| 156 |
+
orders = orders_of(r); unt = [o for o in orders if o not in touched_orders(r)]
|
| 157 |
+
kind = None
|
| 158 |
+
if hist_auth and not cur_auth:
|
| 159 |
+
cat["authed-in-history"] += 1; kind = "authed"
|
| 160 |
+
elif not cur_auth and not hist_auth:
|
| 161 |
+
cat["no-auth"] += 1; kind = "catalog"
|
| 162 |
+
elif cur_auth and len(unt) >= 1:
|
| 163 |
+
cat["opener-untouched"] += 1; kind = "catalog"
|
| 164 |
+
else:
|
| 165 |
+
cat["opener-all-touched (skip)"] += 1
|
| 166 |
+
|
| 167 |
+
if kind:
|
| 168 |
+
hist = list(r.get("history") or (r.get("metadata") or {}).get("history") or [])
|
| 169 |
+
block = add_block(r, kind, i)
|
| 170 |
+
new_hist = hist + block # append just before the harvested turn
|
| 171 |
+
r["history"] = new_hist
|
| 172 |
+
if r.get("metadata"):
|
| 173 |
+
r["metadata"]["history"] = new_hist
|
| 174 |
+
applied[block[1]["tool_calls"][0]["name"]] += 1
|
| 175 |
+
changed.append(eid)
|
| 176 |
+
rows_out.append(r)
|
| 177 |
+
|
| 178 |
+
OUT.parent.mkdir(parents=True, exist_ok=True)
|
| 179 |
+
with OUT.open("w", encoding="utf-8") as fh:
|
| 180 |
+
for r in rows_out:
|
| 181 |
+
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 182 |
+
(HERE / "out" / "changed_ids.txt").write_text("\n".join(changed) + "\n", encoding="utf-8")
|
| 183 |
+
|
| 184 |
+
print(f"base rows : {len(rows_out)}")
|
| 185 |
+
print(f"eligibility : {dict(cat)}")
|
| 186 |
+
print(f"rows changed : {len(changed)}")
|
| 187 |
+
print(f"added tool by type: {dict(applied)}")
|
| 188 |
+
# effect: turns-with-tool-call before/after on changed rows
|
| 189 |
+
def tt(r):
|
| 190 |
+
return sum(1 for m in (r.get("history") or []) if m.get("tool_calls")) + (1 if r.get("calls") else 0)
|
| 191 |
+
before = [tt(base[e]) for e in changed]
|
| 192 |
+
after = [tt(next(x for x in rows_out if x["example_id"] == e)) for e in changed]
|
| 193 |
+
import statistics as st
|
| 194 |
+
print(f"changed rows tool-call turns: before mean {st.mean(before):.2f} -> after mean {st.mean(after):.2f}")
|
| 195 |
+
print(f"wrote {OUT.relative_to(ROOT)} + out/changed_ids.txt")
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
if __name__ == "__main__":
|
| 199 |
+
main()
|
tempscripts/story_remediation/add_turns/replay_v2.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Free-running state runthrough on the REMEDIATED trajectories.
|
| 2 |
+
|
| 3 |
+
Reuses the exact executor (fake_state + fake_tools + catalog) from
|
| 4 |
+
systemUpgrade/executor, but seeds/replays from our remediated file. Since the
|
| 5 |
+
remediation changed ONLY dialogue (history + query) and never `calls`, this must
|
| 6 |
+
reproduce recorded outputs at the same rate as baseline -- any new mismatch/EXC
|
| 7 |
+
would be a logic or I/O regression introduced by the rewrite.
|
| 8 |
+
|
| 9 |
+
Also cross-checks each remediated row's calls are byte-identical to the source
|
| 10 |
+
n100 row (proves no floating vars / dropped IDs leaked into calls).
|
| 11 |
+
|
| 12 |
+
Run from repo root: python -u temp/story_remediation/replay_remediated.py
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
import json, sys
|
| 16 |
+
from collections import Counter, defaultdict
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 20 |
+
EXEC = ROOT / "systemUpgrade" / "executor"
|
| 21 |
+
sys.path.insert(0, str(EXEC))
|
| 22 |
+
from fake_state import EpisodeState # noqa: E402
|
| 23 |
+
from fake_tools import TOOLS # noqa: E402
|
| 24 |
+
|
| 25 |
+
catalog = json.load(open(EXEC / "catalog.json", encoding="utf-8"))
|
| 26 |
+
REMED = ROOT / "temp" / "story_remediation" / "add_turns" / "out" / "trajectories_v2.jsonl"
|
| 27 |
+
SRC = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 28 |
+
|
| 29 |
+
rem = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()]
|
| 30 |
+
src = {json.loads(l)["example_id"]: json.loads(l)
|
| 31 |
+
for l in open(SRC, encoding="utf-8") if l.strip()}
|
| 32 |
+
|
| 33 |
+
# 1) calls integrity: remediated calls must equal source calls exactly
|
| 34 |
+
calls_diff = [r["example_id"] for r in rem
|
| 35 |
+
if json.dumps(r["calls"], sort_keys=True) != json.dumps(src[r["example_id"]]["calls"], sort_keys=True)]
|
| 36 |
+
|
| 37 |
+
# reuse replay.py's CHECK/FULLMATCH/FIND config
|
| 38 |
+
import importlib.util
|
| 39 |
+
spec = importlib.util.spec_from_file_location("_replay", EXEC / "replay.py")
|
| 40 |
+
# can't exec replay.py (it runs on import); inline the needed maps instead:
|
| 41 |
+
FULLMATCH = {"get_product_details", "get_size_guide", "get_product_reviews", "get_item_details",
|
| 42 |
+
"get_warranty_details", "get_extended_warranty_options", "get_shipping_options",
|
| 43 |
+
"get_active_promotions", "list_all_product_types", "get_user_reviews", "get_order_invoice"}
|
| 44 |
+
FIND = {"find_user_id_by_email", "find_user_id_by_phone", "find_user_id_by_username", "find_user_id_by_name_zip"}
|
| 45 |
+
CHECK = {
|
| 46 |
+
"apply_gift_card": ["amount_applied", "remaining_balance_due"], "apply_discount_code": ["discount", "status"],
|
| 47 |
+
"checkout_cart": ["total"], "cancel_order_item": ["status", "item_id"],
|
| 48 |
+
"return_pending_order_items": ["status", "item_ids"], "return_delivered_order_items": ["status", "item_ids"],
|
| 49 |
+
"exchange_delivered_order_items": ["status"], "modify_pending_order_items": [],
|
| 50 |
+
"remove_item_from_cart": ["subtotal"], "add_item_to_cart": ["user_id"], "get_order_details": ["status"],
|
| 51 |
+
"get_user_details": ["user_id", "email"], "get_cart_contents": ["subtotal"], "get_gift_card_balance": ["balance"],
|
| 52 |
+
"get_loyalty_points_balance": ["points"], "get_store_credit_balance": ["balance"], "get_wishlist": ["items"],
|
| 53 |
+
"cancel_delivered_order": ["status", "refund"], "cancel_pending_order": ["status", "refund"],
|
| 54 |
+
"modify_pending_order_address": ["status"], "add_gift_message": ["gift_message"],
|
| 55 |
+
"schedule_delivery": ["scheduled_delivery", "status"], "set_delivery_instructions": ["delivery_instructions", "status"],
|
| 56 |
+
"schedule_installation": ["appointment_id"], "book_repair_appointment": ["appointment_id"],
|
| 57 |
+
"request_return_pickup": ["confirmation"], "get_return_label": ["label_url"],
|
| 58 |
+
"request_gift_receipt": ["gift_receipt_url", "prices_shown"],
|
| 59 |
+
"file_shipping_insurance_claim": ["claim_id", "status", "estimated_review_days"],
|
| 60 |
+
"upgrade_shipping_speed": ["shipping_speed", "status"], "split_order_shipment": ["status"],
|
| 61 |
+
"request_price_adjustment": ["status"], "request_price_match": ["item_id"],
|
| 62 |
+
"reorder_previous_order": ["duplicated_from", "status", "total"], "register_product_warranty": [],
|
| 63 |
+
"submit_product_review": [], "subscribe_to_restock_alert": [], "redeem_loyalty_points": ["points_redeemed", "credit"],
|
| 64 |
+
"purchase_gift_card": ["amount"], "add_to_wishlist": ["user_id"], "modify_user_email": ["status", "email"],
|
| 65 |
+
"modify_user_name": ["status"], "modify_user_phone": ["status", "phone"], "update_user_password": ["status"],
|
| 66 |
+
"add_user_address": ["status"], "modify_user_address": ["status"], "delete_user_address": ["status", "deleted_zip"],
|
| 67 |
+
"verify_user_identity": ["verified"],
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def parse(o):
|
| 72 |
+
try:
|
| 73 |
+
return json.loads(o) if isinstance(o, str) else o
|
| 74 |
+
except json.JSONDecodeError:
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
stats = defaultdict(lambda: {"n": 0, "match": 0, "skip_nodata": 0, "mism": [], "exc": []})
|
| 79 |
+
covered, uncovered = Counter(), Counter()
|
| 80 |
+
|
| 81 |
+
for r in rem:
|
| 82 |
+
s = EpisodeState.from_trajectory(r, catalog)
|
| 83 |
+
for c in r["calls"]:
|
| 84 |
+
n = c["name"]
|
| 85 |
+
if n not in TOOLS:
|
| 86 |
+
uncovered[n] += 1
|
| 87 |
+
continue
|
| 88 |
+
covered[n] += 1
|
| 89 |
+
rec = parse(c.get("output"))
|
| 90 |
+
st = stats[n]
|
| 91 |
+
st["n"] += 1
|
| 92 |
+
try:
|
| 93 |
+
got = TOOLS[n](s, c.get("arguments", {}))
|
| 94 |
+
except Exception as e: # noqa
|
| 95 |
+
st["exc"].append((r["example_id"], f"{type(e).__name__}: {e}"))
|
| 96 |
+
continue
|
| 97 |
+
if n in FIND:
|
| 98 |
+
if got == (c.get("output") or "").strip().strip('"'):
|
| 99 |
+
st["match"] += 1
|
| 100 |
+
else:
|
| 101 |
+
st["mism"].append((r["example_id"], {"uid": (got, c.get("output"))}))
|
| 102 |
+
continue
|
| 103 |
+
if not isinstance(rec, dict):
|
| 104 |
+
st["match"] += 1
|
| 105 |
+
continue
|
| 106 |
+
if n in FULLMATCH:
|
| 107 |
+
st["match"] += 1 if got == rec else st["mism"].append((r["example_id"], "dict-diff"))
|
| 108 |
+
if got == rec:
|
| 109 |
+
pass
|
| 110 |
+
continue
|
| 111 |
+
keys = CHECK.get(n, [])
|
| 112 |
+
if any(got.get(k) is None and rec.get(k) is not None for k in keys):
|
| 113 |
+
st["skip_nodata"] += 1
|
| 114 |
+
continue
|
| 115 |
+
|
| 116 |
+
def _eq(k):
|
| 117 |
+
g, rv = got.get(k), rec.get(k)
|
| 118 |
+
if k == "status" and isinstance(g, str) and isinstance(rv, str):
|
| 119 |
+
return g.replace(" ", "_") == rv.replace(" ", "_")
|
| 120 |
+
return g == rv
|
| 121 |
+
if all(_eq(k) for k in keys):
|
| 122 |
+
st["match"] += 1
|
| 123 |
+
else:
|
| 124 |
+
st["mism"].append((r["example_id"], {k: (got.get(k), rec.get(k)) for k in keys if not _eq(k)}))
|
| 125 |
+
|
| 126 |
+
tot_chk = sum(st["n"] - st["skip_nodata"] for st in stats.values())
|
| 127 |
+
tot_match = sum(st["match"] for st in stats.values())
|
| 128 |
+
tot_exc = sum(len(st["exc"]) for st in stats.values())
|
| 129 |
+
tot_mism = sum(len(st["mism"]) for st in stats.values())
|
| 130 |
+
tot_skip = sum(st["skip_nodata"] for st in stats.values())
|
| 131 |
+
|
| 132 |
+
print("=== CALLS INTEGRITY (remediated vs source n100) ===")
|
| 133 |
+
print(f" rows: {len(rem)} calls differ from source: {len(calls_diff)} {calls_diff[:5]}")
|
| 134 |
+
print("\n=== FREE-RUNNING REPLAY (remediated trajectories) ===")
|
| 135 |
+
print(f" reproduced : {tot_match}/{tot_chk} = {tot_match/max(tot_chk,1):.1%}")
|
| 136 |
+
print(f" exceptions : {tot_exc}")
|
| 137 |
+
print(f" mismatches : {tot_mism}")
|
| 138 |
+
print(f" skipped-no-seed : {tot_skip}")
|
| 139 |
+
print(f" tools implemented/exercised : {len(stats)} uncovered(echo) calls: {sum(uncovered.values())}")
|
| 140 |
+
if tot_exc:
|
| 141 |
+
print("\n -- EXCEPTIONS --")
|
| 142 |
+
for n, st in sorted(stats.items()):
|
| 143 |
+
for eid, msg in st["exc"][:5]:
|
| 144 |
+
print(f" [{n}] {eid}: {msg}")
|
| 145 |
+
if tot_mism:
|
| 146 |
+
print("\n -- MISMATCHES --")
|
| 147 |
+
for n, st in sorted(stats.items()):
|
| 148 |
+
for eid, d in st["mism"][:5]:
|
| 149 |
+
print(f" [{n}] {eid}: {d}")
|
| 150 |
+
|
| 151 |
+
|
tempscripts/story_remediation/add_turns/run_c3_v2.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run C3 on the remediated trajectories and compare to baseline.
|
| 2 |
+
|
| 3 |
+
Same judge procedure as the baseline C3 pass (samples=3 majority, workers from
|
| 4 |
+
config, model from datasetreview/config.yaml). For a controlled before/after we
|
| 5 |
+
reuse each row's BASELINE pairing + orientation (answer_key) so the ONLY thing
|
| 6 |
+
that changed is the remediated dialogue.
|
| 7 |
+
|
| 8 |
+
Writes out/C3_remediated.jsonl (canonical files untouched).
|
| 9 |
+
Run from repo root: python -u temp/story_remediation/run_c3_remediated.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json, logging, sys
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import yaml
|
| 17 |
+
|
| 18 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 19 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
ROOT = HERE.parents[2]
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
|
| 25 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 26 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 27 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 28 |
+
|
| 29 |
+
OUT = HERE / "out"
|
| 30 |
+
REMED = OUT / "trajectories_v2.jsonl"
|
| 31 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 32 |
+
RESULT = OUT / "C3_v2.jsonl"
|
| 33 |
+
|
| 34 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 35 |
+
SAMPLES = 3
|
| 36 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 37 |
+
|
| 38 |
+
base = {}
|
| 39 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 40 |
+
if line.strip():
|
| 41 |
+
d = json.loads(line)
|
| 42 |
+
base[d["item_id"]] = d
|
| 43 |
+
|
| 44 |
+
reals = P.real_trajectories()
|
| 45 |
+
pairer = P.make_pairer(reals)
|
| 46 |
+
judge = make_judge(cfg["model"])
|
| 47 |
+
fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def judge_one(fake):
|
| 51 |
+
eid = fake["example_id"]
|
| 52 |
+
b = base.get(eid)
|
| 53 |
+
real = pairer(fake)
|
| 54 |
+
# reuse baseline orientation: answer_key A => swap False, B => swap True
|
| 55 |
+
swap = (b or {}).get("answer_key") == "B"
|
| 56 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 57 |
+
key = msgs["answer_key"]
|
| 58 |
+
guesses, err = [], None
|
| 59 |
+
for _ in range(SAMPLES):
|
| 60 |
+
try:
|
| 61 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 62 |
+
guesses.append(r.get("guess"))
|
| 63 |
+
except Exception as e: # noqa: BLE001
|
| 64 |
+
err = str(e)
|
| 65 |
+
if not guesses:
|
| 66 |
+
return {"item_id": eid, "error": err, "answer_key": key,
|
| 67 |
+
"real_id": real.get("example_id")}
|
| 68 |
+
majority = Counter(guesses).most_common(1)[0][0]
|
| 69 |
+
agree = guesses.count(majority) / len(guesses)
|
| 70 |
+
return {"item_id": eid, "answer_key": key, "real_id": real.get("example_id"),
|
| 71 |
+
"baseline_real_id": (b or {}).get("real_id"),
|
| 72 |
+
"guess": majority, "agreement": agree, "n_samples": len(guesses),
|
| 73 |
+
"sample_guesses": guesses, "caught": majority == key,
|
| 74 |
+
"baseline_caught": (b or {}).get("caught"), "error": None}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def main():
|
| 78 |
+
print(f"judging {len(fakes)} remediated rows (samples={SAMPLES}, workers={WORKERS}, "
|
| 79 |
+
f"model={cfg['model']['label']})")
|
| 80 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 81 |
+
results = list(ex.map(judge_one, fakes))
|
| 82 |
+
results.sort(key=lambda r: r["item_id"])
|
| 83 |
+
RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8")
|
| 84 |
+
|
| 85 |
+
ok = [r for r in results if r.get("error") is None and "caught" in r]
|
| 86 |
+
errs = [r for r in results if r.get("error") is not None or "caught" not in r]
|
| 87 |
+
caught = sum(1 for r in ok if r["caught"])
|
| 88 |
+
n = len(ok)
|
| 89 |
+
base_caught = sum(1 for r in ok if r.get("baseline_caught"))
|
| 90 |
+
pair_match = sum(1 for r in ok if r.get("real_id") == r.get("baseline_real_id"))
|
| 91 |
+
flip_fixed = sum(1 for r in ok if r.get("baseline_caught") and not r["caught"])
|
| 92 |
+
flip_regress = sum(1 for r in ok if not r.get("baseline_caught") and r["caught"])
|
| 93 |
+
|
| 94 |
+
print("\n=== C3 V2 (ADD-TURNS) RESULT ===")
|
| 95 |
+
print(f" rows judged : {n} errors: {len(errs)}")
|
| 96 |
+
print(f" pairing match base : {pair_match}/{n}")
|
| 97 |
+
print(f" baseline caught : {base_caught}/{n} = {base_caught/n:.1%}")
|
| 98 |
+
print(f" remediated caught : {caught}/{n} = {caught/n:.1%}")
|
| 99 |
+
print(f" fixed (caught->fooled) : {flip_fixed}")
|
| 100 |
+
print(f" regressed (fooled->caught): {flip_regress}")
|
| 101 |
+
print(f" wrote {RESULT.relative_to(ROOT)}")
|
| 102 |
+
if errs:
|
| 103 |
+
print(" sample error:", errs[0].get("error"))
|
| 104 |
+
return 0
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
raise SystemExit(main())
|
| 109 |
+
|
tempscripts/story_remediation/analyze_caught.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Capture C3 reasoning for the STILL-CAUGHT remediated rows, then bucket the
|
| 2 |
+
tells so we can see what C3 is still catching them on.
|
| 3 |
+
|
| 4 |
+
Rebuilds the exact same prompt/orientation used in the scored run (baseline
|
| 5 |
+
answer_key), calls the judge once per row for its reasoning, writes
|
| 6 |
+
out/C3_remediated_caught_reasons.jsonl, and prints a tell-bucket histogram.
|
| 7 |
+
|
| 8 |
+
Run: python -u temp/story_remediation/analyze_caught.py
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
import json, logging, re, sys
|
| 12 |
+
from collections import Counter
|
| 13 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import yaml
|
| 16 |
+
|
| 17 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 18 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 19 |
+
|
| 20 |
+
HERE = Path(__file__).resolve().parent
|
| 21 |
+
ROOT = HERE.parents[1]
|
| 22 |
+
sys.path.insert(0, str(ROOT))
|
| 23 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 24 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 25 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 26 |
+
|
| 27 |
+
OUT = HERE / "out"
|
| 28 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 29 |
+
base = {json.loads(l)["item_id"]: json.loads(l)
|
| 30 |
+
for l in open(ROOT / "datasetreview" / "results" / "new" / "C3.jsonl", encoding="utf-8") if l.strip()}
|
| 31 |
+
remed = {r["example_id"]: r for r in
|
| 32 |
+
(json.loads(l) for l in open(OUT / "trajectories_remediated.jsonl", encoding="utf-8") if l.strip())}
|
| 33 |
+
scored = {json.loads(l)["item_id"]: json.loads(l)
|
| 34 |
+
for l in open(OUT / "C3_remediated.jsonl", encoding="utf-8") if l.strip()}
|
| 35 |
+
caught_ids = [iid for iid, r in scored.items() if r.get("caught")]
|
| 36 |
+
|
| 37 |
+
reals = P.real_trajectories()
|
| 38 |
+
pairer = P.make_pairer(reals)
|
| 39 |
+
judge = make_judge(cfg["model"])
|
| 40 |
+
|
| 41 |
+
# tell buckets -> keyword patterns matched against reasoning about the fake side
|
| 42 |
+
BUCKETS = {
|
| 43 |
+
"bundled_multitask": r"multi[- ]?task|multiple (distinct|separate) |several (distinct|requests)|checklist|enumerat|packs|laundry list|bundl",
|
| 44 |
+
"too_precise_ids": r"exact (order|id|item)|precise|order number|conveniently|front[- ]?load|all the details|specific ids|recites|recite",
|
| 45 |
+
"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)",
|
| 46 |
+
"invented_capability": r"unusual (request|task|service)|would not (typically|normally)|no real|not (a )?(typical|standard|common)|niche|obscure|rare (request|service)|atypical",
|
| 47 |
+
"agent_overconfident": r"agent (volunteer|claims|asserts|states)|policy|without (verif|confirm|authenticat)|overconfident|too confident|proactively",
|
| 48 |
+
"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",
|
| 49 |
+
"verification_flow": r"verif|authenticat|identity|name and zip|otp|one[- ]?time code",
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def which_side_is_fake(key):
|
| 54 |
+
return "A" if key == "A" else "B"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def one(iid):
|
| 58 |
+
fake = remed[iid]; b = base.get(iid)
|
| 59 |
+
real = pairer(fake)
|
| 60 |
+
swap = (b or {}).get("answer_key") == "B"
|
| 61 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 62 |
+
try:
|
| 63 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 64 |
+
except Exception as e: # noqa
|
| 65 |
+
return {"item_id": iid, "error": str(e)}
|
| 66 |
+
return {"item_id": iid, "answer_key": msgs["answer_key"], "guess": r.get("guess"),
|
| 67 |
+
"confidence": r.get("confidence"), "reasoning": r.get("reasoning", ""),
|
| 68 |
+
"fake_side": which_side_is_fake(msgs["answer_key"])}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def main():
|
| 72 |
+
print(f"capturing reasoning for {len(caught_ids)} still-caught rows...")
|
| 73 |
+
with ThreadPoolExecutor(max_workers=8) as ex:
|
| 74 |
+
res = list(ex.map(one, caught_ids))
|
| 75 |
+
res = [r for r in res if not r.get("error")]
|
| 76 |
+
(OUT / "C3_remediated_caught_reasons.jsonl").write_text(
|
| 77 |
+
"\n".join(json.dumps(r) for r in res) + "\n", encoding="utf-8")
|
| 78 |
+
|
| 79 |
+
bucket = Counter(); multi = Counter(); conf = Counter()
|
| 80 |
+
per_row = []
|
| 81 |
+
for r in res:
|
| 82 |
+
txt = (r.get("reasoning") or "").lower()
|
| 83 |
+
conf[r.get("confidence")] += 1
|
| 84 |
+
hits = [name for name, pat in BUCKETS.items() if re.search(pat, txt)]
|
| 85 |
+
if not hits:
|
| 86 |
+
hits = ["other_unbucketed"]
|
| 87 |
+
for h in hits:
|
| 88 |
+
bucket[h] += 1
|
| 89 |
+
multi[len(hits)] += 1
|
| 90 |
+
per_row.append((r["item_id"], r.get("confidence"), hits))
|
| 91 |
+
|
| 92 |
+
n = len(res)
|
| 93 |
+
print(f"\nreasoning captured: {n} (confidence: {dict(conf)})")
|
| 94 |
+
print("\n=== WHY STILL CAUGHT: tell buckets (rows whose reasoning cites each; multi-count) ===")
|
| 95 |
+
for name, c in bucket.most_common():
|
| 96 |
+
print(f" {name:22s} {c:3d} ({c/n:.0%})")
|
| 97 |
+
print("\n=== tells per row ===", dict(sorted(multi.items())))
|
| 98 |
+
# sample a few high-confidence catches verbatim
|
| 99 |
+
print("\n=== sample HIGH-confidence catches (verbatim reasoning) ===")
|
| 100 |
+
hi = [r for r in res if r.get("confidence") == "high"][:6]
|
| 101 |
+
for r in hi:
|
| 102 |
+
print(f"\n[{r['item_id']}] fake={r['fake_side']} guess={r['guess']}")
|
| 103 |
+
print(" " + (r.get("reasoning") or "")[:400])
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
main()
|
tempscripts/story_remediation/build_join.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Join every C3 result row to its confuser story and the EXACT text C3 judged.
|
| 2 |
+
|
| 3 |
+
For each caught row we emit: item_id, tool, real_id, confidence, the judge's
|
| 4 |
+
reasoning, the query, a compact history view, the rendered C3 conversation, and
|
| 5 |
+
tell tags (keyword-derived from the reasoning). Also emits an uncaught set so we
|
| 6 |
+
can study what already fools C3.
|
| 7 |
+
|
| 8 |
+
Run from repo root: python -u temp/story_remediation/build_join.py
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import sys
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 17 |
+
sys.path.insert(0, str(ROOT))
|
| 18 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 19 |
+
|
| 20 |
+
OUT = Path(__file__).resolve().parent / "out"
|
| 21 |
+
C3 = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 22 |
+
TRAJ = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _rows(p: Path):
|
| 26 |
+
return [json.loads(l) for l in p.read_text(encoding="utf-8").splitlines() if l.strip()]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
TELLS = {
|
| 30 |
+
"bundled_checklist": ("bundl", "packs", "checklist", "enumerat", "multiple distinct",
|
| 31 |
+
"multi-task", "one turn", "one message", "exercise many",
|
| 32 |
+
"exercise multiple", "one-to-one", "stack", "all at once",
|
| 33 |
+
"everything at once", "comprehensive", "front-load"),
|
| 34 |
+
"no_verification": ("verificat", "authenticat", "identity", "without verif",
|
| 35 |
+
"skips ident", "glossed", "no auth"),
|
| 36 |
+
"over_precise_ids": ("precise", "exact order", "exact item", "id-laden", "unprompted",
|
| 37 |
+
"conveniently", "verbatim", "recite", "specific order number"),
|
| 38 |
+
"agent_burst_no_confirm": ("fires", "burst", "no confirmation", "no intermediate",
|
| 39 |
+
"without confirm", "batch of tool", "silently", "no clarif",
|
| 40 |
+
"many tool call", "rapid sequence"),
|
| 41 |
+
"terse_closer": ("taken care of", "all set", "that's handled", "done.", "what else",
|
| 42 |
+
"formulaic", "terse"),
|
| 43 |
+
"duplicate_request": ("redundant", "restate", "re-asks", "re-state", "twice",
|
| 44 |
+
"double-statement", "identical repeated", "repeats the"),
|
| 45 |
+
"invented_capability": ("unusual", "atypical", "don't typically", "invent",
|
| 46 |
+
"doesn't typically", "not typically", "uncommon", "rarely"),
|
| 47 |
+
"sequential_orders": ("sequential", "conveniently formatted", "clean order number"),
|
| 48 |
+
"scripted_flavor": ("scripted", "staged", "stagey", "stilted", "canned", "test prompt",
|
| 49 |
+
"task prompt", "flavor text", "persona"),
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def tag(reason: str) -> list[str]:
|
| 54 |
+
r = reason.lower()
|
| 55 |
+
return [k for k, ws in TELLS.items() if any(w in r for w in ws)]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def hist_view(story: dict):
|
| 59 |
+
out = []
|
| 60 |
+
for m in story.get("history") or []:
|
| 61 |
+
if m.get("role") == "tool":
|
| 62 |
+
continue
|
| 63 |
+
out.append({"role": m.get("role"),
|
| 64 |
+
"content": (m.get("content") or "").strip(),
|
| 65 |
+
"n_tool_calls": len(m.get("tool_calls") or [])})
|
| 66 |
+
return out
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main() -> int:
|
| 70 |
+
c3 = _rows(C3)
|
| 71 |
+
traj = {t["example_id"]: t for t in _rows(TRAJ)}
|
| 72 |
+
caught, fooled = [], []
|
| 73 |
+
missing = 0
|
| 74 |
+
for r in c3:
|
| 75 |
+
iid = r["item_id"]
|
| 76 |
+
story = traj.get(iid)
|
| 77 |
+
if story is None:
|
| 78 |
+
missing += 1
|
| 79 |
+
continue
|
| 80 |
+
parts = iid.split("-")
|
| 81 |
+
tool = parts[1] if len(parts) >= 3 else "?"
|
| 82 |
+
rec = {
|
| 83 |
+
"item_id": iid,
|
| 84 |
+
"tool": tool,
|
| 85 |
+
"real_id": r.get("real_id"),
|
| 86 |
+
"caught": bool(r.get("caught")),
|
| 87 |
+
"confidence": (r.get("result") or {}).get("confidence"),
|
| 88 |
+
"reasoning": (r.get("result") or {}).get("reasoning") or "",
|
| 89 |
+
"tells": tag((r.get("result") or {}).get("reasoning") or ""),
|
| 90 |
+
"n_calls": len(story.get("calls") or []),
|
| 91 |
+
"n_hist_turns": len(hist_view(story)),
|
| 92 |
+
"query": (story.get("query") or story.get("retrieval_text") or "").strip(),
|
| 93 |
+
"history": hist_view(story),
|
| 94 |
+
"c3_view": J.render_trajectory(story, blind_tools=True,
|
| 95 |
+
include_metadata=False, conversation_only=True),
|
| 96 |
+
}
|
| 97 |
+
(caught if rec["caught"] else fooled).append(rec)
|
| 98 |
+
|
| 99 |
+
(OUT / "caught_rows.jsonl").write_text(
|
| 100 |
+
"\n".join(json.dumps(r, ensure_ascii=False) for r in caught) + "\n", encoding="utf-8")
|
| 101 |
+
(OUT / "fooled_rows.jsonl").write_text(
|
| 102 |
+
"\n".join(json.dumps(r, ensure_ascii=False) for r in fooled) + "\n", encoding="utf-8")
|
| 103 |
+
|
| 104 |
+
from collections import Counter
|
| 105 |
+
tally = Counter(t for r in caught for t in r["tells"])
|
| 106 |
+
notag = sum(1 for r in caught if not r["tells"])
|
| 107 |
+
print(f"caught={len(caught)} fooled={len(fooled)} missing_story={missing}")
|
| 108 |
+
print(f"caught rows with NO tell tag: {notag}")
|
| 109 |
+
print("tell frequency among caught:")
|
| 110 |
+
for k, v in tally.most_common():
|
| 111 |
+
print(f" {v:4d} {k}")
|
| 112 |
+
# history presence
|
| 113 |
+
openers = sum(1 for r in caught if r["n_hist_turns"] == 0)
|
| 114 |
+
print(f"caught openers (no history): {openers} | caught with history: {len(caught)-openers}")
|
| 115 |
+
return 0
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
raise SystemExit(main())
|
tempscripts/story_remediation/build_remediated.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Parse PROPOSALS.md -> build remediated n100 trajectories (temp only).
|
| 2 |
+
|
| 3 |
+
For each of the 514 caught rows the proposal supplies:
|
| 4 |
+
* history_insert : the enriched dialogue turns (replace probe/checklist NL turns)
|
| 5 |
+
* A : the reworded harvested query
|
| 6 |
+
|
| 7 |
+
Remediation build (C3 only sees dialogue + blinded call markers):
|
| 8 |
+
new history = [original turns that carry tool_calls] (verification realism kept)
|
| 9 |
+
+ history_insert turns (enriched NL dialogue)
|
| 10 |
+
new query = A
|
| 11 |
+
calls / metadata : unchanged
|
| 12 |
+
Closer is NOT rendered by C3 (it lands after the calls) so it is ignored here.
|
| 13 |
+
|
| 14 |
+
Writes out/trajectories_remediated.jsonl and prints parse stats.
|
| 15 |
+
Run: python -u temp/story_remediation/build_remediated.py
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
import json, re, sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
ROOT = HERE.parents[1]
|
| 23 |
+
PROPOSALS = HERE / "PROPOSALS.md"
|
| 24 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 25 |
+
OUT = HERE / "out" / "trajectories_remediated.jsonl"
|
| 26 |
+
|
| 27 |
+
HEADER = re.compile(r"^###\s*\d+\.\s*`([^`]+)`")
|
| 28 |
+
TURN = re.compile(r"^>\s*\[(user|assistant)\]\s*(.*)$")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _clean(text: str) -> str:
|
| 32 |
+
t = text.strip()
|
| 33 |
+
# drop a leading marker like **A:** / **query_after:**
|
| 34 |
+
t = re.sub(r"^\*\*[^*]+\*\*\s*", "", t).strip()
|
| 35 |
+
# strip surrounding *italics* and quotes
|
| 36 |
+
t = t.strip()
|
| 37 |
+
t = re.sub(r"^\*+", "", t)
|
| 38 |
+
t = re.sub(r"\*+$", "", t).strip()
|
| 39 |
+
t = t.strip('"\u201c\u201d ').strip()
|
| 40 |
+
return t
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_blocks(md: str):
|
| 44 |
+
lines = md.splitlines()
|
| 45 |
+
blocks = {}
|
| 46 |
+
cur = None
|
| 47 |
+
for ln in lines:
|
| 48 |
+
m = HEADER.match(ln)
|
| 49 |
+
if m:
|
| 50 |
+
cur = {"example_id": m.group(1), "insert": [], "A": None}
|
| 51 |
+
blocks[m.group(1)] = cur
|
| 52 |
+
continue
|
| 53 |
+
if cur is None:
|
| 54 |
+
continue
|
| 55 |
+
tm = TURN.match(ln)
|
| 56 |
+
if tm:
|
| 57 |
+
cur["insert"].append({"role": tm.group(1), "content": tm.group(2).strip()})
|
| 58 |
+
continue
|
| 59 |
+
s = ln.strip()
|
| 60 |
+
am = re.match(r"^\*\*A\b.*?:\*\*\s*(.*)$", s)
|
| 61 |
+
if am:
|
| 62 |
+
cur["A"] = _clean(am.group(1))
|
| 63 |
+
elif s.startswith("**query_after:**"):
|
| 64 |
+
cur["A"] = _clean(s)
|
| 65 |
+
return blocks
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _is_note(a: str | None) -> bool:
|
| 69 |
+
if not a:
|
| 70 |
+
return True
|
| 71 |
+
t = a.strip().strip('"').strip()
|
| 72 |
+
return t.startswith("(") or "folded into" in t.lower() or "resolved in the exchange" in t.lower() \
|
| 73 |
+
or "resolved in the verification" in t.lower()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def main():
|
| 77 |
+
md = PROPOSALS.read_text(encoding="utf-8")
|
| 78 |
+
blocks = parse_blocks(md)
|
| 79 |
+
orig = {}
|
| 80 |
+
for l in N100.open(encoding="utf-8"):
|
| 81 |
+
if l.strip():
|
| 82 |
+
d = json.loads(l)
|
| 83 |
+
orig[d["example_id"]] = d
|
| 84 |
+
|
| 85 |
+
made, miss_orig, no_A, no_insert, promoted = [], [], 0, 0, []
|
| 86 |
+
for eid, blk in blocks.items():
|
| 87 |
+
if eid not in orig:
|
| 88 |
+
miss_orig.append(eid); continue
|
| 89 |
+
o = orig[eid]
|
| 90 |
+
hist = o.get("history") or (o.get("metadata") or {}).get("history") or []
|
| 91 |
+
tool_turns = [m for m in hist if m.get("tool_calls")]
|
| 92 |
+
insert = list(blk["insert"])
|
| 93 |
+
query = blk["A"]
|
| 94 |
+
# If A is a scaffolding note (query was "folded into" history), promote the
|
| 95 |
+
# last inserted USER turn to be the harvested query and drop it from history.
|
| 96 |
+
if _is_note(query):
|
| 97 |
+
last_user = next((i for i in range(len(insert) - 1, -1, -1)
|
| 98 |
+
if insert[i]["role"] == "user"), None)
|
| 99 |
+
if last_user is not None:
|
| 100 |
+
query = insert.pop(last_user)["content"]
|
| 101 |
+
promoted.append(eid)
|
| 102 |
+
else:
|
| 103 |
+
query = o.get("query")
|
| 104 |
+
if not query:
|
| 105 |
+
no_A += 1; query = o.get("query")
|
| 106 |
+
if not insert:
|
| 107 |
+
no_insert += 1
|
| 108 |
+
insert_turns = [{"role": t["role"], "content": t["content"],
|
| 109 |
+
"tool_calls": [], "tool_call_id": None} for t in insert]
|
| 110 |
+
new_hist = tool_turns + insert_turns
|
| 111 |
+
row = dict(o)
|
| 112 |
+
row["history"] = new_hist
|
| 113 |
+
if row.get("metadata"):
|
| 114 |
+
row["metadata"] = dict(row["metadata"]); row["metadata"]["history"] = new_hist
|
| 115 |
+
row["query"] = query
|
| 116 |
+
row["retrieval_text"] = query
|
| 117 |
+
made.append(row)
|
| 118 |
+
|
| 119 |
+
OUT.parent.mkdir(parents=True, exist_ok=True)
|
| 120 |
+
with OUT.open("w", encoding="utf-8") as fh:
|
| 121 |
+
for r in made:
|
| 122 |
+
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 123 |
+
|
| 124 |
+
print(f"proposal blocks : {len(blocks)}")
|
| 125 |
+
print(f"built rows : {len(made)}")
|
| 126 |
+
print(f"missing in n100 : {len(miss_orig)} {miss_orig[:8]}")
|
| 127 |
+
print(f"promoted note->query : {len(promoted)} {promoted}")
|
| 128 |
+
print(f"blocks w/o A : {no_A}")
|
| 129 |
+
print(f"blocks w/o insert: {no_insert}")
|
| 130 |
+
print(f"wrote : {OUT.relative_to(ROOT)}")
|
| 131 |
+
# spot check
|
| 132 |
+
for r in made[:2]:
|
| 133 |
+
print("\n--- sample", r["example_id"])
|
| 134 |
+
for m in r["history"]:
|
| 135 |
+
tc = " [TOOLCALL]" if m.get("tool_calls") else ""
|
| 136 |
+
print(f" [{m['role']}]{tc} {(m.get('content') or '')[:70]}")
|
| 137 |
+
print(" QUERY:", r["query"][:90])
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
main()
|
tempscripts/story_remediation/next_batch.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Print the next N caught rows not yet in out/done_ids.txt, with everything
|
| 2 |
+
needed to author a bespoke remediation proposal. Usage:
|
| 3 |
+
python temp/story_remediation/next_batch.py [N]
|
| 4 |
+
"""
|
| 5 |
+
import json, sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
HERE = Path(__file__).resolve().parent
|
| 9 |
+
OUT = HERE / "out"
|
| 10 |
+
N = int(sys.argv[1]) if len(sys.argv) > 1 else 20
|
| 11 |
+
|
| 12 |
+
done = set()
|
| 13 |
+
p = OUT / "done_ids.txt"
|
| 14 |
+
if p.exists():
|
| 15 |
+
done = {l.strip() for l in p.read_text(encoding="utf-8").splitlines() if l.strip()}
|
| 16 |
+
|
| 17 |
+
rows = [json.loads(l) for l in (OUT / "caught_rows.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()]
|
| 18 |
+
pending = [r for r in rows if r["item_id"] not in done]
|
| 19 |
+
print(f"# done={len(done)} pending={len(pending)} showing next {min(N,len(pending))}")
|
| 20 |
+
for r in pending[:N]:
|
| 21 |
+
print("=" * 100)
|
| 22 |
+
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"]}')
|
| 23 |
+
print("QUERY:", r["query"])
|
| 24 |
+
print("REASON:", r["reasoning"])
|
| 25 |
+
# show the history dialogue so re-staging fits the existing flow
|
| 26 |
+
for h in r["history"]:
|
| 27 |
+
tc = f" [+{h['n_tool_calls']} tool_calls]" if h["n_tool_calls"] else ""
|
| 28 |
+
c = h["content"][:220] if h["content"] else ""
|
| 29 |
+
print(f' ({h["role"]}){tc}: {c}')
|
tempscripts/story_remediation/replay_remediated.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Free-running state runthrough on the REMEDIATED trajectories.
|
| 2 |
+
|
| 3 |
+
Reuses the exact executor (fake_state + fake_tools + catalog) from
|
| 4 |
+
systemUpgrade/executor, but seeds/replays from our remediated file. Since the
|
| 5 |
+
remediation changed ONLY dialogue (history + query) and never `calls`, this must
|
| 6 |
+
reproduce recorded outputs at the same rate as baseline -- any new mismatch/EXC
|
| 7 |
+
would be a logic or I/O regression introduced by the rewrite.
|
| 8 |
+
|
| 9 |
+
Also cross-checks each remediated row's calls are byte-identical to the source
|
| 10 |
+
n100 row (proves no floating vars / dropped IDs leaked into calls).
|
| 11 |
+
|
| 12 |
+
Run from repo root: python -u temp/story_remediation/replay_remediated.py
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
import json, sys
|
| 16 |
+
from collections import Counter, defaultdict
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 20 |
+
EXEC = ROOT / "systemUpgrade" / "executor"
|
| 21 |
+
sys.path.insert(0, str(EXEC))
|
| 22 |
+
from fake_state import EpisodeState # noqa: E402
|
| 23 |
+
from fake_tools import TOOLS # noqa: E402
|
| 24 |
+
|
| 25 |
+
catalog = json.load(open(EXEC / "catalog.json", encoding="utf-8"))
|
| 26 |
+
REMED = ROOT / "temp" / "story_remediation" / "out" / "trajectories_remediated.jsonl"
|
| 27 |
+
SRC = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 28 |
+
|
| 29 |
+
rem = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()]
|
| 30 |
+
src = {json.loads(l)["example_id"]: json.loads(l)
|
| 31 |
+
for l in open(SRC, encoding="utf-8") if l.strip()}
|
| 32 |
+
|
| 33 |
+
# 1) calls integrity: remediated calls must equal source calls exactly
|
| 34 |
+
calls_diff = [r["example_id"] for r in rem
|
| 35 |
+
if json.dumps(r["calls"], sort_keys=True) != json.dumps(src[r["example_id"]]["calls"], sort_keys=True)]
|
| 36 |
+
|
| 37 |
+
# reuse replay.py's CHECK/FULLMATCH/FIND config
|
| 38 |
+
import importlib.util
|
| 39 |
+
spec = importlib.util.spec_from_file_location("_replay", EXEC / "replay.py")
|
| 40 |
+
# can't exec replay.py (it runs on import); inline the needed maps instead:
|
| 41 |
+
FULLMATCH = {"get_product_details", "get_size_guide", "get_product_reviews", "get_item_details",
|
| 42 |
+
"get_warranty_details", "get_extended_warranty_options", "get_shipping_options",
|
| 43 |
+
"get_active_promotions", "list_all_product_types", "get_user_reviews", "get_order_invoice"}
|
| 44 |
+
FIND = {"find_user_id_by_email", "find_user_id_by_phone", "find_user_id_by_username", "find_user_id_by_name_zip"}
|
| 45 |
+
CHECK = {
|
| 46 |
+
"apply_gift_card": ["amount_applied", "remaining_balance_due"], "apply_discount_code": ["discount", "status"],
|
| 47 |
+
"checkout_cart": ["total"], "cancel_order_item": ["status", "item_id"],
|
| 48 |
+
"return_pending_order_items": ["status", "item_ids"], "return_delivered_order_items": ["status", "item_ids"],
|
| 49 |
+
"exchange_delivered_order_items": ["status"], "modify_pending_order_items": [],
|
| 50 |
+
"remove_item_from_cart": ["subtotal"], "add_item_to_cart": ["user_id"], "get_order_details": ["status"],
|
| 51 |
+
"get_user_details": ["user_id", "email"], "get_cart_contents": ["subtotal"], "get_gift_card_balance": ["balance"],
|
| 52 |
+
"get_loyalty_points_balance": ["points"], "get_store_credit_balance": ["balance"], "get_wishlist": ["items"],
|
| 53 |
+
"cancel_delivered_order": ["status", "refund"], "cancel_pending_order": ["status", "refund"],
|
| 54 |
+
"modify_pending_order_address": ["status"], "add_gift_message": ["gift_message"],
|
| 55 |
+
"schedule_delivery": ["scheduled_delivery", "status"], "set_delivery_instructions": ["delivery_instructions", "status"],
|
| 56 |
+
"schedule_installation": ["appointment_id"], "book_repair_appointment": ["appointment_id"],
|
| 57 |
+
"request_return_pickup": ["confirmation"], "get_return_label": ["label_url"],
|
| 58 |
+
"request_gift_receipt": ["gift_receipt_url", "prices_shown"],
|
| 59 |
+
"file_shipping_insurance_claim": ["claim_id", "status", "estimated_review_days"],
|
| 60 |
+
"upgrade_shipping_speed": ["shipping_speed", "status"], "split_order_shipment": ["status"],
|
| 61 |
+
"request_price_adjustment": ["status"], "request_price_match": ["item_id"],
|
| 62 |
+
"reorder_previous_order": ["duplicated_from", "status", "total"], "register_product_warranty": [],
|
| 63 |
+
"submit_product_review": [], "subscribe_to_restock_alert": [], "redeem_loyalty_points": ["points_redeemed", "credit"],
|
| 64 |
+
"purchase_gift_card": ["amount"], "add_to_wishlist": ["user_id"], "modify_user_email": ["status", "email"],
|
| 65 |
+
"modify_user_name": ["status"], "modify_user_phone": ["status", "phone"], "update_user_password": ["status"],
|
| 66 |
+
"add_user_address": ["status"], "modify_user_address": ["status"], "delete_user_address": ["status", "deleted_zip"],
|
| 67 |
+
"verify_user_identity": ["verified"],
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def parse(o):
|
| 72 |
+
try:
|
| 73 |
+
return json.loads(o) if isinstance(o, str) else o
|
| 74 |
+
except json.JSONDecodeError:
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
stats = defaultdict(lambda: {"n": 0, "match": 0, "skip_nodata": 0, "mism": [], "exc": []})
|
| 79 |
+
covered, uncovered = Counter(), Counter()
|
| 80 |
+
|
| 81 |
+
for r in rem:
|
| 82 |
+
s = EpisodeState.from_trajectory(r, catalog)
|
| 83 |
+
for c in r["calls"]:
|
| 84 |
+
n = c["name"]
|
| 85 |
+
if n not in TOOLS:
|
| 86 |
+
uncovered[n] += 1
|
| 87 |
+
continue
|
| 88 |
+
covered[n] += 1
|
| 89 |
+
rec = parse(c.get("output"))
|
| 90 |
+
st = stats[n]
|
| 91 |
+
st["n"] += 1
|
| 92 |
+
try:
|
| 93 |
+
got = TOOLS[n](s, c.get("arguments", {}))
|
| 94 |
+
except Exception as e: # noqa
|
| 95 |
+
st["exc"].append((r["example_id"], f"{type(e).__name__}: {e}"))
|
| 96 |
+
continue
|
| 97 |
+
if n in FIND:
|
| 98 |
+
if got == (c.get("output") or "").strip().strip('"'):
|
| 99 |
+
st["match"] += 1
|
| 100 |
+
else:
|
| 101 |
+
st["mism"].append((r["example_id"], {"uid": (got, c.get("output"))}))
|
| 102 |
+
continue
|
| 103 |
+
if not isinstance(rec, dict):
|
| 104 |
+
st["match"] += 1
|
| 105 |
+
continue
|
| 106 |
+
if n in FULLMATCH:
|
| 107 |
+
st["match"] += 1 if got == rec else st["mism"].append((r["example_id"], "dict-diff"))
|
| 108 |
+
if got == rec:
|
| 109 |
+
pass
|
| 110 |
+
continue
|
| 111 |
+
keys = CHECK.get(n, [])
|
| 112 |
+
if any(got.get(k) is None and rec.get(k) is not None for k in keys):
|
| 113 |
+
st["skip_nodata"] += 1
|
| 114 |
+
continue
|
| 115 |
+
|
| 116 |
+
def _eq(k):
|
| 117 |
+
g, rv = got.get(k), rec.get(k)
|
| 118 |
+
if k == "status" and isinstance(g, str) and isinstance(rv, str):
|
| 119 |
+
return g.replace(" ", "_") == rv.replace(" ", "_")
|
| 120 |
+
return g == rv
|
| 121 |
+
if all(_eq(k) for k in keys):
|
| 122 |
+
st["match"] += 1
|
| 123 |
+
else:
|
| 124 |
+
st["mism"].append((r["example_id"], {k: (got.get(k), rec.get(k)) for k in keys if not _eq(k)}))
|
| 125 |
+
|
| 126 |
+
tot_chk = sum(st["n"] - st["skip_nodata"] for st in stats.values())
|
| 127 |
+
tot_match = sum(st["match"] for st in stats.values())
|
| 128 |
+
tot_exc = sum(len(st["exc"]) for st in stats.values())
|
| 129 |
+
tot_mism = sum(len(st["mism"]) for st in stats.values())
|
| 130 |
+
tot_skip = sum(st["skip_nodata"] for st in stats.values())
|
| 131 |
+
|
| 132 |
+
print("=== CALLS INTEGRITY (remediated vs source n100) ===")
|
| 133 |
+
print(f" rows: {len(rem)} calls differ from source: {len(calls_diff)} {calls_diff[:5]}")
|
| 134 |
+
print("\n=== FREE-RUNNING REPLAY (remediated trajectories) ===")
|
| 135 |
+
print(f" reproduced : {tot_match}/{tot_chk} = {tot_match/max(tot_chk,1):.1%}")
|
| 136 |
+
print(f" exceptions : {tot_exc}")
|
| 137 |
+
print(f" mismatches : {tot_mism}")
|
| 138 |
+
print(f" skipped-no-seed : {tot_skip}")
|
| 139 |
+
print(f" tools implemented/exercised : {len(stats)} uncovered(echo) calls: {sum(uncovered.values())}")
|
| 140 |
+
if tot_exc:
|
| 141 |
+
print("\n -- EXCEPTIONS --")
|
| 142 |
+
for n, st in sorted(stats.items()):
|
| 143 |
+
for eid, msg in st["exc"][:5]:
|
| 144 |
+
print(f" [{n}] {eid}: {msg}")
|
| 145 |
+
if tot_mism:
|
| 146 |
+
print("\n -- MISMATCHES --")
|
| 147 |
+
for n, st in sorted(stats.items()):
|
| 148 |
+
for eid, d in st["mism"][:5]:
|
| 149 |
+
print(f" [{n}] {eid}: {d}")
|
tempscripts/story_remediation/run_c3_remediated.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run C3 on the remediated trajectories and compare to baseline.
|
| 2 |
+
|
| 3 |
+
Same judge procedure as the baseline C3 pass (samples=3 majority, workers from
|
| 4 |
+
config, model from datasetreview/config.yaml). For a controlled before/after we
|
| 5 |
+
reuse each row's BASELINE pairing + orientation (answer_key) so the ONLY thing
|
| 6 |
+
that changed is the remediated dialogue.
|
| 7 |
+
|
| 8 |
+
Writes out/C3_remediated.jsonl (canonical files untouched).
|
| 9 |
+
Run from repo root: python -u temp/story_remediation/run_c3_remediated.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json, logging, sys
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import yaml
|
| 17 |
+
|
| 18 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 19 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
ROOT = HERE.parents[1]
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
|
| 25 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 26 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 27 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 28 |
+
|
| 29 |
+
OUT = HERE / "out"
|
| 30 |
+
REMED = OUT / "trajectories_remediated.jsonl"
|
| 31 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 32 |
+
RESULT = OUT / "C3_remediated.jsonl"
|
| 33 |
+
|
| 34 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 35 |
+
SAMPLES = 3
|
| 36 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 37 |
+
|
| 38 |
+
base = {}
|
| 39 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 40 |
+
if line.strip():
|
| 41 |
+
d = json.loads(line)
|
| 42 |
+
base[d["item_id"]] = d
|
| 43 |
+
|
| 44 |
+
reals = P.real_trajectories()
|
| 45 |
+
pairer = P.make_pairer(reals)
|
| 46 |
+
judge = make_judge(cfg["model"])
|
| 47 |
+
fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def judge_one(fake):
|
| 51 |
+
eid = fake["example_id"]
|
| 52 |
+
b = base.get(eid)
|
| 53 |
+
real = pairer(fake)
|
| 54 |
+
# reuse baseline orientation: answer_key A => swap False, B => swap True
|
| 55 |
+
swap = (b or {}).get("answer_key") == "B"
|
| 56 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 57 |
+
key = msgs["answer_key"]
|
| 58 |
+
guesses, err = [], None
|
| 59 |
+
for _ in range(SAMPLES):
|
| 60 |
+
try:
|
| 61 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 62 |
+
guesses.append(r.get("guess"))
|
| 63 |
+
except Exception as e: # noqa: BLE001
|
| 64 |
+
err = str(e)
|
| 65 |
+
if not guesses:
|
| 66 |
+
return {"item_id": eid, "error": err, "answer_key": key,
|
| 67 |
+
"real_id": real.get("example_id")}
|
| 68 |
+
majority = Counter(guesses).most_common(1)[0][0]
|
| 69 |
+
agree = guesses.count(majority) / len(guesses)
|
| 70 |
+
return {"item_id": eid, "answer_key": key, "real_id": real.get("example_id"),
|
| 71 |
+
"baseline_real_id": (b or {}).get("real_id"),
|
| 72 |
+
"guess": majority, "agreement": agree, "n_samples": len(guesses),
|
| 73 |
+
"sample_guesses": guesses, "caught": majority == key,
|
| 74 |
+
"baseline_caught": (b or {}).get("caught"), "error": None}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def main():
|
| 78 |
+
print(f"judging {len(fakes)} remediated rows (samples={SAMPLES}, workers={WORKERS}, "
|
| 79 |
+
f"model={cfg['model']['label']})")
|
| 80 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 81 |
+
results = list(ex.map(judge_one, fakes))
|
| 82 |
+
results.sort(key=lambda r: r["item_id"])
|
| 83 |
+
RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8")
|
| 84 |
+
|
| 85 |
+
ok = [r for r in results if r.get("error") is None and "caught" in r]
|
| 86 |
+
errs = [r for r in results if r.get("error") is not None or "caught" not in r]
|
| 87 |
+
caught = sum(1 for r in ok if r["caught"])
|
| 88 |
+
n = len(ok)
|
| 89 |
+
base_caught = sum(1 for r in ok if r.get("baseline_caught"))
|
| 90 |
+
pair_match = sum(1 for r in ok if r.get("real_id") == r.get("baseline_real_id"))
|
| 91 |
+
flip_fixed = sum(1 for r in ok if r.get("baseline_caught") and not r["caught"])
|
| 92 |
+
flip_regress = sum(1 for r in ok if not r.get("baseline_caught") and r["caught"])
|
| 93 |
+
|
| 94 |
+
print("\n=== C3 REMEDIATED RESULT ===")
|
| 95 |
+
print(f" rows judged : {n} errors: {len(errs)}")
|
| 96 |
+
print(f" pairing match base : {pair_match}/{n}")
|
| 97 |
+
print(f" baseline caught : {base_caught}/{n} = {base_caught/n:.1%}")
|
| 98 |
+
print(f" remediated caught : {caught}/{n} = {caught/n:.1%}")
|
| 99 |
+
print(f" fixed (caught->fooled) : {flip_fixed}")
|
| 100 |
+
print(f" regressed (fooled->caught): {flip_regress}")
|
| 101 |
+
print(f" wrote {RESULT.relative_to(ROOT)}")
|
| 102 |
+
if errs:
|
| 103 |
+
print(" sample error:", errs[0].get("error"))
|
| 104 |
+
return 0
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
raise SystemExit(main())
|
tempscripts/story_remediation/unbundle/ab_capability_reasons.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Task: take 50 rows whose PRIMARY tell (old prompt) was 'capability/scenario
|
| 2 |
+
realism', re-judge each with BOTH the old C3 prompt and the v2 variant, capturing
|
| 3 |
+
the REASONING from both so we can see what changed and why.
|
| 4 |
+
|
| 5 |
+
Reads out/caught_reasons_v5.jsonl (primary bucket labels), samples 50 from
|
| 6 |
+
A_capability_scenario_realism, judges 1 sample per prompt (reasoning captured),
|
| 7 |
+
prints per-row old-vs-new guess + both rationales, and a thematic summary.
|
| 8 |
+
Saves out/ab_capability_reasons.jsonl.
|
| 9 |
+
|
| 10 |
+
Run: python -u temp/story_remediation/unbundle/ab_capability_reasons.py [N]
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
import json, logging, sys, random, collections
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import yaml
|
| 17 |
+
|
| 18 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 19 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
ROOT = HERE.parents[2]
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 25 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 26 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 27 |
+
|
| 28 |
+
OUT = HERE / "out"
|
| 29 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 30 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 31 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 32 |
+
|
| 33 |
+
reasons = [json.loads(l) for l in open(OUT / "caught_reasons_v5.jsonl", encoding="utf-8") if l.strip()]
|
| 34 |
+
cap = [r for r in reasons if r.get("primary") == "A_capability_scenario_realism" and r.get("sample_caught")]
|
| 35 |
+
fakes = {e["example_id"]: e for e in
|
| 36 |
+
(json.loads(l) for l in open(OUT / "trajectories_all_v5.jsonl", encoding="utf-8") if l.strip())}
|
| 37 |
+
base = {}
|
| 38 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 39 |
+
if line.strip():
|
| 40 |
+
d = json.loads(line); base[d["item_id"]] = d
|
| 41 |
+
|
| 42 |
+
reals = P.real_trajectories()
|
| 43 |
+
pairer = P.make_pairer(reals)
|
| 44 |
+
judge = make_judge(cfg["model"])
|
| 45 |
+
|
| 46 |
+
random.seed(13)
|
| 47 |
+
random.shuffle(cap)
|
| 48 |
+
N = int(sys.argv[1]) if len(sys.argv) > 1 else 50
|
| 49 |
+
sample = cap[:N]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def build(fake, real, swap, variant):
|
| 53 |
+
system, user = J.load_prompt(variant)
|
| 54 |
+
fr = J.render_trajectory(fake, blind_tools=True, include_metadata=False, conversation_only=True)
|
| 55 |
+
rr = J.render_trajectory(real, blind_tools=True, include_metadata=False, conversation_only=True)
|
| 56 |
+
if swap:
|
| 57 |
+
a, b, key = rr, fr, "B"
|
| 58 |
+
else:
|
| 59 |
+
a, b, key = fr, rr, "A"
|
| 60 |
+
user = user.replace("{{CONV_A}}", a).replace("{{CONV_B}}", b)
|
| 61 |
+
return {"system": system, "user": user, "answer_key": key}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def jr(msgs):
|
| 65 |
+
try:
|
| 66 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 67 |
+
return r.get("guess"), (r.get("reasoning") or "").strip()
|
| 68 |
+
except Exception as e: # noqa: BLE001
|
| 69 |
+
return None, f"ERR {e}"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def one(row):
|
| 73 |
+
eid = row["item_id"]; fake = fakes.get(eid)
|
| 74 |
+
if not fake:
|
| 75 |
+
return None
|
| 76 |
+
real = pairer(fake)
|
| 77 |
+
swap = (base.get(eid) or base.get((fake.get("metadata") or {}).get("orig_eid")) or {}).get("answer_key") == "B"
|
| 78 |
+
om = build(fake, real, swap, "C3"); nm = build(fake, real, swap, "C3v2")
|
| 79 |
+
key = om["answer_key"]
|
| 80 |
+
og, orz = jr(om); ng, nrz = jr(nm)
|
| 81 |
+
return {"item_id": eid, "role": row.get("role"), "key": key,
|
| 82 |
+
"old_guess": og, "old_caught": og == key, "old_reason": orz,
|
| 83 |
+
"new_guess": ng, "new_caught": ng == key, "new_reason": nrz}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# does the NEW reasoning still lean on the capability/scenario/auth leak?
|
| 87 |
+
LEAK_KW = ["capab", "unrealistic", "unusual", "atypical", "wouldn't", "implausible",
|
| 88 |
+
"unlikely", "niche", "fabricat", "scripted", "constructed", "staged",
|
| 89 |
+
"designed to", "exercise", "test scenario", "red-team", "red team",
|
| 90 |
+
"benchmark", "probe", "verif", "identity", "authent", "policy", "unrelated"]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def leaky(txt):
|
| 94 |
+
low = (txt or "").lower()
|
| 95 |
+
return any(k in low for k in LEAK_KW)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def main():
|
| 99 |
+
print(f"capability-bucket A/B: {len(sample)} rows (of {len(cap)} in bucket), workers={WORKERS}")
|
| 100 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 101 |
+
rows = [r for r in ex.map(one, sample) if r]
|
| 102 |
+
|
| 103 |
+
oc = sum(r["old_caught"] for r in rows)
|
| 104 |
+
nc = sum(r["new_caught"] for r in rows)
|
| 105 |
+
flip = [r for r in rows if r["old_caught"] and not r["new_caught"]]
|
| 106 |
+
still = [r for r in rows if r["old_caught"] and r["new_caught"]]
|
| 107 |
+
n = len(rows)
|
| 108 |
+
old_leak = sum(leaky(r["old_reason"]) for r in rows)
|
| 109 |
+
new_leak = sum(leaky(r["new_reason"]) for r in rows)
|
| 110 |
+
|
| 111 |
+
print("\n" + "=" * 80)
|
| 112 |
+
print(f"rows: {n} (all had capability/scenario as the OLD primary tell)")
|
| 113 |
+
print(f" OLD catches: {oc}/{n} = {oc/n:.0%} NEW(v2) catches: {nc}/{n} = {nc/n:.0%}")
|
| 114 |
+
print(f" FLIPPED caught->fooled under v2: {len(flip)}/{max(oc,1)} = {len(flip)/max(oc,1):.0%}")
|
| 115 |
+
print(f" still caught by both: {len(still)}")
|
| 116 |
+
print(f" reasoning invoking capability/scenario/auth 'leak' language:")
|
| 117 |
+
print(f" OLD: {old_leak}/{n} = {old_leak/n:.0%} NEW: {new_leak}/{n} = {new_leak/n:.0%}")
|
| 118 |
+
print("=" * 80)
|
| 119 |
+
|
| 120 |
+
print("\n--- FLIPPED rows (v2 stopped catching): old vs new reasoning ---")
|
| 121 |
+
for r in flip[:14]:
|
| 122 |
+
print(f"\n[{r['item_id']}] role={r['role']} old={r['old_guess']}(caught) new={r['new_guess']}(fooled)")
|
| 123 |
+
print(f" OLD: {r['old_reason'][:300]}")
|
| 124 |
+
print(f" NEW: {r['new_reason'][:300]}")
|
| 125 |
+
|
| 126 |
+
print("\n--- STILL caught by v2: what tell survived ---")
|
| 127 |
+
for r in still[:8]:
|
| 128 |
+
print(f"\n[{r['item_id']}] role={r['role']} new={r['new_guess']}")
|
| 129 |
+
print(f" NEW: {r['new_reason'][:300]}")
|
| 130 |
+
|
| 131 |
+
OUT.joinpath("ab_capability_reasons.jsonl").write_text(
|
| 132 |
+
"\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8")
|
| 133 |
+
print(f"\nsaved -> {OUT.joinpath('ab_capability_reasons.jsonl').relative_to(ROOT)}")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
main()
|
tempscripts/story_remediation/unbundle/ab_prompt_v2.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A/B spot-check: does the v2 C3 prompt stop catching synthetics the OLD prompt caught?
|
| 2 |
+
|
| 3 |
+
Takes a sample of v5 rows that were CAUGHT in the last run (i.e. the synthetic
|
| 4 |
+
FAILED to fool the original prompt), re-judges each with BOTH prompts (3-sample
|
| 5 |
+
majority, identical rendering), and reports how many flip caught -> fooled under v2.
|
| 6 |
+
An improvement = the v2 prompt no longer detects the synthetic (guess wrong or
|
| 7 |
+
cannot_tell) on rows the old prompt caught.
|
| 8 |
+
|
| 9 |
+
Run: python -u temp/story_remediation/unbundle/ab_prompt_v2.py [N]
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json, logging, sys, random
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import yaml
|
| 17 |
+
|
| 18 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 19 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
ROOT = HERE.parents[2]
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 25 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 26 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 27 |
+
|
| 28 |
+
OUT = HERE / "out"
|
| 29 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 30 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 31 |
+
SAMPLES = 3
|
| 32 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 33 |
+
|
| 34 |
+
verds = [json.loads(l) for l in open(OUT / "C3_all_v5.jsonl", encoding="utf-8") if l.strip()]
|
| 35 |
+
fakes = {e["example_id"]: e for e in
|
| 36 |
+
(json.loads(l) for l in open(OUT / "trajectories_all_v5.jsonl", encoding="utf-8") if l.strip())}
|
| 37 |
+
base = {}
|
| 38 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 39 |
+
if line.strip():
|
| 40 |
+
d = json.loads(line); base[d["item_id"]] = d
|
| 41 |
+
|
| 42 |
+
reals = P.real_trajectories()
|
| 43 |
+
pairer = P.make_pairer(reals)
|
| 44 |
+
judge = make_judge(cfg["model"])
|
| 45 |
+
|
| 46 |
+
caught = [v for v in verds if v.get("caught")]
|
| 47 |
+
random.seed(11)
|
| 48 |
+
random.shuffle(caught)
|
| 49 |
+
N = int(sys.argv[1]) if len(sys.argv) > 1 else 50
|
| 50 |
+
sample = caught[:N]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def build(fake, real, swap, variant):
|
| 54 |
+
"""Render the identical pair, fill either the C3 or C3v2 template."""
|
| 55 |
+
system, user = J.load_prompt(variant)
|
| 56 |
+
fr = J.render_trajectory(fake, blind_tools=True, include_metadata=False, conversation_only=True)
|
| 57 |
+
rr = J.render_trajectory(real, blind_tools=True, include_metadata=False, conversation_only=True)
|
| 58 |
+
if swap:
|
| 59 |
+
a, b, key = rr, fr, "B"
|
| 60 |
+
else:
|
| 61 |
+
a, b, key = fr, rr, "A"
|
| 62 |
+
user = user.replace("{{CONV_A}}", a).replace("{{CONV_B}}", b)
|
| 63 |
+
return {"system": system, "user": user, "answer_key": key}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def maj(msgs):
|
| 67 |
+
gs = []
|
| 68 |
+
for _ in range(SAMPLES):
|
| 69 |
+
try:
|
| 70 |
+
gs.append(judge.judge({"system": msgs["system"], "user": msgs["user"]}).get("guess"))
|
| 71 |
+
except Exception: # noqa: BLE001
|
| 72 |
+
pass
|
| 73 |
+
if not gs:
|
| 74 |
+
return None, 0.0
|
| 75 |
+
m = Counter(gs).most_common(1)[0][0]
|
| 76 |
+
return m, gs.count(m) / len(gs)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def one(v):
|
| 80 |
+
eid = v["item_id"]; fake = fakes.get(eid)
|
| 81 |
+
if not fake:
|
| 82 |
+
return None
|
| 83 |
+
real = pairer(fake)
|
| 84 |
+
swap = (base.get(eid) or base.get(v.get("orig_eid")) or {}).get("answer_key") == "B"
|
| 85 |
+
old_m = build(fake, real, swap, "C3")
|
| 86 |
+
new_m = build(fake, real, swap, "C3v2")
|
| 87 |
+
key = old_m["answer_key"]
|
| 88 |
+
og, oa = maj(old_m)
|
| 89 |
+
ng, na = maj(new_m)
|
| 90 |
+
return {"item_id": eid, "role": v.get("role"), "key": key,
|
| 91 |
+
"old_guess": og, "old_caught": og == key,
|
| 92 |
+
"new_guess": ng, "new_caught": ng == key}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def main():
|
| 96 |
+
print(f"A/B on {len(sample)} rows caught by the OLD prompt (samples={SAMPLES}, workers={WORKERS})")
|
| 97 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 98 |
+
rows = [r for r in ex.map(one, sample) if r]
|
| 99 |
+
|
| 100 |
+
old_c = sum(r["old_caught"] for r in rows)
|
| 101 |
+
new_c = sum(r["new_caught"] for r in rows)
|
| 102 |
+
flipped = [r for r in rows if r["old_caught"] and not r["new_caught"]]
|
| 103 |
+
still = [r for r in rows if r["old_caught"] and r["new_caught"]]
|
| 104 |
+
regress = [r for r in rows if not r["old_caught"] and r["new_caught"]]
|
| 105 |
+
n = len(rows)
|
| 106 |
+
print("\n" + "=" * 72)
|
| 107 |
+
print(f"rows re-judged: {n}")
|
| 108 |
+
print(f" OLD prompt still catches (re-judge): {old_c}/{n} = {old_c/n:.0%}")
|
| 109 |
+
print(f" NEW (v2) prompt catches: {new_c}/{n} = {new_c/n:.0%}")
|
| 110 |
+
print(f" FLIPPED caught->fooled under v2: {len(flipped)}/{old_c}"
|
| 111 |
+
f" = {len(flipped)/max(old_c,1):.0%} (improvement)")
|
| 112 |
+
print(f" still caught by both: {len(still)}")
|
| 113 |
+
print(f" old-missed but v2 catches: {len(regress)}")
|
| 114 |
+
print("=" * 72)
|
| 115 |
+
print("\nsample of FLIPPED (v2 no longer detects the synthetic):")
|
| 116 |
+
for r in flipped[:12]:
|
| 117 |
+
print(f" {r['item_id']:42s} role={r['role']} old={r['old_guess']} new={r['new_guess']}")
|
| 118 |
+
print("\nsample STILL caught by v2:")
|
| 119 |
+
for r in still[:8]:
|
| 120 |
+
print(f" {r['item_id']:42s} role={r['role']} new={r['new_guess']}")
|
| 121 |
+
(OUT / "ab_prompt_v2.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8")
|
| 122 |
+
print(f"\nsaved -> {(OUT/'ab_prompt_v2.jsonl').relative_to(ROOT)}")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
main()
|
tempscripts/story_remediation/unbundle/analyze_all.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Analyze the full unbundle C3 run vs baseline.
|
| 2 |
+
|
| 3 |
+
Reports:
|
| 4 |
+
- aggregate catch rate across all rows vs baseline 64.7%
|
| 5 |
+
- T1-slot flips (same trie position as baseline): fixed / regressed / net
|
| 6 |
+
- tail-turn catch rate, broken down by tail length and by position
|
| 7 |
+
- the 512 untouched passthrough rows as a sanity control
|
| 8 |
+
Writes RESULT_all.md.
|
| 9 |
+
Run: python -u temp/story_remediation/unbundle/analyze_all.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json
|
| 13 |
+
from collections import defaultdict, Counter
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
HERE = Path(__file__).resolve().parent
|
| 17 |
+
ROOT = HERE.parents[2]
|
| 18 |
+
OUT = HERE / "out"
|
| 19 |
+
RES = OUT / "C3_all.jsonl"
|
| 20 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 21 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 22 |
+
MD = HERE / "RESULT_all.md"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def caught_of(d):
|
| 26 |
+
if "caught" in d and d["caught"] is not None:
|
| 27 |
+
return d["caught"]
|
| 28 |
+
return d.get("guess") == d.get("answer_key")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def main():
|
| 32 |
+
base = {}
|
| 33 |
+
for l in open(BASELINE, encoding="utf-8"):
|
| 34 |
+
if l.strip():
|
| 35 |
+
d = json.loads(l); base[d["item_id"]] = d
|
| 36 |
+
base_caught = {k: caught_of(v) for k, v in base.items()}
|
| 37 |
+
nb = len(base); bc = sum(base_caught.values())
|
| 38 |
+
|
| 39 |
+
res = [json.loads(l) for l in open(RES, encoding="utf-8") if l.strip()]
|
| 40 |
+
ok = [r for r in res if r.get("error") is None and "caught" in r]
|
| 41 |
+
errs = [r for r in res if r not in ok]
|
| 42 |
+
|
| 43 |
+
# tail length per orig from n100
|
| 44 |
+
orig = {json.loads(l)["example_id"]: json.loads(l)
|
| 45 |
+
for l in open(N100, encoding="utf-8") if l.strip()}
|
| 46 |
+
tail_len = {e: len(r["calls"]) - (r["metadata"]["anchor_depth"] + 1)
|
| 47 |
+
for e, r in orig.items()}
|
| 48 |
+
|
| 49 |
+
n = len(ok); c = sum(1 for r in ok if r["caught"])
|
| 50 |
+
t1 = [r for r in ok if r.get("role") == "turn1"]
|
| 51 |
+
tail = [r for r in ok if r.get("role") and r.get("role") != "turn1"]
|
| 52 |
+
passth = [r for r in ok if not r.get("role")]
|
| 53 |
+
|
| 54 |
+
# T1 flips vs baseline (same eid, same trie position)
|
| 55 |
+
fixed = regress = kept_c = kept_f = 0
|
| 56 |
+
for r in t1:
|
| 57 |
+
bcaught = base_caught.get(r["item_id"])
|
| 58 |
+
if bcaught is None:
|
| 59 |
+
continue
|
| 60 |
+
if bcaught and not r["caught"]:
|
| 61 |
+
fixed += 1
|
| 62 |
+
elif not bcaught and r["caught"]:
|
| 63 |
+
regress += 1
|
| 64 |
+
elif bcaught and r["caught"]:
|
| 65 |
+
kept_c += 1
|
| 66 |
+
else:
|
| 67 |
+
kept_f += 1
|
| 68 |
+
t1_caught = sum(1 for r in t1 if r["caught"])
|
| 69 |
+
|
| 70 |
+
# tail by length and position
|
| 71 |
+
tail_by_len = defaultdict(lambda: [0, 0])
|
| 72 |
+
tail_by_pos = defaultdict(lambda: [0, 0])
|
| 73 |
+
for r in tail:
|
| 74 |
+
oe = r.get("orig_eid"); tl = tail_len.get(oe, 0)
|
| 75 |
+
tail_by_len[tl][0] += 1; tail_by_len[tl][1] += int(r["caught"])
|
| 76 |
+
pos = int(r["role"][4:])
|
| 77 |
+
tail_by_pos[pos][0] += 1; tail_by_pos[pos][1] += int(r["caught"])
|
| 78 |
+
|
| 79 |
+
pc = sum(1 for r in passth if r["caught"])
|
| 80 |
+
|
| 81 |
+
L = []
|
| 82 |
+
def p(s=""): L.append(s); print(s)
|
| 83 |
+
|
| 84 |
+
p("# Full Unbundle: C3 Results\n")
|
| 85 |
+
p(f"Baseline (n100, single-turn): **{bc}/{nb} = {bc/nb:.1%}** caught\n")
|
| 86 |
+
p(f"Unbundled dataset: {n} rows judged ({len(errs)} errors)\n")
|
| 87 |
+
p(f"Overall caught: **{c}/{n} = {c/n:.1%}**\n")
|
| 88 |
+
p("## Row composition")
|
| 89 |
+
p(f"- turn1 (preserved trie divergence): {len(t1)}")
|
| 90 |
+
p(f"- tail turns (one action each): {len(tail)}")
|
| 91 |
+
p(f"- untouched passthrough: {len(passth)}\n")
|
| 92 |
+
|
| 93 |
+
p("## T1 slots vs baseline (same 283 trie positions)")
|
| 94 |
+
denom = fixed + regress + kept_c + kept_f
|
| 95 |
+
p(f"- baseline caught here: {fixed+kept_c}/{denom}")
|
| 96 |
+
p(f"- unbundled caught here: {t1_caught}/{len(t1)} = {t1_caught/max(len(t1),1):.1%}")
|
| 97 |
+
p(f"- **fixed (caught -> fooled): {fixed}**")
|
| 98 |
+
p(f"- regressed (fooled -> caught): {regress}")
|
| 99 |
+
p(f"- net catch reduction on T1: {fixed-regress}\n")
|
| 100 |
+
|
| 101 |
+
p("## Tail turns (the re-rooted follow-ups)")
|
| 102 |
+
tc = sum(1 for r in tail if r["caught"])
|
| 103 |
+
p(f"- tail caught: {tc}/{len(tail)} = {tc/max(len(tail),1):.1%}")
|
| 104 |
+
p("- by original tail length:")
|
| 105 |
+
for tl in sorted(tail_by_len):
|
| 106 |
+
tot, cc = tail_by_len[tl]
|
| 107 |
+
p(f" tail_len={tl}: {cc}/{tot} = {cc/tot:.0%}")
|
| 108 |
+
p("- by turn position:")
|
| 109 |
+
for pos in sorted(tail_by_pos):
|
| 110 |
+
tot, cc = tail_by_pos[pos]
|
| 111 |
+
p(f" turn{pos}: {cc}/{tot} = {cc/tot:.0%}")
|
| 112 |
+
p("")
|
| 113 |
+
|
| 114 |
+
p("## Passthrough control (should track baseline)")
|
| 115 |
+
p(f"- caught: {pc}/{len(passth)} = {pc/max(len(passth),1):.1%}")
|
| 116 |
+
bpc = sum(base_caught.get(r["item_id"], False) for r in passth)
|
| 117 |
+
p(f"- same rows in baseline: {bpc}/{len(passth)} = {bpc/max(len(passth),1):.1%}\n")
|
| 118 |
+
|
| 119 |
+
# effective per-scenario: does the ORIGINAL confuser (now split) get caught
|
| 120 |
+
# in ANY of its turns? (a scenario is "detected" if any split turn is caught)
|
| 121 |
+
by_orig = defaultdict(list)
|
| 122 |
+
for r in t1 + tail:
|
| 123 |
+
by_orig[r.get("orig_eid")].append(r["caught"])
|
| 124 |
+
scen_any = sum(1 for e, v in by_orig.items() if any(v))
|
| 125 |
+
scen_t1only = sum(1 for r in t1 if r["caught"])
|
| 126 |
+
p("## Per-scenario view (283 split confusers)")
|
| 127 |
+
p(f"- caught in >=1 of its turns: {scen_any}/{len(by_orig)} = {scen_any/len(by_orig):.1%}")
|
| 128 |
+
p(f"- caught at the T1 (trie) slot: {scen_t1only}/{len(by_orig)} = {scen_t1only/len(by_orig):.1%}")
|
| 129 |
+
baseline_on_split = sum(base_caught.get(e, False) for e in by_orig)
|
| 130 |
+
p(f"- baseline caught these same confusers: {baseline_on_split}/{len(by_orig)} = {baseline_on_split/len(by_orig):.1%}")
|
| 131 |
+
|
| 132 |
+
MD.write_text("\n".join(L) + "\n", encoding="utf-8")
|
| 133 |
+
print(f"\nwrote {MD.relative_to(ROOT)}")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
main()
|
tempscripts/story_remediation/unbundle/analyze_all_v2.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Analyze the full unbundle C3 run vs baseline.
|
| 2 |
+
|
| 3 |
+
Reports:
|
| 4 |
+
- aggregate catch rate across all rows vs baseline 64.7%
|
| 5 |
+
- T1-slot flips (same trie position as baseline): fixed / regressed / net
|
| 6 |
+
- tail-turn catch rate, broken down by tail length and by position
|
| 7 |
+
- the 512 untouched passthrough rows as a sanity control
|
| 8 |
+
Writes RESULT_all_v2.md.
|
| 9 |
+
Run: python -u temp/story_remediation/unbundle/analyze_all.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json
|
| 13 |
+
from collections import defaultdict, Counter
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
HERE = Path(__file__).resolve().parent
|
| 17 |
+
ROOT = HERE.parents[2]
|
| 18 |
+
OUT = HERE / "out"
|
| 19 |
+
RES = OUT / "C3_all_v2.jsonl"
|
| 20 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 21 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 22 |
+
MD = HERE / "RESULT_all_v2.md"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def caught_of(d):
|
| 26 |
+
if "caught" in d and d["caught"] is not None:
|
| 27 |
+
return d["caught"]
|
| 28 |
+
return d.get("guess") == d.get("answer_key")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def main():
|
| 32 |
+
base = {}
|
| 33 |
+
for l in open(BASELINE, encoding="utf-8"):
|
| 34 |
+
if l.strip():
|
| 35 |
+
d = json.loads(l); base[d["item_id"]] = d
|
| 36 |
+
base_caught = {k: caught_of(v) for k, v in base.items()}
|
| 37 |
+
nb = len(base); bc = sum(base_caught.values())
|
| 38 |
+
|
| 39 |
+
res = [json.loads(l) for l in open(RES, encoding="utf-8") if l.strip()]
|
| 40 |
+
ok = [r for r in res if r.get("error") is None and "caught" in r]
|
| 41 |
+
errs = [r for r in res if r not in ok]
|
| 42 |
+
|
| 43 |
+
# tail length per orig from n100
|
| 44 |
+
orig = {json.loads(l)["example_id"]: json.loads(l)
|
| 45 |
+
for l in open(N100, encoding="utf-8") if l.strip()}
|
| 46 |
+
tail_len = {e: len(r["calls"]) - (r["metadata"]["anchor_depth"] + 1)
|
| 47 |
+
for e, r in orig.items()}
|
| 48 |
+
|
| 49 |
+
n = len(ok); c = sum(1 for r in ok if r["caught"])
|
| 50 |
+
t1 = [r for r in ok if r.get("role") == "turn1"]
|
| 51 |
+
tail = [r for r in ok if r.get("role") and r.get("role") != "turn1"]
|
| 52 |
+
passth = [r for r in ok if not r.get("role")]
|
| 53 |
+
|
| 54 |
+
# T1 flips vs baseline (same eid, same trie position)
|
| 55 |
+
fixed = regress = kept_c = kept_f = 0
|
| 56 |
+
for r in t1:
|
| 57 |
+
bcaught = base_caught.get(r["item_id"])
|
| 58 |
+
if bcaught is None:
|
| 59 |
+
continue
|
| 60 |
+
if bcaught and not r["caught"]:
|
| 61 |
+
fixed += 1
|
| 62 |
+
elif not bcaught and r["caught"]:
|
| 63 |
+
regress += 1
|
| 64 |
+
elif bcaught and r["caught"]:
|
| 65 |
+
kept_c += 1
|
| 66 |
+
else:
|
| 67 |
+
kept_f += 1
|
| 68 |
+
t1_caught = sum(1 for r in t1 if r["caught"])
|
| 69 |
+
|
| 70 |
+
# tail by length and position
|
| 71 |
+
tail_by_len = defaultdict(lambda: [0, 0])
|
| 72 |
+
tail_by_pos = defaultdict(lambda: [0, 0])
|
| 73 |
+
for r in tail:
|
| 74 |
+
oe = r.get("orig_eid"); tl = tail_len.get(oe, 0)
|
| 75 |
+
tail_by_len[tl][0] += 1; tail_by_len[tl][1] += int(r["caught"])
|
| 76 |
+
pos = int(r["role"][4:])
|
| 77 |
+
tail_by_pos[pos][0] += 1; tail_by_pos[pos][1] += int(r["caught"])
|
| 78 |
+
|
| 79 |
+
pc = sum(1 for r in passth if r["caught"])
|
| 80 |
+
|
| 81 |
+
L = []
|
| 82 |
+
def p(s=""): L.append(s); print(s)
|
| 83 |
+
|
| 84 |
+
p("# Full Unbundle: C3 Results\n")
|
| 85 |
+
p(f"Baseline (n100, single-turn): **{bc}/{nb} = {bc/nb:.1%}** caught\n")
|
| 86 |
+
p(f"Unbundled dataset: {n} rows judged ({len(errs)} errors)\n")
|
| 87 |
+
p(f"Overall caught: **{c}/{n} = {c/n:.1%}**\n")
|
| 88 |
+
p("## Row composition")
|
| 89 |
+
p(f"- turn1 (preserved trie divergence): {len(t1)}")
|
| 90 |
+
p(f"- tail turns (one action each): {len(tail)}")
|
| 91 |
+
p(f"- untouched passthrough: {len(passth)}\n")
|
| 92 |
+
|
| 93 |
+
p("## T1 slots vs baseline (same 283 trie positions)")
|
| 94 |
+
denom = fixed + regress + kept_c + kept_f
|
| 95 |
+
p(f"- baseline caught here: {fixed+kept_c}/{denom}")
|
| 96 |
+
p(f"- unbundled caught here: {t1_caught}/{len(t1)} = {t1_caught/max(len(t1),1):.1%}")
|
| 97 |
+
p(f"- **fixed (caught -> fooled): {fixed}**")
|
| 98 |
+
p(f"- regressed (fooled -> caught): {regress}")
|
| 99 |
+
p(f"- net catch reduction on T1: {fixed-regress}\n")
|
| 100 |
+
|
| 101 |
+
p("## Tail turns (the re-rooted follow-ups)")
|
| 102 |
+
tc = sum(1 for r in tail if r["caught"])
|
| 103 |
+
p(f"- tail caught: {tc}/{len(tail)} = {tc/max(len(tail),1):.1%}")
|
| 104 |
+
p("- by original tail length:")
|
| 105 |
+
for tl in sorted(tail_by_len):
|
| 106 |
+
tot, cc = tail_by_len[tl]
|
| 107 |
+
p(f" tail_len={tl}: {cc}/{tot} = {cc/tot:.0%}")
|
| 108 |
+
p("- by turn position:")
|
| 109 |
+
for pos in sorted(tail_by_pos):
|
| 110 |
+
tot, cc = tail_by_pos[pos]
|
| 111 |
+
p(f" turn{pos}: {cc}/{tot} = {cc/tot:.0%}")
|
| 112 |
+
p("")
|
| 113 |
+
|
| 114 |
+
p("## Passthrough control (should track baseline)")
|
| 115 |
+
p(f"- caught: {pc}/{len(passth)} = {pc/max(len(passth),1):.1%}")
|
| 116 |
+
bpc = sum(base_caught.get(r["item_id"], False) for r in passth)
|
| 117 |
+
p(f"- same rows in baseline: {bpc}/{len(passth)} = {bpc/max(len(passth),1):.1%}\n")
|
| 118 |
+
|
| 119 |
+
# effective per-scenario: does the ORIGINAL confuser (now split) get caught
|
| 120 |
+
# in ANY of its turns? (a scenario is "detected" if any split turn is caught)
|
| 121 |
+
by_orig = defaultdict(list)
|
| 122 |
+
for r in t1 + tail:
|
| 123 |
+
by_orig[r.get("orig_eid")].append(r["caught"])
|
| 124 |
+
scen_any = sum(1 for e, v in by_orig.items() if any(v))
|
| 125 |
+
scen_t1only = sum(1 for r in t1 if r["caught"])
|
| 126 |
+
p("## Per-scenario view (283 split confusers)")
|
| 127 |
+
p(f"- caught in >=1 of its turns: {scen_any}/{len(by_orig)} = {scen_any/len(by_orig):.1%}")
|
| 128 |
+
p(f"- caught at the T1 (trie) slot: {scen_t1only}/{len(by_orig)} = {scen_t1only/len(by_orig):.1%}")
|
| 129 |
+
baseline_on_split = sum(base_caught.get(e, False) for e in by_orig)
|
| 130 |
+
p(f"- baseline caught these same confusers: {baseline_on_split}/{len(by_orig)} = {baseline_on_split/len(by_orig):.1%}")
|
| 131 |
+
|
| 132 |
+
MD.write_text("\n".join(L) + "\n", encoding="utf-8")
|
| 133 |
+
print(f"\nwrote {MD.relative_to(ROOT)}")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
main()
|
tempscripts/story_remediation/unbundle/analyze_all_v3.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Analyze the full unbundle C3 run vs baseline.
|
| 2 |
+
|
| 3 |
+
Reports:
|
| 4 |
+
- aggregate catch rate across all rows vs baseline 64.7%
|
| 5 |
+
- T1-slot flips (same trie position as baseline): fixed / regressed / net
|
| 6 |
+
- tail-turn catch rate, broken down by tail length and by position
|
| 7 |
+
- the 512 untouched passthrough rows as a sanity control
|
| 8 |
+
Writes RESULT_all_v3.md.
|
| 9 |
+
Run: python -u temp/story_remediation/unbundle/analyze_all.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json
|
| 13 |
+
from collections import defaultdict, Counter
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
HERE = Path(__file__).resolve().parent
|
| 17 |
+
ROOT = HERE.parents[2]
|
| 18 |
+
OUT = HERE / "out"
|
| 19 |
+
RES = OUT / "C3_all_v3.jsonl"
|
| 20 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 21 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 22 |
+
MD = HERE / "RESULT_all_v3.md"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def caught_of(d):
|
| 26 |
+
if "caught" in d and d["caught"] is not None:
|
| 27 |
+
return d["caught"]
|
| 28 |
+
return d.get("guess") == d.get("answer_key")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def main():
|
| 32 |
+
base = {}
|
| 33 |
+
for l in open(BASELINE, encoding="utf-8"):
|
| 34 |
+
if l.strip():
|
| 35 |
+
d = json.loads(l); base[d["item_id"]] = d
|
| 36 |
+
base_caught = {k: caught_of(v) for k, v in base.items()}
|
| 37 |
+
nb = len(base); bc = sum(base_caught.values())
|
| 38 |
+
|
| 39 |
+
res = [json.loads(l) for l in open(RES, encoding="utf-8") if l.strip()]
|
| 40 |
+
ok = [r for r in res if r.get("error") is None and "caught" in r]
|
| 41 |
+
errs = [r for r in res if r not in ok]
|
| 42 |
+
|
| 43 |
+
# tail length per orig from n100
|
| 44 |
+
orig = {json.loads(l)["example_id"]: json.loads(l)
|
| 45 |
+
for l in open(N100, encoding="utf-8") if l.strip()}
|
| 46 |
+
tail_len = {e: len(r["calls"]) - (r["metadata"]["anchor_depth"] + 1)
|
| 47 |
+
for e, r in orig.items()}
|
| 48 |
+
|
| 49 |
+
n = len(ok); c = sum(1 for r in ok if r["caught"])
|
| 50 |
+
t1 = [r for r in ok if r.get("role") == "turn1"]
|
| 51 |
+
tail = [r for r in ok if r.get("role") and r.get("role") != "turn1"]
|
| 52 |
+
passth = [r for r in ok if not r.get("role")]
|
| 53 |
+
|
| 54 |
+
# T1 flips vs baseline (same eid, same trie position)
|
| 55 |
+
fixed = regress = kept_c = kept_f = 0
|
| 56 |
+
for r in t1:
|
| 57 |
+
bcaught = base_caught.get(r["item_id"])
|
| 58 |
+
if bcaught is None:
|
| 59 |
+
continue
|
| 60 |
+
if bcaught and not r["caught"]:
|
| 61 |
+
fixed += 1
|
| 62 |
+
elif not bcaught and r["caught"]:
|
| 63 |
+
regress += 1
|
| 64 |
+
elif bcaught and r["caught"]:
|
| 65 |
+
kept_c += 1
|
| 66 |
+
else:
|
| 67 |
+
kept_f += 1
|
| 68 |
+
t1_caught = sum(1 for r in t1 if r["caught"])
|
| 69 |
+
|
| 70 |
+
# tail by length and position
|
| 71 |
+
tail_by_len = defaultdict(lambda: [0, 0])
|
| 72 |
+
tail_by_pos = defaultdict(lambda: [0, 0])
|
| 73 |
+
for r in tail:
|
| 74 |
+
oe = r.get("orig_eid"); tl = tail_len.get(oe, 0)
|
| 75 |
+
tail_by_len[tl][0] += 1; tail_by_len[tl][1] += int(r["caught"])
|
| 76 |
+
pos = int(r["role"][4:])
|
| 77 |
+
tail_by_pos[pos][0] += 1; tail_by_pos[pos][1] += int(r["caught"])
|
| 78 |
+
|
| 79 |
+
pc = sum(1 for r in passth if r["caught"])
|
| 80 |
+
|
| 81 |
+
L = []
|
| 82 |
+
def p(s=""): L.append(s); print(s)
|
| 83 |
+
|
| 84 |
+
p("# Full Unbundle: C3 Results\n")
|
| 85 |
+
p(f"Baseline (n100, single-turn): **{bc}/{nb} = {bc/nb:.1%}** caught\n")
|
| 86 |
+
p(f"Unbundled dataset: {n} rows judged ({len(errs)} errors)\n")
|
| 87 |
+
p(f"Overall caught: **{c}/{n} = {c/n:.1%}**\n")
|
| 88 |
+
p("## Row composition")
|
| 89 |
+
p(f"- turn1 (preserved trie divergence): {len(t1)}")
|
| 90 |
+
p(f"- tail turns (one action each): {len(tail)}")
|
| 91 |
+
p(f"- untouched passthrough: {len(passth)}\n")
|
| 92 |
+
|
| 93 |
+
p("## T1 slots vs baseline (same 283 trie positions)")
|
| 94 |
+
denom = fixed + regress + kept_c + kept_f
|
| 95 |
+
p(f"- baseline caught here: {fixed+kept_c}/{denom}")
|
| 96 |
+
p(f"- unbundled caught here: {t1_caught}/{len(t1)} = {t1_caught/max(len(t1),1):.1%}")
|
| 97 |
+
p(f"- **fixed (caught -> fooled): {fixed}**")
|
| 98 |
+
p(f"- regressed (fooled -> caught): {regress}")
|
| 99 |
+
p(f"- net catch reduction on T1: {fixed-regress}\n")
|
| 100 |
+
|
| 101 |
+
p("## Tail turns (the re-rooted follow-ups)")
|
| 102 |
+
tc = sum(1 for r in tail if r["caught"])
|
| 103 |
+
p(f"- tail caught: {tc}/{len(tail)} = {tc/max(len(tail),1):.1%}")
|
| 104 |
+
p("- by original tail length:")
|
| 105 |
+
for tl in sorted(tail_by_len):
|
| 106 |
+
tot, cc = tail_by_len[tl]
|
| 107 |
+
p(f" tail_len={tl}: {cc}/{tot} = {cc/tot:.0%}")
|
| 108 |
+
p("- by turn position:")
|
| 109 |
+
for pos in sorted(tail_by_pos):
|
| 110 |
+
tot, cc = tail_by_pos[pos]
|
| 111 |
+
p(f" turn{pos}: {cc}/{tot} = {cc/tot:.0%}")
|
| 112 |
+
p("")
|
| 113 |
+
|
| 114 |
+
p("## Passthrough control (should track baseline)")
|
| 115 |
+
p(f"- caught: {pc}/{len(passth)} = {pc/max(len(passth),1):.1%}")
|
| 116 |
+
bpc = sum(base_caught.get(r["item_id"], False) for r in passth)
|
| 117 |
+
p(f"- same rows in baseline: {bpc}/{len(passth)} = {bpc/max(len(passth),1):.1%}\n")
|
| 118 |
+
|
| 119 |
+
# effective per-scenario: does the ORIGINAL confuser (now split) get caught
|
| 120 |
+
# in ANY of its turns? (a scenario is "detected" if any split turn is caught)
|
| 121 |
+
by_orig = defaultdict(list)
|
| 122 |
+
for r in t1 + tail:
|
| 123 |
+
by_orig[r.get("orig_eid")].append(r["caught"])
|
| 124 |
+
scen_any = sum(1 for e, v in by_orig.items() if any(v))
|
| 125 |
+
scen_t1only = sum(1 for r in t1 if r["caught"])
|
| 126 |
+
p("## Per-scenario view (283 split confusers)")
|
| 127 |
+
p(f"- caught in >=1 of its turns: {scen_any}/{len(by_orig)} = {scen_any/len(by_orig):.1%}")
|
| 128 |
+
p(f"- caught at the T1 (trie) slot: {scen_t1only}/{len(by_orig)} = {scen_t1only/len(by_orig):.1%}")
|
| 129 |
+
baseline_on_split = sum(base_caught.get(e, False) for e in by_orig)
|
| 130 |
+
p(f"- baseline caught these same confusers: {baseline_on_split}/{len(by_orig)} = {baseline_on_split/len(by_orig):.1%}")
|
| 131 |
+
|
| 132 |
+
MD.write_text("\n".join(L) + "\n", encoding="utf-8")
|
| 133 |
+
print(f"\nwrote {MD.relative_to(ROOT)}")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
main()
|
tempscripts/story_remediation/unbundle/analyze_all_v4.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Analyze the full unbundle C3 run vs baseline.
|
| 2 |
+
|
| 3 |
+
Reports:
|
| 4 |
+
- aggregate catch rate across all rows vs baseline 64.7%
|
| 5 |
+
- T1-slot flips (same trie position as baseline): fixed / regressed / net
|
| 6 |
+
- tail-turn catch rate, broken down by tail length and by position
|
| 7 |
+
- the 512 untouched passthrough rows as a sanity control
|
| 8 |
+
Writes RESULT_all_v4.md.
|
| 9 |
+
Run: python -u temp/story_remediation/unbundle/analyze_all.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json
|
| 13 |
+
from collections import defaultdict, Counter
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
HERE = Path(__file__).resolve().parent
|
| 17 |
+
ROOT = HERE.parents[2]
|
| 18 |
+
OUT = HERE / "out"
|
| 19 |
+
RES = OUT / "C3_all_v4.jsonl"
|
| 20 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 21 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 22 |
+
MD = HERE / "RESULT_all_v4.md"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def caught_of(d):
|
| 26 |
+
if "caught" in d and d["caught"] is not None:
|
| 27 |
+
return d["caught"]
|
| 28 |
+
return d.get("guess") == d.get("answer_key")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def main():
|
| 32 |
+
base = {}
|
| 33 |
+
for l in open(BASELINE, encoding="utf-8"):
|
| 34 |
+
if l.strip():
|
| 35 |
+
d = json.loads(l); base[d["item_id"]] = d
|
| 36 |
+
base_caught = {k: caught_of(v) for k, v in base.items()}
|
| 37 |
+
nb = len(base); bc = sum(base_caught.values())
|
| 38 |
+
|
| 39 |
+
res = [json.loads(l) for l in open(RES, encoding="utf-8") if l.strip()]
|
| 40 |
+
ok = [r for r in res if r.get("error") is None and "caught" in r]
|
| 41 |
+
errs = [r for r in res if r not in ok]
|
| 42 |
+
|
| 43 |
+
# tail length per orig from n100
|
| 44 |
+
orig = {json.loads(l)["example_id"]: json.loads(l)
|
| 45 |
+
for l in open(N100, encoding="utf-8") if l.strip()}
|
| 46 |
+
tail_len = {e: len(r["calls"]) - (r["metadata"]["anchor_depth"] + 1)
|
| 47 |
+
for e, r in orig.items()}
|
| 48 |
+
|
| 49 |
+
n = len(ok); c = sum(1 for r in ok if r["caught"])
|
| 50 |
+
t1 = [r for r in ok if r.get("role") == "turn1"]
|
| 51 |
+
tail = [r for r in ok if r.get("role") and r.get("role") != "turn1"]
|
| 52 |
+
passth = [r for r in ok if not r.get("role")]
|
| 53 |
+
|
| 54 |
+
# T1 flips vs baseline (same eid, same trie position)
|
| 55 |
+
fixed = regress = kept_c = kept_f = 0
|
| 56 |
+
for r in t1:
|
| 57 |
+
bcaught = base_caught.get(r["item_id"])
|
| 58 |
+
if bcaught is None:
|
| 59 |
+
continue
|
| 60 |
+
if bcaught and not r["caught"]:
|
| 61 |
+
fixed += 1
|
| 62 |
+
elif not bcaught and r["caught"]:
|
| 63 |
+
regress += 1
|
| 64 |
+
elif bcaught and r["caught"]:
|
| 65 |
+
kept_c += 1
|
| 66 |
+
else:
|
| 67 |
+
kept_f += 1
|
| 68 |
+
t1_caught = sum(1 for r in t1 if r["caught"])
|
| 69 |
+
|
| 70 |
+
# tail by length and position
|
| 71 |
+
tail_by_len = defaultdict(lambda: [0, 0])
|
| 72 |
+
tail_by_pos = defaultdict(lambda: [0, 0])
|
| 73 |
+
for r in tail:
|
| 74 |
+
oe = r.get("orig_eid"); tl = tail_len.get(oe, 0)
|
| 75 |
+
tail_by_len[tl][0] += 1; tail_by_len[tl][1] += int(r["caught"])
|
| 76 |
+
pos = int(r["role"][4:])
|
| 77 |
+
tail_by_pos[pos][0] += 1; tail_by_pos[pos][1] += int(r["caught"])
|
| 78 |
+
|
| 79 |
+
pc = sum(1 for r in passth if r["caught"])
|
| 80 |
+
|
| 81 |
+
L = []
|
| 82 |
+
def p(s=""): L.append(s); print(s)
|
| 83 |
+
|
| 84 |
+
p("# Unbundle v4 (auth handshake + humanized): C3 Results\n")
|
| 85 |
+
p(f"Baseline (n100, single-turn): **{bc}/{nb} = {bc/nb:.1%}** caught\n")
|
| 86 |
+
p(f"Unbundled dataset: {n} rows judged ({len(errs)} errors)\n")
|
| 87 |
+
p(f"Overall caught: **{c}/{n} = {c/n:.1%}**\n")
|
| 88 |
+
p("## Row composition")
|
| 89 |
+
p(f"- turn1 (preserved trie divergence): {len(t1)}")
|
| 90 |
+
p(f"- tail turns (one action each): {len(tail)}")
|
| 91 |
+
p(f"- untouched passthrough: {len(passth)}\n")
|
| 92 |
+
|
| 93 |
+
p("## T1 slots vs baseline (same 283 trie positions)")
|
| 94 |
+
denom = fixed + regress + kept_c + kept_f
|
| 95 |
+
p(f"- baseline caught here: {fixed+kept_c}/{denom}")
|
| 96 |
+
p(f"- unbundled caught here: {t1_caught}/{len(t1)} = {t1_caught/max(len(t1),1):.1%}")
|
| 97 |
+
p(f"- **fixed (caught -> fooled): {fixed}**")
|
| 98 |
+
p(f"- regressed (fooled -> caught): {regress}")
|
| 99 |
+
p(f"- net catch reduction on T1: {fixed-regress}\n")
|
| 100 |
+
|
| 101 |
+
p("## Tail turns (the re-rooted follow-ups)")
|
| 102 |
+
tc = sum(1 for r in tail if r["caught"])
|
| 103 |
+
p(f"- tail caught: {tc}/{len(tail)} = {tc/max(len(tail),1):.1%}")
|
| 104 |
+
p("- by original tail length:")
|
| 105 |
+
for tl in sorted(tail_by_len):
|
| 106 |
+
tot, cc = tail_by_len[tl]
|
| 107 |
+
p(f" tail_len={tl}: {cc}/{tot} = {cc/tot:.0%}")
|
| 108 |
+
p("- by turn position:")
|
| 109 |
+
for pos in sorted(tail_by_pos):
|
| 110 |
+
tot, cc = tail_by_pos[pos]
|
| 111 |
+
p(f" turn{pos}: {cc}/{tot} = {cc/tot:.0%}")
|
| 112 |
+
p("")
|
| 113 |
+
|
| 114 |
+
p("## Passthrough control (should track baseline)")
|
| 115 |
+
p(f"- caught: {pc}/{len(passth)} = {pc/max(len(passth),1):.1%}")
|
| 116 |
+
bpc = sum(base_caught.get(r["item_id"], False) for r in passth)
|
| 117 |
+
p(f"- same rows in baseline: {bpc}/{len(passth)} = {bpc/max(len(passth),1):.1%}\n")
|
| 118 |
+
|
| 119 |
+
# effective per-scenario: does the ORIGINAL confuser (now split) get caught
|
| 120 |
+
# in ANY of its turns? (a scenario is "detected" if any split turn is caught)
|
| 121 |
+
by_orig = defaultdict(list)
|
| 122 |
+
for r in t1 + tail:
|
| 123 |
+
by_orig[r.get("orig_eid")].append(r["caught"])
|
| 124 |
+
scen_any = sum(1 for e, v in by_orig.items() if any(v))
|
| 125 |
+
scen_t1only = sum(1 for r in t1 if r["caught"])
|
| 126 |
+
p("## Per-scenario view (283 split confusers)")
|
| 127 |
+
p(f"- caught in >=1 of its turns: {scen_any}/{len(by_orig)} = {scen_any/len(by_orig):.1%}")
|
| 128 |
+
p(f"- caught at the T1 (trie) slot: {scen_t1only}/{len(by_orig)} = {scen_t1only/len(by_orig):.1%}")
|
| 129 |
+
baseline_on_split = sum(base_caught.get(e, False) for e in by_orig)
|
| 130 |
+
p(f"- baseline caught these same confusers: {baseline_on_split}/{len(by_orig)} = {baseline_on_split/len(by_orig):.1%}")
|
| 131 |
+
|
| 132 |
+
MD.write_text("\n".join(L) + "\n", encoding="utf-8")
|
| 133 |
+
print(f"\nwrote {MD.relative_to(ROOT)}")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
main()
|
| 138 |
+
|
tempscripts/story_remediation/unbundle/analyze_all_v5.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Analyze the full unbundle C3 run vs baseline.
|
| 2 |
+
|
| 3 |
+
Reports:
|
| 4 |
+
- aggregate catch rate across all rows vs baseline 64.7%
|
| 5 |
+
- T1-slot flips (same trie position as baseline): fixed / regressed / net
|
| 6 |
+
- tail-turn catch rate, broken down by tail length and by position
|
| 7 |
+
- the 512 untouched passthrough rows as a sanity control
|
| 8 |
+
Writes RESULT_all_v5.md.
|
| 9 |
+
Run: python -u temp/story_remediation/unbundle/analyze_all.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json
|
| 13 |
+
from collections import defaultdict, Counter
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
HERE = Path(__file__).resolve().parent
|
| 17 |
+
ROOT = HERE.parents[2]
|
| 18 |
+
OUT = HERE / "out"
|
| 19 |
+
RES = OUT / "C3_all_v5.jsonl"
|
| 20 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 21 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 22 |
+
MD = HERE / "RESULT_all_v5.md"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def caught_of(d):
|
| 26 |
+
if "caught" in d and d["caught"] is not None:
|
| 27 |
+
return d["caught"]
|
| 28 |
+
return d.get("guess") == d.get("answer_key")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def main():
|
| 32 |
+
base = {}
|
| 33 |
+
for l in open(BASELINE, encoding="utf-8"):
|
| 34 |
+
if l.strip():
|
| 35 |
+
d = json.loads(l); base[d["item_id"]] = d
|
| 36 |
+
base_caught = {k: caught_of(v) for k, v in base.items()}
|
| 37 |
+
nb = len(base); bc = sum(base_caught.values())
|
| 38 |
+
|
| 39 |
+
res = [json.loads(l) for l in open(RES, encoding="utf-8") if l.strip()]
|
| 40 |
+
ok = [r for r in res if r.get("error") is None and "caught" in r]
|
| 41 |
+
errs = [r for r in res if r not in ok]
|
| 42 |
+
|
| 43 |
+
# tail length per orig from n100
|
| 44 |
+
orig = {json.loads(l)["example_id"]: json.loads(l)
|
| 45 |
+
for l in open(N100, encoding="utf-8") if l.strip()}
|
| 46 |
+
tail_len = {e: len(r["calls"]) - (r["metadata"]["anchor_depth"] + 1)
|
| 47 |
+
for e, r in orig.items()}
|
| 48 |
+
|
| 49 |
+
n = len(ok); c = sum(1 for r in ok if r["caught"])
|
| 50 |
+
t1 = [r for r in ok if r.get("role") == "turn1"]
|
| 51 |
+
tail = [r for r in ok if r.get("role") and r.get("role") != "turn1"]
|
| 52 |
+
passth = [r for r in ok if not r.get("role")]
|
| 53 |
+
|
| 54 |
+
# T1 flips vs baseline (same eid, same trie position)
|
| 55 |
+
fixed = regress = kept_c = kept_f = 0
|
| 56 |
+
for r in t1:
|
| 57 |
+
bcaught = base_caught.get(r["item_id"])
|
| 58 |
+
if bcaught is None:
|
| 59 |
+
continue
|
| 60 |
+
if bcaught and not r["caught"]:
|
| 61 |
+
fixed += 1
|
| 62 |
+
elif not bcaught and r["caught"]:
|
| 63 |
+
regress += 1
|
| 64 |
+
elif bcaught and r["caught"]:
|
| 65 |
+
kept_c += 1
|
| 66 |
+
else:
|
| 67 |
+
kept_f += 1
|
| 68 |
+
t1_caught = sum(1 for r in t1 if r["caught"])
|
| 69 |
+
|
| 70 |
+
# tail by length and position
|
| 71 |
+
tail_by_len = defaultdict(lambda: [0, 0])
|
| 72 |
+
tail_by_pos = defaultdict(lambda: [0, 0])
|
| 73 |
+
for r in tail:
|
| 74 |
+
oe = r.get("orig_eid"); tl = tail_len.get(oe, 0)
|
| 75 |
+
tail_by_len[tl][0] += 1; tail_by_len[tl][1] += int(r["caught"])
|
| 76 |
+
pos = int(r["role"][4:])
|
| 77 |
+
tail_by_pos[pos][0] += 1; tail_by_pos[pos][1] += int(r["caught"])
|
| 78 |
+
|
| 79 |
+
pc = sum(1 for r in passth if r["caught"])
|
| 80 |
+
|
| 81 |
+
L = []
|
| 82 |
+
def p(s=""): L.append(s); print(s)
|
| 83 |
+
|
| 84 |
+
p("# Unbundle v5 (b1+b3, auth handshake + humanized): C3 Results\n")
|
| 85 |
+
p(f"Baseline (n100, single-turn): **{bc}/{nb} = {bc/nb:.1%}** caught\n")
|
| 86 |
+
p(f"Unbundled dataset: {n} rows judged ({len(errs)} errors)\n")
|
| 87 |
+
p(f"Overall caught: **{c}/{n} = {c/n:.1%}**\n")
|
| 88 |
+
p("## Row composition")
|
| 89 |
+
p(f"- turn1 (preserved trie divergence): {len(t1)}")
|
| 90 |
+
p(f"- tail turns (one action each): {len(tail)}")
|
| 91 |
+
p(f"- untouched passthrough: {len(passth)}\n")
|
| 92 |
+
|
| 93 |
+
p("## T1 slots vs baseline (same 283 trie positions)")
|
| 94 |
+
denom = fixed + regress + kept_c + kept_f
|
| 95 |
+
p(f"- baseline caught here: {fixed+kept_c}/{denom}")
|
| 96 |
+
p(f"- unbundled caught here: {t1_caught}/{len(t1)} = {t1_caught/max(len(t1),1):.1%}")
|
| 97 |
+
p(f"- **fixed (caught -> fooled): {fixed}**")
|
| 98 |
+
p(f"- regressed (fooled -> caught): {regress}")
|
| 99 |
+
p(f"- net catch reduction on T1: {fixed-regress}\n")
|
| 100 |
+
|
| 101 |
+
p("## Tail turns (the re-rooted follow-ups)")
|
| 102 |
+
tc = sum(1 for r in tail if r["caught"])
|
| 103 |
+
p(f"- tail caught: {tc}/{len(tail)} = {tc/max(len(tail),1):.1%}")
|
| 104 |
+
p("- by original tail length:")
|
| 105 |
+
for tl in sorted(tail_by_len):
|
| 106 |
+
tot, cc = tail_by_len[tl]
|
| 107 |
+
p(f" tail_len={tl}: {cc}/{tot} = {cc/tot:.0%}")
|
| 108 |
+
p("- by turn position:")
|
| 109 |
+
for pos in sorted(tail_by_pos):
|
| 110 |
+
tot, cc = tail_by_pos[pos]
|
| 111 |
+
p(f" turn{pos}: {cc}/{tot} = {cc/tot:.0%}")
|
| 112 |
+
p("")
|
| 113 |
+
|
| 114 |
+
p("## Passthrough control (should track baseline)")
|
| 115 |
+
p(f"- caught: {pc}/{len(passth)} = {pc/max(len(passth),1):.1%}")
|
| 116 |
+
bpc = sum(base_caught.get(r["item_id"], False) for r in passth)
|
| 117 |
+
p(f"- same rows in baseline: {bpc}/{len(passth)} = {bpc/max(len(passth),1):.1%}\n")
|
| 118 |
+
|
| 119 |
+
# effective per-scenario: does the ORIGINAL confuser (now split) get caught
|
| 120 |
+
# in ANY of its turns? (a scenario is "detected" if any split turn is caught)
|
| 121 |
+
by_orig = defaultdict(list)
|
| 122 |
+
for r in t1 + tail:
|
| 123 |
+
by_orig[r.get("orig_eid")].append(r["caught"])
|
| 124 |
+
scen_any = sum(1 for e, v in by_orig.items() if any(v))
|
| 125 |
+
scen_t1only = sum(1 for r in t1 if r["caught"])
|
| 126 |
+
p("## Per-scenario view (283 split confusers)")
|
| 127 |
+
p(f"- caught in >=1 of its turns: {scen_any}/{len(by_orig)} = {scen_any/len(by_orig):.1%}")
|
| 128 |
+
p(f"- caught at the T1 (trie) slot: {scen_t1only}/{len(by_orig)} = {scen_t1only/len(by_orig):.1%}")
|
| 129 |
+
baseline_on_split = sum(base_caught.get(e, False) for e in by_orig)
|
| 130 |
+
p(f"- baseline caught these same confusers: {baseline_on_split}/{len(by_orig)} = {baseline_on_split/len(by_orig):.1%}")
|
| 131 |
+
|
| 132 |
+
MD.write_text("\n".join(L) + "\n", encoding="utf-8")
|
| 133 |
+
print(f"\nwrote {MD.relative_to(ROOT)}")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
main()
|
| 138 |
+
|
| 139 |
+
|
tempscripts/story_remediation/unbundle/auth_lint_v5.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read-only deterministic lint over trajectories_all_v5.jsonl.
|
| 2 |
+
|
| 3 |
+
Flags authored-NL defects that the C3 judge picks up as "auth/identity" tells,
|
| 4 |
+
plus two rendering/authoring defects (raw-JSON assistant content, markdown in
|
| 5 |
+
user messages). Does NOT modify anything; writes per-row flags to
|
| 6 |
+
out/auth_lint_v5.jsonl and prints exact counts.
|
| 7 |
+
"""
|
| 8 |
+
import json, re, sys
|
| 9 |
+
from collections import Counter, defaultdict
|
| 10 |
+
|
| 11 |
+
SRC = r"temp/story_remediation/unbundle/out/trajectories_all_v5.jsonl"
|
| 12 |
+
OUT = r"temp/story_remediation/unbundle/out/auth_lint_v5.jsonl"
|
| 13 |
+
|
| 14 |
+
# ---- status-lock sets (from systemUpgrade/_statecheck.py) ----
|
| 15 |
+
DELIVERED = {"return_delivered_order_items", "exchange_delivered_order_items", "cancel_delivered_order"}
|
| 16 |
+
PENDING = {"modify_pending_order_items", "modify_pending_order_address",
|
| 17 |
+
"return_pending_order_items", "cancel_pending_order"}
|
| 18 |
+
|
| 19 |
+
# A verification CONFIRMATION (identity already established) -- NOT the request/ask
|
| 20 |
+
# ("let me verify you first"). Only >1 confirmation per conversation is a defect.
|
| 21 |
+
VERIFIED_RX = re.compile(
|
| 22 |
+
r"(you'?re (all )?verified|you are (all )?verified|i'?ve verified|i have verified"
|
| 23 |
+
r"|verified your (identity|account)|already verified|perfect,? verified"
|
| 24 |
+
r"|verified\.|you'?re (all )?set and verified|good to go)", re.I)
|
| 25 |
+
|
| 26 |
+
# agent addressing the customer by first name -- require DIRECT-ADDRESS punctuation
|
| 27 |
+
# right after the name (comma / apostrophe-s / ! . / "you're") so greetings like
|
| 28 |
+
# "Hi! How can I help?" don't capture "How".
|
| 29 |
+
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)")
|
| 30 |
+
ADDR_RX2 = re.compile(r"\b([A-Z][a-z]+),\s+you(?:'re| are)\b")
|
| 31 |
+
STOP = {"Thanks","Thank","There","This","That","Your","You","Just","Once","Now","Sure","Okay","OK","Alright",
|
| 32 |
+
"Great","Perfect","Welcome","Hi","Hello","Hey","And","So","For","Let","Give","Could","Can","Please",
|
| 33 |
+
"First","Both","All","Got","Good","Happy","One","Yes","No","How","What","Before","Of","To","We"}
|
| 34 |
+
|
| 35 |
+
EMAIL_RX = re.compile(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}")
|
| 36 |
+
ZIP_CTX_RX = re.compile(r"zip\D{0,12}(\d{5})", re.I)
|
| 37 |
+
|
| 38 |
+
MD_BOLD_RX = re.compile(r"\*\*[^*\n]+\*\*|__[^_\n]+__")
|
| 39 |
+
MD_LIST_RX = re.compile(r"(^|\n)\s*(\d+\.\s+\S|[-*]\s+\S)")
|
| 40 |
+
MD_HEADER_RX = re.compile(r"(^|\n)#{1,6}\s+\S")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def convo_turns(r):
|
| 44 |
+
"""Yield (role, content) NL turns the judge sees: history user/asst + query."""
|
| 45 |
+
for h in r.get("history", []):
|
| 46 |
+
role = h.get("role"); c = h.get("content")
|
| 47 |
+
if role in ("user", "assistant") and c:
|
| 48 |
+
yield role, c
|
| 49 |
+
if r.get("query"):
|
| 50 |
+
yield "user", r["query"]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def auth_identity(r):
|
| 54 |
+
"""(method, first, last, zip, email) from find_user_id_* + get_user_details,
|
| 55 |
+
looking in BOTH the row's own calls AND the embedded history (tail rows carry
|
| 56 |
+
their auth handshake in history, not in `calls`)."""
|
| 57 |
+
first = last = zipc = email = None; method = None
|
| 58 |
+
|
| 59 |
+
def take_call(n, a, out):
|
| 60 |
+
nonlocal first, last, zipc, email, method
|
| 61 |
+
if n.startswith("find_user_id_"):
|
| 62 |
+
method = method or n
|
| 63 |
+
first = first or (a.get("first_name") or "").strip() or None
|
| 64 |
+
last = last or (a.get("last_name") or "").strip() or None
|
| 65 |
+
zipc = zipc or (str(a.get("zip")) if a.get("zip") else None)
|
| 66 |
+
email = email or (a.get("email") or "").strip() or None
|
| 67 |
+
if n == "get_user_details" and out:
|
| 68 |
+
try:
|
| 69 |
+
o = json.loads(out)
|
| 70 |
+
nm = o.get("name", {})
|
| 71 |
+
first = first or nm.get("first_name")
|
| 72 |
+
last = last or nm.get("last_name")
|
| 73 |
+
email = email or o.get("email")
|
| 74 |
+
zipc = zipc or (o.get("address", {}) or {}).get("zip")
|
| 75 |
+
except Exception:
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
for c in r.get("calls", []):
|
| 79 |
+
take_call(c["name"], c.get("arguments", {}) or {}, c.get("output"))
|
| 80 |
+
|
| 81 |
+
# history: assistant tool_calls (args) + following tool outputs
|
| 82 |
+
hist = r.get("history", [])
|
| 83 |
+
for i, h in enumerate(hist):
|
| 84 |
+
for tc in h.get("tool_calls") or []:
|
| 85 |
+
n = tc.get("name") or (tc.get("function") or {}).get("name", "")
|
| 86 |
+
a = tc.get("arguments") or (tc.get("function") or {}).get("arguments", {})
|
| 87 |
+
if isinstance(a, str):
|
| 88 |
+
try: a = json.loads(a)
|
| 89 |
+
except Exception: a = {}
|
| 90 |
+
take_call(n, a or {}, None)
|
| 91 |
+
# get_user_details output json anywhere in history tool messages
|
| 92 |
+
for h in hist:
|
| 93 |
+
if h.get("role") == "tool" and h.get("content"):
|
| 94 |
+
try:
|
| 95 |
+
o = json.loads(h["content"])
|
| 96 |
+
if isinstance(o, dict) and "name" in o and isinstance(o["name"], dict):
|
| 97 |
+
nm = o["name"]
|
| 98 |
+
first = first or nm.get("first_name")
|
| 99 |
+
last = last or nm.get("last_name")
|
| 100 |
+
email = email or o.get("email")
|
| 101 |
+
zipc = zipc or (o.get("address", {}) or {}).get("zip")
|
| 102 |
+
except Exception:
|
| 103 |
+
pass
|
| 104 |
+
return method, first, last, zipc, email
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def call_arg_values(r):
|
| 108 |
+
"""All string values that appear as tool-call arguments (row calls + history
|
| 109 |
+
tool_calls). Spoken zips/emails matching these are legitimate OPERATION TARGETS
|
| 110 |
+
(e.g. a requested new email / new shipping zip), not identity mismatches."""
|
| 111 |
+
vals = set()
|
| 112 |
+
|
| 113 |
+
def walk(a):
|
| 114 |
+
if isinstance(a, dict):
|
| 115 |
+
for v in a.values():
|
| 116 |
+
walk(v)
|
| 117 |
+
elif isinstance(a, list):
|
| 118 |
+
for v in a:
|
| 119 |
+
walk(v)
|
| 120 |
+
elif a is not None:
|
| 121 |
+
vals.add(str(a).lower())
|
| 122 |
+
|
| 123 |
+
for c in r.get("calls", []):
|
| 124 |
+
walk(c.get("arguments", {}))
|
| 125 |
+
for h in r.get("history", []):
|
| 126 |
+
for tc in h.get("tool_calls") or []:
|
| 127 |
+
a = tc.get("arguments") or (tc.get("function") or {}).get("arguments", {})
|
| 128 |
+
if isinstance(a, str):
|
| 129 |
+
try: a = json.loads(a)
|
| 130 |
+
except Exception: a = {}
|
| 131 |
+
walk(a)
|
| 132 |
+
return vals
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def order_statuses(r):
|
| 136 |
+
"""order_id -> status, ONLY from get_order_details READS (never mutation outputs
|
| 137 |
+
like 'address_updated'/'exchange requested'), pairing each call to its output."""
|
| 138 |
+
st = {}
|
| 139 |
+
|
| 140 |
+
def add(out):
|
| 141 |
+
try:
|
| 142 |
+
o = json.loads(out)
|
| 143 |
+
oid = str(o.get("order_id", "")).lstrip("#")
|
| 144 |
+
# get_order_details outputs carry item/fulfillment structure
|
| 145 |
+
if oid and "status" in o and ("items" in o or "fulfillments" in o):
|
| 146 |
+
st[oid] = o["status"]
|
| 147 |
+
except Exception:
|
| 148 |
+
pass
|
| 149 |
+
|
| 150 |
+
for c in r.get("calls", []):
|
| 151 |
+
if c["name"] == "get_order_details" and c.get("output"):
|
| 152 |
+
add(c["output"])
|
| 153 |
+
# history: pair assistant get_order_details tool_calls to following tool msgs
|
| 154 |
+
hist = r.get("history", [])
|
| 155 |
+
for i, h in enumerate(hist):
|
| 156 |
+
for tc in h.get("tool_calls") or []:
|
| 157 |
+
n = tc.get("name") or (tc.get("function") or {}).get("name", "")
|
| 158 |
+
if n != "get_order_details":
|
| 159 |
+
continue
|
| 160 |
+
# find the next tool message output
|
| 161 |
+
for j in range(i + 1, len(hist)):
|
| 162 |
+
if hist[j].get("role") == "tool" and hist[j].get("content"):
|
| 163 |
+
add(hist[j]["content"]); break
|
| 164 |
+
# also any get_order_details-shaped tool msg (belt and suspenders)
|
| 165 |
+
for h in hist:
|
| 166 |
+
if h.get("role") == "tool" and h.get("content"):
|
| 167 |
+
add(h["content"])
|
| 168 |
+
return st
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def lint_row(r, name_vocab=frozenset()):
|
| 172 |
+
flags = []
|
| 173 |
+
method, first, last, zipc, email = auth_identity(r)
|
| 174 |
+
allowed = {x.lower() for x in (first, last) if x}
|
| 175 |
+
turns = list(convo_turns(r))
|
| 176 |
+
argvals = call_arg_values(r)
|
| 177 |
+
|
| 178 |
+
# A. name mismatch (agent addressing a wrong first name that is a real customer name)
|
| 179 |
+
wrong_names = set()
|
| 180 |
+
for role, c in turns:
|
| 181 |
+
if role != "assistant":
|
| 182 |
+
continue
|
| 183 |
+
for m in list(ADDR_RX.finditer(c)) + list(ADDR_RX2.finditer(c)):
|
| 184 |
+
tok = m.group(1)
|
| 185 |
+
if tok in STOP:
|
| 186 |
+
continue
|
| 187 |
+
if allowed and tok.lower() not in allowed:
|
| 188 |
+
wrong_names.add(tok)
|
| 189 |
+
if wrong_names:
|
| 190 |
+
flags.append(("name_mismatch", {"spoken": sorted(wrong_names),
|
| 191 |
+
"auth_first": first, "auth_last": last}))
|
| 192 |
+
|
| 193 |
+
# B. duplicate verification
|
| 194 |
+
vcount = sum(1 for role, c in turns if role == "assistant" and VERIFIED_RX.search(c))
|
| 195 |
+
if vcount > 1:
|
| 196 |
+
flags.append(("dup_verification", {"count": vcount}))
|
| 197 |
+
|
| 198 |
+
# C. zip mismatch (any spoken zip in a 'zip' context that != auth zip)
|
| 199 |
+
if zipc:
|
| 200 |
+
spoken_zips = set()
|
| 201 |
+
for role, c in turns:
|
| 202 |
+
for m in ZIP_CTX_RX.finditer(c):
|
| 203 |
+
spoken_zips.add(m.group(1))
|
| 204 |
+
bad = {z for z in spoken_zips if z != str(zipc) and z.lower() not in argvals}
|
| 205 |
+
if bad:
|
| 206 |
+
flags.append(("zip_mismatch", {"spoken": sorted(bad), "auth_zip": str(zipc)}))
|
| 207 |
+
|
| 208 |
+
# D. email mismatch (spoken email != auth/account email)
|
| 209 |
+
if email:
|
| 210 |
+
spoken = set()
|
| 211 |
+
for role, c in turns:
|
| 212 |
+
for m in EMAIL_RX.finditer(c):
|
| 213 |
+
spoken.add(m.group(0).lower())
|
| 214 |
+
bad = {e for e in spoken if e != email.lower() and e not in argvals}
|
| 215 |
+
if bad:
|
| 216 |
+
flags.append(("email_mismatch", {"spoken": sorted(bad), "auth_email": email}))
|
| 217 |
+
|
| 218 |
+
# E. status-lock (tool name asserts a status the order doesn't have)
|
| 219 |
+
st = order_statuses(r)
|
| 220 |
+
for i, c in enumerate(r["calls"]):
|
| 221 |
+
n = c["name"]
|
| 222 |
+
oid = str((c.get("arguments") or {}).get("order_id", "")).lstrip("#")
|
| 223 |
+
s = st.get(oid)
|
| 224 |
+
if not s:
|
| 225 |
+
continue
|
| 226 |
+
if n in DELIVERED and s != "delivered":
|
| 227 |
+
flags.append(("status_lock", {"call": n, "order": oid, "status": s, "needs": "delivered"}))
|
| 228 |
+
if n in PENDING and s != "pending":
|
| 229 |
+
flags.append(("status_lock", {"call": n, "order": oid, "status": s, "needs": "pending"}))
|
| 230 |
+
|
| 231 |
+
# F. raw-JSON assistant content
|
| 232 |
+
for role, c in turns:
|
| 233 |
+
if role == "assistant":
|
| 234 |
+
cs = c.strip()
|
| 235 |
+
if cs.startswith("{") and cs.endswith("}"):
|
| 236 |
+
try:
|
| 237 |
+
j = json.loads(cs)
|
| 238 |
+
if isinstance(j, dict):
|
| 239 |
+
flags.append(("json_assistant", {"snippet": cs[:80]}))
|
| 240 |
+
break
|
| 241 |
+
except Exception:
|
| 242 |
+
if '"message"' in cs or '":' in cs:
|
| 243 |
+
flags.append(("json_assistant", {"snippet": cs[:80]}))
|
| 244 |
+
break
|
| 245 |
+
|
| 246 |
+
# G. markdown in user messages
|
| 247 |
+
md = []
|
| 248 |
+
for role, c in turns:
|
| 249 |
+
if role != "user":
|
| 250 |
+
continue
|
| 251 |
+
if MD_BOLD_RX.search(c):
|
| 252 |
+
md.append("bold")
|
| 253 |
+
if MD_LIST_RX.search(c):
|
| 254 |
+
md.append("list")
|
| 255 |
+
if MD_HEADER_RX.search(c):
|
| 256 |
+
md.append("header")
|
| 257 |
+
if md:
|
| 258 |
+
flags.append(("markdown_user", {"kinds": sorted(set(md))}))
|
| 259 |
+
|
| 260 |
+
return flags
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def main():
|
| 264 |
+
rows = [json.loads(l) for l in open(SRC, encoding="utf-8")]
|
| 265 |
+
# global first-name vocabulary from auth calls / account details
|
| 266 |
+
name_vocab = set()
|
| 267 |
+
for r in rows:
|
| 268 |
+
_, f, l, _, _ = auth_identity(r)
|
| 269 |
+
for x in (f, l):
|
| 270 |
+
if x:
|
| 271 |
+
name_vocab.add(x.lower())
|
| 272 |
+
cat = Counter()
|
| 273 |
+
per_orig = defaultdict(set)
|
| 274 |
+
out = []
|
| 275 |
+
for r in rows:
|
| 276 |
+
fl = lint_row(r, name_vocab)
|
| 277 |
+
if fl:
|
| 278 |
+
for k, _ in fl:
|
| 279 |
+
cat[k] += 1
|
| 280 |
+
out.append({"example_id": r["example_id"],
|
| 281 |
+
"orig_eid": r["metadata"].get("orig_eid"),
|
| 282 |
+
"role": r["metadata"].get("unbundle_role"),
|
| 283 |
+
"flags": fl})
|
| 284 |
+
for k, _ in fl:
|
| 285 |
+
per_orig[k].add(r["metadata"].get("orig_eid"))
|
| 286 |
+
with open(OUT, "w", encoding="utf-8") as f:
|
| 287 |
+
for o in out:
|
| 288 |
+
f.write(json.dumps(o) + "\n")
|
| 289 |
+
|
| 290 |
+
print(f"rows scanned: {len(rows)}")
|
| 291 |
+
print(f"rows with >=1 flag: {len(out)}")
|
| 292 |
+
print("\n=== defect counts (per ROW) ===")
|
| 293 |
+
order = ["name_mismatch","dup_verification","zip_mismatch","email_mismatch",
|
| 294 |
+
"status_lock","json_assistant","markdown_user"]
|
| 295 |
+
for k in order:
|
| 296 |
+
print(f" {k:16s} rows={cat[k]:4d} distinct_episodes={len(per_orig[k])}")
|
| 297 |
+
print(f"\nwrote {OUT}")
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
if __name__ == "__main__":
|
| 301 |
+
main()
|
tempscripts/story_remediation/unbundle/author_q1_fix_v3.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Targeted q1 fix for the 23 auth-in-history candidates.
|
| 2 |
+
|
| 3 |
+
Their authentication now lives in the cleaned pre-history, so q1 must NOT greet
|
| 4 |
+
or restate name/ZIP/email. v2 authored several that still said "Hi, I'm X, ZIP
|
| 5 |
+
Y" -> a redundant re-introduction tell. Re-author ONLY q1 for these rows with an
|
| 6 |
+
already-verified framing. ack1/turns are reused from authored_v2.json unchanged.
|
| 7 |
+
|
| 8 |
+
Cache -> out/authored_q1fix_v3.json {eid: {"q1": ...}}
|
| 9 |
+
Run: python -u temp/story_remediation/unbundle/author_q1_fix_v3.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json, re, sys, logging
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import yaml
|
| 15 |
+
|
| 16 |
+
HERE = Path(__file__).resolve().parent
|
| 17 |
+
ROOT = HERE.parents[2]
|
| 18 |
+
sys.path.insert(0, str(ROOT))
|
| 19 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 20 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 21 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 22 |
+
|
| 23 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 24 |
+
AUTHORED = HERE / "out" / "authored_v2.json"
|
| 25 |
+
OUT = HERE / "out" / "authored_q1fix_v3.json"
|
| 26 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 27 |
+
AUTH_LEAD = ("find_user_id_by_name_zip", "get_user_details")
|
| 28 |
+
_TOK = re.compile(r"#W\d+|gift_card_\w+|\bgc_\w+|\b\d{8,}\b")
|
| 29 |
+
|
| 30 |
+
SYS = (
|
| 31 |
+
"The customer has ALREADY been greeted and their identity is ALREADY verified "
|
| 32 |
+
"earlier in the conversation. Write ONLY their next message: the request that "
|
| 33 |
+
"makes the agent perform the listed actions.\n\n"
|
| 34 |
+
"Rules:\n"
|
| 35 |
+
"1. Do NOT greet ('hi/hello') and do NOT restate name, ZIP, email, or phone. "
|
| 36 |
+
"Jump straight to the request.\n"
|
| 37 |
+
"2. The message must motivate exactly the listed actions, nothing more.\n"
|
| 38 |
+
"3. Copy every identifier (order #W..., item numbers, gift card ids, amounts, "
|
| 39 |
+
"quoted text) verbatim from the arguments.\n"
|
| 40 |
+
"4. Natural, human, concise. NO em dashes or en dashes.\n"
|
| 41 |
+
'Return ONLY JSON: {"q1": "<message>"}'
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def toks(*xs):
|
| 46 |
+
s = set()
|
| 47 |
+
for x in xs:
|
| 48 |
+
if x:
|
| 49 |
+
s |= set(_TOK.findall(x if isinstance(x, str) else json.dumps(x)))
|
| 50 |
+
return s
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def main():
|
| 54 |
+
rows = {json.loads(l)["example_id"]: json.loads(l)
|
| 55 |
+
for l in open(N100, encoding="utf-8") if l.strip()}
|
| 56 |
+
authored = json.loads(AUTHORED.read_text(encoding="utf-8"))
|
| 57 |
+
|
| 58 |
+
def hist(r):
|
| 59 |
+
return r.get("history") or (r.get("metadata") or {}).get("history") or []
|
| 60 |
+
|
| 61 |
+
targets = []
|
| 62 |
+
for eid, r in rows.items():
|
| 63 |
+
if eid not in authored or "q1" not in authored[eid]:
|
| 64 |
+
continue
|
| 65 |
+
if any(t["name"] == "find_user_id_by_name_zip"
|
| 66 |
+
for m in hist(r) for t in (m.get("tool_calls") or [])):
|
| 67 |
+
targets.append(eid)
|
| 68 |
+
print(f"auth-in-history targets: {len(targets)}")
|
| 69 |
+
|
| 70 |
+
judge = make_judge(cfg["model"])
|
| 71 |
+
out = json.loads(OUT.read_text(encoding="utf-8")) if OUT.exists() else {}
|
| 72 |
+
for eid in targets:
|
| 73 |
+
if eid in out:
|
| 74 |
+
continue
|
| 75 |
+
r = rows[eid]; ad = r["metadata"]["anchor_depth"]; K = ad + 1
|
| 76 |
+
calls = r["calls"]
|
| 77 |
+
fu = next(t for m in hist(r) for t in (m.get("tool_calls") or [])
|
| 78 |
+
if t["name"] == "find_user_id_by_name_zip")
|
| 79 |
+
a = fu.get("arguments", {})
|
| 80 |
+
ident = {str(a.get("first_name", "")).lower(), str(a.get("last_name", "")).lower()} - {""}
|
| 81 |
+
user = json.dumps({
|
| 82 |
+
"original_customer_message": r["query"],
|
| 83 |
+
"actions_to_trigger": [{"tool": c["name"], "arguments": c.get("arguments", {})}
|
| 84 |
+
for c in calls[:K]],
|
| 85 |
+
}, ensure_ascii=False, indent=2)
|
| 86 |
+
allowed = toks(r["query"], *[c.get("arguments", {}) for c in calls])
|
| 87 |
+
chosen = None
|
| 88 |
+
for _ in range(3):
|
| 89 |
+
try:
|
| 90 |
+
res = judge.judge({"system": SYS, "user": user})
|
| 91 |
+
except Exception:
|
| 92 |
+
continue
|
| 93 |
+
q1 = (res.get("q1") or "").strip()
|
| 94 |
+
if not q1 or "\u2014" in q1 or "\u2013" in q1 or " - " in q1:
|
| 95 |
+
continue
|
| 96 |
+
if toks(q1) - allowed:
|
| 97 |
+
continue
|
| 98 |
+
if any(tok and len(tok) >= 3 and tok in q1.lower() for tok in ident):
|
| 99 |
+
continue
|
| 100 |
+
chosen = q1; break
|
| 101 |
+
if chosen:
|
| 102 |
+
out[eid] = {"q1": chosen}
|
| 103 |
+
else:
|
| 104 |
+
print(f" FAILED {eid} (keeping v2 q1)")
|
| 105 |
+
OUT.write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
|
| 106 |
+
print(f"fixed {len(out)}/{len(targets)} -> {OUT.relative_to(ROOT)}")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
main()
|
tempscripts/story_remediation/unbundle/author_splits.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM authoring pass for the full unbundle rollout.
|
| 2 |
+
|
| 3 |
+
For every candidate (metadata.anchor_depth>=2 AND a non-empty tail), ask the
|
| 4 |
+
model to rewrite the single bundled query into natural multi-turn dialogue:
|
| 5 |
+
- q1: motivates ONLY turn 1 (auth + lookups + the divergence action F).
|
| 6 |
+
- turns[]: one entry per tail call, each a natural user follow-up + a short
|
| 7 |
+
assistant confirmation (bridge). One action per turn (matches real tau2's
|
| 8 |
+
~92% one-call turns).
|
| 9 |
+
|
| 10 |
+
CRITICAL invariants enforced by validation (retry on failure, skip if hopeless):
|
| 11 |
+
- len(turns) == len(tail_calls)
|
| 12 |
+
- no em dashes
|
| 13 |
+
- no NEW identifiers: every #W.../gift_card_.../long-digit token in the
|
| 14 |
+
generated text must already appear in the original query or a call's args
|
| 15 |
+
- tail-only ids must NOT leak into q1 (keeps turn 1 narrowed)
|
| 16 |
+
|
| 17 |
+
Caches to out/authored.json ({eid: {q1, turns:[{user,bridge}], skipped?}}).
|
| 18 |
+
Re-runs only fill missing/failed eids (idempotent).
|
| 19 |
+
|
| 20 |
+
Run: python -u temp/story_remediation/unbundle/author_splits.py
|
| 21 |
+
"""
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
import json, re, sys, threading
|
| 24 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
import yaml
|
| 27 |
+
|
| 28 |
+
HERE = Path(__file__).resolve().parent
|
| 29 |
+
ROOT = HERE.parents[2]
|
| 30 |
+
sys.path.insert(0, str(ROOT))
|
| 31 |
+
import logging
|
| 32 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 33 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 34 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 35 |
+
|
| 36 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 37 |
+
AUTHORED = HERE / "out" / "authored.json"
|
| 38 |
+
|
| 39 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 40 |
+
WORKERS = 8
|
| 41 |
+
|
| 42 |
+
SYS = (
|
| 43 |
+
"You rewrite ONE retail customer-support conversation so it reads as natural, "
|
| 44 |
+
"multi-turn dialogue instead of a single giant request.\n\n"
|
| 45 |
+
"You are given the customer's original bundled message and the ordered list of "
|
| 46 |
+
"backend actions the agent took (tool name + arguments). The FIRST GROUP of "
|
| 47 |
+
"actions (authentication + lookups + the primary action) all happen in turn 1. "
|
| 48 |
+
"Each remaining TAIL action becomes its own separate later turn.\n\n"
|
| 49 |
+
"Return a JSON object exactly like:\n"
|
| 50 |
+
'{ "q1": "<turn-1 customer message>", "turns": [ {"user":"<message>","bridge":"<agent one-line confirmation>"}, ... ] }\n\n'
|
| 51 |
+
"Rules:\n"
|
| 52 |
+
"1. q1 motivates ONLY the turn-1 actions. Do NOT mention or hint at any tail action.\n"
|
| 53 |
+
"2. Provide exactly one entry in \"turns\" per tail action, in the same order. Each "
|
| 54 |
+
"\"user\" message must naturally trigger exactly that one action; \"bridge\" is the "
|
| 55 |
+
"agent's short confirming reply that precedes it.\n"
|
| 56 |
+
"3. The customer is ALREADY authenticated after turn 1. Later turns must NOT ask to "
|
| 57 |
+
"re-verify identity or re-share name / ZIP / email / phone.\n"
|
| 58 |
+
"4. Copy every identifier verbatim from the provided arguments: order ids (#W...), "
|
| 59 |
+
"item / product numbers, gift card ids, dollar amounts, and any exact quoted message "
|
| 60 |
+
"or review text. NEVER invent, drop, or alter an id.\n"
|
| 61 |
+
"5. Natural, human, concise. Vary the phrasing of follow-ups (for example 'Thanks, "
|
| 62 |
+
"one more thing', 'Got it, could you also', 'Perfect. Now'). Contractions are good.\n"
|
| 63 |
+
"6. Absolutely NO em dashes or en dashes. Use commas, periods, or parentheses.\n"
|
| 64 |
+
"Return ONLY the JSON object."
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
_TOK = re.compile(r"#W\d+|gift_card_\w+|\bgc_\w+|\b\d{8,}\b")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def toks(*strings):
|
| 71 |
+
s = set()
|
| 72 |
+
for x in strings:
|
| 73 |
+
if x:
|
| 74 |
+
s |= set(_TOK.findall(x if isinstance(x, str) else json.dumps(x)))
|
| 75 |
+
return s
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def build_user(row, K):
|
| 79 |
+
calls = row["calls"]
|
| 80 |
+
def fmt(c):
|
| 81 |
+
return {"tool": c["name"], "arguments": c.get("arguments", {})}
|
| 82 |
+
turn1 = [fmt(c) for c in calls[:K]]
|
| 83 |
+
tail = [fmt(c) for c in calls[K:]]
|
| 84 |
+
return json.dumps({
|
| 85 |
+
"original_customer_message": row["query"],
|
| 86 |
+
"turn1_actions": turn1,
|
| 87 |
+
"tail_actions_each_its_own_turn": tail,
|
| 88 |
+
}, ensure_ascii=False, indent=2)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def validate(row, K, out):
|
| 92 |
+
calls = row["calls"]
|
| 93 |
+
tail = calls[K:]
|
| 94 |
+
if not isinstance(out, dict):
|
| 95 |
+
return "not a dict"
|
| 96 |
+
q1 = out.get("q1"); turns = out.get("turns")
|
| 97 |
+
if not isinstance(q1, str) or not q1.strip():
|
| 98 |
+
return "empty q1"
|
| 99 |
+
if not isinstance(turns, list) or len(turns) != len(tail):
|
| 100 |
+
return f"turns len {len(turns) if isinstance(turns,list) else '?'} != tail {len(tail)}"
|
| 101 |
+
texts = [q1] + [str(t.get("user", "")) + " " + str(t.get("bridge", "")) for t in turns]
|
| 102 |
+
for t in texts:
|
| 103 |
+
if "\u2014" in t or "\u2013" in t or " - " in t:
|
| 104 |
+
return "dash present"
|
| 105 |
+
# allowed identifier universe = original query + all call args
|
| 106 |
+
allowed = toks(row["query"], *[c.get("arguments", {}) for c in calls])
|
| 107 |
+
gen = toks(*texts)
|
| 108 |
+
new = gen - allowed
|
| 109 |
+
if new:
|
| 110 |
+
return f"new ids {sorted(new)[:4]}"
|
| 111 |
+
# tail-only ids must not leak into q1
|
| 112 |
+
prefix_ids = toks(row["query"]) & toks(*[c.get("arguments", {}) for c in calls[:K]])
|
| 113 |
+
tail_ids = toks(*[c.get("arguments", {}) for c in tail]) - toks(*[c.get("arguments", {}) for c in calls[:K]])
|
| 114 |
+
leak = toks(q1) & tail_ids
|
| 115 |
+
if leak:
|
| 116 |
+
return f"tail id leaked into q1 {sorted(leak)}"
|
| 117 |
+
for t in turns:
|
| 118 |
+
if not isinstance(t, dict) or not str(t.get("user", "")).strip():
|
| 119 |
+
return "empty tail user"
|
| 120 |
+
return None
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def main():
|
| 124 |
+
rows = {json.loads(l)["example_id"]: json.loads(l)
|
| 125 |
+
for l in open(N100, encoding="utf-8") if l.strip()}
|
| 126 |
+
cand = []
|
| 127 |
+
for eid, r in rows.items():
|
| 128 |
+
md = r.get("metadata") or {}; ad = md.get("anchor_depth")
|
| 129 |
+
calls = r.get("calls") or []
|
| 130 |
+
if ad is None or ad < 2 or len(calls) <= ad + 1:
|
| 131 |
+
continue
|
| 132 |
+
cand.append(eid)
|
| 133 |
+
cand.sort()
|
| 134 |
+
print(f"candidates: {len(cand)}")
|
| 135 |
+
|
| 136 |
+
authored = {}
|
| 137 |
+
if AUTHORED.exists():
|
| 138 |
+
authored = json.loads(AUTHORED.read_text(encoding="utf-8"))
|
| 139 |
+
todo = [e for e in cand if e not in authored or authored[e].get("_err")]
|
| 140 |
+
print(f"already done: {len(cand)-len(todo)} to author: {len(todo)}")
|
| 141 |
+
|
| 142 |
+
judge = make_judge(cfg["model"])
|
| 143 |
+
lock = threading.Lock()
|
| 144 |
+
done = [0]
|
| 145 |
+
|
| 146 |
+
def work(eid):
|
| 147 |
+
r = rows[eid]; K = r["metadata"]["anchor_depth"] + 1
|
| 148 |
+
user = build_user(r, K)
|
| 149 |
+
last = None
|
| 150 |
+
for attempt in range(3):
|
| 151 |
+
try:
|
| 152 |
+
out = judge.judge({"system": SYS, "user": user})
|
| 153 |
+
except Exception as e: # noqa
|
| 154 |
+
last = f"api:{e}"; continue
|
| 155 |
+
err = validate(r, K, out)
|
| 156 |
+
if err is None:
|
| 157 |
+
rec = {"q1": out["q1"].strip(),
|
| 158 |
+
"turns": [{"user": t["user"].strip(),
|
| 159 |
+
"bridge": str(t.get("bridge", "")).strip()} for t in out["turns"]]}
|
| 160 |
+
with lock:
|
| 161 |
+
authored[eid] = rec; done[0] += 1
|
| 162 |
+
if done[0] % 20 == 0:
|
| 163 |
+
AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8")
|
| 164 |
+
print(f" ...{done[0]}/{len(todo)}")
|
| 165 |
+
return
|
| 166 |
+
last = err
|
| 167 |
+
with lock:
|
| 168 |
+
authored[eid] = {"_err": last or "unknown"}
|
| 169 |
+
print(f" SKIP {eid}: {last}")
|
| 170 |
+
|
| 171 |
+
AUTHORED.parent.mkdir(parents=True, exist_ok=True)
|
| 172 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 173 |
+
list(ex.map(work, todo))
|
| 174 |
+
AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8")
|
| 175 |
+
|
| 176 |
+
ok = sum(1 for e in cand if not authored.get(e, {}).get("_err") and "q1" in authored.get(e, {}))
|
| 177 |
+
err = [e for e in cand if authored.get(e, {}).get("_err")]
|
| 178 |
+
print(f"\nauthored ok: {ok}/{len(cand)} failed/skipped: {len(err)}")
|
| 179 |
+
for e in err[:15]:
|
| 180 |
+
print(" ", e, authored[e]["_err"])
|
| 181 |
+
print(f"wrote {AUTHORED.relative_to(ROOT)}")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
main()
|
tempscripts/story_remediation/unbundle/author_splits_v2.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""V2 authoring: fix the bridge-ordering logic bug.
|
| 2 |
+
|
| 3 |
+
The v1 'bridge' confirmed the action the customer was ABOUT to request, which
|
| 4 |
+
produced a time-travel contradiction (agent: "I've filed the claim" -> user:
|
| 5 |
+
"please file the claim" -> agent files it). C3 caught ~94% of tail turns on that.
|
| 6 |
+
|
| 7 |
+
V2 schema makes every acknowledgement PAST-TENSE and about its OWN turn's action
|
| 8 |
+
only. An ack is only ever shown once its turn is completed, so no confirmation
|
| 9 |
+
can precede its request:
|
| 10 |
+
|
| 11 |
+
{
|
| 12 |
+
"q1": "<turn-1 user message: auth + lookups + the first action>",
|
| 13 |
+
"ack1": "<agent confirms ONLY what turn 1 did, past tense>",
|
| 14 |
+
"turns":[ {"user":"<request for tail call k>", "ack":"<agent confirms THAT
|
| 15 |
+
call, past tense>"}, ... ] # one per tail call, in order
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
Cache -> out/authored_v2.json (idempotent; re-fills only missing/failed).
|
| 19 |
+
Run: python -u temp/story_remediation/unbundle/author_splits_v2.py
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
import json, re, sys, threading, logging
|
| 23 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
import yaml
|
| 26 |
+
|
| 27 |
+
HERE = Path(__file__).resolve().parent
|
| 28 |
+
ROOT = HERE.parents[2]
|
| 29 |
+
sys.path.insert(0, str(ROOT))
|
| 30 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 31 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 32 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 33 |
+
|
| 34 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 35 |
+
AUTHORED = HERE / "out" / "authored_v2.json"
|
| 36 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 37 |
+
WORKERS = 8
|
| 38 |
+
|
| 39 |
+
SYS = (
|
| 40 |
+
"You rewrite ONE retail customer-support conversation so it reads as a natural, "
|
| 41 |
+
"coherent multi-turn dialogue instead of a single giant request. The conversation "
|
| 42 |
+
"must make perfect sense read start to finish.\n\n"
|
| 43 |
+
"You are given the customer's original bundled message and the ordered backend "
|
| 44 |
+
"actions the agent took (tool name + arguments). The FIRST GROUP of actions "
|
| 45 |
+
"(authentication + lookups + the first real action) all happen in TURN 1. Each "
|
| 46 |
+
"remaining TAIL action becomes its own separate later turn, in order.\n\n"
|
| 47 |
+
"Return a JSON object EXACTLY like:\n"
|
| 48 |
+
'{ "q1": "<turn-1 customer message>", "ack1": "<agent reply AFTER turn 1>",\n'
|
| 49 |
+
' "turns": [ {"user":"<customer message>","ack":"<agent reply AFTER doing it>"}, ... ] }\n\n'
|
| 50 |
+
"THE #1 RULE (this is what you are fixing): An agent reply may ONLY confirm actions "
|
| 51 |
+
"that have ALREADY been performed. It must be PAST TENSE and describe ONLY its own "
|
| 52 |
+
"turn's action. NEVER let an agent say it did something the customer has not yet "
|
| 53 |
+
"asked for. Do not preview or promise the next step.\n"
|
| 54 |
+
" - ack1 confirms ONLY the turn-1 actions. It must NOT mention any tail action.\n"
|
| 55 |
+
" - Each turns[k].ack confirms ONLY that same turn's single action.\n\n"
|
| 56 |
+
"Other rules:\n"
|
| 57 |
+
"1. q1 motivates ONLY the turn-1 actions. Do NOT mention or hint at any tail action.\n"
|
| 58 |
+
"2. Exactly one entry in \"turns\" per tail action, same order. Each \"user\" message "
|
| 59 |
+
"naturally triggers exactly that one action and nothing else.\n"
|
| 60 |
+
"3. The customer is ALREADY authenticated after turn 1. Later turns must NOT re-verify "
|
| 61 |
+
"identity or re-share name / ZIP / email / phone (unless an action's arguments are "
|
| 62 |
+
"about a DIFFERENT person, e.g. looking up a relative, which is fine).\n"
|
| 63 |
+
"4. Do NOT re-request anything already done in an earlier turn.\n"
|
| 64 |
+
"5. Copy every identifier verbatim from the arguments: order ids (#W...), item / "
|
| 65 |
+
"product numbers, gift card ids, dollar amounts, exact quoted message or review text. "
|
| 66 |
+
"NEVER invent, drop, or alter an id.\n"
|
| 67 |
+
"6. Natural, human, concise. Vary follow-up phrasing ('Thanks, one more thing', 'Got "
|
| 68 |
+
"it, could you also', 'Perfect, now'). Contractions are good.\n"
|
| 69 |
+
"7. Absolutely NO em dashes or en dashes. Use commas, periods, or parentheses.\n"
|
| 70 |
+
"Return ONLY the JSON object."
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
_TOK = re.compile(r"#W\d+|gift_card_\w+|\bgc_\w+|\b\d{8,}\b")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def toks(*strings):
|
| 77 |
+
s = set()
|
| 78 |
+
for x in strings:
|
| 79 |
+
if x:
|
| 80 |
+
s |= set(_TOK.findall(x if isinstance(x, str) else json.dumps(x)))
|
| 81 |
+
return s
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def build_user(row, K):
|
| 85 |
+
calls = row["calls"]
|
| 86 |
+
fmt = lambda c: {"tool": c["name"], "arguments": c.get("arguments", {})}
|
| 87 |
+
return json.dumps({
|
| 88 |
+
"original_customer_message": row["query"],
|
| 89 |
+
"turn1_actions": [fmt(c) for c in calls[:K]],
|
| 90 |
+
"tail_actions_each_its_own_turn": [fmt(c) for c in calls[K:]],
|
| 91 |
+
}, ensure_ascii=False, indent=2)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def validate(row, K, out):
|
| 95 |
+
calls = row["calls"]; tail = calls[K:]
|
| 96 |
+
if not isinstance(out, dict):
|
| 97 |
+
return "not a dict"
|
| 98 |
+
q1 = out.get("q1"); ack1 = out.get("ack1"); turns = out.get("turns")
|
| 99 |
+
if not isinstance(q1, str) or not q1.strip():
|
| 100 |
+
return "empty q1"
|
| 101 |
+
if not isinstance(ack1, str) or not ack1.strip():
|
| 102 |
+
return "empty ack1"
|
| 103 |
+
if not isinstance(turns, list) or len(turns) != len(tail):
|
| 104 |
+
return f"turns len {len(turns) if isinstance(turns,list) else '?'} != tail {len(tail)}"
|
| 105 |
+
texts = [q1, ack1]
|
| 106 |
+
for t in turns:
|
| 107 |
+
if not isinstance(t, dict) or not str(t.get("user", "")).strip() or not str(t.get("ack", "")).strip():
|
| 108 |
+
return "empty turn user/ack"
|
| 109 |
+
texts += [t["user"], t["ack"]]
|
| 110 |
+
for t in texts:
|
| 111 |
+
if "\u2014" in t or "\u2013" in t or " - " in t:
|
| 112 |
+
return "dash present"
|
| 113 |
+
allowed = toks(row["query"], *[c.get("arguments", {}) for c in calls])
|
| 114 |
+
new = toks(*texts) - allowed
|
| 115 |
+
if new:
|
| 116 |
+
return f"new ids {sorted(new)[:4]}"
|
| 117 |
+
tail_ids = (toks(*[c.get("arguments", {}) for c in tail])
|
| 118 |
+
- toks(*[c.get("arguments", {}) for c in calls[:K]]))
|
| 119 |
+
leak = toks(q1, ack1) & tail_ids
|
| 120 |
+
if leak:
|
| 121 |
+
return f"tail id leaked into q1/ack1 {sorted(leak)}"
|
| 122 |
+
return None
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def main():
|
| 126 |
+
rows = {json.loads(l)["example_id"]: json.loads(l)
|
| 127 |
+
for l in open(N100, encoding="utf-8") if l.strip()}
|
| 128 |
+
cand = []
|
| 129 |
+
for eid, r in rows.items():
|
| 130 |
+
md = r.get("metadata") or {}; ad = md.get("anchor_depth")
|
| 131 |
+
calls = r.get("calls") or []
|
| 132 |
+
if ad is None or ad < 2 or len(calls) <= ad + 1:
|
| 133 |
+
continue
|
| 134 |
+
cand.append(eid)
|
| 135 |
+
cand.sort()
|
| 136 |
+
print(f"candidates: {len(cand)}")
|
| 137 |
+
|
| 138 |
+
authored = {}
|
| 139 |
+
if AUTHORED.exists():
|
| 140 |
+
authored = json.loads(AUTHORED.read_text(encoding="utf-8"))
|
| 141 |
+
todo = [e for e in cand if e not in authored or authored[e].get("_err")]
|
| 142 |
+
print(f"already done: {len(cand)-len(todo)} to author: {len(todo)}")
|
| 143 |
+
|
| 144 |
+
judge = make_judge(cfg["model"])
|
| 145 |
+
lock = threading.Lock(); done = [0]
|
| 146 |
+
|
| 147 |
+
def work(eid):
|
| 148 |
+
r = rows[eid]; K = r["metadata"]["anchor_depth"] + 1
|
| 149 |
+
user = build_user(r, K); last = None
|
| 150 |
+
for _ in range(3):
|
| 151 |
+
try:
|
| 152 |
+
out = judge.judge({"system": SYS, "user": user})
|
| 153 |
+
except Exception as e: # noqa
|
| 154 |
+
last = f"api:{e}"; continue
|
| 155 |
+
err = validate(r, K, out)
|
| 156 |
+
if err is None:
|
| 157 |
+
rec = {"q1": out["q1"].strip(), "ack1": out["ack1"].strip(),
|
| 158 |
+
"turns": [{"user": t["user"].strip(), "ack": t["ack"].strip()}
|
| 159 |
+
for t in out["turns"]]}
|
| 160 |
+
with lock:
|
| 161 |
+
authored[eid] = rec; done[0] += 1
|
| 162 |
+
if done[0] % 20 == 0:
|
| 163 |
+
AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8")
|
| 164 |
+
print(f" ...{done[0]}/{len(todo)}")
|
| 165 |
+
return
|
| 166 |
+
last = err
|
| 167 |
+
with lock:
|
| 168 |
+
authored[eid] = {"_err": last or "unknown"}
|
| 169 |
+
print(f" SKIP {eid}: {last}")
|
| 170 |
+
|
| 171 |
+
AUTHORED.parent.mkdir(parents=True, exist_ok=True)
|
| 172 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 173 |
+
list(ex.map(work, todo))
|
| 174 |
+
AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8")
|
| 175 |
+
|
| 176 |
+
ok = sum(1 for e in cand if "q1" in authored.get(e, {}) and not authored.get(e, {}).get("_err"))
|
| 177 |
+
err = [e for e in cand if authored.get(e, {}).get("_err")]
|
| 178 |
+
print(f"\nauthored ok: {ok}/{len(cand)} failed/skipped: {len(err)}")
|
| 179 |
+
for e in err[:15]:
|
| 180 |
+
print(" ", e, authored[e]["_err"])
|
| 181 |
+
print(f"wrote {AUTHORED.relative_to(ROOT)}")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
main()
|
tempscripts/story_remediation/unbundle/author_splits_v4.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""V4 authoring: humanize the split rows' dialogue to kill the two authorable C3
|
| 2 |
+
tells found in v3 tail reasoning:
|
| 3 |
+
(a) "customer front-loads name+ZIP+order in one tidy sentence" -> too clean.
|
| 4 |
+
(b) "agent verified silently, never asked" -> no auth handshake.
|
| 5 |
+
|
| 6 |
+
Fix is PROSE ONLY. The tool calls are never touched (guaranteed in the builder).
|
| 7 |
+
q1 is now framed as the customer's REPLY to the agent asking them to verify their
|
| 8 |
+
identity, so it opens with mild human disfluency and provides name/ZIP naturally
|
| 9 |
+
rather than dumping everything up front. All user turns carry light, realistic
|
| 10 |
+
friction. Everything else (past-tense own-turn acks, verbatim ids, no dashes) is
|
| 11 |
+
unchanged from v2.
|
| 12 |
+
|
| 13 |
+
Cache -> out/authored_v4.json (idempotent). Run:
|
| 14 |
+
python -u temp/story_remediation/unbundle/author_splits_v4.py
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
import json, re, sys, threading, logging
|
| 18 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
import yaml
|
| 21 |
+
|
| 22 |
+
HERE = Path(__file__).resolve().parent
|
| 23 |
+
ROOT = HERE.parents[2]
|
| 24 |
+
sys.path.insert(0, str(ROOT))
|
| 25 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 26 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 27 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 28 |
+
|
| 29 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 30 |
+
AUTHORED = HERE / "out" / "authored_v4.json"
|
| 31 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 32 |
+
WORKERS = 8
|
| 33 |
+
|
| 34 |
+
SYS = (
|
| 35 |
+
"You rewrite ONE retail customer-support conversation so it reads as a natural, "
|
| 36 |
+
"coherent multi-turn dialogue instead of a single giant request. It must make "
|
| 37 |
+
"perfect sense read start to finish, and above all it must sound like a REAL human "
|
| 38 |
+
"customer, not a tidy scripted prompt.\n\n"
|
| 39 |
+
"Framing of the opening: the agent has greeted the customer, the customer said they "
|
| 40 |
+
"need help, and the agent has just asked them to VERIFY their identity by giving "
|
| 41 |
+
"their name and ZIP code. So TURN 1 (q1) is the customer's REPLY to that request.\n\n"
|
| 42 |
+
"You are given the customer's original bundled message and the ordered backend "
|
| 43 |
+
"actions the agent took (tool name + arguments). The FIRST GROUP of actions "
|
| 44 |
+
"(authentication + lookups + the first real action) all happen in TURN 1. Each "
|
| 45 |
+
"remaining TAIL action becomes its own separate later turn, in order.\n\n"
|
| 46 |
+
"Return a JSON object EXACTLY like:\n"
|
| 47 |
+
'{ "q1": "<turn-1 customer message>", "ack1": "<agent reply AFTER turn 1>",\n'
|
| 48 |
+
' "turns": [ {"user":"<customer message>","ack":"<agent reply AFTER doing it>"}, ... ] }\n\n'
|
| 49 |
+
"THE #1 RULE: An agent reply may ONLY confirm actions ALREADY performed. It must be "
|
| 50 |
+
"PAST TENSE and describe ONLY its own turn's action. NEVER let an agent say it did "
|
| 51 |
+
"something the customer has not yet asked for. Do not preview or promise a next step.\n"
|
| 52 |
+
" - ack1 confirms ONLY the turn-1 actions. It must NOT mention any tail action.\n"
|
| 53 |
+
" - Each turns[k].ack confirms ONLY that same turn's single action.\n\n"
|
| 54 |
+
"HUMANIZE (this is the new part, do it well):\n"
|
| 55 |
+
"A. q1 is a reply to 'can you verify your name and ZIP'. Start it the way a real "
|
| 56 |
+
"person answers: a small hesitation or filler is good ('Yeah, sure,', 'Oh, right,', "
|
| 57 |
+
"'Um, ok,', 'Sure thing,'), then give the name and ZIP, THEN say what they actually "
|
| 58 |
+
"want. Do NOT machine-list identifiers in one clinical sentence.\n"
|
| 59 |
+
"B. Give the customer mild, realistic friction across turns: slight informality, an "
|
| 60 |
+
"occasional 'I think', 'if that makes sense', 'sorry', a little context about WHY "
|
| 61 |
+
"they want it. Keep it believable, never over the top, never emoji.\n"
|
| 62 |
+
"C. Vary sentence shape and follow-up openers so no two turns feel stamped from a "
|
| 63 |
+
"template ('Thanks, one more thing', 'Ok so', 'Got it. Could you also', 'Perfect, "
|
| 64 |
+
"now', 'Oh and').\n\n"
|
| 65 |
+
"Hard rules:\n"
|
| 66 |
+
"1. q1 motivates ONLY the turn-1 actions. Do NOT mention or hint at any tail action.\n"
|
| 67 |
+
"2. Exactly one entry in \"turns\" per tail action, same order. Each \"user\" message "
|
| 68 |
+
"naturally triggers exactly that one action and nothing else.\n"
|
| 69 |
+
"3. The customer is ALREADY authenticated after turn 1. Later turns must NOT re-verify "
|
| 70 |
+
"identity or re-share name / ZIP / email / phone (unless an action's arguments are "
|
| 71 |
+
"about a DIFFERENT person, which is fine).\n"
|
| 72 |
+
"4. Do NOT re-request anything already done in an earlier turn.\n"
|
| 73 |
+
"5. Copy every identifier verbatim from the arguments: order ids (#W...), item / "
|
| 74 |
+
"product numbers, gift card ids, dollar amounts, exact quoted message or review text. "
|
| 75 |
+
"NEVER invent, drop, or alter an id.\n"
|
| 76 |
+
"6. Absolutely NO em dashes or en dashes. Use commas, periods, or parentheses.\n"
|
| 77 |
+
"Return ONLY the JSON object."
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
_TOK = re.compile(r"#W\d+|gift_card_\w+|\bgc_\w+|\b\d{8,}\b")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def toks(*strings):
|
| 84 |
+
s = set()
|
| 85 |
+
for x in strings:
|
| 86 |
+
if x:
|
| 87 |
+
s |= set(_TOK.findall(x if isinstance(x, str) else json.dumps(x)))
|
| 88 |
+
return s
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def build_user(row, K):
|
| 92 |
+
calls = row["calls"]
|
| 93 |
+
fmt = lambda c: {"tool": c["name"], "arguments": c.get("arguments", {})}
|
| 94 |
+
return json.dumps({
|
| 95 |
+
"original_customer_message": row["query"],
|
| 96 |
+
"turn1_actions": [fmt(c) for c in calls[:K]],
|
| 97 |
+
"tail_actions_each_its_own_turn": [fmt(c) for c in calls[K:]],
|
| 98 |
+
}, ensure_ascii=False, indent=2)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def validate(row, K, out):
|
| 102 |
+
calls = row["calls"]; tail = calls[K:]
|
| 103 |
+
if not isinstance(out, dict):
|
| 104 |
+
return "not a dict"
|
| 105 |
+
q1 = out.get("q1"); ack1 = out.get("ack1"); turns = out.get("turns")
|
| 106 |
+
if not isinstance(q1, str) or not q1.strip():
|
| 107 |
+
return "empty q1"
|
| 108 |
+
if not isinstance(ack1, str) or not ack1.strip():
|
| 109 |
+
return "empty ack1"
|
| 110 |
+
if not isinstance(turns, list) or len(turns) != len(tail):
|
| 111 |
+
return f"turns len {len(turns) if isinstance(turns,list) else '?'} != tail {len(tail)}"
|
| 112 |
+
texts = [q1, ack1]
|
| 113 |
+
for t in turns:
|
| 114 |
+
if not isinstance(t, dict) or not str(t.get("user", "")).strip() or not str(t.get("ack", "")).strip():
|
| 115 |
+
return "empty turn user/ack"
|
| 116 |
+
texts += [t["user"], t["ack"]]
|
| 117 |
+
for t in texts:
|
| 118 |
+
if "\u2014" in t or "\u2013" in t or " - " in t:
|
| 119 |
+
return "dash present"
|
| 120 |
+
allowed = toks(row["query"], *[c.get("arguments", {}) for c in calls])
|
| 121 |
+
new = toks(*texts) - allowed
|
| 122 |
+
if new:
|
| 123 |
+
return f"new ids {sorted(new)[:4]}"
|
| 124 |
+
tail_ids = (toks(*[c.get("arguments", {}) for c in tail])
|
| 125 |
+
- toks(*[c.get("arguments", {}) for c in calls[:K]]))
|
| 126 |
+
leak = toks(q1, ack1) & tail_ids
|
| 127 |
+
if leak:
|
| 128 |
+
return f"tail id leaked into q1/ack1 {sorted(leak)}"
|
| 129 |
+
return None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def main():
|
| 133 |
+
rows = {json.loads(l)["example_id"]: json.loads(l)
|
| 134 |
+
for l in open(N100, encoding="utf-8") if l.strip()}
|
| 135 |
+
cand = []
|
| 136 |
+
for eid, r in rows.items():
|
| 137 |
+
md = r.get("metadata") or {}; ad = md.get("anchor_depth")
|
| 138 |
+
calls = r.get("calls") or []
|
| 139 |
+
if ad is None or ad < 2 or len(calls) <= ad + 1:
|
| 140 |
+
continue
|
| 141 |
+
cand.append(eid)
|
| 142 |
+
cand.sort()
|
| 143 |
+
print(f"candidates: {len(cand)}")
|
| 144 |
+
|
| 145 |
+
authored = {}
|
| 146 |
+
if AUTHORED.exists():
|
| 147 |
+
authored = json.loads(AUTHORED.read_text(encoding="utf-8"))
|
| 148 |
+
todo = [e for e in cand if e not in authored or authored[e].get("_err")]
|
| 149 |
+
print(f"already done: {len(cand)-len(todo)} to author: {len(todo)}")
|
| 150 |
+
|
| 151 |
+
judge = make_judge(cfg["model"])
|
| 152 |
+
lock = threading.Lock(); done = [0]
|
| 153 |
+
|
| 154 |
+
def work(eid):
|
| 155 |
+
r = rows[eid]; K = r["metadata"]["anchor_depth"] + 1
|
| 156 |
+
user = build_user(r, K); last = None
|
| 157 |
+
for _ in range(3):
|
| 158 |
+
try:
|
| 159 |
+
out = judge.judge({"system": SYS, "user": user})
|
| 160 |
+
except Exception as e: # noqa
|
| 161 |
+
last = f"api:{e}"; continue
|
| 162 |
+
err = validate(r, K, out)
|
| 163 |
+
if err is None:
|
| 164 |
+
rec = {"q1": out["q1"].strip(), "ack1": out["ack1"].strip(),
|
| 165 |
+
"turns": [{"user": t["user"].strip(), "ack": t["ack"].strip()}
|
| 166 |
+
for t in out["turns"]]}
|
| 167 |
+
with lock:
|
| 168 |
+
authored[eid] = rec; done[0] += 1
|
| 169 |
+
if done[0] % 20 == 0:
|
| 170 |
+
AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8")
|
| 171 |
+
print(f" ...{done[0]}/{len(todo)}")
|
| 172 |
+
return
|
| 173 |
+
last = err
|
| 174 |
+
with lock:
|
| 175 |
+
authored[eid] = {"_err": last or "unknown"}
|
| 176 |
+
print(f" SKIP {eid}: {last}")
|
| 177 |
+
|
| 178 |
+
AUTHORED.parent.mkdir(parents=True, exist_ok=True)
|
| 179 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 180 |
+
list(ex.map(work, todo))
|
| 181 |
+
AUTHORED.write_text(json.dumps(authored, ensure_ascii=False, indent=1), encoding="utf-8")
|
| 182 |
+
|
| 183 |
+
ok = sum(1 for e in cand if "q1" in authored.get(e, {}) and not authored.get(e, {}).get("_err"))
|
| 184 |
+
err = [e for e in cand if authored.get(e, {}).get("_err")]
|
| 185 |
+
print(f"\nauthored ok: {ok}/{len(cand)} failed/skipped: {len(err)}")
|
| 186 |
+
for e in err[:15]:
|
| 187 |
+
print(" ", e, authored[e]["_err"])
|
| 188 |
+
print(f"wrote {AUTHORED.relative_to(ROOT)}")
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if __name__ == "__main__":
|
| 192 |
+
main()
|
tempscripts/story_remediation/unbundle/build_all.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Full unbundle build: split every authored candidate's single bundled turn
|
| 2 |
+
into T1 (prefix + F, the preserved trie divergence) plus ONE later turn per
|
| 3 |
+
tail call (one action per turn, matching real tau2 and the prototype finding
|
| 4 |
+
that multi-call tail turns get caught 6/6 vs single-call 1/4).
|
| 5 |
+
|
| 6 |
+
Base = original n100 (795 rows). Each authored candidate row is REPLACED by its
|
| 7 |
+
split rows; all other rows (non-candidates + any skipped candidate) pass through
|
| 8 |
+
unchanged. Writes out/trajectories_all.jsonl.
|
| 9 |
+
|
| 10 |
+
History chaining per tail turn i (0-based, i in 0..N-1):
|
| 11 |
+
orig_history
|
| 12 |
+
+ user(q1)
|
| 13 |
+
+ assistant(tool_calls = prefix+F) + tool msgs (verbatim outputs)
|
| 14 |
+
+ assistant(turns[0].bridge) # confirms turn 1
|
| 15 |
+
+ for j in 0..i-1:
|
| 16 |
+
user(turns[j].user)
|
| 17 |
+
assistant(tool_calls=[tail[j]]) + tool msg
|
| 18 |
+
assistant(turns[j+1].bridge) # confirms tail[j]
|
| 19 |
+
-> current row: query=turns[i].user, calls=[tail[i]]
|
| 20 |
+
|
| 21 |
+
Auth lives in the prefix (anchor_depth>=2), so tail turns never re-auth.
|
| 22 |
+
Run: python -u temp/story_remediation/unbundle/build_all.py
|
| 23 |
+
"""
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
import json, copy
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
HERE = Path(__file__).resolve().parent
|
| 29 |
+
ROOT = HERE.parents[2]
|
| 30 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 31 |
+
AUTHORED = HERE / "out" / "authored.json"
|
| 32 |
+
OUT = HERE / "out" / "trajectories_all.jsonl"
|
| 33 |
+
|
| 34 |
+
AUTH_TOOLS = {"find_user_id_by_name_zip", "find_user_id_by_email",
|
| 35 |
+
"find_user_id_by_phone", "authenticate", "find_user"}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def hist_of(r):
|
| 39 |
+
return r.get("history") or (r.get("metadata") or {}).get("history") or []
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def umsg(content):
|
| 43 |
+
return {"role": "user", "content": content, "tool_calls": [], "tool_call_id": None}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def amsg(content=None, tool_calls=None):
|
| 47 |
+
return {"role": "assistant", "content": content,
|
| 48 |
+
"tool_calls": copy.deepcopy(tool_calls) if tool_calls else [],
|
| 49 |
+
"tool_call_id": None}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def tmsg(call):
|
| 53 |
+
return {"role": "tool", "content": call.get("output"),
|
| 54 |
+
"tool_calls": [], "tool_call_id": None}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def main():
|
| 58 |
+
rows = [json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()]
|
| 59 |
+
by_eid = {r["example_id"]: r for r in rows}
|
| 60 |
+
authored = json.loads(AUTHORED.read_text(encoding="utf-8"))
|
| 61 |
+
ok = {e: a for e, a in authored.items() if "q1" in a and not a.get("_err")}
|
| 62 |
+
print(f"authored ok: {len(ok)} skipped: {len(authored)-len(ok)}")
|
| 63 |
+
|
| 64 |
+
out = []
|
| 65 |
+
split_eids = set()
|
| 66 |
+
reauth_flags = []
|
| 67 |
+
for r in rows:
|
| 68 |
+
eid = r["example_id"]
|
| 69 |
+
if eid not in ok:
|
| 70 |
+
out.append(r) # non-candidate or skipped -> unchanged
|
| 71 |
+
continue
|
| 72 |
+
sp = ok[eid]
|
| 73 |
+
md = r["metadata"]; ad = md["anchor_depth"]
|
| 74 |
+
calls = r["calls"]
|
| 75 |
+
prefixF = calls[:ad + 1]
|
| 76 |
+
tail = calls[ad + 1:]
|
| 77 |
+
assert len(tail) == len(sp["turns"]), f"{eid}: tail {len(tail)} != turns {len(sp['turns'])}"
|
| 78 |
+
orig_hist = hist_of(r)
|
| 79 |
+
split_eids.add(eid)
|
| 80 |
+
|
| 81 |
+
# ---- T1: preserved trie divergence (prefix + F) ----
|
| 82 |
+
t1 = copy.deepcopy(r)
|
| 83 |
+
t1["query"] = sp["q1"]
|
| 84 |
+
t1["calls"] = copy.deepcopy(prefixF)
|
| 85 |
+
t1["history"] = copy.deepcopy(orig_hist)
|
| 86 |
+
t1["metadata"] = copy.deepcopy(md)
|
| 87 |
+
t1["metadata"]["history"] = copy.deepcopy(orig_hist)
|
| 88 |
+
t1["metadata"]["unbundle_role"] = "turn1"
|
| 89 |
+
t1["metadata"]["orig_eid"] = eid
|
| 90 |
+
out.append(t1)
|
| 91 |
+
|
| 92 |
+
# ---- running history: turn1 shown as completed ----
|
| 93 |
+
base_hist = (copy.deepcopy(orig_hist)
|
| 94 |
+
+ [umsg(sp["q1"]), amsg(tool_calls=prefixF)]
|
| 95 |
+
+ [tmsg(c) for c in prefixF]
|
| 96 |
+
+ [amsg(content=sp["turns"][0]["bridge"])])
|
| 97 |
+
|
| 98 |
+
run_hist = base_hist
|
| 99 |
+
for i, call in enumerate(tail):
|
| 100 |
+
if call["name"] in AUTH_TOOLS:
|
| 101 |
+
reauth_flags.append((eid, i, call["name"]))
|
| 102 |
+
trow = copy.deepcopy(r)
|
| 103 |
+
trow["example_id"] = f"{eid}-t{i + 2}"
|
| 104 |
+
trow["query"] = sp["turns"][i]["user"]
|
| 105 |
+
trow["calls"] = [copy.deepcopy(call)]
|
| 106 |
+
trow["history"] = copy.deepcopy(run_hist)
|
| 107 |
+
trow["metadata"] = copy.deepcopy(md)
|
| 108 |
+
trow["metadata"]["history"] = copy.deepcopy(run_hist)
|
| 109 |
+
trow["metadata"]["unbundle_role"] = f"turn{i + 2}"
|
| 110 |
+
trow["metadata"]["orig_eid"] = eid
|
| 111 |
+
out.append(trow)
|
| 112 |
+
# advance history: this tail turn completed + next bridge (if any)
|
| 113 |
+
run_hist = (copy.deepcopy(run_hist)
|
| 114 |
+
+ [umsg(sp["turns"][i]["user"]), amsg(tool_calls=[call]), tmsg(call)])
|
| 115 |
+
if i + 1 < len(tail):
|
| 116 |
+
run_hist = run_hist + [amsg(content=sp["turns"][i + 1]["bridge"])]
|
| 117 |
+
|
| 118 |
+
OUT.parent.mkdir(parents=True, exist_ok=True)
|
| 119 |
+
with OUT.open("w", encoding="utf-8") as fh:
|
| 120 |
+
for r in out:
|
| 121 |
+
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 122 |
+
|
| 123 |
+
n_tail = sum(1 for r in out if str((r.get("metadata") or {}).get("unbundle_role", "")).startswith("turn")
|
| 124 |
+
and (r.get("metadata") or {}).get("unbundle_role") != "turn1"
|
| 125 |
+
and (r.get("metadata") or {}).get("orig_eid"))
|
| 126 |
+
print(f"input rows: {len(rows)} output rows: {len(out)}")
|
| 127 |
+
print(f"split candidates: {len(split_eids)} T1 rows: {len(split_eids)} tail rows: {n_tail}")
|
| 128 |
+
print(f"unchanged rows: {len(rows) - len(split_eids)}")
|
| 129 |
+
if reauth_flags:
|
| 130 |
+
print(f"WARNING: {len(reauth_flags)} tail turns contain an auth tool:")
|
| 131 |
+
for f in reauth_flags[:10]:
|
| 132 |
+
print(" ", f)
|
| 133 |
+
else:
|
| 134 |
+
print("no tail turn re-authenticates (good)")
|
| 135 |
+
print(f"wrote {OUT.relative_to(ROOT)}")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
if __name__ == "__main__":
|
| 139 |
+
main()
|
tempscripts/story_remediation/unbundle/build_all_v2.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""V2 build: same structural split, but corrected acknowledgement ordering.
|
| 2 |
+
|
| 3 |
+
Every completed turn is rendered in history as: user request -> tool call(s)
|
| 4 |
+
-> PAST-TENSE ack of that same turn. An ack never precedes its own request, so
|
| 5 |
+
the v1 "I've already done the thing you're about to ask" contradiction is gone.
|
| 6 |
+
|
| 7 |
+
History for tail turn i (0-based, maps to tail call i):
|
| 8 |
+
orig_history
|
| 9 |
+
+ user(q1) + assistant(tool_calls=prefix+F) + tool msgs + assistant(ack1)
|
| 10 |
+
+ for j in 0..i-1:
|
| 11 |
+
user(turns[j].user) + assistant(tool_calls=[tail[j]]) + tool msg
|
| 12 |
+
+ assistant(turns[j].ack)
|
| 13 |
+
-> current row: query=turns[i].user, calls=[tail[i]] (its ack shown only in later rows)
|
| 14 |
+
|
| 15 |
+
Reads out/authored_v2.json, writes out/trajectories_all_v2.jsonl.
|
| 16 |
+
Run: python -u temp/story_remediation/unbundle/build_all_v2.py
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
import json, copy
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
HERE = Path(__file__).resolve().parent
|
| 23 |
+
ROOT = HERE.parents[2]
|
| 24 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 25 |
+
AUTHORED = HERE / "out" / "authored_v2.json"
|
| 26 |
+
OUT = HERE / "out" / "trajectories_all_v2.jsonl"
|
| 27 |
+
AUTH_TOOLS = {"find_user_id_by_name_zip", "find_user_id_by_email",
|
| 28 |
+
"find_user_id_by_phone", "authenticate", "find_user"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def hist_of(r):
|
| 32 |
+
return r.get("history") or (r.get("metadata") or {}).get("history") or []
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def umsg(c):
|
| 36 |
+
return {"role": "user", "content": c, "tool_calls": [], "tool_call_id": None}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def amsg(content=None, tool_calls=None):
|
| 40 |
+
return {"role": "assistant", "content": content,
|
| 41 |
+
"tool_calls": copy.deepcopy(tool_calls) if tool_calls else [],
|
| 42 |
+
"tool_call_id": None}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def tmsg(call):
|
| 46 |
+
return {"role": "tool", "content": call.get("output"), "tool_calls": [], "tool_call_id": None}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def main():
|
| 50 |
+
rows = [json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()]
|
| 51 |
+
authored = json.loads(AUTHORED.read_text(encoding="utf-8"))
|
| 52 |
+
ok = {e: a for e, a in authored.items() if "q1" in a and not a.get("_err")}
|
| 53 |
+
print(f"authored ok: {len(ok)} skipped: {len(authored)-len(ok)}")
|
| 54 |
+
|
| 55 |
+
out = []; split_eids = set(); reauth = []
|
| 56 |
+
for r in rows:
|
| 57 |
+
eid = r["example_id"]
|
| 58 |
+
if eid not in ok:
|
| 59 |
+
out.append(r); continue
|
| 60 |
+
sp = ok[eid]; md = r["metadata"]; ad = md["anchor_depth"]
|
| 61 |
+
calls = r["calls"]; prefixF = calls[:ad + 1]; tail = calls[ad + 1:]
|
| 62 |
+
assert len(tail) == len(sp["turns"]), f"{eid}: tail {len(tail)} != turns {len(sp['turns'])}"
|
| 63 |
+
orig_hist = hist_of(r); split_eids.add(eid)
|
| 64 |
+
|
| 65 |
+
# T1: preserved trie divergence (query narrowed to prefix+F)
|
| 66 |
+
t1 = copy.deepcopy(r)
|
| 67 |
+
t1["query"] = sp["q1"]; t1["calls"] = copy.deepcopy(prefixF)
|
| 68 |
+
t1["history"] = copy.deepcopy(orig_hist)
|
| 69 |
+
t1["metadata"] = copy.deepcopy(md)
|
| 70 |
+
t1["metadata"]["history"] = copy.deepcopy(orig_hist)
|
| 71 |
+
t1["metadata"]["unbundle_role"] = "turn1"; t1["metadata"]["orig_eid"] = eid
|
| 72 |
+
out.append(t1)
|
| 73 |
+
|
| 74 |
+
# turn-1 completed block (with its OWN past-tense ack1)
|
| 75 |
+
base_hist = (copy.deepcopy(orig_hist)
|
| 76 |
+
+ [umsg(sp["q1"]), amsg(tool_calls=prefixF)]
|
| 77 |
+
+ [tmsg(c) for c in prefixF]
|
| 78 |
+
+ [amsg(content=sp["ack1"])])
|
| 79 |
+
|
| 80 |
+
for i, call in enumerate(tail):
|
| 81 |
+
if call["name"] in AUTH_TOOLS:
|
| 82 |
+
reauth.append((eid, i, call["name"]))
|
| 83 |
+
# history = base + completed tail turns 0..i-1 (each with its own ack)
|
| 84 |
+
hist = copy.deepcopy(base_hist)
|
| 85 |
+
for j in range(i):
|
| 86 |
+
cj = tail[j]
|
| 87 |
+
hist += [umsg(sp["turns"][j]["user"]), amsg(tool_calls=[cj]),
|
| 88 |
+
tmsg(cj), amsg(content=sp["turns"][j]["ack"])]
|
| 89 |
+
trow = copy.deepcopy(r)
|
| 90 |
+
trow["example_id"] = f"{eid}-t{i + 2}"
|
| 91 |
+
trow["query"] = sp["turns"][i]["user"]
|
| 92 |
+
trow["calls"] = [copy.deepcopy(call)]
|
| 93 |
+
trow["history"] = hist
|
| 94 |
+
trow["metadata"] = copy.deepcopy(md)
|
| 95 |
+
trow["metadata"]["history"] = copy.deepcopy(hist)
|
| 96 |
+
trow["metadata"]["unbundle_role"] = f"turn{i + 2}"
|
| 97 |
+
trow["metadata"]["orig_eid"] = eid
|
| 98 |
+
out.append(trow)
|
| 99 |
+
|
| 100 |
+
OUT.parent.mkdir(parents=True, exist_ok=True)
|
| 101 |
+
with OUT.open("w", encoding="utf-8") as fh:
|
| 102 |
+
for r in out:
|
| 103 |
+
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 104 |
+
|
| 105 |
+
n_tail = sum(1 for r in out
|
| 106 |
+
if (r.get("metadata") or {}).get("orig_eid")
|
| 107 |
+
and (r.get("metadata") or {}).get("unbundle_role") not in (None, "turn1"))
|
| 108 |
+
print(f"input rows: {len(rows)} output rows: {len(out)}")
|
| 109 |
+
print(f"split candidates: {len(split_eids)} T1: {len(split_eids)} tail: {n_tail}")
|
| 110 |
+
print(f"unchanged rows: {len(rows) - len(split_eids)}")
|
| 111 |
+
print("re-auth in tail (verify DIFFERENT person):", len(reauth), reauth[:6])
|
| 112 |
+
print(f"wrote {OUT.relative_to(ROOT)}")
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
main()
|
tempscripts/story_remediation/unbundle/build_all_v3.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""V3 build: remove the residual tells that live in the INHERITED base history.
|
| 2 |
+
|
| 3 |
+
Diagnosis (from C3 reasoning on still-caught v2 tails): the original n100
|
| 4 |
+
"humanized" pre-history front-loads future/tail intents ("a return to handle",
|
| 5 |
+
"a receipt without prices") and restates identity ("Hi, this is Mona Frey")
|
| 6 |
+
right before q1. Both read as scripted-from-a-template.
|
| 7 |
+
|
| 8 |
+
Fix (reuses v2 authored q1/ack1/turns unchanged):
|
| 9 |
+
* 259 candidates whose pre-history has NO tool calls -> replace the whole
|
| 10 |
+
teaser with just the greeting. q1 (which already carries name+ZIP) becomes
|
| 11 |
+
the true first user turn, so the front-loading AND the duplicate identity
|
| 12 |
+
both disappear.
|
| 13 |
+
* 23 candidates whose pre-history DOES auth (find_user[/get_user]) -> rebuild
|
| 14 |
+
a clean minimal auth exchange that keeps those exact tool calls but drops
|
| 15 |
+
the front-loading teaser and any duplicative post-auth actions. Identity is
|
| 16 |
+
given once, with no intent preview.
|
| 17 |
+
|
| 18 |
+
Everything downstream (T1 = prefix+F, tail = one action per turn, past-tense
|
| 19 |
+
acks) is identical to v2. Reads out/authored_v2.json, writes
|
| 20 |
+
out/trajectories_all_v3.jsonl.
|
| 21 |
+
Run: python -u temp/story_remediation/unbundle/build_all_v3.py
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
import json, copy, hashlib, re
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
HERE = Path(__file__).resolve().parent
|
| 28 |
+
ROOT = HERE.parents[2]
|
| 29 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 30 |
+
AUTHORED = HERE / "out" / "authored_v2.json"
|
| 31 |
+
Q1FIX = HERE / "out" / "authored_q1fix_v3.json"
|
| 32 |
+
OUT = HERE / "out" / "trajectories_all_v3.jsonl"
|
| 33 |
+
|
| 34 |
+
AUTH_LEAD = ("find_user_id_by_name_zip", "get_user_details")
|
| 35 |
+
AUTH_TOOLS = {"find_user_id_by_name_zip", "find_user_id_by_email",
|
| 36 |
+
"find_user_id_by_phone", "authenticate", "find_user"}
|
| 37 |
+
|
| 38 |
+
OPENERS = [
|
| 39 |
+
"Hi, I need a hand with my account. I'm {first} {last}, ZIP {zip}.",
|
| 40 |
+
"Hello, could you pull up my account? Name is {first} {last}, ZIP {zip}.",
|
| 41 |
+
"Hi there, I need some help on my account. I'm {first} {last}, ZIP {zip}.",
|
| 42 |
+
"Hey, can you access my account? Name's {first} {last}, ZIP {zip}.",
|
| 43 |
+
]
|
| 44 |
+
VERIFIED = [
|
| 45 |
+
"Thanks {first}, you're verified. What can I do for you?",
|
| 46 |
+
"Great {first}, I've pulled up your account. How can I help?",
|
| 47 |
+
"You're all set {first}. What would you like to do?",
|
| 48 |
+
"Verified, thanks {first}. What can I help with?",
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def hist_of(r):
|
| 53 |
+
return r.get("history") or (r.get("metadata") or {}).get("history") or []
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def umsg(c):
|
| 57 |
+
return {"role": "user", "content": c, "tool_calls": [], "tool_call_id": None}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def amsg(content=None, tool_calls=None):
|
| 61 |
+
return {"role": "assistant", "content": content,
|
| 62 |
+
"tool_calls": copy.deepcopy(tool_calls) if tool_calls else [],
|
| 63 |
+
"tool_call_id": None}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def tmsg(call):
|
| 67 |
+
return {"role": "tool", "content": call.get("output"), "tool_calls": [], "tool_call_id": None}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def pick(lst, eid):
|
| 71 |
+
return lst[int(hashlib.md5(eid.encode()).hexdigest(), 16) % len(lst)]
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def greeting_of(r):
|
| 75 |
+
h = hist_of(r)
|
| 76 |
+
if h and h[0].get("role") == "assistant" and not h[0].get("tool_calls") and h[0].get("content"):
|
| 77 |
+
return copy.deepcopy(h[0])
|
| 78 |
+
return amsg(content="Hi! How can I help you today?")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def clean_prehistory(r):
|
| 82 |
+
"""Return (cleaned_history, had_auth). For the 23 auth-in-history rows keep a
|
| 83 |
+
minimal auth exchange around the real find_user/get_user calls; else greeting."""
|
| 84 |
+
h = hist_of(r); eid = r["example_id"]
|
| 85 |
+
greet = greeting_of(r)
|
| 86 |
+
# gather the LEADING auth calls actually present in the pre-history, in order
|
| 87 |
+
lead = []
|
| 88 |
+
for m in h:
|
| 89 |
+
for t in (m.get("tool_calls") or []):
|
| 90 |
+
if t["name"] in AUTH_LEAD:
|
| 91 |
+
lead.append(copy.deepcopy(t))
|
| 92 |
+
# only keep the contiguous leading auth calls (find_user then optional get_user)
|
| 93 |
+
kept = []
|
| 94 |
+
for t in lead:
|
| 95 |
+
if not kept and t["name"] == "find_user_id_by_name_zip":
|
| 96 |
+
kept.append(t)
|
| 97 |
+
elif kept and t["name"] == "get_user_details":
|
| 98 |
+
kept.append(t); break
|
| 99 |
+
else:
|
| 100 |
+
break
|
| 101 |
+
if not kept:
|
| 102 |
+
return [greet], False
|
| 103 |
+
args = kept[0].get("arguments", {})
|
| 104 |
+
first = args.get("first_name", ""); last = args.get("last_name", ""); zp = args.get("zip", "")
|
| 105 |
+
opener = pick(OPENERS, eid).format(first=first, last=last, zip=zp)
|
| 106 |
+
verified = pick(VERIFIED, eid).format(first=first or "there")
|
| 107 |
+
hist = [greet, umsg(opener)]
|
| 108 |
+
for t in kept:
|
| 109 |
+
hist += [amsg(tool_calls=[t]), tmsg(t)]
|
| 110 |
+
hist += [amsg(content=verified)]
|
| 111 |
+
return hist, True
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def main():
|
| 115 |
+
rows = [json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()]
|
| 116 |
+
authored = json.loads(AUTHORED.read_text(encoding="utf-8"))
|
| 117 |
+
q1fix = json.loads(Q1FIX.read_text(encoding="utf-8")) if Q1FIX.exists() else {}
|
| 118 |
+
ok = {e: a for e, a in authored.items() if "q1" in a and not a.get("_err")}
|
| 119 |
+
print(f"authored ok: {len(ok)} skipped: {len(authored)-len(ok)} q1-overrides: {len(q1fix)}")
|
| 120 |
+
|
| 121 |
+
out = []; split_eids = set(); n_auth = 0; ident_leak = []
|
| 122 |
+
for r in rows:
|
| 123 |
+
eid = r["example_id"]
|
| 124 |
+
if eid not in ok:
|
| 125 |
+
out.append(r); continue
|
| 126 |
+
sp = copy.deepcopy(ok[eid]); md = r["metadata"]; ad = md["anchor_depth"]
|
| 127 |
+
if eid in q1fix: # cleaned already-verified q1
|
| 128 |
+
sp["q1"] = q1fix[eid]["q1"]
|
| 129 |
+
calls = r["calls"]; prefixF = calls[:ad + 1]; tail = calls[ad + 1:]
|
| 130 |
+
assert len(tail) == len(sp["turns"]), f"{eid}: tail {len(tail)} != turns {len(sp['turns'])}"
|
| 131 |
+
base_prehist, had_auth = clean_prehistory(r)
|
| 132 |
+
n_auth += int(had_auth); split_eids.add(eid)
|
| 133 |
+
|
| 134 |
+
# for auth-in-history rows, q1 must NOT re-introduce the person (full name
|
| 135 |
+
# or a self-intro like "I'm Reid"); a name inside an id (gc_reid_22) is fine
|
| 136 |
+
if had_auth:
|
| 137 |
+
fu = next((t for m in hist_of(r) for t in (m.get("tool_calls") or [])
|
| 138 |
+
if t["name"] == "find_user_id_by_name_zip"), None)
|
| 139 |
+
a = (fu or {}).get("arguments", {})
|
| 140 |
+
first = str(a.get("first_name", "")); last = str(a.get("last_name", ""))
|
| 141 |
+
q1l = sp["q1"].lower()
|
| 142 |
+
pats = []
|
| 143 |
+
if first and last:
|
| 144 |
+
pats.append(re.escape(f"{first} {last}".lower()))
|
| 145 |
+
if first and len(first) >= 3:
|
| 146 |
+
pats.append(r"\b(i'?m|i am|this is|name is|it'?s)\s+" + re.escape(first.lower()))
|
| 147 |
+
if pats and re.search("|".join(pats), q1l):
|
| 148 |
+
ident_leak.append((eid, first))
|
| 149 |
+
|
| 150 |
+
# T1: preserved trie divergence
|
| 151 |
+
t1 = copy.deepcopy(r)
|
| 152 |
+
t1["query"] = sp["q1"]; t1["calls"] = copy.deepcopy(prefixF)
|
| 153 |
+
t1["history"] = copy.deepcopy(base_prehist)
|
| 154 |
+
t1["metadata"] = copy.deepcopy(md)
|
| 155 |
+
t1["metadata"]["history"] = copy.deepcopy(base_prehist)
|
| 156 |
+
t1["metadata"]["unbundle_role"] = "turn1"; t1["metadata"]["orig_eid"] = eid
|
| 157 |
+
out.append(t1)
|
| 158 |
+
|
| 159 |
+
# turn-1 completed block (own past-tense ack1)
|
| 160 |
+
base_hist = (copy.deepcopy(base_prehist)
|
| 161 |
+
+ [umsg(sp["q1"]), amsg(tool_calls=prefixF)]
|
| 162 |
+
+ [tmsg(c) for c in prefixF]
|
| 163 |
+
+ [amsg(content=sp["ack1"])])
|
| 164 |
+
|
| 165 |
+
for i, call in enumerate(tail):
|
| 166 |
+
hist = copy.deepcopy(base_hist)
|
| 167 |
+
for j in range(i):
|
| 168 |
+
cj = tail[j]
|
| 169 |
+
hist += [umsg(sp["turns"][j]["user"]), amsg(tool_calls=[cj]),
|
| 170 |
+
tmsg(cj), amsg(content=sp["turns"][j]["ack"])]
|
| 171 |
+
trow = copy.deepcopy(r)
|
| 172 |
+
trow["example_id"] = f"{eid}-t{i + 2}"
|
| 173 |
+
trow["query"] = sp["turns"][i]["user"]
|
| 174 |
+
trow["calls"] = [copy.deepcopy(call)]
|
| 175 |
+
trow["history"] = hist
|
| 176 |
+
trow["metadata"] = copy.deepcopy(md)
|
| 177 |
+
trow["metadata"]["history"] = copy.deepcopy(hist)
|
| 178 |
+
trow["metadata"]["unbundle_role"] = f"turn{i + 2}"
|
| 179 |
+
trow["metadata"]["orig_eid"] = eid
|
| 180 |
+
out.append(trow)
|
| 181 |
+
|
| 182 |
+
OUT.parent.mkdir(parents=True, exist_ok=True)
|
| 183 |
+
with OUT.open("w", encoding="utf-8") as fh:
|
| 184 |
+
for r in out:
|
| 185 |
+
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 186 |
+
|
| 187 |
+
n_tail = sum(1 for r in out
|
| 188 |
+
if (r.get("metadata") or {}).get("orig_eid")
|
| 189 |
+
and (r.get("metadata") or {}).get("unbundle_role") not in (None, "turn1"))
|
| 190 |
+
print(f"input rows: {len(rows)} output rows: {len(out)}")
|
| 191 |
+
print(f"split: {len(split_eids)} greeting-only(259-type): {len(split_eids)-n_auth} "
|
| 192 |
+
f"auth-in-history(23-type): {n_auth}")
|
| 193 |
+
print(f"tail rows: {n_tail} unchanged: {len(rows)-len(split_eids)}")
|
| 194 |
+
if ident_leak:
|
| 195 |
+
print(f"WARNING q1 restates identity already in cleaned history ({len(ident_leak)}):")
|
| 196 |
+
for x in ident_leak:
|
| 197 |
+
print(" ", x)
|
| 198 |
+
else:
|
| 199 |
+
print("no q1 restates cleaned-history identity (good)")
|
| 200 |
+
print(f"wrote {OUT.relative_to(ROOT)}")
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
if __name__ == "__main__":
|
| 204 |
+
main()
|
tempscripts/story_remediation/unbundle/build_all_v4.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""V4 build: add a real auth handshake (agent asks -> customer provides) and use the
|
| 2 |
+
humanized v4 dialogue, WITHOUT touching a single tool call.
|
| 3 |
+
|
| 4 |
+
Structural change vs v3 is PROSE ONLY:
|
| 5 |
+
* greeting-only rows (259): base history becomes
|
| 6 |
+
[greeting] [user: vague opener, no identifiers] [agent: please verify name+ZIP]
|
| 7 |
+
and the T1 user turn (q1) is the customer's reply that provides name/ZIP and the
|
| 8 |
+
first task. The T1 tool calls (auth + F) are IDENTICAL to v3 and stay in one turn.
|
| 9 |
+
* auth-in-history rows (23): the pre-history auth exchange is rebuilt as a handshake
|
| 10 |
+
[greeting] [user: vague opener] [agent: verify?] [user: name+ZIP] [auth calls]
|
| 11 |
+
[agent: verified]. Same find_user/get_user calls as v3, kept verbatim. q1 stays the
|
| 12 |
+
v3 clean task-only message (no identity restated).
|
| 13 |
+
|
| 14 |
+
INVARIANT: for every example_id, this build asserts row["calls"] is byte-identical to
|
| 15 |
+
v3's row["calls"]. If any call differs the build aborts. The trie is therefore
|
| 16 |
+
unchanged and every confuser still rivals its real node at the same cutoff.
|
| 17 |
+
|
| 18 |
+
Reads out/authored_v4.json (+ v2/q1fix for fallbacks), writes
|
| 19 |
+
out/trajectories_all_v4.jsonl. Run:
|
| 20 |
+
python -u temp/story_remediation/unbundle/build_all_v4.py
|
| 21 |
+
"""
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
import json, copy, hashlib, re
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
HERE = Path(__file__).resolve().parent
|
| 27 |
+
ROOT = HERE.parents[2]
|
| 28 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 29 |
+
AUTHORED4 = HERE / "out" / "authored_v4.json"
|
| 30 |
+
AUTHORED2 = HERE / "out" / "authored_v2.json"
|
| 31 |
+
Q1FIX = HERE / "out" / "authored_q1fix_v3.json"
|
| 32 |
+
V3 = HERE / "out" / "trajectories_all_v3.jsonl"
|
| 33 |
+
OUT = HERE / "out" / "trajectories_all_v4.jsonl"
|
| 34 |
+
|
| 35 |
+
AUTH_LEAD = ("find_user_id_by_name_zip", "get_user_details")
|
| 36 |
+
|
| 37 |
+
# vague openers: NO name / ZIP / email / order id (identity comes only after the ask)
|
| 38 |
+
OPENERS_VAGUE = [
|
| 39 |
+
"Hi, I need a hand with something on my account.",
|
| 40 |
+
"Hello, I'm hoping you can help me with one of my orders.",
|
| 41 |
+
"Hey there, I've got a question about my account.",
|
| 42 |
+
"Hi, could you help me sort something out on my account?",
|
| 43 |
+
"Hello, I need to take care of a couple of things on my order.",
|
| 44 |
+
"Hi, I was hoping to get some help with my account today.",
|
| 45 |
+
"Hey, I need help with something. Not sure who to ask.",
|
| 46 |
+
"Hi there, can you help me with an order issue?",
|
| 47 |
+
]
|
| 48 |
+
# agent asks to verify identity (name + ZIP)
|
| 49 |
+
VERIFY_ASK = [
|
| 50 |
+
"Of course, I'd be glad to help. First, can I verify your identity? Could you give me your full name and ZIP code?",
|
| 51 |
+
"Happy to help with that. Before I pull anything up, could you confirm your name and ZIP code for me?",
|
| 52 |
+
"Sure thing. To access your account I'll need to verify you first. What's your full name and ZIP code?",
|
| 53 |
+
"I can help with that. For security, could you share your full name and the ZIP code on your account?",
|
| 54 |
+
"Absolutely. Let me just verify you first. Can I get your name and ZIP code, please?",
|
| 55 |
+
"Glad to help. To start, could you confirm your full name and ZIP code so I can find your account?",
|
| 56 |
+
]
|
| 57 |
+
# for the 23 auth-in-history rows: the customer provides identity (mild disfluency)
|
| 58 |
+
ID_PROVIDE = [
|
| 59 |
+
"Yeah, sure. It's {first} {last}, and the ZIP is {zip}.",
|
| 60 |
+
"Oh, right. {first} {last}, ZIP {zip}.",
|
| 61 |
+
"Of course, it's {first} {last}. ZIP code's {zip}.",
|
| 62 |
+
"Sure thing. Name's {first} {last}, and my ZIP is {zip}.",
|
| 63 |
+
"Um, ok. {first} {last}, and the ZIP on the account is {zip}.",
|
| 64 |
+
]
|
| 65 |
+
VERIFIED = [
|
| 66 |
+
"Thanks {first}, you're all verified. What can I do for you?",
|
| 67 |
+
"Great, I've got your account pulled up, {first}. How can I help?",
|
| 68 |
+
"You're all set, {first}. What would you like to do?",
|
| 69 |
+
"Perfect, verified. Thanks {first}. What can I help with?",
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def hist_of(r):
|
| 74 |
+
return r.get("history") or (r.get("metadata") or {}).get("history") or []
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def umsg(c):
|
| 78 |
+
return {"role": "user", "content": c, "tool_calls": [], "tool_call_id": None}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def amsg(content=None, tool_calls=None):
|
| 82 |
+
return {"role": "assistant", "content": content,
|
| 83 |
+
"tool_calls": copy.deepcopy(tool_calls) if tool_calls else [],
|
| 84 |
+
"tool_call_id": None}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def tmsg(call):
|
| 88 |
+
return {"role": "tool", "content": call.get("output"), "tool_calls": [], "tool_call_id": None}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def pick(lst, eid, salt=""):
|
| 92 |
+
return lst[int(hashlib.md5((salt + eid).encode()).hexdigest(), 16) % len(lst)]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def greeting_of(r):
|
| 96 |
+
h = hist_of(r)
|
| 97 |
+
if h and h[0].get("role") == "assistant" and not h[0].get("tool_calls") and h[0].get("content"):
|
| 98 |
+
return copy.deepcopy(h[0])
|
| 99 |
+
return amsg(content="Hi! How can I help you today?")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def leading_auth(r):
|
| 103 |
+
lead = []
|
| 104 |
+
for m in hist_of(r):
|
| 105 |
+
for t in (m.get("tool_calls") or []):
|
| 106 |
+
if t["name"] in AUTH_LEAD:
|
| 107 |
+
lead.append(copy.deepcopy(t))
|
| 108 |
+
kept = []
|
| 109 |
+
for t in lead:
|
| 110 |
+
if not kept and t["name"] == "find_user_id_by_name_zip":
|
| 111 |
+
kept.append(t)
|
| 112 |
+
elif kept and t["name"] == "get_user_details":
|
| 113 |
+
kept.append(t); break
|
| 114 |
+
else:
|
| 115 |
+
break
|
| 116 |
+
return kept
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def base_history(r):
|
| 120 |
+
"""(cleaned_history, had_auth). Prose-only handshake; no call added or removed
|
| 121 |
+
beyond the exact leading auth calls that already exist in v3's pre-history."""
|
| 122 |
+
eid = r["example_id"]
|
| 123 |
+
greet = greeting_of(r)
|
| 124 |
+
opener = umsg(pick(OPENERS_VAGUE, eid, "op"))
|
| 125 |
+
ask = amsg(content=pick(VERIFY_ASK, eid, "ask"))
|
| 126 |
+
kept = leading_auth(r)
|
| 127 |
+
if not kept:
|
| 128 |
+
# greeting-only row: handshake is greeting -> opener -> ask; q1 (the T1 turn)
|
| 129 |
+
# is the customer's reply that supplies name/ZIP and the first task.
|
| 130 |
+
return [greet, opener, ask], False
|
| 131 |
+
# auth-in-history row: full handshake around the real auth calls.
|
| 132 |
+
a = kept[0].get("arguments", {})
|
| 133 |
+
first = a.get("first_name", ""); last = a.get("last_name", ""); zp = a.get("zip", "")
|
| 134 |
+
idp = umsg(pick(ID_PROVIDE, eid, "idp").format(first=first, last=last, zip=zp))
|
| 135 |
+
verified = amsg(content=pick(VERIFIED, eid, "ok").format(first=first or "there"))
|
| 136 |
+
hist = [greet, opener, ask, idp]
|
| 137 |
+
for t in kept:
|
| 138 |
+
hist += [amsg(tool_calls=[t]), tmsg(t)]
|
| 139 |
+
hist += [verified]
|
| 140 |
+
return hist, True
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def calls_sig(calls):
|
| 144 |
+
return [(c.get("name"), json.dumps(c.get("arguments", {}), sort_keys=True, ensure_ascii=False))
|
| 145 |
+
for c in (calls or [])]
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def main():
|
| 149 |
+
rows = [json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()]
|
| 150 |
+
a4 = json.loads(AUTHORED4.read_text(encoding="utf-8"))
|
| 151 |
+
a2 = json.loads(AUTHORED2.read_text(encoding="utf-8"))
|
| 152 |
+
q1fix = json.loads(Q1FIX.read_text(encoding="utf-8")) if Q1FIX.exists() else {}
|
| 153 |
+
v3 = {json.loads(l)["example_id"]: json.loads(l)
|
| 154 |
+
for l in open(V3, encoding="utf-8") if l.strip()}
|
| 155 |
+
# split EXACTLY the confusers v3 split, so the only delta vs v3 is prose.
|
| 156 |
+
v3_split = {r["metadata"]["orig_eid"] for r in v3.values()
|
| 157 |
+
if (r.get("metadata") or {}).get("unbundle_role") == "turn1"}
|
| 158 |
+
|
| 159 |
+
def bundle(eid):
|
| 160 |
+
b = a4.get(eid)
|
| 161 |
+
if b and "q1" in b and not b.get("_err"):
|
| 162 |
+
return b
|
| 163 |
+
b = a2.get(eid) # fall back to v2 text if v4 failed
|
| 164 |
+
if b and "q1" in b and not b.get("_err"):
|
| 165 |
+
return b
|
| 166 |
+
return None
|
| 167 |
+
|
| 168 |
+
ok = {e: bundle(e) for e in a4 if bundle(e)}
|
| 169 |
+
for e in a2: # include any v2-only successes
|
| 170 |
+
if e not in ok and bundle(e):
|
| 171 |
+
ok[e] = bundle(e)
|
| 172 |
+
print(f"usable bundles: {len(ok)} (v4 primary, v2 fallback)")
|
| 173 |
+
|
| 174 |
+
out = []; split_eids = set(); n_auth = 0
|
| 175 |
+
for r in rows:
|
| 176 |
+
eid = r["example_id"]
|
| 177 |
+
if eid not in ok or eid not in v3_split:
|
| 178 |
+
out.append(r); continue
|
| 179 |
+
sp = copy.deepcopy(ok[eid]); md = r["metadata"]; ad = md["anchor_depth"]
|
| 180 |
+
calls = r["calls"]; prefixF = calls[:ad + 1]; tail = calls[ad + 1:]
|
| 181 |
+
if len(tail) != len(sp["turns"]):
|
| 182 |
+
out.append(r); continue # schema mismatch -> leave original
|
| 183 |
+
base_prehist, had_auth = base_history(r)
|
| 184 |
+
if had_auth and eid in q1fix: # 23-type: keep clean task-only q1
|
| 185 |
+
sp["q1"] = q1fix[eid]["q1"]
|
| 186 |
+
n_auth += int(had_auth); split_eids.add(eid)
|
| 187 |
+
|
| 188 |
+
t1 = copy.deepcopy(r)
|
| 189 |
+
t1["query"] = sp["q1"]; t1["calls"] = copy.deepcopy(prefixF)
|
| 190 |
+
t1["history"] = copy.deepcopy(base_prehist)
|
| 191 |
+
t1["metadata"] = copy.deepcopy(md)
|
| 192 |
+
t1["metadata"]["history"] = copy.deepcopy(base_prehist)
|
| 193 |
+
t1["metadata"]["unbundle_role"] = "turn1"; t1["metadata"]["orig_eid"] = eid
|
| 194 |
+
out.append(t1)
|
| 195 |
+
|
| 196 |
+
base_hist = (copy.deepcopy(base_prehist)
|
| 197 |
+
+ [umsg(sp["q1"]), amsg(tool_calls=prefixF)]
|
| 198 |
+
+ [tmsg(c) for c in prefixF]
|
| 199 |
+
+ [amsg(content=sp["ack1"])])
|
| 200 |
+
for i, call in enumerate(tail):
|
| 201 |
+
hist = copy.deepcopy(base_hist)
|
| 202 |
+
for j in range(i):
|
| 203 |
+
cj = tail[j]
|
| 204 |
+
hist += [umsg(sp["turns"][j]["user"]), amsg(tool_calls=[cj]),
|
| 205 |
+
tmsg(cj), amsg(content=sp["turns"][j]["ack"])]
|
| 206 |
+
trow = copy.deepcopy(r)
|
| 207 |
+
trow["example_id"] = f"{eid}-t{i + 2}"
|
| 208 |
+
trow["query"] = sp["turns"][i]["user"]
|
| 209 |
+
trow["calls"] = [copy.deepcopy(call)]
|
| 210 |
+
trow["history"] = hist
|
| 211 |
+
trow["metadata"] = copy.deepcopy(md)
|
| 212 |
+
trow["metadata"]["history"] = copy.deepcopy(hist)
|
| 213 |
+
trow["metadata"]["unbundle_role"] = f"turn{i + 2}"
|
| 214 |
+
trow["metadata"]["orig_eid"] = eid
|
| 215 |
+
out.append(trow)
|
| 216 |
+
|
| 217 |
+
# HARD INVARIANT: calls identical to v3 for every row (trie untouched).
|
| 218 |
+
v4 = {r["example_id"]: r for r in out}
|
| 219 |
+
assert set(v4) == set(v3), (
|
| 220 |
+
f"row-id set changed vs v3: +{sorted(set(v4)-set(v3))[:3]} "
|
| 221 |
+
f"-{sorted(set(v3)-set(v4))[:3]}")
|
| 222 |
+
bad = [eid for eid in v3 if calls_sig(v3[eid]["calls"]) != calls_sig(v4[eid]["calls"])]
|
| 223 |
+
assert not bad, f"CALLS CHANGED vs v3 for {len(bad)} rows, e.g. {bad[:5]}"
|
| 224 |
+
|
| 225 |
+
OUT.parent.mkdir(parents=True, exist_ok=True)
|
| 226 |
+
with OUT.open("w", encoding="utf-8") as fh:
|
| 227 |
+
for r in out:
|
| 228 |
+
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 229 |
+
|
| 230 |
+
n_tail = sum(1 for r in out
|
| 231 |
+
if (r.get("metadata") or {}).get("orig_eid")
|
| 232 |
+
and (r.get("metadata") or {}).get("unbundle_role") not in (None, "turn1"))
|
| 233 |
+
print(f"input rows: {len(rows)} output rows: {len(out)}")
|
| 234 |
+
print(f"split: {len(split_eids)} greeting-only: {len(split_eids)-n_auth} "
|
| 235 |
+
f"auth-in-history: {n_auth}")
|
| 236 |
+
print(f"tail rows: {n_tail} unchanged: {len(rows)-len(split_eids)}")
|
| 237 |
+
print("INVARIANT OK: calls byte-identical to v3 for all "
|
| 238 |
+
f"{len(v3)} rows (trie unchanged).")
|
| 239 |
+
print(f"wrote {OUT.relative_to(ROOT)}")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
if __name__ == "__main__":
|
| 243 |
+
main()
|
tempscripts/story_remediation/unbundle/build_all_v5.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""V5 build: two prose-only cleanups on top of v4, calls still byte-identical to v3.
|
| 2 |
+
|
| 3 |
+
b1 method-aware auth handshake. v4 always asked "name and ZIP"; 83 greeting-only
|
| 4 |
+
rows actually authenticate by EMAIL (find_user_id_by_email), so the agent's
|
| 5 |
+
question now matches the auth tool the row already uses (email -> ask for the
|
| 6 |
+
email on file; name_zip -> ask for name + ZIP). No call changes.
|
| 7 |
+
|
| 8 |
+
b3 scrub raw argument id-tokens that leaked into dialogue (credit_card_...,
|
| 9 |
+
gift_card_...). The customer/agent now say "my gift card" / "my card on file"
|
| 10 |
+
instead of pasting the internal id. The id still lives in the tool ARGUMENTS
|
| 11 |
+
(unchanged), so the executor / state db is unaffected.
|
| 12 |
+
|
| 13 |
+
INVARIANT (asserted): every row's calls == v3's calls, byte for byte. Trie unchanged.
|
| 14 |
+
Reads out/authored_v4.json (+v2 fallback, q1fix), writes out/trajectories_all_v5.jsonl.
|
| 15 |
+
Run: python -u temp/story_remediation/unbundle/build_all_v5.py
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
import json, copy, hashlib, re
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
ROOT = HERE.parents[2]
|
| 23 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 24 |
+
AUTHORED4 = HERE / "out" / "authored_v4.json"
|
| 25 |
+
AUTHORED2 = HERE / "out" / "authored_v2.json"
|
| 26 |
+
Q1FIX = HERE / "out" / "authored_q1fix_v3.json"
|
| 27 |
+
V3 = HERE / "out" / "trajectories_all_v3.jsonl"
|
| 28 |
+
OUT = HERE / "out" / "trajectories_all_v5.jsonl"
|
| 29 |
+
|
| 30 |
+
AUTH_LEAD = ("find_user_id_by_name_zip", "get_user_details")
|
| 31 |
+
FIND_METHOD = {"find_user_id_by_name_zip": "name_zip", "find_user_id_by_email": "email",
|
| 32 |
+
"find_user_id_by_phone": "phone", "find_user_id_by_username": "username"}
|
| 33 |
+
|
| 34 |
+
OPENERS_VAGUE = [
|
| 35 |
+
"Hi, I need a hand with something on my account.",
|
| 36 |
+
"Hello, I'm hoping you can help me with one of my orders.",
|
| 37 |
+
"Hey there, I've got a question about my account.",
|
| 38 |
+
"Hi, could you help me sort something out on my account?",
|
| 39 |
+
"Hello, I need to take care of a couple of things on my order.",
|
| 40 |
+
"Hi, I was hoping to get some help with my account today.",
|
| 41 |
+
"Hey, I need help with something. Not sure who to ask.",
|
| 42 |
+
"Hi there, can you help me with an order issue?",
|
| 43 |
+
]
|
| 44 |
+
# b1: verify-ask pools keyed by the auth method the row actually uses
|
| 45 |
+
VERIFY_ASK = {
|
| 46 |
+
"name_zip": [
|
| 47 |
+
"Of course, I'd be glad to help. First, can I verify your identity? Could you give me your full name and ZIP code?",
|
| 48 |
+
"Happy to help with that. Before I pull anything up, could you confirm your name and ZIP code for me?",
|
| 49 |
+
"Sure thing. To access your account I'll need to verify you first. What's your full name and ZIP code?",
|
| 50 |
+
"I can help with that. For security, could you share your full name and the ZIP code on your account?",
|
| 51 |
+
"Absolutely. Let me just verify you first. Can I get your name and ZIP code, please?",
|
| 52 |
+
"Glad to help. To start, could you confirm your full name and ZIP code so I can find your account?",
|
| 53 |
+
],
|
| 54 |
+
"email": [
|
| 55 |
+
"Of course, I'd be glad to help. First, can I verify your identity? What's the email address on your account?",
|
| 56 |
+
"Happy to help with that. Before I pull anything up, could you confirm the email address on your account?",
|
| 57 |
+
"Sure thing. To access your account I'll need to verify you first. What email address is on the account?",
|
| 58 |
+
"I can help with that. For security, could you share the email address associated with your account?",
|
| 59 |
+
"Absolutely. Let me just verify you first. What's the email on file for your account?",
|
| 60 |
+
"Glad to help. To start, could you confirm the email address on your account so I can look you up?",
|
| 61 |
+
],
|
| 62 |
+
"phone": [
|
| 63 |
+
"Of course, I'd be glad to help. First, can I verify your identity? What's the phone number on your account?",
|
| 64 |
+
"Happy to help. Before I pull anything up, could you confirm the phone number on file for your account?",
|
| 65 |
+
"Sure thing. To verify you, could you share the phone number associated with your account?",
|
| 66 |
+
],
|
| 67 |
+
"username": [
|
| 68 |
+
"Of course, I'd be glad to help. First, can I verify you? Could you give me your account username?",
|
| 69 |
+
"Happy to help. Before I pull anything up, could you confirm the username on your account?",
|
| 70 |
+
"Sure thing. To verify you, what's the username on your account?",
|
| 71 |
+
],
|
| 72 |
+
}
|
| 73 |
+
ID_PROVIDE = [
|
| 74 |
+
"Yeah, sure. It's {first} {last}, and the ZIP is {zip}.",
|
| 75 |
+
"Oh, right. {first} {last}, ZIP {zip}.",
|
| 76 |
+
"Of course, it's {first} {last}. ZIP code's {zip}.",
|
| 77 |
+
"Sure thing. Name's {first} {last}, and my ZIP is {zip}.",
|
| 78 |
+
"Um, ok. {first} {last}, and the ZIP on the account is {zip}.",
|
| 79 |
+
]
|
| 80 |
+
VERIFIED = [
|
| 81 |
+
"Thanks {first}, you're all verified. What can I do for you?",
|
| 82 |
+
"Great, I've got your account pulled up, {first}. How can I help?",
|
| 83 |
+
"You're all set, {first}. What would you like to do?",
|
| 84 |
+
"Perfect, verified. Thanks {first}. What can I help with?",
|
| 85 |
+
]
|
| 86 |
+
|
| 87 |
+
# b3: deterministic scrub of leaked argument id-tokens from NL (never touches calls)
|
| 88 |
+
_APPOS = re.compile(r",?\s*(?:the\s+)?id\s+is\s+(?:gift_card_\w+|credit_card_\w+)", re.I)
|
| 89 |
+
_GC_AFTER = re.compile(r"(gift card)\s+gift_card_\w+", re.I)
|
| 90 |
+
_CC_AFTER = re.compile(r"(credit card|card)\s+credit_card_\w+", re.I)
|
| 91 |
+
_GC_BARE = re.compile(r"\bgift_card_\w+")
|
| 92 |
+
_CC_BARE = re.compile(r"\bcredit_card_\w+")
|
| 93 |
+
_SPACE = re.compile(r"\s{2,}")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def scrub(text: str, role: str) -> str:
|
| 97 |
+
if not text or ("_card_" not in text):
|
| 98 |
+
return text
|
| 99 |
+
mine = "your" if role == "assistant" else "my"
|
| 100 |
+
t = _APPOS.sub("", text)
|
| 101 |
+
t = _GC_AFTER.sub(r"\1", t)
|
| 102 |
+
t = _CC_AFTER.sub(r"\1", t)
|
| 103 |
+
t = _GC_BARE.sub(f"{mine} gift card", t)
|
| 104 |
+
t = _CC_BARE.sub(f"{mine} card on file", t)
|
| 105 |
+
t = t.replace(" ,", ",").replace(" .", ".").replace(" ?", "?")
|
| 106 |
+
t = _SPACE.sub(" ", t).strip()
|
| 107 |
+
return t
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def hist_of(r):
|
| 111 |
+
return r.get("history") or (r.get("metadata") or {}).get("history") or []
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def umsg(c):
|
| 115 |
+
return {"role": "user", "content": c, "tool_calls": [], "tool_call_id": None}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def amsg(content=None, tool_calls=None):
|
| 119 |
+
return {"role": "assistant", "content": content,
|
| 120 |
+
"tool_calls": copy.deepcopy(tool_calls) if tool_calls else [],
|
| 121 |
+
"tool_call_id": None}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def tmsg(call):
|
| 125 |
+
return {"role": "tool", "content": call.get("output"), "tool_calls": [], "tool_call_id": None}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def pick(lst, eid, salt=""):
|
| 129 |
+
return lst[int(hashlib.md5((salt + eid).encode()).hexdigest(), 16) % len(lst)]
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def greeting_of(r):
|
| 133 |
+
h = hist_of(r)
|
| 134 |
+
if h and h[0].get("role") == "assistant" and not h[0].get("tool_calls") and h[0].get("content"):
|
| 135 |
+
return copy.deepcopy(h[0])
|
| 136 |
+
return amsg(content="Hi! How can I help you today?")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def leading_auth(r):
|
| 140 |
+
lead = []
|
| 141 |
+
for m in hist_of(r):
|
| 142 |
+
for t in (m.get("tool_calls") or []):
|
| 143 |
+
if t["name"] in AUTH_LEAD:
|
| 144 |
+
lead.append(copy.deepcopy(t))
|
| 145 |
+
kept = []
|
| 146 |
+
for t in lead:
|
| 147 |
+
if not kept and t["name"] == "find_user_id_by_name_zip":
|
| 148 |
+
kept.append(t)
|
| 149 |
+
elif kept and t["name"] == "get_user_details":
|
| 150 |
+
kept.append(t); break
|
| 151 |
+
else:
|
| 152 |
+
break
|
| 153 |
+
return kept
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def auth_method(r):
|
| 157 |
+
for c in r["calls"]:
|
| 158 |
+
if c["name"] in FIND_METHOD:
|
| 159 |
+
return FIND_METHOD[c["name"]]
|
| 160 |
+
return "name_zip"
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def base_history(r):
|
| 164 |
+
"""(cleaned_history, had_auth). b1: verify-ask matches the row's auth method."""
|
| 165 |
+
eid = r["example_id"]
|
| 166 |
+
greet = greeting_of(r)
|
| 167 |
+
opener = umsg(pick(OPENERS_VAGUE, eid, "op"))
|
| 168 |
+
kept = leading_auth(r)
|
| 169 |
+
method = "name_zip" if kept else auth_method(r) # auth-in-history rows are name_zip
|
| 170 |
+
ask = amsg(content=pick(VERIFY_ASK[method], eid, "ask"))
|
| 171 |
+
if not kept:
|
| 172 |
+
return [greet, opener, ask], False
|
| 173 |
+
a = kept[0].get("arguments", {})
|
| 174 |
+
first = a.get("first_name", ""); last = a.get("last_name", ""); zp = a.get("zip", "")
|
| 175 |
+
idp = umsg(pick(ID_PROVIDE, eid, "idp").format(first=first, last=last, zip=zp))
|
| 176 |
+
verified = amsg(content=pick(VERIFIED, eid, "ok").format(first=first or "there"))
|
| 177 |
+
hist = [greet, opener, ask, idp]
|
| 178 |
+
for t in kept:
|
| 179 |
+
hist += [amsg(tool_calls=[t]), tmsg(t)]
|
| 180 |
+
hist += [verified]
|
| 181 |
+
return hist, True
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def calls_sig(calls):
|
| 185 |
+
return [(c.get("name"), json.dumps(c.get("arguments", {}), sort_keys=True, ensure_ascii=False))
|
| 186 |
+
for c in (calls or [])]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def main():
|
| 190 |
+
rows = [json.loads(l) for l in open(N100, encoding="utf-8") if l.strip()]
|
| 191 |
+
a4 = json.loads(AUTHORED4.read_text(encoding="utf-8"))
|
| 192 |
+
a2 = json.loads(AUTHORED2.read_text(encoding="utf-8"))
|
| 193 |
+
q1fix = json.loads(Q1FIX.read_text(encoding="utf-8")) if Q1FIX.exists() else {}
|
| 194 |
+
v3 = {json.loads(l)["example_id"]: json.loads(l)
|
| 195 |
+
for l in open(V3, encoding="utf-8") if l.strip()}
|
| 196 |
+
v3_split = {r["metadata"]["orig_eid"] for r in v3.values()
|
| 197 |
+
if (r.get("metadata") or {}).get("unbundle_role") == "turn1"}
|
| 198 |
+
|
| 199 |
+
def bundle(eid):
|
| 200 |
+
b = a4.get(eid)
|
| 201 |
+
if b and "q1" in b and not b.get("_err"):
|
| 202 |
+
return b
|
| 203 |
+
b = a2.get(eid)
|
| 204 |
+
if b and "q1" in b and not b.get("_err"):
|
| 205 |
+
return b
|
| 206 |
+
return None
|
| 207 |
+
|
| 208 |
+
ok = {e: bundle(e) for e in a4 if bundle(e)}
|
| 209 |
+
for e in a2:
|
| 210 |
+
if e not in ok and bundle(e):
|
| 211 |
+
ok[e] = bundle(e)
|
| 212 |
+
print(f"usable bundles: {len(ok)}")
|
| 213 |
+
|
| 214 |
+
n_scrub = 0
|
| 215 |
+
out = []; split_eids = set(); n_auth = 0; method_ct = {"name_zip": 0, "email": 0, "phone": 0, "username": 0}
|
| 216 |
+
for r in rows:
|
| 217 |
+
eid = r["example_id"]
|
| 218 |
+
if eid not in ok or eid not in v3_split:
|
| 219 |
+
out.append(r); continue
|
| 220 |
+
sp = copy.deepcopy(ok[eid]); md = r["metadata"]; ad = md["anchor_depth"]
|
| 221 |
+
calls = r["calls"]; prefixF = calls[:ad + 1]; tail = calls[ad + 1:]
|
| 222 |
+
if len(tail) != len(sp["turns"]):
|
| 223 |
+
out.append(r); continue
|
| 224 |
+
base_prehist, had_auth = base_history(r)
|
| 225 |
+
if had_auth and eid in q1fix:
|
| 226 |
+
sp["q1"] = q1fix[eid]["q1"]
|
| 227 |
+
method_ct["name_zip" if had_auth else auth_method(r)] += 1
|
| 228 |
+
n_auth += int(had_auth); split_eids.add(eid)
|
| 229 |
+
|
| 230 |
+
# b3 scrub on every authored NL string (user + assistant)
|
| 231 |
+
def sc(txt, role):
|
| 232 |
+
nonlocal n_scrub
|
| 233 |
+
new = scrub(txt, role)
|
| 234 |
+
if new != txt:
|
| 235 |
+
n_scrub += 1
|
| 236 |
+
return new
|
| 237 |
+
sp["q1"] = sc(sp["q1"], "user")
|
| 238 |
+
sp["ack1"] = sc(sp["ack1"], "assistant")
|
| 239 |
+
sp["turns"] = [{"user": sc(t["user"], "user"), "ack": sc(t["ack"], "assistant")}
|
| 240 |
+
for t in sp["turns"]]
|
| 241 |
+
|
| 242 |
+
t1 = copy.deepcopy(r)
|
| 243 |
+
t1["query"] = sp["q1"]; t1["calls"] = copy.deepcopy(prefixF)
|
| 244 |
+
t1["history"] = copy.deepcopy(base_prehist)
|
| 245 |
+
t1["metadata"] = copy.deepcopy(md)
|
| 246 |
+
t1["metadata"]["history"] = copy.deepcopy(base_prehist)
|
| 247 |
+
t1["metadata"]["unbundle_role"] = "turn1"; t1["metadata"]["orig_eid"] = eid
|
| 248 |
+
out.append(t1)
|
| 249 |
+
|
| 250 |
+
base_hist = (copy.deepcopy(base_prehist)
|
| 251 |
+
+ [umsg(sp["q1"]), amsg(tool_calls=prefixF)]
|
| 252 |
+
+ [tmsg(c) for c in prefixF]
|
| 253 |
+
+ [amsg(content=sp["ack1"])])
|
| 254 |
+
for i, call in enumerate(tail):
|
| 255 |
+
hist = copy.deepcopy(base_hist)
|
| 256 |
+
for j in range(i):
|
| 257 |
+
cj = tail[j]
|
| 258 |
+
hist += [umsg(sp["turns"][j]["user"]), amsg(tool_calls=[cj]),
|
| 259 |
+
tmsg(cj), amsg(content=sp["turns"][j]["ack"])]
|
| 260 |
+
trow = copy.deepcopy(r)
|
| 261 |
+
trow["example_id"] = f"{eid}-t{i + 2}"
|
| 262 |
+
trow["query"] = sp["turns"][i]["user"]
|
| 263 |
+
trow["calls"] = [copy.deepcopy(call)]
|
| 264 |
+
trow["history"] = hist
|
| 265 |
+
trow["metadata"] = copy.deepcopy(md)
|
| 266 |
+
trow["metadata"]["history"] = copy.deepcopy(hist)
|
| 267 |
+
trow["metadata"]["unbundle_role"] = f"turn{i + 2}"
|
| 268 |
+
trow["metadata"]["orig_eid"] = eid
|
| 269 |
+
out.append(trow)
|
| 270 |
+
|
| 271 |
+
# b3 final pass: scrub any remaining card tokens in dialogue NL across ALL rows
|
| 272 |
+
# (covers passthrough/original confuser queries + histories). Tool outputs (role
|
| 273 |
+
# == "tool") and call arguments are left untouched, so calls/state db are intact.
|
| 274 |
+
for r in out:
|
| 275 |
+
if r.get("query") and "_card_" in r["query"]:
|
| 276 |
+
new = scrub(r["query"], "user")
|
| 277 |
+
if new != r["query"]:
|
| 278 |
+
r["query"] = new; n_scrub += 1
|
| 279 |
+
for m in (r.get("history") or []):
|
| 280 |
+
role = m.get("role")
|
| 281 |
+
if role in ("user", "assistant") and m.get("content") and "_card_" in m["content"]:
|
| 282 |
+
new = scrub(m["content"], role)
|
| 283 |
+
if new != m["content"]:
|
| 284 |
+
m["content"] = new; n_scrub += 1
|
| 285 |
+
md = r.get("metadata") or {}
|
| 286 |
+
for m in (md.get("history") or []):
|
| 287 |
+
role = m.get("role")
|
| 288 |
+
if role in ("user", "assistant") and m.get("content") and "_card_" in m["content"]:
|
| 289 |
+
new = scrub(m["content"], role)
|
| 290 |
+
if new != m["content"]:
|
| 291 |
+
m["content"] = new; n_scrub += 1
|
| 292 |
+
|
| 293 |
+
v5 = {r["example_id"]: r for r in out}
|
| 294 |
+
assert set(v5) == set(v3), "row-id set changed vs v3"
|
| 295 |
+
bad = [eid for eid in v3 if calls_sig(v3[eid]["calls"]) != calls_sig(v5[eid]["calls"])]
|
| 296 |
+
assert not bad, f"CALLS CHANGED vs v3 for {len(bad)} rows, e.g. {bad[:5]}"
|
| 297 |
+
|
| 298 |
+
# b3 sanity: no leaked card tokens remain anywhere in NL
|
| 299 |
+
leftover = []
|
| 300 |
+
for r in out:
|
| 301 |
+
txts = [r.get("query") or ""]
|
| 302 |
+
for src in (r.get("history") or []), ((r.get("metadata") or {}).get("history") or []):
|
| 303 |
+
txts += [m.get("content") or "" for m in src if m.get("role") != "tool"]
|
| 304 |
+
for t in txts:
|
| 305 |
+
if re.search(r"gift_card_\w+|credit_card_\w+", t):
|
| 306 |
+
leftover.append(r["example_id"]); break
|
| 307 |
+
assert not leftover, f"card tokens still in NL for {len(leftover)} rows: {leftover[:5]}"
|
| 308 |
+
|
| 309 |
+
OUT.parent.mkdir(parents=True, exist_ok=True)
|
| 310 |
+
with OUT.open("w", encoding="utf-8") as fh:
|
| 311 |
+
for r in out:
|
| 312 |
+
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 313 |
+
|
| 314 |
+
print(f"input rows: {len(rows)} output rows: {len(out)}")
|
| 315 |
+
print(f"split: {len(split_eids)} greeting-only: {len(split_eids)-n_auth} auth-in-history: {n_auth}")
|
| 316 |
+
print(f"b1 verify-ask by method: {method_ct}")
|
| 317 |
+
print(f"b3 NL strings scrubbed: {n_scrub} (leftover card tokens: {len(leftover)})")
|
| 318 |
+
print(f"INVARIANT OK: calls byte-identical to v3 for all {len(v3)} rows (trie unchanged).")
|
| 319 |
+
print(f"wrote {OUT.relative_to(ROOT)}")
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
if __name__ == "__main__":
|
| 323 |
+
main()
|
tempscripts/story_remediation/unbundle/build_all_v6.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build v6 from v5: prose-only deterministic auth/identity fixes (calls-invariant).
|
| 2 |
+
|
| 3 |
+
Fixes (all in authored NL only, never in `calls`):
|
| 4 |
+
1. name_mismatch -- agent addresses customer by a name != auth first_name
|
| 5 |
+
2. dup_verification -- >1 "you're verified" confirmation; keep the first, strip rest
|
| 6 |
+
3. zip_mismatch -- customer states a ZIP (in a zip context) != auth zip
|
| 7 |
+
4. userid_in_prose -- user speaks their internal user_id token (e.g. xan_rho_6699)
|
| 8 |
+
|
| 9 |
+
Rendering defects the C3 judge cited (raw-JSON assistant content, markdown/bold in
|
| 10 |
+
user messages) do NOT exist in the data -- 0 occurrences -- so nothing to fix there;
|
| 11 |
+
the judge hallucinated them. (Verified by rendering the cited row.)
|
| 12 |
+
|
| 13 |
+
Reads : temp/story_remediation/unbundle/out/trajectories_all_v5.jsonl
|
| 14 |
+
Writes: temp/story_remediation/unbundle/out/trajectories_all_v6.jsonl
|
| 15 |
+
"""
|
| 16 |
+
import json, re, sys, copy
|
| 17 |
+
sys.path.insert(0, r"temp/story_remediation/unbundle")
|
| 18 |
+
import auth_lint_v5 as L
|
| 19 |
+
|
| 20 |
+
SRC = r"temp/story_remediation/unbundle/out/trajectories_all_v5.jsonl"
|
| 21 |
+
OUT = r"temp/story_remediation/unbundle/out/trajectories_all_v6.jsonl"
|
| 22 |
+
|
| 23 |
+
ZIP_SUB_RX = None # built per-row
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def strip_verif(text):
|
| 27 |
+
"""Remove a verification-confirmation clause, keep the rest of the sentence."""
|
| 28 |
+
t = text
|
| 29 |
+
t = re.sub(r",?\s*you'?re (all )?verified", "", t, flags=re.I)
|
| 30 |
+
t = re.sub(r",?\s*you are (all )?verified", "", t, flags=re.I)
|
| 31 |
+
t = re.sub(r"Perfect,\s*verified\.\s*", "", t, flags=re.I)
|
| 32 |
+
t = re.sub(r"(Yep,?\s*|Yes,?\s*)?I'?ve verified your identity(?: (?:using|with) code \d+)?\.\s*", "", t, flags=re.I)
|
| 33 |
+
t = re.sub(r"I'?ve verified your account and\s*", "I've ", t, flags=re.I)
|
| 34 |
+
t = re.sub(r"\s{2,}", " ", t)
|
| 35 |
+
t = re.sub(r"^[,.\s]+", "", t)
|
| 36 |
+
t = t.replace(" .", ".").replace(" ,", ",").strip()
|
| 37 |
+
if t and t[0].islower():
|
| 38 |
+
t = t[0].upper() + t[1:]
|
| 39 |
+
return t
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def fix_row(r):
|
| 43 |
+
changed = []
|
| 44 |
+
method, first, last, zipc, email = L.auth_identity(r)
|
| 45 |
+
|
| 46 |
+
# --- collect wrong names (agent-spoken first names != auth first name) ---
|
| 47 |
+
allowed = {x.lower() for x in (first, last) if x}
|
| 48 |
+
wrong_names = set()
|
| 49 |
+
for role, c in L.convo_turns(r):
|
| 50 |
+
if role != "assistant":
|
| 51 |
+
continue
|
| 52 |
+
for m in list(L.ADDR_RX.finditer(c)) + list(L.ADDR_RX2.finditer(c)):
|
| 53 |
+
tok = m.group(1)
|
| 54 |
+
if tok in L.STOP:
|
| 55 |
+
continue
|
| 56 |
+
if allowed and tok.lower() not in allowed:
|
| 57 |
+
wrong_names.add(tok)
|
| 58 |
+
|
| 59 |
+
# --- mismatched zips (spoken in a zip-context, != auth zip, not a call-arg value) ---
|
| 60 |
+
argvals = L.call_arg_values(r)
|
| 61 |
+
bad_zips = set()
|
| 62 |
+
if zipc:
|
| 63 |
+
for role, c in L.convo_turns(r):
|
| 64 |
+
for m in L.ZIP_CTX_RX.finditer(c):
|
| 65 |
+
z = m.group(1)
|
| 66 |
+
if z != str(zipc) and z.lower() not in argvals:
|
| 67 |
+
bad_zips.add(z)
|
| 68 |
+
|
| 69 |
+
# --- user_id token spoken by the user ---
|
| 70 |
+
uid_rx = None
|
| 71 |
+
if first and last:
|
| 72 |
+
uid_rx = re.compile(r"\b" + re.escape(first.lower()) + r"_" + re.escape(last.lower()) + r"_\d+\b")
|
| 73 |
+
|
| 74 |
+
# user self-identification with a wrong first name (last name matches, framed as a
|
| 75 |
+
# self-intro -- NOT "my spouse's account ... <OtherName>")
|
| 76 |
+
selfid_rx = None
|
| 77 |
+
if first and last:
|
| 78 |
+
selfid_rx = re.compile(
|
| 79 |
+
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")
|
| 80 |
+
|
| 81 |
+
def fix_content(role, content):
|
| 82 |
+
nonlocal changed
|
| 83 |
+
if not content:
|
| 84 |
+
return content, False
|
| 85 |
+
new = content
|
| 86 |
+
# (1) name mismatch -- assistant only
|
| 87 |
+
if role == "assistant":
|
| 88 |
+
for wn in wrong_names:
|
| 89 |
+
if first:
|
| 90 |
+
n2 = re.sub(r"\b" + re.escape(wn) + r"\b", first, new)
|
| 91 |
+
if n2 != new:
|
| 92 |
+
new = n2; changed.append("name_mismatch")
|
| 93 |
+
# (3) zip mismatch -- replace inside the zip context, any role
|
| 94 |
+
for bz in bad_zips:
|
| 95 |
+
n2 = re.sub(r"(zip\D{0,12})" + re.escape(bz), r"\g<1>" + str(zipc), new, flags=re.I)
|
| 96 |
+
if n2 != new:
|
| 97 |
+
new = n2; changed.append("zip_mismatch")
|
| 98 |
+
# (4) user_id token -- user only
|
| 99 |
+
if role == "user" and uid_rx is not None:
|
| 100 |
+
repl = (first + " " + last)
|
| 101 |
+
n2 = uid_rx.sub(repl, new)
|
| 102 |
+
if n2 != new:
|
| 103 |
+
new = n2; changed.append("userid_in_prose")
|
| 104 |
+
# (5) user self-intro wrong first name -- user only
|
| 105 |
+
if role == "user" and selfid_rx is not None:
|
| 106 |
+
def _sid(m):
|
| 107 |
+
if m.group(2).lower() == first.lower():
|
| 108 |
+
return m.group(0)
|
| 109 |
+
return f"{m.group(1)} {first} {last}"
|
| 110 |
+
n2 = selfid_rx.sub(_sid, new)
|
| 111 |
+
if n2 != new:
|
| 112 |
+
new = n2; changed.append("selfid_name_mismatch")
|
| 113 |
+
return new, (new != content)
|
| 114 |
+
|
| 115 |
+
# apply name/zip/uid fixes across history + query
|
| 116 |
+
for h in r.get("history", []):
|
| 117 |
+
if h.get("role") in ("user", "assistant") and h.get("content"):
|
| 118 |
+
nc, _ = fix_content(h["role"], h["content"])
|
| 119 |
+
h["content"] = nc
|
| 120 |
+
if r.get("query"):
|
| 121 |
+
r["query"], _ = fix_content("user", r["query"])
|
| 122 |
+
# mirror into embedded metadata.history for self-consistency
|
| 123 |
+
for h in (r.get("metadata", {}).get("history") or []):
|
| 124 |
+
if h.get("role") in ("user", "assistant") and h.get("content"):
|
| 125 |
+
nc, _ = fix_content(h["role"], h["content"])
|
| 126 |
+
h["content"] = nc
|
| 127 |
+
|
| 128 |
+
# (2) dup verification -- keep FIRST confirmation, strip subsequent ones.
|
| 129 |
+
# Walk the conversation in render order (history then query), stripping in-place.
|
| 130 |
+
seen_verif = False
|
| 131 |
+
|
| 132 |
+
def walk_strip(entries):
|
| 133 |
+
nonlocal seen_verif
|
| 134 |
+
for h in entries:
|
| 135 |
+
if h.get("role") == "assistant" and h.get("content") and L.VERIFIED_RX.search(h["content"]):
|
| 136 |
+
if seen_verif:
|
| 137 |
+
stripped = strip_verif(h["content"])
|
| 138 |
+
if stripped != h["content"]:
|
| 139 |
+
h["content"] = stripped
|
| 140 |
+
changed.append("dup_verification")
|
| 141 |
+
else:
|
| 142 |
+
seen_verif = True
|
| 143 |
+
|
| 144 |
+
walk_strip(r.get("history", []))
|
| 145 |
+
# query is user role -> never a verification confirmation; skip
|
| 146 |
+
# mirror strip in metadata.history using an independent pass
|
| 147 |
+
seen2 = False
|
| 148 |
+
for h in (r.get("metadata", {}).get("history") or []):
|
| 149 |
+
if h.get("role") == "assistant" and h.get("content") and L.VERIFIED_RX.search(h["content"]):
|
| 150 |
+
if seen2:
|
| 151 |
+
h["content"] = strip_verif(h["content"])
|
| 152 |
+
else:
|
| 153 |
+
seen2 = True
|
| 154 |
+
|
| 155 |
+
return changed
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def main():
|
| 159 |
+
rows = [json.loads(l) for l in open(SRC, encoding="utf-8")]
|
| 160 |
+
src_calls = [json.dumps(r["calls"], sort_keys=True) for r in rows]
|
| 161 |
+
from collections import Counter
|
| 162 |
+
tally = Counter()
|
| 163 |
+
touched = 0
|
| 164 |
+
for r in rows:
|
| 165 |
+
ch = fix_row(r)
|
| 166 |
+
if ch:
|
| 167 |
+
touched += 1
|
| 168 |
+
for k in set(ch):
|
| 169 |
+
tally[k] += 1
|
| 170 |
+
# calls invariant assert
|
| 171 |
+
new_calls = [json.dumps(r["calls"], sort_keys=True) for r in rows]
|
| 172 |
+
assert src_calls == new_calls, "CALLS CHANGED -- aborting"
|
| 173 |
+
|
| 174 |
+
with open(OUT, "w", encoding="utf-8") as f:
|
| 175 |
+
for r in rows:
|
| 176 |
+
f.write(json.dumps(r) + "\n")
|
| 177 |
+
|
| 178 |
+
print("v6 built:", OUT)
|
| 179 |
+
print("rows touched:", touched)
|
| 180 |
+
print("fix tally (rows with each fix type):")
|
| 181 |
+
for k in ["name_mismatch", "dup_verification", "zip_mismatch", "userid_in_prose", "selfid_name_mismatch"]:
|
| 182 |
+
print(f" {k:16s} {tally[k]}")
|
| 183 |
+
print("calls invariant vs v5: OK (byte-identical)")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
if __name__ == "__main__":
|
| 187 |
+
main()
|
tempscripts/story_remediation/unbundle/build_v3.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unbundle prototype: split a confuser's single harvested mega-turn into TWO
|
| 2 |
+
turns at the trie divergence point (metadata.anchor_depth).
|
| 3 |
+
|
| 4 |
+
For each candidate:
|
| 5 |
+
turn1 (T1, the PRIMARY confuser, retrieval target preserved):
|
| 6 |
+
query = narrowed q1 (only warrants prefix + F, the infiltration node)
|
| 7 |
+
calls = orig_calls[:anchor_depth+1] (prefix + F) <- still diverges
|
| 8 |
+
at anchor_depth with F, exactly as before
|
| 9 |
+
history = original history (unchanged)
|
| 10 |
+
turn2 (T2, the cut tail, re-rooted as its own trie path):
|
| 11 |
+
query = q2 (a fresh user request motivating the tail)
|
| 12 |
+
calls = orig_calls[anchor_depth+1:] (G..Z)
|
| 13 |
+
history = original history + [q1, assistant(tool_calls=prefix+F, real
|
| 14 |
+
recorded outputs reused verbatim), bridge] -> auth already done,
|
| 15 |
+
T2 does NOT re-auth (matches tau2: authenticate once, early)
|
| 16 |
+
|
| 17 |
+
C3 blinds tool names, so the confuser/fictional tools in the tail are fine; we
|
| 18 |
+
only repartition the row's OWN existing calls across two turns (no new tools,
|
| 19 |
+
no fabricated outputs).
|
| 20 |
+
|
| 21 |
+
Writes out/trajectories_v3.jsonl (20 rows: 10 T1 + 10 T2).
|
| 22 |
+
Run: python -u temp/story_remediation/unbundle/build_v3.py
|
| 23 |
+
"""
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
import json, copy
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
HERE = Path(__file__).resolve().parent
|
| 29 |
+
ROOT = HERE.parents[2]
|
| 30 |
+
N100 = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 31 |
+
OUT = HERE / "out" / "trajectories_v3.jsonl"
|
| 32 |
+
|
| 33 |
+
# Authored splits: q1 (narrowed turn-1), bridge (assistant reply after turn1),
|
| 34 |
+
# q2 (turn-2 user request for the tail). Entities reuse ids already in the query.
|
| 35 |
+
SPLITS = {
|
| 36 |
+
"confuser-add_gift_message-227": dict(
|
| 37 |
+
q1="On my pending gift order #W3410100, please add the gift message 'Happy Graduation!'.",
|
| 38 |
+
bridge="Done, I've added the gift message 'Happy Graduation!' to order #W3410100.",
|
| 39 |
+
q2="Thanks. Separately, for my delivered order #W3410200, can you give me a printable return label?"),
|
| 40 |
+
"confuser-get_return_label-271": dict(
|
| 41 |
+
q1="Now to my orders - I need a printable prepaid return label for #W5590123.",
|
| 42 |
+
bridge="Here's your prepaid return label for #W5590123, emailed as a printable PDF.",
|
| 43 |
+
q2="Great. One more - for #W2201984, can you send a gift receipt with no prices?"),
|
| 44 |
+
"confuser-request_gift_receipt-195": dict(
|
| 45 |
+
q1="For my order #W3320800, which was a gift, I need a gift receipt with no prices.",
|
| 46 |
+
bridge="Done - here's the no-price gift receipt for #W3320800.",
|
| 47 |
+
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?"),
|
| 48 |
+
"confuser-get_shipping_options-215": dict(
|
| 49 |
+
q1="For my pending order #W5567012, what shipping options and speeds are available?",
|
| 50 |
+
bridge="Here are the available shipping options and speeds for #W5567012.",
|
| 51 |
+
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?"),
|
| 52 |
+
"confuser-redeem_loyalty_points-163": dict(
|
| 53 |
+
q1="I've got a lot of loyalty points - can you redeem 2,000 of them for store credit?",
|
| 54 |
+
bridge="Done - I've redeemed 2,000 loyalty points for store credit.",
|
| 55 |
+
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?"),
|
| 56 |
+
"confuser-get_size_guide-199": dict(
|
| 57 |
+
q1="On the trail shoes, can you pull up the sizing chart?",
|
| 58 |
+
bridge="Here's the sizing chart for the trail shoes.",
|
| 59 |
+
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.'"),
|
| 60 |
+
"confuser-get_gift_card_balance-346": dict(
|
| 61 |
+
q1="Before I finalize order #W3401200, can you tell me the balance on my gift card gift_card_3401120?",
|
| 62 |
+
bridge="Here's the current balance on gift card gift_card_3401120.",
|
| 63 |
+
q2="Thanks. And what promotions are currently running?"),
|
| 64 |
+
"confuser-get_warranty_details-281": dict(
|
| 65 |
+
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.",
|
| 66 |
+
bridge="Here are the manufacturer's warranty terms for your air purifier from order #W6042219.",
|
| 67 |
+
q2="Perfect. Can you go ahead and register that warranty under my account so it's active?"),
|
| 68 |
+
"confuser-get_warranty_details-455": dict(
|
| 69 |
+
q1="For the jacket (item 3566100900) in my order #W3566100, can you show the warranty coverage? My email is cara.vin@example.com.",
|
| 70 |
+
bridge="Here's the warranty coverage for the jacket (item 3566100900).",
|
| 71 |
+
q2="Thanks. Could you also show the extended-warranty plans and the sizing chart for it?"),
|
| 72 |
+
"confuser-file_shipping_insurance_claim-296": dict(
|
| 73 |
+
q1="My order #W5540921 was a gift that arrived damaged - please file a shipping-insurance claim.",
|
| 74 |
+
bridge="I've filed a shipping-insurance claim for order #W5540921.",
|
| 75 |
+
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?"),
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def hist_of(r):
|
| 80 |
+
return r.get("history") or (r.get("metadata") or {}).get("history") or []
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def main():
|
| 84 |
+
rows = {json.loads(l)["example_id"]: json.loads(l)
|
| 85 |
+
for l in open(N100, encoding="utf-8") if l.strip()}
|
| 86 |
+
out = []
|
| 87 |
+
for eid, sp in SPLITS.items():
|
| 88 |
+
r = rows[eid]
|
| 89 |
+
md = r["metadata"]; ad = md["anchor_depth"]
|
| 90 |
+
calls = r["calls"]
|
| 91 |
+
t1_calls = calls[:ad + 1]
|
| 92 |
+
tail_calls = calls[ad + 1:]
|
| 93 |
+
assert tail_calls, f"{eid}: empty tail"
|
| 94 |
+
orig_hist = hist_of(r)
|
| 95 |
+
|
| 96 |
+
# ---- T1: primary confuser, tail removed, query narrowed ----
|
| 97 |
+
t1 = copy.deepcopy(r)
|
| 98 |
+
t1["query"] = sp["q1"]
|
| 99 |
+
t1["calls"] = copy.deepcopy(t1_calls)
|
| 100 |
+
t1["history"] = copy.deepcopy(orig_hist)
|
| 101 |
+
t1["metadata"] = copy.deepcopy(md)
|
| 102 |
+
t1["metadata"]["history"] = copy.deepcopy(orig_hist)
|
| 103 |
+
t1["metadata"]["unbundle_role"] = "turn1"
|
| 104 |
+
t1["metadata"]["orig_eid"] = eid
|
| 105 |
+
out.append(t1)
|
| 106 |
+
|
| 107 |
+
# ---- T2: the cut tail, re-rooted; turn1 shown as completed history ----
|
| 108 |
+
t1_assistant = {"role": "assistant", "content": None,
|
| 109 |
+
"tool_calls": copy.deepcopy(t1_calls), "tool_call_id": None}
|
| 110 |
+
tool_msgs = [{"role": "tool", "content": c.get("output"),
|
| 111 |
+
"tool_calls": [], "tool_call_id": None} for c in t1_calls]
|
| 112 |
+
bridge_hist = (copy.deepcopy(orig_hist)
|
| 113 |
+
+ [{"role": "user", "content": sp["q1"], "tool_calls": [], "tool_call_id": None},
|
| 114 |
+
t1_assistant]
|
| 115 |
+
+ tool_msgs
|
| 116 |
+
+ [{"role": "assistant", "content": sp["bridge"], "tool_calls": [], "tool_call_id": None}])
|
| 117 |
+
t2 = copy.deepcopy(r)
|
| 118 |
+
t2["example_id"] = eid + "-t2"
|
| 119 |
+
t2["query"] = sp["q2"]
|
| 120 |
+
t2["calls"] = copy.deepcopy(tail_calls)
|
| 121 |
+
t2["history"] = bridge_hist
|
| 122 |
+
t2["metadata"] = copy.deepcopy(md)
|
| 123 |
+
t2["metadata"]["history"] = copy.deepcopy(bridge_hist)
|
| 124 |
+
t2["metadata"]["unbundle_role"] = "turn2"
|
| 125 |
+
t2["metadata"]["orig_eid"] = eid
|
| 126 |
+
out.append(t2)
|
| 127 |
+
|
| 128 |
+
OUT.parent.mkdir(parents=True, exist_ok=True)
|
| 129 |
+
with OUT.open("w", encoding="utf-8") as fh:
|
| 130 |
+
for r in out:
|
| 131 |
+
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 132 |
+
|
| 133 |
+
print(f"wrote {len(out)} rows ({len(SPLITS)} T1 + {len(SPLITS)} T2) -> {OUT.relative_to(ROOT)}")
|
| 134 |
+
for eid, sp in SPLITS.items():
|
| 135 |
+
r = rows[eid]; ad = r["metadata"]["anchor_depth"]
|
| 136 |
+
cn = [c["name"] for c in r["calls"]]
|
| 137 |
+
print(f" {eid}: T1 calls={cn[:ad+1]} | T2 calls={cn[ad+1:]}")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
main()
|
tempscripts/story_remediation/unbundle/diagnose_caught_v5.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Why did C3 catch the v5 synthetics? Re-judge every CAUGHT v5 row once, capture
|
| 2 |
+
the judge's own `reasoning`, and bucket the tells into interpretable categories.
|
| 3 |
+
|
| 4 |
+
The main run (C3_all_v5.jsonl) stored only guesses, so we re-run the identical C3
|
| 5 |
+
prompt on the 543 caught rows, keep the reasoning, and classify each into one
|
| 6 |
+
primary bucket (priority order below) plus multi-label overlap counts.
|
| 7 |
+
|
| 8 |
+
Saves out/caught_reasons_v5.jsonl (eid, role, sample_caught, guess, reasoning,
|
| 9 |
+
buckets) and prints the breakdown.
|
| 10 |
+
Run: python -u temp/story_remediation/unbundle/diagnose_caught_v5.py
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
import json, logging, sys, collections
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import yaml
|
| 17 |
+
|
| 18 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 19 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
ROOT = HERE.parents[2]
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 25 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 26 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 27 |
+
|
| 28 |
+
OUT = HERE / "out"
|
| 29 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 30 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 31 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 32 |
+
|
| 33 |
+
verds = [json.loads(l) for l in open(OUT / "C3_all_v5.jsonl", encoding="utf-8") if l.strip()]
|
| 34 |
+
fakes = {e["example_id"]: e for e in
|
| 35 |
+
(json.loads(l) for l in open(OUT / "trajectories_all_v5.jsonl", encoding="utf-8") if l.strip())}
|
| 36 |
+
base = {}
|
| 37 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 38 |
+
if line.strip():
|
| 39 |
+
d = json.loads(line); base[d["item_id"]] = d
|
| 40 |
+
|
| 41 |
+
reals = P.real_trajectories()
|
| 42 |
+
pairer = P.make_pairer(reals)
|
| 43 |
+
judge = make_judge(cfg["model"])
|
| 44 |
+
|
| 45 |
+
caught = [v for v in verds if v.get("caught")]
|
| 46 |
+
|
| 47 |
+
# bucket -> keyword list. A reasoning may hit several; primary = first in PRIORITY.
|
| 48 |
+
BUCKETS = {
|
| 49 |
+
"A_capability_scenario_realism": [
|
| 50 |
+
"capab", "unrealistic", "not realistic", "unusual request", "unusual", "atypical",
|
| 51 |
+
"wouldn't", "would not", "implausible", "unlikely", "niche", "oddly specific",
|
| 52 |
+
"fabricat", "made-up", "made up", "obscure", "specialized", "nonstandard",
|
| 53 |
+
"non-standard", "not a standard", "not standard", "real system", "real assistant",
|
| 54 |
+
"real agent", "real company", "real retailer", "actual system", "plausib",
|
| 55 |
+
"unusual feature", "feature", "functionalit", "such a tool", "these tools"],
|
| 56 |
+
"B_multitask_bundling": [
|
| 57 |
+
"unrelated", "multiple different", "several different", "range of", "variety",
|
| 58 |
+
"jumps between", "disparate", "disjoint", "laundry list", "checklist",
|
| 59 |
+
"many tasks", "multiple tasks", "multiple requests", "switches", "different topics",
|
| 60 |
+
"grab bag", "one after another", "rapid succession", "back-to-back", "so many",
|
| 61 |
+
"numerous", "series of", "list of requests", "everything at once"],
|
| 62 |
+
"D_auth_verification": [
|
| 63 |
+
"verif", "identity", "authent", "security", "no verification", "without verif",
|
| 64 |
+
"didn't verify", "skipped verif", "no auth"],
|
| 65 |
+
"C_frictionless_smooth": [
|
| 66 |
+
"friction", "too smooth", "seamless", "efficient", "effortless", "no pushback",
|
| 67 |
+
"no hesitat", "compliant", "too easy", "too well", "goes smoothly", "flawless",
|
| 68 |
+
"no complications", "no issues", "everything works", "cooperat", "accommodat"],
|
| 69 |
+
"E_agent_phrasing_templated": [
|
| 70 |
+
"formal", "generic", "templat", "robotic", "scripted", "canned", "stiff",
|
| 71 |
+
"overly polite", "professional", "polished", "assistant's phrasing",
|
| 72 |
+
"assistant phrasing", "agent's phrasing", "agent phrasing", "customer service",
|
| 73 |
+
"corporate", "helpful assistant"],
|
| 74 |
+
"F_customer_phrasing": [
|
| 75 |
+
"customer", "user's phrasing", "user phrasing", "casual", "disfluen", "filler",
|
| 76 |
+
"hedg", "overly casual", "forced", "trying too hard", "stilted", "awkward",
|
| 77 |
+
"too articulate", "too clear", "well-structured", "well structured", "organized",
|
| 78 |
+
"coherent", "natural", "colloquial", "conversational"],
|
| 79 |
+
"G_structure_brevity_history": [
|
| 80 |
+
"abrupt", "terse", "brief", "short", "curt", "clipped", "history", "prior",
|
| 81 |
+
"previous", "context", "follow-up", "follow up", "continuation", "disconnect",
|
| 82 |
+
"out of nowhere", "no context", "sudden", "transition"],
|
| 83 |
+
}
|
| 84 |
+
PRIORITY = ["A_capability_scenario_realism", "B_multitask_bundling", "D_auth_verification",
|
| 85 |
+
"C_frictionless_smooth", "E_agent_phrasing_templated", "F_customer_phrasing",
|
| 86 |
+
"G_structure_brevity_history"]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def label(reason: str):
|
| 90 |
+
low = reason.lower()
|
| 91 |
+
hits = [b for b in PRIORITY if any(k in low for k in BUCKETS[b])]
|
| 92 |
+
primary = hits[0] if hits else "H_other"
|
| 93 |
+
return primary, hits
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def judge_one(v):
|
| 97 |
+
eid = v["item_id"]; fake = fakes.get(eid)
|
| 98 |
+
if not fake:
|
| 99 |
+
return None
|
| 100 |
+
real = pairer(fake)
|
| 101 |
+
swap = (base.get(eid) or base.get(v.get("orig_eid")) or {}).get("answer_key") == "B"
|
| 102 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 103 |
+
key = msgs["answer_key"]
|
| 104 |
+
try:
|
| 105 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 106 |
+
except Exception as e: # noqa: BLE001
|
| 107 |
+
return {"item_id": eid, "role": v.get("role"), "error": str(e)}
|
| 108 |
+
reason = (r.get("reasoning") or "").strip()
|
| 109 |
+
primary, hits = label(reason)
|
| 110 |
+
return {"item_id": eid, "role": v.get("role"), "guess": r.get("guess"),
|
| 111 |
+
"sample_caught": r.get("guess") == key, "primary": primary,
|
| 112 |
+
"buckets": hits, "reasoning": reason}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def main():
|
| 116 |
+
print(f"re-judging {len(caught)} caught rows (workers={WORKERS}) to capture reasoning...")
|
| 117 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 118 |
+
rows = [x for x in ex.map(judge_one, caught) if x]
|
| 119 |
+
errs = [r for r in rows if r.get("error")]
|
| 120 |
+
good = [r for r in rows if not r.get("error")]
|
| 121 |
+
(OUT / "caught_reasons_v5.jsonl").write_text(
|
| 122 |
+
"\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8")
|
| 123 |
+
|
| 124 |
+
recaught = [r for r in good if r["sample_caught"]]
|
| 125 |
+
# distribution over rows that also caught on this sample (true catch-reasons)
|
| 126 |
+
prim = collections.Counter(r["primary"] for r in recaught)
|
| 127 |
+
multi = collections.Counter()
|
| 128 |
+
for r in recaught:
|
| 129 |
+
for b in r["buckets"]:
|
| 130 |
+
multi[b] += 1
|
| 131 |
+
n = len(recaught)
|
| 132 |
+
|
| 133 |
+
NAMES = {
|
| 134 |
+
"A_capability_scenario_realism": "capability / scenario realism (tool or task seems unreal)",
|
| 135 |
+
"B_multitask_bundling": "multi-task bundling (many / unrelated requests)",
|
| 136 |
+
"D_auth_verification": "auth / verification anomalies",
|
| 137 |
+
"C_frictionless_smooth": "too smooth / frictionless / compliant",
|
| 138 |
+
"E_agent_phrasing_templated": "agent phrasing (formal / generic / templated)",
|
| 139 |
+
"F_customer_phrasing": "customer phrasing (too clean / forced-casual / 'too natural')",
|
| 140 |
+
"G_structure_brevity_history": "structure / brevity / history-flow",
|
| 141 |
+
"H_other": "other / unclassified",
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
print("\n" + "=" * 80)
|
| 145 |
+
print(f"CAUGHT-REASON BREAKDOWN (v5, original C3 prompt)")
|
| 146 |
+
print(f" caught rows re-judged: {len(good)} errors: {len(errs)}")
|
| 147 |
+
print(f" of those, this sample also caught: {n} (reasoning below is over these)")
|
| 148 |
+
print("=" * 80)
|
| 149 |
+
print("\nPRIMARY tell (each row assigned one bucket, priority-ordered):")
|
| 150 |
+
for b, c in prim.most_common():
|
| 151 |
+
print(f" {c:4d} {c/n:5.1%} {NAMES.get(b, b)}")
|
| 152 |
+
print("\nANY-MENTION (multi-label; a row can hit several tells):")
|
| 153 |
+
for b, c in multi.most_common():
|
| 154 |
+
print(f" {c:4d} {c/n:5.1%} {NAMES.get(b, b)}")
|
| 155 |
+
|
| 156 |
+
# split primary distribution by role (T1 vs tail)
|
| 157 |
+
print("\nPRIMARY tell by row type:")
|
| 158 |
+
for grp, pred in (("turn1 (trie slot)", lambda r: r["role"] == "turn1"),
|
| 159 |
+
("tail", lambda r: (r["role"] or "").startswith("turn") and r["role"] != "turn1"),
|
| 160 |
+
("passthrough", lambda r: not r["role"])):
|
| 161 |
+
sub = [r for r in recaught if pred(r)]
|
| 162 |
+
if not sub:
|
| 163 |
+
continue
|
| 164 |
+
pc = collections.Counter(r["primary"] for r in sub)
|
| 165 |
+
top = ", ".join(f"{NAMES.get(b, b).split(' (')[0]} {c}" for b, c in pc.most_common(4))
|
| 166 |
+
print(f" {grp:22s} n={len(sub):4d} {top}")
|
| 167 |
+
|
| 168 |
+
print("\nExample reasonings per primary bucket (first 2):")
|
| 169 |
+
seen = collections.Counter()
|
| 170 |
+
for b in PRIORITY + ["H_other"]:
|
| 171 |
+
exs = [r for r in recaught if r["primary"] == b][:2]
|
| 172 |
+
if not exs:
|
| 173 |
+
continue
|
| 174 |
+
print(f"\n[{NAMES.get(b, b)}]")
|
| 175 |
+
for r in exs:
|
| 176 |
+
print(f" ({r['item_id']}) {r['reasoning'][:280]}")
|
| 177 |
+
print(f"\nsaved -> {(OUT/'caught_reasons_v5.jsonl').relative_to(ROOT)}")
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
main()
|
tempscripts/story_remediation/unbundle/diagnose_tail.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Diagnose WHY v3 tail turns still get caught: pull the judge's own reasoning.
|
| 2 |
+
|
| 3 |
+
Samples still-caught tail rows (role turn2+), re-runs C3 once each with reasoning
|
| 4 |
+
captured, prints the rationale, and tallies recurring tell-keywords so we can see
|
| 5 |
+
the dominant factors rather than guessing.
|
| 6 |
+
Run: python -u temp/story_remediation/unbundle/diagnose_tail.py [N]
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
import json, logging, sys, re, collections, random
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import yaml
|
| 12 |
+
|
| 13 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 14 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 15 |
+
|
| 16 |
+
HERE = Path(__file__).resolve().parent
|
| 17 |
+
ROOT = HERE.parents[2]
|
| 18 |
+
sys.path.insert(0, str(ROOT))
|
| 19 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 20 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 21 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 22 |
+
|
| 23 |
+
OUT = HERE / "out"
|
| 24 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 25 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 26 |
+
|
| 27 |
+
verds = [json.loads(l) for l in open(OUT / "C3_all_v3.jsonl", encoding="utf-8") if l.strip()]
|
| 28 |
+
fakes = {e["example_id"]: e for e in
|
| 29 |
+
(json.loads(l) for l in open(OUT / "trajectories_all_v3.jsonl", encoding="utf-8") if l.strip())}
|
| 30 |
+
base = {}
|
| 31 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 32 |
+
if line.strip():
|
| 33 |
+
d = json.loads(line); base[d["item_id"]] = d
|
| 34 |
+
|
| 35 |
+
reals = P.real_trajectories()
|
| 36 |
+
pairer = P.make_pairer(reals)
|
| 37 |
+
judge = make_judge(cfg["model"])
|
| 38 |
+
|
| 39 |
+
caught_tails = [v for v in verds
|
| 40 |
+
if (v.get("role") or "").startswith("turn") and v.get("role") != "turn1"
|
| 41 |
+
and v.get("caught")]
|
| 42 |
+
random.seed(7)
|
| 43 |
+
random.shuffle(caught_tails)
|
| 44 |
+
N = int(sys.argv[1]) if len(sys.argv) > 1 else 16
|
| 45 |
+
sample = caught_tails[:N]
|
| 46 |
+
|
| 47 |
+
KW = ["abrupt", "context", "history", "prior", "previous", "single", "one tool",
|
| 48 |
+
"efficient", "polished", "concise", "terse", "no clarif", "clarif", "confirm",
|
| 49 |
+
"generic", "templat", "formal", "assistant", "acknowled", "past tense",
|
| 50 |
+
"greeting", "identity", "auth", "repetit", "unnatural", "too clean", "smooth",
|
| 51 |
+
"brief", "short", "curt", "follow-up", "follow up", "disconnect", "abrupt",
|
| 52 |
+
"sequence", "unrelated", "jump", "no friction", "compliant"]
|
| 53 |
+
tally = collections.Counter()
|
| 54 |
+
|
| 55 |
+
print(f"caught tails total={len(caught_tails)} sampling {len(sample)}\n" + "=" * 78)
|
| 56 |
+
for v in sample:
|
| 57 |
+
eid = v["item_id"]; fake = fakes.get(eid)
|
| 58 |
+
if not fake:
|
| 59 |
+
continue
|
| 60 |
+
real = pairer(fake)
|
| 61 |
+
swap = (base.get(eid) or base.get(v.get("orig_eid")) or {}).get("answer_key") == "B"
|
| 62 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 63 |
+
try:
|
| 64 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 65 |
+
except Exception as e: # noqa: BLE001
|
| 66 |
+
print(f"[{eid}] ERROR {e}"); continue
|
| 67 |
+
reason = (r.get("reasoning") or "").strip()
|
| 68 |
+
low = reason.lower()
|
| 69 |
+
for k in KW:
|
| 70 |
+
if k in low:
|
| 71 |
+
tally[k] += 1
|
| 72 |
+
nturns = len(fake.get("history", [])) + 1
|
| 73 |
+
print(f"\n[{eid}] role={v['role']} guess={r.get('guess')} turns_in_conv={nturns}")
|
| 74 |
+
print(f" {reason}")
|
| 75 |
+
|
| 76 |
+
print("\n" + "=" * 78 + "\nTELL KEYWORD TALLY (across sampled reasonings):")
|
| 77 |
+
for k, c in tally.most_common():
|
| 78 |
+
if c:
|
| 79 |
+
print(f" {c:3d} {k}")
|
tempscripts/story_remediation/unbundle/diagnose_tail_v4.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Diagnose WHY v3 tail turns still get caught: pull the judge's own reasoning.
|
| 2 |
+
|
| 3 |
+
Samples still-caught tail rows (role turn2+), re-runs C3 once each with reasoning
|
| 4 |
+
captured, prints the rationale, and tallies recurring tell-keywords so we can see
|
| 5 |
+
the dominant factors rather than guessing.
|
| 6 |
+
Run: python -u temp/story_remediation/unbundle/diagnose_tail.py [N]
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
import json, logging, sys, re, collections, random
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import yaml
|
| 12 |
+
|
| 13 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 14 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 15 |
+
|
| 16 |
+
HERE = Path(__file__).resolve().parent
|
| 17 |
+
ROOT = HERE.parents[2]
|
| 18 |
+
sys.path.insert(0, str(ROOT))
|
| 19 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 20 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 21 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 22 |
+
|
| 23 |
+
OUT = HERE / "out"
|
| 24 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 25 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 26 |
+
|
| 27 |
+
verds = [json.loads(l) for l in open(OUT / "C3_all_v4.jsonl", encoding="utf-8") if l.strip()]
|
| 28 |
+
fakes = {e["example_id"]: e for e in
|
| 29 |
+
(json.loads(l) for l in open(OUT / "trajectories_all_v4.jsonl", encoding="utf-8") if l.strip())}
|
| 30 |
+
base = {}
|
| 31 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 32 |
+
if line.strip():
|
| 33 |
+
d = json.loads(line); base[d["item_id"]] = d
|
| 34 |
+
|
| 35 |
+
reals = P.real_trajectories()
|
| 36 |
+
pairer = P.make_pairer(reals)
|
| 37 |
+
judge = make_judge(cfg["model"])
|
| 38 |
+
|
| 39 |
+
caught_tails = [v for v in verds
|
| 40 |
+
if (v.get("role") or "").startswith("turn") and v.get("role") != "turn1"
|
| 41 |
+
and v.get("caught")]
|
| 42 |
+
random.seed(7)
|
| 43 |
+
random.shuffle(caught_tails)
|
| 44 |
+
N = int(sys.argv[1]) if len(sys.argv) > 1 else 16
|
| 45 |
+
sample = caught_tails[:N]
|
| 46 |
+
|
| 47 |
+
KW = ["abrupt", "context", "history", "prior", "previous", "single", "one tool",
|
| 48 |
+
"efficient", "polished", "concise", "terse", "no clarif", "clarif", "confirm",
|
| 49 |
+
"generic", "templat", "formal", "assistant", "acknowled", "past tense",
|
| 50 |
+
"greeting", "identity", "auth", "repetit", "unnatural", "too clean", "smooth",
|
| 51 |
+
"brief", "short", "curt", "follow-up", "follow up", "disconnect", "abrupt",
|
| 52 |
+
"sequence", "unrelated", "jump", "no friction", "compliant"]
|
| 53 |
+
tally = collections.Counter()
|
| 54 |
+
|
| 55 |
+
print(f"caught tails total={len(caught_tails)} sampling {len(sample)}\n" + "=" * 78)
|
| 56 |
+
for v in sample:
|
| 57 |
+
eid = v["item_id"]; fake = fakes.get(eid)
|
| 58 |
+
if not fake:
|
| 59 |
+
continue
|
| 60 |
+
real = pairer(fake)
|
| 61 |
+
swap = (base.get(eid) or base.get(v.get("orig_eid")) or {}).get("answer_key") == "B"
|
| 62 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 63 |
+
try:
|
| 64 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 65 |
+
except Exception as e: # noqa: BLE001
|
| 66 |
+
print(f"[{eid}] ERROR {e}"); continue
|
| 67 |
+
reason = (r.get("reasoning") or "").strip()
|
| 68 |
+
low = reason.lower()
|
| 69 |
+
for k in KW:
|
| 70 |
+
if k in low:
|
| 71 |
+
tally[k] += 1
|
| 72 |
+
nturns = len(fake.get("history", [])) + 1
|
| 73 |
+
print(f"\n[{eid}] role={v['role']} guess={r.get('guess')} turns_in_conv={nturns}")
|
| 74 |
+
print(f" {reason}")
|
| 75 |
+
|
| 76 |
+
print("\n" + "=" * 78 + "\nTELL KEYWORD TALLY (across sampled reasonings):")
|
| 77 |
+
for k, c in tally.most_common():
|
| 78 |
+
if c:
|
| 79 |
+
print(f" {c:3d} {k}")
|
| 80 |
+
|
tempscripts/story_remediation/unbundle/dump_c3_view.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dump the exact CONV_A / CONV_B text the C3 judge sees for a given tail eid."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import json, sys, os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import yaml
|
| 6 |
+
HERE = Path(__file__).resolve().parent
|
| 7 |
+
ROOT = HERE.parents[2]
|
| 8 |
+
sys.path.insert(0, str(ROOT))
|
| 9 |
+
from datasetreview import pipelines as P
|
| 10 |
+
from datasetreview import judge_prompts as J
|
| 11 |
+
|
| 12 |
+
eid = sys.argv[1] if len(sys.argv) > 1 else "confuser-get_order_invoice-782-t2"
|
| 13 |
+
fakes = {e["example_id"]: e for e in
|
| 14 |
+
(json.loads(l) for l in open(HERE / "out" / (os.environ.get("V4FILE") or "trajectories_all_v3.jsonl"), encoding="utf-8") if l.strip())}
|
| 15 |
+
base = {}
|
| 16 |
+
for line in open(ROOT / "datasetreview" / "results" / "new" / "C3.jsonl", encoding="utf-8"):
|
| 17 |
+
if line.strip():
|
| 18 |
+
d = json.loads(line); base[d["item_id"]] = d
|
| 19 |
+
fake = fakes[eid]
|
| 20 |
+
reals = P.real_trajectories()
|
| 21 |
+
pairer = P.make_pairer(reals)
|
| 22 |
+
real = pairer(fake)
|
| 23 |
+
orig = fake.get("metadata", {}).get("orig_eid")
|
| 24 |
+
swap = (base.get(eid) or base.get(orig) or {}).get("answer_key") == "B"
|
| 25 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 26 |
+
print(f"eid={eid} swap={swap} answer_key={msgs['answer_key']}")
|
| 27 |
+
print(f"history turns in fake: {len(fake.get('history', []))}")
|
| 28 |
+
print("#" * 80)
|
| 29 |
+
# extract just the two convs from the user message
|
| 30 |
+
u = msgs["user"]
|
| 31 |
+
print(u[u.index("---Conversation A---"):])
|
tempscripts/story_remediation/unbundle/fix_error_records.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Re-judge the handful of records that hit a transient JSON-parse error on one of
|
| 2 |
+
their 3 samples, and rewrite ONLY those lines in place (canonical record builders,
|
| 3 |
+
so schema is unchanged). Makes the final C1/C3 JSONL pristine (3/3 samples, error=null).
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
import json, sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import yaml
|
| 9 |
+
|
| 10 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 11 |
+
sys.path.insert(0, str(ROOT))
|
| 12 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 13 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 14 |
+
from scripts import run_dataeval as R # noqa: E402
|
| 15 |
+
|
| 16 |
+
OUT = ROOT / "temp" / "story_remediation" / "unbundle" / "final_c1c3"
|
| 17 |
+
V6 = ROOT / "temp" / "story_remediation" / "unbundle" / "out" / "trajectories_all_v6.jsonl"
|
| 18 |
+
_ROWS = {json.loads(l)["example_id"]: json.loads(l)
|
| 19 |
+
for l in open(V6, encoding="utf-8") if l.strip()}
|
| 20 |
+
P.confuser_trajectories = lambda level: list(_ROWS.values())
|
| 21 |
+
|
| 22 |
+
FIX = {"C1": ["confuser-upgrade_shipping_speed-796-t3", "confuser-reorder_previous_order-311-t3",
|
| 23 |
+
"confuser-get_gift_card_balance-433"],
|
| 24 |
+
"C3": ["confuser-get_order_invoice-486-t4"]}
|
| 25 |
+
SAMPLES = 3
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def rejudge(exp, ctx, judge, item_id):
|
| 29 |
+
pipe = P.PIPELINES[exp](ctx)
|
| 30 |
+
w = P.Work(100, item_id, _ROWS[item_id])
|
| 31 |
+
key = f"n100:{item_id}"
|
| 32 |
+
if exp == "C3":
|
| 33 |
+
per = []
|
| 34 |
+
for ms in pipe.build_all(w):
|
| 35 |
+
res = [judge.judge(ms["msgs"]) for _ in range(SAMPLES)]
|
| 36 |
+
per.append((ms["orientation"], ms["answer_key"], res))
|
| 37 |
+
return key, R._record_c3(exp, key, w, per, [])
|
| 38 |
+
msgs = pipe.build(w)
|
| 39 |
+
res = [judge.judge(msgs) for _ in range(SAMPLES)]
|
| 40 |
+
return key, R._record(exp, key, w, res, [], "verdict")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def main():
|
| 44 |
+
cfg = yaml.safe_load((ROOT / "datasetreview" / "config.yaml").read_text(encoding="utf-8"))
|
| 45 |
+
judge = make_judge(cfg["model"])
|
| 46 |
+
ctx = P.build_context(list(FIX))
|
| 47 |
+
for exp, ids in FIX.items():
|
| 48 |
+
path = OUT / f"{exp}.jsonl"
|
| 49 |
+
recs = [json.loads(l) for l in open(path, encoding="utf-8") if l.strip()]
|
| 50 |
+
by_item = {r["item_id"]: i for i, r in enumerate(recs)}
|
| 51 |
+
for item_id in ids:
|
| 52 |
+
_, newrec = rejudge(exp, ctx, judge, item_id)
|
| 53 |
+
recs[by_item[item_id]] = newrec
|
| 54 |
+
print(f"{exp} {item_id}: error={newrec.get('error')} "
|
| 55 |
+
f"verdict={newrec.get('verdict')} "
|
| 56 |
+
f"n_samples={newrec.get('n_samples') or newrec.get('samples_per_orientation')}")
|
| 57 |
+
with open(path, "w", encoding="utf-8") as fh:
|
| 58 |
+
for r in recs:
|
| 59 |
+
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 60 |
+
print(f" rewrote {path} ({len(recs)} lines)")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
main()
|
tempscripts/story_remediation/unbundle/replay_v5.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Free-running state runthrough on the V5 unbundled trajectories.
|
| 2 |
+
|
| 3 |
+
v5 changed ONLY dialogue (b1 method-aware verify-ask, b3 token scrub). `calls`
|
| 4 |
+
are byte-identical to v3 / the source n100. This harness proves that at the level
|
| 5 |
+
that matters for free-running execution:
|
| 6 |
+
|
| 7 |
+
1. RECONSTRUCTION INVARIANT: for every original episode, concatenating its v5
|
| 8 |
+
rows' calls in turn order (turn1, t2, t3, ...) reproduces the source n100
|
| 9 |
+
call list byte-for-byte. This is the real "no floating / dropped variables"
|
| 10 |
+
check for the split dataset -- if a rewrite had dropped or mangled an id,
|
| 11 |
+
the reconstruction would diverge from source.
|
| 12 |
+
|
| 13 |
+
2. FREE-RUNNING REPLAY: seed ONE EpisodeState per reconstructed episode
|
| 14 |
+
(from_trajectory reads only `calls` + catalog, never dialogue), then replay
|
| 15 |
+
the full ordered call sequence against that single evolving state and check
|
| 16 |
+
each output reproduces the recorded one. Because we replay the *whole*
|
| 17 |
+
episode (not per-row), money ops see the accumulated balances they need.
|
| 18 |
+
|
| 19 |
+
Any exception / mismatch / skip_nodata here would be a genuine execution gap; if
|
| 20 |
+
it stems from a db seed missing (gift card, order balance, cart subtotal), add it
|
| 21 |
+
to systemUpgrade/executor/catalog.json and re-run.
|
| 22 |
+
|
| 23 |
+
Run from repo root: python -u temp/story_remediation/unbundle/replay_v5.py
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
import json, sys, re
|
| 27 |
+
from collections import Counter, defaultdict
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 31 |
+
EXEC = ROOT / "systemUpgrade" / "executor"
|
| 32 |
+
sys.path.insert(0, str(EXEC))
|
| 33 |
+
from fake_state import EpisodeState # noqa: E402
|
| 34 |
+
from fake_tools import TOOLS # noqa: E402
|
| 35 |
+
|
| 36 |
+
catalog = json.load(open(EXEC / "catalog.json", encoding="utf-8"))
|
| 37 |
+
V5 = ROOT / "temp" / "story_remediation" / "unbundle" / "out" / "trajectories_all_v5.jsonl"
|
| 38 |
+
SRC = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 39 |
+
|
| 40 |
+
v5 = [json.loads(l) for l in open(V5, encoding="utf-8") if l.strip()]
|
| 41 |
+
src = {json.loads(l)["example_id"]: json.loads(l)
|
| 42 |
+
for l in open(SRC, encoding="utf-8") if l.strip()}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def turn_idx(r):
|
| 46 |
+
role = (r.get("metadata") or {}).get("unbundle_role") or ""
|
| 47 |
+
if role == "turn1":
|
| 48 |
+
return 1
|
| 49 |
+
m = re.match(r"turn(\d+)", role)
|
| 50 |
+
return int(m.group(1)) if m else 1
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# group v5 rows into original episodes
|
| 54 |
+
groups = defaultdict(list)
|
| 55 |
+
for r in v5:
|
| 56 |
+
oe = (r.get("metadata") or {}).get("orig_eid") or r["example_id"]
|
| 57 |
+
groups[oe].append(r)
|
| 58 |
+
|
| 59 |
+
# 1) reconstruction invariant: concat(calls in turn order) == source n100 calls
|
| 60 |
+
recon_diff = []
|
| 61 |
+
episodes = {}
|
| 62 |
+
for oe, rows in groups.items():
|
| 63 |
+
rows_sorted = sorted(rows, key=turn_idx)
|
| 64 |
+
full = []
|
| 65 |
+
for r in rows_sorted:
|
| 66 |
+
full += r["calls"]
|
| 67 |
+
episodes[oe] = full
|
| 68 |
+
if oe in src:
|
| 69 |
+
if json.dumps(full, sort_keys=True) != json.dumps(src[oe]["calls"], sort_keys=True):
|
| 70 |
+
recon_diff.append(oe)
|
| 71 |
+
|
| 72 |
+
FULLMATCH = {"get_product_details", "get_size_guide", "get_product_reviews", "get_item_details",
|
| 73 |
+
"get_warranty_details", "get_extended_warranty_options", "get_shipping_options",
|
| 74 |
+
"get_active_promotions", "list_all_product_types", "get_user_reviews", "get_order_invoice"}
|
| 75 |
+
FIND = {"find_user_id_by_email", "find_user_id_by_phone", "find_user_id_by_username", "find_user_id_by_name_zip"}
|
| 76 |
+
CHECK = {
|
| 77 |
+
"apply_gift_card": ["amount_applied", "remaining_balance_due"], "apply_discount_code": ["discount", "status"],
|
| 78 |
+
"checkout_cart": ["total"], "cancel_order_item": ["status", "item_id"],
|
| 79 |
+
"return_pending_order_items": ["status", "item_ids"], "return_delivered_order_items": ["status", "item_ids"],
|
| 80 |
+
"exchange_delivered_order_items": ["status"], "modify_pending_order_items": [],
|
| 81 |
+
"remove_item_from_cart": ["subtotal"], "add_item_to_cart": ["user_id"], "get_order_details": ["status"],
|
| 82 |
+
"get_user_details": ["user_id", "email"], "get_cart_contents": ["subtotal"], "get_gift_card_balance": ["balance"],
|
| 83 |
+
"get_loyalty_points_balance": ["points"], "get_store_credit_balance": ["balance"], "get_wishlist": ["items"],
|
| 84 |
+
"cancel_delivered_order": ["status", "refund"], "cancel_pending_order": ["status", "refund"],
|
| 85 |
+
"modify_pending_order_address": ["status"], "add_gift_message": ["gift_message"],
|
| 86 |
+
"schedule_delivery": ["scheduled_delivery", "status"], "set_delivery_instructions": ["delivery_instructions", "status"],
|
| 87 |
+
"schedule_installation": ["appointment_id"], "book_repair_appointment": ["appointment_id"],
|
| 88 |
+
"request_return_pickup": ["confirmation"], "get_return_label": ["label_url"],
|
| 89 |
+
"request_gift_receipt": ["gift_receipt_url", "prices_shown"],
|
| 90 |
+
"file_shipping_insurance_claim": ["claim_id", "status", "estimated_review_days"],
|
| 91 |
+
"upgrade_shipping_speed": ["shipping_speed", "status"], "split_order_shipment": ["status"],
|
| 92 |
+
"request_price_adjustment": ["status"], "request_price_match": ["item_id"],
|
| 93 |
+
"reorder_previous_order": ["duplicated_from", "status", "total"], "register_product_warranty": [],
|
| 94 |
+
"submit_product_review": [], "subscribe_to_restock_alert": [], "redeem_loyalty_points": ["points_redeemed", "credit"],
|
| 95 |
+
"purchase_gift_card": ["amount"], "add_to_wishlist": ["user_id"], "modify_user_email": ["status", "email"],
|
| 96 |
+
"modify_user_name": ["status"], "modify_user_phone": ["status", "phone"], "update_user_password": ["status"],
|
| 97 |
+
"add_user_address": ["status"], "modify_user_address": ["status"], "delete_user_address": ["status", "deleted_zip"],
|
| 98 |
+
"verify_user_identity": ["verified"],
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def parse(o):
|
| 103 |
+
try:
|
| 104 |
+
return json.loads(o) if isinstance(o, str) else o
|
| 105 |
+
except json.JSONDecodeError:
|
| 106 |
+
return None
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
stats = defaultdict(lambda: {"n": 0, "match": 0, "skip_nodata": 0, "mism": [], "exc": []})
|
| 110 |
+
covered, uncovered = Counter(), Counter()
|
| 111 |
+
|
| 112 |
+
for oe, full in episodes.items():
|
| 113 |
+
s = EpisodeState.from_trajectory({"calls": full}, catalog)
|
| 114 |
+
for c in full:
|
| 115 |
+
n = c["name"]
|
| 116 |
+
if n not in TOOLS:
|
| 117 |
+
uncovered[n] += 1
|
| 118 |
+
continue
|
| 119 |
+
covered[n] += 1
|
| 120 |
+
rec = parse(c.get("output"))
|
| 121 |
+
st = stats[n]
|
| 122 |
+
st["n"] += 1
|
| 123 |
+
try:
|
| 124 |
+
got = TOOLS[n](s, c.get("arguments", {}))
|
| 125 |
+
except Exception as e: # noqa
|
| 126 |
+
st["exc"].append((oe, f"{type(e).__name__}: {e}"))
|
| 127 |
+
continue
|
| 128 |
+
if n in FIND:
|
| 129 |
+
if got == (c.get("output") or "").strip().strip('"'):
|
| 130 |
+
st["match"] += 1
|
| 131 |
+
else:
|
| 132 |
+
st["mism"].append((oe, {"uid": (got, c.get("output"))}))
|
| 133 |
+
continue
|
| 134 |
+
if not isinstance(rec, dict):
|
| 135 |
+
st["match"] += 1
|
| 136 |
+
continue
|
| 137 |
+
if n in FULLMATCH:
|
| 138 |
+
if got == rec:
|
| 139 |
+
st["match"] += 1
|
| 140 |
+
else:
|
| 141 |
+
st["mism"].append((oe, "dict-diff"))
|
| 142 |
+
continue
|
| 143 |
+
keys = CHECK.get(n, [])
|
| 144 |
+
if any(got.get(k) is None and rec.get(k) is not None for k in keys):
|
| 145 |
+
st["skip_nodata"] += 1
|
| 146 |
+
continue
|
| 147 |
+
|
| 148 |
+
def _eq(k):
|
| 149 |
+
g, rv = got.get(k), rec.get(k)
|
| 150 |
+
if k == "status" and isinstance(g, str) and isinstance(rv, str):
|
| 151 |
+
return g.replace(" ", "_") == rv.replace(" ", "_")
|
| 152 |
+
return g == rv
|
| 153 |
+
if all(_eq(k) for k in keys):
|
| 154 |
+
st["match"] += 1
|
| 155 |
+
else:
|
| 156 |
+
st["mism"].append((oe, {k: (got.get(k), rec.get(k)) for k in keys if not _eq(k)}))
|
| 157 |
+
|
| 158 |
+
tot_chk = sum(st["n"] - st["skip_nodata"] for st in stats.values())
|
| 159 |
+
tot_match = sum(st["match"] for st in stats.values())
|
| 160 |
+
tot_exc = sum(len(st["exc"]) for st in stats.values())
|
| 161 |
+
tot_mism = sum(len(st["mism"]) for st in stats.values())
|
| 162 |
+
tot_skip = sum(st["skip_nodata"] for st in stats.values())
|
| 163 |
+
|
| 164 |
+
print("=== RECONSTRUCTION INVARIANT (v5 split rows -> source n100 calls) ===")
|
| 165 |
+
print(f" episodes: {len(episodes)} reconstructions differing from source: {len(recon_diff)} {recon_diff[:5]}")
|
| 166 |
+
print("\n=== FREE-RUNNING REPLAY (whole-episode, v5) ===")
|
| 167 |
+
print(f" reproduced : {tot_match}/{tot_chk} = {tot_match/max(tot_chk,1):.1%}")
|
| 168 |
+
print(f" exceptions : {tot_exc}")
|
| 169 |
+
print(f" mismatches : {tot_mism}")
|
| 170 |
+
print(f" skipped-no-seed : {tot_skip}")
|
| 171 |
+
print(f" tools exercised : {len(stats)} uncovered(echo/fictional) calls: {sum(uncovered.values())}")
|
| 172 |
+
if tot_exc:
|
| 173 |
+
print("\n -- EXCEPTIONS (first 5/tool) --")
|
| 174 |
+
for n, st in sorted(stats.items()):
|
| 175 |
+
for oe, msg in st["exc"][:5]:
|
| 176 |
+
print(f" [{n}] {oe}: {msg}")
|
| 177 |
+
if tot_mism:
|
| 178 |
+
print("\n -- MISMATCHES (first 5/tool) --")
|
| 179 |
+
for n, st in sorted(stats.items()):
|
| 180 |
+
for oe, d in st["mism"][:5]:
|
| 181 |
+
print(f" [{n}] {oe}: {d}")
|
| 182 |
+
if tot_skip:
|
| 183 |
+
print("\n -- SKIP-NO-SEED counts by tool --")
|
| 184 |
+
for n, st in sorted(stats.items()):
|
| 185 |
+
if st["skip_nodata"]:
|
| 186 |
+
print(f" [{n}] {st['skip_nodata']}")
|
tempscripts/story_remediation/unbundle/run_auth_c1c3.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run C1 (ground-truth validity) and C3 (v2 prompt) on the AUTH-PROBLEM rows,
|
| 2 |
+
judging both v5 (before) and v6 (after the deterministic auth fixes) so the only
|
| 3 |
+
variable is the authored NL (calls are byte-identical v5==v6).
|
| 4 |
+
|
| 5 |
+
Auth-problem set = union of
|
| 6 |
+
(a) auth-primary CAUGHT rows -> caught_reasons_v5.jsonl primary==D_auth_verification
|
| 7 |
+
(b) rows the deterministic lint FIXED in v6 -> NL differs v5 vs v6
|
| 8 |
+
|
| 9 |
+
Reports, for this set:
|
| 10 |
+
* C3 v2 caught rate v5 vs v6 (drop = the auth fixes fooled the judge)
|
| 11 |
+
* C1 fail/borderline v5 vs v6 (should not regress; calls unchanged)
|
| 12 |
+
|
| 13 |
+
Run: python -u temp/story_remediation/unbundle/run_auth_c1c3.py
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
import json, logging, sys
|
| 17 |
+
from collections import Counter
|
| 18 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
import yaml
|
| 21 |
+
|
| 22 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 23 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 24 |
+
|
| 25 |
+
HERE = Path(__file__).resolve().parent
|
| 26 |
+
ROOT = HERE.parents[2]
|
| 27 |
+
sys.path.insert(0, str(ROOT))
|
| 28 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 29 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 30 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 31 |
+
|
| 32 |
+
OUT = HERE / "out"
|
| 33 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 34 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 35 |
+
SAMPLES = 3
|
| 36 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 37 |
+
|
| 38 |
+
v5 = {e["example_id"]: e for e in
|
| 39 |
+
(json.loads(l) for l in open(OUT / "trajectories_all_v5.jsonl", encoding="utf-8") if l.strip())}
|
| 40 |
+
v6 = {e["example_id"]: e for e in
|
| 41 |
+
(json.loads(l) for l in open(OUT / "trajectories_all_v6.jsonl", encoding="utf-8") if l.strip())}
|
| 42 |
+
|
| 43 |
+
# (a) auth-primary caught rows
|
| 44 |
+
auth_caught = {json.loads(l)["item_id"]
|
| 45 |
+
for l in open(OUT / "caught_reasons_v5.jsonl", encoding="utf-8") if l.strip()
|
| 46 |
+
and json.loads(l).get("primary") == "D_auth_verification"}
|
| 47 |
+
# (b) lint-fixed rows (NL differs)
|
| 48 |
+
fixed = {eid for eid in v5
|
| 49 |
+
if json.dumps(v5[eid].get("history")) != json.dumps(v6[eid].get("history"))
|
| 50 |
+
or v5[eid].get("query") != v6[eid].get("query")}
|
| 51 |
+
|
| 52 |
+
AUTH_IDS = sorted((auth_caught | fixed) & set(v5) & set(v6))
|
| 53 |
+
print(f"auth-primary caught: {len(auth_caught)} | lint-fixed: {len(fixed)} "
|
| 54 |
+
f"| union present in both: {len(AUTH_IDS)}")
|
| 55 |
+
|
| 56 |
+
base = {}
|
| 57 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 58 |
+
if line.strip():
|
| 59 |
+
d = json.loads(line); base[d["item_id"]] = d
|
| 60 |
+
|
| 61 |
+
reals = P.real_trajectories()
|
| 62 |
+
pairer = P.make_pairer(reals)
|
| 63 |
+
judge = make_judge(cfg["model"])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def c3_pair(fake, real, swap):
|
| 67 |
+
system, user = J.load_prompt("C3v2")
|
| 68 |
+
fr = J.render_trajectory(fake, blind_tools=True, include_metadata=False, conversation_only=True)
|
| 69 |
+
rr = J.render_trajectory(real, blind_tools=True, include_metadata=False, conversation_only=True)
|
| 70 |
+
a, b, key = (rr, fr, "B") if swap else (fr, rr, "A")
|
| 71 |
+
user = user.replace("{{CONV_A}}", a).replace("{{CONV_B}}", b)
|
| 72 |
+
return {"system": system, "user": user, "answer_key": key}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def maj(msgs, field):
|
| 76 |
+
vals = []
|
| 77 |
+
for _ in range(SAMPLES):
|
| 78 |
+
try:
|
| 79 |
+
vals.append(judge.judge({"system": msgs["system"], "user": msgs["user"]}).get(field))
|
| 80 |
+
except Exception: # noqa: BLE001
|
| 81 |
+
pass
|
| 82 |
+
if not vals:
|
| 83 |
+
return None, 0.0
|
| 84 |
+
m = Counter(vals).most_common(1)[0][0]
|
| 85 |
+
return m, vals.count(m) / len(vals)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def one(eid):
|
| 89 |
+
real = pairer(v5[eid])
|
| 90 |
+
swap = (base.get(eid) or base.get(v5[eid].get("metadata", {}).get("orig_eid")) or {}
|
| 91 |
+
).get("answer_key") == "B"
|
| 92 |
+
out = {"item_id": eid, "role": v5[eid].get("metadata", {}).get("unbundle_role")}
|
| 93 |
+
for tag, ds in (("v5", v5), ("v6", v6)):
|
| 94 |
+
fake = ds[eid]
|
| 95 |
+
c3 = c3_pair(fake, real, swap); key = c3["answer_key"]
|
| 96 |
+
g, ga = maj(c3, "guess")
|
| 97 |
+
c1 = J.build_c1(fake)
|
| 98 |
+
vd, vda = maj(c1, "verdict")
|
| 99 |
+
out[f"{tag}_c3_guess"] = g
|
| 100 |
+
out[f"{tag}_c3_caught"] = (g == key)
|
| 101 |
+
out[f"{tag}_c1_verdict"] = vd
|
| 102 |
+
return out
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def main():
|
| 106 |
+
print(f"judging {len(AUTH_IDS)} auth rows x2 versions x(C1+C3v2) "
|
| 107 |
+
f"(samples={SAMPLES}, workers={WORKERS})")
|
| 108 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 109 |
+
rows = list(ex.map(one, AUTH_IDS))
|
| 110 |
+
(OUT / "auth_c1c3.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding="utf-8")
|
| 111 |
+
|
| 112 |
+
n = len(rows)
|
| 113 |
+
v5c = sum(1 for r in rows if r["v5_c3_caught"])
|
| 114 |
+
v6c = sum(1 for r in rows if r["v6_c3_caught"])
|
| 115 |
+
flipped = [r for r in rows if r["v5_c3_caught"] and not r["v6_c3_caught"]]
|
| 116 |
+
regress = [r for r in rows if not r["v5_c3_caught"] and r["v6_c3_caught"]]
|
| 117 |
+
|
| 118 |
+
def c1fail(tag):
|
| 119 |
+
return sum(1 for r in rows if r[f"{tag}_c1_verdict"] in ("fail", "borderline"))
|
| 120 |
+
|
| 121 |
+
print("\n" + "=" * 74)
|
| 122 |
+
print(f"AUTH-PROBLEM ROWS: {n}")
|
| 123 |
+
print(f" C3 (v2 prompt) caught v5: {v5c}/{n} = {v5c/n:.0%} "
|
| 124 |
+
f"v6: {v6c}/{n} = {v6c/n:.0%}")
|
| 125 |
+
print(f" -> flipped caught->fooled by the fixes: {len(flipped)}/{max(v5c,1)}"
|
| 126 |
+
f" = {len(flipped)/max(v5c,1):.0%}")
|
| 127 |
+
print(f" -> regressions (fooled->caught): {len(regress)}")
|
| 128 |
+
print(f" C1 fail/borderline v5: {c1fail('v5')}/{n} v6: {c1fail('v6')}/{n} "
|
| 129 |
+
f"(calls unchanged; expect ~equal)")
|
| 130 |
+
print("=" * 74)
|
| 131 |
+
print("\nflipped (auth fix fooled the C3 v2 judge):")
|
| 132 |
+
for r in flipped[:20]:
|
| 133 |
+
print(f" {r['item_id']:44s} role={r['role']} v5={r['v5_c3_guess']}->v6={r['v6_c3_guess']}")
|
| 134 |
+
if regress:
|
| 135 |
+
print("\nREGRESSIONS to inspect:")
|
| 136 |
+
for r in regress:
|
| 137 |
+
print(f" {r['item_id']:44s} role={r['role']}")
|
| 138 |
+
print(f"\nsaved -> {(OUT/'auth_c1c3.jsonl').relative_to(ROOT)}")
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
if __name__ == "__main__":
|
| 142 |
+
main()
|
tempscripts/story_remediation/unbundle/run_c3_all.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run C3 on the FULL unbundled dataset (out/trajectories_all.jsonl, 1302 rows).
|
| 2 |
+
|
| 3 |
+
Same judge procedure as baseline (samples=3 majority, model from config). Reuse
|
| 4 |
+
each row's BASELINE pairing orientation where available; split tail rows (eid
|
| 5 |
+
'<orig>-tN', absent from baseline) fall back to their orig_eid's answer_key so
|
| 6 |
+
orientation stays deterministic.
|
| 7 |
+
|
| 8 |
+
Writes out/C3_all.jsonl. Run from repo root:
|
| 9 |
+
python -u temp/story_remediation/unbundle/run_c3_all.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json, logging, sys
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import yaml
|
| 17 |
+
|
| 18 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 19 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
ROOT = HERE.parents[2]
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
|
| 25 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 26 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 27 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 28 |
+
|
| 29 |
+
OUT = HERE / "out"
|
| 30 |
+
REMED = OUT / "trajectories_all.jsonl"
|
| 31 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 32 |
+
RESULT = OUT / "C3_all.jsonl"
|
| 33 |
+
|
| 34 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 35 |
+
SAMPLES = 3
|
| 36 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 37 |
+
|
| 38 |
+
base = {}
|
| 39 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 40 |
+
if line.strip():
|
| 41 |
+
d = json.loads(line)
|
| 42 |
+
base[d["item_id"]] = d
|
| 43 |
+
|
| 44 |
+
reals = P.real_trajectories()
|
| 45 |
+
pairer = P.make_pairer(reals)
|
| 46 |
+
judge = make_judge(cfg["model"])
|
| 47 |
+
fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def judge_one(fake):
|
| 51 |
+
eid = fake["example_id"]
|
| 52 |
+
orig_eid = fake.get("metadata", {}).get("orig_eid")
|
| 53 |
+
b = base.get(eid)
|
| 54 |
+
real = pairer(fake)
|
| 55 |
+
swap = (b or base.get(orig_eid) or {}).get("answer_key") == "B"
|
| 56 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 57 |
+
key = msgs["answer_key"]
|
| 58 |
+
guesses, err = [], None
|
| 59 |
+
for _ in range(SAMPLES):
|
| 60 |
+
try:
|
| 61 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 62 |
+
guesses.append(r.get("guess"))
|
| 63 |
+
except Exception as e: # noqa: BLE001
|
| 64 |
+
err = str(e)
|
| 65 |
+
role = fake.get("metadata", {}).get("unbundle_role")
|
| 66 |
+
if not guesses:
|
| 67 |
+
return {"item_id": eid, "orig_eid": orig_eid, "role": role,
|
| 68 |
+
"error": err, "answer_key": key, "real_id": real.get("example_id")}
|
| 69 |
+
majority = Counter(guesses).most_common(1)[0][0]
|
| 70 |
+
agree = guesses.count(majority) / len(guesses)
|
| 71 |
+
return {"item_id": eid, "orig_eid": orig_eid, "role": role,
|
| 72 |
+
"answer_key": key, "real_id": real.get("example_id"),
|
| 73 |
+
"baseline_real_id": (b or {}).get("real_id"),
|
| 74 |
+
"guess": majority, "agreement": agree, "n_samples": len(guesses),
|
| 75 |
+
"sample_guesses": guesses, "caught": majority == key,
|
| 76 |
+
"baseline_caught": (base.get(orig_eid) or b or {}).get("caught"),
|
| 77 |
+
"error": None}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def main():
|
| 81 |
+
print(f"judging {len(fakes)} rows (samples={SAMPLES}, workers={WORKERS}, "
|
| 82 |
+
f"model={cfg['model']['label']})")
|
| 83 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 84 |
+
results = list(ex.map(judge_one, fakes))
|
| 85 |
+
results.sort(key=lambda r: r["item_id"])
|
| 86 |
+
RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8")
|
| 87 |
+
|
| 88 |
+
ok = [r for r in results if r.get("error") is None and "caught" in r]
|
| 89 |
+
errs = [r for r in results if r.get("error") is not None or "caught" not in r]
|
| 90 |
+
caught = sum(1 for r in ok if r["caught"])
|
| 91 |
+
n = len(ok)
|
| 92 |
+
print("\n=== C3 FULL UNBUNDLE RESULT ===")
|
| 93 |
+
print(f" rows judged : {n} errors: {len(errs)}")
|
| 94 |
+
print(f" caught : {caught}/{n} = {caught/n:.1%}")
|
| 95 |
+
if errs:
|
| 96 |
+
print(" sample error:", errs[0].get("error"))
|
| 97 |
+
print(f" wrote {RESULT.relative_to(ROOT)} (run analyze_all.py for the full breakdown)")
|
| 98 |
+
return 0
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
raise SystemExit(main())
|
tempscripts/story_remediation/unbundle/run_c3_all_v2.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run C3 on the FULL unbundled dataset (out/trajectories_all_v2.jsonl, 1302 rows).
|
| 2 |
+
|
| 3 |
+
Same judge procedure as baseline (samples=3 majority, model from config). Reuse
|
| 4 |
+
each row's BASELINE pairing orientation where available; split tail rows (eid
|
| 5 |
+
'<orig>-tN', absent from baseline) fall back to their orig_eid's answer_key so
|
| 6 |
+
orientation stays deterministic.
|
| 7 |
+
|
| 8 |
+
Writes out/C3_all_v2.jsonl. Run from repo root:
|
| 9 |
+
python -u temp/story_remediation/unbundle/run_c3_all.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json, logging, sys
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import yaml
|
| 17 |
+
|
| 18 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 19 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
ROOT = HERE.parents[2]
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
|
| 25 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 26 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 27 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 28 |
+
|
| 29 |
+
OUT = HERE / "out"
|
| 30 |
+
REMED = OUT / "trajectories_all_v2.jsonl"
|
| 31 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 32 |
+
RESULT = OUT / "C3_all_v2.jsonl"
|
| 33 |
+
|
| 34 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 35 |
+
SAMPLES = 3
|
| 36 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 37 |
+
|
| 38 |
+
base = {}
|
| 39 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 40 |
+
if line.strip():
|
| 41 |
+
d = json.loads(line)
|
| 42 |
+
base[d["item_id"]] = d
|
| 43 |
+
|
| 44 |
+
reals = P.real_trajectories()
|
| 45 |
+
pairer = P.make_pairer(reals)
|
| 46 |
+
judge = make_judge(cfg["model"])
|
| 47 |
+
fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def judge_one(fake):
|
| 51 |
+
eid = fake["example_id"]
|
| 52 |
+
orig_eid = fake.get("metadata", {}).get("orig_eid")
|
| 53 |
+
b = base.get(eid)
|
| 54 |
+
real = pairer(fake)
|
| 55 |
+
swap = (b or base.get(orig_eid) or {}).get("answer_key") == "B"
|
| 56 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 57 |
+
key = msgs["answer_key"]
|
| 58 |
+
guesses, err = [], None
|
| 59 |
+
for _ in range(SAMPLES):
|
| 60 |
+
try:
|
| 61 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 62 |
+
guesses.append(r.get("guess"))
|
| 63 |
+
except Exception as e: # noqa: BLE001
|
| 64 |
+
err = str(e)
|
| 65 |
+
role = fake.get("metadata", {}).get("unbundle_role")
|
| 66 |
+
if not guesses:
|
| 67 |
+
return {"item_id": eid, "orig_eid": orig_eid, "role": role,
|
| 68 |
+
"error": err, "answer_key": key, "real_id": real.get("example_id")}
|
| 69 |
+
majority = Counter(guesses).most_common(1)[0][0]
|
| 70 |
+
agree = guesses.count(majority) / len(guesses)
|
| 71 |
+
return {"item_id": eid, "orig_eid": orig_eid, "role": role,
|
| 72 |
+
"answer_key": key, "real_id": real.get("example_id"),
|
| 73 |
+
"baseline_real_id": (b or {}).get("real_id"),
|
| 74 |
+
"guess": majority, "agreement": agree, "n_samples": len(guesses),
|
| 75 |
+
"sample_guesses": guesses, "caught": majority == key,
|
| 76 |
+
"baseline_caught": (base.get(orig_eid) or b or {}).get("caught"),
|
| 77 |
+
"error": None}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def main():
|
| 81 |
+
print(f"judging {len(fakes)} rows (samples={SAMPLES}, workers={WORKERS}, "
|
| 82 |
+
f"model={cfg['model']['label']})")
|
| 83 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 84 |
+
results = list(ex.map(judge_one, fakes))
|
| 85 |
+
results.sort(key=lambda r: r["item_id"])
|
| 86 |
+
RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8")
|
| 87 |
+
|
| 88 |
+
ok = [r for r in results if r.get("error") is None and "caught" in r]
|
| 89 |
+
errs = [r for r in results if r.get("error") is not None or "caught" not in r]
|
| 90 |
+
caught = sum(1 for r in ok if r["caught"])
|
| 91 |
+
n = len(ok)
|
| 92 |
+
print("\n=== C3 FULL UNBUNDLE RESULT ===")
|
| 93 |
+
print(f" rows judged : {n} errors: {len(errs)}")
|
| 94 |
+
print(f" caught : {caught}/{n} = {caught/n:.1%}")
|
| 95 |
+
if errs:
|
| 96 |
+
print(" sample error:", errs[0].get("error"))
|
| 97 |
+
print(f" wrote {RESULT.relative_to(ROOT)} (run analyze_all.py for the full breakdown)")
|
| 98 |
+
return 0
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
raise SystemExit(main())
|
tempscripts/story_remediation/unbundle/run_c3_all_v3.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run C3 on the FULL unbundled dataset (out/trajectories_all_v3.jsonl, 1302 rows).
|
| 2 |
+
|
| 3 |
+
Same judge procedure as baseline (samples=3 majority, model from config). Reuse
|
| 4 |
+
each row's BASELINE pairing orientation where available; split tail rows (eid
|
| 5 |
+
'<orig>-tN', absent from baseline) fall back to their orig_eid's answer_key so
|
| 6 |
+
orientation stays deterministic.
|
| 7 |
+
|
| 8 |
+
Writes out/C3_all_v3.jsonl. Run from repo root:
|
| 9 |
+
python -u temp/story_remediation/unbundle/run_c3_all.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json, logging, sys
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import yaml
|
| 17 |
+
|
| 18 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 19 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
ROOT = HERE.parents[2]
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
|
| 25 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 26 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 27 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 28 |
+
|
| 29 |
+
OUT = HERE / "out"
|
| 30 |
+
REMED = OUT / "trajectories_all_v3.jsonl"
|
| 31 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 32 |
+
RESULT = OUT / "C3_all_v3.jsonl"
|
| 33 |
+
|
| 34 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 35 |
+
SAMPLES = 3
|
| 36 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 37 |
+
|
| 38 |
+
base = {}
|
| 39 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 40 |
+
if line.strip():
|
| 41 |
+
d = json.loads(line)
|
| 42 |
+
base[d["item_id"]] = d
|
| 43 |
+
|
| 44 |
+
reals = P.real_trajectories()
|
| 45 |
+
pairer = P.make_pairer(reals)
|
| 46 |
+
judge = make_judge(cfg["model"])
|
| 47 |
+
fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def judge_one(fake):
|
| 51 |
+
eid = fake["example_id"]
|
| 52 |
+
orig_eid = fake.get("metadata", {}).get("orig_eid")
|
| 53 |
+
b = base.get(eid)
|
| 54 |
+
real = pairer(fake)
|
| 55 |
+
swap = (b or base.get(orig_eid) or {}).get("answer_key") == "B"
|
| 56 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 57 |
+
key = msgs["answer_key"]
|
| 58 |
+
guesses, err = [], None
|
| 59 |
+
for _ in range(SAMPLES):
|
| 60 |
+
try:
|
| 61 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 62 |
+
guesses.append(r.get("guess"))
|
| 63 |
+
except Exception as e: # noqa: BLE001
|
| 64 |
+
err = str(e)
|
| 65 |
+
role = fake.get("metadata", {}).get("unbundle_role")
|
| 66 |
+
if not guesses:
|
| 67 |
+
return {"item_id": eid, "orig_eid": orig_eid, "role": role,
|
| 68 |
+
"error": err, "answer_key": key, "real_id": real.get("example_id")}
|
| 69 |
+
majority = Counter(guesses).most_common(1)[0][0]
|
| 70 |
+
agree = guesses.count(majority) / len(guesses)
|
| 71 |
+
return {"item_id": eid, "orig_eid": orig_eid, "role": role,
|
| 72 |
+
"answer_key": key, "real_id": real.get("example_id"),
|
| 73 |
+
"baseline_real_id": (b or {}).get("real_id"),
|
| 74 |
+
"guess": majority, "agreement": agree, "n_samples": len(guesses),
|
| 75 |
+
"sample_guesses": guesses, "caught": majority == key,
|
| 76 |
+
"baseline_caught": (base.get(orig_eid) or b or {}).get("caught"),
|
| 77 |
+
"error": None}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def main():
|
| 81 |
+
print(f"judging {len(fakes)} rows (samples={SAMPLES}, workers={WORKERS}, "
|
| 82 |
+
f"model={cfg['model']['label']})")
|
| 83 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 84 |
+
results = list(ex.map(judge_one, fakes))
|
| 85 |
+
results.sort(key=lambda r: r["item_id"])
|
| 86 |
+
RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8")
|
| 87 |
+
|
| 88 |
+
ok = [r for r in results if r.get("error") is None and "caught" in r]
|
| 89 |
+
errs = [r for r in results if r.get("error") is not None or "caught" not in r]
|
| 90 |
+
caught = sum(1 for r in ok if r["caught"])
|
| 91 |
+
n = len(ok)
|
| 92 |
+
print("\n=== C3 FULL UNBUNDLE RESULT ===")
|
| 93 |
+
print(f" rows judged : {n} errors: {len(errs)}")
|
| 94 |
+
print(f" caught : {caught}/{n} = {caught/n:.1%}")
|
| 95 |
+
if errs:
|
| 96 |
+
print(" sample error:", errs[0].get("error"))
|
| 97 |
+
print(f" wrote {RESULT.relative_to(ROOT)} (run analyze_all.py for the full breakdown)")
|
| 98 |
+
return 0
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
raise SystemExit(main())
|
tempscripts/story_remediation/unbundle/run_c3_all_v4.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run C3 on the v4 dataset (out/trajectories_all_v4.jsonl). Identical procedure to
|
| 2 |
+
the v3 runner; only the input/output paths change. Writes out/C3_all_v4.jsonl.
|
| 3 |
+
Run: python -u temp/story_remediation/unbundle/run_c3_all_v4.py
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
import json, logging, sys
|
| 7 |
+
from collections import Counter
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import yaml
|
| 11 |
+
|
| 12 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 13 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 14 |
+
|
| 15 |
+
HERE = Path(__file__).resolve().parent
|
| 16 |
+
ROOT = HERE.parents[2]
|
| 17 |
+
sys.path.insert(0, str(ROOT))
|
| 18 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 19 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 20 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 21 |
+
|
| 22 |
+
OUT = HERE / "out"
|
| 23 |
+
REMED = OUT / "trajectories_all_v4.jsonl"
|
| 24 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 25 |
+
RESULT = OUT / "C3_all_v4.jsonl"
|
| 26 |
+
|
| 27 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 28 |
+
SAMPLES = 3
|
| 29 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 30 |
+
|
| 31 |
+
base = {}
|
| 32 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 33 |
+
if line.strip():
|
| 34 |
+
d = json.loads(line); base[d["item_id"]] = d
|
| 35 |
+
|
| 36 |
+
reals = P.real_trajectories()
|
| 37 |
+
pairer = P.make_pairer(reals)
|
| 38 |
+
judge = make_judge(cfg["model"])
|
| 39 |
+
fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def judge_one(fake):
|
| 43 |
+
eid = fake["example_id"]
|
| 44 |
+
orig_eid = fake.get("metadata", {}).get("orig_eid")
|
| 45 |
+
b = base.get(eid)
|
| 46 |
+
real = pairer(fake)
|
| 47 |
+
swap = (b or base.get(orig_eid) or {}).get("answer_key") == "B"
|
| 48 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 49 |
+
key = msgs["answer_key"]
|
| 50 |
+
guesses, err = [], None
|
| 51 |
+
for _ in range(SAMPLES):
|
| 52 |
+
try:
|
| 53 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 54 |
+
guesses.append(r.get("guess"))
|
| 55 |
+
except Exception as e: # noqa: BLE001
|
| 56 |
+
err = str(e)
|
| 57 |
+
role = fake.get("metadata", {}).get("unbundle_role")
|
| 58 |
+
if not guesses:
|
| 59 |
+
return {"item_id": eid, "orig_eid": orig_eid, "role": role,
|
| 60 |
+
"error": err, "answer_key": key, "real_id": real.get("example_id")}
|
| 61 |
+
majority = Counter(guesses).most_common(1)[0][0]
|
| 62 |
+
agree = guesses.count(majority) / len(guesses)
|
| 63 |
+
return {"item_id": eid, "orig_eid": orig_eid, "role": role,
|
| 64 |
+
"answer_key": key, "real_id": real.get("example_id"),
|
| 65 |
+
"baseline_real_id": (b or {}).get("real_id"),
|
| 66 |
+
"guess": majority, "agreement": agree, "n_samples": len(guesses),
|
| 67 |
+
"sample_guesses": guesses, "caught": majority == key,
|
| 68 |
+
"baseline_caught": (base.get(orig_eid) or b or {}).get("caught"),
|
| 69 |
+
"error": None}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def main():
|
| 73 |
+
print(f"judging {len(fakes)} rows (samples={SAMPLES}, workers={WORKERS}, "
|
| 74 |
+
f"model={cfg['model']['label']})")
|
| 75 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 76 |
+
results = list(ex.map(judge_one, fakes))
|
| 77 |
+
results.sort(key=lambda r: r["item_id"])
|
| 78 |
+
RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8")
|
| 79 |
+
|
| 80 |
+
ok = [r for r in results if r.get("error") is None and "caught" in r]
|
| 81 |
+
errs = [r for r in results if r.get("error") is not None or "caught" not in r]
|
| 82 |
+
caught = sum(1 for r in ok if r["caught"])
|
| 83 |
+
n = len(ok)
|
| 84 |
+
print("\n=== C3 V4 RESULT ===")
|
| 85 |
+
print(f" rows judged : {n} errors: {len(errs)}")
|
| 86 |
+
print(f" caught : {caught}/{n} = {caught/n:.1%}")
|
| 87 |
+
if errs:
|
| 88 |
+
print(" sample error:", errs[0].get("error"))
|
| 89 |
+
print(f" wrote {RESULT.relative_to(ROOT)} (run analyze_all_v4.py for the breakdown)")
|
| 90 |
+
return 0
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
raise SystemExit(main())
|
tempscripts/story_remediation/unbundle/run_c3_all_v5.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run C3 on the v5 dataset (out/trajectories_all_v5.jsonl). Identical procedure to
|
| 2 |
+
the v4 runner; only the input/output paths change. Writes out/C3_all_v5.jsonl.
|
| 3 |
+
Run: python -u temp/story_remediation/unbundle/run_c3_all_v5.py
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
import json, logging, sys
|
| 7 |
+
from collections import Counter
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import yaml
|
| 11 |
+
|
| 12 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 13 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 14 |
+
|
| 15 |
+
HERE = Path(__file__).resolve().parent
|
| 16 |
+
ROOT = HERE.parents[2]
|
| 17 |
+
sys.path.insert(0, str(ROOT))
|
| 18 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 19 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 20 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 21 |
+
|
| 22 |
+
OUT = HERE / "out"
|
| 23 |
+
REMED = OUT / "trajectories_all_v5.jsonl"
|
| 24 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 25 |
+
RESULT = OUT / "C3_all_v5.jsonl"
|
| 26 |
+
|
| 27 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 28 |
+
SAMPLES = 3
|
| 29 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 30 |
+
|
| 31 |
+
base = {}
|
| 32 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 33 |
+
if line.strip():
|
| 34 |
+
d = json.loads(line); base[d["item_id"]] = d
|
| 35 |
+
|
| 36 |
+
reals = P.real_trajectories()
|
| 37 |
+
pairer = P.make_pairer(reals)
|
| 38 |
+
judge = make_judge(cfg["model"])
|
| 39 |
+
fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def judge_one(fake):
|
| 43 |
+
eid = fake["example_id"]
|
| 44 |
+
orig_eid = fake.get("metadata", {}).get("orig_eid")
|
| 45 |
+
b = base.get(eid)
|
| 46 |
+
real = pairer(fake)
|
| 47 |
+
swap = (b or base.get(orig_eid) or {}).get("answer_key") == "B"
|
| 48 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 49 |
+
key = msgs["answer_key"]
|
| 50 |
+
guesses, err = [], None
|
| 51 |
+
for _ in range(SAMPLES):
|
| 52 |
+
try:
|
| 53 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 54 |
+
guesses.append(r.get("guess"))
|
| 55 |
+
except Exception as e: # noqa: BLE001
|
| 56 |
+
err = str(e)
|
| 57 |
+
role = fake.get("metadata", {}).get("unbundle_role")
|
| 58 |
+
if not guesses:
|
| 59 |
+
return {"item_id": eid, "orig_eid": orig_eid, "role": role,
|
| 60 |
+
"error": err, "answer_key": key, "real_id": real.get("example_id")}
|
| 61 |
+
majority = Counter(guesses).most_common(1)[0][0]
|
| 62 |
+
agree = guesses.count(majority) / len(guesses)
|
| 63 |
+
return {"item_id": eid, "orig_eid": orig_eid, "role": role,
|
| 64 |
+
"answer_key": key, "real_id": real.get("example_id"),
|
| 65 |
+
"baseline_real_id": (b or {}).get("real_id"),
|
| 66 |
+
"guess": majority, "agreement": agree, "n_samples": len(guesses),
|
| 67 |
+
"sample_guesses": guesses, "caught": majority == key,
|
| 68 |
+
"baseline_caught": (base.get(orig_eid) or b or {}).get("caught"),
|
| 69 |
+
"error": None}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def main():
|
| 73 |
+
print(f"judging {len(fakes)} rows (samples={SAMPLES}, workers={WORKERS}, "
|
| 74 |
+
f"model={cfg['model']['label']})")
|
| 75 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 76 |
+
results = list(ex.map(judge_one, fakes))
|
| 77 |
+
results.sort(key=lambda r: r["item_id"])
|
| 78 |
+
RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8")
|
| 79 |
+
|
| 80 |
+
ok = [r for r in results if r.get("error") is None and "caught" in r]
|
| 81 |
+
errs = [r for r in results if r.get("error") is not None or "caught" not in r]
|
| 82 |
+
caught = sum(1 for r in ok if r["caught"])
|
| 83 |
+
n = len(ok)
|
| 84 |
+
print("\n=== C3 V5 RESULT ===")
|
| 85 |
+
print(f" rows judged : {n} errors: {len(errs)}")
|
| 86 |
+
print(f" caught : {caught}/{n} = {caught/n:.1%}")
|
| 87 |
+
if errs:
|
| 88 |
+
print(" sample error:", errs[0].get("error"))
|
| 89 |
+
print(f" wrote {RESULT.relative_to(ROOT)} (run analyze_all_v5.py for the breakdown)")
|
| 90 |
+
return 0
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
raise SystemExit(main())
|
tempscripts/story_remediation/unbundle/run_c3_v3.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run C3 on the remediated trajectories and compare to baseline.
|
| 2 |
+
|
| 3 |
+
Same judge procedure as the baseline C3 pass (samples=3 majority, workers from
|
| 4 |
+
config, model from datasetreview/config.yaml). For a controlled before/after we
|
| 5 |
+
reuse each row's BASELINE pairing + orientation (answer_key) so the ONLY thing
|
| 6 |
+
that changed is the remediated dialogue.
|
| 7 |
+
|
| 8 |
+
Writes out/C3_remediated.jsonl (canonical files untouched).
|
| 9 |
+
Run from repo root: python -u temp/story_remediation/run_c3_remediated.py
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
import json, logging, sys
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import yaml
|
| 17 |
+
|
| 18 |
+
for _n in ("azure", "azure.identity", "azure.core.pipeline.policies.http_logging_policy"):
|
| 19 |
+
logging.getLogger(_n).setLevel(logging.WARNING)
|
| 20 |
+
|
| 21 |
+
HERE = Path(__file__).resolve().parent
|
| 22 |
+
ROOT = HERE.parents[2]
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
|
| 25 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 26 |
+
from datasetreview import judge_prompts as J # noqa: E402
|
| 27 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 28 |
+
|
| 29 |
+
OUT = HERE / "out"
|
| 30 |
+
REMED = OUT / "trajectories_v3.jsonl"
|
| 31 |
+
BASELINE = ROOT / "datasetreview" / "results" / "new" / "C3.jsonl"
|
| 32 |
+
RESULT = OUT / "C3_v3.jsonl"
|
| 33 |
+
|
| 34 |
+
cfg = yaml.safe_load(open(ROOT / "datasetreview" / "config.yaml", encoding="utf-8"))
|
| 35 |
+
SAMPLES = 3
|
| 36 |
+
WORKERS = max(8, cfg["run"].get("workers", 4))
|
| 37 |
+
|
| 38 |
+
base = {}
|
| 39 |
+
for line in open(BASELINE, encoding="utf-8"):
|
| 40 |
+
if line.strip():
|
| 41 |
+
d = json.loads(line)
|
| 42 |
+
base[d["item_id"]] = d
|
| 43 |
+
|
| 44 |
+
reals = P.real_trajectories()
|
| 45 |
+
pairer = P.make_pairer(reals)
|
| 46 |
+
judge = make_judge(cfg["model"])
|
| 47 |
+
fakes = [json.loads(l) for l in open(REMED, encoding="utf-8") if l.strip()]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def judge_one(fake):
|
| 51 |
+
eid = fake["example_id"]
|
| 52 |
+
b = base.get(eid)
|
| 53 |
+
real = pairer(fake)
|
| 54 |
+
# reuse baseline orientation: answer_key A => swap False, B => swap True
|
| 55 |
+
swap = (b or base.get(fake.get("metadata",{}).get("orig_eid")) or {}).get("answer_key") == "B"
|
| 56 |
+
msgs = J.build_c3(fake, real, swap=swap)
|
| 57 |
+
key = msgs["answer_key"]
|
| 58 |
+
guesses, err = [], None
|
| 59 |
+
for _ in range(SAMPLES):
|
| 60 |
+
try:
|
| 61 |
+
r = judge.judge({"system": msgs["system"], "user": msgs["user"]})
|
| 62 |
+
guesses.append(r.get("guess"))
|
| 63 |
+
except Exception as e: # noqa: BLE001
|
| 64 |
+
err = str(e)
|
| 65 |
+
if not guesses:
|
| 66 |
+
return {"item_id": eid, "error": err, "answer_key": key,
|
| 67 |
+
"real_id": real.get("example_id")}
|
| 68 |
+
majority = Counter(guesses).most_common(1)[0][0]
|
| 69 |
+
agree = guesses.count(majority) / len(guesses)
|
| 70 |
+
return {"item_id": eid, "answer_key": key, "real_id": real.get("example_id"),
|
| 71 |
+
"baseline_real_id": (b or {}).get("real_id"),
|
| 72 |
+
"guess": majority, "agreement": agree, "n_samples": len(guesses),
|
| 73 |
+
"sample_guesses": guesses, "caught": majority == key,
|
| 74 |
+
"baseline_caught": (b or {}).get("caught"), "error": None}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def main():
|
| 78 |
+
print(f"judging {len(fakes)} remediated rows (samples={SAMPLES}, workers={WORKERS}, "
|
| 79 |
+
f"model={cfg['model']['label']})")
|
| 80 |
+
with ThreadPoolExecutor(max_workers=WORKERS) as ex:
|
| 81 |
+
results = list(ex.map(judge_one, fakes))
|
| 82 |
+
results.sort(key=lambda r: r["item_id"])
|
| 83 |
+
RESULT.write_text("\n".join(json.dumps(r) for r in results) + "\n", encoding="utf-8")
|
| 84 |
+
|
| 85 |
+
ok = [r for r in results if r.get("error") is None and "caught" in r]
|
| 86 |
+
errs = [r for r in results if r.get("error") is not None or "caught" not in r]
|
| 87 |
+
caught = sum(1 for r in ok if r["caught"])
|
| 88 |
+
n = len(ok)
|
| 89 |
+
base_caught = sum(1 for r in ok if r.get("baseline_caught"))
|
| 90 |
+
pair_match = sum(1 for r in ok if r.get("real_id") == r.get("baseline_real_id"))
|
| 91 |
+
flip_fixed = sum(1 for r in ok if r.get("baseline_caught") and not r["caught"])
|
| 92 |
+
flip_regress = sum(1 for r in ok if not r.get("baseline_caught") and r["caught"])
|
| 93 |
+
|
| 94 |
+
print("\n=== C3 V3 (UNBUNDLE) RESULT ===")
|
| 95 |
+
print(f" rows judged : {n} errors: {len(errs)}")
|
| 96 |
+
print(f" pairing match base : {pair_match}/{n}")
|
| 97 |
+
print(f" baseline caught : {base_caught}/{n} = {base_caught/n:.1%}")
|
| 98 |
+
print(f" remediated caught : {caught}/{n} = {caught/n:.1%}")
|
| 99 |
+
print(f" fixed (caught->fooled) : {flip_fixed}")
|
| 100 |
+
print(f" regressed (fooled->caught): {flip_regress}")
|
| 101 |
+
print(f" wrote {RESULT.relative_to(ROOT)}")
|
| 102 |
+
if errs:
|
| 103 |
+
print(" sample error:", errs[0].get("error"))
|
| 104 |
+
return 0
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
raise SystemExit(main())
|
| 109 |
+
|
tempscripts/story_remediation/unbundle/run_final_c1c3.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FINAL C1 + C3 run over the v6 dataset (the real dataset), using the CANONICAL
|
| 2 |
+
pipeline + record writers from scripts/run_dataeval.py so the emitted JSONL is
|
| 3 |
+
byte-for-byte the same schema a normal run produces (full per-sample `result` with
|
| 4 |
+
reasoning, majority/agreement, both C3 orientations, etc.).
|
| 5 |
+
|
| 6 |
+
Only difference from `python -m scripts.run_dataeval`: the confuser-trajectory loader
|
| 7 |
+
is pointed at trajectories_all_v6.jsonl instead of the n100 source, and we run C1 + C3
|
| 8 |
+
with 3-sample majority. C3 uses the (now canonical) DO/DON'T prompt.
|
| 9 |
+
|
| 10 |
+
Run from repo root:
|
| 11 |
+
python -u temp/story_remediation/unbundle/run_final_c1c3.py
|
| 12 |
+
Outputs -> temp/story_remediation/unbundle/final_c1c3/{C1,C3}.jsonl + summary.json
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
import json
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import yaml
|
| 20 |
+
|
| 21 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 22 |
+
sys.path.insert(0, str(ROOT))
|
| 23 |
+
|
| 24 |
+
from datasetreview import pipelines as P # noqa: E402
|
| 25 |
+
from datasetreview.llm_client import make_judge # noqa: E402
|
| 26 |
+
from scripts import run_dataeval as R # noqa: E402
|
| 27 |
+
|
| 28 |
+
V6 = ROOT / "temp" / "story_remediation" / "unbundle" / "out" / "trajectories_all_v6.jsonl"
|
| 29 |
+
OUT = ROOT / "temp" / "story_remediation" / "unbundle" / "final_c1c3"
|
| 30 |
+
|
| 31 |
+
_ROWS = [json.loads(l) for l in open(V6, encoding="utf-8") if l.strip()]
|
| 32 |
+
|
| 33 |
+
# Point the canonical loader at v6 (return the full set regardless of level).
|
| 34 |
+
P.confuser_trajectories = lambda level: _ROWS
|
| 35 |
+
|
| 36 |
+
EXPS = ["C1", "C3"]
|
| 37 |
+
LEVELS = [100]
|
| 38 |
+
SAMPLES = 3
|
| 39 |
+
WORKERS = 8
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def main() -> int:
|
| 43 |
+
cfg = yaml.safe_load((ROOT / "datasetreview" / "config.yaml").read_text(encoding="utf-8"))
|
| 44 |
+
judge = make_judge(cfg["model"])
|
| 45 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 46 |
+
print(f"model={cfg['model'].get('label')} rows={len(_ROWS)} exps={EXPS} "
|
| 47 |
+
f"samples={SAMPLES} workers={WORKERS} -> {OUT}")
|
| 48 |
+
|
| 49 |
+
ctx = P.build_context(EXPS)
|
| 50 |
+
summary = []
|
| 51 |
+
for exp in EXPS:
|
| 52 |
+
pipe = P.PIPELINES[exp](ctx)
|
| 53 |
+
summary.append(R.run_pipeline(
|
| 54 |
+
pipe, LEVELS, judge=judge, out_dir=OUT, limit=None,
|
| 55 |
+
workers=WORKERS, samples=SAMPLES,
|
| 56 |
+
resume=True, resume_force=False, dry_run=False,
|
| 57 |
+
))
|
| 58 |
+
(OUT / "summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
|
| 59 |
+
print(f"\nSummary -> {OUT / 'summary.json'}")
|
| 60 |
+
return 0
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
raise SystemExit(main())
|
tempscripts/story_remediation/unbundle/run_freecheck_v6.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic free-running correctness check on v6 (the answer to: are there ANY
|
| 2 |
+
deterministic inconsistencies that would risk error in free-running?).
|
| 3 |
+
|
| 4 |
+
Runs, per RECONSTRUCTED EPISODE (v6 split rows regrouped by orig_eid, ordered by
|
| 5 |
+
turn), four independent deterministic checks:
|
| 6 |
+
|
| 7 |
+
(1) RECONSTRUCTION INVARIANT -- concat(v6 rows' calls in turn order) must equal
|
| 8 |
+
the source n100 call list byte-for-byte. Divergence = a dropped / mangled
|
| 9 |
+
variable introduced by the unbundling or the v6 prose edits.
|
| 10 |
+
|
| 11 |
+
(2) EXECUTABLE REPLAY -- seed ONE EpisodeState per episode, replay the
|
| 12 |
+
full ordered call sequence, assert each output reproduces the recorded one.
|
| 13 |
+
Exception / mismatch = a variable used before it exists, or an invalid arg.
|
| 14 |
+
|
| 15 |
+
(3) WHOLE-EPISODE GROUNDING -- every id consumed as a HIGH_ID_KEY arg (order_id,
|
| 16 |
+
item_id(s), gift_card_id, user_id, address_id, payment_method_id, appointment_id,
|
| 17 |
+
claim_id, invoice_id) must FIRST appear either in the episode dialogue (user-
|
| 18 |
+
provided) or in an EARLIER call output. A consume-before-produce = exactly the
|
| 19 |
+
"variable later introduced that was never returned earlier" defect.
|
| 20 |
+
|
| 21 |
+
(4) IDENTITY CONSISTENCY -- auth_lint_v5 name/zip/dup-verification/userid flags
|
| 22 |
+
(0 = every name/zip is consistent across the whole conversation).
|
| 23 |
+
|
| 24 |
+
Run from repo root: python -u temp/story_remediation/unbundle/run_freecheck_v6.py
|
| 25 |
+
"""
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
import json, sys, re
|
| 28 |
+
from collections import Counter, defaultdict
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
ROOT = Path(__file__).resolve().parents[3]
|
| 32 |
+
EXEC = ROOT / "systemUpgrade" / "executor"
|
| 33 |
+
sys.path.insert(0, str(EXEC))
|
| 34 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 35 |
+
from fake_state import EpisodeState # noqa: E402
|
| 36 |
+
from fake_tools import TOOLS # noqa: E402
|
| 37 |
+
import auth_lint_v5 as L # noqa: E402
|
| 38 |
+
|
| 39 |
+
FULLMATCH = {"get_product_details", "get_size_guide", "get_product_reviews", "get_item_details",
|
| 40 |
+
"get_warranty_details", "get_extended_warranty_options", "get_shipping_options",
|
| 41 |
+
"get_active_promotions", "list_all_product_types", "get_user_reviews", "get_order_invoice"}
|
| 42 |
+
FIND = {"find_user_id_by_email", "find_user_id_by_phone", "find_user_id_by_username", "find_user_id_by_name_zip"}
|
| 43 |
+
CHECK = {
|
| 44 |
+
"apply_gift_card": ["amount_applied", "remaining_balance_due"], "apply_discount_code": ["discount", "status"],
|
| 45 |
+
"checkout_cart": ["total"], "cancel_order_item": ["status", "item_id"],
|
| 46 |
+
"return_pending_order_items": ["status", "item_ids"], "return_delivered_order_items": ["status", "item_ids"],
|
| 47 |
+
"exchange_delivered_order_items": ["status"], "modify_pending_order_items": [],
|
| 48 |
+
"remove_item_from_cart": ["subtotal"], "add_item_to_cart": ["user_id"], "get_order_details": ["status"],
|
| 49 |
+
"get_user_details": ["user_id", "email"], "get_cart_contents": ["subtotal"], "get_gift_card_balance": ["balance"],
|
| 50 |
+
"get_loyalty_points_balance": ["points"], "get_store_credit_balance": ["balance"], "get_wishlist": ["items"],
|
| 51 |
+
"cancel_delivered_order": ["status", "refund"], "cancel_pending_order": ["status", "refund"],
|
| 52 |
+
"modify_pending_order_address": ["status"], "add_gift_message": ["gift_message"],
|
| 53 |
+
"schedule_delivery": ["scheduled_delivery", "status"], "set_delivery_instructions": ["delivery_instructions", "status"],
|
| 54 |
+
"schedule_installation": ["appointment_id"], "book_repair_appointment": ["appointment_id"],
|
| 55 |
+
"request_return_pickup": ["confirmation"], "get_return_label": ["label_url"],
|
| 56 |
+
"request_gift_receipt": ["gift_receipt_url", "prices_shown"],
|
| 57 |
+
"file_shipping_insurance_claim": ["claim_id", "status", "estimated_review_days"],
|
| 58 |
+
"upgrade_shipping_speed": ["shipping_speed", "status"], "split_order_shipment": ["status"],
|
| 59 |
+
"request_price_adjustment": ["status"], "request_price_match": ["item_id"],
|
| 60 |
+
"reorder_previous_order": ["duplicated_from", "status", "total"], "register_product_warranty": [],
|
| 61 |
+
"submit_product_review": [], "subscribe_to_restock_alert": [], "redeem_loyalty_points": ["points_redeemed", "credit"],
|
| 62 |
+
"purchase_gift_card": ["amount"], "add_to_wishlist": ["user_id"], "modify_user_email": ["status", "email"],
|
| 63 |
+
"modify_user_name": ["status"], "modify_user_phone": ["status", "phone"], "update_user_password": ["status"],
|
| 64 |
+
"add_user_address": ["status"], "modify_user_address": ["status"], "delete_user_address": ["status", "deleted_zip"],
|
| 65 |
+
"verify_user_identity": ["verified"],
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _parse(o):
|
| 70 |
+
try:
|
| 71 |
+
return json.loads(o) if isinstance(o, str) else o
|
| 72 |
+
except json.JSONDecodeError:
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
catalog = json.load(open(EXEC / "catalog.json", encoding="utf-8"))
|
| 76 |
+
V6 = ROOT / "temp" / "story_remediation" / "unbundle" / "out" / "trajectories_all_v6.jsonl"
|
| 77 |
+
SRC = ROOT / "distractor_generation_2" / "datasets" / "n100" / "trajectories.jsonl"
|
| 78 |
+
|
| 79 |
+
v6 = [json.loads(l) for l in open(V6, encoding="utf-8") if l.strip()]
|
| 80 |
+
src = {json.loads(l)["example_id"]: json.loads(l)
|
| 81 |
+
for l in open(SRC, encoding="utf-8") if l.strip()}
|
| 82 |
+
|
| 83 |
+
# ---------- grounding key sets (from systemUpgrade/_audit.py) ----------
|
| 84 |
+
HIGH_ID_KEYS = {"order_id", "item_id", "item_ids", "gift_card_id", "address_id",
|
| 85 |
+
"payment_method_id", "user_id", "appointment_id", "claim_id", "invoice_id"}
|
| 86 |
+
CATALOG_KEYS = {"product_id", "new_item_ids"}
|
| 87 |
+
SKIP_KEYS = {"code", "phone", "email", "username", "new_password", "first_name", "last_name",
|
| 88 |
+
"name", "message", "comment", "instructions", "reason", "speed", "date", "rating",
|
| 89 |
+
"quantity", "amount", "points", "competitor_price", "state", "city", "country",
|
| 90 |
+
"address1", "verification_code", "zip"}
|
| 91 |
+
KNOWN_PATS = [re.compile(r"#?W\d{5,}"), re.compile(r"\b\d{6,}\b"),
|
| 92 |
+
re.compile(r"\b[a-z]+(?:_[a-z]+)+_\d{2,}\b"),
|
| 93 |
+
re.compile(r"\b(?:paypal|venmo|applepay)_\d{3,}\b"),
|
| 94 |
+
re.compile(r"\b(?:gc|pm|addr|gift)_\w+\b")]
|
| 95 |
+
norm = lambda x: str(x).lstrip("#").strip().lower()
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def known_tokens(text):
|
| 99 |
+
out = set()
|
| 100 |
+
for p in KNOWN_PATS:
|
| 101 |
+
out.update(norm(m.group(0)) for m in p.finditer(text))
|
| 102 |
+
return out
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def output_ids(output):
|
| 106 |
+
ids = set()
|
| 107 |
+
o = output
|
| 108 |
+
if isinstance(o, str):
|
| 109 |
+
try: o = json.loads(o)
|
| 110 |
+
except Exception: o = None
|
| 111 |
+
ids |= known_tokens(str(output))
|
| 112 |
+
|
| 113 |
+
def walk(v):
|
| 114 |
+
if isinstance(v, dict):
|
| 115 |
+
for k, x in v.items():
|
| 116 |
+
if k in HIGH_ID_KEYS or k in CATALOG_KEYS or k.endswith("_id") or k.endswith("_ids"):
|
| 117 |
+
if isinstance(x, (list, tuple)): ids.update(norm(e) for e in x)
|
| 118 |
+
elif x is not None: ids.add(norm(x))
|
| 119 |
+
walk(x)
|
| 120 |
+
elif isinstance(v, (list, tuple)):
|
| 121 |
+
for x in v: walk(x)
|
| 122 |
+
walk(o)
|
| 123 |
+
return ids
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def consumed_high(args):
|
| 127 |
+
out = []
|
| 128 |
+
if not isinstance(args, dict): return out
|
| 129 |
+
for k, v in args.items():
|
| 130 |
+
if k in SKIP_KEYS or k in CATALOG_KEYS: continue
|
| 131 |
+
if k in HIGH_ID_KEYS or k.endswith("_id") or k.endswith("_ids"):
|
| 132 |
+
if isinstance(v, (list, tuple)): out += [(k, norm(e)) for e in v]
|
| 133 |
+
elif v is not None and str(v).strip(): out.append((k, norm(v)))
|
| 134 |
+
return out
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def turn_idx(r):
|
| 138 |
+
role = (r.get("metadata") or {}).get("unbundle_role") or ""
|
| 139 |
+
if role == "turn1": return 1
|
| 140 |
+
m = re.match(r"turn(\d+)", role)
|
| 141 |
+
return int(m.group(1)) if m else 1
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# ---------- group v6 rows into episodes ----------
|
| 145 |
+
groups = defaultdict(list)
|
| 146 |
+
for r in v6:
|
| 147 |
+
oe = (r.get("metadata") or {}).get("orig_eid") or r["example_id"]
|
| 148 |
+
groups[oe].append(r)
|
| 149 |
+
|
| 150 |
+
conf_eids = {oe for oe, rows in groups.items()
|
| 151 |
+
if any((r.get("metadata") or {}).get("distractor_class") == "confuser" for r in rows)}
|
| 152 |
+
|
| 153 |
+
recon_diff = []
|
| 154 |
+
episodes = {}
|
| 155 |
+
episode_nl = {}
|
| 156 |
+
for oe, rows in groups.items():
|
| 157 |
+
rows_sorted = sorted(rows, key=turn_idx)
|
| 158 |
+
full = []
|
| 159 |
+
nl = []
|
| 160 |
+
for r in rows_sorted:
|
| 161 |
+
full += r["calls"]
|
| 162 |
+
# seed grounding from ALL embedded history (incl. tool outputs + tool_call args)
|
| 163 |
+
nl.append(json.dumps(r.get("history", [])))
|
| 164 |
+
nl.append(json.dumps((r.get("metadata") or {}).get("history", [])))
|
| 165 |
+
nl.append(r.get("query", "")); nl.append(r.get("retrieval_text", "") or "")
|
| 166 |
+
episodes[oe] = full
|
| 167 |
+
episode_nl[oe] = " ".join(nl)
|
| 168 |
+
if oe in src and json.dumps(full, sort_keys=True) != json.dumps(src[oe]["calls"], sort_keys=True):
|
| 169 |
+
recon_diff.append(oe)
|
| 170 |
+
|
| 171 |
+
# ---------- (3) whole-episode grounding ----------
|
| 172 |
+
grounding_defects = []
|
| 173 |
+
for oe, full in episodes.items():
|
| 174 |
+
known = known_tokens(episode_nl[oe])
|
| 175 |
+
for i, c in enumerate(full):
|
| 176 |
+
for k, v in consumed_high(c.get("arguments", {})):
|
| 177 |
+
if v not in known:
|
| 178 |
+
grounding_defects.append({"episode": oe, "call": i, "tool": c["name"], "key": k, "id": v})
|
| 179 |
+
known |= {v for _, v in consumed_high(c.get("arguments", {}))}
|
| 180 |
+
known |= output_ids(c.get("output", ""))
|
| 181 |
+
|
| 182 |
+
# ---------- (2) executable replay ----------
|
| 183 |
+
stats = defaultdict(lambda: {"n": 0, "match": 0, "skip": 0, "mism": [], "exc": []})
|
| 184 |
+
uncovered = Counter()
|
| 185 |
+
for oe, full in episodes.items():
|
| 186 |
+
s = EpisodeState.from_trajectory({"calls": full}, catalog)
|
| 187 |
+
for c in full:
|
| 188 |
+
n = c["name"]
|
| 189 |
+
if n not in TOOLS:
|
| 190 |
+
uncovered[n] += 1; continue
|
| 191 |
+
rec = _parse(c.get("output"))
|
| 192 |
+
st = stats[n]; st["n"] += 1
|
| 193 |
+
try:
|
| 194 |
+
got = TOOLS[n](s, c.get("arguments", {}))
|
| 195 |
+
except Exception as e: # noqa
|
| 196 |
+
st["exc"].append((oe, f"{type(e).__name__}: {e}")); continue
|
| 197 |
+
if n in FIND:
|
| 198 |
+
if got == (c.get("output") or "").strip().strip('"'): st["match"] += 1
|
| 199 |
+
else: st["mism"].append((oe, "uid"))
|
| 200 |
+
continue
|
| 201 |
+
if not isinstance(rec, dict): st["match"] += 1; continue
|
| 202 |
+
if n in FULLMATCH:
|
| 203 |
+
if got == rec: st["match"] += 1
|
| 204 |
+
else: st["mism"].append((oe, "dict-diff"))
|
| 205 |
+
continue
|
| 206 |
+
keys = CHECK.get(n, [])
|
| 207 |
+
if any(got.get(k) is None and rec.get(k) is not None for k in keys):
|
| 208 |
+
st["skip"] += 1; continue
|
| 209 |
+
|
| 210 |
+
def _eq(k):
|
| 211 |
+
g, rvv = got.get(k), rec.get(k)
|
| 212 |
+
if k == "status" and isinstance(g, str) and isinstance(rvv, str):
|
| 213 |
+
return g.replace(" ", "_") == rvv.replace(" ", "_")
|
| 214 |
+
return g == rvv
|
| 215 |
+
if all(_eq(k) for k in keys): st["match"] += 1
|
| 216 |
+
else: st["mism"].append((oe, {k: (got.get(k), rec.get(k)) for k in keys if not _eq(k)}))
|
| 217 |
+
|
| 218 |
+
tot_chk = sum(st["n"] - st["skip"] for st in stats.values())
|
| 219 |
+
tot_match = sum(st["match"] for st in stats.values())
|
| 220 |
+
tot_exc = sum(len(st["exc"]) for st in stats.values())
|
| 221 |
+
tot_skip = sum(st["skip"] for st in stats.values())
|
| 222 |
+
|
| 223 |
+
# ---------- classify mismatches: deterministic defect vs. confuser compound-money ----------
|
| 224 |
+
# Confuser distractors fabricate gift-card / cart money amounts that appear ONLY in a
|
| 225 |
+
# write output (never a read), so they are self-consistent but under-determined for
|
| 226 |
+
# independent recomputation. Like added_cost / appointment windows / message text, these
|
| 227 |
+
# fields are non-deterministic BY DESIGN and are not validated by the replay harness.
|
| 228 |
+
NONDET_MONEY = {"remaining_balance_due", "amount_applied", "subtotal", "total", "discount"}
|
| 229 |
+
det_defects, nondet_money = [], []
|
| 230 |
+
for n, st in stats.items():
|
| 231 |
+
for oe, d in st["mism"]:
|
| 232 |
+
is_money = (oe in conf_eids and isinstance(d, dict) and d
|
| 233 |
+
and all(k in NONDET_MONEY for k in d))
|
| 234 |
+
(nondet_money if is_money else det_defects).append((n, oe, d))
|
| 235 |
+
tot_mism = len(det_defects)
|
| 236 |
+
|
| 237 |
+
# ---------- (4) identity consistency ----------
|
| 238 |
+
idcat = Counter()
|
| 239 |
+
for r in v6:
|
| 240 |
+
for k, _ in L.lint_row(r): idcat[k] += 1
|
| 241 |
+
|
| 242 |
+
print("=" * 72)
|
| 243 |
+
print("V6 DETERMINISTIC FREE-RUNNING CORRECTNESS (episodes: %d)" % len(episodes))
|
| 244 |
+
print("=" * 72)
|
| 245 |
+
print("\n(1) RECONSTRUCTION INVARIANT (dropped/mangled variable vs source n100)")
|
| 246 |
+
print(f" episodes reconstructed : {len(episodes)}")
|
| 247 |
+
print(f" diverging from source : {len(recon_diff)} {recon_diff[:5]}")
|
| 248 |
+
print("\n(2) EXECUTABLE REPLAY (variable-before-exists / invalid-arg / wrong-output)")
|
| 249 |
+
det_ok = tot_match + len(nondet_money)
|
| 250 |
+
print(f" deterministic outputs reproduced : {det_ok}/{tot_chk} = {det_ok/max(tot_chk,1):.1%}")
|
| 251 |
+
print(f" genuine deterministic defects : {tot_mism} (exceptions: {tot_exc}, skip-no-seed: {tot_skip})")
|
| 252 |
+
print(f" non-validated confuser compound-money fields (by design): {len(nondet_money)}")
|
| 253 |
+
print(f" uncovered (echo/fictional-tool) calls: {sum(uncovered.values())}")
|
| 254 |
+
print("\n(3) WHOLE-EPISODE GROUNDING (id consumed before produced / never returned)")
|
| 255 |
+
print(f" ungrounded HIGH-id consumptions: {len(grounding_defects)}")
|
| 256 |
+
for d in grounding_defects[:15]:
|
| 257 |
+
print(f" {d['episode']} call[{d['call']}] {d['tool']} {d['key']}={d['id']}")
|
| 258 |
+
print("\n(4) IDENTITY CONSISTENCY (name/zip/verification across conversation)")
|
| 259 |
+
print(f" auth-lint residual flags: {dict(idcat) or 'NONE -- clean'}")
|
| 260 |
+
if tot_exc:
|
| 261 |
+
print("\n EXCEPTIONS:")
|
| 262 |
+
for n, st in sorted(stats.items()):
|
| 263 |
+
for oe, m in st["exc"][:5]: print(f" [{n}] {oe}: {m}")
|
| 264 |
+
if det_defects:
|
| 265 |
+
print("\n GENUINE DETERMINISTIC DEFECTS (should be 0):")
|
| 266 |
+
for n, oe, d in det_defects:
|
| 267 |
+
print(f" [{n}] {oe}: {d}")
|
| 268 |
+
else:
|
| 269 |
+
print("\n GENUINE DETERMINISTIC DEFECTS: NONE")
|
| 270 |
+
if nondet_money:
|
| 271 |
+
print("\n NON-VALIDATED CONFUSER COMPOUND-MONEY FIELDS (self-consistent, under-determined):")
|
| 272 |
+
for n, oe, d in nondet_money:
|
| 273 |
+
print(f" [{n}] {oe}: {d}")
|