mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
feat(valid-detection-benchmark): combine preserved arm observations
This commit is contained in:
@@ -169,7 +169,7 @@
|
||||
- Done when identity or scope changes create a new plan, the parked access-control arm cannot enter a plan, and every claimed scope has one exact core V3 policy.
|
||||
- _Requirements: 5.5, 6.1, 8.6, 9.1, 9.2, 10.4, 10.5_
|
||||
- _Boundary: Arm Registry_
|
||||
- [ ] 6.2 Preserve component observations through deterministic combination plans
|
||||
- [x] 6.2 Preserve component observations through deterministic combination plans
|
||||
- Pre-register only closed deterministic combination rules over complete component observation sets.
|
||||
- Retain each contributing component identity and result while deriving a separate combined-arm observation set without rerunning cases.
|
||||
- Prevent proof manufacture or transfer unless family, change input, packet identity, and finding-location anchor are identical.
|
||||
@@ -430,3 +430,4 @@
|
||||
- Task 5.3 gates real-population admission on a canonical report bound to exact store namespaces and a typed retention profile; negative conditional-write proofs, distinct visible versions, bound pre-deadline current/noncurrent evidence, and closed handling of null IDs, delete markers, and provider ambiguity prevent plausible-but-unsupported capability passes.
|
||||
- Task 5.4 persists one canonical AVAILABLE head and permits only its direct AVAILABLE-to-SPENT successor through capability-gated conditional writes; domain digests govern state while advancing version and ETag tokens prove storage concurrency and exact rereads before any caller may expose labels.
|
||||
- Task 6.1 delegates plan and baseline algebra exclusively to detection-core V3 while binding separate arm roles and lifecycle identity; every parked-arm factory, validator, and serializer path re-resolves an exact independently reviewed strategy-decision authority, and access control remains unconditionally excluded.
|
||||
- Task 6.2 derives closed UNION or INTERSECTION observations only from complete scope-compatible component sets, preserves every component independently, and retains proof continuity only when all anchors match and the exact proof scope belongs to the combined arm; deterministic re-derivation rejects forged or unrelated proof authority.
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
"""Pure label-blind combination of complete component observation sets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from benchmarks.valid.arm_combination_contract import (
|
||||
CombinationPlannerError,
|
||||
CombinationRuleKindV1,
|
||||
CombinationRuleRegistrationV1,
|
||||
CombinedObservationV1,
|
||||
ComponentObservationV1,
|
||||
ProofContinuityAnchorV1,
|
||||
RegisteredCombinationPlanV1,
|
||||
combined_value,
|
||||
)
|
||||
from benchmarks.valid.arm_contract import RegisteredEvaluationPlanV1, validate_registered_evaluation_plan
|
||||
from openultrasast.core import canonical
|
||||
from openultrasast.core.canonical import JsonValue
|
||||
from openultrasast.core.evaluation_case_outcome import CaseOutcomeProjectionPolicyV3, CaseOutcomeProjectionV3
|
||||
from openultrasast.core.evaluation_measurement import (
|
||||
ArmConfigurationV3,
|
||||
ArmKindV3,
|
||||
CombinationDecisionRowV3,
|
||||
CombinationRuleV3,
|
||||
NeutralOutcome,
|
||||
)
|
||||
from openultrasast.core.evaluation_observation import ArmObservationSetV3, ObservationCaseRefV3
|
||||
from openultrasast.core.factpack import ReviewIndependencePolicy
|
||||
|
||||
|
||||
def register_combination_plan(
|
||||
plan: RegisteredEvaluationPlanV1,
|
||||
registrations: tuple[CombinationRuleRegistrationV1, ...],
|
||||
*,
|
||||
strategy_review_policy: ReviewIndependencePolicy | None = None,
|
||||
strategy_resolver: canonical.ContentResolver | None = None,
|
||||
) -> RegisteredCombinationPlanV1:
|
||||
"""Pre-register the closed meaning of every core combined-arm table."""
|
||||
validate_registered_evaluation_plan(
|
||||
plan,
|
||||
strategy_review_policy=strategy_review_policy,
|
||||
strategy_resolver=strategy_resolver,
|
||||
)
|
||||
if type(registrations) is not tuple:
|
||||
raise CombinationPlannerError("rule registrations must be an exact tuple")
|
||||
ordered = tuple(sorted(registrations, key=lambda item: item.combined_arm_id))
|
||||
return RegisteredCombinationPlanV1(plan, ordered, "")
|
||||
|
||||
|
||||
def _configuration(plan: RegisteredEvaluationPlanV1, arm_id: str) -> ArmConfigurationV3:
|
||||
matches = tuple(item for item in plan.declaration.arm_configurations if item.arm_id == arm_id)
|
||||
if len(matches) != 1:
|
||||
raise CombinationPlannerError("arm is absent or ambiguous in the registered plan")
|
||||
return matches[0]
|
||||
|
||||
|
||||
def _validate_component(plan: RegisteredEvaluationPlanV1, component: ComponentObservationV1) -> None:
|
||||
component.__post_init__()
|
||||
observation = component.observation
|
||||
configuration = _configuration(plan, observation.arm_id)
|
||||
if configuration.kind is not ArmKindV3.COMPONENT:
|
||||
raise CombinationPlannerError("combined arms cannot be supplied as component observations")
|
||||
if (
|
||||
observation.configuration_digest != configuration.configuration_identity_digest
|
||||
or observation.registered_budget_digest != configuration.registered_budget_digest
|
||||
or observation.execution_identity != configuration.execution_identity
|
||||
):
|
||||
raise CombinationPlannerError("component observation differs from its registered configuration")
|
||||
slots = tuple(
|
||||
item
|
||||
for item in plan.declaration.expected_observation_slots
|
||||
if item.arm_id == observation.arm_id and item.input_identity_digest == observation.input_identity_digest
|
||||
)
|
||||
if len(slots) != 1 or observation.slot_digest != slots[0].slot_digest:
|
||||
raise CombinationPlannerError("component observation differs from its exact planned slot")
|
||||
for anchor in component.proof_anchors:
|
||||
candidate = anchor.candidate
|
||||
if candidate.scope not in configuration.exact_scopes or candidate.family_id != candidate.scope.family_id:
|
||||
raise CombinationPlannerError("proof anchor family or scope differs from its component arm")
|
||||
|
||||
|
||||
def _component_map(component: ComponentObservationV1) -> dict[tuple[str, str], ObservationCaseRefV3]:
|
||||
result = {(case.case_input_digest, case.underlying_push_digest): case for case in component.observation.cases}
|
||||
if not result or len(result) != len(component.observation.cases):
|
||||
raise CombinationPlannerError("component cases must be nonempty and unique by input and push")
|
||||
return result
|
||||
|
||||
|
||||
def _decision(rule: CombinationRuleV3, outcomes: tuple[NeutralOutcome, ...]) -> CombinationDecisionRowV3:
|
||||
matches = tuple(row for row in rule.decision_rows if row.component_outcomes == outcomes)
|
||||
if len(matches) != 1:
|
||||
raise CombinationPlannerError("registered decision row is absent or ambiguous")
|
||||
return matches[0]
|
||||
|
||||
|
||||
def _anchor_for_case(component: ComponentObservationV1, case: ObservationCaseRefV3) -> ProofContinuityAnchorV1 | None:
|
||||
if case.proof_candidate_digest is None:
|
||||
return None
|
||||
matches = tuple(anchor for anchor in component.proof_anchors if anchor.candidate.candidate_digest == case.proof_candidate_digest)
|
||||
if len(matches) > 1:
|
||||
raise CombinationPlannerError("component case has ambiguous proof continuity")
|
||||
return None if not matches else matches[0]
|
||||
|
||||
|
||||
def _continuity_key(anchor: ProofContinuityAnchorV1) -> tuple[object, ...]:
|
||||
candidate = anchor.candidate
|
||||
return (
|
||||
candidate.family_id,
|
||||
candidate.scope,
|
||||
candidate.change_input_digest,
|
||||
anchor.packet_digest,
|
||||
candidate.finding_location_digest,
|
||||
anchor.proof_reference,
|
||||
)
|
||||
|
||||
|
||||
def _retained_anchor(
|
||||
configuration: ArmConfigurationV3,
|
||||
components: tuple[ComponentObservationV1, ...],
|
||||
cases: tuple[ObservationCaseRefV3, ...],
|
||||
) -> ProofContinuityAnchorV1 | None:
|
||||
anchors = tuple(anchor for component, case in zip(components, cases, strict=True) if (anchor := _anchor_for_case(component, case)))
|
||||
if len(anchors) != len(cases) or len({_continuity_key(anchor) for anchor in anchors}) != 1:
|
||||
return None
|
||||
retained = min(anchors, key=lambda item: (item.candidate.component_arm_id, item.anchor_digest))
|
||||
candidate = retained.candidate
|
||||
if candidate.scope not in configuration.exact_scopes or candidate.family_id != candidate.scope.family_id:
|
||||
return None
|
||||
return retained
|
||||
|
||||
|
||||
def _case_sort(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 _combined_case(
|
||||
configuration: ArmConfigurationV3,
|
||||
components: tuple[ComponentObservationV1, ...],
|
||||
key: tuple[str, str],
|
||||
cases: tuple[ObservationCaseRefV3, ...],
|
||||
) -> tuple[ObservationCaseRefV3, ProofContinuityAnchorV1 | None]:
|
||||
rule = configuration.combination_rule
|
||||
if type(rule) is not CombinationRuleV3:
|
||||
raise CombinationPlannerError("combined configuration has no exact core rule")
|
||||
outcomes = tuple(item.outcome_projection.normalized_outcome for item in cases)
|
||||
decision = _decision(rule, outcomes)
|
||||
projection = CaseOutcomeProjectionV3(
|
||||
key[0],
|
||||
CaseOutcomeProjectionPolicyV3.DECLARATIVE_COMBINATION_TABLE,
|
||||
tuple(item.outcome_projection.projection_digest for item in cases),
|
||||
decision.combined_outcome,
|
||||
"",
|
||||
)
|
||||
anchor = _retained_anchor(configuration, components, cases)
|
||||
identity: dict[str, JsonValue] = {
|
||||
"combined_arm_id": configuration.arm_id,
|
||||
"case_input_digest": key[0],
|
||||
"underlying_push_digest": key[1],
|
||||
"component_case_ids": tuple(item.case_id_digest for item in cases),
|
||||
}
|
||||
result: JsonValue = {
|
||||
**identity,
|
||||
"component_result_digests": tuple(item.result_digest for item in cases),
|
||||
"outcome_projection_digest": projection.projection_digest,
|
||||
"retained_anchor_digest": None if anchor is None else anchor.anchor_digest,
|
||||
}
|
||||
combined = ObservationCaseRefV3(
|
||||
canonical.content_digest(identity),
|
||||
key[0],
|
||||
key[1],
|
||||
canonical.content_digest(result),
|
||||
projection,
|
||||
None if anchor is None else anchor.candidate.candidate_digest,
|
||||
)
|
||||
return combined, anchor
|
||||
|
||||
|
||||
def _derive_cases(
|
||||
configuration: ArmConfigurationV3,
|
||||
components: tuple[ComponentObservationV1, ...],
|
||||
) -> tuple[tuple[ObservationCaseRefV3, ...], tuple[ProofContinuityAnchorV1, ...]]:
|
||||
maps = tuple(_component_map(item) for item in components)
|
||||
keys = set(maps[0])
|
||||
if any(set(item) != keys for item in maps[1:]):
|
||||
raise CombinationPlannerError("component case sets are incomplete or mismatched")
|
||||
derived = tuple(_combined_case(configuration, components, key, tuple(item[key] for item in maps)) for key in sorted(keys))
|
||||
cases = tuple(sorted((item[0] for item in derived), key=_case_sort))
|
||||
anchors = tuple(sorted((item[1] for item in derived if item[1] is not None), key=lambda item: item.anchor_digest))
|
||||
return cases, anchors
|
||||
|
||||
|
||||
def _derive_combined_observation(
|
||||
registered: RegisteredCombinationPlanV1,
|
||||
rule_registration: CombinationRuleRegistrationV1,
|
||||
components: tuple[ComponentObservationV1, ...],
|
||||
) -> ArmObservationSetV3:
|
||||
configuration = _configuration(registered.plan, rule_registration.combined_arm_id)
|
||||
input_identity = components[0].observation.input_identity_digest
|
||||
slots = tuple(
|
||||
item
|
||||
for item in registered.plan.declaration.expected_observation_slots
|
||||
if item.arm_id == configuration.arm_id and item.input_identity_digest == input_identity
|
||||
)
|
||||
if len(slots) != 1:
|
||||
raise CombinationPlannerError("combined observation has no exact planned slot")
|
||||
cases, _ = _derive_cases(configuration, components)
|
||||
return ArmObservationSetV3(
|
||||
slots[0].slot_digest,
|
||||
configuration.arm_id,
|
||||
input_identity,
|
||||
configuration.execution_identity,
|
||||
configuration.registered_budget_digest,
|
||||
configuration.configuration_identity_digest,
|
||||
canonical.content_digest(tuple(item.observation.input_read_evidence_digest for item in components)),
|
||||
canonical.content_digest(tuple(item.observation.stage_execution_evidence_digest for item in components)),
|
||||
cases,
|
||||
"",
|
||||
)
|
||||
|
||||
|
||||
def _derive_combination(
|
||||
registered: RegisteredCombinationPlanV1,
|
||||
combined_arm_id: str,
|
||||
components: tuple[ComponentObservationV1, ...],
|
||||
) -> CombinedObservationV1:
|
||||
registrations = tuple(item for item in registered.rule_registrations if item.combined_arm_id == combined_arm_id)
|
||||
if len(registrations) != 1:
|
||||
raise CombinationPlannerError("combined arm has no unique registered rule")
|
||||
rule_registration = registrations[0]
|
||||
configuration = _configuration(registered.plan, combined_arm_id)
|
||||
rule = configuration.combination_rule
|
||||
if type(rule) is not CombinationRuleV3:
|
||||
raise CombinationPlannerError("combined arm has no exact core rule")
|
||||
if type(components) is not tuple or any(type(item) is not ComponentObservationV1 for item in components):
|
||||
raise CombinationPlannerError("components must use an exact tuple")
|
||||
ordered = tuple(sorted(components, key=lambda item: item.observation.arm_id))
|
||||
if tuple(item.observation.arm_id for item in ordered) != rule.component_arm_ids:
|
||||
raise CombinationPlannerError("component observations must cover every and only registered component")
|
||||
for item in ordered:
|
||||
_validate_component(registered.plan, item)
|
||||
if len({item.observation.input_identity_digest for item in ordered}) != 1:
|
||||
raise CombinationPlannerError("component observations belong to different planned inputs")
|
||||
combined = _derive_combined_observation(registered, rule_registration, ordered)
|
||||
cases, retained = _derive_cases(configuration, ordered)
|
||||
if combined.cases != cases:
|
||||
raise CombinationPlannerError("combined observation cases cannot be re-derived")
|
||||
return CombinedObservationV1(registered, rule_registration, ordered, combined, retained, "")
|
||||
|
||||
|
||||
def combine_observations(
|
||||
registered: RegisteredCombinationPlanV1,
|
||||
combined_arm_id: str,
|
||||
components: tuple[ComponentObservationV1, ...],
|
||||
*,
|
||||
strategy_review_policy: ReviewIndependencePolicy | None = None,
|
||||
strategy_resolver: canonical.ContentResolver | None = None,
|
||||
) -> CombinedObservationV1:
|
||||
"""Purely derive one combined observation without invoking any arm."""
|
||||
if type(registered) is not RegisteredCombinationPlanV1:
|
||||
raise CombinationPlannerError("registered combination plan must use the exact contract")
|
||||
registered.__post_init__()
|
||||
validate_registered_evaluation_plan(
|
||||
registered.plan,
|
||||
strategy_review_policy=strategy_review_policy,
|
||||
strategy_resolver=strategy_resolver,
|
||||
)
|
||||
return _derive_combination(registered, combined_arm_id, components)
|
||||
|
||||
|
||||
def validate_combined_observation(
|
||||
value: CombinedObservationV1,
|
||||
*,
|
||||
strategy_review_policy: ReviewIndependencePolicy | None = None,
|
||||
strategy_resolver: canonical.ContentResolver | None = None,
|
||||
) -> None:
|
||||
if type(value) is not CombinedObservationV1:
|
||||
raise CombinationPlannerError("combined observation must use the exact contract")
|
||||
value.__post_init__()
|
||||
expected = combine_observations(
|
||||
value.registered_plan,
|
||||
value.rule_registration.combined_arm_id,
|
||||
value.component_observations,
|
||||
strategy_review_policy=strategy_review_policy,
|
||||
strategy_resolver=strategy_resolver,
|
||||
)
|
||||
if value != expected:
|
||||
raise CombinationPlannerError("combined observation differs from deterministic re-derivation")
|
||||
|
||||
|
||||
def combined_observation_bytes(
|
||||
value: CombinedObservationV1,
|
||||
*,
|
||||
strategy_review_policy: ReviewIndependencePolicy | None = None,
|
||||
strategy_resolver: canonical.ContentResolver | None = None,
|
||||
) -> bytes:
|
||||
validate_combined_observation(
|
||||
value,
|
||||
strategy_review_policy=strategy_review_policy,
|
||||
strategy_resolver=strategy_resolver,
|
||||
)
|
||||
return canonical.canonical_bytes(combined_value(value, include_digest=True))
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CombinedObservationV1",
|
||||
"CombinationPlannerError",
|
||||
"CombinationRuleKindV1",
|
||||
"CombinationRuleRegistrationV1",
|
||||
"ComponentObservationV1",
|
||||
"ProofContinuityAnchorV1",
|
||||
"RegisteredCombinationPlanV1",
|
||||
"combine_observations",
|
||||
"combined_observation_bytes",
|
||||
"register_combination_plan",
|
||||
"validate_combined_observation",
|
||||
]
|
||||
@@ -0,0 +1,291 @@
|
||||
"""Immutable contracts for deterministic benchmark arm combination."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from itertools import product
|
||||
|
||||
from benchmarks.valid.arm_contract import RegisteredEvaluationPlanV1
|
||||
from openultrasast.core import canonical
|
||||
from openultrasast.core.canonical import JsonValue
|
||||
from openultrasast.core.evaluation_measurement import ArmConfigurationV3, ArmKindV3, CombinationRuleV3, NeutralOutcome
|
||||
from openultrasast.core.evaluation_observation import ArmObservationSetV3
|
||||
from openultrasast.core.evaluation_release import ProofCandidateIdentityV3, derive_proof_candidate_identity_digest
|
||||
|
||||
COMBINATION_REGISTRATION_SCHEMA = "openultrasast.valid-detection-benchmark.combination-registration.v1"
|
||||
COMBINATION_PLAN_SCHEMA = "openultrasast.valid-detection-benchmark.combination-plan.v1"
|
||||
PROOF_CONTINUITY_SCHEMA = "openultrasast.valid-detection-benchmark.proof-continuity-anchor.v1"
|
||||
COMPONENT_OBSERVATION_SCHEMA = "openultrasast.valid-detection-benchmark.component-observation.v1"
|
||||
COMBINED_OBSERVATION_SCHEMA = "openultrasast.valid-detection-benchmark.combined-observation.v1"
|
||||
_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||
|
||||
|
||||
class CombinationPlannerError(ValueError):
|
||||
"""A combination is incomplete, unregistered, or proof-unsafe."""
|
||||
|
||||
|
||||
class CombinationRuleKindV1(StrEnum):
|
||||
"""The only benchmark-owned combination semantics."""
|
||||
|
||||
UNION = "union"
|
||||
INTERSECTION = "intersection"
|
||||
|
||||
|
||||
def _digest(value: object, field: str) -> str:
|
||||
if type(value) is not str or _DIGEST.fullmatch(value) is None:
|
||||
raise CombinationPlannerError(f"{field} must be a full lowercase SHA-256 digest")
|
||||
return value
|
||||
|
||||
|
||||
def _bind(value: object, field: str, payload: JsonValue) -> None:
|
||||
expected = canonical.content_digest(payload)
|
||||
actual = getattr(value, field)
|
||||
if actual == "":
|
||||
object.__setattr__(value, field, expected)
|
||||
elif _digest(actual, field) != expected:
|
||||
raise CombinationPlannerError(f"{field} does not match canonical content")
|
||||
|
||||
|
||||
def _ref_value(reference: canonical.ContentRef) -> JsonValue:
|
||||
return {
|
||||
"artifact_id": reference.artifact_id,
|
||||
"content_digest": reference.content_digest,
|
||||
"media_type": reference.media_type,
|
||||
"byte_length": reference.byte_length,
|
||||
"retention_policy_digest": reference.retention_policy_digest,
|
||||
"storage_receipt_digest": reference.storage_receipt_digest,
|
||||
}
|
||||
|
||||
|
||||
def _candidate_value(candidate: ProofCandidateIdentityV3) -> JsonValue:
|
||||
return {
|
||||
"component_arm_id": candidate.component_arm_id,
|
||||
"observation_digest": candidate.observation_digest,
|
||||
"family_id": candidate.family_id,
|
||||
"scope": {"family_id": candidate.scope.family_id, "ecosystem": candidate.scope.ecosystem},
|
||||
"finding_location_digest": candidate.finding_location_digest,
|
||||
"change_input_digest": candidate.change_input_digest,
|
||||
"candidate_digest": candidate.candidate_digest,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProofContinuityAnchorV1:
|
||||
"""Non-authorizing identity needed to preserve, never create, proof continuity."""
|
||||
|
||||
candidate: ProofCandidateIdentityV3
|
||||
packet_digest: str
|
||||
proof_reference: canonical.ContentRef
|
||||
anchor_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if type(self) is not ProofContinuityAnchorV1 or type(self.candidate) is not ProofCandidateIdentityV3:
|
||||
raise CombinationPlannerError("proof anchor must use exact continuity contracts")
|
||||
self.candidate.__post_init__()
|
||||
if self.candidate.candidate_digest != derive_proof_candidate_identity_digest(self.candidate):
|
||||
raise CombinationPlannerError("proof candidate identity cannot be re-derived")
|
||||
_digest(self.packet_digest, "proof packet digest")
|
||||
if type(self.proof_reference) is not canonical.ContentRef:
|
||||
raise CombinationPlannerError("proof reference must use exact ContentRef")
|
||||
self.proof_reference.__post_init__()
|
||||
payload: JsonValue = {
|
||||
"schema_version": PROOF_CONTINUITY_SCHEMA,
|
||||
"candidate": _candidate_value(self.candidate),
|
||||
"packet_digest": self.packet_digest,
|
||||
"proof_reference": _ref_value(self.proof_reference),
|
||||
}
|
||||
_bind(self, "anchor_digest", payload)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ComponentObservationV1:
|
||||
"""One exact component observation and its non-authorizing proof anchors."""
|
||||
|
||||
observation: ArmObservationSetV3
|
||||
proof_anchors: tuple[ProofContinuityAnchorV1, ...]
|
||||
component_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if type(self) is not ComponentObservationV1 or type(self.observation) is not ArmObservationSetV3:
|
||||
raise CombinationPlannerError("component must use exact observation contracts")
|
||||
self.observation.__post_init__()
|
||||
if type(self.proof_anchors) is not tuple or any(type(item) is not ProofContinuityAnchorV1 for item in self.proof_anchors):
|
||||
raise CombinationPlannerError("proof anchors must be an exact tuple")
|
||||
for anchor in self.proof_anchors:
|
||||
anchor.__post_init__()
|
||||
if self.proof_anchors != tuple(sorted(self.proof_anchors, key=lambda item: item.anchor_digest)):
|
||||
raise CombinationPlannerError("proof anchors must use canonical order")
|
||||
if len({item.candidate.candidate_digest for item in self.proof_anchors}) != len(self.proof_anchors):
|
||||
raise CombinationPlannerError("proof anchors must identify unique candidates")
|
||||
candidates = {case.proof_candidate_digest for case in self.observation.cases if case.proof_candidate_digest}
|
||||
for anchor in self.proof_anchors:
|
||||
candidate = anchor.candidate
|
||||
if (
|
||||
candidate.component_arm_id != self.observation.arm_id
|
||||
or candidate.observation_digest != self.observation.observation_digest
|
||||
or candidate.candidate_digest not in candidates
|
||||
):
|
||||
raise CombinationPlannerError("proof anchor differs from its component observation")
|
||||
payload: JsonValue = {
|
||||
"schema_version": COMPONENT_OBSERVATION_SCHEMA,
|
||||
"observation_digest": self.observation.observation_digest,
|
||||
"proof_anchor_digests": tuple(item.anchor_digest for item in self.proof_anchors),
|
||||
}
|
||||
_bind(self, "component_digest", payload)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CombinationRuleRegistrationV1:
|
||||
combined_arm_id: str
|
||||
kind: CombinationRuleKindV1
|
||||
core_rule_digest: str
|
||||
registration_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if type(self) is not CombinationRuleRegistrationV1 or type(self.combined_arm_id) is not str or not self.combined_arm_id:
|
||||
raise CombinationPlannerError("combination registration must use exact nonempty identities")
|
||||
if type(self.kind) is not CombinationRuleKindV1:
|
||||
raise CombinationPlannerError("combination kind must use the closed enum")
|
||||
_digest(self.core_rule_digest, "core combination rule digest")
|
||||
payload: JsonValue = {
|
||||
"schema_version": COMBINATION_REGISTRATION_SCHEMA,
|
||||
"combined_arm_id": self.combined_arm_id,
|
||||
"kind": self.kind.value,
|
||||
"core_rule_digest": self.core_rule_digest,
|
||||
}
|
||||
_bind(self, "registration_digest", payload)
|
||||
|
||||
|
||||
def _expected_outcome(kind: CombinationRuleKindV1, outcomes: tuple[NeutralOutcome, ...]) -> NeutralOutcome:
|
||||
if kind is CombinationRuleKindV1.UNION:
|
||||
if NeutralOutcome.VIOLATION in outcomes:
|
||||
return NeutralOutcome.VIOLATION
|
||||
if NeutralOutcome.INDETERMINATE in outcomes:
|
||||
return NeutralOutcome.INDETERMINATE
|
||||
return NeutralOutcome.SATISFIED
|
||||
if all(item is NeutralOutcome.VIOLATION for item in outcomes):
|
||||
return NeutralOutcome.VIOLATION
|
||||
if NeutralOutcome.SATISFIED in outcomes:
|
||||
return NeutralOutcome.SATISFIED
|
||||
return NeutralOutcome.INDETERMINATE
|
||||
|
||||
|
||||
def _validate_rule_semantics(rule: CombinationRuleV3, kind: CombinationRuleKindV1) -> None:
|
||||
rule.__post_init__()
|
||||
outcomes = tuple(product(tuple(NeutralOutcome), repeat=len(rule.component_arm_ids)))
|
||||
expected = tuple((row, _expected_outcome(kind, row)) for row in outcomes)
|
||||
actual = tuple((row.component_outcomes, row.combined_outcome) for row in rule.decision_rows)
|
||||
if actual != expected:
|
||||
raise CombinationPlannerError("core decision table differs from the registered closed combination rule")
|
||||
|
||||
|
||||
def _combined_configurations(plan: RegisteredEvaluationPlanV1) -> tuple[ArmConfigurationV3, ...]:
|
||||
return tuple(row for row in plan.declaration.arm_configurations if row.kind is ArmKindV3.COMBINED)
|
||||
|
||||
|
||||
def _validate_component_scope_coverage(
|
||||
plan: RegisteredEvaluationPlanV1,
|
||||
combined: ArmConfigurationV3,
|
||||
rule: CombinationRuleV3,
|
||||
) -> None:
|
||||
configurations = {item.arm_id: item for item in plan.declaration.arm_configurations}
|
||||
for component_arm_id in rule.component_arm_ids:
|
||||
component = configurations.get(component_arm_id)
|
||||
if type(component) is not ArmConfigurationV3 or component.kind is not ArmKindV3.COMPONENT:
|
||||
raise CombinationPlannerError("combination rule must identify exact registered component arms")
|
||||
if not set(combined.exact_scopes).issubset(component.exact_scopes):
|
||||
raise CombinationPlannerError("every component arm must cover every exact combined-arm scope")
|
||||
|
||||
|
||||
def _validate_registered_rules(
|
||||
plan: RegisteredEvaluationPlanV1,
|
||||
registrations: tuple[CombinationRuleRegistrationV1, ...],
|
||||
) -> None:
|
||||
combined = _combined_configurations(plan)
|
||||
if tuple(item.arm_id for item in combined) != tuple(item.combined_arm_id for item in registrations):
|
||||
raise CombinationPlannerError("rule registrations must cover every and only combined arm")
|
||||
for configuration, registration in zip(combined, registrations, strict=True):
|
||||
rule = configuration.combination_rule
|
||||
if type(rule) is not CombinationRuleV3 or rule.rule_digest != registration.core_rule_digest:
|
||||
raise CombinationPlannerError("registered rule differs from the core plan")
|
||||
_validate_rule_semantics(rule, registration.kind)
|
||||
_validate_component_scope_coverage(plan, configuration, rule)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RegisteredCombinationPlanV1:
|
||||
plan: RegisteredEvaluationPlanV1
|
||||
rule_registrations: tuple[CombinationRuleRegistrationV1, ...]
|
||||
combination_plan_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if type(self) is not RegisteredCombinationPlanV1 or type(self.plan) is not RegisteredEvaluationPlanV1:
|
||||
raise CombinationPlannerError("combination plan must use exact registry contracts")
|
||||
self.plan.__post_init__()
|
||||
if type(self.rule_registrations) is not tuple or any(
|
||||
type(item) is not CombinationRuleRegistrationV1 for item in self.rule_registrations
|
||||
):
|
||||
raise CombinationPlannerError("rule registrations must be an exact tuple")
|
||||
for item in self.rule_registrations:
|
||||
item.__post_init__()
|
||||
if self.rule_registrations != tuple(sorted(self.rule_registrations, key=lambda item: item.combined_arm_id)):
|
||||
raise CombinationPlannerError("rule registrations must use canonical arm order")
|
||||
_validate_registered_rules(self.plan, self.rule_registrations)
|
||||
payload: JsonValue = {
|
||||
"schema_version": COMBINATION_PLAN_SCHEMA,
|
||||
"plan_digest": self.plan.plan_digest,
|
||||
"rule_registration_digests": tuple(item.registration_digest for item in self.rule_registrations),
|
||||
}
|
||||
_bind(self, "combination_plan_digest", payload)
|
||||
|
||||
|
||||
def combined_value(value: CombinedObservationV1, *, include_digest: bool) -> dict[str, JsonValue]:
|
||||
payload: dict[str, JsonValue] = {
|
||||
"schema_version": COMBINED_OBSERVATION_SCHEMA,
|
||||
"combination_plan_digest": value.registered_plan.combination_plan_digest,
|
||||
"rule_registration_digest": value.rule_registration.registration_digest,
|
||||
"component_digests": tuple(item.component_digest for item in value.component_observations),
|
||||
"combined_observation_digest": value.combined_observation.observation_digest,
|
||||
"retained_anchor_digests": tuple(item.anchor_digest for item in value.retained_proof_anchors),
|
||||
}
|
||||
if include_digest:
|
||||
payload["combination_digest"] = value.combination_digest
|
||||
return payload
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CombinedObservationV1:
|
||||
"""Preserved components plus one separately derived combined observation."""
|
||||
|
||||
registered_plan: RegisteredCombinationPlanV1
|
||||
rule_registration: CombinationRuleRegistrationV1
|
||||
component_observations: tuple[ComponentObservationV1, ...]
|
||||
combined_observation: ArmObservationSetV3
|
||||
retained_proof_anchors: tuple[ProofContinuityAnchorV1, ...]
|
||||
combination_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if type(self) is not CombinedObservationV1 or type(self.registered_plan) is not RegisteredCombinationPlanV1:
|
||||
raise CombinationPlannerError("combined observation must use exact planner contracts")
|
||||
self.registered_plan.__post_init__()
|
||||
if type(self.rule_registration) is not CombinationRuleRegistrationV1:
|
||||
raise CombinationPlannerError("combined observation has no exact rule registration")
|
||||
self.rule_registration.__post_init__()
|
||||
if type(self.component_observations) is not tuple or any(
|
||||
type(item) is not ComponentObservationV1 for item in self.component_observations
|
||||
):
|
||||
raise CombinationPlannerError("combined components must use exact observation wrappers")
|
||||
for component in self.component_observations:
|
||||
component.__post_init__()
|
||||
if type(self.combined_observation) is not ArmObservationSetV3:
|
||||
raise CombinationPlannerError("combined result must use exact ArmObservationSetV3")
|
||||
self.combined_observation.__post_init__()
|
||||
if type(self.retained_proof_anchors) is not tuple or any(
|
||||
type(item) is not ProofContinuityAnchorV1 for item in self.retained_proof_anchors
|
||||
):
|
||||
raise CombinationPlannerError("retained proof anchors must be an exact tuple")
|
||||
for anchor in self.retained_proof_anchors:
|
||||
anchor.__post_init__()
|
||||
_bind(self, "combination_digest", combined_value(self, include_digest=False))
|
||||
@@ -0,0 +1,293 @@
|
||||
"""Factories for deterministic arm-combination contract tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from itertools import product
|
||||
|
||||
from test_valid_benchmark_arm_registry import _configuration, _digest, _registration
|
||||
|
||||
from benchmarks.valid import arm_combination as combination
|
||||
from benchmarks.valid import arm_contract as registry
|
||||
from openultrasast.core import canonical
|
||||
from openultrasast.core.evaluation_case_outcome import CaseOutcomeProjectionPolicyV3, CaseOutcomeProjectionV3
|
||||
from openultrasast.core.evaluation_measurement import (
|
||||
ArmConfigurationV3,
|
||||
ArmScopeKey,
|
||||
CombinationDecisionRowV3,
|
||||
CombinationOperatorV3,
|
||||
CombinationRuleV3,
|
||||
MetricId,
|
||||
NeutralOutcome,
|
||||
ProofCandidatePolicyV3,
|
||||
ScopeKey,
|
||||
)
|
||||
from openultrasast.core.evaluation_observation import ArmObservationSetV3, ObservationCaseRefV3
|
||||
from openultrasast.core.evaluation_plan import derive_evaluation_input_set_digest
|
||||
from openultrasast.core.evaluation_release import ProofCandidateIdentityV3, derive_proof_candidate_identity_digest
|
||||
|
||||
|
||||
def combined_outcome(kind: combination.CombinationRuleKindV1, outcomes: tuple[NeutralOutcome, ...]) -> NeutralOutcome:
|
||||
if kind is combination.CombinationRuleKindV1.UNION:
|
||||
if NeutralOutcome.VIOLATION in outcomes:
|
||||
return NeutralOutcome.VIOLATION
|
||||
if NeutralOutcome.INDETERMINATE in outcomes:
|
||||
return NeutralOutcome.INDETERMINATE
|
||||
return NeutralOutcome.SATISFIED
|
||||
if all(item is NeutralOutcome.VIOLATION for item in outcomes):
|
||||
return NeutralOutcome.VIOLATION
|
||||
if NeutralOutcome.SATISFIED in outcomes:
|
||||
return NeutralOutcome.SATISFIED
|
||||
return NeutralOutcome.INDETERMINATE
|
||||
|
||||
|
||||
def rule(kind: combination.CombinationRuleKindV1) -> CombinationRuleV3:
|
||||
arm_ids = ("arm-experimental", "arm-shipped")
|
||||
rows = tuple(
|
||||
CombinationDecisionRowV3(outcomes, combined_outcome(kind, outcomes), "") for outcomes in product(tuple(NeutralOutcome), repeat=2)
|
||||
)
|
||||
return CombinationRuleV3(
|
||||
"arm-combined",
|
||||
arm_ids,
|
||||
CombinationOperatorV3.DECLARATIVE_TABLE,
|
||||
rows,
|
||||
ProofCandidatePolicyV3.IDENTICAL_COMPONENT_ONLY,
|
||||
"",
|
||||
)
|
||||
|
||||
|
||||
def configuration_with_scopes(
|
||||
arm_id: str,
|
||||
scopes: tuple[ScopeKey, ...],
|
||||
*,
|
||||
configuration: str = "configuration",
|
||||
) -> ArmConfigurationV3:
|
||||
base = _configuration(arm_id, configuration=configuration)
|
||||
scopes = tuple(sorted(scopes))
|
||||
keys = tuple(ArmScopeKey(arm_id, scope) for scope in scopes)
|
||||
policy = base.denominator_policies[0]
|
||||
sufficiency = base.sufficiency_rules[0]
|
||||
threshold_templates = {row.metric_id: row for row in base.thresholds}
|
||||
policies = tuple(
|
||||
replace(
|
||||
policy,
|
||||
key=key,
|
||||
rules=tuple(replace(metric_rule, key=key, rule_digest="") for metric_rule in policy.rules),
|
||||
policy_digest="",
|
||||
)
|
||||
for key in keys
|
||||
)
|
||||
thresholds = tuple(replace(threshold_templates[metric], key=key, threshold_digest="") for key in keys for metric in MetricId)
|
||||
sufficiency_rules = tuple(replace(sufficiency, key=key, rule_digest="") for key in keys)
|
||||
return replace(
|
||||
base,
|
||||
exact_scopes=scopes,
|
||||
denominator_policies=policies,
|
||||
thresholds=thresholds,
|
||||
sufficiency_rules=sufficiency_rules,
|
||||
configuration_identity_digest="",
|
||||
)
|
||||
|
||||
|
||||
def plan(
|
||||
kind: combination.CombinationRuleKindV1 = combination.CombinationRuleKindV1.UNION,
|
||||
*,
|
||||
experimental_scopes: tuple[ScopeKey, ...] = (ScopeKey("injection", "python"),),
|
||||
shipped_scopes: tuple[ScopeKey, ...] = (ScopeKey("injection", "python"),),
|
||||
shipped_configuration: str = "configuration",
|
||||
) -> registry.RegisteredEvaluationPlanV1:
|
||||
combined = replace(
|
||||
_configuration("arm-combined", combined=True),
|
||||
combination_rule=rule(kind),
|
||||
configuration_identity_digest="",
|
||||
)
|
||||
registrations = (
|
||||
_registration(registry.ArmRole.COMBINED, combined),
|
||||
_registration(
|
||||
registry.ArmRole.EXPERIMENTAL,
|
||||
configuration_with_scopes("arm-experimental", experimental_scopes),
|
||||
),
|
||||
_registration(
|
||||
registry.ArmRole.SHIPPED,
|
||||
configuration_with_scopes("arm-shipped", shipped_scopes, configuration=shipped_configuration),
|
||||
),
|
||||
)
|
||||
inputs = (_digest("input-a"),)
|
||||
return registry.register_evaluation_plan(
|
||||
registrations=registrations,
|
||||
population_digest=_digest("population"),
|
||||
freeze_digest=_digest("freeze"),
|
||||
input_set_digest=derive_evaluation_input_set_digest(inputs),
|
||||
input_identity_digests=inputs,
|
||||
)
|
||||
|
||||
|
||||
def registered(
|
||||
kind: combination.CombinationRuleKindV1 = combination.CombinationRuleKindV1.UNION,
|
||||
*,
|
||||
experimental_scopes: tuple[ScopeKey, ...] = (ScopeKey("injection", "python"),),
|
||||
shipped_scopes: tuple[ScopeKey, ...] = (ScopeKey("injection", "python"),),
|
||||
shipped_configuration: str = "configuration",
|
||||
) -> combination.RegisteredCombinationPlanV1:
|
||||
registered_plan = plan(
|
||||
kind,
|
||||
experimental_scopes=experimental_scopes,
|
||||
shipped_scopes=shipped_scopes,
|
||||
shipped_configuration=shipped_configuration,
|
||||
)
|
||||
registration = combination.CombinationRuleRegistrationV1("arm-combined", kind, rule(kind).rule_digest, "")
|
||||
return combination.register_combination_plan(registered_plan, (registration,))
|
||||
|
||||
|
||||
def unchecked_registered(registered_plan: registry.RegisteredEvaluationPlanV1) -> combination.RegisteredCombinationPlanV1:
|
||||
registration = combination.CombinationRuleRegistrationV1(
|
||||
"arm-combined",
|
||||
combination.CombinationRuleKindV1.UNION,
|
||||
rule(combination.CombinationRuleKindV1.UNION).rule_digest,
|
||||
"",
|
||||
)
|
||||
value = object.__new__(combination.RegisteredCombinationPlanV1)
|
||||
object.__setattr__(value, "plan", registered_plan)
|
||||
object.__setattr__(value, "rule_registrations", (registration,))
|
||||
object.__setattr__(value, "combination_plan_digest", "")
|
||||
return value
|
||||
|
||||
|
||||
def _content_ref(label: str) -> canonical.ContentRef:
|
||||
content = label.encode()
|
||||
return canonical.ContentRef(
|
||||
f"proof-{label}",
|
||||
canonical.bytes_digest(content),
|
||||
"application/json",
|
||||
len(content),
|
||||
_digest("proof-retention"),
|
||||
_digest(f"proof-receipt-{label}"),
|
||||
)
|
||||
|
||||
|
||||
def _projection(case_input: str, outcome: NeutralOutcome, arm_id: str) -> CaseOutcomeProjectionV3:
|
||||
return CaseOutcomeProjectionV3(
|
||||
case_input,
|
||||
CaseOutcomeProjectionPolicyV3.UNANIMOUS_EVIDENCE,
|
||||
(_digest(f"source-{arm_id}-{case_input}"),),
|
||||
outcome,
|
||||
"",
|
||||
)
|
||||
|
||||
|
||||
def _candidate(
|
||||
arm_id: str,
|
||||
observation_digest: str,
|
||||
scope: ScopeKey,
|
||||
*,
|
||||
family: str,
|
||||
change: str,
|
||||
location: str,
|
||||
) -> ProofCandidateIdentityV3:
|
||||
draft = ProofCandidateIdentityV3(
|
||||
arm_id,
|
||||
observation_digest,
|
||||
family,
|
||||
scope,
|
||||
_digest(location),
|
||||
_digest(change),
|
||||
"0" * 64,
|
||||
)
|
||||
return replace(draft, candidate_digest=derive_proof_candidate_identity_digest(draft))
|
||||
|
||||
|
||||
def _observation_shell(
|
||||
registered_plan: combination.RegisteredCombinationPlanV1,
|
||||
arm_id: str,
|
||||
) -> tuple[ArmConfigurationV3, ArmObservationSetV3]:
|
||||
plan_value = registered_plan.plan
|
||||
configuration = next(row.configuration for row in plan_value.registrations if row.arm_id == arm_id)
|
||||
slot = next(row for row in plan_value.declaration.expected_observation_slots if row.arm_id == arm_id)
|
||||
observation = ArmObservationSetV3(
|
||||
slot.slot_digest,
|
||||
arm_id,
|
||||
slot.input_identity_digest,
|
||||
configuration.execution_identity,
|
||||
configuration.registered_budget_digest,
|
||||
configuration.configuration_identity_digest,
|
||||
_digest(f"read-{arm_id}"),
|
||||
_digest(f"stage-{arm_id}"),
|
||||
(),
|
||||
"",
|
||||
)
|
||||
return configuration, observation
|
||||
|
||||
|
||||
def _bind_proof(
|
||||
candidate: ProofCandidateIdentityV3,
|
||||
observation: ArmObservationSetV3,
|
||||
case: ObservationCaseRefV3,
|
||||
packet: str,
|
||||
proof_ref: str,
|
||||
) -> tuple[ArmObservationSetV3, tuple[combination.ProofContinuityAnchorV1, ...]]:
|
||||
candidate = replace(candidate, observation_digest=observation.observation_digest)
|
||||
anchor = combination.ProofContinuityAnchorV1(candidate, _digest(packet), _content_ref(proof_ref), "")
|
||||
case = replace(case, proof_candidate_digest=candidate.candidate_digest)
|
||||
observation = replace(observation, cases=(case,), observation_digest="")
|
||||
candidate = replace(candidate, observation_digest=observation.observation_digest)
|
||||
return observation, (replace(anchor, candidate=candidate, anchor_digest=""),)
|
||||
|
||||
|
||||
def component(
|
||||
registered_plan: combination.RegisteredCombinationPlanV1,
|
||||
arm_id: str,
|
||||
outcome: NeutralOutcome,
|
||||
*,
|
||||
proof: bool = False,
|
||||
family: str = "injection",
|
||||
ecosystem: str = "python",
|
||||
change: str = "change",
|
||||
packet: str = "packet",
|
||||
location: str = "location",
|
||||
proof_ref: str = "shared",
|
||||
case_input: str | None = None,
|
||||
push: str = "push",
|
||||
) -> combination.ComponentObservationV1:
|
||||
configuration, provisional = _observation_shell(registered_plan, arm_id)
|
||||
case_input = _digest("case-input") if case_input is None else case_input
|
||||
candidate_scope = next(
|
||||
(scope for scope in configuration.exact_scopes if (scope.family_id, scope.ecosystem) == (family, ecosystem)),
|
||||
configuration.exact_scopes[0],
|
||||
)
|
||||
candidate = (
|
||||
_candidate(
|
||||
arm_id,
|
||||
provisional.observation_digest,
|
||||
candidate_scope,
|
||||
family=family,
|
||||
change=change,
|
||||
location=location,
|
||||
)
|
||||
if proof
|
||||
else None
|
||||
)
|
||||
case = ObservationCaseRefV3(
|
||||
_digest(f"case-{arm_id}"),
|
||||
case_input,
|
||||
_digest(push),
|
||||
_digest(f"result-{arm_id}-{outcome.value}"),
|
||||
_projection(case_input, outcome, arm_id),
|
||||
None if candidate is None else candidate.candidate_digest,
|
||||
)
|
||||
observation = replace(provisional, cases=(case,), observation_digest="")
|
||||
anchors: tuple[combination.ProofContinuityAnchorV1, ...] = ()
|
||||
if candidate is not None:
|
||||
observation, anchors = _bind_proof(candidate, observation, case, packet, proof_ref)
|
||||
return combination.ComponentObservationV1(observation, anchors, "")
|
||||
|
||||
|
||||
def components(
|
||||
registered_plan: combination.RegisteredCombinationPlanV1,
|
||||
outcomes: tuple[NeutralOutcome, NeutralOutcome] = (NeutralOutcome.SATISFIED, NeutralOutcome.VIOLATION),
|
||||
*,
|
||||
proof: bool = False,
|
||||
) -> tuple[combination.ComponentObservationV1, ...]:
|
||||
return (
|
||||
component(registered_plan, "arm-experimental", outcomes[0], proof=proof),
|
||||
component(registered_plan, "arm-shipped", outcomes[1], proof=proof),
|
||||
)
|
||||
@@ -0,0 +1,259 @@
|
||||
"""Task 6.2 deterministic label-blind arm-combination tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from dataclasses import fields, replace
|
||||
from itertools import product
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from arm_combination_fixtures import ( # noqa: E402
|
||||
combined_outcome as _combined_outcome,
|
||||
)
|
||||
from arm_combination_fixtures import (
|
||||
component as _component,
|
||||
)
|
||||
from arm_combination_fixtures import (
|
||||
components as _components,
|
||||
)
|
||||
from arm_combination_fixtures import (
|
||||
plan as _plan,
|
||||
)
|
||||
from arm_combination_fixtures import (
|
||||
registered as _registered,
|
||||
)
|
||||
from arm_combination_fixtures import (
|
||||
rule as _rule,
|
||||
)
|
||||
from arm_combination_fixtures import (
|
||||
unchecked_registered as _unchecked_registered,
|
||||
)
|
||||
from test_valid_benchmark_arm_registry import _digest # noqa: E402
|
||||
|
||||
from benchmarks.valid import arm_combination as combination
|
||||
from openultrasast.core.evaluation_measurement import NeutralOutcome, ScopeKey
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", tuple(combination.CombinationRuleKindV1))
|
||||
@pytest.mark.parametrize("outcomes", tuple(product(tuple(NeutralOutcome), repeat=2)))
|
||||
def test_closed_rules_replay_every_outcome_deterministically(kind, outcomes) -> None:
|
||||
registered = _registered(kind)
|
||||
result = combination.combine_observations(registered, "arm-combined", _components(registered, outcomes))
|
||||
assert result.combined_observation.cases[0].outcome_projection.normalized_outcome is _combined_outcome(kind, outcomes)
|
||||
assert result.rule_registration.kind is kind
|
||||
|
||||
|
||||
def test_component_order_is_normalized_and_every_result_is_preserved() -> None:
|
||||
registered = _registered()
|
||||
components = _components(registered)
|
||||
result = combination.combine_observations(registered, "arm-combined", tuple(reversed(components)))
|
||||
assert result.component_observations == components
|
||||
assert tuple(item.observation.observation_digest for item in result.component_observations) == tuple(
|
||||
item.observation.observation_digest for item in components
|
||||
)
|
||||
assert result.combined_observation.arm_id == "arm-combined"
|
||||
assert result.combined_observation not in tuple(item.observation for item in components)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mutation",
|
||||
("missing", "duplicate", "extra", "cross_plan", "cross_observation_input", "cross_case_input", "cross_push"),
|
||||
)
|
||||
def test_missing_extra_duplicate_or_mismatched_components_are_refused(mutation: str) -> None:
|
||||
registered = _registered()
|
||||
components = _components(registered)
|
||||
if mutation == "missing":
|
||||
changed = components[:1]
|
||||
elif mutation == "duplicate":
|
||||
changed = (components[0], components[0], components[1])
|
||||
elif mutation == "extra":
|
||||
extra = replace(components[0].observation, arm_id="arm-extra", observation_digest="")
|
||||
changed = components + (combination.ComponentObservationV1(extra, (), ""),)
|
||||
elif mutation == "cross_plan":
|
||||
other = _registered(shipped_configuration="other-configuration")
|
||||
changed = (components[0], _component(other, "arm-shipped", NeutralOutcome.VIOLATION))
|
||||
elif mutation == "cross_observation_input":
|
||||
observation = replace(components[1].observation, input_identity_digest=_digest("other-input"), observation_digest="")
|
||||
changed = (components[0], combination.ComponentObservationV1(observation, (), ""))
|
||||
elif mutation == "cross_case_input":
|
||||
changed = (components[0], _component(registered, "arm-shipped", NeutralOutcome.VIOLATION, case_input=_digest("other")))
|
||||
else:
|
||||
changed = (components[0], _component(registered, "arm-shipped", NeutralOutcome.VIOLATION, push="other"))
|
||||
with pytest.raises(combination.CombinationPlannerError):
|
||||
combination.combine_observations(registered, "arm-combined", changed)
|
||||
|
||||
|
||||
def test_unregistered_or_semantically_changed_rules_are_refused() -> None:
|
||||
plan = _plan(combination.CombinationRuleKindV1.UNION)
|
||||
wrong_kind = combination.CombinationRuleRegistrationV1(
|
||||
"arm-combined",
|
||||
combination.CombinationRuleKindV1.INTERSECTION,
|
||||
next(row.configuration.combination_rule for row in plan.registrations if row.arm_id == "arm-combined").rule_digest,
|
||||
"",
|
||||
)
|
||||
with pytest.raises(combination.CombinationPlannerError):
|
||||
combination.register_combination_plan(plan, (wrong_kind,))
|
||||
with pytest.raises(combination.CombinationPlannerError):
|
||||
combination.register_combination_plan(plan, ())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing_scope", (ScopeKey("other-family", "python"), ScopeKey("injection", "javascript")))
|
||||
def test_registration_rejects_component_missing_combined_family_or_ecosystem(missing_scope: ScopeKey) -> None:
|
||||
plan = _plan(shipped_scopes=(missing_scope,))
|
||||
registration = combination.CombinationRuleRegistrationV1(
|
||||
"arm-combined", combination.CombinationRuleKindV1.UNION, _rule(combination.CombinationRuleKindV1.UNION).rule_digest, ""
|
||||
)
|
||||
with pytest.raises(combination.CombinationPlannerError):
|
||||
combination.register_combination_plan(plan, (registration,))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing_scope", (ScopeKey("other-family", "python"), ScopeKey("injection", "javascript")))
|
||||
@pytest.mark.parametrize("proof", (False, True))
|
||||
def test_constructor_bypass_cannot_combine_scope_incompatible_components(missing_scope: ScopeKey, proof: bool) -> None:
|
||||
registered = _unchecked_registered(_plan(shipped_scopes=(missing_scope,)))
|
||||
components = (
|
||||
_component(registered, "arm-experimental", NeutralOutcome.VIOLATION, proof=proof),
|
||||
_component(
|
||||
registered,
|
||||
"arm-shipped",
|
||||
NeutralOutcome.VIOLATION,
|
||||
proof=proof,
|
||||
family=missing_scope.family_id,
|
||||
ecosystem=missing_scope.ecosystem,
|
||||
),
|
||||
)
|
||||
with pytest.raises(combination.CombinationPlannerError):
|
||||
combination.combine_observations(registered, "arm-combined", components)
|
||||
|
||||
|
||||
def test_scope_configuration_is_bound_into_plan_identity() -> None:
|
||||
base = _registered()
|
||||
expanded = _registered(shipped_scopes=(ScopeKey("injection", "python"), ScopeKey("other-family", "python")))
|
||||
assert base.plan.plan_digest != expanded.plan.plan_digest
|
||||
assert base.combination_plan_digest != expanded.combination_plan_digest
|
||||
|
||||
|
||||
def test_serializer_revalidates_scope_compatibility_after_constructor_bypass() -> None:
|
||||
registered = _registered()
|
||||
valid = combination.combine_observations(registered, "arm-combined", _components(registered))
|
||||
invalid_plan = _unchecked_registered(_plan(shipped_scopes=(ScopeKey("other-family", "python"),)))
|
||||
forged = object.__new__(combination.CombinedObservationV1)
|
||||
for field in fields(combination.CombinedObservationV1):
|
||||
value = invalid_plan if field.name == "registered_plan" else getattr(valid, field.name)
|
||||
object.__setattr__(forged, field.name, value)
|
||||
with pytest.raises(combination.CombinationPlannerError):
|
||||
combination.combined_observation_bytes(forged)
|
||||
|
||||
|
||||
def test_exact_component_proof_continuity_is_retained_without_manufacture() -> None:
|
||||
registered = _registered()
|
||||
components = _components(registered, proof=True)
|
||||
result = combination.combine_observations(registered, "arm-combined", components)
|
||||
assert len(result.retained_proof_anchors) == 1
|
||||
retained = result.retained_proof_anchors[0]
|
||||
assert retained in tuple(anchor for component in components for anchor in component.proof_anchors)
|
||||
assert result.combined_observation.cases[0].proof_candidate_digest == retained.candidate.candidate_digest
|
||||
|
||||
|
||||
@pytest.mark.parametrize("extra_scope", (ScopeKey("other-family", "python"), ScopeKey("injection", "javascript")))
|
||||
def test_matching_component_only_scope_proof_is_not_retained(extra_scope: ScopeKey) -> None:
|
||||
scopes = tuple(sorted((ScopeKey("injection", "python"), extra_scope)))
|
||||
registered = _registered(experimental_scopes=scopes, shipped_scopes=scopes)
|
||||
components = (
|
||||
_component(
|
||||
registered,
|
||||
"arm-experimental",
|
||||
NeutralOutcome.VIOLATION,
|
||||
proof=True,
|
||||
family=extra_scope.family_id,
|
||||
ecosystem=extra_scope.ecosystem,
|
||||
),
|
||||
_component(
|
||||
registered,
|
||||
"arm-shipped",
|
||||
NeutralOutcome.VIOLATION,
|
||||
proof=True,
|
||||
family=extra_scope.family_id,
|
||||
ecosystem=extra_scope.ecosystem,
|
||||
),
|
||||
)
|
||||
|
||||
result = combination.combine_observations(registered, "arm-combined", components)
|
||||
|
||||
assert result.component_observations == components
|
||||
assert result.retained_proof_anchors == ()
|
||||
assert result.combined_observation.cases[0].proof_candidate_digest is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", (combination.validate_combined_observation, combination.combined_observation_bytes))
|
||||
def test_forged_unrelated_retained_anchor_is_rejected_by_rederivation(operation) -> None:
|
||||
extra_scope = ScopeKey("other-family", "python")
|
||||
scopes = tuple(sorted((ScopeKey("injection", "python"), extra_scope)))
|
||||
registered = _registered(experimental_scopes=scopes, shipped_scopes=scopes)
|
||||
components = (
|
||||
_component(registered, "arm-experimental", NeutralOutcome.VIOLATION, proof=True, family=extra_scope.family_id),
|
||||
_component(registered, "arm-shipped", NeutralOutcome.VIOLATION, proof=True, family=extra_scope.family_id),
|
||||
)
|
||||
valid = combination.combine_observations(registered, "arm-combined", components)
|
||||
anchor = components[0].proof_anchors[0]
|
||||
case = replace(valid.combined_observation.cases[0], proof_candidate_digest=anchor.candidate.candidate_digest)
|
||||
observation = replace(valid.combined_observation, cases=(case,), observation_digest="")
|
||||
forged = combination.CombinedObservationV1(
|
||||
valid.registered_plan,
|
||||
valid.rule_registration,
|
||||
valid.component_observations,
|
||||
observation,
|
||||
(anchor,),
|
||||
"",
|
||||
)
|
||||
|
||||
with pytest.raises(combination.CombinationPlannerError):
|
||||
operation(forged)
|
||||
|
||||
|
||||
def test_missing_component_proof_blocks_combined_proof_continuity() -> None:
|
||||
registered = _registered()
|
||||
components = (
|
||||
_component(registered, "arm-experimental", NeutralOutcome.VIOLATION, proof=True),
|
||||
_component(registered, "arm-shipped", NeutralOutcome.VIOLATION),
|
||||
)
|
||||
result = combination.combine_observations(registered, "arm-combined", components)
|
||||
assert result.retained_proof_anchors == ()
|
||||
assert result.combined_observation.cases[0].proof_candidate_digest is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ("family", "change", "packet", "location", "proof_ref"))
|
||||
def test_any_proof_continuity_mismatch_drops_combined_proof_authority(field: str) -> None:
|
||||
shipped_scopes = (ScopeKey("injection", "python"), ScopeKey("other-family", "python"))
|
||||
registered = _registered(shipped_scopes=shipped_scopes) if field == "family" else _registered()
|
||||
first = _component(registered, "arm-experimental", NeutralOutcome.VIOLATION, proof=True)
|
||||
kwargs = {field: f"other-{field}"}
|
||||
second = _component(registered, "arm-shipped", NeutralOutcome.VIOLATION, proof=True, **kwargs)
|
||||
result = combination.combine_observations(registered, "arm-combined", (first, second))
|
||||
assert result.retained_proof_anchors == ()
|
||||
assert result.combined_observation.cases[0].proof_candidate_digest is None
|
||||
|
||||
|
||||
def test_no_proof_candidate_remains_not_demonstrated_and_confidence_cannot_enter() -> None:
|
||||
registered = _registered()
|
||||
result = combination.combine_observations(registered, "arm-combined", _components(registered))
|
||||
assert result.retained_proof_anchors == ()
|
||||
assert result.combined_observation.cases[0].proof_candidate_digest is None
|
||||
names = {item.name for item in fields(combination.CombinedObservationV1)}
|
||||
assert names.isdisjoint({"confidence", "agreement", "demonstrated", "label", "expected_outcome"})
|
||||
encoded = combination.combined_observation_bytes(result)
|
||||
assert all(token not in encoded for token in (b"confidence", b"agreement", b"demonstrated", b"label"))
|
||||
|
||||
|
||||
def test_combined_identity_changes_with_component_result_and_api_has_no_runner_hook() -> None:
|
||||
registered = _registered()
|
||||
base = combination.combine_observations(registered, "arm-combined", _components(registered))
|
||||
changed = combination.combine_observations(
|
||||
registered, "arm-combined", _components(registered, (NeutralOutcome.SATISFIED, NeutralOutcome.SATISFIED))
|
||||
)
|
||||
assert base.combination_digest != changed.combination_digest
|
||||
assert {item.name for item in fields(combination.ComponentObservationV1)} == {"observation", "proof_anchors", "component_digest"}
|
||||
Reference in New Issue
Block a user