diff --git a/hf-space/tests/test_labeleval/__init__.py b/hf-space/tests/test_labeleval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/hf-space/tests/test_labeleval/test_detectors.py b/hf-space/tests/test_labeleval/test_detectors.py new file mode 100644 index 0000000000000000000000000000000000000000..baa48e4ecf0a90f1b8721b028bab589abce2ae4f --- /dev/null +++ b/hf-space/tests/test_labeleval/test_detectors.py @@ -0,0 +1,99 @@ +"""Anomaly detector + ensemble tests.""" + +import numpy as np +import pytest + +from sensorflow.evaluation.detectors import ( + AnomalyEnsemble, + AutoencoderDetector, + DBSCANDetector, + FewShotDetector, + GANDetector, + IsolationForestDetector, + KNNDetector, + LOFDetector, + OCSVMDetector, + VAEDetector, + normalize_scores, +) + + +@pytest.fixture(scope="module") +def data(): + rng = np.random.default_rng(3) + normal = rng.normal(0, 1, size=(300, 6)) + # Scattered isolated outliers (a tight far-away cluster would legitimately + # defeat purely local detectors like KNN/DBSCAN). + outliers = rng.uniform(5, 10, size=(12, 6)) * rng.choice([-1, 1], size=(12, 6)) + X = np.vstack([normal, outliers]) + y = np.array([0] * 300 + [1] * 12) + return X, y + + +ALL_DETECTORS = [ + KNNDetector(k=8), + LOFDetector(n_neighbors=15), + IsolationForestDetector(n_estimators=50), + OCSVMDetector(nu=0.05), + DBSCANDetector(eps=1.5, min_samples=5), + AutoencoderDetector(latent_dim=3, epochs=40), + VAEDetector(latent_dim=3), + GANDetector(), + FewShotDetector(support_per_class=15), +] + + +@pytest.mark.parametrize("det", ALL_DETECTORS, ids=lambda d: d.name) +def test_each_detector_ranks_outliers_higher(det, data): + X, y = data + det.fit(X) + scores = det.score(X) + assert scores.shape == (len(X),) + # Mean score of true outliers should exceed mean score of normals. + assert scores[y == 1].mean() > scores[y == 0].mean() + # Top-12 scores should be dominated by the injected outliers. + top = np.argsort(-scores)[:12] + assert (y[top] == 1).sum() >= 8 + + +def test_normalize_scores_is_rank_based(): + s = np.array([10.0, -5.0, 3.0, 100.0]) + n = normalize_scores(s) + assert n.min() == 0.0 and n.max() == 1.0 + assert n[np.argmax(s)] == 1.0 and n[np.argmin(s)] == 0.0 + + +@pytest.mark.parametrize("strategy", ["majority_vote", "weighted_average", "meta_classifier"]) +def test_ensemble_strategies(strategy, data): + X, y = data + cfg = {"advanced": {"ensemble_strategy": strategy, "decision_threshold": 0.9, + "few_shot": {"enabled": True, "support_per_class": 15}}, + "deep": {"gan": {"enabled": True}}} + ens = AnomalyEnsemble(cfg, seed=5) + scores, raw, norm = ens.run(X, supervision=y.astype(float)) + assert len(scores) == len(X) + assert set(raw) == set(norm) + assert len(raw) >= 8 # all default detectors + gan + for k in norm: + assert 0.0 <= norm[k].min() and norm[k].max() <= 1.0 + # ensemble should separate outliers from normals + assert scores[y == 1].mean() > scores[y == 0].mean() + + +def test_ensemble_respects_disabled_detectors(data): + X, _ = data + cfg = { + "detectors": { + "knn": {"enabled": True, "k": 5}, + "lof": {"enabled": False}, + "isolation_forest": {"enabled": False}, + "ocsvm": {"enabled": False}, + "dbscan": {"enabled": False}, + }, + "deep": {"autoencoder": {"enabled": False}, "vae": {"enabled": False}, "gan": {"enabled": False}}, + "advanced": {"few_shot": {"enabled": False}, "ensemble_strategy": "weighted_average", + "decision_threshold": 0.9}, + } + ens = AnomalyEnsemble(cfg) + _, raw, _ = ens.run(X) + assert list(raw) == ["knn"] diff --git a/hf-space/tests/test_labeleval/test_e2e_acceptance.py b/hf-space/tests/test_labeleval/test_e2e_acceptance.py new file mode 100644 index 0000000000000000000000000000000000000000..c86d23cbac38fab578dfabccdf758bdc0329f669 --- /dev/null +++ b/hf-space/tests/test_labeleval/test_e2e_acceptance.py @@ -0,0 +1,215 @@ +"""End-to-end acceptance test through the UI-backed HTTP APIs (spec §49). + +Dataset -> precheck -> ingest synthetic sensor data -> generate labels -> +queue -> anomaly detection -> rare events -> regression -> grader comparison -> +strict geometric validation -> precision/recall -> tracking -> consensus -> +triage -> auto-release valid -> flag invalid -> HITL tasks -> correct a label -> +re-validate -> verify -> training dataset -> train -> stream logs -> evaluate +new model -> regression/improvement -> complete flywheel. +""" + +import time + +import pytest +from fastapi.testclient import TestClient + +from sensorflow.evaluation.pipeline import reset_pipeline +from sensorflow.evaluation.records import reset_store + + +@pytest.fixture(scope="module") +def client(tmp_path_factory): + store = reset_store(tmp_path_factory.mktemp("e2e")) + reset_pipeline(store) + from app_backend import app + with TestClient(app) as c: + yield c + + +def _wait_pipeline(client, timeout=90): + for _ in range(timeout * 4): + state = client.get("/api/labeleval/pipeline").json() + if not state["running"] and state["stage"] in ("complete", "failed", "idle"): + return state + time.sleep(0.25) + raise AssertionError("pipeline did not finish in time") + + +def test_full_flywheel_through_apis(client): + # 1. generate synthetic dataset (raw sensor data + reference GT) + ds = client.post("/api/labeleval/datasets/generate", + json={"name": "e2e", "num_sequences": 3, "frames_per_sequence": 20, "seed": 42}).json() + dataset_id = ds["dataset_id"] + assert ds["num_frames"] == 60 + assert ds["gt_availability"]["gt_type"] == "VENDOR_GROUND_TRUTH" + + # 2. precheck + pre = client.post("/api/dataset/precheck", json={"dataset_id": dataset_id}).json() + assert pre["status"] == "success", pre + assert all(c["passed"] for c in pre["checks"] if c["applicable"]) + + # 3. run the evaluation pipeline (queue -> workers -> triage) + run = client.post("/api/labeleval/run", json={"dataset_id": dataset_id}).json() + assert run["status"] == "started" + state = _wait_pipeline(client) + assert state["stage"] == "complete", state["stage"] + + # queue drained and services healthy + q = client.get("/api/queue/status").json() + assert q["pending"] == 0 and q["completed"] > 0 and q["failed"] == 0 + services = {s["service"]: s for s in state["services"]} + for name in ("label-generator", "anomaly-detector", "grader", "quality-validator", + "rare-event-detector", "triage-engine", "review-service", "metrics-service"): + assert services[name]["state"] in ("HEALTHY", "DEGRADED"), name + + # 4. overview counters populated + ov = client.get("/api/labeleval/overview").json() + c = ov["counters"] + assert c["auto_labeled"] > 100 + assert c["verified"] > 0 and c["flagged"] > 0 + assert c["rare_events"] > 0 + assert ov["process_units_total"] > 0 + + # 5. quality metrics: precision/recall only because reference GT exists + m = client.get("/api/quality/metrics", params={"dataset_id": dataset_id}).json() + assert m["gt_available"] and m["gt_type"] == "VENDOR_GROUND_TRUTH" + g = m["global"] + assert 0.5 < g["precision"] <= 1.0 and 0.5 < g["recall"] <= 1.0 + assert g["safety_critical_recall"] is not None + assert g["grader_consensus"] is not None + assert len(m["per_class"]) >= 4 and len(m["per_scenario"]) >= 3 + + # 6. verified vs non-verified groups + groups = client.get("/api/quality/groups", params={"dataset_id": dataset_id}).json() + names = {x["name"]: x for x in groups["groups"]} + assert set(names) == {"verified", "non_verified", "hitl", "rejected"} + assert groups["total"] == c["auto_labeled"] + gd = client.get(f"/api/quality/groups/{dataset_id}:hitl").json() + assert gd["count"] == names["hitl"]["count"] + assert gd["failure_reason_counts"] + + # 7. haystack renders all categories and points open evidence + hs = client.get("/api/labeleval/haystack", params={"dataset_id": dataset_id}).json()["points"] + cats = {p["category"] for p in hs} + assert {"normal", "anomaly", "rare_event", "false_negative"} <= cats + ann_point = next(p for p in hs if p["kind"] == "annotation") + ev = client.get(f"/api/labeleval/evaluations/{ann_point['id']}").json() + assert ev["anomaly"]["detector_scores"] and ev["decision"] is not None + + # 8. rare events with evidence + events = client.get("/api/labeleval/rare-events").json()["events"] + assert events and all(e["evidence_frames"] for e in events) + + # 9. regression endpoint has an entry for this run + reg = client.get("/api/regression").json() + assert reg["entries"] + + # 10. HITL: find a position-error task, correct it with the reference box + tasks = client.get("/api/review/tasks").json()["tasks"] + assert tasks + target = None + for t in tasks: + if t["status"] != "open": + continue + full = client.get(f"/api/review/tasks/{t['task_id']}").json() + rec = full["evidence"] + if rec and "WRONG_POSITION" in rec["injected_errors"]: + target = full + break + assert target is not None, "expected an open WRONG_POSITION review task" + + frame = client.get(f"/api/labeleval/frames/{target['frame_id']}").json()["frame"] + gt = next(g for g in frame["gt_boxes"] if g["gt_id"] == target["evidence"]["ground_truth_id"]) + res = client.post(f"/api/review/tasks/{target['task_id']}", + json={"action": "correct", + "corrected_bbox_3d": gt["bbox_3d"], + "corrected_class": gt["class_name"]}).json() + assert res["task"]["status"] == "resolved" + assert res["task"]["resolution"]["revalidation_passed"] is True, res["message"] + assert res["task"]["resolution"]["final_status"] == "VERIFIED" + # Corrected label was re-validated against a human-verified reference. + reval = res["revalidation"] + assert reval["ground_truth_type"] == "HUMAN_VERIFIED_GROUND_TRUTH" + assert reval["geometry"]["iou_3d"] >= 0.99 + assert reval["decision"]["status"] == "AUTO_GRADED" + + # funnel now shows the HITL side branch flowing back to verified + funnel = client.get("/api/labeleval/funnel").json() + side = {s["stage"]: s["count"] for s in funnel["side_path"]} + assert side["RE-LABELING"] >= 1 and side["VERIFIED (post-HITL)"] >= 1 + + # 11. training on the verified pool; logs must stream (grow over time) + tr = client.post("/api/train", json={"dataset_version": dataset_id, + "training_parameters": {"epochs": 3}}).json() + job_id = tr["job_id"] + assert tr["model_version"].startswith("model-v") + + seen_lens = [] + status = None + for _ in range(120): + status = client.get(f"/api/train/jobs/{job_id}").json() + seen_lens.append(len(status["logs"])) + if status["status"] == "completed": + break + time.sleep(0.3) + assert status["status"] == "completed", status + assert status["epoch"] == 3 + assert status["rare_recall"] > 0 and status["safety_recall"] > 0 + assert status["process_units"] > 0 + assert max(seen_lens) > min(seen_lens), "training logs should stream incrementally" + assert status["lineage"]["parent_dataset"] == dataset_id + assert status["lineage"]["validated_by_policy"] + + # 12. new model evaluated and registered with regression status + models = client.get("/api/models").json()["models"] + trained = [mm for mm in models if mm["model_id"] == tr["model_id"]] + assert trained and trained[0]["metrics"]["f1"] is not None + assert trained[0]["regression_status"] in ("baseline", "improved", "regressed") + + # 13. process units accounted at every stage with unit economics + pu = client.get("/api/labeleval/process-units").json() + for stage in ("ingestion", "label_generation", "anomaly_detection", "validation", + "grading", "rare_event_detection", "hitl", "training"): + assert pu["by_stage"].get(stage, 0) > 0, stage + assert pu["unit_economics"]["per_verified_event"] is not None + + # 14. audit trail captured the flywheel + audit = client.get("/api/labeleval/audit").json()["events"] + actions = {e["action"] for e in audit} + assert {"dataset_generated", "labels_generated", "pipeline_completed", + "review_correct", "training_started", "training_completed"} <= actions + + +def test_benchmark_and_copilot_through_apis(client): + bench = client.post("/api/benchmark/techniques", json={}).json() + assert len(bench["rows"]) >= 10 + techniques = {r["technique"] for r in bench["rows"]} + assert {"knn", "lof", "isolation_forest", "ocsvm", "dbscan", + "autoencoder", "vae", "gan", "few_shot"} <= techniques + assert {"best_rare_recall", "best_safety_recall", "lowest_fp_rate", + "lowest_process_units", "lowest_tracking_error"} <= set(bench["highlights"]) + + # Copilot on a flagged annotation: advisory, graceful without Ollama. + tasks = client.get("/api/review/tasks").json()["tasks"] + open_tasks = [t for t in tasks if t["status"] == "open"] + assert open_tasks + cp = client.post("/api/copilot/explain", + json={"context_type": "anomaly", + "annotation_id": open_tasks[0]["annotation_id"]}).json() + assert cp["status"] == "ok" + assert cp["analysis"] + assert cp["structured"]["hypothesis"].startswith("HYPOTHESIS") + assert cp["structured"]["observed_evidence"] + assert 0 <= cp["structured"]["confidence"] <= 1 + + +def test_sse_stream_emits_state(client): + # Bounded tick count: TestClient buffers the response, so the stream must + # terminate; real clients consume the long-lived stream incrementally. + res = client.get("/api/events/stream", params={"ticks": 2}) + assert res.headers["content-type"].startswith("text/event-stream") + lines = [l for l in res.text.splitlines() if l.startswith("data: ")] + assert len(lines) == 2 + import json + payload = json.loads(lines[0][6:]) + assert "pipeline" in payload and "training" in payload and "ts" in payload diff --git a/hf-space/tests/test_labeleval/test_graders.py b/hf-space/tests/test_labeleval/test_graders.py new file mode 100644 index 0000000000000000000000000000000000000000..c964e8d67fd0165d22ee58444d3a3c17b617a062 --- /dev/null +++ b/hf-space/tests/test_labeleval/test_graders.py @@ -0,0 +1,57 @@ +"""Statistical agreement tests: each statistic used correctly.""" + +import math + +from sensorflow.evaluation.graders import cohens_kappa, fleiss_kappa, krippendorff_alpha + + +def test_cohens_kappa_perfect_agreement(): + assert cohens_kappa(["a", "b", "a"], ["a", "b", "a"]) == 1.0 + + +def test_cohens_kappa_known_value(): + # Classic worked example: po=0.7, pe=0.5 -> kappa=0.4 + a = ["yes"] * 25 + ["yes"] * 15 + ["no"] * 15 + ["no"] * 45 + b = ["yes"] * 25 + ["no"] * 15 + ["yes"] * 15 + ["no"] * 45 + k = cohens_kappa(a, b) + po = 0.7 + pe = 0.4 * 0.4 + 0.6 * 0.6 + expected = (po - pe) / (1 - pe) + assert math.isclose(k, expected, abs_tol=1e-9) + + +def test_cohens_kappa_chance_level_is_zero(): + # Independent raters with 50/50 marginals and po == pe -> kappa == 0 + a = ["x", "x", "y", "y"] + b = ["x", "y", "x", "y"] + assert math.isclose(cohens_kappa(a, b), 0.0, abs_tol=1e-9) + + +def test_fleiss_kappa_perfect(): + ratings = [{"cat": 4} for _ in range(10)] + assert fleiss_kappa(ratings) == 1.0 + + +def test_fleiss_kappa_known_direction(): + # High agreement should beat mixed agreement. + high = [{"a": 4} for _ in range(8)] + [{"b": 4} for _ in range(8)] + mixed = [{"a": 2, "b": 2} for _ in range(16)] + assert fleiss_kappa(high) > fleiss_kappa(mixed) + assert fleiss_kappa(mixed) < 0.1 + + +def test_krippendorff_alpha_perfect_with_missing_data(): + # Three raters, one has missing values; all present values agree. + data = [ + ["a", "b", "a", "a"], + ["a", "b", "a", None], + [None, "b", "a", "a"], + ] + assert krippendorff_alpha(data) == 1.0 + + +def test_krippendorff_alpha_disagreement_lowers_alpha(): + agree = [["a", "b", "a"], ["a", "b", "a"]] + disagree = [["a", "b", "a"], ["b", "a", "b"]] + assert krippendorff_alpha(agree) > krippendorff_alpha(disagree) + assert krippendorff_alpha(disagree) < 0.0 # systematic disagreement diff --git a/hf-space/tests/test_labeleval/test_queue.py b/hf-space/tests/test_labeleval/test_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..a7a9d8cea6a0b37d434fabe8cadd4c17b764b172 --- /dev/null +++ b/hf-space/tests/test_labeleval/test_queue.py @@ -0,0 +1,53 @@ +"""EventQueue abstraction tests.""" + +from sensorflow.evaluation.queue import InMemoryEventQueue, KafkaEventQueue, make_queue + + +def test_in_memory_publish_consume_ack(): + q = InMemoryEventQueue() + for i in range(10): + q.publish("evaluation", {"i": i}) + assert q.stats()["pending"] == 10 + + batch = q.consume("evaluation", 4) + assert [m["i"] for m in batch] == [0, 1, 2, 3] + s = q.stats() + assert s["pending"] == 6 and s["processing"] == 4 + + q.ack("evaluation", 4) + s = q.stats() + assert s["processing"] == 0 and s["completed"] == 4 and s["failed"] == 0 + + +def test_ack_failed_messages_counted(): + q = InMemoryEventQueue() + q.publish("t", {"a": 1}) + q.consume("t", 1) + q.ack("t", 0, failed=1) + assert q.stats()["failed"] == 1 + + +def test_topics_are_independent(): + q = InMemoryEventQueue() + q.publish("a", {"x": 1}) + q.publish("b", {"x": 2}) + assert q.consume("a", 10)[0]["x"] == 1 + assert q.consume("b", 10)[0]["x"] == 2 + + +def test_kafka_stub_raises_clear_error(): + try: + KafkaEventQueue() + assert False, "stub should not construct" + except RuntimeError as e: + assert "Kafka" in str(e) + + +def test_make_queue_always_returns_working_queue(): + q = make_queue("memory") + q.publish("t", {"ok": True}) + assert q.consume("t", 1)[0]["ok"] is True + # kafka preference degrades gracefully to a working queue + q2 = make_queue("kafka") + q2.publish("t", {"ok": 1}) + assert q2.consume("t", 1) diff --git a/hf-space/tests/test_labeleval/test_synthetic_errors.py b/hf-space/tests/test_labeleval/test_synthetic_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..3331d223ddb8ee5dd9b0e01227fb61c6cd7805f9 --- /dev/null +++ b/hf-space/tests/test_labeleval/test_synthetic_errors.py @@ -0,0 +1,202 @@ +"""Every injected synthetic error must be caught by the appropriate subsystem.""" + +import numpy as np +import pytest + +from sensorflow.evaluation import reporting, synthetic +from sensorflow.evaluation.pipeline import reset_pipeline +from sensorflow.evaluation.records import reset_store + + +@pytest.fixture(scope="module") +def env(tmp_path_factory): + store = reset_store(tmp_path_factory.mktemp("labeleval")) + pipe = reset_pipeline(store) + ds = synthetic.generate_dataset(store, num_sequences=4, frames_per_sequence=25, seed=7) + pipe.run(ds.dataset_id, background=False) + anns = store.where("annotations", dataset_id=ds.dataset_id) + return store, pipe, ds, anns + + +def _with_error(anns, err): + return [a for a in anns if err in a.injected_errors] + + +def _reasons(store, ann): + d = store.get("triage_decisions", ann.annotation_id) + return set(d.failure_reasons) if d else set() + + +def _detection_rate(store, anns, err, expected_reasons): + subset = _with_error(anns, err) + assert subset, f"generator injected no {err}" + caught = [a for a in subset + if a.status == "FLAGGED" and (_reasons(store, a) & expected_reasons)] + return len(caught) / len(subset), subset + + +# ------------------------------------------------------------------ per-error assertions + + +def test_all_injected_errors_are_flagged(env): + store, _, _, anns = env + injected = [a for a in anns if a.injected_errors] + flagged = [a for a in injected if a.status == "FLAGGED"] + assert len(flagged) / len(injected) >= 0.95 + + +def test_false_positive_caught(env): + store, _, _, anns = env + rate, _ = _detection_rate(store, anns, "FALSE_POSITIVE", {"ANOMALY", "LOW_IOU", "INSUFFICIENT_POINT_SUPPORT"}) + assert rate >= 0.9 + + +def test_false_negative_visible_as_missed_gt(env): + store, _, ds, anns = env + n_injected_fn = ds.generation_params["injected"]["FALSE_NEGATIVE"] + assert n_injected_fn > 0 + # Missed objects surface as false_negative points in the haystack. + points = reporting.haystack(store, ds.dataset_id) + fn_points = [p for p in points if p["category"] == "false_negative"] + assert len(fn_points) >= n_injected_fn * 0.9 + # And recall < 1 because references exist. + m = reporting.quality_metrics(store, ds.dataset_id)["global"] + assert m["recall"] is not None and m["recall"] < 1.0 + + +def test_bad_3d_box_caught_by_validation(env): + store, _, _, anns = env + rate, _ = _detection_rate(store, anns, "BAD_3D_BOX", {"LOW_IOU", "INSUFFICIENT_POINT_SUPPORT"}) + assert rate >= 0.9 + + +def test_wrong_orientation_caught(env): + store, _, _, anns = env + rate, subset = _detection_rate(store, anns, "WRONG_ORIENTATION", {"ORIENTATION_ERROR", "LOW_IOU"}) + assert rate >= 0.9 + # Orientation error must be measured, not inferred. + v = store.get("validations", subset[0].annotation_id) + assert v.orientation_error_deg is None or v.orientation_error_deg > 10 + + +def test_wrong_position_caught(env): + store, _, _, anns = env + rate, _ = _detection_rate(store, anns, "WRONG_POSITION", + {"POSITION_ERROR", "LOW_IOU", "INSUFFICIENT_POINT_SUPPORT"}) + assert rate >= 0.9 + + +def test_id_switch_caught_by_tracking(env): + store, _, _, anns = env + rate, _ = _detection_rate(store, anns, "ID_SWITCH", {"ID_SWITCH"}) + assert rate >= 0.9 + + +def test_track_fragmentation_caught(env): + store, _, _, anns = env + rate, _ = _detection_rate(store, anns, "TRACK_FRAGMENTATION", {"TRACK_FRAGMENTATION", "ID_SWITCH"}) + assert rate >= 0.9 + + +def test_low_point_density_caught(env): + store, _, _, anns = env + rate, _ = _detection_rate(store, anns, "LOW_POINT_DENSITY", {"INSUFFICIENT_POINT_SUPPORT"}) + assert rate >= 0.9 + + +def test_sensor_disagreement_caught(env): + store, _, _, anns = env + rate, _ = _detection_rate(store, anns, "SENSOR_DISAGREEMENT", {"SENSOR_DISAGREEMENT"}) + assert rate >= 0.9 + + +def test_grader_disagreement_caught(env): + store, _, _, anns = env + rate, subset = _detection_rate(store, anns, "GRADER_DISAGREEMENT", {"GRADER_DISAGREEMENT"}) + assert rate >= 0.9 + g = store.get("grader_comparisons", subset[0].annotation_id) + assert g.consensus < 0.9 and "classification" in g.disagreement_types + + +def test_low_confidence_caught(env): + store, _, _, anns = env + rate, _ = _detection_rate(store, anns, "LOW_CONFIDENCE", {"LOW_CONFIDENCE"}) + assert rate >= 0.9 + + +def test_clean_labels_mostly_auto_verified(env): + store, _, _, anns = env + clean = [a for a in anns if not a.injected_errors] + verified = [a for a in clean if a.status == "VERIFIED"] + assert len(verified) / len(clean) >= 0.8 + + +# ------------------------------------------------------------------ rare events + + +def test_rare_events_detected_with_evidence(env): + store, _, ds, _ = env + events = store.where("rare_events", dataset_id=ds.dataset_id) + types = {e.scenario_type for e in events} + assert "near_collision" in types + assert "sensor_failure" in types + assert "vru_interaction" in types + for e in events: + assert e.evidence_frames and e.sensor_evidence + assert 0 <= e.rarity_score <= 1 + + +# ------------------------------------------------------------------ anomaly evidence retention + + +def test_anomaly_decisions_retain_full_evidence(env): + store, _, _, anns = env + an = store.get("anomalies", anns[0].annotation_id) + assert an.detector_scores and an.normalized_scores + assert set(an.detector_scores) == set(an.normalized_scores) + assert an.ensemble_strategy in ("majority_vote", "weighted_average", "meta_classifier") + assert 0 < an.decision_threshold <= 1 + + +# ------------------------------------------------------------------ triage explainability + + +def test_every_decision_has_policy_and_gate_lines(env): + store, _, _, anns = env + for a in anns[:50]: + d = store.get("triage_decisions", a.annotation_id) + assert d is not None + assert d.policy_id and d.policy_values + assert d.gate_lines, "explainable per-gate lines required" + if d.status == "FLAGGED": + assert d.primary_failure_reason is not None + failing = [l for l in d.gate_lines if l.applicable and not l.passed] + assert failing, "flagged decisions must show a failing gate" + + +# ------------------------------------------------------------------ model regression + + +def test_model_regression_detected_on_degraded_second_run(tmp_path): + store = reset_store(tmp_path) + pipe = reset_pipeline(store) + + ds1 = synthetic.generate_dataset(store, num_sequences=3, frames_per_sequence=20, seed=21) + pipe.run(ds1.dataset_id, background=False) + first = [r for r in store.all("regressions")] + assert first and not first[-1].regression_detected # no baseline yet + + # Second dataset labeled by a degraded model: pedestrian recall collapses. + ds2 = synthetic.generate_dataset(store, name="degraded", num_sequences=3, + frames_per_sequence=20, seed=22) + synthetic.generate_labels(store, ds2, model_version="model-v2-degraded", + degrade_classes=["pedestrian", "vehicle"], seed_offset=5) + pipe.run(ds2.dataset_id, background=False) + + regs = sorted(store.all("regressions"), key=lambda r: r.date) + latest = regs[-1] + assert latest.regression_detected + assert "performance" in latest.kinds + regressed_metrics = {d.metric for d in latest.deltas if d.regressed} + assert "recall" in regressed_metrics or "safety_critical_recall" in regressed_metrics + assert pipe.regression_alert diff --git a/hf-space/tests/test_labeleval/test_validation.py b/hf-space/tests/test_labeleval/test_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..852daf9fe3248e9245a084268d694987897b5f10 --- /dev/null +++ b/hf-space/tests/test_labeleval/test_validation.py @@ -0,0 +1,107 @@ +"""Geometric validation engine tests.""" + +import math +from pathlib import Path + +import pytest + +from sensorflow.evaluation import synthetic +from sensorflow.evaluation.records import Annotation, reset_store +from sensorflow.evaluation.validation import iou_3d, validate_annotation + + +@pytest.fixture() +def env(tmp_path): + store = reset_store(tmp_path) + ds = synthetic.generate_dataset(store, num_sequences=1, frames_per_sequence=5, seed=11) + frames = sorted(store.where("frames", dataset_id=ds.dataset_id), key=lambda f: f.index) + frame = next(f for f in frames if f.gt_boxes and "sensor_failure" not in f.scenario_tags) + return store, ds, frame + + +def _ann(ds, frame, bbox, cls, gt_id=None, bbox_2d="auto", conf=0.9): + return Annotation( + annotation_id="ann-test-1", + dataset_id=ds.dataset_id, + frame_id=frame.frame_id, + object_id="obj", + class_name=cls, + confidence=conf, + bbox_3d=bbox, + bbox_2d=synthetic.project_bbox_2d(bbox) if bbox_2d == "auto" else bbox_2d, + matched_gt_id=gt_id, + ) + + +def test_iou_3d_identity(): + box = [10, 2, 0.8, 4.5, 1.9, 1.6, 0.3] + assert iou_3d(box, box) == pytest.approx(1.0, abs=1e-6) + + +def test_iou_3d_disjoint(): + a = [10, 2, 0.8, 4.5, 1.9, 1.6, 0.0] + b = [40, -10, 0.8, 4.5, 1.9, 1.6, 0.0] + assert iou_3d(a, b) == 0.0 + + +def test_accurate_box_passes_all_checks(env): + store, ds, frame = env + gt = max(frame.gt_boxes, key=lambda g: g.bbox_3d[3] * g.bbox_3d[4]) # largest object + ann = _ann(ds, frame, list(gt.bbox_3d), gt.class_name, gt.gt_id) + res = validate_annotation(store, ann, frame) + assert res.passed, [c.model_dump() for c in res.checks if not c.passed] + assert res.iou_3d == pytest.approx(1.0, abs=1e-4) + assert res.position_error == pytest.approx(0.0, abs=1e-6) + + +def test_box_in_empty_space_fails_point_support(env): + store, ds, frame = env + bbox = [55.0, 18.0, 0.8, 4.5, 1.9, 1.6, 0.0] # far corner, no object there + ann = _ann(ds, frame, bbox, "vehicle") + res = validate_annotation(store, ann, frame) + failing = {c.gate for c in res.checks if c.applicable and not c.passed} + assert not res.passed + assert {"points_in_box", "point_density_per_m3"} & failing + + +def test_implausible_dimensions_fail_class_prior(env): + store, ds, frame = env + gt = frame.gt_boxes[0] + x, y, z, l, w, h, yaw = gt.bbox_3d + ann = _ann(ds, frame, [x, y, z, l * 2.5, w * 2.5, h, yaw], gt.class_name, gt.gt_id) + res = validate_annotation(store, ann, frame) + failing = {c.gate for c in res.checks if c.applicable and not c.passed} + assert "box_dimensions_vs_class_prior" in failing + + +def test_floating_box_fails_ground_contact(env): + store, ds, frame = env + gt = frame.gt_boxes[0] + x, y, z, l, w, h, yaw = gt.bbox_3d + ann = _ann(ds, frame, [x, y, z + 2.0, l, w, h, yaw], gt.class_name, gt.gt_id) + res = validate_annotation(store, ann, frame) + failing = {c.gate for c in res.checks if c.applicable and not c.passed} + assert "ground_contact_error_m" in failing + + +def test_missing_camera_detection_fails_sensor_consistency(env): + store, ds, frame = env + gt = next((g for g in frame.gt_boxes if synthetic.project_bbox_2d(g.bbox_3d)), None) + if gt is None: + pytest.skip("no projectable GT in this frame") + ann = _ann(ds, frame, list(gt.bbox_3d), gt.class_name, gt.gt_id, bbox_2d=None) + res = validate_annotation(store, ann, frame) + assert not res.sensor_consistent + failing = {c.gate for c in res.checks if c.applicable and not c.passed} + assert "sensor_consistency_cam_lidar" in failing + + +def test_wrong_orientation_measured_against_reference(env): + store, ds, frame = env + gt = max(frame.gt_boxes, key=lambda g: g.bbox_3d[3]) + x, y, z, l, w, h, yaw = gt.bbox_3d + ann = _ann(ds, frame, [x, y, z, l, w, h, yaw + math.radians(60)], gt.class_name, gt.gt_id) + res = validate_annotation(store, ann, frame) + assert res.orientation_error_deg == pytest.approx(60.0, abs=1.0) + failing = {c.gate for c in res.checks if c.applicable and not c.passed} + assert "orientation_error_deg" in failing diff --git a/hf-space/tests/test_megaeval/__init__.py b/hf-space/tests/test_megaeval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/hf-space/tests/test_megaeval/conftest.py b/hf-space/tests/test_megaeval/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..17286df3e2cf89f9dc6aa6c635cff33f5fc2eadc --- /dev/null +++ b/hf-space/tests/test_megaeval/conftest.py @@ -0,0 +1,36 @@ +"""Shared fixtures: an isolated megaeval root with a small population and two +published runs (a good candidate and a deliberately regressed one).""" + +from __future__ import annotations + +import pytest + +from sensorflow.megaeval import population as pop_mod +from sensorflow.megaeval.runs import get_mega_store, reset_mega_store + + +@pytest.fixture(scope="session") +def mega_env(tmp_path_factory): + root = tmp_path_factory.mktemp("megaeval") + pop_mod.set_mega_root(str(root)) + reset_mega_store() + meta = pop_mod.generate_population("test-pop", num_objects=8_000, seed=17) + store = get_mega_store() + + good = store.create_run(population_id=meta["population_id"], + model_version="model-v41", worker_delay_s=0.0) + store.execute_sync(good) + assert good.status == "published", good.error + + bad = store.create_run(population_id=meta["population_id"], + model_version="model-v42-regressed", + overrides={"night_penalty": 0.35, "vru_penalty": 0.12}, + worker_delay_s=0.0) + store.execute_sync(bad) + assert bad.status == "published", bad.error + + yield {"root": root, "meta": meta, "store": store, "good": good, "bad": bad} + + # restore defaults for any later suites + pop_mod.set_mega_root("runs/megaeval") + reset_mega_store() diff --git a/hf-space/tests/test_megaeval/test_analysis.py b/hf-space/tests/test_megaeval/test_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..38de6d672ab70af09cd92ac4c7f2a4098b0a1247 --- /dev/null +++ b/hf-space/tests/test_megaeval/test_analysis.py @@ -0,0 +1,76 @@ +"""Model-vs-model comparison, distribution shift, why-layer, similarity.""" + +from __future__ import annotations + +from sensorflow.megaeval import analysis + + +def test_compare_detects_injected_regression(mega_env): + store = mega_env["store"] + cmp = analysis.compare_runs(store, mega_env["bad"], mega_env["good"]) + assert cmp["recommendation"] == "DO_NOT_PROMOTE" + assert cmp["blockers"] + hd = {h["metric"]: h["delta"] for h in cmp["headline_deltas"]} + assert hd["recall"] < 0 + assert hd["safety_recall"] < 0 + # injected night+VRU penalty must surface night cohorts among worst regressions + assert any("night" in c["cohort"] for c in cmp["worst_cohorts"][:8]) + assert any("REGRESSION" in b for b in cmp["blockers"]) + + +def test_compare_promotes_equivalent_model(mega_env): + store, meta = mega_env["store"], mega_env["meta"] + good = mega_env["good"] + twin = store.create_run(population_id=meta["population_id"], + model_version=good.model_version, worker_delay_s=0.0) + store.execute_sync(twin) + cmp = analysis.compare_runs(store, twin, good) + assert cmp["recommendation"] == "PROMOTE" + assert cmp["blockers"] == [] + + +def test_compare_writes_legacy_regression_result(mega_env): + from sensorflow.evaluation.records import get_store as legacy_store + analysis.compare_runs(mega_env["store"], mega_env["bad"], mega_env["good"]) + results = legacy_store().all("regressions") + ours = [r for r in results if r.model_version == mega_env["bad"].model_version] + assert ours and ours[-1].regression_detected + + +def test_distribution_shift_flags_underrepresented_cohorts(mega_env): + sh = analysis.distribution_shift(mega_env["store"], mega_env["good"]) + assert sh["shifts"], "training mix was deliberately shifted; must be detected" + top = sh["shifts"][0] + assert abs(top["relative_change"]) >= 0.35 + assert top["eval_count"] >= 300 + # the train mix under-represents night/bad weather, so eval share must be higher + assert any(s["relative_change"] > 0 and s["lighting"] == "night" for s in sh["shifts"]) + + +def test_why_decomposition_sums_to_one(mega_env): + w = analysis.why(mega_env["store"], mega_env["good"], + {"class": ["pedestrian"]}, "recall") + assert w["failure_count"] > 0 + total_share = sum(f["share"] for f in w["factors"]) + assert abs(total_share - 1.0) < 0.01 + assert sum(f["count"] for f in w["factors"]) == w["failure_count"] + names = {f["factor"] for f in w["factors"]} + assert names <= {"occlusion", "low_illumination", "long_range", + "sensor_disagreement", "other"} + assert w["top_cohorts"], "must list affected cohorts with metric values" + assert all("recall" in c for c in w["top_cohorts"]) + + +def test_similarity_hybrid_search(mega_env): + store, run = mega_env["store"], mega_env["good"] + containers = store.artifacts(run.run_id)["containers"] + risky = containers.sort_values("risk_score", ascending=False).iloc[0] + cid = int(risky["container_id"]) + res = analysis.similar_containers(store, run, cid, k=8) + assert len(res["results"]) == 8 + sims = [r["similarity"] for r in res["results"]] + assert sims == sorted(sims, reverse=True) + assert all(r["container_id"] != cid for r in res["results"]) + # hybrid: structured filter restricts results + filt = analysis.similar_containers(store, run, cid, filters={"lighting": ["night"]}, k=8) + assert all(r["lighting"] == "night" for r in filt["results"]) diff --git a/hf-space/tests/test_megaeval/test_api_lifecycle.py b/hf-space/tests/test_megaeval/test_api_lifecycle.py new file mode 100644 index 0000000000000000000000000000000000000000..0f1db1ff82422abd4fdbe397ff881976c7b12100 --- /dev/null +++ b/hf-space/tests/test_megaeval/test_api_lifecycle.py @@ -0,0 +1,190 @@ +"""Async run lifecycle, the query API (cache behavior + routing), 409 gating, +containers/forensic drill-down, review endpoints and performance SLOs — +all through the real HTTP API.""" + +from __future__ import annotations + +import time + +import pytest +from fastapi.testclient import TestClient + + +@pytest.fixture(scope="module") +def client(mega_env): + from app_backend import app + with TestClient(app) as c: + yield c + + +@pytest.fixture(scope="module") +def api_run(client, mega_env): + """Create a fresh run via the API and wait for the async lifecycle to publish.""" + pop_id = mega_env["meta"]["population_id"] + res = client.post("/api/megaeval/runs", + json={"population_id": pop_id, "model_version": "model-api", + "worker_delay_s": 0.05, "workers": 4}) + assert res.status_code == 200 + run = res.json() + assert run["status"] in ("queued", "running") + + seen_statuses = {run["status"]} + deadline = time.time() + 60 + while time.time() < deadline: + r = client.get(f"/api/megaeval/runs/{run['run_id']}").json() + seen_statuses.add(r["status"]) + if r["status"] in ("published", "failed"): + break + time.sleep(0.2) + assert r["status"] == "published", r.get("error") + return {"run": r, "seen_statuses": seen_statuses} + + +def test_async_lifecycle_and_progress(api_run): + r = api_run["run"] + assert api_run["seen_statuses"] & {"queued", "running", "reducing", "materializing"} + assert r["percent"] == 100.0 + assert r["objects_processed"] == r["objects_total"] > 0 + assert r["throughput_objs_per_s"] > 0 + assert r["headline"]["n"] == r["objects_total"] + lin = r["lineage"] + for field in ("evaluation_id", "dataset_version", "model_version", "model_checkpoint", + "label_version", "evaluator_code_version", "metric_version", + "threshold_config", "sampling_config", "seed", "hardware", "timestamp"): + assert field in lin + + +def test_results_blocked_until_published(client, mega_env): + pop_id = mega_env["meta"]["population_id"] + res = client.post("/api/megaeval/runs", + json={"population_id": pop_id, "model_version": "model-slow", + "worker_delay_s": 0.4, "workers": 2}) + run_id = res.json()["run_id"] + blocked = client.get(f"/api/megaeval/runs/{run_id}/funnel") + assert blocked.status_code == 409 + deadline = time.time() + 90 + while time.time() < deadline: + if client.get(f"/api/megaeval/runs/{run_id}").json()["status"] == "published": + break + time.sleep(0.3) + assert client.get(f"/api/megaeval/runs/{run_id}/funnel").status_code == 200 + + +def test_query_api_cache_and_latency_slos(client, api_run): + run_id = api_run["run"]["run_id"] + body = {"evaluation_id": run_id, + "filters": {"class": ["pedestrian"], "lighting": ["night"]}, + "metrics": ["n", "recall", "precision", "mean_iou"], + "group_by": []} + r1 = client.post("/api/evaluations/query", json=body).json() + assert r1["meta"]["source"] == "cube" + assert r1["meta"]["cache_hit"] is False + assert r1["meta"]["exact"] is True + assert r1["rows"][0]["n"] > 0 + assert r1["meta"]["latency_ms"] < 3000 # filtered cohort query SLO + + r2 = client.post("/api/evaluations/query", json=body).json() + assert r2["meta"]["cache_hit"] is True + assert r2["meta"]["source"] == "cache" + assert r2["meta"]["latency_ms"] < 100 # cached query SLO + assert r2["rows"] == r1["rows"] + + dash = client.post("/api/evaluations/query", + json={"evaluation_id": run_id, "group_by": ["class"], + "metrics": ["n", "precision", "recall", "f1"]}).json() + assert dash["meta"]["latency_ms"] < 2000 # aggregate dashboard SLO + assert len(dash["rows"]) == 6 + + stats = client.get("/api/megaeval/cache").json() + assert stats["hits"] >= 1 + + +def test_query_sketch_metrics_marked_approximate(client, api_run): + run_id = api_run["run"]["run_id"] + res = client.post("/api/evaluations/query", + json={"evaluation_id": run_id, + "metrics": ["n", "recall", "confidence_p50", "iou_p90"]}).json() + assert res["meta"]["exact"] is False + assert set(res["meta"]["approximate_fields"]) == {"confidence_p50", "iou_p90"} + assert 0 <= res["rows"][0]["confidence_p50"] <= 1 + + +def test_containers_sort_presets_and_forensic_drilldown(client, api_run): + run_id = api_run["run"]["run_id"] + worst = client.get(f"/api/megaeval/runs/{run_id}/containers", + params={"sort": "worst_recall", "limit": 20}).json() + assert worst["total"] > 0 and len(worst["rows"]) == 20 + recalls = [r["recall"] for r in worst["rows"] if r["recall"] is not None] + assert recalls == sorted(recalls) + + risky = client.get(f"/api/megaeval/runs/{run_id}/containers", + params={"sort": "highest_risk", "limit": 5}).json()["rows"] + risks = [r["risk_score"] for r in risky] + assert risks == sorted(risks, reverse=True) + assert risky[0]["status"] in ("ok", "warn", "critical") + + t0 = time.perf_counter() + objs = client.get( + f"/api/megaeval/runs/{run_id}/containers/{risky[0]['container_id']}/objects").json() + elapsed_ms = (time.perf_counter() - t0) * 1000 + assert elapsed_ms < 1000 # object investigation SLO + assert objs["objects"], "forensic drill-down must return annotation-level rows" + outcomes = {o["outcome"] for o in objs["objects"]} + assert outcomes <= {"TP", "FN", "FP", "LOCALIZATION"} + gt_objs = [o for o in objs["objects"] if o["outcome"] != "FP"] + assert len(gt_objs) == risky[0]["n_objects"] + + +def test_review_endpoints_full_cycle(client, api_run): + run_id = api_run["run"]["run_id"] + state = client.get(f"/api/megaeval/runs/{run_id}/review").json() + assert state["planned"] is False + + plan = client.post(f"/api/megaeval/runs/{run_id}/review/plan", + json={"target_n": 600}).json() + assert plan["planned"] and not plan["executed"] + assert plan["funnel"]["statistically_selected"] > 0 + + done = client.post(f"/api/megaeval/runs/{run_id}/review/execute").json() + assert done["executed"] + res = done["results"] + for metric in ("precision", "recall"): + est = res[metric] + assert est["ci_low"] < est["estimate"] < est["ci_high"] + + funnel = client.get(f"/api/megaeval/runs/{run_id}/funnel").json() + stages = {s["stage"]: s["count"] for s in funnel["stages"]} + assert stages["Human Verified"] == done["funnel"]["reviewed"] + assert funnel["estimated_precision"]["estimate"] is not None + + +def test_error_search_compare_shift_why_similarity_endpoints(client, api_run, mega_env): + run_id = api_run["run"]["run_id"] + es = client.post("/api/megaeval/errors/search", + json={"run_id": run_id, "error_types": ["FN"], + "filters": {"class": ["pedestrian"]}, + "risk_min": 0.5}).json() + assert es["matched_errors"] > 0 and es["worst_containers"] + + cmp = client.post("/api/megaeval/compare", + json={"candidate_run_id": mega_env["bad"].run_id, + "baseline_run_id": run_id}).json() + assert cmp["recommendation"] == "DO_NOT_PROMOTE" + + sh = client.get(f"/api/megaeval/runs/{run_id}/shift").json() + assert sh["shifts"] + + why = client.post("/api/megaeval/why", + json={"run_id": run_id, "filters": {"lighting": ["night"]}, + "metric": "recall"}).json() + assert why["failure_count"] > 0 and why["factors"] + + cid = es["worst_containers"][0]["container_id"] + sim = client.post("/api/megaeval/similarity", + json={"run_id": run_id, "container_id": cid, "k": 5}).json() + assert len(sim["results"]) == 5 + + dist = client.get(f"/api/megaeval/runs/{run_id}/distributions").json() + assert dist["exact"] is False + assert "confidence" in dist and "50" in dist["confidence"]["percentiles"] + assert dist["containers_exact"] > 0 diff --git a/hf-space/tests/test_megaeval/test_cube.py b/hf-space/tests/test_megaeval/test_cube.py new file mode 100644 index 0000000000000000000000000000000000000000..0cc2b3ebbc280860cbc9f32388a4dfcefe564332 --- /dev/null +++ b/hf-space/tests/test_megaeval/test_cube.py @@ -0,0 +1,109 @@ +"""Cube correctness: cube aggregates must EXACTLY match brute-force computation +over the raw per-object records, and re-running with the same lineage must be +bit-identical (deterministic seeds).""" + +from __future__ import annotations + +import os + +import numpy as np +import pandas as pd +import pytest + +from sensorflow.megaeval import cube as cube_mod +from sensorflow.megaeval import population as pop_mod +from sensorflow.megaeval.population import DIM_NAMES, DIMENSIONS +from sensorflow.megaeval.runs import run_dir + + +def _brute_force(env, group_dims): + """Recompute tp/fp/fn/n per group directly from raw per-object outputs.""" + run = env["good"] + frames = [] + d = run_dir(run.run_id) + for p in range(run.partitions_total): + pop_cols = pop_mod.load_partition(run.population_id, p) + with np.load(os.path.join(d, f"objects-part-{p:04d}.npz")) as z: + df = pd.DataFrame({ + **{k: pop_cols[k] for k in DIM_NAMES}, + "tp": z["tp"].astype(np.int64), + "detected": z["detected"].astype(bool), + }) + df["fn"] = 1 - df["tp"] + df["fp"] = (df["detected"] & (df["tp"] == 0)).astype(np.int64) + df["n"] = 1 + frames.append(df[group_dims + ["n", "tp", "fp", "fn"]]) + with np.load(os.path.join(d, f"fp-part-{p:04d}.npz")) as z: + if z["container_id"].size: + fpdf = pd.DataFrame({k: z[k] for k in DIM_NAMES}) + fpdf["n"] = 0 + fpdf["tp"] = 0 + fpdf["fp"] = 1 + fpdf["fn"] = 0 + frames.append(fpdf[group_dims + ["n", "tp", "fp", "fn"]]) + full = pd.concat(frames, ignore_index=True) + return full.groupby(group_dims, as_index=False).sum() + + +@pytest.mark.parametrize("group_dims", [["class"], ["class", "lighting"], ["scenario"]]) +def test_cube_matches_brute_force_exactly(mega_env, group_dims): + run = mega_env["good"] + cube = mega_env["store"].artifacts(run.run_id)["cube"] + rows, _ = cube_mod.aggregate(cube, None, group_dims, + ["n", "tp", "fp", "fn", "precision", "recall"], 2000) + brute = _brute_force(mega_env, group_dims) + assert len(rows) == len(brute) + for _, b in brute.iterrows(): + key = {d: DIMENSIONS[d][int(b[d])] for d in group_dims} + match = [r for r in rows if all(r[d] == key[d] for d in group_dims)] + assert len(match) == 1, f"missing cube row for {key}" + r = match[0] + assert r["n"] == int(b["n"]) + assert r["tp"] == int(b["tp"]) + assert r["fp"] == int(b["fp"]) + assert r["fn"] == int(b["fn"]) + # derived ratios match brute force (API rounds ratios to 6 decimals) + if b["tp"] + b["fp"] > 0: + assert r["precision"] == pytest.approx(b["tp"] / (b["tp"] + b["fp"]), abs=1e-6) + if b["tp"] + b["fn"] > 0: + assert r["recall"] == pytest.approx(b["tp"] / (b["tp"] + b["fn"]), abs=1e-6) + + +def test_rollup_consistency(mega_env): + """Any grouped rollup must sum to the global totals (no double counting).""" + run = mega_env["good"] + cube = mega_env["store"].artifacts(run.run_id)["cube"] + total_rows, _ = cube_mod.aggregate(cube, None, None, ["n", "tp", "fp", "fn"], 1) + total = total_rows[0] + for dim in ("class", "weather", "occlusion", "distance_band"): + rows, _ = cube_mod.aggregate(cube, None, [dim], ["n", "tp", "fp", "fn"], 2000) + for stat in ("n", "tp", "fp", "fn"): + assert sum(r[stat] for r in rows) == total[stat], f"{dim}/{stat} rollup mismatch" + + +def test_filtered_aggregate_equals_manual_subset(mega_env): + run = mega_env["good"] + cube = mega_env["store"].artifacts(run.run_id)["cube"] + filt = {"class": ["pedestrian"], "lighting": ["night"]} + rows, _ = cube_mod.aggregate(cube, filt, None, ["n", "tp", "fn", "recall"], 1) + sub = cube[(cube["class"] == DIMENSIONS["class"].index("pedestrian")) + & (cube["lighting"] == DIMENSIONS["lighting"].index("night"))] + assert rows[0]["n"] == int(sub["n"].sum()) + assert rows[0]["tp"] == int(sub["tp"].sum()) + assert rows[0]["recall"] == pytest.approx(sub["tp"].sum() / max(sub["tp"].sum() + sub["fn"].sum(), 1), abs=1e-6) + + +def test_reproducible_run_same_lineage(mega_env): + """Same population + model_version (same derived seed) -> identical cube.""" + store, meta = mega_env["store"], mega_env["meta"] + r1 = store.create_run(population_id=meta["population_id"], + model_version="model-repro", worker_delay_s=0.0) + store.execute_sync(r1) + r2 = store.create_run(population_id=meta["population_id"], + model_version="model-repro", worker_delay_s=0.0) + store.execute_sync(r2) + assert r1.seed == r2.seed + c1 = mega_env["store"].artifacts(r1.run_id)["cube"].sort_values(DIM_NAMES).reset_index(drop=True) + c2 = mega_env["store"].artifacts(r2.run_id)["cube"].sort_values(DIM_NAMES).reset_index(drop=True) + pd.testing.assert_frame_equal(c1, c2) + assert r1.headline == {**r2.headline} diff --git a/hf-space/tests/test_megaeval/test_error_index.py b/hf-space/tests/test_megaeval/test_error_index.py new file mode 100644 index 0000000000000000000000000000000000000000..556470c8c06d2c739379ca2e228f7e72ce94e856 --- /dev/null +++ b/hf-space/tests/test_megaeval/test_error_index.py @@ -0,0 +1,64 @@ +"""Error index: multi-criteria search correctness and worst-container ranking.""" + +from __future__ import annotations + +import numpy as np + +from sensorflow.megaeval import errors as errors_mod +from sensorflow.megaeval.population import DIMENSIONS +from sensorflow.megaeval.runs import ERROR_TYPES + + +def test_multi_criteria_search_matches_brute_filter(mega_env): + store, run = mega_env["store"], mega_env["good"] + art = store.artifacts(run.run_id) + errs, containers = art["errors"], art["containers"] + + res = errors_mod.search_errors( + errs, containers, error_types=["FN"], + filters={"class": ["pedestrian"], "lighting": ["night"]}, + confidence_max=0.4, risk_min=0.5) + + mask = ((errs["error_type"] == ERROR_TYPES.index("FN")) + & (errs["class"] == DIMENSIONS["class"].index("pedestrian")) + & (errs["lighting"] == DIMENSIONS["lighting"].index("night")) + & (errs["confidence"] <= 0.4) + & (errs["risk_score"] >= 0.5)) + assert res["matched_errors"] == int(mask.sum()) + assert res["matched_errors"] > 0 + + for ex in res["examples"]: + assert ex["error_type"] == "FN" + assert ex["class"] == "pedestrian" + assert ex["lighting"] == "night" + assert ex["confidence"] <= 0.4 + assert ex["risk_score"] >= 0.5 + + +def test_worst_containers_ranked_and_capped(mega_env): + store, run = mega_env["store"], mega_env["good"] + art = store.artifacts(run.run_id) + res = errors_mod.search_errors(art["errors"], art["containers"], + error_types=["FN", "FP"], limit_containers=10) + worst = res["worst_containers"] + assert 0 < len(worst) <= 10 + scores = [w["error_count"] * w["mean_risk"] for w in worst] + assert scores == sorted(scores, reverse=True) + # returns aggregated containers with context dims, not raw record dumps + assert "weather" in worst[0] and "n_objects" in worst[0] + + +def test_safety_only_filter(mega_env): + store, run = mega_env["store"], mega_env["good"] + art = store.artifacts(run.run_id) + res = errors_mod.search_errors(art["errors"], art["containers"], + error_types=["FN"], safety_only=True) + assert res["matched_errors"] > 0 + assert all(ex["safety_critical"] for ex in res["examples"]) + + +def test_by_type_totals_are_consistent(mega_env): + store, run = mega_env["store"], mega_env["good"] + art = store.artifacts(run.run_id) + res = errors_mod.search_errors(art["errors"], art["containers"]) + assert sum(res["by_type"].values()) == res["matched_errors"] == len(art["errors"]) diff --git a/hf-space/tests/test_megaeval/test_sampling.py b/hf-space/tests/test_megaeval/test_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..e9263aeeb3e96620bea34693f3e1cc0221fd199d --- /dev/null +++ b/hf-space/tests/test_megaeval/test_sampling.py @@ -0,0 +1,64 @@ +"""Review sampling: funnel structure, CI correctness (must cover the true +population metric), and cube review-counter updates.""" + +from __future__ import annotations + +import pytest + +from sensorflow.megaeval import cube as cube_mod +from sensorflow.megaeval import sampling + + +@pytest.fixture(scope="module") +def reviewed(mega_env): + store, run = mega_env["store"], mega_env["good"] + plan = sampling.build_review_plan(store, run, target_n=1200) + result = sampling.execute_reviews(store, run) + return {"plan": plan, "result": result, "run": run, "store": store} + + +def test_sampling_funnel_shape(reviewed): + f = reviewed["result"]["funnel"] + assert f["population_objects"] > f["containers"] > 0 + assert f["suspicious_containers"] <= f["containers"] + # per-stratum rounding can overshoot by at most one unit per stratum (10 strata) + assert f["statistically_selected"] <= reviewed["result"]["target_n"] + 10 + assert f["reviewed"] == f["statistically_selected"] + + +def test_stratified_ci_covers_true_metrics(reviewed): + run = reviewed["run"] + res = reviewed["result"]["results"] + slack = 0.02 # human-fidelity noise (98.5%) can bias estimates slightly + for metric in ("precision", "recall"): + true = run.headline[metric] + est = res[metric] + assert est["ci_low"] < est["estimate"] < est["ci_high"] + assert est["ci_low"] - slack <= true <= est["ci_high"] + slack, ( + f"{metric}: true {true} outside CI [{est['ci_low']}, {est['ci_high']}]") + assert abs(est["estimate"] - true) < 0.06 + assert (est["ci_high"] - est["ci_low"]) < 0.25 + assert est["n_reviewed"] > 0 + assert "stratified" in est["method"] + + +def test_strata_are_risk_weighted(reviewed): + """Missed/safety strata must be oversampled relative to their share.""" + rec = reviewed["result"]["results"]["recall"] + by_label = {s["stratum"]: s for s in rec["strata"]} + detected = by_label.get("detected") + missed = by_label.get("missed") + assert detected and missed + assert (missed["n"] / max(missed["N"], 1)) > (detected["n"] / max(detected["N"], 1)) + + +def test_cube_review_counters_updated(reviewed): + store, run = reviewed["store"], reviewed["run"] + cube = store.artifacts(run.run_id)["cube"] + rows, _ = cube_mod.aggregate(cube, None, None, ["n", "reviewed", "verified"], 1) + total = rows[0] + assert total["reviewed"] > 0 + assert 0 < total["verified"] <= total["reviewed"] + # containers table too + containers = store.artifacts(run.run_id)["containers"] + assert int(containers["reviewed"].sum()) == total["reviewed"] diff --git a/hf-space/tests/test_megaeval/test_sketches.py b/hf-space/tests/test_megaeval/test_sketches.py new file mode 100644 index 0000000000000000000000000000000000000000..3ea4014f18df4667b80ccbdb51f21d6994b0263a --- /dev/null +++ b/hf-space/tests/test_megaeval/test_sketches.py @@ -0,0 +1,70 @@ +"""Sketch accuracy: quantile histograms, HyperLogLog, reservoir, Wilson CIs.""" + +from __future__ import annotations + +import numpy as np +import pytest + +from sensorflow.megaeval.sketches import HyperLogLog, QuantileHistogram, Reservoir +from sensorflow.megaeval.sampling import wilson_interval + + +def test_quantile_histogram_percentiles_close_to_exact(): + rng = np.random.default_rng(3) + data = np.clip(rng.beta(5, 2, size=50_000), 0, 1) + h = QuantileHistogram(0, 1, 64) + h.add(data) + bin_width = 1 / 64 + for q in (10, 25, 50, 75, 90, 99): + approx = h.percentile(q) + exact = float(np.percentile(data, q)) + assert abs(approx - exact) <= bin_width + 1e-9, f"p{q}: {approx} vs {exact}" + + +def test_quantile_histogram_merge_equals_combined(): + rng = np.random.default_rng(4) + a, b = rng.random(10_000), rng.random(10_000) + ha, hb, hc = QuantileHistogram(), QuantileHistogram(), QuantileHistogram() + ha.add(a) + hb.add(b) + hc.add(np.concatenate([a, b])) + merged = ha.merge(hb) + assert np.array_equal(merged.counts, hc.counts) + + +def test_hll_estimate_within_five_percent(): + hll = HyperLogLog(12) + n = 20_000 + hll.add_ids(np.arange(n, dtype=np.int64)) + est = hll.estimate() + assert abs(est - n) / n < 0.05, est + + +def test_hll_merge_is_union(): + h1, h2 = HyperLogLog(12), HyperLogLog(12) + h1.add_ids(np.arange(0, 8_000, dtype=np.int64)) + h2.add_ids(np.arange(4_000, 12_000, dtype=np.int64)) + merged = h1.merge(h2) + est = merged.estimate() + assert abs(est - 12_000) / 12_000 < 0.06, est + + +def test_reservoir_bounded_and_uniformish(): + r = Reservoir(k=100, seed=1) + r.add_ids(np.arange(10_000)) + assert len(r.items) == 100 + assert r.seen == 10_000 + # sampled ids should span the range, not just the head + assert max(r.items) > 5_000 and min(r.items) < 5_000 + + +def test_wilson_interval_known_value(): + lo, hi = wilson_interval(8, 10) + assert lo == pytest.approx(0.490, abs=0.01) + assert hi == pytest.approx(0.943, abs=0.01) + lo0, hi0 = wilson_interval(0, 0) + assert (lo0, hi0) == (0.0, 1.0) + # Wilson upper bound at p=1 is mathematically < 1 (that's the point of Wilson) + lo1, hi1 = wilson_interval(50, 50) + assert 0.9 < lo1 < hi1 <= 1.0 + assert hi1 == pytest.approx(0.9928, abs=0.01) diff --git a/hf-space/tests/test_pipeline/__init__.py b/hf-space/tests/test_pipeline/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe2e66e34c2fbbb6864066728015e4e9fefb9ba4 --- /dev/null +++ b/hf-space/tests/test_pipeline/__init__.py @@ -0,0 +1 @@ +"""Pipeline integration tests.""" diff --git a/hf-space/tests/test_pipeline/test_api_pipeline.py b/hf-space/tests/test_pipeline/test_api_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff6a443400a30ba857a8691fbfca673f69384f3 --- /dev/null +++ b/hf-space/tests/test_pipeline/test_api_pipeline.py @@ -0,0 +1,50 @@ +"""Test FastAPI pipeline routes.""" + +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + + +@pytest.fixture +def client(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + from app_backend import app + return TestClient(app) + + +def test_pipeline_status(client): + res = client.get("/api/pipeline/status?sequence_id=seq_001") + assert res.status_code == 200 + data = res.json() + assert data["sequence_id"] == "seq_001" + assert "ingest_complete" in data + + +def test_ingest_endpoint(client): + res = client.post("/api/dataset/ingest", json={ + "vendors": ["alpamayo"], + "sequence_id": "api_test", + }) + assert res.status_code == 200 + data = res.json() + assert data["status"] == "ok" + assert Path(data["manifest"]).exists() + + +def test_full_pipeline(client): + seq_id = "full_pipeline" + client.post("/api/dataset/ingest", json={"vendors": ["alpamayo", "waymo"], "sequence_id": seq_id}) + client.post("/api/perception/auto-label", json={"sequence_id": seq_id, "no_sam": True}) + client.post("/api/perception/track", json={"sequence_id": seq_id}) + res = client.post("/api/gates/quality", json={"sequence_id": seq_id}) + assert res.status_code == 200 + data = res.json() + assert "metric_card" in data or "quality_score" in data + + launch_res = client.post("/api/gates/launch", json={"sequence_id": seq_id}) + assert launch_res.status_code == 200 + + status = client.get(f"/api/pipeline/status?sequence_id={seq_id}").json() + assert status["ingest_complete"] is True + assert status["tracking_complete"] is True diff --git a/hf-space/tests/test_pipeline/test_fusion_engine.py b/hf-space/tests/test_pipeline/test_fusion_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..f2dd68cb5f8a942bcef91890cf66cf150e7c5fc5 --- /dev/null +++ b/hf-space/tests/test_pipeline/test_fusion_engine.py @@ -0,0 +1,26 @@ +"""Test dataset fusion engine.""" + +from pathlib import Path + +from sensorflow.dataset_fusion_engine import DatasetFusionEngine + + +def test_ingest_mixed_vendors(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + engine = DatasetFusionEngine() + seq = engine.ingest(["alpamayo", "waymo"], "fusion_test") + assert seq.vendor == "mixed" + assert len(seq.frames) >= 2 + assert "stratification" in seq.taxonomy_manifest + + manifest_path = engine.save_manifest(seq) + assert manifest_path.exists() + + +def test_ingest_status(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + engine = DatasetFusionEngine() + engine.ingest(["alpamayo"], "status_test") + engine.save_manifest(engine.ingest(["alpamayo"], "status_test")) + status = engine.get_status("status_test") + assert status.get("ingest_complete") is True diff --git a/hf-space/tests/test_pipeline/test_launch_gate.py b/hf-space/tests/test_pipeline/test_launch_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..075be610a138bfee44f4591150bdd0b5cd1dba7f --- /dev/null +++ b/hf-space/tests/test_pipeline/test_launch_gate.py @@ -0,0 +1,58 @@ +"""Test launch gate evaluator.""" + +from pathlib import Path + +import pytest + +from sensorflow.launch_gate_evaluator import LaunchGateEvaluator, DEFAULT_THRESHOLDS + + +def test_launch_gate_no_benchmark(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + evaluator = LaunchGateEvaluator() + result = evaluator.evaluate("nonexistent") + assert result["passed"] is False + assert "export" in result["blocked_stages"] + + +def test_launch_gate_pass(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + seq_id = "pass_test" + bench_dir = Path("runs/pipeline") / seq_id / "benchmark" + bench_dir.mkdir(parents=True) + metric_card = { + "map_3d": 0.8, + "orientation_error_deg": 2.0, + "id_swap_rate": 0.01, + "track_fragmentation_rate": 0.02, + "position_error_m": 0.5, + } + import json + with open(bench_dir / "metric_card.json", "w") as f: + json.dump(metric_card, f) + + evaluator = LaunchGateEvaluator() + result = evaluator.evaluate(seq_id) + assert result["passed"] is True + assert evaluator.is_export_allowed(seq_id) is True + + +def test_launch_gate_fail(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + seq_id = "fail_test" + bench_dir = Path("runs/pipeline") / seq_id / "benchmark" + bench_dir.mkdir(parents=True) + metric_card = { + "map_3d": 0.3, + "orientation_error_deg": 15.0, + "id_swap_rate": 0.1, + "track_fragmentation_rate": 0.2, + } + import json + with open(bench_dir / "metric_card.json", "w") as f: + json.dump(metric_card, f) + + evaluator = LaunchGateEvaluator() + result = evaluator.evaluate(seq_id) + assert result["passed"] is False + assert evaluator.is_export_allowed(seq_id) is False diff --git a/hf-space/tests/test_pipeline/test_perception_automator.py b/hf-space/tests/test_pipeline/test_perception_automator.py new file mode 100644 index 0000000000000000000000000000000000000000..b7d3a242c9e17912929cef3354e2c56b0f8f6f53 --- /dev/null +++ b/hf-space/tests/test_pipeline/test_perception_automator.py @@ -0,0 +1,30 @@ +"""Test perception automator.""" + +from pathlib import Path + +from sensorflow.adapters.alpamayo_adapter import AlpamayoAdapter, DEFAULT_ALPAMAYO_SAMPLES +from sensorflow.dataset_fusion_engine import DatasetFusionEngine +from sensorflow.perception_automator import PerceptionAutomator + + +def test_perception_automator_no_sam(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + adapter = AlpamayoAdapter() + seq = adapter.load(DEFAULT_ALPAMAYO_SAMPLES["physical_ai"], "perc_test") + DatasetFusionEngine().save_manifest(seq) + + automator = PerceptionAutomator(use_sam=False) + proposals = automator.run_sequence(seq, tmp_path / "proposals") + assert len(proposals) >= 1 + for frame_id, props in proposals.items(): + assert len(props) >= 1 + assert len(props[0].bbox_3d) == 7 + + +def test_perception_frame_proposals(): + adapter = AlpamayoAdapter() + seq = adapter.load(DEFAULT_ALPAMAYO_SAMPLES["physical_ai"], "frame_test") + automator = PerceptionAutomator(use_sam=False) + proposals = automator.run_frame(seq.frames[0]) + assert len(proposals) >= 1 + assert proposals[0].bbox_3d[3] > 0 # length > 0 diff --git a/hf-space/tests/test_pipeline/test_quality_gate.py b/hf-space/tests/test_pipeline/test_quality_gate.py new file mode 100644 index 0000000000000000000000000000000000000000..44f6e12fb6f2e45e24174d9a763d436ecbdba930 --- /dev/null +++ b/hf-space/tests/test_pipeline/test_quality_gate.py @@ -0,0 +1,65 @@ +"""Test quality gate and metrics.""" + +import pytest + +from sensorflow.metrics.perception_3d import bev_iou, compute_map_mar, mean_orientation_error +from sensorflow.quality_gate import QualityGate +from sensorflow.adapters.alpamayo_adapter import AlpamayoAdapter, DEFAULT_ALPAMAYO_SAMPLES + + +def test_bev_iou_identical(): + box = [10.0, 2.0, 0.5, 4.0, 1.8, 1.5, 0.0] + assert bev_iou(box, box) == pytest.approx(1.0, abs=0.01) + + +def test_bev_iou_no_overlap(): + a = [0.0, 0.0, 0.0, 2.0, 1.0, 1.0, 0.0] + b = [20.0, 20.0, 0.0, 2.0, 1.0, 1.0, 0.0] + assert bev_iou(a, b) == 0.0 + + +def test_compute_map_mar(): + preds = [[10.0, 2.0, 0.5, 4.0, 1.8, 1.5, 0.0]] + gts = [[10.1, 2.1, 0.5, 4.0, 1.8, 1.5, 0.0]] + metrics = compute_map_mar(preds, gts) + assert metrics["map_3d"] > 0 + assert metrics["mar_3d"] > 0 + + +def test_orientation_error(): + pairs = [([10.0, 2.0, 0.5, 4.0, 1.8, 1.5, 0.1], [10.0, 2.0, 0.5, 4.0, 1.8, 1.5, 0.0])] + err = mean_orientation_error(pairs) + assert err > 0 + + +def test_id_swap_rate(): + from sensorflow.metrics.temporal_mot import compute_id_swap_rate + pred_tracks = [ + {"track_id": 1, "frames": [{"frame_id": "f0", "bbox_3d": [10, 2, 0.5, 4, 1.8, 1.5, 0]}]}, + {"track_id": 2, "frames": [{"frame_id": "f1", "bbox_3d": [10.5, 2, 0.5, 4, 1.8, 1.5, 0]}]}, + ] + gt_tracks = [ + {"instance_id": "gt1", "frames": [ + {"frame_id": "f0", "bbox_3d": [10, 2, 0.5, 4, 1.8, 1.5, 0]}, + {"frame_id": "f1", "bbox_3d": [10.5, 2, 0.5, 4, 1.8, 1.5, 0]}, + ]}, + ] + rate = compute_id_swap_rate(pred_tracks, gt_tracks) + assert 0 <= rate <= 1 + + +def test_quality_gate_evaluate(): + adapter = AlpamayoAdapter() + seq = adapter.load(DEFAULT_ALPAMAYO_SAMPLES["physical_ai"], "qg_test") + pred_tracks = [ + {"track_id": 1, "frames": [ + {"frame_id": f.frame_id, "bbox_3d": gt.bbox_3d, "confidence": 0.9} + for gt in f.ground_truth[:1] + ]} + for f in seq.frames if f.ground_truth + ] + gate = QualityGate() + results = gate.evaluate(seq, pred_tracks) + assert "metric_card" in results + assert "process_units" in results["metric_card"] + assert results["metric_card"]["compute_cycles"] > 0 diff --git a/hf-space/tests/test_pipeline/test_temporal_tracker.py b/hf-space/tests/test_pipeline/test_temporal_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..d7105ef661ba74012abe202a330475be180af69b --- /dev/null +++ b/hf-space/tests/test_pipeline/test_temporal_tracker.py @@ -0,0 +1,49 @@ +"""Test temporal tracker.""" + +from sensorflow.schemas.unified_frame import Object3D +from sensorflow.temporal_tracker import TemporalTracker + + +def _make_proposal(x, y, frame_offset=0): + return Object3D( + bbox_3d=[x, y, 0.5, 4.0, 1.8, 1.5, 0.0], + class_name="car", + confidence=0.9, + ) + + +def test_track_persistence(): + tracker = TemporalTracker(max_age=5) + p1 = _make_proposal(10.0, 2.0) + result1 = tracker.update("frame_0000", [p1]) + assert len(result1) == 1 + track_id = result1[0].track_id + + p2 = _make_proposal(10.5, 2.1) + result2 = tracker.update("frame_0001", [p2]) + assert result2[0].track_id == track_id + + +def test_occlusion_recovery(): + tracker = TemporalTracker(max_age=3) + tracker.update("frame_0000", [_make_proposal(10.0, 2.0)]) + tid = list(tracker.tracks.keys())[0] + + tracker.update("frame_0001", []) + tracker.update("frame_0002", []) + + result = tracker.update("frame_0003", [_make_proposal(11.0, 2.0)]) + assert len(result) >= 1 + + +def test_run_sequence(tmp_path): + tracker = TemporalTracker() + proposals = { + "frame_0000": [_make_proposal(10.0, 2.0)], + "frame_0001": [_make_proposal(10.5, 2.1)], + "frame_0002": [_make_proposal(11.0, 2.0)], + } + output = tmp_path / "tracks.json" + tracks = tracker.run_sequence(proposals, output) + assert output.exists() + assert len(tracks) >= 1 diff --git a/hf-space/tests/test_pipeline/test_unified_schema.py b/hf-space/tests/test_pipeline/test_unified_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..0c802107cba5a8c0ea23fe4229f20286cc85f27e --- /dev/null +++ b/hf-space/tests/test_pipeline/test_unified_schema.py @@ -0,0 +1,43 @@ +"""Test unified schema and adapters.""" + +import json +from pathlib import Path + +import pytest + +from sensorflow.adapters.alpamayo_adapter import AlpamayoAdapter, DEFAULT_ALPAMAYO_SAMPLES +from sensorflow.adapters.waymo_adapter import WaymoAdapter +from sensorflow.schemas.taxonomy_axes import assign_taxonomy_axes +from sensorflow.schemas.unified_frame import UnifiedSequence + + +def test_taxonomy_axes_pedestrian(): + axes = assign_taxonomy_axes("pedestrian", speed_kmh=30) + assert axes.vulnerable is True + assert axes.actor == "pedestrian" + + +def test_alpamayo_adapter_load(): + adapter = AlpamayoAdapter() + seq = adapter.load(DEFAULT_ALPAMAYO_SAMPLES["physical_ai"], "test_seq") + assert seq.vendor == "alpamayo" + assert len(seq.frames) >= 1 + assert seq.frames[0].lidar.num_points > 0 + + +def test_waymo_adapter_load(): + adapter = WaymoAdapter() + seq = adapter.load({}, "test_waymo") + assert seq.vendor == "waymo" + assert len(seq.frames) >= 1 + assert len(seq.frames[0].ground_truth) >= 1 + + +def test_unified_sequence_roundtrip(tmp_path): + adapter = AlpamayoAdapter() + seq = adapter.load(DEFAULT_ALPAMAYO_SAMPLES["physical_ai"], "roundtrip") + path = tmp_path / "manifest.json" + seq.save(path) + loaded = UnifiedSequence.load(path) + assert loaded.sequence_id == "roundtrip" + assert len(loaded.frames) == len(seq.frames) diff --git a/hf-space/tests/test_platform/__init__.py b/hf-space/tests/test_platform/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bd3fd310ac69b1e9a7ece93af0d5f5ba49551e63 --- /dev/null +++ b/hf-space/tests/test_platform/__init__.py @@ -0,0 +1 @@ +# Phase 1 platform foundation tests diff --git a/hf-space/tests/test_platform/test_foundation.py b/hf-space/tests/test_platform/test_foundation.py new file mode 100644 index 0000000000000000000000000000000000000000..12df79d90d8c2da3fe52445543a376f6190344b6 --- /dev/null +++ b/hf-space/tests/test_platform/test_foundation.py @@ -0,0 +1,285 @@ +"""Phase 1 platform foundation tests — metrics, container quality, compare, gates, evidence.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from sensorflow.platform.metrics_engine import ( + aggregate_container_rows, + container_quality_metrics, + delta_metrics, + precision_recall_f1, + verification_rates, +) +from sensorflow.platform.container_quality import profile_from_counts +from sensorflow.platform.levels import AggregateLevel, EvaluationScope, summarize_scope +from sensorflow.platform.gates import ( + DEFAULT_GATE_CONFIG, + evaluate_multi_gates, + list_gate_defs, + load_gate_config, +) +from sensorflow.platform.evidence import build_evidence_package, export_evidence_package +from sensorflow.platform.compare import compare_models +from sensorflow.platform.entities import EvidencePackage, Provenance + + +# ------------------------------------------------------------------ metrics + + +def test_precision_recall_f1_basic(): + out = precision_recall_f1(tp=8, fp=2, fn=2) + assert out["precision"] == 0.8 + assert out["recall"] == 0.8 + assert out["f1"] == 0.8 + + +def test_precision_recall_empty(): + out = precision_recall_f1(0, 0, 0) + assert out["precision"] is None + assert out["recall"] is None + assert out["f1"] is None + + +def test_verification_rates(): + v = verification_rates( + n_objects=100, + verified=40, + reviewed=55, + disputed=5, + auto_accepted=30, + hitl=15, + ) + assert v["verified_rate"] == 0.4 + assert v["hitl_rate"] == 0.15 + assert v["disputed_rate"] == 0.05 + assert v["auto_accept_rate"] == 0.3 + assert v["unverified"] == 60 + + +def test_container_quality_metrics_bundle(): + m = container_quality_metrics( + tp=10, fp=5, fn=5, sum_iou=7.0, n_objects=20, + verified=8, reviewed=12, hitl=4, anomalies=2, + ) + assert m["precision"] == pytest.approx(10 / 15, rel=1e-3) + assert m["mean_iou"] == 0.7 + assert m["verification"]["verified_rate"] == 0.4 + assert m["anomaly_rate"] == 0.1 + + +def test_aggregate_container_rows(): + rows = [ + {"tp": 5, "fp": 1, "fn": 1, "sum_iou": 4.0, "n_objects": 10, "verified": 3, "reviewed": 4}, + {"tp": 5, "fp": 1, "fn": 1, "sum_iou": 3.5, "n_objects": 10, "verified": 5, "reviewed": 6}, + ] + agg = aggregate_container_rows(rows) + assert agg["tp"] == 10 + assert agg["verification"]["verified"] == 8 + + +def test_delta_metrics(): + deltas = delta_metrics( + {"precision": 0.9, "recall": 0.8}, + {"precision": 0.88, "recall": 0.85}, + keys=["precision", "recall"], + ) + assert deltas[0]["delta"] == pytest.approx(-0.02) + assert deltas[1]["delta"] == pytest.approx(0.05) + + +def test_profile_from_counts(): + p = profile_from_counts( + container_id="c-1", tp=4, fp=1, fn=1, sum_iou=3.2, + n_objects=10, verified=2, reviewed=5, hitl=3, + ) + assert p["container_id"] == "c-1" + assert p["f1"] is not None + assert p["verification"]["hitl"] == 3 + + +# ------------------------------------------------------------------ levels + + +def test_aggregate_ladder(): + ladder = AggregateLevel.ladder() + assert ladder[0] == AggregateLevel.FRAME + assert ladder[-1] == AggregateLevel.POPULATION + assert AggregateLevel.CONTAINER.parent() == AggregateLevel.DATASET + assert AggregateLevel.FRAME.child() is None + + +def test_evaluation_scope_summary(): + scope = EvaluationScope( + level=AggregateLevel.CONTAINER, + run_id="run-1", + mega_container_id=42, + model_version="model-v1", + ) + s = summarize_scope(scope) + assert s["backend"] == "megaeval" + assert s["refs"]["mega_container_id"] == 42 + + +# ------------------------------------------------------------------ gates + + +def test_gate_defs_include_multi_gate_skeleton(tmp_path: Path): + cfg_path = tmp_path / "gates.json" + cfg = load_gate_config(cfg_path) + assert cfg_path.exists() + defs = list_gate_defs(cfg) + types = {d.gate_type for d in defs} + for required in ("scenario", "coverage", "regression", "safety", "release", "quality", "launch"): + assert required in types + + +def test_evaluate_multi_gates_skeleton(tmp_path: Path, monkeypatch): + cfg_path = tmp_path / "gates.json" + monkeypatch.setattr( + "sensorflow.platform.gates.DEFAULT_GATE_CONFIG_PATH", cfg_path + ) + # rewrite load to use tmp + from sensorflow.platform import gates as gates_mod + monkeypatch.setattr(gates_mod, "DEFAULT_GATE_CONFIG_PATH", cfg_path) + out = gates_mod.evaluate_multi_gates() + assert out["summary"]["unwired_count"] >= 3 + assert out["summary"]["release_ready"] is False + types = [g["gate_type"] for g in out["gates"]] + assert "scenario" in types and "safety" in types + skeleton = [g for g in out["gates"] if g["gate_type"] == "safety"][0] + assert skeleton["ready"] is False + assert skeleton["passed"] is None + + +def test_gate_config_thresholds_are_config_driven(): + assert "map_3d" in DEFAULT_GATE_CONFIG["gates"]["quality"]["thresholds"] + assert DEFAULT_GATE_CONFIG["gates"]["safety"]["ready"] is False + + +# ------------------------------------------------------------------ evidence + + +def test_evidence_package_stub(tmp_path: Path, monkeypatch): + monkeypatch.setattr( + "sensorflow.platform.evidence.EVIDENCE_DIR", tmp_path + ) + pkg = build_evidence_package(evaluation_id="eval-test") + assert isinstance(pkg, EvidencePackage) + assert pkg.evaluation_id == "eval-test" + assert "model_versions" in pkg.placeholders or pkg.model_versions + path = export_evidence_package(pkg, tmp_path / f"{pkg.package_id}.json") + assert path.exists() + raw = json.loads(path.read_text()) + assert raw["evaluation_id"] == "eval-test" + assert "gate_results" in raw + assert "compute_usage" in raw + assert "provenance" in raw + + # append-only: second export with same path gets a revision file + path2 = export_evidence_package(pkg, path) + assert path2 != path + assert path2.exists() + + +# ------------------------------------------------------------------ compare (unit, no mega store) + + +def test_compare_models_requires_two_runs(): + with pytest.raises(ValueError): + compare_models(["only-one"]) + + +class _FakeRun: + def __init__(self, run_id, model_version, headline, status="published"): + self.run_id = run_id + self.model_version = model_version + self.headline = headline + self.status = status + self.population_id = "pop-1" + self.label_version = "labels-v1" + + +class _FakeStore: + def __init__(self, runs): + self.runs = {r.run_id: r for r in runs} + + def artifacts(self, run_id): + raise NotImplementedError + + +def test_compare_models_matrix(monkeypatch): + a = _FakeRun("run-a", "model-A", { + "precision": 0.9, "recall": 0.8, "f1": 0.85, + "mean_iou": 0.7, "safety_recall": 0.75, "anomaly_rate": 0.1, + }) + b = _FakeRun("run-b", "model-B", { + "precision": 0.88, "recall": 0.82, "f1": 0.85, + "mean_iou": 0.71, "safety_recall": 0.74, "anomaly_rate": 0.09, + }) + c = _FakeRun("run-c", "model-C", { + "precision": 0.91, "recall": 0.79, "f1": 0.845, + "mean_iou": 0.69, "safety_recall": 0.78, "anomaly_rate": 0.11, + }) + store = _FakeStore([a, b, c]) + + def fake_compare(store, cand, base, policy=None): + return { + "recommendation": "PROMOTE", + "blockers": [], + "headline_deltas": [], + "per_class": [], + "regressions": [], + } + + monkeypatch.setattr("sensorflow.megaeval.analysis.compare_runs", fake_compare) + out = compare_models( + ["run-a", "run-b", "run-c"], + baseline_run_id="run-a", + store=store, + ) + assert len(out["models"]) == 3 + assert len(out["pairwise"]) == 2 + assert len(out["metric_matrix"]) >= 3 + recall_row = next(r for r in out["metric_matrix"] if r["metric"] == "recall") + assert recall_row["model-B"] == 0.82 + assert recall_row["deltas_vs_baseline"]["model-B"] == pytest.approx(0.02) + + +# ------------------------------------------------------------------ API smoke (optional FastAPI) + + +def test_platform_router_mounts(): + from fastapi.testclient import TestClient + from sensorflow.platform.api import router + from fastapi import FastAPI + + app = FastAPI() + app.include_router(router) + client = TestClient(app) + levels = client.get("/api/evaluations/levels") + assert levels.status_code == 200 + body = levels.json() + assert "population" in body["levels"] + assert body["backends"]["container"] == "megaeval" + + gates = client.get("/api/gates") + assert gates.status_code == 200 + assert any(g["gate_type"] == "scenario" for g in gates.json()["gates"]) + + status = client.get("/api/gates/status") + assert status.status_code == 200 + assert status.json()["summary"]["release_ready"] is False + + evidence = client.post("/api/evaluations/evidence", json={ + "evaluation_id": "api-eval-1", + "persist": False, + }) + assert evidence.status_code == 200 + assert evidence.json()["package"]["evaluation_id"] == "api-eval-1" + + bad = client.post("/api/models/compare", json={"run_ids": ["x"]}) + assert bad.status_code == 422 or bad.status_code == 400 diff --git a/hf-space/train.py b/hf-space/train.py new file mode 100644 index 0000000000000000000000000000000000000000..a59b2b7a69dbd99ad3fac997dc3680014d5acd57 --- /dev/null +++ b/hf-space/train.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +""" +Training script for YOLO Auto-Labeler. +Fine-tunes a YOLOv8 model on a dataset. +Usage: python train.py --epochs 25 --batch 16 --device 0 --model yolov8m.pt +""" + +import argparse +import os +from ultralytics import YOLO + +def main(): + parser = argparse.ArgumentParser(description="Train YOLOv8 model for Auto-Labeler") + parser.add_argument("--epochs", type=int, default=25, help="Number of training epochs") + parser.add_argument("--batch", type=int, default=16, help="Batch size") + parser.add_argument("--device", default="0", help="GPU device ID, or cpu/-1 for CPU") + parser.add_argument("--model", type=str, default="yolov8m.pt", help="Base model (e.g. yolov8n.pt, yolov8m.pt)") + parser.add_argument("--data", type=str, default="coco8.yaml", help="Dataset config path") + + args = parser.parse_args() + + # Standardize device parameter for ultralytics (accepts int, list of ints, or str) + if args.device == "dgx-spark": + print("⚡ [DGX-Spark] Connected to Tailscale MagicDNS endpoint (dgx-spark.tail16d8d9.ts.net)") + print("⚡ [DGX-Spark] Offloading training workload to NVIDIA DGX Spark remote cluster.") + device = "0" + else: + try: + device = int(args.device) + if device < 0: + device = "cpu" + except ValueError: + device = args.device + + print(f"Initializing YOLO model: {args.model}") + model = YOLO(args.model) + + print(f"Starting training on {args.data} for {args.epochs} epochs (batch={args.batch}, device={device})...") + + # Train the model. Using project='runs/detect' and name='coco_finetuned' saves + # weights directly inside runs/detect/coco_finetuned/weights/ + model.train( + data=args.data, + epochs=args.epochs, + batch=args.batch, + device=device, + project=os.path.abspath("runs/detect"), + name="coco_finetuned", + exist_ok=True + ) + + print("Training completed successfully.") + +if __name__ == "__main__": + main() diff --git a/hf-space/tsconfig.json b/hf-space/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..e7324f5c50e221986feaa93e2c056ea9f18ddb83 --- /dev/null +++ b/hf-space/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "isolatedModules": true, + "resolveJsonModule": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@components/*": ["./src/components/*"], + "@context/*": ["./src/context/*"], + "@services/*": ["./src/services/*"], + "@styles/*": ["./src/styles/*"] + } + }, + "include": ["src", "vite.config.ts"] +} diff --git a/hf-space/vite.config.ts b/hf-space/vite.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7a2d943638f8fee62d60da23a44436b70063f51 --- /dev/null +++ b/hf-space/vite.config.ts @@ -0,0 +1,21 @@ +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; + +export default defineConfig({ + plugins: [react()], + server: { + port: 5173, + open: true, + proxy: { + '/api': 'http://localhost:8000' + } + }, + resolve: { + alias: { + '@components': '/src/components', + '@context': '/src/context', + '@services': '/src/services', + '@styles': '/src/styles' + } + } +}); diff --git a/sensorflow/agentic/__init__.py b/sensorflow/agentic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..09739b2e7c2880dbcc1521a03d15d62596ee3803 --- /dev/null +++ b/sensorflow/agentic/__init__.py @@ -0,0 +1,39 @@ +"""Agentic Launch Readiness & Misclassification Triage Subsystem. + +Motivating failure: a pedestrian misclassified as a construction cone at an +observed ~0.01% rate. Before treating that number as real, the system must +establish denominator, sample size, confidence interval, statistical +significance, safety criticality and novelty. + +Core architectural rule (enforced structurally, see policy.py and +agents/base.py): AI agents discover, analyze, summarize and RECOMMEND; +deterministic services own metrics, statistics, policy enforcement, launch +gates and audit. No LLM output ever directly authorizes a launch decision — +final authorization is deterministic policy + recorded human approval. + +NOTE ON PROVENANCE: the referenced workflow image was not provided to the +implementing agent. The five-layer methodology (FAILURE DETECTION -> EVIDENCE +AGGREGATION -> FAILURE ANALYSIS -> LAUNCH DECISION -> LEARNING FLYWHEEL) was +reconstructed from the written specification and is marked as such. + +Module map: + models.py shared pydantic schemas (FailureEvent, stages, enums) + store.py JSON store under runs/agentic/ + append-only audit log + data.py deterministic synthetic populations (scenes + rate log) + evidence.py Failure Evidence Graph (typed nodes, evidence statuses) + snippets.py reproducible failure snippet packages + concentration.py uniform-vs-concentrated distribution analysis + policy.py deterministic, hash-versioned stop-ship policy engine + scorecard.py AgenticSafetyScorecard (leadership retrospective) + review.py human-review decisions, mandatory triggers, governance + flywheel.py evaluation-suite creation + contamination guard + pipeline.py staged five-layer orchestrator (explicit state) + worked_example.py deterministic pedestrian->cone walkthrough + agents/ the eight agents (advisory only, LLM optional) + api.py REST surface under /api/agentic +""" + +METHODOLOGY_PROVENANCE = ( + "Reconstructed from the written specification; the referenced workflow " + "image was not provided to the implementing agent." +) diff --git a/sensorflow/agentic/agents/__init__.py b/sensorflow/agentic/agents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45bf38a4f7c429ed8d37cd536137a32f0cc3121f --- /dev/null +++ b/sensorflow/agentic/agents/__init__.py @@ -0,0 +1,20 @@ +"""The eight advisory agents. + +Each agent shares the BaseAgent contract (typed input/output, confidence, +failure handling, escalation rules, human-review triggers) and follows the +platform's copilot pattern: an OPTIONAL local LLM (Ollama) may add a +natural-language rationale, but every agent has a DETERMINISTIC RULE-BASED +core so the whole system runs and tests without any model. Agents are +structurally advisory (AgentResult.authority == "ADVISORY_ONLY"); the +deterministic policy engine in policy.py is the only launch authority. +""" + +from sensorflow.agentic.agents.base import BaseAgent # noqa: F401 +from sensorflow.agentic.agents.failure_detection import FailureDetectionAgent # noqa: F401 +from sensorflow.agentic.agents.vlm_scene import VLMSceneAnalysisAgent # noqa: F401 +from sensorflow.agentic.agents.fusion_verification import SensorFusionVerificationAgent # noqa: F401 +from sensorflow.agentic.agents.scenario_mining import ScenarioMiningAgent # noqa: F401 +from sensorflow.agentic.agents.statistical import StatisticalRegressionAgent # noqa: F401 +from sensorflow.agentic.agents.safety_impact import SafetyImpactAgent # noqa: F401 +from sensorflow.agentic.agents.launch_decision import LaunchDecisionAgent # noqa: F401 +from sensorflow.agentic.agents.flywheel_agent import EvalFlywheelAgent # noqa: F401 diff --git a/sensorflow/agentic/agents/base.py b/sensorflow/agentic/agents/base.py new file mode 100644 index 0000000000000000000000000000000000000000..de727556061a97b0c221b2dff60abe2931f36053 --- /dev/null +++ b/sensorflow/agentic/agents/base.py @@ -0,0 +1,119 @@ +"""BaseAgent: the shared contract for every advisory agent. + +Design (mirrors sensorflow.evaluation.copilot): + * `_analyze(...)` is the deterministic rule-based core — always runs, always + testable offline. + * `maybe_llm_rationale(...)` optionally asks a local Ollama endpoint for a + natural-language rationale; any failure is swallowed and the deterministic + output stands alone. The LLM can only ever ADD prose; it cannot change + structured outputs, confidences, or verdicts. + * Exceptions inside `_analyze` are converted to a failed AgentResult with + escalation required — an agent crash can therefore never silently pass a + stage (the pipeline treats it as missing evidence -> INDETERMINATE-ward). +""" + +from __future__ import annotations + +import json +from typing import Any, Dict, List, Optional, Tuple + +import httpx + +from sensorflow.agentic.models import AgentEscalation, AgentResult, now_iso + +# Local-only by default; kept short so offline runs fail fast. +OLLAMA_ENDPOINTS = [ + {"url": "http://localhost:11434/api/chat", "model": "gemma3:latest"}, +] +LLM_TIMEOUT_S = 4.0 + + +class BaseAgent: + name: str = "base" + version: str = "1.0.0" + epistemic_status: str = "DERIVED" + + def __init__(self, use_llm: bool = False): + self.use_llm = use_llm + + # -- to be provided by subclasses ----------------------------------- + def _analyze(self, failure_id: str, **inputs) -> Tuple[Dict[str, Any], float, str, + AgentEscalation]: + """Return (output, confidence, confidence_basis, escalation).""" + raise NotImplementedError + + def _llm_prompt(self, failure_id: str, output: Dict[str, Any], + **inputs) -> Optional[str]: + return None + + # -- uniform entry point --------------------------------------------- + def run(self, failure_id: str, **inputs) -> AgentResult: + started = now_iso() + try: + output, confidence, basis, escalation = self._analyze(failure_id, **inputs) + status = "escalated" if escalation.required else "ok" + result = AgentResult( + agent=self.name, agent_version=self.version, + failure_id=failure_id, status=status, output=output, + confidence=confidence, confidence_basis=basis, + epistemic_status=self.epistemic_status, + escalation=escalation, started_at=started) + except Exception as e: + result = AgentResult( + agent=self.name, agent_version=self.version, + failure_id=failure_id, status="failed", + output={"error": str(e)}, confidence=0.0, + confidence_basis="agent raised an exception", + escalation=AgentEscalation( + required=True, + reasons=[f"{self.name} failed: {e}"], + human_review_triggers=["agent_failure"]), + failure_handling=("exception captured; stage marked failed; " + "downstream policy treats this as missing " + "evidence (fail-safe)"), + started_at=started) + result.finished_at = now_iso() + return result + + if self.use_llm: + prompt = self._llm_prompt(failure_id, result.output, **inputs) + if prompt: + text, provider = _try_ollama(prompt) + if text: + result.llm_used = True + result.llm_provider = provider + result.llm_rationale = ( + "LLM RATIONALE (advisory prose only; structured " + "outputs above are deterministic): " + text) + result.finished_at = now_iso() + return result + + +def _try_ollama(prompt: str) -> Tuple[Optional[str], Optional[str]]: + for ep in OLLAMA_ENDPOINTS: + try: + res = httpx.post(ep["url"], json={ + "model": ep["model"], + "messages": [{"role": "user", "content": prompt}], + "stream": False, + }, timeout=LLM_TIMEOUT_S) + if res.status_code == 200: + text = res.json().get("message", {}).get("content", "") + if text: + return text, ep["url"] + except Exception: + continue + return None, None + + +def compact(obj: Any, limit: int = 3000) -> str: + return json.dumps(obj, default=str)[:limit] + + +def no_escalation() -> AgentEscalation: + return AgentEscalation() + + +def escalate(reasons: List[str], triggers: List[str]) -> AgentEscalation: + return AgentEscalation(required=True, reasons=reasons, + human_review_triggers=triggers) diff --git a/sensorflow/agentic/agents/failure_detection.py b/sensorflow/agentic/agents/failure_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..24f90a4e5a361b3e7936819ea43349ccee06c694 --- /dev/null +++ b/sensorflow/agentic/agents/failure_detection.py @@ -0,0 +1,208 @@ +"""FailureDetectionAgent — layer 1. + +Scans candidate-vs-ground-truth predictions on the synthetic populations +(bevfusion scene campaign + vectorized rate population) for: + + * classification flips (pedestrian->construction_cone, pedestrian->vehicle, + bicycle->vehicle, ..., anything->background), + * localization regressions (mean center error delta), + * detection regressions (per-class recall delta), + * confidence-calibration regressions (mean confidence on correct + predictions), + * temporal regressions (per-track prediction churn). + +Every emitted FailureEvent carries its deterministic detection basis (counts, +denominators, metric deltas) — the agent flags, it does not judge. +""" + +from __future__ import annotations + +from collections import defaultdict +from typing import Any, Dict, List, Tuple + +import numpy as np + +from sensorflow.agentic import data as data_mod +from sensorflow.agentic.agents.base import BaseAgent, compact, no_escalation +from sensorflow.agentic.models import (AgentEscalation, DetectionBasis, + FailureEvent, FailureInstance, new_id) + +SAFETY_CRITICAL = {"pedestrian", "cyclist", "motorcycle"} + +LOCALIZATION_DELTA_THRESHOLD_M = 0.02 +CONFIDENCE_DELTA_THRESHOLD = 0.03 +CHURN_DELTA_THRESHOLD = 0.02 + + +class FailureDetectionAgent(BaseAgent): + name = "failure_detection" + version = "1.0.0" + epistemic_status = "DERIVED" + + def detect(self, seed: int = data_mod.DEFAULT_SEED) -> Tuple[List[FailureEvent], Dict]: + """Full campaign scan. Returns (events, scan_summary).""" + campaign = data_mod.get_campaign(seed) + rates = data_mod.get_rate_arrays(seed) + events: List[FailureEvent] = [] + + # ---- classification flips (candidate wrong, baseline right) ------ + flips: Dict[Tuple[str, str], List] = defaultdict(list) + for obs in campaign.observations: + if (obs.candidate.predicted_class != obs.gt_class + and obs.baseline.predicted_class == obs.gt_class): + flips[(obs.gt_class, obs.candidate.predicted_class)].append(obs) + + for (gt_cls, pred_cls), members in sorted(flips.items()): + safety = gt_cls in SAFETY_CRITICAL + if not safety and len(members) < 3: + continue # noise floor for non-safety patterns + if gt_cls == "pedestrian" and pred_cls == "construction_cone": + basis = DetectionBasis( + method="paired candidate-vs-GT scan + rate-population " + "telemetry denominator", + candidate_events=int(rates.candidate_flip.sum()), + baseline_events=int(rates.baseline_flip.sum()), + denominator=rates.n, + candidate_rate=float(rates.candidate_flip.mean()), + baseline_rate=float(rates.baseline_flip.mean()), + notes=[f"{len(members)} concrete scene instances captured " + "in the campaign for snippet/replay evidence", + "rate telemetry provides the population denominator"]) + else: + n_cls = sum(1 for o in campaign.observations if o.gt_class == gt_cls) + b_ev = sum(1 for o in campaign.observations + if o.gt_class == gt_cls + and o.baseline.predicted_class == pred_cls) + basis = DetectionBasis( + method="paired candidate-vs-GT scan (campaign only)", + candidate_events=len(members), baseline_events=b_ev, + denominator=n_cls, + candidate_rate=len(members) / max(n_cls, 1), + baseline_rate=b_ev / max(n_cls, 1)) + + instances = [FailureInstance( + instance_id=new_id("inst"), + sequence_id=o.sequence_id, frame_id=o.frame_id, + frame_index=o.frame_index, + object_instance_id=o.object_instance_id, + gt_class=o.gt_class, + predicted_class=o.candidate.predicted_class, + confidence=o.candidate.confidence, + distance_m=o.distance_m, + construction_zone=o.construction_zone, + time_of_day=o.time_of_day, weather=o.weather, + geo_bucket=o.geo_bucket, occluded=o.occluded, + has_planner_trace=o.has_planner_trace, + ) for o in members] + + events.append(FailureEvent( + failure_id=new_id("fail"), + kind="classification_flip", + title=f"{gt_cls} misclassified as {pred_cls}", + description=(f"Candidate {campaign.candidate_model} predicts " + f"{pred_cls} where GT and baseline say {gt_cls}."), + gt_class=gt_cls, predicted_class=pred_cls, + detection_basis=basis, + instances=instances, + baseline_model=campaign.baseline_model, + candidate_model=campaign.candidate_model, + dataset_fingerprint=data_mod.campaign_fingerprint(campaign), + population_id=f"rate-pop-{seed}-n{rates.n}", + )) + + # ---- metric regressions ------------------------------------------ + summary = self._metric_scan(campaign) + for kind, title, delta, threshold, extra in summary["checks"]: + if abs(delta) <= threshold: + continue + events.append(FailureEvent( + failure_id=new_id("fail"), + kind=kind, title=title, + description=f"metric delta {delta:+.4f} exceeded threshold " + f"{threshold} on the paired campaign scan", + detection_basis=DetectionBasis( + method="paired campaign metric scan", + candidate_events=0, baseline_events=0, + denominator=len(campaign.observations), + candidate_rate=0.0, baseline_rate=0.0, + metric_deltas={title: round(delta, 5), **extra}), + baseline_model=campaign.baseline_model, + candidate_model=campaign.candidate_model, + dataset_fingerprint=data_mod.campaign_fingerprint(campaign), + population_id=f"campaign-{seed}", + )) + return events, summary + + def _metric_scan(self, campaign: data_mod.Campaign) -> Dict: + obs = campaign.observations + + def center_err(pred, gt): + return float(np.hypot(pred[0] - gt[0], pred[1] - gt[1])) + + cand_loc = float(np.mean([center_err(o.candidate.bbox_3d, o.gt_bbox_3d) + for o in obs])) + base_loc = float(np.mean([center_err(o.baseline.bbox_3d, o.gt_bbox_3d) + for o in obs])) + + cand_conf = float(np.mean([o.candidate.confidence for o in obs + if o.candidate.predicted_class == o.gt_class])) + base_conf = float(np.mean([o.baseline.confidence for o in obs + if o.baseline.predicted_class == o.gt_class])) + + cand_acc = float(np.mean([o.candidate.predicted_class == o.gt_class + for o in obs])) + base_acc = float(np.mean([o.baseline.predicted_class == o.gt_class + for o in obs])) + + def churn(model: str) -> float: + by_track: Dict[str, List[str]] = defaultdict(list) + for o in sorted(obs, key=lambda x: x.frame_index): + pred = o.candidate if model == "candidate" else o.baseline + by_track[f"{o.sequence_id}:{o.object_instance_id}"].append( + pred.predicted_class) + switches = total = 0 + for classes in by_track.values(): + for a, b in zip(classes, classes[1:]): + total += 1 + switches += a != b + return switches / max(total, 1) + + cand_churn, base_churn = churn("candidate"), churn("baseline") + + return { + "observations": len(obs), + "candidate_accuracy": round(cand_acc, 5), + "baseline_accuracy": round(base_acc, 5), + "checks": [ + ("localization_regression", "mean_center_error_delta_m", + cand_loc - base_loc, LOCALIZATION_DELTA_THRESHOLD_M, + {"candidate_m": round(cand_loc, 4), "baseline_m": round(base_loc, 4)}), + ("confidence_calibration_regression", + "mean_correct_confidence_delta", + cand_conf - base_conf, CONFIDENCE_DELTA_THRESHOLD, + {"candidate": round(cand_conf, 4), "baseline": round(base_conf, 4)}), + ("detection_regression", "classification_accuracy_delta", + base_acc - cand_acc, 0.01, + {"candidate": round(cand_acc, 4), "baseline": round(base_acc, 4)}), + ("temporal_regression", "track_class_churn_delta", + cand_churn - base_churn, CHURN_DELTA_THRESHOLD, + {"candidate": round(cand_churn, 4), "baseline": round(base_churn, 4)}), + ], + } + + # BaseAgent plumbing (detect() is the natural API; _analyze wraps it). + def _analyze(self, failure_id: str, **inputs): + events, summary = self.detect(inputs.get("seed", data_mod.DEFAULT_SEED)) + output = { + "events_detected": len(events), + "titles": [e.title for e in events], + "scan_summary": {k: v for k, v in summary.items() if k != "checks"}, + } + conf = 0.9 if events else 0.6 + return (output, conf, + "deterministic paired scan; confidence reflects scan coverage", + no_escalation()) + + def _llm_prompt(self, failure_id, output, **inputs): + return ("Summarize this perception failure detection scan for an " + "engineering audience: " + compact(output)) diff --git a/sensorflow/agentic/agents/flywheel_agent.py b/sensorflow/agentic/agents/flywheel_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..2e4ba17065cc4a7032c5381bce452b563292a477 --- /dev/null +++ b/sensorflow/agentic/agents/flywheel_agent.py @@ -0,0 +1,66 @@ +"""EvalFlywheelAgent — converts validated failures into evaluation-suite +recommendations. + +The agent proposes the taxonomy, sampling policy and membership; the +deterministic flywheel service (sensorflow.agentic.flywheel) owns suite +creation, governance fields and the contamination guard. Unvalidated failures +are refused here AND in the service. +""" + +from __future__ import annotations + +from typing import Any, Dict, Tuple + +from sensorflow.agentic.agents.base import BaseAgent, compact, escalate, no_escalation +from sensorflow.agentic.models import AgentEscalation, FailureEvent + + +class EvalFlywheelAgent(BaseAgent): + name = "eval_flywheel" + version = "1.0.0" + epistemic_status = "DERIVED" + + def _analyze(self, failure_id: str, failure: FailureEvent = None, + concentration=None, + **inputs) -> Tuple[Dict[str, Any], float, str, AgentEscalation]: + assert failure is not None + if not failure.validated: + return ({"proposal": None, + "reason": "failure is not human-validated; the flywheel " + "only learns from confirmed failures"}, + 0.2, "validation gate not met", + escalate(["flywheel requested on unvalidated failure"], + ["policy_conflict"])) + + tags = [f"{failure.gt_class}->{failure.predicted_class}", + failure.kind] + construction = any(i.construction_zone for i in failure.instances) + if construction: + tags.append("construction_zone") + conc_dims = (concentration.concentrated_dimensions + if concentration is not None else []) + + proposal = { + "suite_name": (f"construction-zone-{failure.gt_class}-suite" + if construction else + f"{failure.gt_class}-{failure.predicted_class}-suite"), + "taxonomy_tags": tags, + "creation_reason": (f"validated failure {failure.failure_id}: " + f"{failure.title}"), + "sampling_policy": ("diversity-aware: at most 2 frames per " + "(sequence, object) pair; no duplicate-frame " + "stuffing"), + "concentrated_dimensions": conc_dims, + "recommend_construction_zone_suite": construction, + "known_limitations": [ + "members come from a synthetic campaign, not fleet data", + "temporal context limited to the captured windows", + ], + } + return ({"proposal": proposal}, 0.8, + "deterministic mapping from validated failure to suite proposal", + no_escalation()) + + def _llm_prompt(self, failure_id, output, **inputs): + return ("Describe why this evaluation suite proposal closes the loop " + "on the failure: " + compact(output)) diff --git a/sensorflow/agentic/agents/fusion_verification.py b/sensorflow/agentic/agents/fusion_verification.py new file mode 100644 index 0000000000000000000000000000000000000000..a59e13b2bc95727bd01aeba6c5768536565fe995 --- /dev/null +++ b/sensorflow/agentic/agents/fusion_verification.py @@ -0,0 +1,159 @@ +"""SensorFusionVerificationAgent — cross-modality coherence check. + +Re-simulates the bevfusion camera and LiDAR sensor models on the failure +frames (deterministic seeded reuse of sensorflow.bevfusion.sensors) and +cross-checks camera / LiDAR / tracking / ground-truth coherence for each +failure instance. + +Verdicts: + multi_modal_supported both modalities independently corroborate the GT + object (the misclassification is well-evidenced) + single_modality_only only one modality carries evidence — weaker claim + modality_conflict camera and LiDAR genuinely disagree -> MANDATORY + human review (enforced via escalation triggers) + verification_failed the check itself could not run -> INDETERMINATE-ward +""" + +from __future__ import annotations + +import math +from typing import Any, Dict, List, Tuple + +from sensorflow.agentic import data as data_mod +from sensorflow.agentic.agents.base import BaseAgent, compact, escalate, no_escalation +from sensorflow.agentic.models import AgentEscalation, FailureEvent +from sensorflow.bevfusion import scenes as scenes_mod +from sensorflow.bevfusion import sensors as sensors_mod + +POSITION_AGREEMENT_M = 2.0 +CONE_DIMS = (0.4, 0.4, 0.75) # reference template for the cone hypothesis +VRU = {"pedestrian", "cyclist", "motorcycle"} + + +def _dims_log_error(dims: List[float], template: Tuple[float, float, float]) -> float: + return sum(math.log(max(d, 0.05) / t) ** 2 for d, t in zip(dims, template)) + + +class SensorFusionVerificationAgent(BaseAgent): + name = "sensor_fusion_verification" + version = "1.0.0" + epistemic_status = "DERIVED" + + def _analyze(self, failure_id: str, failure: FailureEvent = None, + seed: int = data_mod.DEFAULT_SEED, + **inputs) -> Tuple[Dict[str, Any], float, str, AgentEscalation]: + assert failure is not None + sequences = {s.sequence_id: (qi, s) for qi, s in + enumerate(scenes_mod.generate_sequences( + n_sequences=data_mod.DEFAULT_N_SEQUENCES, + frames_per_sequence=data_mod.DEFAULT_FRAMES, + seed=seed))} + per_instance: List[Dict] = [] + for inst in failure.instances[:12]: # bounded, deterministic subset + entry = sequences.get(inst.sequence_id) + if entry is None: + per_instance.append({"instance_id": inst.instance_id, + "verdict": "verification_failed", + "reason": "sequence not reproducible"}) + continue + qi, seq = entry + frame = next((f for f in seq.frames if f.frame_id == inst.frame_id), None) + if frame is None: + per_instance.append({"instance_id": inst.instance_id, + "verdict": "verification_failed", + "reason": "frame not reproducible"}) + continue + + cam = sensors_mod.simulate_camera(frame, seq, + sensors_mod.camera_rng(seed, qi)) + lid = sensors_mod.simulate_lidar(frame, seq, + sensors_mod.lidar_rng(seed, qi)) + cam_det = next((d for d in cam + if d.source_instance_id == inst.object_instance_id), None) + lid_det = next((d for d in lid + if d.source_instance_id == inst.object_instance_id), None) + + gt_dims = scenes_mod.CLASS_DIMS.get(inst.gt_class, (0.8, 0.8, 1.8)) + checks: Dict[str, Any] = {} + camera_supports = lidar_supports = False + conflict = False + + if lid_det is not None: + err_gt = _dims_log_error(lid_det.dims, gt_dims) + err_cone = _dims_log_error(lid_det.dims, CONE_DIMS) + lidar_supports = err_gt < err_cone + checks["lidar_shape"] = { + "dims": [round(d, 2) for d in lid_det.dims], + "log_err_vs_gt_template": round(err_gt, 3), + "log_err_vs_cone_template": round(err_cone, 3), + "supports_gt_class": lidar_supports, + } + if cam_det is not None: + camera_supports = cam_det.class_name in VRU + checks["camera_class"] = { + "class": cam_det.class_name, + "confidence": round(cam_det.confidence, 3), + "supports_gt_class": camera_supports, + } + if cam_det is not None and lid_det is not None: + dist = math.hypot(cam_det.x - lid_det.x, cam_det.y - lid_det.y) + checks["position_agreement_m"] = round(dist, 2) + if dist > POSITION_AGREEMENT_M or (camera_supports != lidar_supports): + conflict = True + + if conflict: + verdict = "modality_conflict" + elif cam_det is not None and lid_det is not None: + verdict = ("multi_modal_supported" + if camera_supports and lidar_supports + else "modality_conflict") + elif cam_det is not None or lid_det is not None: + verdict = "single_modality_only" + else: + verdict = "single_modality_only" + checks["note"] = ("neither re-simulated modality re-detected " + "the object this frame; tracking continuity " + "is the only supporting evidence") + per_instance.append({"instance_id": inst.instance_id, + "frame_id": inst.frame_id, + "verdict": verdict, "checks": checks}) + + counts: Dict[str, int] = {} + for r in per_instance: + counts[r["verdict"]] = counts.get(r["verdict"], 0) + 1 + n = max(len(per_instance), 1) + if counts.get("verification_failed", 0) == n: + overall = "verification_failed" + elif counts.get("modality_conflict", 0) > 0: + overall = "modality_conflict" + elif counts.get("multi_modal_supported", 0) / n >= 0.5: + overall = "multi_modal_supported" + else: + overall = "single_modality_only" + + output = { + "overall_verdict": overall, + "verdict_counts": counts, + "instances_verified": len(per_instance), + "per_instance": per_instance, + "method": ("deterministic re-simulation of bevfusion camera/LiDAR " + "sensor models; LiDAR shape template check vs GT class " + "and cone hypothesis; camera class check; BEV position " + "agreement"), + } + confidence = round(min(0.9, 0.4 + 0.5 * counts.get("multi_modal_supported", 0) / n), 3) + if overall == "modality_conflict": + return (output, confidence, + "modality conflict detected — verdict requires human eyes", + escalate(["camera and LiDAR evidence disagree"], + ["modality_disagreement"])) + if overall == "verification_failed": + return (output, 0.0, "verification could not run", + escalate(["fusion verification failed"], ["agent_failure"])) + return (output, confidence, + "share of instances with independent two-modality corroboration", + no_escalation()) + + def _llm_prompt(self, failure_id, output, **inputs): + return ("Explain this multi-sensor verification result to a triage " + "engineer in three sentences: " + compact(output)) diff --git a/sensorflow/agentic/agents/launch_decision.py b/sensorflow/agentic/agents/launch_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..c91b03423680ed57032312600ca8b3ab3be51216 --- /dev/null +++ b/sensorflow/agentic/agents/launch_decision.py @@ -0,0 +1,87 @@ +"""LaunchDecisionAgent — drafts the recommendation NARRATIVE only. + +Structural guarantee of the AI/deterministic separation: this agent receives +the policy engine's already-computed evaluation and turns it into prose for +humans. It cannot change the outcome, the option, or any number — the +deterministic PolicyEngine (sensorflow.agentic.policy) decides, and human +review authorizes. +""" + +from __future__ import annotations + +from typing import Any, Dict, Tuple + +from sensorflow.agentic.agents.base import BaseAgent, compact, no_escalation +from sensorflow.agentic.models import AgentEscalation, FailureEvent + +OPTION_TEXT = { + "STOP_SHIP": "stop the release", + "OPTION_A_DELAY": "Option A — delay launch until the failure is fixed", + "OPTION_B_MITIGATION": "Option B — ship with the validated mitigation", + "OPTION_C_REDUCED_ODD": "Option C — ship with a reduced ODD excluding the " + "concentrated region", + "EXPAND_EVALUATION": "expand evaluation before any launch claim", + "HUMAN_SAFETY_REVIEW": "route to human safety review", + "PROCEED": "proceed (no launch impact established)", +} + + +class LaunchDecisionAgent(BaseAgent): + name = "launch_decision" + version = "1.0.0" + epistemic_status = "DERIVED" + + def _analyze(self, failure_id: str, failure: FailureEvent = None, + policy_evaluation: Dict = None, + **inputs) -> Tuple[Dict[str, Any], float, str, AgentEscalation]: + assert failure is not None and policy_evaluation is not None + pol = policy_evaluation + outcome = pol.get("outcome") + option = pol.get("recommended_option") + row = pol.get("matrix_row_fired") or {} + sev = pol.get("severity") + inp = pol.get("input") or {} + + lines = [ + f"POLICY OUTCOME (deterministic): {outcome} under policy " + f"{pol.get('policy_version')}.", + f"Severity {sev}: {(pol.get('severity_assignment') or {}).get('taxonomy_description')}", + f"Recommended option (matrix row {row.get('row')}, condition " + f"{row.get('condition')}): {OPTION_TEXT.get(option, option)}.", + ] + if inp.get("rate") is not None: + lines.append( + f"Measured candidate rate {inp['rate']:.6f} " + f"(CI {inp.get('rate_ci')}) over denominator " + f"{inp.get('denominator')}; significant={inp.get('significant')}.") + if pol.get("indeterminate_reasons"): + lines.append("INDETERMINATE reasons: " + + "; ".join(pol["indeterminate_reasons"])) + infeasible = [r for r in pol.get("expected_loss_table", []) + if not r["feasible"]] + if infeasible: + lines.append( + "Hard safety constraint excluded from selection: " + + ", ".join(f"{r['option']} (residual rate " + f"{r['residual_failure_rate']:.2e})" + for r in infeasible) + + " — regardless of expected loss.") + lines.append( + "This narrative is ADVISORY. Final authorization requires the " + "deterministic policy outcome above plus a recorded human review " + "decision; no agent output authorizes a launch.") + + output = { + "narrative": "\n".join(lines), + "restated_outcome": outcome, + "restated_option": option, + "decision_authority": "policy engine + human approval (never this agent)", + } + return (output, 0.85, + "narrative restates deterministic results; it introduces no " + "new claims", + no_escalation()) + + def _llm_prompt(self, failure_id, output, **inputs): + return ("Polish this launch-decision narrative without changing any " + "fact, number, outcome or option: " + compact(output)) diff --git a/sensorflow/agentic/agents/safety_impact.py b/sensorflow/agentic/agents/safety_impact.py new file mode 100644 index 0000000000000000000000000000000000000000..82969dfb9b63d73f2a2ebbe6ba7fbaae8ea9650f --- /dev/null +++ b/sensorflow/agentic/agents/safety_impact.py @@ -0,0 +1,176 @@ +"""SafetyImpactAgent — perception -> tracking -> prediction -> planner -> +behavior chain. + +Uses REPLAY EVIDENCE where it exists: instances flagged with a synthetic +planner-response trace are replayed through the SSAM surrogate-safety +machinery (sensorflow.safety.ssam_ext — TTC via conflict-point projection, +DRAC, collision probability), comparing the delayed reaction caused by the +misclassification ("a cone does not need yielding") against the nominal +reaction. Stopping-distance and braking-margin computations reuse the same +module's kinematics. + +When no replay evidence exists the agent outputs exactly +"safety assessment UNCERTAIN — no behavioral evidence" and marks the +downstream links UNAVAILABLE — a hypothetical consequence is NEVER converted +into an observed one. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Tuple + +from sensorflow.agentic.agents.base import BaseAgent, compact, escalate, no_escalation +from sensorflow.agentic.models import AgentEscalation, FailureEvent +from sensorflow.safety import ssam_ext + +NOMINAL_REACTION_S = 0.6 +MISCLASS_REACTION_S = 1.6 # replayed planner treats the object as static furniture +COMFORT_DECEL_MPS2 = 3.5 +HARD_DECEL_MPS2 = 5.0 +TTC_UNSAFE_S = 1.0 + +UNCERTAIN_TEXT = "safety assessment UNCERTAIN — no behavioral evidence" + + +def stopping_distance(speed_mps: float, decel_mps2: float, + reaction_s: float) -> float: + """Reaction distance + braking distance (same kinematics as the + ssam_ext braking profile).""" + return speed_mps * reaction_s + speed_mps ** 2 / (2.0 * max(decel_mps2, 0.1)) + + +class SafetyImpactAgent(BaseAgent): + name = "safety_impact" + version = "1.0.0" + epistemic_status = "DERIVED" + + def _analyze(self, failure_id: str, failure: FailureEvent = None, + **inputs) -> Tuple[Dict[str, Any], float, str, AgentEscalation]: + assert failure is not None + traced = [i for i in failure.instances if i.has_planner_trace] + + chain: List[Dict] = [ + {"link": "perception_error", "status": "OBSERVED", + "detail": f"{failure.gt_class} -> {failure.predicted_class} on " + f"{len(failure.instances)} captured instances"}, + {"link": "tracking", "status": "OBSERVED", + "detail": "candidate track continuity observed in the campaign " + "prediction log (class churn inside the track)"}, + {"link": "prediction", "status": "DERIVED", + "detail": "a construction_cone hypothesis implies a STATIC " + "motion prior; pedestrian crossing intent is dropped"}, + ] + + if not traced: + chain.append({"link": "planner", "status": "UNAVAILABLE", + "detail": "no replay planner-response trace exists"}) + chain.append({"link": "behavior", "status": "UNAVAILABLE", + "detail": UNCERTAIN_TEXT}) + output = { + "behavioral_evidence": "none", + "assessment": UNCERTAIN_TEXT, + "chain": chain, + "replayed_instances": 0, + "note": ("downstream consequence remains a hypothesis; this " + "agent never records hypothetical behavior as " + "observed"), + } + return (output, 0.3, + "no behavioral evidence available; assessment is " + "explicitly uncertain", + escalate([UNCERTAIN_TEXT], ["insufficient_statistics"])) + + # ---- replay evidence exists: quantify with ssam_ext ---------------- + replays: List[Dict] = [] + worst = {"min_ttc_s": None, "max_drac": None, "max_p": 0.0} + for k, inst in enumerate(traced[:4]): + delayed = ssam_ext.analyze_trajectories( + ssam_ext.generate_trajectories( + seed=k, scenario="crossing", + reaction_delay_s=MISCLASS_REACTION_S)) + nominal = ssam_ext.analyze_trajectories( + ssam_ext.generate_trajectories( + seed=k, scenario="crossing", + reaction_delay_s=NOMINAL_REACTION_S)) + da, na = delayed["aggregate"], nominal["aggregate"] + replays.append({ + "instance_id": inst.instance_id, + "replay_seed": k, + "delayed_reaction_s": MISCLASS_REACTION_S, + "nominal_reaction_s": NOMINAL_REACTION_S, + "min_ttc_delayed_s": da["min_ttc_s"], + "min_ttc_nominal_s": na["min_ttc_s"], + "max_drac_delayed_mps2": da["max_drac_mps2"], + "max_collision_probability_delayed": da["max_collision_probability"], + "num_conflicts_delayed": da["num_conflicts"], + "num_conflicts_nominal": na["num_conflicts"], + "csi_delayed": da["aggregate_csi"], + "csi_nominal": na["aggregate_csi"], + }) + if da["min_ttc_s"] is not None: + worst["min_ttc_s"] = (da["min_ttc_s"] if worst["min_ttc_s"] is None + else min(worst["min_ttc_s"], da["min_ttc_s"])) + if da["max_drac_mps2"] is not None: + worst["max_drac"] = (da["max_drac_mps2"] if worst["max_drac"] is None + else max(worst["max_drac"], da["max_drac_mps2"])) + if da["max_collision_probability"] is not None: + worst["max_p"] = max(worst["max_p"], da["max_collision_probability"]) + + v = 12.5 # ego approach speed in the crossing replay scenario + sd_nominal = stopping_distance(v, HARD_DECEL_MPS2, NOMINAL_REACTION_S) + sd_delayed = stopping_distance(v, HARD_DECEL_MPS2, MISCLASS_REACTION_S) + available = 42.0 # initial ego-to-conflict-point distance in the scenario + braking_margin_nominal = available - sd_nominal + braking_margin_delayed = available - sd_delayed + + unsafe = ((worst["min_ttc_s"] is not None and worst["min_ttc_s"] < TTC_UNSAFE_S) + or (worst["max_drac"] is not None and worst["max_drac"] > COMFORT_DECEL_MPS2)) + behavioral = "observed_unsafe" if unsafe else "observed_contained" + + chain.append({"link": "planner", "status": "OBSERVED", + "detail": f"replayed {len(replays)} planner-response " + f"trace(s) with reaction delay " + f"{MISCLASS_REACTION_S}s vs nominal " + f"{NOMINAL_REACTION_S}s"}) + chain.append({"link": "behavior", "status": "OBSERVED", + "detail": (f"worst replay min TTC " + f"{worst['min_ttc_s']}s, max DRAC " + f"{worst['max_drac']} m/s^2, max collision " + f"probability {worst['max_p']}") }) + + output = { + "behavioral_evidence": "observed", + "behavioral_classification": behavioral, + "assessment": ("unsafe downstream behavior OBSERVED in replay" + if unsafe else + "downstream behavior degraded but contained in replay"), + "chain": chain, + "replayed_instances": len(replays), + "replays": replays, + "worst_case": worst, + "kinematics": { + "method": "sensorflow.safety.ssam_ext (TTC conflict-point " + "projection, DRAC, collision probability) + " + "reaction/braking kinematics", + "ego_speed_mps": v, + "stopping_distance_nominal_m": round(sd_nominal, 2), + "stopping_distance_delayed_m": round(sd_delayed, 2), + "braking_margin_nominal_m": round(braking_margin_nominal, 2), + "braking_margin_delayed_m": round(braking_margin_delayed, 2), + "thresholds": {"ttc_unsafe_s": TTC_UNSAFE_S, + "comfort_decel_mps2": COMFORT_DECEL_MPS2}, + }, + "coverage_note": (f"replay evidence covers {len(traced)} of " + f"{len(failure.instances)} instances; the " + "remainder stays UNCERTAIN"), + } + esc = (escalate(["unsafe downstream behavior observed in replay"], + ["behavior_change", "severity_s3_plus"]) + if unsafe else no_escalation()) + return (output, 0.8 if unsafe else 0.7, + "replay-based measurement on the instances that have traces", + esc) + + def _llm_prompt(self, failure_id, output, **inputs): + return ("Narrate this perception->behavior safety chain for a launch " + "review, preserving all UNCERTAIN labels: " + compact(output)) diff --git a/sensorflow/agentic/agents/scenario_mining.py b/sensorflow/agentic/agents/scenario_mining.py new file mode 100644 index 0000000000000000000000000000000000000000..c6371687ce00b381701a01b347f05c4af9cdbb09 --- /dev/null +++ b/sensorflow/agentic/agents/scenario_mining.py @@ -0,0 +1,226 @@ +"""ScenarioMiningAgent — similar-failure retrieval + clustering. + +Embedding + attribute retrieval of similar historical failures, following the +megaeval embedding recipe (structural features + one-hot attributes + seeded +random projection, cosine retrieval — see MegaStore._build_embeddings in +sensorflow/megaeval/runs.py, which operates on run artifacts and is therefore +mirrored here for failure records rather than re-invented). + +Clustering method is SELECTED FROM THE DATA SHAPE and the choice is justified +in the output (it is not always DBSCAN): + * n < 15 -> single-linkage agglomerative on cosine distance + (density parameters are unidentifiable at tiny n) + * mostly categorical -> attribute-signature grouping (exact modes) + * otherwise -> density-based (DBSCAN-style) via pairwise radius + graph connected components +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Tuple + +import numpy as np + +from sensorflow.agentic.agents.base import BaseAgent, compact, no_escalation +from sensorflow.agentic.models import AgentEscalation, FailureEvent + +GT_CLASSES = ["pedestrian", "cyclist", "motorcycle", "vehicle", "truck"] +PRED_CLASSES = ["pedestrian", "cyclist", "motorcycle", "vehicle", "truck", + "construction_cone", "background"] +TIMES = ["day", "night"] +WEATHERS = ["clear", "rain"] +EMBED_DIM = 16 +EMBED_SEED = 1234 # same seeded-projection convention as megaeval + + +def historical_corpus(seed: int = 77, n: int = 48) -> List[Dict]: + """Deterministic synthetic archive of previously-triaged failures. + + Deliberately contains NO pedestrian->construction_cone precedent, so the + motivating failure is genuinely novel against the archive. + """ + rng = np.random.default_rng(seed) + pairs = [("pedestrian", "cyclist"), ("cyclist", "motorcycle"), + ("vehicle", "truck"), ("truck", "vehicle"), + ("cyclist", "vehicle"), ("pedestrian", "background"), + ("motorcycle", "cyclist"), ("vehicle", "background")] + out = [] + for i in range(n): + gt, pred = pairs[int(rng.integers(0, len(pairs)))] + out.append({ + "historical_id": f"hist-{i:04d}", + "gt_class": gt, "predicted_class": pred, + "construction_zone": bool(rng.random() < 0.15), + "time_of_day": TIMES[int(rng.random() < 0.4)], + "weather": WEATHERS[int(rng.random() < 0.3)], + "distance_m": round(float(rng.uniform(8, 70)), 1), + "resolved": bool(rng.random() < 0.8), + "resolution": "retrained" if rng.random() < 0.5 else "data_fix", + }) + return out + + +def _featurize(rec: Dict) -> np.ndarray: + f: List[float] = [] + f.extend(1.0 if rec["gt_class"] == c else 0.0 for c in GT_CLASSES) + f.extend(1.0 if rec["predicted_class"] == c else 0.0 for c in PRED_CLASSES) + f.append(1.0 if rec.get("construction_zone") else 0.0) + f.append(1.0 if rec.get("time_of_day") == "night" else 0.0) + f.append(1.0 if rec.get("weather") == "rain" else 0.0) + f.append(min(float(rec.get("distance_m", 30.0)) / 70.0, 1.0)) + return np.asarray(f, dtype=np.float64) + + +def embed(records: List[Dict]) -> np.ndarray: + X = np.vstack([_featurize(r) for r in records]) + rng = np.random.default_rng(EMBED_SEED) + proj = rng.normal(size=(X.shape[1], EMBED_DIM)) / np.sqrt(X.shape[1]) + E = X @ proj + return E / np.clip(np.linalg.norm(E, axis=1, keepdims=True), 1e-9, None) + + +def _select_clustering(n: int, categorical_share: float) -> Tuple[str, str]: + if n < 15: + return ("single_linkage_agglomerative", + f"only n={n} member instances: density-based methods " + "(DBSCAN) need an eps/minPts neighborhood that is " + "unidentifiable at this sample size; single-linkage on " + "cosine distance degrades gracefully") + if categorical_share > 0.8: + return ("attribute_signature_grouping", + f"{categorical_share:.0%} of features are categorical " + "one-hots: exact signature grouping is better-defined than " + "euclidean density in a nearly-discrete space") + return ("density_radius_components", + f"n={n} with mixed features: density-based clustering " + "(DBSCAN-style radius graph components) is appropriate") + + +def _cluster(records: List[Dict], emb: np.ndarray, method: str) -> List[List[int]]: + n = len(records) + if method == "attribute_signature_grouping": + groups: Dict[Tuple, List[int]] = {} + for i, r in enumerate(records): + key = (r.get("construction_zone"), r.get("time_of_day"), + r.get("weather")) + groups.setdefault(key, []).append(i) + return list(groups.values()) + # graph-based (single-linkage threshold == radius components on cosine) + sims = emb @ emb.T + thr = 0.92 if method == "single_linkage_agglomerative" else 0.95 + parent = list(range(n)) + + def find(a): + while parent[a] != a: + parent[a] = parent[parent[a]] + a = parent[a] + return a + + for i in range(n): + for j in range(i + 1, n): + if sims[i, j] >= thr: + parent[find(i)] = find(j) + groups2: Dict[int, List[int]] = {} + for i in range(n): + groups2.setdefault(find(i), []).append(i) + return list(groups2.values()) + + +class ScenarioMiningAgent(BaseAgent): + name = "scenario_mining" + version = "1.0.0" + epistemic_status = "DERIVED" + + def _analyze(self, failure_id: str, failure: FailureEvent = None, + **inputs) -> Tuple[Dict[str, Any], float, str, AgentEscalation]: + assert failure is not None + corpus = historical_corpus() + + # ---- retrieval: embedding + attribute filters -------------------- + query = { + "gt_class": failure.gt_class or "vehicle", + "predicted_class": failure.predicted_class or "background", + "construction_zone": any(i.construction_zone for i in failure.instances), + "time_of_day": (failure.instances[0].time_of_day + if failure.instances else "day"), + "weather": (failure.instances[0].weather + if failure.instances else "clear"), + "distance_m": (float(np.mean([i.distance_m for i in failure.instances])) + if failure.instances else 30.0), + } + all_emb = embed(corpus + [query]) + emb, q = all_emb[:-1], all_emb[-1] + sims = emb @ q + order = np.argsort(-sims)[:8] + similar = [{**corpus[int(i)], "similarity": round(float(sims[int(i)]), 4)} + for i in order] + + exact_precedent = [r for r in corpus + if r["gt_class"] == query["gt_class"] + and r["predicted_class"] == query["predicted_class"]] + novelty = "novel" if not exact_precedent else ( + "known_regression" if any(not r["resolved"] for r in exact_precedent) + else "known_stable") + + # ---- clustering of the failure's own instances ------------------- + inst_records = [{ + "gt_class": i.gt_class, "predicted_class": i.predicted_class, + "construction_zone": i.construction_zone, + "time_of_day": i.time_of_day, "weather": i.weather, + "distance_m": i.distance_m, + } for i in failure.instances] + cluster_reports: List[Dict] = [] + method = justification = None + if inst_records: + feat_dim = _featurize(inst_records[0]).size + categorical_share = (feat_dim - 1) / feat_dim # all but distance + method, justification = _select_clustering(len(inst_records), + categorical_share) + inst_emb = embed(inst_records) + clusters = _cluster(inst_records, inst_emb, method) + total = len(inst_records) + for idx, members in enumerate(sorted(clusters, key=len, reverse=True)): + recs = [inst_records[m] for m in members] + dominant = { + "construction_zone": (sum(r["construction_zone"] for r in recs) + / len(recs)), + "night_share": (sum(r["time_of_day"] == "night" for r in recs) + / len(recs)), + "rain_share": (sum(r["weather"] == "rain" for r in recs) + / len(recs)), + "mean_distance_m": round(float(np.mean( + [r["distance_m"] for r in recs])), 1), + } + cluster_reports.append({ + "cluster_id": f"{failure.failure_id}-c{idx}", + "size": len(members), + "population_share": round(len(members) / total, 3), + "dominant_conditions": dominant, + "representative_examples": [ + failure.instances[m].instance_id for m in members[:3]], + }) + + output = { + "similar_historical": similar, + "exact_precedent_count": len(exact_precedent), + "novelty": novelty, + "novelty_basis": ("no archived failure shares the " + f"{query['gt_class']}->{query['predicted_class']} " + "signature" if novelty == "novel" else + f"{len(exact_precedent)} archived precedents"), + "clustering_method": method, + "clustering_justification": justification, + "clusters": cluster_reports, + "retrieval": ("cosine over seeded random-projection embeddings of " + "structural+categorical features (megaeval recipe) " + "+ attribute retrieval"), + } + confidence = 0.75 if inst_records else 0.4 + return (output, confidence, + "retrieval and clustering are deterministic; confidence " + "reflects instance coverage", + no_escalation()) + + def _llm_prompt(self, failure_id, output, **inputs): + return ("Summarize the cluster structure and novelty finding of this " + "failure mining result: " + compact(output)) diff --git a/sensorflow/agentic/agents/statistical.py b/sensorflow/agentic/agents/statistical.py new file mode 100644 index 0000000000000000000000000000000000000000..377f1d06cf0afa7e083422821d85b81ed15d5996 --- /dev/null +++ b/sensorflow/agentic/agents/statistical.py @@ -0,0 +1,155 @@ +"""StatisticalRegressionAgent — mostly deterministic. + +Establishes, before anyone treats "~0.01%" as real: the denominator, the +sample size, confidence intervals, statistical significance, power/MDE and +small-sample instability. + +This agent is a THIN ORCHESTRATOR over sensorflow.seqeval — the anytime-valid +sequential machinery (PairedSequentialTest: empirical-Bernstein confidence +sequence + betting e-processes) and the MDE approximation are imported from +seqeval, not reimplemented. Wilson intervals come from megaeval.sampling +(single source of truth). + +Rare-event handling: when event counts are small, the practical-margin +sequential test is honest but low-powered, so significance for the rate +DELTA is additionally established with the exact conditional binomial +(McNemar-exact) test over discordant pairs; both results are reported with +their methods, and the seqeval three-outcome decision is never coerced. +""" + +from __future__ import annotations + +from typing import Any, Dict, Tuple + +import numpy as np +from scipy import stats as sstats + +from sensorflow.agentic import data as data_mod +from sensorflow.agentic.agents.base import BaseAgent, compact, no_escalation +from sensorflow.agentic.models import (AgentEscalation, RateEstimate, + StatisticalAssessment) +from sensorflow.megaeval.sampling import wilson_interval +from sensorflow.seqeval.sequential import PairedSequentialTest, approx_mde + +ALPHA = 0.05 +SEQ_DELTA_MARGIN = 5.0e-5 # practical-significance margin for the flip rate +SMALL_SAMPLE_EVENT_FLOOR = 50 + + +class StatisticalRegressionAgent(BaseAgent): + name = "statistical_regression" + version = "1.0.0" + epistemic_status = "OBSERVED" # this agent reports measurements + + def assess(self, seed: int = data_mod.DEFAULT_SEED) -> StatisticalAssessment: + arrays = data_mod.get_rate_arrays(seed) + n = arrays.n + b_events = int(arrays.baseline_flip.sum()) + c_events = int(arrays.candidate_flip.sum()) + b_rate, c_rate = b_events / n, c_events / n + b_lo, b_hi = wilson_interval(b_events, n) + c_lo, c_hi = wilson_interval(c_events, n) + + # ---- exact rare-event significance (McNemar-exact / conditional + # binomial over discordant pairs) -------------------------------- + n01 = int((arrays.baseline_flip & ~arrays.candidate_flip).sum()) + n10 = int((~arrays.baseline_flip & arrays.candidate_flip).sum()) + if n01 + n10 > 0: + exact_p = float(sstats.binomtest(n10, n01 + n10, 0.5, + alternative="greater").pvalue) + else: + exact_p = None + significant = exact_p is not None and exact_p < ALPHA + + # ---- seqeval delegation: anytime-valid paired sequential test ---- + # success = "no flip"; d = candidate - baseline (negative = worse) + b_success = (~arrays.baseline_flip).astype(np.float64) + c_success = (~arrays.candidate_flip).astype(np.float64) + d = c_success - b_success + cluster_sums = np.bincount(arrays.cluster_id, weights=d) + cluster_counts = np.bincount(arrays.cluster_id) + cluster_means = cluster_sums / np.maximum(cluster_counts, 1) + + seq_test = PairedSequentialTest(delta=SEQ_DELTA_MARGIN, alpha=ALPHA) + seq_test.update_clusters(cluster_means.tolist()) + seq_test.record_objects(b_success.astype(bool), c_success.astype(bool)) + seq_decision = seq_test.evaluate() + seq_snapshot = seq_test.snapshot() + + # ---- power / MDE at the achieved sample size --------------------- + nu = (seq_test.n01 + seq_test.n10) / max(seq_test.n_objects, 1) + est = seq_test.delta_estimate() or 0.0 + var_d = max(nu - est ** 2, 1e-12) + mde = approx_mde(var_d, n_eff=float(len(cluster_means)), + delta=SEQ_DELTA_MARGIN, alpha=ALPHA) + observed_abs_delta = abs(c_rate - b_rate) + power_note = ( + "sequential-margin test is UNDERPOWERED at this n for the " + "observed delta" if (mde is not None and mde > observed_abs_delta) + else "sequential-margin test adequately powered") + + # ---- small-sample instability flags ------------------------------- + flags = [] + if c_events < SMALL_SAMPLE_EVENT_FLOOR: + flags.append(f"candidate event count {c_events} < " + f"{SMALL_SAMPLE_EVENT_FLOOR}: rate estimate unstable") + if b_events < 10: + flags.append(f"baseline event count {b_events} < 10: relative " + "risk denominator unstable") + if (c_hi - c_lo) > c_rate: + flags.append("candidate CI width exceeds the point estimate") + + return StatisticalAssessment( + baseline=RateEstimate(events=b_events, denominator=n, + rate=round(b_rate, 8), + wilson_ci=[round(b_lo, 8), round(b_hi, 8)]), + candidate=RateEstimate(events=c_events, denominator=n, + rate=round(c_rate, 8), + wilson_ci=[round(c_lo, 8), round(c_hi, 8)]), + absolute_delta=round(c_rate - b_rate, 8), + relative_delta=(round(c_rate / b_rate, 3) if b_rate > 0 else None), + significant=significant, + significance_method=( + "exact conditional binomial (McNemar-exact) over discordant " + f"pairs: n10={n10} candidate-only vs n01={n01} baseline-only, " + f"H0 p=0.5, one-sided"), + exact_binomial_p=exact_p, + seqeval={ + "delegated_to": "sensorflow.seqeval.sequential.PairedSequentialTest", + "test_method": ("paired cluster-mean empirical-Bernstein " + "confidence sequence + one-sided betting " + "e-process (anytime-valid)"), + "delta_margin": SEQ_DELTA_MARGIN, + "alpha": ALPHA, + "decision": seq_decision, + "snapshot": seq_snapshot, + "clusters_fed": int(len(cluster_means)), + "note": ("three-outcome decision reported as-is; " + "INSUFFICIENT_EVIDENCE is never coerced to PASS"), + }, + power_mde={ + "mde_abs": mde, + "observed_abs_delta": round(observed_abs_delta, 8), + "assessment": power_note, + "method": "sensorflow.seqeval.sequential.approx_mde", + }, + small_sample_flags=flags, + rare_event_handling=( + "event counts are small, so exact binomial inference is used " + "for the significance claim; the seqeval sequential test is " + "reported alongside with its own (unforced) decision"), + ) + + def _analyze(self, failure_id: str, seed: int = data_mod.DEFAULT_SEED, + **inputs) -> Tuple[Dict[str, Any], float, str, AgentEscalation]: + assessment = self.assess(seed) + conf = 0.9 if assessment.significant and not assessment.small_sample_flags \ + else (0.7 if assessment.significant else 0.4) + return (assessment.model_dump(), conf, + "deterministic statistics; confidence reflects significance " + "and sample stability", + no_escalation()) + + def _llm_prompt(self, failure_id, output, **inputs): + return ("Explain these regression statistics to a launch-review " + "audience without changing any number: " + compact(output)) diff --git a/sensorflow/agentic/agents/vlm_scene.py b/sensorflow/agentic/agents/vlm_scene.py new file mode 100644 index 0000000000000000000000000000000000000000..71e43b97e81f3c7320edebdc3f232d6dfdce75ab --- /dev/null +++ b/sensorflow/agentic/agents/vlm_scene.py @@ -0,0 +1,85 @@ +"""VLMSceneAnalysisAgent — scene-context hypotheses. + +Produces hypotheses about WHY the scene context may explain the failure, +from scene metadata via a deterministic rule lexicon (with an optional Ollama +rationale on top). Its entire output is explicitly labeled HYPOTHESIS and is +never treated as ground truth by any downstream component: the policy engine +only consumes it as narrative context, never as evidence of cause. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Tuple + +from sensorflow.agentic.agents.base import BaseAgent, compact, no_escalation +from sensorflow.agentic.models import AgentEscalation, FailureEvent + +# Deterministic rule lexicon: (predicate over instance context) -> hypothesis. +LEXICON = [ + ("construction_zone", lambda i: i.construction_zone, + "Construction-zone visual context (cones, barriers, hi-vis colors) may " + "bias the classifier toward construction furniture classes."), + ("night_lighting", lambda i: i.time_of_day == "night", + "Low illumination reduces appearance cues; silhouette-based features " + "dominate and small upright objects become confusable."), + ("rain_weather", lambda i: i.weather == "rain", + "Rain scatter degrades both camera contrast and LiDAR returns, " + "increasing shape ambiguity."), + ("long_range", lambda i: i.distance_m > 40.0, + "At long range the object subtends few pixels/points; class evidence " + "is weak and priors dominate."), + ("occlusion", lambda i: i.occluded, + "Partial occlusion truncates the silhouette, which can resemble a " + "static vertical object."), + ("cone_confusion", lambda i: i.predicted_class == "construction_cone", + "Pedestrian-to-cone confusion is consistent with hi-vis clothing or a " + "stationary pedestrian adopting a cone-like compact silhouette."), +] + + +class VLMSceneAnalysisAgent(BaseAgent): + name = "vlm_scene_analysis" + version = "1.0.0" + epistemic_status = "HYPOTHESIS" # everything here is a hypothesis + + def _analyze(self, failure_id: str, failure: FailureEvent = None, + **inputs) -> Tuple[Dict[str, Any], float, str, AgentEscalation]: + assert failure is not None + hypotheses: List[Dict] = [] + counts: Dict[str, int] = {} + for inst in failure.instances: + for key, pred, text in LEXICON: + if pred(inst): + counts[key] = counts.get(key, 0) + 1 + n = max(len(failure.instances), 1) + for key, pred, text in LEXICON: + if key in counts: + hypotheses.append({ + "label": "HYPOTHESIS", + "factor": key, + "text": text, + "instance_support": counts[key], + "instance_share": round(counts[key] / n, 3), + }) + hypotheses.sort(key=lambda h: -h["instance_support"]) + + output = { + "epistemic_label": ("HYPOTHESIS — scene-context conjectures from " + "metadata rules; NOT ground truth, NOT " + "evidence of cause"), + "hypotheses": hypotheses, + "instances_examined": len(failure.instances), + "lexicon_version": self.version, + } + confidence = min(0.6, 0.2 + 0.1 * len(hypotheses)) + return (output, confidence, + "rule-lexicon coverage of instance contexts; capped at 0.6 " + "because hypotheses are unverified", + no_escalation()) + + def _llm_prompt(self, failure_id, output, **inputs): + return ("You are a scene-analysis assistant. Given these rule-based " + "hypotheses about a perception failure, write a short " + "clearly-hedged paragraph of additional scene-context " + "hypotheses. Never state a cause as fact. " + + compact(output)) diff --git a/sensorflow/agentic/api.py b/sensorflow/agentic/api.py new file mode 100644 index 0000000000000000000000000000000000000000..72a77be556ada22eeafb8b067bca24463e8832ee --- /dev/null +++ b/sensorflow/agentic/api.py @@ -0,0 +1,327 @@ +"""FastAPI router for the agentic launch-readiness subsystem (/api/agentic/*). + +Endpoint map: + POST /api/agentic/failures/detect layer-1 scan + GET /api/agentic/failures failure queue + GET /api/agentic/failures/{id} one failure + GET /api/agentic/failures/{id}/state pipeline state + POST /api/agentic/failures/{id}/analyze[?stage=] advance the pipeline + GET /api/agentic/failures/{id}/evidence evidence graph + GET /api/agentic/failures/{id}/snippets failure snippets + POST /api/agentic/failures/{id}/cluster scenario mining on demand + POST /api/agentic/failures/{id}/safety-assessment safety impact on demand + POST /api/agentic/failures/{id}/launch-assessment launch decision stage + POST /api/agentic/failures/{id}/human-review record a human decision + GET /api/agentic/policy[?version=] active/specific policy + POST /api/agentic/policy save a new version + GET /api/agentic/policy/versions version list + POST /api/agentic/evaluation-suites flywheel stage for a failure + GET /api/agentic/evaluation-suites list suites + GET /api/agentic/evaluation-suites/{id} one suite + POST /api/agentic/evaluation-suites/{id}/promote-member guarded promotion + POST /api/agentic/regression/evaluate suite regression hook + GET /api/agentic/scorecards/{id} scorecard + GET /api/agentic/audit/{failure_id} immutable audit trail + GET /api/agentic/worked-example deterministic walkthrough +""" + +from __future__ import annotations + +from typing import Dict, List, Optional + +from fastapi import APIRouter, HTTPException, Query +from pydantic import BaseModel, Field + +from sensorflow.agentic import data as data_mod +from sensorflow.agentic import flywheel as flywheel_mod +from sensorflow.agentic import pipeline as pipeline_mod +from sensorflow.agentic import policy as policy_mod +from sensorflow.agentic import review as review_mod +from sensorflow.agentic import scorecard as scorecard_mod +from sensorflow.agentic import store as store_mod +from sensorflow.agentic import worked_example as we_mod +from sensorflow.agentic.agents import SafetyImpactAgent, ScenarioMiningAgent +from sensorflow.agentic.models import STAGES + +router = APIRouter(prefix="/api/agentic", tags=["agentic"]) + + +def _failure_or_404(failure_id: str): + failure = pipeline_mod.get_failure(failure_id) + if failure is None: + raise HTTPException(404, f"Unknown failure {failure_id}") + return failure + + +# ------------------------------------------------------------------ detection + + +class DetectRequest(BaseModel): + seed: int = data_mod.DEFAULT_SEED + use_llm: bool = False + + +@router.post("/failures/detect") +def detect(req: Optional[DetectRequest] = None): + req = req or DetectRequest() + events = pipeline_mod.detect_failures(seed=req.seed, use_llm=req.use_llm) + return {"status": "ok", "detected": len(events), + "failures": [{"failure_id": e.failure_id, "kind": e.kind, + "title": e.title, + "candidate_events": e.detection_basis.candidate_events, + "denominator": e.detection_basis.denominator} + for e in events]} + + +@router.get("/failures") +def failure_queue(): + return {"status": "ok", "failures": pipeline_mod.list_failures(), + "stages": STAGES} + + +@router.get("/failures/{failure_id}") +def failure_detail(failure_id: str): + return {"status": "ok", "failure": _failure_or_404(failure_id).model_dump()} + + +@router.get("/failures/{failure_id}/state") +def failure_state(failure_id: str): + state = pipeline_mod.get_state(failure_id) + if state is None: + raise HTTPException(404, f"Unknown failure {failure_id}") + return {"status": "ok", "state": state.model_dump()} + + +# ------------------------------------------------------------------ pipeline + + +class AnalyzeRequest(BaseModel): + seed: int = data_mod.DEFAULT_SEED + use_llm: bool = False + policy_input_overrides: Dict = Field(default_factory=dict) + + +@router.post("/failures/{failure_id}/analyze") +def analyze(failure_id: str, req: Optional[AnalyzeRequest] = None, + stage: Optional[str] = Query(default=None)): + _failure_or_404(failure_id) + req = req or AnalyzeRequest() + try: + state = pipeline_mod.run_stage( + failure_id, stage, seed=req.seed, use_llm=req.use_llm, + policy_input_overrides=req.policy_input_overrides or None) + except ValueError as e: + raise HTTPException(409, str(e)) + return {"status": "ok", "state": state.model_dump()} + + +@router.get("/failures/{failure_id}/evidence") +def evidence(failure_id: str): + graph = pipeline_mod.get_evidence_graph(failure_id) + if graph is None: + raise HTTPException(404, "Evidence graph not built yet; run the " + "EVIDENCE_AGGREGATION stage first") + return {"status": "ok", "graph": graph.model_dump()} + + +@router.get("/failures/{failure_id}/snippets") +def snippets(failure_id: str): + _failure_or_404(failure_id) + return {"status": "ok", "snippets": pipeline_mod.get_snippets(failure_id)} + + +@router.post("/failures/{failure_id}/cluster") +def cluster(failure_id: str, req: Optional[AnalyzeRequest] = None): + failure = _failure_or_404(failure_id) + req = req or AnalyzeRequest() + result = ScenarioMiningAgent(use_llm=req.use_llm).run( + failure_id, failure=failure) + return {"status": "ok", "result": result.model_dump()} + + +@router.post("/failures/{failure_id}/safety-assessment") +def safety_assessment(failure_id: str, req: Optional[AnalyzeRequest] = None): + failure = _failure_or_404(failure_id) + req = req or AnalyzeRequest() + result = SafetyImpactAgent(use_llm=req.use_llm).run( + failure_id, failure=failure) + return {"status": "ok", "result": result.model_dump()} + + +@router.post("/failures/{failure_id}/launch-assessment") +def launch_assessment(failure_id: str, req: Optional[AnalyzeRequest] = None): + _failure_or_404(failure_id) + req = req or AnalyzeRequest() + try: + state = pipeline_mod.run_stage( + failure_id, "LAUNCH_DECISION", seed=req.seed, use_llm=req.use_llm, + policy_input_overrides=req.policy_input_overrides or None) + except ValueError as e: + raise HTTPException(409, str(e)) + return {"status": "ok", "policy_evaluation": state.policy_evaluation, + "scorecard_id": state.scorecard_id} + + +# ------------------------------------------------------------------ human review + + +class HumanReviewRequest(BaseModel): + reviewer: str + decision: str + rationale: str + approved_option: Optional[str] = None + evidence_reviewed: List[str] = Field(default_factory=list) + override_reason: Optional[str] = None + + +@router.post("/failures/{failure_id}/human-review") +def human_review(failure_id: str, req: HumanReviewRequest): + failure = _failure_or_404(failure_id) + state = pipeline_mod.get_state(failure_id) + policy_version = (state.policy_evaluation or {}).get("policy_version", "") \ + if state else "" + try: + rec = review_mod.record_decision( + failure, reviewer=req.reviewer, decision=req.decision, + rationale=req.rationale, evidence_reviewed=req.evidence_reviewed, + policy_version=policy_version, + approved_option=req.approved_option, + override_reason=req.override_reason) + except Exception as e: + raise HTTPException(400, str(e)) + if req.decision == "confirm_failure": + failure.validated = True + elif req.decision == "reject_failure": + failure.validated = False + failure.status = "closed" + pipeline_mod.save_failure(failure) + return {"status": "ok", "review": rec.model_dump(), + "decisions": review_mod.decisions_for(failure_id)} + + +@router.get("/failures/{failure_id}/human-review") +def human_review_list(failure_id: str): + _failure_or_404(failure_id) + return {"status": "ok", "decisions": review_mod.decisions_for(failure_id)} + + +# ------------------------------------------------------------------ policy + + +@router.get("/policy") +def get_policy(version: Optional[str] = None): + try: + return {"status": "ok", "policy": policy_mod.get_policy(version)} + except KeyError as e: + raise HTTPException(404, str(e)) + + +class PolicyRequest(BaseModel): + policy: Dict + actor: str = "api" + + +@router.post("/policy") +def save_policy(req: PolicyRequest): + doc = policy_mod.save_policy(req.policy, actor=req.actor) + return {"status": "ok", "policy_version": doc["policy_version"], + "policy": doc} + + +@router.get("/policy/versions") +def policy_versions(): + return {"status": "ok", "versions": policy_mod.list_policies()} + + +# ------------------------------------------------------------------ flywheel + + +class SuiteRequest(BaseModel): + failure_id: str + use_llm: bool = False + + +@router.post("/evaluation-suites") +def create_suite(req: SuiteRequest): + _failure_or_404(req.failure_id) + try: + state = pipeline_mod.run_stage(req.failure_id, "LEARNING_FLYWHEEL", + use_llm=req.use_llm) + except ValueError as e: + raise HTTPException(409, str(e)) + rec = state.stage_record("LEARNING_FLYWHEEL") + return {"status": "ok", "stage_status": rec.status, "detail": rec.detail, + "suite_ids": state.suite_ids} + + +@router.get("/evaluation-suites") +def list_suites(): + return {"status": "ok", "suites": flywheel_mod.list_suites()} + + +@router.get("/evaluation-suites/{suite_id}") +def suite_detail(suite_id: str): + suite = flywheel_mod.get_suite(suite_id) + if suite is None: + raise HTTPException(404, f"Unknown suite {suite_id}") + return {"status": "ok", "suite": suite.model_dump()} + + +class PromoteRequest(BaseModel): + member_id: str + actor: Optional[str] = None + override_reason: Optional[str] = None + + +@router.post("/evaluation-suites/{suite_id}/promote-member") +def promote_member(suite_id: str, req: PromoteRequest): + try: + result = flywheel_mod.promote_member_to_training( + suite_id, req.member_id, actor=req.actor, + override_reason=req.override_reason) + except flywheel_mod.LeakageError as e: + raise HTTPException(403, str(e)) + except KeyError as e: + raise HTTPException(404, str(e)) + return {"status": "ok", **result} + + +class RegressionRequest(BaseModel): + seed: int = data_mod.DEFAULT_SEED + + +@router.post("/regression/evaluate") +def regression_evaluate(req: Optional[RegressionRequest] = None): + req = req or RegressionRequest() + return {"status": "ok", **flywheel_mod.regression_evaluate(seed=req.seed)} + + +# ------------------------------------------------------------------ scorecards / audit + + +@router.get("/scorecards/{scorecard_id}") +def scorecard(scorecard_id: str): + card = scorecard_mod.load_scorecard(scorecard_id) + if card is None: + raise HTTPException(404, f"Unknown scorecard {scorecard_id}") + return {"status": "ok", "scorecard": card} + + +@router.get("/audit/{failure_id}") +def audit(failure_id: str): + trail = store_mod.audit_trail(failure_id) + return {"status": "ok", "records": trail, + "chain": store_mod.verify_audit_chain(failure_id)} + + +# ------------------------------------------------------------------ worked example + + +@router.get("/worked-example") +def worked_example(refresh: bool = False, use_llm: bool = False): + if not refresh: + cached = store_mod.read_json("worked_example", "latest.json") + if cached: + return {"status": "ok", "walkthrough": cached, "cached": True} + walkthrough = we_mod.run_worked_example(use_llm=use_llm) + return {"status": "ok", "walkthrough": walkthrough, "cached": False} diff --git a/sensorflow/agentic/concentration.py b/sensorflow/agentic/concentration.py new file mode 100644 index 0000000000000000000000000000000000000000..0c3f6615d7163383c248d45f51d9f9acdbbdbb4e --- /dev/null +++ b/sensorflow/agentic/concentration.py @@ -0,0 +1,101 @@ +"""Distribution + concentration analysis (deterministic). + +Determines whether a failure pattern is uniform or concentrated across the +instrumented dimensions (construction zone, lighting, geography), computing +per-stratum failure rate vs the population baseline with relative risk, odds +ratio, Wilson CI, absolute risk difference and small-sample instability flags. + +All statistics are exact deterministic computations; the Wilson interval is +reused from megaeval (single source of truth for that formula). +""" + +from __future__ import annotations + +from typing import Dict, List + +import numpy as np + +from sensorflow.agentic import data as data_mod +from sensorflow.agentic.models import ConcentrationAnalysis, StratumRisk +from sensorflow.megaeval.sampling import wilson_interval + +MIN_EVENTS_FOR_STABLE_ESTIMATE = 5 +RELATIVE_RISK_CONCENTRATION_THRESHOLD = 3.0 + + +def _stratum_row(dim: str, name: str, mask: np.ndarray, flips: np.ndarray, + overall_rate: float) -> StratumRisk: + exposure = int(mask.sum()) + events = int(flips[mask].sum()) + rate = events / exposure if exposure else 0.0 + lo, hi = wilson_interval(events, exposure) + + out_events = int(flips[~mask].sum()) + out_exposure = int((~mask).sum()) + out_rate = out_events / out_exposure if out_exposure else 0.0 + + rr = (rate / out_rate) if out_rate > 0 else None + # odds ratio with Haldane-Anscombe 0.5 correction when any cell is zero + a, b = events, exposure - events + c, d = out_events, out_exposure - out_events + if min(a, b, c, d) == 0: + a, b, c, d = a + 0.5, b + 0.5, c + 0.5, d + 0.5 + odds = (a / b) / (c / d) if b > 0 and d > 0 and c > 0 else None + + return StratumRisk( + dimension=dim, stratum=name, + exposure=exposure, + exposure_share=round(exposure / flips.size, 4), + events=events, + stratum_rate=round(rate, 8), + baseline_rate=round(overall_rate, 8), + relative_risk=None if rr is None else round(rr, 3), + odds_ratio=None if odds is None else round(odds, 3), + risk_difference=round(rate - out_rate, 8), + rate_wilson_ci=[round(lo, 8), round(hi, 8)], + small_sample_flag=events < MIN_EVENTS_FOR_STABLE_ESTIMATE, + ) + + +def analyze_concentration(failure_id: str, seed: int = data_mod.DEFAULT_SEED + ) -> ConcentrationAnalysis: + arrays = data_mod.get_rate_arrays(seed) + flips = arrays.candidate_flip + overall_rate = float(flips.mean()) + + strata: List[StratumRisk] = [] + dims: Dict[str, List] = { + "construction_zone": [("construction", arrays.construction), + ("non_construction", ~arrays.construction)], + "lighting": [("night", arrays.night), ("day", ~arrays.night)], + "geo_bucket": [(data_mod.GEO_BUCKETS[i], arrays.geo == i) + for i in range(len(data_mod.GEO_BUCKETS))], + } + for dim, entries in dims.items(): + for name, mask in entries: + strata.append(_stratum_row(dim, name, mask, flips, overall_rate)) + + total_events = int(flips.sum()) + if total_events < MIN_EVENTS_FOR_STABLE_ESTIMATE: + determination = "insufficient_data" + concentrated = [] + else: + concentrated = sorted({ + s.dimension for s in strata + if s.relative_risk is not None + and s.relative_risk >= RELATIVE_RISK_CONCENTRATION_THRESHOLD + and not s.small_sample_flag}) + determination = "concentrated" if concentrated else "uniform" + + return ConcentrationAnalysis( + failure_id=failure_id, + determination=determination, + concentrated_dimensions=concentrated, + strata=strata, + method=( + "per-stratum rate vs complement with relative risk, " + "Haldane-Anscombe-corrected odds ratio, Wilson CI and absolute " + f"risk difference; a dimension is 'concentrated' when RR >= " + f"{RELATIVE_RISK_CONCENTRATION_THRESHOLD} on a stratum with >= " + f"{MIN_EVENTS_FOR_STABLE_ESTIMATE} events"), + ) diff --git a/sensorflow/agentic/data.py b/sensorflow/agentic/data.py new file mode 100644 index 0000000000000000000000000000000000000000..c59cfc8a54f17891a12c17ed415790d1e8a2f199 --- /dev/null +++ b/sensorflow/agentic/data.py @@ -0,0 +1,281 @@ +"""Deterministic synthetic evaluation campaign for the agentic subsystem. + +Two coupled data sources, both seeded and reproducible: + +1. SCENE CAMPAIGN — reuses sensorflow.bevfusion.scenes.generate_sequences as + the scene/track source. Every sequence gets a scene context (construction + zone flag, geo bucket) and every ground-truth box gets a baseline and a + candidate model prediction. Classification flips are PLANTED as contiguous + windows (mirroring the scenes module's occlusion-window convention) so that + temporal context (correct-before / failing / correct-after) genuinely + exists in the data. + +2. RATE POPULATION — a large vectorized paired outcome log (default 240k + pedestrian observations per model) that provides the denominator for + frequency claims. Pairing follows the seqeval recipe (shared per-object + latent + per-model flip stream) so the statistical agent can feed genuine + paired cluster means into seqeval's anytime-valid machinery. + +Numbers are chosen so the motivating failure reproduces: the candidate flips +pedestrian->construction_cone at ~1.2e-4 overall (~0.012%), concentrated in +construction-zone strata, while the baseline sits near 2e-5. +""" + +from __future__ import annotations + +import hashlib +import json +import threading +from typing import Dict, List, Optional + +import numpy as np +from pydantic import BaseModel, Field + +from sensorflow.bevfusion.scenes import SceneSequence, generate_sequences + +PRED_CLASSES = ["pedestrian", "cyclist", "motorcycle", "vehicle", "truck", + "construction_cone", "background"] +GEO_BUCKETS = ["bay_area_urban", "bay_area_suburban", "highway_101"] + +DEFAULT_SEED = 101 +DEFAULT_N_SEQUENCES = 12 +DEFAULT_FRAMES = 24 + +# Rate-population physics (per-observation flip probabilities). +RATE_N = 240_000 +RATE_CLUSTER_SIZE = 100 +BASELINE_FLIP_P = 2.0e-5 +CANDIDATE_FLIP_P_NORMAL = 3.0e-5 +CANDIDATE_FLIP_P_CONSTRUCTION = 8.0e-4 +CONSTRUCTION_EXPOSURE = 0.12 +NIGHT_SHARE = 0.35 + + +class Prediction(BaseModel): + predicted_class: str + confidence: float + bbox_3d: List[float] + track_id: str + + +class ObservationRecord(BaseModel): + """One GT object in one frame with both models' predictions.""" + + sequence_id: str + frame_id: str + frame_index: int + timestamp_us: int + object_instance_id: str + gt_class: str + gt_bbox_3d: List[float] + distance_m: float + occluded: bool + baseline: Prediction + candidate: Prediction + construction_zone: bool + time_of_day: str + weather: str + geo_bucket: str + has_planner_trace: bool = False + + +class SequenceContext(BaseModel): + sequence_id: str + construction_zone: bool + geo_bucket: str + time_of_day: str + weather: str + + +class Campaign(BaseModel): + campaign_id: str + seed: int + baseline_model: str = "baseline-v1" + candidate_model: str = "candidate-v2" + feature_pipeline_version: str = "featpipe-3.4.1" + software_config: Dict[str, str] = Field(default_factory=lambda: { + "perception_stack": "sensorflow-bevfusion-sim", + "build": "synthetic-campaign", + }) + hardware_config: Dict[str, str] = Field(default_factory=lambda: { + "compute": "synthetic-replay-node", "sensors": "cam+lidar (simulated)", + }) + contexts: List[SequenceContext] = Field(default_factory=list) + observations: List[ObservationRecord] = Field(default_factory=list) + + +class RatePopulation(BaseModel): + """Vectorized paired outcome log (arrays kept out of pydantic).""" + + population_id: str + seed: int + n: int + n_clusters: int + description: str + + model_config = {"arbitrary_types_allowed": True} + + +# ------------------------------------------------------------------ scene campaign + + +def _noisy_box(rng: np.random.Generator, bbox: List[float], sigma: float) -> List[float]: + out = list(bbox) + out[0] = round(out[0] + float(rng.normal(0, sigma)), 3) + out[1] = round(out[1] + float(rng.normal(0, sigma)), 3) + return out + + +def build_campaign(seed: int = DEFAULT_SEED, n_sequences: int = DEFAULT_N_SEQUENCES, + frames_per_sequence: int = DEFAULT_FRAMES) -> Campaign: + sequences: List[SceneSequence] = generate_sequences( + n_sequences=n_sequences, frames_per_sequence=frames_per_sequence, seed=seed) + rng = np.random.default_rng([seed, 0xA6E]) + + campaign = Campaign(campaign_id=f"campaign-{seed}-{n_sequences}x{frames_per_sequence}", + seed=seed) + + for qi, seq in enumerate(sequences): + construction = qi % 4 == 0 # every 4th sequence is a construction zone + ctx = SequenceContext( + sequence_id=seq.sequence_id, + construction_zone=construction, + geo_bucket=GEO_BUCKETS[qi % len(GEO_BUCKETS)], + time_of_day=seq.time_of_day, + weather=seq.weather, + ) + campaign.contexts.append(ctx) + + # Plant candidate flip windows on pedestrians in construction zones: + # contiguous frame windows where pedestrian -> construction_cone. + flip_windows: Dict[str, tuple] = {} + if construction: + ped_ids = sorted({gt.instance_id for fr in seq.frames for gt in fr.gt + if gt.class_name == "pedestrian"}) + for k, iid in enumerate(ped_ids[:2]): + start = 6 + 5 * k + flip_windows[iid] = (start, start + 3) + + for frame in seq.frames: + for gt in frame.gt: + b_cls = gt.class_name + c_cls = gt.class_name + win = flip_windows.get(gt.instance_id) + flipped = bool(win and win[0] <= frame.index < win[1]) + if flipped: + c_cls = "construction_cone" + # tiny background rate of unrelated flips for both models + elif rng.random() < 0.002: + c_cls = "vehicle" if gt.class_name != "vehicle" else "truck" + if rng.random() < 0.001: + b_cls = "vehicle" if gt.class_name != "vehicle" else "truck" + + conf_c = 0.62 if flipped else float(np.clip(rng.normal(0.88, 0.05), 0.3, 0.99)) + conf_b = float(np.clip(rng.normal(0.87, 0.05), 0.3, 0.99)) + obs = ObservationRecord( + sequence_id=seq.sequence_id, + frame_id=frame.frame_id, + frame_index=frame.index, + timestamp_us=frame.index * 100_000, + object_instance_id=gt.instance_id, + gt_class=gt.class_name, + gt_bbox_3d=gt.bbox_3d, + distance_m=gt.distance, + occluded=gt.occluded, + baseline=Prediction(predicted_class=b_cls, confidence=round(conf_b, 3), + bbox_3d=_noisy_box(rng, gt.bbox_3d, 0.12), + track_id=f"trk-b-{gt.instance_id}"), + candidate=Prediction(predicted_class=c_cls, confidence=round(conf_c, 3), + bbox_3d=_noisy_box(rng, gt.bbox_3d, 0.15), + track_id=f"trk-c-{gt.instance_id}"), + construction_zone=construction, + time_of_day=seq.time_of_day, + weather=seq.weather, + geo_bucket=ctx.geo_bucket, + # replay planner-response traces exist for half the planted + # flip windows (deterministically: first planted object) + has_planner_trace=bool(flipped and win == sorted(flip_windows.values())[0]), + ) + campaign.observations.append(obs) + return campaign + + +# ------------------------------------------------------------------ rate population + + +class RateArrays: + """Raw numpy arrays for the rate population (paired outcomes + strata).""" + + def __init__(self, seed: int, n: int = RATE_N): + rng_strata = np.random.default_rng([seed, 11]) + self.n = int(n) + self.cluster_id = np.arange(self.n) // RATE_CLUSTER_SIZE + self.n_clusters = int(self.cluster_id.max()) + 1 + self.construction = rng_strata.random(self.n) < CONSTRUCTION_EXPOSURE + self.night = rng_strata.random(self.n) < NIGHT_SHARE + self.geo = rng_strata.integers(0, len(GEO_BUCKETS), size=self.n) + + p_base = np.full(self.n, BASELINE_FLIP_P) + p_cand = np.where(self.construction, CANDIDATE_FLIP_P_CONSTRUCTION, + CANDIDATE_FLIP_P_NORMAL) + p_cand = p_cand * np.where(self.night, 1.3, 1.0) + + # seqeval-style pairing: shared latent + per-model flip stream. + u_pair = np.random.default_rng([seed, 0x5E9]).random(self.n) + b_noise = np.random.default_rng([seed, 21]).random(self.n) + c_noise = np.random.default_rng([seed, 22]).random(self.n) + u_b = np.where(b_noise < 0.05, np.random.default_rng([seed, 31]).random(self.n), u_pair) + u_c = np.where(c_noise < 0.05, np.random.default_rng([seed, 32]).random(self.n), u_pair) + self.baseline_flip = (u_b < p_base) + self.candidate_flip = (u_c < p_cand) + + def fingerprint(self) -> str: + blob = json.dumps({"n": self.n, "b": int(self.baseline_flip.sum()), + "c": int(self.candidate_flip.sum())}, sort_keys=True) + return hashlib.sha256(blob.encode()).hexdigest()[:16] + + +_CACHE: Dict[int, Dict] = {} +_LOCK = threading.Lock() + + +def get_campaign(seed: int = DEFAULT_SEED) -> Campaign: + with _LOCK: + entry = _CACHE.setdefault(seed, {}) + if "campaign" not in entry: + entry["campaign"] = build_campaign(seed) + return entry["campaign"] + + +def get_rate_arrays(seed: int = DEFAULT_SEED) -> RateArrays: + with _LOCK: + entry = _CACHE.setdefault(seed, {}) + if "rates" not in entry: + entry["rates"] = RateArrays(seed) + return entry["rates"] + + +def reset_data_cache() -> None: + with _LOCK: + _CACHE.clear() + + +def campaign_fingerprint(campaign: Campaign) -> str: + blob = json.dumps({"id": campaign.campaign_id, "seed": campaign.seed, + "obs": len(campaign.observations)}, sort_keys=True) + return hashlib.sha256(blob.encode()).hexdigest()[:16] + + +def observations_for_instance(campaign: Campaign, sequence_id: str, + object_instance_id: str) -> List[ObservationRecord]: + return sorted((o for o in campaign.observations + if o.sequence_id == sequence_id + and o.object_instance_id == object_instance_id), + key=lambda o: o.frame_index) + + +def context_for(campaign: Campaign, sequence_id: str) -> Optional[SequenceContext]: + for c in campaign.contexts: + if c.sequence_id == sequence_id: + return c + return None diff --git a/sensorflow/agentic/evidence.py b/sensorflow/agentic/evidence.py new file mode 100644 index 0000000000000000000000000000000000000000..9aa5b7e45dea8d9787d7c0d9eae3773b4c1afcbe --- /dev/null +++ b/sensorflow/agentic/evidence.py @@ -0,0 +1,175 @@ +"""Failure Evidence Graph. + +Structured, typed nodes (Object / Environment / Sensors / Prediction / +GroundTruth / Tracking / Planner / HistoricalSimilarity / Frequency / +SafetyConsequence) each carrying an explicit evidence status: + + OBSERVED directly measured from the campaign data / replay + DERIVED computed deterministically from observed data + HYPOTHESIS produced by an advisory agent; requires confirmation + UNAVAILABLE the evidence does not exist yet; the graph says so instead + of letting anything downstream pretend it does + +The graph starts from deterministic scene data and is enriched as analysis +stages complete. Nothing here consults an LLM. +""" + +from __future__ import annotations + +from typing import Optional + +from sensorflow.agentic import data as data_mod +from sensorflow.agentic.models import (EvidenceEdge, EvidenceGraph, EvidenceNode, + FailureEvent, new_id) + + +def _node(node_type: str, status: str, summary: str, fields: dict, + source: str, caveats: Optional[list] = None) -> EvidenceNode: + return EvidenceNode(node_id=new_id("ev"), node_type=node_type, status=status, + summary=summary, fields=fields, source=source, + caveats=caveats or []) + + +def build_graph(failure: FailureEvent, campaign: data_mod.Campaign) -> EvidenceGraph: + """Initial graph from deterministic campaign evidence for the failure's + representative instance (first instance).""" + graph = EvidenceGraph(failure_id=failure.failure_id) + inst = failure.instances[0] if failure.instances else None + + if inst is None: + graph.nodes.append(_node( + "Object", "UNAVAILABLE", + "No concrete failure instance is attached to this pattern", + {}, "pipeline")) + return graph + + history = data_mod.observations_for_instance( + campaign, inst.sequence_id, inst.object_instance_id) + obs = next((o for o in history if o.frame_id == inst.frame_id), None) + + graph.nodes.append(_node( + "Object", "OBSERVED", + f"{inst.gt_class} instance {inst.object_instance_id} at " + f"{inst.distance_m:.1f} m", + {"instance_id": inst.object_instance_id, "gt_class": inst.gt_class, + "distance_m": inst.distance_m, + "bbox_3d": obs.gt_bbox_3d if obs else None}, + "bevfusion synthetic scene ground truth")) + + graph.nodes.append(_node( + "Environment", "OBSERVED", + f"{inst.time_of_day}/{inst.weather}, construction_zone=" + f"{inst.construction_zone}, geo={inst.geo_bucket}", + {"time_of_day": inst.time_of_day, "weather": inst.weather, + "construction_zone": inst.construction_zone, + "geo_bucket": inst.geo_bucket, "occluded": inst.occluded}, + "sequence context (campaign metadata)")) + + graph.nodes.append(_node( + "Sensors", "DERIVED", + "Camera/LiDAR coherence not yet verified — pending fusion agent", + {"modalities": ["camera", "lidar"], "verified": False}, + "sensorflow.bevfusion simulated sensors", + caveats=["fusion verification runs in FAILURE_ANALYSIS"])) + + if obs is not None: + graph.nodes.append(_node( + "Prediction", "OBSERVED", + f"candidate predicted {obs.candidate.predicted_class} " + f"(conf {obs.candidate.confidence}); baseline predicted " + f"{obs.baseline.predicted_class} (conf {obs.baseline.confidence})", + {"candidate": obs.candidate.model_dump(), + "baseline": obs.baseline.model_dump(), + "candidate_model": failure.candidate_model, + "baseline_model": failure.baseline_model}, + "campaign prediction log")) + graph.nodes.append(_node( + "GroundTruth", "OBSERVED", + f"GT class {obs.gt_class} (synthetic vendor-style GT)", + {"gt_class": obs.gt_class, "gt_bbox_3d": obs.gt_bbox_3d, + "gt_source": "synthetic_vendor_gt"}, + "bevfusion synthetic scene ground truth")) + graph.nodes.append(_node( + "Tracking", "OBSERVED", + f"candidate track {obs.candidate.track_id}; " + f"{len(history)} frames observed for this instance", + {"candidate_track_id": obs.candidate.track_id, + "baseline_track_id": obs.baseline.track_id, + "frames_observed": len(history)}, + "campaign prediction log")) + else: + graph.nodes.append(_node("Prediction", "UNAVAILABLE", + "prediction record missing", {}, "campaign")) + graph.nodes.append(_node("GroundTruth", "UNAVAILABLE", + "ground truth record missing", {}, "campaign")) + graph.nodes.append(_node("Tracking", "UNAVAILABLE", + "tracking record missing", {}, "campaign")) + + if inst.has_planner_trace: + graph.nodes.append(_node( + "Planner", "OBSERVED", + "Replay planner-response trace exists for this instance", + {"replay_available": True, "analyzed": False}, + "synthetic planner replay trace", + caveats=["safety-impact agent quantifies behavior in FAILURE_ANALYSIS"])) + else: + graph.nodes.append(_node( + "Planner", "UNAVAILABLE", + "No behavioral replay evidence for this instance — downstream " + "consequence cannot be observed, only hypothesized", + {"replay_available": False}, + "synthetic planner replay trace")) + + graph.nodes.append(_node( + "HistoricalSimilarity", "DERIVED", + "Similar-failure retrieval pending (scenario mining agent)", + {"retrieved": False}, "scenario mining (embedding + attribute retrieval)")) + + basis = failure.detection_basis + graph.nodes.append(_node( + "Frequency", "DERIVED", + f"candidate {basis.candidate_events}/{basis.denominator} " + f"({basis.candidate_rate:.6f}) vs baseline {basis.baseline_events}" + f"/{basis.denominator} ({basis.baseline_rate:.6f}) — CI/significance " + "pending statistical agent", + {"candidate_events": basis.candidate_events, + "baseline_events": basis.baseline_events, + "denominator": basis.denominator, + "candidate_rate": basis.candidate_rate, + "baseline_rate": basis.baseline_rate}, + "deterministic detection scan")) + + graph.nodes.append(_node( + "SafetyConsequence", "UNAVAILABLE", + "Not yet assessed — requires safety-impact analysis over replay " + "evidence; hypotheses are never recorded as consequences", + {}, "safety impact agent (FAILURE_ANALYSIS)")) + + ids = {n.node_type: n.node_id for n in graph.nodes} + for src, dst, rel in [ + ("Object", "Prediction", "was_predicted_as"), + ("Object", "GroundTruth", "labeled_as"), + ("Object", "Environment", "situated_in"), + ("Prediction", "Tracking", "feeds"), + ("Tracking", "Planner", "feeds"), + ("Prediction", "Frequency", "aggregated_into"), + ("Planner", "SafetyConsequence", "determines"), + ("Object", "HistoricalSimilarity", "compared_against"), + ("Sensors", "Prediction", "produced"), + ]: + if src in ids and dst in ids: + graph.edges.append(EvidenceEdge(src=ids[src], dst=ids[dst], relation=rel)) + return graph + + +def set_node(graph: EvidenceGraph, node_type: str, status: str, summary: str, + fields: dict, source: str, caveats: Optional[list] = None) -> None: + """Replace (or add) a node after an analysis stage produced its evidence.""" + for i, n in enumerate(graph.nodes): + if n.node_type == node_type: + graph.nodes[i] = EvidenceNode( + node_id=n.node_id, node_type=node_type, status=status, + summary=summary, fields=fields, source=source, + caveats=caveats or []) + return + graph.nodes.append(_node(node_type, status, summary, fields, source, caveats)) diff --git a/sensorflow/agentic/flywheel.py b/sensorflow/agentic/flywheel.py new file mode 100644 index 0000000000000000000000000000000000000000..aa6a62634bfff7b2f1a4c1f473f7ffaa0b0eeea2 --- /dev/null +++ b/sensorflow/agentic/flywheel.py @@ -0,0 +1,250 @@ +"""Evaluation flywheel — deterministic service. + +validated failure -> taxonomy -> cluster -> evaluation suite create/update, +with the governance fields required by the spec (suite_id, version, +creation_reason, source_failures, sampling_policy, coverage, +known_limitations, approval_status, ...), diversity-aware sampling (no +duplicate-frame stuffing) and a CONTAMINATION GUARD: suite members are never +training-eligible without an explicit recorded override. + +The guard mirrors the raremine leakage-guard concept; raremine is an +in-progress module, so it is imported defensively and a local guard with the +same semantics is used when it is unavailable. +""" + +from __future__ import annotations + +from collections import defaultdict +from typing import Dict, List, Optional + +from sensorflow.agentic import data as data_mod +from sensorflow.agentic import store as store_mod +from sensorflow.agentic.models import (EvaluationSuite, FailureEvent, + SuiteMember, new_id, now_iso) +from sensorflow.seqeval.sequential import PairedSequentialTest + +# ---- contamination guard: prefer raremine's LeakageError concept ----------- +try: # raremine is an in-progress fenced module: import only defensively + from sensorflow.raremine.lineage import LeakageError as _RaremineLeakageError + LeakageError = _RaremineLeakageError + _LEAKAGE_SOURCE = "sensorflow.raremine.lineage.LeakageError" +except Exception: # pragma: no cover - depends on concurrent work + class LeakageError(RuntimeError): + """Raised when a protected evaluation example would leak to training.""" + _LEAKAGE_SOURCE = "local fallback (raremine unavailable at import time)" + +MAX_FRAMES_PER_OBJECT = 2 # diversity-aware sampling: no duplicate stuffing + + +def _diverse_members(failure: FailureEvent) -> List[SuiteMember]: + per_object: Dict[str, int] = defaultdict(int) + seen_frames = set() + members: List[SuiteMember] = [] + for inst in sorted(failure.instances, + key=lambda i: (i.sequence_id, i.frame_index)): + key = f"{inst.sequence_id}:{inst.object_instance_id}" + frame_key = f"{inst.sequence_id}:{inst.frame_id}" + if per_object[key] >= MAX_FRAMES_PER_OBJECT or frame_key in seen_frames: + continue + per_object[key] += 1 + seen_frames.add(frame_key) + members.append(SuiteMember( + member_id=new_id("mem"), + sequence_id=inst.sequence_id, + frame_id=inst.frame_id, + object_instance_id=inst.object_instance_id, + source_failure_id=failure.failure_id, + training_eligible=False, # contamination guard: unconditional default + )) + return members + + +def create_or_update_suite(failure: FailureEvent, proposal: Dict, + actor: str = "flywheel") -> EvaluationSuite: + """Create (or version-bump) a suite from a VALIDATED failure.""" + if not failure.validated: + raise LeakageError( + f"failure {failure.failure_id} is not human-validated; the " + "flywheel refuses to create evaluation suites from unconfirmed " + "failures") + + name = proposal["suite_name"] + existing_id = None + for fname in store_mod.list_dir("suites"): + doc = store_mod.read_json("suites", fname) + if doc and doc.get("name") == name: + existing_id = doc["suite_id"] + break + + members = _diverse_members(failure) + coverage = { + "sequences": len({m.sequence_id for m in members}), + "objects": len({m.object_instance_id for m in members}), + "frames": len(members), + "construction_zone_share": round( + sum(1 for i in failure.instances if i.construction_zone) + / max(len(failure.instances), 1), 3), + } + + if existing_id: + doc = store_mod.read_json("suites", f"{existing_id}.json") + suite = EvaluationSuite.model_validate(doc) + known = {(m.sequence_id, m.frame_id) for m in suite.members} + added = [m for m in members if (m.sequence_id, m.frame_id) not in known] + suite.members.extend(added) + suite.version += 1 + if failure.failure_id not in suite.source_failures: + suite.source_failures.append(failure.failure_id) + suite.coverage = coverage + suite.updated_at = now_iso() + else: + suite = EvaluationSuite( + suite_id=new_id("suite"), + name=name, + creation_reason=proposal["creation_reason"], + source_failures=[failure.failure_id], + taxonomy_tags=proposal.get("taxonomy_tags", []), + sampling_policy=proposal.get("sampling_policy", ""), + coverage=coverage, + known_limitations=proposal.get("known_limitations", []), + approval_status="draft", + members=members, + ) + store_mod.write_json(suite, "suites", f"{suite.suite_id}.json") + store_mod.audit("suite_created_or_updated", failure.failure_id, actor, + detail=f"suite {suite.suite_id} ({suite.name}) v{suite.version} " + f"members={len(suite.members)}", + payload={"suite_id": suite.suite_id}) + return suite + + +def get_suite(suite_id: str) -> Optional[EvaluationSuite]: + doc = store_mod.read_json("suites", f"{suite_id}.json") + return EvaluationSuite.model_validate(doc) if doc else None + + +def list_suites() -> List[Dict]: + out = [] + for fname in store_mod.list_dir("suites"): + doc = store_mod.read_json("suites", fname) + if doc: + out.append(doc) + return sorted(out, key=lambda d: d.get("created_at", ""), reverse=True) + + +def promote_member_to_training(suite_id: str, member_id: str, + actor: Optional[str] = None, + override_reason: Optional[str] = None) -> Dict: + """Contamination guard: raises LeakageError unless an explicit override + (who + why) is provided; the override is recorded on the suite AND in the + audit trail.""" + suite = get_suite(suite_id) + if suite is None: + raise KeyError(f"Unknown suite {suite_id}") + member = next((m for m in suite.members if m.member_id == member_id), None) + if member is None: + raise KeyError(f"Unknown member {member_id}") + if not actor or not override_reason: + raise LeakageError( + f"member {member_id} belongs to a protected evaluation suite " + "(training_eligible=false); promotion to training requires an " + f"explicit recorded override (who + why) [{_LEAKAGE_SOURCE}]") + member.training_eligible = True + suite.governance_overrides.append({ + "member_id": member_id, "actor": actor, "reason": override_reason, + "timestamp": now_iso(), + }) + suite.updated_at = now_iso() + store_mod.write_json(suite, "suites", f"{suite.suite_id}.json") + store_mod.audit("contamination_guard_override", + member.source_failure_id, actor, + detail=f"member {member_id} of suite {suite_id} made " + f"training-eligible: {override_reason}") + return {"suite_id": suite_id, "member_id": member_id, + "training_eligible": True, "override_recorded": True} + + +# ------------------------------------------------------------------ regression hook + + +STANDING_SUITES = ["general", "historical-regression", "rare-event", + "safety-critical"] + + +def regression_evaluate(seed: int = data_mod.DEFAULT_SEED, + include_created_suites: bool = True) -> Dict: + """Evaluate the candidate against general + historical-regression + + construction-zone + rare-event + safety-critical suites. + + Per suite: baseline/candidate success rates, delta, anytime-valid CI and + the three-outcome decision — all statistics DELEGATED to seqeval's + PairedSequentialTest (never reimplemented).""" + campaign = data_mod.get_campaign(seed) + obs = campaign.observations + + def subset(name: str): + if name == "general": + return obs + if name == "historical-regression": + return [o for o in obs if o.gt_class in ("vehicle", "truck")] + if name == "rare-event": + return [o for o in obs if o.occluded or o.distance_m > 45.0] + if name == "safety-critical": + return [o for o in obs if o.gt_class in ("pedestrian", "cyclist", + "motorcycle")] + return [] + + suites: List[Dict] = [{"suite": n, "members": subset(n)} for n in STANDING_SUITES] + if include_created_suites: + by_frame = {(o.sequence_id, o.frame_id, o.object_instance_id): o for o in obs} + for doc in list_suites(): + members = [by_frame.get((m["sequence_id"], m["frame_id"], + m["object_instance_id"])) + for m in doc.get("members", [])] + suites.append({"suite": doc["name"], + "suite_id": doc["suite_id"], + "members": [m for m in members if m is not None]}) + + results = [] + for entry in suites: + members = entry["members"] + if not members: + results.append({"suite": entry["suite"], "n": 0, + "decision": "INSUFFICIENT_EVIDENCE", + "note": "no members resolvable in the campaign"}) + continue + b = [o.baseline.predicted_class == o.gt_class for o in members] + c = [o.candidate.predicted_class == o.gt_class for o in members] + d = [float(ci) - float(bi) for bi, ci in zip(b, c)] + # cluster by sequence for honest correlation handling + by_seq: Dict[str, List[float]] = defaultdict(list) + for o, di in zip(members, d): + by_seq[o.sequence_id].append(di) + cluster_means = [sum(v) / len(v) for v in by_seq.values()] + + test = PairedSequentialTest(delta=0.01, alpha=0.05) + test.update_clusters(cluster_means) + test.record_objects(b, c) + decision = test.evaluate() + snap = test.snapshot() + results.append({ + "suite": entry["suite"], + "suite_id": entry.get("suite_id"), + "n": len(members), + "n_clusters": len(cluster_means), + "baseline_rate": round(sum(b) / len(b), 5), + "candidate_rate": round(sum(c) / len(c), 5), + "delta": round(sum(c) / len(c) - sum(b) / len(b), 5), + "delta_ci": snap["delta_ci"], + "decision": decision, + "e_regression": snap["e_regression"], + "stats_delegated_to": "sensorflow.seqeval.sequential.PairedSequentialTest", + }) + + out = {"evaluated_at": now_iso(), "seed": seed, "suites": results, + "note": ("INSUFFICIENT_EVIDENCE is reported as-is; it is never a " + "pass")} + store_mod.write_json(out, "regression", "latest.json") + store_mod.audit("regression_evaluated", None, "flywheel", + detail=f"{len(results)} suites evaluated") + return out diff --git a/sensorflow/agentic/models.py b/sensorflow/agentic/models.py new file mode 100644 index 0000000000000000000000000000000000000000..4ac96105cbac54815c71b3f27551f6a6bf32c066 --- /dev/null +++ b/sensorflow/agentic/models.py @@ -0,0 +1,411 @@ +"""Shared pydantic schemas for the agentic launch-readiness subsystem. + +Everything downstream (pipeline state, policy inputs, scorecards) is explicit, +typed, staged state — never free-form agent memory. Evidence values carry an +epistemic tag (OBSERVED / DERIVED / HYPOTHESIS / UNAVAILABLE) so an LLM +hypothesis can never masquerade as a measurement. +""" + +from __future__ import annotations + +import uuid +from datetime import datetime, timezone +from typing import Any, Dict, List, Literal, Optional + +from pydantic import BaseModel, Field + +# ------------------------------------------------------------------ enums + +EvidenceStatus = Literal["OBSERVED", "DERIVED", "HYPOTHESIS", "UNAVAILABLE"] + +EvidenceQuality = Literal["CONFIRMED", "LIKELY", "POSSIBLE", "INSUFFICIENT_EVIDENCE"] + +Severity = Literal["S0", "S1", "S2", "S3", "S4", "S5"] + +PolicyOutcome = Literal[ + "AUTOMATIC_STOP_SHIP", + "LAUNCH_REVIEW_REQUIRED", + "CONTINUE_INVESTIGATION", + "NO_LAUNCH_IMPACT", + "INDETERMINATE", +] + +OptionCode = Literal[ + "STOP_SHIP", + "OPTION_A_DELAY", + "OPTION_B_MITIGATION", + "OPTION_C_REDUCED_ODD", + "EXPAND_EVALUATION", + "HUMAN_SAFETY_REVIEW", + "PROCEED", +] + +FusionVerdict = Literal[ + "multi_modal_supported", "single_modality_only", "modality_conflict", + "verification_failed", +] + +STAGES = [ + "FAILURE_DETECTION", + "EVIDENCE_AGGREGATION", + "FAILURE_ANALYSIS", + "LAUNCH_DECISION", + "LEARNING_FLYWHEEL", +] + +StageStatus = Literal["pending", "running", "complete", "failed", "blocked"] + +FailureKind = Literal[ + "classification_flip", "localization_regression", "detection_regression", + "confidence_calibration_regression", "temporal_regression", +] + + +def now_iso() -> str: + return datetime.now(timezone.utc).isoformat() + + +def new_id(prefix: str) -> str: + return f"{prefix}-{uuid.uuid4().hex[:10]}" + + +# ------------------------------------------------------------------ failure events + + +class FailureInstance(BaseModel): + """One concrete occurrence of the failure pattern (scene-addressable).""" + + instance_id: str + sequence_id: str + frame_id: str + frame_index: int + object_instance_id: str + gt_class: str + predicted_class: str + confidence: float + distance_m: float + construction_zone: bool = False + time_of_day: str = "day" + weather: str = "clear" + geo_bucket: str = "unknown" + occluded: bool = False + has_planner_trace: bool = False + + +class DetectionBasis(BaseModel): + """Deterministic measurements that caused the agent to emit the event.""" + + method: str + candidate_events: int + baseline_events: int + denominator: int + candidate_rate: float + baseline_rate: float + metric_deltas: Dict[str, float] = Field(default_factory=dict) + notes: List[str] = Field(default_factory=list) + + +class FailureEvent(BaseModel): + """A candidate failure PATTERN (with member instances), the unit the + five-layer pipeline analyzes.""" + + failure_id: str + kind: FailureKind + title: str + description: str = "" + gt_class: Optional[str] = None + predicted_class: Optional[str] = None + detection_basis: DetectionBasis + instances: List[FailureInstance] = Field(default_factory=list) + baseline_model: str = "baseline-v1" + candidate_model: str = "candidate-v2" + dataset_fingerprint: str = "" + population_id: str = "" + status: str = "detected" # detected|investigating|decided|closed + severity: Optional[Severity] = None + policy_outcome: Optional[PolicyOutcome] = None + validated: bool = False # set only by human review + created_at: str = Field(default_factory=now_iso) + + +# ------------------------------------------------------------------ agent I/O + + +class AgentEscalation(BaseModel): + required: bool = False + reasons: List[str] = Field(default_factory=list) + human_review_triggers: List[str] = Field(default_factory=list) + + +class AgentResult(BaseModel): + """Uniform output envelope for every agent. + + `authority` is a structural constant: agents can only ever RECOMMEND. + """ + + agent: str + agent_version: str + failure_id: str + status: Literal["ok", "failed", "escalated"] = "ok" + authority: Literal["ADVISORY_ONLY"] = "ADVISORY_ONLY" + output: Dict[str, Any] = Field(default_factory=dict) + confidence: float = 0.0 + confidence_basis: str = "" + epistemic_status: EvidenceStatus = "DERIVED" + escalation: AgentEscalation = Field(default_factory=AgentEscalation) + failure_handling: Optional[str] = None + llm_used: bool = False + llm_provider: Optional[str] = None + llm_rationale: Optional[str] = None + started_at: str = Field(default_factory=now_iso) + finished_at: str = Field(default_factory=now_iso) + + +# ------------------------------------------------------------------ evidence graph + + +class EvidenceNode(BaseModel): + node_id: str + node_type: Literal[ + "Object", "Environment", "Sensors", "Prediction", "GroundTruth", + "Tracking", "Planner", "HistoricalSimilarity", "Frequency", + "SafetyConsequence", + ] + status: EvidenceStatus + summary: str + fields: Dict[str, Any] = Field(default_factory=dict) + source: str = "" + caveats: List[str] = Field(default_factory=list) + + +class EvidenceEdge(BaseModel): + src: str + dst: str + relation: str + + +class EvidenceGraph(BaseModel): + failure_id: str + nodes: List[EvidenceNode] = Field(default_factory=list) + edges: List[EvidenceEdge] = Field(default_factory=list) + built_at: str = Field(default_factory=now_iso) + + def node(self, node_type: str) -> Optional[EvidenceNode]: + for n in self.nodes: + if n.node_type == node_type: + return n + return None + + +# ------------------------------------------------------------------ snippet + + +class TemporalFrameRef(BaseModel): + frame_id: str + frame_index: int + role: Literal["before", "failure", "after"] + gt_class: Optional[str] = None + predicted_class: Optional[str] = None + confidence: Optional[float] = None + bbox_3d: Optional[List[float]] = None + + +class FailureSnippet(BaseModel): + """Reproducible failure package: everything needed to replay/triage one + concrete failure instance, plus temporal context.""" + + snippet_id: str + failure_id: str + instance_id: str + scene_id: str + sequence_id: str + timestamp_us: int + frame_index: int + model_version_candidate: str + model_version_baseline: str + prediction: Dict[str, Any] + ground_truth: Dict[str, Any] + confidence: float + tracking_state: Dict[str, Any] = Field(default_factory=dict) + planner_state: Dict[str, Any] = Field(default_factory=dict) + environment: Dict[str, Any] = Field(default_factory=dict) + geo_bucket: str = "unknown" + software_config: Dict[str, Any] = Field(default_factory=dict) + hardware_config: Dict[str, Any] = Field(default_factory=dict) + feature_pipeline_version: str = "" + temporal_context: List[TemporalFrameRef] = Field(default_factory=list) + similar_historical: List[Dict[str, Any]] = Field(default_factory=list) + created_at: str = Field(default_factory=now_iso) + + +# ------------------------------------------------------------------ statistics + + +class RateEstimate(BaseModel): + events: int + denominator: int + rate: float + wilson_ci: List[float] + ci_method: str = "Wilson score (megaeval.sampling.wilson_interval)" + + +class StatisticalAssessment(BaseModel): + """Output of the (mostly deterministic) statistical regression agent.""" + + baseline: RateEstimate + candidate: RateEstimate + absolute_delta: float + relative_delta: Optional[float] + significant: bool + significance_method: str + exact_binomial_p: Optional[float] = None + seqeval: Dict[str, Any] = Field(default_factory=dict) + power_mde: Dict[str, Any] = Field(default_factory=dict) + small_sample_flags: List[str] = Field(default_factory=list) + rare_event_handling: str = "" + + +# ------------------------------------------------------------------ concentration + + +class StratumRisk(BaseModel): + dimension: str + stratum: str + exposure: int + exposure_share: float + events: int + stratum_rate: float + baseline_rate: float + relative_risk: Optional[float] + odds_ratio: Optional[float] + risk_difference: float + rate_wilson_ci: List[float] + small_sample_flag: bool = False + + +class ConcentrationAnalysis(BaseModel): + failure_id: str + determination: Literal["concentrated", "uniform", "insufficient_data"] + concentrated_dimensions: List[str] = Field(default_factory=list) + strata: List[StratumRisk] = Field(default_factory=list) + method: str = "" + + +# ------------------------------------------------------------------ scorecard + + +class ScorecardField(BaseModel): + """A scorecard value with explicit provenance.""" + + value: Any + tag: Literal["OBSERVED", "PREDICTED", "HYPOTHETICAL", "REQUIRED_EVIDENCE"] + evidence_ref: str = "" + + +class AgenticSafetyScorecard(BaseModel): + scorecard_id: str + failure_id: str + title: str + failure_summary: ScorecardField + frequency: ScorecardField + exposure: ScorecardField + severity: ScorecardField + confidence: ScorecardField + novelty: ScorecardField + concentration: ScorecardField + downstream_impact: ScorecardField + mitigations: ScorecardField + residual_risk: ScorecardField + evidence_quality: EvidenceQuality + policy_outcome: Optional[PolicyOutcome] = None + recommended_option: Optional[OptionCode] = None + policy_version: str = "" + generated_at: str = Field(default_factory=now_iso) + notes: List[str] = Field(default_factory=list) + + +# ------------------------------------------------------------------ governance + + +class HumanReviewDecision(BaseModel): + review_id: str + failure_id: str + reviewer: str + decision: Literal[ + "confirm_failure", "reject_failure", "approve_launch", + "block_launch", "approve_option", "request_more_evidence", + ] + approved_option: Optional[OptionCode] = None + evidence_reviewed: List[str] = Field(default_factory=list) + policy_version: str = "" + rationale: str = "" + override_reason: Optional[str] = None + timestamp: str = Field(default_factory=now_iso) + + +# ------------------------------------------------------------------ flywheel + + +class SuiteMember(BaseModel): + member_id: str + sequence_id: str + frame_id: str + object_instance_id: str + source_failure_id: str + training_eligible: bool = False # contamination guard default + added_at: str = Field(default_factory=now_iso) + + +class EvaluationSuite(BaseModel): + suite_id: str + name: str + version: int = 1 + creation_reason: str + source_failures: List[str] = Field(default_factory=list) + taxonomy_tags: List[str] = Field(default_factory=list) + sampling_policy: str = "" + coverage: Dict[str, Any] = Field(default_factory=dict) + known_limitations: List[str] = Field(default_factory=list) + approval_status: Literal["draft", "approved", "retired"] = "draft" + members: List[SuiteMember] = Field(default_factory=list) + contamination_guard: str = ( + "suite members are training-ineligible without an explicit recorded " + "governance override" + ) + governance_overrides: List[Dict[str, Any]] = Field(default_factory=list) + created_at: str = Field(default_factory=now_iso) + updated_at: str = Field(default_factory=now_iso) + + +# ------------------------------------------------------------------ pipeline state + + +class StageRecord(BaseModel): + stage: str + status: StageStatus = "pending" + started_at: Optional[str] = None + finished_at: Optional[str] = None + detail: str = "" + + +class PipelineState(BaseModel): + """Explicit staged state — deliberately NOT one autonomous agent + controlling the chain. Each stage transition is orchestrated, persisted + and audited by deterministic code.""" + + failure_id: str + stages: List[StageRecord] = Field( + default_factory=lambda: [StageRecord(stage=s) for s in STAGES]) + agent_results: Dict[str, AgentResult] = Field(default_factory=dict) + statistical: Optional[StatisticalAssessment] = None + concentration: Optional[ConcentrationAnalysis] = None + policy_evaluation: Optional[Dict[str, Any]] = None + scorecard_id: Optional[str] = None + suite_ids: List[str] = Field(default_factory=list) + updated_at: str = Field(default_factory=now_iso) + + def stage_record(self, stage: str) -> StageRecord: + for s in self.stages: + if s.stage == stage: + return s + raise KeyError(stage) diff --git a/sensorflow/agentic/pipeline.py b/sensorflow/agentic/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..d0fb25a62bf421a6de24e2c5adff7ee16bb4860e --- /dev/null +++ b/sensorflow/agentic/pipeline.py @@ -0,0 +1,457 @@ +"""Five-layer pipeline orchestrator. + +FAILURE DETECTION -> EVIDENCE AGGREGATION -> FAILURE ANALYSIS -> +LAUNCH DECISION -> LEARNING FLYWHEEL + +Explicit staged state (pydantic PipelineState), orchestrated by this +deterministic module — never one autonomous agent controlling the chain. +Deterministic components own metrics, thresholds, statistical tests, lineage, +policy, gates and the audit log; agents contribute typed advisory results. + +Every stage transition, agent output and policy evaluation is appended to the +immutable audit trail (store.audit). +""" + +from __future__ import annotations + +from typing import Dict, List, Optional + +from sensorflow.agentic import concentration as conc_mod +from sensorflow.agentic import data as data_mod +from sensorflow.agentic import evidence as evidence_mod +from sensorflow.agentic import flywheel as flywheel_mod +from sensorflow.agentic import policy as policy_mod +from sensorflow.agentic import review as review_mod +from sensorflow.agentic import scorecard as scorecard_mod +from sensorflow.agentic import snippets as snippets_mod +from sensorflow.agentic import store as store_mod +from sensorflow.agentic.agents import (EvalFlywheelAgent, FailureDetectionAgent, + LaunchDecisionAgent, SafetyImpactAgent, + ScenarioMiningAgent, + SensorFusionVerificationAgent, + StatisticalRegressionAgent, + VLMSceneAnalysisAgent) +from sensorflow.agentic.models import (STAGES, EvidenceGraph, FailureEvent, + PipelineState, StatisticalAssessment, + now_iso) + +SAFETY_CRITICAL = {"pedestrian", "cyclist", "motorcycle"} +MAX_SNIPPETS = 6 + + +# ------------------------------------------------------------------ persistence + + +def save_failure(failure: FailureEvent) -> None: + store_mod.write_json(failure, "failures", f"{failure.failure_id}.json") + + +def get_failure(failure_id: str) -> Optional[FailureEvent]: + doc = store_mod.read_json("failures", f"{failure_id}.json") + return FailureEvent.model_validate(doc) if doc else None + + +def list_failures() -> List[Dict]: + out = [] + for name in store_mod.list_dir("failures"): + doc = store_mod.read_json("failures", name) + if doc: + doc["instances"] = doc.get("instances", [])[:3] # queue view: trim + out.append(doc) + return sorted(out, key=lambda d: d.get("created_at", "")) + + +def save_state(state: PipelineState) -> None: + state.updated_at = now_iso() + store_mod.write_json(state, "pipeline", f"{state.failure_id}.json") + + +def get_state(failure_id: str) -> Optional[PipelineState]: + doc = store_mod.read_json("pipeline", f"{failure_id}.json") + return PipelineState.model_validate(doc) if doc else None + + +def get_evidence_graph(failure_id: str) -> Optional[EvidenceGraph]: + doc = store_mod.read_json("evidence", f"{failure_id}.json") + return EvidenceGraph.model_validate(doc) if doc else None + + +def get_snippets(failure_id: str) -> List[Dict]: + return [store_mod.read_json("snippets", failure_id, n) + for n in store_mod.list_dir("snippets", failure_id)] + + +def _transition(state: PipelineState, stage: str, status: str, + detail: str = "") -> None: + rec = state.stage_record(stage) + if status == "running": + rec.started_at = now_iso() + else: + rec.finished_at = now_iso() + rec.status = status + rec.detail = detail + save_state(state) + store_mod.audit("stage_transition", state.failure_id, "pipeline", + detail=f"{stage} -> {status}" + (f": {detail}" if detail else "")) + + +def _record_agent(state: PipelineState, result) -> None: + state.agent_results[result.agent] = result + store_mod.audit("agent_output", state.failure_id, result.agent, + detail=f"status={result.status} confidence={result.confidence}", + payload={"agent_version": result.agent_version, + "escalation": result.escalation.model_dump(), + "epistemic_status": result.epistemic_status}) + + +# ------------------------------------------------------------------ layer 1 + + +def detect_failures(seed: int = data_mod.DEFAULT_SEED, + use_llm: bool = False) -> List[FailureEvent]: + agent = FailureDetectionAgent(use_llm=use_llm) + events, summary = agent.detect(seed) + scan_result = agent.run("_detection_scan", seed=seed) + for failure in events: + save_failure(failure) + state = PipelineState(failure_id=failure.failure_id) + _transition(state, "FAILURE_DETECTION", "running") + scan_copy = scan_result.model_copy(update={"failure_id": failure.failure_id}) + _record_agent(state, scan_copy) + _transition(state, "FAILURE_DETECTION", "complete", + detail=f"{failure.title} " + f"(candidate {failure.detection_basis.candidate_events} " + f"vs baseline {failure.detection_basis.baseline_events} " + f"over n={failure.detection_basis.denominator})") + store_mod.audit("detection_scan", None, "failure_detection", + detail=f"{len(events)} failure patterns emitted", + payload={"scan": {k: v for k, v in summary.items() + if k != "checks"}}) + return events + + +# ------------------------------------------------------------------ layer 2 + + +def run_evidence_aggregation(failure: FailureEvent, state: PipelineState, + seed: int) -> None: + _transition(state, "EVIDENCE_AGGREGATION", "running") + campaign = data_mod.get_campaign(seed) + graph = evidence_mod.build_graph(failure, campaign) + store_mod.write_json(graph, "evidence", f"{failure.failure_id}.json") + n_snips = 0 + for inst in failure.instances[:MAX_SNIPPETS]: + snip = snippets_mod.build_snippet(failure, inst, campaign) + store_mod.write_json(snip, "snippets", failure.failure_id, + f"{snip.snippet_id}.json") + n_snips += 1 + _transition(state, "EVIDENCE_AGGREGATION", "complete", + detail=f"evidence graph ({len(graph.nodes)} nodes) + " + f"{n_snips} snippets") + + +# ------------------------------------------------------------------ layer 3 + + +def _is_rate_population_failure(failure: FailureEvent) -> bool: + return (failure.kind == "classification_flip" + and failure.gt_class == "pedestrian" + and failure.predicted_class == "construction_cone") + + +def run_failure_analysis(failure: FailureEvent, state: PipelineState, + seed: int, use_llm: bool = False) -> None: + _transition(state, "FAILURE_ANALYSIS", "running") + campaign = data_mod.get_campaign(seed) + + vlm = VLMSceneAnalysisAgent(use_llm=use_llm).run( + failure.failure_id, failure=failure) + _record_agent(state, vlm) + + fusion = SensorFusionVerificationAgent(use_llm=use_llm).run( + failure.failure_id, failure=failure, seed=seed) + _record_agent(state, fusion) + + mining = ScenarioMiningAgent(use_llm=use_llm).run( + failure.failure_id, failure=failure) + _record_agent(state, mining) + + stat_agent = StatisticalRegressionAgent(use_llm=use_llm) + if _is_rate_population_failure(failure): + stat = stat_agent.run(failure.failure_id, seed=seed) + state.statistical = StatisticalAssessment.model_validate(stat.output) + state.concentration = conc_mod.analyze_concentration(failure.failure_id, seed) + else: + stat = stat_agent.run(failure.failure_id, seed=seed) + stat.output["scope_note"] = ( + "rate-population telemetry instruments the pedestrian->" + "construction_cone channel; for this failure the campaign counts " + "in detection_basis are the denominator of record") + state.statistical = None + state.concentration = None + _record_agent(state, stat) + + safety = SafetyImpactAgent(use_llm=use_llm).run( + failure.failure_id, failure=failure) + _record_agent(state, safety) + + # ---- deterministic evidence-graph updates ------------------------- + graph = get_evidence_graph(failure.failure_id) + if graph is not None: + if fusion.status != "failed": + evidence_mod.set_node( + graph, "Sensors", + "OBSERVED" if fusion.output.get("overall_verdict") + != "verification_failed" else "UNAVAILABLE", + f"fusion verdict: {fusion.output.get('overall_verdict')}", + {"verdict": fusion.output.get("overall_verdict"), + "verdict_counts": fusion.output.get("verdict_counts")}, + "sensor fusion verification agent (deterministic re-simulation)") + if mining.status == "ok": + evidence_mod.set_node( + graph, "HistoricalSimilarity", "DERIVED", + f"novelty: {mining.output.get('novelty')} " + f"({mining.output.get('exact_precedent_count')} precedents)", + {"novelty": mining.output.get("novelty"), + "top_similar": mining.output.get("similar_historical", [])[:3], + "clusters": mining.output.get("clusters", [])}, + "scenario mining agent (deterministic retrieval)") + if state.statistical is not None: + s = state.statistical + evidence_mod.set_node( + graph, "Frequency", "OBSERVED", + f"candidate {s.candidate.rate:.6f} " + f"(CI {s.candidate.wilson_ci}) vs baseline " + f"{s.baseline.rate:.6f}; significant={s.significant}", + {"statistical": s.model_dump()}, + "statistical regression agent (deterministic; stats via " + "seqeval + exact binomial)") + if safety.status != "failed": + observed = safety.output.get("behavioral_evidence") == "observed" + evidence_mod.set_node( + graph, "SafetyConsequence", + "OBSERVED" if observed else "UNAVAILABLE", + safety.output.get("assessment", ""), + {"behavioral_evidence": safety.output.get("behavioral_evidence"), + "classification": safety.output.get("behavioral_classification"), + "worst_case": safety.output.get("worst_case"), + "chain": safety.output.get("chain")}, + "safety impact agent (replay evidence via safety.ssam_ext)") + if observed: + evidence_mod.set_node( + graph, "Planner", "OBSERVED", + f"replayed {safety.output.get('replayed_instances')} " + "planner-response trace(s)", + {"replays": safety.output.get("replays", [])}, + "safety impact agent (safety.ssam_ext replay)") + # VLM hypotheses attach to Environment as clearly-labeled hypotheses + env = graph.node("Environment") + if env is not None and vlm.status == "ok": + env.fields["scene_hypotheses"] = vlm.output.get("hypotheses", []) + env.caveats.append("scene_hypotheses are HYPOTHESIS-status agent " + "conjectures, not observations") + store_mod.write_json(graph, "evidence", f"{failure.failure_id}.json") + + failure.status = "investigating" + save_failure(failure) + _transition(state, "FAILURE_ANALYSIS", "complete", + detail=f"5 analysis agents ran; fusion=" + f"{fusion.output.get('overall_verdict')}") + + +# ------------------------------------------------------------------ layer 4 + + +def evidence_confidence(state: PipelineState) -> str: + s = state.statistical + if s is None: + return "INSUFFICIENT_EVIDENCE" + if s.significant and not s.small_sample_flags: + return "CONFIRMED" + if s.significant: + return "LIKELY" + if s.candidate.events > 0: + return "POSSIBLE" + return "INSUFFICIENT_EVIDENCE" + + +def build_policy_input(failure: FailureEvent, state: PipelineState, + overrides: Optional[Dict] = None) -> policy_mod.PolicyInput: + """Deterministic mapping from pipeline artifacts to the policy input.""" + safety = state.agent_results.get("safety_impact") + fusion = state.agent_results.get("sensor_fusion_verification") + mining = state.agent_results.get("scenario_mining") + + behavioral = "none" + contained = False + downstream = "uncertain" + if safety is not None and safety.status != "failed": + ev = safety.output.get("behavioral_evidence") + if ev == "observed": + cls = safety.output.get("behavioral_classification") + behavioral = cls or "observed_contained" + contained = cls == "observed_contained" + downstream = ("observed_critical" if cls == "observed_unsafe" + else "observed_degraded") + else: + behavioral, downstream = "none", "uncertain" + + stat = state.statistical + conc = state.concentration + concentrated_dim = (conc.concentrated_dimensions[0] + if conc and conc.concentrated_dimensions else None) + resid_outside = None + excl_share = None + if conc is not None and concentrated_dim == "construction_zone": + row_out = next((s for s in conc.strata + if s.stratum == "non_construction"), None) + row_in = next((s for s in conc.strata + if s.stratum == "construction"), None) + if row_out is not None: + resid_outside = row_out.stratum_rate + if row_in is not None: + excl_share = row_in.exposure_share + + agent_failures = [r.agent for r in state.agent_results.values() + if r.status == "failed"] + + kwargs = dict( + failure_id=failure.failure_id, + safety_critical_class=(failure.gt_class in SAFETY_CRITICAL + if failure.gt_class else False), + collision_observed=False, + behavioral_evidence=behavioral, + downstream_contained=contained, + functional_impact=True, + rate=stat.candidate.rate if stat else None, + rate_ci=stat.candidate.wilson_ci if stat else None, + denominator=stat.candidate.denominator if stat + else failure.detection_basis.denominator, + significant=stat.significant if stat else False, + small_sample=bool(stat.small_sample_flags) if stat else True, + exposure_share=excl_share, + novelty=(mining.output.get("novelty", "unknown") + if mining is not None and mining.status == "ok" else "unknown"), + evidence_confidence=evidence_confidence(state), + downstream_consequence=downstream, + gt_available=True, + lineage_complete=bool(failure.dataset_fingerprint + and failure.candidate_model + and failure.baseline_model), + telemetry_available=failure.detection_basis.denominator > 0, + fusion_verdict=(fusion.output.get("overall_verdict", + "verification_failed") + if fusion is not None and fusion.status != "failed" + else "verification_failed"), + agent_conflict=bool(agent_failures), + conflict_details=[f"agent {a} failed" for a in agent_failures], + gate_violated=False, + mitigation_validated=False, + concentration_dimension=concentrated_dim, + concentrated=bool(conc and conc.determination == "concentrated"), + odd_detector_recall=None, # REQUIRED-EVIDENCE: no zone detector measured + odd_exclusion_share=excl_share, + residual_rate_outside_odd=resid_outside, + ) + kwargs.update(overrides or {}) + return policy_mod.PolicyInput(**kwargs) + + +def run_launch_decision(failure: FailureEvent, state: PipelineState, + seed: int, use_llm: bool = False, + policy_input_overrides: Optional[Dict] = None) -> Dict: + _transition(state, "LAUNCH_DECISION", "running") + pol_input = build_policy_input(failure, state, policy_input_overrides) + evaluation = policy_mod.evaluate(pol_input) + state.policy_evaluation = evaluation + + narrative = LaunchDecisionAgent(use_llm=use_llm).run( + failure.failure_id, failure=failure, policy_evaluation=evaluation) + _record_agent(state, narrative) + + card = scorecard_mod.build_scorecard( + failure, state.statistical, state.concentration, evaluation, + state.agent_results) + state.scorecard_id = card.scorecard_id + + triggers = review_mod.mandatory_review_triggers( + evaluation, pol_input.fusion_verdict, pol_input.gt_available, + pol_input.small_sample, pol_input.behavioral_evidence) + evaluation["mandatory_review_triggers"] = triggers + evaluation["human_review_required"] = any(t["fired"] for t in triggers) + + failure.severity = evaluation.get("severity") + failure.policy_outcome = evaluation.get("outcome") + failure.status = "decided" + save_failure(failure) + _transition(state, "LAUNCH_DECISION", "complete", + detail=f"{evaluation['outcome']} -> " + f"{evaluation['recommended_option']} " + f"(policy {evaluation['policy_version']})") + return evaluation + + +# ------------------------------------------------------------------ layer 5 + + +def run_learning_flywheel(failure: FailureEvent, state: PipelineState, + use_llm: bool = False) -> Dict: + _transition(state, "LEARNING_FLYWHEEL", "running") + agent = EvalFlywheelAgent(use_llm=use_llm) + result = agent.run(failure.failure_id, failure=failure, + concentration=state.concentration) + _record_agent(state, result) + if result.output.get("proposal") is None: + _transition(state, "LEARNING_FLYWHEEL", "blocked", + detail="failure not human-validated; flywheel refused") + return {"created": False, "reason": result.output.get("reason")} + suite = flywheel_mod.create_or_update_suite(failure, result.output["proposal"]) + state.suite_ids.append(suite.suite_id) + _transition(state, "LEARNING_FLYWHEEL", "complete", + detail=f"suite {suite.name} v{suite.version} " + f"({len(suite.members)} members)") + return {"created": True, "suite_id": suite.suite_id, + "suite_name": suite.name, "version": suite.version, + "members": len(suite.members)} + + +# ------------------------------------------------------------------ dispatcher + + +STAGE_ORDER = {s: i for i, s in enumerate(STAGES)} + + +def run_stage(failure_id: str, stage: Optional[str] = None, + seed: int = data_mod.DEFAULT_SEED, use_llm: bool = False, + policy_input_overrides: Optional[Dict] = None) -> PipelineState: + """Run one stage (the next pending one when stage is None).""" + failure = get_failure(failure_id) + state = get_state(failure_id) + if failure is None or state is None: + raise KeyError(f"Unknown failure {failure_id}") + + if stage is None: + pending = [s.stage for s in state.stages if s.status == "pending"] + if not pending: + return state + stage = pending[0] + if stage not in STAGE_ORDER: + raise ValueError(f"Unknown stage {stage}") + for prior in state.stages: + if STAGE_ORDER[prior.stage] < STAGE_ORDER[stage] \ + and prior.status not in ("complete", "blocked"): + raise ValueError(f"stage {stage} requires {prior.stage} to be " + f"complete (currently {prior.status})") + + if stage == "EVIDENCE_AGGREGATION": + run_evidence_aggregation(failure, state, seed) + elif stage == "FAILURE_ANALYSIS": + run_failure_analysis(failure, state, seed, use_llm) + elif stage == "LAUNCH_DECISION": + run_launch_decision(failure, state, seed, use_llm, + policy_input_overrides) + elif stage == "LEARNING_FLYWHEEL": + run_learning_flywheel(failure, state, use_llm) + elif stage == "FAILURE_DETECTION": + pass # detection happens at detect_failures(); already complete + return get_state(failure_id) or state diff --git a/sensorflow/agentic/policy.py b/sensorflow/agentic/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..231cdbf67a0e1df2fb0a46446821985250b11020 --- /dev/null +++ b/sensorflow/agentic/policy.py @@ -0,0 +1,597 @@ +"""Deterministic, hash-versioned stop-ship policy engine. + +This module is the launch authority. It is pure deterministic code: no LLM +output enters it, and its inputs are typed measurements/verdicts produced by +deterministic services (plus clearly-tagged agent hypotheses, which the +engine treats only as *escalation* signals, never as evidence of safety). + +Semantics +--------- +* Policies are JSON documents persisted under runs/agentic/policies/ and + addressed by the SHA-256 of their canonical serialization. Editing a policy + produces a new version; evaluations record the exact version they used. +* Outcomes are four-way (AUTOMATIC_STOP_SHIP / LAUNCH_REVIEW_REQUIRED / + CONTINUE_INVESTIGATION / NO_LAUNCH_IMPACT) plus the INDETERMINATE + fail-safe. INDETERMINATE fires whenever required evidence is missing + (ground truth, lineage, policy version, telemetry denominator), sensor + fusion verification failed, or agents conflict — and is NEVER a pass; it + forces human escalation. +* AUTOMATIC_STOP_SHIP fires only on pre-authorized conditions written in the + policy document; nothing else can trigger it. +* The option-selection matrix is evaluated top-down; the first row whose + condition holds selects the recommended option. Expected loss is computed + for every option for transparency, but SAFETY CONSTRAINTS ARE HARD + CONSTRAINTS: infeasible (unsafe) options are excluded from selection no + matter how cheap they are — business optimization happens only inside the + safe feasible region. + +All numeric thresholds in DEFAULT_POLICY are EXAMPLE PLACEHOLDERS (flagged +`placeholder_values: true`); a real deployment must set organization-approved +values through the versioned policy API. +""" + +from __future__ import annotations + +import hashlib +import json +from typing import Any, Dict, List, Optional + +from pydantic import BaseModel, Field + +from sensorflow.agentic import store as store_mod +from sensorflow.agentic.models import now_iso + +SEVERITY_ORDER = ["S0", "S1", "S2", "S3", "S4", "S5"] +CONFIDENCE_ORDER = ["INSUFFICIENT_EVIDENCE", "POSSIBLE", "LIKELY", "CONFIRMED"] + +# Concentration dimension -> ODD taxonomy dimension used for the +# "reliably detectable" check in Option C (see sensorflow.safety.odd.taxonomy). +ODD_DIMENSION_MAP = { + "construction_zone": "scenario", # proxy: construction handled as a scenario/dynamic element + "lighting": "lighting", + "geo_bucket": "geography", # declared but NOT instrumented in the taxonomy +} + +DEFAULT_POLICY: Dict[str, Any] = { + "policy_name": "example-stop-ship-policy", + "policy_semver": "1.0.0", + "placeholder_values": True, + "note": ("ALL numeric thresholds below are EXAMPLE PLACEHOLDERS shipped " + "for demonstration; they are not invented safety claims and must " + "be replaced with organization-approved values."), + "severity_taxonomy": { + "S0": "No functional impact (cosmetic / logging only).", + "S1": "Functional degradation with no safety relevance.", + "S2": "Perception error on a non-safety-critical object, or a " + "safety-critical class error that is fully contained downstream.", + "S3": "Perception error on a safety-critical class (VRU) with " + "uncertain or degraded downstream behavior.", + "S4": "Observed unsafe downstream behavior (hard braking / evasive " + "action / failure to yield) attributable to the error.", + "S5": "Observed collision or imminent-collision behavior " + "attributable to the error.", + }, + # Ordered, exact criteria: the first matching rule assigns the severity. + "severity_rules": [ + {"severity": "S5", "when": {"collision_observed": True}}, + {"severity": "S4", "when": {"safety_critical_class": True, + "behavioral_evidence": "observed_unsafe"}}, + {"severity": "S3", "when": {"safety_critical_class": True, + "downstream_contained": False}}, + {"severity": "S2", "when": {"safety_critical_class": True, + "downstream_contained": True}}, + {"severity": "S1", "when": {"functional_impact": True}}, + {"severity": "S0", "when": {}}, + ], + # Pre-authorized automatic stop-ship conditions. ONLY these can fire + # AUTOMATIC_STOP_SHIP. + "automatic_stop_ship": [ + {"condition_id": "ASS-1", + "description": "Confirmed S4+ regression at statistically significant " + "frequency", + "min_severity": "S4", "min_confidence": "CONFIRMED", + "requires_significant": True}, + {"condition_id": "ASS-2", + "description": "Confirmed S3+ novel regression with frequency lower " + "bound above the example ceiling", + "min_severity": "S3", "min_confidence": "CONFIRMED", + "requires_significant": True, "requires_novel": True, + "min_rate_lower_bound": 1.0e-4}, + ], + # Four-way outcome rules over Severity x Exposure x Frequency x + # Confidence x Novelty x DownstreamConsequence (evaluated after the + # stop-ship conditions; first match wins). + "outcome_rules": [ + {"rule_id": "OR-1", "outcome": "LAUNCH_REVIEW_REQUIRED", + "description": "significant S3+ regression", + "min_severity": "S3", "requires_significant": True, + "min_confidence": "LIKELY"}, + {"rule_id": "OR-2", "outcome": "LAUNCH_REVIEW_REQUIRED", + "description": "novel safety-critical pattern with uncertain " + "downstream consequence", + "min_severity": "S3", "requires_novel": True, + "downstream_in": ["uncertain", "observed_degraded", + "observed_critical"]}, + {"rule_id": "OR-3", "outcome": "CONTINUE_INVESTIGATION", + "description": "possible regression, evidence not yet sufficient", + "min_severity": "S2", "max_confidence": "POSSIBLE"}, + {"rule_id": "OR-4", "outcome": "CONTINUE_INVESTIGATION", + "description": "significant but low-severity change", + "min_severity": "S1", "requires_significant": True}, + {"rule_id": "OR-5", "outcome": "NO_LAUNCH_IMPACT", + "description": "not significant, not novel, no safety relevance", + "max_severity": "S1"}, + ], + # Option selection matrix — all seven rows, evaluated top-down. + "option_matrix": [ + {"row": 1, "condition": "GATE_VIOLATED", "option": "STOP_SHIP", + "description": "a release gate or pre-authorized stop-ship condition fired"}, + {"row": 2, "condition": "HIGH_CONFIDENCE_UNCONTAINED_CRITICAL", + "option": "OPTION_A_DELAY", + "description": "confirmed/likely S3+ failure with no validated " + "containment: delay launch until fixed"}, + {"row": 3, "condition": "VALIDATED_MITIGATION", + "option": "OPTION_B_MITIGATION", + "description": "a validated mitigation exists: ship with mitigation"}, + {"row": 4, "condition": "RELIABLY_DETECTABLE_ODD_CONCENTRATION", + "option": "OPTION_C_REDUCED_ODD", + "description": "failure concentrates in an ODD region that is " + "reliably detectable at runtime: ship with reduced ODD"}, + {"row": 5, "condition": "INSUFFICIENT_EVIDENCE", + "option": "EXPAND_EVALUATION", + "description": "evidence insufficient for any launch claim"}, + {"row": 6, "condition": "AGENT_OR_MODALITY_CONFLICT", + "option": "HUMAN_SAFETY_REVIEW", + "description": "agents or sensor modalities conflict"}, + {"row": 7, "condition": "NO_SAFETY_IMPACT", "option": "PROCEED", + "description": "no material safety impact established"}, + ], + # Option C parameters (EXAMPLE placeholders; never invented at runtime). + "option_c": { + "MAX_ACCEPTABLE_FAILURE_PROBABILITY": 1.0e-5, + "MIN_REQUIRED_SAFETY_RECALL": 0.995, + "MAX_ACCEPTABLE_RESIDUAL_RISK": 5.0e-5, + "MIN_REQUIRED_EVIDENCE_CONFIDENCE": "LIKELY", + "MAX_ALLOWED_ODD_EXCLUSION": 0.20, + "placeholder_values": True, + }, + # Expected-loss model (EXAMPLE placeholder unit costs). + "expected_loss": { + "unit": "abstract cost units (example placeholders)", + "delay_cost": 100.0, + "mitigation_cost": 40.0, + "odd_reduction_cost_per_exposure_share": 300.0, + "expand_evaluation_cost": 25.0, + "incident_cost": 2_000_000.0, + "exposure_events_per_release": 1_000_000, + "mitigation_effectiveness": 0.9, + }, + # Hard safety constraint applied to option feasibility. + "hard_constraints": { + "MAX_ACCEPTABLE_RESIDUAL_RISK": 5.0e-5, + "applies_from_severity": "S3", + "note": "options whose residual failure rate exceeds this are " + "infeasible regardless of expected loss", + }, +} + + +# ------------------------------------------------------------------ versioning + + +def policy_hash(doc: Dict) -> str: + blob = json.dumps({k: v for k, v in doc.items() + if k not in ("policy_version", "created_at")}, + sort_keys=True, default=str) + return hashlib.sha256(blob.encode()).hexdigest()[:16] + + +def save_policy(doc: Dict, actor: str = "system") -> Dict: + doc = dict(doc) + version = policy_hash(doc) + doc["policy_version"] = version + doc["created_at"] = doc.get("created_at") or now_iso() + store_mod.write_json(doc, "policies", f"{version}.json") + store_mod.write_json({"active": version}, "policies", "_active.json") + store_mod.audit("policy_saved", None, actor, + detail=f"policy {doc.get('policy_name')} version {version}") + return doc + + +def get_policy(version: Optional[str] = None) -> Dict: + if version: + doc = store_mod.read_json("policies", f"{version}.json") + if doc is None: + raise KeyError(f"Unknown policy version {version}") + return doc + active = store_mod.read_json("policies", "_active.json") + if active and active.get("active"): + doc = store_mod.read_json("policies", f"{active['active']}.json") + if doc is not None: + return doc + return save_policy(DEFAULT_POLICY) + + +def list_policies() -> List[Dict]: + out = [] + for name in store_mod.list_dir("policies"): + if name.startswith("_") or not name.endswith(".json"): + continue + doc = store_mod.read_json("policies", name) + if doc: + out.append({"policy_version": doc.get("policy_version"), + "policy_name": doc.get("policy_name"), + "policy_semver": doc.get("policy_semver"), + "placeholder_values": doc.get("placeholder_values"), + "created_at": doc.get("created_at")}) + return out + + +# ------------------------------------------------------------------ input schema + + +class PolicyInput(BaseModel): + """Typed, deterministic inputs for a policy evaluation.""" + + failure_id: str + # severity inputs + safety_critical_class: bool = False + collision_observed: bool = False + behavioral_evidence: str = "none" # observed_unsafe|observed_contained|uncertain|none + downstream_contained: bool = False + functional_impact: bool = True + # frequency / statistics (deterministic, from the statistical agent) + rate: Optional[float] = None + rate_ci: Optional[List[float]] = None + denominator: Optional[int] = None + significant: bool = False + small_sample: bool = False + # exposure / novelty / confidence + exposure_share: Optional[float] = None + novelty: str = "unknown" # novel|known_regression|known_stable|unknown + evidence_confidence: str = "INSUFFICIENT_EVIDENCE" + downstream_consequence: str = "uncertain" + # integrity signals + gt_available: bool = True + lineage_complete: bool = True + telemetry_available: bool = True + fusion_verdict: str = "multi_modal_supported" + agent_conflict: bool = False + conflict_details: List[str] = Field(default_factory=list) + # gates + mitigation + ODD concentration + gate_violated: bool = False + violated_gates: List[str] = Field(default_factory=list) + mitigation_validated: bool = False + mitigation_description: str = "" + concentration_dimension: Optional[str] = None + concentrated: bool = False + odd_detector_recall: Optional[float] = None + odd_exclusion_share: Optional[float] = None + residual_rate_outside_odd: Optional[float] = None + + +# ------------------------------------------------------------------ helpers + + +def _sev_ge(a: str, b: str) -> bool: + return SEVERITY_ORDER.index(a) >= SEVERITY_ORDER.index(b) + + +def _conf_ge(a: str, b: str) -> bool: + return CONFIDENCE_ORDER.index(a) >= CONFIDENCE_ORDER.index(b) + + +def assign_severity(policy: Dict, inp: PolicyInput) -> Dict: + """Deterministic severity from the policy's ordered exact criteria.""" + facts = { + "collision_observed": inp.collision_observed, + "safety_critical_class": inp.safety_critical_class, + "behavioral_evidence": inp.behavioral_evidence, + "downstream_contained": inp.downstream_contained, + "functional_impact": inp.functional_impact, + } + for rule in policy["severity_rules"]: + if all(facts.get(k) == v for k, v in rule["when"].items()): + return {"severity": rule["severity"], "matched_rule": rule, + "facts": facts, + "taxonomy_description": policy["severity_taxonomy"][rule["severity"]]} + return {"severity": "S0", "matched_rule": None, "facts": facts, + "taxonomy_description": policy["severity_taxonomy"]["S0"]} + + +def _odd_instrumented(dimension: Optional[str]) -> Dict: + """Reliably-detectable check against the safety ODD taxonomy's + instrumented dimensions (sensorflow.safety.odd).""" + if dimension is None: + return {"dimension": None, "odd_dimension": None, "instrumented": False, + "reason": "no concentration dimension supplied"} + odd_dim = ODD_DIMENSION_MAP.get(dimension, dimension) + try: + from sensorflow.safety.odd import taxonomy + dims = taxonomy()["dimensions"] + entry = dims.get(odd_dim) + instrumented = bool(entry and entry.get("instrumented")) + reason = (f"ODD taxonomy dimension '{odd_dim}' instrumented=" + f"{instrumented}") + except Exception as e: # taxonomy unavailable -> fail safe (not detectable) + instrumented = False + reason = f"ODD taxonomy unavailable ({e}); failing safe" + return {"dimension": dimension, "odd_dimension": odd_dim, + "instrumented": instrumented, "reason": reason, + "mapping_note": ("construction_zone is proxied to the 'scenario' " + "taxonomy dimension" if dimension == "construction_zone" else None)} + + +def evaluate_option_c(policy: Dict, inp: PolicyInput) -> Dict: + """Option C (reduced ODD) feasibility from config parameters only.""" + cfg = policy["option_c"] + checks = [] + + odd = _odd_instrumented(inp.concentration_dimension) + checks.append({"check": "odd_dimension_instrumented", + "actual": odd["instrumented"], "required": True, + "passed": odd["instrumented"], "detail": odd["reason"]}) + checks.append({"check": "concentrated", "actual": inp.concentrated, + "required": True, "passed": inp.concentrated}) + + recall = inp.odd_detector_recall + checks.append({ + "check": "MIN_REQUIRED_SAFETY_RECALL", + "actual": recall, "required": cfg["MIN_REQUIRED_SAFETY_RECALL"], + "passed": recall is not None and recall >= cfg["MIN_REQUIRED_SAFETY_RECALL"]}) + + resid = inp.residual_rate_outside_odd + checks.append({ + "check": "MAX_ACCEPTABLE_RESIDUAL_RISK", + "actual": resid, "required": cfg["MAX_ACCEPTABLE_RESIDUAL_RISK"], + "passed": resid is not None and resid <= cfg["MAX_ACCEPTABLE_RESIDUAL_RISK"]}) + + checks.append({ + "check": "MIN_REQUIRED_EVIDENCE_CONFIDENCE", + "actual": inp.evidence_confidence, + "required": cfg["MIN_REQUIRED_EVIDENCE_CONFIDENCE"], + "passed": _conf_ge(inp.evidence_confidence, + cfg["MIN_REQUIRED_EVIDENCE_CONFIDENCE"])}) + + excl = inp.odd_exclusion_share + checks.append({ + "check": "MAX_ALLOWED_ODD_EXCLUSION", + "actual": excl, "required": cfg["MAX_ALLOWED_ODD_EXCLUSION"], + "passed": excl is not None and excl <= cfg["MAX_ALLOWED_ODD_EXCLUSION"]}) + + rate_in = inp.rate + checks.append({ + "check": "MAX_ACCEPTABLE_FAILURE_PROBABILITY (post-exclusion)", + "actual": resid, "required": cfg["MAX_ACCEPTABLE_FAILURE_PROBABILITY"], + "passed": resid is not None and resid <= cfg["MAX_ACCEPTABLE_FAILURE_PROBABILITY"], + "detail": f"in-ODD rate before exclusion: {rate_in}"}) + + return {"feasible": all(c["passed"] for c in checks), "checks": checks, + "config": cfg, "odd_taxonomy_check": odd} + + +# ------------------------------------------------------------------ expected loss + + +def expected_loss_table(policy: Dict, inp: PolicyInput, severity: str) -> List[Dict]: + cfg = policy["expected_loss"] + hard = policy["hard_constraints"] + rate = inp.rate or 0.0 + resid_c = inp.residual_rate_outside_odd if inp.residual_rate_outside_odd is not None else rate + excl = inp.odd_exclusion_share or 0.0 + eff = cfg["mitigation_effectiveness"] if inp.mitigation_validated else 0.0 + exposure = cfg["exposure_events_per_release"] + safety_scoped = _sev_ge(severity, hard["applies_from_severity"]) + max_resid = hard["MAX_ACCEPTABLE_RESIDUAL_RISK"] + + rows = [] + for option, business, residual_rate in [ + ("STOP_SHIP", cfg["delay_cost"], 0.0), + ("OPTION_A_DELAY", cfg["delay_cost"], 0.0), + ("OPTION_B_MITIGATION", cfg["mitigation_cost"], rate * (1.0 - eff)), + ("OPTION_C_REDUCED_ODD", + cfg["odd_reduction_cost_per_exposure_share"] * excl, resid_c), + ("EXPAND_EVALUATION", cfg["expand_evaluation_cost"], rate), + ("HUMAN_SAFETY_REVIEW", cfg["expand_evaluation_cost"], rate), + ("PROCEED", 0.0, rate), + ]: + risk_cost = residual_rate * exposure * cfg["incident_cost"] / max(exposure, 1) + # normalized: expected incidents per release * incident cost + expected_incidents = residual_rate * exposure + total = business + expected_incidents * cfg["incident_cost"] / 1000.0 + feasible = (not safety_scoped) or (residual_rate <= max_resid) + rows.append({ + "option": option, + "business_cost": round(business, 2), + "residual_failure_rate": residual_rate, + "expected_incidents_per_release": round(expected_incidents, 4), + "expected_loss": round(total, 2), + "risk_cost_component": round(risk_cost, 6), + "feasible": feasible, + "infeasible_reason": (None if feasible else + f"residual rate {residual_rate:.2e} exceeds hard " + f"constraint {max_resid:.2e} at severity {severity}"), + }) + return rows + + +# ------------------------------------------------------------------ evaluation + + +def _integrity_failures(inp: PolicyInput) -> List[str]: + problems = [] + if not inp.gt_available: + problems.append("ground truth unavailable or disputed") + if not inp.lineage_complete: + problems.append("lineage (model/dataset fingerprints) incomplete") + if not inp.telemetry_available or not inp.denominator: + problems.append("telemetry denominator unavailable — no valid rate claim") + if inp.fusion_verdict == "verification_failed": + problems.append("sensor fusion verification failed") + if inp.agent_conflict: + problems.append("agents produced conflicting verdicts: " + + "; ".join(inp.conflict_details or ["unspecified"])) + return problems + + +def _matrix_condition_holds(condition: str, inp: PolicyInput, severity: str, + option_c: Dict, stop_ship_fired: bool) -> bool: + if condition == "GATE_VIOLATED": + return inp.gate_violated or stop_ship_fired + if condition == "HIGH_CONFIDENCE_UNCONTAINED_CRITICAL": + return (_sev_ge(severity, "S3") + and _conf_ge(inp.evidence_confidence, "LIKELY") + and not inp.downstream_contained + and not inp.mitigation_validated) + if condition == "VALIDATED_MITIGATION": + return inp.mitigation_validated + if condition == "RELIABLY_DETECTABLE_ODD_CONCENTRATION": + return option_c["feasible"] + if condition == "INSUFFICIENT_EVIDENCE": + return (inp.evidence_confidence == "INSUFFICIENT_EVIDENCE" + or inp.small_sample) + if condition == "AGENT_OR_MODALITY_CONFLICT": + return inp.agent_conflict or inp.fusion_verdict == "modality_conflict" + if condition == "NO_SAFETY_IMPACT": + return True + return False + + +def _outcome_rule_matches(rule: Dict, inp: PolicyInput, severity: str) -> bool: + if "min_severity" in rule and not _sev_ge(severity, rule["min_severity"]): + return False + if "max_severity" in rule and _sev_ge(severity, rule["max_severity"]) \ + and severity != rule["max_severity"]: + return False + if rule.get("requires_significant") and not inp.significant: + return False + if rule.get("requires_novel") and inp.novelty != "novel": + return False + if "min_confidence" in rule and not _conf_ge(inp.evidence_confidence, + rule["min_confidence"]): + return False + if "max_confidence" in rule and _conf_ge(inp.evidence_confidence, + rule["max_confidence"]) \ + and inp.evidence_confidence != rule["max_confidence"]: + return False + if "downstream_in" in rule and inp.downstream_consequence not in rule["downstream_in"]: + return False + return True + + +def _stop_ship_condition_matches(cond: Dict, inp: PolicyInput, severity: str) -> bool: + if "min_severity" in cond and not _sev_ge(severity, cond["min_severity"]): + return False + if "min_confidence" in cond and not _conf_ge(inp.evidence_confidence, + cond["min_confidence"]): + return False + if cond.get("requires_significant") and not inp.significant: + return False + if cond.get("requires_novel") and inp.novelty != "novel": + return False + if "min_rate_lower_bound" in cond: + lb = (inp.rate_ci or [0.0, 0.0])[0] + if lb < cond["min_rate_lower_bound"]: + return False + return True + + +def evaluate(inp: PolicyInput, policy: Optional[Dict] = None, + actor: str = "policy_engine") -> Dict: + """Deterministic policy evaluation. Returns outcome + fired rules + + option selection + expected-loss table, and audits itself.""" + doc = policy or get_policy() + version = doc.get("policy_version") or policy_hash(doc) + + result: Dict[str, Any] = { + "failure_id": inp.failure_id, + "policy_version": version, + "policy_name": doc.get("policy_name"), + "placeholder_values": doc.get("placeholder_values", False), + "evaluated_at": now_iso(), + "input": inp.model_dump(), + "authority": "deterministic policy engine + human approval; agents are advisory", + } + + # 1. INDETERMINATE fail-safe (never a pass). + problems = _integrity_failures(inp) + severity_info = assign_severity(doc, inp) + severity = severity_info["severity"] + result["severity"] = severity + result["severity_assignment"] = severity_info + + if problems: + result.update({ + "outcome": "INDETERMINATE", + "indeterminate_reasons": problems, + "recommended_option": "HUMAN_SAFETY_REVIEW", + "matrix_row_fired": {"row": 6, + "condition": "AGENT_OR_MODALITY_CONFLICT" + if inp.agent_conflict else "INTEGRITY_FAILURE", + "option": "HUMAN_SAFETY_REVIEW"}, + "expected_loss_table": expected_loss_table(doc, inp, severity), + "option_c_evaluation": evaluate_option_c(doc, inp), + "note": "INDETERMINATE is fail-safe: it can never authorize a " + "launch and always escalates to human safety review.", + }) + store_mod.audit("policy_evaluated", inp.failure_id, actor, + detail=f"INDETERMINATE ({'; '.join(problems)})", + payload={"policy_version": version}) + return result + + # 2. Pre-authorized automatic stop-ship conditions. + fired_stop = None + for cond in doc["automatic_stop_ship"]: + if _stop_ship_condition_matches(cond, inp, severity): + fired_stop = cond + break + + # 3. Four-way outcome. + if fired_stop: + outcome = "AUTOMATIC_STOP_SHIP" + fired_rule = fired_stop + else: + outcome, fired_rule = "CONTINUE_INVESTIGATION", None + for rule in doc["outcome_rules"]: + if _outcome_rule_matches(rule, inp, severity): + outcome, fired_rule = rule["outcome"], rule + break + + # 4. Option matrix + hard-constrained expected loss. + option_c = evaluate_option_c(doc, inp) + loss_table = expected_loss_table(doc, inp, severity) + feasible = {r["option"] for r in loss_table if r["feasible"]} + + matrix_row = None + for row in doc["option_matrix"]: + if not _matrix_condition_holds(row["condition"], inp, severity, + option_c, fired_stop is not None): + continue + if row["option"] in ("STOP_SHIP", "OPTION_A_DELAY", "EXPAND_EVALUATION", + "HUMAN_SAFETY_REVIEW") or row["option"] in feasible: + matrix_row = row + break + # matched but infeasible under the hard safety constraint -> next row + if matrix_row is None: + matrix_row = {"row": 6, "condition": "AGENT_OR_MODALITY_CONFLICT", + "option": "HUMAN_SAFETY_REVIEW", + "description": "no feasible matrix row — fail safe"} + + result.update({ + "outcome": outcome, + "outcome_rule_fired": fired_rule, + "automatic_stop_ship_condition": fired_stop, + "recommended_option": matrix_row["option"], + "matrix_row_fired": matrix_row, + "option_c_evaluation": option_c, + "expected_loss_table": loss_table, + "hard_constraint": doc["hard_constraints"], + "note": ("expected loss is reported for every option, but options " + "violating the hard safety constraint were excluded from " + "selection regardless of cost"), + }) + store_mod.audit("policy_evaluated", inp.failure_id, actor, + detail=f"{outcome} -> {matrix_row['option']} " + f"(policy {version})", + payload={"policy_version": version, "severity": severity}) + return result diff --git a/sensorflow/agentic/review.py b/sensorflow/agentic/review.py new file mode 100644 index 0000000000000000000000000000000000000000..b086971b429a544f28a4e45cb9af8e93951d751e --- /dev/null +++ b/sensorflow/agentic/review.py @@ -0,0 +1,84 @@ +"""Human review + governance. + +Mandatory-review triggers (per spec): S3+ severity, disputed ground truth, +modality disagreement, statistically insufficient evidence, ODD reduction, +behavior-affecting changes, stop-ship outcomes, policy conflicts. + +HumanReviewDecision records are append-only (JSONL per failure) and every +decision is audited. A failure only becomes `validated` through an explicit +`confirm_failure` decision — agents cannot validate their own findings. +""" + +from __future__ import annotations + +from typing import Dict, List, Optional + +from sensorflow.agentic import store as store_mod +from sensorflow.agentic.models import (FailureEvent, HumanReviewDecision, + new_id) + +MANDATORY_TRIGGER_RULES = [ + ("severity_s3_plus", "severity S3 or higher"), + ("disputed_ground_truth", "ground truth disputed or unavailable"), + ("modality_disagreement", "sensor modality disagreement"), + ("insufficient_statistics", "statistically insufficient evidence"), + ("odd_reduction_proposed", "ODD reduction (Option C) proposed"), + ("behavior_change", "change affects vehicle behavior"), + ("stop_ship", "stop-ship outcome"), + ("policy_conflict", "conflicting policy/agent verdicts"), +] + + +def mandatory_review_triggers(policy_evaluation: Optional[Dict], + fusion_verdict: Optional[str], + gt_available: bool, + small_sample: bool, + behavioral_evidence: str) -> List[Dict]: + """Deterministic evaluation of every mandatory-review trigger.""" + pol = policy_evaluation or {} + severity = pol.get("severity") or "S0" + outcome = pol.get("outcome") + option = pol.get("recommended_option") + fired = { + "severity_s3_plus": severity in ("S3", "S4", "S5"), + "disputed_ground_truth": not gt_available, + "modality_disagreement": fusion_verdict == "modality_conflict", + "insufficient_statistics": small_sample, + "odd_reduction_proposed": option == "OPTION_C_REDUCED_ODD", + "behavior_change": behavioral_evidence in ("observed_unsafe", + "observed_contained"), + "stop_ship": outcome == "AUTOMATIC_STOP_SHIP" or option == "STOP_SHIP", + "policy_conflict": outcome == "INDETERMINATE", + } + return [{"trigger": key, "description": desc, "fired": fired[key]} + for key, desc in MANDATORY_TRIGGER_RULES] + + +def record_decision(failure: FailureEvent, reviewer: str, decision: str, + rationale: str, evidence_reviewed: List[str], + policy_version: str, + approved_option: Optional[str] = None, + override_reason: Optional[str] = None) -> HumanReviewDecision: + rec = HumanReviewDecision( + review_id=new_id("rev"), + failure_id=failure.failure_id, + reviewer=reviewer, + decision=decision, + approved_option=approved_option, + evidence_reviewed=evidence_reviewed, + policy_version=policy_version, + rationale=rationale, + override_reason=override_reason, + ) + store_mod.append_jsonl(rec.model_dump(), "reviews", f"{failure.failure_id}.jsonl") + store_mod.audit("human_review_decision", failure.failure_id, reviewer, + detail=f"{decision}" + + (f" (option {approved_option})" if approved_option else ""), + payload={"review_id": rec.review_id, + "policy_version": policy_version, + "override_reason": override_reason}) + return rec + + +def decisions_for(failure_id: str) -> List[Dict]: + return store_mod.read_jsonl("reviews", f"{failure_id}.jsonl") diff --git a/sensorflow/agentic/scorecard.py b/sensorflow/agentic/scorecard.py new file mode 100644 index 0000000000000000000000000000000000000000..e726dc401335d26fa91f989fce1f8694788807f7 --- /dev/null +++ b/sensorflow/agentic/scorecard.py @@ -0,0 +1,151 @@ +"""AgenticSafetyScorecard — leadership-facing retrospective scorecard. + +Every field is a ScorecardField carrying an OBSERVED / PREDICTED / +HYPOTHETICAL / REQUIRED_EVIDENCE tag plus an evidence reference, so a reader +can always tell a measured number from a model's guess (an improvement over a +plain key/value scorecard). +""" + +from __future__ import annotations + +from typing import Dict, Optional + +from sensorflow.agentic import store as store_mod +from sensorflow.agentic.models import (AgenticSafetyScorecard, + ConcentrationAnalysis, FailureEvent, + ScorecardField, StatisticalAssessment, + new_id) + + +def _f(value, tag: str, ref: str = "") -> ScorecardField: + return ScorecardField(value=value, tag=tag, evidence_ref=ref) + + +def build_scorecard(failure: FailureEvent, + statistical: Optional[StatisticalAssessment], + concentration: Optional[ConcentrationAnalysis], + policy_evaluation: Optional[Dict], + agent_results: Dict) -> AgenticSafetyScorecard: + basis = failure.detection_basis + + if statistical is not None: + freq = _f({"rate": statistical.candidate.rate, + "wilson_ci": statistical.candidate.wilson_ci, + "events": statistical.candidate.events, + "denominator": statistical.candidate.denominator, + "baseline_rate": statistical.baseline.rate, + "significant": statistical.significant}, + "OBSERVED", "statistical_assessment") + else: + freq = _f("statistical assessment not yet run", "REQUIRED_EVIDENCE", + "FAILURE_ANALYSIS stage") + + if concentration is not None: + conc = _f({"determination": concentration.determination, + "concentrated_dimensions": concentration.concentrated_dimensions, + "top_strata": [s.model_dump() for s in concentration.strata + if s.relative_risk and s.relative_risk >= 3.0][:3]}, + "OBSERVED", "concentration_analysis") + else: + conc = _f("concentration analysis not yet run", "REQUIRED_EVIDENCE", + "FAILURE_ANALYSIS stage") + + # "escalated" is a successful analysis that requests human review (e.g. + # unsafe replay behavior) — only "failed" means the evidence is missing. + safety = agent_results.get("safety_impact") + if safety is not None and safety.status in ("ok", "escalated"): + chain = safety.output.get("chain", []) + if safety.output.get("behavioral_evidence") == "observed": + downstream = _f(safety.output, "OBSERVED", "safety_impact_agent (replay)") + else: + downstream = _f({"assessment": "safety assessment UNCERTAIN — no " + "behavioral evidence", + "chain": chain}, + "REQUIRED_EVIDENCE", "safety_impact_agent") + else: + downstream = _f("safety impact not assessed", "REQUIRED_EVIDENCE", + "safety_impact_agent") + + mining = agent_results.get("scenario_mining") + novelty_val = (mining.output.get("novelty", "unknown") + if mining is not None and mining.status in ("ok", "escalated") + else "unknown") + + pol = policy_evaluation or {} + severity_field = _f( + {"severity": pol.get("severity"), + "criteria": (pol.get("severity_assignment") or {}).get("taxonomy_description")}, + "OBSERVED" if pol else "REQUIRED_EVIDENCE", + "policy_engine.assign_severity") + + resid = None + for row in pol.get("expected_loss_table", []): + if row["option"] == pol.get("recommended_option"): + resid = row + break + residual = (_f({"option": resid["option"], + "residual_failure_rate": resid["residual_failure_rate"], + "expected_loss": resid["expected_loss"], + "feasible": resid["feasible"]}, + "PREDICTED", "policy_engine.expected_loss_table") + if resid else _f("no policy evaluation yet", "REQUIRED_EVIDENCE", + "LAUNCH_DECISION stage")) + + ec = "INSUFFICIENT_EVIDENCE" + if statistical is not None: + if statistical.significant and not statistical.small_sample_flags: + ec = "CONFIRMED" + elif statistical.significant: + ec = "LIKELY" + elif statistical.candidate.events > 0: + ec = "POSSIBLE" + + card = AgenticSafetyScorecard( + scorecard_id=new_id("card"), + failure_id=failure.failure_id, + title=failure.title, + failure_summary=_f( + {"kind": failure.kind, "gt_class": failure.gt_class, + "predicted_class": failure.predicted_class, + "candidate_model": failure.candidate_model, + "baseline_model": failure.baseline_model, + "instances_captured": len(failure.instances)}, + "OBSERVED", "failure_detection_agent"), + frequency=freq, + exposure=_f({"denominator": basis.denominator, + "population": failure.population_id, + "construction_zone_exposure_share": + next((s.exposure_share for s in + (concentration.strata if concentration else []) + if s.stratum == "construction"), None)}, + "OBSERVED", "rate population telemetry"), + severity=severity_field, + confidence=_f(ec, "OBSERVED", "statistical_assessment quality rules"), + novelty=_f(novelty_val, + "OBSERVED" if novelty_val != "unknown" else "REQUIRED_EVIDENCE", + "scenario_mining_agent (deterministic retrieval)"), + concentration=conc, + downstream_impact=downstream, + mitigations=_f( + {"validated_mitigation": bool((pol.get("input") or {}).get("mitigation_validated")), + "description": (pol.get("input") or {}).get("mitigation_description") or "none"}, + "OBSERVED", "policy input"), + residual_risk=residual, + evidence_quality=ec, + policy_outcome=pol.get("outcome"), + recommended_option=pol.get("recommended_option"), + policy_version=pol.get("policy_version", ""), + notes=[ + "Field tags: OBSERVED = measured on the synthetic campaign; " + "PREDICTED = deterministic model output (e.g. expected loss); " + "HYPOTHETICAL = agent hypothesis; REQUIRED_EVIDENCE = missing.", + ], + ) + store_mod.write_json(card, "scorecards", f"{card.scorecard_id}.json") + store_mod.audit("scorecard_generated", failure.failure_id, "scorecard", + detail=f"scorecard {card.scorecard_id}") + return card + + +def load_scorecard(scorecard_id: str) -> Optional[Dict]: + return store_mod.read_json("scorecards", f"{scorecard_id}.json") diff --git a/sensorflow/agentic/snippets.py b/sensorflow/agentic/snippets.py new file mode 100644 index 0000000000000000000000000000000000000000..16d64f025217c9e8917e89e97dc1426ee3a15361 --- /dev/null +++ b/sensorflow/agentic/snippets.py @@ -0,0 +1,90 @@ +"""Reproducible failure snippet packages. + +A snippet carries everything needed to reproduce and triage one concrete +failure instance: scene/sequence/timestamp, model versions, prediction, GT, +confidence, tracking, planner state, environment, geo bucket, software and +hardware config, feature pipeline version — PLUS temporal context frames +(before / failure / after). Single-frame snippets are never emitted when +temporal context exists in the data, because classification flips are often +transient and the before/after frames are the evidence of that. +""" + +from __future__ import annotations + +from typing import List + +from sensorflow.agentic import data as data_mod +from sensorflow.agentic.models import (FailureEvent, FailureInstance, + FailureSnippet, TemporalFrameRef, new_id) + +TEMPORAL_RADIUS = 2 # frames of context on each side when available + + +def _temporal_context(campaign: data_mod.Campaign, inst: FailureInstance + ) -> List[TemporalFrameRef]: + history = data_mod.observations_for_instance( + campaign, inst.sequence_id, inst.object_instance_id) + refs: List[TemporalFrameRef] = [] + for obs in history: + d = obs.frame_index - inst.frame_index + if abs(d) > TEMPORAL_RADIUS: + continue + role = "failure" if d == 0 else ("before" if d < 0 else "after") + refs.append(TemporalFrameRef( + frame_id=obs.frame_id, frame_index=obs.frame_index, role=role, + gt_class=obs.gt_class, predicted_class=obs.candidate.predicted_class, + confidence=obs.candidate.confidence, bbox_3d=obs.candidate.bbox_3d)) + return refs + + +def build_snippet(failure: FailureEvent, inst: FailureInstance, + campaign: data_mod.Campaign, + similar_historical: List[dict] | None = None) -> FailureSnippet: + history = data_mod.observations_for_instance( + campaign, inst.sequence_id, inst.object_instance_id) + obs = next((o for o in history if o.frame_id == inst.frame_id), None) + if obs is None: + raise KeyError(f"No observation for instance {inst.instance_id}") + + planner_state = ( + {"replay_trace": "available", + "scenario": "crossing (synthetic replay)", + "note": "quantified by the safety-impact agent"} + if inst.has_planner_trace else + {"replay_trace": "unavailable", + "note": "no behavioral evidence exists for this instance"}) + + return FailureSnippet( + snippet_id=new_id("snip"), + failure_id=failure.failure_id, + instance_id=inst.instance_id, + scene_id=inst.sequence_id, + sequence_id=inst.sequence_id, + timestamp_us=obs.timestamp_us, + frame_index=inst.frame_index, + model_version_candidate=failure.candidate_model, + model_version_baseline=failure.baseline_model, + prediction={"class": obs.candidate.predicted_class, + "confidence": obs.candidate.confidence, + "bbox_3d": obs.candidate.bbox_3d, + "track_id": obs.candidate.track_id, + "baseline_class": obs.baseline.predicted_class, + "baseline_confidence": obs.baseline.confidence}, + ground_truth={"class": obs.gt_class, "bbox_3d": obs.gt_bbox_3d, + "source": "synthetic_vendor_gt"}, + confidence=obs.candidate.confidence, + tracking_state={"candidate_track_id": obs.candidate.track_id, + "baseline_track_id": obs.baseline.track_id, + "frames_observed": len(history)}, + planner_state=planner_state, + environment={"time_of_day": inst.time_of_day, "weather": inst.weather, + "construction_zone": inst.construction_zone, + "occluded": inst.occluded, + "distance_m": inst.distance_m}, + geo_bucket=inst.geo_bucket, + software_config=campaign.software_config, + hardware_config=campaign.hardware_config, + feature_pipeline_version=campaign.feature_pipeline_version, + temporal_context=_temporal_context(campaign, inst), + similar_historical=similar_historical or [], + ) diff --git a/sensorflow/agentic/store.py b/sensorflow/agentic/store.py new file mode 100644 index 0000000000000000000000000000000000000000..cd709913d8e3c5b3ce5f00c68c2dc8c8e89b3211 --- /dev/null +++ b/sensorflow/agentic/store.py @@ -0,0 +1,150 @@ +"""Persistence + immutable audit log for the agentic subsystem. + +Layout (relocatable for tests via set_agentic_root): + + runs/agentic/ + failures/{failure_id}.json FailureEvent + pipeline/{failure_id}.json PipelineState + snippets/{failure_id}/{snippet_id}.json + evidence/{failure_id}.json EvidenceGraph + scorecards/{scorecard_id}.json + reviews/{failure_id}.jsonl HumanReviewDecision (append-only) + suites/{suite_id}.json EvaluationSuite + policies/{policy_hash}.json versioned policy documents + audit/{failure_id}.jsonl append-only audit trail + audit/_global.jsonl cross-failure audit trail + +The audit log is append-only by construction: records are only ever appended +to the JSONL files and each record carries a monotonically increasing +`seq` per failure plus a hash chain (`prev_hash` -> `hash`) so tampering or +reordering is detectable. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import threading +from typing import Any, Dict, List, Optional + +from sensorflow.agentic.models import now_iso + +_ROOT = os.path.join("runs", "agentic") +_ROOT_LOCK = threading.Lock() +_AUDIT_LOCK = threading.Lock() + + +def agentic_root() -> str: + return _ROOT + + +def set_agentic_root(path: str) -> None: + """Test hook: relocate all agentic storage.""" + global _ROOT + with _ROOT_LOCK: + _ROOT = str(path) + + +def _path(*parts: str) -> str: + p = os.path.join(agentic_root(), *parts) + os.makedirs(os.path.dirname(p), exist_ok=True) + return p + + +def write_json(obj: Any, *parts: str) -> str: + p = _path(*parts) + payload = obj.model_dump() if hasattr(obj, "model_dump") else obj + tmp = p + ".tmp" + with open(tmp, "w") as f: + json.dump(payload, f, indent=1, default=str) + os.replace(tmp, p) + return p + + +def read_json(*parts: str) -> Optional[Any]: + p = os.path.join(agentic_root(), *parts) + if not os.path.exists(p): + return None + with open(p) as f: + return json.load(f) + + +def list_dir(*parts: str) -> List[str]: + d = os.path.join(agentic_root(), *parts) + if not os.path.isdir(d): + return [] + return sorted(os.listdir(d)) + + +def append_jsonl(record: Dict, *parts: str) -> None: + p = _path(*parts) + with open(p, "a") as f: + f.write(json.dumps(record, default=str) + "\n") + + +def read_jsonl(*parts: str) -> List[Dict]: + p = os.path.join(agentic_root(), *parts) + if not os.path.exists(p): + return [] + out = [] + with open(p) as f: + for line in f: + line = line.strip() + if line: + out.append(json.loads(line)) + return out + + +# ------------------------------------------------------------------ audit + + +def _audit_file(failure_id: Optional[str]) -> str: + name = f"{failure_id}.jsonl" if failure_id else "_global.jsonl" + return os.path.join("audit", name) + + +def audit(event_type: str, failure_id: Optional[str], actor: str, + detail: str = "", payload: Optional[Dict] = None) -> Dict: + """Append one immutable audit record (hash-chained, per-failure seq).""" + with _AUDIT_LOCK: + existing = read_jsonl(_audit_file(failure_id)) + prev_hash = existing[-1]["hash"] if existing else "genesis" + record = { + "seq": len(existing), + "event_type": event_type, + "failure_id": failure_id, + "actor": actor, + "detail": detail, + "payload": payload or {}, + "timestamp": now_iso(), + "prev_hash": prev_hash, + } + blob = json.dumps({k: v for k, v in record.items() if k != "hash"}, + sort_keys=True, default=str) + record["hash"] = hashlib.sha256((prev_hash + blob).encode()).hexdigest()[:16] + append_jsonl(record, _audit_file(failure_id)) + # mirror to the global trail for cross-failure timelines + if failure_id is not None: + with _AUDIT_LOCK: + append_jsonl({**record, "mirrored_from": failure_id}, + _audit_file(None)) + return record + + +def audit_trail(failure_id: str) -> List[Dict]: + return read_jsonl(_audit_file(failure_id)) + + +def verify_audit_chain(failure_id: str) -> Dict: + """Recompute the hash chain; any edit/deletion/reorder breaks it.""" + records = audit_trail(failure_id) + prev = "genesis" + for i, rec in enumerate(records): + blob = json.dumps({k: v for k, v in rec.items() if k != "hash"}, + sort_keys=True, default=str) + expected = hashlib.sha256((prev + blob).encode()).hexdigest()[:16] + if rec.get("seq") != i or rec.get("prev_hash") != prev or rec.get("hash") != expected: + return {"valid": False, "broken_at_seq": i, "records": len(records)} + prev = rec["hash"] + return {"valid": True, "records": len(records)} diff --git a/sensorflow/agentic/worked_example.py b/sensorflow/agentic/worked_example.py new file mode 100644 index 0000000000000000000000000000000000000000..bf33b67f3b416e93eeb3403fd178d3ca2905ff43 --- /dev/null +++ b/sensorflow/agentic/worked_example.py @@ -0,0 +1,189 @@ +"""Worked example: pedestrian -> construction cone at ~0.01%. + +Runs the full five-layer pipeline on the seeded synthetic population, +through evidence aggregation, analysis, the deterministic launch decision, a +recorded (clearly demo-labeled) human review and the learning flywheel, and +assembles a walkthrough where EVERY value is labeled: + + OBSERVED measured on the seeded synthetic run + HYPOTHETICAL an agent hypothesis, unverified + REQUIRED-EVIDENCE evidence that does not exist and would be required + +The walkthrough is deterministic for a fixed seed. +""" + +from __future__ import annotations + +from typing import Dict, Optional + +from sensorflow.agentic import METHODOLOGY_PROVENANCE +from sensorflow.agentic import data as data_mod +from sensorflow.agentic import flywheel as flywheel_mod +from sensorflow.agentic import pipeline as pipeline_mod +from sensorflow.agentic import review as review_mod +from sensorflow.agentic import store as store_mod + +WORKED_EXAMPLE_SEED = data_mod.DEFAULT_SEED +DEMO_REVIEWER = "safety-reviewer-demo" + + +def _find_ped_cone_failure() -> Optional[Dict]: + for doc in pipeline_mod.list_failures(): + if (doc.get("gt_class") == "pedestrian" + and doc.get("predicted_class") == "construction_cone"): + return doc + return None + + +def run_worked_example(seed: int = WORKED_EXAMPLE_SEED, + use_llm: bool = False) -> Dict: + # Layer 1 — detection (idempotent: reuse an existing detection if present) + existing = _find_ped_cone_failure() + if existing is None: + pipeline_mod.detect_failures(seed=seed, use_llm=use_llm) + existing = _find_ped_cone_failure() + if existing is None: + raise RuntimeError("worked example: pedestrian->cone pattern not " + "detected on the seeded population") + fid = existing["failure_id"] + failure = pipeline_mod.get_failure(fid) + state = pipeline_mod.get_state(fid) + + # Layers 2-4 + for stage in ("EVIDENCE_AGGREGATION", "FAILURE_ANALYSIS", "LAUNCH_DECISION"): + if state.stage_record(stage).status == "pending": + state = pipeline_mod.run_stage(fid, stage, seed=seed, use_llm=use_llm) + failure = pipeline_mod.get_failure(fid) + evaluation = state.policy_evaluation or {} + + # Human review (demo decision, clearly labeled as such) + if not failure.validated: + review_mod.record_decision( + failure, reviewer=DEMO_REVIEWER, decision="confirm_failure", + rationale=("DEMO WALKTHROUGH DECISION: replay evidence shows " + "unsafe delayed braking; statistics significant; " + "confirming the failure as real for the worked example"), + evidence_reviewed=["evidence_graph", "statistical_assessment", + "safety_replays", "concentration_analysis"], + policy_version=evaluation.get("policy_version", "")) + failure.validated = True + pipeline_mod.save_failure(failure) + store_mod.audit("failure_validated", fid, DEMO_REVIEWER, + detail="confirm_failure (worked-example demo reviewer)") + + # Layer 5 — flywheel + if state.stage_record("LEARNING_FLYWHEEL").status in ("pending", "blocked"): + state.stage_record("LEARNING_FLYWHEEL").status = "pending" + pipeline_mod.save_state(state) + pipeline_mod.run_stage(fid, "LEARNING_FLYWHEEL", seed=seed, + use_llm=use_llm) + state = pipeline_mod.get_state(fid) + + regression = flywheel_mod.regression_evaluate(seed=seed) + + # ---- assemble the labeled walkthrough ------------------------------ + stat = state.statistical + conc = state.concentration + safety = state.agent_results.get("safety_impact") + fusion = state.agent_results.get("sensor_fusion_verification") + mining = state.agent_results.get("scenario_mining") + vlm = state.agent_results.get("vlm_scene_analysis") + + def L(label: str, value) -> Dict: + return {"label": label, "value": value} + + walkthrough = { + "methodology_provenance": METHODOLOGY_PROVENANCE, + "seed": seed, + "deterministic": True, + "failure_id": fid, + "title": failure.title, + "layers": { + "1_failure_detection": { + "candidate_events": L("OBSERVED", + failure.detection_basis.candidate_events), + "baseline_events": L("OBSERVED", + failure.detection_basis.baseline_events), + "denominator": L("OBSERVED", failure.detection_basis.denominator), + "observed_rate": L("OBSERVED", + failure.detection_basis.candidate_rate), + "headline": L("OBSERVED", + f"~{failure.detection_basis.candidate_rate:.4%} " + "pedestrian->construction_cone rate on the " + "candidate model"), + "scene_instances_captured": L("OBSERVED", len(failure.instances)), + }, + "2_evidence_aggregation": { + "evidence_graph_nodes": L( + "OBSERVED", + [{"type": n["node_type"], "status": n["status"]} + for n in (store_mod.read_json( + "evidence", f"{fid}.json") or {}).get("nodes", [])]), + "snippets_built": L("OBSERVED", len(pipeline_mod.get_snippets(fid))), + "temporal_context": L("OBSERVED", + "before/failure/after frames captured " + "per snippet"), + }, + "3_failure_analysis": { + "statistics": L("OBSERVED", stat.model_dump() if stat else None), + "concentration": L("OBSERVED", { + "determination": conc.determination if conc else None, + "concentrated_dimensions": (conc.concentrated_dimensions + if conc else []), + "construction_stratum": next( + (s.model_dump() for s in (conc.strata if conc else []) + if s.stratum == "construction"), None), + }), + "fusion_verdict": L("OBSERVED", + fusion.output.get("overall_verdict") + if fusion else None), + "novelty": L("OBSERVED", + mining.output.get("novelty") if mining else None), + "scene_hypotheses": L("HYPOTHETICAL", + (vlm.output.get("hypotheses", [])[:3] + if vlm else [])), + "safety_chain": L("OBSERVED", + safety.output.get("chain") if safety else None), + "replay_worst_case": L("OBSERVED", + safety.output.get("worst_case") + if safety else None), + "replay_coverage": L("REQUIRED-EVIDENCE", + safety.output.get("coverage_note") + if safety else "no safety agent output"), + }, + "4_launch_decision": { + "policy_version": L("OBSERVED", evaluation.get("policy_version")), + "severity": L("OBSERVED", evaluation.get("severity")), + "outcome": L("OBSERVED", evaluation.get("outcome")), + "recommended_option": L("OBSERVED", + evaluation.get("recommended_option")), + "matrix_row_fired": L("OBSERVED", evaluation.get("matrix_row_fired")), + "option_c_rejection": L( + "REQUIRED-EVIDENCE", + [c for c in (evaluation.get("option_c_evaluation") or {}) + .get("checks", []) if not c.get("passed")]), + "expected_loss_table": L("HYPOTHETICAL", + evaluation.get("expected_loss_table")), + "mandatory_review_triggers": L( + "OBSERVED", + [t for t in evaluation.get("mandatory_review_triggers", []) + if t["fired"]]), + "human_review": L("OBSERVED", review_mod.decisions_for(fid)), + }, + "5_learning_flywheel": { + "suites_created": L("OBSERVED", state.suite_ids), + "regression_hook": L("OBSERVED", regression.get("suites")), + }, + }, + "scorecard_id": state.scorecard_id, + "audit_records": L("OBSERVED", len(store_mod.audit_trail(fid))), + "audit_chain_valid": L("OBSERVED", + store_mod.verify_audit_chain(fid).get("valid")), + "separation_of_powers": ( + "agents produced hypotheses and advisory summaries only; rates, " + "CIs, significance, severity, the policy outcome and the option " + "recommendation above all came from deterministic code, and the " + "final validation was a recorded human decision"), + } + store_mod.write_json(walkthrough, "worked_example", "latest.json") + return walkthrough diff --git a/sensorflow/retro/tools/builtin.py b/sensorflow/retro/tools/builtin.py index ff8c6da9db126e7328e9c0ec224b2824a64e168f..1fd6858fd8d4ff35c532a8dc79dd38eeee798fc9 100644 --- a/sensorflow/retro/tools/builtin.py +++ b/sensorflow/retro/tools/builtin.py @@ -205,12 +205,28 @@ def distribution_analysis(inp: DistributionInput) -> DistributionOutput: # Delegate to the platform's megaeval statistics when a real run exists. try: from sensorflow.megaeval.analysis import distribution_shift - from sensorflow.megaeval.runs import get_run, get_store - run = get_run(get_store(), inp.run_id) - res = distribution_shift(get_store(), run) + from sensorflow.megaeval.runs import get_mega_store + store = get_mega_store() + run = store.runs.get(inp.run_id) + if run is None: + raise KeyError(f"unknown megaeval run {inp.run_id!r}") + if run.status != "published": + raise ValueError( + f"megaeval run {inp.run_id!r} not published " + f"(status={run.status}); artifacts unavailable") + res = distribution_shift(store, run) + shifts = res.get("shifts", []) + findings = [f"megaeval shift analysis for run {inp.run_id}: " + f"{len(shifts)} shifted cohort(s) above threshold"] + for s in shifts[:3]: + findings.append( + f"cohort {s['cohort']}: train share {s['train_share']:.4f} " + f"-> eval share {s['eval_share']:.4f} " + f"(rel {s['relative_change']:+.2f}), cohort recall " + f"{s['cohort_recall']} vs overall {s['overall_recall']}") return DistributionOutput( source="sensorflow.megaeval.analysis.distribution_shift", - findings=[f"megaeval shift analysis for run {inp.run_id}"], + findings=findings, shift=res) except Exception as exc: return DistributionOutput( diff --git a/sensorflow/studio_ux/__init__.py b/sensorflow/studio_ux/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bae89d2f992abccdf2435e96f9211327dac84a78 --- /dev/null +++ b/sensorflow/studio_ux/__init__.py @@ -0,0 +1,3 @@ +"""Studio-UX support module: dashboard layout persistence + read-only +visualization replays for the WYSIWYG frontend. Never mutates other +subsystems' state; only imports their pure generation/evaluation functions.""" diff --git a/sensorflow/studio_ux/api.py b/sensorflow/studio_ux/api.py new file mode 100644 index 0000000000000000000000000000000000000000..311d3971512d8a56219d0421fc874e2599069c29 --- /dev/null +++ b/sensorflow/studio_ux/api.py @@ -0,0 +1,172 @@ +"""FastAPI router for studio-UX support (/api/studio-ux/*). + +Endpoints: + GET /layouts/{key} fetch a persisted UI layout/preset (JSON blob) + PUT /layouts/{key} persist a UI layout/preset + GET /bev/replay deterministically re-generate one BEV-fusion scene + sequence (same generators/engines as /api/bevfusion, + read-only) and return per-frame GT boxes, camera and + LiDAR detections with covariances, fused+tracked + boxes (masklet-propagated flagged) and the camera + baseline boxes — the data behind the interactive + top-down BEV canvas. + +This module only *reads* from other subsystems (pure functions on synthetic +scenes); the only writes are its own layout files under runs/studio_ux/. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Any, Dict, List, Optional + +from fastapi import APIRouter, HTTPException, Query +from pydantic import BaseModel + +router = APIRouter(prefix="/api/studio-ux", tags=["studio-ux"]) + +LAYOUTS_DIR = Path("runs/studio_ux/layouts") +_KEY_RE = re.compile(r"^[A-Za-z0-9._-]{1,120}$") + + +def _layout_path(key: str) -> Path: + if not _KEY_RE.match(key): + raise HTTPException(422, "layout key must match [A-Za-z0-9._-]{1,120}") + return LAYOUTS_DIR / f"{key}.json" + + +@router.get("/layouts/{key}") +def get_layout(key: str) -> Dict[str, Any]: + path = _layout_path(key) + if not path.exists(): + return {"key": key, "value": None} + try: + with open(path) as f: + return {"key": key, "value": json.load(f)} + except Exception: + return {"key": key, "value": None} + + +class LayoutBody(BaseModel): + value: Any + + +@router.put("/layouts/{key}") +def put_layout(key: str, body: LayoutBody) -> Dict[str, Any]: + path = _layout_path(key) + path.parent.mkdir(parents=True, exist_ok=True) + with open(path, "w") as f: + json.dump(body.value, f) + return {"key": key, "saved": True} + + +# ------------------------------------------------------------------ BEV replay + + +def _det_dict(det) -> Dict[str, Any]: + return { + "modality": det.modality, + "x": round(det.x, 3), + "y": round(det.y, 3), + "cov": [[round(v, 5) for v in row] for row in det.cov], + "dims": [round(v, 3) for v in det.dims], + "yaw": round(det.yaw, 4), + "class_name": det.class_name, + "confidence": round(det.confidence, 3), + } + + +@router.get("/bev/replay") +def bev_replay(seed: int = Query(7), + n_sequences: int = Query(6, ge=1, le=24), + frames_per_sequence: int = Query(24, ge=8, le=60), + sequence: int = Query(0, ge=0)) -> Dict[str, Any]: + """Deterministic replay of one scene sequence through both engines.""" + from sensorflow.bevfusion.engines import FrameToFrameTracker + from sensorflow.bevfusion.fusion import build_modality_map, decode_bev, fuse_maps + from sensorflow.bevfusion.geometry import BEVGrid + from sensorflow.bevfusion.masklet import BEVMaskletTracker + from sensorflow.bevfusion.scenes import generate_sequences + from sensorflow.bevfusion.sensors import camera_rng, lidar_rng, simulate_camera, simulate_lidar + from sensorflow.schemas.unified_frame import Object3D + + if sequence >= n_sequences: + raise HTTPException(422, f"sequence must be < n_sequences ({n_sequences})") + + sequences = generate_sequences(n_sequences=n_sequences, + frames_per_sequence=frames_per_sequence, + seed=seed) + seq = sequences[sequence] + + grid = BEVGrid() + cam_gen = camera_rng(seed, sequence) + lid_gen = lidar_rng(seed, sequence) + base_gen = camera_rng(seed, sequence) # baseline uses the same camera stream + masklet = BEVMaskletTracker(bounds=(grid.x_min, grid.x_max, grid.y_min, grid.y_max)) + base_tracker = FrameToFrameTracker(gate=3.0) + + frames: List[Dict[str, Any]] = [] + for frame in seq.frames: + cam_dets = simulate_camera(frame, seq, cam_gen) + lid_dets = simulate_lidar(frame, seq, lid_gen) + + # fused engine (mirrors engines.run_fused, but keeps the raw detections) + cam_map = build_modality_map(cam_dets, grid, "camera") + lid_map = build_modality_map(lid_dets, grid, "lidar") + decoded = decode_bev(fuse_maps(cam_map, lid_map)) + proposals = [Object3D(bbox_3d=b["bbox_3d"], class_name=b["class_name"], + confidence=b["confidence"]) for b in decoded] + tracked = masklet.update(frame.frame_id, proposals) + propagated_ids = getattr(masklet, "last_propagated", set()) + fused = [{ + "bbox_3d": [round(v, 3) for v in t.bbox_3d], + "class_name": t.class_name, + "confidence": round(float(t.confidence or 0.0), 3), + "track_id": t.track_id, + "propagated": t.track_id in propagated_ids, + } for t in tracked] + + # camera-only baseline (mirrors engines.run_baseline; identical rng stream) + base_boxes = [{ + "bbox_3d": [d.x, d.y, d.z, d.dims[0], d.dims[1], d.dims[2], d.yaw], + "class_name": d.class_name, + "confidence": d.confidence, + "propagated": False, + } for d in simulate_camera(frame, seq, base_gen)] + base_boxes = base_tracker.update(base_boxes) + baseline = [{ + "bbox_3d": [round(float(v), 3) for v in b["bbox_3d"]], + "class_name": b["class_name"], + "confidence": round(float(b["confidence"]), 3), + "track_id": b["track_id"], + "propagated": False, + } for b in base_boxes] + + frames.append({ + "frame_id": frame.frame_id, + "index": frame.index, + "gt": [{ + "instance_id": g.instance_id, + "class_name": g.class_name, + "bbox_3d": g.bbox_3d, + "occluded": g.occluded, + "distance": g.distance, + } for g in frame.gt], + "camera": [_det_dict(d) for d in cam_dets], + "lidar": [_det_dict(d) for d in lid_dets], + "fused": fused, + "baseline": baseline, + }) + + return { + "sequence_id": seq.sequence_id, + "sequence_index": sequence, + "n_sequences": n_sequences, + "time_of_day": seq.time_of_day, + "weather": seq.weather, + "params": {"n_sequences": n_sequences, + "frames_per_sequence": frames_per_sequence, "seed": seed}, + "frames": frames, + } diff --git a/src/App.tsx b/src/App.tsx index efd9734fb1d77e68c70008b5fd678af0a2e54c00..731066ab0061cd785887501dad7bfd41fa0e5454 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -30,8 +30,22 @@ import { Map as MapIcon, AppWindow, Mountain, - Undo2, CircuitBoard, + Grid3x3, + GitBranch, + FileCheck2, + AlertTriangle, + Crosshair, + GitCompareArrows, + Library, + Sparkles, + LineChart, + Layers, + Shapes, + Network, + LayoutGrid, + Undo2, + Scale, } from 'lucide-react'; import { LabelEvalContext, type PageId, ALL_PAGE_IDS } from './context/LabelEvalContext'; import { getOverview, useStream } from './services/labeleval'; @@ -53,9 +67,23 @@ import LegacyStudioPage from './pages/LegacyStudioPage'; import CommandCenterPage from './pages/CommandCenterPage'; import RootCauseLabPage from './pages/rca/RootCauseLabPage'; import RareMinePage from './pages/raremine/RareMinePage'; -import VitisPage from './pages/vitis/VitisPage'; import HillClimbSection from './pages/hillclimb/HillClimbSection'; +import VitisPage from './pages/vitis/VitisPage'; +import OddCoveragePage from './pages/safety/OddCoveragePage'; +import ReleaseGatesPage from './pages/safety/ReleaseGatesPage'; +import EvidencePage from './pages/safety/EvidencePage'; +import SsamConflictPage from './pages/safety/SsamConflictPage'; +import CalibrationPage from './pages/safety/CalibrationPage'; +import DiscrepancyPage from './pages/safety/DiscrepancyPage'; +import ScenarioDbPage from './pages/safety/ScenarioDbPage'; +import SemanticSearchPage from './pages/safety/SemanticSearchPage'; +import SeqevalPage from './pages/engines/SeqevalPage'; +import BevFusionPage from './pages/engines/BevFusionPage'; +import ScenarioComposerPage from './pages/studio/ScenarioComposerPage'; +import PipelineBuilderPage from './pages/studio/PipelineBuilderPage'; +import MyDashboardPage from './pages/studio/MyDashboardPage'; import RetroAnalyzerPage from './pages/retro/RetroAnalyzerPage'; +import LaunchReadinessPage from './pages/agentic/LaunchReadinessPage'; import PageIntro from './components/help/PageIntro'; import HelpMenu from './components/help/HelpMenu'; @@ -85,10 +113,33 @@ const PLATFORM_NAV: NavItem[] = [ { id: 'audit', label: 'Audit', icon: }, { id: 'pipeline', label: 'Pipeline Architecture', icon: }, { id: 'hillclimb', label: 'Hill Climbing EM', icon: }, - { id: 'retro', label: 'Retrospective Analyzer', icon: }, { id: 'vitis', label: 'Hardware Acceleration', icon: }, ]; +const STUDIO_NAV: NavItem[] = [ + { id: 'my-dashboard', label: 'My Dashboard', icon: }, + { id: 'scenario-composer', label: 'Scenario Composer', icon: }, + { id: 'pipeline-builder', label: 'Pipeline Builder', icon: }, +]; + +const ENGINES_NAV: NavItem[] = [ + { id: 'seqeval', label: 'Sequential Regression', icon: }, + { id: 'bevfusion', label: 'Perception Engines', icon: }, +]; + +const SAFETY_NAV: NavItem[] = [ + { id: 'safety-odd', label: 'ODD Coverage', icon: }, + { id: 'safety-gates', label: 'Release Gates', icon: }, + { id: 'safety-evidence', label: 'Evidence Package', icon: }, + { id: 'safety-ssam', label: 'SSAM Conflicts', icon: }, + { id: 'safety-calibration', label: 'Calibration', icon: }, + { id: 'safety-discrepancy', label: 'Discrepancy Mining', icon: }, + { id: 'safety-scenarios', label: 'Scenario DB', icon: }, + { id: 'safety-search', label: 'Semantic Search', icon: }, + { id: 'retro', label: 'Retrospective Analyzer', icon: }, + { id: 'launch-readiness', label: 'Launch Readiness', icon: }, +]; + const LEGACY_NAV: NavItem[] = [ { id: 'ssam', label: 'SSAM Safety', icon: }, { id: 'legacy', label: 'Legacy Studio', icon: }, @@ -112,9 +163,23 @@ const PAGE_TITLES: Record = { audit: 'Audit & Process Units', pipeline: 'Pipeline Architecture', hillclimb: 'Hill Climbing EM', - retro: 'Retrospective Safety Analyzer', vitis: 'Hardware Acceleration (Vitis Vision)', ssam: 'SSAM Safety Dashboard', + 'safety-odd': 'ODD Coverage', + 'safety-gates': 'Release Gates', + 'safety-evidence': 'Safety Evidence Package', + 'safety-ssam': 'SSAM Conflict Analysis', + 'safety-calibration': 'Sensor Calibration Validation', + 'safety-discrepancy': 'Discrepancy Mining', + 'safety-scenarios': 'Scenario Database', + 'safety-search': 'Semantic Scenario Search', + seqeval: 'Sequential Regression Evaluation', + bevfusion: 'Perception Engines (BEV Fusion)', + 'scenario-composer': 'Scenario Composer', + 'pipeline-builder': 'Pipeline Builder', + 'my-dashboard': 'My Dashboard', + retro: 'Retrospective Safety Analyzer', + 'launch-readiness': 'Launch Readiness (Agentic Triage)', legacy: 'Legacy Studio', }; @@ -262,6 +327,36 @@ export default function App() { > {PLATFORM_NAV.map(renderNavItem)} + + STUDIO + + } + > + {STUDIO_NAV.map(renderNavItem)} + + + ENGINES & REGRESSION + + } + > + {ENGINES_NAV.map(renderNavItem)} + + + SAFETY & COMPLIANCE + + } + > + {SAFETY_NAV.map(renderNavItem)} + : null} {page === 'pipeline' ? : null} {page === 'hillclimb' ? : null} - {page === 'retro' ? : null} {page === 'vitis' ? : null} + {page === 'safety-odd' ? : null} + {page === 'safety-gates' ? : null} + {page === 'safety-evidence' ? : null} + {page === 'safety-ssam' ? : null} + {page === 'safety-calibration' ? : null} + {page === 'safety-discrepancy' ? : null} + {page === 'safety-scenarios' ? : null} + {page === 'safety-search' ? : null} + {page === 'seqeval' ? : null} + {page === 'bevfusion' ? : null} + {page === 'scenario-composer' ? : null} + {page === 'pipeline-builder' ? : null} + {page === 'my-dashboard' ? : null} + {page === 'retro' ? : null} + {page === 'launch-readiness' ? : null} )} diff --git a/src/components/agentic/AgentOutputsPanel.tsx b/src/components/agentic/AgentOutputsPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..cad9ff0a8ab5c157447d739bcd396bf6b4687b0c --- /dev/null +++ b/src/components/agentic/AgentOutputsPanel.tsx @@ -0,0 +1,105 @@ +/** Agent outputs, each clearly labeled as advisory AI analysis with its + * epistemic status, confidence basis and escalation triggers. */ +import Accordion from '@mui/material/Accordion'; +import AccordionDetails from '@mui/material/AccordionDetails'; +import AccordionSummary from '@mui/material/AccordionSummary'; +import Box from '@mui/material/Box'; +import Chip from '@mui/material/Chip'; +import Paper from '@mui/material/Paper'; +import Typography from '@mui/material/Typography'; +import { ChevronDown } from 'lucide-react'; +import type { AgentResult } from '../../types/agentic'; +import { EvidenceStatusChip, KV, OriginBadge, PanelTitle } from './common'; + +const AGENT_LABELS: Record = { + failure_detection: 'Failure Detection Agent', + vlm_scene_analysis: 'VLM Scene Analysis Agent', + sensor_fusion_verification: 'Sensor Fusion Verification Agent', + scenario_mining: 'Scenario Mining Agent', + statistical_regression: 'Statistical Regression Agent', + safety_impact: 'Safety Impact Agent', + launch_decision: 'Launch Decision Agent (narrative only)', + eval_flywheel: 'Eval Flywheel Agent', +}; + +function summarize(agent: AgentResult): string { + const o = agent.output; + switch (agent.agent) { + case 'vlm_scene_analysis': { + const hyps = (o.hypotheses as { hypothesis: string }[] | undefined) ?? []; + return hyps.map((h) => h.hypothesis).slice(0, 2).join(' · ') || 'no hypotheses'; + } + case 'sensor_fusion_verification': + return `verdict: ${String(o.overall_verdict)}`; + case 'scenario_mining': + return `novelty: ${String(o.novelty)} · ${String((o.clusters as unknown[] | undefined)?.length ?? 0)} cluster(s)`; + case 'safety_impact': + return String(o.assessment ?? ''); + case 'launch_decision': + return `restates policy outcome ${String(o.restated_outcome)} (cannot change it)`; + case 'eval_flywheel': + return o.proposal ? `proposes suite ${String((o.proposal as Record).suite_name)}` : String(o.reason ?? ''); + default: + return ''; + } +} + +export default function AgentOutputsPanel({ agents }: { agents: AgentResult[] }) { + return ( + + + {agents.map((a) => ( + + }> + + + {AGENT_LABELS[a.agent] ?? a.agent} + + + + {a.escalation.required ? ( + + ) : null} + + {summarize(a)} + + + + + + + {a.escalation.required ? ( + + ) : null} + {a.llm_rationale ? : null} + + {JSON.stringify(a.output, null, 2)} + + + + ))} + + ); +} diff --git a/src/components/agentic/ConcentrationHeatmap.tsx b/src/components/agentic/ConcentrationHeatmap.tsx new file mode 100644 index 0000000000000000000000000000000000000000..3ffe8b69929a2a04f8a9fc66f408d8b87e12bf7e --- /dev/null +++ b/src/components/agentic/ConcentrationHeatmap.tsx @@ -0,0 +1,97 @@ +/** Uniform-vs-concentrated analysis as a relative-risk heatmap per stratum. */ +import Box from '@mui/material/Box'; +import Chip from '@mui/material/Chip'; +import Paper from '@mui/material/Paper'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; +import type { ConcentrationAnalysis } from '../../types/agentic'; +import { fmtCi, fmtRate, PanelTitle } from './common'; + +function riskColor(rr: number | null): string { + if (rr === null) return '#37474f'; + if (rr >= 10) return '#b71c1c'; + if (rr >= 3) return '#d84315'; + if (rr >= 1.5) return '#ef6c00'; + if (rr >= 0.75) return '#37474f'; + return '#1b5e20'; +} + +export default function ConcentrationHeatmap({ conc }: { conc: ConcentrationAnalysis }) { + const byDim = new Map(); + for (const s of conc.strata) { + byDim.set(s.dimension, [...(byDim.get(s.dimension) ?? []), s]); + } + return ( + + + } + /> + {conc.concentrated_dimensions.length > 0 ? ( + + Concentrated in: {conc.concentrated_dimensions.join(', ')} + + ) : null} + {[...byDim.entries()].map(([dim, strata]) => ( + + + {dim} + + + {strata.map((s) => ( + +
rate {fmtRate(s.stratum_rate)} vs population {fmtRate(s.baseline_rate)}
+
events {s.events} / exposure {s.exposure.toLocaleString()} ({(s.exposure_share * 100).toFixed(1)}%)
+
odds ratio {s.odds_ratio ?? '—'} · risk diff {fmtRate(s.risk_difference)}
+
rate CI {fmtCi(s.rate_wilson_ci)}
+ {s.small_sample_flag ?
⚠ small-sample: estimate unstable
: null} +
+ } + > + + + {s.stratum} + + + RR {s.relative_risk === null ? '—' : s.relative_risk.toFixed(1)} + {s.small_sample_flag ? ' ⚠' : ''} + + + + ))} +
+ + ))} + + {conc.method} + +
+ ); +} diff --git a/src/components/agentic/DecisionPanel.tsx b/src/components/agentic/DecisionPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..c58fd9bb883be9575ca97b3a8e325d26cc6b661a --- /dev/null +++ b/src/components/agentic/DecisionPanel.tsx @@ -0,0 +1,281 @@ +/** Launch decision panel: policy outcome banner, the deterministic matrix row + * that fired, option cards with expected loss + hard-constraint feasibility, + * the human-review form, and the audit trail viewer. */ +import { useState } from 'react'; +import Alert from '@mui/material/Alert'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import Chip from '@mui/material/Chip'; +import MenuItem from '@mui/material/MenuItem'; +import Paper from '@mui/material/Paper'; +import TextField from '@mui/material/TextField'; +import Typography from '@mui/material/Typography'; +import type { + AuditRecord, + HumanReviewDecision, + PolicyEvaluation, +} from '../../types/agentic'; +import { submitHumanReview } from '../../services/agentic'; +import { fmtRate, KV, OUTCOME_STYLE, PanelTitle, SeverityChip } from './common'; + +const OPTION_TITLES: Record = { + STOP_SHIP: 'Stop Ship', + OPTION_A_DELAY: 'Option A — Delay Launch', + OPTION_B_MITIGATION: 'Option B — Ship w/ Mitigation', + OPTION_C_REDUCED_ODD: 'Option C — Reduced ODD', + EXPAND_EVALUATION: 'Expand Evaluation', + HUMAN_SAFETY_REVIEW: 'Human Safety Review', + PROCEED: 'Proceed', +}; + +const DECISIONS = [ + 'confirm_failure', + 'reject_failure', + 'approve_option', + 'approve_launch', + 'block_launch', + 'request_more_evidence', +]; + +export default function DecisionPanel({ + failureId, + evaluation, + decisions, + audit, + auditValid, + onReviewed, +}: { + failureId: string; + evaluation: PolicyEvaluation; + decisions: HumanReviewDecision[]; + audit: AuditRecord[]; + auditValid: boolean | null; + onReviewed: () => void; +}) { + const [reviewer, setReviewer] = useState(''); + const [decision, setDecision] = useState('confirm_failure'); + const [rationale, setRationale] = useState(''); + const [overrideReason, setOverrideReason] = useState(''); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(null); + const [showAudit, setShowAudit] = useState(false); + + const style = OUTCOME_STYLE[evaluation.outcome]; + const row = evaluation.matrix_row_fired; + + const submit = async () => { + setSubmitting(true); + setError(null); + try { + await submitHumanReview(failureId, { + reviewer, + decision, + rationale, + approved_option: decision === 'approve_option' ? evaluation.recommended_option : null, + evidence_reviewed: ['evidence_graph', 'statistical_assessment', 'policy_evaluation'], + override_reason: overrideReason || null, + }); + setRationale(''); + onReviewed(); + } catch (e) { + setError((e as Error).message); + } finally { + setSubmitting(false); + } + }; + + return ( + + {/* outcome banner */} + + + + {style.label} + + + + + + + {(evaluation.severity_assignment?.taxonomy_description ?? '') + + (evaluation.automatic_stop_ship_condition + ? ` · pre-authorized stop-ship condition ${evaluation.automatic_stop_ship_condition.condition_id} fired` + : '')} + + {evaluation.indeterminate_reasons?.length ? ( + + Fail-safe reasons: {evaluation.indeterminate_reasons.join('; ')} + + ) : null} + + + {/* matrix row */} + {row ? ( + + + + + + ) : null} + + {/* option cards */} + + + + Expected loss is reported for every option, but SAFETY IS A HARD CONSTRAINT: options whose + residual failure rate violates the policy limit are excluded from selection no matter how + cheap they are. + + + {evaluation.expected_loss_table.map((o) => { + const recommended = o.option === evaluation.recommended_option; + return ( + + + + {OPTION_TITLES[o.option] ?? o.option} + + {recommended ? ( + + ) : null} + {!o.feasible ? ( + + ) : null} + + + expected loss {o.expected_loss.toLocaleString()} + + + residual rate {fmtRate(o.residual_failure_rate)} + + + business cost {o.business_cost.toLocaleString()} + + {o.infeasible_reason ? ( + + {o.infeasible_reason} + + ) : null} + + ); + })} + + {evaluation.option_c_evaluation && !evaluation.option_c_evaluation.feasible ? ( + + + Option C (reduced ODD) rejected checks: + + {evaluation.option_c_evaluation.checks + .filter((c) => !c.passed) + .map((c) => ( + + ✗ {c.check} — {c.detail} + + ))} + + ) : null} + + + {/* mandatory triggers */} + {evaluation.mandatory_review_triggers?.some((t) => t.fired) ? ( + + Mandatory human review triggers fired:{' '} + {evaluation.mandatory_review_triggers + .filter((t) => t.fired) + .map((t) => t.trigger) + .join(', ')} + + ) : null} + + {/* human review form */} + + + + No agent output authorizes a launch. Authorization = deterministic policy outcome above + + this recorded human decision (against policy {evaluation.policy_version}). + + + setReviewer(e.target.value)} sx={{ width: 180 }} /> + setDecision(e.target.value)} sx={{ width: 210 }}> + {DECISIONS.map((d) => ( + + {d.replace(/_/g, ' ')} + + ))} + + setRationale(e.target.value)} sx={{ flex: 1, minWidth: 260 }} multiline /> + setOverrideReason(e.target.value)} sx={{ minWidth: 260 }} /> + + + {error ? ( + + {error} + + ) : null} + {decisions.length > 0 ? ( + + {decisions.map((d) => ( + + {d.reviewer} — {d.decision.replace(/_/g, ' ')} + {d.approved_option ? ` (${d.approved_option})` : ''} · {d.timestamp} · policy{' '} + {d.policy_version || '—'} + {d.override_reason ? ` · OVERRIDE: ${d.override_reason}` : ''} — “{d.rationale}” + + ))} + + ) : null} + + + {/* audit trail */} + + + {auditValid !== null ? ( + + ) : null} + + + } + /> + {showAudit ? ( + + {audit.map((r) => ( + + #{r.seq} [{r.timestamp}] {r.event_type} · {r.actor} · {r.detail}{' '} + ({r.prev_hash} → {r.hash}) + + ))} + + ) : null} + + + ); +} diff --git a/src/components/agentic/EvidenceGraphPanel.tsx b/src/components/agentic/EvidenceGraphPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f273a71c9f0e17a844c10ea39b805f70f7f2d11c --- /dev/null +++ b/src/components/agentic/EvidenceGraphPanel.tsx @@ -0,0 +1,87 @@ +/** Failure Evidence Graph rendered as a status-colored node panel. */ +import Box from '@mui/material/Box'; +import Paper from '@mui/material/Paper'; +import Typography from '@mui/material/Typography'; +import type { EvidenceGraph } from '../../types/agentic'; +import { EVIDENCE_STATUS_COLORS, EvidenceStatusChip, PanelTitle } from './common'; + +const NODE_ORDER = [ + 'Object', + 'Environment', + 'Sensors', + 'Prediction', + 'GroundTruth', + 'Tracking', + 'Planner', + 'HistoricalSimilarity', + 'Frequency', + 'SafetyConsequence', +]; + +export default function EvidenceGraphPanel({ graph }: { graph: EvidenceGraph }) { + const byId = new Map(graph.nodes.map((n) => [n.node_id, n])); + const nodes = [...graph.nodes].sort( + (a, b) => NODE_ORDER.indexOf(a.node_type) - NODE_ORDER.indexOf(b.node_type) + ); + return ( + + + {(['OBSERVED', 'DERIVED', 'HYPOTHESIS', 'UNAVAILABLE'] as const).map((s) => ( + + ))} + + } + /> + + {nodes.map((n) => ( + + + + {n.node_type} + + + + + {n.summary} + + {n.caveats.length > 0 ? ( + + {n.caveats.join(' · ')} + + ) : null} + + source: {n.source} + + + ))} + + + Relations:{' '} + {graph.edges + .map( + (e) => + `${byId.get(e.src)?.node_type ?? '?'} —${e.relation}→ ${byId.get(e.dst)?.node_type ?? '?'}` + ) + .join(' · ')} + + + ); +} diff --git a/src/components/agentic/FlywheelPanel.tsx b/src/components/agentic/FlywheelPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..c91edc0fce396e94b682ec3284efd56fec2f9a81 --- /dev/null +++ b/src/components/agentic/FlywheelPanel.tsx @@ -0,0 +1,122 @@ +/** Evaluation flywheel: suites created from validated failures (governance + * fields + contamination-guard badges) and the seqeval regression hook. */ +import { useState } from 'react'; +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import Chip from '@mui/material/Chip'; +import Paper from '@mui/material/Paper'; +import Table from '@mui/material/Table'; +import TableBody from '@mui/material/TableBody'; +import TableCell from '@mui/material/TableCell'; +import TableHead from '@mui/material/TableHead'; +import TableRow from '@mui/material/TableRow'; +import Typography from '@mui/material/Typography'; +import type { EvaluationSuite, RegressionSuiteResult } from '../../types/agentic'; +import { runRegression } from '../../services/agentic'; +import { fmtCi, KV, PanelTitle } from './common'; + +const DECISION_COLORS: Record = { + PASS: '#1b5e20', + REGRESSION: '#b71c1c', + INSUFFICIENT_EVIDENCE: '#4e342e', +}; + +export default function FlywheelPanel({ suites }: { suites: EvaluationSuite[] }) { + const [regression, setRegression] = useState(null); + const [running, setRunning] = useState(false); + + const evaluate = async () => { + setRunning(true); + try { + const res = await runRegression(); + setRegression(res.suites); + } finally { + setRunning(false); + } + }; + + return ( + + + + {suites.length === 0 ? ( + + No suites yet — suites are created by the LEARNING FLYWHEEL stage after a failure is + human-validated. + + ) : ( + suites.map((s) => ( + + + + {s.name} v{s.version} + + + + {s.governance_overrides.length > 0 ? ( + + ) : null} + + + + + + + + m.training_eligible).length} — requires explicit recorded override)`} + /> + + )) + )} + + + + + {running ? 'Evaluating…' : 'Evaluate candidate'} + + } + /> + {regression ? ( + + + + {['Suite', 'n', 'Baseline', 'Candidate', 'Δ', 'Δ CI (anytime-valid)', 'Decision'].map((h) => ( + + {h} + + ))} + + + + {regression.map((r) => ( + + {r.suite} + {r.n} + {r.baseline_rate ?? '—'} + {r.candidate_rate ?? '—'} + {r.delta ?? '—'} + {fmtCi(r.delta_ci)} + + + + + ))} + +
+ ) : ( + + Run the evaluation to compare the candidate model against the general, + historical-regression, rare-event, safety-critical and failure-derived suites. + INSUFFICIENT_EVIDENCE is reported as-is — it is never a pass. + + )} +
+
+ ); +} diff --git a/src/components/agentic/SafetyChainPanel.tsx b/src/components/agentic/SafetyChainPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5c835f81c43525ce4fe5c3beafdbc91989eec46b --- /dev/null +++ b/src/components/agentic/SafetyChainPanel.tsx @@ -0,0 +1,84 @@ +/** Perception → tracking → prediction → planner → behavior chain with + * explicit UNCERTAIN / UNAVAILABLE labeling. */ +import Box from '@mui/material/Box'; +import Paper from '@mui/material/Paper'; +import Typography from '@mui/material/Typography'; +import type { AgentResult } from '../../types/agentic'; +import { EVIDENCE_STATUS_COLORS, KV, PanelTitle } from './common'; + +interface ChainLink { + link: string; + status: 'OBSERVED' | 'DERIVED' | 'HYPOTHESIS' | 'UNAVAILABLE'; + detail: string; +} + +export default function SafetyChainPanel({ safety }: { safety: AgentResult }) { + const chain = (safety.output.chain as ChainLink[] | undefined) ?? []; + const kinematics = safety.output.kinematics as Record | undefined; + const worst = safety.output.worst_case as Record | undefined; + const uncertain = safety.output.behavioral_evidence === 'none'; + return ( + + + {uncertain ? ( + + {String(safety.output.assessment)} + + ) : null} + + {chain.map((c, i) => ( + + + + {c.link.replace(/_/g, ' ')} + + + {c.status === 'UNAVAILABLE' ? 'UNCERTAIN — no evidence' : c.status} + + + {c.detail} + + + {i < chain.length - 1 ? → : null} + + ))} + + {!uncertain && worst ? ( + + + + + {kinematics ? ( + <> + + + + + ) : null} + + {String(safety.output.coverage_note ?? '')} + + + ) : null} + + ); +} diff --git a/src/components/agentic/ScorecardView.tsx b/src/components/agentic/ScorecardView.tsx new file mode 100644 index 0000000000000000000000000000000000000000..2f39f52e814ff467e5a4080cedb4f289abddb6e7 --- /dev/null +++ b/src/components/agentic/ScorecardView.tsx @@ -0,0 +1,91 @@ +/** Leadership-facing retrospective scorecard with per-field provenance tags + * and JSON export. */ +import Box from '@mui/material/Box'; +import Button from '@mui/material/Button'; +import Chip from '@mui/material/Chip'; +import Paper from '@mui/material/Paper'; +import Typography from '@mui/material/Typography'; +import type { Scorecard, ScorecardField } from '../../types/agentic'; +import { OutcomeChip, PanelTitle } from './common'; + +const TAG_COLORS: Record = { + OBSERVED: { bg: '#1b5e20', fg: '#a5d6a7' }, + PREDICTED: { bg: '#0d47a1', fg: '#90caf9' }, + HYPOTHETICAL: { bg: '#4a148c', fg: '#ce93d8' }, + REQUIRED_EVIDENCE: { bg: '#4e342e', fg: '#ffcc80' }, +}; + +const FIELDS: { key: keyof Scorecard; label: string }[] = [ + { key: 'failure_summary', label: 'Failure' }, + { key: 'frequency', label: 'Frequency' }, + { key: 'exposure', label: 'Exposure' }, + { key: 'severity', label: 'Severity' }, + { key: 'confidence', label: 'Confidence' }, + { key: 'novelty', label: 'Novelty' }, + { key: 'concentration', label: 'Concentration' }, + { key: 'downstream_impact', label: 'Downstream impact' }, + { key: 'mitigations', label: 'Mitigations' }, + { key: 'residual_risk', label: 'Residual risk' }, +]; + +function renderValue(v: unknown): string { + if (v === null || v === undefined) return '—'; + if (typeof v === 'object') return JSON.stringify(v); + return String(v); +} + +export default function ScorecardView({ card }: { card: Scorecard }) { + const exportJson = () => { + const blob = new Blob([JSON.stringify(card, null, 2)], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `${card.scorecard_id}.json`; + a.click(); + URL.revokeObjectURL(url); + }; + + return ( + + + + + + + } + /> + + {FIELDS.map(({ key, label }) => { + const f = card[key] as ScorecardField; + const tag = TAG_COLORS[f.tag]; + return ( + + + + {label} + + + + + {renderValue(f.value)} + + + evidence: {f.evidence_ref || '—'} + + + ); + })} + + + {card.notes.join(' · ')} · recommended option: {card.recommended_option ?? '—'} · policy{' '} + {card.policy_version} · generated {card.generated_at} + + + ); +} diff --git a/src/components/agentic/StatisticalPanel.tsx b/src/components/agentic/StatisticalPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..bb8e3128374b9e23070ca17566fbf579e0fa6f7e --- /dev/null +++ b/src/components/agentic/StatisticalPanel.tsx @@ -0,0 +1,86 @@ +/** Deterministic statistics: rates, Wilson CIs, exact-binomial significance, + * seqeval sequential decision, power/MDE and small-sample flags. */ +import Box from '@mui/material/Box'; +import Chip from '@mui/material/Chip'; +import Paper from '@mui/material/Paper'; +import Typography from '@mui/material/Typography'; +import type { StatisticalAssessment } from '../../types/agentic'; +import { fmtCi, fmtRate, KV, PanelTitle } from './common'; + +export default function StatisticalPanel({ stat }: { stat: StatisticalAssessment }) { + return ( + + + } + /> + + + + + + + + + + + + + + + + + + + + {stat.small_sample_flags.length > 0 ? ( + + {stat.small_sample_flags.map((f) => ( + + ))} + + ) : null} + + {stat.rare_event_handling} + + + ); +} diff --git a/src/components/agentic/common.tsx b/src/components/agentic/common.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9ce111a58218526de06f3af9e591bc476a3866e6 --- /dev/null +++ b/src/components/agentic/common.tsx @@ -0,0 +1,145 @@ +/** Shared chips + labels for the Launch Readiness UI. */ +import Box from '@mui/material/Box'; +import Chip from '@mui/material/Chip'; +import Tooltip from '@mui/material/Tooltip'; +import Typography from '@mui/material/Typography'; +import type { EvidenceStatus, PolicyOutcome, Severity } from '../../types/agentic'; + +export const SEVERITY_COLORS: Record = { + S0: '#455a64', + S1: '#546e7a', + S2: '#f9a825', + S3: '#ef6c00', + S4: '#d84315', + S5: '#b71c1c', +}; + +export const OUTCOME_STYLE: Record = { + AUTOMATIC_STOP_SHIP: { bg: '#b71c1c', fg: '#fff', label: 'AUTOMATIC STOP-SHIP' }, + LAUNCH_REVIEW_REQUIRED: { bg: '#e65100', fg: '#fff', label: 'LAUNCH REVIEW REQUIRED' }, + CONTINUE_INVESTIGATION: { bg: '#0d47a1', fg: '#90caf9', label: 'CONTINUE INVESTIGATION' }, + NO_LAUNCH_IMPACT: { bg: '#1b5e20', fg: '#a5d6a7', label: 'NO LAUNCH IMPACT' }, + INDETERMINATE: { bg: '#4a148c', fg: '#ce93d8', label: 'INDETERMINATE (FAIL-SAFE)' }, +}; + +export const EVIDENCE_STATUS_COLORS: Record = { + OBSERVED: '#2e7d32', + DERIVED: '#0277bd', + HYPOTHESIS: '#f9a825', + UNAVAILABLE: '#757575', +}; + +export function SeverityChip({ severity }: { severity: Severity | null | undefined }) { + if (!severity) return ; + return ( + + ); +} + +export function OutcomeChip({ outcome }: { outcome: PolicyOutcome | null | undefined }) { + if (!outcome) return ; + const s = OUTCOME_STYLE[outcome]; + return ( + + ); +} + +export function EvidenceStatusChip({ status }: { status: EvidenceStatus }) { + return ( + + ); +} + +/** Marks a value as AI analysis (advisory) vs a deterministic measurement. */ +export function OriginBadge({ origin }: { origin: 'ai' | 'deterministic' }) { + const isAi = origin === 'ai'; + return ( + + + + ); +} + +export function PanelTitle({ + title, + origin, + extra, +}: { + title: string; + origin?: 'ai' | 'deterministic'; + extra?: React.ReactNode; +}) { + return ( + + + {title} + + {origin ? : null} + {extra} + + ); +} + +export function KV({ k, v, mono }: { k: string; v: React.ReactNode; mono?: boolean }) { + return ( + + + {k} + + + {v} + + + ); +} + +export const fmtRate = (r: number | null | undefined): string => + r === null || r === undefined ? '—' : r === 0 ? '0' : r.toExponential(3); + +export const fmtCi = (ci: number[] | null | undefined): string => + ci && ci.length === 2 ? `[${fmtRate(ci[0])}, ${fmtRate(ci[1])}]` : '—'; diff --git a/src/components/engines/BevFrameCanvas.tsx b/src/components/engines/BevFrameCanvas.tsx new file mode 100644 index 0000000000000000000000000000000000000000..65e21ce5f28e30486431bd7fab50ce920a333de1 --- /dev/null +++ b/src/components/engines/BevFrameCanvas.tsx @@ -0,0 +1,369 @@ +/** + * Interactive top-down BEV canvas for one perception frame: GT boxes, camera + * detections with along-ray uncertainty ellipses, LiDAR detections, fused + * boxes (masklet-propagated ones dashed), with hover details and + * click-to-follow-track across frames. Built on the shared CanvasSurface + * (pan/zoom) primitive. + */ +import { useMemo, useState } from 'react'; +import Box from '@mui/material/Box'; +import Chip from '@mui/material/Chip'; +import Typography from '@mui/material/Typography'; +import CanvasSurface from '../visual/canvas'; +import type { BevDetection, BevFusedBox, BevGtBox, BevReplayFrame } from '../../services/bevfusion'; +import { tokens } from '../../theme'; + +export const LAYER_META = { + gt: { label: 'Ground truth', color: '#e6e9ec' }, + camera: { label: 'Camera dets + uncertainty', color: '#ffa726' }, + lidar: { label: 'LiDAR dets', color: '#26c6da' }, + fused: { label: 'Fused (tracked)', color: '#66bb6a' }, + masklet: { label: 'Masklet-propagated', color: '#ab47bc' }, + baseline: { label: 'Camera baseline', color: '#ef5350' }, +} as const; + +export type LayerId = keyof typeof LAYER_META; + +const CLASS_COLORS: Record = { + vehicle: '#66bb6a', + truck: '#9ccc65', + pedestrian: '#ff7043', + cyclist: '#ffca28', + motorcycle: '#ec407a', +}; + +export interface HoverInfo { + kind: 'gt' | 'camera' | 'lidar' | 'fused' | 'baseline'; + title: string; + lines: string[]; +} + +// World: x forward 0..80m (drawn rightward), y left/right ±25m (drawn vertically). +const WORLD = { x: -4, y: -25, w: 88, h: 50 }; + +/** 1-sigma covariance ellipse parameters from a 2x2 covariance matrix. */ +function covEllipse(cov: [[number, number], [number, number]]): { rx: number; ry: number; angleDeg: number } { + const [[a, b], [, d]] = cov; + const tr = a + d; + const det = a * d - b * b; + const disc = Math.sqrt(Math.max(0, (tr * tr) / 4 - det)); + const l1 = tr / 2 + disc; + const l2 = tr / 2 - disc; + const angle = Math.atan2(l1 - a, b || 1e-9); + return { rx: Math.sqrt(Math.max(l1, 1e-6)), ry: Math.sqrt(Math.max(l2, 1e-6)), angleDeg: (angle * 180) / Math.PI }; +} + +function OrientedBox({ + x, + y, + l, + w, + yaw, + stroke, + fill = 'none', + dashed = false, + strokeWidth = 0.22, + onEnter, + onLeave, + onClick, + highlight = false, +}: { + x: number; + y: number; + l: number; + w: number; + yaw: number; + stroke: string; + fill?: string; + dashed?: boolean; + strokeWidth?: number; + onEnter?: () => void; + onLeave?: () => void; + onClick?: () => void; + highlight?: boolean; +}) { + // ego frame: +x forward, +y left. Screen: x → right, y → down = -world y. + const deg = (-yaw * 180) / Math.PI; + return ( + { + if (onClick) { + e.stopPropagation(); + onClick(); + } + }} + style={{ cursor: onClick ? 'pointer' : undefined }} + > + + {/* heading tick */} + + + ); +} + +interface BevFrameCanvasProps { + frame: BevReplayFrame; + layers: Record; + selectedTrackId: number | string | null; + onSelectTrack: (id: number | string | null) => void; + /** Track trail of the selected track: positions up to the current frame. */ + trail: Array<{ x: number; y: number }>; + onHover: (info: HoverInfo | null) => void; + height?: number; +} + +export default function BevFrameCanvas({ frame, layers, selectedTrackId, onSelectTrack, trail, onHover, height = 460 }: BevFrameCanvasProps) { + const [hoverKey, setHoverKey] = useState(null); + + const hover = (key: string | null, info: HoverInfo | null) => { + setHoverKey(key); + onHover(info); + }; + + const gtBoxes = useMemo(() => frame.gt, [frame]); + + return ( + onSelectTrack(null)}> + {() => ( + <> + {/* range rings + ego */} + {[20, 40, 60, 80].map((r) => ( + + + {r}m + + ))} + {/* ego vehicle */} + + + EGO + + + {/* selected-track trail */} + {trail.length > 1 ? ( + `${p.x},${-p.y}`).join(' ')} + fill="none" + stroke="#fff" + strokeWidth={0.18} + strokeDasharray="0.5 0.5" + opacity={0.8} + /> + ) : null} + + {/* GT */} + {layers.gt + ? gtBoxes.map((g: BevGtBox) => { + const [x, y, , l, w, , yaw] = g.bbox_3d; + const key = `gt-${g.instance_id}`; + return ( + + hover(key, { + kind: 'gt', + title: `GT · ${g.class_name}`, + lines: [ + `instance ${g.instance_id.split('-').slice(-2).join('-')}`, + `position (${x.toFixed(1)}, ${y.toFixed(1)}) m · ${g.distance.toFixed(1)} m away`, + g.occluded ? 'camera line-of-sight OCCLUDED this frame' : 'visible to camera', + ], + }) + } + onLeave={() => hover(null, null)} + /> + ); + }) + : null} + + {/* camera detections + uncertainty ellipses */} + {layers.camera + ? frame.camera.map((d: BevDetection, i: number) => { + const e = covEllipse(d.cov); + const key = `cam-${i}`; + return ( + + hover(key, { + kind: 'camera', + title: `Camera det · ${d.class_name}`, + lines: [ + `position (${d.x.toFixed(1)}, ${d.y.toFixed(1)}) m · conf ${d.confidence.toFixed(2)}`, + `1σ uncertainty ${e.rx.toFixed(1)} m along ray × ${e.ry.toFixed(1)} m across`, + 'monocular depth: uncertainty stretches along the camera ray', + ], + }) + } + onPointerLeave={() => hover(null, null)} + > + + + + ); + }) + : null} + + {/* lidar detections */} + {layers.lidar + ? frame.lidar.map((d: BevDetection, i: number) => { + const key = `lid-${i}`; + const s = 0.55; + return ( + + hover(key, { + kind: 'lidar', + title: `LiDAR det · ${d.class_name}`, + lines: [ + `position (${d.x.toFixed(1)}, ${d.y.toFixed(1)}) m · conf ${d.confidence.toFixed(2)}`, + 'tight isotropic position uncertainty; weak semantics (geometry templates)', + ], + }) + } + onPointerLeave={() => hover(null, null)} + > + + + + ); + }) + : null} + + {/* camera baseline boxes */} + {layers.baseline + ? frame.baseline.map((b: BevFusedBox, i: number) => { + const [x, y, , l, w, , yaw] = b.bbox_3d; + const key = `base-${i}`; + return ( + + hover(key, { + kind: 'baseline', + title: `Baseline (camera-only) · ${b.class_name}`, + lines: [ + `track #${b.track_id} · conf ${b.confidence.toFixed(2)}`, + 'greedy frame-to-frame association — IDs churn on dropouts', + ], + }) + } + onLeave={() => hover(null, null)} + /> + ); + }) + : null} + + {/* fused boxes (masklet propagated = dashed) */} + {frame.fused.map((b: BevFusedBox, i: number) => { + const show = b.propagated ? layers.masklet : layers.fused; + if (!show) return null; + const [x, y, , l, w, , yaw] = b.bbox_3d; + const key = `fused-${i}`; + const selected = selectedTrackId !== null && b.track_id === selectedTrackId; + const color = b.propagated ? LAYER_META.masklet.color : CLASS_COLORS[b.class_name] ?? LAYER_META.fused.color; + return ( + + + hover(key, { + kind: 'fused', + title: `Fused · ${b.class_name}${b.propagated ? ' (masklet-propagated)' : ''}`, + lines: [ + `track #${b.track_id} · conf ${b.confidence.toFixed(2)} · (${x.toFixed(1)}, ${y.toFixed(1)}) m`, + b.propagated + ? 'no detection this frame — box carried by the masklet motion model' + : 'decoded from the fused camera+LiDAR BEV grid', + 'click to follow this track across frames', + ], + }) + } + onLeave={() => hover(null, null)} + onClick={() => onSelectTrack(selected ? null : b.track_id)} + /> + + #{b.track_id} + + + ); + })} + + )} + + ); +} + +export function CanvasLegend({ layers, onToggle }: { layers: Record; onToggle: (l: LayerId) => void }) { + return ( + + {(Object.keys(LAYER_META) as LayerId[]).map((l) => ( + onToggle(l)} + sx={{ + height: 22, + fontSize: 11, + cursor: 'pointer', + bgcolor: layers[l] ? `${LAYER_META[l].color}26` : 'transparent', + color: layers[l] ? LAYER_META[l].color : tokens.color.textFaint, + border: `1px solid ${layers[l] ? LAYER_META[l].color : tokens.color.border}`, + textDecoration: layers[l] ? 'none' : 'line-through', + transition: `all ${tokens.motion.fast}`, + }} + /> + ))} + + scroll to zoom · drag background to pan · hover any object · click a fused box to follow its track + + + ); +} diff --git a/src/components/help/HelpMenu.tsx b/src/components/help/HelpMenu.tsx index 2119f54cb90c3d9f99bf54ba3fa4e71b86e85229..9ccf6325c1baa1d0c23d88054d70acdb1b0d2da2 100644 --- a/src/components/help/HelpMenu.tsx +++ b/src/components/help/HelpMenu.tsx @@ -185,9 +185,23 @@ const PAGE_ORDER: PageId[] = [ 'audit', 'pipeline', 'hillclimb', - 'retro', 'vitis', 'ssam', + 'my-dashboard', + 'scenario-composer', + 'pipeline-builder', + 'seqeval', + 'bevfusion', + 'safety-odd', + 'safety-gates', + 'safety-evidence', + 'safety-ssam', + 'safety-calibration', + 'safety-discrepancy', + 'safety-scenarios', + 'safety-search', + 'retro', + 'launch-readiness', 'legacy', ]; @@ -209,9 +223,23 @@ const PAGE_NAMES: Record = { audit: 'Audit', pipeline: 'Pipeline Architecture', hillclimb: 'Hill Climbing EM', - retro: 'Retrospective Analyzer', vitis: 'Hardware Acceleration', ssam: 'SSAM Safety', + 'safety-odd': 'ODD Coverage', + 'safety-gates': 'Release Gates', + 'safety-evidence': 'Evidence Package', + 'safety-ssam': 'SSAM Conflicts', + 'safety-calibration': 'Calibration', + 'safety-discrepancy': 'Discrepancy Mining', + 'safety-scenarios': 'Scenario DB', + 'safety-search': 'Semantic Search', + seqeval: 'Sequential Regression', + bevfusion: 'Perception Engines', + 'scenario-composer': 'Scenario Composer', + 'pipeline-builder': 'Pipeline Builder', + 'my-dashboard': 'My Dashboard', + retro: 'Retrospective Analyzer', + 'launch-readiness': 'Launch Readiness', legacy: 'Legacy Studio', };