#!/usr/bin/env python3 """Validate one PDM-Lite closed-loop acceptance artifact.""" from __future__ import annotations import argparse import json import re from pathlib import Path FATAL_LOG_PATTERNS = { "setup_error": re.compile( r"Skipping scenario|Failed to spawn|Error during the simulation|" r"Actor .* could not be spawned", re.IGNORECASE, ), "carla_crash": re.compile( r"Signal 11|Segmentation fault|CARLA crash detected|core dumped", re.IGNORECASE, ), "scenario_exception": re.compile( r"Traceback \\(most recent call last\\)|Exception in thread", re.IGNORECASE, ), } EXPECTED_EVENTS = ( "scenario_initialized", "hint_gate_reached", "event_triggered", "hazard_started", "hazard_cleared", ) PHYSICAL_COMPLETION_EVENTS = { "ClosedOccludedPedestrian": "pedestrian_crossing_completed", "ClosedLaneCutIn": "cut_in_completed", "ClosedRevealObstacle": "obstacle_reveal_completed", "ClosedGhostDriverLeftTurn": "hazard_actor_cleared_route", "ClosedGhostDriverRightTurn": "hazard_actor_cleared_route", "ClosedSignalizedJunctionRightTurnOnRed": "flow_actor_cleared", } PHYSICAL_FAILURE_EVENTS = { "hazard_crossing_timeout": "pedestrian crossing exceeded its physical completion deadline", "cut_in_incomplete": "cut-in actor did not enter the ego route", "obstacle_spawn_failed": "stationary reveal obstacle was not spawned", "hazard_actor_timeout": "wrong-way actor did not clear the ego route", "flow_actor_timeout": "yielding flow actor did not clear the conflict area", } def _read_jsonl(path: Path) -> list[dict]: if not path.is_file(): return [] rows = [] for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): try: rows.append(json.loads(line)) except json.JSONDecodeError: continue return rows def _metric_record(payload: dict) -> dict | None: records = payload.get("_checkpoint", {}).get("records", []) return records[-1] if records else None def validate(run_dir: Path) -> dict: result_path = run_dir / "results.json" console_path = run_dir / "logs/acceptance_console.log" timeline_path = run_dir / "event_timeline.jsonl" agent_event_path = run_dir / "logs/scenario_events.jsonl" errors = [] result = {} record = None if result_path.is_file(): try: result = json.loads(result_path.read_text(encoding="utf-8")) record = _metric_record(result) except json.JSONDecodeError as exc: errors.append(f"invalid results.json: {exc}") else: errors.append("missing results.json") if record is None: errors.append("missing evaluator route record") status = "Missing" route_completion = 0.0 infractions = {} duration_game = 0.0 else: status = record.get("status", "Unknown") route_completion = float(record.get("scores", {}).get("score_route", 0.0)) infractions = record.get("infractions", {}) duration_game = float(record.get("meta", {}).get("duration_game", 0.0)) if status not in {"Completed", "Perfect"}: errors.append(f"route status is {status}") if route_completion < 99.0: errors.append(f"route completion is only {route_completion:.2f}") timeline = _read_jsonl(timeline_path) event_names = [row.get("event") for row in timeline] for event_name, message in PHYSICAL_FAILURE_EVENTS.items(): if event_name in event_names: errors.append(message) scenario_name = next( ( str(row.get("scenario_name", "")) for row in timeline if row.get("scenario_name") ), "", ) scenario_type = next( ( prefix for prefix in PHYSICAL_COMPLETION_EVENTS if scenario_name.startswith(prefix) ), None, ) physical_completion_event = ( PHYSICAL_COMPLETION_EVENTS.get(scenario_type) if scenario_type is not None else None ) if physical_completion_event is None: errors.append(f"unknown scenario lifecycle: {scenario_name or 'missing'}") else: completion_count = event_names.count(physical_completion_event) if completion_count != 1: errors.append( f"physical completion event {physical_completion_event} " f"occurs {completion_count} times" ) event_index = {} for name in EXPECTED_EVENTS: count = event_names.count(name) if count == 0: errors.append(f"missing lifecycle event: {name}") continue if count != 1: errors.append(f"lifecycle event {name} occurs {count} times") event_index[name] = event_names.index(name) if len(event_index) == len(EXPECTED_EVENTS): indices = [event_index[name] for name in EXPECTED_EVENTS] if indices != sorted(indices): errors.append(f"lifecycle order is invalid: {event_names}") agent_events = _read_jsonl(agent_event_path) agent_event_names = [ row.get("event") for row in agent_events if row.get("scenario_family") == "COOPERATIVE_AGENT" ] for name in ("hint_on", "hint_off"): count = agent_event_names.count(name) if count != 1: errors.append(f"cooperative agent event {name} occurs {count} times") if ( "hint_on" in agent_event_names and "hint_off" in agent_event_names and agent_event_names.index("hint_on") > agent_event_names.index("hint_off") ): errors.append(f"cooperative agent event order is invalid: {agent_event_names}") event_row = next( (row for row in timeline if row.get("event") == "event_triggered"), {}, ) release_reason = event_row.get("release_reason") elapsed_since_hint = event_row.get("elapsed_since_hint_s") if release_reason not in {"distance", "timeout"}: errors.append(f"invalid event release reason: {release_reason}") if release_reason == "timeout" and elapsed_since_hint is not None: if not 1.85 <= float(elapsed_since_hint) <= 2.35: errors.append( f"anti-deadlock timeout is {float(elapsed_since_hint):.2f} s" ) frame_files = [] for extension in ("jpg", "jpeg", "png"): frame_files.extend(run_dir.glob(f"data/**/rgb/*.{extension}")) frame_count = len(frame_files) if frame_count < 20: errors.append(f"only {frame_count} RGB frames") videos = sorted((run_dir / "videos").glob("*.mp4")) if not videos: errors.append("no MP4 video") console = ( console_path.read_text(encoding="utf-8", errors="replace") if console_path.is_file() else "" ) log_failures = [] for label, pattern in FATAL_LOG_PATTERNS.items(): if pattern.search(console): log_failures.append(label) errors.append(f"log contains {label}") collision_counts = { key: len(value) if isinstance(value, list) else float(value or 0.0) for key, value in infractions.items() if key.startswith("collisions_") } collision_total = sum(collision_counts.values()) blocked = infractions.get("vehicle_blocked", []) blocked_count = len(blocked) if isinstance(blocked, list) else float(blocked or 0.0) scenario_timeouts = infractions.get("scenario_timeouts", []) scenario_timeout_count = ( len(scenario_timeouts) if isinstance(scenario_timeouts, list) else float(scenario_timeouts or 0.0) ) if blocked_count: errors.append(f"vehicle blocked infractions: {blocked_count}") if collision_total: errors.append(f"collision infractions: {collision_total}") if scenario_timeout_count: errors.append(f"scenario timeout infractions: {scenario_timeout_count}") return { "run_dir": str(run_dir), "accepted": not errors, "errors": errors, "route_status": status, "route_completion": route_completion, "duration_game_s": duration_game, "frame_count": frame_count, "video_count": len(videos), "lifecycle_events": event_names, "scenario_name": scenario_name, "physical_completion_event": physical_completion_event, "cooperative_agent_events": agent_event_names, "event_release_reason": release_reason, "elapsed_since_hint_s": elapsed_since_hint, "collision_counts": collision_counts, "blocked_count": blocked_count, "scenario_timeout_count": scenario_timeout_count, "log_failures": log_failures, } def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("run_dir", type=Path) parser.add_argument("--output", type=Path) args = parser.parse_args() report = validate(args.run_dir.resolve()) output = args.output or args.run_dir / "acceptance_report.json" output.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") print(json.dumps(report, indent=2, sort_keys=True)) return 0 if report["accepted"] else 1 if __name__ == "__main__": raise SystemExit(main())