File size: 5,922 Bytes
ff376c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compare every generated callable with direct pinned-tool dispatch on equal state."""

import argparse
import importlib.util
import inspect
import json
from pathlib import Path

from expander.environment import Tau2Environment
from expander.snapshots import file_hash, load_snapshot
from expander.tau_expansion import digest


def load_module(path):
    spec = importlib.util.spec_from_file_location("generated_tau2_tools", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def validate(bundle, checkout, python):
    bundle = Path(bundle)
    snapshot = load_snapshot(bundle / "snapshot", checkout)
    if snapshot.domain != "retail":
        raise ValueError("This parity fixture covers retail tools only")
    original = json.loads((Path(checkout) / "data/tau2/domains/retail/db.json").read_text())
    generated_users = set(snapshot.state["users"]) - set(original["users"])
    module = load_module(bundle / "tools.py")
    uid = next(
        key
        for key, user in snapshot.state["users"].items()
        if key in generated_users
        and any(snapshot.state["orders"][order]["status"] == "pending" for order in user["orders"])
    )
    user = snapshot.state["users"][uid]
    order_id = next(
        key for key in user["orders"] if snapshot.state["orders"][key]["status"] == "pending"
    )
    order = snapshot.state["orders"][order_id]
    item = order["items"][0]
    payment = order["payment_history"][0]["payment_method_id"]
    address = user["address"] | {"address1": "123 Adapter Test Street"}
    cases = {
        "calculate": {"expression": "2 + 3"},
        "cancel_pending_order": {"order_id": order_id, "reason": "ordered by mistake"},
        "exchange_delivered_order_items": {
            "order_id": order_id,
            "item_ids": [item["item_id"]],
            "new_item_ids": [item["item_id"]],
            "payment_method_id": payment,
        },
        "find_user_id_by_name_zip": {
            "first_name": user["name"]["first_name"],
            "last_name": user["name"]["last_name"],
            "zip": user["address"]["zip"],
        },
        "find_user_id_by_email": {"email": user["email"]},
        "get_order_details": {"order_id": order_id},
        "get_product_details": {"product_id": item["product_id"]},
        "get_item_details": {"item_id": item["item_id"]},
        "get_user_details": {"user_id": uid},
        "list_all_product_types": {},
        "modify_pending_order_address": {"order_id": order_id, **address},
        "modify_pending_order_items": {
            "order_id": order_id,
            "item_ids": [item["item_id"]],
            "new_item_ids": [item["item_id"]],
            "payment_method_id": payment,
        },
        "modify_pending_order_payment": {"order_id": order_id, "payment_method_id": payment},
        "modify_user_address": {"user_id": uid, **address},
        "return_delivered_order_items": {
            "order_id": order_id,
            "item_ids": [item["item_id"]],
            "payment_method_id": payment,
        },
        "transfer_to_human_agents": {"summary": "Synthetic adapter routing check"},
    }
    registered = [t["function"]["name"] for t in snapshot.tools]
    assert set(cases) == set(registered)
    rows = []
    original_hash = file_hash(bundle / "snapshot/expanded.json")
    with (
        module.ToolFunctions(checkout, python=python) as tools,
        Tau2Environment(bundle / "snapshot", checkout, python=python) as direct,
    ):
        direct.reset()
        initial_runtime = tools.state()
        for name in registered:
            kwargs = cases[name]
            observation = getattr(tools, name)(**kwargs)
            reference = direct.step({"kind": "tool", "tool": name, "arguments": kwargs})[
                "observation"
            ]
            state = tools.state()
            assert observation == reference, name
            assert state == direct.export_state(), name
            trace = tools._env.trace_since()[-1]
            assert trace["invoked"], name
            rows.append(
                {
                    "name": name,
                    "signature": str(inspect.signature(getattr(tools, name))),
                    "observation_matches": True,
                    "state_matches": True,
                    "native_error": trace["error"],
                    "state_hash": digest(state),
                }
            )
        assert tools.calculate(expression="10 + 2") == "12.0"
        try:
            tools.get_user_details(unexpected="x")
            raise AssertionError("Unknown argument accepted")
        except TypeError:
            pass
        tools.reset()
        assert tools.state() == initial_runtime
    assert file_hash(bundle / "snapshot/expanded.json") == original_hash
    return {
        "passed": True,
        "tools_checked": len(rows),
        "successful_calls": sum(not r["native_error"] for r in rows),
        "matching_native_rejections": sum(r["native_error"] for r in rows),
        "reset_restores_initial": True,
        "snapshot_unchanged": True,
        "model_calls": 0,
        "rows": rows,
        "scope": "All registered methods invoked and matched direct observations and state. Includes native rejection paths; not 16 successful business workflows.",
    }


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--bundle", type=Path, required=True)
    parser.add_argument("--checkout", type=Path, required=True)
    parser.add_argument("--python", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    result = validate(args.bundle, args.checkout, args.python)
    args.output.write_text(json.dumps(result, indent=2) + "\n")
    print(json.dumps({k: v for k, v in result.items() if k != "rows"}))


if __name__ == "__main__":
    main()