Spaces:
Paused
Paused
Deploy Sensorflow Studio (part 2)
Browse filesFiles changed (43)
- main.py+15-2
- sensorflow/evaluation/detectors.py+10-2
- sensorflow/evaluation/regression.py+65-12
- sensorflow/hardening/__init__.pyAdded+8
- sensorflow/hardening/api.pyAdded+261
- sensorflow/hardening/cache_manifest.pyAdded+184
- sensorflow/hardening/contracts.pyAdded+328
- sensorflow/hardening/hitl.pyAdded+134
- sensorflow/hardening/interfaces.pyAdded+315
- sensorflow/hardening/power.pyAdded+209
- sensorflow/hardening/quality.pyAdded+243
- sensorflow/hardening/readiness.pyAdded+141
- sensorflow/hardening/safety_config.pyAdded+150
- sensorflow/hardening/sampling.pyAdded+236
- sensorflow/megaeval/cube.py+8-2
- sensorflow/metrics/perception_3d.py+49-1
- sensorflow/metrics/temporal_mot.py+7-1
- sensorflow/mitl_copilot.py+21-4
- sensorflow/nextgen/__init__.pyAdded+55
- sensorflow/nextgen/api.pyAdded+329
- sensorflow/nextgen/cache.pyAdded+196
- sensorflow/nextgen/causal.pyAdded+137
- sensorflow/nextgen/closedloop.pyAdded+466
- sensorflow/nextgen/compute.pyAdded+181
- sensorflow/nextgen/counterfactual.pyAdded+631
- sensorflow/nextgen/lineage.pyAdded+62
- sensorflow/nextgen/models.pyAdded+220
- sensorflow/nextgen/regression.pyAdded+162
- sensorflow/nextgen/safety_metrics.pyAdded+263
- sensorflow/nextgen/scheduler.pyAdded+349
- sensorflow/nextgen/store.pyAdded+56
- sensorflow/nextgen/validity.pyAdded+454
- sensorflow/nextgen/worldmodel.pyAdded+105
- sensorflow/perception_automator.py+7-1
- sensorflow/quality_gate.py+29-5
- sensorflow/studio2/__init__.pyAdded+33
- sensorflow/studio2/api.pyAdded+294
- sensorflow/studio2/demo.pyAdded+274
- sensorflow/studio2/funnel.pyAdded+363
- sensorflow/studio2/hardware.pyAdded+331
- sensorflow/studio2/registry.pyAdded+492
- sensorflow/studio2/release_gate.pyAdded+319
- sensorflow/studio2/store.pyAdded+99
4 unmodified lines5678910207 unmodified lines21821922022122222325 unmodified lines24925025125225325425525625725825926026126226326426526626726826927027122 unmodified lines29429529629729829917 unmodified lines3173183193203213224 unmodified linesimport ioimport loggingfrom typing import Dict, Any, List, Optionalfrom fastapi import FastAPI, UploadFile, File, HTTPException, WebSocket, WebSocketDisconnectfrom fastapi.responses import HTMLResponse, JSONResponse207 unmodified linesif not file.filename or not file.filename.endswith(".csv"):raise HTTPException(status_code=400, detail="Only CSV datasets are accepted.")try:# Validate file size (limit to 50MB)content = await file.read()25 unmodified linesinsights = MockAccidentInsights(metrics)profile = insights.get_risk_profile()# Cache for sub-resource queries with TTL (1 hour)await engine_cache.set("latest", {"metrics": metrics,"insights": profile,"processing_time": len(clean_df) # for reference}, ttl=3600)# Broadcast trigger over WebSocketsbroadcast_message = f"New dataset processed. Total records: {len(clean_df)}. Risk index: {profile.get('risk_index', 'N/A')}"await manager.broadcast(broadcast_message)return {"status": "success","records_processed": len(clean_df),"quality_score": report.quality_score,"insights": profile,"processing_time_seconds": len(clean_df) # Add processing info}except pd.errors.EmptyDataError:22 unmodified linesreturn {"status": "success","hotspots": hotspots,"count": len(hotspots)}17 unmodified linesinsights = cached_data["insights"]return {"status": "success","insights": insights}except Exception as e:4 unmodified lines567891011207 unmodified lines21922022122222322422525 unmodified lines25125225325425525625725825926026126226326426526626726826927027127227327427527627727827928022 unmodified lines30330430530630730830931017 unmodified lines3283293303313323333343354 unmodified linesimport ioimport loggingimport timefrom typing import Dict, Any, List, Optionalfrom fastapi import FastAPI, UploadFile, File, HTTPException, WebSocket, WebSocketDisconnectfrom fastapi.responses import HTMLResponse, JSONResponse207 unmodified linesif not file.filename or not file.filename.endswith(".csv"):raise HTTPException(status_code=400, detail="Only CSV datasets are accepted.")t0 = time.perf_counter()try:# Validate file size (limit to 50MB)content = await file.read()25 unmodified linesinsights = MockAccidentInsights(metrics)profile = insights.get_risk_profile()elapsed = round(time.perf_counter() - t0, 4)# Cache for sub-resource queries with TTL (1 hour)await engine_cache.set("latest", {"metrics": metrics,"insights": profile,"processing_time": elapsed,}, ttl=3600)# Broadcast trigger over WebSocketsbroadcast_message = f"New dataset processed. Total records: {len(clean_df)}. Risk index: {profile.get('risk_index', 'N/A')}"await manager.broadcast(broadcast_message)# `simulated`/`analysis_provenance` mark that validation, analysis and# insights come from mock engines with constant outputs — the payload# must never present them as real analysis results.return {"status": "success","simulated": True,"analysis_provenance": "MOCK_ENGINE","records_processed": len(clean_df),"quality_score": report.quality_score,"insights": profile,"processing_time_seconds": elapsed,}except pd.errors.EmptyDataError:22 unmodified linesreturn {"status": "success","simulated": True,"analysis_provenance": "MOCK_ENGINE","hotspots": hotspots,"count": len(hotspots)}17 unmodified linesinsights = cached_data["insights"]return {"status": "success","simulated": True,"analysis_provenance": "MOCK_ENGINE","insights": insights}except Exception as e:
314 unmodified lines31531631731831932055 unmodified lines376377378379380381382383384385386387314 unmodified linesself.seed = seedself.detectors = self._build()self.scaler = StandardScaler()def _cfg(self, *path, default=None):node = self.config55 unmodified linesXs = self.scaler.fit_transform(X)raw: Dict[str, np.ndarray] = {}norm: Dict[str, np.ndarray] = {}for det in self.detectors:try:det.fit(Xs)s = det.score(Xs)except Exception:s = np.zeros(len(Xs))raw[det.name] = snorm[det.name] = normalize_scores(s)314 unmodified lines31531631731831932032132232355 unmodified lines379380381382383384385386387388389390391392393394395314 unmodified linesself.seed = seedself.detectors = self._build()self.scaler = StandardScaler()# detector name -> error string for detectors that failed in the last# run() and were excluded from the ensemble (never silently zeroed).self.last_failures: Dict[str, str] = {}def _cfg(self, *path, default=None):node = self.config55 unmodified linesXs = self.scaler.fit_transform(X)raw: Dict[str, np.ndarray] = {}norm: Dict[str, np.ndarray] = {}self.last_failures: Dict[str, str] = {}for det in self.detectors:try:det.fit(Xs)s = det.score(Xs)except Exception as exc:# A failed detector is recorded and EXCLUDED from the ensemble.# Substituting zeros (the previous behavior) silently diluted# every other detector's signal and masked anomalies.self.last_failures[det.name] = f"{type(exc).__name__}: {exc}"continueraw[det.name] = snorm[det.name] = normalize_scores(s)
7 unmodified lines8910111213143 unmodified lines1819202122232425262728293031323334355 unmodified lines41424344454647485 unmodified lines545556575859607 unmodified linesfrom __future__ import annotationsfrom typing import Dict, List, Optionalfrom sensorflow.evaluation.records import (EvalStore,3 unmodified lines)# metric -> (tolerance, direction). "up" means higher is better.METRIC_SPECS: Dict[str, Dict] = {"precision": {"tolerance": 0.03, "better": "up", "kind": "performance"},"recall": {"tolerance": 0.03, "better": "up", "kind": "performance"},"safety_critical_recall": {"tolerance": 0.02, "better": "up", "kind": "performance"},"idf1": {"tolerance": 0.05, "better": "up", "kind": "tracking"},"id_swap_rate": {"tolerance": 0.02, "better": "down", "kind": "tracking"},"fragmentation_rate": {"tolerance": 0.03, "better": "down", "kind": "tracking"},"mean_iou_3d": {"tolerance": 0.03, "better": "up", "kind": "annotation"},"mean_position_error": {"tolerance": 0.10, "better": "down", "kind": "annotation"},"mean_orientation_error_deg": {"tolerance": 3.0, "better": "down", "kind": "annotation"},}def compare_runs(store: EvalStore,5 unmodified linesbaseline_version: Optional[str] = None,affected_classes: Optional[List[str]] = None,affected_scenarios: Optional[List[str]] = None,) -> RegressionResult:"""Compare current run metrics vs a baseline run; persist RegressionResult."""deltas: List[RegressionMetricDelta] = []kinds: List[str] = []regressed_any = False5 unmodified linesif base is None or cur is None:continuedelta = cur - baseif spec["better"] == "up":regressed = delta < -spec["tolerance"]else:regressed = delta > spec["tolerance"]7 unmodified lines891011121314153 unmodified lines1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162635 unmodified lines69707172737475767778798081828384858687888990915 unmodified lines9798991001011021031041051061071081091101111121137 unmodified linesfrom __future__ import annotationsimport mathfrom typing import Dict, List, Optional, Tuplefrom sensorflow.evaluation.records import (EvalStore,3 unmodified lines)# metric -> (tolerance, direction). "up" means higher is better.# "proportion" marks metrics that are rates in [0, 1] backed by trial counts,# eligible for the confidence-interval decision path in compare_runs.METRIC_SPECS: Dict[str, Dict] = {"precision": {"tolerance": 0.03, "better": "up", "kind": "performance", "proportion": True},"recall": {"tolerance": 0.03, "better": "up", "kind": "performance", "proportion": True},"safety_critical_recall": {"tolerance": 0.02, "better": "up", "kind": "performance", "proportion": True},"idf1": {"tolerance": 0.05, "better": "up", "kind": "tracking", "proportion": True},"id_swap_rate": {"tolerance": 0.02, "better": "down", "kind": "tracking", "proportion": True},"fragmentation_rate": {"tolerance": 0.03, "better": "down", "kind": "tracking", "proportion": True},"mean_iou_3d": {"tolerance": 0.03, "better": "up", "kind": "annotation", "proportion": False},"mean_position_error": {"tolerance": 0.10, "better": "down", "kind": "annotation", "proportion": False},"mean_orientation_error_deg": {"tolerance": 3.0, "better": "down", "kind": "annotation", "proportion": False},}_Z_95 = 1.959963984540054 # two-sided 95%def wilson_interval(p: float, n: int, z: float = _Z_95) -> Tuple[float, float]:"""Wilson score interval for a binomial proportion (never degenerate at 0/1)."""if n <= 0:return (0.0, 1.0)denom = 1.0 + z * z / ncenter = (p + z * z / (2 * n)) / denomhalf = z * math.sqrt(max(p * (1 - p) / n + z * z / (4 * n * n), 0.0)) / denomreturn (max(0.0, center - half), min(1.0, center + half))def newcombe_delta_ci(p_base: float, n_base: int,p_cur: float, n_cur: int,z: float = _Z_95) -> Tuple[float, float]:"""Newcombe hybrid-score CI for the difference (p_cur - p_base).Combines the two Wilson intervals; well-behaved for small n andboundary proportions, unlike the Wald interval."""lb, ub = wilson_interval(p_base, n_base, z)lc, uc = wilson_interval(p_cur, n_cur, z)return (lc - ub, uc - lb)def compare_runs(store: EvalStore,5 unmodified linesbaseline_version: Optional[str] = None,affected_classes: Optional[List[str]] = None,affected_scenarios: Optional[List[str]] = None,sample_sizes: Optional[Dict[str, Tuple[int, int]]] = None,) -> RegressionResult:"""Compare current run metrics vs a baseline run; persist RegressionResult.sample_sizes (optional, additive): metric -> (n_baseline, n_current) trialcounts. When provided for a proportion metric, the regression decision usesa Newcombe 95% CI on the delta with the tolerance acting as thepractical-significance margin: a regression is flagged only when theENTIRE interval lies beyond the tolerance in the bad direction. Thisprevents noise-flagging on small runs and adds sensitivity on large runs.Without sample_sizes the legacy point-delta rule is preserved.For repeated/sequential monitoring across many runs, delegate tosensorflow.seqeval (anytime-valid e-processes, e-BH multiplicity) insteadof calling this per run: fixed-level CIs are not valid under continuousmonitoring."""deltas: List[RegressionMetricDelta] = []kinds: List[str] = []regressed_any = False5 unmodified linesif base is None or cur is None:continuedelta = cur - basens = (sample_sizes or {}).get(metric)use_ci = (spec.get("proportion") and ns is not Noneand ns[0] > 0 and ns[1] > 0and 0.0 <= base <= 1.0 and 0.0 <= cur <= 1.0)if use_ci:lo, hi = newcombe_delta_ci(base, ns[0], cur, ns[1])if spec["better"] == "up":regressed = hi < -spec["tolerance"]else:regressed = lo > spec["tolerance"]elif spec["better"] == "up":regressed = delta < -spec["tolerance"]else:regressed = delta > spec["tolerance"]
12345678"""Production hardening layer for Sensorflow Studio.
Built from the audit in docs/hardening/audit.md. This package LAYERSproduction-grade contracts, sampling, quality routing, HITL prioritization,cache manifests, power analysis and interface seams on top of the existingpackages without modifying their public APIs. Adoption path documented ineach module."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261"""/api/hardening — audit browser, readiness scorecard, funnel, demos.
Read-only over other packages' data (funnel counts come from the existingruns/ stores). Demo endpoints run the hardening primitives on SEEDEDSYNTHETIC fixtures and label them as such."""
from __future__ import annotations
import jsonfrom collections import Counterfrom pathlib import Pathfrom typing import Dict, List, Optional
import numpy as npfrom fastapi import APIRouter, HTTPExceptionfrom fastapi.responses import PlainTextResponse
from sensorflow.hardening import hitl, power, quality, readiness, safety_config, samplingfrom sensorflow.hardening.interfaces import describe_implementations
router = APIRouter(prefix="/api/hardening", tags=["hardening"])
_DOCS_DIR = Path(__file__).resolve().parents[2] / "docs" / "hardening"_RUNS_DIR = Path(__file__).resolve().parents[2] / "runs"
# ------------------------------------------------------------------ audit & readiness
@router.get("/audit")def get_audit() -> Dict: path = _DOCS_DIR / "audit.json" if not path.exists(): raise HTTPException(404, "audit.json not found") return json.loads(path.read_text())
@router.get("/audit.md", response_class=PlainTextResponse)def get_audit_markdown() -> str: path = _DOCS_DIR / "audit.md" if not path.exists(): raise HTTPException(404, "audit.md not found") return path.read_text()
@router.get("/readiness")def get_readiness() -> Dict: try: return readiness.scorecard() except FileNotFoundError: raise HTTPException(404, "audit.json not found; run the audit first")
@router.get("/thresholds")def get_thresholds() -> Dict: return { "config_version": safety_config.CONFIG_VERSION, "thresholds": safety_config.registry_summary(), }
@router.get("/interfaces")def get_interfaces() -> Dict: return {"implementations": describe_implementations()}
# ------------------------------------------------------------------ funnel / observability
@router.get("/funnel")def get_funnel() -> Dict: """Data-funnel counts pulled from the existing labeleval store (read-only).
Stages: frames -> annotations -> validated -> triaged (by outcome) -> review tasks -> human reviews. Counts are from the local prototype store; the `store` field says exactly where they came from. """ store_path = _RUNS_DIR / "labeleval" / "store.json" if not store_path.exists(): return {"available": False, "store": str(store_path), "note": "labeleval store not present; run the labeleval pipeline"} data = json.loads(store_path.read_text())
def count(kind: str) -> int: v = data.get(kind, {}) return len(v)
triage_statuses: Counter = Counter() for rec in (data.get("triage_decisions") or {}).values(): triage_statuses[str(rec.get("status", rec.get("decision", "unknown")))] += 1
review_statuses: Counter = Counter() for rec in (data.get("review_tasks") or {}).values(): review_statuses[str(rec.get("status", "unknown"))] += 1
return { "available": True, "store": "runs/labeleval/store.json (LOCAL prototype store)", "stages": [ {"stage": "frames", "count": count("frames")}, {"stage": "annotations", "count": count("annotations")}, {"stage": "validations", "count": count("validations")}, {"stage": "anomaly_checks", "count": count("anomalies")}, {"stage": "grader_comparisons", "count": count("grader_comparisons")}, {"stage": "triage_decisions", "count": count("triage_decisions")}, {"stage": "review_tasks", "count": count("review_tasks")}, {"stage": "human_reviews", "count": count("human_reviews")}, ], "triage_breakdown": dict(triage_statuses), "review_breakdown": dict(review_statuses), "alerts": count("alerts"), "audit_events": count("audit_events"), }
# ------------------------------------------------------------------ demos (seeded synthetic)
@router.get("/demo/sampling")def demo_sampling(seed: int = 7, budget: int = 60) -> Dict: """Stratified sampling + HT reweighting on a SEEDED SYNTHETIC population.""" rng = np.random.default_rng(seed) pop_sizes = { sampling.Stratum.REPRESENTATIVE: 500, sampling.Stratum.NOMINAL: 300, sampling.Stratum.RARE: 60, sampling.Stratum.SAFETY_CRITICAL: 40, sampling.Stratum.KNOWN_FAILURES: 25, sampling.Stratum.NOVEL: 50, sampling.Stratum.DISTRIBUTION_SHIFTED: 25, } # Per-stratum true failure rates: rare/safety strata fail far more often. true_rates = { sampling.Stratum.REPRESENTATIVE: 0.02, sampling.Stratum.NOMINAL: 0.03, sampling.Stratum.RARE: 0.20, sampling.Stratum.SAFETY_CRITICAL: 0.30, sampling.Stratum.KNOWN_FAILURES: 0.60, sampling.Stratum.NOVEL: 0.15, sampling.Stratum.DISTRIBUTION_SHIFTED: 0.25, } population = {s: [f"{s.value}-{i}" for i in range(n)] for s, n in pop_sizes.items()} failures = {} for s, ids in population.items(): fails = rng.random(len(ids)) < true_rates[s] for item_id, f in zip(ids, fails): failures[item_id] = float(f)
sample = sampling.stratified_sample(population, budget=budget, seed=seed) measured = {it.item_id: failures[it.item_id] for it in sample.items} ht_estimate = sample.estimate_population_rate(measured) naive_estimate = float(np.mean(list(measured.values()))) if measured else None total = sum(pop_sizes.values()) true_rate = sum(pop_sizes[s] * true_rates[s] for s in pop_sizes) / total
return { "simulated": True, "seed": seed, "quotas": {s.value: n for s, n in sample.quotas.items()}, "sampled": len(sample.items), "true_population_rate": round(true_rate, 4), "ht_reweighted_estimate": round(ht_estimate, 4) if ht_estimate is not None else None, "naive_sample_mean": round(naive_estimate, 4) if naive_estimate is not None else None, "note": "The naive mean is inflated by oversampling rare/safety strata; " "the stratum-weighted estimate recovers the population rate.", }
@router.get("/demo/quality")def demo_quality() -> Dict: """Explainable routing on fixed synthetic fixtures (incl. required cases).""" fixtures = { "clean_vehicle": quality.QualityEvidence( geometric_validity=0.95, sensor_agreement=0.9, temporal_consistency=0.92, semantic_agreement=0.9, confidence=0.88, uncertainty=0.1, occlusion=0.1, safety_relevance=0.1), "vru_miss_in_boundary": quality.QualityEvidence( geometric_validity=0.6, sensor_agreement=0.25, temporal_consistency=0.5, semantic_agreement=0.4, confidence=0.3, uncertainty=0.8, occlusion=0.6, safety_relevance=0.95), "phantom_obstacle": quality.QualityEvidence( geometric_validity=0.8, sensor_agreement=0.15, temporal_consistency=0.3, semantic_agreement=0.5, confidence=0.7, uncertainty=0.6, occlusion=0.2, safety_relevance=0.7), "incomplete_telemetry": quality.QualityEvidence( geometric_validity=0.9, sensor_agreement=None, temporal_consistency=None, semantic_agreement=0.85, confidence=0.9, uncertainty=0.2, occlusion=0.1, safety_relevance=0.2), } routed = {name: quality.route(ev) for name, ev in fixtures.items()}
profiles = [ quality.GraderProfile(grader_id="g1", backbone="vit-l14", training_data="webds-3b"), quality.GraderProfile(grader_id="g2", backbone="vit-l14", training_data="webds-3b"), quality.GraderProfile(grader_id="g3", backbone="convnext", training_data="internal-av"), ] consensus = quality.consensus_with_dependence( {"g1": "pedestrian", "g2": "pedestrian", "g3": "pedestrian"}, profiles)
return {"simulated": True, "routing": { name: {"decision": r["decision"].value, "explanation": r["explanation"]} for name, r in routed.items() }, "grader_dependence_example": consensus}
@router.get("/demo/hitl")def demo_hitl(budget: int = 5) -> Dict: """HITL prioritization comparison on fixed synthetic candidates.""" candidates = [ hitl.ReviewCandidate(item_id="max_risk_certain", risk=0.99, uncertainty=0.05, novelty=0.1, training_value=0.2), hitl.ReviewCandidate(item_id="balanced_high", risk=0.7, uncertainty=0.7, novelty=0.6, training_value=0.7), hitl.ReviewCandidate(item_id="novel_uncertain", risk=0.3, uncertainty=0.8, novelty=0.95, training_value=0.8), hitl.ReviewCandidate(item_id="routine", risk=0.2, uncertainty=0.2, novelty=0.1, training_value=0.2), hitl.ReviewCandidate(item_id="risky_uncertain", risk=0.9, uncertainty=0.85, novelty=0.3, training_value=0.5), hitl.ReviewCandidate(item_id="training_gold", risk=0.4, uncertainty=0.6, novelty=0.7, training_value=0.95), ] ranked = hitl.prioritize(candidates, budget=budget) product_only = sorted(candidates, key=lambda c: -hitl.information_gain_score(c)) metrics = hitl.acceptance_metrics( routed_ids=[r["item_id"] for r in ranked], true_problem_ids=["balanced_high", "risky_uncertain", "max_risk_certain", "novel_uncertain"], critical_ids=["max_risk_certain", "risky_uncertain"], total_items=len(candidates), ) return { "simulated": True, "pareto_then_product": ranked, "product_only_order": [c.item_id for c in product_only], "comparison_note": "Pareto ranking keeps max_risk_certain (extreme on one " "axis) on the first front; the pure product buries it.", "acceptance_metrics": metrics, }
@router.get("/demo/power")def demo_power() -> Dict: """Tier sizing derived from decision parameters (no fixed counts).""" return { "tiers": [power.tier_sizing(spec) for spec in power.default_tiers().values()], "example_rare_event": power.required_events_rare( prevalence=0.01, baseline_rate=0.95, mde=0.02), }
@router.get("/summary")def get_summary() -> Dict: """One-call overview for the frontend page.""" audit = get_audit() return { "summary": audit.get("summary", {}), "strengths": audit.get("strengths", []), "readiness": readiness.scorecard(audit), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184"""Reproducible feature-cache keys, manifests, integrity and eviction.
Audit findings this design corrects:- F-006 (megaeval query cache): key omitted run identity -> collisions between a run and its baseline. Fixed surgically there by keying on run_id; this module is the general design every cache should migrate to.- F-027 (megaeval artifact cache): insertion-order eviction, no checksums.- vitis feature reuse: keyed on config but without dependency versions.
Principles:1. The key is a content hash over a COMPLETE manifest of everything the cached value depends on. If it isn't in the manifest, it can't be allowed to affect the value.2. Integrity: every payload stores a checksum, verified on read; corrupt entries are treated as misses, never returned.3. Invalidation is free: bump any dependency version and the key changes. Explicit invalidation exists only for "the manifest lied" incidents.4. Eviction: LRU by last access (not insertion order), with a byte budget.
Migration note for the audited caches:- megaeval QueryCache: adopt CacheManifest with dependencies {run_id, population_id, model_version, label_version, threshold_config, seed, query(filters, group_by, metrics)}. The surgical run_id fix already pins lineage; the manifest form adds integrity + persistence.- megaeval RunRegistry._artifacts: keep in-memory map but move eviction to LRU and add npz checksums (this module's LocalDiskCache can back it).- vitis feature reuse: manifest must include IP core version, precision flags (quant mode), calibration id and input data hash."""
from __future__ import annotations
import hashlibimport jsonimport osimport threadingimport timefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Dict, Optional, Protocol, Tuple
from pydantic import BaseModel, Field
class CacheManifest(BaseModel): """Complete dependency record for one cached value.
`dependencies` must include EVERY version/config/precision input: e.g. {"data_hash": ..., "model_version": ..., "label_version": ..., "evaluator_version": ..., "config_hash": ..., "precision": "fp32", "seed": "7"}. Keys and values are strings for stable hashing. """
namespace: str # e.g. "vitis.features", "megaeval.query" dependencies: Dict[str, str] = Field(default_factory=dict) schema_version: str = "manifest-v1"
def cache_key(self) -> str: blob = json.dumps({ "ns": self.namespace, "deps": dict(sorted(self.dependencies.items())), "schema": self.schema_version, }, sort_keys=True) return hashlib.sha256(blob.encode()).hexdigest()
def payload_checksum(payload: bytes) -> str: return hashlib.sha256(payload).hexdigest()
class FeatureCacheStorage(Protocol): """Storage seam for the cache.
Local implementation below writes to disk. The PRODUCTION option is an object store (S3/GCS: key = f"{namespace}/{cache_key}", payload + manifest JSON as separate objects, checksum in object metadata, lifecycle rules for eviction) fronted by a small metadata DB for LRU bookkeeping. """
def read(self, key: str) -> Optional[Tuple[bytes, Dict]]: ... def write(self, key: str, payload: bytes, manifest: Dict) -> None: ... def delete(self, key: str) -> None: ...
class LocalDiskCache: """LOCAL implementation: content-addressed files with sidecar manifests.
Layout: root/<key>.bin (payload), root/<key>.json (manifest + checksum + access time). Reads verify the checksum; a mismatch deletes the entry and reports a miss (corruption never propagates). Eviction is LRU by last-access when the byte budget is exceeded. """
def __init__(self, root: Path, max_bytes: int = 512 * 1024 * 1024): self.root = Path(root) self.root.mkdir(parents=True, exist_ok=True) self.max_bytes = max_bytes self._lock = threading.Lock()
def _paths(self, key: str) -> Tuple[Path, Path]: return self.root / f"{key}.bin", self.root / f"{key}.json"
def read(self, key: str) -> Optional[Tuple[bytes, Dict]]: bin_p, meta_p = self._paths(key) with self._lock: if not bin_p.exists() or not meta_p.exists(): return None payload = bin_p.read_bytes() meta = json.loads(meta_p.read_text()) if payload_checksum(payload) != meta.get("checksum"): # Integrity failure: purge and miss. bin_p.unlink(missing_ok=True) meta_p.unlink(missing_ok=True) return None meta["last_accessed_at"] = time.time() meta_p.write_text(json.dumps(meta)) return payload, meta
def write(self, key: str, payload: bytes, manifest: Dict) -> None: bin_p, meta_p = self._paths(key) with self._lock: bin_p.write_bytes(payload) meta_p.write_text(json.dumps({ "manifest": manifest, "checksum": payload_checksum(payload), "size_bytes": len(payload), "created_at": time.time(), "last_accessed_at": time.time(), })) self._evict_if_needed()
def delete(self, key: str) -> None: bin_p, meta_p = self._paths(key) with self._lock: bin_p.unlink(missing_ok=True) meta_p.unlink(missing_ok=True)
def _evict_if_needed(self) -> None: entries = [] total = 0 for meta_p in self.root.glob("*.json"): try: meta = json.loads(meta_p.read_text()) except (json.JSONDecodeError, OSError): continue total += meta.get("size_bytes", 0) entries.append((meta.get("last_accessed_at", 0), meta.get("size_bytes", 0), meta_p)) if total <= self.max_bytes: return entries.sort() # oldest access first for _, size, meta_p in entries: if total <= self.max_bytes: break key = meta_p.stem (self.root / f"{key}.bin").unlink(missing_ok=True) meta_p.unlink(missing_ok=True) total -= size
class FeatureCache: """Manifest-keyed cache facade over any FeatureCacheStorage."""
def __init__(self, storage: FeatureCacheStorage): self.storage = storage self.hits = 0 self.misses = 0
def get(self, manifest: CacheManifest) -> Optional[bytes]: result = self.storage.read(manifest.cache_key()) if result is None: self.misses += 1 return None self.hits += 1 return result[0]
def put(self, manifest: CacheManifest, payload: bytes) -> str: key = manifest.cache_key() self.storage.write(key, payload, manifest.model_dump()) return key
def stats(self) -> Dict: total = self.hits + self.misses return {"hits": self.hits, "misses": self.misses, "hit_rate": self.hits / total if total else None}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328"""Production-grade data contracts with mandatory provenance.
The audit (F-002, F-004, F-014: mock-presented-as-real; label-provenanceconflation) found that the platform blurs MODEL PREDICTION vs AUTO-LABEL vsVLM output vs HUMAN label vs CERTIFIED ground truth in several paths. Thesecontracts make provenance a first-class, mandatory field so downstream codecan refuse inputs whose provenance is insufficient (e.g. a quality gate mustnever benchmark against AUTO_LABEL "ground truth").
Adoption path (existing packages are NOT rewritten now):1. New code (hardening, future packages) imports these contracts directly.2. Existing records are mapped through the `adapt_*` helpers below at package boundaries; the adapters make the implicit provenance of each legacy record type explicit.3. At each package's next breaking release, its internal records inherit from or are replaced by these contracts (tracked in the remediation plan)."""
from __future__ import annotations
import hashlibimport jsonfrom datetime import datetime, timezonefrom enum import Enumfrom typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
def utc_now_iso() -> str: return datetime.now(timezone.utc).isoformat()
class LabelProvenance(str, Enum): """Where a label came from, ordered roughly by trust.
The distinction the legacy code blurs: a MODEL_PREDICTION is a hypothesis to be evaluated; CERTIFIED_GROUND_TRUTH is calibrated, human-audited truth suitable for gating launches. Nothing in between may silently substitute for the level above it. """
MODEL_PREDICTION = "MODEL_PREDICTION" AUTO_LABEL = "AUTO_LABEL" VLM_INFERENCE = "VLM_INFERENCE" HUMAN_LABEL = "HUMAN_LABEL" CERTIFIED_GROUND_TRUTH = "CERTIFIED_GROUND_TRUTH"
#: Trust ordering for gate checks (higher = more trustworthy).PROVENANCE_RANK: Dict[LabelProvenance, int] = { LabelProvenance.MODEL_PREDICTION: 0, LabelProvenance.AUTO_LABEL: 1, LabelProvenance.VLM_INFERENCE: 1, LabelProvenance.HUMAN_LABEL: 3, LabelProvenance.CERTIFIED_GROUND_TRUTH: 4,}
class DataOrigin(str, Enum): """Whether the underlying sensor data is real or simulated."""
REAL_SENSOR = "REAL_SENSOR" SYNTHETIC = "SYNTHETIC" SYNTHETIC_FALLBACK = "SYNTHETIC_FALLBACK" # substituted when real data missing REPLAYED = "REPLAYED"
class Provenance(BaseModel): """Common provenance block attached to every contract."""
label_provenance: LabelProvenance data_origin: DataOrigin = DataOrigin.REAL_SENSOR source_system: str = "" # e.g. "perception_automator", "vendor:acme" model_version: Optional[str] = None created_at: str = Field(default_factory=utc_now_iso) lineage_ids: List[str] = Field(default_factory=list) # parent record ids notes: str = ""
# ------------------------------------------------------------------ sensor / scene
class SensorFrame(BaseModel): frame_id: str sequence_id: str dataset_version: str timestamp_us: int data_origin: DataOrigin sensor_uris: Dict[str, str] = Field(default_factory=dict) # sensor name -> URI calibration_version: str = "" ego_speed_mps: float = 0.0 weather: str = "unknown" lighting: str = "unknown"
class ScenarioEvidence(BaseModel): """One piece of evidence supporting a scenario classification — kept decomposed so routing/review can explain WHY a scenario was flagged."""
kind: str # e.g. "ttc_conflict", "novelty_knn", "detector_anomaly" value: float threshold: Optional[float] = None frame_ids: List[str] = Field(default_factory=list) detail: Dict[str, Any] = Field(default_factory=dict)
class Scenario(BaseModel): scenario_id: str dataset_version: str scenario_type: str stratum: Optional[str] = None # sampling stratum (see sampling.py) frame_ids: List[str] = Field(default_factory=list) evidence: List[ScenarioEvidence] = Field(default_factory=list) provenance: Provenance sampling_weight: float = 1.0 # inverse-inclusion-probability weight
# ------------------------------------------------------------------ objects / tracks
class ObjectProposal(BaseModel): proposal_id: str frame_id: str class_name: str bbox_3d: List[float] # [x, y, z, l, w, h, yaw] confidence: float = 0.0 provenance: Provenance mask_ref: Optional[str] = None
class Track(BaseModel): track_id: str sequence_id: str class_name: str frame_ids: List[str] = Field(default_factory=list) proposal_ids: List[str] = Field(default_factory=list) provenance: Provenance
class GroundTruthObject(BaseModel): gt_id: str frame_id: str class_name: str bbox_3d: List[float] instance_id: str = "" provenance: Provenance # must be HUMAN_LABEL or CERTIFIED_GROUND_TRUTH certified: bool = False
def is_gate_grade(self) -> bool: """True iff this object may back a launch/quality gate.""" return PROVENANCE_RANK[self.provenance.label_provenance] >= \ PROVENANCE_RANK[LabelProvenance.HUMAN_LABEL]
# ------------------------------------------------------------------ decisions / results
class ValidationResult(BaseModel): target_id: str checks: List[Dict[str, Any]] = Field(default_factory=list) # name/passed/value/threshold passed: bool provenance: Provenance
class SafetyAssessment(BaseModel): target_id: str measures: Dict[str, Optional[float]] = Field(default_factory=dict) # ttc/pet/drac... severity: str = "none" threshold_config_version: str = "" # from hardening.safety_config simulated: bool = False provenance: Provenance
class TriageDecision(BaseModel): target_id: str decision: str # ACCEPT | HITL | QUARANTINE explanation: List[str] = Field(default_factory=list) evidence: Dict[str, float] = Field(default_factory=dict) priority: float = 0.0 provenance: Provenance
class EvaluationResult(BaseModel): run_id: str dataset_version: str model_version: str metrics: Dict[str, Optional[float]] = Field(default_factory=dict) sample_sizes: Dict[str, int] = Field(default_factory=dict) # metric -> n seed: Optional[int] = None provenance: Provenance
class RegressionResult(BaseModel): run_id: str baseline_run_id: str metric_decisions: List[Dict[str, Any]] = Field(default_factory=list) regression_detected: bool method: str = "newcombe_ci" # or "seqeval_eprocess" provenance: Provenance
# ------------------------------------------------------------------ versions / cache
class DatasetVersion(BaseModel): dataset_version: str parent_version: Optional[str] = None label_provenance: LabelProvenance data_origin: DataOrigin num_frames: int = 0 content_hash: str = "" created_at: str = Field(default_factory=utc_now_iso) split_assignments: Dict[str, str] = Field(default_factory=dict) # unit -> train/val/test
class ModelVersion(BaseModel): model_version: str training_dataset_version: Optional[str] = None weights_hash: str = "" config_hash: str = "" created_at: str = Field(default_factory=utc_now_iso)
class FeatureCacheEntry(BaseModel): """See cache_manifest.py for the full key derivation."""
cache_key: str manifest: Dict[str, str] = Field(default_factory=dict) # dependency -> version/hash checksum: str = "" size_bytes: int = 0 created_at: str = Field(default_factory=utc_now_iso) last_accessed_at: str = Field(default_factory=utc_now_iso)
# ------------------------------------------------------------------ adapters## Map existing packages' records into these contracts, making implicit# provenance explicit. Read-only: they never mutate the source records.
def adapt_labeleval_annotation(ann: Any) -> ObjectProposal: """evaluation.records.Annotation -> ObjectProposal.
Annotations in labeleval are auto-generated hypotheses (their docstring says so), so provenance is AUTO_LABEL unless a human review verified them. """ verified = getattr(ann, "status", "") == "VERIFIED" return ObjectProposal( proposal_id=ann.annotation_id, frame_id=ann.frame_id, class_name=ann.class_name, bbox_3d=list(ann.bbox_3d or [0.0] * 7), confidence=float(ann.confidence), mask_ref=getattr(ann, "mask", None), provenance=Provenance( label_provenance=(LabelProvenance.HUMAN_LABEL if verified else LabelProvenance.AUTO_LABEL), data_origin=DataOrigin.SYNTHETIC, # labeleval datasets are synthetic source_system="evaluation.records.Annotation", model_version=getattr(ann, "model_version", None), lineage_ids=[ann.dataset_id], ), )
_GT_TYPE_TO_PROVENANCE: Dict[str, LabelProvenance] = { "PSEUDO_GROUND_TRUTH": LabelProvenance.AUTO_LABEL, "VENDOR_GROUND_TRUTH": LabelProvenance.HUMAN_LABEL, "HUMAN_VERIFIED_GROUND_TRUTH": LabelProvenance.HUMAN_LABEL, "GOLD_STANDARD": LabelProvenance.CERTIFIED_GROUND_TRUTH,}
def adapt_labeleval_gt_box(box: Any, frame_id: str = "", data_origin: DataOrigin = DataOrigin.SYNTHETIC) -> GroundTruthObject: """evaluation.records.GroundTruthBox -> GroundTruthObject.
Maps the 4-level labeleval GroundTruthType onto LabelProvenance. Note PSEUDO_GROUND_TRUTH maps to AUTO_LABEL — is_gate_grade() correctly refuses it for launch gates. """ gt_type = str(getattr(box, "gt_type", "VENDOR_GROUND_TRUTH")) prov = _GT_TYPE_TO_PROVENANCE.get(gt_type, LabelProvenance.AUTO_LABEL) return GroundTruthObject( gt_id=box.gt_id, frame_id=frame_id, class_name=box.class_name, bbox_3d=list(box.bbox_3d), instance_id=getattr(box, "track_instance_id", ""), certified=prov == LabelProvenance.CERTIFIED_GROUND_TRUTH, provenance=Provenance( label_provenance=prov, data_origin=data_origin, source_system="evaluation.records.GroundTruthBox", ), )
def adapt_pipeline_proposal(obj: Any, frame_id: str, used_gt_fallback: bool) -> ObjectProposal: """sensorflow.schemas.unified_frame.Object3D -> ObjectProposal.
`used_gt_fallback` MUST be True when the legacy perception pipeline built the proposal from GT-derived fallback masks (audit F-004) — those proposals are AUTO_LABELs contaminated by GT and must never be evaluated against the same GT. """ return ObjectProposal( proposal_id=f"{frame_id}:{getattr(obj, 'track_id', '') or id(obj)}", frame_id=frame_id, class_name=obj.class_name, bbox_3d=list(obj.bbox_3d), confidence=float(obj.confidence), mask_ref=getattr(obj, "sam_mask_ref", None), provenance=Provenance( label_provenance=LabelProvenance.AUTO_LABEL, data_origin=DataOrigin.REAL_SENSOR, source_system="perception_automator", notes="GT_CONTAMINATED: built from ground-truth fallback masks" if used_gt_fallback else "", ), )
def content_hash(payload: Any) -> str: """Stable content hash for contract payloads (sorted-key JSON, sha256).""" blob = json.dumps(payload, sort_keys=True, default=str) return hashlib.sha256(blob.encode()).hexdigest()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""Information-gain HITL prioritization (audit F-015).
The legacy review queue (evaluation/pipeline.py review batches,mitl_copilot's flat FIFO with `pred_tracks[:3]` as "evidence") spends humanattention in arrival order. This module prioritizes by expected informationvalue, two ways, with a documented comparison:
1. `information_gain_score`: multiplicative Risk x Uncertainty x Novelty x TrainingValue. One scalar, easy to sort and budget. Weakness: the product collapses the axes — a maximally risky but certain item scores the same as a moderately risky, moderately uncertain one, and a zero on any axis zeroes the whole item even when another axis is extreme.2. `pareto_rank`: non-dominated sorting over the same four axes. Keeps items that are extreme on ANY axis on the first fronts (nothing with the highest risk can be starved by a low novelty score). Weakness: partial order — within a front you still need a tiebreaker (we use the product score), and front sizes vary so budgeting is less direct.
Recommendation encoded in `prioritize`: rank by Pareto front first (so nosingle-axis-extreme item is starved), break ties inside a front with themultiplicative score (so budget-limited review still favors balanced value).
Acceptance metrics for the ROUTING SYSTEM itself (not the labels) are in`acceptance_metrics`: HITL precision, recall, workload, critical-miss-rateand false-routing rate. "99.99% of routed items contain anomalies" is NOT avalid acceptance criterion — a router that routes almost nothing achieves itwhile missing almost everything; the pair that matters is precision ANDcritical-miss-rate at a given workload."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import Dict, List, Optional, Sequence
from pydantic import BaseModel
class ReviewCandidate(BaseModel): item_id: str risk: float # [0,1] harm if this label is wrong (safety relevance x exposure) uncertainty: float # [0,1] epistemic uncertainty / disagreement novelty: float # [0,1] distance from training distribution (see sampling.py) training_value: float # [0,1] expected model improvement if corrected
def information_gain_score(c: ReviewCandidate) -> float: """Risk x Uncertainty x Novelty x TrainingValue, floored at 0.01 per axis.
The floor keeps a zero on one axis from erasing extreme value on another (partial mitigation of the product's main weakness; the Pareto ranking is the full mitigation). """ floor = 0.01 score = 1.0 for v in (c.risk, c.uncertainty, c.novelty, c.training_value): score *= max(floor, min(1.0, v)) return score
def _dominates(a: ReviewCandidate, b: ReviewCandidate) -> bool: axes = ("risk", "uncertainty", "novelty", "training_value") ge = all(getattr(a, x) >= getattr(b, x) for x in axes) gt = any(getattr(a, x) > getattr(b, x) for x in axes) return ge and gt
def pareto_rank(candidates: Sequence[ReviewCandidate]) -> Dict[str, int]: """Non-dominated sorting: front 0 = not dominated by anyone, etc. O(n^2) per front — fine for review queues (thousands); use NSGA-II style sorting if queues grow beyond ~10^5.""" remaining = list(candidates) fronts: Dict[str, int] = {} front = 0 while remaining: nondominated = [c for c in remaining if not any(_dominates(o, c) for o in remaining if o is not c)] if not nondominated: # all mutually dominated cycles impossible, but guard nondominated = remaining[:] for c in nondominated: fronts[c.item_id] = front remaining = [c for c in remaining if c.item_id not in fronts] front += 1 return fronts
def prioritize(candidates: Sequence[ReviewCandidate], budget: Optional[int] = None) -> List[Dict]: """Pareto front first, multiplicative score as tiebreaker, id as final tie.
Deterministic: same candidates -> same order regardless of input order. """ fronts = pareto_rank(candidates) rows = [{ "item_id": c.item_id, "pareto_front": fronts[c.item_id], "info_gain": round(information_gain_score(c), 9), "components": {"risk": c.risk, "uncertainty": c.uncertainty, "novelty": c.novelty, "training_value": c.training_value}, } for c in candidates] rows.sort(key=lambda r: (r["pareto_front"], -r["info_gain"], r["item_id"])) return rows[:budget] if budget else rows
# ------------------------------------------------------------------ acceptance metrics
def acceptance_metrics( routed_ids: Sequence[str], true_problem_ids: Sequence[str], critical_ids: Sequence[str], total_items: int,) -> Dict[str, Optional[float]]: """Metrics for evaluating the HITL ROUTER itself.
- hitl_precision: fraction of routed items that were true problems (wasted-review complement). - hitl_recall: fraction of true problems that got routed. - workload: fraction of all items sent to humans. - critical_miss_rate: fraction of CRITICAL problems NOT routed — the metric that must gate deployment of any router change. - false_routing_rate: fraction of clean items routed (reviewer burn). """ routed = set(routed_ids) problems = set(true_problem_ids) critical = set(critical_ids) clean = total_items - len(problems) return { "hitl_precision": len(routed & problems) / len(routed) if routed else None, "hitl_recall": len(routed & problems) / len(problems) if problems else None, "workload": len(routed) / total_items if total_items else None, "critical_miss_rate": len(critical - routed) / len(critical) if critical else None, "false_routing_rate": len(routed - problems) / clean if clean > 0 else None, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315"""Production interface protocols with explicitly-labeled LOCAL implementations.
Audit F-026: the platform's stores are single-node, in-process dicts and JSONfiles under runs/, while the narrative talks exabyte scale. The honest fix isa seam: code depends on these Protocols; the CURRENT implementations areregistered as LOCAL/MOCK so nobody can mistake them for the productionsubstrate; production options are documented per protocol.
Registry usage: impl = get_implementation("VectorDB") # -> registered LOCAL impl describe_implementations() # -> label + production options"""
from __future__ import annotations
import jsonimport timefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Callable, Dict, Iterable, List, Optional, Protocol, Sequence, Tuple
import numpy as np
# ------------------------------------------------------------------ protocols
class VectorDB(Protocol): """Similarity search over embeddings.
Production options: Milvus/Qdrant/Vertex Matching Engine with HNSW or IVF-PQ indexes; embeddings versioned alongside the encoder model. """
def upsert(self, ids: Sequence[str], vectors: np.ndarray) -> None: ... def search(self, query: np.ndarray, k: int) -> List[Tuple[str, float]]: ...
class ObjectStorage(Protocol): """Immutable blob storage.
Production options: S3/GCS with bucket versioning, lifecycle policies, SSE; content-addressed keys from cache_manifest.CacheManifest. """
def put(self, key: str, data: bytes) -> None: ... def get(self, key: str) -> Optional[bytes]: ... def exists(self, key: str) -> bool: ...
class DistributedCompute(Protocol): """Partitioned map + reduce over large datasets.
Production options: Spark/Ray/Dask. megaeval's partial_stats/ reduce_partials pair is already shaped for map-side combine + shuffle reduce and should port directly. """
def map_partitions(self, partitions: Iterable[Any], fn: Callable[[Any], Any]) -> List[Any]: ... def reduce(self, partials: List[Any], fn: Callable[[List[Any]], Any]) -> Any: ...
class GPUInference(Protocol): """Batched model inference.
Production options: Triton Inference Server / TensorRT-LLM / Ray Serve with explicit model_version pinning per request. """
def infer(self, model_version: str, batch: np.ndarray) -> np.ndarray: ...
class FeatureCacheProtocol(Protocol): """Manifest-keyed feature cache (see cache_manifest.py).
Production options: object store payloads + Redis/DB metadata for LRU. """
def get(self, manifest: Any) -> Optional[bytes]: ... def put(self, manifest: Any, payload: bytes) -> str: ...
class MetadataStore(Protocol): """Transactional metadata (datasets, runs, lineage).
Production options: Postgres with migrations; DataHub/OpenLineage for lineage graphs. NOT JSON files under runs/. """
def put(self, kind: str, record_id: str, record: Dict) -> None: ... def get(self, kind: str, record_id: str) -> Optional[Dict]: ... def query(self, kind: str, **filters: Any) -> List[Dict]: ...
class ExperimentTracking(Protocol): """Run/metric/artifact tracking.
Production options: MLflow / W&B; every EvaluationResult logged with dataset_version, model_version, seed and config hash. """
def log_run(self, run_id: str, params: Dict, metrics: Dict) -> None: ... def get_run(self, run_id: str) -> Optional[Dict]: ...
class Observability(Protocol): """Metrics/traces/alerts.
Production options: Prometheus + Grafana + OpenTelemetry traces; alert rules on funnel-stage drop rates and cache integrity failures. """
def emit_metric(self, name: str, value: float, tags: Optional[Dict] = None) -> None: ... def counters(self) -> Dict[str, float]: ...
# ------------------------------------------------------------------ LOCAL implementations# Every one of these is a single-process, in-memory or local-disk stand-in.# They exist so the seam is real and testable — NOT to serve production load.
class LocalBruteForceVectorDB: """LOCAL/MOCK: exact brute-force search in memory. O(n) per query; fine below ~10^5 vectors, nowhere near production."""
LABEL = "LOCAL"
def __init__(self): self._ids: List[str] = [] self._vecs: Optional[np.ndarray] = None
def upsert(self, ids: Sequence[str], vectors: np.ndarray) -> None: self._ids.extend(ids) self._vecs = vectors if self._vecs is None else np.vstack([self._vecs, vectors])
def search(self, query: np.ndarray, k: int) -> List[Tuple[str, float]]: if self._vecs is None or not len(self._ids): return [] d = np.linalg.norm(self._vecs - query[None, :], axis=1) order = np.argsort(d)[:k] return [(self._ids[i], float(d[i])) for i in order]
class LocalDiskObjectStorage: """LOCAL/MOCK: files under a root dir. No versioning, no durability."""
LABEL = "LOCAL"
def __init__(self, root: Path = Path("runs/hardening/objects")): self.root = Path(root) self.root.mkdir(parents=True, exist_ok=True)
def _p(self, key: str) -> Path: safe = key.replace("/", "_") return self.root / safe
def put(self, key: str, data: bytes) -> None: self._p(key).write_bytes(data)
def get(self, key: str) -> Optional[bytes]: p = self._p(key) return p.read_bytes() if p.exists() else None
def exists(self, key: str) -> bool: return self._p(key).exists()
class LocalSerialCompute: """LOCAL/MOCK: serial in-process execution posing as distributed compute. Preserves the map/reduce shape so megaeval-style partials port unchanged."""
LABEL = "LOCAL"
def map_partitions(self, partitions: Iterable[Any], fn: Callable[[Any], Any]) -> List[Any]: return [fn(p) for p in partitions]
def reduce(self, partials: List[Any], fn: Callable[[List[Any]], Any]) -> Any: return fn(partials)
class MockGPUInference: """MOCK: deterministic hash-seeded outputs; NO real model runs here. Outputs are simulated and must never be presented as model predictions."""
LABEL = "MOCK"
def infer(self, model_version: str, batch: np.ndarray) -> np.ndarray: seed = abs(hash(model_version)) % (2 ** 32) rng = np.random.default_rng(seed) return rng.random((len(batch), 8))
class LocalJsonMetadataStore: """LOCAL/MOCK: JSON files, no transactions, no concurrent writers."""
LABEL = "LOCAL"
def __init__(self, root: Path = Path("runs/hardening/metadata")): self.root = Path(root) self.root.mkdir(parents=True, exist_ok=True)
def _p(self, kind: str, record_id: str) -> Path: d = self.root / kind d.mkdir(parents=True, exist_ok=True) return d / f"{record_id}.json"
def put(self, kind: str, record_id: str, record: Dict) -> None: self._p(kind, record_id).write_text(json.dumps(record, default=str))
def get(self, kind: str, record_id: str) -> Optional[Dict]: p = self._p(kind, record_id) return json.loads(p.read_text()) if p.exists() else None
def query(self, kind: str, **filters: Any) -> List[Dict]: d = self.root / kind if not d.exists(): return [] out = [] for p in sorted(d.glob("*.json")): rec = json.loads(p.read_text()) if all(rec.get(k) == v for k, v in filters.items()): out.append(rec) return out
class LocalExperimentTracking: """LOCAL/MOCK: in-memory run log, lost on restart."""
LABEL = "LOCAL"
def __init__(self): self._runs: Dict[str, Dict] = {}
def log_run(self, run_id: str, params: Dict, metrics: Dict) -> None: self._runs[run_id] = {"params": params, "metrics": metrics, "logged_at": time.time()}
def get_run(self, run_id: str) -> Optional[Dict]: return self._runs.get(run_id)
class LocalObservability: """LOCAL/MOCK: in-memory counters; no alerting, no retention."""
LABEL = "LOCAL"
def __init__(self): self._counters: Dict[str, float] = {}
def emit_metric(self, name: str, value: float, tags: Optional[Dict] = None) -> None: tag_key = "" if not tags else "|" + ",".join( f"{k}={v}" for k, v in sorted(tags.items())) self._counters[name + tag_key] = self._counters.get(name + tag_key, 0.0) + value
def counters(self) -> Dict[str, float]: return dict(self._counters)
# ------------------------------------------------------------------ registry
@dataclassclass Registration: protocol: str implementation: Any label: str # LOCAL | MOCK | PRODUCTION production_options: str
_REGISTRY: Dict[str, Registration] = {}
def register(protocol: str, implementation: Any, label: str, production_options: str) -> None: _REGISTRY[protocol] = Registration(protocol, implementation, label, production_options)
def get_implementation(protocol: str) -> Any: return _REGISTRY[protocol].implementation
def describe_implementations() -> List[Dict]: return [{ "protocol": r.protocol, "implementation": type(r.implementation).__name__, "label": r.label, "production_options": r.production_options, } for r in _REGISTRY.values()]
def _register_defaults() -> None: from sensorflow.hardening.cache_manifest import FeatureCache, LocalDiskCache register("VectorDB", LocalBruteForceVectorDB(), "LOCAL", "Milvus / Qdrant / Vertex Matching Engine (HNSW, IVF-PQ)") register("ObjectStorage", LocalDiskObjectStorage(), "LOCAL", "S3 / GCS with versioning, lifecycle policies, SSE") register("DistributedCompute", LocalSerialCompute(), "LOCAL", "Spark / Ray / Dask (megaeval partials port directly)") register("GPUInference", MockGPUInference(), "MOCK", "Triton Inference Server / TensorRT / Ray Serve") register("FeatureCache", FeatureCache(LocalDiskCache(Path("runs/hardening/feature_cache"))), "LOCAL", "Object-store payloads + Redis/DB metadata for LRU") register("MetadataStore", LocalJsonMetadataStore(), "LOCAL", "Postgres + migrations; DataHub/OpenLineage for lineage") register("ExperimentTracking", LocalExperimentTracking(), "LOCAL", "MLflow / Weights & Biases") register("Observability", LocalObservability(), "LOCAL", "Prometheus + Grafana + OpenTelemetry")
_register_defaults()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209"""Sample-size derivation for evaluation sizing (audit F-010 support).
The platform's evaluation tiers previously used fixed counts with no powerjustification. This module derives the required n from the actual decisionparameters, so tier sizes follow from (baseline rate, MDE, alpha, power,prevalence, pairing correlation) instead of tradition.
Sequential/anytime aspects are OUT of scope here by design: for continuousmonitoring, delegate to sensorflow.seqeval (e-processes remain valid underoptional stopping; the fixed-n formulas below do not)."""
from __future__ import annotations
import mathfrom dataclasses import dataclassfrom typing import Dict, Optional
# Inverse standard normal CDF (Acklam's rational approximation, |err| < 1.2e-8;# avoids a scipy dependency for a handful of quantiles).def _norm_ppf(p: float) -> float: if not 0.0 < p < 1.0: raise ValueError("p must be in (0, 1)") a = [-3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02, 1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00] b = [-5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02, 6.680131188771972e+01, -1.328068155288572e+01] c = [-7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00, -2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00] d = [7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00, 3.754408661907416e+00] plow, phigh = 0.02425, 1 - 0.02425 if p < plow: q = math.sqrt(-2 * math.log(p)) return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / \ ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1) if p > phigh: q = math.sqrt(-2 * math.log(1 - p)) return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / \ ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1) q = p - 0.5 r = q * q return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q / \ (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1)
def required_n_two_proportions( baseline_rate: float, mde: float, alpha: float = 0.05, power: float = 0.8, two_sided: bool = True,) -> int: """Required n PER ARM to detect an absolute change `mde` in a proportion.
Standard two-sample proportion formula:
n = (z_{1-alpha[/2]} * sqrt(2 * p_bar * (1 - p_bar)) + z_{power} * sqrt(p1*(1-p1) + p2*(1-p2)))^2 / mde^2
where p1 = baseline_rate, p2 = p1 +/- mde (worse direction), p_bar = (p1 + p2) / 2. Larger MDE -> smaller n; smaller alpha or higher power -> larger n. """ if not 0 < baseline_rate < 1: raise ValueError("baseline_rate must be in (0, 1)") if mde <= 0: raise ValueError("mde must be positive") p1 = baseline_rate p2 = min(max(p1 + mde, 1e-9), 1 - 1e-9) p_bar = (p1 + p2) / 2 z_a = _norm_ppf(1 - alpha / (2 if two_sided else 1)) z_b = _norm_ppf(power) num = (z_a * math.sqrt(2 * p_bar * (1 - p_bar)) + z_b * math.sqrt(p1 * (1 - p1) + p2 * (1 - p2))) ** 2 return math.ceil(num / mde ** 2)
def required_n_paired( baseline_rate: float, mde: float, alpha: float = 0.05, power: float = 0.8, pairing_correlation: float = 0.0,) -> int: """Required PAIRS when both models are evaluated on the SAME items.
Pairing reduces the variance of the difference by (1 - rho):
var(p2_hat - p1_hat) ~ [p1(1-p1) + p2(1-p2) - 2*rho*sd1*sd2] / n
so n_paired ~ n_unpaired * (1 - rho) for sd1 ~ sd2. Positive correlation between paired outcomes (the common case: both models fail on the same hard frames) strictly reduces the required n; rho=0 recovers the independent formula. """ if not -1 < pairing_correlation < 1: raise ValueError("pairing_correlation must be in (-1, 1)") n_indep = required_n_two_proportions(baseline_rate, mde, alpha, power) return max(1, math.ceil(n_indep * (1 - pairing_correlation)))
def required_events_rare( prevalence: float, baseline_rate: float, mde: float, alpha: float = 0.05, power: float = 0.8,) -> Dict[str, int]: """Sizing when the metric only exists on a rare subpopulation.
If the failure mode occurs on a slice with `prevalence` in the fleet stream, the n from the proportion formula applies to SLICE items, so the raw stream requirement inflates by 1/prevalence:
n_slice = required_n_two_proportions(...) n_stream = ceil(n_slice / prevalence)
This is exactly why stratified oversampling (sampling.py) exists: mine slice items directly instead of paying the 1/prevalence stream tax. """ if not 0 < prevalence <= 1: raise ValueError("prevalence must be in (0, 1]") n_slice = required_n_two_proportions(baseline_rate, mde, alpha, power) return {"n_slice": n_slice, "n_stream": math.ceil(n_slice / prevalence)}
def cluster_design_effect(mean_cluster_size: float, icc: float) -> float: """Kish design effect for cluster-correlated data:
DEFF = 1 + (m_bar - 1) * ICC
Frames within a driving sequence are correlated (same scene, weather, model state); effective n = n / DEFF. Use rca.stats for ICC estimation. """ if mean_cluster_size < 1: raise ValueError("mean_cluster_size must be >= 1") if not 0 <= icc <= 1: raise ValueError("icc must be in [0, 1]") return 1.0 + (mean_cluster_size - 1.0) * icc
@dataclassclass TierSpec: name: str purpose: str baseline_rate: float mde: float alpha: float power: float prevalence: float = 1.0 pairing_correlation: float = 0.0 mean_cluster_size: float = 1.0 icc: float = 0.0
def tier_sizing(spec: TierSpec) -> Dict: """Derived (never fixed) size for one evaluation tier.
Pipeline: paired proportion n -> inflate by cluster DEFF -> inflate by 1/prevalence for the raw stream. All inputs and intermediate numbers are returned so the sizing is auditable. """ n_pairs = required_n_paired(spec.baseline_rate, spec.mde, spec.alpha, spec.power, spec.pairing_correlation) deff = cluster_design_effect(spec.mean_cluster_size, spec.icc) n_effective = math.ceil(n_pairs * deff) n_stream = math.ceil(n_effective / spec.prevalence) return { "tier": spec.name, "purpose": spec.purpose, "inputs": { "baseline_rate": spec.baseline_rate, "mde": spec.mde, "alpha": spec.alpha, "power": spec.power, "prevalence": spec.prevalence, "pairing_correlation": spec.pairing_correlation, "mean_cluster_size": spec.mean_cluster_size, "icc": spec.icc, }, "n_pairs": n_pairs, "design_effect": round(deff, 4), "n_slice_items": n_effective, "n_stream_items": n_stream, "sequential_note": "For continuous monitoring at this tier, use " "sensorflow.seqeval; these are fixed-n sizes.", }
def default_tiers() -> Dict[str, TierSpec]: """Tier 0-3 sizing driven by decision parameters, not fixed counts.
The parameter choices are explicit policy: smoke tests accept coarse MDEs; launch gates demand small MDEs on rare safety slices. """ return { "tier0": TierSpec("tier0", "smoke: catch gross breakage fast", baseline_rate=0.90, mde=0.10, alpha=0.05, power=0.80, pairing_correlation=0.5), "tier1": TierSpec("tier1", "PR gate: moderate regressions on common slices", baseline_rate=0.90, mde=0.03, alpha=0.05, power=0.80, pairing_correlation=0.5, mean_cluster_size=20, icc=0.1), "tier2": TierSpec("tier2", "release candidate: small regressions incl. rare slices", baseline_rate=0.95, mde=0.01, alpha=0.01, power=0.90, prevalence=0.05, pairing_correlation=0.5, mean_cluster_size=20, icc=0.1), "tier3": TierSpec("tier3", "launch gate: safety-critical slices", baseline_rate=0.99, mde=0.005, alpha=0.01, power=0.95, prevalence=0.01, pairing_correlation=0.5, mean_cluster_size=20, icc=0.1), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243"""Explicit quality evidence model, explainable routing, grader dependence.
Addresses audit F-015 (opaque HITL routing), F-012 (grader consensus treatedas independent evidence) and the platform-wide requirement that routingdecisions be evidence-decomposed and explainable.
Design rule enforced throughout: the DECOMPOSED evidence vector is theauthoritative object. The aggregate scalar exists only for sorting; everydecision cites the specific evidence dimensions that produced it."""
from __future__ import annotations
import mathfrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Dict, List, Optional, Sequence, Tuple
from pydantic import BaseModel, Field
class QualityEvidence(BaseModel): """Decomposed evidence about one label/proposal. All dimensions in [0, 1] where 1 is "good/confident" — except uncertainty, occlusion and safety_relevance where 1 means "high" (direction noted per field). None means "not measured" and is treated conservatively (never as 1.0)."""
geometric_validity: Optional[float] = None # 1 = geometrically sound sensor_agreement: Optional[float] = None # 1 = modalities agree temporal_consistency: Optional[float] = None # 1 = stable across frames semantic_agreement: Optional[float] = None # 1 = graders/models agree on class confidence: Optional[float] = None # model confidence uncertainty: Optional[float] = None # 1 = high epistemic uncertainty occlusion: Optional[float] = None # 1 = heavily occluded safety_relevance: Optional[float] = None # 1 = VRU/near-path/high severity
def missing_dimensions(self) -> List[str]: return [k for k, v in self.model_dump().items() if v is None]
class RoutingDecision(str, Enum): ACCEPT = "ACCEPT" HITL = "HITL" QUARANTINE = "QUARANTINE"
@dataclass(frozen=True)class RoutingPolicy: """Explicit, versioned routing thresholds (policy parameters, not magic).
Semantics: - QUARANTINE: evidence of an actively dangerous or unusable label (bad geometry, contradictory sensors) — block it from any downstream use until resolved. - HITL: not provably bad, but not trustworthy enough to auto-accept — low agreement, high uncertainty, safety-relevant, or unmeasured dimensions on a safety-relevant item. - ACCEPT: every measured dimension is healthy AND nothing safety-relevant is unmeasured. Incomplete telemetry can never be silently accepted. """
version: str = "routing-policy-v1" geometric_quarantine_below: float = 0.3 sensor_quarantine_below: float = 0.3 accept_min_good: float = 0.7 # every measured "good" dim must exceed accept_max_uncertainty: float = 0.3 safety_hitl_at_or_above: float = 0.5 # safety-relevant items always get eyes max_missing_for_accept: int = 0 # ACCEPT requires complete evidence
GOOD_DIMS = ("geometric_validity", "sensor_agreement", "temporal_consistency", "semantic_agreement", "confidence")BAD_DIMS = ("uncertainty", "occlusion")
def route(evidence: QualityEvidence, policy: RoutingPolicy = RoutingPolicy()) -> Dict: """Deterministic, explainable routing. Returns decision + per-decision explanation listing the exact evidence dimensions responsible.""" ev = evidence.model_dump() reasons: List[str] = []
# 1) Quarantine conditions: provably bad. if ev["geometric_validity"] is not None and \ ev["geometric_validity"] < policy.geometric_quarantine_below: reasons.append( f"geometric_validity={ev['geometric_validity']:.2f} < " f"{policy.geometric_quarantine_below} (physically implausible box)") if ev["sensor_agreement"] is not None and \ ev["sensor_agreement"] < policy.sensor_quarantine_below: reasons.append( f"sensor_agreement={ev['sensor_agreement']:.2f} < " f"{policy.sensor_quarantine_below} (modalities contradict — possible " f"phantom object or sensor fault)") if reasons: # Safety-relevant quarantines also demand human review of the quarantine. if (ev["safety_relevance"] or 0.0) >= policy.safety_hitl_at_or_above: reasons.append("safety_relevance high: quarantine escalated to human review") return {"decision": RoutingDecision.QUARANTINE, "explanation": reasons, "policy_version": policy.version, "evidence": ev}
# 2) HITL conditions: not trustworthy enough to auto-accept. missing = evidence.missing_dimensions() if (ev["safety_relevance"] or 0.0) >= policy.safety_hitl_at_or_above: reasons.append(f"safety_relevance={ev['safety_relevance']:.2f} >= " f"{policy.safety_hitl_at_or_above} (safety-relevant items always reviewed)") if ev["uncertainty"] is not None and ev["uncertainty"] > policy.accept_max_uncertainty: reasons.append(f"uncertainty={ev['uncertainty']:.2f} > {policy.accept_max_uncertainty}") for dim in GOOD_DIMS: if ev[dim] is not None and ev[dim] < policy.accept_min_good: reasons.append(f"{dim}={ev[dim]:.2f} < {policy.accept_min_good}") if len(missing) > policy.max_missing_for_accept: reasons.append(f"incomplete evidence ({', '.join(missing)} unmeasured) — " f"never silently accepted") if reasons: return {"decision": RoutingDecision.HITL, "explanation": reasons, "policy_version": policy.version, "evidence": ev}
# 3) Accept: complete evidence, everything healthy. return {"decision": RoutingDecision.ACCEPT, "explanation": ["all measured dimensions healthy; evidence complete"], "policy_version": policy.version, "evidence": ev}
def aggregate_score(evidence: QualityEvidence) -> float: """Sorting-only scalar (never a decision input): mean of good dims minus mean of bad dims, missing treated as 0 contribution and penalized.""" ev = evidence.model_dump() goods = [ev[d] for d in GOOD_DIMS if ev[d] is not None] bads = [ev[d] for d in BAD_DIMS if ev[d] is not None] missing_penalty = 0.05 * len(evidence.missing_dimensions()) g = sum(goods) / len(goods) if goods else 0.0 b = sum(bads) / len(bads) if bads else 0.0 return max(0.0, min(1.0, g - 0.5 * b - missing_penalty))
# ------------------------------------------------------------------ grader dependence## Layered on evaluation/graders.py WITHOUT modifying it (audit F-012). The# existing weighted-majority consensus treats each grader as independent# evidence; when graders share a backbone, training data, or architecture,# their errors correlate and k agreeing graders are worth fewer than k# independent opinions.
class GraderProfile(BaseModel): grader_id: str backbone: str = "" # e.g. "vit-l14" training_data: str = "" # e.g. "laion-2b" architecture: str = "" # e.g. "two-stage-detector"
#: How much shared infrastructure correlates two graders' ERRORS. These are#: priors to be replaced by measured error correlations once per-grader audit#: data exists (the honest path: estimate rho from disagreement-with-GT logs).SHARED_COMPONENT_RHO = { "backbone": 0.5, "training_data": 0.3, "architecture": 0.2,}
def dependence_matrix(profiles: Sequence[GraderProfile]) -> List[List[float]]: """Pairwise error-correlation prior from shared components (capped at 0.9).""" n = len(profiles) rho = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)] for i in range(n): for j in range(i + 1, n): r = 0.0 if profiles[i].backbone and profiles[i].backbone == profiles[j].backbone: r += SHARED_COMPONENT_RHO["backbone"] if profiles[i].training_data and \ profiles[i].training_data == profiles[j].training_data: r += SHARED_COMPONENT_RHO["training_data"] if profiles[i].architecture and \ profiles[i].architecture == profiles[j].architecture: r += SHARED_COMPONENT_RHO["architecture"] rho[i][j] = rho[j][i] = min(r, 0.9) return rho
def effective_grader_count(profiles: Sequence[GraderProfile]) -> float: """Effective number of independent graders under equicorrelated votes.
For k unit-variance votes with average pairwise correlation rho_bar, the variance of the mean is (1 + (k-1)*rho_bar)/k, so the equivalent number of independent votes is k_eff = k / (1 + (k-1) * rho_bar). k_eff == k when all graders are independent; k_eff -> 1 as rho_bar -> 1. """ k = len(profiles) if k <= 1: return float(k) rho = dependence_matrix(profiles) off_diag = [rho[i][j] for i in range(k) for j in range(k) if i != j] rho_bar = sum(off_diag) / len(off_diag) return k / (1.0 + (k - 1) * rho_bar)
def consensus_with_dependence( votes: Dict[str, str], profiles: Sequence[GraderProfile],) -> Dict: """Compute naive consensus AND independence-adjusted confidence, separately.
- naive_consensus: fraction of graders voting for the majority class (what evaluation/graders.py effectively reports). - adjusted_confidence: the same agreement level, but evaluated as if it came from k_eff independent graders instead of k. Using a normal approximation to the binomial vote margin, the z-score of the majority margin scales with sqrt(k_eff) rather than sqrt(k); we report Phi(margin * sqrt(k_eff)) which is strictly below the naive Phi(margin * sqrt(k)) whenever graders are correlated. """ if not votes: return {"majority_class": None, "naive_consensus": 0.0, "adjusted_confidence": 0.0, "effective_graders": 0.0} by_grader = {p.grader_id: p for p in profiles} counts: Dict[str, int] = {} for cls in votes.values(): counts[cls] = counts.get(cls, 0) + 1 majority = max(sorted(counts), key=lambda c: counts[c]) k = len(votes) naive = counts[majority] / k k_eff = effective_grader_count( [by_grader.get(g, GraderProfile(grader_id=g)) for g in votes])
margin = 2 * naive - 1.0 # majority margin in [-1, 1] z_adj = margin * math.sqrt(max(k_eff, 1e-9)) z_naive = margin * math.sqrt(k) phi = lambda z: 0.5 * (1 + math.erf(z / math.sqrt(2))) return { "majority_class": majority, "naive_consensus": round(naive, 6), "naive_confidence": round(phi(z_naive), 6), "adjusted_confidence": round(phi(z_adj), 6), "effective_graders": round(k_eff, 4), "total_graders": k, "dependence_note": ( "adjusted_confidence < naive_confidence indicates correlated " "graders; priors from shared backbone/data/architecture, to be " "replaced by measured error correlations."), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141"""Production-readiness scorecard computed from audit.json.
Rule enforced in code: NO "production ready" status can be reported whileany Critical finding remains open. The scorecard is derived, neverhand-written, so it cannot drift from the audit."""
from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Dict, List, Optional
AUDIT_JSON = Path(__file__).resolve().parents[2] / "docs" / "hardening" / "audit.json"
#: Category -> (prototype description, production requirement). Findings are#: assigned to categories via keyword match against their free-text audit#: `area` field (first matching category wins, in this order).CATEGORY_SPECS: Dict[str, Dict] = { "Data honesty & provenance": { "prototype": "Several legacy endpoints fabricate data or serve mocks unlabeled", "production": "Every payload carries provenance + simulated markers; " "LabelProvenance enforced at gates", "keywords": ["mock", "leakage", "provenance", "determinism / mock"], }, "Security": { "prototype": "Arbitrary path read/write, CORS wildcard with credentials, " "no authn", "production": "AuthN/AuthZ on all endpoints, path allowlists, strict CORS", "keywords": ["security"], }, "Safety configuration": { "prototype": "Magic severity weights, conflicting formulas, buried literals", "production": "Versioned threshold registry with per-value provenance; " "one severity definition", "keywords": ["safety thresholds", "scoring provenance"], }, "Caching & reproducibility": { "prototype": "Incomplete cache keys, no integrity checks, unseeded fallbacks", "production": "Manifest-keyed caches with checksums; all randomness seeded", "keywords": ["cache", "determinism", "configuration hygiene"], }, "HITL & triage": { "prototype": "FIFO review queues, arbitrary evidence snippets", "production": "Information-gain prioritization; router gated on precision " "AND critical-miss-rate", "keywords": ["hitl"], }, "Statistical validity": { "prototype": "Point-delta tolerances, rolling baselines, no power analysis " "outside seqeval", "production": "CI/e-process decisions, pinned baselines, derived sample " "sizes, multiplicity control", "keywords": ["regression statistics", "sampling", "grader", "novelty", "statistics", "anomaly ensemble", "meta-classifier"], }, "Metric correctness": { "prototype": "Cross-frame matching, ungated ID-swap matching, mAP misnomer", "production": "Frame-scoped matching, gated association, literature-" "consistent naming", "keywords": ["metric", "temporal", "geometric validation"], }, "Scalability & infrastructure": { "prototype": "In-process dicts and JSON files under runs/; single node", "production": "Storage/compute seams (interfaces.py) backed by managed " "services", "keywords": ["scalability"], },}
_FIXED_DISPOSITIONS = {"fix_now", "fix_now_partial", "fix_now_layered"}
def load_audit(path: Optional[Path] = None) -> Dict: p = path or AUDIT_JSON return json.loads(p.read_text())
def _categorize(findings: List[Dict]) -> Dict[str, List[Dict]]: """Assign each finding to the first category whose keyword matches its area.""" buckets: Dict[str, List[Dict]] = {name: [] for name in CATEGORY_SPECS} for f in findings: area = str(f.get("area", "")).lower() for name, spec in CATEGORY_SPECS.items(): if any(kw in area for kw in spec["keywords"]): buckets[name].append(f) break return buckets
def scorecard(audit: Optional[Dict] = None) -> Dict: """Category | Prototype | Production Requirement | Gap, from audit.json.""" audit = audit or load_audit() findings = audit.get("findings", []) buckets = _categorize(findings)
categories: List[Dict] = [] for name, spec in CATEGORY_SPECS.items(): related = buckets[name] open_findings = [f for f in related if f.get("disposition") not in _FIXED_DISPOSITIONS] open_critical = [f for f in open_findings if str(f.get("severity", "")).lower() == "critical"] partial = [f for f in related if f.get("disposition") in ("fix_now_partial", "fix_now_layered")]
if related and not open_findings and not partial: status = "closed" elif open_critical: status = "blocked_critical" elif open_findings: status = "gaps_open" elif partial: status = "partially_hardened" else: status = "no_findings"
categories.append({ "category": name, "prototype": spec["prototype"], "production_requirement": spec["production"], "gap_count": len(open_findings), "open_finding_ids": [f["id"] for f in open_findings], "open_critical_ids": [f["id"] for f in open_critical], "partially_fixed_ids": [f["id"] for f in partial], "status": status, })
any_open_critical = any( str(f.get("severity", "")).lower() == "critical" and f.get("disposition") not in _FIXED_DISPOSITIONS for f in findings)
return { "categories": categories, "overall_status": "NOT_PRODUCTION_READY" if any_open_critical else ("HARDENING_IN_PROGRESS" if any(c["gap_count"] for c in categories) else "READY_CANDIDATE"), "rule": "No production-ready status while any Critical finding is open.", "summary": audit.get("summary", {}), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""Versioned safety-threshold registry with per-value provenance.
Audit F-007: the same "severity" concept is computed with TWO differentmagic weightings in app_backend.py (line ~1101 vs ~1139), and TTC/PETscenario cutoffs are buried as literals in evaluation/rare_events.py. Noneof them carries provenance. This registry centralizes every audited value,tags each with where it came from and whether it is defensible policy or anillustrative placeholder, and versions the whole set so a SafetyAssessmentcan record exactly which config produced it.
Provenance labels:- FHWA_SSAM_DEFAULT: consistent with FHWA Surrogate Safety Assessment Model guidance (e.g. TTC < 1.5 s as critical-conflict threshold).- ILLUSTRATIVE_THRESHOLD: a prototype constant with NO documented safety basis. It must not gate a real launch; replace with policy-derived values.
Wiring status: sensorflow/safety/ssam_ext.py already documents its defaults;app_backend.py wiring is a follow-up (one-additive-edit budget, see audit)."""
from __future__ import annotations
from dataclasses import dataclass, fieldfrom typing import Dict, List, Optional
CONFIG_VERSION = "safety-config-v1"
FHWA_SSAM_DEFAULT = "FHWA_SSAM_DEFAULT"ILLUSTRATIVE_THRESHOLD = "ILLUSTRATIVE_THRESHOLD"
@dataclass(frozen=True)class ThresholdSpec: name: str value: float unit: str provenance: str # FHWA_SSAM_DEFAULT | ILLUSTRATIVE_THRESHOLD source: str # FILE:LINE or document reference description: str = ""
# Every audited literal, in one place. Names are namespaced by the component# that used them so the two conflicting severity weightings are both visible.THRESHOLDS: Dict[str, ThresholdSpec] = {spec.name: spec for spec in [ # --- SSAM conflict thresholds (defensible) ------------------------------- ThresholdSpec("ssam.ttc_critical_s", 1.5, "s", FHWA_SSAM_DEFAULT, "FHWA-HRT-08-051; safety/ssam_ext.py defaults", "TTC below this marks a critical conflict."), ThresholdSpec("ssam.pet_critical_s", 5.0, "s", FHWA_SSAM_DEFAULT, "FHWA SSAM guidance; app_backend.py:1101", "PET cap used in severity normalization."), # --- Legacy severity weighting #1 (app_backend._compute_severity) -------- ThresholdSpec("legacy.severity.ttc_weight", 0.5, "unitless", ILLUSTRATIVE_THRESHOLD, "app_backend.py:1101", "Weight of normalized TTC in severity_index."), ThresholdSpec("legacy.severity.pet_weight", 0.2, "unitless", ILLUSTRATIVE_THRESHOLD, "app_backend.py:1101", "Weight of normalized PET in severity_index."), ThresholdSpec("legacy.severity.speed_weight", 0.3, "unitless", ILLUSTRATIVE_THRESHOLD, "app_backend.py:1101", "Weight of normalized max_speed in severity_index."), ThresholdSpec("legacy.severity.speed_cap_mps", 18.0, "m/s", ILLUSTRATIVE_THRESHOLD, "app_backend.py:1101", "Speed normalization cap."), # --- Legacy severity weighting #2 (streets endpoint) — CONFLICTS with #1 - ThresholdSpec("legacy.streets.ttc_weight", 0.7, "unitless", ILLUSTRATIVE_THRESHOLD, "app_backend.py:1139", "DIFFERENT weighting for the same severity concept; the two " "endpoints disagree about identical inputs (audit F-007)."), ThresholdSpec("legacy.streets.pet_weight", 0.3, "unitless", ILLUSTRATIVE_THRESHOLD, "app_backend.py:1139", "See above."), # --- Severity band cutoffs ------------------------------------------------ ThresholdSpec("legacy.severity.band_critical", 0.7, "unitless", ILLUSTRATIVE_THRESHOLD, "app_backend.py:1103", "severity_index >= this -> Critical."), ThresholdSpec("legacy.severity.band_high", 0.45, "unitless", ILLUSTRATIVE_THRESHOLD, "app_backend.py:1105", "severity_index >= this -> High."), ThresholdSpec("legacy.severity.band_medium", 0.25, "unitless", ILLUSTRATIVE_THRESHOLD, "app_backend.py:1107", "severity_index >= this -> Medium."), # --- Rare-event scenario cutoffs ------------------------------------------ ThresholdSpec("rare_events.ttc_extreme_s", 3.0, "s", ILLUSTRATIVE_THRESHOLD, "evaluation/rare_events.py:84", "extreme_ttc scenario cutoff."), ThresholdSpec("rare_events.ttc_near_collision_s", 1.8, "s", ILLUSTRATIVE_THRESHOLD, "evaluation/rare_events.py:86", "near_collision scenario cutoff."), ThresholdSpec("rare_events.pet_extreme_s", 1.5, "s", ILLUSTRATIVE_THRESHOLD, "evaluation/rare_events.py:89", "extreme_pet scenario cutoff."), # --- Legacy quality gate --------------------------------------------------- ThresholdSpec("quality_gate.map_3d_min", 0.65, "unitless", ILLUSTRATIVE_THRESHOLD, "sensorflow/quality_gate.py:24", "Launch-gate mAP floor."), ThresholdSpec("quality_gate.orientation_error_max_deg", 5.0, "deg", ILLUSTRATIVE_THRESHOLD, "sensorflow/quality_gate.py:25", "Launch-gate orientation ceiling."), ThresholdSpec("quality_gate.id_swap_rate_max", 0.02, "unitless", ILLUSTRATIVE_THRESHOLD, "sensorflow/quality_gate.py:26", "Launch-gate ID-swap ceiling."), ThresholdSpec("quality_gate.fragmentation_rate_max", 0.05, "unitless", ILLUSTRATIVE_THRESHOLD, "sensorflow/quality_gate.py:27", "Launch-gate fragmentation ceiling."), ThresholdSpec("quality_gate.position_error_max_m", 2.0, "m", ILLUSTRATIVE_THRESHOLD, "sensorflow/quality_gate.py:28", "Launch-gate position-error ceiling."),]}
def get_threshold(name: str) -> ThresholdSpec: return THRESHOLDS[name]
def compute_severity(ttc_s: Optional[float], pet_s: Optional[float], max_speed_mps: Optional[float]) -> Dict: """Canonical severity computation replacing the two conflicting legacy weightings (F-007). Same functional form as app_backend._compute_severity, but every constant is sourced from the registry, missing inputs degrade the confidence rather than defaulting silently, and the config version is stamped on the result. """ used: List[str] = [] score = 1.0 if ttc_s is not None: cap = THRESHOLDS["ssam.ttc_critical_s"].value w = THRESHOLDS["legacy.severity.ttc_weight"].value score -= (min(ttc_s, cap) / cap) * w used.append("ttc") if pet_s is not None: cap = THRESHOLDS["ssam.pet_critical_s"].value w = THRESHOLDS["legacy.severity.pet_weight"].value score -= (min(pet_s, cap) / cap) * w used.append("pet") if max_speed_mps is not None: cap = THRESHOLDS["legacy.severity.speed_cap_mps"].value w = THRESHOLDS["legacy.severity.speed_weight"].value score -= (1.0 - min(max_speed_mps, cap) / cap) * w used.append("speed")
score = round(max(0.0, min(1.0, score)), 3) if score >= THRESHOLDS["legacy.severity.band_critical"].value: label = "Critical" elif score >= THRESHOLDS["legacy.severity.band_high"].value: label = "High" elif score >= THRESHOLDS["legacy.severity.band_medium"].value: label = "Medium" else: label = "Low" return { "severity_index": score, "severity_label": label, "inputs_used": used, "inputs_missing": [k for k in ("ttc", "pet", "speed") if k not in used], "config_version": CONFIG_VERSION, "weights_provenance": ILLUSTRATIVE_THRESHOLD, }
def registry_summary() -> List[Dict]: return [ {"name": s.name, "value": s.value, "unit": s.unit, "provenance": s.provenance, "source": s.source, "description": s.description} for s in THRESHOLDS.values() ]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236"""Corrected scenario ranking and stratified sampling with reweighting.
Fixes the audit's sampling findings for the legacy paths (F-020: arbitraryrarity coefficients and confidence-from-rarity; "most interesting first"ordering biasing P(failure) estimates):
1. Ranking is deterministic and evidence-decomposed (no unseeded randomness, no collapsed opaque score without its components).2. Evaluation sets are drawn by STRATIFIED sampling with explicit quotas, and every drawn item carries an inverse-inclusion-probability weight so fleet-level rates can be estimated without oversampling bias (Horvitz-Thompson, same estimator megaeval.sampling already uses — that implementation was verified correct, F-029).3. Novelty is real geometry over embeddings: kNN distance and centroid distance, with the trade-offs documented on each scorer."""
from __future__ import annotations
from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Dict, List, Optional, Sequence, Tuple
import numpy as np
class Stratum(str, Enum): REPRESENTATIVE = "Representative" NOMINAL = "Nominal" RARE = "Rare" SAFETY_CRITICAL = "SafetyCritical" KNOWN_FAILURES = "KnownFailures" NOVEL = "Novel" DISTRIBUTION_SHIFTED = "DistributionShifted"
#: Default sampling quotas (fraction of the evaluation budget per stratum).#: These are POLICY parameters — explicit, versioned, and overridable — not#: buried magic numbers. They intentionally oversample rare/safety strata;#: the HT weights below undo that oversampling for population estimates.DEFAULT_QUOTAS: Dict[Stratum, float] = { Stratum.REPRESENTATIVE: 0.30, Stratum.NOMINAL: 0.15, Stratum.RARE: 0.15, Stratum.SAFETY_CRITICAL: 0.15, Stratum.KNOWN_FAILURES: 0.10, Stratum.NOVEL: 0.10, Stratum.DISTRIBUTION_SHIFTED: 0.05,}
@dataclassclass SampledItem: item_id: str stratum: Stratum inclusion_probability: float weight: float # 1 / inclusion_probability (Horvitz-Thompson)
@dataclassclass StratifiedSample: items: List[SampledItem] quotas: Dict[Stratum, int] population_sizes: Dict[Stratum, int] seed: int
def estimate_population_rate(self, indicator: Dict[str, float]) -> Optional[float]: """HT estimate of a population mean/rate from the stratified sample.
indicator: item_id -> 0/1 (or real-valued) outcome measured on the sample. Returns sum(w_i * y_i) / sum over population size — i.e. the stratum-weighted mean that recovers the true population rate under oversampling (each stratum's sample mean weighted by its true share). """ total_pop = sum(self.population_sizes.values()) if total_pop == 0: return None est = 0.0 for stratum, pop in self.population_sizes.items(): in_stratum = [it for it in self.items if it.stratum == stratum and it.item_id in indicator] if not in_stratum: if pop > 0: return None # a non-empty stratum with no measurements: refuse continue stratum_mean = float(np.mean([indicator[it.item_id] for it in in_stratum])) est += (pop / total_pop) * stratum_mean return est
def stratified_sample( population: Dict[Stratum, Sequence[str]], budget: int, quotas: Optional[Dict[Stratum, float]] = None, seed: int = 0,) -> StratifiedSample: """Draw a stratified sample with explicit quotas and HT weights.
- Quota fractions are converted to integer counts by largest-remainder allocation (fixes the naive-rounding caveat noted in the audit, F-029). - Sampling within a stratum is uniform without replacement, from a seeded generator: same seed -> same sample, always. - If a stratum has fewer items than its quota, the whole stratum is taken (inclusion probability 1) and the leftover budget is redistributed to the remaining strata proportionally. """ quotas = quotas or DEFAULT_QUOTAS rng = np.random.default_rng(seed)
# Largest-remainder integer allocation of the budget. fracs = {s: quotas.get(s, 0.0) for s in population} total_frac = sum(fracs.values()) or 1.0 raw = {s: budget * f / total_frac for s, f in fracs.items()} alloc = {s: int(v) for s, v in raw.items()} remainders = sorted(raw, key=lambda s: raw[s] - alloc[s], reverse=True) for s in remainders[: budget - sum(alloc.values())]: alloc[s] += 1
# Cap at stratum size; redistribute leftovers deterministically. leftover = 0 for s in sorted(alloc, key=lambda s: s.value): n_avail = len(population[s]) if alloc[s] > n_avail: leftover += alloc[s] - n_avail alloc[s] = n_avail while leftover > 0: expandable = [s for s in sorted(alloc, key=lambda s: s.value) if alloc[s] < len(population[s])] if not expandable: break for s in expandable: if leftover == 0: break alloc[s] += 1 leftover -= 1
items: List[SampledItem] = [] for s in sorted(population, key=lambda s: s.value): ids = sorted(population[s]) # order-independence: canonical order first k = alloc.get(s, 0) if k == 0 or not ids: continue chosen = rng.choice(len(ids), size=k, replace=False) p_inc = k / len(ids) for idx in sorted(chosen.tolist()): items.append(SampledItem( item_id=ids[idx], stratum=s, inclusion_probability=p_inc, weight=1.0 / p_inc, ))
return StratifiedSample( items=items, quotas=alloc, population_sizes={s: len(v) for s, v in population.items()}, seed=seed, )
# ------------------------------------------------------------------ novelty
def knn_novelty(embeddings: np.ndarray, reference: np.ndarray, k: int = 10) -> np.ndarray: """Novelty = mean Euclidean distance to the k nearest reference embeddings.
Trade-offs: sensitive to LOCAL density, so it finds points in sparse pockets even inside the reference hull (good for multi-modal fleets); cost is O(n_query * n_reference) without an index — use the VectorDB interface (interfaces.py) with an ANN index at production scale. k too small -> noisy; k too large -> smooths away small novel clusters. """ if len(reference) == 0: return np.full(len(embeddings), np.inf) k = min(k, len(reference)) # Chunked exact distances; replace with ANN via VectorDB in production. out = np.empty(len(embeddings)) for i in range(0, len(embeddings), 1024): chunk = embeddings[i:i + 1024] d = np.linalg.norm(chunk[:, None, :] - reference[None, :, :], axis=2) d.sort(axis=1) out[i:i + 1024] = d[:, :k].mean(axis=1) return out
def centroid_novelty(embeddings: np.ndarray, reference: np.ndarray) -> np.ndarray: """Novelty = distance to the reference centroid, scaled by mean spread.
Trade-offs: O(n) and index-free, but UNIMODAL — it misses novel points that sit near the global centroid of a multi-modal distribution and over-flags legitimate points on the far side of a wide mode. Use as a cheap first pass; confirm with knn_novelty before routing on it. """ if len(reference) == 0: return np.full(len(embeddings), np.inf) centroid = reference.mean(axis=0) spread = float(np.mean(np.linalg.norm(reference - centroid, axis=1))) or 1.0 return np.linalg.norm(embeddings - centroid, axis=1) / spread
# ------------------------------------------------------------------ ranking
@dataclassclass RankedScenario: scenario_id: str score: float components: Dict[str, float] = field(default_factory=dict)
def rank_scenarios( scenario_ids: Sequence[str], component_scores: Dict[str, Dict[str, float]], weights: Optional[Dict[str, float]] = None,) -> List[RankedScenario]: """Deterministic, decomposed scenario ranking for REVIEW ordering only.
component_scores: component name -> {scenario_id -> score in [0, 1]}. The returned score keeps its components attached so every ranking is explainable. Ties break on scenario_id, so the order is fully deterministic regardless of dict insertion order.
IMPORTANT: this ordering must never be used to SELECT an evaluation set — "most interesting first" selection biases P(failure) estimates upward. Selection goes through stratified_sample(); ranking only orders items already selected (or a human review queue). """ weights = weights or {name: 1.0 for name in component_scores} ranked = [] for sid in scenario_ids: comps = {name: float(scores.get(sid, 0.0)) for name, scores in component_scores.items()} total_w = sum(weights.get(n, 0.0) for n in comps) or 1.0 score = sum(comps[n] * weights.get(n, 0.0) for n in comps) / total_w ranked.append(RankedScenario(scenario_id=sid, score=round(score, 9), components=comps)) ranked.sort(key=lambda r: (-r.score, r.scenario_id)) return ranked114 unmodified lines115116117118119120121122104 unmodified lines227228229230231232233114 unmodified lines@staticmethoddef key(dataset_version: str, model_version: str, filters: Dict,group_by: List[str], metrics: List[str]) -> str:blob = json.dumps({"d": dataset_version, "m": model_version,"f": {k: sorted(v) for k, v in sorted((filters or {}).items())},"g": list(group_by or []), "x": sorted(metrics or []),104 unmodified linest0 = time.perf_counter()metrics = metrics or []key = QueryCache.key(run.population_id, run.model_version,filters or {}, group_by or [], metrics)cached = self.cache.get(key)if cached is not None:return {**cached,114 unmodified lines115116117118119120121122123124125126127104 unmodified lines232233234235236237238239114 unmodified lines@staticmethoddef key(dataset_version: str, model_version: str, filters: Dict,group_by: List[str], metrics: List[str], run_id: str = "") -> str:# run_id pins the full run lineage (label version, overrides, seed,# threshold config). Without it, two runs on the same population+model# (e.g. a baseline and a run with injected regressions) collide and# the cache serves one run's rows for the other.blob = json.dumps({"r": run_id,"d": dataset_version, "m": model_version,"f": {k: sorted(v) for k, v in sorted((filters or {}).items())},"g": list(group_by or []), "x": sorted(metrics or []),104 unmodified linest0 = time.perf_counter()metrics = metrics or []key = QueryCache.key(run.population_id, run.model_version,filters or {}, group_by or [], metrics,run_id=getattr(run, "run_id", ""))cached = self.cache.get(key)if cached is not None:return {**cached,
105 unmodified lines10610710810911011111212 unmodified lines125126127128129130105 unmodified linesall_gts: List[List[float]],iou_thresholds: List[float] = None,) -> Dict[str, float]:"""Compute mean AP and mean AR across IoU thresholds."""iou_thresholds = iou_thresholds or [0.5, 0.7]aps, ars = [], []for thresh in iou_thresholds:12 unmodified lines}def mean_orientation_error(matched_pairs: List[Tuple[List[float], List[float]]]) -> float:"""Mean absolute yaw error in degrees."""if not matched_pairs:105 unmodified lines10610710810911011111211311411511611711811912012112 unmodified lines134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178105 unmodified linesall_gts: List[List[float]],iou_thresholds: List[float] = None,) -> Dict[str, float]:"""Set-level precision/recall at fixed IoU thresholds (NOT literature mAP).Despite the key names ("map_3d"/"mar_3d", kept for API compatibility),this computes greedy-matched precision and recall averaged over the givenIoU thresholds. It does NOT rank detections by confidence or integrate aprecision-recall curve, so it is not comparable to COCO/nuScenes mAP.Matching is performed over the box sets as given: callers are responsiblefor scoping the inputs to a single frame (see compute_map_mar_by_frame),otherwise boxes from different timestamps can match each other."""iou_thresholds = iou_thresholds or [0.5, 0.7]aps, ars = [], []for thresh in iou_thresholds:12 unmodified lines}def compute_map_mar_by_frame(preds_by_frame: Dict[str, List[List[float]]],gts_by_frame: Dict[str, List[List[float]]],iou_thresholds: List[float] = None,) -> Dict[str, float]:"""Frame-scoped precision/recall at fixed IoU thresholds (micro-averaged).Matching runs independently within each frame, so a prediction can onlymatch ground truth from the same timestamp. TP/FP/FN counts are summedacross frames before ratios are taken. Same naming caveat ascompute_map_mar: "map_3d"/"mar_3d" are precision/recall at fixed IoUthresholds, not ranked average precision."""iou_thresholds = iou_thresholds or [0.5, 0.7]frame_ids = sorted(set(preds_by_frame) | set(gts_by_frame))aps, ars = [], []for thresh in iou_thresholds:tp = fp = fn = 0for fid in frame_ids:pairs, unmatched_pred, unmatched_gt = _match_boxes(preds_by_frame.get(fid, []), gts_by_frame.get(fid, []), thresh)tp += len(pairs)fp += len(unmatched_pred)fn += len(unmatched_gt)aps.append(tp / (tp + fp) if (tp + fp) > 0 else 0.0)ars.append(tp / (tp + fn) if (tp + fn) > 0 else 0.0)matched_ious = []for fid in frame_ids:pairs, _, _ = _match_boxes(preds_by_frame.get(fid, []), gts_by_frame.get(fid, []), 0.5)matched_ious.extend(p[2] for p in pairs)return {"map_3d": float(np.mean(aps)) if aps else 0.0,"mar_3d": float(np.mean(ars)) if ars else 0.0,"mean_iou_3d": float(np.mean(matched_ious)) if matched_ious else 0.0,}def mean_orientation_error(matched_pairs: List[Tuple[List[float], List[float]]]) -> float:"""Mean absolute yaw error in degrees."""if not matched_pairs:
8 unmodified lines910111213141516171821 unmodified lines404142434445468 unmodified linesdef compute_id_swap_rate(pred_tracks: List[Dict],gt_tracks: List[Dict],) -> float:"""Count ID swaps: when GT instance_id is stable but pred track_id changes.pred_tracks/gt_tracks: [{track_id/instance_id, frames: [{frame_id, bbox_3d}]}]"""swaps = 0total_updates = 021 unmodified linesfor tid, pframes in pred_by_track.items():if fid in pframes:dist = _center_dist(pframes[fid], gt_frames[fid])if dist < best_dist:best_dist = distbest_tid = tidif best_tid is not None:8 unmodified lines910111213141516171819202122232421 unmodified lines464748495051528 unmodified linesdef compute_id_swap_rate(pred_tracks: List[Dict],gt_tracks: List[Dict],match_threshold_m: float = 2.0,) -> float:"""Count ID swaps: when GT instance_id is stable but pred track_id changes.pred_tracks/gt_tracks: [{track_id/instance_id, frames: [{frame_id, bbox_3d}]}]Candidate pred tracks must lie within `match_threshold_m` of the GT box(same gate as fragmentation). Without the gate, an arbitrarily distanttrack becomes the "match" whenever the true one is absent, manufacturingphantom swaps (or hiding real ones)."""swaps = 0total_updates = 021 unmodified linesfor tid, pframes in pred_by_track.items():if fid in pframes:dist = _center_dist(pframes[fid], gt_frames[fid])if dist < best_dist and dist < match_threshold_m:best_dist = distbest_tid = tidif best_tid is not None:
2 unmodified lines345678910111213141516172 unmodified linesfrom __future__ import annotationsimport jsonfrom pathlib import Pathfrom typing import Any, Dict, List, Optionalimport httpxOLLAMA_ENDPOINTS = [{"url": "http://dgx-spark.tail16d8d9.ts.net:11434/api/chat", "model": "gemma4:26b"},{"url": "http://localhost:11434/api/chat", "model": "gemma4:latest"},]MITL_QUEUE_PATH = Path("runs/pipeline/mitl_queue.json")2 unmodified lines3456789101112131415161718192021222324252627282930313233342 unmodified linesfrom __future__ import annotationsimport jsonimport osfrom pathlib import Pathfrom typing import Any, Dict, List, Optionalimport httpxdef _llm_endpoints() -> List[Dict[str, str]]:"""LLM endpoints in fallback order, configurable via environment.SENSORFLOW_LLM_URL / SENSORFLOW_LLM_MODEL prepend a primary endpoint(e.g. a remote GPU box); local Ollama is always the last fallback.Deployment-specific hostnames must never be hard-coded in source."""endpoints: List[Dict[str, str]] = []url = os.environ.get("SENSORFLOW_LLM_URL")if url:endpoints.append({"url": url,"model": os.environ.get("SENSORFLOW_LLM_MODEL", "gemma4:latest"),})endpoints.append({"url": "http://localhost:11434/api/chat", "model": "gemma4:latest"})return endpointsOLLAMA_ENDPOINTS = _llm_endpoints()MITL_QUEUE_PATH = Path("runs/pipeline/mitl_queue.json")
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""Next-Generation AV Perception Evaluation platform (Features 2-5).
This package adds four capabilities on top of the existing evaluationsubstrate, plus the architecture decision deliverables underdocs/architecture/:
2. Counterfactual simulation with validity gating (:mod:`counterfactual`, :mod:`worldmodel`, :mod:`validity`)3. Closed-loop behavioral evaluation + causal counterfactual replay (:mod:`closedloop`, :mod:`causal`)4. Safety-informed metrics (Safety-Critical Recall, risk-weighted metrics) (:mod:`safety_metrics`)5. Compute dedup + intelligent launch-eval scheduling (:mod:`cache`, :mod:`compute`, :mod:`scheduler`, :mod:`regression`, :mod:`lineage`)
Design principles enforced in code----------------------------------* Evidence before inference: every metric, gate and verdict here is deterministic math on data; nothing is decided by a model's opinion.* Open-loop AND closed-loop metrics are complementary: closed-loop behavioral reports always carry the open-loop metrics (mAP/recall/IoU) alongside; no report replaces them.* Simulation is evidence, not reality: every datum carries a :class:`sensorflow.nextgen.models.DataLabel` (REAL / REPLAYED / SIMULATED / GENERATED / COUNTERFACTUAL) which is carried through every downstream report.* Deterministic safety policy: gate thresholds are explicit, versioned parameters; the same inputs always produce the same launch recommendation.* Scale without linear recompute: the content-addressed feature cache (:mod:`cache`) and the anytime-valid early-stopping scheduler (:mod:`scheduler`, delegating to :mod:`sensorflow.seqeval`) together keep a 100k-scenario gauntlet sublinear in full-inference cost.* Design for deletion / reuse > extend > new. Reuse map (each documented at the point of use):
- sensorflow.bevfusion scenes/sensors/engines/evaluate: the scenario, sensor-simulation and perception substrate. Counterfactuals are transformations of its SceneSequence; closed-loop runs its sensor models. - sensorflow.seqeval ALL sequential statistics: anytime-valid e-process early stopping, cluster units, paired deltas. - sensorflow.safety ssam_ext TTC/DRAC/collision-probability/stopping math; gate structuring conventions; ODD strata. - sensorflow.megaeval distribution-shift machinery (train-vs-eval mix) and metric-cube aggregation patterns. - sensorflow.rca.stats PSI/JS divergence primitives (imported read-only with a guarded fallback). - sensorflow.vitis optional optical-flow temporal cross-check (guarded import; absent -> skipped, reported). - sensorflow.agentic Feature 1 (built concurrently by another agent): guarded import for the AgenticSafetyScorecard shape; a compatible local definition is used when the package is not importable."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329"""FastAPI router for the Next-Generation AV Perception Evaluation platform.
Included by app_backend with prefix /api/nextgen. All artifacts persistunder runs/nextgen/ (store.py)."""
from __future__ import annotations
from pathlib import Pathfrom typing import Any, Dict, List, Optionalfrom uuid import uuid4
from fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field
from sensorflow.nextgen import causal as causal_modfrom sensorflow.nextgen import compute as compute_modfrom sensorflow.nextgen import counterfactual as cf_modfrom sensorflow.nextgen import lineage as lineage_modfrom sensorflow.nextgen import safety_metrics as sm_modfrom sensorflow.nextgen import scheduler as sched_modfrom sensorflow.nextgen import storefrom sensorflow.nextgen import validity as validity_modfrom sensorflow.nextgen.closedloop import DEFAULT_ENGINE, ENGINE_PROFILES, run_closed_loopfrom sensorflow.nextgen.models import ( AGENTIC_SCORECARD_SOURCE, DataLabel, DistributionShiftAssessment, TransformationStep,)
router = APIRouter(prefix="/api/nextgen")
_DOCS_DIR = Path(__file__).resolve().parents[2] / "docs" / "architecture"_DOC_FILES = { "comparison": "nextgen-architecture-comparison.md", "adr": "nextgen-adr.md", "rollout": "nextgen-rollout.md", "worldmodel": "nextgen-worldmodel-generative-comparison.md",}
# ------------------------------------------------------------ status
@router.get("/status")def status(): return { "package": "sensorflow.nextgen", "engines": sorted(ENGINE_PROFILES), "transformations": sorted(cf_mod.TRANSFORMATIONS), "counterfactuals": len(store.list_json("counterfactuals")), "gauntlets": sched_mod.list_gauntlets(), "compute_report_available": compute_mod.latest_report() is not None, "agentic_scorecard_source": AGENTIC_SCORECARD_SOURCE, "data_labels": [d.value for d in DataLabel], "component_versions": lineage_mod.COMPONENT_VERSIONS, }
# ------------------------------------------------------------ counterfactuals
class GenerateRequest(BaseModel): recipe: List[TransformationStep] seed: int = 7 n_scenarios: int = Field(3, ge=1, le=12) frames_per_sequence: int = Field(40, ge=10, le=80)
@router.get("/counterfactuals/catalogue")def catalogue(): return {"transformations": cf_mod.transformation_catalogue()}
@router.post("/counterfactuals/generate")def generate(req: GenerateRequest): if not req.recipe: raise HTTPException(422, "recipe must contain at least one transformation") try: scenarios = cf_mod.generate_counterfactuals( req.recipe, seed=req.seed, n_scenarios=req.n_scenarios, frames_per_sequence=req.frames_per_sequence) except ValueError as e: raise HTTPException(422, str(e)) return {"scenarios": [s.model_dump(mode="json") for s in scenarios]}
@router.get("/counterfactuals")def list_counterfactuals(): return {"scenarios": [s.model_dump(mode="json") for s in cf_mod.list_scenarios()]}
@router.post("/counterfactuals/{scenario_id}/validate")def validate(scenario_id: str): bundle = cf_mod.load_bundle(scenario_id) if bundle is None: raise HTTPException(404, f"unknown scenario {scenario_id}") scenario = bundle["scenario"] report = validity_mod.validate_scenario( scenario_id, bundle["sequence"], bundle["actors"], scenario.environment, scenario.provenance.seed, source_overlap_pairs=bundle.get("source_overlap_pairs"), source_features=bundle.get("source_features")) scenario.validity = report cf_mod.save_scenario(scenario) return report.model_dump(mode="json")
@router.get("/counterfactuals/suite-weights")def suite_weights(): """Suite-level weight policy over every validated scenario.""" reports = [s.validity for s in cf_mod.list_scenarios() if s.validity] return validity_mod.apply_suite_weight_policy(reports)
# ------------------------------------------------------------ closed loop
class ReplayRequest(BaseModel): scenario_id: str engine: str = DEFAULT_ENGINE seed: int = 0 corrected: bool = False faults: List[Dict[str, Any]] = Field(default_factory=list)
def _resolve_scenario(scenario_id: str, faults: List[Dict[str, Any]], default_demo_fault: bool = False): """Returns (actors, environment, scenario_id, data_label, faults).""" if scenario_id in ("demo", "demo-occluded-emergence"): from sensorflow.nextgen.closedloop import demo_emergence_scenario demo = demo_emergence_scenario() if not faults and default_demo_fault: # Out-of-the-box causal demo: the emergent pedestrian is missed # until far too late. faults = [{"type": "miss", "instance_id": demo["critical_instance_id"], "from_s": 0.0, "until_s": 4.0}] return (demo["actors"], demo["environment"], demo["scenario_id"], DataLabel.COUNTERFACTUAL, faults) bundle = cf_mod.load_bundle(scenario_id) if bundle is None: raise HTTPException(404, f"unknown scenario {scenario_id}; generate " f"counterfactuals first or use scenario_id='demo'") scenario = bundle["scenario"] return (bundle["actors"], scenario.environment, scenario.scenario_id, scenario.provenance.data_label, faults)
@router.post("/simulation/replay")def simulation_replay(req: ReplayRequest): if req.engine not in ENGINE_PROFILES: raise HTTPException(422, f"unknown engine {req.engine}") actors, env, sid, label, faults = _resolve_scenario(req.scenario_id, req.faults) assessment = run_closed_loop(actors, env, sid, label, engine=req.engine, seed=req.seed, corrected=req.corrected, faults=faults) result = assessment.model_dump(mode="json") store.write_json(result, "closedloop", f"{sid}-{req.engine}.json") return result
@router.post("/causal/replay")def causal_replay(req: ReplayRequest): if req.engine not in ENGINE_PROFILES: raise HTTPException(422, f"unknown engine {req.engine}") actors, env, sid, label, faults = _resolve_scenario( req.scenario_id, req.faults, default_demo_fault=True) result = causal_mod.causal_replay(actors, env, sid, label, engine=req.engine, seed=req.seed, faults=faults) payload = result.model_dump(mode="json") store.write_json(payload, "causal", f"{sid}.json") return payload
# ------------------------------------------------------------ safety metrics
class SafetyReportRequest(BaseModel): objects: Optional[List[Dict[str, Any]]] = None ego_speed_mps: float = 10.0 reaction_time_s: float = 0.9 brake_capability_mps2: float = 7.0 friction_mu: float = 0.9
@router.post("/metrics/safety-report")def safety_report(req: SafetyReportRequest): params = sm_mod.SafetyRegionParams( reaction_time_s=req.reaction_time_s, brake_capability_mps2=req.brake_capability_mps2, friction_mu=req.friction_mu) if req.objects: return sm_mod.safety_report(req.objects, req.ego_speed_mps, params) return sm_mod.divergence_demo(req.ego_speed_mps)
@router.get("/metrics/divergence-demo")def divergence_demo(): return sm_mod.divergence_demo()
# ------------------------------------------------------------ gauntlet
class GauntletRequest(BaseModel): candidate_version: str = "candidate-v4" baseline_version: str = "baseline-v3" effects: Dict[str, float] = Field(default_factory=dict) budget_units: int = Field(80_000, ge=1_000, le=500_000) batch_units: int = Field(2_000, ge=100, le=20_000) seed: int = 11
@router.post("/gauntlet/run")def gauntlet_run(req: GauntletRequest): return sched_mod.run_gauntlet( candidate_version=req.candidate_version, baseline_version=req.baseline_version, effects=req.effects, config={"budget_units": req.budget_units, "batch_units": req.batch_units}, seed=req.seed)
@router.get("/gauntlet/{run_id}/status")def gauntlet_status(run_id: str): g = sched_mod.get_gauntlet(run_id) if g is None: raise HTTPException(404, f"unknown gauntlet {run_id}") return {"run_id": g["run_id"], "status": g["status"], "scale": g["scale"], "timing": g["timing"], "events": g["events"], "halted": g["halted"], "recommendation": g["recommendation"]["recommendation"]}
@router.get("/gauntlet/{run_id}/results")def gauntlet_results(run_id: str): g = sched_mod.get_gauntlet(run_id) if g is None: raise HTTPException(404, f"unknown gauntlet {run_id}") return g
@router.get("/gauntlets")def gauntlets(): return {"gauntlets": sched_mod.list_gauntlets()}
# ------------------------------------------------------------ compute
@router.get("/compute/report")def compute_report(): rep = compute_mod.latest_report() if rep is None: raise HTTPException(404, "no compute benchmark yet; POST " "/api/nextgen/compute/benchmark first") return rep
class BenchmarkRequest(BaseModel): n_scenarios: int = Field(6, ge=2, le=16) frames_per_sequence: int = Field(20, ge=8, le=40) seed: int = 7
@router.post("/compute/benchmark")def compute_benchmark(req: BenchmarkRequest): result = compute_mod.benchmark(n_scenarios=req.n_scenarios, frames_per_sequence=req.frames_per_sequence, seed=req.seed) return result.model_dump(mode="json")
# ------------------------------------------------------------ distribution
class DistributionRequest(BaseModel): megaeval_run_id: Optional[str] = None scenario_id: Optional[str] = None
@router.post("/distribution/analyze")def distribution_analyze(req: DistributionRequest): """Distribution-shift analysis. Preferred path DELEGATES to sensorflow.megaeval.analysis.distribution_shift for a megaeval run; the scenario path compares a counterfactual's feature distributions to the real-scene reference (validity.check_distribution).""" if req.megaeval_run_id: from sensorflow.megaeval.analysis import distribution_shift from sensorflow.megaeval.runs import get_mega_store mstore = get_mega_store() run = mstore.runs.get(req.megaeval_run_id) if run is None: raise HTTPException(404, f"unknown megaeval run {req.megaeval_run_id}") shift = distribution_shift(mstore, run) return DistributionShiftAssessment( run_id=req.megaeval_run_id, method=shift["method"], shifts=shift["shifts"], data_labels=[DataLabel.SIMULATED]).model_dump(mode="json") if req.scenario_id: bundle = cf_mod.load_bundle(req.scenario_id) if bundle is None: raise HTTPException(404, f"unknown scenario {req.scenario_id}") check, _reasons, realism = validity_mod.check_distribution(bundle["sequence"]) # parse psi/js out of the structured check return DistributionShiftAssessment( run_id=req.scenario_id, method=check["detail"], shifts=[check], psi=None, js_divergence=None, magnitude=None, data_labels=[bundle["scenario"].provenance.data_label] ).model_dump(mode="json") raise HTTPException(422, "provide megaeval_run_id or scenario_id")
# ------------------------------------------------------------ architecture
@router.get("/architecture/docs")def architecture_docs(): docs = {} for key, fname in _DOC_FILES.items(): p = _DOCS_DIR / fname docs[key] = {"file": f"docs/architecture/{fname}", "content": p.read_text() if p.exists() else None} missing = [k for k, v in docs.items() if v["content"] is None] if len(missing) == len(docs): raise HTTPException(404, "architecture docs not found") return {"docs": docs, "missing": missing}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196"""Content-addressed intermediate-representation cache.
Keying: sha256 over the canonical JSON of (scenario_id, sensor_version, preprocessing_version, backbone_version, feature_schema_version)plus an artifact kind. ANY version bump changes the key, so a versionmismatch is a MISS by construction — cross-version reuse is impossible, notmerely discouraged (tested in tests/test_nextgen/test_cache.py).
Invalidation strategy (documented, deliberate):* No explicit invalidation exists or is needed: keys are content-addressed over everything the artifact depends on. Producing new sensor data, a new preprocessing pipeline, a new backbone or a new feature schema produces new keys; stale entries simply stop being referenced.* Disk growth is bounded by an LRU-style entry cap (`max_entries`): oldest by mtime are evicted when the cap is exceeded.* A deploy that changes semantics WITHOUT bumping a version is the one hazard; lineage records (lineage.py COMPONENT_VERSIONS) make the versions part of every evaluation run so that mistake is visible in audits.
REUSE NOTE: sensorflow.seqeval.paired.PredictionCache uses the samefingerprint-keyed design for full-population success vectors. It is bound tomegaeval populations and npz success arrays, while this cache storesarbitrary JSON-serializable feature artifacts for the bevfusion pipeline —shared design, different artifact domain (documented reuse decision:pattern reused, code not force-fit)."""
from __future__ import annotations
import hashlibimport jsonimport osimport threadingimport timefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Callable, Dict, Optional
from sensorflow.nextgen import store
@dataclassclass CacheKeyVersions: """Everything a shared intermediate representation depends on."""
sensor_version: str = "bevfusion-sensors-1.0" preprocessing_version: str = "nextgen-preproc-1.0" backbone_version: str = "bevfusion-fusion-1.0" feature_schema_version: str = "nextgen-features-1.0"
def key_for(self, scenario_id: str, kind: str = "features") -> str: blob = json.dumps({ "scenario_id": scenario_id, "kind": kind, "sensor": self.sensor_version, "preprocessing": self.preprocessing_version, "backbone": self.backbone_version, "schema": self.feature_schema_version, }, sort_keys=True) return hashlib.sha256(blob.encode()).hexdigest()[:24]
@dataclassclass CacheStats: hits: int = 0 misses: int = 0 compute_time_s: float = 0.0 # time spent on misses (real compute) lookup_time_s: float = 0.0 # time spent serving hits per_kind: Dict[str, Dict[str, int]] = field(default_factory=dict)
@property def hit_rate(self) -> float: total = self.hits + self.misses return self.hits / total if total else 0.0
def as_dict(self) -> Dict: return {"hits": self.hits, "misses": self.misses, "hit_rate": round(self.hit_rate, 4), "compute_time_s": round(self.compute_time_s, 4), "lookup_time_s": round(self.lookup_time_s, 4), "per_kind": self.per_kind}
class FeatureCache: """Memory + disk cache of shared intermediate representations."""
def __init__(self, subdir: str = "cache", max_entries: int = 4096, max_memory_entries: int = 256): self.subdir = subdir self.max_entries = max_entries self.max_memory_entries = max_memory_entries self._mem: Dict[str, Any] = {} self._lock = threading.Lock() self.stats = CacheStats()
def _dir(self) -> Path: return Path(store.nextgen_root()) / self.subdir
def _path(self, key: str) -> Path: return self._dir() / f"{key}.json"
def get_or_compute(self, key: str, compute: Callable[[], Any], kind: str = "features") -> Any: pk = self.stats.per_kind.setdefault(kind, {"hits": 0, "misses": 0}) with self._lock: if key in self._mem: t0 = time.perf_counter() value = self._mem[key] self.stats.hits += 1 pk["hits"] += 1 self.stats.lookup_time_s += time.perf_counter() - t0 return value path = self._path(key) if path.exists(): t0 = time.perf_counter() with open(path) as f: value = json.load(f) os.utime(path) # LRU recency with self._lock: self.stats.hits += 1 pk["hits"] += 1 self.stats.lookup_time_s += time.perf_counter() - t0 self._remember(key, value) return value
t0 = time.perf_counter() value = compute() elapsed = time.perf_counter() - t0 self._dir().mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(".tmp") with open(tmp, "w") as f: json.dump(value, f) os.replace(tmp, path) with self._lock: self.stats.misses += 1 pk["misses"] += 1 self.stats.compute_time_s += elapsed self._remember(key, value) self._evict_if_needed() return value
def _remember(self, key: str, value: Any) -> None: if len(self._mem) >= self.max_memory_entries: self._mem.clear() self._mem[key] = value
def _evict_if_needed(self) -> None: d = self._dir() if not d.exists(): return entries = sorted(d.glob("*.json"), key=lambda p: p.stat().st_mtime) for p in entries[:max(0, len(entries) - self.max_entries)]: try: p.unlink() except OSError: pass
def contains(self, key: str) -> bool: with self._lock: if key in self._mem: return True return self._path(key).exists()
def clear(self) -> None: with self._lock: self._mem.clear() self.stats = CacheStats() d = self._dir() if d.exists(): for p in d.glob("*.json"): try: p.unlink() except OSError: pass
def reset_stats(self) -> None: with self._lock: self.stats = CacheStats()
_CACHE: Optional[FeatureCache] = None_CACHE_LOCK = threading.Lock()
def get_feature_cache() -> FeatureCache: global _CACHE with _CACHE_LOCK: if _CACHE is None: _CACHE = FeatureCache() return _CACHE
def reset_feature_cache() -> None: global _CACHE with _CACHE_LOCK: _CACHE = None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""Causal counterfactual replay: does a perception error actually MATTER?
The SAME scenario is run twice through the closed loop (closedloop.py):
actual perception as-is (engine failure model + any injected faults) corrected ground-truth-injected perception (perfect detection)
The two runs are diffed on planner output, trajectory, velocity, braking,minimum separation and collision probability, and the causal chain isanswered stepwise:
Q1 Would correct perception change the planner output? Q2 Would that change the vehicle's behavior (trajectory/velocity)? Q3 Would that change the safety outcome (separation / collision)?
Verdict (deterministic policy): BEHAVIORALLY_CONSEQUENTIAL iff Q3 is yes (the perception difference propagates all the way to a safety outcome) METRIC_ONLY otherwise — the error shows up in open-loop metrics but does not change what the vehicle does in any safety-relevant way (e.g. a cosmetic class flip: the planner reacts to geometry, not class).
Both assessments carry the scenario's data label; nothing here upgradessimulation to reality."""
from __future__ import annotations
from typing import Dict, List, Optional
import numpy as np
from sensorflow.nextgen.closedloop import DEFAULT_ENGINE, run_closed_loopfrom sensorflow.nextgen.models import ( CAUSAL_BEHAVIORAL, CAUSAL_METRIC_ONLY, BehavioralAssessment, CausalReplayResult, DataLabel,)from sensorflow.nextgen.worldmodel import ActorTrack
# Deterministic thresholds of the causal policy (versioned via lineage).PLANNER_DIFF_MPS2 = 0.5 # commanded-accel divergence that counts as "changed plan"TRAJECTORY_DIFF_M = 0.5 # positional divergence that counts as "changed behavior"VELOCITY_DIFF_MPS = 1.0SEPARATION_DIFF_M = 0.5 # safety-outcome deltasCOLLISION_PROB_DIFF = 0.15TTC_DIFF_S = 0.5
def _aligned(actual: List[Dict], corrected: List[Dict]): n = min(len(actual), len(corrected)) return actual[:n], corrected[:n]
def causal_replay(actors: List[ActorTrack], environment: Dict[str, str], scenario_id: str, data_label: DataLabel, engine: str = DEFAULT_ENGINE, seed: int = 0, faults: Optional[List[Dict]] = None) -> CausalReplayResult: actual = run_closed_loop(actors, environment, scenario_id, data_label, engine=engine, seed=seed, corrected=False, faults=faults) corrected = run_closed_loop(actors, environment, scenario_id, data_label, engine=engine, seed=seed, corrected=True)
ta, tc = _aligned(actual.trajectory, corrected.trajectory) if ta: pos_div = float(max(abs(a["x"] - c["x"]) + abs(a["y"] - c["y"]) for a, c in zip(ta, tc))) vel_div = float(max(abs(a["v"] - c["v"]) for a, c in zip(ta, tc))) acc_div = float(max(abs(a["a"] - c["a"]) for a, c in zip(ta, tc))) else: pos_div = vel_div = acc_div = 0.0 # A truncated run means one branch collided and stopped early — that is # itself maximal behavioral divergence. if len(actual.trajectory) != len(corrected.trajectory): pos_div = max(pos_div, TRAJECTORY_DIFF_M * 2)
ma, mc = actual.metrics, corrected.metrics sep_diff = _diff(ma.min_separation_m, mc.min_separation_m) col_prob_diff = ma.collision_probability - mc.collision_probability ttc_diff = _diff(ma.min_ttc_s, mc.min_ttc_s) brake_diff = ma.max_deceleration_mps2 - mc.max_deceleration_mps2
q1 = acc_div > PLANNER_DIFF_MPS2 q2 = q1 and (pos_div > TRAJECTORY_DIFF_M or vel_div > VELOCITY_DIFF_MPS) q3 = q2 and (ma.collision != mc.collision or (sep_diff is not None and abs(sep_diff) > SEPARATION_DIFF_M) or abs(col_prob_diff) > COLLISION_PROB_DIFF or (ttc_diff is not None and abs(ttc_diff) > TTC_DIFF_S))
chain = [ {"question": "Would correct perception change the planner output?", "answer": q1, "evidence": f"max commanded-accel divergence {acc_div:.2f} m/s^2 " f"(threshold {PLANNER_DIFF_MPS2})"}, {"question": "Would that change the vehicle's behavior?", "answer": q2, "evidence": f"max trajectory divergence {pos_div:.2f} m, " f"max velocity divergence {vel_div:.2f} m/s " f"(thresholds {TRAJECTORY_DIFF_M} m / {VELOCITY_DIFF_MPS} m/s)"}, {"question": "Would that change the safety outcome?", "answer": q3, "evidence": f"collision {ma.collision} vs {mc.collision}; " f"min-separation diff " f"{'n/a' if sep_diff is None else f'{sep_diff:+.2f} m'}; " f"collision-probability diff {col_prob_diff:+.2f}; " f"min-TTC diff " f"{'n/a' if ttc_diff is None else f'{ttc_diff:+.2f} s'}"}, ]
return CausalReplayResult( scenario_id=scenario_id, data_label=data_label, actual=actual, corrected=corrected, diffs={ "max_trajectory_divergence_m": round(pos_div, 3), "max_velocity_divergence_mps": round(vel_div, 3), "max_planner_divergence_mps2": round(acc_div, 3), "min_separation_diff_m": _round(sep_diff), "collision_probability_diff": round(col_prob_diff, 4), "min_ttc_diff_s": _round(ttc_diff), "max_braking_diff_mps2": round(brake_diff, 3), "collision_actual": ma.collision, "collision_corrected": mc.collision, }, causal_chain=chain, verdict=CAUSAL_BEHAVIORAL if q3 else CAUSAL_METRIC_ONLY)
def _diff(a: Optional[float], b: Optional[float]) -> Optional[float]: if a is None or b is None: return None return a - b
def _round(v: Optional[float], nd: int = 3) -> Optional[float]: return None if v is None else round(float(v), nd)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466"""Closed-loop behavioral evaluation.
Extends the platform's open-loop chain (scenario -> perception -> metrics)into scenario -> perception -> prediction -> planner -> controller ->vehicle-response, and measures BEHAVIOR, not just detection quality.
Honest scope: the planner/controller here is a deterministic simplifiedstack — IDM-style longitudinal control + PD lane-keep lateral + constant-velocity prediction — sufficient to measure how perception quality changesbehavior. It is NOT a production planner; docs/architecture/nextgen-adr.mddiscusses what a real planner would change.
REUSE: all safety-region math comes from sensorflow.safety.ssam_ext —projected_ttc (rectangle conflict-point projection), rect_gap (rotated-rectangle separation), rects_overlap (collision detection),collision_probability (TTC-threshold proxy). Open-loop metrics (per-framerecall etc.) are computed alongside and attached to every assessment:closed-loop NEVER replaces open-loop.
Perception model: detection sampling with modality-informed failure ratesmirroring sensorflow.bevfusion.sensors (occlusion/night/rain/distance), withtwo engine profiles (camera-primary baseline vs BEV-fused candidate) plusparameterized extended-condition effects (fog/glare/wet — conditions thebevfusion simulators don't model; documented inPERCEPTION_CONDITION_EFFECTS). A "corrected" mode injects ground truth(perfect perception) — that is what causal.py diffs against. All randomnessis seeded: same scenario + engine + seed -> identical behavior."""
from __future__ import annotations
import mathfrom typing import Dict, List, Optional
import numpy as np
from sensorflow.bevfusion.scenes import DT, EGO_SPEED# REUSE: SSAM safety-region math from the safety package.from sensorflow.safety.ssam_ext import ( collision_probability, projected_ttc, rect_gap, rects_overlap,)from sensorflow.nextgen.models import ( BehavioralAssessment, BehavioralMetrics, DataLabel,)from sensorflow.nextgen.worldmodel import ActorTrack
EGO_DIMS = (4.5, 1.9) # l, w (matches ssam_ext synthetic ego)CORRIDOR_HALF_WIDTH_M = 1.6 # lateral extent of the ego pathTTC_BRAKE_S = 4.0 # begin comfort braking below this projected TTCTTC_EMERGENCY_S = 1.5 # FHWA SSAM conflict threshold (ssam_ext default)A_MAX_ACCEL = 2.5 # m/s^2A_COMFORT_BRAKE = 3.5A_MAX_BRAKE = 8.0IDM_T_HEADWAY = 1.5 # sIDM_S0 = 2.0 # m minimum gapACTUATION_TAU_S = 0.25 # first-order lag of the vehicle responseDETECT_RANGE_M = 75.0
ENGINE_PROFILES: Dict[str, Dict[str, float]] = { # Camera-primary baseline: heavy occlusion/night misses (cf. # bevfusion.sensors.simulate_camera failure model). "perception-v1-camera": {"base_miss": 0.06, "occlusion_miss": 0.80, "night_miss": 0.40, "rain_miss": 0.06, "range_miss_per_m": 0.0015, "pos_sigma": 0.55}, # BEV-fused candidate: LiDAR recovers occlusion/night (cf. # bevfusion.engines.run_fused complementarity). "perception-v3-bevfusion": {"base_miss": 0.02, "occlusion_miss": 0.25, "night_miss": 0.04, "rain_miss": 0.04, "range_miss_per_m": 0.0008, "pos_sigma": 0.18},}DEFAULT_ENGINE = "perception-v3-bevfusion"
# Extended environment conditions produced by counterfactual transforms.# These are OUR parameterization (the bevfusion sensor sims don't model them);# additive miss probability, scaled by distance/DETECT_RANGE_M where noted.PERCEPTION_CONDITION_EFFECTS: Dict[str, Dict[str, float]] = { "fog": {"add_miss_scaled_by_range": 0.45, "pos_sigma_mult": 1.6}, "sunset_glare": {"add_miss": 0.12, "pos_sigma_mult": 1.2}, "wet": {"add_miss": 0.03, "pos_sigma_mult": 1.1},}
# ------------------------------------------------------------ perception
class PerceptionModel: """Deterministic seeded detection sampler over world-frame actors."""
def __init__(self, engine: str, environment: Dict[str, str], seed: int, corrected: bool = False, faults: Optional[List[Dict]] = None): if engine not in ENGINE_PROFILES: raise ValueError(f"unknown engine {engine!r}; known: " f"{sorted(ENGINE_PROFILES)}") self.engine = engine self.profile = ENGINE_PROFILES[engine] self.environment = environment self.corrected = corrected self.faults = faults or [] self.rng = np.random.default_rng( [seed, sum(map(ord, engine)) % 100003, int(corrected)]) self.tracked: Dict[str, int] = {} # iid -> consecutive hits self.first_detection_s: Dict[str, float] = {} # open-loop accounting (complementary metrics) self.n_gt_visible = 0 self.n_detected = 0 self.n_misclassified = 0
def _miss_probability(self, dist: float, occluded: bool) -> float: p = self.profile["base_miss"] + self.profile["range_miss_per_m"] * dist if occluded: p += self.profile["occlusion_miss"] if self.environment.get("time_of_day") == "night": p += self.profile["night_miss"] if self.environment.get("weather") == "rain": p += self.profile["rain_miss"] for tag in ("weather_extended", "glare", "road_surface"): eff = PERCEPTION_CONDITION_EFFECTS.get(self.environment.get(tag, "")) if eff: p += eff.get("add_miss", 0.0) p += eff.get("add_miss_scaled_by_range", 0.0) * min(1.0, dist / DETECT_RANGE_M) return min(p, 0.97)
def _pos_sigma(self) -> float: s = self.profile["pos_sigma"] for tag in ("weather_extended", "glare", "road_surface"): eff = PERCEPTION_CONDITION_EFFECTS.get(self.environment.get(tag, "")) if eff: s *= eff.get("pos_sigma_mult", 1.0) return s
def perceive(self, t: float, ego: Dict, actors: List[ActorTrack], fi: int) -> List[Dict]: """Detections in world frame for the current step.""" out: List[Dict] = [] for a in actors: st = a.states[min(fi, len(a.states) - 1)] if st.get("absent"): continue rel_x, rel_y = st["x"] - ego["x"], st["y"] - ego["y"] dist = math.hypot(rel_x, rel_y) if rel_x < -5.0 or dist > DETECT_RANGE_M: continue self.n_gt_visible += 1
fault = self._active_fault(a.instance_id, t) if self.corrected: detected = True elif fault and fault["type"] == "miss": detected = False else: p_miss = self._miss_probability(dist, bool(st.get("occluded"))) if self.tracked.get(a.instance_id, 0) >= 2: p_miss *= 0.15 # track continuity (masklet-style latching) detected = self.rng.random() >= p_miss
if not detected: self.tracked[a.instance_id] = 0 continue self.tracked[a.instance_id] = self.tracked.get(a.instance_id, 0) + 1 self.first_detection_s.setdefault(a.instance_id, t) self.n_detected += 1
sigma = 0.0 if self.corrected else self._pos_sigma() cls = a.class_name if fault and fault["type"] == "misclassify" and not self.corrected: cls = fault.get("as_class", cls) self.n_misclassified += 1 dx_bias = fault.get("dx_m", 0.0) if fault and fault["type"] == "position_bias" \ and not self.corrected else 0.0 out.append({ "instance_id": a.instance_id, "class_name": cls, "x": st["x"] + float(self.rng.normal(0, sigma)) + dx_bias, "y": st["y"] + float(self.rng.normal(0, sigma * 0.6)), "vx": st["vx"], "vy": st["vy"], # tracker velocity estimate "dims": a.dims, "yaw": st["yaw"], }) return out
def _active_fault(self, iid: str, t: float) -> Optional[Dict]: for f in self.faults: if f.get("instance_id") != iid: continue if f["type"] == "miss": if float(f.get("from_s", 0.0)) <= t < float(f.get("until_s", 1e9)): return f else: return f return None
def open_loop_metrics(self) -> Dict: recall = self.n_detected / self.n_gt_visible if self.n_gt_visible else None return { "engine": self.engine, "frame_recall": None if recall is None else round(recall, 4), "n_gt_visible": self.n_gt_visible, "n_detected": self.n_detected, "n_misclassified": self.n_misclassified, "note": "open-loop metrics are complementary to the behavioral " "metrics and are always reported alongside them", }
# ------------------------------------------------------------ planner
def plan_acceleration(ego: Dict, detections: List[Dict]) -> Dict: """IDM-style longitudinal command with TTC-based emergency reaction.
The planner reacts to perceived GEOMETRY (position/velocity), not class: a cosmetic misclassification does not change the plan — which is exactly what causal replay demonstrates as METRIC_ONLY. """ v = ego["v"] a_cmd = A_MAX_ACCEL * (1.0 - (v / max(EGO_SPEED, 0.1)) ** 4) reason = "free_road" intervention = False
ego_state = {"x": ego["x"], "y": ego["y"], "speed": v, "heading": ego["heading"]} min_ttc: Optional[float] = None for det in detections: rel_x = det["x"] - ego["x"] obj_state = {"x": det["x"], "y": det["y"], "speed": math.hypot(det["vx"], det["vy"]), "heading": math.atan2(det["vy"], det["vx"]) if (det["vx"], det["vy"]) != (0.0, 0.0) else 0.0} # In-corridor lead vehicle: IDM following. if abs(det["y"] - ego["y"]) <= CORRIDOR_HALF_WIDTH_M and rel_x > 0: gap = rect_gap((ego["x"], ego["y"]), ego["heading"], *EGO_DIMS, (det["x"], det["y"]), obj_state["heading"], det["dims"][0], det["dims"][1]) dv = v - det["vx"] # closing speed along the lane s_star = IDM_S0 + max(0.0, v * IDM_T_HEADWAY + v * dv / (2 * math.sqrt(A_MAX_ACCEL * A_COMFORT_BRAKE))) a_idm = A_MAX_ACCEL * (1.0 - (v / max(EGO_SPEED, 0.1)) ** 4 - (s_star / max(gap, 0.5)) ** 2) if a_idm < a_cmd: a_cmd, reason = a_idm, f"idm_follow:{det['instance_id']}"
# Projected-TTC reaction (REUSED ssam_ext conflict-point projection): # covers crossing/merging actors that are not yet in the corridor. ttc = projected_ttc(ego_state, EGO_DIMS, obj_state, (det["dims"][0], det["dims"][1]), look_ahead=TTC_BRAKE_S, dt=0.1) if ttc is not None: min_ttc = ttc if min_ttc is None else min(min_ttc, ttc) if ttc <= TTC_EMERGENCY_S: a_cmd = -A_MAX_BRAKE reason = f"emergency_brake:{det['instance_id']}" intervention = True elif ttc <= TTC_BRAKE_S: a_brake = -A_COMFORT_BRAKE * (TTC_BRAKE_S - ttc) / (TTC_BRAKE_S - TTC_EMERGENCY_S) if a_brake < a_cmd: a_cmd = a_brake reason = f"ttc_brake:{det['instance_id']}" intervention = True
return {"a_cmd": float(np.clip(a_cmd, -A_MAX_BRAKE, A_MAX_ACCEL)), "reason": reason, "intervention": intervention, "perceived_min_ttc": min_ttc}
# ------------------------------------------------------------ simulation
def run_closed_loop(actors: List[ActorTrack], environment: Dict[str, str], scenario_id: str, data_label: DataLabel, engine: str = DEFAULT_ENGINE, seed: int = 0, corrected: bool = False, faults: Optional[List[Dict]] = None, horizon_s: Optional[float] = None) -> BehavioralAssessment: """Simulate the full loop and measure behavioral metrics.""" n_frames = max(len(a.states) for a in actors) if actors else 0 n_steps = int(round((horizon_s or n_frames * DT) / DT)) perception = PerceptionModel(engine, environment, seed, corrected=corrected, faults=faults)
target_y = -1.6 if "construction_zone" in environment else 0.0 ego = {"x": 0.0, "y": 0.0, "v": EGO_SPEED, "a": 0.0, "heading": 0.0}
trajectory: List[Dict[str, float]] = [] min_ttc: Optional[float] = None min_sep: Optional[float] = None min_sep_speed = 0.0 max_decel = 0.0 max_steer_rate = 0.0 interventions = 0 intervening = False collision = False max_col_prob = 0.0 brake_start_x: Optional[float] = None stopping_distance: Optional[float] = None critical_iid: Optional[str] = None
for step in range(n_steps): t = step * DT fi = min(step, n_frames - 1) if n_frames else 0 detections = perception.perceive(t, ego, actors, fi) plan = plan_acceleration(ego, detections)
if plan["intervention"] and not intervening: interventions += 1 critical_iid = critical_iid or plan["reason"].split(":")[-1] intervening = plan["intervention"]
# Vehicle response: first-order actuation lag + kinematic update. alpha = DT / (DT + ACTUATION_TAU_S) ego["a"] += alpha * (plan["a_cmd"] - ego["a"]) prev_heading = ego["heading"] ego["v"] = max(0.0, ego["v"] + ego["a"] * DT) ego["x"] += ego["v"] * DT vy_cmd = float(np.clip(0.8 * (target_y - ego["y"]), -1.5, 1.5)) ego["y"] += vy_cmd * DT ego["heading"] = math.atan2(vy_cmd, max(ego["v"], 0.5)) max_steer_rate = max(max_steer_rate, abs(ego["heading"] - prev_heading) / DT) max_decel = max(max_decel, -ego["a"])
if ego["a"] < -2.0 and brake_start_x is None: brake_start_x = ego["x"] if brake_start_x is not None and stopping_distance is None and ego["v"] < 0.1: stopping_distance = ego["x"] - brake_start_x
# Ground-truth safety measures vs every actor (REUSED ssam_ext math). ego_state = {"x": ego["x"], "y": ego["y"], "speed": ego["v"], "heading": ego["heading"]} for a in actors: st = a.states[fi] if st.get("absent"): continue if abs(st["x"] - ego["x"]) > 60 or abs(st["y"] - ego["y"]) > 25: continue obj_state = {"x": st["x"], "y": st["y"], "speed": math.hypot(st["vx"], st["vy"]), "heading": st["yaw"]} gap = rect_gap((ego["x"], ego["y"]), ego["heading"], *EGO_DIMS, (st["x"], st["y"]), st["yaw"], a.dims[0], a.dims[1]) if min_sep is None or gap < min_sep: min_sep, min_sep_speed = gap, ego["v"] ttc = projected_ttc(ego_state, EGO_DIMS, obj_state, (a.dims[0], a.dims[1]), look_ahead=3.0, dt=0.1) if ttc is not None: min_ttc = ttc if min_ttc is None else min(min_ttc, ttc) max_col_prob = max(max_col_prob, collision_probability(ttc, TTC_EMERGENCY_S)) if rects_overlap((ego["x"], ego["y"]), ego["heading"], *EGO_DIMS, (st["x"], st["y"]), st["yaw"], a.dims[0], a.dims[1]): collision = True max_col_prob = 1.0
trajectory.append({"t": round(t, 2), "x": round(ego["x"], 3), "y": round(ego["y"], 3), "v": round(ego["v"], 3), "a": round(ego["a"], 3), "n_detections": len(detections)}) if collision: break
# Detection latency of the intervention-critical actor: delay between it # becoming detectable (in range/FOV) and its first detection. detection_latency = time_to_detection = None if critical_iid: first_det = perception.first_detection_s.get(critical_iid) if first_det is not None: time_to_detection = first_det appear_t = _first_detectable_time(actors, critical_iid, n_steps) if appear_t is not None: detection_latency = max(0.0, first_det - appear_t)
# Safety margin at closest approach: gap minus the reaction-time headway # distance at the speed the ego carried at that moment. safety_margin = None if min_sep is not None: safety_margin = min_sep - min_sep_speed * 0.6 # 0.6 s reaction headway
metrics = BehavioralMetrics( detection_latency_s=_round(detection_latency), time_to_detection_s=_round(time_to_detection), min_ttc_s=_round(min_ttc), stopping_distance_m=_round(stopping_distance), max_deceleration_mps2=round(max_decel, 3), max_steering_rate_radps=round(max_steer_rate, 4), planner_interventions=interventions, collision=collision, collision_probability=round(max_col_prob, 4), min_separation_m=_round(min_sep), safety_margin_m=_round(safety_margin), final_speed_mps=round(ego["v"], 3))
return BehavioralAssessment( scenario_id=scenario_id, data_label=data_label, perception_mode="corrected" if corrected else "actual", metrics=metrics, open_loop=perception.open_loop_metrics(), trajectory=trajectory)
def demo_emergence_scenario(conflict_t_s: float = 3.0, t_emerge_s: float = 1.6) -> Dict: """Controlled occluded-emergence scenario for causal-replay demos/tests.
Minimal actor set (occluder truck + emergent crossing pedestrian + one benign lead vehicle) so the causal experiment is not polluted by unrelated actors triggering the planner in both branches. The pedestrian is timed to enter the ego corridor when a non-reacting ego would reach its position at conflict_t_s. Data label COUNTERFACTUAL (constructed). """ n_frames = 60 x_conflict = EGO_SPEED * conflict_t_s y0 = 4.0 vy = -1.9 ramp_a = 6.0 truck = ActorTrack( instance_id="demo-occluder-truck", class_name="truck", dims=[8.5, 2.5, 3.2], states=[{"x": x_conflict - 2.0, "y": y0 + 2.0, "vx": 0.0, "vy": 0.0, "yaw": 0.0, "occluded": False} for _ in range(n_frames)]) ped_states = [] for fi in range(n_frames): t = fi * DT if t <= t_emerge_s: y, vy_i = y0, 0.0 else: dt_m = t - t_emerge_s t_ramp = abs(vy) / ramp_a if dt_m <= t_ramp: vy_i = -ramp_a * dt_m y = y0 - 0.5 * ramp_a * dt_m * dt_m else: vy_i = vy y = y0 - 0.5 * ramp_a * t_ramp * t_ramp + vy * (dt_m - t_ramp) ped_states.append({"x": x_conflict + 3.5, "y": y, "vx": 0.0, "vy": vy_i, "yaw": -math.pi / 2, "occluded": t <= t_emerge_s}) ped = ActorTrack(instance_id="demo-crossing-ped", class_name="pedestrian", dims=[0.6, 0.6, 1.75], states=ped_states) lead = ActorTrack( instance_id="demo-lead-vehicle", class_name="vehicle", dims=[4.5, 1.9, 1.6], states=[{"x": 55.0 + 9.5 * fi * DT, "y": 0.0, "vx": 9.5, "vy": 0.0, "yaw": 0.0, "occluded": False} for fi in range(n_frames)]) return {"actors": [truck, ped, lead], "environment": {"time_of_day": "day", "weather": "clear"}, "scenario_id": "demo-occluded-emergence", "critical_instance_id": ped.instance_id, "horizon_s": n_frames * DT}
def _first_detectable_time(actors: List[ActorTrack], iid: str, n_steps: int) -> Optional[float]: actor = next((a for a in actors if a.instance_id == iid), None) if actor is None: return None # Approximate the moving ego with the nominal profile for detectability # onset (detectability begins before behavior diverges materially). for step in range(n_steps): fi = min(step, len(actor.states) - 1) st = actor.states[fi] ego_x = EGO_SPEED * DT * step rel_x = st["x"] - ego_x if -5.0 <= rel_x and math.hypot(rel_x, st["y"]) <= DETECT_RANGE_M: return step * DT return None
def _round(v: Optional[float], nd: int = 3) -> Optional[float]: return None if v is None else round(float(v), nd)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""Compute deduplication over the bevfusion pipeline + quantified savings.
The insight: when N models are evaluated on the same scenario, the sensorsimulation, BEV rasterization and fusion decode (the "backbone-equivalent"stages of sensorflow.bevfusion — build_modality_map / fuse_maps / decode_bev)are IDENTICAL across models. Only the model-specific head (confidencerecalibration + class thresholds here) differs. So:
naive cost = scenarios x models x (backbone + head) optimized cost = scenarios x backbone + scenarios x models x head
The shared stage is cached content-addressed (cache.py) under(scenario_id, sensor_version, preprocessing_version, backbone_version,feature_schema_version); a version bump on any component is a miss byconstruction. `benchmark` runs the real pipeline twice and reports MEASUREDtimings and hit rates — no estimated numbers.
Honest scope: the "backbone" is the numpy bevfusion pipeline, not a neuralnetwork, and the "heads" are deterministic calibration/threshold profiles.The cost STRUCTURE (shared expensive stage, cheap per-model stage) is thereal thing being demonstrated; absolute times would scale with a real stack."""
from __future__ import annotations
import timefrom typing import Dict, List, Optionalfrom uuid import uuid4
from sensorflow.bevfusion.fusion import build_modality_map, decode_bev, fuse_mapsfrom sensorflow.bevfusion.geometry import BEVGridfrom sensorflow.bevfusion.scenes import SceneSequence, generate_sequencesfrom sensorflow.bevfusion.sensors import ( camera_rng, lidar_rng, simulate_camera, simulate_lidar,)from sensorflow.nextgen import storefrom sensorflow.nextgen.cache import CacheKeyVersions, get_feature_cachefrom sensorflow.nextgen.models import ComputeOptimizationResult
# Model-specific head profiles: deterministic post-processing over the shared# fused features. Cheap by design — that is the point of the split.HEAD_PROFILES: Dict[str, Dict[str, float]] = { "candidate-v4": {"confidence_gain": 1.05, "min_confidence": 0.30, "vru_boost": 1.10}, "candidate-v4.1": {"confidence_gain": 1.02, "min_confidence": 0.35, "vru_boost": 1.15}, "baseline-v3": {"confidence_gain": 1.00, "min_confidence": 0.40, "vru_boost": 1.00},}VRU = {"pedestrian", "cyclist", "motorcycle"}
def compute_backbone_features(seq: SceneSequence, seed: int = 7, seq_index: int = 0) -> List[Dict]: """Shared stage: sensor sim -> BEV rasterization -> fusion -> decode. REUSES the bevfusion pipeline verbatim; returns JSON-serializable per-frame decoded fused boxes (the cacheable IR).""" grid = BEVGrid() cam_gen = camera_rng(seed, seq_index) lid_gen = lidar_rng(seed, seq_index) frames: List[Dict] = [] for frame in seq.frames: cam = simulate_camera(frame, seq, cam_gen) lid = simulate_lidar(frame, seq, lid_gen) fused = fuse_maps(build_modality_map(cam, grid, "camera"), build_modality_map(lid, grid, "lidar")) decoded = decode_bev(fused) frames.append({"frame_id": frame.frame_id, "boxes": [{"bbox_3d": b["bbox_3d"], "class_name": b["class_name"], "confidence": round(float(b["confidence"]), 4)} for b in decoded]}) return frames
def run_model_head(features: List[Dict], model_version: str) -> Dict: """Model-specific stage: recalibrate + threshold the shared features.""" prof = HEAD_PROFILES.get(model_version, HEAD_PROFILES["baseline-v3"]) n_out = 0 n_vru = 0 conf_sum = 0.0 for frame in features: for b in frame["boxes"]: c = b["confidence"] * prof["confidence_gain"] if b["class_name"] in VRU: c *= prof["vru_boost"] if c >= prof["min_confidence"]: n_out += 1 conf_sum += min(c, 1.0) if b["class_name"] in VRU: n_vru += 1 return {"model_version": model_version, "n_detections": n_out, "n_vru": n_vru, "mean_confidence": round(conf_sum / n_out, 4) if n_out else None}
def evaluate_scenarios(sequences: List[SceneSequence], models: List[str], versions: Optional[CacheKeyVersions] = None, seed: int = 7) -> Dict: """Evaluate models x scenarios with backbone dedup. Returns measured per-stage timings + head outputs.""" versions = versions or CacheKeyVersions() cache = get_feature_cache() backbone_times: List[float] = [] head_times: List[float] = [] outputs = [] t_start = time.perf_counter() for si, seq in enumerate(sequences): key = versions.key_for(seq.sequence_id, kind="bev-features")
def _compute(seq=seq, si=si): t0 = time.perf_counter() feats = compute_backbone_features(seq, seed=seed, seq_index=si) backbone_times.append(time.perf_counter() - t0) return feats
features = cache.get_or_compute(key, _compute, kind="bev-features") for model in models: t0 = time.perf_counter() head = run_model_head(features, model) head_times.append(time.perf_counter() - t0) outputs.append({"scenario_id": seq.sequence_id, **head}) wall = time.perf_counter() - t_start return {"outputs": outputs, "wall_s": wall, "backbone_times": backbone_times, "head_times": head_times}
def benchmark(n_scenarios: int = 6, frames_per_sequence: int = 20, models: Optional[List[str]] = None, seed: int = 7, versions: Optional[CacheKeyVersions] = None, persist: bool = True) -> ComputeOptimizationResult: """Real benchmark: cold pass (misses) + warm pass (hits) over the same suite; every timing measured, nothing estimated except the naive extrapolation which uses the MEASURED mean backbone/head times.""" models = models or list(HEAD_PROFILES) versions = versions or CacheKeyVersions() cache = get_feature_cache() cache.reset_stats()
sequences = generate_sequences(n_sequences=n_scenarios, frames_per_sequence=frames_per_sequence, seed=seed) cold = evaluate_scenarios(sequences, models, versions, seed) warm = evaluate_scenarios(sequences, models, versions, seed)
stats = cache.stats all_backbone = cold["backbone_times"] + warm["backbone_times"] all_heads = cold["head_times"] + warm["head_times"] mean_backbone = sum(all_backbone) / len(all_backbone) if all_backbone else 0.0 mean_head = sum(all_heads) / len(all_heads) if all_heads else 0.0
n_units = 2 * len(sequences) * len(models) # two passes naive_cost = n_units * (mean_backbone + mean_head) optimized_cost = cold["wall_s"] + warm["wall_s"]
result = ComputeOptimizationResult( report_id=f"compute-{uuid4().hex[:8]}", n_scenarios=len(sequences), n_models=len(models), naive_full_inferences=n_units, optimized_backbone_computes=stats.misses, optimized_head_computes=len(all_heads), cache_hits=stats.hits, cache_misses=stats.misses, hit_rate=round(stats.hit_rate, 4), naive_cost_s=round(naive_cost, 4), optimized_cost_s=round(optimized_cost, 4), savings_ratio=round(1.0 - optimized_cost / naive_cost, 4) if naive_cost else 0.0, measured_backbone_s=round(mean_backbone, 4), measured_head_s=round(mean_head, 6), invalidation="content-addressed keys over (scenario_id, sensor, " "preprocessing, backbone, feature-schema versions); any " "version bump is a new key (cross-version reuse " "impossible); LRU eviction bounds disk growth") if persist: store.write_json(result.model_dump(mode="json"), "compute", f"{result.report_id}.json") store.write_json(result.model_dump(mode="json"), "compute", "latest.json") return result
def latest_report() -> Optional[Dict]: return store.read_json("compute", "latest.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631"""Counterfactual scenario engine: deterministic transformations overbevfusion scenes.
REUSE DECISION: scenarios are NOT a new format. A counterfactual is atransformation of a :class:`sensorflow.bevfusion.scenes.SceneSequence` — theplatform's existing scenario substrate — so everything that already consumesthose sequences (sensor simulators, both perception engines, the evaluatemodule) runs on counterfactuals unchanged. We reconstruct world-frame actorkinematics from the source frames, transform them, and re-render frames withthe same conventions (ego +x at 10 m/s, culling bounds, occlusion flags) asscenes.generate_sequences.
Transformation catalogue------------------------environment.* clear->fog / clear->rain / day->night / glare / wet_roadactors.* sudden_brake, swerve, stationary_to_crossing, occluded_emergence, teleport (stress transform: physically implausible BY DESIGN, used to prove the validity gate rejects)scene.* add_construction_zone, pedestrian_density, add_occlusion, distance_shift, lane_shift
Every generated scenario carries provenance (source scene id, recipe, seed,generator + version) and the data label COUNTERFACTUAL. Provenance ispersisted with the scenario and carried into every downstream report.
Extended environment conditions (fog / glare / wet_road) are not modeled bythe bevfusion sensor simulators (which know day/night, clear/rain). They arerecorded as environment tags here and applied as documented, parameterizeddetection-degradation factors by the closed-loop perception model(closedloop.PERCEPTION_CONDITION_EFFECTS) and by the validity gate's sensorconsistency expectations."""
from __future__ import annotations
import mathfrom typing import Callable, Dict, List, Optionalfrom uuid import uuid4
import numpy as np
from sensorflow.bevfusion.scenes import ( CLASS_DIMS, DT, EGO_SPEED, GTBox, SceneFrame, SceneSequence, generate_sequences,)from sensorflow.nextgen import storefrom sensorflow.nextgen.models import ( CounterfactualScenario, DataLabel, Provenance, TransformationStep,)from sensorflow.nextgen.worldmodel import ( ActorTrack, SceneTransformer, TransformedScene,)
# Culling bounds identical to scenes.generate_sequences._X_MIN, _X_MAX, _Y_MAX = 3.0, 78.0, 22.0
# ------------------------------------------------------- reconstruction
def reconstruct_actors(seq: SceneSequence) -> List[ActorTrack]: """Recover world-frame constant-velocity kinematics from a sequence.
Source scenes are constant-velocity by construction (scenes.py), so a least-squares linear fit over the observed frames recovers the exact generating kinematics; frames where the actor was culled are filled by extrapolation. """ n_frames = len(seq.frames) obs: Dict[str, Dict] = {} for frame in seq.frames: ego_x = EGO_SPEED * DT * frame.index for gt in frame.gt: rec = obs.setdefault(gt.instance_id, { "cls": gt.class_name, "dims": gt.bbox_3d[3:6], "yaw": gt.bbox_3d[6], "t": [], "x": [], "y": [], "occ": {}, }) rec["t"].append(frame.index * DT) rec["x"].append(gt.bbox_3d[0] + ego_x) # world x rec["y"].append(gt.bbox_3d[1]) # world y (ego drives +x) rec["occ"][frame.index] = gt.occluded
actors: List[ActorTrack] = [] for iid, rec in obs.items(): t = np.asarray(rec["t"]) if t.size >= 2: vx, x0 = np.polyfit(t, np.asarray(rec["x"]), 1) vy, y0 = np.polyfit(t, np.asarray(rec["y"]), 1) else: x0, y0, vx, vy = rec["x"][0], rec["y"][0], 0.0, 0.0 states = [] for fi in range(n_frames): ti = fi * DT states.append({ "x": float(x0 + vx * ti), "y": float(y0 + vy * ti), "vx": float(vx), "vy": float(vy), "yaw": float(rec["yaw"]), "occluded": bool(rec["occ"].get(fi, False)), }) actors.append(ActorTrack(instance_id=iid, class_name=rec["cls"], dims=[float(d) for d in rec["dims"]], states=states)) return actors
def render_sequence(actors: List[ActorTrack], environment: Dict[str, str], n_frames: int, sequence_id: str) -> SceneSequence: """Re-render frames from world tracks with the scenes.py conventions.""" seq = SceneSequence( sequence_id=sequence_id, time_of_day=environment.get("time_of_day", "day"), weather=environment.get("weather", "clear")) for fi in range(n_frames): ego_x = EGO_SPEED * DT * fi frame = SceneFrame(frame_id=f"{sequence_id}-f{fi:04d}", index=fi) for actor in actors: st = actor.states[fi] if st.get("absent"): continue rel_x, rel_y = st["x"] - ego_x, st["y"] if rel_x < _X_MIN or rel_x > _X_MAX or abs(rel_y) > _Y_MAX: continue l, w, h = actor.dims frame.gt.append(GTBox( instance_id=actor.instance_id, class_name=actor.class_name, bbox_3d=[round(rel_x, 3), round(rel_y, 3), round(h / 2, 3), l, w, h, round(st["yaw"], 4)], occluded=bool(st["occluded"]), distance=round(math.hypot(rel_x, rel_y), 3))) seq.frames.append(frame) return seq
# ------------------------------------------------------- transform helpers
def _brake_from(states: List[Dict], k: int, decel: float) -> None: """Re-integrate a track from frame k braking at `decel` along its fixed heading; the speed profile is a clamped scalar (stops, never reverses).""" st = states[k] speed0 = math.hypot(st["vx"], st["vy"]) if speed0 < 1e-6: return ux, uy = st["vx"] / speed0, st["vy"] / speed0 for fi in range(k + 1, len(states)): prev = states[fi - 1] speed = max(0.0, math.hypot(prev["vx"], prev["vy"]) - decel * DT) vx, vy = ux * speed, uy * speed states[fi].update({ "x": prev["x"] + vx * DT, "y": prev["y"] + vy * DT, "vx": vx, "vy": vy, "yaw": st["yaw"], })
def _ramped_lateral(y0: float, vy_target: float, t_start: float, ti: float, ramp_a: float = 6.0) -> tuple: """Lateral position/velocity with a bounded-acceleration ramp to vy_target starting at t_start (keeps transforms physically plausible: ramp_a stays below the validity gate's pedestrian limit).""" if ti <= t_start: return y0, 0.0 t = ti - t_start t_ramp = abs(vy_target) / ramp_a if t <= t_ramp: vy = math.copysign(ramp_a * t, vy_target) y = y0 + math.copysign(0.5 * ramp_a * t * t, vy_target) else: vy = vy_target y = y0 + math.copysign(0.5 * ramp_a * t_ramp * t_ramp, vy_target) \ + vy_target * (t - t_ramp) return y, vy
def _clear_x(actors: List[ActorTrack], n_frames: int, y: float, rng: np.random.Generator, x_lo: float = 18.0, x_hi: float = 60.0, min_dist: float = 4.0) -> float: """Longitudinal spot whose distance to every existing trajectory at the given y stays >= min_dist (best-of-K deterministic search).""" best_x, best_d = (x_lo + x_hi) / 2, -1.0 for _ in range(24): x = float(rng.uniform(x_lo, x_hi)) d = min((math.hypot(st["x"] - x, st["y"] - y) for a in actors for st in a.states[::4]), default=1e9) if d > best_d: best_x, best_d = x, d if d >= min_dist: return x return best_x
def _lead_actor(actors: List[ActorTrack]) -> Optional[ActorTrack]: """Nearest vehicle-like actor ahead of ego near the ego lane at t=0; falls back to the fastest lane-following motorized actor (braking a slow crossing pedestrian is not a meaningful sudden-brake scenario).""" best, best_x = None, float("inf") for a in actors: st = a.states[0] if a.class_name in ("vehicle", "truck") and st["x"] > 5.0 and abs(st["y"]) < 4.0: if st["x"] < best_x: best, best_x = a, st["x"] if best is not None: return best motorized = [a for a in actors if a.class_name in ("vehicle", "truck", "motorcycle") and abs(a.states[0]["vy"]) < 0.5] if motorized: return max(motorized, key=lambda a: math.hypot(a.states[0]["vx"], a.states[0]["vy"])) return actors[0] if actors else None
def _pick(actors: List[ActorTrack], params: Dict, rng: np.random.Generator, prefer_class: Optional[str] = None) -> Optional[ActorTrack]: iid = params.get("instance_id") if iid: for a in actors: if a.instance_id == iid: return a if prefer_class: cands = [a for a in actors if a.class_name == prefer_class] if cands: return cands[int(rng.integers(0, len(cands)))] return actors[int(rng.integers(0, len(actors)))] if actors else None
# ------------------------------------------------------- transformations
# Each op: (actors, env, rng, params, n_frames) -> note string.
def _op_env(tag: str, value: str) -> Callable: def op(actors, env, rng, params, n_frames): env[tag] = value return f"environment: {tag} -> {value}" return op
def _op_sudden_brake(actors, env, rng, params, n_frames): target = _pick(actors, params, rng, prefer_class="vehicle") if params.get("instance_id") \ else _lead_actor(actors) if target is None: return "sudden_brake: no actor available" t_start = float(params.get("t_start_s", 1.0)) decel = float(params.get("decel_mps2", 7.5)) k = max(0, min(n_frames - 1, int(round(t_start / DT)))) st = target.states[k] if math.hypot(st["vx"], st["vy"]) < 1e-6: return f"sudden_brake: target {target.instance_id} already stationary" _brake_from(target.states, k, decel) # Chain reaction: same-lane followers brake 0.8 s later (traffic is not # frozen — otherwise the counterfactual plants unphysical rear-endings # that the validity gate would rightly reject). k2 = min(n_frames - 1, k + int(round(0.8 / DT))) speed_t = math.hypot(st["vx"], st["vy"]) ux, uy = st["vx"] / speed_t, st["vy"] / speed_t n_followers = 0 for a in actors: if a is target: continue s0 = a.states[k] along = (st["x"] - s0["x"]) * ux + (st["y"] - s0["y"]) * uy lateral = abs(-(st["x"] - s0["x"]) * uy + (st["y"] - s0["y"]) * ux) same_dir = (s0["vx"] * ux + s0["vy"] * uy) > 0.5 if along > 0 and lateral < 2.5 and same_dir: _brake_from(a.states, k2, min(decel, 8.0)) n_followers += 1 return (f"sudden_brake: {target.instance_id} decelerates at " f"{decel} m/s^2 from t={t_start}s; {n_followers} follower(s) " f"chain-brake at t={t_start + 0.8}s")
def _op_swerve(actors, env, rng, params, n_frames): target = _pick(actors, params, rng, prefer_class="vehicle") if target is None: return "swerve: no actor available" t_start = float(params.get("t_start_s", 1.0)) lat_acc = float(params.get("lateral_accel_mps2", 2.5)) duration = float(params.get("duration_s", 1.2)) k = max(0, min(n_frames - 1, int(round(t_start / DT)))) k_end = min(n_frames - 1, int(round((t_start + duration) / DT))) sign = -1.0 if target.states[k]["y"] > 0 else 1.0 # swerve toward ego lane for fi in range(k + 1, n_frames): prev = target.states[fi - 1] ay = sign * lat_acc if fi <= k_end else 0.0 vy = prev["vy"] + ay * DT target.states[fi].update({ "x": prev["x"] + prev["vx"] * DT, "y": prev["y"] + vy * DT, "vx": prev["vx"], "vy": vy, "yaw": math.atan2(vy, prev["vx"]) if prev["vx"] or vy else prev["yaw"], }) return (f"swerve: {target.instance_id} lateral accel {sign * lat_acc:+.1f} " f"m/s^2 for {duration}s from t={t_start}s")
def _op_stationary_to_crossing(actors, env, rng, params, n_frames): target = _pick(actors, params, rng, prefer_class="pedestrian") if target is None: return "stationary_to_crossing: no actor available" t_start = float(params.get("t_start_s", 0.8)) st0 = target.states[0] # Time the crossing so the actor reaches the ego lane center (y=0) when # a nominal-speed ego reaches its x -> a genuine conflict geometry. t_conflict = max(t_start + 0.8, st0["x"] / EGO_SPEED) vy = -st0["y"] / max(t_conflict - t_start, 0.5) vy = float(np.clip(vy, -2.5, 2.5)) # pedestrian-plausible speed for fi in range(n_frames): ti = fi * DT s = target.states[fi] y, vy_i = _ramped_lateral(st0["y"], vy, t_start, ti) s.update({"x": st0["x"], "y": y, "vx": 0.0, "vy": vy_i, "yaw": (math.pi / 2 if vy > 0 else -math.pi / 2) if vy_i else s["yaw"]}) return (f"stationary_to_crossing: {target.instance_id} crosses at " f"{vy:+.2f} m/s from t={t_start}s (conflict ~t={t_conflict:.1f}s)")
def _op_occluded_emergence(actors, env, rng, params, n_frames): """Plant an occluder truck and a pedestrian that emerges from behind it.""" t_emerge = float(params.get("t_emerge_s", 1.6)) y_side = float(params.get("y_m", 4.0)) tl, tw, th = CLASS_DIMS["truck"] x_emerge = float(params.get("x_m", _clear_x(actors, n_frames, y_side, rng, x_lo=EGO_SPEED * t_emerge + 10.0, x_hi=EGO_SPEED * t_emerge + 34.0))) truck = ActorTrack( instance_id=f"cf-occluder-{len(actors)}", class_name="truck", dims=[tl, tw, th], states=[{"x": x_emerge, "y": y_side + 1.8, "vx": 0.0, "vy": 0.0, "yaw": 0.0, "occluded": False} for _ in range(n_frames)]) pl, pw, ph = CLASS_DIMS["pedestrian"] vy = -1.9 states = [] for fi in range(n_frames): ti = fi * DT y, vy_i = _ramped_lateral(y_side, vy, t_emerge, ti) states.append({"x": x_emerge + tl / 2 + 0.8, "y": y, "vx": 0.0, "vy": vy_i, "yaw": -math.pi / 2, "occluded": ti <= t_emerge}) ped = ActorTrack(instance_id=f"cf-emergent-ped-{len(actors)}", class_name="pedestrian", dims=[pl, pw, ph], states=states) actors.extend([truck, ped]) return (f"occluded_emergence: pedestrian emerges from behind truck at " f"x={x_emerge:.1f} m, t={t_emerge}s")
def _op_teleport(actors, env, rng, params, n_frames): """STRESS TRANSFORM: instantaneous position jump — physically implausible by construction. Exists so tests/demos can prove the validity gate rejects implausible scenarios; never part of production recipes.""" target = _pick(actors, params, rng) if target is None: return "teleport: no actor available" k = max(1, min(n_frames - 1, int(round(float(params.get("t_s", 1.0)) / DT)))) jump = float(params.get("jump_m", 25.0)) for fi in range(k, n_frames): target.states[fi]["x"] += jump return f"teleport: {target.instance_id} jumps {jump} m at frame {k} (IMPLAUSIBLE)"
def _op_construction_zone(actors, env, rng, params, n_frames): length = float(params.get("length_m", 20.0)) # Deterministic search for a barrier line clear of existing trajectories. y_line = params.get("y_m") x0 = params.get("x_start_m") if x0 is None or y_line is None: best, best_d = (30.0, 3.4), -1.0 for _ in range(36): cx = float(rng.uniform(20.0, 55.0 - length / 2)) cy = float(rng.choice([3.4, 4.8, 6.2, -3.4, -4.8])) d = min((math.hypot(min(max(st["x"], cx), cx + length) - st["x"], cy - st["y"]) for a in actors for st in a.states[::2]), default=1e9) if d > best_d: best, best_d = (cx, cy), d if d >= 3.2: break x0 = x0 if x0 is not None else best[0] y_line = y_line if y_line is not None else best[1] x0, y_line = float(x0), float(y_line) n_barriers = max(2, int(length / 8)) for bi in range(n_barriers): actors.append(ActorTrack( instance_id=f"cf-construction-{bi}", class_name="truck", dims=[6.0, 2.2, 2.4], states=[{"x": x0 + bi * (length / max(n_barriers - 1, 1)), "y": y_line, "vx": 0.0, "vy": 0.0, "yaw": 0.0, "occluded": False} for _ in range(n_frames)]))
# Lane-following traffic near the closed shoulder shifts away, with a # smooth 10 m taper. Membership is decided ONCE per actor (initial lane + # longitudinal travel), so no temporal discontinuity is introduced. def taper(x: float) -> float: ramp = 10.0 if x < x0 - ramp or x > x0 + length + ramp: return 0.0 if x < x0: u = (x - (x0 - ramp)) / ramp elif x > x0 + length: u = ((x0 + length + ramp) - x) / ramp else: u = 1.0 return u * u * (3 - 2 * u) # smoothstep
away = -1.0 if y_line > 0 else 1.0 # shift direction: away from barriers for a in actors: if a.instance_id.startswith("cf-construction"): continue st0 = a.states[0] lane_following = abs(st0["vy"]) < 0.5 in_band = abs(st0["y"] - y_line) <= 4.0 if lane_following and in_band: for st in a.states: st["y"] += away * 1.6 * taper(st["x"]) env["construction_zone"] = f"x={x0:.0f}..{x0 + length:.0f}m" return f"add_construction_zone: {n_barriers} barriers at x={x0:.0f}..{x0+length:.0f} m"
def _op_pedestrian_density(actors, env, rng, params, n_frames): n = int(params.get("n", 4)) pl, pw, ph = CLASS_DIMS["pedestrian"] for pi in range(n): y = float(rng.uniform(4.0, 10.0)) * (1 if pi % 2 == 0 else -1) x = _clear_x(actors, n_frames, y, rng, x_lo=15.0, x_hi=65.0) vy = float(rng.uniform(0.8, 1.6)) * (-1 if y > 0 else 1) states = [] for fi in range(n_frames): yy, vy_i = _ramped_lateral(y, vy, 0.2, fi * DT) states.append({"x": x, "y": yy, "vx": 0.0, "vy": vy_i, "yaw": math.copysign(math.pi / 2, vy), "occluded": False}) actors.append(ActorTrack( instance_id=f"cf-ped-{pi}", class_name="pedestrian", dims=[pl, pw, ph], states=states)) return f"pedestrian_density: +{n} crossing pedestrians"
def _op_add_occlusion(actors, env, rng, params, n_frames): target = _pick(actors, params, rng) if target is None: return "add_occlusion: no actor available" start = int(params.get("start_frame", max(2, n_frames // 3))) length = int(params.get("length_frames", 4)) for fi in range(start, min(start + length, n_frames)): target.states[fi]["occluded"] = True return f"add_occlusion: {target.instance_id} occluded frames {start}..{start+length-1}"
def _op_distance_shift(actors, env, rng, params, n_frames): dx = float(params.get("delta_m", 10.0)) for a in actors: for st in a.states: st["x"] += dx return f"distance_shift: all actors shifted {dx:+.1f} m longitudinally"
def _op_lane_shift(actors, env, rng, params, n_frames): dy = float(params.get("delta_m", 1.5)) for a in actors: for st in a.states: st["y"] += dy return f"lane_shift: road geometry shifted {dy:+.1f} m laterally"
TRANSFORMATIONS: Dict[str, Callable] = { "environment.clear_to_fog": _op_env("weather_extended", "fog"), "environment.clear_to_rain": _op_env("weather", "rain"), "environment.day_to_night": _op_env("time_of_day", "night"), "environment.add_glare": _op_env("glare", "sunset_glare"), "environment.wet_road": _op_env("road_surface", "wet"), "actors.sudden_brake": _op_sudden_brake, "actors.swerve": _op_swerve, "actors.stationary_to_crossing": _op_stationary_to_crossing, "actors.occluded_emergence": _op_occluded_emergence, "actors.teleport": _op_teleport, "scene.add_construction_zone": _op_construction_zone, "scene.pedestrian_density": _op_pedestrian_density, "scene.add_occlusion": _op_add_occlusion, "scene.distance_shift": _op_distance_shift, "scene.lane_shift": _op_lane_shift,}
def transformation_catalogue() -> List[Dict]: """Recipe-builder metadata for the UI.""" docs = { "environment.clear_to_fog": {"family": "environment", "params": {}}, "environment.clear_to_rain": {"family": "environment", "params": {}}, "environment.day_to_night": {"family": "environment", "params": {}}, "environment.add_glare": {"family": "environment", "params": {}}, "environment.wet_road": {"family": "environment", "params": {}}, "actors.sudden_brake": {"family": "actors", "params": {"t_start_s": 1.0, "decel_mps2": 7.5}}, "actors.swerve": {"family": "actors", "params": {"t_start_s": 1.0, "lateral_accel_mps2": 2.5, "duration_s": 1.2}}, "actors.stationary_to_crossing": {"family": "actors", "params": {"t_start_s": 0.8}}, "actors.occluded_emergence": {"family": "actors", "params": {"t_emerge_s": 1.6}}, "actors.teleport": {"family": "actors (stress/test only)", "params": {"t_s": 1.0, "jump_m": 25.0}}, "scene.add_construction_zone": {"family": "scene", "params": {"x_start_m": 30.0, "length_m": 20.0}}, "scene.pedestrian_density": {"family": "scene", "params": {"n": 4}}, "scene.add_occlusion": {"family": "scene", "params": {"start_frame": 8, "length_frames": 4}}, "scene.distance_shift": {"family": "scene", "params": {"delta_m": 10.0}}, "scene.lane_shift": {"family": "scene", "params": {"delta_m": 1.5}}, } return [{"kind": k, **v} for k, v in docs.items()]
# ------------------------------------------------------- the live transformer
class DeterministicSceneTransformer(SceneTransformer): """The internal world model: deterministic rule-based scene transformer.
Pure function of (source, recipe, seed); all randomness (actor selection, added-actor placement) is drawn from a generator seeded with the given seed, so a scenario's provenance record fully reproduces it. """
name = "nextgen.worldmodel.DeterministicSceneTransformer" version = "1.0"
def transform(self, source: SceneSequence, recipe: List[TransformationStep], seed: int) -> TransformedScene: rng = np.random.default_rng([seed, 0xC0FFEE]) n_frames = len(source.frames) actors = reconstruct_actors(source) env: Dict[str, str] = {"time_of_day": source.time_of_day, "weather": source.weather} notes: List[str] = [] for step in recipe: op = TRANSFORMATIONS.get(step.kind) if op is None: raise ValueError(f"unknown transformation {step.kind!r}; " f"known: {sorted(TRANSFORMATIONS)}") notes.append(op(actors, env, rng, step.params, n_frames)) seq = render_sequence(actors, env, n_frames, sequence_id=f"cf-{source.sequence_id}-{seed}") return TransformedScene(sequence=seq, actors=actors, environment=env, applied=list(recipe), notes=notes)
# ------------------------------------------------------- generation + storage
def _actor_dump(a: ActorTrack) -> Dict: return {"instance_id": a.instance_id, "class_name": a.class_name, "dims": a.dims, "states": a.states}
def _actor_load(d: Dict) -> ActorTrack: return ActorTrack(instance_id=d["instance_id"], class_name=d["class_name"], dims=d["dims"], states=d["states"])
def generate_counterfactuals(recipe: List[TransformationStep], seed: int = 7, n_scenarios: int = 3, frames_per_sequence: int = 40) -> List[CounterfactualScenario]: """Generate counterfactual scenarios from bevfusion source scenes and persist them (with full provenance) under runs/nextgen/counterfactuals/.""" sources = generate_sequences(n_sequences=n_scenarios, frames_per_sequence=frames_per_sequence, seed=seed) from sensorflow.nextgen.validity import overlap_pairs, scene_features transformer = DeterministicSceneTransformer() out: List[CounterfactualScenario] = [] for si, source in enumerate(sources): scenario_seed = seed * 1009 + si source_overlaps = overlap_pairs(reconstruct_actors(source)) source_feats = {k: [round(float(x), 3) for x in v] for k, v in scene_features(source).items()} result = transformer.transform(source, recipe, scenario_seed) scenario_id = f"cfs-{uuid4().hex[:10]}" scenario = CounterfactualScenario( scenario_id=scenario_id, provenance=Provenance( source_scene_id=source.sequence_id, recipe=list(recipe), seed=scenario_seed, generator=transformer.name, generator_version=transformer.version, data_label=DataLabel.COUNTERFACTUAL), n_frames=len(result.sequence.frames), n_actors=len(result.actors), environment=result.environment) store.write_json({ "scenario": scenario.model_dump(mode="json"), "sequence": result.sequence.model_dump(mode="json"), "actors": [_actor_dump(a) for a in result.actors], "notes": result.notes, "source_overlap_pairs": [sorted(p) for p in source_overlaps], "source_features": source_feats, }, "counterfactuals", f"{scenario_id}.json") out.append(scenario) return out
def load_bundle(scenario_id: str) -> Optional[Dict]: """Load a persisted scenario bundle: scenario + sequence + world tracks.""" raw = store.read_json("counterfactuals", f"{scenario_id}.json") if raw is None: return None return { "scenario": CounterfactualScenario(**raw["scenario"]), "sequence": SceneSequence(**raw["sequence"]), "actors": [_actor_load(d) for d in raw["actors"]], "notes": raw.get("notes", []), "source_overlap_pairs": {frozenset(p) for p in raw.get("source_overlap_pairs", [])}, "source_features": raw.get("source_features"), }
def save_scenario(scenario: CounterfactualScenario) -> None: """Update the persisted scenario record (e.g. after validity gating).""" raw = store.read_json("counterfactuals", f"{scenario.scenario_id}.json") if raw is None: raise KeyError(f"unknown scenario {scenario.scenario_id}") raw["scenario"] = scenario.model_dump(mode="json") store.write_json(raw, "counterfactuals", f"{scenario.scenario_id}.json")
def list_scenarios() -> List[CounterfactualScenario]: out = [] for sid in store.list_json("counterfactuals"): raw = store.read_json("counterfactuals", f"{sid}.json") if raw: out.append(CounterfactualScenario(**raw["scenario"])) return out1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Evaluation-run lineage: reproducibility records and launch validity.
Policy (deterministic): a run missing ANY lineage field is marked INVALID forlaunch purposes. It may still be inspected, but LaunchRecommendation for sucha run is forced to INVALID by regression.py / scheduler.py."""
from __future__ import annotations
from typing import Dict, List, Tuple
from sensorflow.nextgen.models import EvaluationRun, LineageRecord
# Current component versions of this package. Bumping any of these changes# cache keys (cache.py) and appears in every lineage record.COMPONENT_VERSIONS: Dict[str, str] = { "scenario_set_version": "bevfusion-scenes-1.0", "sensor_sim_version": "bevfusion-sensors-1.0", "simulation_version": "nextgen-closedloop-1.0", "feature_pipeline_version": "nextgen-features-1.0", "metric_version": "nextgen-metrics-1.0", "policy_version": "nextgen-launch-policy-1.0",}
REQUIRED_FIELDS = [ "model_version", "dataset_version", "scenario_set_version", "sensor_sim_version", "simulation_version", "feature_pipeline_version", "metric_version", "policy_version",]
def build_lineage(model_version: str, dataset_version: str, seeds: Dict[str, int], baseline_version: str | None = None, overrides: Dict[str, str] | None = None) -> LineageRecord: fields = {**COMPONENT_VERSIONS, **(overrides or {})} return LineageRecord(model_version=model_version, baseline_version=baseline_version, dataset_version=dataset_version, seeds=dict(seeds), **fields)
def validate_lineage(lineage: LineageRecord | None) -> Tuple[bool, List[str]]: """Deterministic completeness check. Missing seeds are also a violation: without them the run is not reproducible.""" if lineage is None: return False, ["lineage record entirely missing"] missing = [f for f in REQUIRED_FIELDS if not getattr(lineage, f)] if not lineage.seeds: missing.append("seeds") return (len(missing) == 0, [f"missing lineage field: {m}" for m in missing])
def stamp_run(run: EvaluationRun) -> EvaluationRun: """Attach validity verdict to a run based on its lineage.""" ok, reasons = validate_lineage(run.lineage) run.lineage_valid = ok if not ok: run.valid_for_launch = False run.invalid_reasons = list(dict.fromkeys(run.invalid_reasons + reasons)) return run123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220"""Pydantic schemas shared by the nextgen evaluation platform.
Every datum that can appear in a report carries a DataLabel; the label isassigned at creation time and is never inferred downstream.
AgenticSafetyScorecard: Feature 1 (sensorflow.agentic) is being builtconcurrently by another workstream. We import its scorecard when available sothe two subsystems share one shape; otherwise a compatible local definition(the fields relevant to Features 2-5: behavioral_impact,counterfactual_validated, closed_loop_validated) is used and marked as such."""
from __future__ import annotations
from datetime import datetime, timezonefrom enum import Enumfrom typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
def utc_now() -> str: return datetime.now(timezone.utc).isoformat()
class DataLabel(str, Enum): """Provenance of a datum. Simulation is evidence, not reality; the label says which kind of evidence and travels with every report."""
REAL = "REAL" # captured on-vehicle REPLAYED = "REPLAYED" # real log replayed open-loop SIMULATED = "SIMULATED" # synthetic scenario, nominal params GENERATED = "GENERATED" # model-generated content COUNTERFACTUAL = "COUNTERFACTUAL" # transformation of a source scenario
class TransformationStep(BaseModel): """One step of a counterfactual recipe (deterministic, parameterized)."""
kind: str # e.g. "environment.day_to_night" params: Dict[str, Any] = Field(default_factory=dict)
class Provenance(BaseModel): """Where a counterfactual scenario came from — carried through every evaluation report that touches the scenario."""
source_scene_id: str recipe: List[TransformationStep] = Field(default_factory=list) seed: int = 0 generator: str = "nextgen.worldmodel.DeterministicSceneTransformer" generator_version: str = "1.0" data_label: DataLabel = DataLabel.COUNTERFACTUAL created_at: str = Field(default_factory=utc_now)
class ValidityReport(BaseModel): """Output of the counterfactual validity gate (validity.py)."""
scenario_id: str checks: List[Dict[str, Any]] = Field(default_factory=list) simulation_fidelity_score: float = 0.0 # [0,1] physical/temporal/sensor counterfactual_validity: float = 0.0 # [0,1] gate-weighted composite realism_confidence: float = 0.0 # [0,1] distribution similarity accepted: bool = False evaluation_weight: float = 0.0 # cap applied for low fidelity weight_capped: bool = False reasons: List[str] = Field(default_factory=list)
class CounterfactualScenario(BaseModel): scenario_id: str provenance: Provenance n_frames: int = 0 n_actors: int = 0 environment: Dict[str, str] = Field(default_factory=dict) validity: Optional[ValidityReport] = None
class LineageRecord(BaseModel): """Full reproducibility record for one evaluation run. A run whose lineage is incomplete is marked INVALID for launch purposes (lineage.py)."""
model_version: Optional[str] = None baseline_version: Optional[str] = None dataset_version: Optional[str] = None scenario_set_version: Optional[str] = None sensor_sim_version: Optional[str] = None simulation_version: Optional[str] = None feature_pipeline_version: Optional[str] = None metric_version: Optional[str] = None policy_version: Optional[str] = None seeds: Dict[str, int] = Field(default_factory=dict) created_at: str = Field(default_factory=utc_now)
class EvaluationRun(BaseModel): run_id: str kind: str # counterfactual_generation | closed_loop | causal_replay | gauntlet | safety_report status: str = "created" # created | running | completed | halted | failed data_labels: List[DataLabel] = Field(default_factory=list) lineage: Optional[LineageRecord] = None lineage_valid: bool = False valid_for_launch: bool = False invalid_reasons: List[str] = Field(default_factory=list) created_at: str = Field(default_factory=utc_now) params: Dict[str, Any] = Field(default_factory=dict) results: Dict[str, Any] = Field(default_factory=dict)
class BehavioralMetrics(BaseModel): """Closed-loop behavioral metrics for one scenario run (closedloop.py). All safety-region math reuses sensorflow.safety.ssam_ext."""
detection_latency_s: Optional[float] = None # first-relevant-object detect delay time_to_detection_s: Optional[float] = None # sim time of first detection min_ttc_s: Optional[float] = None stopping_distance_m: Optional[float] = None max_deceleration_mps2: float = 0.0 max_steering_rate_radps: float = 0.0 planner_interventions: int = 0 collision: bool = False collision_probability: float = 0.0 min_separation_m: Optional[float] = None safety_margin_m: Optional[float] = None # min_separation - required stopping gap final_speed_mps: float = 0.0
class BehavioralAssessment(BaseModel): scenario_id: str data_label: DataLabel perception_mode: str # "actual" | "corrected" metrics: BehavioralMetrics open_loop: Dict[str, Any] = Field(default_factory=dict) # complementary, never replaced trajectory: List[Dict[str, float]] = Field(default_factory=list)
CAUSAL_METRIC_ONLY = "METRIC_ONLY"CAUSAL_BEHAVIORAL = "BEHAVIORALLY_CONSEQUENTIAL"
class CausalReplayResult(BaseModel): scenario_id: str data_label: DataLabel actual: BehavioralAssessment corrected: BehavioralAssessment diffs: Dict[str, Any] = Field(default_factory=dict) causal_chain: List[Dict[str, Any]] = Field(default_factory=list) verdict: str = CAUSAL_METRIC_ONLY
class DistributionShiftAssessment(BaseModel): run_id: str method: str shifts: List[Dict[str, Any]] = Field(default_factory=list) psi: Optional[float] = None js_divergence: Optional[float] = None magnitude: Optional[str] = None data_labels: List[DataLabel] = Field(default_factory=list)
class ComputeOptimizationResult(BaseModel): report_id: str n_scenarios: int n_models: int naive_full_inferences: int optimized_backbone_computes: int optimized_head_computes: int cache_hits: int cache_misses: int hit_rate: float naive_cost_s: float # measured per-unit timings x naive counts optimized_cost_s: float # actually measured wall time savings_ratio: float measured_backbone_s: float measured_head_s: float invalidation: str created_at: str = Field(default_factory=utc_now)
class LaunchRecommendation(BaseModel): run_id: str recommendation: str # LAUNCH | DO_NOT_LAUNCH | INSUFFICIENT_EVIDENCE | INVALID blockers: List[str] = Field(default_factory=list) statistical_significance: Dict[str, Any] = Field(default_factory=dict) safety_significance: Dict[str, Any] = Field(default_factory=dict) # never equated with statistical lineage_valid: bool = False data_labels: List[DataLabel] = Field(default_factory=list) policy_version: str = "nextgen-launch-policy-1.0"
# --------------------------------------------------------------- scorecard
try: # Feature 1 is built concurrently in sensorflow/agentic (guarded import). from sensorflow.agentic.models import AgenticSafetyScorecard # type: ignore # noqa: F401 AGENTIC_SCORECARD_SOURCE = "sensorflow.agentic.models"except Exception: # pragma: no cover - depends on sibling workstream timing AgenticSafetyScorecard = None # type: ignore[assignment] AGENTIC_SCORECARD_SOURCE = "unavailable (sensorflow.agentic not importable)"
class ScorecardBehavioralExtension(BaseModel): """The Features-2-5 contribution to the shared safety scorecard.
The agentic package's AgenticSafetyScorecard (severity / exposure / policy_outcome / ...) does not itself carry closed-loop fields; this extension composes with it via agentic_scorecard_id rather than redefining it. behavioral_impact carries the causal-replay verdict (METRIC_ONLY / BEHAVIORALLY_CONSEQUENTIAL); the two *_validated flags say whether counterfactual validity gating and closed-loop replay were actually run for the case. """
case_id: str agentic_scorecard_id: Optional[str] = None # link to Feature 1's scorecard behavioral_impact: Optional[str] = None # causal replay verdict counterfactual_validated: Optional[bool] = None closed_loop_validated: Optional[bool] = None data_label: DataLabel = DataLabel.SIMULATED details: Dict[str, Any] = Field(default_factory=dict)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""Baseline-vs-candidate regression analysis across strata, with statisticaland safety significance kept STRICTLY separate.
Strata: global / class / scenario-type / safety / ODD. For each stratum wereport absolute + relative delta, a cluster-robust confidence interval,sample size, and two independent verdicts:
* statistical significance — is the delta distinguishable from noise? Delegated to sensorflow.seqeval (anytime-valid PairedSequentialTest on cluster means) — REUSE, not reimplementation. The descriptive CI uses seqeval's cluster machinery (units.py) as well.* safety significance — does the delta matter for safety? A deterministic policy question: the stratum's safety margin (tighter for safety strata) and the direction of the effect. A tiny-but-certain regression can be statistically significant yet safety-insignificant; a large regression on a small safety stratum can be safety-significant (blocking further evaluation, demanding more data) while statistically unresolved. The two are NEVER combined into one number.
Launch recommendation policy (deterministic):* lineage invalid -> INVALID (never launchable)* any safety-significant regression that is also statistically confirmed -> DO_NOT_LAUNCH* safety-significant but statistically unresolved -> INSUFFICIENT_EVIDENCE* otherwise -> LAUNCH"""
from __future__ import annotations
from typing import Dict, List, Optional
import numpy as np
# REUSE: all sequential statistics from seqeval.from sensorflow.seqeval.sequential import ( DECISION_INSUFFICIENT, DECISION_PASS, DECISION_REGRESSION, PairedSequentialTest,)from sensorflow.seqeval.units import cluster_summary, cluster_units
from sensorflow.nextgen.lineage import validate_lineagefrom sensorflow.nextgen.models import LaunchRecommendation, LineageRecord
# Safety margins per stratum kind (absolute metric points).SAFETY_MARGINS = {"safety": 0.005, "odd": 0.010, "scenario": 0.010, "class": 0.015, "global": 0.010}STATISTICAL_MARGIN = 0.005 # practical-significance margin for the e-processALPHA = 0.05
def analyze_stratum(name: str, kind: str, baseline: np.ndarray, candidate: np.ndarray, cluster_ids: np.ndarray, data_label: str = "SIMULATED") -> Dict: """Full per-stratum record from paired per-unit outcomes.""" b = np.asarray(baseline, dtype=np.float64) c = np.asarray(candidate, dtype=np.float64) d = c - b
test = PairedSequentialTest(delta=STATISTICAL_MARGIN, alpha=ALPHA) means, _sizes = cluster_units(d, cluster_ids) test.update_clusters(means) test.record_objects(b.astype(bool), c.astype(bool)) decision = test.evaluate() lo, hi = test.delta_interval()
base_rate = float(b.mean()) if b.size else None cand_rate = float(c.mean()) if c.size else None delta_abs = None if base_rate is None else cand_rate - base_rate delta_rel = (None if not base_rate else delta_abs / base_rate)
margin = SAFETY_MARGINS.get(kind, 0.010) # Safety significance: the point estimate breaches the stratum's safety # margin in the harmful direction. Deliberately a POLICY statement about # magnitude, independent of the statistical verdict. safety_significant = delta_abs is not None and delta_abs < -margin statistically_significant = decision == DECISION_REGRESSION
return { "stratum": name, "kind": kind, "data_label": data_label, "n": int(b.size), "clustering": cluster_summary(d, cluster_ids), "baseline_rate": _r(base_rate), "candidate_rate": _r(cand_rate), "delta_abs": _r(delta_abs), "delta_rel": _r(delta_rel), "delta_ci": [_r(lo), _r(hi)], "ci_method": "anytime-valid empirical-Bernstein confidence sequence " "on cluster means (seqeval)", "statistical": { "decision": decision, "significant_regression": statistically_significant, "e_regression": round(test.e_reg.e_value, 4), "e_pass": round(test.e_pass.e_value, 4), "margin": STATISTICAL_MARGIN, "alpha": ALPHA, }, "safety": { "margin": margin, "significant": bool(safety_significant), "note": "safety significance is a policy magnitude judgment; it " "is never derived from, nor equated with, the " "statistical verdict", }, }
def launch_recommendation(run_id: str, strata: List[Dict], lineage: Optional[LineageRecord], data_labels: List[str]) -> LaunchRecommendation: lineage_ok, lineage_reasons = validate_lineage(lineage)
blockers: List[str] = [] stat_summary: Dict = {"regressions": [], "passes": [], "unresolved": []} safety_summary: Dict = {"significant_regressions": [], "margins": SAFETY_MARGINS}
for s in strata: dec = s["statistical"]["decision"] if dec == DECISION_REGRESSION: stat_summary["regressions"].append(s["stratum"]) elif dec == DECISION_PASS: stat_summary["passes"].append(s["stratum"]) else: stat_summary["unresolved"].append(s["stratum"]) if s["safety"]["significant"]: safety_summary["significant_regressions"].append( {"stratum": s["stratum"], "delta_abs": s["delta_abs"], "statistical_decision": dec})
if not lineage_ok: recommendation = "INVALID" blockers.extend(lineage_reasons) blockers.append("run is INVALID for launch purposes: incomplete lineage") else: confirmed = [r for r in safety_summary["significant_regressions"] if r["statistical_decision"] == DECISION_REGRESSION] unresolved = [r for r in safety_summary["significant_regressions"] if r["statistical_decision"] == DECISION_INSUFFICIENT] if confirmed: recommendation = "DO_NOT_LAUNCH" for r in confirmed: blockers.append( f"safety-significant regression in {r['stratum']} " f"(delta {r['delta_abs']:+.4f}), statistically confirmed") elif unresolved: recommendation = "INSUFFICIENT_EVIDENCE" for r in unresolved: blockers.append( f"safety-significant point estimate in {r['stratum']} " f"(delta {r['delta_abs']:+.4f}) not yet statistically " f"resolved — needs more evidence, not a launch") else: recommendation = "LAUNCH"
return LaunchRecommendation( run_id=run_id, recommendation=recommendation, blockers=blockers, statistical_significance=stat_summary, safety_significance=safety_summary, lineage_valid=lineage_ok, data_labels=list(dict.fromkeys(data_labels))) # type: ignore[arg-type]
def _r(v: Optional[float], nd: int = 5) -> Optional[float]: return None if v is None else round(float(v), nd)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263"""Safety-informed metrics: Safety-Critical Recall (SCR) and risk weighting.
Design principle: open-loop metrics (recall/precision/IoU) are NEVER replaced— every report here carries them alongside the safety-informed view. The twoviews answer different questions ("how good is perception?" vs "how good isperception where it matters?") and can legitimately move in oppositedirections; `divergence_demo` constructs exactly that case.
Safety-critical region (explicitly defined, parameterized)----------------------------------------------------------NOT naive stopping distance. An object is safety-critical when ANY of:
1. Longitudinal criticality: it lies ahead within d_crit(v) = v * t_react + v^2 / (2 * a_eff) + buffer where a_eff = min(brake_capability, mu * g) — the friction-limited achievable deceleration — AND laterally within the encroachment band |y| <= corridor_half_width + v_lat_max(class) * t_stop(v) with t_stop(v) = t_react + v / a_eff: anything that can REACH the ego corridor before the ego can stop counts, scaled by how fast that class of actor can move laterally.2. TTC criticality: projected TTC below ttc_critical_s (reuses the sensorflow.safety.ssam_ext conflict-point projection when velocity data is available).
Risk weight (per object, deterministic): w = vulnerability(class) * proximity * closing_speed_factor * ttc_factor * occlusion_factor * ego_speed_factor"""
from __future__ import annotations
import mathfrom dataclasses import asdict, dataclassfrom typing import Dict, List, Optional
import numpy as np
from sensorflow.safety.ssam_ext import projected_ttc
G = 9.81
VULNERABILITY = {"pedestrian": 1.0, "cyclist": 0.9, "motorcycle": 0.8, "vehicle": 0.4, "truck": 0.35}# How fast each class can move laterally toward the corridor (m/s).LATERAL_SPEED_CAP = {"pedestrian": 2.5, "cyclist": 5.0, "motorcycle": 8.0, "vehicle": 6.0, "truck": 4.0}
@dataclassclass SafetyRegionParams: """All region math is a pure function of these documented parameters."""
reaction_time_s: float = 0.9 # perception->brake-onset latency budget brake_capability_mps2: float = 7.0 # vehicle hardware limit friction_mu: float = 0.9 # 0.9 dry asphalt; ~0.5-0.6 wet corridor_half_width_m: float = 1.6 buffer_m: float = 2.0 ttc_critical_s: float = 3.0
@property def effective_decel(self) -> float: return min(self.brake_capability_mps2, self.friction_mu * G)
def stopping_distance(self, v: float) -> float: return v * self.reaction_time_s + v ** 2 / (2 * self.effective_decel)
def d_crit(self, v: float) -> float: return self.stopping_distance(v) + self.buffer_m
def t_stop(self, v: float) -> float: return self.reaction_time_s + v / self.effective_decel
def in_safety_critical_region(obj: Dict, ego_speed: float, params: Optional[SafetyRegionParams] = None) -> Dict: """Classify one object. obj: {x, y (ego frame), class_name, vx, vy, occluded}. Returns the verdict plus every intermediate quantity.""" p = params or SafetyRegionParams() x, y = float(obj["x"]), float(obj["y"]) cls = obj.get("class_name", "vehicle") d_crit = p.d_crit(ego_speed) lat_band = (p.corridor_half_width_m + LATERAL_SPEED_CAP.get(cls, 5.0) * p.t_stop(ego_speed)) longitudinal = 0.0 <= x <= d_crit and abs(y) <= lat_band
ttc = None if "vx" in obj and "vy" in obj: ego_state = {"x": 0.0, "y": 0.0, "speed": ego_speed, "heading": 0.0} obj_state = {"x": x, "y": y, "speed": math.hypot(obj["vx"], obj["vy"]), "heading": math.atan2(obj["vy"], obj["vx"]) if (obj["vx"], obj["vy"]) != (0.0, 0.0) else 0.0} dims = tuple(obj.get("dims", [1.0, 1.0])[:2]) ttc = projected_ttc(ego_state, (4.5, 1.9), obj_state, dims, look_ahead=p.ttc_critical_s + 1.0, dt=0.1) ttc_critical = ttc is not None and ttc <= p.ttc_critical_s
return {"safety_critical": bool(longitudinal or ttc_critical), "longitudinal_critical": bool(longitudinal), "ttc_critical": bool(ttc_critical), "d_crit_m": round(d_crit, 3), "lateral_band_m": round(lat_band, 3), "effective_decel_mps2": round(p.effective_decel, 3), "ttc_s": None if ttc is None else round(ttc, 3)}
def risk_weight(obj: Dict, ego_speed: float, params: Optional[SafetyRegionParams] = None) -> float: """Deterministic risk weight: vulnerability x proximity x closing speed x TTC x occlusion x ego speed.""" p = params or SafetyRegionParams() x, y = float(obj["x"]), float(obj["y"]) dist = math.hypot(x, y) vuln = VULNERABILITY.get(obj.get("class_name", "vehicle"), 0.5) proximity = float(np.clip(1.0 - dist / 80.0, 0.05, 1.0)) closing = ego_speed - float(obj.get("vx", 0.0)) if x > 0 else 0.0 closing_f = float(np.clip(0.3 + closing / 20.0, 0.3, 1.5)) region = in_safety_critical_region(obj, ego_speed, p) ttc = region["ttc_s"] ttc_f = 1.5 if ttc is None and region["safety_critical"] else ( float(np.clip(2.0 - (ttc or 10.0) / p.ttc_critical_s, 0.5, 2.0))) occl_f = 1.25 if obj.get("occluded") else 1.0 ego_f = float(np.clip(ego_speed / 15.0, 0.3, 1.5)) return round(vuln * proximity * closing_f * ttc_f * occl_f * ego_f, 6)
# ------------------------------------------------------------ reporting
def safety_report(objects: List[Dict], ego_speed: float = 10.0, params: Optional[SafetyRegionParams] = None, data_label: str = "SIMULATED") -> Dict: """Full safety-informed report for a set of GT objects with `detected` flags. Open-loop recall is ALWAYS reported alongside SCR.""" p = params or SafetyRegionParams() n = len(objects) detected = np.array([bool(o.get("detected")) for o in objects]) critical = np.zeros(n, dtype=bool) weights = np.zeros(n) per_object = [] for i, o in enumerate(objects): region = in_safety_critical_region(o, ego_speed, p) critical[i] = region["safety_critical"] weights[i] = risk_weight(o, ego_speed, p) per_object.append({**{k: o.get(k) for k in ("x", "y", "class_name", "occluded", "detected")}, **region, "risk_weight": weights[i]})
overall_recall = float(detected.mean()) if n else None n_crit = int(critical.sum()) scr = float(detected[critical].mean()) if n_crit else None rw_recall = (float((weights * detected).sum() / weights.sum()) if weights.sum() > 0 else None)
by_class: Dict[str, Dict] = {} for cls in sorted({o.get("class_name", "vehicle") for o in objects}): mask = np.array([o.get("class_name") == cls for o in objects]) cmask = mask & critical by_class[cls] = { "n": int(mask.sum()), "recall": round(float(detected[mask].mean()), 4) if mask.any() else None, "n_safety_critical": int(cmask.sum()), "safety_critical_recall": (round(float(detected[cmask].mean()), 4) if cmask.any() else None), "risk_weighted_recall": (round(float((weights[mask] * detected[mask]).sum() / weights[mask].sum()), 4) if weights[mask].sum() > 0 else None), }
return { "data_label": data_label, "region_params": asdict(p), "region_definition": ( "d_crit(v) = v*t_react + v^2/(2*min(brake, mu*g)) + buffer; " "lateral band = corridor + v_lat_max(class)*t_stop(v); " "OR projected TTC <= ttc_critical_s (ssam_ext conflict-point " "projection)"), "ego_speed_mps": ego_speed, "open_loop": {"n_objects": n, "recall": _r(overall_recall)}, "safety_informed": { "n_safety_critical": n_crit, "safety_critical_recall": _r(scr), "risk_weighted_recall": _r(rw_recall), }, "by_class": by_class, "per_object": per_object, "note": "open-loop and safety-informed metrics are complementary; " "reports always show both", }
# ------------------------------------------------------------ divergence demo
def divergence_demo(ego_speed: float = 12.0) -> Dict: """Constructed demonstration: candidate improves OVERALL recall while Safety-Critical Recall DEGRADES. Deterministic synthetic data:
* 400 far-field vehicles (45-75 m, off-corridor): easy volume. The candidate detects far more of them (0.60 -> 0.85) — e.g. a model tuned for long-range benchmarks. * 60 near in-path pedestrians (inside d_crit, in corridor): the candidate regresses (0.92 -> 0.78) — e.g. lost close-range VRU sensitivity.
Detected counts are exact (first k of each group), so the demonstration is fully deterministic and testable. """ p = SafetyRegionParams() objects_base: List[Dict] = [] objects_cand: List[Dict] = []
def add_group(n: int, base_rate: float, cand_rate: float, maker) -> None: k_base, k_cand = int(round(n * base_rate)), int(round(n * cand_rate)) for i in range(n): o = maker(i) objects_base.append({**o, "detected": i < k_base}) objects_cand.append({**o, "detected": i < k_cand})
add_group(400, 0.60, 0.85, lambda i: { "x": 45.0 + 30.0 * (i % 20) / 20.0, "y": 6.0 * (1 if i % 2 else -1), "class_name": "vehicle", "vx": 8.0, "vy": 0.0, "occluded": False}) d_near = p.d_crit(ego_speed) * 0.6 add_group(60, 0.92, 0.78, lambda i: { "x": 4.0 + d_near * (i % 12) / 12.0, "y": 0.9 * (1 if i % 2 else -1), "class_name": "pedestrian", "vx": 0.0, "vy": 1.2 * (-1 if i % 2 else 1), "occluded": i % 5 == 0})
base = safety_report(objects_base, ego_speed, p) cand = safety_report(objects_cand, ego_speed, p) for rep in (base, cand): rep.pop("per_object", None)
return { "baseline": base, "candidate": cand, "deltas": { "overall_recall": _delta(base["open_loop"]["recall"], cand["open_loop"]["recall"]), "safety_critical_recall": _delta( base["safety_informed"]["safety_critical_recall"], cand["safety_informed"]["safety_critical_recall"]), "risk_weighted_recall": _delta( base["safety_informed"]["risk_weighted_recall"], cand["safety_informed"]["risk_weighted_recall"]), }, "headline": "overall recall IMPROVES while safety-critical recall " "DEGRADES — why launch decisions must never rely on " "aggregate recall alone", "construction": "400 far-field vehicles (0.60->0.85 detected) + 60 " "near in-path pedestrians (0.92->0.78 detected); " "exact counts, deterministic", "data_label": "SIMULATED", }
def _r(v: Optional[float]) -> Optional[float]: return None if v is None else round(float(v), 4)
def _delta(b: Optional[float], c: Optional[float]) -> Optional[float]: if b is None or c is None: return None return round(c - b, 4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349"""Intelligent launch-evaluation scheduler: the priority-ordered gauntlet.
Priority order (deterministic policy): 1. safety_critical 2. historical_regressions 3. new_odd 4. distribution_shift 5. rare_events 6. nominal
Budget-aware batched execution with sequential early stopping DELEGATED tosensorflow.seqeval (reuse, not reimplementation): every stopping decision isan anytime-valid e-process decision from seqeval.PairedSequentialTest.
STATISTICAL VALIDITY CONDITIONS FOR EARLY STOPPING (documented + enforced):* Only ANYTIME-VALID statistics may stop a stratum: the e-process guarantees (Ville's inequality) hold at every data-dependent stopping time, so peeking after every batch costs nothing. Enforced structurally — the loop has no other stopping test; the descriptive Wilson-style CIs in reports are never consulted for control flow.* Observations fed to the tests are CLUSTER means (seqeval.units), so within-scene correlation cannot make stopping anti-conservative.* Decisions are sticky (seqeval semantics): once REGRESSION/PASS is declared at level alpha it is never revisited.
Early-stop policy:* catastrophic regression (safety_critical stratum, REGRESSION decision, delta estimate below -catastrophic_delta) -> HALT the entire candidate;* high-confidence regression in any stratum -> related strata (RELATED map) are promoted to the front of the remaining queue;* critical-suite PASS (safety_critical passes) -> EXPAND: the nominal stratum's unit allowance is multiplied (cheap volume evidence only after the safety-critical evidence is in).
Scenario units are lightweight paired-outcome units (the 100k-scaledemonstration measures scheduling + caching math with real timings; eachunit stands for one scenario evaluation). Unit outcome vectors are cachedcontent-addressed per (stratum, model pair, versions) via cache.py, so are-run of the same gauntlet hits the cache instead of recomputing — thesame dedup math that makes a real 100k-scenario gauntlet sublinear."""
from __future__ import annotations
import timefrom typing import Dict, List, Optionalfrom uuid import uuid4
import numpy as np
from sensorflow.seqeval.sequential import ( DECISION_INSUFFICIENT, DECISION_PASS, DECISION_REGRESSION, PairedSequentialTest,)from sensorflow.seqeval.units import cluster_units
from sensorflow.nextgen import storefrom sensorflow.nextgen.cache import CacheKeyVersions, get_feature_cachefrom sensorflow.nextgen.lineage import build_lineagefrom sensorflow.nextgen.models import DataLabel, EvaluationRunfrom sensorflow.nextgen.regression import launch_recommendationfrom sensorflow.nextgen import lineage as lineage_mod
PRIORITY_ORDER = ["safety_critical", "historical_regressions", "new_odd", "distribution_shift", "rare_events", "nominal"]
RELATED = { "safety_critical": ["historical_regressions", "rare_events"], "historical_regressions": ["safety_critical"], "new_odd": ["distribution_shift"], "distribution_shift": ["new_odd", "rare_events"], "rare_events": ["safety_critical"], "nominal": [],}
# Default synthetic gauntlet: >= 100k scenario units total.DEFAULT_STRATA: Dict[str, Dict] = { "safety_critical": {"units": 12_000, "base_rate": 0.90, "cluster_size": 20, "data_label": "COUNTERFACTUAL"}, "historical_regressions": {"units": 10_000, "base_rate": 0.88, "cluster_size": 20, "data_label": "REPLAYED"}, "new_odd": {"units": 14_000, "base_rate": 0.86, "cluster_size": 25, "data_label": "SIMULATED"}, "distribution_shift": {"units": 14_000, "base_rate": 0.90, "cluster_size": 25, "data_label": "REPLAYED"}, "rare_events": {"units": 10_000, "base_rate": 0.82, "cluster_size": 10, "data_label": "COUNTERFACTUAL"}, "nominal": {"units": 40_000, "base_rate": 0.95, "cluster_size": 40, "data_label": "REPLAYED"},}
DEFAULT_CONFIG = { "batch_units": 2_000, "budget_units": 80_000, "alpha": 0.05, "margin_delta": 0.005, "catastrophic_delta": 0.03, "nominal_expand_factor": 2.0, "nominal_base_allowance": 8_000,}
# ------------------------------------------------------- unit simulation
def _outcome_vectors(stratum: str, cfg: Dict, effect: float, baseline_version: str, candidate_version: str, seed: int, versions: CacheKeyVersions) -> Dict: """Paired unit outcomes for one stratum, content-addressed cached.
The pairing construction mirrors seqeval.paired (shared latent + per- model flip noise) but over abstract scenario units; the cache key covers stratum, both model versions, seed and the component versions, so a version bump is a miss by construction. """ cache = get_feature_cache() key = versions.key_for( f"gauntlet|{stratum}|{baseline_version}|{candidate_version}|{seed}" f"|{cfg['units']}|{cfg['base_rate']}|{effect}", kind="gauntlet-units")
def _compute(): n = int(cfg["units"]) rng = np.random.default_rng([seed, hash(stratum) % (2 ** 31)]) u = rng.random(n) cluster_size = int(cfg["cluster_size"]) clusters = np.arange(n) // cluster_size scene = rng.normal(0.0, 0.02, size=int(np.ceil(n / cluster_size))) p_base = np.clip(cfg["base_rate"] + scene[clusters], 0.02, 0.995) p_cand = np.clip(p_base + effect, 0.02, 0.995) flip = rng.random(n) < 0.04 fresh = rng.random(n) u_base = u u_cand = np.where(flip, fresh, u) b = (u_base < p_base) c = (u_cand < p_cand) return {"baseline": b.astype(int).tolist(), "candidate": c.astype(int).tolist(), "clusters": clusters.astype(int).tolist()}
return cache.get_or_compute(key, _compute, kind="gauntlet-units")
# ------------------------------------------------------- gauntlet runner
def run_gauntlet(candidate_version: str = "candidate-v4", baseline_version: str = "baseline-v3", effects: Optional[Dict[str, float]] = None, strata: Optional[Dict[str, Dict]] = None, config: Optional[Dict] = None, seed: int = 11, versions: Optional[CacheKeyVersions] = None, persist: bool = True) -> Dict: """Run the full priority-ordered gauntlet. `effects` plants per-stratum candidate deltas (absolute points), e.g. {"safety_critical": -0.06} for a catastrophic safety regression.""" cfg = {**DEFAULT_CONFIG, **(config or {})} strata_cfg = {k: dict(v) for k, v in (strata or DEFAULT_STRATA).items()} effects = effects or {} versions = versions or CacheKeyVersions() cache = get_feature_cache() hits0, misses0 = cache.stats.hits, cache.stats.misses
run_id = f"gauntlet-{uuid4().hex[:10]}" t_start = time.perf_counter()
queue: List[str] = [s for s in PRIORITY_ORDER if s in strata_cfg] nominal_allowance = int(cfg["nominal_base_allowance"]) budget_left = int(cfg["budget_units"]) total_units = sum(int(s["units"]) for s in strata_cfg.values())
events: List[Dict] = [] stratum_results: List[Dict] = [] halted = False processed_order: List[str] = [] units_evaluated = 0
while queue and budget_left > 0 and not halted: name = queue.pop(0) scfg = strata_cfg[name] processed_order.append(name) effect = float(effects.get(name, 0.0)) vectors = _outcome_vectors(name, scfg, effect, baseline_version, candidate_version, seed, versions) b = np.asarray(vectors["baseline"], dtype=np.float64) c = np.asarray(vectors["candidate"], dtype=np.float64) clusters = np.asarray(vectors["clusters"])
limit = int(scfg["units"]) if name == "nominal": limit = min(limit, nominal_allowance) limit = min(limit, budget_left)
test = PairedSequentialTest(delta=cfg["margin_delta"], alpha=cfg["alpha"]) used = 0 decision = DECISION_INSUFFICIENT batch = int(cfg["batch_units"]) while used < limit: end = min(used + batch, limit) db = c[used:end] - b[used:end] means, _ = cluster_units(db, clusters[used:end]) test.update_clusters(means) test.record_objects(b[used:end].astype(bool), c[used:end].astype(bool)) used = end test.record_trajectory_point() # ONLY anytime-valid stopping: seqeval e-process decision. decision = test.evaluate() if decision != DECISION_INSUFFICIENT: break
budget_left -= used units_evaluated += used est = test.delta_estimate() or 0.0 snapshot = test.snapshot() stratum_results.append({ "stratum": name, "priority": PRIORITY_ORDER.index(name) + 1, "data_label": scfg.get("data_label", "SIMULATED"), "planted_effect": effect, "units_available": int(scfg["units"]), "units_evaluated": used, "units_saved_by_early_stop": max(0, limit - used), **snapshot, "trajectory": test.trajectory[-20:], })
if decision == DECISION_REGRESSION: if name == "safety_critical" and est < -cfg["catastrophic_delta"]: halted = True events.append({ "event": "CATASTROPHIC_HALT", "stratum": name, "delta_estimate": round(est, 5), "detail": f"safety-critical regression {est:+.4f} below " f"-{cfg['catastrophic_delta']}: candidate halted, " f"remaining strata not evaluated"}) else: promoted = [r for r in RELATED.get(name, []) if r in queue] for r in reversed(promoted): queue.remove(r) queue.insert(0, r) events.append({ "event": "REGRESSION_PRIORITIZE_RELATED", "stratum": name, "delta_estimate": round(est, 5), "promoted": promoted, "detail": f"high-confidence regression in {name}; related " f"strata promoted: {promoted or 'none pending'}"}) elif decision == DECISION_PASS and name == "safety_critical": nominal_allowance = int(nominal_allowance * cfg["nominal_expand_factor"]) events.append({ "event": "CRITICAL_PASS_EXPAND", "stratum": name, "detail": f"safety-critical suite passed; nominal allowance " f"expanded to {nominal_allowance} units"})
elapsed = time.perf_counter() - t_start hits = cache.stats.hits - hits0 misses = cache.stats.misses - misses0
lineage = build_lineage(candidate_version, f"gauntlet-strata-{seed}", seeds={"gauntlet": seed}, baseline_version=baseline_version) data_labels = list(dict.fromkeys( s.get("data_label", "SIMULATED") for s in strata_cfg.values()))
# Strata records for the launch recommendation (statistical verdicts come # from the seqeval snapshots; safety significance from the point deltas). from sensorflow.nextgen.regression import SAFETY_MARGINS strata_records = [] for r in stratum_results: kind = "safety" if r["stratum"] in ("safety_critical", "rare_events") else "global" strata_records.append({ "stratum": r["stratum"], "kind": kind, "delta_abs": r["delta_estimate"], "statistical": {"decision": r["decision"]}, "safety": {"significant": (r["delta_estimate"] is not None and r["delta_estimate"] < -SAFETY_MARGINS[kind]), "margin": SAFETY_MARGINS[kind]}, }) recommendation = launch_recommendation(run_id, strata_records, lineage, data_labels) if halted: recommendation.recommendation = "DO_NOT_LAUNCH" recommendation.blockers.insert( 0, "gauntlet halted: catastrophic safety-critical regression")
result = { "run_id": run_id, "candidate_version": candidate_version, "baseline_version": baseline_version, "config": cfg, "planted_effects": effects, "scale": { "total_units_defined": total_units, "units_evaluated": units_evaluated, "units_saved": total_units - units_evaluated, "budget_units": cfg["budget_units"], "budget_remaining": budget_left, }, "timing": {"wall_s": round(elapsed, 4), "units_per_second": (round(units_evaluated / elapsed) if elapsed > 0 else None)}, "cache": {"hits": hits, "misses": misses, "hit_rate": round(hits / (hits + misses), 4) if hits + misses else None}, "priority_order": PRIORITY_ORDER, "processed_order": processed_order, "halted": halted, "events": events, "strata": stratum_results, "recommendation": recommendation.model_dump(mode="json"), "statistical_validity": ( "all early stopping via seqeval anytime-valid e-processes on " "cluster means; sticky decisions; no fixed-n test is ever used " "for control flow"), "status": "halted" if halted else "completed", }
run = EvaluationRun(run_id=run_id, kind="gauntlet", status=result["status"], data_labels=[DataLabel(d) for d in data_labels], lineage=lineage, params={"effects": effects, "config": cfg, "seed": seed}, results={k: result[k] for k in ("scale", "timing", "cache", "events")}) lineage_mod.stamp_run(run) run.valid_for_launch = run.lineage_valid and not halted result["lineage"] = lineage.model_dump(mode="json") result["lineage_valid"] = run.lineage_valid
if persist: store.write_json(result, "gauntlets", f"{run_id}.json") store.write_json({"latest": run_id}, "gauntlets", "latest.json") return result
def get_gauntlet(run_id: str) -> Optional[Dict]: if run_id == "latest": pointer = store.read_json("gauntlets", "latest.json") if not pointer: return None run_id = pointer["latest"] return store.read_json("gauntlets", f"{run_id}.json")
def list_gauntlets() -> List[Dict]: out = [] for rid in store.list_json("gauntlets"): if rid == "latest": continue raw = store.read_json("gauntlets", f"{rid}.json") if raw: out.append({"run_id": raw["run_id"], "status": raw["status"], "recommendation": raw["recommendation"]["recommendation"], "units_evaluated": raw["scale"]["units_evaluated"], "wall_s": raw["timing"]["wall_s"]}) return out1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556"""JSON persistence for nextgen artifacts under runs/nextgen/.
Mirrors the conventions of sensorflow.safety.store (reused pattern ratherthan importing it: that store hard-codes runs/safety/ and offers no rootoverride, which the nextgen tests need for isolation)."""
from __future__ import annotations
import jsonimport osimport threadingfrom pathlib import Pathfrom typing import Dict, List, Optional
_ROOT = "runs/nextgen"_LOCK = threading.Lock()
def set_nextgen_root(path: str) -> None: global _ROOT _ROOT = path
def nextgen_root() -> str: return _ROOT
def _path(*parts: str) -> Path: return Path(_ROOT, *parts)
def write_json(obj: Dict, *parts: str) -> str: p = _path(*parts) with _LOCK: p.parent.mkdir(parents=True, exist_ok=True) tmp = p.with_suffix(p.suffix + ".tmp") with open(tmp, "w") as f: json.dump(obj, f, indent=1, default=str) os.replace(tmp, p) return str(p)
def read_json(*parts: str) -> Optional[Dict]: p = _path(*parts) if not p.exists(): return None with open(p) as f: return json.load(f)
def list_json(subdir: str) -> List[str]: d = _path(subdir) if not d.exists(): return [] return sorted(p.stem for p in d.glob("*.json"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454"""Counterfactual validity gate.
Before ANY generated scenario enters an evaluation suite it passes throughthis gate. Everything here is deterministic math on the scenario data —no model opinions (evidence before inference).
Checks------1. physical plausibility per-class speed limits, acceleration limits, rotated-rectangle object overlap (reuses sensorflow.safety.ssam_ext.rects_overlap)2. temporal consistency position/velocity finite-difference agreement, frame-to-frame acceleration continuity (teleports and discontinuities land here AND in #1)3. sensor consistency the bevfusion camera+LiDAR simulators are run on the rendered sequence; cross-modal position agreement and condition-conditioned detection-rate expectations must hold (e.g. at night the camera rate must sit below the LiDAR rate)4. identity/trajectory unique instance ids per frame, stable class per id, no id teleports between consecutive frames5. distribution similarity feature distributions (range, lateral offset, speed, class mix) vs a real-data reference built from untransformed source scenes; PSI/JS reuse sensorflow.rca.stats (guarded import + fallback)
Scores------simulation_fidelity_score 0.4*physical + 0.3*temporal + 0.3*sensorrealism_confidence distribution-similarity score (PSI-mapped)counterfactual_validity 0.5*fidelity + 0.2*identity + 0.3*realism
Weight policy (deterministic, tested)-------------------------------------* rejected scenarios get evaluation_weight = 0 (never enter a suite);* accepted scenarios with fidelity >= HIGH_FIDELITY get weight 1.0;* accepted low-fidelity scenarios are weight-capped at LOW_FIDELITY_WEIGHT_CAP per scenario, and `apply_suite_weight_policy` additionally caps the TOTAL low-fidelity share of a suite at LOW_FIDELITY_SUITE_SHARE so low-fidelity evidence can never dominate a launch decision."""
from __future__ import annotations
import mathfrom typing import Dict, List, Optional, Tuple
import numpy as np
from sensorflow.bevfusion.scenes import DT, SceneSequencefrom sensorflow.bevfusion.sensors import ( camera_rng, lidar_rng, simulate_camera, simulate_lidar,)# REUSE: rotated-rectangle overlap from the safety package's SSAM module.from sensorflow.safety.ssam_ext import rects_overlapfrom sensorflow.nextgen.models import ValidityReportfrom sensorflow.nextgen.worldmodel import ActorTrack
try: # REUSE (read-only): PSI / JS divergence primitives from the RCA package. from sensorflow.rca.stats import js_divergence_continuous, psi_continuous _DIVERGENCE_SOURCE = "sensorflow.rca.stats"except Exception: # pragma: no cover - rca is expected to be importable _DIVERGENCE_SOURCE = "local fallback (rca.stats unavailable)"
def _hist(a, b, bins=10, eps=1e-4): lo, hi = min(np.min(a), np.min(b)), max(np.max(a), np.max(b)) if hi <= lo: hi = lo + 1e-9 edges = np.linspace(lo, hi, bins + 1) pa, _ = np.histogram(a, bins=edges) pb, _ = np.histogram(b, bins=edges) return (pa / max(1, pa.sum()) + eps, pb / max(1, pb.sum()) + eps)
def psi_continuous(expected, actual, bins=10): # type: ignore[no-redef] pa, pb = _hist(np.asarray(expected, float), np.asarray(actual, float), bins) pa, pb = pa / pa.sum(), pb / pb.sum() return float(np.sum((pb - pa) * np.log(pb / pa)))
def js_divergence_continuous(a, b, bins=10): # type: ignore[no-redef] pa, pb = _hist(np.asarray(a, float), np.asarray(b, float), bins) pa, pb = pa / pa.sum(), pb / pb.sum() m = 0.5 * (pa + pb) return float(0.5 * np.sum(pa * np.log(pa / m)) + 0.5 * np.sum(pb * np.log(pb / m)))
# Deterministic policy constants (versioned via lineage policy_version).MAX_SPEED_MPS = {"pedestrian": 3.5, "cyclist": 12.0, "motorcycle": 50.0, "vehicle": 50.0, "truck": 40.0}MAX_ACCEL_MPS2 = 12.0 # ~1.2 g: beyond road-vehicle physicsMAX_PED_ACCEL_MPS2 = 8.0POSITION_VELOCITY_TOL_M = 0.35 # |dx - v*dt| tolerance per frameCROSS_MODAL_AGREEMENT_M = 2.0 # camera-vs-LiDAR median position agreementHIGH_FIDELITY = 0.80LOW_FIDELITY_WEIGHT_CAP = 0.30LOW_FIDELITY_SUITE_SHARE = 0.25ACCEPT_VALIDITY_MIN = 0.50
def _check(name: str, passed: bool, score: float, detail: str) -> Dict: return {"check": name, "passed": bool(passed), "score": round(float(np.clip(score, 0.0, 1.0)), 4), "detail": detail}
# ------------------------------------------------------------ 1. physical
def overlap_pairs(actors: List[ActorTrack], step: int = 4) -> set: """Pairs of actors whose rectangles intersect at any sampled frame.""" pairs = set() n_frames = len(actors[0].states) if actors else 0 for fi in range(0, n_frames, step): for i in range(len(actors)): for j in range(i + 1, len(actors)): a, b = actors[i], actors[j] key = frozenset((a.instance_id, b.instance_id)) if key in pairs: continue sa, sb = a.states[fi], b.states[fi] if abs(sa["x"] - sb["x"]) > 12 or abs(sa["y"] - sb["y"]) > 12: continue if rects_overlap((sa["x"], sa["y"]), sa["yaw"], a.dims[0], a.dims[1], (sb["x"], sb["y"]), sb["yaw"], b.dims[0], b.dims[1]): pairs.add(key) return pairs
def check_physical(actors: List[ActorTrack], ignore_overlap_pairs: Optional[set] = None) -> Tuple[Dict, List[str]]: reasons: List[str] = [] worst = 1.0 n_viol = 0 for a in actors: vmax = MAX_SPEED_MPS.get(a.class_name, 50.0) amax = MAX_PED_ACCEL_MPS2 if a.class_name == "pedestrian" else MAX_ACCEL_MPS2 speeds = np.array([math.hypot(s["vx"], s["vy"]) for s in a.states]) # Acceleration from position second differences (catches teleports # even when the stored velocity fields lie about the jump). xs = np.array([s["x"] for s in a.states]) ys = np.array([s["y"] for s in a.states]) if len(xs) >= 3: ax = np.diff(xs, 2) / DT ** 2 ay = np.diff(ys, 2) / DT ** 2 amag = np.hypot(ax, ay) else: amag = np.zeros(1) if speeds.max(initial=0.0) > vmax: n_viol += 1 worst = min(worst, vmax / max(speeds.max(), 1e-9)) reasons.append(f"{a.instance_id}: speed {speeds.max():.1f} m/s exceeds " f"{a.class_name} limit {vmax} m/s") if amag.max(initial=0.0) > amax: n_viol += 1 worst = min(worst, amax / max(amag.max(), 1e-9)) reasons.append(f"{a.instance_id}: acceleration {amag.max():.1f} m/s^2 " f"exceeds limit {amax} m/s^2")
# Pairwise overlap, EXCLUDING pairs that already intersected in the # source scene: the gate scores what the TRANSFORMATION introduced, not # pre-existing substrate quirks. new_overlaps = overlap_pairs(actors) - (ignore_overlap_pairs or set()) if new_overlaps: n_viol += len(new_overlaps) worst = min(worst, 0.2) for pair in sorted(new_overlaps, key=sorted): a_id, b_id = sorted(pair) reasons.append(f"object overlap introduced by transformation: " f"{a_id} intersects {b_id}")
passed = n_viol == 0 score = 1.0 if passed else worst * max(0.0, 1.0 - 0.2 * n_viol) return _check("physical_plausibility", passed, score, f"{n_viol} violation(s); kinematic limits + rotated-rect overlap"), reasons
# ------------------------------------------------------------ 2. temporal
def check_temporal(actors: List[ActorTrack]) -> Tuple[Dict, List[str]]: reasons: List[str] = [] worst_err = 0.0 for a in actors: xs = np.array([s["x"] for s in a.states]) ys = np.array([s["y"] for s in a.states]) vx = np.array([s["vx"] for s in a.states]) vy = np.array([s["vy"] for s in a.states]) if len(xs) < 2: continue # Stored velocity must explain the position increments. ex = np.abs(np.diff(xs) - vx[1:] * DT) ey = np.abs(np.diff(ys) - vy[1:] * DT) err = float(np.hypot(ex, ey).max()) worst_err = max(worst_err, err) if err > POSITION_VELOCITY_TOL_M: reasons.append(f"{a.instance_id}: position/velocity mismatch " f"{err:.2f} m in one frame (tol {POSITION_VELOCITY_TOL_M})") passed = worst_err <= POSITION_VELOCITY_TOL_M score = float(np.clip(1.0 - worst_err / 5.0, 0.0, 1.0)) if not passed else 1.0 return _check("temporal_consistency", passed, score, f"max |dx - v dt| = {worst_err:.3f} m"), reasons
# ------------------------------------------------------------ 3. sensor
def check_sensor(seq: SceneSequence, environment: Dict[str, str], seed: int) -> Tuple[Dict, List[str]]: """Run the REUSED bevfusion sensor simulators on the rendered sequence and check cross-modal agreement + condition-conditioned expectations.""" cam_gen, lid_gen = camera_rng(seed, 0), lidar_rng(seed, 0) agree_dists: List[float] = [] cam_hits = lid_hits = gt_total = 0 for frame in seq.frames: if not frame.gt: continue gt_total += len(frame.gt) cams = simulate_camera(frame, seq, cam_gen) lids = simulate_lidar(frame, seq, lid_gen) cam_by_iid = {d.source_instance_id: d for d in cams if d.source_instance_id} lid_by_iid = {d.source_instance_id: d for d in lids if d.source_instance_id} cam_hits += len(cam_by_iid) lid_hits += len(lid_by_iid) for iid, c in cam_by_iid.items(): l = lid_by_iid.get(iid) if l is not None: agree_dists.append(math.hypot(c.x - l.x, c.y - l.y))
reasons: List[str] = [] if gt_total == 0: return _check("sensor_consistency", False, 0.0, "no ground truth visible in rendered frames"), \ ["sensor consistency unverifiable: empty scenario"]
cam_rate = cam_hits / gt_total lid_rate = lid_hits / gt_total median_agree = float(np.median(agree_dists)) if agree_dists else None
score = 1.0 if median_agree is None: score -= 0.4 reasons.append("no object seen by both modalities; cross-modal " "agreement unverifiable") elif median_agree > CROSS_MODAL_AGREEMENT_M: score -= min(0.6, 0.3 * median_agree / CROSS_MODAL_AGREEMENT_M) reasons.append(f"camera/LiDAR median position disagreement " f"{median_agree:.2f} m > {CROSS_MODAL_AGREEMENT_M} m") if seq.time_of_day == "night" and cam_rate > lid_rate: score -= 0.3 reasons.append(f"claimed night but camera rate {cam_rate:.2f} exceeds " f"LiDAR rate {lid_rate:.2f} (inconsistent with darkness)") if seq.weather == "rain" and lid_rate > 0.98: score -= 0.15 reasons.append("claimed rain but LiDAR shows zero attenuation")
passed = score >= 0.7 detail = (f"camera rate {cam_rate:.2f}, lidar rate {lid_rate:.2f}, " f"median cross-modal agreement " f"{'n/a' if median_agree is None else f'{median_agree:.2f} m'}") return _check("sensor_consistency", passed, score, detail), reasons
# ------------------------------------------------------------ 4. identity
def check_identity(seq: SceneSequence, actors: List[ActorTrack]) -> Tuple[Dict, List[str]]: reasons: List[str] = [] class_by_id: Dict[str, str] = {} last_pos: Dict[str, Tuple[int, float, float]] = {} max_jump = 0.0 for frame in seq.frames: ids = [g.instance_id for g in frame.gt] if len(ids) != len(set(ids)): reasons.append(f"duplicate instance id in frame {frame.frame_id}") for g in frame.gt: prev_cls = class_by_id.setdefault(g.instance_id, g.class_name) if prev_cls != g.class_name: reasons.append(f"{g.instance_id}: class flip {prev_cls} -> " f"{g.class_name}") prev = last_pos.get(g.instance_id) # World-frame displacement between consecutive visible frames. wx = g.bbox_3d[0] + 10.0 * DT * frame.index if prev is not None and frame.index - prev[0] == 1: jump = math.hypot(wx - prev[1], g.bbox_3d[1] - prev[2]) max_jump = max(max_jump, jump) if jump > 6.0: # > 60 m/s implied inter-frame motion reasons.append(f"{g.instance_id}: {jump:.1f} m jump between " f"consecutive frames") last_pos[g.instance_id] = (frame.index, wx, g.bbox_3d[1]) passed = not reasons score = 1.0 if passed else max(0.0, 1.0 - 0.25 * len(reasons)) return _check("identity_trajectory_consistency", passed, score, f"max inter-frame world jump {max_jump:.2f} m"), reasons
# ------------------------------------------------------------ 5. distribution
def scene_features(seq: SceneSequence) -> Dict[str, np.ndarray]: dist, lat = [], [] for frame in seq.frames: for g in frame.gt: dist.append(g.distance) lat.append(g.bbox_3d[1]) return {"distance": np.asarray(dist, float), "lateral": np.asarray(lat, float)}
def _mean_psi_js(ref: Dict[str, np.ndarray], cur: Dict[str, np.ndarray], reasons: List[str]) -> Tuple[float, float]: psis, jss = [], [] for k in ("distance", "lateral"): if cur[k].size < 5 or ref[k].size < 5: reasons.append(f"too few observations to compare {k} distribution") continue psis.append(psi_continuous(ref[k], cur[k])) jss.append(js_divergence_continuous(ref[k], cur[k])) return (float(np.mean(psis)) if psis else 1.0, float(np.mean(jss)) if jss else 1.0)
def check_distribution(seq: SceneSequence, reference: Optional[List[SceneSequence]] = None, source_features: Optional[Dict[str, List[float]]] = None ) -> Tuple[Dict, List[str], float]: """PSI/JS of scenario feature distributions vs a real-data reference.
The reference is a pool of untransformed source scenes (the platform's stand-in for real fleet data; documented as such). Divergence primitives are reused from sensorflow.rca.stats.
A single scenario has natural sampling variance against the pooled reference, so when the SOURCE scene's features are available we score the shift ADDED by the transformation (psi_cf - psi_source): the realism question is "did the transformation push the scenario away from real data", not "is one scene a perfect sample of the fleet". """ if reference is None: from sensorflow.bevfusion.scenes import generate_sequences reference = generate_sequences(n_sequences=6, frames_per_sequence=24, seed=7)
feats = scene_features(seq) ref_feats: Dict[str, List[np.ndarray]] = {"distance": [], "lateral": []} for r in reference: rf = scene_features(r) for k in ref_feats: ref_feats[k].append(rf[k]) ref = {k: (np.concatenate(v) if v else np.zeros(1)) for k, v in ref_feats.items()}
reasons: List[str] = [] psi, js = _mean_psi_js(ref, feats, reasons)
psi_source = None if source_features: src = {k: np.asarray(source_features.get(k, []), float) for k in ("distance", "lateral")} psi_source, _ = _mean_psi_js(ref, src, []) added = max(0.0, psi - psi_source) else: added = psi
# Added-PSI -> similarity score: 0.25 ("large shift" in the standard # reading) maps to 0.5; counterfactuals legitimately shift distributions, # so this informs realism_confidence rather than hard-failing the gate. score = float(np.clip(1.0 - 2.0 * added, 0.0, 1.0)) if added > 0.25: reasons.append(f"large transformation-added distribution shift " f"(added PSI {added:.3f})") detail = (f"PSI {psi:.3f}" + (f" (source scene PSI {psi_source:.3f}, added {added:.3f})" if psi_source is not None else "") + f", JS {js:.4f} over range/lateral features " f"(source: {_DIVERGENCE_SOURCE})") check = _check("distribution_similarity", added <= 0.25, score, detail) return check, reasons, score
# ------------------------------------------------------------ gate
def validate_scenario(scenario_id: str, seq: SceneSequence, actors: List[ActorTrack], environment: Dict[str, str], seed: int, reference: Optional[List[SceneSequence]] = None, source_overlap_pairs: Optional[set] = None, source_features: Optional[Dict[str, List[float]]] = None ) -> ValidityReport: phys, r1 = check_physical(actors, ignore_overlap_pairs=source_overlap_pairs) temp, r2 = check_temporal(actors) sens, r3 = check_sensor(seq, environment, seed) ident, r4 = check_identity(seq, actors) dist, r5, realism = check_distribution(seq, reference, source_features)
fidelity = 0.4 * phys["score"] + 0.3 * temp["score"] + 0.3 * sens["score"] validity = 0.5 * fidelity + 0.2 * ident["score"] + 0.3 * realism
# Hard physical/temporal failures reject outright; otherwise threshold. accepted = phys["passed"] and temp["passed"] and validity >= ACCEPT_VALIDITY_MIN weight, capped = weight_policy(accepted, fidelity)
return ValidityReport( scenario_id=scenario_id, checks=[phys, temp, sens, ident, dist], simulation_fidelity_score=round(fidelity, 4), counterfactual_validity=round(validity, 4), realism_confidence=round(realism, 4), accepted=accepted, evaluation_weight=weight, weight_capped=capped, reasons=r1 + r2 + r3 + r4 + r5)
def weight_policy(accepted: bool, fidelity: float) -> Tuple[float, bool]: """Deterministic per-scenario weight: rejected -> 0; high fidelity -> 1; accepted low fidelity -> capped at LOW_FIDELITY_WEIGHT_CAP.""" if not accepted: return 0.0, False if fidelity >= HIGH_FIDELITY: return 1.0, False return LOW_FIDELITY_WEIGHT_CAP, True
def apply_suite_weight_policy(reports: List[ValidityReport]) -> Dict: """Suite-level cap: the total weight of low-fidelity (capped) scenarios may not exceed LOW_FIDELITY_SUITE_SHARE of the suite's total weight. Returns the final per-scenario weights (deterministic policy, tested).""" high = [r for r in reports if r.accepted and not r.weight_capped] low = [r for r in reports if r.accepted and r.weight_capped] total_high = sum(r.evaluation_weight for r in high) total_low = sum(r.evaluation_weight for r in low) weights = {r.scenario_id: (r.evaluation_weight if r.accepted else 0.0) for r in reports} scaled = False if total_low > 0 and total_high + total_low > 0: share = total_low / (total_high + total_low) if share > LOW_FIDELITY_SUITE_SHARE: # Solve for the factor that brings the low-fidelity share to cap. target = LOW_FIDELITY_SUITE_SHARE factor = (target * total_high) / ((1 - target) * total_low) for r in low: weights[r.scenario_id] = round(r.evaluation_weight * factor, 6) scaled = True final_low = sum(weights[r.scenario_id] for r in low) final_total = final_low + total_high return { "weights": weights, "low_fidelity_share": round(final_low / final_total, 4) if final_total else 0.0, "share_cap": LOW_FIDELITY_SUITE_SHARE, "scaled_down": scaled, "policy": "per-scenario cap LOW_FIDELITY_WEIGHT_CAP=" f"{LOW_FIDELITY_WEIGHT_CAP}; suite share cap " f"{LOW_FIDELITY_SUITE_SHARE}; rejected scenarios weight 0", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""World-model integration boundary for counterfactual scene generation.
The platform's counterfactual engine (counterfactual.py) needs one thing froma "world model": given a source scene and a transformation recipe, produce aphysically coherent transformed scene with full ground truth. This moduledefines that boundary as an explicit interface with exactly one liveimplementation:
* :class:`DeterministicSceneTransformer` — the internal, deterministic, physics-rule-based transformer. It operates on reconstructed world-frame actor kinematics from :mod:`sensorflow.bevfusion.scenes` sequences and is fully seeded/reproducible. This is what runs today.
* :class:`ExternalWorldModelAdapter` — a stub adapter documenting where a learned generative world model (e.g. a proprietary video/world model such as an internal WWM) would plug in. It is intentionally NOT implemented: we assume no proprietary APIs. The contract it would have to satisfy is documented on the class, and everything downstream (validity gate, closed-loop evaluation, provenance labels) is already generator-agnostic — a generated scenario from ANY implementation goes through the same validity gate before it can enter an evaluation suite.
The generative-architecture trade study (diffusion vs transformer world modelvs hybrid) lives in docs/architecture/nextgen-worldmodel-generative-comparison.mdand is served by GET /api/nextgen/architecture/docs."""
from __future__ import annotations
from abc import ABC, abstractmethodfrom dataclasses import dataclass, fieldfrom typing import Dict, List
from sensorflow.bevfusion.scenes import SceneSequencefrom sensorflow.nextgen.models import TransformationStep
@dataclassclass ActorTrack: """World-frame kinematics of one actor across the scenario horizon.
states[i] corresponds to frame i: dict with x, y, vx, vy, yaw, occluded. """
instance_id: str class_name: str dims: List[float] # l, w, h states: List[Dict] = field(default_factory=list)
@dataclassclass TransformedScene: """Output contract of a scene transformer: a renderable sequence plus the world-frame tracks it was built from (needed by validity + closed loop)."""
sequence: SceneSequence actors: List[ActorTrack] environment: Dict[str, str] # weather / time_of_day / extended tags applied: List[TransformationStep] notes: List[str] = field(default_factory=list)
class SceneTransformer(ABC): """The world-model boundary. Implementations must be pure functions of (source, recipe, seed): same inputs -> identical output."""
name: str = "abstract" version: str = "0"
@abstractmethod def transform(self, source: SceneSequence, recipe: List[TransformationStep], seed: int) -> TransformedScene: ...
class ExternalWorldModelAdapter(SceneTransformer): """Stub for a learned generative world model.
Contract an external implementation must satisfy:
1. Input: a source scene (sensor-agnostic ground-truth representation, as :class:`SceneSequence`) + a transformation recipe expressed as :class:`TransformationStep` s + a seed. 2. Output: a :class:`TransformedScene` with FULL ground truth (world-frame actor kinematics per frame) — not just rendered pixels. Without GT the result cannot be evaluated, only admired. 3. Determinism: same (source, recipe, seed) must reproduce the same output, or the run's lineage record is unreproducible and the run is INVALID for launch purposes (lineage.py). 4. Provenance: outputs are labeled GENERATED (vs COUNTERFACTUAL for rule-based transforms of a real/synthetic source) so reports can distinguish generator classes. 5. Every output still passes through the validity gate (validity.py); being expensive to generate earns no exemption from gating. """
name = "external-worldmodel-stub" version = "0 (not implemented)"
def transform(self, source: SceneSequence, recipe: List[TransformationStep], seed: int) -> TransformedScene: raise NotImplementedError( "No external world model is wired in. This adapter documents the " "integration contract; see class docstring and " "docs/architecture/nextgen-worldmodel-generative-comparison.md")2 unmodified lines345678108 unmodified lines1171181191201211221232 unmodified linesfrom __future__ import annotationsimport jsonfrom pathlib import Pathfrom typing import Dict, List, Optional, Tuple108 unmodified linespts = np.fromfile(path, dtype=np.float32)if len(pts) % 3 == 0:return pts.reshape(-1, 3)return np.random.randn(500, 3).astype(np.float32) * 2def _lift_masks_to_3d(self,2 unmodified lines3456789108 unmodified lines1181191201211221231241251261271281292 unmodified linesfrom __future__ import annotationsimport jsonimport zlibfrom pathlib import Pathfrom typing import Dict, List, Optional, Tuple108 unmodified linespts = np.fromfile(path, dtype=np.float32)if len(pts) % 3 == 0:return pts.reshape(-1, 3)# SYNTHETIC_FALLBACK: no LiDAR file available. The point cloud is# simulated, seeded deterministically from the requested path so that# repeated runs over the same input produce identical proposals.seed = zlib.crc32((path or "missing").encode("utf-8")) & 0xFFFFFFFFrng = np.random.default_rng(seed)return (rng.standard_normal((500, 3)) * 2).astype(np.float32)def _lift_masks_to_3d(self,
7 unmodified lines89101112131426 unmodified lines4142434445464748495050 unmodified lines1011021031041051067 unmodified linesfrom sensorflow.metrics.perception_3d import (bev_iou,compute_map_mar,mean_orientation_error,mean_position_error,)26 unmodified linespred_tracks: List[Dict],stages_run: Optional[List[str]] = None,) -> Dict[str, Any]:all_preds, all_gts = self._collect_boxes(sequence, pred_tracks)map_metrics = compute_map_mar(all_preds, all_gts)matched_pairs = self._match_for_errors(all_preds, all_gts)orient_err = mean_orientation_error(matched_pairs)pos_err = mean_position_error(matched_pairs)50 unmodified linesall_gts.append(gt.bbox_3d)return all_preds, all_gtsdef _match_for_errors(self,preds: List[List[float]],7 unmodified lines89101112131426 unmodified lines4142434445464748495051525354555657585950 unmodified lines1101111121131141151161171181191201211221231241251261271281291307 unmodified linesfrom sensorflow.metrics.perception_3d import (bev_iou,compute_map_mar_by_frame,mean_orientation_error,mean_position_error,)26 unmodified linespred_tracks: List[Dict],stages_run: Optional[List[str]] = None,) -> Dict[str, Any]:# Matching is scoped per frame: a prediction may only match ground# truth from the same timestamp. Pooling boxes across all frames# (the previous behavior) allowed physically impossible cross-frame# matches, inflating mAP/mAR and corrupting error statistics.preds_by_frame, gts_by_frame = self._collect_boxes_by_frame(sequence, pred_tracks)all_preds = [b for boxes in preds_by_frame.values() for b in boxes]all_gts = [b for boxes in gts_by_frame.values() for b in boxes]map_metrics = compute_map_mar_by_frame(preds_by_frame, gts_by_frame)matched_pairs = []for fid in sorted(set(preds_by_frame) | set(gts_by_frame)):matched_pairs.extend(self._match_for_errors(preds_by_frame.get(fid, []), gts_by_frame.get(fid, [])))orient_err = mean_orientation_error(matched_pairs)pos_err = mean_position_error(matched_pairs)50 unmodified linesall_gts.append(gt.bbox_3d)return all_preds, all_gtsdef _collect_boxes_by_frame(self,sequence: UnifiedSequence,pred_tracks: List[Dict],) -> Tuple[Dict[str, List[List[float]]], Dict[str, List[List[float]]]]:preds_by_frame: Dict[str, List[List[float]]] = {}gts_by_frame: Dict[str, List[List[float]]] = {}for track in pred_tracks:for fr in track.get("frames", []):preds_by_frame.setdefault(fr["frame_id"], []).append(fr["bbox_3d"])for frame in sequence.frames:for gt in frame.ground_truth:gts_by_frame.setdefault(frame.frame_id, []).append(gt.bbox_3d)return preds_by_frame, gts_by_framedef _match_for_errors(self,preds: List[List[float]],
123456789101112131415161718192021222324252627282930313233"""studio2 — the Studio 2.0 integration layer: unified control plane +deterministic release governance.
This package deliberately builds NO new evaluation math. It composes theengines that already exist:
registry.py versioned control-plane entities (models, datasets with roles + contamination guard, scenarios, policies, experiments, evaluation runs with reproducibility tuples, safety cases, release decisions) + retroactive ingest of the existing runs/ stores release_gate.py ReleaseGate.evaluate(...) -> GO/REVIEW/NO-GO composed from safety gates + seqeval verdicts + megaeval shift (+ agentic policy / nextgen closed loop when importable); GO never authorizes deployment — human approval is a separate recorded action hardware.py hardware/domain strata as first-class gate dimensions; per-combination gate matrix with insufficient-evidence reporting funnel.py unified observability funnel aggregated best-effort from the real stores (absent sources are UNAVAILABLE, never fabricated) demo.py one seeded closed-loop run stitching the real engines end-to-end api.py REST surface under /api/studio2
Landed dependencies are imported directly; in-flight packages (agentic,nextgen, hardening, retro) are imported in try/except and their absencedegrades the release decision to REVIEW with the gap named."""
from sensorflow.studio2.registry import Registry, get_registry # noqa: F401from sensorflow.studio2.release_gate import ReleaseGate # noqa: F401123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294"""REST surface for the Studio 2.0 control plane under /api/studio2."""
from __future__ import annotations
import importlibimport osfrom typing import Dict, Optional
from fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field
from sensorflow.studio2 import demo as demo_modfrom sensorflow.studio2 import funnel as funnel_modfrom sensorflow.studio2 import hardware as hw_modfrom sensorflow.studio2 import storefrom sensorflow.studio2.registry import ( DATASET_ROLES, KINDS, RoleTransitionError, get_registry, ingest_existing_stores,)from sensorflow.studio2.release_gate import ReleaseGate
router = APIRouter(prefix="/api/studio2", tags=["studio2"])
_SOFT_DEPS = ["sensorflow.agentic", "sensorflow.nextgen", "sensorflow.hardening", "sensorflow.retro"]_HARD_DEPS = ["sensorflow.safety", "sensorflow.seqeval", "sensorflow.megaeval", "sensorflow.rca", "sensorflow.raremine", "sensorflow.bevfusion", "sensorflow.vitis", "sensorflow.evaluation"]
@router.get("/status")def status(): deps = {} for mod in _HARD_DEPS + _SOFT_DEPS: try: importlib.import_module(mod) deps[mod] = "importable" except Exception as e: deps[mod] = f"unavailable ({type(e).__name__})" return {"registry_counts": get_registry().counts(), "dependencies": deps, "soft_dependencies": _SOFT_DEPS}
# ------------------------------------------------------------------ registry
@router.get("/registry/summary")def registry_summary(): return {"counts": get_registry().counts(), "kinds": list(KINDS), "dataset_roles": list(DATASET_ROLES)}
@router.post("/registry/ingest")def registry_ingest(): return ingest_existing_stores(get_registry())
@router.get("/registry/{kind}")def registry_list(kind: str): try: return {"kind": kind, "entities": get_registry().list(kind)} except KeyError as e: raise HTTPException(404, str(e))
@router.get("/registry/{kind}/{entity_id}")def registry_get(kind: str, entity_id: str): if kind not in KINDS: raise HTTPException(404, f"unknown kind {kind}") doc = get_registry().get(kind, entity_id) if doc is None: raise HTTPException(404, f"no {kind} entity {entity_id}") return doc
class DatasetCreate(BaseModel): name: str role: str lineage_parents: list = Field(default_factory=list) meta: Dict = Field(default_factory=dict) actor: str = "api"
@router.post("/registry/datasets")def dataset_create(req: DatasetCreate): try: return get_registry().register_dataset( req.name, req.role, lineage_parents=req.lineage_parents, meta=req.meta, actor=req.actor, provenance={"source_package": "studio2-api"}) except ValueError as e: raise HTTPException(400, str(e))
class RoleTransition(BaseModel): new_role: str actor: str override_reason: Optional[str] = None
@router.post("/registry/datasets/{dataset_id}/role")def dataset_role(dataset_id: str, req: RoleTransition): try: return get_registry().transition_role( dataset_id, req.new_role, req.actor, override_reason=req.override_reason) except RoleTransitionError as e: raise HTTPException(409, str(e)) except KeyError as e: raise HTTPException(404, str(e)) except ValueError as e: raise HTTPException(400, str(e))
@router.get("/audit")def audit_log(limit: int = 100): return {"events": store.read_audit(limit=limit)}
# ------------------------------------------------------------------ release
class ReleaseEvaluate(BaseModel): """Inputs may be omitted; the gate degrades to REVIEW naming the gap. When use_live_sources=true the server gathers the real latest inputs.""" safety_metrics: Optional[Dict] = None regression_results: Optional[Dict] = None distribution_shift: Optional[Dict] = None agentic_outcome: Optional[Dict] = None closed_loop: Optional[Dict] = None hardware_matrix: Optional[Dict] = None policy: Optional[Dict] = None context: Optional[Dict] = None use_live_sources: bool = False
def _gather_live_inputs(req: ReleaseEvaluate) -> ReleaseEvaluate: data = req.model_dump() try: from sensorflow.megaeval.runs import get_mega_store from sensorflow.megaeval import analysis as mega_analysis from sensorflow.safety import gates as safety_gates mega = get_mega_store() published = sorted( [r for r in mega.runs.values() if getattr(r, "status", "") == "published"], key=lambda r: getattr(r, "published_at", "") or "") if len(published) >= 2 and data["safety_metrics"] is None: cand = published[-1] data["safety_metrics"] = (safety_gates.latest_gate_result(cand.run_id) or safety_gates.evaluate_gates( mega, cand, published[-2])) if published and data["distribution_shift"] is None: data["distribution_shift"] = mega_analysis.distribution_shift( mega, published[-1]) except Exception: pass if data["regression_results"] is None: try: from sensorflow.seqeval.controller import get_seqeval_store states = get_seqeval_store().list_states() done = [s for s in states if s.get("status") == "done"] if done: s = done[0] data["regression_results"] = { "run_id": s["run_id"], "decision": s["decision"], "stopping_reason": s.get("stopping_reason"), "samples_used": s.get("budget", {}).get("samples_used"), "affected_strata": [], "regression_map": []} except Exception: pass if data["hardware_matrix"] is None: try: data["hardware_matrix"] = (hw_mod.latest_matrix() or hw_mod.gate_matrix()) except Exception: pass return ReleaseEvaluate(**data)
@router.post("/release/evaluate")def release_evaluate(req: ReleaseEvaluate): if req.use_live_sources: req = _gather_live_inputs(req) gate = ReleaseGate(get_registry(), policy=req.policy) return gate.evaluate( safety_metrics=req.safety_metrics, regression_results=req.regression_results, distribution_shift=req.distribution_shift, agentic_outcome=req.agentic_outcome, closed_loop=req.closed_loop, hardware_matrix=req.hardware_matrix, context=req.context)
@router.get("/release/decisions")def release_decisions(): return {"decisions": get_registry().list("decisions")}
@router.get("/release/decisions/{decision_id}")def release_decision(decision_id: str): doc = get_registry().get("decisions", decision_id) if doc is None: raise HTTPException(404, f"no decision {decision_id}") return doc
class Approval(BaseModel): approver: str rationale: str
@router.post("/release/decisions/{decision_id}/approve")def release_approve(decision_id: str, req: Approval): gate = ReleaseGate(get_registry()) try: return gate.approve(decision_id, req.approver, req.rationale) except KeyError as e: raise HTTPException(404, str(e)) except ValueError as e: raise HTTPException(409, str(e))
# ------------------------------------------------------------------ hardware
@router.get("/hardware/matrix")def hardware_matrix(refresh: bool = False): if not refresh: cached = hw_mod.latest_matrix() if cached: return cached try: return hw_mod.gate_matrix() except Exception as e: raise HTTPException(503, f"hardware matrix unavailable: {e}")
# ------------------------------------------------------------------ funnel
@router.get("/funnel")def funnel(): return funnel_mod.build_funnel(registry=get_registry())
# ------------------------------------------------------------------ demo
class DemoRequest(BaseModel): seed: int = demo_mod.DEMO_SEED
@router.post("/demo/run")def demo_run(req: DemoRequest): return demo_mod.run_demo(seed=req.seed, registry=get_registry())
@router.get("/demo/latest")def demo_latest(): doc = demo_mod.latest_demo() if doc is None: raise HTTPException(404, "no demo run yet; POST /api/studio2/demo/run") return doc
# ------------------------------------------------------------------ docs
_DOCS_DIR = os.path.join("docs", "architecture")
@router.get("/docs")def docs_list(): if not os.path.isdir(_DOCS_DIR): return {"docs": []} return {"docs": [n for n in sorted(os.listdir(_DOCS_DIR)) if n.startswith("studio2-") and n.endswith(".md")]}
@router.get("/docs/{name}")def docs_get(name: str): if not (name.startswith("studio2-") and name.endswith(".md") and "/" not in name and ".." not in name): raise HTTPException(404, "unknown document") path = os.path.join(_DOCS_DIR, name) if not os.path.exists(path): raise HTTPException(404, f"no document {name}") with open(path) as f: return {"name": name, "content": f.read()}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274"""Closed-loop demo: one seeded scenario moves through the whole system.
Stitches the REAL engines end-to-end:
1. bevfusion scenario suite (deterministic multi-sensor scenes) 2. baseline vs candidate perception comparison (bevfusion engines) 3. seqeval anytime-valid regression verdict (with a planted night-stratum regression so governance has something to catch) 4. nextgen counterfactual + closed-loop causal replay (when importable) 5. safety layered gates + evidence package (reusing the latest published megaeval candidate/baseline runs) 6. megaeval distribution-shift report 7. studio2 ReleaseGate composition -> ReleaseDecision with the evidence tuple 8. flywheel step: the failure is registered as a REGRESSION-role dataset (protected by the contamination guard)
Every step records availability; steps whose engine/store is absent areskipped with the reason, and the release gate degrades accordingly (that ISthe demo of graceful degradation). Deterministic for a fixed seed."""
from __future__ import annotations
import osfrom typing import Dict, Optional
from sensorflow.studio2 import storefrom sensorflow.studio2.registry import Registry, content_hash, get_registryfrom sensorflow.studio2.release_gate import ReleaseGatefrom sensorflow.studio2 import hardware as hw_mod
DEMO_SEED = 977
def _step(name: str, available: bool, detail: Dict) -> Dict: return {"step": name, "available": available, **detail}
def run_demo(seed: int = DEMO_SEED, registry: Optional[Registry] = None, repo_root: str = ".", persist: bool = True) -> Dict: registry = registry or get_registry() steps = []
# ---- 1+2. scenario + perception comparison (bevfusion, landed) -------- scenario_entity = None perception = None try: from sensorflow.bevfusion.evaluate import run_comparison report = run_comparison(n_sequences=3, frames_per_sequence=16, seed=seed, persist=persist) params = report["params"] scenario_entity = registry.register_scenario( name=f"demo-suite-seed{seed}", generator="bevfusion.scenes.generate_sequences", seed=seed, recipe=params, provenance={"source_package": "bevfusion", "run_id": report["run_id"]}) dataset_entity = registry.register_dataset( name=f"demo-scenes-seed{seed}", role="TEST", provenance={"source_package": "bevfusion", "generator_seed": seed}) model_entity = registry.register_model( name=report["engines"]["candidate"], version=report["engines"]["candidate"], provenance={"source_package": "bevfusion"}) baseline_entity = registry.register_model( name=report["engines"]["baseline"], version=report["engines"]["baseline"], provenance={"source_package": "bevfusion"}) experiment = registry.register_experiment( name=f"studio2-demo-seed{seed}", candidate_model_id=model_entity["entity_id"], baseline_model_id=baseline_entity["entity_id"]) gate_policy_entity = registry.register_policy( name="studio2-demo-run-config", doc={"n_sequences": 3, "frames_per_sequence": 16, "seed": seed}) run_entity = registry.register_run( name=f"demo-bev-{report['run_id']}", engine="bevfusion", experiment_id=experiment["entity_id"], tuple_components={ "model_version_id": model_entity["entity_id"], "dataset_version_id": dataset_entity["entity_id"], "scenario_version_id": scenario_entity["entity_id"], "config_hash": content_hash(params, exclude=()), # bevfusion sensor models are pinned in code; version the pin "calibration_version": "bevfusion-sensors-v1", "seed": seed, "policy_version_id": gate_policy_entity["entity_id"], }, results={"recommendation": report["recommendation"], "headline_deltas": report["headline_deltas"]}, provenance={"source_package": "bevfusion", "run_id": report["run_id"]}) perception = report steps.append(_step("scenario_and_perception", True, { "bevfusion_run_id": report["run_id"], "scenario_version": scenario_entity["entity_id"], "evaluation_run": run_entity["entity_id"], "reproducibility": run_entity["reproducibility"], "recommendation": report["recommendation"]})) except Exception as e: steps.append(_step("scenario_and_perception", False, {"reason": f"{type(e).__name__}: {e}"}))
# ---- 3. seqeval verdict (landed; needs a megaeval population) --------- seq_verdict = None try: pop_dir = os.path.join(repo_root, "runs", "megaeval", "populations") pops = sorted(os.listdir(pop_dir)) if os.path.isdir(pop_dir) else [] if not pops: raise RuntimeError("no megaeval population available") from sensorflow.seqeval import evaluate_regression # planted regression in the pedestrian|night stratum: the point of # the demo is to show governance catching a real per-stratum failure planted = {"pedestrian|night": -0.05} seq_verdict = evaluate_regression( pops[-1], baseline={"model_version": "demo-baseline"}, candidate={"model_version": "demo-candidate", "effects": planted}, seed=seed) steps.append(_step("sequential_regression", True, { "seqeval_run_id": seq_verdict["run_id"], "decision": seq_verdict["decision"], "affected_strata": seq_verdict["affected_strata"], "samples_used": seq_verdict["samples_used"], "planted_effect": planted})) except Exception as e: steps.append(_step("sequential_regression", False, {"reason": f"{type(e).__name__}: {e}"}))
# ---- 4. nextgen counterfactual + closed loop (in-flight, guarded) ----- closed_loop = None try: from sensorflow.nextgen.causal import causal_replay from sensorflow.nextgen.closedloop import demo_emergence_scenario from sensorflow.nextgen.models import DataLabel scn = demo_emergence_scenario() result = causal_replay(scn["actors"], scn["environment"], scn["scenario_id"], DataLabel.COUNTERFACTUAL, seed=seed) closed_loop = {"scenario_id": result.scenario_id, "verdict": result.verdict, "diffs": result.diffs} steps.append(_step("closed_loop_replay", True, { "scenario_id": result.scenario_id, "verdict": result.verdict})) except Exception as e: steps.append(_step("closed_loop_replay", False, {"reason": f"nextgen unavailable or failed: " f"{type(e).__name__}: {e}"}))
# ---- 5+6. safety gates + shift on the latest published megaeval runs -- safety_result = None shift_report = None try: from sensorflow.megaeval.runs import get_mega_store from sensorflow.megaeval import analysis as mega_analysis from sensorflow.safety import gates as safety_gates mega = get_mega_store() published = sorted( [r for r in mega.runs.values() if getattr(r, "status", "") == "published"], key=lambda r: getattr(r, "published_at", "") or "") if len(published) < 2: raise RuntimeError("fewer than two published megaeval runs") candidate, baseline = published[-1], published[-2] cached = safety_gates.latest_gate_result(candidate.run_id) safety_result = cached or safety_gates.evaluate_gates( mega, candidate, baseline) shift_report = mega_analysis.distribution_shift(mega, candidate) steps.append(_step("safety_gates_and_shift", True, { "candidate_run_id": candidate.run_id, "baseline_run_id": baseline.run_id, "safety_decision": safety_result["decision"], "blocking_gates": safety_result["blocking_gates"], "shifts_reported": len(shift_report.get("shifts") or []), "reused_cached_gate_result": bool(cached)})) except Exception as e: steps.append(_step("safety_gates_and_shift", False, {"reason": f"{type(e).__name__}: {e}"}))
# ---- hardware matrix (studio2, best-effort) ---------------------------- hardware_matrix = None try: hardware_matrix = hw_mod.gate_matrix(persist=persist) steps.append(_step("hardware_matrix", True, { "status": hardware_matrix["status"], "n_combinations": hardware_matrix["n_combinations"], "n_insufficient": hardware_matrix["n_insufficient"]})) except Exception as e: steps.append(_step("hardware_matrix", False, {"reason": f"{type(e).__name__}: {e}"}))
# ---- agentic policy outcome (in-flight, guarded) ----------------------- agentic_outcome = None try: from sensorflow.agentic.policy import PolicyInput, evaluate as agentic_eval night_regressed = bool(seq_verdict and any( "night" in str(s) for s in (seq_verdict.get("affected_strata") or []))) agentic_outcome = agentic_eval(PolicyInput( failure_id=f"demo-failure-seed{seed}", safety_critical_class=False, behavioral_evidence="uncertain", significant=night_regressed, novelty="known_regression" if night_regressed else "unknown", evidence_confidence="CONFIRMED" if night_regressed else "LIKELY", concentration_dimension="lighting", concentrated=night_regressed)) steps.append(_step("agentic_policy", True, { "outcome": agentic_outcome["outcome"], "severity": agentic_outcome["severity"], "policy_version": agentic_outcome["policy_version"]})) except Exception as e: steps.append(_step("agentic_policy", False, {"reason": f"agentic unavailable or failed: " f"{type(e).__name__}: {e}"}))
# ---- 7. release decision ---------------------------------------------- gate = ReleaseGate(registry) decision = gate.evaluate( safety_metrics=safety_result, regression_results=seq_verdict, distribution_shift=shift_report, agentic_outcome=agentic_outcome, closed_loop=closed_loop, hardware_matrix=hardware_matrix, context={"demo_seed": seed, "scenario_version": (scenario_entity or {}).get("entity_id"), "perception_run": (perception or {}).get("run_id")}) steps.append(_step("release_decision", True, { "decision_id": decision["entity_id"], "status": decision["status"], "blocking_conditions": decision["blocking_conditions"], "degraded_inputs": decision["degraded_inputs"], "evidence_completeness": decision["evidence_completeness"]}))
# ---- 8. flywheel: failure -> REGRESSION-role dataset ------------------- regression_dataset = None if decision["status"] in ("NO_GO", "REVIEW"): parents = [p for p in [ (scenario_entity or {}).get("entity_id"), (seq_verdict or {}).get("run_id"), decision["entity_id"]] if p] regression_dataset = registry.register_dataset( name=f"demo-regression-suite-seed{seed}", role="REGRESSION", lineage_parents=parents, provenance={"source": "studio2.demo", "release_decision": decision["entity_id"], "seqeval_run": (seq_verdict or {}).get("run_id")}, meta={"affected_strata": (seq_verdict or {}).get("affected_strata"), "note": "failure registered for perpetual re-evaluation; " "protected from training by the contamination guard"}) steps.append(_step("flywheel_registration", True, { "dataset_id": regression_dataset["entity_id"], "role": regression_dataset["role"], "protected_evaluation": regression_dataset["protected_evaluation"]})) else: steps.append(_step("flywheel_registration", False, {"reason": "decision was GO; nothing to register"}))
demo = { "demo_id": f"demo-{content_hash({'seed': seed}, exclude=())}", "seed": seed, "steps": steps, "decision": decision, "regression_dataset": regression_dataset, "generated_at": store.now_iso(), } if persist: store.write_json(demo, "demo", f"{demo['demo_id']}.json") store.write_json(demo, "demo", "latest.json") return demo
def latest_demo() -> Optional[Dict]: return store.read_json("demo", "latest.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363"""Unified observability funnel over the real stores.
One view of the whole system: the evaluation funnel (raw → selected →simulated → evaluated → failed → HITL → regression suite), the safety panel(SCR, VRU miss rate, TTC distribution), model comparison, drift, and compute.
Everything is aggregated best-effort per source package with an availabilityflag. Absent sources report available=False with the reason — numbers areNEVER fabricated. Reads go through the packages' persisted stores (plainJSON/filesystem) so an unimportable in-flight package does not break thefunnel for the landed ones."""
from __future__ import annotations
import jsonimport osfrom typing import Dict, List, Optional
from sensorflow.studio2 import storefrom sensorflow.studio2.registry import Registry, get_registry
def _panel(available: bool, source: str, data: Optional[Dict] = None, reason: str = "") -> Dict: out = {"available": available, "source": source} if available: out["data"] = data or {} else: out["status"] = "UNAVAILABLE" out["reason"] = reason return out
def _safe_json(path: str): try: with open(path) as f: return json.load(f) except Exception: return None
def _mega_states(repo_root: str) -> List[Dict]: base = os.path.join(repo_root, "runs", "megaeval", "runs") out = [] if os.path.isdir(base): for rid in sorted(os.listdir(base)): d = _safe_json(os.path.join(base, rid, "run.json")) state = (d or {}).get("state") if state: out.append(state) return out
# ------------------------------------------------------------------ stages
def _stage_raw(repo_root: str) -> Dict: base = os.path.join(repo_root, "runs", "megaeval", "populations") total, pops = 0, 0 if os.path.isdir(base): for pid in os.listdir(base): meta = _safe_json(os.path.join(base, pid, "meta.json")) if meta: pops += 1 total += int(meta.get("num_objects") or 0) if pops == 0: return _panel(False, "megaeval.populations", reason="no populations built") return _panel(True, "megaeval.populations", {"populations": pops, "objects": total})
def _stage_selected(repo_root: str) -> Dict: base = os.path.join(repo_root, "runs", "seqeval", "runs") allocated, runs = 0, 0 if os.path.isdir(base): for rid in sorted(os.listdir(base)): st = _safe_json(os.path.join(base, rid, "run.json")) if not st: continue plan = st.get("plan") or {} if plan.get("total_allocated"): runs += 1 allocated += int(plan["total_allocated"]) if runs == 0: return _panel(False, "seqeval.plans", reason="no sequential plans frozen") return _panel(True, "seqeval.plans", {"plans": runs, "objects_allocated": allocated})
def _stage_simulated(repo_root: str) -> Dict: # nextgen counterfactual scenarios (in-flight package; read its store) candidates = [os.path.join(repo_root, "runs", "nextgen", "counterfactuals"), os.path.join(repo_root, "runs", "nextgen", "scenarios")] n = 0 found_dir = None for base in candidates: if os.path.isdir(base): found_dir = base n += sum(1 for f in os.listdir(base) if f.endswith(".json")) if found_dir is None: try: from sensorflow.nextgen import counterfactual as cf n = len(cf.list_scenarios()) found_dir = "nextgen.counterfactual.list_scenarios" except Exception: return _panel(False, "nextgen.counterfactuals", reason="nextgen counterfactual store absent " "(in-flight package)") return _panel(True, str(found_dir), {"counterfactual_scenarios": n})
def _stage_evaluated(repo_root: str) -> Dict: states = _mega_states(repo_root) published = [s for s in states if s.get("status") == "published"] if not published: return _panel(False, "megaeval.runs", reason="no published evaluation runs") return _panel(True, "megaeval.runs", { "runs": len(published), "objects_evaluated": sum(int(s.get("objects_processed") or 0) for s in published)})
def _stage_failed(repo_root: str) -> Dict: states = _mega_states(repo_root) published = [s for s in states if s.get("status") == "published"] fp = sum(int((s.get("headline") or {}).get("fp") or 0) for s in published) fn = sum(int((s.get("headline") or {}).get("fn") or 0) for s in published) agentic_dir = os.path.join(repo_root, "runs", "agentic", "failures") agentic_failures = (len([f for f in os.listdir(agentic_dir) if f.endswith(".json")]) if os.path.isdir(agentic_dir) else None) if not published and agentic_failures is None: return _panel(False, "megaeval.errors + agentic.failures", reason="no evaluation errors recorded") return _panel(True, "megaeval.errors + agentic.failures", {"false_positives": fp, "false_negatives": fn, "agentic_failure_events": agentic_failures})
def _stage_hitl(repo_root: str) -> Dict: try: from sensorflow.evaluation.records import get_store st = get_store() tasks = st.all("review_tasks") reviews = st.all("human_reviews") return _panel(True, "evaluation.review_queue", {"review_tasks": len(tasks), "completed_reviews": len(reviews), "open_tasks": sum(1 for t in tasks if getattr(t, "status", "") not in ("resolved", "completed"))}) except Exception as e: return _panel(False, "evaluation.review_queue", reason=f"labeleval store unavailable: {type(e).__name__}")
def _stage_regression(repo_root: str, registry: Registry) -> Dict: suites_dir = os.path.join(repo_root, "runs", "agentic", "suites") suites = (len([f for f in os.listdir(suites_dir) if f.endswith(".json")]) if os.path.isdir(suites_dir) else 0) reg_datasets = [d for d in registry.list("datasets") if d.get("role") == "REGRESSION"] if suites == 0 and not reg_datasets: return _panel(False, "agentic.suites + studio2.registry", reason="no regression suites registered yet") return _panel(True, "agentic.suites + studio2.registry", {"agentic_evaluation_suites": suites, "regression_role_datasets": len(reg_datasets)})
# ------------------------------------------------------------------ panels
def _safety_panel(repo_root: str) -> Dict: data: Dict = {} sources: List[str] = []
# SCR / risk-weighted metrics need a nextgen safety report (in-flight) try: from sensorflow.nextgen.safety_metrics import divergence_demo rep = divergence_demo() base = ((rep.get("baseline") or {}).get("safety_informed") or {}) cand = ((rep.get("candidate") or {}).get("safety_informed") or {}) data["scr"] = { "safety_critical_recall": { "baseline": base.get("safety_critical_recall"), "candidate": cand.get("safety_critical_recall")}, "risk_weighted_recall": { "baseline": base.get("risk_weighted_recall"), "candidate": cand.get("risk_weighted_recall")}, "deltas": rep.get("deltas"), "note": "nextgen safety-region analysis (deterministic demo scene, " "data_label SIMULATED)"} sources.append("nextgen.safety_metrics") except Exception: data["scr"] = {"status": "UNAVAILABLE", "reason": "nextgen safety metrics not importable (in-flight)"}
# VRU miss rate from the real megaeval per-class recall states = [s for s in _mega_states(repo_root) if s.get("status") == "published"] if states: latest = max(states, key=lambda s: s.get("published_at") or "") vru = {} for cls in ("pedestrian", "cyclist"): pc = (latest.get("per_class") or {}).get(cls) or {} if pc.get("recall") is not None: vru[cls] = {"miss_rate": round(1.0 - pc["recall"], 4), "n": pc.get("n")} if vru: data["vru_miss_rate"] = {"run_id": latest.get("run_id"), **vru} sources.append("megaeval.per_class") if "vru_miss_rate" not in data: data["vru_miss_rate"] = {"status": "UNAVAILABLE", "reason": "no published megaeval run with per-class stats"}
# TTC distribution from the safety SSAM store ssam_dir = os.path.join(repo_root, "runs", "safety", "ssam") ttcs: List[float] = [] if os.path.isdir(ssam_dir): for name in os.listdir(ssam_dir): doc = _safe_json(os.path.join(ssam_dir, name)) if not doc: continue for sc in doc.get("scenarios") or []: v = sc.get("min_ttc_s") if isinstance(v, (int, float)): ttcs.append(float(v)) if ttcs: ttcs.sort() data["ttc"] = {"n_scenarios": len(ttcs), "min": round(ttcs[0], 3), "p50": round(ttcs[len(ttcs) // 2], 3), "max": round(ttcs[-1], 3), "values": ttcs[:50]} sources.append("safety.ssam") else: data["ttc"] = {"status": "UNAVAILABLE", "reason": "no SSAM analyses persisted under runs/safety/ssam"}
available = any(k for k in ("scr", "vru_miss_rate", "ttc") if "status" not in data[k]) return _panel(available, " + ".join(sources) or "safety sources", data, reason="no safety metric source available")
def _comparison_panel(repo_root: str) -> Dict: bev = _safe_json(os.path.join(repo_root, "runs", "bevfusion", "latest.json")) if bev: return _panel(True, "bevfusion.latest", { "baseline": (bev.get("engines") or {}).get("baseline"), "candidate": (bev.get("engines") or {}).get("candidate"), "headline_deltas": bev.get("headline_deltas"), "recommendation": bev.get("recommendation"), "blockers": bev.get("blockers")}) states = [s for s in _mega_states(repo_root) if s.get("status") == "published"] if len(states) >= 2: states.sort(key=lambda s: s.get("published_at") or "") b, c = states[-2], states[-1] deltas = [] for m in ("precision", "recall", "safety_recall", "mean_iou"): bv, cv = (b.get("headline") or {}).get(m), (c.get("headline") or {}).get(m) if bv is not None and cv is not None: deltas.append({"metric": m, "baseline": round(bv, 4), "candidate": round(cv, 4), "delta": round(cv - bv, 4)}) return _panel(True, "megaeval.headlines", {"baseline": b.get("model_version"), "candidate": c.get("model_version"), "headline_deltas": deltas}) return _panel(False, "bevfusion + megaeval", reason="fewer than two comparable runs")
def _drift_panel(repo_root: str) -> Dict: base = os.path.join(repo_root, "runs", "megaeval", "runs") if os.path.isdir(base): for rid in sorted(os.listdir(base), reverse=True): shift = _safe_json(os.path.join(base, rid, "shift.json")) if shift: worst = (shift.get("shifts") or [])[:5] return _panel(True, f"megaeval.shift ({rid})", {"run_id": rid, "method": shift.get("method"), "worst_shifts": worst, "n_shifts": len(shift.get("shifts") or [])}) return _panel(False, "megaeval.shift", reason="no cached distribution-shift report; run " "megaeval distribution_shift for a published run")
def _compute_panel(repo_root: str) -> Dict: data: Dict = {} sources: List[str] = [] comp = _safe_json(os.path.join(repo_root, "runs", "nextgen", "compute", "latest.json")) if comp: data["dedup"] = {k: comp.get(k) for k in ("cache_hit_rate", "hit_rate", "saved_units", "baseline_units", "dedup_units", "speedup") if comp.get(k) is not None} or comp sources.append("nextgen.compute") try: from sensorflow.nextgen.cache import get_feature_cache stats = get_feature_cache().stats data["feature_cache"] = {"hits": stats.hits, "misses": stats.misses, "hit_rate": round(stats.hits / max(1, stats.hits + stats.misses), 4)} sources.append("nextgen.cache") except Exception: pass gaunt = _safe_json(os.path.join(repo_root, "runs", "nextgen", "gauntlets", "latest.json")) if gaunt: elapsed = gaunt.get("elapsed_s") or gaunt.get("wall_s") units = gaunt.get("units_evaluated") or gaunt.get("samples_used") data["gauntlet"] = {"run_id": gaunt.get("run_id"), "units_evaluated": units, "elapsed_s": elapsed, "scenarios_per_sec": (round(units / elapsed, 2) if units and elapsed else None), "halted": gaunt.get("halted")} sources.append("nextgen.gauntlets") # megaeval throughput is always real when runs exist states = [s for s in _mega_states(repo_root) if s.get("status") == "published"] if states: latest = max(states, key=lambda s: s.get("published_at") or "") data["megaeval_throughput"] = { "run_id": latest.get("run_id"), "objects_per_sec": latest.get("throughput_objs_per_s")} sources.append("megaeval.runs") if not data: return _panel(False, "nextgen + megaeval", reason="no compute telemetry persisted") return _panel(True, " + ".join(sources), data)
# ------------------------------------------------------------------ assembly
def build_funnel(repo_root: str = ".", registry: Optional[Registry] = None) -> Dict: registry = registry or get_registry() stages = [ {"stage": "raw", "label": "Raw population objects", **_stage_raw(repo_root)}, {"stage": "selected", "label": "Selected for evaluation (frozen plans)", **_stage_selected(repo_root)}, {"stage": "simulated", "label": "Counterfactual / simulated scenarios", **_stage_simulated(repo_root)}, {"stage": "evaluated", "label": "Objects evaluated", **_stage_evaluated(repo_root)}, {"stage": "failed", "label": "Failures detected", **_stage_failed(repo_root)}, {"stage": "hitl", "label": "Human-in-the-loop review", **_stage_hitl(repo_root)}, {"stage": "regression", "label": "Regression suite entries", **_stage_regression(repo_root, registry)}, ] funnel = { "generated_at": store.now_iso(), "stages": stages, "safety": _safety_panel(repo_root), "model_comparison": _comparison_panel(repo_root), "drift": _drift_panel(repo_root), "compute": _compute_panel(repo_root), "availability": {s["stage"]: s["available"] for s in stages}, } return funnel123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331"""Hardware/domain dimensions as first-class gate strata.
A release that passes globally can still be unshippable on one platform inone city with one sensor generation. This module builds a gate matrix whoserows are combinations of:
compute_platform real device configs from sensorflow.vitis.backend (KNOWN_DEVICES) + the reference CPU harness sensor_config the megaeval 'sensor' cube dimension (lidar/camera/fused) sensor_generation config-mapped generation label per sensor_config calibration_version latest sensorflow.safety.calibration status firmware config-mapped per compute_platform region domain stratum proxied from the megaeval 'road_type' cube dimension (the derivation is recorded per row)
Metrics per combination come from REAL per-cohort data (megaeval metric cubeof the latest published run). Platform-specific evidence exists only where avitis HIL run exists for that device; combinations without evidence arereported INSUFFICIENT — never assumed passing.
evaluate_matrix() is a pure function of (rows, policy) so the gate logic istestable on planted inputs, separate from data synthesis.
Minimum-evidence math is delegated to hardening/seqeval power utilities whenimportable; the fallback is a Wilson-interval width bound."""
from __future__ import annotations
import mathimport osfrom typing import Dict, List, Optional
from sensorflow.studio2 import storefrom sensorflow.studio2.registry import content_hash
# ------------------------------------------------------------------ policy
DEFAULT_HARDWARE_POLICY: Dict = { "policy_name": "studio2-hardware-v1", "metrics": { "recall": {"min": 0.80}, "precision": {"min": 0.90}, }, # evidence adequacy: a combination needs enough support that a Wilson CI # on its pass proportion is narrower than this (min-n delegated to # hardening/seqeval when importable) "max_ci_width": 0.10, # combinations matching any of these dicts are launch-critical: a failure # there blocks even when the global aggregate passes "critical_combinations": [ {"region": "san_francisco", "sensor_config": "lidar"}, {"sensor_config": "fused"}, ],}
# region strata proxied from the megaeval road_type dimension; the mapping is# reported on every row so nobody mistakes it for geo-tagged dataREGION_PROFILES = { "san_francisco": {"road_type": "urban"}, "phoenix": {"road_type": "highway"}, "rural_pilot": {"road_type": "rural"},}
SENSOR_GENERATIONS = {"lidar": "LiDAR-Gen2", "camera": "Camera-Gen3", "fused": "Fusion-Stack-v1"}
FIRMWARE = {"cpu-reference": "host-fp32", "versal-ai-edge": "vitis-2024.2", "zynq-ultrascale": "vitis-2024.2"}
# ------------------------------------------------------------------ min-n
def min_support(max_ci_width: float, p: float = 0.85) -> Dict: """Minimum per-combination sample size for adequate evidence.
Delegates to hardening.power when that package is importable (n to detect a proportion drop of max_ci_width/2 below the threshold, one-sided); otherwise a Wilson/normal-approximation bound: the CI full width at proportion p is ~ 2*z*sqrt(p(1-p)/n). """ try: from sensorflow.hardening import power as hardening_power # type: ignore n = int(hardening_power.required_n_two_proportions( baseline_rate=p, mde=max_ci_width / 2.0, two_sided=False)) return {"n": n, "method": "hardening.power.required_n_two_proportions " f"(one-sided, p={p}, mde={max_ci_width / 2.0})"} except Exception: pass z = 1.959964 # 95% n = math.ceil((2.0 * z / max_ci_width) ** 2 * p * (1.0 - p)) return {"n": int(n), "method": "wilson/normal-approx fallback " f"(z=1.96, p={p}, full width<={max_ci_width})"}
# ------------------------------------------------------------------ synthesis
def _latest_published_mega_run(): """Returns (mega_store, run_object) for the newest published run.""" from sensorflow.megaeval.runs import get_mega_store store_ = get_mega_store() published = [r for r in store_.runs.values() if getattr(r, "status", None) == "published"] if not published: raise RuntimeError("no published megaeval runs") published.sort(key=lambda r: getattr(r, "published_at", None) or getattr(r, "created_at", "") or "") return store_, published[-1]
def _cohort_metrics(mega_store, run_id: str, sensor: str, road_type: str) -> Optional[Dict]: from sensorflow.megaeval import cube as cube_mod cube_df = mega_store.artifacts(run_id)["cube"] rows, _ = cube_mod.aggregate(cube_df, {"sensor": [sensor], "road_type": [road_type]}, None, ["n", "recall", "precision"], 1) return rows[0] if rows else None
def _vitis_platforms() -> Dict[str, Dict]: """Real device configs + whether any HIL evidence exists for them.""" platforms: Dict[str, Dict] = { "cpu-reference": {"description": "reference CPU harness (fp32)", "hil_evidence": True, "evidence_note": "metrics measured directly on this harness"}} try: from sensorflow.vitis.backend import KNOWN_DEVICES hil_dir = os.path.join("runs", "vitis", "hil") has_hil = os.path.isdir(hil_dir) and any( n.startswith(("hilrun-", "hilsweep-")) for n in os.listdir(hil_dir)) for name, spec in KNOWN_DEVICES.items(): platforms[name] = { "description": spec.get("description", name), "hil_evidence": bool(has_hil), "evidence_note": ("vitis HIL quantization-gap runs present" if has_hil else "no vitis HIL run for this device"), } except Exception: pass return platforms
def synthesize_combinations() -> Dict: """Build combination rows from the real stores. Raises RuntimeError when the megaeval store has no published run (callers surface that as an unavailable matrix, they do not invent one).""" mega_store, run = _latest_published_mega_run() run_id = run.run_id calibration = None try: from sensorflow.safety import calibration as calib_mod cal = calib_mod.latest_status() calibration = (cal or {}).get("status") except Exception: pass calibration_version = f"calib-{(calibration or 'UNKNOWN').lower()}"
platforms = _vitis_platforms() sensors = ["lidar", "camera", "fused"]
rows: List[Dict] = [] for platform, pinfo in platforms.items(): for sensor in sensors: for region, proxy in REGION_PROFILES.items(): combo = { "compute_platform": platform, "sensor_config": sensor, "sensor_generation": SENSOR_GENERATIONS.get(sensor, "unknown"), "calibration_version": calibration_version, "firmware": FIRMWARE.get(platform, "unknown"), "region": region, } row: Dict = { "combination": combo, "combination_label": f"{region} × {platform} × " f"{SENSOR_GENERATIONS.get(sensor, sensor)}", "derivation": { "metrics_source": f"megaeval cube of run {run_id}, " f"filter sensor={sensor}, " f"road_type={proxy['road_type']} " f"(region proxied from road_type)", "platform_evidence": pinfo["evidence_note"], }, } if not pinfo["hil_evidence"]: row.update({"metrics": None, "n": 0, "evidence": "MISSING", "evidence_reason": pinfo["evidence_note"]}) else: m = _cohort_metrics(mega_store, run_id, sensor, proxy["road_type"]) if m is None: row.update({"metrics": None, "n": 0, "evidence": "MISSING", "evidence_reason": "no cube cells for this cohort"}) else: row.update({"metrics": {"recall": m.get("recall"), "precision": m.get("precision")}, "n": int(m.get("n") or 0), "evidence": "PRESENT"}) rows.append(row)
# global aggregate for the "global pass but critical combo fails" check headline = getattr(run, "headline", None) or {} global_metrics = {"recall": headline.get("recall"), "precision": headline.get("precision")} return {"rows": rows, "global_metrics": global_metrics, "source_run_id": run_id}
# ------------------------------------------------------------------ evaluation
def _check_metrics(metrics: Optional[Dict], thresholds: Dict) -> List[str]: failed = [] for metric, spec in thresholds.items(): val = (metrics or {}).get(metric) if val is None: failed.append(f"{metric} missing") elif "min" in spec and val < spec["min"]: failed.append(f"{metric} {val:.3f} < {spec['min']}") elif "max" in spec and val > spec["max"]: failed.append(f"{metric} {val:.3f} > {spec['max']}") return failed
def _matches(combo: Dict, pattern: Dict) -> bool: return all(combo.get(k) == v for k, v in pattern.items())
def evaluate_matrix(rows: List[Dict], policy: Optional[Dict] = None, global_metrics: Optional[Dict] = None, source_run_id: Optional[str] = None, persist: bool = True) -> Dict: """Pure gate logic over combination rows.
Each row: {combination: {...}, combination_label, metrics|None, n, evidence: PRESENT|MISSING, [evidence_reason]}. """ pol = {**DEFAULT_HARDWARE_POLICY, **(policy or {})} support = min_support(pol["max_ci_width"]) thresholds = pol["metrics"]
evaluated: List[Dict] = [] insufficient: List[Dict] = [] failures: List[Dict] = [] critical_failures: List[Dict] = []
for row in rows: out = dict(row) critical = any(_matches(row["combination"], pat) for pat in pol["critical_combinations"]) out["critical"] = critical if row.get("evidence") != "PRESENT" or row.get("metrics") is None: out["status"] = "INSUFFICIENT" out["reason"] = row.get("evidence_reason") or "no evidence" insufficient.append(out) elif int(row.get("n") or 0) < support["n"]: out["status"] = "INSUFFICIENT" out["reason"] = (f"support n={row.get('n')} below minimum " f"{support['n']} ({support['method']})") insufficient.append(out) else: failed = _check_metrics(row["metrics"], thresholds) if failed: out["status"] = "FAIL" out["failed_checks"] = failed failures.append(out) if critical: critical_failures.append(out) else: out["status"] = "PASS" evaluated.append(out)
global_failed = _check_metrics(global_metrics, thresholds) if global_metrics else None global_pass = (global_failed == []) if global_failed is not None else None
if critical_failures: status = "FAIL_CRITICAL" elif failures: status = "FAIL" elif not any(r["status"] == "PASS" for r in evaluated): status = "INSUFFICIENT" else: status = "PASS"
report = { "matrix_id": f"hwm-{content_hash({'rows': [r.get('combination') for r in rows], 'policy': pol}, exclude=())}", "status": status, "global_pass": global_pass, "global_metrics": global_metrics, "global_vs_matrix_note": ( "global aggregate passes but a launch-critical combination fails — " "the aggregate is hiding a stratum failure (Simpson-style); the " "matrix verdict wins" if global_pass and critical_failures else None), "n_combinations": len(evaluated), "n_pass": sum(1 for r in evaluated if r["status"] == "PASS"), "n_fail": len(failures), "n_insufficient": len(insufficient), "min_support": support, "critical_failures": critical_failures, "failures": [f for f in failures if f not in critical_failures], "insufficient": [{"combination_label": r["combination_label"], "combination": r["combination"], "critical": r["critical"], "reason": r["reason"]} for r in insufficient], "rows": evaluated, "policy": pol, "source_run_id": source_run_id, "evaluated_at": store.now_iso(), } if persist: store.write_json(report, "hardware", "latest.json") return report
def gate_matrix(policy: Optional[Dict] = None, persist: bool = True) -> Dict: """Synthesize combinations from the real stores and evaluate them.""" data = synthesize_combinations() return evaluate_matrix(data["rows"], policy=policy, global_metrics=data["global_metrics"], source_run_id=data["source_run_id"], persist=persist)
def latest_matrix() -> Optional[Dict]: return store.read_json("hardware", "latest.json")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492"""Control-plane registry: versioned entities for the whole evaluation system.
Entities (all persisted as JSON under runs/studio2/registry/<kind>/):
models ModelVersion name/version/checkpoint + provenance datasets DatasetVersion role (TRAINING/VALIDATION/TEST/REGRESSION/ LAUNCH/MONITORING), immutable lineage, role-transition rules with the raremine contamination-guard pattern scenarios ScenarioVersion generator + seed + recipe hash policies PolicyVersion content-hashed policy documents experiments Experiment candidate-vs-baseline grouping runs EvaluationRun full reproducibility tuple; runs missing any component are NON_REPRODUCIBLE safety_cases SafetyCase pointers to safety evidence packages / agentic scorecards decisions ReleaseDecision written by release_gate.py approvals HumanApproval the separate recorded human action
Auto-ingest adapters scan the existing runs/ stores (megaeval, seqeval,safety evidence, agentic scorecards, bevfusion) and register entitiesretroactively with provenance where derivable. Ingest is idempotent: entityids are content-derived from the source references."""
from __future__ import annotations
import hashlibimport jsonimport osimport threadingfrom typing import Dict, List, Optional
from sensorflow.studio2 import store
# ------------------------------------------------------------------ constants
KINDS = ("models", "datasets", "scenarios", "policies", "experiments", "runs", "safety_cases", "decisions", "approvals")
DATASET_ROLES = ("TRAINING", "VALIDATION", "TEST", "REGRESSION", "LAUNCH", "MONITORING")
# Same semantics as raremine.models.PROTECTED_EVAL_DESTINATIONS: examples in# these roles decide launches, so silently moving them across the# training/evaluation boundary would corrupt every future measurement.PROTECTED_EVAL_ROLES = frozenset({"TEST", "REGRESSION", "LAUNCH"})
# The reproducibility tuple. A run missing any component cannot be replayed# bit-for-bit and is marked NON_REPRODUCIBLE.REPRO_COMPONENTS = ("model_version_id", "dataset_version_id", "scenario_version_id", "config_hash", "calibration_version", "seed", "policy_version_id")
REPRODUCIBLE = "REPRODUCIBLE"NON_REPRODUCIBLE = "NON_REPRODUCIBLE"
class RoleTransitionError(RuntimeError): """Raised on any attempt to move a dataset across the training/evaluation contamination boundary without an explicit governance override."""
def new_id(prefix: str, *seed_parts: str) -> str: """Deterministic when seed_parts are given (used by ingest for idempotency), random-ish otherwise.""" if seed_parts: h = hashlib.sha256("|".join(seed_parts).encode()).hexdigest()[:10] else: h = hashlib.sha256(os.urandom(16)).hexdigest()[:10] return f"{prefix}-{h}"
def content_hash(doc: Dict, exclude: tuple = ("policy_version", "created_at")) -> str: blob = json.dumps({k: v for k, v in doc.items() if k not in exclude}, sort_keys=True, default=str) return hashlib.sha256(blob.encode()).hexdigest()[:16]
# ------------------------------------------------------------------ registry
class Registry: """Thin persisted entity store with the governance rules baked in."""
def __init__(self): self._lock = threading.RLock()
# -------------------------------------------------------------- storage
def _path_parts(self, kind: str, entity_id: str): return ("registry", kind, f"{entity_id}.json")
def put(self, kind: str, entity: Dict) -> Dict: if kind not in KINDS: raise KeyError(f"unknown entity kind {kind!r}; known: {KINDS}") entity = dict(entity) entity.setdefault("kind", kind) entity.setdefault("created_at", store.now_iso()) store.write_json(entity, *self._path_parts(kind, entity["entity_id"])) return entity
def get(self, kind: str, entity_id: str) -> Optional[Dict]: return store.read_json(*self._path_parts(kind, entity_id))
def list(self, kind: str) -> List[Dict]: if kind not in KINDS: raise KeyError(f"unknown entity kind {kind!r}; known: {KINDS}") out = [] for name in store.list_dir("registry", kind): if not name.endswith(".json"): continue doc = store.read_json("registry", kind, name) if doc: out.append(doc) out.sort(key=lambda e: e.get("created_at") or "", reverse=True) return out
def counts(self) -> Dict[str, int]: return {kind: len(store.list_dir("registry", kind)) for kind in KINDS}
# -------------------------------------------------------------- models
def register_model(self, name: str, version: str, checkpoint: str = "", provenance: Optional[Dict] = None, meta: Optional[Dict] = None) -> Dict: entity_id = new_id("mv", name, version, checkpoint) existing = self.get("models", entity_id) if existing: return existing return self.put("models", { "entity_id": entity_id, "name": name, "version": version, "checkpoint": checkpoint, "provenance": provenance or {}, "meta": meta or {}})
# -------------------------------------------------------------- datasets
def register_dataset(self, name: str, role: str, lineage_parents: Optional[List[str]] = None, provenance: Optional[Dict] = None, meta: Optional[Dict] = None, actor: str = "studio2") -> Dict: if role not in DATASET_ROLES: raise ValueError(f"unknown dataset role {role!r}; known: {DATASET_ROLES}") entity_id = new_id("dv", name, role_seed := role) existing = self.get("datasets", entity_id) if existing: return existing entity = self.put("datasets", { "entity_id": entity_id, "name": name, "role": role, "protected_evaluation": role in PROTECTED_EVAL_ROLES, # lineage is immutable: parents are recorded once, at creation "lineage": {"parents": list(lineage_parents or []), "recorded_at": store.now_iso()}, "role_history": [{"from": None, "to": role, "actor": actor, "override": None, "timestamp": store.now_iso()}], "governance_overrides": [], "provenance": provenance or {}, "meta": meta or {}}) store.audit("dataset_registered", "datasets", entity_id, actor=actor, detail=f"{name} role={role}") return entity
def transition_role(self, dataset_id: str, new_role: str, actor: str, override_reason: Optional[str] = None) -> Dict: """The ONLY path that changes a dataset's role.
Contamination guard (raremine.lineage pattern): - protected eval role -> TRAINING requires an explicit override (who + why), otherwise RoleTransitionError; - TRAINING -> protected eval role is guarded the same way (training examples silently becoming launch evidence is the same corruption in the other direction). Every transition and every override is audited. """ if new_role not in DATASET_ROLES: raise ValueError(f"unknown dataset role {new_role!r}") with self._lock: entity = self.get("datasets", dataset_id) if entity is None: raise KeyError(f"unknown dataset {dataset_id}") old_role = entity["role"] if old_role == new_role: return entity
crossing = ((old_role in PROTECTED_EVAL_ROLES and new_role == "TRAINING") or (old_role == "TRAINING" and new_role in PROTECTED_EVAL_ROLES)) override = None if crossing: if not (override_reason and override_reason.strip() and actor.strip()): raise RoleTransitionError( f"dataset {dataset_id} ({entity['name']}): {old_role} -> " f"{new_role} crosses the training/evaluation contamination " "boundary; it requires an explicit governance override " "recording who and why") override = {"actor": actor, "reason": override_reason, "timestamp": store.now_iso(), "transition": f"{old_role}->{new_role}"} entity["governance_overrides"].append(override) store.audit("governance_override", "datasets", dataset_id, actor=actor, detail=override_reason)
entity["role"] = new_role entity["protected_evaluation"] = new_role in PROTECTED_EVAL_ROLES entity["role_history"].append( {"from": old_role, "to": new_role, "actor": actor, "override": override, "timestamp": store.now_iso()}) self.put("datasets", entity) store.audit("role_transition", "datasets", dataset_id, actor=actor, detail=f"{old_role} -> {new_role}") return entity
# -------------------------------------------------------------- scenarios
def register_scenario(self, name: str, generator: str, seed: Optional[int], recipe: Optional[Dict] = None, provenance: Optional[Dict] = None) -> Dict: recipe_hash = content_hash(recipe or {}, exclude=()) entity_id = new_id("sv", name, generator, str(seed), recipe_hash) existing = self.get("scenarios", entity_id) if existing: return existing return self.put("scenarios", { "entity_id": entity_id, "name": name, "generator": generator, "seed": seed, "recipe": recipe or {}, "recipe_hash": recipe_hash, "provenance": provenance or {}})
# -------------------------------------------------------------- policies
def register_policy(self, name: str, doc: Dict, provenance: Optional[Dict] = None) -> Dict: version = content_hash(doc) entity_id = f"pol-{version}" existing = self.get("policies", entity_id) if existing: return existing return self.put("policies", { "entity_id": entity_id, "name": name, "policy_version": version, "doc": doc, "provenance": provenance or {}})
# -------------------------------------------------------------- experiments
def register_experiment(self, name: str, candidate_model_id: str, baseline_model_id: str, meta: Optional[Dict] = None) -> Dict: entity_id = new_id("exp", name, candidate_model_id, baseline_model_id) existing = self.get("experiments", entity_id) if existing: return existing return self.put("experiments", { "entity_id": entity_id, "name": name, "candidate_model_id": candidate_model_id, "baseline_model_id": baseline_model_id, "meta": meta or {}})
# -------------------------------------------------------------- runs
def register_run(self, name: str, engine: str, tuple_components: Dict, results: Optional[Dict] = None, experiment_id: Optional[str] = None, provenance: Optional[Dict] = None) -> Dict: """tuple_components: values for REPRO_COMPONENTS (None/'' = missing). The reproducibility verdict is computed here and cannot be supplied.""" missing = [c for c in REPRO_COMPONENTS if tuple_components.get(c) in (None, "")] entity_id = new_id("run", name, engine, content_hash(tuple_components, exclude=())) existing = self.get("runs", entity_id) if existing: return existing return self.put("runs", { "entity_id": entity_id, "name": name, "engine": engine, "experiment_id": experiment_id, "reproducibility_tuple": {c: tuple_components.get(c) for c in REPRO_COMPONENTS}, "missing_components": missing, "reproducibility": NON_REPRODUCIBLE if missing else REPRODUCIBLE, "results": results or {}, "provenance": provenance or {}})
# -------------------------------------------------------------- safety cases
def register_safety_case(self, name: str, case_kind: str, reference: Dict, provenance: Optional[Dict] = None) -> Dict: entity_id = new_id("sc", name, case_kind, content_hash(reference, exclude=())) existing = self.get("safety_cases", entity_id) if existing: return existing return self.put("safety_cases", { "entity_id": entity_id, "name": name, "case_kind": case_kind, "reference": reference, "provenance": provenance or {}})
# ------------------------------------------------------------------ ingest
def _safe_json(path: str) -> Optional[Dict]: try: with open(path) as f: return json.load(f) except Exception: return None
def ingest_existing_stores(registry: Registry, repo_root: str = ".") -> Dict: """Scan the landed packages' stores and register entities retroactively.
Best-effort and idempotent. Nothing is fabricated: components that cannot be derived from the source records stay missing, so most ingested runs are honestly NON_REPRODUCIBLE (megaeval lineage carries the most complete tuple; it still lacks scenario + calibration components). """ counts = {"models": 0, "datasets": 0, "runs": 0, "safety_cases": 0, "scenarios": 0, "policies": 0} sources: Dict[str, str] = {}
# ---- megaeval runs (runs/megaeval/runs/*/run.json -> {"state": {...}}) mega_dir = os.path.join(repo_root, "runs", "megaeval", "runs") if os.path.isdir(mega_dir): sources["megaeval"] = mega_dir for rid in sorted(os.listdir(mega_dir)): state = (_safe_json(os.path.join(mega_dir, rid, "run.json")) or {}).get("state") if not state or state.get("status") != "published": continue lin = state.get("lineage") or {} model = registry.register_model( name=state.get("model_version") or "unknown", version=state.get("model_version") or "unknown", checkpoint=lin.get("model_checkpoint") or "", provenance={"source_package": "megaeval", "run_id": rid}) counts["models"] += 1 dataset = registry.register_dataset( name=lin.get("dataset_version") or state.get("population_id") or rid, role="TEST", provenance={"source_package": "megaeval", "population_id": state.get("population_id")}, meta={"label_version": lin.get("label_version")}) counts["datasets"] += 1 registry.register_run( name=rid, engine="megaeval", tuple_components={ "model_version_id": model["entity_id"], "dataset_version_id": dataset["entity_id"], "scenario_version_id": None, # megaeval has no scenario axis "config_hash": content_hash( {"threshold": lin.get("threshold_config"), "sampling": lin.get("sampling_config"), "metric_version": lin.get("metric_version"), "evaluator": lin.get("evaluator_code_version")}, exclude=()), "calibration_version": None, # not recorded in megaeval lineage "seed": state.get("seed"), "policy_version_id": None, }, results={"headline": state.get("headline")}, provenance={"source_package": "megaeval", "run_id": rid, "lineage": lin}) counts["runs"] += 1
# ---- seqeval runs (runs/seqeval/runs/*/run.json) seq_dir = os.path.join(repo_root, "runs", "seqeval", "runs") if os.path.isdir(seq_dir): sources["seqeval"] = seq_dir for rid in sorted(os.listdir(seq_dir)): st = _safe_json(os.path.join(seq_dir, rid, "run.json")) if not st: continue policy = registry.register_policy( name="seqeval-policy", doc=st.get("policy") or {}, provenance={"source_package": "seqeval", "run_id": rid}) counts["policies"] += 1 cand = (st.get("candidate") or {}).get("model_version") or "candidate" base = (st.get("baseline") or {}).get("model_version") or "baseline" model = registry.register_model( name=cand, version=cand, provenance={"source_package": "seqeval", "run_id": rid}) counts["models"] += 1 registry.register_run( name=rid, engine="seqeval", tuple_components={ "model_version_id": model["entity_id"], "dataset_version_id": st.get("population_id"), "scenario_version_id": None, "config_hash": content_hash(st.get("policy") or {}, exclude=()), "calibration_version": None, "seed": st.get("seed"), "policy_version_id": policy["entity_id"], }, results={"decision": st.get("decision"), "gate": st.get("gate"), "stopping_reason": st.get("stopping_reason"), "baseline": base, "candidate": cand}, provenance={"source_package": "seqeval", "run_id": rid}) counts["runs"] += 1
# ---- safety evidence packages (runs/safety/evidence/*.json) ev_dir = os.path.join(repo_root, "runs", "safety", "evidence") if os.path.isdir(ev_dir): sources["safety"] = ev_dir for name in sorted(os.listdir(ev_dir)): if not name.endswith(".json"): continue pkg = _safe_json(os.path.join(ev_dir, name)) if not pkg: continue registry.register_safety_case( name=pkg.get("package_id") or name, case_kind="safety_evidence_package", reference={"package_id": pkg.get("package_id"), "candidate_run_id": (pkg.get("candidate") or {}).get("run_id"), "baseline_run_id": (pkg.get("baseline") or {}).get("run_id"), "release_ready": (pkg.get("decision") or {}).get("release_ready"), "path": os.path.join("runs", "safety", "evidence", name)}, provenance={"source_package": "safety"}) counts["safety_cases"] += 1
# ---- agentic scorecards (runs/agentic/scorecards/*.json) — in-flight pkg, # but ingest reads plain JSON so it works regardless of importability sc_dir = os.path.join(repo_root, "runs", "agentic", "scorecards") if os.path.isdir(sc_dir): sources["agentic"] = sc_dir for name in sorted(os.listdir(sc_dir)): if not name.endswith(".json"): continue card = _safe_json(os.path.join(sc_dir, name)) if not card: continue registry.register_safety_case( name=card.get("scorecard_id") or name, case_kind="agentic_scorecard", reference={"scorecard_id": card.get("scorecard_id"), "failure_id": card.get("failure_id"), "policy_version": card.get("policy_version"), "recommended_option": card.get("recommended_option"), "path": os.path.join("runs", "agentic", "scorecards", name)}, provenance={"source_package": "agentic"}) counts["safety_cases"] += 1
# ---- bevfusion comparison runs (runs/bevfusion/bevrun-*.json) bev_dir = os.path.join(repo_root, "runs", "bevfusion") if os.path.isdir(bev_dir): sources["bevfusion"] = bev_dir for name in sorted(os.listdir(bev_dir)): if not (name.startswith("bevrun-") and name.endswith(".json")): continue rep = _safe_json(os.path.join(bev_dir, name)) if not rep: continue params = rep.get("params") or {} scenario = registry.register_scenario( name=f"bevfusion-suite-{params.get('seed')}", generator="bevfusion.scenes.generate_sequences", seed=params.get("seed"), recipe=params, provenance={"source_package": "bevfusion", "run_id": rep.get("run_id")}) counts["scenarios"] += 1 engines = rep.get("engines") or {} model = registry.register_model( name=engines.get("candidate") or "bev-fused", version=engines.get("candidate") or "bev-fused", provenance={"source_package": "bevfusion", "run_id": rep.get("run_id")}) counts["models"] += 1 registry.register_run( name=rep.get("run_id") or name, engine="bevfusion", tuple_components={ "model_version_id": model["entity_id"], "dataset_version_id": None, # scenes are generated, not versioned data "scenario_version_id": scenario["entity_id"], "config_hash": content_hash(params, exclude=()), "calibration_version": None, "seed": params.get("seed"), "policy_version_id": None, }, results={"recommendation": rep.get("recommendation"), "headline_deltas": rep.get("headline_deltas")}, provenance={"source_package": "bevfusion", "run_id": rep.get("run_id")}) counts["runs"] += 1
store.audit("ingest", None, None, detail=f"scanned {sorted(sources)}", payload={"counts": counts}) return {"sources": sources, "registered": counts, "totals": registry.counts()}
# ------------------------------------------------------------------ singleton
_REGISTRY: Optional[Registry] = None_REG_LOCK = threading.RLock()
def get_registry() -> Registry: global _REGISTRY with _REG_LOCK: if _REGISTRY is None: _REGISTRY = Registry() return _REGISTRY123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319"""Deterministic release gate: composes the real verdicts into one decision.
ReleaseGate.evaluate(safety_metrics, regression_results, distribution_shift,policy) -> ReleaseDecision, where the inputs are the actual outputs of theexisting engines:
safety_metrics sensorflow.safety.gates.evaluate_gates(...) result (decision RELEASE_READY/BLOCKED + layered gates) regression_results sensorflow.seqeval.evaluate_regression(...) verdict (decision PASS/REGRESSION/INCONCLUSIVE + regression map) distribution_shift sensorflow.megaeval.analysis.distribution_shift(...) report ({"shifts": [...]}) agentic_outcome sensorflow.agentic.policy.evaluate(...) result (optional) closed_loop sensorflow.nextgen gauntlet result or causal-replay verdict (optional) hardware_matrix sensorflow.studio2.hardware.evaluate_matrix(...) report (optional)
Hard rules (all covered by tests): - GO never authorizes deployment. A ReleaseDecision with status GO still has deployment_authorized=False; authorization is a separate recorded human approval action (Registry 'approvals' + audit). - A missing or failed required subsystem degrades the decision to REVIEW with the gap named — never a silent GO. - The policy is content-hash versioned, and every decision records the full evidence tuple it was computed from."""
from __future__ import annotations
from typing import Dict, List, Optional
from sensorflow.studio2 import storefrom sensorflow.studio2.registry import Registry, get_registry, new_id
GO, REVIEW, NO_GO = "GO", "REVIEW", "NO_GO"
DEFAULT_RELEASE_POLICY: Dict = { "policy_name": "studio2-release-v1", # subsystems that MUST contribute evidence; absence -> REVIEW, named "required_inputs": ["safety_gates", "sequential_regression", "distribution_shift"], # consulted when supplied; never silently skipped once configured here "optional_inputs": ["agentic_policy", "closed_loop", "hardware_matrix"], # a cohort whose eval share shifted AND whose recall trails overall by # more than this gap forces REVIEW (megaeval shift report semantics) "shift_review_recall_gap": -0.05, "inconclusive_outcome": REVIEW, # never GO on absence of evidence "critical_hardware_failure_outcome": NO_GO, "confidence_penalty_per_gap": 0.25, "confidence_penalty_per_review_condition": 0.10,}
class ReleaseGate: def __init__(self, registry: Optional[Registry] = None, policy: Optional[Dict] = None): self.registry = registry or get_registry() doc = {**DEFAULT_RELEASE_POLICY, **(policy or {})} self.policy_entity = self.registry.register_policy( name=doc.get("policy_name", "studio2-release"), doc=doc, provenance={"source_package": "studio2"}) self.policy = doc
# ---------------------------------------------------------------- signals
def _signal_safety(self, payload: Optional[Dict]) -> Dict: if not payload or "decision" not in payload: return {"present": False, "gap": "safety gate results unavailable " "(sensorflow.safety evaluate_gates output missing)"} blocking = payload.get("blocking_gates") or [] if payload["decision"] == "RELEASE_READY" and not blocking: return {"present": True, "verdict": "pass", "evidence": {"safety_gate_run": payload.get("candidate_run_id"), "evidence_package_id": payload.get("evidence_package_id")}} return {"present": True, "verdict": "block", "conditions": [f"safety gate blocked: {g}" for g in blocking] or ["safety layer decision BLOCKED"], "evidence": {"safety_gate_run": payload.get("candidate_run_id"), "evidence_package_id": payload.get("evidence_package_id")}}
def _signal_seqeval(self, payload: Optional[Dict]) -> Dict: if not payload or "decision" not in payload: return {"present": False, "gap": "sequential regression verdict " "unavailable (sensorflow.seqeval evaluate_regression missing)"} decision = payload["decision"] evidence = {"seqeval_run_id": payload.get("run_id"), "samples_used": payload.get("samples_used")} if decision == "PASS": return {"present": True, "verdict": "pass", "evidence": evidence} if decision == "REGRESSION": strata = payload.get("affected_strata") or [] return {"present": True, "verdict": "block", "conditions": [ "sequential regression confirmed" + (f" in strata: {', '.join(map(str, strata))}" if strata else "")], "evidence": evidence} # INCONCLUSIVE / INSUFFICIENT: absence of evidence is never a pass reason = payload.get("stopping_reason") or "budget exhausted without a decision" return {"present": True, "verdict": "review", "questions": [f"sequential regression verdict {decision}: {reason}"], "evidence": evidence}
def _signal_shift(self, payload: Optional[Dict]) -> Dict: if not payload or "shifts" not in payload: return {"present": False, "gap": "distribution shift report " "unavailable (megaeval shift monitor missing)"} gap_limit = self.policy["shift_review_recall_gap"] flagged = [s for s in payload["shifts"] if s.get("recall_gap") is not None and s["recall_gap"] <= gap_limit] evidence = {"shift_run_id": payload.get("run_id"), "shifts_reported": len(payload["shifts"])} if flagged: return {"present": True, "verdict": "review", "questions": [ f"distribution shift with recall impact on {s['cohort']}: " f"eval share {s.get('relative_change', 0)*100:+.0f}% vs train, " f"cohort recall gap {s['recall_gap']:+.3f} — open an RCA " "investigation (offline-vs-shadow 4-way root cause)" for s in flagged[:5]], "evidence": evidence} return {"present": True, "verdict": "pass", "evidence": evidence}
def _signal_agentic(self, payload: Optional[Dict]) -> Dict: if not payload or "outcome" not in payload: return {"present": False, "gap": "agentic policy outcome unavailable " "(sensorflow.agentic not importable or not evaluated)"} outcome = payload["outcome"] evidence = {"agentic_policy_version": payload.get("policy_version"), "failure_id": payload.get("failure_id"), "outcome": outcome} if outcome == "AUTOMATIC_STOP_SHIP": return {"present": True, "verdict": "block", "conditions": ["agentic policy fired AUTOMATIC_STOP_SHIP " f"(severity {payload.get('severity')})"], "evidence": evidence} if outcome == "INDETERMINATE": return {"present": True, "verdict": "review", "questions": ["agentic policy INDETERMINATE (fail-safe): " + "; ".join(payload.get("indeterminate_reasons") or ["integrity failure"])], "evidence": evidence} return {"present": True, "verdict": "pass", "evidence": evidence}
def _signal_closed_loop(self, payload: Optional[Dict]) -> Dict: if not payload: return {"present": False, "gap": "closed-loop verdict unavailable " "(sensorflow.nextgen not importable or no replay/gauntlet run)"} # accept either a gauntlet result or a causal replay result evidence = {"closed_loop_run_id": payload.get("run_id") or payload.get("scenario_id")} if payload.get("halted") or payload.get("recommendation") == "NO_GO": return {"present": True, "verdict": "block", "conditions": ["closed-loop gauntlet halted: " + str(payload.get("halt_reason") or payload.get("recommendation"))], "evidence": evidence} if payload.get("verdict") == "BEHAVIORALLY_CONSEQUENTIAL": return {"present": True, "verdict": "review", "questions": ["closed-loop replay shows behaviorally " "consequential perception divergence on " f"{payload.get('scenario_id')}"], "evidence": evidence} return {"present": True, "verdict": "pass", "evidence": evidence}
def _signal_hardware(self, payload: Optional[Dict]) -> Dict: if not payload or "status" not in payload: return {"present": False, "gap": "hardware gate matrix unavailable"} evidence = {"hardware_matrix_id": payload.get("matrix_id"), "combinations": payload.get("n_combinations")} questions = [ f"insufficient evidence for {c['combination_label']}: {c['reason']}" for c in (payload.get("insufficient") or [])[:5]] if payload["status"] == "FAIL_CRITICAL": outcome = self.policy["critical_hardware_failure_outcome"] return {"present": True, "verdict": "block" if outcome == NO_GO else "review", "conditions": [ f"critical hardware combination failing: {c['combination_label']}" f" ({', '.join(c['failed_checks'])})" for c in (payload.get("critical_failures") or [])[:5]], "questions": questions, "evidence": evidence} if payload["status"] == "FAIL": return {"present": True, "verdict": "review", "questions": questions + [ f"non-critical hardware combination failing: {c['combination_label']}" for c in (payload.get("failures") or [])[:5]], "evidence": evidence} return {"present": True, "verdict": "review" if questions else "pass", "questions": questions, "evidence": evidence}
# ---------------------------------------------------------------- evaluate
def evaluate(self, safety_metrics: Optional[Dict], regression_results: Optional[Dict], distribution_shift: Optional[Dict], policy: Optional[Dict] = None, agentic_outcome: Optional[Dict] = None, closed_loop: Optional[Dict] = None, hardware_matrix: Optional[Dict] = None, context: Optional[Dict] = None, actor: str = "studio2") -> Dict: """Pure function of inputs + versioned policy; persists and returns a ReleaseDecision.""" if policy: gate = ReleaseGate(self.registry, policy={**self.policy, **policy}) return gate.evaluate(safety_metrics, regression_results, distribution_shift, agentic_outcome=agentic_outcome, closed_loop=closed_loop, hardware_matrix=hardware_matrix, context=context, actor=actor)
signals = { "safety_gates": self._signal_safety(safety_metrics), "sequential_regression": self._signal_seqeval(regression_results), "distribution_shift": self._signal_shift(distribution_shift), "agentic_policy": self._signal_agentic(agentic_outcome), "closed_loop": self._signal_closed_loop(closed_loop), "hardware_matrix": self._signal_hardware(hardware_matrix), }
required = self.policy["required_inputs"] optional = self.policy["optional_inputs"] considered = list(required) + list(optional)
blocking: List[str] = [] questions: List[str] = [] gaps: List[str] = [] evidence_tuple: Dict = {"release_policy_version": self.policy_entity["policy_version"]} for name in considered: sig = signals[name] if not sig["present"]: if name in required: gaps.append(sig["gap"]) else: # optional-but-configured subsystems: absence is surfaced # as an open question, never silently ignored questions.append(f"[{name}] {sig['gap']}") evidence_tuple[name] = None continue evidence_tuple[name] = sig.get("evidence") blocking.extend(sig.get("conditions") or []) questions.extend(sig.get("questions") or []) if context: evidence_tuple["context"] = context
if blocking: status = NO_GO elif gaps or questions: status = REVIEW else: status = GO
n_present = sum(1 for n in considered if signals[n]["present"]) evidence_completeness = round(n_present / len(considered), 3) confidence = 1.0 confidence -= self.policy["confidence_penalty_per_gap"] * len(gaps) confidence -= (self.policy["confidence_penalty_per_review_condition"] * len(questions)) confidence = round(max(0.05, min(confidence, evidence_completeness if status != NO_GO else 1.0)), 3)
decision = { "entity_id": new_id("rd"), "status": status, "confidence": confidence, "evidence_completeness": evidence_completeness, "blocking_conditions": blocking, "unresolved_questions": questions, "degraded_inputs": gaps, # GO is a *recommendation*; deployment always needs a human "human_approval_required": True, "deployment_authorized": False, "approval": None, "policy_version": self.policy_entity["policy_version"], "evidence_tuple": evidence_tuple, "signals": {k: {kk: vv for kk, vv in v.items() if kk != "evidence"} for k, v in signals.items()}, "evaluated_at": store.now_iso(), } self.registry.put("decisions", decision) store.audit("release_decision", "decisions", decision["entity_id"], actor=actor, detail=f"status={status} " f"completeness={evidence_completeness}", payload={"blocking": blocking[:5], "gaps": gaps[:5]}) return decision
# ---------------------------------------------------------------- approval
def approve(self, decision_id: str, approver: str, rationale: str) -> Dict: """The separate human action that authorizes deployment. Only a GO decision can be approved; REVIEW/NO_GO must be re-evaluated first.""" if not approver.strip() or not rationale.strip(): raise ValueError("human approval requires a named approver and a rationale") decision = self.registry.get("decisions", decision_id) if decision is None: raise KeyError(f"unknown release decision {decision_id}") if decision["status"] != GO: raise ValueError( f"decision {decision_id} has status {decision['status']}; only GO " "decisions can be approved for deployment — resolve the blocking " "conditions / unresolved questions and re-evaluate") approval = { "entity_id": new_id("app"), "decision_id": decision_id, "approver": approver, "rationale": rationale, "approved_at": store.now_iso(), } self.registry.put("approvals", approval) decision["deployment_authorized"] = True decision["approval"] = approval self.registry.put("decisions", decision) store.audit("human_approval", "approvals", approval["entity_id"], actor=approver, detail=f"authorized deployment for {decision_id}", payload={"rationale": rationale}) return decision123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Filesystem layout for the studio2 control plane.
Everything persists under runs/studio2/ (relocatable for tests viaset_studio2_root, mirroring safety.store / megaeval patterns):
runs/studio2/ registry/<kind>/<entity_id>.json control-plane entities decisions/<decision_id>.json release decisions (append-only) demo/<demo_id>.json + latest.json closed-loop demo runs audit.jsonl append-only audit trail"""
from __future__ import annotations
import jsonimport osimport threadingfrom datetime import datetime, timezonefrom typing import Any, Dict, List, Optional
STUDIO2_ROOT = os.path.join("runs", "studio2")
_LOCK = threading.RLock()
def set_studio2_root(path: str) -> None: """Test hook: relocate all studio2 storage.""" global STUDIO2_ROOT STUDIO2_ROOT = str(path)
def studio2_path(*parts: str) -> str: path = os.path.join(STUDIO2_ROOT, *parts) os.makedirs(os.path.dirname(path), exist_ok=True) return path
def read_json(*parts: str) -> Optional[Any]: path = os.path.join(STUDIO2_ROOT, *parts) if not os.path.exists(path): return None with _LOCK: try: with open(path) as f: return json.load(f) except Exception: return None
def write_json(payload: Any, *parts: str) -> str: path = studio2_path(*parts) with _LOCK: tmp = path + ".tmp" with open(tmp, "w") as f: json.dump(payload, f, indent=2, default=str) os.replace(tmp, path) return path
def list_dir(*parts: str) -> List[str]: path = os.path.join(STUDIO2_ROOT, *parts) if not os.path.isdir(path): return [] return sorted(os.listdir(path))
def now_iso() -> str: return datetime.now(timezone.utc).isoformat()
def audit(action: str, entity_kind: Optional[str], entity_id: Optional[str], actor: str = "studio2", detail: str = "", payload: Optional[Dict] = None) -> Dict: rec = {"timestamp": now_iso(), "action": action, "entity_kind": entity_kind, "entity_id": entity_id, "actor": actor, "detail": detail, "payload": payload or {}} path = studio2_path("audit.jsonl") with _LOCK: with open(path, "a") as f: f.write(json.dumps(rec, default=str) + "\n") return rec
def read_audit(limit: int = 200) -> List[Dict]: path = os.path.join(STUDIO2_ROOT, "audit.jsonl") if not os.path.exists(path): return [] out: List[Dict] = [] with _LOCK: with open(path) as f: for line in f: line = line.strip() if not line: continue try: out.append(json.loads(line)) except Exception: continue return out[-limit:]main.py+15-2
sensorflow/evaluation/detectors.py+10-2
sensorflow/evaluation/regression.py+65-12
sensorflow/hardening/__init__.pyAdded+8
sensorflow/hardening/api.pyAdded+261
sensorflow/hardening/cache_manifest.pyAdded+184
sensorflow/hardening/contracts.pyAdded+328
sensorflow/hardening/hitl.pyAdded+134
sensorflow/hardening/interfaces.pyAdded+315
sensorflow/hardening/power.pyAdded+209
sensorflow/hardening/quality.pyAdded+243
sensorflow/hardening/readiness.pyAdded+141
sensorflow/hardening/safety_config.pyAdded+150
sensorflow/hardening/sampling.pyAdded+236
sensorflow/megaeval/cube.py+8-2
sensorflow/metrics/perception_3d.py+49-1
sensorflow/metrics/temporal_mot.py+7-1
sensorflow/mitl_copilot.py+21-4
sensorflow/nextgen/__init__.pyAdded+55
sensorflow/nextgen/api.pyAdded+329
sensorflow/nextgen/cache.pyAdded+196
sensorflow/nextgen/causal.pyAdded+137
sensorflow/nextgen/closedloop.pyAdded+466
sensorflow/nextgen/compute.pyAdded+181
sensorflow/nextgen/counterfactual.pyAdded+631
sensorflow/nextgen/lineage.pyAdded+62
sensorflow/nextgen/models.pyAdded+220
sensorflow/nextgen/regression.pyAdded+162
sensorflow/nextgen/safety_metrics.pyAdded+263
sensorflow/nextgen/scheduler.pyAdded+349
sensorflow/nextgen/store.pyAdded+56
sensorflow/nextgen/validity.pyAdded+454
sensorflow/nextgen/worldmodel.pyAdded+105
sensorflow/perception_automator.py+7-1
sensorflow/quality_gate.py+29-5
sensorflow/studio2/__init__.pyAdded+33
sensorflow/studio2/api.pyAdded+294
sensorflow/studio2/demo.pyAdded+274
sensorflow/studio2/funnel.pyAdded+363
sensorflow/studio2/hardware.pyAdded+331
sensorflow/studio2/registry.pyAdded+492
sensorflow/studio2/release_gate.pyAdded+319
sensorflow/studio2/store.pyAdded+99