"""SANDBOX validation: logic tests + I/O tests over the 51 merged injected rows (each replayed together with its host turn). Reads only sandbox artifacts. Run: python -u temp/injection_sandbox/validate.py """ from __future__ import annotations import json import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[2] SAND = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "systemUpgrade" / "executor")) import scripts._gen_injections2 as G # noqa: E402 from fake_state import EpisodeState # noqa: E402 from fake_tools import TOOLS # noqa: E402 DATA = SAND / "data" OUT = SAND / "out" CATALOG = json.load(open(DATA / "catalog.json", encoding="utf-8")) G.CATALOG = CATALOG STRICT_PENDING = {"upgrade_shipping_speed", "modify_pending_order_items", "cancel_pending_order", "return_pending_order_items"} PRE_DELIVERY = {"schedule_delivery", "set_delivery_instructions", "get_shipping_options"} PENDING_OK = ("pending", "processing", "open", "pending (modified)") DELIVERED_OK = {"file_shipping_insurance_claim", "return_delivered_order_items", "exchange_delivered_order_items"} BAD_STATUS = {"cancelled", "returned", "return requested"} def parse(o): try: return json.loads(o) if isinstance(o, str) and o.strip().startswith("{") else None except json.JSONDecodeError: return None def order_status_map(calls): m = {} for c in calls: o = parse(c.get("output")) if c["name"] == "get_order_details" and o and o.get("order_id"): m["#" + str(o["order_id"]).lstrip("#").upper()] = (o.get("status") or "").lower() return m def main(): inj = [json.loads(l) for l in open(OUT / "_staging_merged_injections.jsonl", encoding="utf-8") if l.strip()] prov = json.load(open(OUT / "_merged_injections.prov.json", encoding="utf-8")) c3 = {r["example_id"]: r for r in (json.loads(l) for l in open(DATA / "c3_trajectories.jsonl", encoding="utf-8") if l.strip())} host_of = {p["example_id"]: p["host_of"] for p in prov} logic = {"open_status": [], "delivered_status": [], "acted_on_bad": [], "modify_before_subscribe": [], "auth_before_use": []} io = {"row_replay": [], "conv_replay": []} for row in inj: eid = row["example_id"] calls = row["calls"] host = c3[host_of[eid]] merged = host["calls"] + calls smap = order_status_map(merged) # ---- LOGIC 1: order-status fit for the injected leaf/prefix ops ---- for c in calls: n = c["name"] oid = c.get("arguments", {}).get("order_id") if not oid: continue oid = "#" + str(oid).lstrip("#").upper() st = smap.get(oid) if st is None: continue if n in STRICT_PENDING and st not in PENDING_OK: logic["open_status"].append((eid, n, oid, st)) if n in PRE_DELIVERY and st not in PENDING_OK + ("shipped",): logic["open_status"].append((eid, n, oid, st)) if n in DELIVERED_OK and st and st != "delivered": logic["delivered_status"].append((eid, n, oid, st)) if st in BAD_STATUS: logic["acted_on_bad"].append((eid, n, oid, st)) # ---- LOGIC 2: modify precedes subscribe (N3) ---- names = [c["name"] for c in calls] if "subscribe_to_restock_alert" in names and "modify_pending_order_items" in names: if names.index("modify_pending_order_items") > names.index("subscribe_to_restock_alert"): logic["modify_before_subscribe"].append((eid, names)) # ---- LOGIC 3: auth/reads before use across the whole conversation ---- # Entities are established by the host's history tool calls and host turn # first; the injected turn may legitimately act on them (later turn). est_users, est_orders = set(), set() cat_o = {"#" + str(x).lstrip("#").upper() for x in CATALOG.get("order_balances", {})} hist_calls = [] for m in (host.get("history") or []): for tc in (m.get("tool_calls") or []): hist_calls.append({"name": tc.get("name"), "arguments": tc.get("arguments", {}), "output": tc.get("output")}) for c in hist_calls + host["calls"]: # pre-establish from prior turns n = c["name"] o = parse(c.get("output")) if n.startswith("find_user_id"): u = (c.get("output") or "").strip().strip('"') if "_" in u: est_users.add(u) if n == "get_user_details" and o and o.get("user_id"): est_users.add(o["user_id"]) if n == "get_order_details" and o and o.get("order_id"): est_orders.add("#" + str(o["order_id"]).lstrip("#").upper()) for c in calls: n = c["name"] a = c.get("arguments", {}) if a.get("user_id") and a["user_id"] not in est_users and not n.startswith("find_user_id") and n != "get_user_details": logic["auth_before_use"].append((eid, n, "user_id", a["user_id"])) if a.get("order_id"): oo = "#" + str(a["order_id"]).lstrip("#").upper() if oo not in est_orders and n != "get_order_details" and oo not in cat_o: logic["auth_before_use"].append((eid, n, "order_id", a["order_id"])) o = parse(c.get("output")) if n.startswith("find_user_id"): u = (c.get("output") or "").strip().strip('"') if "_" in u: est_users.add(u) if n == "get_user_details" and o and o.get("user_id"): est_users.add(o["user_id"]) if n == "get_order_details" and o and o.get("order_id"): est_orders.add("#" + str(o["order_id"]).lstrip("#").upper()) # ---- IO 1: row-level replay (row's own calls reproduce) ---- if G.verify_row(calls): io["row_replay"].append((eid, G.verify_row(calls))) # ---- IO 2: conversation-level replay (host turn + injected turn) ---- s = EpisodeState.from_trajectory({"calls": merged}, CATALOG) for c in merged: n = c["name"] if n not in TOOLS: continue got = TOOLS[n](s, c.get("arguments", {})) rec = parse(c.get("output")) if n in G.FIND: if got != (c.get("output") or "").strip().strip('"'): io["conv_replay"].append((eid, n, "uid")) continue if not isinstance(rec, dict): continue if n in G.FULLMATCH: if got != rec: io["conv_replay"].append((eid, n, "dict-diff")) continue keys = G.CHECK.get(n, []) if any(got.get(k) is None and rec.get(k) is not None for k in keys): continue def _eq(k): g, rv = got.get(k), rec.get(k) if k == "status" and isinstance(g, str) and isinstance(rv, str): return g.replace(" ", "_") == rv.replace(" ", "_") return g == rv bad = [k for k in keys if not _eq(k)] if bad: io["conv_replay"].append((eid, n, {k: (got.get(k), rec.get(k)) for k in bad})) print(f"validated {len(inj)} injected rows (each replayed with its host turn)\n") print("=== LOGIC TESTS ===") for k, v in logic.items(): print(f" {k}: {len(v)} violation(s)") for x in v[:8]: print(" ", x) print("\n=== I/O TESTS ===") for k, v in io.items(): print(f" {k}: {len(v)} mismatch(es)") for x in v[:8]: print(" ", x) total = sum(len(v) for v in logic.values()) + sum(len(v) for v in io.values()) print("\nRESULT:", "ALL CLEAN" if total == 0 else f"{total} ISSUE(S)") return 0 if total == 0 else 1 if __name__ == "__main__": raise SystemExit(main())