feat(detection-core): establish V3 version boundary

This commit is contained in:
Marius Ciepluch
2026-11-06 17:27:19 +01:00
parent a60b5397c6
commit 16c04cf24f
3 changed files with 565 additions and 2 deletions
+3 -2
View File
@@ -451,7 +451,7 @@ implementation record. The unresolved downstream-governance item 11.4 is not reo
is not a prerequisite for this V3 stream; V3 tasks depend explicitly on completed V2
contract work and use synthetic/in-memory workflow boundaries only.
- [ ] 12. Preserve V2 admission and establish V3 measurement foundations
- [x] 12. Preserve V2 admission and establish V3 measurement foundations
- [x] 12.1 (P) Freeze representative V2 admission behavior
- Pin accepted canonical bytes, digests, decisions, validation failures, report output, and authoritative replay output for representative V2 admissions.
- Prove every frozen fixture is readable and nonzero before treating a stable result as compatibility evidence.
@@ -477,7 +477,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
- _Requirements: 16.1, 16.4, 16.5, 18.1, 18.6, 18.7_
- _Boundary: Evaluation Measurement_
- _Depends: 12.2_
- [ ] 12.4 Establish distinct V3 version-boundary primitives
- [x] 12.4 Establish distinct V3 version-boundary primitives
- Reserve the exact evaluation-admission V3 schema identity and version-routing primitives without changing any V2 public name or route.
- Make V3 contracts exact-type only and prohibit V2-to-V3 conversion, subclass acceptance, and mixed-version child relationships as each later root is introduced.
- Define the shared non-authorizing marker for feasibility, insufficiency, raw reports, aggregates, incomplete arm results, and other partial values; leave complete root decoding to facade integration.
@@ -710,6 +710,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.
- Task 12.4 reserved the exact V3 evaluation-admission identity, added closed extensible V3 contract routing, and made partial artifacts structurally non-authorizing across inheritance, wrapped aliases, and post-definition/shared-base mutation while leaving V2 routes unchanged.
- 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,252 @@
"""Closed version-boundary primitives for evaluation admission V3."""
from __future__ import annotations
import re
from dataclasses import dataclass
from enum import Enum
from functools import partial, partialmethod
from inspect import getattr_static
from types import BuiltinFunctionType, FunctionType
from typing import ClassVar, TypeVar, cast
EVALUATION_ADMISSION_V3_SCHEMA = "openultrasast.detection-core.evaluation-admission.v3"
_DIGEST = re.compile(r"[0-9a-f]{64}")
_FORBIDDEN_AUTHORITY_NAMES = frozenset(
{
"__call__",
"authorize",
"authorization",
"authorization_capability",
"authorize_consumer",
"consumer_authority",
"consumer_authorization",
"may_authorize",
}
)
_ContractT = TypeVar("_ContractT")
_REGISTERED_V3_CONTRACT_TYPES: list[type[object]] = []
_MISSING = object()
_MAX_CALLABLE_UNWRAP_DEPTH = 16
class EvaluationVersionError(ValueError):
"""An evaluation value crosses or violates the V3 contract boundary."""
class EvaluationContractVersion(Enum):
"""Closed evaluation-admission versions accepted by the V3 path."""
V3 = EVALUATION_ADMISSION_V3_SCHEMA
class PartialArtifactKindV3(Enum):
"""Closed non-authorizing artifact categories shared by later V3 roots."""
FEASIBILITY = "feasibility"
INSUFFICIENCY = "insufficiency"
IMPAIRED_RESULT = "impaired_result"
RAW_REPORT = "raw_report"
AGGREGATE = "aggregate"
INCOMPLETE_ARM_RESULT = "incomplete_arm_result"
OTHER_PARTIAL = "other_partial"
def _wrapped_callable(value: object) -> object:
if type(value) is partial or type(value) is partialmethod:
return value.func
if type(value) is FunctionType:
return value.__dict__.get("__wrapped__", _MISSING)
return getattr_static(value, "__wrapped__", _MISSING)
def _callable_identities(value: object) -> tuple[str, ...]:
if isinstance(value, (classmethod, staticmethod)):
value = value.__func__
if isinstance(value, property):
accessors = (value.fget, value.fset, value.fdel)
return tuple(name for accessor in accessors if accessor is not None for name in _callable_identities(accessor))
names: list[str] = []
seen: set[int] = set()
current = value
for _ in range(_MAX_CALLABLE_UNWRAP_DEPTH):
identity = id(current)
if identity in seen:
break
seen.add(identity)
if type(current) in (FunctionType, BuiltinFunctionType):
names.append(cast(FunctionType | BuiltinFunctionType, current).__name__)
wrapped = _wrapped_callable(current)
if wrapped is _MISSING:
break
current = wrapped
return tuple(names)
def _is_authority_name(name: object) -> bool:
if type(name) is not str:
return False
return name in _FORBIDDEN_AUTHORITY_NAMES or name.startswith("authorize_") or name.endswith("_authorization")
def _authority_capability_names(contract_type: type[object]) -> tuple[str, ...]:
forbidden: set[str] = set()
for owner in contract_type.__mro__:
namespace = vars(owner)
annotations = namespace.get("__annotations__", {})
dataclass_fields = namespace.get("__dataclass_fields__", {})
names = set(namespace)
if isinstance(annotations, dict):
names.update(annotations)
if isinstance(dataclass_fields, dict):
names.update(dataclass_fields)
for name in names:
value = namespace.get(name)
callable_names = _callable_identities(value)
if _is_authority_name(name) or any(_is_authority_name(item) for item in callable_names):
forbidden.add(name)
return tuple(sorted(forbidden))
def _validate_non_authorizing_type(contract_type: type[object]) -> None:
forbidden = _authority_capability_names(contract_type)
if forbidden:
names = ", ".join(forbidden)
raise TypeError(f"non-authorizing V3 artifacts cannot declare authority capability: {names}")
def _propagates_to_non_authorizing_type(contract_type: type[object]) -> bool:
marker = globals().get("NonAuthorizingV3")
if not isinstance(marker, type):
return False
pending = [contract_type]
seen: set[int] = set()
while pending:
current = pending.pop()
identity = id(current)
if identity in seen:
continue
seen.add(identity)
if marker in type.__getattribute__(current, "__mro__"):
return True
pending.extend(type.__subclasses__(current))
return False
class _NonAuthorizingMeta(type):
def __new__(
mcls,
name: str,
bases: tuple[type[object], ...],
namespace: dict[str, object],
**kwargs: object,
) -> _NonAuthorizingMeta:
contract_type = super().__new__(mcls, name, bases, namespace, **kwargs)
if bases:
_validate_non_authorizing_type(contract_type)
return contract_type
def __setattr__(cls, name: str, value: object) -> None:
callable_names = _callable_identities(value)
is_authority = _is_authority_name(name) or any(_is_authority_name(item) for item in callable_names)
if is_authority and _propagates_to_non_authorizing_type(cls):
raise TypeError(f"non-authorizing V3 artifacts cannot declare authority capability: {name}")
super().__setattr__(name, value)
class NonAuthorizingV3(metaclass=_NonAuthorizingMeta):
"""Nominal marker for V3 values that cannot authorize consumer use."""
__slots__ = ()
class _EvaluationV3ContractMeta(_NonAuthorizingMeta):
def __new__(
mcls,
name: str,
bases: tuple[type[object], ...],
namespace: dict[str, object],
**kwargs: object,
) -> _EvaluationV3ContractMeta:
contract_type = cast(_EvaluationV3ContractMeta, super().__new__(mcls, name, bases, namespace, **kwargs))
declared_schema = namespace.get("__evaluation_v3_contract_schema__")
owner = namespace.get("__module__")
if (
bases
and type(owner) is str
and owner.startswith("openultrasast.core.evaluation_")
and type(declared_schema) is str
and declared_schema == EVALUATION_ADMISSION_V3_SCHEMA
):
_REGISTERED_V3_CONTRACT_TYPES.append(contract_type)
return contract_type
class EvaluationV3Contract(metaclass=_EvaluationV3ContractMeta):
"""Nominal base for explicitly registered contracts owned by V3 core modules."""
__slots__ = ()
def route_evaluation_schema(schema: str) -> EvaluationContractVersion:
"""Route only the reserved V3 root identity; never reinterpret V2 or unknown shapes."""
if type(schema) is not str:
raise EvaluationVersionError("evaluation schema must be exact text")
if schema == EVALUATION_ADMISSION_V3_SCHEMA:
return EvaluationContractVersion.V3
if schema.endswith(".v2"):
raise EvaluationVersionError("V2 evidence cannot be converted; construct a new V3 baseline")
raise EvaluationVersionError(f"unknown evaluation schema: {schema}")
def require_v3_child_schema(schema: object, *, field: str) -> None:
"""Require a later V3 root child to name the exact parent contract version."""
if type(field) is not str or not field:
raise EvaluationVersionError("child field must be nonempty exact text")
if type(schema) is not str or schema != EVALUATION_ADMISSION_V3_SCHEMA:
raise EvaluationVersionError(f"{field} has a mixed or incompatible evaluation schema")
def require_exact_v3_contract(value: object, expected_type: type[_ContractT], *, field: str) -> _ContractT:
"""Refuse subclasses and shape inference at every later V3 contract boundary."""
if type(field) is not str or not field:
raise EvaluationVersionError("contract field must be nonempty exact text")
if not isinstance(expected_type, type):
raise EvaluationVersionError("expected contract must be an exact runtime type")
if not any(expected_type is registered_type for registered_type in _REGISTERED_V3_CONTRACT_TYPES):
raise EvaluationVersionError(f"{field} must name a registered V3 contract type")
if type(value) is not expected_type:
raise EvaluationVersionError(f"{field} must use exact {expected_type.__name__}")
return value
@dataclass(frozen=True)
class PartialEvaluationArtifactV3(EvaluationV3Contract, NonAuthorizingV3):
"""Representative partial V3 value with no consumer-authority interface."""
__evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA
evaluation_schema: str
kind: PartialArtifactKindV3
artifact_digest: str
def __post_init__(self) -> None:
require_exact_v3_contract(self, PartialEvaluationArtifactV3, field="partial evaluation artifact")
require_v3_child_schema(self.evaluation_schema, field="partial evaluation artifact")
if type(self.kind) is not PartialArtifactKindV3:
raise EvaluationVersionError("partial artifact kind must use the closed PartialArtifactKindV3 enum")
if type(self.artifact_digest) is not str or _DIGEST.fullmatch(self.artifact_digest) is None:
raise EvaluationVersionError("partial artifact digest must be a full lowercase SHA-256 digest")
__all__ = [
"EVALUATION_ADMISSION_V3_SCHEMA",
"EvaluationContractVersion",
"EvaluationV3Contract",
"EvaluationVersionError",
"NonAuthorizingV3",
"PartialArtifactKindV3",
"PartialEvaluationArtifactV3",
"require_exact_v3_contract",
"require_v3_child_schema",
"route_evaluation_schema",
]
+310
View File
@@ -0,0 +1,310 @@
"""Evaluation-admission V3 version and partial-authority boundary."""
from __future__ import annotations
import subprocess
import sys
import textwrap
from dataclasses import replace
from functools import partial, wraps
import pytest
from openultrasast.core import admission, canonical
from openultrasast.core.admission_report import ADMISSION_REPLAY_SCHEMA, AdmissionReportV2
from openultrasast.core.evaluation_version import (
EVALUATION_ADMISSION_V3_SCHEMA,
EvaluationContractVersion,
EvaluationV3Contract,
EvaluationVersionError,
NonAuthorizingV3,
PartialArtifactKindV3,
PartialEvaluationArtifactV3,
require_exact_v3_contract,
require_v3_child_schema,
route_evaluation_schema,
)
def _partial(kind: PartialArtifactKindV3 = PartialArtifactKindV3.FEASIBILITY) -> PartialEvaluationArtifactV3:
return PartialEvaluationArtifactV3(
evaluation_schema=EVALUATION_ADMISSION_V3_SCHEMA,
kind=kind,
artifact_digest=canonical.content_digest(kind.value),
)
def test_exact_v3_root_identity_is_the_only_v3_route() -> None:
assert EVALUATION_ADMISSION_V3_SCHEMA == "openultrasast.detection-core.evaluation-admission.v3"
assert route_evaluation_schema(EVALUATION_ADMISSION_V3_SCHEMA) is EvaluationContractVersion.V3
with pytest.raises(EvaluationVersionError, match="V2.*new V3 baseline"):
route_evaluation_schema(ADMISSION_REPLAY_SCHEMA)
with pytest.raises(EvaluationVersionError, match="unknown evaluation schema"):
route_evaluation_schema("openultrasast.detection-core.evaluation-admission.v4")
with pytest.raises(EvaluationVersionError, match="schema must be exact text"):
route_evaluation_schema(None) # type: ignore[arg-type]
def test_v2_facade_names_and_routes_remain_separate_and_unchanged() -> None:
assert admission.ADMISSION_REPLAY_SCHEMA == "openultrasast.detection-core.admission-replay.v2"
assert admission.ADMISSION_REPORT_SCHEMA == "openultrasast.detection-core.admission-report.v2"
assert admission.AdmissionReplay.__module__ == "openultrasast.core._admission_replay"
assert admission.AdmissionReportV2.__module__ == "openultrasast.core.admission_report"
assert "EVALUATION_ADMISSION_V3_SCHEMA" not in admission.__all__
def test_exact_contract_and_child_guards_refuse_subclasses_and_mixed_versions() -> None:
partial = _partial()
require_exact_v3_contract(partial, PartialEvaluationArtifactV3, field="partial")
require_v3_child_schema(EVALUATION_ADMISSION_V3_SCHEMA, field="partial")
class DerivedPartial(PartialEvaluationArtifactV3):
pass
with pytest.raises(EvaluationVersionError, match="exact PartialEvaluationArtifactV3"):
DerivedPartial(
EVALUATION_ADMISSION_V3_SCHEMA,
PartialArtifactKindV3.FEASIBILITY,
canonical.content_digest("derived"),
)
with pytest.raises(EvaluationVersionError, match="mixed or incompatible"):
require_v3_child_schema(ADMISSION_REPLAY_SCHEMA, field="report")
with pytest.raises(EvaluationVersionError, match="mixed or incompatible"):
require_v3_child_schema("openultrasast.detection-core.evaluation-admission.v4", field="report")
def test_every_partial_kind_is_exactly_non_authorizing() -> None:
for kind in PartialArtifactKindV3:
partial = _partial(kind)
assert isinstance(partial, NonAuthorizingV3)
assert partial.kind is kind
assert not hasattr(partial, "authorize")
assert not hasattr(partial, "authorization")
assert not hasattr(partial, "consumer_authority")
with pytest.raises(TypeError, match="non-authorizing V3 artifacts cannot declare"):
class InvalidPartial(NonAuthorizingV3):
def authorize(self) -> None:
pass
def test_partial_contract_rejects_wrong_version_kind_digest_and_rehash() -> None:
partial = _partial()
with pytest.raises(EvaluationVersionError, match="mixed or incompatible"):
replace(partial, evaluation_schema=ADMISSION_REPLAY_SCHEMA)
with pytest.raises(EvaluationVersionError, match="closed PartialArtifactKindV3"):
replace(partial, kind="feasibility") # type: ignore[arg-type]
with pytest.raises(EvaluationVersionError, match="lowercase SHA-256"):
replace(partial, artifact_digest="not-a-digest")
def test_exact_contract_guard_rejects_v2_arbitrary_and_marker_spoof_types() -> None:
v2_report = object.__new__(AdmissionReportV2)
with pytest.raises(EvaluationVersionError, match="registered V3 contract"):
require_exact_v3_contract(v2_report, AdmissionReportV2, field="report")
class Arbitrary:
pass
with pytest.raises(EvaluationVersionError, match="registered V3 contract"):
require_exact_v3_contract(Arbitrary(), Arbitrary, field="arbitrary")
class SpoofedMarker:
__evaluation_v3_contract__ = True
with pytest.raises(EvaluationVersionError, match="registered V3 contract"):
require_exact_v3_contract(SpoofedMarker(), SpoofedMarker, field="spoof")
class EqualitySpoofMeta(type):
def __hash__(cls) -> int:
return hash(PartialEvaluationArtifactV3)
def __eq__(cls, other: object) -> bool:
return other is PartialEvaluationArtifactV3
class EqualitySpoof(metaclass=EqualitySpoofMeta):
pass
with pytest.raises(EvaluationVersionError, match="registered V3 contract"):
require_exact_v3_contract(EqualitySpoof(), EqualitySpoof, field="equality spoof")
with pytest.raises(EvaluationVersionError, match="runtime type"):
require_exact_v3_contract(_partial(), "PartialEvaluationArtifactV3", field="partial") # type: ignore[arg-type]
with pytest.raises(EvaluationVersionError, match="nonempty exact text"):
require_exact_v3_contract(_partial(), PartialEvaluationArtifactV3, field="")
def test_later_evaluation_modules_have_an_intentional_closed_registration_path() -> None:
class RepresentativePlanContract(EvaluationV3Contract):
__module__ = "openultrasast.core.evaluation_plan"
__evaluation_v3_contract_schema__ = EVALUATION_ADMISSION_V3_SCHEMA
value = RepresentativePlanContract()
assert require_exact_v3_contract(value, RepresentativePlanContract, field="plan") is value
class UnmarkedPlanContract(EvaluationV3Contract):
__module__ = "openultrasast.core.evaluation_plan"
with pytest.raises(EvaluationVersionError, match="registered V3 contract"):
require_exact_v3_contract(UnmarkedPlanContract(), UnmarkedPlanContract, field="unmarked plan")
class WrongOwnerContract(EvaluationV3Contract):
__evaluation_v3_contract_schema__ = EVALUATION_ADMISSION_V3_SCHEMA
with pytest.raises(EvaluationVersionError, match="registered V3 contract"):
require_exact_v3_contract(WrongOwnerContract(), WrongOwnerContract, field="wrong owner")
def test_non_authorizing_marker_rejects_inherited_authority_capabilities() -> None:
class AuthorizingBase:
def authorize(self) -> None:
pass
with pytest.raises(TypeError, match="non-authorizing V3 artifacts cannot declare"):
class InheritedAuthorize(NonAuthorizingV3, AuthorizingBase):
pass
class AuthorizationPropertyBase:
@property
def authorization(self) -> str:
return "forbidden"
with pytest.raises(TypeError, match="non-authorizing V3 artifacts cannot declare"):
class InheritedProperty(AuthorizationPropertyBase, NonAuthorizingV3):
pass
class CallableBase:
def __call__(self) -> None:
pass
with pytest.raises(TypeError, match="non-authorizing V3 artifacts cannot declare"):
class InheritedCallable(CallableBase, NonAuthorizingV3):
pass
def test_non_authorizing_marker_rejects_inherited_fields_descriptors_and_aliases() -> None:
from dataclasses import dataclass
@dataclass
class AuthorizationFieldBase:
consumer_authority: str
with pytest.raises(TypeError, match="consumer_authority"):
class InheritedField(NonAuthorizingV3, AuthorizationFieldBase):
pass
class AuthorityDescriptor:
def __get__(self, instance: object, owner: type[object]) -> object:
return self
class DescriptorBase:
authorization = AuthorityDescriptor()
with pytest.raises(TypeError, match="authorization"):
class InheritedDescriptor(NonAuthorizingV3, DescriptorBase):
pass
def authorize() -> None:
pass
with pytest.raises(TypeError, match="authority_alias"):
class AliasedCapability(NonAuthorizingV3):
authority_alias = staticmethod(authorize)
def test_registration_rejects_non_string_schema_equality_spoof() -> None:
class EqualSchema:
def __eq__(self, other: object) -> bool:
return other == EVALUATION_ADMISSION_V3_SCHEMA
class SchemaEqualitySpoof(EvaluationV3Contract):
__module__ = "openultrasast.core.evaluation_plan"
__evaluation_v3_contract_schema__ = EqualSchema()
with pytest.raises(EvaluationVersionError, match="registered V3 contract"):
require_exact_v3_contract(SchemaEqualitySpoof(), SchemaEqualitySpoof, field="schema spoof")
def test_non_authorizing_marker_rejects_partial_and_wrapped_authority_aliases() -> None:
def authorize_consumer() -> None:
pass
with pytest.raises(TypeError, match="partial_alias"):
class PartialAlias(NonAuthorizingV3):
partial_alias = partial(authorize_consumer)
def harmless_wrapper() -> None:
pass
wrapped_authority = wraps(authorize_consumer)(harmless_wrapper)
with pytest.raises(TypeError, match="wrapped_alias"):
class WrappedAlias(NonAuthorizingV3):
wrapped_alias = staticmethod(wrapped_authority)
def test_non_authorizing_marker_rejects_post_class_authority_injection() -> None:
def authorize_consumer() -> None:
pass
with pytest.raises(TypeError, match="authorize"):
NonAuthorizingV3.authorize = authorize_consumer # type: ignore[attr-defined]
with pytest.raises(TypeError, match="consumer_authority"):
PartialEvaluationArtifactV3.consumer_authority = property(lambda self: "forbidden") # type: ignore[attr-defined]
with pytest.raises(TypeError, match="partial_alias"):
PartialEvaluationArtifactV3.partial_alias = partial(authorize_consumer) # type: ignore[attr-defined]
class HarmlessPartial(NonAuthorizingV3):
pass
HarmlessPartial.display_label = "partial" # type: ignore[attr-defined]
assert HarmlessPartial.display_label == "partial" # type: ignore[attr-defined]
@pytest.mark.parametrize(
("assignment", "attribute"),
(
("EvaluationV3Contract.authorize = authorize_consumer", "authorize"),
("EvaluationV3Contract.wrapped_alias = staticmethod(wrapped_authority)", "wrapped_alias"),
),
)
def test_authority_cannot_be_injected_through_a_shared_contract_base(assignment: str, attribute: str) -> None:
program = textwrap.dedent(
f"""
from functools import wraps
from openultrasast.core.evaluation_version import EvaluationV3Contract, PartialEvaluationArtifactV3
def authorize_consumer():
pass
def harmless_wrapper():
pass
wrapped_authority = wraps(authorize_consumer)(harmless_wrapper)
try:
{assignment}
except TypeError:
pass
else:
raise AssertionError("shared-base authority assignment was accepted")
assert not hasattr(PartialEvaluationArtifactV3, {attribute!r})
EvaluationV3Contract.display_label = "evaluation-v3"
assert PartialEvaluationArtifactV3.display_label == "evaluation-v3"
"""
)
completed = subprocess.run(
[sys.executable, "-c", program],
check=False,
capture_output=True,
text=True,
)
assert completed.returncode == 0, completed.stderr