mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 10:18:18 +00:00
feat(valid-detection-benchmark): 11.3 end-to-end lifecycle with case adapter and hostile-decode retrofit
This commit is contained in:
@@ -0,0 +1,520 @@
|
||||
"""Task 11.3 conversion adapter: benchmark spend products to the core V3 replay.
|
||||
|
||||
Closes the R1 final-validation gap by converting the benchmark-owned 8.3 spend
|
||||
release plus the custodian-sealed 8.2 observations into the exact core V3 case
|
||||
graph that ``derive_scoped_replay`` scores. Every field either derives from
|
||||
real sealed observation content decoded inside the custodian boundary, the
|
||||
released label join, or the custodian-owned case-content port -- or the
|
||||
conversion refuses closed.
|
||||
|
||||
Documented derivation decisions:
|
||||
|
||||
1. Case identity convention (proven end to end by task 11.3). The committed
|
||||
8.3 label join keys ground truth by the raw population change digests and
|
||||
the core observation contract pins each ref's outcome projection to its
|
||||
case input digest, so sealed refs carry the raw identity the projection
|
||||
was sealed under while ``underlying_push_digest`` carries the same raw
|
||||
population identity. The core V3 case graph instead requires the
|
||||
``derive_case_input_digest`` wrapper over the validated evidence records,
|
||||
so the bridge rebuilds every observation ref -- component and combined --
|
||||
re-keying to that wrapper after pinning the sealed case identity, result
|
||||
digest, projection, and proof candidate.
|
||||
2. Label-blind scope resolution plus post-spend label cross-check. Scopes
|
||||
resolve through the custodian case-content port, which binds each identity
|
||||
to exactly one planned scope per arm, so the derivation never opens
|
||||
ground truth; ``derive_case_adapter_replay`` then cross-checks every
|
||||
released positive label against the port-bound scope.
|
||||
3. Corrected reviewable census. The orchestrator preflight census sets every
|
||||
scope capacity to the positive count, while core reconciliation requires
|
||||
pair/vulnerable/fixed capacities equal to the released pair structure and
|
||||
nonzero site and model capacities. The adapter recomposes the census from
|
||||
the case contents and the ordinary selection, and reviews it through the
|
||||
committed ``compose_plan_manifest`` seam.
|
||||
4. Pre-spend authority over a reconstructed head. ``authorize_evaluation``
|
||||
requires the population to be currently available, so the production
|
||||
spend stage commits the custody compare-and-swap from
|
||||
``derive_case_adapter_preparation`` while the population is available,
|
||||
and the post-spend conversion re-derives that exact preparation over the
|
||||
committed chain's prior head before binding the receipt through
|
||||
``validate_shared_spend`` against the real store.
|
||||
5. Combined arms. 8.2 derives combined observations through
|
||||
``arm_combination``. The adapter rebuilds each combined observation in
|
||||
core form from the same sealed component bytes plus the registered rule
|
||||
after proving projection policy, sources, and outcome equivalence with
|
||||
the sealed combined observation, and refuses on divergence.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
from benchmarks.valid.admission_case_graph import ( # noqa: E402
|
||||
AdmissionAdapterReason,
|
||||
AdmissionCaseAdapterRequestV1,
|
||||
_pinned_candidate,
|
||||
assert_labeled_scopes,
|
||||
case_release_graph,
|
||||
combined_arm_ids,
|
||||
combined_projection,
|
||||
combined_rule,
|
||||
component_projections,
|
||||
corrected_census,
|
||||
labeled_facts,
|
||||
planned_arm_scopes,
|
||||
refused,
|
||||
scope_resolver,
|
||||
validate_adapter_request,
|
||||
)
|
||||
from benchmarks.valid.admission_orchestrator import compose_plan_manifest
|
||||
from benchmarks.valid.admission_replay import (
|
||||
BridgedContentResolver,
|
||||
ScopedReplayRequestV1,
|
||||
derive_scoped_replay,
|
||||
)
|
||||
from benchmarks.valid.admission_spend import AdmissionSpendReleaseV1
|
||||
from benchmarks.valid.artifact_repository import (
|
||||
ArtifactActorRole,
|
||||
ArtifactReadPermission,
|
||||
ArtifactRepositoryError,
|
||||
S3ArtifactRepository,
|
||||
artifact_read_authority,
|
||||
)
|
||||
from benchmarks.valid.replacement_artifact_contract import (
|
||||
ArtifactAccessClass,
|
||||
ArtifactKind,
|
||||
ArtifactReference,
|
||||
)
|
||||
from openultrasast.core import canonical
|
||||
from openultrasast.core.canonical import ContentRef, ResolvedContent, StorageReceipt
|
||||
from openultrasast.core.custody import PopulationUseReceipt
|
||||
from openultrasast.core.evaluation_admission import (
|
||||
EvaluationAdmissionV3Error,
|
||||
authorize_evaluation,
|
||||
preflight_evaluation,
|
||||
validate_shared_spend,
|
||||
)
|
||||
from openultrasast.core.evaluation_attempt import AttemptHistoryV3
|
||||
from openultrasast.core.evaluation_authority import (
|
||||
EvaluationAdmissionManifestV3,
|
||||
derive_evaluation_admission_manifest_digest,
|
||||
derive_evaluation_admission_manifest_payload_digest,
|
||||
)
|
||||
from openultrasast.core.evaluation_measurement import ScopeKey
|
||||
from openultrasast.core.evaluation_observation import (
|
||||
ArmObservationSetV3,
|
||||
ObservationCaseRefV3,
|
||||
SealedObservationRefV3,
|
||||
decode_arm_observation_set,
|
||||
encode_arm_observation_set,
|
||||
)
|
||||
from openultrasast.core.evaluation_plan import EvaluationPlanManifestV3, PopulationCensusV3
|
||||
from openultrasast.core.evaluation_replay import EvaluationReplayV3
|
||||
from openultrasast.core.evaluation_spend import EvaluationPreparationV3
|
||||
|
||||
_ZERO = "0" * 64
|
||||
_DECODE_FAILURES = (AttributeError, KeyError, RecursionError, TypeError, UnicodeDecodeError, ValueError)
|
||||
_CORE_REFUSALS = (
|
||||
EvaluationAdmissionV3Error,
|
||||
canonical.ArtifactResolutionError,
|
||||
canonical.ArtifactValidationError,
|
||||
ValueError,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BridgedCaseGraphV1:
|
||||
"""Bridged custodian-decoded observations and raw core-form documents."""
|
||||
|
||||
decoded: dict[tuple[str, str], ArmObservationSetV3]
|
||||
documents: dict[str, ResolvedContent]
|
||||
sealed: tuple[SealedObservationRefV3, ...]
|
||||
|
||||
|
||||
def _sealed_raw(
|
||||
repository: S3ArtifactRepository,
|
||||
policy: str,
|
||||
content: ContentRef,
|
||||
expected_digest: str,
|
||||
kind: ArtifactKind,
|
||||
field: str,
|
||||
) -> bytes:
|
||||
reference = ArtifactReference(
|
||||
kind, content.content_digest, content.byte_length, expected_digest, ArtifactAccessClass.CUSTODIAN_SEALED
|
||||
)
|
||||
authority = artifact_read_authority(
|
||||
ArtifactActorRole.CUSTODIAN, (ArtifactReadPermission.CUSTODIAN_SEALED,), policy,
|
||||
expected_access_policy_digest=policy,
|
||||
)
|
||||
try:
|
||||
accepted = repository.get(
|
||||
reference, expected_kind=kind, authority=authority, expected_access_policy_digest=policy
|
||||
)
|
||||
except ArtifactRepositoryError:
|
||||
raise refused(AdmissionAdapterReason.OBSERVATIONS_UNREADABLE) from None
|
||||
payload = accepted.artifact.payload
|
||||
if type(payload) is not dict or payload.get("observation_digest") != expected_digest and payload.get("event_digest") != expected_digest:
|
||||
raise refused(AdmissionAdapterReason.OBSERVATIONS_UNREADABLE)
|
||||
document = payload.get(field)
|
||||
if type(document) is not str or not document:
|
||||
raise refused(AdmissionAdapterReason.OBSERVATIONS_UNREADABLE)
|
||||
return document.encode("utf-8")
|
||||
|
||||
|
||||
def _decode_observation(raw: bytes) -> ArmObservationSetV3:
|
||||
try:
|
||||
return decode_arm_observation_set(raw)
|
||||
except _DECODE_FAILURES:
|
||||
raise refused(AdmissionAdapterReason.OBSERVATIONS_UNREADABLE) from None
|
||||
|
||||
|
||||
def _bridged_reference(
|
||||
document: bytes, prefix: str, request: AdmissionCaseAdapterRequestV1
|
||||
) -> tuple[ContentRef, ResolvedContent]:
|
||||
digest = canonical.bytes_digest(document)
|
||||
receipt_digest = canonical.derive_storage_receipt_digest(
|
||||
store_identity=request.bridged_store_identity,
|
||||
content_digest=digest,
|
||||
byte_length=len(document),
|
||||
retention_policy_digest=request.bridged_retention_policy_digest,
|
||||
)
|
||||
reference = ContentRef(
|
||||
f"{prefix}/{digest}.json", digest, "application/json", len(document),
|
||||
request.bridged_retention_policy_digest, receipt_digest,
|
||||
)
|
||||
receipt = StorageReceipt(
|
||||
request.bridged_store_identity, digest, len(document),
|
||||
request.bridged_retention_policy_digest, receipt_digest,
|
||||
)
|
||||
return reference, ResolvedContent(document, receipt)
|
||||
|
||||
|
||||
def _core_form_combined(
|
||||
request: AdmissionCaseAdapterRequestV1,
|
||||
sealed: SealedObservationRefV3,
|
||||
observation: ArmObservationSetV3,
|
||||
decoded: dict[tuple[str, str], ArmObservationSetV3],
|
||||
resolve: Callable[[str, str, str], ScopeKey],
|
||||
) -> ArmObservationSetV3:
|
||||
"""Rebuild one combined observation over full contents, equivalence-checked."""
|
||||
rule = combined_rule(request.plan, sealed.arm_id)
|
||||
cases = []
|
||||
for reference in observation.cases:
|
||||
scope = resolve(sealed.arm_id, reference.case_input_digest, reference.underlying_push_digest)
|
||||
projections = component_projections(
|
||||
decoded, rule, sealed.input_identity_digest, reference.case_input_digest, reference.underlying_push_digest
|
||||
)
|
||||
projection = combined_projection(rule, projections)
|
||||
sealed_projection = reference.outcome_projection
|
||||
if (
|
||||
projection.policy is not sealed_projection.policy
|
||||
or projection.source_outcome_digests != sealed_projection.source_outcome_digests
|
||||
or projection.normalized_outcome != sealed_projection.normalized_outcome
|
||||
):
|
||||
raise refused(AdmissionAdapterReason.COMBINATION_DIVERGED)
|
||||
content = request.case_content(sealed.arm_id, reference.case_input_digest, scope)
|
||||
cases.append(
|
||||
ObservationCaseRefV3(
|
||||
content.case_id_digest,
|
||||
projection.case_input_digest,
|
||||
reference.underlying_push_digest,
|
||||
content.result_digest,
|
||||
projection,
|
||||
reference.proof_candidate_digest,
|
||||
)
|
||||
)
|
||||
return ArmObservationSetV3(
|
||||
observation.slot_digest, observation.arm_id, observation.input_identity_digest,
|
||||
observation.execution_identity, observation.registered_budget_digest,
|
||||
observation.configuration_digest, observation.input_read_evidence_digest,
|
||||
observation.stage_execution_evidence_digest, tuple(sorted(cases, key=_case_order)), "",
|
||||
)
|
||||
|
||||
|
||||
def _core_form_component(
|
||||
request: AdmissionCaseAdapterRequestV1,
|
||||
sealed: SealedObservationRefV3,
|
||||
observation: ArmObservationSetV3,
|
||||
resolve: Callable[[str, str, str], ScopeKey],
|
||||
) -> ArmObservationSetV3:
|
||||
"""Rebuild one component observation, re-keying cases to core wrapper digests.
|
||||
|
||||
The committed 8.3 label join keys ground truth by the raw population
|
||||
identity, so sealed component case refs carry that identity as their case
|
||||
input digest; the core V3 graph instead requires the wrapper digest
|
||||
derived from the validated evidence records. Each rebuilt ref is pinned to
|
||||
the sealed case identity and projection before the re-keying.
|
||||
"""
|
||||
from openultrasast.core.evaluation_case_outcome import derive_component_case_outcome_projection
|
||||
|
||||
cases = []
|
||||
for reference in observation.cases:
|
||||
scope = resolve(sealed.arm_id, reference.case_input_digest, reference.underlying_push_digest)
|
||||
content = request.case_content(sealed.arm_id, reference.case_input_digest, scope)
|
||||
_pinned_candidate(request, sealed.arm_id, reference.case_input_digest, scope, reference.proof_candidate_digest)
|
||||
records = tuple(item.record for item in content.evidence_inputs)
|
||||
try:
|
||||
projection = derive_component_case_outcome_projection(records)
|
||||
except ValueError:
|
||||
raise refused(AdmissionAdapterReason.CASE_CONTENT_UNBOUND) from None
|
||||
if (content.case_id_digest, content.result_digest, projection) != (
|
||||
reference.case_id_digest,
|
||||
reference.result_digest,
|
||||
reference.outcome_projection,
|
||||
):
|
||||
raise refused(AdmissionAdapterReason.CASE_CONTENT_UNBOUND)
|
||||
cases.append(
|
||||
ObservationCaseRefV3(
|
||||
content.case_id_digest,
|
||||
projection.case_input_digest,
|
||||
reference.underlying_push_digest,
|
||||
content.result_digest,
|
||||
projection,
|
||||
reference.proof_candidate_digest,
|
||||
)
|
||||
)
|
||||
return ArmObservationSetV3(
|
||||
observation.slot_digest, observation.arm_id, observation.input_identity_digest,
|
||||
observation.execution_identity, observation.registered_budget_digest,
|
||||
observation.configuration_digest, observation.input_read_evidence_digest,
|
||||
observation.stage_execution_evidence_digest, tuple(sorted(cases, key=_case_order)), "",
|
||||
)
|
||||
|
||||
|
||||
def _case_order(case: ObservationCaseRefV3) -> tuple[str, ...]:
|
||||
return (
|
||||
case.case_id_digest, case.case_input_digest, case.underlying_push_digest,
|
||||
case.result_digest, case.outcome_projection.projection_digest, case.proof_candidate_digest or "",
|
||||
)
|
||||
|
||||
|
||||
def _bridge(
|
||||
request: AdmissionCaseAdapterRequestV1, resolve: Callable[[str, str, str], ScopeKey]
|
||||
) -> BridgedCaseGraphV1:
|
||||
manifest = request.execution.admission_manifest
|
||||
assert manifest is not None
|
||||
combined = combined_arm_ids(request.plan)
|
||||
raw = {
|
||||
(sealed.arm_id, sealed.input_identity_digest): _decode_observation(
|
||||
_sealed_raw(
|
||||
request.repository,
|
||||
request.custodian_access_policy_digest,
|
||||
sealed.observation,
|
||||
sealed.observation_digest,
|
||||
ArtifactKind.OBSERVATION,
|
||||
"observation",
|
||||
)
|
||||
)
|
||||
for sealed in manifest.observations
|
||||
}
|
||||
decoded = dict(raw)
|
||||
documents: dict[str, ResolvedContent] = {}
|
||||
sealed_refs = []
|
||||
for sealed in manifest.observations:
|
||||
observation = raw[(sealed.arm_id, sealed.input_identity_digest)]
|
||||
if sealed.arm_id in combined:
|
||||
core_form = _core_form_combined(request, sealed, observation, raw, resolve)
|
||||
else:
|
||||
core_form = _core_form_component(request, sealed, observation, resolve)
|
||||
document = encode_arm_observation_set(core_form)
|
||||
reference, resolved = _bridged_reference(document, "observations/raw", request)
|
||||
documents[reference.artifact_id] = resolved
|
||||
decoded[(sealed.arm_id, sealed.input_identity_digest)] = core_form
|
||||
sealed_refs.append(
|
||||
replace(sealed, observation=reference, observation_digest=core_form.observation_digest, ref_digest="")
|
||||
)
|
||||
return BridgedCaseGraphV1(decoded, documents, tuple(sealed_refs))
|
||||
|
||||
|
||||
def _bridged_history(request: AdmissionCaseAdapterRequestV1, documents: dict[str, ResolvedContent]) -> AttemptHistoryV3:
|
||||
from openultrasast.core.evaluation_attempt import AttemptEventRefV3, decode_attempt_event
|
||||
|
||||
manifest = request.execution.admission_manifest
|
||||
assert manifest is not None
|
||||
history = manifest.attempt_history
|
||||
events = []
|
||||
for event in history.events:
|
||||
raw = _sealed_raw(
|
||||
request.repository,
|
||||
request.custodian_access_policy_digest,
|
||||
event.event,
|
||||
event.event_digest,
|
||||
ArtifactKind.WORKFLOW,
|
||||
"event",
|
||||
)
|
||||
try:
|
||||
decoded = decode_attempt_event(raw)
|
||||
except _DECODE_FAILURES:
|
||||
raise refused(AdmissionAdapterReason.OBSERVATIONS_UNREADABLE) from None
|
||||
if decoded.event_digest != event.event_digest:
|
||||
raise refused(AdmissionAdapterReason.OBSERVATIONS_UNREADABLE)
|
||||
reference, resolved = _bridged_reference(raw, "workflows/raw", request)
|
||||
documents[reference.artifact_id] = resolved
|
||||
events.append(AttemptEventRefV3(reference, event.event_digest, ""))
|
||||
return type(history)(history.population_digest, tuple(events), history.head_event_digest, "")
|
||||
|
||||
|
||||
def _committed_receipt(request: AdmissionCaseAdapterRequestV1, release: AdmissionSpendReleaseV1) -> PopulationUseReceipt:
|
||||
log = request.custody.current_log(request.population_digest)
|
||||
receipts = log.receipts
|
||||
if not receipts or receipts[-1].receipt_digest != release.custody_receipt_digest:
|
||||
raise refused(AdmissionAdapterReason.RELEASE_REFUSED)
|
||||
return receipts[-1]
|
||||
|
||||
|
||||
class _PreSpendCustodyView:
|
||||
"""Custody port restricted to the exact pre-spend head the receipt chained from.
|
||||
|
||||
``authorize_evaluation`` derives pre-spend authority and therefore requires
|
||||
the population to be currently available; the conversion runs after the
|
||||
shared custody spend has already committed the exact available-to-spent
|
||||
successor. The view reconstructs the committed chain's prior head and the
|
||||
real port still binds the receipt through ``validate_shared_spend``.
|
||||
"""
|
||||
|
||||
def __init__(self, prior) -> None:
|
||||
self._prior = prior
|
||||
|
||||
def current_log(self, population_digest: str):
|
||||
if self._prior.population_digest != population_digest:
|
||||
raise ValueError("pre-spend custody population differs from the reviewed plan")
|
||||
return self._prior
|
||||
|
||||
|
||||
def _pre_spend_view(request: AdmissionCaseAdapterRequestV1, release: AdmissionSpendReleaseV1) -> _PreSpendCustodyView:
|
||||
from openultrasast.core.custody import append_population_use, empty_population_custody_log
|
||||
|
||||
current = request.custody.current_log(request.population_digest)
|
||||
receipts = current.receipts
|
||||
if not receipts or receipts[-1].receipt_digest != release.custody_receipt_digest:
|
||||
raise refused(AdmissionAdapterReason.RELEASE_REFUSED)
|
||||
policy = request.context.evidence.custody_policy
|
||||
prior = empty_population_custody_log(current.population_digest, current.custodian_identity)
|
||||
for receipt in receipts[:-1]:
|
||||
try:
|
||||
prior = append_population_use(prior, receipt, policy)
|
||||
except (TypeError, ValueError):
|
||||
raise refused(AdmissionAdapterReason.AUTHORIZATION_REFUSED) from None
|
||||
return _PreSpendCustodyView(prior)
|
||||
|
||||
|
||||
def derive_case_adapter_preparation(request: AdmissionCaseAdapterRequestV1) -> EvaluationPreparationV3:
|
||||
"""Derive the exact pre-spend core preparation the shared custody spend commits against.
|
||||
|
||||
The custody compare-and-swap that opens the labels must chain from the
|
||||
preparation's own label-release request, so the production spend stage
|
||||
calls this seam while the population is still available. The derivation is
|
||||
label-blind: scope resolution runs through the custodian case-content port.
|
||||
"""
|
||||
|
||||
(
|
||||
validated, _resolve, _bridge, plan_manifest, resolver,
|
||||
feasibility, admission_manifest,
|
||||
) = _bridged_preparation_graph(request)
|
||||
try:
|
||||
return authorize_evaluation(
|
||||
admission_manifest, feasibility, validated.readiness, validated.context, validated.custody, resolver
|
||||
)
|
||||
except _CORE_REFUSALS:
|
||||
raise refused(AdmissionAdapterReason.AUTHORIZATION_REFUSED) from None
|
||||
|
||||
|
||||
def _bridged_preparation_graph(request: AdmissionCaseAdapterRequestV1):
|
||||
"""Derive every deterministic pre-spend root without any opened label."""
|
||||
|
||||
validated = validate_adapter_request(request)
|
||||
manifest = validated.execution.admission_manifest
|
||||
assert manifest is not None
|
||||
planned = planned_arm_scopes(validated.plan)
|
||||
resolve = scope_resolver(validated, planned)
|
||||
bridge = _bridge(validated, resolve)
|
||||
history = _bridged_history(validated, bridge.documents)
|
||||
census = corrected_census(validated, planned, bridge.decoded, resolve)
|
||||
readiness_digests = tuple(sorted(item.result_digest for item in validated.readiness))
|
||||
plan_manifest = _composed_plan_manifest(validated, manifest, census, readiness_digests)
|
||||
resolver = BridgedContentResolver(bridge.documents, validated.resolver)
|
||||
try:
|
||||
feasibility = preflight_evaluation(plan_manifest, validated.context, resolver)
|
||||
except _CORE_REFUSALS:
|
||||
raise refused(AdmissionAdapterReason.CENSUS_MISMATCH) from None
|
||||
draft = EvaluationAdmissionManifestV3(
|
||||
plan_manifest, feasibility.feasibility_digest, bridge.sealed, readiness_digests,
|
||||
manifest.custody_log_digest, history, _ZERO, validated.plan_review, _ZERO,
|
||||
)
|
||||
payload = derive_evaluation_admission_manifest_payload_digest(draft)
|
||||
admission_manifest = replace(
|
||||
draft, payload_digest=payload, review=validated.admission_review(payload)
|
||||
)
|
||||
admission_manifest = replace(
|
||||
admission_manifest, manifest_digest=derive_evaluation_admission_manifest_digest(admission_manifest)
|
||||
)
|
||||
return validated, resolve, bridge, plan_manifest, resolver, feasibility, admission_manifest
|
||||
|
||||
|
||||
def derive_case_adapter_replay(
|
||||
request: AdmissionCaseAdapterRequestV1, release: AdmissionSpendReleaseV1
|
||||
) -> EvaluationReplayV3:
|
||||
"""Convert one reviewed spend release into the scored core V3 replay."""
|
||||
|
||||
|
||||
if type(release) is not AdmissionSpendReleaseV1 or release.refusal_reason is not None or not release.released_cases:
|
||||
raise refused(AdmissionAdapterReason.RELEASE_REFUSED)
|
||||
validated, resolve, bridge, plan_manifest, resolver, feasibility, admission_manifest = (
|
||||
_bridged_preparation_graph(request)
|
||||
)
|
||||
assert_labeled_scopes(validated, planned_arm_scopes(validated.plan), labeled_facts(release))
|
||||
view = _pre_spend_view(validated, release)
|
||||
try:
|
||||
preparation = authorize_evaluation(
|
||||
admission_manifest, feasibility, validated.readiness, validated.context, view, resolver
|
||||
)
|
||||
receipt = _committed_receipt(validated, release)
|
||||
spend = validate_shared_spend(admission_manifest, preparation, receipt, validated.context, validated.custody)
|
||||
except _CORE_REFUSALS:
|
||||
raise refused(AdmissionAdapterReason.AUTHORIZATION_REFUSED) from None
|
||||
groups, v3_release = case_release_graph(
|
||||
validated, planned_arm_scopes(validated.plan), bridge.decoded, resolve, plan_manifest, admission_manifest, preparation, spend
|
||||
)
|
||||
ordered_readiness = tuple(sorted(validated.readiness, key=lambda item: item.result_digest))
|
||||
try:
|
||||
return derive_scoped_replay(
|
||||
ScopedReplayRequestV1(
|
||||
admission_manifest, feasibility, preparation, receipt, spend, v3_release, groups,
|
||||
ordered_readiness, validated.context, validated.custody, resolver, validated.aggregate,
|
||||
)
|
||||
)
|
||||
except _CORE_REFUSALS:
|
||||
raise refused(AdmissionAdapterReason.RELEASE_REFUSED) from None
|
||||
|
||||
|
||||
def _composed_plan_manifest(
|
||||
validated: AdmissionCaseAdapterRequestV1,
|
||||
manifest: EvaluationAdmissionManifestV3,
|
||||
census: PopulationCensusV3,
|
||||
readiness_digests: tuple[str, ...],
|
||||
) -> EvaluationPlanManifestV3:
|
||||
try:
|
||||
return compose_plan_manifest(
|
||||
validated.plan, census, readiness_digests, manifest.custody_log_digest, validated.plan_review
|
||||
)
|
||||
except ValueError:
|
||||
raise refused(AdmissionAdapterReason.CENSUS_MISMATCH) from None
|
||||
|
||||
|
||||
def bind_case_adapter_replay_stage(
|
||||
request: AdmissionCaseAdapterRequestV1,
|
||||
) -> Callable[[AdmissionSpendReleaseV1], EvaluationReplayV3]:
|
||||
"""Bind one production replay stage satisfying the run command's seam."""
|
||||
|
||||
def stage(release: AdmissionSpendReleaseV1) -> EvaluationReplayV3:
|
||||
return derive_case_adapter_replay(request, release)
|
||||
|
||||
return stage
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BridgedCaseGraphV1",
|
||||
"bind_case_adapter_replay_stage",
|
||||
"derive_case_adapter_preparation",
|
||||
"derive_case_adapter_replay",
|
||||
]
|
||||
@@ -0,0 +1,524 @@
|
||||
"""Task 11.3 custodian-side case graph over the released spend products.
|
||||
|
||||
Graph builders for the conversion adapter: the request contract, the exact
|
||||
scope assignment, and the core V3 case/release graph derivation. Every case
|
||||
field is pinned to the custodian-decoded sealed observation content and the
|
||||
released label join, or the conversion is refused closed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, replace
|
||||
from enum import StrEnum
|
||||
from typing import Protocol
|
||||
|
||||
from benchmarks.valid.admission_execution import AdmissionExecutionV1
|
||||
from benchmarks.valid.admission_spend import AdmissionSpendReleaseV1
|
||||
from benchmarks.valid.arm_contract import RegisteredEvaluationPlanV1
|
||||
from benchmarks.valid.artifact_repository import S3ArtifactRepository
|
||||
from benchmarks.valid.ecosystem_review import CanonicalEcosystem
|
||||
from benchmarks.valid.ordinary_change_contract import OrdinarySelectionV1
|
||||
from openultrasast.core.admission_case import AdmissionCaseResult
|
||||
from openultrasast.core.admission_context import AdmissionValidationContext
|
||||
from openultrasast.core.canonical import ContentResolver
|
||||
from openultrasast.core.custody import PopulationCustodyPort
|
||||
from openultrasast.core.evaluation_authority import EvaluationAdmissionManifestV3
|
||||
from openultrasast.core.evaluation_case_outcome import CaseOutcomeProjectionV3
|
||||
from openultrasast.core.evaluation_combination import CombinationRuleV3
|
||||
from openultrasast.core.evaluation_measurement import ArmKindV3, ArmScopeKey, ScopeKey
|
||||
from openultrasast.core.evaluation_observation import ArmObservationSetV3, ObservationCaseRefV3
|
||||
from openultrasast.core.evaluation_plan import (
|
||||
EcosystemOrdinaryCensusV3,
|
||||
EvaluationPlanManifestV3,
|
||||
ExactScopeCensusV3,
|
||||
PopulationCensusV3,
|
||||
derive_evaluation_census_digest,
|
||||
derive_evaluation_census_payload_digest,
|
||||
)
|
||||
from openultrasast.core.evaluation_release import (
|
||||
AdmissionCaseReleaseV3,
|
||||
ArmAdmissionCaseResultV3,
|
||||
ArmAdmissionCasesV3,
|
||||
ProofCandidateIdentityV3,
|
||||
ReleasedArmCaseBindingV3,
|
||||
derive_admission_case_release_digest_v3,
|
||||
derive_admission_case_release_payload_digest_v3,
|
||||
derive_released_arm_case_binding,
|
||||
)
|
||||
from openultrasast.core.evaluation_spend import EvaluationPreparationV3, EvaluationSpendBindingV3
|
||||
from openultrasast.core.factpack import IndependenceAttestation
|
||||
from openultrasast.core.readiness import ReadinessResult
|
||||
|
||||
_ZERO = "0" * 64
|
||||
_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||
_ORDINARY = "ordinary"
|
||||
ScopeResolver = Callable[[str, str, str], ScopeKey]
|
||||
|
||||
|
||||
class AdmissionAdapterReason(StrEnum):
|
||||
"""Closed refusal reasons; no caller content is serializable."""
|
||||
|
||||
INVALID_REQUEST = "invalid_request"
|
||||
RELEASE_REFUSED = "release_refused"
|
||||
OBSERVATIONS_UNREADABLE = "observations_unreadable"
|
||||
CASE_CONTENT_UNBOUND = "case_content_unbound"
|
||||
SCOPE_UNVERIFIED = "scope_unverified"
|
||||
CENSUS_MISMATCH = "census_mismatch"
|
||||
AUTHORIZATION_REFUSED = "authorization_refused"
|
||||
COMBINATION_DIVERGED = "combination_diverged"
|
||||
|
||||
|
||||
class AdmissionAdapterError(RuntimeError):
|
||||
"""Refuse one conversion step with a closed reason and no caller content."""
|
||||
|
||||
def __init__(self, reason: AdmissionAdapterReason) -> None:
|
||||
self.reason = reason
|
||||
super().__init__(f"admission_case_adapter_{reason.value}")
|
||||
|
||||
|
||||
def refused(reason: AdmissionAdapterReason) -> AdmissionAdapterError:
|
||||
return AdmissionAdapterError(reason)
|
||||
|
||||
|
||||
def require_digest(value: object) -> str:
|
||||
if type(value) is not str or _DIGEST.fullmatch(value) is None:
|
||||
raise refused(AdmissionAdapterReason.INVALID_REQUEST)
|
||||
return value
|
||||
|
||||
|
||||
class CaseContentPort(Protocol):
|
||||
"""Custodian-owned full case-content source keyed by arm, identity, scope."""
|
||||
|
||||
def __call__(self, arm_id: str, case_input_digest: str, scope: ScopeKey) -> AdmissionCaseResult: ...
|
||||
|
||||
|
||||
class ReviewFactory(Protocol):
|
||||
"""External review minting over one derived payload digest."""
|
||||
|
||||
def __call__(self, subject_digest: str) -> IndependenceAttestation: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AdmissionCaseAdapterRequestV1:
|
||||
"""Every authority the post-spend core conversion needs."""
|
||||
|
||||
repository: S3ArtifactRepository
|
||||
custodian_access_policy_digest: str
|
||||
execution: AdmissionExecutionV1
|
||||
plan: RegisteredEvaluationPlanV1
|
||||
selection: OrdinarySelectionV1
|
||||
population_digest: str
|
||||
input_count: int
|
||||
custody: PopulationCustodyPort
|
||||
resolver: ContentResolver
|
||||
context: AdmissionValidationContext
|
||||
readiness: tuple[ReadinessResult, ...]
|
||||
case_content: CaseContentPort
|
||||
proof_candidates: Callable[[str, str, ScopeKey], ProofCandidateIdentityV3 | None]
|
||||
census_review: IndependenceAttestation
|
||||
plan_review: IndependenceAttestation
|
||||
admission_review: ReviewFactory
|
||||
release_review: ReviewFactory
|
||||
bridged_store_identity: str
|
||||
bridged_retention_policy_digest: str
|
||||
aggregate: bool = False
|
||||
|
||||
|
||||
def validate_adapter_request(request: object) -> AdmissionCaseAdapterRequestV1:
|
||||
if (
|
||||
type(request) is not AdmissionCaseAdapterRequestV1
|
||||
or type(request.repository) is not S3ArtifactRepository
|
||||
or type(request.execution) is not AdmissionExecutionV1
|
||||
or type(request.plan) is not RegisteredEvaluationPlanV1
|
||||
or type(request.selection) is not OrdinarySelectionV1
|
||||
or type(request.context) is not AdmissionValidationContext
|
||||
or type(request.census_review) is not IndependenceAttestation
|
||||
or type(request.plan_review) is not IndependenceAttestation
|
||||
or not callable(request.release_review)
|
||||
or not callable(request.admission_review)
|
||||
or not callable(request.case_content)
|
||||
or not callable(request.proof_candidates)
|
||||
or not callable(getattr(request.custody, "current_log", None))
|
||||
or type(request.readiness) is not tuple
|
||||
or not request.readiness
|
||||
or type(request.input_count) is not int
|
||||
or request.input_count < 1
|
||||
or request.execution.refusal_reason is not None
|
||||
or request.execution.admission_manifest is None
|
||||
or request.execution.spend_authorization is None
|
||||
or request.execution.spend_authorization.may_spend is not True
|
||||
or type(request.bridged_store_identity) is not str
|
||||
or not request.bridged_store_identity
|
||||
):
|
||||
raise refused(AdmissionAdapterReason.INVALID_REQUEST)
|
||||
for digest in (request.population_digest, request.bridged_retention_policy_digest, request.custodian_access_policy_digest):
|
||||
require_digest(digest)
|
||||
for item in request.readiness:
|
||||
if type(item) is not ReadinessResult:
|
||||
raise refused(AdmissionAdapterReason.INVALID_REQUEST)
|
||||
return request # type: ignore[return-value]
|
||||
|
||||
|
||||
def planned_arm_scopes(plan: RegisteredEvaluationPlanV1) -> dict[str, tuple[ScopeKey, ...]]:
|
||||
planned: dict[str, tuple[ScopeKey, ...]] = {}
|
||||
for row in plan.registrations:
|
||||
planned[row.arm_id] = tuple(sorted(set(row.configuration.exact_scopes)))
|
||||
return planned
|
||||
|
||||
|
||||
def combined_arm_ids(plan: RegisteredEvaluationPlanV1) -> set[str]:
|
||||
return {row.arm_id for row in plan.registrations if row.configuration.kind is ArmKindV3.COMBINED}
|
||||
|
||||
|
||||
def combined_rule(plan: RegisteredEvaluationPlanV1, arm_id: str) -> CombinationRuleV3:
|
||||
for row in plan.registrations:
|
||||
if row.arm_id == arm_id:
|
||||
rule = row.configuration.combination_rule
|
||||
if rule is None:
|
||||
raise refused(AdmissionAdapterReason.INVALID_REQUEST)
|
||||
return rule
|
||||
raise refused(AdmissionAdapterReason.INVALID_REQUEST)
|
||||
|
||||
|
||||
def labeled_facts(release: AdmissionSpendReleaseV1) -> dict[str, tuple[str, str]]:
|
||||
"""One (family, ecosystem) fact per labeled raw population identity; conflicting joins refuse.
|
||||
|
||||
The committed 8.3 join keys ground-truth labels by the raw positive change
|
||||
digests and carries that identity on each released row's underlying digest,
|
||||
so the label join resolves through the underlying population identity.
|
||||
"""
|
||||
labeled: dict[str, tuple[str, str]] = {}
|
||||
for row in release.released_cases:
|
||||
if row.role.value == _ORDINARY:
|
||||
continue
|
||||
fact = (row.family_id, row.ecosystem)
|
||||
if labeled.setdefault(row.underlying_push_digest, fact) != fact:
|
||||
raise refused(AdmissionAdapterReason.RELEASE_REFUSED)
|
||||
if not labeled:
|
||||
raise refused(AdmissionAdapterReason.RELEASE_REFUSED)
|
||||
return labeled
|
||||
|
||||
|
||||
def scope_resolver(
|
||||
request: AdmissionCaseAdapterRequestV1,
|
||||
planned: dict[str, tuple[ScopeKey, ...]],
|
||||
) -> ScopeResolver:
|
||||
"""Resolve the exact scope of one observed case through the custodian port.
|
||||
|
||||
Each custodian case content binds to exactly one planned scope per arm, so
|
||||
the resolution probes the planned scopes and refuses when no port content
|
||||
binds the identity. Positive-label facts are cross-checked separately after
|
||||
the spend; the resolution itself stays label-blind.
|
||||
"""
|
||||
|
||||
def resolve(arm_id: str, case_input_digest: str, underlying_push_digest: str) -> ScopeKey:
|
||||
for scope in planned[arm_id]:
|
||||
if _port_content(request, arm_id, case_input_digest, scope) is not None:
|
||||
return scope
|
||||
raise refused(AdmissionAdapterReason.CASE_CONTENT_UNBOUND)
|
||||
|
||||
return resolve
|
||||
|
||||
|
||||
def _port_content(request: AdmissionCaseAdapterRequestV1, arm_id: str, key: str, scope: ScopeKey):
|
||||
try:
|
||||
content = request.case_content(arm_id, key, scope)
|
||||
except KeyError:
|
||||
return None
|
||||
if content is None:
|
||||
return None
|
||||
if (content.scope.family_id, content.scope.ecosystem) != (scope.family_id, scope.ecosystem):
|
||||
return None
|
||||
return content
|
||||
|
||||
|
||||
def assert_labeled_scopes(
|
||||
request: AdmissionCaseAdapterRequestV1,
|
||||
planned: dict[str, tuple[ScopeKey, ...]],
|
||||
labeled: dict[str, tuple[str, str]],
|
||||
) -> None:
|
||||
"""Pin every released positive label to the exact scope the custodian port binds."""
|
||||
anchor_arm = next(iter(sorted(planned)))
|
||||
for raw, (family_id, ecosystem) in labeled.items():
|
||||
for scope in planned[anchor_arm]:
|
||||
if _port_content(request, anchor_arm, raw, scope) is None:
|
||||
continue
|
||||
if (scope.family_id, scope.ecosystem) != (family_id, ecosystem):
|
||||
raise refused(AdmissionAdapterReason.RELEASE_REFUSED)
|
||||
break
|
||||
else:
|
||||
raise refused(AdmissionAdapterReason.CASE_CONTENT_UNBOUND)
|
||||
|
||||
|
||||
def _pinned_candidate(
|
||||
request: AdmissionCaseAdapterRequestV1,
|
||||
arm_id: str,
|
||||
case_input_digest: str,
|
||||
scope: ScopeKey,
|
||||
sealed_candidate_digest: object,
|
||||
) -> ProofCandidateIdentityV3 | None:
|
||||
candidate = request.proof_candidates(arm_id, case_input_digest, scope)
|
||||
actual = candidate.candidate_digest if candidate is not None else None
|
||||
if actual != sealed_candidate_digest:
|
||||
raise refused(AdmissionAdapterReason.CASE_CONTENT_UNBOUND)
|
||||
return candidate
|
||||
|
||||
|
||||
def _case_result(
|
||||
arm_id: str,
|
||||
scope: ScopeKey,
|
||||
reference: ObservationCaseRefV3,
|
||||
observation: ArmObservationSetV3,
|
||||
content: AdmissionCaseResult,
|
||||
projection: CaseOutcomeProjectionV3,
|
||||
candidate: ProofCandidateIdentityV3 | None,
|
||||
) -> ArmAdmissionCaseResultV3:
|
||||
return ArmAdmissionCaseResultV3(
|
||||
ArmScopeKey(arm_id, scope),
|
||||
observation.slot_digest,
|
||||
observation.observation_digest,
|
||||
reference.underlying_push_digest,
|
||||
content.case_id_digest,
|
||||
reference.case_input_digest,
|
||||
projection,
|
||||
content.role,
|
||||
content.pair_id_digest,
|
||||
content.evidence_inputs,
|
||||
content.defect_claims,
|
||||
content.satisfactions,
|
||||
content.silence,
|
||||
candidate,
|
||||
content.proof_attachments,
|
||||
content.coverage,
|
||||
content.input_manifest,
|
||||
content.input_receipts,
|
||||
content.complexity,
|
||||
content.budget,
|
||||
content.total_reply_ms,
|
||||
content.result_digest,
|
||||
)
|
||||
|
||||
|
||||
def _pinned_content(
|
||||
request: AdmissionCaseAdapterRequestV1, arm_id: str, scope: ScopeKey, reference: ObservationCaseRefV3
|
||||
) -> AdmissionCaseResult:
|
||||
content = request.case_content(arm_id, reference.case_input_digest, scope)
|
||||
if (content.scope.family_id, content.scope.ecosystem) != (scope.family_id, scope.ecosystem):
|
||||
raise refused(AdmissionAdapterReason.RELEASE_REFUSED)
|
||||
return content
|
||||
|
||||
|
||||
def component_case(
|
||||
request: AdmissionCaseAdapterRequestV1,
|
||||
arm_id: str,
|
||||
scope: ScopeKey,
|
||||
reference: ObservationCaseRefV3,
|
||||
observation: ArmObservationSetV3,
|
||||
) -> ArmAdmissionCaseResultV3:
|
||||
"""Pin one component case to its sealed observation and label join."""
|
||||
from openultrasast.core.evaluation_case_outcome import derive_component_case_outcome_projection
|
||||
|
||||
content = _pinned_content(request, arm_id, scope, reference)
|
||||
records = tuple(item.record for item in content.evidence_inputs)
|
||||
try:
|
||||
projection = derive_component_case_outcome_projection(records)
|
||||
except ValueError:
|
||||
raise refused(AdmissionAdapterReason.CASE_CONTENT_UNBOUND) from None
|
||||
if (content.case_id_digest, content.result_digest, projection) != (
|
||||
reference.case_id_digest,
|
||||
reference.result_digest,
|
||||
reference.outcome_projection,
|
||||
):
|
||||
raise refused(AdmissionAdapterReason.CASE_CONTENT_UNBOUND)
|
||||
candidate = _pinned_candidate(request, arm_id, reference.case_input_digest, scope, reference.proof_candidate_digest)
|
||||
return _case_result(arm_id, scope, reference, observation, content, projection, candidate)
|
||||
|
||||
|
||||
def combined_projection(rule: CombinationRuleV3, projections: tuple[CaseOutcomeProjectionV3, ...]) -> CaseOutcomeProjectionV3:
|
||||
"""Derive the declarative combined projection from ordered component projections."""
|
||||
from openultrasast.core.evaluation_case_outcome import (
|
||||
CaseOutcomeProjectionPolicyV3,
|
||||
CaseOutcomeProjectionV3,
|
||||
)
|
||||
|
||||
outcomes = tuple(item.normalized_outcome for item in projections)
|
||||
for row in rule.decision_rows:
|
||||
if row.component_outcomes == outcomes:
|
||||
return CaseOutcomeProjectionV3(
|
||||
projections[0].case_input_digest,
|
||||
CaseOutcomeProjectionPolicyV3.DECLARATIVE_COMBINATION_TABLE,
|
||||
tuple(item.projection_digest for item in projections),
|
||||
row.combined_outcome,
|
||||
"",
|
||||
)
|
||||
raise refused(AdmissionAdapterReason.COMBINATION_DIVERGED)
|
||||
|
||||
|
||||
def component_projections(
|
||||
decoded: dict[tuple[str, str], ArmObservationSetV3],
|
||||
rule: CombinationRuleV3,
|
||||
input_identity_digest: str,
|
||||
case_input_digest: str,
|
||||
underlying_push_digest: str,
|
||||
) -> tuple[CaseOutcomeProjectionV3, ...]:
|
||||
"""Ordered component projections for one combined case key."""
|
||||
ordered = []
|
||||
for arm_id in rule.component_arm_ids:
|
||||
observation = decoded.get((arm_id, input_identity_digest))
|
||||
if observation is None:
|
||||
raise refused(AdmissionAdapterReason.COMBINATION_DIVERGED)
|
||||
match = next(
|
||||
(
|
||||
case.outcome_projection
|
||||
for case in observation.cases
|
||||
if case.case_input_digest == case_input_digest and case.underlying_push_digest == underlying_push_digest
|
||||
),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
raise refused(AdmissionAdapterReason.COMBINATION_DIVERGED)
|
||||
ordered.append(match)
|
||||
return tuple(ordered)
|
||||
|
||||
|
||||
def combined_case(
|
||||
request: AdmissionCaseAdapterRequestV1,
|
||||
arm_id: str,
|
||||
scope: ScopeKey,
|
||||
reference: ObservationCaseRefV3,
|
||||
observation: ArmObservationSetV3,
|
||||
projections: tuple[CaseOutcomeProjectionV3, ...],
|
||||
) -> ArmAdmissionCaseResultV3:
|
||||
"""Pin one combined case to the rule-derived projection and port content."""
|
||||
projection = combined_projection(combined_rule(request.plan, arm_id), projections)
|
||||
if projection.projection_digest != reference.outcome_projection.projection_digest:
|
||||
raise refused(AdmissionAdapterReason.COMBINATION_DIVERGED)
|
||||
content = _pinned_content(request, arm_id, scope, reference)
|
||||
if (content.case_id_digest, content.result_digest) != (reference.case_id_digest, reference.result_digest):
|
||||
raise refused(AdmissionAdapterReason.CASE_CONTENT_UNBOUND)
|
||||
candidate = _pinned_candidate(request, arm_id, reference.case_input_digest, scope, reference.proof_candidate_digest)
|
||||
return _case_result(arm_id, scope, reference, observation, content, projection, candidate)
|
||||
|
||||
|
||||
def corrected_census(
|
||||
request: AdmissionCaseAdapterRequestV1,
|
||||
planned: dict[str, tuple[ScopeKey, ...]],
|
||||
decoded: dict[tuple[str, str], ArmObservationSetV3],
|
||||
scope_of: ScopeResolver,
|
||||
) -> PopulationCensusV3:
|
||||
"""Recompose the reviewable census from the released join and case contents."""
|
||||
scopes = tuple(sorted({scope for claimed in planned.values() for scope in claimed}))
|
||||
sites: dict[ScopeKey, int] = {scope: 0 for scope in scopes}
|
||||
models: dict[ScopeKey, int] = {scope: 0 for scope in scopes}
|
||||
pairs: dict[ScopeKey, set[str]] = {scope: set() for scope in scopes}
|
||||
anchor_arm = next(iter(sorted(planned)))
|
||||
for (arm_id, _identity), observation in decoded.items():
|
||||
for reference in observation.cases:
|
||||
scope = scope_of(arm_id, reference.case_input_digest, reference.underlying_push_digest)
|
||||
content = request.case_content(arm_id, reference.case_input_digest, scope)
|
||||
if content.pair_id_digest is not None and content.role.value != _ORDINARY:
|
||||
pairs[scope].add(content.pair_id_digest)
|
||||
if arm_id == anchor_arm:
|
||||
sites[scope] += content.coverage.sites_considered
|
||||
models[scope] += sum(1 for item in content.evidence_inputs if item.model_result is not None)
|
||||
ordinary: dict[str, int] = {}
|
||||
for push in request.selection.pushes:
|
||||
ecosystem = CanonicalEcosystem(push.ecosystem).value
|
||||
ordinary[ecosystem] = ordinary.get(ecosystem, 0) + 1
|
||||
scope_rows = tuple(
|
||||
sorted(
|
||||
ExactScopeCensusV3(scope, len(pairs[scope]), len(pairs[scope]), len(pairs[scope]), sites[scope], models[scope])
|
||||
for scope in scopes
|
||||
)
|
||||
)
|
||||
ordinary_rows = tuple(EcosystemOrdinaryCensusV3(eco, ordinary[eco]) for eco in sorted(ordinary))
|
||||
draft = PopulationCensusV3(
|
||||
request.population_digest, scope_rows, ordinary_rows, request.input_count, False,
|
||||
_ZERO, request.census_review, _ZERO,
|
||||
)
|
||||
if request.census_review.subject_digest != derive_evaluation_census_payload_digest(draft):
|
||||
raise refused(AdmissionAdapterReason.CENSUS_MISMATCH)
|
||||
bound = replace(draft, payload_digest=request.census_review.subject_digest)
|
||||
return replace(bound, census_digest=derive_evaluation_census_digest(bound))
|
||||
|
||||
|
||||
def case_release_graph(
|
||||
request: AdmissionCaseAdapterRequestV1,
|
||||
planned: dict[str, tuple[ScopeKey, ...]],
|
||||
decoded: dict[tuple[str, str], ArmObservationSetV3],
|
||||
scope_of: ScopeResolver,
|
||||
plan_manifest: EvaluationPlanManifestV3,
|
||||
admission_manifest: EvaluationAdmissionManifestV3,
|
||||
preparation: EvaluationPreparationV3,
|
||||
spend: EvaluationSpendBindingV3,
|
||||
) -> tuple[tuple[ArmAdmissionCasesV3, ...], AdmissionCaseReleaseV3]:
|
||||
"""Build every planned arm's case group and the reviewed V3 release."""
|
||||
groups: list[ArmAdmissionCasesV3] = []
|
||||
bindings: list[ReleasedArmCaseBindingV3] = []
|
||||
combined = combined_arm_ids(request.plan)
|
||||
for arm_id in sorted(planned):
|
||||
cases = []
|
||||
for (owner, identity), observation in sorted(decoded.items()):
|
||||
if owner != arm_id:
|
||||
continue
|
||||
for reference in observation.cases:
|
||||
scope = scope_of(arm_id, reference.case_input_digest, reference.underlying_push_digest)
|
||||
if arm_id in combined:
|
||||
rule = combined_rule(request.plan, arm_id)
|
||||
projections = component_projections(
|
||||
decoded, rule, identity, reference.case_input_digest, reference.underlying_push_digest
|
||||
)
|
||||
cases.append(combined_case(request, arm_id, scope, reference, observation, projections))
|
||||
else:
|
||||
cases.append(component_case(request, arm_id, scope, reference, observation))
|
||||
baseline = next(item.baseline_digest for item in plan_manifest.baselines if item.arm_id == arm_id)
|
||||
ordered = tuple(sorted(cases, key=lambda item: (item.key.scope.family_id, item.key.scope.ecosystem, item.case_id_digest)))
|
||||
groups.append(ArmAdmissionCasesV3(arm_id, baseline, ordered, ""))
|
||||
bindings.extend(derive_released_arm_case_binding(case, plan_manifest) for case in ordered)
|
||||
ordered_bindings = tuple(
|
||||
sorted(
|
||||
bindings,
|
||||
key=lambda item: (item.key.arm_id, item.key.scope.family_id, item.key.scope.ecosystem, item.case_id_digest),
|
||||
)
|
||||
)
|
||||
draft = AdmissionCaseReleaseV3(
|
||||
plan_manifest.manifest_digest,
|
||||
admission_manifest.manifest_digest,
|
||||
preparation.authority.authority_digest,
|
||||
preparation.preparation_digest,
|
||||
spend.binding_digest,
|
||||
ordered_bindings,
|
||||
_ZERO,
|
||||
request.release_review(_ZERO),
|
||||
_ZERO,
|
||||
)
|
||||
payload = derive_admission_case_release_payload_digest_v3(draft)
|
||||
reviewed = replace(draft, payload_digest=payload, review=request.release_review(payload))
|
||||
release = replace(reviewed, release_digest=derive_admission_case_release_digest_v3(reviewed))
|
||||
return tuple(sorted(groups, key=lambda item: item.arm_id)), release
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AdmissionAdapterError",
|
||||
"AdmissionAdapterReason",
|
||||
"AdmissionCaseAdapterRequestV1",
|
||||
"CaseContentPort",
|
||||
"ReviewFactory",
|
||||
"assert_labeled_scopes",
|
||||
"case_release_graph",
|
||||
"combined_arm_ids",
|
||||
"combined_case",
|
||||
"combined_projection",
|
||||
"combined_rule",
|
||||
"component_case",
|
||||
"component_projections",
|
||||
"corrected_census",
|
||||
"labeled_facts",
|
||||
"planned_arm_scopes",
|
||||
"refused",
|
||||
"require_digest",
|
||||
"scope_resolver",
|
||||
"validate_adapter_request",
|
||||
]
|
||||
@@ -494,10 +494,10 @@ def join_released_cases(
|
||||
except (ValueError, RecursionError):
|
||||
raise _refused(AdmissionSpendReason.OBSERVATIONS_UNREADABLE) from None
|
||||
for case in observation.cases:
|
||||
matched: GroundTruthLabelV1 | None = index.get(case.case_input_digest)
|
||||
if case.case_input_digest in positives and matched is None:
|
||||
matched: GroundTruthLabelV1 | None = index.get(case.underlying_push_digest)
|
||||
if case.underlying_push_digest in positives and matched is None:
|
||||
raise _refused(AdmissionSpendReason.JOIN_INCOMPLETE)
|
||||
seen.add(case.case_input_digest)
|
||||
seen.add(case.underlying_push_digest)
|
||||
cases.append(
|
||||
ReleasedCaseV1(
|
||||
sealed.arm_id,
|
||||
|
||||
@@ -240,7 +240,7 @@ class S3ArtifactRepository:
|
||||
invalid = False
|
||||
try:
|
||||
accepted = accept_artifact(content, reference=reference)
|
||||
except ArtifactContractError:
|
||||
except (ArtifactContractError, RecursionError):
|
||||
invalid = True
|
||||
accepted = None
|
||||
if invalid or accepted is None:
|
||||
|
||||
@@ -8,6 +8,7 @@ replacement benchmark.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
@@ -200,14 +201,27 @@ def _unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
||||
return value
|
||||
|
||||
|
||||
def _reject_constant(name: str) -> None:
|
||||
raise ArtifactContractError(f"{name} constant is not canonical JSON")
|
||||
|
||||
|
||||
def _finite_float(text: str) -> float:
|
||||
value = float(text)
|
||||
if not math.isfinite(value):
|
||||
raise ArtifactContractError("non-finite JSON numbers are unreadable")
|
||||
return value
|
||||
|
||||
|
||||
def _decode_canonical(content: bytes, label: str) -> dict[str, object]:
|
||||
if not isinstance(content, bytes) or not content:
|
||||
raise ArtifactContractError(f"{label} bytes must be nonempty")
|
||||
try:
|
||||
decoded = json.loads(content, object_pairs_hook=_unique_object)
|
||||
decoded = json.loads(
|
||||
content, object_pairs_hook=_unique_object, parse_constant=_reject_constant, parse_float=_finite_float
|
||||
)
|
||||
except ArtifactContractError:
|
||||
raise
|
||||
except (UnicodeError, json.JSONDecodeError) as error:
|
||||
except (UnicodeError, json.JSONDecodeError, RecursionError) as error:
|
||||
raise ArtifactContractError(f"{label} bytes are unreadable") from error
|
||||
if not isinstance(decoded, dict):
|
||||
raise ArtifactContractError(f"{label} must be a canonical JSON object")
|
||||
|
||||
@@ -17,6 +17,8 @@ from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import TypeVar, cast
|
||||
|
||||
from benchmarks.valid.admission_case_adapter import bind_case_adapter_replay_stage
|
||||
from benchmarks.valid.admission_case_graph import AdmissionCaseAdapterRequestV1
|
||||
from benchmarks.valid.admission_execution import (
|
||||
AdmissionExecutionError,
|
||||
AdmissionExecutionV1,
|
||||
@@ -761,6 +763,7 @@ def _rendered(
|
||||
|
||||
__all__ = [
|
||||
"OPERATOR_COMMAND_SCHEMA",
|
||||
"AdmissionCaseAdapterRequestV1",
|
||||
"BenchmarkOperatorContextV1",
|
||||
"BenchmarkResumeRequestV1",
|
||||
"BenchmarkRunRequestV1",
|
||||
@@ -773,6 +776,7 @@ __all__ = [
|
||||
"benchmark_resume_command",
|
||||
"benchmark_run_command",
|
||||
"benchmark_status_command",
|
||||
"bind_case_adapter_replay_stage",
|
||||
"bound_operator_context",
|
||||
"validated_operator_configuration",
|
||||
]
|
||||
|
||||
@@ -12,6 +12,7 @@ labels, payloads, secrets, and customer content have no entry point.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
@@ -372,12 +373,30 @@ def _unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
||||
return value
|
||||
|
||||
|
||||
def _journal_reject_constant(name: str) -> None:
|
||||
raise WorkflowJournalError(WorkflowJournalReason.MALFORMED_CONTENT) from ValueError(f"non-canonical JSON constant: {name}")
|
||||
|
||||
|
||||
def _journal_finite_float(text: str) -> float:
|
||||
value = float(text)
|
||||
if not math.isfinite(value):
|
||||
raise WorkflowJournalError(WorkflowJournalReason.MALFORMED_CONTENT) from ValueError(f"non-finite JSON number: {text}")
|
||||
return value
|
||||
|
||||
|
||||
def _decode_canonical(content: bytes) -> dict[str, object]:
|
||||
if type(content) is not bytes or not content:
|
||||
raise WorkflowJournalError(WorkflowJournalReason.MALFORMED_CONTENT)
|
||||
try:
|
||||
decoded = json.loads(content, object_pairs_hook=_unique_object)
|
||||
except (UnicodeError, json.JSONDecodeError):
|
||||
decoded = json.loads(
|
||||
content,
|
||||
object_pairs_hook=_unique_object,
|
||||
parse_constant=_journal_reject_constant,
|
||||
parse_float=_journal_finite_float,
|
||||
)
|
||||
except WorkflowJournalError:
|
||||
raise
|
||||
except (UnicodeError, json.JSONDecodeError, RecursionError):
|
||||
raise WorkflowJournalError(WorkflowJournalReason.MALFORMED_CONTENT) from None
|
||||
if type(decoded) is not dict or canonical_json_bytes(decoded) != content:
|
||||
raise WorkflowJournalError(WorkflowJournalReason.MALFORMED_CONTENT)
|
||||
|
||||
@@ -11,6 +11,7 @@ digest over the canonical redacted projection.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
@@ -387,14 +388,38 @@ def _unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
||||
return value
|
||||
|
||||
|
||||
def _outcome_reject_constant(name: str) -> None:
|
||||
raise WorkflowOutcomeError(WorkflowOutcomeErrorReason.MALFORMED_CONTENT) from _constant_cause(name)
|
||||
|
||||
|
||||
def _outcome_finite_float(text: str) -> float:
|
||||
value = float(text)
|
||||
if not math.isfinite(value):
|
||||
raise WorkflowOutcomeError(WorkflowOutcomeErrorReason.MALFORMED_CONTENT) from _overflow_cause(text)
|
||||
return value
|
||||
|
||||
|
||||
def _constant_cause(name: str) -> ValueError:
|
||||
return ValueError(f"non-canonical JSON constant: {name}")
|
||||
|
||||
|
||||
def _overflow_cause(text: str) -> ValueError:
|
||||
return ValueError(f"non-finite JSON number: {text}")
|
||||
|
||||
|
||||
def _decode_canonical(content: bytes) -> dict[str, object]:
|
||||
if type(content) is not bytes or not content:
|
||||
raise WorkflowOutcomeError(WorkflowOutcomeErrorReason.MALFORMED_CONTENT)
|
||||
try:
|
||||
decoded = json.loads(content, object_pairs_hook=_unique_object)
|
||||
decoded = json.loads(
|
||||
content,
|
||||
object_pairs_hook=_unique_object,
|
||||
parse_constant=_outcome_reject_constant,
|
||||
parse_float=_outcome_finite_float,
|
||||
)
|
||||
except WorkflowOutcomeError:
|
||||
raise
|
||||
except (UnicodeError, json.JSONDecodeError):
|
||||
except (UnicodeError, json.JSONDecodeError, RecursionError):
|
||||
raise WorkflowOutcomeError(WorkflowOutcomeErrorReason.MALFORMED_CONTENT) from None
|
||||
if type(decoded) is not dict:
|
||||
raise WorkflowOutcomeError(WorkflowOutcomeErrorReason.MALFORMED_CONTENT)
|
||||
|
||||
Reference in New Issue
Block a user