agentdojo-verdict-audit / scripts /build_tables.py
Gautam-R-Patil's picture
Verdict-audit tables and the full preprint v1.2 artifact (raw/), byte for byte (part 3)
f706361 verified
Raw History Blame Contribute Delete
11.1 kB
# SPDX-License-Identifier: Apache-2.0
"""Build the Parquet tables of this dataset from the released files in raw/.
Run from anywhere; every path is relative to the dataset folder (the parent of scripts/):
python scripts/build_tables.py
Inputs (unchanged copies of TRUSCOR/research artifacts/pf-v1.1 and artifacts/pf-v1.2):
raw/pf-v1.1/overlay/private/experiments/results/pf-confirmatory-2026-11-14/<study>/episodes.jsonl
raw/pf-v1.1/overlay/private/experiments/results/pf-confirmatory-2026-11-14/scoreboard.json
raw/pf-v1.1/overlay/private/experiments/results/pf-confirmatory-2026-11-14/scoreboard-anthropic.json
raw/pf-v1.1/overlay/private/experiments/scoreboard_table_pf.py (its NAMES table, read as data)
Outputs:
data/runs-<study>.parquet one row per run, every released field plus `study` and `source_file`
data/scoreboard.parquet one row per model of the study S2 scoreboard
The script checks each input against raw/pf-v1.1/SHA256SUMS before reading it, and reads every
Parquet file back to check that it holds the released values unchanged.
Needs pandas and pyarrow.
"""
from __future__ import annotations
import ast
import hashlib
import json
import sys
from pathlib import Path
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
ROOT = Path(__file__).resolve().parent.parent
ARTIFACT = Path("raw/pf-v1.1")
RESULTS = ARTIFACT / "overlay/private/experiments/results/pf-confirmatory-2026-11-14"
NAMES_SCRIPT = ARTIFACT / "overlay/private/experiments/scoreboard_table_pf.py"
DATA = Path("data")
# The study folders named in the study table of raw/pf-v1.1/README.md that hold run records.
# Each config of the dataset card groups the folders of one study.
CONFIGS = {
"s2": ["s2", "s2-anthropic"],
"s34": ["s34"],
"s5": ["s5", "s5-anthropic"],
"e2": ["e2"],
}
# Parquet types for the released fields. Absent fields are stored as null, so that every runs
# file has the same schema and the folders of one config can be read together.
STRUCT_FIELDS = {
"software": ["agentdojo", "anthropicSdk", "openaiSdk", "provider", "python"],
"tokens": ["cacheRead", "cacheWrite", "input", "output", "reasoning"],
}
JSON_FIELDS = {"stopReasons"} # keys depend on the provider's API, so stored as a JSON object string
RUN_FIELDS = {
"assistantTurns": pa.int64(),
"attack": pa.string(),
"attackModelName": pa.string(),
"benchmarkVersion": pa.string(),
"condition": pa.string(),
"costUsd": pa.float64(),
"error": pa.string(),
"evidence": pa.string(),
"failedAttempts": pa.list_(pa.string()),
"injectionDigest": pa.string(),
"injectionTask": pa.string(),
"llmCalls": pa.int64(),
"messages": pa.int64(),
"model": pa.string(),
"protocolSha256": pa.string(),
"returnedModels": pa.list_(pa.string()),
"seconds": pa.float64(),
"security": pa.bool_(),
"software": pa.struct([(k, pa.string()) for k in STRUCT_FIELDS["software"]]),
"startedAt": pa.string(),
"stopReasons": pa.string(),
"suite": pa.string(),
"tokens": pa.struct([(k, pa.int64()) for k in STRUCT_FIELDS["tokens"]]),
"toolCallNames": pa.list_(pa.string()),
"toolCalls": pa.int64(),
"trial": pa.int64(),
"userPromptDigest": pa.string(),
"userTask": pa.string(),
"utility": pa.bool_(),
}
RUN_SCHEMA = pa.schema([*RUN_FIELDS.items(), ("study", pa.string()), ("source_file", pa.string())])
def posix(path: Path) -> str:
return path.as_posix()
def released_sums() -> dict[str, str]:
sums = {}
for line in (ROOT / ARTIFACT / "SHA256SUMS").read_text(encoding="utf-8").splitlines():
if line.strip():
digest, name = line.split(maxsplit=1)
sums[name.lstrip("*")] = digest
return sums
def checked_bytes(path: Path, sums: dict[str, str]) -> bytes:
"""Read a file of raw/pf-v1.1 and stop if it differs from SHA256SUMS."""
data = (ROOT / path).read_bytes()
name = posix(path.relative_to(ARTIFACT))
if sums.get(name) != hashlib.sha256(data).hexdigest():
sys.exit(f"checksum mismatch or not listed in SHA256SUMS: {posix(path)}")
return data
# ------------------------------------------------------------------ runs
def to_row(record: dict, study: str, source: str) -> dict:
unknown = set(record) - set(RUN_FIELDS)
if unknown:
sys.exit(f"{source}: fields not in the schema: {sorted(unknown)}")
row = {}
for name in RUN_FIELDS:
value = record.get(name)
if name in STRUCT_FIELDS and value is not None:
extra = set(value) - set(STRUCT_FIELDS[name])
if extra:
sys.exit(f"{source}: {name} has keys not in the schema: {sorted(extra)}")
if name in JSON_FIELDS and value is not None:
value = json.dumps(value, ensure_ascii=False)
row[name] = value
row["study"] = study
row["source_file"] = source
return row
def same_run(record: dict, row: dict) -> bool:
"""True when a row read back from Parquet holds exactly the released record."""
for name in RUN_FIELDS:
value = row[name]
if name not in record:
if value is not None:
return False
continue
if name in JSON_FIELDS and value is not None:
value = json.loads(value)
if name in STRUCT_FIELDS and value is not None:
if any(k not in record[name] and v is not None for k, v in value.items()):
return False
value = {k: v for k, v in value.items() if k in record[name]}
if value != record[name]:
return False
return True
def build_runs(sums: dict[str, str]) -> dict[str, int]:
counts = {}
for folders in CONFIGS.values():
for study in folders:
source = RESULTS / study / "episodes.jsonl"
text = checked_bytes(source, sums).decode("utf-8")
records = [json.loads(line) for line in text.splitlines() if line.strip()]
rows = [to_row(r, study, posix(source)) for r in records]
table = pa.Table.from_pylist(rows, schema=RUN_SCHEMA)
out = DATA / f"runs-{study}.parquet"
pq.write_table(table, ROOT / out, compression="snappy")
back = pq.read_table(ROOT / out).to_pylist()
if len(back) != len(records) or not all(same_run(r, b) for r, b in zip(records, back)):
sys.exit(f"{posix(out)} does not hold the released records unchanged")
counts[study] = len(records)
return counts
# ------------------------------------------------------------------ scoreboard
def released_names(sums: dict[str, str]) -> dict[str, tuple[str, str]]:
"""The NAMES table (model -> developer, name in the paper) of the released script, read as data."""
tree = ast.parse(checked_bytes(NAMES_SCRIPT, sums).decode("utf-8"))
for node in tree.body:
if isinstance(node, ast.Assign) and any(getattr(t, "id", None) == "NAMES" for t in node.targets):
return ast.literal_eval(node.value)
sys.exit("NAMES not found in scoreboard_table_pf.py")
def build_scoreboard(sums: dict[str, str]) -> int:
main_path = RESULTS / "scoreboard.json"
anthropic_path = RESULTS / "scoreboard-anthropic.json"
main = json.loads(checked_bytes(main_path, sums))["models"]
anthropic = json.loads(checked_bytes(anthropic_path, sums))["models"]
# scoreboard.json holds all models; scoreboard-anthropic.json repeats the Anthropic ones.
# A model in both files must have identical values, and is counted once.
models: dict[str, tuple[dict, Path]] = {m: (v, main_path) for m, v in main.items()}
for m, v in anthropic.items():
if m in models and models[m][0] != v:
sys.exit(f"{m} differs between scoreboard.json and scoreboard-anthropic.json")
models.setdefault(m, (v, anthropic_path))
names = released_names(sums)
if len(models) != 24 or set(models) != set(names):
sys.exit(f"expected the 24 models of the NAMES table, found {len(models)}: {sorted(models)}")
fields = ["attackerActionCI95", "attackerActionRate", "benchmarkASR", "categories", "costUsd", "crashes",
"hotelEndorsements", "hotelRuns", "hotelScored", "hotelWarningsScored", "instances", "returnedModels"]
labels = sorted({c for v, _ in models.values() for c in v["categories"]})
rows = []
for m, (v, source) in models.items():
if set(v) != set(fields):
sys.exit(f"{m}: unexpected fields {sorted(set(v) ^ set(fields))}")
if sum(v["categories"].values()) != v["instances"]:
sys.exit(f"{m}: category counts do not add up to instances")
low, high = v["attackerActionCI95"]
developer, name = names[m]
row = {"model": m, "developer": developer, "model_name": name,
"benchmarkASR": v["benchmarkASR"], "attackerActionRate": v["attackerActionRate"],
"attackerActionCI95_low": low, "attackerActionCI95_high": high}
for label in labels:
row["category_" + label.replace("-", "_")] = v["categories"].get(label, 0)
for key in ["costUsd", "crashes", "hotelEndorsements", "hotelRuns", "hotelScored", "hotelWarningsScored",
"instances", "returnedModels"]:
row[key] = v[key]
row["source_file"] = posix(source)
rows.append(row)
# Same order as the released scoreboard_table_pf.py, which made the paper's table.
frame = pd.DataFrame(rows)
frame = frame.sort_values(["attackerActionRate", "benchmarkASR", "model_name"],
ascending=[False, False, True], kind="mergesort").reset_index(drop=True)
floats = {"benchmarkASR", "attackerActionRate", "attackerActionCI95_low", "attackerActionCI95_high", "costUsd"}
ints = {"crashes", "hotelEndorsements", "hotelRuns", "hotelScored", "hotelWarningsScored", "instances"}
def arrow_type(column: str) -> pa.DataType:
if column == "returnedModels":
return pa.list_(pa.string())
if column in ints or column.startswith("category_"):
return pa.int64()
return pa.float64() if column in floats else pa.string()
schema = pa.schema([(c, arrow_type(c)) for c in frame.columns])
table = pa.Table.from_pandas(frame, schema=schema, preserve_index=False)
out = DATA / "scoreboard.parquet"
pq.write_table(table, ROOT / out, compression="snappy")
if pq.read_table(ROOT / out).num_rows != 24:
sys.exit("scoreboard.parquet does not have 24 rows")
return table.num_rows
def main() -> int:
(ROOT / DATA).mkdir(exist_ok=True)
sums = released_sums()
counts = build_runs(sums)
for config, folders in CONFIGS.items():
parts = ", ".join(f"{s} {counts[s]}" for s in folders)
print(f"config {config}: {sum(counts[s] for s in folders)} runs ({parts})")
print(f"runs, all configs: {sum(counts.values())}")
print(f"config scoreboard: {build_scoreboard(sums)} models")
return 0
if __name__ == "__main__":
sys.exit(main())