feat(lab): freeze RAVNOVES00 R0 acceptance contract
This commit is contained in:
@@ -0,0 +1,728 @@
|
||||
"""Freeze the RAVNOVES00 R0 acceptance denominator and validation split."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Final, Literal
|
||||
|
||||
E37_PROFILE_SCHEMA: Final = "missioncore.e37-acceptance-profile/v1"
|
||||
E37_PACKAGE_SCHEMA: Final = "missioncore.e37-worker-package/v1"
|
||||
E37_RESULT_SCHEMA: Final = "missioncore.e37-acceptance-contract/v1"
|
||||
E37_ITEM_SCHEMA: Final = "missioncore.e37-acceptance-item/v1"
|
||||
E37_REPORT_SCHEMA: Final = "missioncore.e37-acceptance-report/v1"
|
||||
E37_CONTRACT_SCHEMA: Final = "missioncore.ravnoves00-acceptance-contract/v1"
|
||||
|
||||
E37_ITEMS_NAME: Final = "acceptance-items.jsonl"
|
||||
E37_CONTRACT_NAME: Final = "acceptance-contract.json"
|
||||
E37_REPORT_NAME: Final = "run-report.json"
|
||||
E37_MANIFEST_NAME: Final = "manifest.json"
|
||||
|
||||
_MATERIALIZATION_SCHEMA: Final = "missioncore.e30-evidence-materialization/v2"
|
||||
_ENGINEERING_SCHEMA: Final = "missioncore.e30-engineering-generation/v1"
|
||||
_HUMAN_SCHEMA: Final = "missioncore.e30-human-review-generation/v2"
|
||||
_SOURCE_SESSION_ID: Final = "20260720T065719Z_viewer_live"
|
||||
_SOURCE_DISPLAY_NAME: Final = "RAVNOVES00"
|
||||
_AUTHORITY: Final = {
|
||||
"commands_enabled": False,
|
||||
"navigation_or_safety_accepted": False,
|
||||
}
|
||||
|
||||
PresenceLabel = Literal[
|
||||
"object-present",
|
||||
"occupied-environment",
|
||||
"background-or-noise",
|
||||
"unknown",
|
||||
]
|
||||
GeometryLabel = Literal[
|
||||
"object-associated",
|
||||
"independent-occupied",
|
||||
"rejected-nonobject",
|
||||
"insufficient-support",
|
||||
"unknown",
|
||||
]
|
||||
FreshnessLabel = Literal["current", "held", "stale", "unavailable", "unknown"]
|
||||
SplitName = Literal["development", "validation"]
|
||||
|
||||
|
||||
class E37AcceptanceContractError(RuntimeError):
|
||||
"""The R0 profile, source review, or immutable result is invalid."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class E37AcceptanceContract:
|
||||
result_id: str
|
||||
result_root: Path
|
||||
manifest: dict[str, Any]
|
||||
contract: dict[str, Any]
|
||||
report: dict[str, Any]
|
||||
|
||||
@property
|
||||
def accepted(self) -> bool:
|
||||
return self.report.get("acceptance", {}).get("accepted") is True
|
||||
|
||||
|
||||
def derive_reference_labels(
|
||||
decision: dict[str, Any],
|
||||
human_disposition: str | None,
|
||||
) -> tuple[PresenceLabel, GeometryLabel, FreshnessLabel]:
|
||||
"""Project the reviewed E30 decision into the frozen R0 task ontology."""
|
||||
|
||||
detector = decision.get("detector_assessment")
|
||||
ownership = decision.get("point_ownership")
|
||||
cause = decision.get("cause_code")
|
||||
effective_stratum = decision.get("effective_stratum")
|
||||
|
||||
if human_disposition == "object-present":
|
||||
presence: PresenceLabel = "occupied-environment"
|
||||
geometry: GeometryLabel = "independent-occupied"
|
||||
elif human_disposition == "background-or-noise":
|
||||
presence = "background-or-noise"
|
||||
geometry = "rejected-nonobject"
|
||||
elif human_disposition == "insufficient-evidence":
|
||||
presence = "unknown"
|
||||
geometry = "unknown"
|
||||
elif detector in {"valid", "class-mismatch", "missed-object"}:
|
||||
presence = "object-present"
|
||||
geometry = _geometry_label(ownership)
|
||||
elif detector == "false-positive":
|
||||
presence = "background-or-noise"
|
||||
geometry = _geometry_label(ownership)
|
||||
elif detector == "not-applicable":
|
||||
if ownership == "object":
|
||||
presence = "object-present"
|
||||
elif ownership == "static-environment":
|
||||
presence = "occupied-environment"
|
||||
elif ownership in {"surface-or-background", "self"}:
|
||||
presence = "background-or-noise"
|
||||
else:
|
||||
presence = "unknown"
|
||||
geometry = _geometry_label(ownership)
|
||||
else:
|
||||
presence = "unknown"
|
||||
geometry = _geometry_label(ownership)
|
||||
|
||||
if cause == "time_mismatch":
|
||||
freshness: FreshnessLabel = "stale"
|
||||
elif effective_stratum in {"camera-only", "unknown"} or ownership in {
|
||||
"insufficient-support",
|
||||
"insufficient-evidence",
|
||||
}:
|
||||
freshness = "unavailable"
|
||||
else:
|
||||
freshness = "current"
|
||||
return presence, geometry, freshness
|
||||
|
||||
|
||||
def assign_split(
|
||||
rows: list[dict[str, Any]],
|
||||
*,
|
||||
seed: str,
|
||||
validation_fraction: float,
|
||||
) -> dict[str, SplitName]:
|
||||
"""Assign a deterministic source-stratum/range-balanced holdout."""
|
||||
|
||||
if not seed or not 0.1 <= validation_fraction <= 0.5:
|
||||
raise E37AcceptanceContractError("E37 split profile is invalid")
|
||||
grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
|
||||
for row in rows:
|
||||
item_id = row.get("item_id")
|
||||
stratum = row.get("source_stratum")
|
||||
range_bucket = row.get("range_bucket")
|
||||
if not all(isinstance(value, str) and value for value in (
|
||||
item_id,
|
||||
stratum,
|
||||
range_bucket,
|
||||
)):
|
||||
raise E37AcceptanceContractError("E37 split source row is invalid")
|
||||
grouped[(stratum, range_bucket)].append(row)
|
||||
|
||||
assignments: dict[str, SplitName] = {}
|
||||
for group_rows in grouped.values():
|
||||
ordered = sorted(
|
||||
group_rows,
|
||||
key=lambda row: hashlib.sha256(
|
||||
f"{seed}:{row['item_id']}".encode()
|
||||
).hexdigest(),
|
||||
)
|
||||
validation_count = round(len(ordered) * validation_fraction)
|
||||
if len(ordered) > 1:
|
||||
validation_count = min(len(ordered) - 1, max(1, validation_count))
|
||||
else:
|
||||
validation_count = 0
|
||||
for index, row in enumerate(ordered):
|
||||
assignments[row["item_id"]] = (
|
||||
"validation" if index < validation_count else "development"
|
||||
)
|
||||
if set(assignments) != {row["item_id"] for row in rows}:
|
||||
raise E37AcceptanceContractError("E37 split accounting is incomplete")
|
||||
return assignments
|
||||
|
||||
|
||||
def build_e37_acceptance_contract(
|
||||
*,
|
||||
materialization_root: Path,
|
||||
engineering_generation_root: Path,
|
||||
human_generation_root: Path,
|
||||
profile_path: Path,
|
||||
output_root: Path,
|
||||
worker_node: str | None = None,
|
||||
) -> E37AcceptanceContract:
|
||||
"""Build or verify one immutable source-scoped R0 contract."""
|
||||
|
||||
profile_file = profile_path.resolve(strict=True)
|
||||
profile = _read_json(profile_file)
|
||||
_validate_profile(profile)
|
||||
materialization = materialization_root.resolve(strict=True)
|
||||
engineering = engineering_generation_root.resolve(strict=True)
|
||||
human = human_generation_root.resolve(strict=True)
|
||||
inputs = _load_inputs(materialization, engineering, human, profile)
|
||||
|
||||
identity = {
|
||||
"schema_version": E37_RESULT_SCHEMA,
|
||||
"source": {
|
||||
"session_id": _SOURCE_SESSION_ID,
|
||||
"display_name": _SOURCE_DISPLAY_NAME,
|
||||
"classification": "immutable-private-physical-recording",
|
||||
},
|
||||
"profile": {
|
||||
"profile_id": profile["profile_id"],
|
||||
"sha256": _sha256(profile_file),
|
||||
},
|
||||
"reviewed_substrate": inputs["bindings"],
|
||||
"split": profile["split"],
|
||||
"ontology": profile["ontology"],
|
||||
"metrics": profile["metrics"],
|
||||
"severity": profile["severity"],
|
||||
"execution": {
|
||||
"class": "deterministic-offline-contract-build",
|
||||
"worker_node": worker_node or "unbound-local",
|
||||
},
|
||||
"authority": _AUTHORITY,
|
||||
}
|
||||
identity_sha256 = hashlib.sha256(_canonical_json(identity)).hexdigest()
|
||||
result_id = f"e37-ravnoves-acceptance-{identity_sha256}"
|
||||
destination = output_root.expanduser().absolute() / result_id
|
||||
if destination.exists():
|
||||
return read_e37_acceptance_contract(destination)
|
||||
|
||||
materialization_by_id = {
|
||||
row["item_id"]: row for row in inputs["materialization_rows"]
|
||||
}
|
||||
engineering_rows = inputs["engineering_rows"]
|
||||
human_by_id = {
|
||||
row["item_id"]: row for row in inputs["human_rows"]
|
||||
}
|
||||
joined_for_split = []
|
||||
for decision in engineering_rows:
|
||||
source = materialization_by_id.get(decision["item_id"])
|
||||
if source is None:
|
||||
raise E37AcceptanceContractError(
|
||||
"E37 engineering/materialization accounting differs"
|
||||
)
|
||||
joined_for_split.append(
|
||||
{
|
||||
"item_id": decision["item_id"],
|
||||
"source_stratum": decision["source_stratum"],
|
||||
"range_bucket": source["range_bucket"],
|
||||
}
|
||||
)
|
||||
assignments = assign_split(
|
||||
joined_for_split,
|
||||
seed=profile["split"]["seed"],
|
||||
validation_fraction=float(profile["split"]["validation_fraction"]),
|
||||
)
|
||||
|
||||
items: list[dict[str, Any]] = []
|
||||
for decision in engineering_rows:
|
||||
item_id = decision["item_id"]
|
||||
source = materialization_by_id[item_id]
|
||||
human_row = human_by_id.get(item_id)
|
||||
human_disposition = (
|
||||
human_row.get("disposition") if human_row is not None else None
|
||||
)
|
||||
if decision.get("human_exception_required") is True and human_row is None:
|
||||
raise E37AcceptanceContractError("E37 human exception is unresolved")
|
||||
if decision.get("human_exception_required") is not True and human_row is not None:
|
||||
raise E37AcceptanceContractError("E37 human review escaped its exception set")
|
||||
presence, geometry, freshness = derive_reference_labels(
|
||||
decision,
|
||||
human_disposition,
|
||||
)
|
||||
item = {
|
||||
"schema_version": E37_ITEM_SCHEMA,
|
||||
"sequence": len(items),
|
||||
"item_id": item_id,
|
||||
"review_key": decision["review_key"],
|
||||
"source_frame_index": source["evidence_binding"]["source_frame_index"],
|
||||
"session_seconds": source["evidence_binding"]["session_seconds"],
|
||||
"source_stratum": decision["source_stratum"],
|
||||
"range_bucket": source["range_bucket"],
|
||||
"severity": _severity(decision, human_disposition),
|
||||
"split": assignments[item_id],
|
||||
"reference": {
|
||||
"presence": presence,
|
||||
"geometry_association": geometry,
|
||||
"freshness": freshness,
|
||||
},
|
||||
"provenance": {
|
||||
"engineering_verdict": decision["verdict"],
|
||||
"engineering_confidence": decision["confidence"],
|
||||
"human_exception": human_row is not None,
|
||||
"human_disposition": human_disposition,
|
||||
},
|
||||
"authority": _AUTHORITY,
|
||||
}
|
||||
items.append(item)
|
||||
|
||||
contract = _contract_document(
|
||||
result_id=result_id,
|
||||
identity_sha256=identity_sha256,
|
||||
profile=profile,
|
||||
items=items,
|
||||
)
|
||||
report = _report_document(
|
||||
result_id=result_id,
|
||||
identity_sha256=identity_sha256,
|
||||
profile=profile,
|
||||
items=items,
|
||||
execution=identity["execution"],
|
||||
)
|
||||
|
||||
destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
staging = destination.parent / f".{result_id}.{uuid.uuid4().hex}.tmp"
|
||||
staging.mkdir(mode=0o700, exist_ok=False)
|
||||
try:
|
||||
_write_jsonl(staging / E37_ITEMS_NAME, items)
|
||||
_write_json(staging / E37_CONTRACT_NAME, contract)
|
||||
_write_json(staging / E37_REPORT_NAME, report)
|
||||
artifacts = [
|
||||
_artifact(staging / E37_ITEMS_NAME, "reviewed-denominator"),
|
||||
_artifact(staging / E37_CONTRACT_NAME, "acceptance-contract"),
|
||||
_artifact(staging / E37_REPORT_NAME, "run-report"),
|
||||
]
|
||||
manifest = {
|
||||
"schema_version": E37_RESULT_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"identity_sha256": identity_sha256,
|
||||
"identity": identity,
|
||||
"created_at_utc": _utc_now(),
|
||||
"acceptance_state": "accepted-r0-source-scoped-contract",
|
||||
"artifacts": artifacts,
|
||||
}
|
||||
_write_json(staging / E37_MANIFEST_NAME, manifest)
|
||||
os.replace(staging, destination)
|
||||
except BaseException:
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
raise
|
||||
return read_e37_acceptance_contract(destination)
|
||||
|
||||
|
||||
def read_e37_acceptance_contract(root: Path) -> E37AcceptanceContract:
|
||||
resolved = root.resolve(strict=True)
|
||||
manifest = _read_json(resolved / E37_MANIFEST_NAME)
|
||||
identity = _object(manifest.get("identity"), "E37 identity")
|
||||
identity_sha256 = manifest.get("identity_sha256")
|
||||
if (
|
||||
manifest.get("schema_version") != E37_RESULT_SCHEMA
|
||||
or not isinstance(identity_sha256, str)
|
||||
or hashlib.sha256(_canonical_json(identity)).hexdigest() != identity_sha256
|
||||
or manifest.get("result_id") != f"e37-ravnoves-acceptance-{identity_sha256}"
|
||||
or resolved.name != manifest.get("result_id")
|
||||
or manifest.get("acceptance_state") != "accepted-r0-source-scoped-contract"
|
||||
or identity.get("authority") != _AUTHORITY
|
||||
):
|
||||
raise E37AcceptanceContractError("E37 result identity is invalid")
|
||||
artifacts = manifest.get("artifacts")
|
||||
if not isinstance(artifacts, list) or len(artifacts) != 3:
|
||||
raise E37AcceptanceContractError("E37 artifact catalog is invalid")
|
||||
expected = {
|
||||
E37_ITEMS_NAME: "reviewed-denominator",
|
||||
E37_CONTRACT_NAME: "acceptance-contract",
|
||||
E37_REPORT_NAME: "run-report",
|
||||
}
|
||||
for row in artifacts:
|
||||
if not isinstance(row, dict):
|
||||
raise E37AcceptanceContractError("E37 artifact descriptor is invalid")
|
||||
name = row.get("path")
|
||||
if name not in expected or row.get("role") != expected[name]:
|
||||
raise E37AcceptanceContractError("E37 artifact role changed")
|
||||
path = resolved / name
|
||||
if (
|
||||
not path.is_file()
|
||||
or path.is_symlink()
|
||||
or row.get("byte_length") != path.stat().st_size
|
||||
or row.get("sha256") != _sha256(path)
|
||||
):
|
||||
raise E37AcceptanceContractError("E37 artifact content changed")
|
||||
contract = _read_json(resolved / E37_CONTRACT_NAME)
|
||||
report = _read_json(resolved / E37_REPORT_NAME)
|
||||
if (
|
||||
contract.get("schema_version") != E37_CONTRACT_SCHEMA
|
||||
or report.get("schema_version") != E37_REPORT_SCHEMA
|
||||
or contract.get("result_id") != resolved.name
|
||||
or report.get("result_id") != resolved.name
|
||||
or report.get("acceptance", {}).get("accepted") is not True
|
||||
):
|
||||
raise E37AcceptanceContractError("E37 contract or report is invalid")
|
||||
return E37AcceptanceContract(
|
||||
result_id=resolved.name,
|
||||
result_root=resolved,
|
||||
manifest=manifest,
|
||||
contract=contract,
|
||||
report=report,
|
||||
)
|
||||
|
||||
|
||||
def _geometry_label(value: object) -> GeometryLabel:
|
||||
return {
|
||||
"object": "object-associated",
|
||||
"static-environment": "independent-occupied",
|
||||
"surface-or-background": "rejected-nonobject",
|
||||
"self": "rejected-nonobject",
|
||||
"insufficient-support": "insufficient-support",
|
||||
"insufficient-evidence": "unknown",
|
||||
}.get(str(value), "unknown") # type: ignore[return-value]
|
||||
|
||||
|
||||
def _severity(
|
||||
decision: dict[str, Any],
|
||||
human_disposition: str | None,
|
||||
) -> str:
|
||||
if human_disposition is not None:
|
||||
return "high"
|
||||
if decision.get("cause_code") in {"time_mismatch", "self_points"}:
|
||||
return "high"
|
||||
if decision.get("detector_assessment") == "missed-object":
|
||||
return "high"
|
||||
if decision.get("verdict") == "corrected":
|
||||
return "medium"
|
||||
return "standard"
|
||||
|
||||
|
||||
def _load_inputs(
|
||||
materialization: Path,
|
||||
engineering: Path,
|
||||
human: Path,
|
||||
profile: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
materialization_manifest = _read_json(materialization / "manifest.json")
|
||||
engineering_manifest = _read_json(engineering / "manifest.json")
|
||||
human_manifest = _read_json(human / "manifest.json")
|
||||
if (
|
||||
materialization_manifest.get("schema_version") != _MATERIALIZATION_SCHEMA
|
||||
or materialization.name != profile["source"]["materialization_id"]
|
||||
or materialization_manifest.get("result_id") != materialization.name
|
||||
or engineering_manifest.get("schema_version") != _ENGINEERING_SCHEMA
|
||||
or engineering.name != profile["source"]["engineering_generation_id"]
|
||||
or engineering_manifest.get("result_id") != engineering.name
|
||||
or human_manifest.get("schema_version") != _HUMAN_SCHEMA
|
||||
or human.name != profile["source"]["human_generation_id"]
|
||||
or human_manifest.get("result_id") != human.name
|
||||
):
|
||||
raise E37AcceptanceContractError("E37 input identity is invalid")
|
||||
materialization_index = materialization / "materialized-items.jsonl"
|
||||
engineering_decisions = engineering / "engineering-decisions.jsonl"
|
||||
human_decisions = human / "review-decisions.jsonl"
|
||||
for path in (materialization_index, engineering_decisions, human_decisions):
|
||||
if not path.is_file() or path.is_symlink():
|
||||
raise E37AcceptanceContractError("E37 input artifact is unavailable")
|
||||
materialization_rows = _read_jsonl(materialization_index)
|
||||
engineering_rows = _read_jsonl(engineering_decisions)
|
||||
human_rows = _read_jsonl(human_decisions)
|
||||
expected = int(profile["denominator"]["expected_items"])
|
||||
if (
|
||||
len(materialization_rows) != expected
|
||||
or len(engineering_rows) != expected
|
||||
or len({row.get("item_id") for row in materialization_rows}) != expected
|
||||
or len({row.get("item_id") for row in engineering_rows}) != expected
|
||||
or {row.get("item_id") for row in materialization_rows}
|
||||
!= {row.get("item_id") for row in engineering_rows}
|
||||
or {row.get("item_id") for row in human_rows}
|
||||
!= {
|
||||
row.get("item_id")
|
||||
for row in engineering_rows
|
||||
if row.get("human_exception_required") is True
|
||||
}
|
||||
):
|
||||
raise E37AcceptanceContractError("E37 reviewed denominator is incomplete")
|
||||
source_binding = materialization_manifest.get("identity", {}).get("source", {})
|
||||
if source_binding.get("source_session_id") != _SOURCE_SESSION_ID:
|
||||
raise E37AcceptanceContractError("E37 source session changed")
|
||||
return {
|
||||
"materialization_rows": materialization_rows,
|
||||
"engineering_rows": engineering_rows,
|
||||
"human_rows": human_rows,
|
||||
"bindings": {
|
||||
"materialization_id": materialization.name,
|
||||
"materialization_identity_sha256": materialization_manifest.get(
|
||||
"identity_sha256"
|
||||
),
|
||||
"materialization_manifest_sha256": _sha256(
|
||||
materialization / "manifest.json"
|
||||
),
|
||||
"materialization_index_sha256": _sha256(materialization_index),
|
||||
"engineering_generation_id": engineering.name,
|
||||
"engineering_identity_sha256": engineering_manifest.get(
|
||||
"identity_sha256"
|
||||
),
|
||||
"engineering_manifest_sha256": _sha256(engineering / "manifest.json"),
|
||||
"engineering_decisions_sha256": _sha256(engineering_decisions),
|
||||
"human_generation_id": human.name,
|
||||
"human_identity_sha256": human_manifest.get("identity_sha256"),
|
||||
"human_manifest_sha256": _sha256(human / "manifest.json"),
|
||||
"human_decisions_sha256": _sha256(human_decisions),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _validate_profile(profile: dict[str, Any]) -> None:
|
||||
source = _object(profile.get("source"), "E37 source")
|
||||
denominator = _object(profile.get("denominator"), "E37 denominator")
|
||||
split = _object(profile.get("split"), "E37 split")
|
||||
metrics = _object(profile.get("metrics"), "E37 metrics")
|
||||
authority = _object(profile.get("authority"), "E37 authority")
|
||||
ontology = _object(profile.get("ontology"), "E37 ontology")
|
||||
if (
|
||||
profile.get("schema_version") != E37_PROFILE_SCHEMA
|
||||
or profile.get("profile_id") != "e37-ravnoves00-r0-acceptance/v1"
|
||||
or source.get("session_id") != _SOURCE_SESSION_ID
|
||||
or source.get("display_name") != _SOURCE_DISPLAY_NAME
|
||||
or denominator.get("expected_items") != 486
|
||||
or split.get("strategy")
|
||||
!= "deterministic-source-stratum-range-holdout"
|
||||
or not isinstance(split.get("seed"), str)
|
||||
or not 0.1 <= float(split.get("validation_fraction", 0)) <= 0.5
|
||||
or metrics.get("presence_target") != 0.9
|
||||
or metrics.get("geometry_association_target") != 0.9
|
||||
or metrics.get("freshness_target") != 0.9
|
||||
or metrics.get("accounting_target") != 1.0
|
||||
or metrics.get("maximum_false_free_claims") != 0
|
||||
or authority != _AUTHORITY
|
||||
or sorted(ontology) != [
|
||||
"freshness",
|
||||
"geometry_association",
|
||||
"presence",
|
||||
]
|
||||
):
|
||||
raise E37AcceptanceContractError("E37 profile contract changed")
|
||||
|
||||
|
||||
def _contract_document(
|
||||
*,
|
||||
result_id: str,
|
||||
identity_sha256: str,
|
||||
profile: dict[str, Any],
|
||||
items: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
split_counts = Counter(item["split"] for item in items)
|
||||
dimensions = {
|
||||
name: Counter(item["reference"][name] for item in items)
|
||||
for name in ("presence", "geometry_association", "freshness")
|
||||
}
|
||||
return {
|
||||
"schema_version": E37_CONTRACT_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"identity_sha256": identity_sha256,
|
||||
"source_session_id": _SOURCE_SESSION_ID,
|
||||
"denominator": {
|
||||
"reviewed_items": len(items),
|
||||
"development_items": split_counts["development"],
|
||||
"validation_items": split_counts["validation"],
|
||||
"terminal_outcomes": len(items),
|
||||
"accounting_fraction": 1.0,
|
||||
},
|
||||
"split": profile["split"],
|
||||
"ontology": profile["ontology"],
|
||||
"dimension_distributions": {
|
||||
name: dict(sorted(counts.items()))
|
||||
for name, counts in dimensions.items()
|
||||
},
|
||||
"targets": profile["metrics"],
|
||||
"severity_distribution": dict(
|
||||
sorted(Counter(item["severity"] for item in items).items())
|
||||
),
|
||||
"label_provenance": {
|
||||
"engineering_items": sum(
|
||||
not item["provenance"]["human_exception"] for item in items
|
||||
),
|
||||
"human_exception_items": sum(
|
||||
item["provenance"]["human_exception"] for item in items
|
||||
),
|
||||
"independent_ground_truth": False,
|
||||
},
|
||||
"authority": _AUTHORITY,
|
||||
}
|
||||
|
||||
|
||||
def _report_document(
|
||||
*,
|
||||
result_id: str,
|
||||
identity_sha256: str,
|
||||
profile: dict[str, Any],
|
||||
items: list[dict[str, Any]],
|
||||
execution: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
split_counts = Counter(item["split"] for item in items)
|
||||
false_free_claims = sum(
|
||||
value == "free"
|
||||
for item in items
|
||||
for value in item["reference"].values()
|
||||
)
|
||||
checks = {
|
||||
"source_identity_frozen": True,
|
||||
"reviewed_denominator_complete": len(items) == 486,
|
||||
"development_validation_split_complete": (
|
||||
split_counts["development"] + split_counts["validation"] == len(items)
|
||||
and split_counts["development"] > 0
|
||||
and split_counts["validation"] > 0
|
||||
),
|
||||
"every_dimension_has_terminal_label": all(
|
||||
len(item["reference"]) == 3
|
||||
and all(isinstance(value, str) and value for value in item["reference"].values())
|
||||
for item in items
|
||||
),
|
||||
"human_exception_accounting_complete": sum(
|
||||
item["provenance"]["human_exception"] for item in items
|
||||
)
|
||||
== 2,
|
||||
"false_free_claims_zero": false_free_claims == 0,
|
||||
"authority_remains_diagnostic": True,
|
||||
}
|
||||
accepted = all(checks.values())
|
||||
return {
|
||||
"schema_version": E37_REPORT_SCHEMA,
|
||||
"result_id": result_id,
|
||||
"identity_sha256": identity_sha256,
|
||||
"status": (
|
||||
"accepted-r0-source-scoped-contract"
|
||||
if accepted
|
||||
else "rejected-r0-source-scoped-contract"
|
||||
),
|
||||
"source_session_id": _SOURCE_SESSION_ID,
|
||||
"profile_id": profile["profile_id"],
|
||||
"execution": execution,
|
||||
"metrics": {
|
||||
"reviewed_items": len(items),
|
||||
"development_items": split_counts["development"],
|
||||
"validation_items": split_counts["validation"],
|
||||
"engineering_items": len(items) - 2,
|
||||
"human_exception_items": 2,
|
||||
"terminal_outcomes": len(items),
|
||||
"accounting_fraction": 1.0,
|
||||
"false_free_claims": false_free_claims,
|
||||
},
|
||||
"acceptance": {
|
||||
"accepted": accepted,
|
||||
"checks": checks,
|
||||
"rejection_reasons": [
|
||||
name for name, passed in checks.items() if not passed
|
||||
],
|
||||
},
|
||||
"decision": {
|
||||
"r0_contract_frozen": accepted,
|
||||
"quality_target_evaluated": False,
|
||||
"next_gate": "R1 source-scoped perception quality baseline",
|
||||
},
|
||||
"limitations": [
|
||||
(
|
||||
"labels are an engineering-reviewed source-scoped substrate, "
|
||||
"not independent ground truth"
|
||||
),
|
||||
(
|
||||
"R0 freezes evaluation and does not claim that any 90 percent "
|
||||
"quality target has passed"
|
||||
),
|
||||
"RAVNOVES00 does not prove another route, camera, rig or mount",
|
||||
"navigation, command and safety authority remain false",
|
||||
],
|
||||
"authority": _AUTHORITY,
|
||||
}
|
||||
|
||||
|
||||
def _artifact(path: Path, role: str) -> dict[str, Any]:
|
||||
return {
|
||||
"role": role,
|
||||
"path": path.name,
|
||||
"byte_length": path.stat().st_size,
|
||||
"sha256": _sha256(path),
|
||||
}
|
||||
|
||||
|
||||
def _object(value: object, label: str) -> dict[str, Any]:
|
||||
if not isinstance(value, dict):
|
||||
raise E37AcceptanceContractError(f"{label} must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _read_json(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
value = json.loads(path.read_text(encoding="utf-8-sig"))
|
||||
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise E37AcceptanceContractError(f"invalid JSON: {path.name}") from exc
|
||||
return _object(value, path.name)
|
||||
|
||||
|
||||
def _read_jsonl(path: Path) -> list[dict[str, Any]]:
|
||||
rows: list[dict[str, Any]] = []
|
||||
try:
|
||||
with path.open("r", encoding="utf-8-sig") as stream:
|
||||
for line in stream:
|
||||
rows.append(_object(json.loads(line), path.name))
|
||||
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise E37AcceptanceContractError(f"invalid JSONL: {path.name}") from exc
|
||||
return rows
|
||||
|
||||
|
||||
def _write_json(path: Path, value: object) -> None:
|
||||
with path.open("x", encoding="utf-8", newline="\n") as stream:
|
||||
json.dump(value, stream, ensure_ascii=False, indent=2, sort_keys=True)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def _write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
|
||||
with path.open("x", encoding="utf-8", newline="\n") as stream:
|
||||
for row in rows:
|
||||
stream.write(
|
||||
json.dumps(
|
||||
row,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
)
|
||||
)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def _canonical_json(value: object) -> bytes:
|
||||
return json.dumps(
|
||||
value,
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
allow_nan=False,
|
||||
).encode()
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
while chunk := stream.read(1024 * 1024):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _utc_now() -> str:
|
||||
return datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
||||
Reference in New Issue
Block a user