mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
feat(detection-core): define non-circular evaluation plans
This commit is contained in:
@@ -495,7 +495,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
|
||||
- _Requirements: 16.5, 17.1, 17.2, 19.4_
|
||||
- _Boundary: Evaluation Arm Configuration_
|
||||
- _Depends: 12.3_
|
||||
- [ ] 13.2 Build the non-circular plan declaration, baselines, and expected slots
|
||||
- [x] 13.2 Build the non-circular plan declaration, baselines, and expected slots
|
||||
- Derive the complete label-blind plan declaration before constructing per-arm baselines so the plan and baselines cannot form a digest cycle.
|
||||
- Bind each baseline to the population, freeze, input set, declaration, and exact arm configuration so any listed change creates a new baseline.
|
||||
- Define expected observation slots for every planned arm and input without including ground-truth roles or labels.
|
||||
@@ -712,6 +712,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
|
||||
- Task 12.3 established exact V3 arm/scope measurement, sufficiency, immutable arm-identity, scoped Wilson-result, and rational aggregate-weight contracts behind an acyclic public facade; all malformed public-factory inputs fail through `EvaluationMeasurementError` before arithmetic.
|
||||
- Task 12.4 reserved the exact V3 evaluation-admission identity, added closed extensible V3 contract routing, and made partial artifacts structurally non-authorizing across inheritance, wrapped aliases, and post-definition/shared-base mutation while leaving V2 routes unchanged.
|
||||
- Task 13.1 closed the arm-configuration gap by requiring at least two canonical non-self component identities for a combined arm and proving its complete finite decision table, proof-retention policy, and every configuration input remain digest-bound without executable behavior.
|
||||
- Task 13.2 established a label-blind non-circular plan declaration, an authoritative canonical input-set identity and complete arm-by-input slot product, exact component-kind lineage, and one declaration-derived baseline per arm.
|
||||
- The frozen migration inventory is a reviewed worklist with stable identities, not a semantic-use census. It may only close entries as `v2_migrated` or `retired`; it never grows, deletes entries, or proves absence by interpreting Python flow.
|
||||
- Cutover is proved by explicit syntax checks plus deletion of the compatibility and v1 write capability. No task extends the discarded alias/data-flow interpreter.
|
||||
- Task 10.5 debug established that executable owner probes cannot compensate for blanket source-closure acceptance; resumed hunt attempts also require collision-resistant attempt identity and create-only persistence before handoff validation is authoritative.
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
"""Non-circular label-blind plan identities for evaluation admission V3."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import ClassVar
|
||||
|
||||
from openultrasast.core import canonical
|
||||
from openultrasast.core.evaluation_measurement import ArmConfigurationV3, ArmKindV3
|
||||
from openultrasast.core.evaluation_version import (
|
||||
EVALUATION_ADMISSION_V3_SCHEMA,
|
||||
EvaluationV3Contract,
|
||||
NonAuthorizingV3,
|
||||
require_exact_v3_contract,
|
||||
)
|
||||
|
||||
_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||
_PLAN_VALUE_SCHEMA = "openultrasast.detection-core.evaluation-plan-value.v3"
|
||||
|
||||
|
||||
class EvaluationPlanError(ValueError):
|
||||
"""A V3 plan identity is incomplete, non-canonical, or cross-bound."""
|
||||
|
||||
|
||||
def _digest(value: object, field: str) -> str:
|
||||
if type(value) is not str or _DIGEST.fullmatch(value) is None:
|
||||
raise EvaluationPlanError(f"{field} must be a full lowercase SHA-256 digest")
|
||||
return value
|
||||
|
||||
|
||||
def _text(value: object, field: str) -> str:
|
||||
if type(value) is not str or not value:
|
||||
raise EvaluationPlanError(f"{field} must be nonempty exact text")
|
||||
return value
|
||||
|
||||
|
||||
def _value(kind: str, payload: canonical.JsonValue) -> canonical.JsonValue:
|
||||
return {"schema_version": _PLAN_VALUE_SCHEMA, "kind": kind, "payload": payload}
|
||||
|
||||
|
||||
def _bind_digest(value: object, field: str, expected: str) -> None:
|
||||
actual = getattr(value, field)
|
||||
if actual == "":
|
||||
object.__setattr__(value, field, expected)
|
||||
return
|
||||
_digest(actual, field)
|
||||
if actual != expected:
|
||||
raise EvaluationPlanError(f"{field} does not match canonical content")
|
||||
|
||||
|
||||
def _slot_id(arm_id: str, input_identity_digest: str) -> str:
|
||||
return canonical.content_digest(
|
||||
_value("expected_observation_slot_id", {"arm_id": arm_id, "input_identity_digest": input_identity_digest})
|
||||
)
|
||||
|
||||
|
||||
def _slot_payload(slot: ExpectedObservationSlotV3) -> canonical.JsonValue:
|
||||
return {
|
||||
"slot_id": slot.slot_id,
|
||||
"arm_id": slot.arm_id,
|
||||
"input_identity_digest": slot.input_identity_digest,
|
||||
"execution_identity": slot.execution_identity,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExpectedObservationSlotV3(EvaluationV3Contract, NonAuthorizingV3):
|
||||
"""One label-blind arm/input execution expected by the reviewed plan."""
|
||||
|
||||
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
|
||||
slot_id: str
|
||||
arm_id: str
|
||||
input_identity_digest: str
|
||||
execution_identity: str
|
||||
slot_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
require_exact_v3_contract(self, ExpectedObservationSlotV3, field="expected observation slot")
|
||||
_text(self.arm_id, "slot arm_id")
|
||||
_digest(self.input_identity_digest, "slot input identity digest")
|
||||
_text(self.execution_identity, "slot execution identity")
|
||||
if self.slot_id != _slot_id(self.arm_id, self.input_identity_digest):
|
||||
raise EvaluationPlanError("slot_id does not match the canonical arm/input identity")
|
||||
_bind_digest(self, "slot_digest", canonical.content_digest(_value("expected_observation_slot", _slot_payload(self))))
|
||||
|
||||
|
||||
def _declaration_payload(value: EvaluationPlanDeclarationV3) -> canonical.JsonValue:
|
||||
return {
|
||||
"population_digest": value.population_digest,
|
||||
"freeze_digest": value.freeze_digest,
|
||||
"input_set_digest": value.input_set_digest,
|
||||
"arm_configuration_digests": tuple(row.configuration_identity_digest for row in value.arm_configurations),
|
||||
"expected_observation_slot_digests": tuple(row.slot_digest for row in value.expected_observation_slots),
|
||||
}
|
||||
|
||||
|
||||
def _canonical_configurations(value: object) -> tuple[ArmConfigurationV3, ...]:
|
||||
if type(value) is not tuple or not value or any(type(row) is not ArmConfigurationV3 for row in value):
|
||||
raise EvaluationPlanError("arm configurations must be a nonempty tuple of exact ArmConfigurationV3 values")
|
||||
rows = value
|
||||
if rows != tuple(sorted(rows, key=lambda row: row.arm_id)):
|
||||
raise EvaluationPlanError("arm configurations must use canonical arm order")
|
||||
arm_ids = tuple(row.arm_id for row in rows)
|
||||
if len(set(arm_ids)) != len(arm_ids):
|
||||
raise EvaluationPlanError("arm configurations must use unique arm identities")
|
||||
for row in rows:
|
||||
row.__post_init__()
|
||||
return rows
|
||||
|
||||
|
||||
def _validate_combined_components(configurations: tuple[ArmConfigurationV3, ...]) -> None:
|
||||
configurations_by_arm = {row.arm_id: row for row in configurations}
|
||||
for row in configurations:
|
||||
if row.kind is ArmKindV3.COMBINED:
|
||||
rule = row.combination_rule
|
||||
if rule is None:
|
||||
raise EvaluationPlanError("combined arm requires its validated combination rule")
|
||||
absent = set(rule.component_arm_ids) - set(configurations_by_arm)
|
||||
if absent:
|
||||
raise EvaluationPlanError("combined arm names an absent component")
|
||||
if any(configurations_by_arm[arm_id].kind is not ArmKindV3.COMPONENT for arm_id in rule.component_arm_ids):
|
||||
raise EvaluationPlanError("combined arm component identity must resolve to a component configuration")
|
||||
|
||||
|
||||
def _input_identities(slots: tuple[ExpectedObservationSlotV3, ...]) -> tuple[str, ...]:
|
||||
return tuple(sorted({row.input_identity_digest for row in slots}))
|
||||
|
||||
|
||||
def _expected_slot_keys(configurations: tuple[ArmConfigurationV3, ...], input_identities: tuple[str, ...]) -> tuple[tuple[str, str], ...]:
|
||||
return tuple((configuration.arm_id, input_digest) for configuration in configurations for input_digest in input_identities)
|
||||
|
||||
|
||||
def _validate_slots(configurations: tuple[ArmConfigurationV3, ...], slots: object) -> tuple[ExpectedObservationSlotV3, ...]:
|
||||
if type(slots) is not tuple or not slots or any(type(row) is not ExpectedObservationSlotV3 for row in slots):
|
||||
raise EvaluationPlanError("expected observation slots must be a nonempty tuple of exact slot values")
|
||||
rows = slots
|
||||
for row in rows:
|
||||
row.__post_init__()
|
||||
expected = _expected_slot_keys(configurations, _input_identities(rows))
|
||||
actual = tuple((row.arm_id, row.input_identity_digest) for row in rows)
|
||||
if actual != expected:
|
||||
raise EvaluationPlanError("expected observation slots must equal the canonical arm/input product")
|
||||
execution_by_arm = {row.arm_id: row.execution_identity for row in configurations}
|
||||
if any(row.execution_identity != execution_by_arm[row.arm_id] for row in rows):
|
||||
raise EvaluationPlanError("slot execution identity does not match its arm configuration")
|
||||
return rows
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EvaluationPlanDeclarationV3(EvaluationV3Contract, NonAuthorizingV3):
|
||||
"""Complete label-blind declaration hashed before any baseline exists."""
|
||||
|
||||
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
|
||||
population_digest: str
|
||||
freeze_digest: str
|
||||
input_set_digest: str
|
||||
arm_configurations: tuple[ArmConfigurationV3, ...]
|
||||
expected_observation_slots: tuple[ExpectedObservationSlotV3, ...]
|
||||
declaration_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
require_exact_v3_contract(self, EvaluationPlanDeclarationV3, field="evaluation plan declaration")
|
||||
_digest(self.population_digest, "population digest")
|
||||
_digest(self.freeze_digest, "freeze digest")
|
||||
_digest(self.input_set_digest, "input set digest")
|
||||
configurations = _canonical_configurations(self.arm_configurations)
|
||||
_validate_combined_components(configurations)
|
||||
slots = _validate_slots(configurations, self.expected_observation_slots)
|
||||
expected_input_set_digest = derive_evaluation_input_set_digest(_input_identities(slots))
|
||||
if self.input_set_digest != expected_input_set_digest:
|
||||
raise EvaluationPlanError("input set digest does not match the canonical slot input identities")
|
||||
_bind_digest(
|
||||
self, "declaration_digest", canonical.content_digest(_value("evaluation_plan_declaration", _declaration_payload(self)))
|
||||
)
|
||||
|
||||
|
||||
def _baseline_payload(value: EvaluationBaselineIdentityV3) -> canonical.JsonValue:
|
||||
return {
|
||||
"arm_id": value.arm_id,
|
||||
"plan_declaration_digest": value.plan_declaration_digest,
|
||||
"population_digest": value.population_digest,
|
||||
"freeze_digest": value.freeze_digest,
|
||||
"input_set_digest": value.input_set_digest,
|
||||
"arm_configuration_digest": value.arm_configuration_digest,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EvaluationBaselineIdentityV3(EvaluationV3Contract, NonAuthorizingV3):
|
||||
"""One arm baseline derived only after its declaration is complete."""
|
||||
|
||||
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
|
||||
arm_id: str
|
||||
plan_declaration_digest: str
|
||||
population_digest: str
|
||||
freeze_digest: str
|
||||
input_set_digest: str
|
||||
arm_configuration_digest: str
|
||||
baseline_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
require_exact_v3_contract(self, EvaluationBaselineIdentityV3, field="evaluation baseline identity")
|
||||
_text(self.arm_id, "baseline arm_id")
|
||||
for item, field in (
|
||||
(self.plan_declaration_digest, "plan declaration digest"),
|
||||
(self.population_digest, "baseline population digest"),
|
||||
(self.freeze_digest, "baseline freeze digest"),
|
||||
(self.input_set_digest, "baseline input set digest"),
|
||||
(self.arm_configuration_digest, "arm configuration digest"),
|
||||
):
|
||||
_digest(item, field)
|
||||
_bind_digest(self, "baseline_digest", canonical.content_digest(_value("evaluation_baseline_identity", _baseline_payload(self))))
|
||||
|
||||
|
||||
def _canonical_input_identities(value: object) -> tuple[str, ...]:
|
||||
if type(value) is not tuple or not value:
|
||||
raise EvaluationPlanError("input identities must be a nonempty tuple")
|
||||
for item in value:
|
||||
_digest(item, "input identity digest")
|
||||
if len(set(value)) != len(value):
|
||||
raise EvaluationPlanError("input identities must be unique")
|
||||
return tuple(sorted(value))
|
||||
|
||||
|
||||
def derive_evaluation_input_set_digest(input_identity_digests: tuple[str, ...]) -> str:
|
||||
"""Derive the authoritative identity of one exact label-blind input set."""
|
||||
identities = _canonical_input_identities(input_identity_digests)
|
||||
return canonical.content_digest(_value("evaluation_input_set_identity", {"input_identity_digests": identities}))
|
||||
|
||||
|
||||
def _create_slot(configuration: ArmConfigurationV3, input_digest: str) -> ExpectedObservationSlotV3:
|
||||
return ExpectedObservationSlotV3(
|
||||
_slot_id(configuration.arm_id, input_digest),
|
||||
configuration.arm_id,
|
||||
input_digest,
|
||||
configuration.execution_identity,
|
||||
"",
|
||||
)
|
||||
|
||||
|
||||
def create_evaluation_plan_declaration(
|
||||
*,
|
||||
population_digest: str,
|
||||
freeze_digest: str,
|
||||
input_set_digest: str,
|
||||
arm_configurations: tuple[ArmConfigurationV3, ...],
|
||||
input_identity_digests: tuple[str, ...],
|
||||
) -> EvaluationPlanDeclarationV3:
|
||||
"""Canonicalize caller order and construct the declaration before baselines."""
|
||||
if type(arm_configurations) is not tuple or not arm_configurations:
|
||||
raise EvaluationPlanError("arm configurations must be a nonempty tuple")
|
||||
if any(type(row) is not ArmConfigurationV3 for row in arm_configurations):
|
||||
raise EvaluationPlanError("arm configurations must use exact ArmConfigurationV3 values")
|
||||
configurations = tuple(sorted(arm_configurations, key=lambda row: row.arm_id))
|
||||
inputs = _canonical_input_identities(input_identity_digests)
|
||||
if input_set_digest != derive_evaluation_input_set_digest(inputs):
|
||||
raise EvaluationPlanError("input set digest does not match the canonical input identities")
|
||||
slots = tuple(_create_slot(configuration, input_digest) for configuration in configurations for input_digest in inputs)
|
||||
return EvaluationPlanDeclarationV3(
|
||||
population_digest,
|
||||
freeze_digest,
|
||||
input_set_digest,
|
||||
configurations,
|
||||
slots,
|
||||
"",
|
||||
)
|
||||
|
||||
|
||||
def derive_evaluation_baselines(
|
||||
declaration: EvaluationPlanDeclarationV3,
|
||||
) -> tuple[EvaluationBaselineIdentityV3, ...]:
|
||||
"""Derive one baseline per arm after validating the complete declaration."""
|
||||
require_exact_v3_contract(declaration, EvaluationPlanDeclarationV3, field="evaluation plan declaration")
|
||||
declaration.__post_init__()
|
||||
return tuple(
|
||||
EvaluationBaselineIdentityV3(
|
||||
configuration.arm_id,
|
||||
declaration.declaration_digest,
|
||||
declaration.population_digest,
|
||||
declaration.freeze_digest,
|
||||
declaration.input_set_digest,
|
||||
configuration.configuration_identity_digest,
|
||||
"",
|
||||
)
|
||||
for configuration in declaration.arm_configurations
|
||||
)
|
||||
|
||||
|
||||
def validate_evaluation_baselines(declaration: EvaluationPlanDeclarationV3, baselines: tuple[EvaluationBaselineIdentityV3, ...]) -> None:
|
||||
"""Require exact equality with the declaration-derived canonical baseline set."""
|
||||
if type(baselines) is not tuple or any(type(row) is not EvaluationBaselineIdentityV3 for row in baselines):
|
||||
raise EvaluationPlanError("baselines must be a tuple of exact EvaluationBaselineIdentityV3 values")
|
||||
for row in baselines:
|
||||
row.__post_init__()
|
||||
if baselines != derive_evaluation_baselines(declaration):
|
||||
raise EvaluationPlanError("baselines do not match the canonical declaration-derived set")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"EvaluationBaselineIdentityV3",
|
||||
"EvaluationPlanDeclarationV3",
|
||||
"EvaluationPlanError",
|
||||
"ExpectedObservationSlotV3",
|
||||
"create_evaluation_plan_declaration",
|
||||
"derive_evaluation_baselines",
|
||||
"derive_evaluation_input_set_digest",
|
||||
"validate_evaluation_baselines",
|
||||
]
|
||||
@@ -0,0 +1,263 @@
|
||||
"""Non-circular label-blind evaluation-plan contracts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import fields, replace
|
||||
from itertools import product
|
||||
|
||||
import pytest
|
||||
|
||||
from openultrasast.core import canonical
|
||||
from openultrasast.core.evaluation_measurement import (
|
||||
ArmConfigurationV3,
|
||||
ArmKindV3,
|
||||
ArmScopeKey,
|
||||
CombinationDecisionRowV3,
|
||||
CombinationOperatorV3,
|
||||
CombinationRuleV3,
|
||||
Comparator,
|
||||
DenominatorPolicyV3,
|
||||
IntervalMethod,
|
||||
IntervalPrecisionRuleV3,
|
||||
MetricId,
|
||||
NeutralOutcome,
|
||||
ProofCandidatePolicyV3,
|
||||
ScopedThresholdV3,
|
||||
ScopeKey,
|
||||
ScopeSufficiencyRuleV3,
|
||||
Statistic,
|
||||
standard_scoped_metric_rules,
|
||||
)
|
||||
from openultrasast.core.evaluation_plan import (
|
||||
EvaluationPlanDeclarationV3,
|
||||
EvaluationPlanError,
|
||||
ExpectedObservationSlotV3,
|
||||
create_evaluation_plan_declaration,
|
||||
derive_evaluation_baselines,
|
||||
derive_evaluation_input_set_digest,
|
||||
validate_evaluation_baselines,
|
||||
)
|
||||
|
||||
|
||||
def _digest(label: str) -> str:
|
||||
return canonical.content_digest(label)
|
||||
|
||||
|
||||
def _slot_id(arm_id: str, input_digest: str) -> str:
|
||||
return canonical.content_digest(
|
||||
{
|
||||
"schema_version": "openultrasast.detection-core.evaluation-plan-value.v3",
|
||||
"kind": "expected_observation_slot_id",
|
||||
"payload": {"arm_id": arm_id, "input_identity_digest": input_digest},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _combination_rule(combined_arm_id: str = "arm-combined", arm_ids: tuple[str, ...] = ("arm-a", "arm-b")) -> CombinationRuleV3:
|
||||
rows = tuple(
|
||||
CombinationDecisionRowV3(outcomes, NeutralOutcome.VIOLATION if NeutralOutcome.VIOLATION in outcomes else outcomes[0], "")
|
||||
for outcomes in product(tuple(NeutralOutcome), repeat=len(arm_ids))
|
||||
)
|
||||
return CombinationRuleV3(
|
||||
combined_arm_id,
|
||||
arm_ids,
|
||||
CombinationOperatorV3.DECLARATIVE_TABLE,
|
||||
rows,
|
||||
ProofCandidatePolicyV3.IDENTICAL_COMPONENT_ONLY,
|
||||
"",
|
||||
)
|
||||
|
||||
|
||||
def _configuration(arm_id: str, *, combined: bool = False, configuration: str = "configuration") -> ArmConfigurationV3:
|
||||
scope = ScopeKey("access_control", "python")
|
||||
key = ArmScopeKey(arm_id, scope)
|
||||
thresholds = tuple(
|
||||
ScopedThresholdV3(
|
||||
key,
|
||||
metric_id,
|
||||
Statistic.PER_100 if metric_id is MetricId.ORDINARY_FALSE_ALARMS_PER_100 else Statistic.RATE,
|
||||
Comparator.AT_MOST
|
||||
if metric_id in {MetricId.FIXED_FALSE_ALARM_RATE, MetricId.ORDINARY_FALSE_ALARMS_PER_100}
|
||||
else Comparator.AT_LEAST,
|
||||
0.5,
|
||||
"",
|
||||
)
|
||||
for metric_id in MetricId
|
||||
)
|
||||
precision = tuple(IntervalPrecisionRuleV3(metric_id, 0.25, 4, "") for metric_id in MetricId)
|
||||
return ArmConfigurationV3(
|
||||
arm_id,
|
||||
ArmKindV3.COMBINED if combined else ArmKindV3.COMPONENT,
|
||||
(scope,),
|
||||
(DenominatorPolicyV3(key, standard_scoped_metric_rules(key), IntervalMethod.WILSON_95, ""),),
|
||||
thresholds,
|
||||
(ScopeSufficiencyRuleV3(key, 4, 8, precision, ""),),
|
||||
_digest("judgments"),
|
||||
"joern-v3",
|
||||
_digest("facts"),
|
||||
_digest(configuration),
|
||||
_digest("budget"),
|
||||
"container@sha256:abc",
|
||||
_digest("outcomes"),
|
||||
_combination_rule() if combined else None,
|
||||
"",
|
||||
)
|
||||
|
||||
|
||||
def _declaration(*, configurations: tuple[ArmConfigurationV3, ...] | None = None) -> EvaluationPlanDeclarationV3:
|
||||
if configurations is None:
|
||||
configurations = (_configuration("arm-combined", combined=True), _configuration("arm-b"), _configuration("arm-a"))
|
||||
inputs = (_digest("input-b"), _digest("input-a"))
|
||||
return create_evaluation_plan_declaration(
|
||||
population_digest=_digest("population"),
|
||||
freeze_digest=_digest("freeze"),
|
||||
input_set_digest=derive_evaluation_input_set_digest(inputs),
|
||||
arm_configurations=configurations,
|
||||
input_identity_digests=inputs,
|
||||
)
|
||||
|
||||
|
||||
def test_constructor_canonicalizes_plan_and_derives_complete_label_blind_slots() -> None:
|
||||
declaration = _declaration()
|
||||
assert tuple(row.arm_id for row in declaration.arm_configurations) == ("arm-a", "arm-b", "arm-combined")
|
||||
assert tuple((row.arm_id, row.input_identity_digest) for row in declaration.expected_observation_slots) == tuple(
|
||||
(arm_id, input_digest)
|
||||
for arm_id in ("arm-a", "arm-b", "arm-combined")
|
||||
for input_digest in sorted((_digest("input-a"), _digest("input-b")))
|
||||
)
|
||||
slot_fields = {field.name for field in fields(ExpectedObservationSlotV3)}
|
||||
assert slot_fields == {"slot_id", "arm_id", "input_identity_digest", "execution_identity", "slot_digest"}
|
||||
assert not {"label", "labels", "role", "ground_truth"} & slot_fields
|
||||
|
||||
|
||||
def test_declaration_is_non_circular_and_baselines_are_derived_afterward() -> None:
|
||||
declaration = _declaration()
|
||||
declaration_fields = {field.name for field in fields(EvaluationPlanDeclarationV3)}
|
||||
assert "baselines" not in declaration_fields
|
||||
assert "baseline_digests" not in declaration_fields
|
||||
baselines = derive_evaluation_baselines(declaration)
|
||||
validate_evaluation_baselines(declaration, baselines)
|
||||
assert tuple(row.arm_id for row in baselines) == ("arm-a", "arm-b", "arm-combined")
|
||||
assert all(row.plan_declaration_digest == declaration.declaration_digest for row in baselines)
|
||||
assert not hasattr(declaration, "authorize")
|
||||
assert all(not hasattr(row, "authorize") for row in baselines)
|
||||
|
||||
|
||||
def test_every_plan_identity_mutation_changes_declaration_and_affected_baselines() -> None:
|
||||
base = _declaration()
|
||||
mutations = (
|
||||
replace(base, population_digest=_digest("population-2"), declaration_digest=""),
|
||||
replace(base, freeze_digest=_digest("freeze-2"), declaration_digest=""),
|
||||
_declaration(
|
||||
configurations=(
|
||||
_configuration("arm-a", configuration="configuration-2"),
|
||||
_configuration("arm-b"),
|
||||
_configuration("arm-combined", combined=True),
|
||||
)
|
||||
),
|
||||
create_evaluation_plan_declaration(
|
||||
population_digest=_digest("population"),
|
||||
freeze_digest=_digest("freeze"),
|
||||
input_set_digest=derive_evaluation_input_set_digest((_digest("input-a"), _digest("input-c"))),
|
||||
arm_configurations=base.arm_configurations,
|
||||
input_identity_digests=(_digest("input-a"), _digest("input-c")),
|
||||
),
|
||||
)
|
||||
base_baselines = derive_evaluation_baselines(base)
|
||||
for changed in mutations:
|
||||
assert changed.declaration_digest != base.declaration_digest
|
||||
changed_baselines = derive_evaluation_baselines(changed)
|
||||
assert tuple(row.baseline_digest for row in changed_baselines) != tuple(row.baseline_digest for row in base_baselines)
|
||||
|
||||
|
||||
def test_combined_arm_cannot_name_an_absent_component() -> None:
|
||||
with pytest.raises(EvaluationPlanError, match="absent component"):
|
||||
_declaration(configurations=(_configuration("arm-a"), _configuration("arm-combined", combined=True)))
|
||||
|
||||
|
||||
def test_constructor_refuses_duplicate_arm_and_input_identities() -> None:
|
||||
component = _configuration("arm-a")
|
||||
with pytest.raises(EvaluationPlanError, match="unique arm identities"):
|
||||
_declaration(configurations=(component, component))
|
||||
with pytest.raises(EvaluationPlanError, match="input identities must be unique"):
|
||||
create_evaluation_plan_declaration(
|
||||
population_digest=_digest("population"),
|
||||
freeze_digest=_digest("freeze"),
|
||||
input_set_digest=derive_evaluation_input_set_digest((_digest("input-a"),)),
|
||||
arm_configurations=(component,),
|
||||
input_identity_digests=(_digest("input-a"), _digest("input-a")),
|
||||
)
|
||||
for invalid in ((), ("not-a-digest",), (None,)):
|
||||
with pytest.raises(EvaluationPlanError):
|
||||
derive_evaluation_input_set_digest(invalid) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_input_set_identity_refuses_digest_mismatch_and_whole_column_omission() -> None:
|
||||
base = _declaration()
|
||||
with pytest.raises(EvaluationPlanError, match="input set digest"):
|
||||
replace(base, input_set_digest=_digest("wrong"), declaration_digest="")
|
||||
|
||||
retained = tuple(slot for slot in base.expected_observation_slots if slot.input_identity_digest == _digest("input-a"))
|
||||
with pytest.raises(EvaluationPlanError, match="input set digest"):
|
||||
replace(base, expected_observation_slots=retained, declaration_digest="")
|
||||
|
||||
|
||||
def test_combined_arm_cannot_use_another_combined_arm_as_a_component() -> None:
|
||||
base = _declaration()
|
||||
arm_a = base.arm_configurations[0]
|
||||
nested_rule = _combination_rule("arm-a", ("arm-b", "arm-combined"))
|
||||
nested = replace(
|
||||
arm_a,
|
||||
kind=ArmKindV3.COMBINED,
|
||||
combination_rule=nested_rule,
|
||||
configuration_identity_digest="",
|
||||
)
|
||||
with pytest.raises(EvaluationPlanError, match="component configuration"):
|
||||
_declaration(configurations=(nested, base.arm_configurations[1], base.arm_configurations[2]))
|
||||
|
||||
|
||||
def test_direct_contract_refuses_missing_extra_duplicate_unsorted_and_cross_arm_slots() -> None:
|
||||
base = _declaration()
|
||||
slots = base.expected_observation_slots
|
||||
cross_arm = ExpectedObservationSlotV3(
|
||||
_slot_id("arm-z", slots[0].input_identity_digest),
|
||||
"arm-z",
|
||||
slots[0].input_identity_digest,
|
||||
slots[0].execution_identity,
|
||||
"",
|
||||
)
|
||||
mutations = (
|
||||
slots[:-1],
|
||||
slots + (slots[-1],),
|
||||
tuple(reversed(slots)),
|
||||
(cross_arm,) + slots[1:],
|
||||
(replace(slots[0], execution_identity="wrong", slot_digest=""),) + slots[1:],
|
||||
)
|
||||
for changed_slots in mutations:
|
||||
with pytest.raises(EvaluationPlanError):
|
||||
replace(base, expected_observation_slots=changed_slots, declaration_digest="")
|
||||
|
||||
|
||||
def test_baseline_validation_refuses_missing_extra_reordered_and_rehashed_rows() -> None:
|
||||
declaration = _declaration()
|
||||
baselines = derive_evaluation_baselines(declaration)
|
||||
for changed in (
|
||||
baselines[:-1],
|
||||
baselines + (baselines[-1],),
|
||||
tuple(reversed(baselines)),
|
||||
(replace(baselines[0], arm_configuration_digest=_digest("wrong"), baseline_digest=""),) + baselines[1:],
|
||||
):
|
||||
with pytest.raises(EvaluationPlanError):
|
||||
validate_evaluation_baselines(declaration, changed)
|
||||
|
||||
|
||||
def test_exact_contracts_reject_subclasses_and_tampered_digests() -> None:
|
||||
declaration = _declaration()
|
||||
|
||||
class DerivedDeclaration(EvaluationPlanDeclarationV3):
|
||||
pass
|
||||
|
||||
with pytest.raises((EvaluationPlanError, TypeError, ValueError)):
|
||||
DerivedDeclaration(*tuple(getattr(declaration, field.name) for field in fields(EvaluationPlanDeclarationV3)))
|
||||
with pytest.raises(EvaluationPlanError, match="canonical content"):
|
||||
replace(declaration, declaration_digest=_digest("wrong"))
|
||||
Reference in New Issue
Block a user