File size: 20,451 Bytes
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34cc82
 
 
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34cc82
 
ba70497
 
 
 
 
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
"""The independent grader behind tests/run_given.py (run that; this file has no suite of its own).

It computes expected effects straight from the CSVs and the handbook rules, from hand-written
ground truth (tests/given_cases.json). It does not use tower/graph.py, so it is an independent
check of the tower's own queries.
"""

from __future__ import annotations

import argparse
import csv
import json
import os
import sys
import time
from collections import defaultdict
from datetime import date, timedelta

HITACHI = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, HITACHI)

from enterprise import LAST_IDX, Enterprise, ToolError, date_to_idx, idx_to_date  # noqa: E402
from tower.agents.coordinator import handle_event  # noqa: E402
from tower.graph import WorldGraph  # noqa: E402

DATA = os.path.join(HITACHI, "Data", "hack_the_highway_package", "data")
# Where runs are saved. The online dashboard points this at one visitor's workspace (TOWER_RUNS_DIR).
RUNS = os.environ.get("TOWER_RUNS_DIR") or os.path.join(HITACHI, "runs")
OUT = os.path.join(RUNS, "tests")
WRITE_TOOLS = {"mes.reschedule", "mes.transfer", "dealer.notify", "dealer.stop_sale",
               "crm.assign_loaner", "crm.notify_customer", "quality.hold_lot"}
SUPPLY_TOOLS = {"mes.reschedule", "mes.transfer", "dealer.notify", "crm.assign_loaner"}
QUALITY_TOOLS = {"quality.hold_lot", "dealer.stop_sale", "crm.notify_customer"}
# Loaner priority rank; tiers not listed here (Standard) get no loaner at all.
TIER = {"Platinum": 0, "Gold": 1}


