feat(valid-detection-benchmark): combine preserved arm observations

This commit is contained in:
Marius Ciepluch
2026-11-17 17:34:49 +01:00
parent abe3f9ccd9
commit 6a71a86ee5
5 changed files with 1167 additions and 1 deletions
+293
View File
@@ -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"}