File size: 8,384 Bytes
94da461
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
"""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())