mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
feat(detection-core): extract version-neutral metric arithmetic
This commit is contained in:
@@ -460,7 +460,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
|
||||
- _Requirements: 16.1, 16.2, 16.3, 16.4_
|
||||
- _Boundary: V2 Admission Compatibility_
|
||||
- _Depends: 8.9, 8.10_
|
||||
- [ ] 12.2 Extract version-neutral metric arithmetic without changing V2
|
||||
- [x] 12.2 Extract version-neutral metric arithmetic without changing V2
|
||||
- Isolate only the closed standard-metric algebra and Wilson calculation; keep every serialized V2 identity and validator in its existing owner.
|
||||
- Route V2 through the shared arithmetic and compare all frozen V2 outputs byte-for-byte.
|
||||
- Expose the same pure arithmetic to V3 without accepting a V2 policy, result, or report as a V3 value.
|
||||
@@ -708,6 +708,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
|
||||
## Implementation Notes
|
||||
|
||||
- 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.
|
||||
- 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,52 @@
|
||||
"""Version-neutral arithmetic for the closed standard metric set."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
_WILSON_Z_95 = 1.959963984540054
|
||||
_STANDARD_METRIC_ALGEBRA = {
|
||||
"paired_correctness": ("correct_pairs", "pairs", "at_least"),
|
||||
"vulnerable_recall": ("vulnerable_violation_cases", "vulnerable_sides", "at_least"),
|
||||
"fixed_false_alarm_rate": ("fixed_defect_cases", "fixed_sides", "at_most"),
|
||||
"ordinary_false_alarms_per_100": ("ordinary_defect_cases", "ordinary_cases", "at_most"),
|
||||
"precision": ("true_defect_cases", "all_defect_cases", "at_least"),
|
||||
"semantic_stage_coverage": ("sites_recognized", "sites_considered", "at_least"),
|
||||
"model_success_rate": ("successful_model_calls", "model_calls", "at_least"),
|
||||
}
|
||||
|
||||
|
||||
def metric_algebra(metric_id: str) -> tuple[str, str, str]:
|
||||
"""Return numerator, denominator, and comparator identities for one metric."""
|
||||
try:
|
||||
return _STANDARD_METRIC_ALGEBRA[metric_id]
|
||||
except (KeyError, TypeError) as exc:
|
||||
raise ValueError("unknown standard metric identity") from exc
|
||||
|
||||
|
||||
def _wilson_95(numerator: int, denominator: int) -> tuple[float, float]:
|
||||
proportion = numerator / denominator
|
||||
z_squared = _WILSON_Z_95 * _WILSON_Z_95
|
||||
denominator_term = 1.0 + z_squared / denominator
|
||||
center = (proportion + z_squared / (2.0 * denominator)) / denominator_term
|
||||
margin = (_WILSON_Z_95 / denominator_term) * math.sqrt(
|
||||
proportion * (1.0 - proportion) / denominator + z_squared / (4.0 * denominator * denominator)
|
||||
)
|
||||
return center - margin, center + margin
|
||||
|
||||
|
||||
def metric_values(
|
||||
metric_id: str,
|
||||
numerator: int,
|
||||
denominator: int,
|
||||
) -> tuple[float | None, float | None, float | None]:
|
||||
"""Derive the value and Wilson interval for one closed standard metric."""
|
||||
metric_algebra(metric_id)
|
||||
if denominator == 0:
|
||||
return None, None, None
|
||||
lower, upper = _wilson_95(numerator, denominator)
|
||||
scale = 100.0 if metric_id == "ordinary_false_alarms_per_100" else 1.0
|
||||
return (numerator / denominator) * scale, lower * scale, upper * scale
|
||||
|
||||
|
||||
__all__ = ["metric_algebra", "metric_values"]
|
||||
@@ -10,12 +10,13 @@ from enum import Enum
|
||||
|
||||
from openultrasast.core import canonical
|
||||
from openultrasast.core._closed_graph import closed_graph_problem
|
||||
from openultrasast.core._metric_algebra import metric_algebra as _shared_metric_algebra
|
||||
from openultrasast.core._metric_algebra import metric_values as _shared_metric_values
|
||||
|
||||
BASELINE_IDENTITY_SCHEMA = "openultrasast.detection-core.baseline-identity.v2"
|
||||
DENOMINATOR_POLICY_SCHEMA = "openultrasast.detection-core.denominator-policy.v2"
|
||||
IDENTITY_SET_SCHEMA = "openultrasast.detection-core.identity-set.v2"
|
||||
_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||
_WILSON_Z_95 = 1.959963984540054
|
||||
|
||||
|
||||
class MeasurementContractError(ValueError):
|
||||
@@ -231,35 +232,9 @@ class Comparator(Enum):
|
||||
AT_MOST = "at_most"
|
||||
|
||||
|
||||
_ALGEBRA = {
|
||||
MetricId.PAIRED_CORRECTNESS: (NumeratorKind.CORRECT_PAIRS, DenominatorKind.PAIRS, Comparator.AT_LEAST),
|
||||
MetricId.VULNERABLE_RECALL: (
|
||||
NumeratorKind.VULNERABLE_VIOLATION_CASES,
|
||||
DenominatorKind.VULNERABLE_SIDES,
|
||||
Comparator.AT_LEAST,
|
||||
),
|
||||
MetricId.FIXED_FALSE_ALARM_RATE: (
|
||||
NumeratorKind.FIXED_DEFECT_CASES,
|
||||
DenominatorKind.FIXED_SIDES,
|
||||
Comparator.AT_MOST,
|
||||
),
|
||||
MetricId.ORDINARY_FALSE_ALARMS_PER_100: (
|
||||
NumeratorKind.ORDINARY_DEFECT_CASES,
|
||||
DenominatorKind.ORDINARY_CASES,
|
||||
Comparator.AT_MOST,
|
||||
),
|
||||
MetricId.PRECISION: (NumeratorKind.TRUE_DEFECT_CASES, DenominatorKind.ALL_DEFECT_CASES, Comparator.AT_LEAST),
|
||||
MetricId.SEMANTIC_STAGE_COVERAGE: (
|
||||
NumeratorKind.SITES_RECOGNIZED,
|
||||
DenominatorKind.SITES_CONSIDERED,
|
||||
Comparator.AT_LEAST,
|
||||
),
|
||||
MetricId.MODEL_SUCCESS_RATE: (
|
||||
NumeratorKind.SUCCESSFUL_MODEL_CALLS,
|
||||
DenominatorKind.MODEL_CALLS,
|
||||
Comparator.AT_LEAST,
|
||||
),
|
||||
}
|
||||
def _metric_algebra(metric_id: MetricId) -> tuple[NumeratorKind, DenominatorKind, Comparator]:
|
||||
numerator, denominator, comparator = _shared_metric_algebra(metric_id.value)
|
||||
return NumeratorKind(numerator), DenominatorKind(denominator), Comparator(comparator)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -279,7 +254,11 @@ class MetricRule:
|
||||
|
||||
def standard_metric_rules(scopes: tuple[ScopeKey, ...]) -> tuple[MetricRule, ...]:
|
||||
_canonical_scopes(scopes, "metric scopes")
|
||||
return tuple(MetricRule(metric, scopes, _ALGEBRA[metric][0], _ALGEBRA[metric][1]) for metric in MetricId)
|
||||
rules = []
|
||||
for metric in MetricId:
|
||||
numerator, denominator, _ = _metric_algebra(metric)
|
||||
rules.append(MetricRule(metric, scopes, numerator, denominator))
|
||||
return tuple(rules)
|
||||
|
||||
|
||||
def _rule_value(value: MetricRule) -> canonical.JsonValue:
|
||||
@@ -315,7 +294,7 @@ def _validate_policy(value: DenominatorPolicy) -> None:
|
||||
raise MeasurementContractError("each standard metric must occur exactly once in canonical order")
|
||||
for rule in value.rules:
|
||||
rule.__post_init__()
|
||||
expected_numerator, expected_denominator, _ = _ALGEBRA[rule.metric_id]
|
||||
expected_numerator, expected_denominator, _ = _metric_algebra(rule.metric_id)
|
||||
if (rule.numerator, rule.denominator) != (expected_numerator, expected_denominator):
|
||||
raise MeasurementContractError("metric rule violates the fixed algebra")
|
||||
if value.interval_method is not IntervalMethod.WILSON_95:
|
||||
@@ -365,30 +344,11 @@ class MetricResult:
|
||||
def _validate_rule(rule: MetricRule) -> None:
|
||||
if not isinstance(rule, MetricRule):
|
||||
raise MeasurementContractError("rule must be a MetricRule")
|
||||
expected = _ALGEBRA[rule.metric_id]
|
||||
expected = _metric_algebra(rule.metric_id)
|
||||
if (rule.numerator, rule.denominator) != expected[:2]:
|
||||
raise MeasurementContractError("metric rule violates the fixed algebra")
|
||||
|
||||
|
||||
def _wilson(numerator: int, denominator: int) -> tuple[float, float]:
|
||||
proportion = numerator / denominator
|
||||
z_squared = _WILSON_Z_95 * _WILSON_Z_95
|
||||
denominator_term = 1.0 + z_squared / denominator
|
||||
center = (proportion + z_squared / (2.0 * denominator)) / denominator_term
|
||||
margin = (_WILSON_Z_95 / denominator_term) * math.sqrt(
|
||||
proportion * (1.0 - proportion) / denominator + z_squared / (4.0 * denominator * denominator)
|
||||
)
|
||||
return center - margin, center + margin
|
||||
|
||||
|
||||
def _metric_values(metric_id: MetricId, numerator: int, denominator: int) -> tuple[float | None, float | None, float | None]:
|
||||
if denominator == 0:
|
||||
return None, None, None
|
||||
lower, upper = _wilson(numerator, denominator)
|
||||
scale = 100.0 if metric_id is MetricId.ORDINARY_FALSE_ALARMS_PER_100 else 1.0
|
||||
return (numerator / denominator) * scale, lower * scale, upper * scale
|
||||
|
||||
|
||||
def _canonical_metric_float(actual: object, expected: float | None) -> bool:
|
||||
if expected is None:
|
||||
return actual is None
|
||||
@@ -405,7 +365,7 @@ def _validate_result(result: MetricResult) -> None:
|
||||
if result.interval_method is not IntervalMethod.WILSON_95:
|
||||
raise MeasurementContractError("interval method must be Wilson 95%")
|
||||
actual = (result.value, result.interval_lower, result.interval_upper)
|
||||
expected = _metric_values(result.metric_id, numerator, denominator)
|
||||
expected = _shared_metric_values(result.metric_id.value, numerator, denominator)
|
||||
if not all(_canonical_metric_float(item, expected[index]) for index, item in enumerate(actual)):
|
||||
raise MeasurementContractError("metric values do not match the fixed Wilson algebra")
|
||||
|
||||
@@ -416,7 +376,7 @@ def evaluate_metric(rule: MetricRule, *, numerator: int, denominator: int) -> Me
|
||||
denominator = _count(denominator, "denominator")
|
||||
if numerator > denominator:
|
||||
raise MeasurementContractError("numerator must not exceed denominator")
|
||||
value, lower, upper = _metric_values(rule.metric_id, numerator, denominator)
|
||||
value, lower, upper = _shared_metric_values(rule.metric_id.value, numerator, denominator)
|
||||
return MetricResult(rule.metric_id, numerator, denominator, value, IntervalMethod.WILSON_95, lower, upper)
|
||||
|
||||
|
||||
@@ -447,7 +407,7 @@ def metric_passes(result: MetricResult, statistic: Statistic, comparator: Compar
|
||||
if not isinstance(comparator, Comparator):
|
||||
raise MeasurementContractError("comparator must use the closed enum")
|
||||
target = _finite(target, "target")
|
||||
required = _ALGEBRA[result.metric_id][2]
|
||||
required = _metric_algebra(result.metric_id)[2]
|
||||
if comparator is not required:
|
||||
raise MeasurementContractError("comparator direction violates the fixed metric algebra")
|
||||
value = _statistic_value(result, statistic)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Version-neutral tests for the closed standard-metric arithmetic."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from openultrasast.core._metric_algebra import metric_algebra, metric_values
|
||||
|
||||
EXPECTED_ALGEBRA = {
|
||||
"paired_correctness": ("correct_pairs", "pairs", "at_least"),
|
||||
"vulnerable_recall": ("vulnerable_violation_cases", "vulnerable_sides", "at_least"),
|
||||
"fixed_false_alarm_rate": ("fixed_defect_cases", "fixed_sides", "at_most"),
|
||||
"ordinary_false_alarms_per_100": ("ordinary_defect_cases", "ordinary_cases", "at_most"),
|
||||
"precision": ("true_defect_cases", "all_defect_cases", "at_least"),
|
||||
"semantic_stage_coverage": ("sites_recognized", "sites_considered", "at_least"),
|
||||
"model_success_rate": ("successful_model_calls", "model_calls", "at_least"),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("metric_id", "expected"), EXPECTED_ALGEBRA.items())
|
||||
def test_closed_metric_algebra_uses_version_neutral_identities(
|
||||
metric_id: str,
|
||||
expected: tuple[str, str, str],
|
||||
) -> None:
|
||||
assert metric_algebra(metric_id) == expected
|
||||
|
||||
|
||||
def test_metric_algebra_rejects_an_identity_outside_the_closed_set() -> None:
|
||||
with pytest.raises(ValueError, match="unknown standard metric identity"):
|
||||
metric_algebra("future_metric")
|
||||
with pytest.raises(ValueError, match="unknown standard metric identity"):
|
||||
metric_values("future_metric", 1, 1)
|
||||
|
||||
|
||||
def test_wilson_values_preserve_the_frozen_v2_operation_order() -> None:
|
||||
recall = metric_values("vulnerable_recall", 8, 10)
|
||||
ordinary = metric_values("ordinary_false_alarms_per_100", 2, 40)
|
||||
|
||||
assert tuple(value.hex() for value in recall if value is not None) == (
|
||||
"0x1.999999999999ap-1",
|
||||
"0x1.f5ed26a3e7d75p-2",
|
||||
"0x1.e2fa8e9a791bcp-1",
|
||||
)
|
||||
assert tuple(value.hex() for value in ordinary if value is not None) == (
|
||||
"0x1.4000000000000p+2",
|
||||
"0x1.61cf20333d76dp+0",
|
||||
"0x1.080fe1b75a7abp+4",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("metric_id", EXPECTED_ALGEBRA)
|
||||
def test_zero_denominator_has_no_derived_values(metric_id: str) -> None:
|
||||
assert metric_values(metric_id, 0, 0) == (None, None, None)
|
||||
Reference in New Issue
Block a user