feat(detection-core): derive non-authorizing aggregates

This commit is contained in:
Marius Ciepluch
2026-11-11 17:08:45 +01:00
parent 101de60e70
commit b452333eb4
3 changed files with 336 additions and 2 deletions
+3 -2
View File
@@ -612,7 +612,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
- _Boundary: Proof Continuity_
- _Depends: 15.5_
- [ ] 16. Derive exact scoped metrics and completed reports
- [x] 16. Derive exact scoped metrics and completed reports
- [x] 16.1 Partition quality evidence by exact arm, family, and ecosystem
- Select vulnerable and fixed cases only from the independently released exact scope and derive pair correctness without cross-scope reuse.
- Derive precision only from findings and cases assigned to the same arm-scope key under its reviewed denominator policy.
@@ -643,7 +643,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
- Done when every completed scope receives one reproducible decision and every incomplete or impaired fixture is refused without a quality decision.
- _Requirements: 20.1, 20.2, 20.3, 20.8_
- _Boundary: Evaluation Report_
- [ ] 16.5 Derive optional aggregates that can never authorize
- [x] 16.5 Derive optional aggregates that can never authorize
- Bind aggregate constituents, sample counts, canonical rational weights, and derived metric values to exact arm-scope metric identities.
- Require weights to be non-negative, canonical, one-to-one with constituents, and sum exactly to one through integer arithmetic.
- Exclude gates, GO/NO-GO, proof promotion, and every consumer-authorization capability from the aggregate contract.
@@ -750,6 +750,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
- Task 16.2 reconciles exact ordinary-push identity sets within each reviewed ecosystem, refuses cross-ecosystem reuse, and derives whole-population coverage from the globally deduplicated released push union.
- Task 16.3 derives the complete seven-metric bundle with fixed algebra and Wilson intervals only after exact census and released-lineage reconciliation, treating zero denominators, missing metrics, or inconsistent projections as invalid evidence.
- Task 16.4 emits non-authorizing completed scope reports only after canonical gate, operational, observation, release, and combination-lineage replay; incomplete or impaired measurement remains outside GO/NO-GO.
- Task 16.5 derives optional aggregates only from complete canonical scoped metrics using exact rational weights and reproducible constituent identities, while exposing no gate, decision, proof, or authorization capability.
- 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,212 @@
"""Optional non-authorizing aggregate summaries for evaluation admission V3."""
from __future__ import annotations
import math
import re
from dataclasses import dataclass
from fractions import Fraction
from typing import ClassVar
from openultrasast.core import canonical
from openultrasast.core.evaluation_measurement import (
AggregateWeightV3,
ArmScopeKey,
EvaluationMeasurementError,
MetricId,
ScopedMetricResultV3,
validate_aggregate_weights,
)
from openultrasast.core.evaluation_version import (
EVALUATION_ADMISSION_V3_SCHEMA,
EvaluationV3Contract,
NonAuthorizingV3,
require_exact_v3_contract,
)
_SCHEMA = "openultrasast.detection-core.evaluation-aggregate.v3"
_DIGEST = re.compile(r"[0-9a-f]{64}")
class EvaluationAggregateError(ValueError):
"""An aggregate cannot be reproduced from complete exact-scope metrics."""
def _bind(value: object, field: str, expected: str) -> None:
actual = getattr(value, field)
if actual == "":
object.__setattr__(value, field, expected)
elif type(actual) is not str or _DIGEST.fullmatch(actual) is None or actual != expected:
raise EvaluationAggregateError(f"{field} does not match canonical content")
def _key_value(key: ArmScopeKey) -> canonical.JsonValue:
return {"arm_id": key.arm_id, "family_id": key.scope.family_id, "ecosystem": key.scope.ecosystem}
def _scoped_metric_value(metric: ScopedMetricResultV3) -> canonical.JsonValue:
return {
"key": _key_value(metric.key),
"metric_id": metric.metric_id.value,
"numerator": metric.numerator,
"denominator": metric.denominator,
"sample_count": metric.sample_count,
"value": metric.value,
"interval_method": metric.interval_method.value,
"interval_lower": metric.interval_lower,
"interval_upper": metric.interval_upper,
}
def _scoped_metric_digest(metric: ScopedMetricResultV3) -> str:
metric.__post_init__()
return canonical.content_digest({"schema_version": _SCHEMA, "kind": "scoped_metric", "payload": _scoped_metric_value(metric)})
def _aggregate_metric_value(metric: AggregateMetricV3) -> canonical.JsonValue:
return {
"metric_id": metric.metric_id.value,
"weighted_value": metric.weighted_value,
"constituent_metric_digests": metric.constituent_metric_digests,
}
@dataclass(frozen=True)
class AggregateMetricV3(EvaluationV3Contract, NonAuthorizingV3):
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
metric_id: MetricId
weighted_value: float
constituent_metric_digests: tuple[str, ...]
metric_digest: str
def __post_init__(self) -> None:
require_exact_v3_contract(self, AggregateMetricV3, field="aggregate metric")
if type(self.metric_id) is not MetricId:
raise EvaluationAggregateError("aggregate metric requires a closed metric identity")
if type(self.weighted_value) is not float or not math.isfinite(self.weighted_value):
raise EvaluationAggregateError("aggregate metric value must be a finite float")
digests = self.constituent_metric_digests
if type(digests) is not tuple or not digests:
raise EvaluationAggregateError("aggregate metric requires constituent metric identities")
if any(type(item) is not str or _DIGEST.fullmatch(item) is None for item in digests):
raise EvaluationAggregateError("constituent metric identities must be full lowercase SHA-256 digests")
payload = _aggregate_metric_value(self)
_bind(self, "metric_digest", canonical.content_digest({"schema_version": _SCHEMA, "kind": "metric", "payload": payload}))
def _weight_value(weight: AggregateWeightV3) -> canonical.JsonValue:
return {
"key": _key_value(weight.key),
"numerator": weight.numerator,
"denominator": weight.denominator,
"weight_digest": weight.weight_digest,
}
@dataclass(frozen=True)
class EvaluationAggregateV3(EvaluationV3Contract, NonAuthorizingV3):
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
constituents: tuple[ArmScopeKey, ...]
sample_counts: tuple[int, ...]
weights: tuple[AggregateWeightV3, ...]
metrics: tuple[AggregateMetricV3, ...]
aggregate_digest: str
def __post_init__(self) -> None:
require_exact_v3_contract(self, EvaluationAggregateV3, field="evaluation aggregate")
try:
validate_aggregate_weights(self.constituents, self.sample_counts, self.weights)
except EvaluationMeasurementError as exc:
raise EvaluationAggregateError(f"aggregate weights or sample counts are invalid: {exc}") from exc
if type(self.metrics) is not tuple:
raise EvaluationAggregateError("aggregate metrics must use an exact tuple")
metric_ids = tuple(row.metric_id for row in self.metrics if type(row) is AggregateMetricV3)
if metric_ids != tuple(MetricId):
raise EvaluationAggregateError("aggregate requires every metric in canonical order")
for row in self.metrics:
row.__post_init__()
if len(row.constituent_metric_digests) != len(self.constituents):
raise EvaluationAggregateError("aggregate metric identities must align one-to-one with constituents")
payload: canonical.JsonValue = {
"constituents": tuple(_key_value(key) for key in self.constituents),
"sample_counts": self.sample_counts,
"weights": tuple(_weight_value(weight) for weight in self.weights),
"metric_digests": tuple(metric.metric_digest for metric in self.metrics),
}
_bind(self, "aggregate_digest", canonical.content_digest({"schema_version": _SCHEMA, "kind": "aggregate", "payload": payload}))
def _validate_source_metrics(metrics: object) -> tuple[tuple[ArmScopeKey, ...], tuple[ScopedMetricResultV3, ...]]:
if type(metrics) is not tuple or not metrics or any(type(item) is not ScopedMetricResultV3 for item in metrics):
raise EvaluationAggregateError("aggregate source metrics must be a nonempty exact tuple")
for metric in metrics:
metric.__post_init__()
if metric.value is None:
raise EvaluationAggregateError("aggregate source metric value must be complete")
keys = tuple(sorted({metric.key for metric in metrics}))
expected = tuple((key, metric_id) for key in keys for metric_id in MetricId)
actual = tuple((metric.key, metric.metric_id) for metric in metrics)
if actual != expected:
raise EvaluationAggregateError("aggregate source metrics must be complete and in canonical order")
return keys, metrics
def _derive_metric_rows(
keys: tuple[ArmScopeKey, ...],
metrics: tuple[ScopedMetricResultV3, ...],
weights: tuple[AggregateWeightV3, ...],
) -> tuple[AggregateMetricV3, ...]:
metrics_by_identity = {(metric.key, metric.metric_id): metric for metric in metrics}
rows = []
for metric_id in MetricId:
selected = tuple(metrics_by_identity[(key, metric_id)] for key in keys)
weighted = math.fsum(
metric.value * float(Fraction(weight.numerator, weight.denominator))
for metric, weight in zip(selected, weights, strict=True)
if metric.value is not None
)
rows.append(AggregateMetricV3(metric_id, weighted, tuple(_scoped_metric_digest(metric) for metric in selected), ""))
return tuple(rows)
def derive_evaluation_aggregate_v3(
metrics: tuple[ScopedMetricResultV3, ...],
sample_counts: tuple[int, ...],
weights: tuple[AggregateWeightV3, ...],
) -> EvaluationAggregateV3:
"""Derive an optional summary that has no consumer-authority capability."""
try:
keys, selected = _validate_source_metrics(metrics)
validate_aggregate_weights(keys, sample_counts, weights)
rows = _derive_metric_rows(keys, selected, weights)
return EvaluationAggregateV3(keys, sample_counts, weights, rows, "")
except EvaluationAggregateError:
raise
except (EvaluationMeasurementError, AttributeError, KeyError, TypeError, ValueError) as exc:
raise EvaluationAggregateError(f"aggregate derivation refused invalid evidence: {exc}") from exc
def validate_evaluation_aggregate_v3(
aggregate: EvaluationAggregateV3,
metrics: tuple[ScopedMetricResultV3, ...],
) -> None:
"""Reproduce an aggregate exactly from its canonical scoped metric identities."""
try:
require_exact_v3_contract(aggregate, EvaluationAggregateV3, field="evaluation aggregate")
aggregate.__post_init__()
expected = derive_evaluation_aggregate_v3(metrics, aggregate.sample_counts, aggregate.weights)
if aggregate != expected:
raise EvaluationAggregateError("aggregate does not reproduce from exact scoped metrics")
except EvaluationAggregateError:
raise
except (EvaluationMeasurementError, AttributeError, KeyError, TypeError, ValueError) as exc:
raise EvaluationAggregateError(f"aggregate validation refused invalid evidence: {exc}") from exc
__all__ = [
"AggregateMetricV3",
"EvaluationAggregateError",
"EvaluationAggregateV3",
"derive_evaluation_aggregate_v3",
"validate_evaluation_aggregate_v3",
]
+121
View File
@@ -0,0 +1,121 @@
"""Optional non-authorizing aggregates for evaluation V3."""
from __future__ import annotations
import math
from dataclasses import replace
import pytest
from openultrasast.core.evaluation_measurement import (
AggregateWeightV3,
ArmScopeKey,
MetricId,
ScopedMetricResultV3,
ScopeKey,
)
def _key(arm_id: str, ecosystem: str = "python") -> ArmScopeKey:
return ArmScopeKey(arm_id, ScopeKey("reference-family", ecosystem))
def _inputs():
keys = (_key("arm-a"), _key("arm-b", "javascript"))
counts = ((1, 2), (3, 4))
metrics = tuple(
ScopedMetricResultV3.from_counts(key, metric_id, numerator=numerator, denominator=denominator)
for key, (numerator, denominator) in zip(keys, counts, strict=True)
for metric_id in MetricId
)
sample_counts = (2, 4)
weights = (
AggregateWeightV3(keys[0], 1, 3, ""),
AggregateWeightV3(keys[1], 2, 3, ""),
)
return keys, metrics, sample_counts, weights
def _derive(metrics, sample_counts, weights):
from openultrasast.core.evaluation_aggregate import derive_evaluation_aggregate_v3
return derive_evaluation_aggregate_v3(metrics, sample_counts, weights)
def test_valid_aggregate_reproduces_every_weighted_metric_and_identity() -> None:
keys, metrics, sample_counts, weights = _inputs()
aggregate = _derive(metrics, sample_counts, weights)
assert aggregate.constituents == keys
assert aggregate.sample_counts == sample_counts
assert aggregate.weights == weights
assert tuple(row.metric_id for row in aggregate.metrics) == tuple(MetricId)
for row in aggregate.metrics:
values = tuple(metric.value for metric in metrics if metric.metric_id is row.metric_id)
assert None not in values
expected = math.fsum((values[0] * (1 / 3), values[1] * (2 / 3)))
assert row.weighted_value.hex() == expected.hex()
assert len(row.constituent_metric_digests) == len(keys)
def test_aggregate_requires_complete_canonical_exact_scope_metric_sets() -> None:
_, metrics, sample_counts, weights = _inputs()
malformed = (metrics[:-1], tuple(reversed(metrics)), list(metrics))
for supplied in malformed:
with pytest.raises(ValueError, match="complete|canonical|exact tuple"):
_derive(supplied, sample_counts, weights)
def test_aggregate_requires_canonical_one_to_one_weights_and_sample_counts() -> None:
keys, metrics, sample_counts, weights = _inputs()
invalid_weights = (
AggregateWeightV3(keys[0], 1, 3, ""),
AggregateWeightV3(keys[1], 1, 3, ""),
)
with pytest.raises(ValueError, match="sum exactly to one"):
_derive(metrics, sample_counts, invalid_weights)
with pytest.raises(ValueError, match="sample counts"):
_derive(metrics, (2,), weights)
with pytest.raises(ValueError, match="sample counts"):
_derive(metrics, (2, 0), weights)
def test_aggregate_validation_rederives_values_digests_and_weight_binding() -> None:
from openultrasast.core.evaluation_aggregate import (
EvaluationAggregateError,
validate_evaluation_aggregate_v3,
)
_, metrics, sample_counts, weights = _inputs()
aggregate = _derive(metrics, sample_counts, weights)
validate_evaluation_aggregate_v3(aggregate, metrics)
changed_metric = replace(aggregate.metrics[0], weighted_value=0.75, metric_digest="")
changed = replace(aggregate, metrics=(changed_metric,) + aggregate.metrics[1:], aggregate_digest="")
with pytest.raises(EvaluationAggregateError, match="reproduce"):
validate_evaluation_aggregate_v3(changed, metrics)
swapped_weights = (
AggregateWeightV3(aggregate.constituents[0], 2, 3, ""),
AggregateWeightV3(aggregate.constituents[1], 1, 3, ""),
)
reweighted = _derive(metrics, sample_counts, swapped_weights)
assert reweighted.aggregate_digest != aggregate.aggregate_digest
assert reweighted.metrics[0].metric_digest != aggregate.metrics[0].metric_digest
def test_aggregate_contract_has_no_gate_decision_proof_or_authority_capability() -> None:
from openultrasast.core.evaluation_aggregate import AggregateMetricV3, EvaluationAggregateV3
from openultrasast.core.evaluation_version import NonAuthorizingV3
fields = set(EvaluationAggregateV3.__dataclass_fields__) | set(AggregateMetricV3.__dataclass_fields__)
assert not {"gate", "decision", "proof", "authorization", "consumer_authority"} & fields
assert issubclass(EvaluationAggregateV3, NonAuthorizingV3)
assert not any(name.startswith("authorize") for name in dir(EvaluationAggregateV3))
def test_v2_metric_algebra_remains_unchanged() -> None:
from openultrasast.core import admission_metrics
assert admission_metrics._metric_counts.__name__ == "_metric_counts"