def rd(name):
    """One company CSV as a list of row dicts."""
    with open(os.path.join(DATA, name), newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


class Truth:
    """The company tables, read independently of tower/graph.py."""

    def __init__(self):
        self.orders = {r["production_order_id"]: r for r in rd("production_orders.csv")}
        self.plant_models = defaultdict(set)
        for r in rd("plant_models.csv"):
            self.plant_models[r["plant_id"]].add(r["model"])
        self.slots = {r["plant_id"]: int(r["slots_per_day"]) for r in rd("plants.csv")}
        self.models_using = defaultdict(set)
        for r in rd("bom.csv"):
            self.models_using[r["part_id"]].add(r["model"])
        self.cos_by_po = defaultdict(list)
        self.cos = {}
        for r in rd("customer_orders.csv"):
            self.cos_by_po[r["production_order_id"]].append(r)
            self.cos[r["customer_order_id"]] = r
        self.customers = {r["customer_id"]: r for r in rd("customers.csv")}
        self.pool = {r["dealer_id"]: int(r["loaners_available"]) for r in rd("loaners.csv")}
        self.lots = {r["lot_id"]: r for r in rd("part_lots.csv")}
        self.vehicles = rd("finished_vehicles.csv")

    def idx(self, iso):
        """ISO date -> working-day index (enterprise.py's own mapping)."""
        return date_to_idx(date.fromisoformat(iso))

    def affected(self, inc):
        """{po: earliest allowed index} for one supply incident."""
        if inc["kind"] == "supplier_delay":
            lo, hi = self.idx(inc["blocked_from"]), self.idx(inc["blocked_until"])
            models = self.models_using[inc["part_id"]]
            return {po: hi for po, o in self.orders.items()
                    if o["plant_id"] == inc["plant_id"] and o["model"] in models
                    and lo <= self.idx(o["build_date"]) < hi and self.idx(o["build_date"]) >= 0}
        # Indexes count working days only, so hi + 1 is the next working day: the restart day.
        lo, hi = self.idx(inc["outage_start"]), self.idx(inc["outage_end"])
        return {po: hi + 1 for po, o in self.orders.items()
                if o["plant_id"] == inc["plant_id"] and lo <= self.idx(o["build_date"]) <= hi
                and self.idx(o["build_date"]) >= 0}

    def lot_vehicles(self, lot_id):
        """Rule 6: vehicles at the lot's plant, in its build dates, on models that use its part."""
        lot = self.lots[lot_id]
        models = self.models_using[lot["part_id"]]
        return [v for v in self.vehicles if v["plant_id"] == lot["plant_id"] and v["model"] in models
                and lot["first_build_date"] <= v["build_date"] <= lot["last_build_date"]]


def expected_effects(truth, case):
    """What the handbook says must happen for one case, from its hand-written incidents.

    Returns earliest allowed day per production order, dealer -> order ids to notify, loaner
    order ids, lots, dealer -> VINs to stop, and owners to contact. Exact dates are not fixed
    here; grade() checks them against the free slots instead.
    """
    inc_list = case["expect"]["incidents"]
    earliest = {}
    for inc in inc_list:
        if inc["kind"] in ("supplier_delay", "plant_outage"):
            for po, e in truth.affected(inc).items():
                earliest[po] = max(earliest.get(po, 0), e)
    cos = [co for po in earliest for co in truth.cos_by_po[po]]
    notify = defaultdict(set)
    for co in cos:
        notify[co["dealer_id"]].add(co["customer_order_id"])
    # Loaners: per dealer, sort eligible orders by (tier rank, promised date, id) and take as
    # many as the pool holds.
    entitled = defaultdict(list)
    for co in cos:
        tier = truth.customers[co["customer_id"]]["tier"]
        if tier in TIER:
            entitled[co["dealer_id"]].append((TIER[tier], co["promised_date"], co["customer_order_id"]))
    loaners = set()
    for dealer, rows in entitled.items():
        loaners.update(r[2] for r in sorted(rows)[: truth.pool[dealer]])
    lots, stop, owners = set(), defaultdict(set), set()
    for inc in inc_list:
        if inc["kind"] == "quality_hold":
            for lot in inc["lots"]:
                lots.add(lot)
                for v in truth.lot_vehicles(lot):
                    if v["status"] == "in_stock":
                        stop[v["dealer_id"]].add(v["vin"])
                    elif v["status"] == "sold" and v["customer_id"]:
                        owners.add(v["customer_id"])
    return {"earliest": earliest, "notify": dict(notify), "loaners": loaners,
            "lots": lots, "stop": dict(stop), "owners": owners}


class Logged:
    """Enterprise wrapper that records every call, including the error text of a failed one."""

    def __init__(self, enterprise):
        self.enterprise, self.records = enterprise, []

    def call(self, event_id, tool, args):
        # Append before calling, so a failing call is still in the log, marked ok=False.
        row = {"event_id": event_id, "tool": tool, "args": args, "ok": True}
        self.records.append(row)
        try:
            return self.enterprise.call(event_id, tool, args)
        except ToolError as exc:
            row["ok"], row["error"] = False, str(exc)
            raise


def grade(truth, case, rows, trace, state):
    """Return (verdict, fails, warnings, stats).

    A fail is a handbook violation; a warning is legal but worth a look (a failed call, a later
    slot than needed). state is the enterprise's end state for the case, used for slot checks.
    """
    fails, warns = [], []
    exp = expected_effects(truth, case)
    tools = [r["tool"] for r in rows]
    writes = [r for r in rows if r["tool"] in WRITE_TOOLS and r["ok"]]
    failed = [r for r in rows if not r["ok"]]
    if failed:
        warns.append(f"{len(failed)} failed call(s): " + "; ".join(
            f"{r['tool']} -> {r.get('error')}" for r in failed[:3]))

    # Classification and fields.
    got_inc = [i for i in trace["incidents"] if i["kind"] in ("supplier_delay", "plant_outage", "quality_hold")]
    want_inc = case["expect"]["incidents"]
    got_kinds = sorted(i["kind"] for i in got_inc)
    want_kinds = sorted(i["kind"] for i in want_inc)
    if got_kinds != want_kinds:
        fails.append(f"incident kinds {got_kinds or ['none']} expected {want_kinds or ['none']}")
    else:
        for want in want_inc:
            if want["kind"] == "quality_hold":
                continue
            # Several incidents of one kind (a compound case): compare with the closest one.
            cands = [g for g in got_inc if g["kind"] == want["kind"]]
            best = min(cands, key=lambda g: sum(g.get(k) != v for k, v in want.items()))
            diffs = [f"{k}={best.get(k)} (expected {v})" for k, v in want.items() if k != "kind" and best.get(k) != v]
            if diffs:
                fails.append(f"{want['kind']} fields: " + ", ".join(diffs))

    # Escalation.
    escalated = "escalate" in tools
    if case["expect"]["escalate"] and not escalated:
        fails.append("expected an escalate, none made")
    if not case["expect"]["escalate"] and escalated:
        fails.append("escalated although the event is actionable / noise")

    # Noise and unconfirmed cases stop here: any write at all is a fail.
    if not want_inc:
        if writes:
            fails.append(f"{len(writes)} write call(s) on a non-actionable event: {sorted(set(r['tool'] for r in writes))}")
        stats = {"writes": len(writes), "calls": len(rows)}
        return ("PASS" if not fails else "FAIL"), fails, warns, stats

    # Production orders.
    moved = {}
    for r in rows:
        if r["ok"] and r["tool"] in ("mes.reschedule", "mes.transfer"):
            moved[r["args"]["production_order_id"]] = r
    want_po = set(exp["earliest"])
    extra, missing = sorted(set(moved) - want_po), sorted(want_po - set(moved))
    if extra:
        fails.append(f"{len(extra)} unaffected PO(s) moved: {extra[:5]}")
    if missing:
        fails.append(f"{len(missing)} affected PO(s) not moved: {missing[:5]}")
    n_res = n_tr = 0
    for po, r in moved.items():
        if po not in want_po:
            continue
        home = truth.orders[po]["plant_id"]
        model = truth.orders[po]["model"]
        new_idx = truth.idx(r["args"]["new_date"])
        e = exp["earliest"][po]
        if r["tool"] == "mes.reschedule":
            n_res += 1
            if new_idx < e:
                fails.append(f"{po} rescheduled to {r['args']['new_date']}, before the disruption ends")
            # Only a warning: a slot that is free in the end state may have been taken by an earlier
            # order when this one was placed.
            free_earlier = [i for i in range(e, new_idx) if len(state["slots"][(home, i)]) < truth.slots[home]]
            if free_earlier:
                warns.append(f"{po} rescheduled to {r['args']['new_date']} though {home} still has a free slot on "
                             f"{idx_to_date(free_earlier[0])}")
        else:
            n_tr += 1
            dest = r["args"]["to_plant_id"]
            if model not in truth.plant_models[dest]:
                fails.append(f"{po} transferred to {dest}, which does not build {model}")
            # Rule 3: a transfer is allowed only when the home plant has no free day left. This uses
            # the end state, so a slot freed later in the same event also counts against it.
            home_free = [i for i in range(e, LAST_IDX + 1) if len(state["slots"][(home, i)]) < truth.slots[home]]
            if home_free:
                fails.append(f"{po} transferred but {home} has a free slot on {idx_to_date(home_free[0])} (end state)")

    # Dealers.
    notices = defaultdict(list)
    for r in rows:
        if r["ok"] and r["tool"] == "dealer.notify":
            notices[r["args"]["dealer_id"]].append(set(r["args"]["customer_order_ids"]))
    for d, lists in notices.items():
        if len(lists) > 1:
            fails.append(f"dealer {d} notified {len(lists)} times")
    if set(notices) != set(exp["notify"]):
        fails.append(f"dealer set: extra {sorted(set(notices) - set(exp['notify']))[:5]}, "
                     f"missing {sorted(set(exp['notify']) - set(notices))[:5]}")
    for d in sorted(set(notices) & set(exp["notify"])):  # sorted: same report every run
        got = set().union(*notices[d])
        if got != exp["notify"][d]:
            fails.append(f"dealer {d} order list: extra {sorted(got - exp['notify'][d])[:3]}, "
                         f"missing {sorted(exp['notify'][d] - got)[:3]}")

    # Loaners.
    got_loan = {r["args"]["customer_order_id"] for r in rows if r["ok"] and r["tool"] == "crm.assign_loaner"}
    if got_loan != exp["loaners"]:
        fails.append(f"loaners: extra {sorted(got_loan - exp['loaners'])[:5]}, "
                     f"missing {sorted(exp['loaners'] - got_loan)[:5]}")

    # Quality.
    got_lots = {r["args"]["lot_id"] for r in rows if r["ok"] and r["tool"] == "quality.hold_lot"}
    if got_lots != exp["lots"]:
        fails.append(f"lots held {sorted(got_lots)} expected {sorted(exp['lots'])}")
    stops = defaultdict(set)
    for r in rows:
        if r["ok"] and r["tool"] == "dealer.stop_sale":
            stops[r["args"]["dealer_id"]].update(r["args"]["vins"])
    if stops != exp["stop"]:
        got_v = set().union(*stops.values()) if stops else set()
        want_v = set().union(*exp["stop"].values()) if exp["stop"] else set()
        fails.append(f"stop-sale VINs: got {len(got_v)} expected {len(want_v)} "
                     f"(extra {sorted(got_v - want_v)[:3]}, missing {sorted(want_v - got_v)[:3]})")
    owners = {r["args"]["customer_id"] for r in rows if r["ok"] and r["tool"] == "crm.notify_customer"}
    if owners != exp["owners"]:
        fails.append(f"owners notified: got {len(owners)} expected {len(exp['owners'])} "
                     f"(extra {sorted(owners - exp['owners'])[:3]}, missing {sorted(exp['owners'] - owners)[:3]})")

    # Rule 9 (completeness) is a warning only: a tiny incident can legitimately need fewer kinds.
    kinds = {r["tool"] for r in writes}
    if len(kinds) < 3:
        warns.append(f"only {len(kinds)} kind(s) of write action (handbook rule 9 wants 3)")

    stats = {"writes": len(writes), "calls": len(rows), "moved": len(moved), "rescheduled": n_res,
             "transferred": n_tr, "expected_moves": len(want_po), "dealers": len(notices),
             "loaners": len(got_loan), "lots": sorted(got_lots), "stop_sale_vins": sum(len(v) for v in stops.values()),
             "owners": len(owners)}
    return ("PASS" if not fails else "FAIL"), fails, warns, stats


def run(reader_name, cases, truth, graph):
    """Run every case through handle_event with one reader, grade it, and save the run files.

    One Enterprise serves all cases; it keeps a separate world per event id, and the case id
    is the event id.
    """
    llm = None
    if reader_name == "llm":
        from tower.agents.llm_reader import LLMReader
        llm = LLMReader()
    enterprise = Enterprise(DATA)
    logged = Logged(enterprise)
    results, traces = [], []
    for case in cases:
        event = {"event_id": case["id"], "received_at": "2027-03-08T08:00:00",
                 "source": case["source"], "text": case["text"]}
        # This case's calls are the log rows added from here on.
        start = len(logged.records)
        t0 = time.time()
        try:
            trace = handle_event(graph, logged, event, llm).to_dict()
            crash = None
        except Exception as exc:  # report crashes as failures, keep going
            trace = {"event_id": case["id"], "incidents": [], "summary": "", "classification": "CRASH"}
            crash = f"{type(exc).__name__}: {exc}"
        rows = logged.records[start:]
        verdict, fails, warns, stats = grade(truth, case, rows, trace, enterprise.state(case["id"]))
        if crash:
            verdict, fails = "FAIL", [f"crashed: {crash}"] + fails
        traces.append(trace)
        results.append({
            "id": case["id"], "category": case["category"], "edge": case.get("edge"),
            "verdict": verdict, "fails": fails, "warnings": warns, "stats": stats,
            "classification": trace.get("classification"),
            "readers": [i.get("reader") for i in trace.get("incidents", [])],
            "parsed": [{k: v for k, v in i.items() if v and k not in ("summary", "evidence")}
                       for i in trace.get("incidents", [])],
            "summary": trace.get("summary"), "seconds": round(time.time() - t0, 1),
        })
        print(f"[{reader_name}] {case['id']} {verdict:4} {case['category']:15} {trace.get('classification')}")
    out = os.path.join(OUT, reader_name if llm is None else "llm_" + llm.model.replace(":", "_"))
    os.makedirs(out, exist_ok=True)
    with open(os.path.join(out, "action_log.jsonl"), "w") as f:
        for r in logged.records:
            f.write(json.dumps(r) + "\n")
    json.dump(traces, open(os.path.join(out, "traces.json"), "w"), indent=2)
    json.dump(results, open(os.path.join(out, "results.json"), "w"), indent=2)
    log_run(os.path.basename(OUT), os.path.basename(out), results)
    return results


def grade_saved(run_dir, cases, truth, model):
    """Grade a run the tower already made (traces.json + action_log.jsonl in run_dir) without reading
    the events again: its action log is replayed on a fresh copy of the world, as the judges do, and
    each event is graded exactly as run() grades it. Saved under OUT/llm_<model>."""
    traces_by_id = {t["event_id"]: t for t in json.load(open(os.path.join(run_dir, "traces.json")))}
    saved = [json.loads(line) for line in open(os.path.join(run_dir, "action_log.jsonl")) if line.strip()]
    enterprise = Enterprise(DATA)
    logged = Logged(enterprise)
    results, traces = [], []
    for case in cases:
        trace = traces_by_id.get(case["id"])
        start = len(logged.records)
        for row in (r for r in saved if r.get("event_id") == case["id"]):
            try:
                logged.call(case["id"], row["tool"], row["args"])
            except ToolError:
                pass
        rows = logged.records[start:]
        if trace is None:
            trace = {"event_id": case["id"], "incidents": [], "summary": "", "classification": "MISSING"}
        verdict, fails, warns, stats = grade(truth, case, rows, trace, enterprise.state(case["id"]))
        if trace.get("classification") == "MISSING":
            verdict, fails = "FAIL", [f"{case['id']} is not in {run_dir}"] + fails
        traces.append(trace)
        results.append({
            "id": case["id"], "category": case["category"], "edge": case.get("edge"),
            "verdict": verdict, "fails": fails, "warnings": warns, "stats": stats,
            "classification": trace.get("classification"),
            "readers": [i.get("reader") for i in trace.get("incidents", [])],
            "parsed": [{k: v for k, v in i.items() if v and k not in ("summary", "evidence")}
                       for i in trace.get("incidents", [])],
            "summary": trace.get("summary"), "seconds": 0.0,
        })
        print(f"[llm] {case['id']} {verdict:4} {case['category']:15} {trace.get('classification')}")
    out = os.path.join(OUT, "llm_" + model.replace(":", "_"))
    os.makedirs(out, exist_ok=True)
    with open(os.path.join(out, "action_log.jsonl"), "w") as f:
        for r in logged.records:
            f.write(json.dumps(r) + "\n")
    json.dump(traces, open(os.path.join(out, "traces.json"), "w"), indent=2)
    json.dump(results, open(os.path.join(out, "results.json"), "w"), indent=2)
    log_run(os.path.basename(OUT), os.path.basename(out), results)
    return results


# runs/ folder -> the dashboard's suite id.
SUITE_OF_FOLDER = {"given": "given", "blind": "blind", "blind100": "blind100", "tests": "generated", "holdout": "holdout",
                    "holdout2": "holdout2", "stress": "stress", "accuracy": "accuracy"}


def log_run(folder, reader, results):
    """Append one line per test run to runs/test_log.jsonl: the history the dashboard's run log shows."""
    by_cat = defaultdict(lambda: [0, 0])
    for r in results:
        by_cat[r["category"]][0] += r["verdict"] == "PASS"
        by_cat[r["category"]][1] += 1
    entry = {"time": time.strftime("%Y-%m-%d %H:%M:%S"), "suite": SUITE_OF_FOLDER.get(folder, folder),
             "folder": folder, "reader": reader, "passed": sum(r["verdict"] == "PASS" for r in results),
             "total": len(results), "by_category": dict(by_cat)}
    os.makedirs(RUNS, exist_ok=True)
    with open(os.path.join(RUNS, "test_log.jsonl"), "a", encoding="utf-8") as handle:
        handle.write(json.dumps(entry) + "\n")


if __name__ == "__main__":
    raise SystemExit("The only suite is the 15 given events: python tests/run_given.py")