Download code/validate_vc_bench.py from badr7/rapidchat-data: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/datasets/badr7/rapidchat-data/resolve/main/code/validate_vc_bench.py
- Command line
-
hf download hf://datasets/badr7/rapidchat-data/code/validate_vc_bench.py
-
curl -L -o validate_vc_bench.py https://huggingface.co/datasets/badr7/rapidchat-data/resolve/main/code/validate_vc_bench.py
19.2 kB
| #!/usr/bin/env python3 | |
| """Checks the generated bench against the real tau2 airline tools and against the written policy, | |
| using logic written separately from the generator. Run with the tau2 environment's python. | |
| usage: validate_vc_bench.py <bench dir> <original airline db.json> <original airline tasks.json> | |
| """ | |
| import collections | |
| import json | |
| import re | |
| import sys | |
| from loguru import logger | |
| logger.remove() | |
| from tau2.data_model.tasks import Task | |
| from tau2.domains.airline.data_model import FlightDB | |
| from tau2.domains.airline.tools import AirlineTools | |
| bench, orig_db_path, orig_tasks_path = sys.argv[1:4] | |
| raw_db = json.load(open(f"{bench}/db.json")) | |
| tasks = json.load(open(f"{bench}/tasks.json")) | |
| splits = json.load(open(f"{bench}/split_tasks.json")) | |
| orig_db = json.load(open(orig_db_path)) | |
| orig_tasks_blob = open(orig_tasks_path).read() | |
| base = FlightDB.model_validate(raw_db) | |
| base_hash = base.get_hash() | |
| ALLOW = {"regular": {"basic_economy": 0, "economy": 1, "business": 2}, | |
| "silver": {"basic_economy": 1, "economy": 2, "business": 3}, | |
| "gold": {"basic_economy": 2, "economy": 3, "business": 4}} | |
| WRITES = {"book_reservation", "cancel_reservation", "update_reservation_flights", "update_reservation_passengers", | |
| "update_reservation_baggages", "send_certificate"} | |
| problems = collections.defaultdict(list) | |
| def st(seg): | |
| return raw_db["flights"][seg["flight_number"]]["dates"][seg["date"]]["status"] | |
| def check(cond, task, msg): | |
| if not cond: | |
| problems[msg].append(task["id"]) | |
| CABIN_WORD = {"basic economy": "basic_economy", "economy": "economy", "business": "business"} | |
| def is_future(r): | |
| return all(s["date"] > "2024-05-15" and st(s) == "available" for s in r["flights"]) | |
| def audit_sweep(task, fam, acts, meta): | |
| """A rule applied across all of one customer's bookings: recompute which bookings it should touch.""" | |
| txt = task["user_scenario"]["instructions"]["task_instructions"] | |
| u = raw_db["users"][meta["users"][0]] | |
| res = [raw_db["reservations"][x] for x in u["reservations"]] | |
| future = [r for r in res if is_future(r)] | |
| check(all(is_future(r) or all(s["date"] < "2024-05-15" for s in r["flights"]) for r in res), task, "sweep customer has a booking that is neither upcoming nor past") | |
| got = [a["arguments"]["reservation_id"] for a in acts] | |
| check(len(got) == len(set(got)), task, "sweep touches a booking twice") | |
| if fam == "sweep_cancel": | |
| covered = ("sick" in txt) or ("storm" in txt) | |
| want = {r["reservation_id"] for r in future if r["created_at"] > "2024-05-14T15:00:00" or r["cabin"] == "business" | |
| or (r["insurance"] == "yes" and covered)} | |
| check(all(a["name"] == "cancel_reservation" for a in acts) and set(got) == want, task, "sweep cancels the wrong set of bookings") | |
| check(len(future) >= 2, task, "sweep has fewer than two upcoming bookings") | |
| else: | |
| m = re.search(r"currently in (basic economy|economy|business) class changed to (basic economy|economy|business) class", txt) | |
| src, dst = CABIN_WORD[m.group(1)], CABIN_WORD[m.group(2)] | |
| want = {r["reservation_id"] for r in future if r["cabin"] == src} | |
| check(set(got) == want and src != dst, task, "sweep changes the wrong set of bookings") | |
| for a in acts: | |
| r = raw_db["reservations"][a["arguments"]["reservation_id"]] | |
| check(a["name"] == "update_reservation_flights" and a["arguments"]["cabin"] == dst | |
| and a["arguments"]["flights"] == [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]], | |
| task, "sweep cabin change altered flights or used the wrong cabin") | |
| pid = a["arguments"]["payment_id"] | |
| if "originally used" in txt: | |
| check(len(r["payment_history"]) == 1 and pid == r["payment_history"][0]["payment_id"] | |
| and u["payment_methods"][pid]["source"] in ("credit_card", "gift_card"), task, "sweep does not use each booking's original payment method") | |
| else: | |
| check(u["payment_methods"][pid]["source"] == "credit_card", task, "sweep not paid by card") | |
| def audit(task, fam, acts, meta=None): | |
| """Policy re-derived independently of the generator, per scenario family.""" | |
| if fam.startswith("sweep"): | |
| return audit_sweep(task, fam, acts, meta) | |
| if fam in ("upgrade_then_change", "upgrade_and_bags"): | |
| a0, a1 = acts[0]["arguments"], acts[1]["arguments"] | |
| r = raw_db["reservations"][a0["reservation_id"]] | |
| u = raw_db["users"][r["user_id"]] | |
| same = [{"flight_number": x["flight_number"], "date": x["date"]} for x in r["flights"]] | |
| rank = ["basic_economy", "economy", "business"] | |
| check(len(acts) == 2 and acts[0]["name"] == "update_reservation_flights" and a0["flights"] == same | |
| and rank.index(a0["cabin"]) > rank.index(r["cabin"]) and a1["reservation_id"] == a0["reservation_id"] | |
| and all(st(x) == "available" for x in r["flights"]), task, "upgrade step is not a pure cabin upgrade on an untouched booking") | |
| if fam == "upgrade_then_change": | |
| check(r["cabin"] == "basic_economy" and acts[1]["name"] == "update_reservation_flights" and a1["cabin"] == a0["cabin"] | |
| and a1["flights"] != same and len(a1["flights"]) == len(same) and a1["payment_id"] == a0["payment_id"], task, "second step is not a flight change in the upgraded cabin") | |
| for old, n in zip(r["flights"], a1["flights"]): | |
| f = raw_db["flights"][n["flight_number"]] | |
| check((f["origin"], f["destination"]) == (old["origin"], old["destination"]) and f["dates"][n["date"]]["status"] == "available", | |
| task, "upgrade-then-change moves to a wrong or unavailable flight") | |
| if len(a1["flights"]) == 2: | |
| check(a1["flights"][0]["date"] < a1["flights"][1]["date"], task, "outbound not before return") | |
| else: | |
| pax = len(r["passengers"]) | |
| old_free, new_free = ALLOW[u["membership"]][r["cabin"]] * pax, ALLOW[u["membership"]][a0["cabin"]] * pax | |
| check(acts[1]["name"] == "update_reservation_baggages" and r["nonfree_baggages"] == 0 and a1["nonfree_baggages"] == 0 | |
| and old_free < a1["total_baggages"] <= new_free and a1["total_baggages"] > r["total_baggages"], task, "bags are not free only under the new cabin") | |
| return | |
| if fam == "multi_change": | |
| names = [a["name"] for a in acts] | |
| check(names[:2] == ["update_reservation_flights", "update_reservation_passengers"] and len(set(a["arguments"]["reservation_id"] for a in acts)) == 1, | |
| task, "multi-change has the wrong actions") | |
| audit(task, "flight_change", acts[:1]) | |
| audit(task, "passenger_update", acts[1:2]) | |
| if len(acts) == 3: | |
| b = acts[2]["arguments"] | |
| r = raw_db["reservations"][b["reservation_id"]] | |
| free = ALLOW[raw_db["users"][r["user_id"]]["membership"]][r["cabin"]] * len(r["passengers"]) | |
| check(acts[2]["name"] == "update_reservation_baggages" and r["total_baggages"] < b["total_baggages"] <= free | |
| and b["nonfree_baggages"] == 0 and r["nonfree_baggages"] == 0, task, "multi-change bag add is not free") | |
| return | |
| args = acts[0]["arguments"] if acts else {} | |
| txt = task["user_scenario"]["instructions"] | |
| rid = args.get("reservation_id") or (meta or {}).get("reservation") | |
| m = re.search(r"reservation id is ([A-Z0-9]{6})", txt["known_info"]) | |
| if m: | |
| check(m.group(1) == rid, task, "booking code told to the customer differs from the scenario's booking") | |
| if not fam.startswith("booking"): | |
| check(rid in raw_db["reservations"], task, "scenario does not point at a booking") | |
| r = raw_db["reservations"].get(rid) if rid else None | |
| u = raw_db["users"][r["user_id"]] if r else None | |
| if fam.startswith("cancel") and r: | |
| flown = any(st(s) in ("landed", "flying") for s in r["flights"]) | |
| covered_reason = ("sick" in txt["task_instructions"]) or ("storm" in txt["task_instructions"]) | |
| allowed = (r["created_at"] > "2024-05-14T15:00:00" or r["cabin"] == "business" | |
| or any(st(s) == "cancelled" for s in r["flights"]) or (r["insurance"] == "yes" and covered_reason)) | |
| want = "cancel_flown" if flown else ("cancel_ok" if allowed else "cancel_denied") | |
| check(fam == want, task, "cancellation outcome disagrees with policy") | |
| check((fam == "cancel_ok") == bool(acts), task, "cancellation gold action presence wrong") | |
| if fam in ("flight_change", "flight_change_dest_first"): | |
| new = args["flights"] | |
| check(r["cabin"] != "basic_economy" and args["cabin"] == r["cabin"], task, "flight change on basic economy or cabin altered") | |
| check(len(new) == len(r["flights"]), task, "flight change altered the number of flights") | |
| check(not any(st(s) in ("landed", "flying") for s in r["flights"]), task, "flight change on a flown trip") | |
| for old, n in zip(r["flights"], new): | |
| f = raw_db["flights"][n["flight_number"]] | |
| check((f["origin"], f["destination"]) == (old["origin"], old["destination"]), task, "flight change altered a route") | |
| check(f["dates"][n["date"]]["status"] == "available", task, "flight change to an unavailable flight") | |
| check(new != [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]], task, "flight change is a no-op") | |
| check(u["payment_methods"][args["payment_id"]]["source"] in ("credit_card", "gift_card"), task, "flight change paid with a certificate") | |
| if len(new) == 2: | |
| check(new[0]["date"] < new[1]["date"], task, "outbound not before return") | |
| if fam == "flight_change_denied" and r: | |
| check(r["cabin"] == "basic_economy" and not acts, task, "flight-change refusal not on basic economy") | |
| if fam in ("cabin_change", "cabin_partial") and acts: | |
| check(args["cabin"] != r["cabin"], task, "cabin change keeps the cabin") | |
| check(args["flights"] == [{"flight_number": s["flight_number"], "date": s["date"]} for s in r["flights"]], task, "cabin change altered flights") | |
| check(not any(st(s) in ("landed", "flying") for s in r["flights"]), task, "cabin change on a flown trip") | |
| if fam == "baggage_add": | |
| free = ALLOW[u["membership"]][r["cabin"]] * len(r["passengers"]) | |
| check(args["total_baggages"] > r["total_baggages"], task, "baggage add does not add") | |
| check(args["nonfree_baggages"] == max(0, args["total_baggages"] - free), task, "baggage paid count wrong") | |
| if fam == "passenger_update": | |
| check(len(args["passengers"]) == len(r["passengers"]) and args["passengers"] != r["passengers"], task, "passenger update wrong shape") | |
| if fam.startswith("booking"): | |
| bu = raw_db["users"][args["user_id"]] | |
| kinds = collections.Counter(bu["payment_methods"][p["payment_id"]]["source"] for p in args["payment_methods"]) | |
| check(kinds["certificate"] <= 1 and kinds["credit_card"] <= 1 and kinds["gift_card"] <= 3, task, "booking payment mix breaks policy") | |
| check(1 <= len(args["passengers"]) <= 5, task, "booking passenger count") | |
| free = ALLOW[bu["membership"]][args["cabin"]] * len(args["passengers"]) | |
| check(args["nonfree_baggages"] == max(0, args["total_baggages"] - free), task, "booking paid bags wrong") | |
| price = sum(raw_db["flights"][f["flight_number"]]["dates"][f["date"]]["prices"][args["cabin"]] for f in args["flights"]) | |
| total = price * len(args["passengers"]) + (30 * len(args["passengers"]) if args["insurance"] == "yes" else 0) + 50 * args["nonfree_baggages"] | |
| check(sum(p["amount"] for p in args["payment_methods"]) == total, task, "booking total wrong") | |
| legs = [raw_db["flights"][f["flight_number"]] for f in args["flights"]] | |
| if args["flight_type"] == "round_trip": | |
| check(len(legs) == 2 and (legs[0]["origin"], legs[0]["destination"]) == (args["origin"], args["destination"]) | |
| and (legs[1]["origin"], legs[1]["destination"]) == (args["destination"], args["origin"]) | |
| and args["flights"][0]["date"] < args["flights"][1]["date"], task, "booking return leg wrong") | |
| else: | |
| check(legs[0]["origin"] == args["origin"] and legs[-1]["destination"] == args["destination"] | |
| and all(a["destination"] == b["origin"] for a, b in zip(legs, legs[1:])), task, "booking route mismatch") | |
| if len(legs) == 2: | |
| check(fam == "booking_one_stop" and args["flights"][0]["date"] == args["flights"][1]["date"] | |
| and legs[1]["scheduled_departure_time_est"] >= legs[0]["scheduled_arrival_time_est"], task, "one-stop connection does not connect") | |
| if fam == "booking_by_rule": | |
| day, cab = args["flights"][0]["date"], args["cabin"] | |
| listed = [f for f in raw_db["flights"].values() if (f["origin"], f["destination"]) == (args["origin"], args["destination"]) | |
| and f["dates"].get(day, {}).get("status") == "available"] | |
| ti = txt["task_instructions"] | |
| if "cheapest" in ti: | |
| best = min(listed, key=lambda f: f["dates"][day]["prices"][cab]) | |
| tie = sum(f["dates"][day]["prices"][cab] == best["dates"][day]["prices"][cab] for f in listed) | |
| else: | |
| pick = min if "earliest" in ti else max | |
| best = pick(listed, key=lambda f: f["scheduled_departure_time_est"]) | |
| tie = sum(f["scheduled_departure_time_est"] == best["scheduled_departure_time_est"] for f in listed) | |
| check(best["flight_number"] == args["flights"][0]["flight_number"] and tie == 1 and len(listed) >= 2, task, "rule-based booking picks the wrong flight") | |
| if fam.startswith("compensation") and r: | |
| cancelled = any(st(s) == "cancelled" for s in r["flights"]) | |
| eligible = u["membership"] in ("silver", "gold") or r["insurance"] == "yes" or r["cabin"] == "business" | |
| want = "compensation_false_claim" if not cancelled else ("compensation_ok" if eligible else "compensation_denied") | |
| check(fam == want, task, "compensation outcome disagrees with policy") | |
| if acts: | |
| check(args["amount"] == 100 * len(r["passengers"]) and args["user_id"] == r["user_id"], task, "compensation amount or recipient wrong") | |
| if fam in ("baggage_remove_denied", "insurance_add_denied", "passenger_count_denied"): | |
| check(not acts, task, "refusal scenario has a gold action") | |
| replay_errors, fam_count, write_count, said_count = [], collections.Counter(), collections.Counter(), collections.Counter() | |
| ids = set() | |
| tools = AirlineTools(base.model_copy(deep=True)) | |
| full_resets = 0 | |
| for n, t in enumerate(tasks): | |
| if n % 200 == 0: | |
| print(" ...", n, "of", len(tasks), flush=True) | |
| Task.model_validate(t) | |
| assert t["id"] not in ids, "duplicate id " + t["id"] | |
| ids.add(t["id"]) | |
| meta = json.loads(t["description"]["notes"]) | |
| fam = meta["family"] | |
| fam_count[fam] += 1 | |
| acts = t["evaluation_criteria"]["actions"] | |
| # snapshot only the records a task can touch; a full hash afterwards proves the restore was complete | |
| db = tools.db | |
| touched = set(meta["users"]) | {a["arguments"]["user_id"] for a in acts if "user_id" in a["arguments"]} | |
| for a in acts: | |
| rid = a["arguments"].get("reservation_id") | |
| if rid in db.reservations: | |
| touched.add(db.reservations[rid].user_id) | |
| saved_users = {u: db.users[u].model_copy(deep=True) for u in touched if u in db.users} | |
| saved_res = {r: db.reservations[r].model_copy(deep=True) for u in saved_users.values() for r in u.reservations if r in db.reservations} | |
| res_keys = set(db.reservations) | |
| paid_before = {r: len(v.payment_history) for r, v in saved_res.items()} | |
| err = None | |
| try: | |
| for a in acts: | |
| assert a["name"] in WRITES, "unexpected gold tool " + a["name"] | |
| getattr(tools, a["name"])(**json.loads(json.dumps(a["arguments"]))) | |
| except Exception as e: | |
| err = repr(e)[:160] | |
| changed = db.get_hash() != base_hash | |
| charged = sum(p.amount for r, k in paid_before.items() for p in db.reservations[r].payment_history[k:]) | |
| for r in set(db.reservations) - res_keys: | |
| del db.reservations[r] | |
| db.reservations.update(saved_res) | |
| db.users.update(saved_users) | |
| if changed and db.get_hash() != base_hash: | |
| tools = AirlineTools(base.model_copy(deep=True)) | |
| full_resets += 1 | |
| if err: | |
| replay_errors.append((t["id"], err)) | |
| continue | |
| check(changed == bool(acts), t, "database change does not match gold actions") | |
| write_count["write" if acts else "no write"] += 1 | |
| for c in t["evaluation_criteria"]["communicate_info"]: | |
| check(c.isdigit() and int(c) > 0, t, "amount to be said aloud is not a positive number") | |
| if fam in ("baggage_add", "cabin_change", "sweep_cabin"): | |
| check(not err and int(c) == abs(charged), t, "amount to be said aloud differs from what the tools charge") | |
| said_count[fam] += 1 | |
| if fam == "two_requests": | |
| continue | |
| audit(t, fam, acts, meta) | |
| print("full database resets needed:", full_resets) | |
| blob = json.dumps(tasks) + json.dumps(raw_db) | |
| leaked_users = [u for u in orig_db["users"] if u in blob] | |
| leaked_res = [r for r in orig_db["reservations"] if '"%s"' % r in blob or " %s." % r in blob] | |
| old_flights = sorted(set(re.findall(r"HAT[0-2]\d\d\b|HAT300\b", blob))) | |
| bench_users_in_tasks = [u for u in raw_db["users"] if u in json.dumps(tasks)] | |
| who = {s: {x for t in tasks if t["id"] in set(splits[s]) for x in json.loads(t["description"]["notes"])["users"]} for s in ("train", "holdout")} | |
| who["devil"] = who["holdout"] | |
| assert set(splits["devil"]) <= set(splits["holdout"]) and not set(splits["train"]) & set(splits["holdout"]) | |
| print("tasks:", len(tasks), "| valid tau2 Task objects: all | families:", len(fam_count)) | |
| print("gold replays on the real tools: %d ok, %d failed" % (len(tasks) - len(replay_errors), len(replay_errors))) | |
| for e in replay_errors[:8]: | |
| print(" REPLAY ERROR", e) | |
| print("write / no-write:", dict(write_count), "| amounts to be said aloud, checked against the tools:", dict(said_count)) | |
| print("policy audit problems:", {k: len(v) for k, v in problems.items()} or "none") | |
| for k, v in list(problems.items())[:6]: | |
| print(" ", k, "->", v[:4]) | |
| print("original customer ids present:", len(leaked_users), "| original booking codes present:", len(leaked_res), "| original flight numbers present:", len(old_flights)) | |
| print("customers used in tasks:", len(bench_users_in_tasks), "| train customers:", len(who["train"]), "| devil customers:", len(who["devil"]), | |
| "| shared between train and devil:", len(who["train"] & who["devil"])) | |
| print("splits:", {k: len(v) for k, v in splits.items()}) | |
| bad = len(replay_errors) + sum(len(v) for v in problems.values()) + len(leaked_users) + len(leaked_res) + len(old_flights) + len(who["train"] & who["devil"]) | |
| print("VALIDATION", "PASSED" if bad == 0 else "FAILED (%d issues)" % bad) | |