"""Close a Worker episode into a compact report and an immutable evidence index. No frames or full-rate telemetry leave the Worker. Missing measurements remain null; a duration limit is never counted as successful route completion. """ import hashlib import json import math import statistics from collections import defaultdict from datetime import UTC, datetime from pathlib import Path from local_state import read_json, write_json def records(path): if path.exists(): with path.open(encoding="utf-8") as stream: for line in stream: if line.strip(): yield json.loads(line) def sha256(path): with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def execution_inputs(episode, run): """Check identity without reinterpreting old evidence with today's schema.""" path = episode / "execution-inputs.json" if not path.exists(): return None # Legacy episodes and failed preparation may lack this file. inputs = read_json(path) if not isinstance(inputs, dict): raise ValueError("Invalid execution input evidence") encoded = json.dumps( {key: value for key, value in inputs.items() if key != "sha256"}, sort_keys=True, separators=(",", ":"), allow_nan=False, ) if inputs.get("sha256") != hashlib.sha256(encoded.encode()).hexdigest(): raise ValueError("Execution input evidence identity changed") declared = run.get("execution_inputs") if declared is not None and inputs != declared: raise ValueError("Execution input evidence differs from the run") return inputs def summarize(episode, result): episode = Path(episode) run = read_json(episode / "run.json") inputs = execution_inputs(episode, run) route = ( inputs["mission"]["route_xy"] if inputs else run["world"]["settings"].get("route_xy", []) ) physics = episode / "physics-motion.jsonl" distance, seconds, previous, final_xy = 0.0, 0.0, None, None stops = defaultdict(lambda: {"events": 0, "seconds": 0.0}) stop_reason = None requested_speed = ( inputs["behavior"]["max_speed_mps"] if inputs else run["world"]["settings"].get("max_speed_mps") ) speeds, above_speed_seconds = [], 0.0 for row in records(physics): if requested_speed is not None and "velocity" in row: speed = math.hypot(*row["velocity"][:2]) speeds.append(speed) if speed > requested_speed: above_speed_seconds += row["dt"] xy = row["pose"][:2] if previous is not None: distance += math.dist(previous, xy) previous = final_xy = xy seconds += row["dt"] moving = sum(abs(value) for value in row["command"]) >= 1e-5 reason = None if not moving: reason = row["stop_reason"] if reason == "none": reason = row.get("decision_reason", "unknown") # Include initial holding and split an uninterrupted hold when its # cause changes. These are zero-command intervals, not body stops. if reason != stop_reason: stops[reason]["events"] += 1 stops[reason]["seconds"] += row["dt"] stop_reason = reason latencies, waypoints_reached = [], None for row in records(episode / "camera/decisions.jsonl"): latencies.append(row["inference_ms"]) mission = row.get("mission") if mission: reached = ( mission["waypoint_count"] if mission["state"] == "goal-reached" else mission["waypoint"] ) waypoints_reached = max(waypoints_reached or 0, reached) latencies.sort() composition = read_json(episode / "composition.json") or {} robot = run.get("robot") or {} outcome = result.get("mission_outcome", "not-evaluated") report = { "schema_version": "missioncore.simulation-report/v2", "run_id": run["run_id"], "generated_at": datetime.now(UTC).isoformat(), "mission_outcome": outcome, "plan_id": (run.get("plan") or {}).get("plan_id"), "plan_sha256": (run.get("plan") or {}).get("sha256"), "robot_id": robot.get("robot_id"), "robot_sha256": robot.get("sha256"), "composition_sha256": composition.get("sha256"), "world_sha256": run["world"]["sha256"], "runtime_sources": run["worker"].get("runtime_sources", {}), "simulation_seconds": seconds if previous is not None else None, "distance_m": distance if previous is not None else None, "goal_error_m": math.dist(final_xy, route[-1]) if final_xy is not None and route else None, "waypoint_count": len(route), "waypoints_reached": waypoints_reached, "inference_count": len(latencies), "inference_errors": sum(1 for _ in records(episode / "camera/errors.jsonl")), "inference_ms_p50": statistics.median(latencies) if latencies else None, "inference_ms_p95": latencies[math.ceil(len(latencies) * 0.95) - 1] if latencies else None, "stops": [{"reason": reason, **value} for reason, value in sorted(stops.items())], "execution_inputs_sha256": (run.get("execution_inputs") or {}).get("sha256"), "collision_count": None, # No qualified contact-event classifier yet. } scenario = (run.get("qualification") or {}).get("scenario") if requested_speed is not None: maximum = max(speeds) if speeds else None report["speed"] = { "requested_max_mps": requested_speed, "measured_max_mps": maximum, "maximum_excess_mps": max(0, maximum - requested_speed) if maximum is not None else None, "seconds_above_requested": above_speed_seconds if speeds else None, } if run.get("rover_configuration") is not None: config = run["rover_configuration"] report["rover_configuration_sha256"] = config["sha256"] report["effective_robot_sha256"] = config["effective_robot_sha256"] if scenario is not None: from qualification_report import assess_challenge from qualification_scenarios import scenario_from_run report["challenge"] = assess_challenge( scenario_from_run(run), list(records(episode / "challenge-events.jsonl")), list(records(physics)), ) # Stopping and briefly moving again do not qualify route recovery. # Keep both gates: disturbance response and completion of the mission. challenge = report["challenge"] challenge["checks"]["route_completed"] = ( outcome == "goal-reached" and bool(route) and waypoints_reached == len(route) ) challenge["checks"]["no_inference_errors"] = report["inference_errors"] == 0 challenge["passed"] = all(challenge["checks"].values()) return report def seal_episode(episode, result): """Call only after native processes, inference, file handles and IPC close.""" episode = Path(episode) report_path, manifest_path = episode / "report.json", episode / "evidence-manifest.json" if report_path.exists() or manifest_path.exists(): raise FileExistsError("An episode report must never be overwritten") report = summarize(episode, result) write_json(report_path, report) files = [] for path in sorted(episode.rglob("*")): if path.is_symlink(): raise ValueError("Evidence contains a symbolic link") if path.is_file(): files.append( { "path": path.relative_to(episode).as_posix(), "bytes": path.stat().st_size, "sha256": sha256(path), } ) write_json( manifest_path, { "schema_version": "missioncore.simulation-evidence/v1", "run_id": report["run_id"], "sealed_at": datetime.now(UTC).isoformat(), "files": files, }, ) return { **report, "report_sha256": sha256(report_path), "manifest_sha256": sha256(manifest_path), "evidence_files": len(files), "evidence_bytes": sum(item["bytes"] for item in files), } def derive_report(episode, output): """Re-evaluate sealed inputs in a new directory; never edit the episode.""" episode, output = Path(episode).resolve(), Path(output).resolve() if output == episode or episode in output.parents: raise ValueError("Derived evidence must be outside the sealed episode") manifest_path = episode / "evidence-manifest.json" manifest = read_json(manifest_path) if not manifest or manifest.get("schema_version") != "missioncore.simulation-evidence/v1": raise ValueError("A sealed evidence manifest is required") entries = {item["path"]: item for item in manifest["files"]} if len(entries) != len(manifest["files"]): raise ValueError("Duplicate evidence member") sources = {} for name in ( "run.json", "report.json", "composition.json", "execution-inputs.json", "physics-motion.jsonl", "camera/decisions.jsonl", "camera/errors.jsonl", "challenge-events.jsonl", ): path, entry = episode / name, entries.get(name) if entry is None and not path.exists() and name not in {"run.json", "report.json"}: continue # Failed preparation may legitimately lack observations. if ( entry is None or not path.is_file() or path.is_symlink() or not path.resolve().is_relative_to(episode) or path.stat().st_size != entry["bytes"] or sha256(path) != entry["sha256"] ): raise ValueError(f"Evidence member changed or is unsealed: {name}") sources[name] = entry["sha256"] original = read_json(episode / "report.json") report = summarize(episode, original) if report["run_id"] != original["run_id"] or report["run_id"] != manifest["run_id"]: raise ValueError("Evidence run identity mismatch") document = { "schema_version": "missioncore.simulation-report-derivation/v1", "source_manifest_sha256": sha256(manifest_path), "source_members": sources, "evaluator_sha256": sha256(Path(__file__)), "evaluator_sources_sha256": { name: sha256(Path(__file__).with_name(name)) for name in ( "run_report.py", "qualification_report.py", "qualification_scenarios.py", "qualification_scene.py", ) }, "report": report, } output.mkdir(parents=True, exist_ok=False) write_json(output / "derived-report.json", document) return document if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Derive corrected metrics from a sealed episode") parser.add_argument("--episode", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) arguments = parser.parse_args() derived = derive_report(arguments.episode, arguments.output) print(json.dumps({"run_id": derived["report"]["run_id"], "output": str(arguments.output)}))