feat(detection-core): derive exact evaluation feasibility

This commit is contained in:
Marius Ciepluch
2026-11-10 07:56:20 +01:00
parent c810a559ec
commit 8cdd2de692
5 changed files with 671 additions and 5 deletions
+14
View File
@@ -2972,6 +2972,20 @@ The feasibility rows equal the canonical product of every arm and its exact clai
Every row rederives minimum sizes, threshold reachability, and interval precision from the Every row rederives minimum sizes, threshold reachability, and interval precision from the
reviewed label-blind census. `may_spend` is true only when every row is feasible. reviewed label-blind census. `may_spend` is true only when every row is feasible.
Feasibility uses the shipped V2 jointly-optimal reachability arithmetic independently for
each exact `ArmScopeKey`; it does not predict a post-spend quality result. Denominator
capacities map to the row's pair, vulnerable-side, fixed-side, semantic-site, and model-call
capacities, while ordinary capacity comes only from the ordinary census row for that exact
scope's ecosystem. The reachable witness is `(capacity, capacity)` for at-least metrics and
`(0, capacity)` for fixed or ordinary false-alarm metrics. Precision uses
`(vulnerable_side_count, vulnerable_side_count)` when vulnerable capacity is nonzero,
otherwise `(0, 1)` when fixed-side or same-ecosystem ordinary capacity is nonzero, and
otherwise `(0, 0)`. Each threshold is evaluated from that witness through the fixed metric
algebra and its registered statistic/comparator. Each interval-precision rule uses the same
witness, requires its registered minimum denominator, and compares the derived Wilson 95%
width with the registered maximum. A zero-denominator witness is unattainable and therefore
insufficient. These are pre-spend feasibility facts only: they never produce GO or NO-GO.
#### Observation authority and atomic spend #### Observation authority and atomic spend
```python ```python
+2 -2
View File
@@ -1,7 +1,7 @@
{ {
"feature_name": "detection-core", "feature_name": "detection-core",
"created_at": "2026-10-30T13:55:30Z", "created_at": "2026-10-30T13:55:30Z",
"updated_at": "2026-11-06T12:21:47Z", "updated_at": "2026-11-10T06:56:01Z",
"language": "en", "language": "en",
"phase": "tasks-generated", "phase": "tasks-generated",
"approvals": { "approvals": {
@@ -19,5 +19,5 @@
} }
}, },
"ready_for_implementation": true, "ready_for_implementation": true,
"approval_note": "2026-11-06: Requirements and the merged V3 design were auto-approved by the maintainer's explicit -y request. Additive V3 task groups 12-18 passed the task-plan review and an independent graph sanity review; existing groups 1-11 remain historical V2 context, and blocked task 11.4 is not a V3 prerequisite. Tasks are approved for implementation." "approval_note": "2026-11-10: The maintainer approved the regenerated merge-mode task plan after the feasibility witness amendment. Requirements, design, and tasks remain approved; Task 13.4 and plan/preflight group 13 have now passed independent implementation review and fresh verification."
} }
+5 -3
View File
@@ -486,7 +486,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
- _Boundary: Evaluation Version Compatibility_ - _Boundary: Evaluation Version Compatibility_
- _Depends: 12.1, 12.3_ - _Depends: 12.1, 12.3_
- [ ] 13. Register reviewed multi-arm plans and exact preflight - [x] 13. Register reviewed multi-arm plans and exact preflight
- [x] 13.1 Define component, combined-arm, and declarative combination configurations - [x] 13.1 Define component, combined-arm, and declarative combination configurations
- Represent component and combined arm configurations with exact scopes, policies, thresholds, sufficiency rules, outcome mapping, and a closed declarative combination rule. - Represent component and combined arm configurations with exact scopes, policies, thresholds, sufficiency rules, outcome mapping, and a closed declarative combination rule.
- Require component identities and a finite normalized decision table for every combined arm, with identical-component-candidate-only proof retention. - Require component identities and a finite normalized decision table for every combined arm, with identical-component-candidate-only proof retention.
@@ -510,9 +510,10 @@ contract work and use synthetic/in-memory workflow boundaries only.
- Done when one reviewed multi-arm manifest validates with labels sealed and every review, census, scope, ordinary-ecosystem, or slot substitution is refused before feasibility. - Done when one reviewed multi-arm manifest validates with labels sealed and every review, census, scope, ordinary-ecosystem, or slot substitution is refused before feasibility.
- _Requirements: 17.1, 17.2, 17.3, 18.1, 18.3_ - _Requirements: 17.1, 17.2, 17.3, 18.1, 18.3_
- _Boundary: Evaluation Plan Review_ - _Boundary: Evaluation Plan Review_
- [ ] 13.4 Derive feasibility independently for every planned arm and exact scope - [x] 13.4 Derive feasibility independently for every planned arm and exact scope
- Produce exactly one feasibility row for the canonical product of planned arms and their claimed scopes. - Produce exactly one feasibility row for the canonical product of planned arms and their claimed scopes.
- Recompute minimum sample size, threshold reachability, and Wilson interval precision from the reviewed label-blind census for each row. - Derive each metric's witness from the exact-scope pair, vulnerable-side, fixed-side, semantic-site, and model-call capacities plus only the same-ecosystem ordinary capacity; preserve the fixed V2 precision fallback of vulnerable-over-vulnerable, otherwise zero-over-one when false-positive capacity exists, otherwise zero-over-zero.
- Evaluate registered thresholds, minimum denominators, and Wilson-width rules from that same witness through the fixed metric algebra; treat a zero denominator as insufficiency and never as GO or NO-GO.
- Derive shared spend eligibility only when every row is feasible; keep insufficiency and its reasons distinct from GO and NO-GO. - Derive shared spend eligibility only when every row is feasible; keep insufficiency and its reasons distinct from GO and NO-GO.
- Refuse missing, extra, duplicated, or caller-summarized rows and prevent preparation when one row is insufficient. - Refuse missing, extra, duplicated, or caller-summarized rows and prevent preparation when one row is insufficient.
- Done when a single insufficient scope blocks the shared spend without opening labels, while the complete feasible plan yields one reproducible preflight digest. - Done when a single insufficient scope blocks the shared spend without opening labels, while the complete feasible plan yields one reproducible preflight digest.
@@ -714,6 +715,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
- 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.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. - 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.
- Task 13.3 added exact label-sealed scope/ecosystem census contracts and an independently reviewed plan manifest that binds the declaration, baselines, census, readiness, custody, and bounded trust-resolved review evidence before feasibility. - Task 13.3 added exact label-sealed scope/ecosystem census contracts and an independently reviewed plan manifest that binds the declaration, baselines, census, readiness, custody, and bounded trust-resolved review evidence before feasibility.
- Task 13.4 revalidates the reviewed manifest before deriving one exact arm/scope feasibility row, preserves the V2 reachability witnesses and same-ecosystem ordinary capacity, and keeps insufficiency and zero denominators outside GO/NO-GO while blocking shared spend.
- 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. - 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. - 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. - 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,351 @@
"""Label-blind per-arm/per-scope feasibility for evaluation admission V3."""
from __future__ import annotations
import re
from dataclasses import dataclass
from enum import Enum
from typing import ClassVar, cast
from openultrasast.core import canonical
from openultrasast.core._metric_algebra import metric_values
from openultrasast.core.evaluation_measurement import (
ArmConfigurationV3,
ArmScopeKey,
Comparator,
IntervalPrecisionRuleV3,
MetricId,
ScopeKey,
Statistic,
)
from openultrasast.core.evaluation_plan import (
EvaluationPlanError,
EvaluationPlanManifestV3,
ExactScopeCensusV3,
derive_evaluation_census_digest,
derive_evaluation_census_payload_digest,
derive_evaluation_plan_manifest_digest,
derive_evaluation_plan_manifest_payload_digest,
validate_reviewed_evaluation_plan,
)
from openultrasast.core.evaluation_version import (
EVALUATION_ADMISSION_V3_SCHEMA,
EvaluationV3Contract,
NonAuthorizingV3,
require_exact_v3_contract,
)
from openultrasast.core.factpack import ReviewIndependencePolicy
_DIGEST = re.compile(r"[0-9a-f]{64}")
_SCHEMA = "openultrasast.detection-core.evaluation-feasibility.v3"
class EvaluationFeasibilityError(ValueError):
"""A feasibility value is incomplete, non-canonical, or caller-summarized."""
class FeasibilityStatusV3(Enum):
FEASIBLE = "feasible"
INSUFFICIENT = "insufficient"
def _digest(value: object, field: str) -> str:
if type(value) is not str or _DIGEST.fullmatch(value) is None:
raise EvaluationFeasibilityError(f"{field} must be a full lowercase SHA-256 digest")
return value
def _count(value: object, field: str) -> int:
if type(value) is not int or value < 0:
raise EvaluationFeasibilityError(f"{field} must be a non-negative integer")
return value
def _value(kind: str, payload: canonical.JsonValue) -> canonical.JsonValue:
return {"schema_version": _SCHEMA, "kind": kind, "payload": payload}
def _bind(value: object, field: str, expected: str) -> None:
actual = getattr(value, field)
if actual == "":
object.__setattr__(value, field, expected)
elif _digest(actual, field) != expected:
raise EvaluationFeasibilityError(f"{field} does not match canonical content")
@dataclass(frozen=True)
class ThresholdFeasibilityV3(EvaluationV3Contract, NonAuthorizingV3):
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
threshold_digest: str
attainable: bool
witness_numerator: int
witness_denominator: int
witness_digest: str
def __post_init__(self) -> None:
require_exact_v3_contract(self, ThresholdFeasibilityV3, field="threshold feasibility")
_digest(self.threshold_digest, "threshold digest")
if type(self.attainable) is not bool:
raise EvaluationFeasibilityError("attainable must be exact boolean")
numerator = _count(self.witness_numerator, "witness numerator")
denominator = _count(self.witness_denominator, "witness denominator")
if numerator > denominator:
raise EvaluationFeasibilityError("witness numerator exceeds denominator")
payload = {
"threshold_digest": self.threshold_digest,
"attainable": self.attainable,
"witness_numerator": numerator,
"witness_denominator": denominator,
}
_bind(self, "witness_digest", canonical.content_digest(_value("threshold_feasibility", cast(canonical.JsonValue, payload))))
@dataclass(frozen=True)
class SufficiencyResultV3(EvaluationV3Contract, NonAuthorizingV3):
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
rule_digest: str
minimum_size_passed: bool
interval_precision_passed: bool
reasons: tuple[str, ...]
result_digest: str
def __post_init__(self) -> None:
require_exact_v3_contract(self, SufficiencyResultV3, field="sufficiency result")
_digest(self.rule_digest, "sufficiency rule digest")
if type(self.minimum_size_passed) is not bool or type(self.interval_precision_passed) is not bool:
raise EvaluationFeasibilityError("sufficiency flags must be exact booleans")
if type(self.reasons) is not tuple or any(type(item) is not str or not item for item in self.reasons):
raise EvaluationFeasibilityError("sufficiency reasons must be exact nonempty text")
if self.reasons != tuple(sorted(set(self.reasons))):
raise EvaluationFeasibilityError("sufficiency reasons must be unique and canonical")
if (self.minimum_size_passed and self.interval_precision_passed) != (not self.reasons):
raise EvaluationFeasibilityError("sufficiency reasons do not match flags")
payload = {
"rule_digest": self.rule_digest,
"minimum_size_passed": self.minimum_size_passed,
"interval_precision_passed": self.interval_precision_passed,
"reasons": self.reasons,
}
_bind(self, "result_digest", canonical.content_digest(_value("sufficiency_result", cast(canonical.JsonValue, payload))))
@dataclass(frozen=True)
class ScopeFeasibilityV3(EvaluationV3Contract, NonAuthorizingV3):
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
key: ArmScopeKey
threshold_witnesses: tuple[ThresholdFeasibilityV3, ...]
sufficiency_results: tuple[SufficiencyResultV3, ...]
status: FeasibilityStatusV3
reasons: tuple[str, ...]
result_digest: str
def __post_init__(self) -> None:
require_exact_v3_contract(self, ScopeFeasibilityV3, field="scope feasibility")
if type(self.key) is not ArmScopeKey:
raise EvaluationFeasibilityError("scope feasibility requires exact ArmScopeKey")
self.key.__post_init__()
if (
type(self.threshold_witnesses) is not tuple
or len(self.threshold_witnesses) != len(MetricId)
or any(type(x) is not ThresholdFeasibilityV3 for x in self.threshold_witnesses)
):
raise EvaluationFeasibilityError("threshold witnesses must contain every standard metric in canonical order")
if type(self.sufficiency_results) is not tuple or len(self.sufficiency_results) != 1:
raise EvaluationFeasibilityError("scope feasibility requires one sufficiency result")
for witness in self.threshold_witnesses:
witness.__post_init__()
for sufficiency in self.sufficiency_results:
sufficiency.__post_init__()
if (
type(self.status) is not FeasibilityStatusV3
or type(self.reasons) is not tuple
or any(type(item) is not str or not item for item in self.reasons)
):
raise EvaluationFeasibilityError("scope status and reasons must use closed values")
if self.reasons != tuple(sorted(set(self.reasons))):
raise EvaluationFeasibilityError("scope reasons must be unique and canonical")
passed = all(x.attainable for x in self.threshold_witnesses) and not self.sufficiency_results[0].reasons
if (self.status is FeasibilityStatusV3.FEASIBLE) != passed or (not self.reasons) != passed:
raise EvaluationFeasibilityError("scope status does not match derived feasibility")
payload = {
"key": {"arm_id": self.key.arm_id, "family_id": self.key.scope.family_id, "ecosystem": self.key.scope.ecosystem},
"threshold_witness_digests": tuple(x.witness_digest for x in self.threshold_witnesses),
"sufficiency_result_digests": tuple(x.result_digest for x in self.sufficiency_results),
"status": self.status.value,
"reasons": self.reasons,
}
_bind(self, "result_digest", canonical.content_digest(_value("scope_feasibility", cast(canonical.JsonValue, payload))))
@dataclass(frozen=True)
class EvaluationFeasibilityV3(EvaluationV3Contract, NonAuthorizingV3):
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
plan_manifest_digest: str
rows: tuple[ScopeFeasibilityV3, ...]
may_spend: bool
feasibility_digest: str
def __post_init__(self) -> None:
require_exact_v3_contract(self, EvaluationFeasibilityV3, field="evaluation feasibility")
_digest(self.plan_manifest_digest, "plan manifest digest")
if type(self.rows) is not tuple or not self.rows or any(type(x) is not ScopeFeasibilityV3 for x in self.rows):
raise EvaluationFeasibilityError("feasibility rows must be nonempty exact values")
for row in self.rows:
row.__post_init__()
if tuple(row.key for row in self.rows) != tuple(sorted({row.key for row in self.rows})):
raise EvaluationFeasibilityError("feasibility rows must be unique and canonical")
expected = all(row.status is FeasibilityStatusV3.FEASIBLE for row in self.rows)
if type(self.may_spend) is not bool or self.may_spend != expected:
raise EvaluationFeasibilityError("may_spend must equal all-row feasibility")
payload = {
"plan_manifest_digest": self.plan_manifest_digest,
"row_digests": tuple(row.result_digest for row in self.rows),
"may_spend": self.may_spend,
}
_bind(self, "feasibility_digest", canonical.content_digest(_value("evaluation_feasibility", cast(canonical.JsonValue, payload))))
def _counts(metric: MetricId, scope: ExactScopeCensusV3, ordinary: int) -> tuple[int, int]:
capacities = {
MetricId.PAIRED_CORRECTNESS: scope.pair_count,
MetricId.VULNERABLE_RECALL: scope.vulnerable_side_count,
MetricId.FIXED_FALSE_ALARM_RATE: scope.fixed_side_count,
MetricId.ORDINARY_FALSE_ALARMS_PER_100: ordinary,
MetricId.SEMANTIC_STAGE_COVERAGE: scope.semantic_site_capacity,
MetricId.MODEL_SUCCESS_RATE: scope.model_call_capacity,
}
if metric is MetricId.PRECISION:
if scope.vulnerable_side_count:
return scope.vulnerable_side_count, scope.vulnerable_side_count
return (0, 1) if scope.fixed_side_count or ordinary else (0, 0)
denominator = capacities[metric]
return (0 if metric in {MetricId.FIXED_FALSE_ALARM_RATE, MetricId.ORDINARY_FALSE_ALARMS_PER_100} else denominator, denominator)
def _stat(metric: MetricId, numerator: int, denominator: int, statistic: Statistic) -> float | None:
if denominator == 0:
return None
value, lower, upper = metric_values(metric.value, numerator, denominator)
return {
Statistic.COUNT: float(numerator),
Statistic.RATE: value,
Statistic.PER_100: value,
Statistic.WILSON_LOWER: lower,
Statistic.WILSON_UPPER: upper,
}[statistic]
def _validated_manifest(
manifest: object,
policy: ReviewIndependencePolicy,
resolver: canonical.ContentResolver,
) -> EvaluationPlanManifestV3:
if type(manifest) is not EvaluationPlanManifestV3:
raise EvaluationFeasibilityError("manifest must use exact EvaluationPlanManifestV3")
try:
validate_reviewed_evaluation_plan(manifest.census, manifest, policy, resolver)
except EvaluationPlanError as exc:
raise EvaluationFeasibilityError(f"reviewed plan is invalid: {exc}") from exc
if manifest.census.payload_digest != derive_evaluation_census_payload_digest(manifest.census):
raise EvaluationFeasibilityError("census payload digest cannot be re-derived")
if manifest.census.census_digest != derive_evaluation_census_digest(manifest.census):
raise EvaluationFeasibilityError("census digest cannot be re-derived")
if manifest.payload_digest != derive_evaluation_plan_manifest_payload_digest(manifest):
raise EvaluationFeasibilityError("manifest payload digest cannot be re-derived")
if manifest.manifest_digest != derive_evaluation_plan_manifest_digest(manifest):
raise EvaluationFeasibilityError("manifest digest cannot be re-derived")
return manifest
def _census_maps(
manifest: EvaluationPlanManifestV3,
) -> tuple[dict[ScopeKey, ExactScopeCensusV3], dict[str, int]]:
planned_scopes = tuple(
sorted({scope for configuration in manifest.declaration.arm_configurations for scope in configuration.exact_scopes})
)
actual_scopes = tuple(row.scope for row in manifest.census.scope_rows)
if actual_scopes != planned_scopes:
raise EvaluationFeasibilityError("census scopes do not exactly match planned scopes")
planned_ecosystems = tuple(sorted({scope.ecosystem for scope in planned_scopes}))
actual_ecosystems = tuple(row.ecosystem for row in manifest.census.ordinary_rows)
if actual_ecosystems != planned_ecosystems:
raise EvaluationFeasibilityError("ordinary census ecosystems do not exactly match planned ecosystems")
return (
{row.scope: row for row in manifest.census.scope_rows},
{row.ecosystem: row.ordinary_push_count for row in manifest.census.ordinary_rows},
)
def _precision_passes(precision: IntervalPrecisionRuleV3, census: ExactScopeCensusV3, ordinary: int) -> bool:
numerator, denominator = _counts(precision.metric_id, census, ordinary)
_, lower, upper = metric_values(precision.metric_id.value, numerator, denominator)
return (
denominator >= precision.minimum_denominator
and lower is not None
and upper is not None
and upper - lower <= precision.maximum_wilson_width
)
def _scope_row(config: ArmConfigurationV3, scope_key: ScopeKey, census: ExactScopeCensusV3, ordinary: int) -> ScopeFeasibilityV3:
key = ArmScopeKey(config.arm_id, scope_key)
thresholds = {(row.key, row.metric_id): row for row in config.thresholds}
witnesses = []
for metric in MetricId:
threshold = thresholds[(key, metric)]
numerator, denominator = _counts(metric, census, ordinary)
observed = _stat(metric, numerator, denominator, threshold.statistic)
attainable = observed is not None and (
observed >= threshold.target if threshold.comparator is Comparator.AT_LEAST else observed <= threshold.target
)
witnesses.append(ThresholdFeasibilityV3(threshold.threshold_digest, attainable, numerator, denominator, ""))
rule = next(row for row in config.sufficiency_rules if row.key == key)
minimum_ok = census.pair_count >= rule.minimum_pairs and ordinary >= rule.minimum_ordinary_pushes
precision_ok = all(_precision_passes(item, census, ordinary) for item in rule.precision_rules)
reasons = tuple(sorted(({"minimum_size"} if not minimum_ok else set()) | ({"interval_precision"} if not precision_ok else set())))
sufficiency = SufficiencyResultV3(rule.rule_digest, minimum_ok, precision_ok, reasons, "")
thresholds_ok = all(item.attainable for item in witnesses)
row_reasons = tuple(sorted(({"threshold_unreachable"} if not thresholds_ok else set()) | set(reasons)))
status = FeasibilityStatusV3.FEASIBLE if thresholds_ok and not reasons else FeasibilityStatusV3.INSUFFICIENT
return ScopeFeasibilityV3(key, tuple(witnesses), (sufficiency,), status, row_reasons, "")
def derive_evaluation_feasibility(
manifest: EvaluationPlanManifestV3,
policy: ReviewIndependencePolicy,
resolver: canonical.ContentResolver,
) -> EvaluationFeasibilityV3:
manifest = _validated_manifest(manifest, policy, resolver)
scopes, ordinary = _census_maps(manifest)
result_rows = tuple(
_scope_row(config, scope, scopes[scope], ordinary[scope.ecosystem])
for config in manifest.declaration.arm_configurations
for scope in config.exact_scopes
)
return EvaluationFeasibilityV3(
manifest.manifest_digest, result_rows, all(row.status is FeasibilityStatusV3.FEASIBLE for row in result_rows), ""
)
def validate_evaluation_feasibility(
manifest: EvaluationPlanManifestV3,
feasibility: EvaluationFeasibilityV3,
policy: ReviewIndependencePolicy,
resolver: canonical.ContentResolver,
) -> None:
if type(feasibility) is not EvaluationFeasibilityV3:
raise EvaluationFeasibilityError("feasibility must use exact EvaluationFeasibilityV3")
if feasibility != derive_evaluation_feasibility(manifest, policy, resolver):
raise EvaluationFeasibilityError("feasibility does not match canonical derivation")
__all__ = [
"EvaluationFeasibilityError",
"EvaluationFeasibilityV3",
"FeasibilityStatusV3",
"ScopeFeasibilityV3",
"SufficiencyResultV3",
"ThresholdFeasibilityV3",
"derive_evaluation_feasibility",
"validate_evaluation_feasibility",
]
+299
View File
@@ -0,0 +1,299 @@
"""Per-arm/per-scope V3 pre-spend feasibility."""
from __future__ import annotations
from dataclasses import replace
import pytest
from test_core_evaluation_plan_review import _attestation, _case, _policy
from openultrasast.core import canonical
from openultrasast.core.evaluation_feasibility import (
EvaluationFeasibilityError,
FeasibilityStatusV3,
derive_evaluation_feasibility,
validate_evaluation_feasibility,
)
from openultrasast.core.evaluation_measurement import (
MetricId,
ScopeKey,
Statistic,
)
from openultrasast.core.evaluation_plan import (
EcosystemOrdinaryCensusV3,
create_evaluation_plan_declaration,
derive_evaluation_baselines,
derive_evaluation_census_digest,
derive_evaluation_census_payload_digest,
derive_evaluation_plan_manifest_digest,
derive_evaluation_plan_manifest_payload_digest,
)
def _rebind_census(manifest, census):
provisional = replace(
census,
payload_digest="0" * 64,
review=replace(census.review, subject_digest="0" * 64, attestation_digest="0" * 64),
census_digest="0" * 64,
)
payload = derive_evaluation_census_payload_digest(provisional)
review = _attestation(
payload,
census.review.producer_identity,
census.review.reviewer_identity,
census.review.conflict_disclosure,
)
reviewed = replace(provisional, payload_digest=payload, review=review)
census = replace(reviewed, census_digest=derive_evaluation_census_digest(reviewed))
return _rebind_manifest(manifest, census=census)
def _rebind_manifest(manifest, *, census=None, configurations=None):
declaration = manifest.declaration
if configurations is not None:
inputs = tuple(sorted({slot.input_identity_digest for slot in declaration.expected_observation_slots}))
declaration = create_evaluation_plan_declaration(
population_digest=declaration.population_digest,
freeze_digest=declaration.freeze_digest,
input_set_digest=declaration.input_set_digest,
arm_configurations=tuple(configurations),
input_identity_digests=inputs,
)
draft = replace(
manifest,
declaration=declaration,
baselines=derive_evaluation_baselines(declaration),
census=manifest.census if census is None else census,
payload_digest="0" * 64,
review=replace(manifest.review, subject_digest="0" * 64, attestation_digest="0" * 64),
manifest_digest="0" * 64,
)
payload = derive_evaluation_plan_manifest_payload_digest(draft)
review = _attestation(
payload,
manifest.review.producer_identity,
manifest.review.reviewer_identity,
manifest.review.conflict_disclosure,
)
reviewed = replace(draft, payload_digest=payload, review=review)
return replace(reviewed, manifest_digest=derive_evaluation_plan_manifest_digest(reviewed))
def _feasible_manifest():
_, manifest, policy, resolver = _case()
configurations = []
for config in manifest.declaration.arm_configurations:
sufficiency = []
for rule in config.sufficiency_rules:
precision = tuple(replace(item, maximum_wilson_width=100.0, rule_digest="") for item in rule.precision_rules)
sufficiency.append(replace(rule, precision_rules=precision, rule_digest=""))
configurations.append(replace(config, sufficiency_rules=tuple(sufficiency), configuration_identity_digest=""))
inputs = tuple(sorted({slot.input_identity_digest for slot in manifest.declaration.expected_observation_slots}))
declaration = create_evaluation_plan_declaration(
population_digest=manifest.declaration.population_digest,
freeze_digest=manifest.declaration.freeze_digest,
input_set_digest=manifest.declaration.input_set_digest,
arm_configurations=tuple(configurations),
input_identity_digests=inputs,
)
draft = replace(
manifest,
declaration=declaration,
baselines=derive_evaluation_baselines(declaration),
payload_digest="0" * 64,
review=replace(manifest.review, subject_digest="0" * 64, attestation_digest="0" * 64),
manifest_digest="0" * 64,
)
payload = derive_evaluation_plan_manifest_payload_digest(draft)
review = _attestation(
payload, manifest.review.producer_identity, manifest.review.reviewer_identity, manifest.review.conflict_disclosure
)
reviewed = replace(draft, payload_digest=payload, review=review)
return replace(reviewed, manifest_digest=derive_evaluation_plan_manifest_digest(reviewed)), policy, resolver
def test_derivation_emits_one_canonical_row_per_arm_scope_without_quality_decisions() -> None:
_, manifest, policy, resolver = _case()
result = derive_evaluation_feasibility(manifest, policy, resolver)
expected_keys = tuple((config.arm_id, scope) for config in manifest.declaration.arm_configurations for scope in config.exact_scopes)
assert tuple((row.key.arm_id, row.key.scope) for row in result.rows) == expected_keys
assert result.may_spend is False
assert all(row.status is FeasibilityStatusV3.INSUFFICIENT for row in result.rows)
assert not hasattr(result, "decision")
assert not hasattr(result, "authorize")
def test_threshold_witnesses_use_exact_v2_preserving_capacities() -> None:
_, manifest, policy, resolver = _case()
row = derive_evaluation_feasibility(manifest, policy, resolver).rows[0]
by_metric = dict(zip(tuple(MetricId), row.threshold_witnesses, strict=True))
assert (by_metric[MetricId.PAIRED_CORRECTNESS].witness_numerator, by_metric[MetricId.PAIRED_CORRECTNESS].witness_denominator) == (4, 4)
assert (
by_metric[MetricId.FIXED_FALSE_ALARM_RATE].witness_numerator,
by_metric[MetricId.FIXED_FALSE_ALARM_RATE].witness_denominator,
) == (0, 4)
assert (
by_metric[MetricId.ORDINARY_FALSE_ALARMS_PER_100].witness_numerator,
by_metric[MetricId.ORDINARY_FALSE_ALARMS_PER_100].witness_denominator,
) == (0, 12)
assert (by_metric[MetricId.PRECISION].witness_numerator, by_metric[MetricId.PRECISION].witness_denominator) == (4, 4)
def test_precision_fallback_and_zero_denominator_are_label_blind_and_insufficient() -> None:
census, manifest, policy, resolver = _case()
base = census.scope_rows[0]
fallback = replace(base, pair_count=0, vulnerable_side_count=0, fixed_side_count=0)
changed = replace(census, scope_rows=(fallback,))
fallback_manifest = _rebind_census(manifest, changed)
row = derive_evaluation_feasibility(fallback_manifest, policy, resolver).rows[0]
precision = row.threshold_witnesses[tuple(MetricId).index(MetricId.PRECISION)]
assert (precision.witness_numerator, precision.witness_denominator) == (0, 1)
zero = replace(base, pair_count=0, vulnerable_side_count=0, fixed_side_count=0)
zero_census = replace(
census,
scope_rows=(zero,),
ordinary_rows=(EcosystemOrdinaryCensusV3("python", 0),),
)
zero_manifest = _rebind_census(manifest, zero_census)
result = derive_evaluation_feasibility(zero_manifest, policy, resolver)
precision = result.rows[0].threshold_witnesses[tuple(MetricId).index(MetricId.PRECISION)]
assert (precision.witness_numerator, precision.witness_denominator) == (0, 0)
assert precision.attainable is False
assert result.may_spend is False
@pytest.mark.parametrize(
("metric_id", "statistic", "target"),
(
(MetricId.PAIRED_CORRECTNESS, Statistic.COUNT, 1.0),
(MetricId.PAIRED_CORRECTNESS, Statistic.RATE, 0.5),
(MetricId.ORDINARY_FALSE_ALARMS_PER_100, Statistic.PER_100, 1.0),
(MetricId.PAIRED_CORRECTNESS, Statistic.WILSON_LOWER, 0.0),
(MetricId.FIXED_FALSE_ALARM_RATE, Statistic.WILSON_UPPER, 1.0),
),
)
def test_every_threshold_statistic_uses_the_fixed_comparator(metric_id: MetricId, statistic: Statistic, target: float) -> None:
_, manifest, policy, resolver = _case()
configurations = []
for config in manifest.declaration.arm_configurations:
thresholds = tuple(
replace(item, statistic=statistic, target=target, threshold_digest="") if item.metric_id is metric_id else item
for item in config.thresholds
)
configurations.append(replace(config, thresholds=thresholds, configuration_identity_digest=""))
changed = _rebind_manifest(manifest, configurations=configurations)
result = derive_evaluation_feasibility(changed, policy, resolver)
index = tuple(MetricId).index(metric_id)
assert all(row.threshold_witnesses[index].attainable for row in result.rows)
def test_minimum_denominator_and_wilson_width_fail_independently() -> None:
_, manifest, policy, resolver = _case()
def changed_manifest(*, minimum: int, width: float):
configurations = []
for config in manifest.declaration.arm_configurations:
rules = []
for rule in config.sufficiency_rules:
precision = tuple(
replace(item, minimum_denominator=minimum, maximum_wilson_width=width, rule_digest="") for item in rule.precision_rules
)
rules.append(replace(rule, precision_rules=precision, rule_digest=""))
configurations.append(replace(config, sufficiency_rules=tuple(rules), configuration_identity_digest=""))
return _rebind_manifest(manifest, configurations=configurations)
minimum_failure = derive_evaluation_feasibility(changed_manifest(minimum=100, width=100.0), policy, resolver)
width_failure = derive_evaluation_feasibility(changed_manifest(minimum=1, width=0.0001), policy, resolver)
assert all(not row.sufficiency_results[0].interval_precision_passed for row in minimum_failure.rows)
assert all(not row.sufficiency_results[0].interval_precision_passed for row in width_failure.rows)
def test_single_insufficient_row_blocks_shared_spend_and_is_reproducible() -> None:
_, manifest, policy, resolver = _case()
first = derive_evaluation_feasibility(manifest, policy, resolver)
second = derive_evaluation_feasibility(manifest, policy, resolver)
assert first == second
assert first.feasibility_digest == second.feasibility_digest
assert not first.may_spend
def test_complete_feasible_plan_yields_one_reproducible_may_spend_digest() -> None:
manifest, policy, resolver = _feasible_manifest()
first = derive_evaluation_feasibility(manifest, policy, resolver)
second = derive_evaluation_feasibility(manifest, policy, resolver)
assert first == second
assert first.may_spend is True
assert all(row.status is FeasibilityStatusV3.FEASIBLE for row in first.rows)
def test_missing_extra_duplicate_cross_key_and_caller_summaries_are_refused() -> None:
_, manifest, policy, resolver = _case()
value = derive_evaluation_feasibility(manifest, policy, resolver)
mutations = (
{"rows": value.rows[:-1], "feasibility_digest": ""},
{"rows": value.rows + (value.rows[0],), "feasibility_digest": ""},
{"may_spend": not value.may_spend, "feasibility_digest": ""},
{"plan_manifest_digest": "0" * 64, "feasibility_digest": ""},
)
for changes in mutations:
with pytest.raises(EvaluationFeasibilityError):
validate_evaluation_feasibility(manifest, replace(value, **changes), policy, resolver)
with pytest.raises(EvaluationFeasibilityError):
replace(value, rows=tuple(reversed(value.rows)), feasibility_digest="")
with pytest.raises(EvaluationFeasibilityError):
replace(value, rows=(replace(value.rows[0], key=value.rows[1].key, result_digest=""),) + value.rows[1:])
changed_witness = replace(value.rows[0].threshold_witnesses[0], attainable=False, witness_digest="")
changed_row = replace(
value.rows[0],
threshold_witnesses=(changed_witness,) + value.rows[0].threshold_witnesses[1:],
status=FeasibilityStatusV3.INSUFFICIENT,
reasons=("threshold_unreachable",),
result_digest="",
)
rehashed = replace(value, rows=(changed_row,) + value.rows[1:], feasibility_digest="")
with pytest.raises(EvaluationFeasibilityError):
validate_evaluation_feasibility(manifest, rehashed, policy, resolver)
def test_review_trust_independence_and_subject_are_revalidated_before_arithmetic() -> None:
_, manifest, policy, resolver = _case()
wrong_subject = replace(manifest.review, subject_digest="0" * 64)
self_review = replace(
manifest.review,
producer_identity=manifest.review.reviewer_identity,
attestation_digest="0" * 64,
)
for review in (wrong_subject, self_review):
with pytest.raises(EvaluationFeasibilityError, match="reviewed plan"):
derive_evaluation_feasibility(replace(manifest, review=review), policy, resolver)
with pytest.raises((canonical.ArtifactResolutionError, canonical.ArtifactValidationError)):
derive_evaluation_feasibility(
manifest,
_policy(manifest.review.reviewer_identity, stores=("other-store",)),
resolver,
)
def test_scope_and_ecosystem_mismatch_fail_before_lookup_with_controlled_errors() -> None:
census, manifest, policy, resolver = _case()
wrong_scope = replace(census.scope_rows[0], scope=ScopeKey("injection", "python"))
wrong_scope_manifest = _rebind_census(manifest, replace(census, scope_rows=(wrong_scope,)))
wrong_ecosystem_manifest = _rebind_census(
manifest,
replace(census, ordinary_rows=(EcosystemOrdinaryCensusV3("javascript", 12),)),
)
for changed in (wrong_scope_manifest, wrong_ecosystem_manifest):
with pytest.raises(EvaluationFeasibilityError, match="reviewed plan"):
derive_evaluation_feasibility(changed, policy, resolver)
def test_malformed_manifest_and_feasibility_fail_through_contract_error() -> None:
_, manifest, policy, resolver = _case()
with pytest.raises(EvaluationFeasibilityError):
derive_evaluation_feasibility(None, policy, resolver) # type: ignore[arg-type]
with pytest.raises(EvaluationFeasibilityError):
validate_evaluation_feasibility(manifest, None, policy, resolver) # type: ignore[arg-type]