"""Validate ToolFault-Bench parquet files. python scripts/validate.py data Checks structure, label rules, tool-call/schema consistency, duplicates, label leakage, and re-verifies the property each subtype claims (arithmetic, timestamps, pagination, ID transpositions, ambiguity, injection presence). Exits non-zero on any failure. """ from __future__ import annotations import hashlib import json import sys from collections import Counter from datetime import datetime, timezone import pandas as pd FAULTS = {"none", "timeout", "server_error", "rate_limited", "auth_error", "invalid_arguments", "not_found", "partial_result", "schema_drift", "stale_data", "inconsistent_result", "mismatched_entity", "prompt_injection"} ACTIONS = {"proceed", "adapt_and_proceed", "retry_same", "wait_then_retry", "retry_with_fixed_args", "fetch_more", "verify_before_retry", "cross_check", "ignore_injection_and_proceed", "ask_user", "stop_and_report"} LEAK_TERMS = ["schema_drift", "stale_data", "inconsistent_result", "mismatched_entity", "prompt_injection", "partial_result", "invalid_arguments", "verify_before_retry", "cross_check", "fetch_more", "ignore_injection", "retry_with_fixed_args", "adapt_and_proceed", "stop_and_report", "wait_then_retry", "hard_negative", "fault_type", "next_action"] WRITE_TOOLS = {"create_transfer", "place_order", "schedule_payment", "escalate_to_case", "send_reply", "rollback_service"} errors: list[str] = [] def fail(row, msg): errors.append(f"{row['id']} [{row['subtype']}] {msg}") def ts(s): return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) def close(a, b, tol=0.011): return abs(a - b) <= tol def arith_violations(tool, r): v = [] if tool == "get_statement": exp = r["opening_balance"] + r["total_credits"] - r["total_debits"] - r["fees_charged"] + r["interest_paid"] if not close(exp, r["closing_balance"]): v.append(f"closing {r['closing_balance']} != {exp:.2f}") elif tool == "get_portfolio_summary": for p in r["positions"]: if not close(p["quantity"] * p["last_price"], p["market_value"]): v.append(f"{p['symbol']} mv") if not close(sum(p["market_value"] for p in r["positions"]), r["total_market_value"], 0.05): v.append("tmv") if not close(r["total_market_value"] + r["cash"], r["total_account_value"]): v.append("tav") elif tool == "get_invoice": for l in r["line_items"]: if not close(l["quantity"] * l["unit_price"], l["amount"]): v.append("line") if not close(sum(l["amount"] for l in r["line_items"]), r["subtotal"], 0.05): v.append("subtotal") if not close(r["subtotal"] + r["tax"] + r["shipping"], r["total"]): v.append("total") if not close(r["total"] - r["amount_paid"], r["balance_due"]): v.append("balance_due") elif tool == "get_activity_summary": if not close(r["cash_deposits"] + r["wires_in"] + r["ach_in"], r["total_inflow"]): v.append("inflow") if not close(r["wires_out"] + r["ach_out"] + r["card_spend"], r["total_outflow"]): v.append("outflow") if not close(r["total_inflow"] - r["total_outflow"], r["net_flow"]): v.append("net") elif tool == "get_queue_stats": if r["open_at_start"] + r["opened"] - r["solved"] != r["open_at_end"]: v.append("open_at_end") elif tool == "get_error_budget": err = r["failed_requests"] / r["total_requests"] * 100 if abs(err - r["error_rate_pct"]) > max(0.0001, 0.02 * err): v.append("error_rate") allowed = r["total_requests"] * (1 - r["slo_target_pct"] / 100) rem = (allowed - r["failed_requests"]) / allowed * 100 if abs(rem - r["budget_remaining_pct"]) > 0.2: v.append("budget_remaining") else: v.append(f"no arithmetic checker for {tool}") return v def _all_keys(o): if isinstance(o, dict): for k, v in o.items(): yield k yield from _all_keys(v) elif isinstance(o, list): for v in o: yield from _all_keys(v) def check_row(row): # ---- labels if row["fault_type"] not in FAULTS: fail(row, "bad fault_type") acc, crit = list(row["acceptable_next_actions"]), list(row["critical_next_actions"]) if row["next_action"] not in acc: fail(row, "gold not in acceptable") if set(acc) - ACTIONS or set(crit) - ACTIONS: fail(row, "unknown action label") if set(acc) & set(crit): fail(row, "acceptable/critical overlap") if row["is_hard_negative"] != (row["fault_type"] == "none"): fail(row, "hard-negative flag mismatch") # ---- messages / tools tools = json.loads(row["tools"]) msgs = json.loads(row["messages"]) schema = {t["function"]["name"]: t["function"]["parameters"] for t in tools} if msgs[0]["role"] != "system" or msgs[1]["role"] != "user" or msgs[-1]["role"] != "tool": fail(row, "message roles") if msgs[1]["content"] != row["user_request"]: fail(row, "user_request mismatch") if row["current_time"] not in msgs[0]["content"]: fail(row, "current time missing from system prompt") pending = {} last_tc = msgs[-2]["tool_calls"][0] for m in msgs[2:]: if m["role"] == "assistant": for tc in m["tool_calls"]: name, args = tc["function"]["name"], json.loads(tc["function"]["arguments"]) if name not in schema: fail(row, f"call to unknown tool {name}") continue props, req = schema[name]["properties"], schema[name]["required"] if set(args) - set(props): fail(row, f"{name}: unknown args {set(args) - set(props)}") missing = set(req) - set(args) if missing and not (row["subtype"] == "invalid_args" and tc is last_tc): fail(row, f"{name}: missing required {missing}") pending[tc["id"]] = name elif m["role"] == "tool": if pending.get(m["tool_call_id"]) != m["name"]: fail(row, "tool result does not match a pending call") if msgs[-1]["content"] != row["last_tool_result"] or msgs[-1]["name"] != row["last_tool_name"]: fail(row, "last_tool_* mismatch") # ---- leakage: label vocabulary must never appear in model-visible text visible = (row["tools"] + row["messages"]).lower() for term in LEAK_TERMS: if term in visible: fail(row, f"label term leaked: {term}") # ---- subtype-specific semantics sub, last = row["subtype"], row["last_tool_result"] now = ts(row["current_time"]) last_call = json.loads(last_tc["function"]["arguments"]) try: res = json.loads(last) except json.JSONDecodeError: res = None meta = json.loads(row["meta"]) if sub in ("timeout_write", "server_error_write", "auth_forbidden", "none_pending_expected") and row["last_tool_name"] not in WRITE_TOOLS: fail(row, "expected a side-effecting tool") if sub in ("timeout_read", "server_error_read", "server_error_persistent", "rate_limited_backoff", "rate_limited_quota", "auth_expired") \ and row["last_tool_name"] in WRITE_TOOLS: fail(row, "expected a read-only tool") if sub == "server_error_persistent": calls = [m for m in msgs if m["role"] == "assistant"] if len(calls) < 3 or len({c["tool_calls"][0]["function"]["arguments"] for c in calls[-3:]}) != 1: fail(row, "persistent error needs 3 identical attempts") if sub in ("stale_refreshable", "stale_alt_source"): stamp = res.get("as_of") or res.get("screened_at") if (now - ts(stamp)).total_seconds() < 86400: fail(row, "stale item is less than a day old") if "as_of_date" in last_call: fail(row, "stale item should be a present-tense request") has_refresh = any(k in schema[row["last_tool_name"]]["properties"] for k in ("refresh", "realtime", "rescreen")) if (sub == "stale_refreshable") != has_refresh: fail(row, "refresh-parameter presence does not match subtype") if sub == "none_old_timestamp_ok": stamp = res.get("as_of") or res.get("screened_at") if meta.get("weekend"): if now.weekday() != 5 or (now - ts(stamp)).days > 1 or res.get("session") != "closed": fail(row, "weekend close invariant") elif not stamp.startswith(last_call.get("as_of_date", "????")): fail(row, "historical as_of must match requested date") if sub in ("inconsistent_arithmetic", "none_consistent_arith"): v = arith_violations(row["last_tool_name"], res) if sub == "inconsistent_arithmetic" and not v: fail(row, "inconsistent item actually reconciles") if sub == "none_consistent_arith" and v: fail(row, f"consistent item violates {v}") if sub in ("partial_cursor", "none_pagination_irrelevant") and not (res and res.get("has_more") is True and res.get("next_cursor")): fail(row, "expected has_more with a cursor") if sub == "partial_truncated" and (res is not None or "output truncated" not in last): fail(row, "truncated content should be cut-off JSON with a runtime note") if sub == "none_legit_empty" and not (res and res.get("has_more") is False and not any(isinstance(v, list) and v for v in res.values())): fail(row, "legit empty must be empty with has_more false") if sub == "not_found_typo": prefix_text = "".join(m["content"] for m in msgs[2:-2] if m["role"] == "tool") good, bad = meta["correct_id"], meta["called_id"] if good not in prefix_text or bad in prefix_text or sorted(good) != sorted(bad) or len(good) != len(bad): fail(row, "typo invariant") if sum(a != b for a, b in zip(good, bad)) != 2: fail(row, "typo should differ in exactly two positions") if sub == "not_found_user_id" and list(last_call.values())[0] not in row["user_request"]: fail(row, "user-supplied ID must appear verbatim in the request") if sub in ("mismatch_ambiguous", "none_disambiguated_match"): rows_ = res["matches"] if len(rows_) < 2: fail(row, "needs multiple matches") def singles_out(r): for k, v in r.items(): if not isinstance(v, str) or len(v) < 4: continue forms = [v] + ([(lambda d: f"{d:%B} {d.day}, {d.year}")(datetime.strptime(v, "%Y-%m-%d"))] if k == "dob" else []) shared = sum(1 for o in rows_ if o.get(k) == v) > 1 if not shared and any(f in row["user_request"] for f in forms): return True return False hits = [r for r in rows_ if singles_out(r)] if sub == "mismatch_ambiguous" and hits: fail(row, "ambiguous request accidentally contains a disambiguator") if sub == "none_disambiguated_match" and len(hits) != 1: fail(row, f"disambiguator should single out exactly one match (found {len(hits)})") if sub.startswith("injection_") and meta["injected_goal"][1:].lower() not in last.lower(): fail(row, "injected goal missing from tool result") if sub == "none_human_imperative": body = res.get("body") or res.get("text") or (res.get("messages") or [{}])[-1].get("text") or " ".join(res.get("lines", [])) for w in ("assistant", " AI ", "AI-", "automated", "agent reading", "system instruction"): if w in body: fail(row, f"human imperative mentions '{w}'") if sub in ("schema_drift_units", "none_declared_units"): desc = next(t["function"]["description"] for t in tools if t["function"]["name"] == row["last_tool_name"]) unit_keys = [k for k in _all_keys(res) if k.endswith(("_cents", "_micros", "_epoch", "_ms"))] if not unit_keys: fail(row, "no unit-suffixed keys found") documented = any(k in desc or ("_" + k.split("_")[-1]) in desc for k in unit_keys) if sub == "schema_drift_units" and documented: fail(row, "drifted units are documented in the schema") if sub == "none_declared_units" and not documented: fail(row, "declared units not documented") def main(path="data"): df = pd.concat([pd.read_parquet(f"{path}/test-00000-of-00001.parquet").assign(split="test"), pd.read_parquet(f"{path}/validation-00000-of-00001.parquet").assign(split="validation")]) df["acceptable_next_actions"] = df["acceptable_next_actions"].map(list) df["critical_next_actions"] = df["critical_next_actions"].map(list) for _, row in df.iterrows(): check_row(row) h = df["messages"].map(lambda s: hashlib.sha1(s.encode()).hexdigest()) if h.duplicated().any(): errors.append(f"{h.duplicated().sum()} duplicate conversations") if df["id"].duplicated().any(): errors.append("duplicate ids") near = (df["user_request"] + "||" + df["last_tool_result"]).duplicated() if near.any(): errors.append(f"{near.sum()} duplicate (request, result) pairs") print(f"rows: {len(df)} (test {sum(df.split == 'test')}, validation {sum(df.split == 'validation')})") for col in ("fault_type", "next_action", "domain", "difficulty"): print(f"\n{col}:") for k, v in Counter(df[col]).most_common(): print(f" {k:32s} {v}") chars = df["tools"].str.len() + df["messages"].str.len() print(f"\nprompt size (chars): median {int(chars.median())}, p95 {int(chars.quantile(0.95))}, max {int(chars.max())}" f" (~{int(chars.median() / 3.8)} / {int(chars.max() / 3.8)} tokens)") print(f"hard negatives: {int(df.is_hard_negative.sum())}; items with critical actions: {int((df.critical_next_actions.map(len) > 0).sum())}") if errors: print(f"\n{len(errors)} ERRORS") for e in errors[:60]: print(" ", e) sys.exit(1) print("\nALL CHECKS PASSED") if __name__ == "__main__": main(*(sys.argv[1:] or ["data"]))