Spaces:
Paused
Paused
Deploy Sensorflow Studio (part 4)
Browse filesFiles changed (12)
- tests/test_rotr/__init__.pyAdded
- tests/test_rotr/conftest.pyAdded+46
- tests/test_rotr/test_api.pyAdded+151
- tests/test_rotr/test_attribution.pyAdded+99
- tests/test_rotr/test_consequence.pyAdded+67
- tests/test_rotr/test_flywheel.pyAdded+80
- tests/test_rotr/test_metrics.pyAdded+99
- tests/test_rotr/test_regression.pyAdded+64
- tests/test_rotr/test_rules.pyAdded+48
- tests/test_rotr/test_scenes.pyAdded+74
- tests/test_rotr/test_stopship.pyAdded+71
- tests/test_rotr/test_taxonomy.pyAdded+96
12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Isolated persistence roots per test (rotr always; studio2/agentic whenimportable, since the flywheel/stop-ship mirror into them best-effort)."""
from __future__ import annotations
import pytest
from sensorflow.rotr import store as rotr_store
@pytest.fixture(autouse=True)def rotr_env(tmp_path): rotr_store.set_rotr_root(str(tmp_path / "rotr")) restores = [] try: from sensorflow.studio2 import store as s2_store old = s2_store.STUDIO2_ROOT s2_store.set_studio2_root(str(tmp_path / "studio2")) restores.append(lambda: s2_store.set_studio2_root(old)) except Exception: pass try: from sensorflow.agentic import store as ag_store old_ag = ag_store.agentic_root() ag_store.set_agentic_root(str(tmp_path / "agentic")) restores.append(lambda: ag_store.set_agentic_root(old_ag)) except Exception: pass yield rotr_store.set_rotr_root("runs/rotr") for r in restores: r()
@pytest.fixture(scope="session")def bank_v1(): """Deterministic in-memory bank (no store dependency).""" from sensorflow.rotr.scenes import generate_bank return generate_bank(n_scenarios=28, seed=7, model_version="stack-v1")
@pytest.fixture(scope="session")def detections_v1(bank_v1): """Scenario -> violations for the seeded bank (pure, in memory).""" from sensorflow.rotr.rules import detect return {sc.scenario_id: detect(sc) for sc in bank_v1}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151"""API lifecycle over an isolated router: bank -> run -> query ->attribution -> consequence -> HITL -> flywheel -> gate."""
from __future__ import annotations
import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient
from sensorflow.rotr.api import router
SPEC_QUERY = ("failed to yield to pedestrian at uncontrolled intersection " "during low visibility")
@pytest.fixture()def client(): app = FastAPI() app.include_router(router) return TestClient(app)
@pytest.fixture()def run(client): r = client.post("/api/rotr/runs", json={"n_scenarios": 28, "seed": 7, "model_version": "stack-v1"}) assert r.status_code == 200, r.text return r.json()
class TestLifecycle: def test_health_and_rules(self, client): assert client.get("/api/rotr/health").json()["status"] == "ok" rules = client.get("/api/rotr/rules").json() assert len(rules["rules"]) == 6 assert "ILLUSTRATIVE" in rules["config_note"]
def test_bank_endpoints(self, client): r = client.post("/api/rotr/banks", json={"n_scenarios": 14, "seed": 3, "model_version": "stack-v1"}) assert r.status_code == 200 bank = r.json() assert client.get(f"/api/rotr/banks/{bank['bank_id']}").status_code == 200 sid = bank["scenarios"][0]["scenario_id"] sc = client.get(f"/api/rotr/banks/{bank['bank_id']}/scenarios/{sid}").json() assert sc["ego"] and sc["actual_context"] assert client.post("/api/rotr/banks", json={"model_version": "nope"}).status_code == 422
def test_run_and_metrics(self, client, run): assert run["metrics"]["rotr_recall"] == 1.0 assert run["metrics"]["false_accusation_rate"] == 0.0 assert run["gate"]["outcome"] == "NO_GO" got = client.get(f"/api/rotr/runs/{run['run_id']}").json() assert got["run_id"] == run["run_id"] assert client.get("/api/rotr/runs").json()
def test_violation_listing_and_taxonomy_filters(self, client, run): rid = run["run_id"] allv = client.get(f"/api/rotr/runs/{rid}/violations").json() assert allv["n_results"] > 0 vru = client.get(f"/api/rotr/runs/{rid}/violations", params={"vulnerability": "VRU"}).json() assert 0 < vru["n_results"] < allv["n_results"] assert all(x["taxonomy"]["vulnerability"] == "VRU" for x in vru["results"])
def test_spec_structured_query(self, client, run): r = client.post("/api/rotr/query", json={"run_id": run["run_id"], "text": SPEC_QUERY}) assert r.status_code == 200 out = r.json() assert out["query"]["actor"] == "pedestrian" assert out["query"]["visibility"] == "low" assert out["n_results"] >= 1 for item in out["results"]: assert item["taxonomy"]["legality"] == "YIELD" assert item["environment"]["visibility"] == "low" assert item["cluster_id"] assert item["provenance"]["model_version"] == "stack-v1"
def test_attribution_matrix_and_consequence(self, client, run): rid = run["run_id"] matrix = client.get(f"/api/rotr/runs/{rid}/attribution").json() assert matrix["rows"] row = matrix["rows"][0] assert set(row["layers"]) == { "perception", "prediction", "planning", "localization", "map", "control", "policy_rule", "data_label"} vid = row["violation_id"] detail = client.get(f"/api/rotr/runs/{rid}/violations/{vid}").json() assert detail["attribution"]["primary_layer"] cf = client.get( f"/api/rotr/runs/{rid}/violations/{vid}/consequence").json() assert cf["planner_evaluation"]["observed_trajectory"] assert cf["planner_evaluation"]["corrected_trajectory"] assert "scenario_geometry" in cf
def test_clusters_and_gate(self, client, run): rid = run["run_id"] clusters = client.get(f"/api/rotr/runs/{rid}/clusters").json() assert clusters and clusters[0]["count"] >= 1 gate = client.get(f"/api/rotr/runs/{rid}/gate").json() assert gate["outcome"] in ("GO", "NO_GO") policy = client.get("/api/rotr/stopship/policy").json() assert policy["policy_version"]
class TestHITLAndFlywheel: def test_validate_then_guard_then_override(self, client, run): rid = run["run_id"] queue = client.get(f"/api/rotr/runs/{rid}/hitl").json() assert queue and queue[0]["status"] == "PENDING" review = queue[0]
r = client.post("/api/rotr/hitl/action", json={"run_id": rid, "review_id": review["review_id"], "action": "VALIDATE", "actor": "reviewer", "notes": "confirmed"}) assert r.status_code == 200 cand = r.json()["candidate"] assert cand["dataset_role"] == "REGRESSION"
suite = client.get("/api/rotr/flywheel/suite").json() assert any(m["candidate_id"] == cand["candidate_id"] for m in suite["members"])
promote = client.post("/api/rotr/flywheel/promote", json={"candidate_id": cand["candidate_id"], "actor": "sneaky"}) assert promote.status_code == 409 # contamination guard
override = client.post("/api/rotr/flywheel/override", json={"candidate_id": cand["candidate_id"], "actor": "safety-lead", "reason": "governed exception"}) assert override.status_code == 200 promote2 = client.post("/api/rotr/flywheel/promote", json={"candidate_id": cand["candidate_id"], "actor": "lead"}) assert promote2.status_code == 200 assert promote2.json()["guard_state"] == "OVERRIDDEN"
class TestDocs: def test_architecture_doc_served(self, client): r = client.get("/api/rotr/docs/architecture") assert r.status_code == 200 assert "Right-of-the-Road" in r.json()["markdown"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Causal-layer attribution: planted-cause correctness per layer, and thepackage's core invariant — a violation is NEVER auto-attributed toperception."""
from __future__ import annotations
import pytest
from sensorflow.rotr.attribution import attribute
@pytest.fixture(scope="module")def attributions(bank_v1, detections_v1): out = [] for sc in bank_v1: for v in detections_v1[sc.scenario_id]: out.append((sc, v, attribute(sc, v))) return out
def _cases(attributions, cause): return [(sc, v, a) for sc, v, a in attributions if sc.planted.cause_layer == cause]
class TestPlantedCauses: def test_every_planted_cause_matches_primary_layer(self, attributions): for sc, v, a in attributions: assert a.primary_layer == sc.planted.cause_layer, \ (f"{v.violation_id}: planted {sc.planted.cause_layer}, " f"attributed {a.primary_layer}")
def test_planning_error_with_perfect_perception(self, attributions): """THE keystone case: a planted planning fault where perception was perfect must attribute to planning with perception RULED_OUT.""" cases = _cases(attributions, "planning") assert cases, "bank must contain planning-cause violations" for sc, v, a in cases: assert a.primary_layer == "planning" assert a.layers["perception"].status == "RULED_OUT" assert a.layers["planning"].status == "SUPPORTED" assert "OWN world view" in a.layers["planning"].evidence
def test_map_error_case(self, attributions): cases = _cases(attributions, "map") assert cases for sc, v, a in cases: assert a.primary_layer == "map" assert a.layers["map"].status == "SUPPORTED" # The plan was compliant with the (wrong) map: planning ruled out. assert a.layers["planning"].status == "RULED_OUT"
def test_localization_error_case(self, attributions): cases = _cases(attributions, "localization") assert cases for sc, v, a in cases: assert a.primary_layer == "localization" assert a.layers["localization"].status == "SUPPORTED" assert a.layers["perception"].status == "RULED_OUT"
def test_control_error_case(self, attributions): cases = _cases(attributions, "control") assert cases for sc, v, a in cases: assert a.primary_layer == "control" assert a.layers["control"].status == "SUPPORTED" assert a.layers["planning"].status == "RULED_OUT"
def test_prediction_error_case(self, attributions): cases = _cases(attributions, "prediction") assert cases for sc, v, a in cases: assert a.primary_layer == "prediction" assert a.layers["perception"].status == "RULED_OUT"
def test_data_label_case_keeps_unassessable_layers_unknown(self, attributions): cases = _cases(attributions, "data_label") assert cases for sc, v, a in cases: assert a.primary_layer == "data_label" assert a.layers["perception"].status == "UNKNOWN" assert a.layers["prediction"].status == "UNKNOWN"
class TestNoAutoPerception: def test_perception_primary_requires_positive_perception_evidence( self, attributions): for sc, v, a in attributions: if a.primary_layer == "perception": assert a.layers["perception"].status == "SUPPORTED"
def test_tri_state_everywhere(self, attributions): for _, _, a in attributions: assert set(a.layers) == {"perception", "prediction", "planning", "localization", "map", "control", "policy_rule", "data_label"} for le in a.layers.values(): assert le.status in ("SUPPORTED", "RULED_OUT", "UNKNOWN") assert le.evidence12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""Counterfactual consequence: cosmetic violations classify asNO_MATERIAL_CONSEQUENCE; a missed crossing pedestrian is SAFETY_CRITICAL;every verdict carries measured evidence from both branches."""
from __future__ import annotations
import pytest
from sensorflow.rotr.attribution import attributefrom sensorflow.rotr.consequence import classify
@pytest.fixture(scope="module")def classified(bank_v1, detections_v1): out = {} for sc in bank_v1: for v in detections_v1[sc.scenario_id]: attr = attribute(sc, v) out[v.violation_id] = (sc, v, attr, classify(sc, v, attr)) return out
def _by_kind_cause(classified, kind, cause): return [t for t in classified.values() if t[0].planted.kind == kind and t[0].planted.cause_layer == cause]
class TestClasses: def test_missed_crossing_pedestrian_is_safety_critical(self, classified): cases = _by_kind_cause(classified, "fail_yield_pedestrian", "perception") assert cases for sc, v, attr, cf in cases: assert cf.consequence_class == "SAFETY_CRITICAL" assert cf.observed_safety.min_clearance_m is not None assert cf.observed_safety.min_clearance_m < 1.5
def test_cosmetic_wrong_lane_is_no_material_consequence(self, classified): cases = _by_kind_cause(classified, "wrong_lane_association", "localization") assert cases for sc, v, attr, cf in cases: assert cf.consequence_class == "NO_MATERIAL_CONSEQUENCE" assert cf.planner_evaluation.max_position_divergence_m < 2.0
def test_control_fault_replays_the_plan(self, classified): cases = _by_kind_cause(classified, "stop_overshoot", "control") assert cases for sc, v, attr, cf in cases: assert cf.planner_evaluation.engine == "planned-trajectory" assert cf.consequence_class != "NO_MATERIAL_CONSEQUENCE"
class TestEvidence: def test_both_branches_measured(self, classified): for sc, v, attr, cf in classified.values(): pe = cf.planner_evaluation assert pe.observed_trajectory and pe.corrected_trajectory assert pe.engine for sa in (cf.observed_safety, cf.corrected_safety): assert sa.max_braking_mps2 >= 0.0 assert "surrogate" in sa.surrogate_caveat.lower() or \ "TTC" in sa.surrogate_caveat
def test_counterfactual_provenance_labeled(self, classified): for sc, v, attr, cf in classified.values(): assert cf.provenance.source == "COUNTERFACTUAL" assert cf.corrected_layers1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Flywheel governance: HITL -> regression artifact with an immutableprotected role; the contamination guard refuses training promotion withouta recorded override."""
from __future__ import annotations
import pytest
from sensorflow.rotr import flywheelfrom sensorflow.rotr.flywheel import ContaminationError
def _seed_queue(): violations = [{"violation_id": "v1", "scenario_id": "s1"}, {"violation_id": "v2", "scenario_id": "s2"}] clusters = [{"cluster_id": "cl-1", "member_violation_ids": ["v1", "v2"], "exemplar_violation_id": "v1"}] return flywheel.build_queue("run-t", violations, clusters)
class TestHITL: def test_queue_carries_cluster_context(self): reviews = _seed_queue() assert all(r.status == "PENDING" for r in reviews) assert all(r.cluster_id == "cl-1" for r in reviews)
def test_validate_creates_protected_regression_artifact(self): _seed_queue() out = flywheel.act("run-t", "rev-v1", "VALIDATE", actor="reviewer-a", notes="confirmed failure to yield") cand = out["candidate"] assert cand["dataset_role"] == "REGRESSION" assert cand["training_eligible"] is False assert cand["guard_state"] == "PROTECTED" suite = flywheel.get_suite() assert any(m["violation_id"] == "v1" for m in suite["members"]) assert suite["members"][0]["role"] == "REGRESSION"
def test_reject_creates_no_artifact(self): _seed_queue() out = flywheel.act("run-t", "rev-v2", "REJECT", actor="reviewer-a") assert out["candidate"] is None assert out["review"]["status"] == "REJECTED"
def test_double_action_refused(self): _seed_queue() flywheel.act("run-t", "rev-v1", "VALIDATE", actor="a") with pytest.raises(ValueError): flywheel.act("run-t", "rev-v1", "REJECT", actor="b")
class TestContaminationGuard: def test_protected_member_never_training_eligible_without_override(self): _seed_queue() cand = flywheel.act("run-t", "rev-v1", "VALIDATE", actor="a")["candidate"] with pytest.raises(ContaminationError): flywheel.promote_to_training(cand["candidate_id"], actor="sneaky") # still protected after the refused attempt doc = flywheel.get_candidate(cand["candidate_id"]) assert doc["training_eligible"] is False
def test_recorded_override_unlocks_promotion_with_audit(self): _seed_queue() cand = flywheel.act("run-t", "rev-v1", "VALIDATE", actor="a")["candidate"] with pytest.raises(ValueError): flywheel.governance_override(cand["candidate_id"], "lead", " ") flywheel.governance_override(cand["candidate_id"], "safety-lead", "rare-event class needed in training; " "duplicate coverage retained in suite") doc = flywheel.promote_to_training(cand["candidate_id"], actor="lead") assert doc["training_eligible"] is True assert doc["guard_state"] == "OVERRIDDEN" assert doc["override"]["actor"] == "safety-lead"
def test_guard_exception_interops_with_raremine_semantics(self): try: from sensorflow.raremine.lineage import LeakageError except Exception: pytest.skip("raremine unavailable") assert issubclass(ContaminationError, LeakageError)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Metric math: recall/false-accusation denominators, exposure-derivedweight calibration (monotone in measured harm), BCR/CFR."""
from __future__ import annotations
from sensorflow.rotr.metrics import compute_metrics
def _scenario(sid, kind="k", committed=True, opportunity=True, rule="R-X", vul="NON_VRU", vis="clear", light="day"): return {"scenario_id": sid, "kind": kind, "committed": committed, "is_violation_opportunity": opportunity, "expected_rule_id": rule if committed else None, "cause_layer": "planning" if committed else None, "vulnerability": vul, "visibility": vis, "lighting": light, "weather": "clear", "n_violations_detected": 0}
def _violation(vid, sid, rule="R-X"): return {"violation_id": vid, "scenario_id": sid, "rule_id": rule, "taxonomy": {}}
class TestRecallMath: def test_recall_and_false_accusations(self): scenarios = [ _scenario("s1", committed=True), _scenario("s2", committed=True), _scenario("s3", committed=False, opportunity=False), _scenario("s4", committed=False, opportunity=False), ] violations = [_violation("v1", "s1"), # true positive _violation("v3", "s3")] # false accusation m = compute_metrics(scenarios, violations, {}) assert m["rotr_recall"] == 0.5 # 1 of 2 committed found assert m["false_accusation_rate"] == 0.5 # 1 of 2 negatives accused assert m["n_committed_violations"] == 2 assert m["n_planted_non_violations"] == 2
def test_behavior_rates_use_opportunity_denominator(self): scenarios = [ _scenario("s1", committed=True, vul="VRU"), _scenario("s2", committed=False, opportunity=True, vul="VRU"), _scenario("s3", committed=False, opportunity=False), ] m = compute_metrics(scenarios, [], {}) assert m["behavior_rates"]["VRU"] == { "opportunities": 2, "committed": 1, "violation_rate": 0.5} assert m["behavior_rates"]["ALL"]["opportunities"] == 2
class TestWeightCalibration: def test_weights_monotone_in_measured_harm(self): # Stratum A: 2/2 safety-critical; stratum B: 0/2. scenarios = [ _scenario("a1", kind="A", vul="VRU"), _scenario("a2", kind="A", vul="VRU"), _scenario("b1", kind="B"), _scenario("b2", kind="B"), ] violations = [_violation(f"v-{s}", s) for s in ("a1", "a2", "b1", "b2")] consequences = { "v-a1": {"consequence_class": "SAFETY_CRITICAL"}, "v-a2": {"consequence_class": "SAFETY_CRITICAL"}, "v-b1": {"consequence_class": "NO_MATERIAL_CONSEQUENCE"}, "v-b2": {"consequence_class": "DEGRADED_COMFORT"}, } m = compute_metrics(scenarios, violations, consequences) strata = m["weight_calibration"]["strata"] wa = strata["A|VRU"]["weight"] wb = strata["B|NON_VRU"]["weight"] assert strata["A|VRU"]["harm_fraction"] > strata["B|NON_VRU"]["harm_fraction"] assert wa > wb, "higher measured harm must never get a lower weight" assert m["weight_calibration"]["method"].startswith("stratum weight") assert "ILLUSTRATIVE" in m["weight_calibration"]["method"]
def test_zero_harm_strata_get_floor_not_zero(self): scenarios = [_scenario("a1", kind="A"), _scenario("b1", kind="B")] violations = [_violation("v-a1", "a1"), _violation("v-b1", "b1")] consequences = { "v-a1": {"consequence_class": "SAFETY_CRITICAL"}, "v-b1": {"consequence_class": "NO_MATERIAL_CONSEQUENCE"}} m = compute_metrics(scenarios, violations, consequences) assert m["weight_calibration"]["strata"]["B|NON_VRU"]["weight"] == 0.1
class TestRates: def test_bcr_and_cfr(self): scenarios = [_scenario(f"s{i}") for i in range(4)] violations = [_violation("v0", "s0"), _violation("v1", "s1")] consequences = { "v0": {"consequence_class": "SAFETY_CRITICAL"}, "v1": {"consequence_class": "NO_MATERIAL_CONSEQUENCE"}} m = compute_metrics(scenarios, violations, consequences) assert m["bcr"] == 0.5 # 1 of 2 detected is consequential assert m["cfr"] == 0.25 # 1 SC over 4 scenarios lo, hi = m["cfr_wilson_95"] assert 0.0 <= lo < 0.25 < hi <= 1.012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Baseline-vs-candidate regression: seqeval delegation verdicts and thesix-outcome distinction (slowest module: two 140-scenario runs + asequential test over a dedicated megaeval population)."""
from __future__ import annotations
import pytest
from sensorflow.rotr import pipelinefrom sensorflow.rotr import store as rotr_storefrom sensorflow.rotr.metrics import evaluate_candidate
@pytest.fixture(scope="module")def reg_env(tmp_path_factory): from sensorflow.megaeval import population as pop_mod from sensorflow.seqeval import ledger as ledger_mod from sensorflow.seqeval.controller import reset_seqeval_store
root = tmp_path_factory.mktemp("rotr_reg") pop_mod.set_mega_root(str(root / "mega")) ledger_mod.set_seqeval_root(str(root / "seq")) reset_seqeval_store() rotr_store.set_rotr_root(str(root / "rotr")) runs = { "v2": pipeline.execute_run(n_scenarios=140, seed=7, model_version="stack-v2-improved"), "v3": pipeline.execute_run(n_scenarios=140, seed=7, model_version="stack-v3-planning-regression"), } yield runs pop_mod.set_mega_root("runs/megaeval") ledger_mod.set_seqeval_root("runs/seqeval") reset_seqeval_store()
class TestSixOutcomes: def test_planted_planning_regression_is_caught_and_safety_critical(self, reg_env): r = evaluate_candidate("t-reg", reg_env["v2"], reg_env["v3"], seed=11) assert r.six_outcomes["observed_difference"] assert r.six_outcomes["statistically_significant"], \ f"seqeval said {r.seqeval and r.seqeval.get('decision')}" assert r.six_outcomes["practically_significant"] assert r.six_outcomes["safety_critical"] assert not r.six_outcomes["distribution_driven"], \ "same-seed banks share the opportunity mix" assert r.primary_outcome == "SAFETY_CRITICAL_REGRESSION" assert r.seqeval["decision"] == "REGRESSION" assert r.metric_deltas["violation_rate_VRU"] > 0
def test_self_comparison_shows_no_difference(self, reg_env): r = evaluate_candidate("t-self", reg_env["v2"], reg_env["v2"], seed=11) assert not r.six_outcomes["observed_difference"] assert not r.six_outcomes["statistically_significant"] assert not r.six_outcomes["safety_critical"] assert r.primary_outcome in ("NO_DIFFERENCE", "INSUFFICIENT_EVIDENCE")
def test_delegation_payload_is_attached_with_translated_effects(self, reg_env): r = evaluate_candidate("t-payload", reg_env["v2"], reg_env["v3"], seed=11) assert r.seqeval and "run_id" in r.seqeval eff = r.seqeval["translated_effects"] # rate increases translate to NEGATIVE performance effects assert eff["pedestrian|night"] < 0 assert eff["__global__"] < 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Rule engine: every planted violation found, every planted NON-violationrejected (no false accusations), deterministic output."""
from __future__ import annotations
from sensorflow.rotr.rules import RULESET_VERSION, detect
class TestPlantedViolations: def test_every_committed_violation_detected_with_expected_rule( self, bank_v1, detections_v1): for sc in bank_v1: if not sc.planted.committed: continue hits = detections_v1[sc.scenario_id] assert any(v.rule_id == sc.planted.expected_rule_id for v in hits), \ f"{sc.scenario_id} ({sc.planted.kind}) missed"
def test_violations_carry_structured_evidence_and_version( self, bank_v1, detections_v1): for sc in bank_v1: for v in detections_v1[sc.scenario_id]: assert v.rule_version == RULESET_VERSION assert v.evidence, "evidence fields required" assert "ruleset_fingerprint" in v.evidence assert 0.0 < v.confidence <= 1.0 assert v.provenance.model_version == "stack-v1"
class TestPlantedNonViolations: def test_no_false_accusations(self, bank_v1, detections_v1): """Lookalike scenarios (legal assertive merge, yield-with-ROW, green proceed) and non-committed variants must produce ZERO violations.""" for sc in bank_v1: if sc.planted.committed: continue assert detections_v1[sc.scenario_id] == [], \ f"false accusation on {sc.scenario_id} ({sc.planted.kind})"
class TestDeterminism: def test_detect_is_pure(self, bank_v1): sc = next(s for s in bank_v1 if s.planted.committed) a = [v.model_dump(exclude={"provenance"}) for v in detect(sc)] b = [v.model_dump(exclude={"provenance"}) for v in detect(sc)] assert a == b1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Scenario substrate: determinism, planted truth, environment taxonomy."""
from __future__ import annotations
import pytest
from sensorflow.rotr.scenes import MODEL_PROFILES, bank_id_for, generate_bank
class TestDeterminism: def test_same_inputs_identical_banks(self): a = generate_bank(14, seed=3, model_version="stack-v1") b = generate_bank(14, seed=3, model_version="stack-v1") # Wall-clock provenance timestamps are the only permitted difference. da = [s.model_dump(exclude={"provenance": {"timestamp"}}) for s in a] db = [s.model_dump(exclude={"provenance": {"timestamp"}}) for s in b] assert da == db
def test_seed_changes_bank_id_and_content(self): assert bank_id_for(14, 3, "stack-v1") != bank_id_for(14, 4, "stack-v1")
def test_model_version_changes_committed_pattern_not_geometry(self): v1 = generate_bank(28, seed=7, model_version="stack-v1") v2 = generate_bank(28, seed=7, model_version="stack-v2-improved") # Same opportunity mix (same seed) ... assert [s.planted.kind for s in v1] == [s.planted.kind for s in v2] # ... but a better perception stack commits fewer perception-caused. def committed_perception(bank): return sum(1 for s in bank if s.planted.committed and s.planted.cause_layer == "perception") assert committed_perception(v2) < committed_perception(v1)
def test_unknown_model_rejected(self): with pytest.raises(ValueError): generate_bank(4, seed=1, model_version="stack-vX")
class TestPlantedTruth: def test_bank_contains_violations_and_lookalike_non_violations(self, bank_v1): kinds = {s.planted.kind for s in bank_v1} assert {"fail_yield_pedestrian", "restricted_path_entry", "wrong_lane_association", "intersection_conflict", "unsafe_merge", "stop_overshoot"} <= kinds non_viol = {s.planted.kind for s in bank_v1 if not s.planted.is_violation_opportunity} assert {"legal_assertive_merge", "yield_with_right_of_way", "green_proceed"} <= non_viol
def test_non_opportunities_never_committed(self, bank_v1): for s in bank_v1: if not s.planted.is_violation_opportunity: assert not s.planted.committed assert s.planted.expected_rule_id is None
def test_environment_attributes_cover_low_visibility_yield_cases(self, bank_v1): # The spec's taxonomy query needs this cohort to exist. assert any(s.planted.kind == "fail_yield_pedestrian" and s.planted.committed and s.environment.visibility == "low" for s in bank_v1)
def test_provenance_complete(self, bank_v1): for s in bank_v1: p = s.provenance assert p.scenario_id == s.scenario_id assert p.dataset_version and p.model_version and p.software_version assert p.source == "SYNTHETIC"
class TestProfiles: def test_profiles_cover_all_planted_causes(self): causes = {"perception", "prediction", "planning", "localization", "map", "control", "data_label"} for profile in MODEL_PROFILES.values(): assert causes <= set(profile)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Stop-ship trigger: fires ONLY on the full deterministic conjunction."""
from __future__ import annotations
from sensorflow.rotr.stopship import ( STOPSHIP_POLICY, evaluate_gate, policy_version,)
def _item(vru=True, missed=True, sc=True, vid="v-1"): return { "violation_id": vid, "signature": {"vulnerability": "VRU" if vru else "NON_VRU"}, "attribution": {"layers": {"perception": { "status": "SUPPORTED" if missed else "RULED_OUT", "evidence": "actor: missed detection — GT visible" if missed else "detected fine"}}}, "consequence": {"consequence_class": "SAFETY_CRITICAL" if sc else "DEGRADED_COMFORT"}, }
class TestConjunction: def test_full_conjunction_fires_no_go(self): gate = evaluate_gate("run-x", [_item()], forward_to_agentic=False) assert gate.outcome == "NO_GO" assert any(e["fired"] for e in gate.events)
def test_any_two_of_three_do_not_fire(self): for kwargs in ({"vru": False}, {"missed": False}, {"sc": False}): gate = evaluate_gate("run-x", [_item(**kwargs)], forward_to_agentic=False) assert gate.outcome == "GO", f"fired on partial match {kwargs}"
def test_perception_supported_but_not_missed_does_not_fire(self): item = _item() item["attribution"]["layers"]["perception"]["evidence"] = \ "detected but mislocalized (mean |err| 1.4 m)" gate = evaluate_gate("run-x", [item], forward_to_agentic=False) assert gate.outcome == "GO"
def test_empty_run_is_go(self): gate = evaluate_gate("run-x", [], forward_to_agentic=False) assert gate.outcome == "GO" assert gate.events == []
class TestPolicy: def test_policy_version_is_content_hash(self): v = policy_version() assert v == policy_version() assert v != policy_version({**STOPSHIP_POLICY, "policy_semver": "9.9.9"}) assert len(v) == 16
def test_not_llm_driven_is_explicit_policy_text(self): assert "NOT LLM-driven" in STOPSHIP_POLICY["notes"]
class TestAgenticForwarding: def test_no_go_forwards_advisory_when_agentic_importable(self): gate = evaluate_gate("run-x", [_item()], forward_to_agentic=True) assert gate.outcome == "NO_GO" # agentic is a concurrent workstream: either a real advisory or an # honest 'unavailable' record — never a crash, never a changed gate. assert gate.agentic_advisory is not None assert "engine" in gate.agentic_advisory
def test_gate_outcome_never_depends_on_forwarding(self): a = evaluate_gate("run-x", [_item()], forward_to_agentic=False) b = evaluate_gate("run-x", [_item()], forward_to_agentic=True) assert a.outcome == b.outcome == "NO_GO"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Taxonomy signatures, the spec's structured query, and clustering."""
from __future__ import annotations
from sensorflow.rotr.taxonomy import ( build_clusters, cluster_key, matches, parse_query, signature,)
SPEC_QUERY = ("failed to yield to pedestrian at uncontrolled intersection " "during low visibility")
class TestSignature: def test_fail_yield_signature(self, bank_v1, detections_v1): sc = next(s for s in bank_v1 if s.planted.kind == "fail_yield_pedestrian" and s.planted.committed) v = detections_v1[sc.scenario_id][0] sig = signature(v, sc) assert sig["actor"] == "pedestrian" assert sig["vulnerability"] == "VRU" assert sig["legality"] == "YIELD" assert sig["behavior"] == "proceed_without_yield" assert sig["road_geometry"] == "uncontrolled" assert sig["interaction"] == "CROSSING"
class TestStructuredQuery: def test_spec_sentence_parses_to_filterable_object(self): q = parse_query(SPEC_QUERY) assert q.actor == "pedestrian" assert q.legality == "YIELD" assert q.road_geometry == "uncontrolled" assert q.visibility == "low" assert q.text == SPEC_QUERY
def test_query_matches_only_the_planted_cohort(self, bank_v1, detections_v1): q = parse_query(SPEC_QUERY) matched, unmatched_kinds = [], set() for sc in bank_v1: for v in detections_v1[sc.scenario_id]: sig = signature(v, sc) if matches(q, sig, None, None, {"lighting": sc.environment.lighting, "weather": sc.environment.weather}): matched.append((sc, v)) else: unmatched_kinds.add(sc.planted.kind) assert matched, "seeded bank must contain the spec cohort" for sc, v in matched: assert sc.planted.kind == "fail_yield_pedestrian" assert sc.environment.visibility == "low" assert sc.actual_context.intersection_type == "uncontrolled"
def test_consequence_and_layer_filters(self): q = parse_query("safety critical") assert q.consequence_class == "SAFETY_CRITICAL" assert matches(q, {}, "SAFETY_CRITICAL", None, {}) assert not matches(q, {}, "DEGRADED_COMFORT", None, {})
class TestClustering: def test_same_signature_clusters_together(self): items = [ {"violation_id": "v1", "primary_layer": "planning", "consequence_class": "SAFETY_CRITICAL", "signature": {"legality": "YIELD", "actor": "pedestrian", "traffic_control": "none", "behavior": "proceed_without_yield", "environment": "day/clear", "visibility": "low"}}, {"violation_id": "v2", "primary_layer": "planning", "consequence_class": "DEGRADED_COMFORT", "signature": {"legality": "YIELD", "actor": "pedestrian", "traffic_control": "none", "behavior": "proceed_without_yield", "environment": "night/rain", "visibility": "clear"}}, {"violation_id": "v3", "primary_layer": "perception", "consequence_class": "SAFETY_CRITICAL", "signature": {"legality": "MERGE", "actor": "vehicle", "traffic_control": "none", "behavior": "insufficient_gap_merge", "environment": "day/clear", "visibility": "clear"}}, ] clusters = build_clusters(items) assert len(clusters) == 2 big = clusters[0] assert big["count"] == 2 assert set(big["member_violation_ids"]) == {"v1", "v2"} assert len(big["environment_spread"]) == 2 assert big["consequence_distribution"] == {"SAFETY_CRITICAL": 1, "DEGRADED_COMFORT": 1}
def test_primary_layer_separates_clusters(self): sig = {"legality": "YIELD", "actor": "pedestrian", "traffic_control": "none", "behavior": "proceed_without_yield"} assert cluster_key(sig, "planning") != cluster_key(sig, "perception")tests/test_rotr/__init__.pyAdded
tests/test_rotr/conftest.pyAdded+46
tests/test_rotr/test_api.pyAdded+151
tests/test_rotr/test_attribution.pyAdded+99
tests/test_rotr/test_consequence.pyAdded+67
tests/test_rotr/test_flywheel.pyAdded+80
tests/test_rotr/test_metrics.pyAdded+99
tests/test_rotr/test_regression.pyAdded+64
tests/test_rotr/test_rules.pyAdded+48
tests/test_rotr/test_scenes.pyAdded+74
tests/test_rotr/test_stopship.pyAdded+71
tests/test_rotr/test_taxonomy.pyAdded+96