feat(detection-core): define exact V3 measurement contracts

This commit is contained in:
Marius Ciepluch
2026-11-06 16:56:39 +01:00
parent c74506e38b
commit a60b5397c6
5 changed files with 1154 additions and 1 deletions
+2 -1
View File
@@ -468,7 +468,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
- _Requirements: 16.2, 18.6_
- _Boundary: Version-Neutral Metric Algebra_
- _Depends: 12.1_
- [ ] 12.3 Define exact arm-scope measurement and sufficiency contracts
- [x] 12.3 Define exact arm-scope measurement and sufficiency contracts
- Represent one canonical arm-and-scope key for every policy, threshold, sufficiency rule, metric, gate, and decision.
- Bind exact denominator algebra, fixed Wilson intervals, sample counts, minimum sizes, interval precision, and rational aggregate weights.
- Include every arm identity input that must start a new baseline when changed, including judgment vocabulary, analyzer, facts, configuration, registered budget, execution, outcome mapping, and combination rule.
@@ -709,6 +709,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
- Task 12.1 froze three representative V2 admissions and exact failure precedence; shared-helper work must keep the committed bytes, SHA-256 identities, decisions, and authoritative replay output unchanged.
- Task 12.2 moved the seven closed metric identities and bit-exact Wilson arithmetic into `_metric_algebra.py`; V2 retains all schemas, validators, serialization, and error ownership.
- 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.
- 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,230 @@
"""Closed component and combined-arm identities used by V3 measurement."""
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from itertools import product
from openultrasast.core import canonical
from openultrasast.core._evaluation_measurement_contracts import (
ArmScopeKey,
DenominatorPolicyV3,
EvaluationMeasurementError,
MetricId,
ScopedThresholdV3,
ScopeKey,
ScopeSufficiencyRuleV3,
_bind_digest,
_digest,
_exact,
_text,
_value,
)
from openultrasast.core.evidence import NeutralOutcome
class ArmKindV3(Enum):
COMPONENT = "component"
COMBINED = "combined"
class CombinationOperatorV3(Enum):
DECLARATIVE_TABLE = "declarative_table"
class ProofCandidatePolicyV3(Enum):
IDENTICAL_COMPONENT_ONLY = "identical_component_only"
@dataclass(frozen=True)
class CombinationDecisionRowV3:
component_outcomes: tuple[NeutralOutcome, ...]
combined_outcome: NeutralOutcome
row_digest: str
def __post_init__(self) -> None:
_exact(self, CombinationDecisionRowV3, "combination decision row")
if (
type(self.component_outcomes) is not tuple
or not self.component_outcomes
or any(type(item) is not NeutralOutcome for item in self.component_outcomes)
):
raise EvaluationMeasurementError("component outcomes must be a nonempty tuple of NeutralOutcome values")
if type(self.combined_outcome) is not NeutralOutcome:
raise EvaluationMeasurementError("combined outcome must use NeutralOutcome")
payload: canonical.JsonValue = {
"component_outcomes": tuple(item.value for item in self.component_outcomes),
"combined_outcome": self.combined_outcome.value,
}
_bind_digest(self, "row_digest", canonical.content_digest(_value("combination_decision_row", payload)))
@dataclass(frozen=True)
class CombinationRuleV3:
combined_arm_id: str
component_arm_ids: tuple[str, ...]
operator: CombinationOperatorV3
decision_rows: tuple[CombinationDecisionRowV3, ...]
candidate_policy: ProofCandidatePolicyV3
rule_digest: str
def __post_init__(self) -> None:
_exact(self, CombinationRuleV3, "combination rule")
_text(self.combined_arm_id, "combined_arm_id")
if (
type(self.component_arm_ids) is not tuple
or not self.component_arm_ids
or any(type(item) is not str or not item for item in self.component_arm_ids)
):
raise EvaluationMeasurementError("component arm ids must be a nonempty tuple")
canonical_ids = tuple(sorted(set(self.component_arm_ids)))
if self.component_arm_ids != canonical_ids or self.combined_arm_id in self.component_arm_ids:
raise EvaluationMeasurementError("component arm ids must be unique and in canonical order")
if (
self.operator is not CombinationOperatorV3.DECLARATIVE_TABLE
or self.candidate_policy is not ProofCandidatePolicyV3.IDENTICAL_COMPONENT_ONLY
):
raise EvaluationMeasurementError("combination rule must use the closed operator and candidate policy")
expected_outcomes = tuple(product(tuple(NeutralOutcome), repeat=len(self.component_arm_ids)))
if (
type(self.decision_rows) is not tuple
or len(self.decision_rows) != len(expected_outcomes)
or any(type(row) is not CombinationDecisionRowV3 for row in self.decision_rows)
):
raise EvaluationMeasurementError("combination rule requires one canonical row for every component outcome")
if tuple(row.component_outcomes for row in self.decision_rows) != expected_outcomes:
raise EvaluationMeasurementError("combination decision rows must use canonical complete order")
for row in self.decision_rows:
row.__post_init__()
payload: canonical.JsonValue = {
"combined_arm_id": self.combined_arm_id,
"component_arm_ids": self.component_arm_ids,
"operator": self.operator.value,
"row_digests": tuple(row.row_digest for row in self.decision_rows),
"candidate_policy": self.candidate_policy.value,
}
_bind_digest(self, "rule_digest", canonical.content_digest(_value("combination_rule", payload)))
def _validate_scopes(scopes: object) -> tuple[ScopeKey, ...]:
if type(scopes) is not tuple or not scopes or any(type(scope) is not ScopeKey for scope in scopes):
raise EvaluationMeasurementError("exact scopes must be a nonempty tuple of exact ScopeKey values")
if scopes != tuple(sorted(scopes)) or len(set(scopes)) != len(scopes):
raise EvaluationMeasurementError("exact scopes must be unique canonical exact scopes")
for scope in scopes:
scope.__post_init__()
return scopes
@dataclass(frozen=True)
class ArmConfigurationV3:
arm_id: str
kind: ArmKindV3
exact_scopes: tuple[ScopeKey, ...]
denominator_policies: tuple[DenominatorPolicyV3, ...]
thresholds: tuple[ScopedThresholdV3, ...]
sufficiency_rules: tuple[ScopeSufficiencyRuleV3, ...]
judgment_vocabulary_digest: str
analyzer_identity: str
fact_set_digest: str
configuration_digest: str
registered_budget_digest: str
execution_identity: str
outcome_mapping_digest: str
combination_rule: CombinationRuleV3 | None
configuration_identity_digest: str
def __post_init__(self) -> None:
_exact(self, ArmConfigurationV3, "arm configuration")
_text(self.arm_id, "arm_id")
if type(self.kind) is not ArmKindV3:
raise EvaluationMeasurementError("arm kind must use the closed ArmKindV3 enum")
expected_keys = tuple(ArmScopeKey(self.arm_id, scope) for scope in _validate_scopes(self.exact_scopes))
if type(self.denominator_policies) is not tuple:
raise EvaluationMeasurementError("denominator policies must be a canonical tuple")
actual_policy_keys = tuple(policy.key for policy in self.denominator_policies if type(policy) is DenominatorPolicyV3)
if actual_policy_keys != expected_keys:
raise EvaluationMeasurementError("denominator policies must occur once per canonical arm-scope key")
for policy in self.denominator_policies:
policy.__post_init__()
self._validate_thresholds(expected_keys)
if type(self.sufficiency_rules) is not tuple:
raise EvaluationMeasurementError("sufficiency rules must be a canonical tuple")
actual_sufficiency_keys = tuple(row.key for row in self.sufficiency_rules if type(row) is ScopeSufficiencyRuleV3)
if actual_sufficiency_keys != expected_keys:
raise EvaluationMeasurementError("sufficiency rules must occur once per canonical arm-scope key")
for threshold in self.thresholds:
threshold.__post_init__()
for rule in self.sufficiency_rules:
rule.__post_init__()
self._validate_identities()
self._validate_combination()
_bind_digest(self, "configuration_identity_digest", derive_arm_configuration_identity_digest(self))
def _validate_thresholds(self, expected_keys: tuple[ArmScopeKey, ...]) -> None:
if type(self.thresholds) is not tuple:
raise EvaluationMeasurementError("thresholds must be a canonical tuple")
expected = tuple((key, metric_id) for key in expected_keys for metric_id in MetricId)
actual = tuple((row.key, row.metric_id) for row in self.thresholds if type(row) is ScopedThresholdV3)
if actual == expected:
return
if len(self.thresholds) != len(expected):
raise EvaluationMeasurementError("each scoped threshold metric must occur exactly once")
if len(actual) == len(self.thresholds) and actual == tuple(sorted(actual, key=lambda row: (row[0], list(MetricId).index(row[1])))):
raise EvaluationMeasurementError("threshold arm-scope key does not match its configuration")
raise EvaluationMeasurementError("thresholds must use canonical order")
def _validate_identities(self) -> None:
for item, field in (
(self.judgment_vocabulary_digest, "judgment vocabulary digest"),
(self.fact_set_digest, "fact set digest"),
(self.configuration_digest, "configuration digest"),
(self.registered_budget_digest, "registered budget digest"),
(self.outcome_mapping_digest, "outcome mapping digest"),
):
_digest(item, field)
_text(self.analyzer_identity, "analyzer identity")
_text(self.execution_identity, "execution identity")
def _validate_combination(self) -> None:
if self.kind is ArmKindV3.COMPONENT and self.combination_rule is not None:
raise EvaluationMeasurementError("component arm must not carry a combination rule")
if self.kind is ArmKindV3.COMBINED:
if type(self.combination_rule) is not CombinationRuleV3:
raise EvaluationMeasurementError("combined arm requires a combination rule")
self.combination_rule.__post_init__()
if self.combination_rule.combined_arm_id != self.arm_id:
raise EvaluationMeasurementError("combination rule arm does not match configuration")
def derive_arm_configuration_identity_digest(value: ArmConfigurationV3) -> str:
_exact(value, ArmConfigurationV3, "arm configuration")
payload = {
"arm_id": value.arm_id,
"kind": value.kind.value,
"exact_scopes": tuple({"family_id": scope.family_id, "ecosystem": scope.ecosystem} for scope in value.exact_scopes),
"policy_digests": tuple(row.policy_digest for row in value.denominator_policies),
"threshold_digests": tuple(row.threshold_digest for row in value.thresholds),
"sufficiency_digests": tuple(row.rule_digest for row in value.sufficiency_rules),
"judgment_vocabulary_digest": value.judgment_vocabulary_digest,
"analyzer_identity": value.analyzer_identity,
"fact_set_digest": value.fact_set_digest,
"configuration_digest": value.configuration_digest,
"registered_budget_digest": value.registered_budget_digest,
"execution_identity": value.execution_identity,
"outcome_mapping_digest": value.outcome_mapping_digest,
"combination_rule_digest": None if value.combination_rule is None else value.combination_rule.rule_digest,
}
return canonical.content_digest(_value("arm_configuration", payload))
__all__ = [
"ArmConfigurationV3",
"ArmKindV3",
"CombinationDecisionRowV3",
"CombinationOperatorV3",
"CombinationRuleV3",
"ProofCandidatePolicyV3",
"derive_arm_configuration_identity_digest",
]
@@ -0,0 +1,432 @@
"""Lower exact arm/scope measurement contracts for evaluation admission V3."""
from __future__ import annotations
import math
import re
from dataclasses import dataclass
from enum import Enum
from fractions import Fraction
from math import gcd
from typing import cast
from openultrasast.core import canonical
from openultrasast.core._metric_algebra import metric_algebra, metric_values
from openultrasast.core.evidence import NeutralOutcome
_DIGEST = re.compile(r"[0-9a-f]{64}")
_SCHEMA = "openultrasast.detection-core.evaluation-measurement.v3"
class EvaluationMeasurementError(ValueError):
"""A V3 measurement value violates its exact closed contract."""
def _exact(value: object, expected: type[object], field: str) -> None:
if type(value) is not expected:
raise EvaluationMeasurementError(f"{field} must use exact type {expected.__name__}")
def _text(value: object, field: str) -> str:
if type(value) is not str or not value:
raise EvaluationMeasurementError(f"{field} must be nonempty text")
return value
def _digest(value: object, field: str) -> str:
if type(value) is not str or _DIGEST.fullmatch(value) is None:
raise EvaluationMeasurementError(f"{field} must be a full lowercase SHA-256 digest")
return value
def _count(value: object, field: str, *, positive: bool = False) -> int:
if type(value) is not int or value < int(positive):
qualifier = "positive" if positive else "non-negative"
raise EvaluationMeasurementError(f"{field} must be a {qualifier} integer")
return value
def _finite(value: object, field: str) -> float:
number = cast(int | float, value)
if type(value) not in (int, float) or not math.isfinite(number):
raise EvaluationMeasurementError(f"{field} must be finite")
return float(number)
def _value(kind: str, payload: canonical.JsonValue) -> canonical.JsonValue:
return {"schema_version": _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)
else:
_digest(actual, field)
if actual != expected:
raise EvaluationMeasurementError(f"{field} does not match canonical content")
class MetricId(Enum):
PAIRED_CORRECTNESS = "paired_correctness"
VULNERABLE_RECALL = "vulnerable_recall"
FIXED_FALSE_ALARM_RATE = "fixed_false_alarm_rate"
ORDINARY_FALSE_ALARMS_PER_100 = "ordinary_false_alarms_per_100"
PRECISION = "precision"
SEMANTIC_STAGE_COVERAGE = "semantic_stage_coverage"
MODEL_SUCCESS_RATE = "model_success_rate"
class NumeratorKind(Enum):
CORRECT_PAIRS = "correct_pairs"
VULNERABLE_VIOLATION_CASES = "vulnerable_violation_cases"
FIXED_DEFECT_CASES = "fixed_defect_cases"
ORDINARY_DEFECT_CASES = "ordinary_defect_cases"
TRUE_DEFECT_CASES = "true_defect_cases"
SITES_RECOGNIZED = "sites_recognized"
SUCCESSFUL_MODEL_CALLS = "successful_model_calls"
class DenominatorKind(Enum):
PAIRS = "pairs"
VULNERABLE_SIDES = "vulnerable_sides"
FIXED_SIDES = "fixed_sides"
ORDINARY_CASES = "ordinary_cases"
ALL_DEFECT_CASES = "all_defect_cases"
SITES_CONSIDERED = "sites_considered"
MODEL_CALLS = "model_calls"
class IntervalMethod(Enum):
WILSON_95 = "wilson_95"
class Statistic(Enum):
COUNT = "count"
RATE = "rate"
PER_100 = "per_100"
WILSON_LOWER = "wilson_lower"
WILSON_UPPER = "wilson_upper"
class Comparator(Enum):
AT_LEAST = "at_least"
AT_MOST = "at_most"
@dataclass(frozen=True, order=True)
class ScopeKey:
family_id: str
ecosystem: str
def __post_init__(self) -> None:
_exact(self, ScopeKey, "scope")
_text(self.family_id, "family_id")
_text(self.ecosystem, "ecosystem")
@dataclass(frozen=True, order=True)
class ArmScopeKey:
arm_id: str
scope: ScopeKey
def __post_init__(self) -> None:
_exact(self, ArmScopeKey, "arm-scope key")
_text(self.arm_id, "arm_id")
_exact(self.scope, ScopeKey, "scope")
self.scope.__post_init__()
def _key_value(key: ArmScopeKey) -> canonical.JsonValue:
return {"arm_id": key.arm_id, "scope": {"family_id": key.scope.family_id, "ecosystem": key.scope.ecosystem}}
def _metric_parts(metric_id: MetricId) -> tuple[NumeratorKind, DenominatorKind, Comparator]:
if type(metric_id) is not MetricId:
raise EvaluationMeasurementError("metric_id must use the closed MetricId enum")
numerator, denominator, comparator = metric_algebra(metric_id.value)
return NumeratorKind(numerator), DenominatorKind(denominator), Comparator(comparator)
@dataclass(frozen=True)
class ScopedMetricRuleV3:
key: ArmScopeKey
metric_id: MetricId
numerator: NumeratorKind
denominator: DenominatorKind
rule_digest: str
def __post_init__(self) -> None:
_exact(self, ScopedMetricRuleV3, "scoped metric rule")
_exact(self.key, ArmScopeKey, "arm-scope key")
self.key.__post_init__()
expected_numerator, expected_denominator, _ = _metric_parts(self.metric_id)
if type(self.numerator) is not NumeratorKind or type(self.denominator) is not DenominatorKind:
raise EvaluationMeasurementError("metric algebra kinds must use closed enums")
if (self.numerator, self.denominator) != (expected_numerator, expected_denominator):
raise EvaluationMeasurementError("metric rule violates the fixed algebra")
payload = {
"key": _key_value(self.key),
"metric_id": self.metric_id.value,
"numerator": self.numerator.value,
"denominator": self.denominator.value,
}
_bind_digest(self, "rule_digest", canonical.content_digest(_value("scoped_metric_rule", payload)))
def standard_scoped_metric_rules(key: ArmScopeKey) -> tuple[ScopedMetricRuleV3, ...]:
_exact(key, ArmScopeKey, "arm-scope key")
key.__post_init__()
return tuple(ScopedMetricRuleV3(key, metric_id, *_metric_parts(metric_id)[:2], "") for metric_id in MetricId)
@dataclass(frozen=True)
class DenominatorPolicyV3:
key: ArmScopeKey
rules: tuple[ScopedMetricRuleV3, ...]
interval_method: IntervalMethod
policy_digest: str
def __post_init__(self) -> None:
_exact(self, DenominatorPolicyV3, "denominator policy")
_exact(self.key, ArmScopeKey, "arm-scope key")
self.key.__post_init__()
if (
type(self.rules) is not tuple
or tuple(rule.metric_id for rule in self.rules if type(rule) is ScopedMetricRuleV3) != tuple(MetricId)
or len(self.rules) != len(MetricId)
):
raise EvaluationMeasurementError("each standard metric must occur exactly once in canonical order")
if any(type(rule) is not ScopedMetricRuleV3 or rule.key != self.key for rule in self.rules):
raise EvaluationMeasurementError("every policy rule must use the same arm-scope key")
for rule in self.rules:
rule.__post_init__()
if self.interval_method is not IntervalMethod.WILSON_95:
raise EvaluationMeasurementError("interval method must be Wilson 95%")
payload = {
"key": _key_value(self.key),
"rule_digests": tuple(rule.rule_digest for rule in self.rules),
"interval_method": self.interval_method.value,
}
_bind_digest(self, "policy_digest", canonical.content_digest(_value("denominator_policy", payload)))
@dataclass(frozen=True)
class ScopedThresholdV3:
key: ArmScopeKey
metric_id: MetricId
statistic: Statistic
comparator: Comparator
target: float
threshold_digest: str
def __post_init__(self) -> None:
_exact(self, ScopedThresholdV3, "scoped threshold")
_exact(self.key, ArmScopeKey, "arm-scope key")
self.key.__post_init__()
_, _, expected_comparator = _metric_parts(self.metric_id)
if type(self.statistic) is not Statistic or type(self.comparator) is not Comparator:
raise EvaluationMeasurementError("threshold fields must use closed enums")
if self.comparator is not expected_comparator:
raise EvaluationMeasurementError("threshold violates the fixed comparator")
is_ordinary = self.metric_id is MetricId.ORDINARY_FALSE_ALARMS_PER_100
if self.statistic is Statistic.PER_100 and not is_ordinary:
raise EvaluationMeasurementError("PER_100 statistic belongs only to ordinary false alarms")
if self.statistic is Statistic.RATE and is_ordinary:
raise EvaluationMeasurementError("ordinary false alarms require PER_100 rather than RATE")
target = _finite(self.target, "threshold target")
if target < 0:
raise EvaluationMeasurementError("threshold target must be non-negative")
payload = {
"key": _key_value(self.key),
"metric_id": self.metric_id.value,
"statistic": self.statistic.value,
"comparator": self.comparator.value,
"target": target,
}
_bind_digest(self, "threshold_digest", canonical.content_digest(_value("scoped_threshold", payload)))
@dataclass(frozen=True)
class IntervalPrecisionRuleV3:
metric_id: MetricId
maximum_wilson_width: float
minimum_denominator: int
rule_digest: str
def __post_init__(self) -> None:
_exact(self, IntervalPrecisionRuleV3, "interval precision rule")
_metric_parts(self.metric_id)
width = _finite(self.maximum_wilson_width, "maximum Wilson width")
if width <= 0:
raise EvaluationMeasurementError("maximum Wilson width must be positive")
_count(self.minimum_denominator, "minimum denominator", positive=True)
payload = {"metric_id": self.metric_id.value, "maximum_wilson_width": width, "minimum_denominator": self.minimum_denominator}
_bind_digest(self, "rule_digest", canonical.content_digest(_value("interval_precision_rule", payload)))
@dataclass(frozen=True)
class ScopeSufficiencyRuleV3:
key: ArmScopeKey
minimum_pairs: int
minimum_ordinary_pushes: int
precision_rules: tuple[IntervalPrecisionRuleV3, ...]
rule_digest: str
def __post_init__(self) -> None:
_exact(self, ScopeSufficiencyRuleV3, "scope sufficiency rule")
_exact(self.key, ArmScopeKey, "arm-scope key")
self.key.__post_init__()
_count(self.minimum_pairs, "minimum pairs", positive=True)
_count(self.minimum_ordinary_pushes, "minimum ordinary pushes", positive=True)
if (
type(self.precision_rules) is not tuple
or tuple(rule.metric_id for rule in self.precision_rules if type(rule) is IntervalPrecisionRuleV3) != tuple(MetricId)
or len(self.precision_rules) != len(MetricId)
):
raise EvaluationMeasurementError("each precision metric must occur exactly once in canonical order")
for rule in self.precision_rules:
rule.__post_init__()
payload = {
"key": _key_value(self.key),
"minimum_pairs": self.minimum_pairs,
"minimum_ordinary_pushes": self.minimum_ordinary_pushes,
"precision_rule_digests": tuple(rule.rule_digest for rule in self.precision_rules),
}
_bind_digest(self, "rule_digest", canonical.content_digest(_value("scope_sufficiency_rule", payload)))
@dataclass(frozen=True)
class ScopedMetricResultV3:
key: ArmScopeKey
metric_id: MetricId
numerator: int
denominator: int
sample_count: int
value: float | None
interval_method: IntervalMethod
interval_lower: float | None
interval_upper: float | None
def __post_init__(self) -> None:
_exact(self, ScopedMetricResultV3, "scoped metric result")
_exact(self.key, ArmScopeKey, "arm-scope key")
self.key.__post_init__()
_metric_parts(self.metric_id)
numerator = _count(self.numerator, "numerator")
denominator = _count(self.denominator, "denominator", positive=True)
sample_count = _count(self.sample_count, "sample count", positive=True)
if numerator > denominator:
raise EvaluationMeasurementError("numerator must not exceed denominator")
if sample_count != denominator:
raise EvaluationMeasurementError("sample count must equal the exact denominator")
if self.interval_method is not IntervalMethod.WILSON_95:
raise EvaluationMeasurementError("interval method must be Wilson 95%")
expected_value, expected_lower, expected_upper = metric_values(self.metric_id.value, numerator, denominator)
if expected_value is None or expected_lower is None or expected_upper is None:
raise EvaluationMeasurementError("positive denominator must produce Wilson values")
expected = (expected_value, expected_lower, expected_upper)
actual = (self.value, self.interval_lower, self.interval_upper)
if any(
type(item) is not float or not math.isfinite(item) or item.hex() != expected[index].hex() for index, item in enumerate(actual)
):
raise EvaluationMeasurementError("metric values must match the fixed Wilson calculation")
@classmethod
def from_counts(cls, key: ArmScopeKey, metric_id: MetricId, *, numerator: int, denominator: int) -> ScopedMetricResultV3:
_exact(key, ArmScopeKey, "arm-scope key")
key.__post_init__()
_metric_parts(metric_id)
numerator = _count(numerator, "numerator")
denominator = _count(denominator, "denominator", positive=True)
if numerator > denominator:
raise EvaluationMeasurementError("numerator must not exceed denominator")
value, lower, upper = metric_values(metric_id.value, numerator, denominator)
return cls(key, metric_id, numerator, denominator, denominator, value, IntervalMethod.WILSON_95, lower, upper)
def validate_scoped_metric_result(result: ScopedMetricResultV3, rule: ScopedMetricRuleV3) -> None:
_exact(result, ScopedMetricResultV3, "scoped metric result")
_exact(rule, ScopedMetricRuleV3, "scoped metric rule")
result.__post_init__()
rule.__post_init__()
if result.key != rule.key:
raise EvaluationMeasurementError("scoped metric result arm-scope key does not match its rule")
if result.metric_id is not rule.metric_id:
raise EvaluationMeasurementError("scoped metric result identity does not match its rule")
@dataclass(frozen=True)
class AggregateWeightV3:
key: ArmScopeKey
numerator: int
denominator: int
weight_digest: str
def __post_init__(self) -> None:
_exact(self, AggregateWeightV3, "aggregate weight")
_exact(self.key, ArmScopeKey, "arm-scope key")
self.key.__post_init__()
numerator = _count(self.numerator, "weight numerator")
denominator = _count(self.denominator, "weight denominator", positive=True)
if numerator > denominator:
raise EvaluationMeasurementError("aggregate weight must not exceed one")
if gcd(numerator, denominator) != 1:
raise EvaluationMeasurementError("aggregate weight must use a reduced rational")
payload = {"key": _key_value(self.key), "numerator": numerator, "denominator": denominator}
_bind_digest(self, "weight_digest", canonical.content_digest(_value("aggregate_weight", payload)))
def validate_aggregate_weights(
constituents: tuple[ArmScopeKey, ...], sample_counts: tuple[int, ...], weights: tuple[AggregateWeightV3, ...]
) -> None:
if (
type(constituents) is not tuple
or not constituents
or any(type(key) is not ArmScopeKey for key in constituents)
or constituents != tuple(sorted(set(constituents)))
):
raise EvaluationMeasurementError("aggregate constituents must be unique and in canonical order")
for key in constituents:
key.__post_init__()
if (
type(sample_counts) is not tuple
or len(sample_counts) != len(constituents)
or any(type(count) is not int or count <= 0 for count in sample_counts)
):
raise EvaluationMeasurementError("aggregate sample counts must be positive and align one-to-one")
if (
type(weights) is not tuple
or len(weights) != len(constituents)
or any(type(weight) is not AggregateWeightV3 for weight in weights)
or tuple(weight.key for weight in weights) != constituents
):
raise EvaluationMeasurementError("aggregate weights must correspond one-to-one with constituents")
for weight in weights:
weight.__post_init__()
if sum((Fraction(weight.numerator, weight.denominator) for weight in weights), Fraction()) != 1:
raise EvaluationMeasurementError("aggregate weights must sum exactly to one")
__all__ = [
"AggregateWeightV3",
"ArmScopeKey",
"Comparator",
"DenominatorKind",
"DenominatorPolicyV3",
"EvaluationMeasurementError",
"IntervalMethod",
"IntervalPrecisionRuleV3",
"MetricId",
"NeutralOutcome",
"NumeratorKind",
"ScopeKey",
"ScopeSufficiencyRuleV3",
"ScopedMetricResultV3",
"ScopedMetricRuleV3",
"ScopedThresholdV3",
"Statistic",
"standard_scoped_metric_rules",
"validate_aggregate_weights",
"validate_scoped_metric_result",
]
@@ -0,0 +1,63 @@
"""Public exact arm/scope measurement foundations for evaluation admission V3."""
from openultrasast.core._evaluation_arm_configuration import (
ArmConfigurationV3,
ArmKindV3,
CombinationDecisionRowV3,
CombinationOperatorV3,
CombinationRuleV3,
ProofCandidatePolicyV3,
derive_arm_configuration_identity_digest,
)
from openultrasast.core._evaluation_measurement_contracts import (
AggregateWeightV3,
ArmScopeKey,
Comparator,
DenominatorKind,
DenominatorPolicyV3,
EvaluationMeasurementError,
IntervalMethod,
IntervalPrecisionRuleV3,
MetricId,
NeutralOutcome,
NumeratorKind,
ScopedMetricResultV3,
ScopedMetricRuleV3,
ScopedThresholdV3,
ScopeKey,
ScopeSufficiencyRuleV3,
Statistic,
standard_scoped_metric_rules,
validate_aggregate_weights,
validate_scoped_metric_result,
)
__all__ = [
"AggregateWeightV3",
"ArmConfigurationV3",
"ArmKindV3",
"ArmScopeKey",
"CombinationDecisionRowV3",
"CombinationOperatorV3",
"CombinationRuleV3",
"Comparator",
"DenominatorKind",
"DenominatorPolicyV3",
"EvaluationMeasurementError",
"IntervalMethod",
"IntervalPrecisionRuleV3",
"MetricId",
"NeutralOutcome",
"NumeratorKind",
"ProofCandidatePolicyV3",
"ScopeKey",
"ScopeSufficiencyRuleV3",
"ScopedMetricResultV3",
"ScopedMetricRuleV3",
"ScopedThresholdV3",
"Statistic",
"derive_arm_configuration_identity_digest",
"standard_scoped_metric_rules",
"validate_aggregate_weights",
"validate_scoped_metric_result",
]
+427
View File
@@ -0,0 +1,427 @@
"""Exact V3 arm/scope measurement contracts."""
from __future__ import annotations
import subprocess
import sys
from dataclasses import replace
from itertools import product
import pytest
from openultrasast.core import canonical
from openultrasast.core.evaluation_measurement import (
AggregateWeightV3,
ArmConfigurationV3,
ArmKindV3,
ArmScopeKey,
CombinationDecisionRowV3,
CombinationOperatorV3,
CombinationRuleV3,
Comparator,
DenominatorPolicyV3,
EvaluationMeasurementError,
IntervalMethod,
IntervalPrecisionRuleV3,
MetricId,
NeutralOutcome,
ProofCandidatePolicyV3,
ScopedMetricResultV3,
ScopedThresholdV3,
ScopeKey,
ScopeSufficiencyRuleV3,
Statistic,
derive_arm_configuration_identity_digest,
standard_scoped_metric_rules,
validate_aggregate_weights,
validate_scoped_metric_result,
)
def _digest(label: str) -> str:
return canonical.content_digest(label)
def _key(arm_id: str = "arm-a", family: str = "access_control") -> ArmScopeKey:
return ArmScopeKey(arm_id, ScopeKey(family, "python"))
def _policy(key: ArmScopeKey) -> DenominatorPolicyV3:
return DenominatorPolicyV3(key, standard_scoped_metric_rules(key), IntervalMethod.WILSON_95, "")
def _thresholds(key: ArmScopeKey) -> tuple[ScopedThresholdV3, ...]:
rows = []
for metric_id in MetricId:
comparator = (
Comparator.AT_MOST
if metric_id
in {
MetricId.FIXED_FALSE_ALARM_RATE,
MetricId.ORDINARY_FALSE_ALARMS_PER_100,
}
else Comparator.AT_LEAST
)
statistic = Statistic.PER_100 if metric_id is MetricId.ORDINARY_FALSE_ALARMS_PER_100 else Statistic.RATE
rows.append(ScopedThresholdV3(key, metric_id, statistic, comparator, 0.5, ""))
return tuple(rows)
def _sufficiency(key: ArmScopeKey) -> ScopeSufficiencyRuleV3:
precision = tuple(IntervalPrecisionRuleV3(metric_id, 0.25, 4, "") for metric_id in MetricId)
return ScopeSufficiencyRuleV3(key, 4, 8, precision, "")
def _combination_rule() -> CombinationRuleV3:
components = ("arm-a", "arm-b")
rows = []
for outcomes in product(tuple(NeutralOutcome), repeat=len(components)):
combined = NeutralOutcome.VIOLATION if NeutralOutcome.VIOLATION in outcomes else outcomes[0]
rows.append(CombinationDecisionRowV3(outcomes, combined, ""))
return CombinationRuleV3(
"arm-combined",
components,
CombinationOperatorV3.DECLARATIVE_TABLE,
tuple(rows),
ProofCandidatePolicyV3.IDENTICAL_COMPONENT_ONLY,
"",
)
def _configuration(
arm_id: str = "arm-a",
*,
kind: ArmKindV3 = ArmKindV3.COMPONENT,
combination_rule: CombinationRuleV3 | None = None,
) -> ArmConfigurationV3:
key = _key(arm_id)
return ArmConfigurationV3(
arm_id=arm_id,
kind=kind,
exact_scopes=(key.scope,),
denominator_policies=(_policy(key),),
thresholds=_thresholds(key),
sufficiency_rules=(_sufficiency(key),),
judgment_vocabulary_digest=_digest("judgments"),
analyzer_identity="joern-4.0+ousast-v3",
fact_set_digest=_digest("facts"),
configuration_digest=_digest("configuration"),
registered_budget_digest=_digest("budget"),
execution_identity="container@sha256:abc",
outcome_mapping_digest=_digest("outcomes"),
combination_rule=combination_rule,
configuration_identity_digest="",
)
def test_complete_component_and_combined_configurations_are_canonical() -> None:
component = _configuration()
combined = _configuration(
"arm-combined",
kind=ArmKindV3.COMBINED,
combination_rule=_combination_rule(),
)
assert component.combination_rule is None
assert combined.combination_rule is not None
assert component.configuration_identity_digest == derive_arm_configuration_identity_digest(component)
assert combined.configuration_identity_digest == derive_arm_configuration_identity_digest(combined)
assert tuple(rule.metric_id for rule in component.denominator_policies[0].rules) == tuple(MetricId)
def test_every_arm_identity_input_changes_the_configuration_identity() -> None:
value = _configuration()
changed_key = _key("arm-a", "injection")
combined = _configuration("arm-combined", kind=ArmKindV3.COMBINED, combination_rule=_combination_rule())
assert combined.combination_rule is not None
changed_rows = list(combined.combination_rule.decision_rows)
changed_rows[0] = replace(changed_rows[0], combined_outcome=NeutralOutcome.INDETERMINATE, row_digest="")
changed_rule = replace(combined.combination_rule, decision_rows=tuple(changed_rows), rule_digest="")
mutations = (
_configuration("arm-z"),
replace(
value,
exact_scopes=(changed_key.scope,),
denominator_policies=(_policy(changed_key),),
thresholds=_thresholds(changed_key),
sufficiency_rules=(_sufficiency(changed_key),),
configuration_identity_digest="",
),
replace(value, judgment_vocabulary_digest=_digest("judgments-2"), configuration_identity_digest=""),
replace(value, analyzer_identity="analyzer-2", configuration_identity_digest=""),
replace(value, fact_set_digest=_digest("facts-2"), configuration_identity_digest=""),
replace(value, configuration_digest=_digest("configuration-2"), configuration_identity_digest=""),
replace(value, registered_budget_digest=_digest("budget-2"), configuration_identity_digest=""),
replace(value, execution_identity="execution-2", configuration_identity_digest=""),
replace(value, outcome_mapping_digest=_digest("outcomes-2"), configuration_identity_digest=""),
combined,
)
assert all(item.configuration_identity_digest != value.configuration_identity_digest for item in mutations)
assert (
replace(combined, combination_rule=changed_rule, configuration_identity_digest="").configuration_identity_digest
!= combined.configuration_identity_digest
)
def test_configurations_refuse_cross_key_duplicate_unsorted_and_incomplete_values() -> None:
value = _configuration()
other_key = _key("arm-b")
with pytest.raises(EvaluationMeasurementError, match="arm-scope key"):
replace(value, thresholds=_thresholds(other_key), configuration_identity_digest="")
with pytest.raises(EvaluationMeasurementError, match="canonical exact scopes"):
replace(value, exact_scopes=(value.exact_scopes[0],) * 2, configuration_identity_digest="")
with pytest.raises(EvaluationMeasurementError, match="exactly once"):
replace(value, thresholds=value.thresholds[:-1], configuration_identity_digest="")
with pytest.raises(EvaluationMeasurementError, match="canonical order"):
replace(value, thresholds=tuple(reversed(value.thresholds)), configuration_identity_digest="")
with pytest.raises(EvaluationMeasurementError, match="requires a combination rule"):
_configuration("arm-combined", kind=ArmKindV3.COMBINED)
with pytest.raises(EvaluationMeasurementError, match="must not carry"):
_configuration(combination_rule=_combination_rule())
def test_threshold_sufficiency_and_result_contracts_are_exact() -> None:
key = _key()
rule = standard_scoped_metric_rules(key)[1]
result = ScopedMetricResultV3.from_counts(key, rule.metric_id, numerator=8, denominator=10)
assert result.sample_count == 10
assert result.value == 0.8
assert result.interval_lower is not None and result.interval_upper is not None
with pytest.raises(EvaluationMeasurementError, match="fixed comparator"):
replace(_thresholds(key)[0], comparator=Comparator.AT_MOST, threshold_digest="")
with pytest.raises(EvaluationMeasurementError, match="finite"):
replace(_thresholds(key)[0], target=float("nan"), threshold_digest="")
with pytest.raises(EvaluationMeasurementError, match="sample count"):
replace(result, sample_count=9)
with pytest.raises(EvaluationMeasurementError, match="Wilson"):
replace(result, interval_lower=0.0)
def test_aggregate_weights_are_reduced_canonical_and_sum_exactly_to_one() -> None:
keys = (_key("arm-a"), _key("arm-b"))
weights = (AggregateWeightV3(keys[0], 1, 3, ""), AggregateWeightV3(keys[1], 2, 3, ""))
validate_aggregate_weights(keys, (10, 20), weights)
with pytest.raises(EvaluationMeasurementError, match="reduced"):
AggregateWeightV3(keys[0], 2, 6, "")
with pytest.raises(EvaluationMeasurementError, match="sum exactly to one"):
validate_aggregate_weights(keys, (10, 20), (AggregateWeightV3(keys[0], 1, 3, ""), AggregateWeightV3(keys[1], 1, 3, "")))
with pytest.raises(EvaluationMeasurementError, match="one-to-one"):
validate_aggregate_weights(keys, (10, 20), (AggregateWeightV3(keys[0], 1, 2, ""), AggregateWeightV3(keys[0], 1, 2, "")))
with pytest.raises(EvaluationMeasurementError, match="sample counts"):
validate_aggregate_weights(keys, (10,), weights)
def test_exact_types_refuse_subclasses_and_unknown_enum_like_values() -> None:
class DerivedKey(ArmScopeKey):
pass
with pytest.raises(EvaluationMeasurementError, match="exact type"):
DerivedKey("arm-a", ScopeKey("access_control", "python"))
with pytest.raises(EvaluationMeasurementError, match="closed MetricId"):
replace(standard_scoped_metric_rules(_key())[0], metric_id="paired_correctness", rule_digest="") # type: ignore[arg-type]
def test_public_and_lower_configuration_modules_import_in_fresh_processes() -> None:
for module in (
"openultrasast.core.evaluation_measurement",
"openultrasast.core._evaluation_arm_configuration",
):
completed = subprocess.run(
[sys.executable, "-c", f"import {module}; print({module}.__name__)"],
check=False,
capture_output=True,
text=True,
)
assert completed.returncode == 0, completed.stderr
assert completed.stdout.strip() == module
@pytest.mark.parametrize(
("field", "malformed"),
(
("denominator_policies", None),
("denominator_policies", 1),
("denominator_policies", []),
("thresholds", None),
("thresholds", 1),
("thresholds", []),
("sufficiency_rules", None),
("sufficiency_rules", 1),
("sufficiency_rules", []),
),
)
def test_configuration_refuses_malformed_containers_with_contract_error(field: str, malformed: object) -> None:
with pytest.raises(EvaluationMeasurementError):
replace(_configuration(), **{field: malformed, "configuration_identity_digest": ""})
@pytest.mark.parametrize("sample_count", (True, 1.0))
def test_scoped_result_requires_an_exact_integer_sample_count(sample_count: object) -> None:
result = ScopedMetricResultV3.from_counts(_key(), MetricId.VULNERABLE_RECALL, numerator=1, denominator=1)
with pytest.raises(EvaluationMeasurementError, match="sample count"):
replace(result, sample_count=sample_count)
def test_every_nested_arm_scope_key_is_revalidated() -> None:
key = _key()
rules = standard_scoped_metric_rules(key)
policy = DenominatorPolicyV3(key, rules, IntervalMethod.WILSON_95, "")
threshold = _thresholds(key)[0]
sufficiency = _sufficiency(key)
result = ScopedMetricResultV3.from_counts(key, MetricId.VULNERABLE_RECALL, numerator=1, denominator=1)
weight = AggregateWeightV3(key, 1, 1, "")
object.__setattr__(key.scope, "family_id", "")
validators = (
lambda: standard_scoped_metric_rules(key),
rules[0].__post_init__,
policy.__post_init__,
threshold.__post_init__,
sufficiency.__post_init__,
result.__post_init__,
weight.__post_init__,
lambda: validate_aggregate_weights((key,), (1,), (weight,)),
)
for validate in validators:
with pytest.raises(EvaluationMeasurementError, match="family_id"):
validate()
@pytest.mark.parametrize("metric_id", tuple(MetricId))
@pytest.mark.parametrize("statistic", (Statistic.COUNT, Statistic.WILSON_LOWER, Statistic.WILSON_UPPER))
def test_count_and_wilson_statistics_are_allowed_for_every_metric(metric_id: MetricId, statistic: Statistic) -> None:
key = _key()
comparator = (
Comparator.AT_MOST
if metric_id
in {
MetricId.FIXED_FALSE_ALARM_RATE,
MetricId.ORDINARY_FALSE_ALARMS_PER_100,
}
else Comparator.AT_LEAST
)
ScopedThresholdV3(key, metric_id, statistic, comparator, 1.0, "")
@pytest.mark.parametrize("metric_id", tuple(item for item in MetricId if item is not MetricId.ORDINARY_FALSE_ALARMS_PER_100))
def test_rate_is_allowed_only_for_nonordinary_metrics(metric_id: MetricId) -> None:
key = _key()
comparator = Comparator.AT_MOST if metric_id is MetricId.FIXED_FALSE_ALARM_RATE else Comparator.AT_LEAST
ScopedThresholdV3(key, metric_id, Statistic.RATE, comparator, 0.5, "")
with pytest.raises(EvaluationMeasurementError, match="PER_100"):
ScopedThresholdV3(key, metric_id, Statistic.PER_100, comparator, 0.5, "")
def test_ordinary_metric_requires_per_100_or_statistic_independent_count_or_interval() -> None:
key = _key()
ScopedThresholdV3(
key,
MetricId.ORDINARY_FALSE_ALARMS_PER_100,
Statistic.PER_100,
Comparator.AT_MOST,
5.0,
"",
)
with pytest.raises(EvaluationMeasurementError, match="PER_100"):
ScopedThresholdV3(
key,
MetricId.ORDINARY_FALSE_ALARMS_PER_100,
Statistic.RATE,
Comparator.AT_MOST,
0.05,
"",
)
def test_policy_threshold_sufficiency_and_precision_mutations_are_independently_bound() -> None:
value = _configuration()
changed_threshold = replace(value.thresholds[0], target=0.6, threshold_digest="")
threshold_configuration = replace(
value,
thresholds=(changed_threshold,) + value.thresholds[1:],
configuration_identity_digest="",
)
changed_sufficiency = replace(value.sufficiency_rules[0], minimum_pairs=5, rule_digest="")
sufficiency_configuration = replace(
value,
sufficiency_rules=(changed_sufficiency,),
configuration_identity_digest="",
)
changed_precision = replace(
value.sufficiency_rules[0].precision_rules[0],
maximum_wilson_width=0.2,
rule_digest="",
)
precision_sufficiency = replace(
value.sufficiency_rules[0],
precision_rules=(changed_precision,) + value.sufficiency_rules[0].precision_rules[1:],
rule_digest="",
)
precision_configuration = replace(
value,
sufficiency_rules=(precision_sufficiency,),
configuration_identity_digest="",
)
assert (
len(
{
value.configuration_identity_digest,
threshold_configuration.configuration_identity_digest,
sufficiency_configuration.configuration_identity_digest,
precision_configuration.configuration_identity_digest,
}
)
== 4
)
with pytest.raises(EvaluationMeasurementError, match="canonical content"):
replace(value.denominator_policies[0], policy_digest=_digest("substituted-policy"))
def test_cross_key_policy_sufficiency_and_result_are_refused() -> None:
key = _key()
other = _key("arm-b")
value = _configuration()
with pytest.raises(EvaluationMeasurementError, match="canonical arm-scope key"):
replace(value, denominator_policies=(_policy(other),), configuration_identity_digest="")
with pytest.raises(EvaluationMeasurementError, match="canonical arm-scope key"):
replace(value, sufficiency_rules=(_sufficiency(other),), configuration_identity_digest="")
result = ScopedMetricResultV3.from_counts(other, MetricId.VULNERABLE_RECALL, numerator=1, denominator=1)
with pytest.raises(EvaluationMeasurementError, match="arm-scope key"):
validate_scoped_metric_result(result, standard_scoped_metric_rules(key)[1])
@pytest.mark.parametrize(
("key", "metric_id", "numerator", "denominator"),
(
("not-a-key", MetricId.VULNERABLE_RECALL, 1, 2),
(_key(), "vulnerable_recall", 1, 2),
(_key(), None, 1, 2),
(_key(), MetricId.VULNERABLE_RECALL, "1", 2),
(_key(), MetricId.VULNERABLE_RECALL, None, 2),
(_key(), MetricId.VULNERABLE_RECALL, True, 2),
(_key(), MetricId.VULNERABLE_RECALL, 1.0, 2),
(_key(), MetricId.VULNERABLE_RECALL, -1, 2),
(_key(), MetricId.VULNERABLE_RECALL, 1, "2"),
(_key(), MetricId.VULNERABLE_RECALL, 1, None),
(_key(), MetricId.VULNERABLE_RECALL, 1, True),
(_key(), MetricId.VULNERABLE_RECALL, 1, 2.0),
(_key(), MetricId.VULNERABLE_RECALL, 0, 0),
(_key(), MetricId.VULNERABLE_RECALL, 0, -1),
(_key(), MetricId.VULNERABLE_RECALL, 3, 2),
),
)
def test_scoped_result_factory_refuses_invalid_inputs_with_contract_error(
key: object,
metric_id: object,
numerator: object,
denominator: object,
) -> None:
with pytest.raises(EvaluationMeasurementError):
ScopedMetricResultV3.from_counts( # type: ignore[arg-type]
key,
metric_id,
numerator=numerator,
denominator=denominator,
)