mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
feat(detection-core): publish integrated v3 facade
This commit is contained in:
@@ -651,7 +651,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
|
||||
- _Requirements: 16.6, 18.7, 20.7_
|
||||
- _Boundary: Evaluation Aggregate_
|
||||
|
||||
- [ ] 17. Close complete replay and replay-only consumer authorization
|
||||
- [x] 17. Close complete replay and replay-only consumer authorization
|
||||
- [x] 17.1 Assemble one complete replay over the shared evaluation graph
|
||||
- Bind the reviewed plan, exact feasibility, reviewed admission authority, preparation, receipt, all-arm spend binding, attempt-history head, V3 release, cases, per-arm reports, combination lineages, shared whole coverage, and optional aggregate.
|
||||
- Require exact equality between planned arms/scopes and case/report identities, including every component required by a combined arm.
|
||||
@@ -667,7 +667,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
|
||||
- Done when independent replay validation reproduces the original reports exactly and every source, summary, or trust-state mutation is refused.
|
||||
- _Requirements: 16.6, 20.5, 20.6, 20.7, 20.8_
|
||||
- _Boundary: Evaluation Replay Validation_
|
||||
- [ ] 17.3 Publish the integrated V3 preflight, authorization, scoring, and replay facade
|
||||
- [x] 17.3 Publish the integrated V3 preflight, authorization, scoring, and replay facade
|
||||
- Wire the exact plan preflight, reviewed authority, shared-spend validation, score/replay, strict decoding, and replay validation through one public V3 contract surface.
|
||||
- Preserve every V2 facade and import unchanged and expose no benchmark storage, execution, lifecycle, or presentation implementation from core.
|
||||
- Reject wrong-phase values and make each returned artifact usable only by the next declared phase.
|
||||
@@ -753,6 +753,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
|
||||
- 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.
|
||||
- Task 17.1 assembles one deterministic non-authorizing replay from the complete source-rooted plan-to-report graph, rederiving reports, whole coverage, release bindings, and combination lineage while rejecting partial, forged, or noncanonical inputs.
|
||||
- Task 17.2 independently resolves canonical artifacts and current trust/custody state, rederives the complete V3 graph and replay digest, and rejects stale, partial, mixed-version, or coordinated caller-rehashed evidence before authorization.
|
||||
- Task 17.3 publishes one fail-closed V3 phase facade with closed-field validation for every public root and nested input, strict version routing, current-state replay validation, and an additive export that preserves the frozen V2 surface.
|
||||
- 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.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Family-neutral detection-core v2 public surface."""
|
||||
"""Family-neutral detection-core public surfaces."""
|
||||
|
||||
from openultrasast.core import admission, consumer, verdict
|
||||
from openultrasast.core import admission, consumer, evaluation_admission, verdict
|
||||
|
||||
__all__ = ["admission", "consumer", "verdict"]
|
||||
__all__ = ["admission", "consumer", "evaluation_admission", "verdict"]
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
"""Sole public facade for the evaluation-admission V3 contract."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TypeVar, cast
|
||||
|
||||
from openultrasast.core import canonical
|
||||
from openultrasast.core._closed_graph import exact_dataclass_problem
|
||||
from openultrasast.core.admission_context import AdmissionValidationContext, _validate_context
|
||||
from openultrasast.core.custody import PopulationCustodyPort, PopulationUseReceipt, PopulationUseRequest
|
||||
from openultrasast.core.evaluation_aggregate import EvaluationAggregateV3, derive_evaluation_aggregate_v3
|
||||
from openultrasast.core.evaluation_authority import (
|
||||
EvaluationAdmissionManifestV3,
|
||||
authorize_evaluation_admission,
|
||||
)
|
||||
from openultrasast.core.evaluation_combination import CombinationLineageV3, derive_combination_lineages_v3
|
||||
from openultrasast.core.evaluation_feasibility import EvaluationFeasibilityV3, derive_evaluation_feasibility
|
||||
from openultrasast.core.evaluation_measurement import (
|
||||
AggregateWeightV3,
|
||||
ArmScopeKey,
|
||||
MetricId,
|
||||
ScopedMetricResultV3,
|
||||
ScopeKey,
|
||||
)
|
||||
from openultrasast.core.evaluation_metric_derivation import derive_scoped_metrics_v3
|
||||
from openultrasast.core.evaluation_observation import ArmObservationSetV3, validate_evaluation_observations
|
||||
from openultrasast.core.evaluation_ordinary_projection import WholePopulationProjectionV3, project_ordinary_pushes_v3
|
||||
from openultrasast.core.evaluation_plan import EvaluationPlanManifestV3
|
||||
from openultrasast.core.evaluation_release import (
|
||||
AdmissionCaseReleaseV3,
|
||||
ArmAdmissionCaseResultV3,
|
||||
ArmAdmissionCasesV3,
|
||||
)
|
||||
from openultrasast.core.evaluation_replay import (
|
||||
EvaluationReplayReportSourceV3,
|
||||
EvaluationReplayV3,
|
||||
assemble_evaluation_replay_v3,
|
||||
)
|
||||
from openultrasast.core.evaluation_replay_validation import validate_evaluation_replay_v3
|
||||
from openultrasast.core.evaluation_report import ArmEvaluationReportV3, derive_completed_evaluation_reports_v3
|
||||
from openultrasast.core.evaluation_spend import (
|
||||
EvaluationPreparationV3,
|
||||
EvaluationSpendBindingV3,
|
||||
bind_evaluation_spend,
|
||||
prepare_evaluation_spend,
|
||||
)
|
||||
from openultrasast.core.evaluation_version import (
|
||||
EVALUATION_ADMISSION_V3_SCHEMA,
|
||||
EvaluationV3Contract,
|
||||
require_exact_v3_contract,
|
||||
require_v3_child_schema,
|
||||
route_evaluation_schema,
|
||||
)
|
||||
from openultrasast.core.readiness import ReadinessResult, validate_readiness_result
|
||||
|
||||
_ContractT = TypeVar("_ContractT", bound=EvaluationV3Contract)
|
||||
_ExactT = TypeVar("_ExactT")
|
||||
_ScoreSources = tuple[
|
||||
EvaluationSpendBindingV3,
|
||||
tuple[ScopedMetricResultV3, ...],
|
||||
WholePopulationProjectionV3,
|
||||
tuple[ArmObservationSetV3, ...],
|
||||
tuple[CombinationLineageV3, ...],
|
||||
]
|
||||
_ScoreRoots = tuple[
|
||||
EvaluationAdmissionManifestV3,
|
||||
EvaluationFeasibilityV3,
|
||||
EvaluationPreparationV3,
|
||||
PopulationUseReceipt,
|
||||
EvaluationSpendBindingV3,
|
||||
AdmissionCaseReleaseV3,
|
||||
tuple[ArmAdmissionCasesV3, ...],
|
||||
tuple[ReadinessResult, ...],
|
||||
]
|
||||
|
||||
|
||||
class EvaluationAdmissionV3Error(ValueError):
|
||||
"""A value was refused at the public evaluation-admission V3 boundary."""
|
||||
|
||||
|
||||
def _declared(value: object, expected_type: type[_ExactT], field: str) -> _ExactT:
|
||||
try:
|
||||
problem = exact_dataclass_problem(value, expected_type, field)
|
||||
except (AttributeError, TypeError, ValueError) as exc:
|
||||
raise EvaluationAdmissionV3Error(f"{field} was refused at the closed boundary: {exc}") from exc
|
||||
if problem is not None:
|
||||
raise EvaluationAdmissionV3Error(problem)
|
||||
return cast(_ExactT, value)
|
||||
|
||||
|
||||
def _receipt(value: object) -> PopulationUseReceipt:
|
||||
receipt = _declared(value, PopulationUseReceipt, "shared-spend receipt")
|
||||
request = _declared(receipt.request, PopulationUseRequest, "shared-spend receipt request")
|
||||
try:
|
||||
request.__post_init__()
|
||||
receipt.__post_init__()
|
||||
except (AttributeError, TypeError, ValueError) as exc:
|
||||
raise EvaluationAdmissionV3Error(f"shared-spend receipt was refused: {exc}") from exc
|
||||
return receipt
|
||||
|
||||
|
||||
def _readiness(values: object) -> tuple[ReadinessResult, ...]:
|
||||
if type(values) is not tuple:
|
||||
raise EvaluationAdmissionV3Error("readiness must use an exact tuple of ReadinessResult values")
|
||||
items = cast(tuple[object, ...], values)
|
||||
for item in items:
|
||||
try:
|
||||
validate_readiness_result(cast(ReadinessResult, item))
|
||||
except (AttributeError, TypeError, ValueError) as exc:
|
||||
raise EvaluationAdmissionV3Error(f"readiness item was refused at the closed boundary: {exc}") from exc
|
||||
return cast(tuple[ReadinessResult, ...], values)
|
||||
|
||||
|
||||
def _case_groups(values: object) -> tuple[ArmAdmissionCasesV3, ...]:
|
||||
if type(values) is not tuple:
|
||||
raise EvaluationAdmissionV3Error("cases must use an exact tuple of ArmAdmissionCasesV3 values")
|
||||
groups = cast(tuple[object, ...], values)
|
||||
for item in groups:
|
||||
group = _exact(item, ArmAdmissionCasesV3, "evaluation case group")
|
||||
for case in group.cases:
|
||||
_exact(case, ArmAdmissionCaseResultV3, "evaluation case item")
|
||||
return cast(tuple[ArmAdmissionCasesV3, ...], values)
|
||||
|
||||
|
||||
def _aggregate_weights(values: object) -> tuple[AggregateWeightV3, ...] | None:
|
||||
if values is None:
|
||||
return None
|
||||
if type(values) is not tuple:
|
||||
raise EvaluationAdmissionV3Error("aggregate weights must use an exact tuple of AggregateWeightV3 values")
|
||||
weights = cast(tuple[object, ...], values)
|
||||
for item in weights:
|
||||
weight = _declared(item, AggregateWeightV3, "aggregate weight")
|
||||
key = _declared(weight.key, ArmScopeKey, "aggregate weight arm-scope key")
|
||||
_declared(key.scope, ScopeKey, "aggregate weight scope key")
|
||||
return cast(tuple[AggregateWeightV3, ...], values)
|
||||
|
||||
|
||||
def _context(value: object) -> AdmissionValidationContext:
|
||||
if type(value) is not AdmissionValidationContext:
|
||||
raise EvaluationAdmissionV3Error("validation context must use exact AdmissionValidationContext")
|
||||
_validate_context(value)
|
||||
return value
|
||||
|
||||
|
||||
def _exact(value: object, expected_type: type[_ContractT], field: str) -> _ContractT:
|
||||
try:
|
||||
problem = exact_dataclass_problem(value, expected_type, field)
|
||||
if problem is not None:
|
||||
raise EvaluationAdmissionV3Error(problem)
|
||||
result = require_exact_v3_contract(value, expected_type, field=field)
|
||||
require_v3_child_schema(getattr(type(result), "__evaluation_v3_contract_schema__", None), field=field)
|
||||
post_init = getattr(result, "__post_init__", None)
|
||||
if not callable(post_init):
|
||||
raise EvaluationAdmissionV3Error(f"{field} has no exact contract validator")
|
||||
post_init()
|
||||
return result
|
||||
except (AttributeError, TypeError, ValueError) as exc:
|
||||
raise EvaluationAdmissionV3Error(f"{field} was refused at the exact V3 boundary: {exc}") from exc
|
||||
|
||||
|
||||
def decode_evaluation_v3(schema: str, value: object, expected_type: type[_ContractT]) -> _ContractT:
|
||||
"""Route one named root and accept only its exact registered V3 runtime contract."""
|
||||
try:
|
||||
route_evaluation_schema(schema)
|
||||
return _exact(value, expected_type, "decoded evaluation root")
|
||||
except EvaluationAdmissionV3Error:
|
||||
raise
|
||||
except (AttributeError, TypeError, ValueError) as exc:
|
||||
raise EvaluationAdmissionV3Error(f"evaluation root schema was refused: {exc}") from exc
|
||||
|
||||
|
||||
def preflight_evaluation(
|
||||
manifest: EvaluationPlanManifestV3,
|
||||
context: AdmissionValidationContext,
|
||||
resolver: canonical.ContentResolver,
|
||||
) -> EvaluationFeasibilityV3:
|
||||
"""Validate one reviewed plan and derive its exact all-scope feasibility product."""
|
||||
plan = _exact(manifest, EvaluationPlanManifestV3, "evaluation plan manifest")
|
||||
validated_context = _context(context)
|
||||
return derive_evaluation_feasibility(plan, validated_context.admission_review_policy, resolver)
|
||||
|
||||
|
||||
def authorize_evaluation(
|
||||
manifest: EvaluationAdmissionManifestV3,
|
||||
feasibility: EvaluationFeasibilityV3,
|
||||
readiness: tuple[ReadinessResult, ...],
|
||||
context: AdmissionValidationContext,
|
||||
custody: PopulationCustodyPort,
|
||||
resolver: canonical.ContentResolver,
|
||||
) -> EvaluationPreparationV3:
|
||||
"""Derive reviewed pre-spend authority and return only its next-phase preparation."""
|
||||
admission = _exact(manifest, EvaluationAdmissionManifestV3, "evaluation admission manifest")
|
||||
feasible = _exact(feasibility, EvaluationFeasibilityV3, "evaluation feasibility")
|
||||
validated_readiness = _readiness(readiness)
|
||||
validated_context = _context(context)
|
||||
authority = authorize_evaluation_admission(admission, feasible, validated_readiness, validated_context, custody, resolver)
|
||||
return prepare_evaluation_spend(admission, authority, validated_context, custody)
|
||||
|
||||
|
||||
def validate_shared_spend(
|
||||
manifest: EvaluationAdmissionManifestV3,
|
||||
preparation: EvaluationPreparationV3,
|
||||
receipt: PopulationUseReceipt,
|
||||
context: AdmissionValidationContext,
|
||||
custody: PopulationCustodyPort,
|
||||
) -> EvaluationSpendBindingV3:
|
||||
"""Bind an externally recorded exact all-arm AVAILABLE-to-SPENT successor."""
|
||||
admission = _exact(manifest, EvaluationAdmissionManifestV3, "evaluation admission manifest")
|
||||
prepared = _exact(preparation, EvaluationPreparationV3, "evaluation preparation")
|
||||
return bind_evaluation_spend(admission, prepared, _receipt(receipt), _context(context), custody)
|
||||
|
||||
|
||||
def _aggregate(
|
||||
metrics: tuple[ScopedMetricResultV3, ...],
|
||||
weights: tuple[AggregateWeightV3, ...] | None,
|
||||
) -> EvaluationAggregateV3 | None:
|
||||
if weights is None:
|
||||
return None
|
||||
keys = tuple(sorted({metric.key for metric in metrics}))
|
||||
samples = tuple(
|
||||
next(metric.sample_count for metric in metrics if metric.key == key and metric.metric_id is MetricId.PRECISION) for key in keys
|
||||
)
|
||||
return derive_evaluation_aggregate_v3(metrics, samples, weights)
|
||||
|
||||
|
||||
def _score_sources(
|
||||
admission: EvaluationAdmissionManifestV3,
|
||||
preparation: EvaluationPreparationV3,
|
||||
receipt: PopulationUseReceipt,
|
||||
expected_spend: EvaluationSpendBindingV3,
|
||||
release: AdmissionCaseReleaseV3,
|
||||
groups: tuple[ArmAdmissionCasesV3, ...],
|
||||
context: AdmissionValidationContext,
|
||||
custody: PopulationCustodyPort,
|
||||
resolver: canonical.ContentResolver,
|
||||
) -> _ScoreSources:
|
||||
spend = bind_evaluation_spend(admission, preparation, receipt, context, custody)
|
||||
if spend != expected_spend:
|
||||
raise EvaluationAdmissionV3Error("shared-spend binding differs from the exact current transition")
|
||||
common = (admission, preparation.authority, preparation, receipt, spend, release, groups, context, custody, resolver)
|
||||
metrics = derive_scoped_metrics_v3(*common)
|
||||
projection = project_ordinary_pushes_v3(*common)
|
||||
policy = context.admission_review_policy
|
||||
observations = validate_evaluation_observations(
|
||||
admission.plan_manifest.declaration,
|
||||
admission.observations,
|
||||
resolver,
|
||||
trusted_store_identities=policy.trusted_store_identities,
|
||||
maximum_bytes=policy.maximum_evidence_bytes,
|
||||
)
|
||||
lineages = derive_combination_lineages_v3(admission.plan_manifest.declaration, release.bindings)
|
||||
return spend, metrics, projection.whole_population, observations, lineages
|
||||
|
||||
|
||||
def _score_roots(
|
||||
admission: object,
|
||||
feasibility: object,
|
||||
preparation: object,
|
||||
receipt: object,
|
||||
spend: object,
|
||||
release: object,
|
||||
groups: object,
|
||||
readiness: object,
|
||||
) -> _ScoreRoots:
|
||||
roots = (
|
||||
_exact(admission, EvaluationAdmissionManifestV3, "evaluation admission manifest"),
|
||||
_exact(feasibility, EvaluationFeasibilityV3, "evaluation feasibility"),
|
||||
_exact(preparation, EvaluationPreparationV3, "evaluation preparation"),
|
||||
)
|
||||
exact_receipt = _receipt(receipt)
|
||||
binding = _exact(spend, EvaluationSpendBindingV3, "evaluation spend binding")
|
||||
released = _exact(release, AdmissionCaseReleaseV3, "evaluation case release")
|
||||
exact_groups = _case_groups(groups)
|
||||
exact_readiness = _readiness(readiness)
|
||||
return (*roots, exact_receipt, binding, released, exact_groups, exact_readiness)
|
||||
|
||||
|
||||
def score_and_replay(
|
||||
admission_manifest: EvaluationAdmissionManifestV3,
|
||||
feasibility: EvaluationFeasibilityV3,
|
||||
preparation: EvaluationPreparationV3,
|
||||
receipt: PopulationUseReceipt,
|
||||
spend_binding: EvaluationSpendBindingV3,
|
||||
release: AdmissionCaseReleaseV3,
|
||||
cases_by_arm: tuple[ArmAdmissionCasesV3, ...],
|
||||
readiness: tuple[ReadinessResult, ...],
|
||||
context: AdmissionValidationContext,
|
||||
custody: PopulationCustodyPort,
|
||||
resolver: canonical.ContentResolver,
|
||||
*,
|
||||
aggregate_weights: tuple[AggregateWeightV3, ...] | None = None,
|
||||
) -> EvaluationReplayV3:
|
||||
"""Derive reports and assemble one complete source-rooted non-authorizing replay."""
|
||||
exact_weights = _aggregate_weights(aggregate_weights)
|
||||
admission, feasible, prepared, exact_receipt, exact_spend, released, groups, exact_readiness = _score_roots(
|
||||
admission_manifest, feasibility, preparation, receipt, spend_binding, release, cases_by_arm, readiness
|
||||
)
|
||||
validated_context = _context(context)
|
||||
spend, metrics, projection, observations, lineages = _score_sources(
|
||||
admission, prepared, exact_receipt, exact_spend, released, groups, validated_context, custody, resolver
|
||||
)
|
||||
reports, whole = derive_completed_evaluation_reports_v3(
|
||||
admission.plan_manifest, groups, metrics, exact_readiness, observations, lineages, projection
|
||||
)
|
||||
source = EvaluationReplayReportSourceV3(metrics, exact_readiness, observations, projection, "")
|
||||
return assemble_evaluation_replay_v3(
|
||||
admission.plan_manifest,
|
||||
feasible,
|
||||
admission,
|
||||
prepared.authority,
|
||||
prepared,
|
||||
exact_receipt,
|
||||
spend,
|
||||
released,
|
||||
groups,
|
||||
source,
|
||||
reports,
|
||||
lineages,
|
||||
admission.attempt_history.head_event_digest,
|
||||
whole,
|
||||
_aggregate(metrics, exact_weights),
|
||||
)
|
||||
|
||||
|
||||
def validate_evaluation_replay(
|
||||
replay: EvaluationReplayV3,
|
||||
context: AdmissionValidationContext,
|
||||
custody: PopulationCustodyPort,
|
||||
resolver: canonical.ContentResolver,
|
||||
) -> tuple[ArmEvaluationReportV3, ...]:
|
||||
"""Return reports only after independent current-source and custody replay validation."""
|
||||
exact_replay = _exact(replay, EvaluationReplayV3, "evaluation replay")
|
||||
return validate_evaluation_replay_v3(exact_replay, _context(context), custody, resolver)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"EVALUATION_ADMISSION_V3_SCHEMA",
|
||||
"EvaluationAdmissionV3Error",
|
||||
"authorize_evaluation",
|
||||
"decode_evaluation_v3",
|
||||
"preflight_evaluation",
|
||||
"score_and_replay",
|
||||
"validate_evaluation_replay",
|
||||
"validate_shared_spend",
|
||||
]
|
||||
@@ -23,6 +23,7 @@ REMOVED_PATHS = (
|
||||
CORE / "verdict_v2.py",
|
||||
)
|
||||
CANONICAL_V2_MODULES = ("admission", "consumer", "verdict")
|
||||
PUBLIC_CORE_MODULES = ("admission", "consumer", "evaluation_admission", "verdict")
|
||||
OLD_TOP_LEVEL = (
|
||||
"AdmissionManifest",
|
||||
"Budget",
|
||||
@@ -102,22 +103,25 @@ def test_fresh_interpreter_rejects_old_imports_and_loads_canonical_v2() -> None:
|
||||
"openultrasast.core." + "consumer_v2",
|
||||
"openultrasast.core." + "verdict_v2",
|
||||
)
|
||||
canonical = tuple(f"openultrasast.core.{name}" for name in CANONICAL_V2_MODULES)
|
||||
canonical = tuple(f"openultrasast.core.{name}" for name in PUBLIC_CORE_MODULES)
|
||||
result = _fresh_import_probe(*old_modules, *canonical)
|
||||
|
||||
assert result["old_top_level"] == []
|
||||
assert tuple(result["all"]) == PUBLIC_CORE_MODULES
|
||||
assert set(CANONICAL_V2_MODULES) <= set(result["all"])
|
||||
modules = result["modules"]
|
||||
assert isinstance(modules, dict)
|
||||
assert all(modules[name] is None for name in old_modules)
|
||||
assert "AdmissionManifestV2" in modules[canonical[0]]
|
||||
assert "consume_records" in modules[canonical[1]]
|
||||
assert "derive_verdict_outputs" in modules[canonical[2]]
|
||||
assert "preflight_evaluation" in modules[canonical[2]]
|
||||
assert "derive_verdict_outputs" in modules[canonical[3]]
|
||||
|
||||
|
||||
def test_public_v2_surface_has_no_frozen_v1_names() -> None:
|
||||
def test_public_surface_is_the_exact_additive_v3_surface_with_unchanged_v2_subset() -> None:
|
||||
exports = _module_exports(CORE / "__init__.py")
|
||||
|
||||
assert exports == PUBLIC_CORE_MODULES
|
||||
assert set(CANONICAL_V2_MODULES) <= set(exports)
|
||||
assert set(OLD_TOP_LEVEL).isdisjoint(exports)
|
||||
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
"""Integrated public facade for evaluation-admission V3."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from test_core_evaluation_authority import _authority_case
|
||||
from test_core_evaluation_replay import _assemble, _inputs
|
||||
from test_core_evaluation_replay_validation import _bundle_case
|
||||
from test_core_evaluation_spend import _append_without_precheck
|
||||
|
||||
from openultrasast.core import __all__ as core_exports
|
||||
from openultrasast.core import admission
|
||||
from openultrasast.core.evaluation_version import EVALUATION_ADMISSION_V3_SCHEMA
|
||||
|
||||
|
||||
def _raw_copy(value, *, mutation: str | None = None, **changes):
|
||||
copied = object.__new__(type(value))
|
||||
values = {**vars(value), **changes}
|
||||
missing = next(iter(vars(value)))
|
||||
for name, item in values.items():
|
||||
if mutation != "missing" or name != missing:
|
||||
object.__setattr__(copied, name, item)
|
||||
if mutation == "extra":
|
||||
object.__setattr__(copied, "undeclared_phase_field", "forbidden")
|
||||
return copied
|
||||
|
||||
|
||||
def test_public_surface_adds_only_the_separate_v3_facade() -> None:
|
||||
from openultrasast.core import evaluation_admission
|
||||
|
||||
assert "evaluation_admission" in core_exports
|
||||
assert "EVALUATION_ADMISSION_V3_SCHEMA" not in admission.__all__
|
||||
assert not set(evaluation_admission.__all__) & {"authorize_admission", "score_admission"}
|
||||
|
||||
|
||||
def test_facade_preflight_authorization_and_shared_spend_form_exact_phase_chain() -> None:
|
||||
from openultrasast.core import evaluation_admission
|
||||
|
||||
case = _authority_case()
|
||||
context_case, manifest, expected_feasibility, readiness, _, resolver = case
|
||||
feasibility = evaluation_admission.preflight_evaluation(
|
||||
manifest.plan_manifest,
|
||||
context_case.context,
|
||||
resolver,
|
||||
)
|
||||
assert feasibility == expected_feasibility
|
||||
|
||||
preparation = evaluation_admission.authorize_evaluation(
|
||||
manifest,
|
||||
feasibility,
|
||||
readiness,
|
||||
context_case.context,
|
||||
context_case.port,
|
||||
resolver,
|
||||
)
|
||||
receipt = _append_without_precheck(case, preparation)
|
||||
binding = evaluation_admission.validate_shared_spend(
|
||||
manifest,
|
||||
preparation,
|
||||
receipt,
|
||||
context_case.context,
|
||||
context_case.port,
|
||||
)
|
||||
|
||||
assert preparation.authority.feasibility_digest == feasibility.feasibility_digest
|
||||
assert binding.preparation_digest == preparation.preparation_digest
|
||||
assert binding.receipt_digest == receipt.receipt_digest
|
||||
|
||||
|
||||
def test_facade_scores_and_independently_validates_one_complete_replay() -> None:
|
||||
from openultrasast.core import evaluation_admission
|
||||
|
||||
bundle = _bundle_case()
|
||||
canonical_inputs = _inputs(bundle=bundle, canonical_sources=True)
|
||||
expected = _assemble(*canonical_inputs)
|
||||
context_case = bundle[5][0]
|
||||
source = canonical_inputs[9]
|
||||
aggregate = canonical_inputs[14]
|
||||
assert aggregate is not None
|
||||
|
||||
replay = evaluation_admission.score_and_replay(
|
||||
bundle[3],
|
||||
canonical_inputs[1],
|
||||
bundle[7],
|
||||
bundle[8],
|
||||
canonical_inputs[6],
|
||||
bundle[1],
|
||||
bundle[2],
|
||||
source.readiness,
|
||||
context_case.context,
|
||||
context_case.port,
|
||||
bundle[4],
|
||||
aggregate_weights=aggregate.weights,
|
||||
)
|
||||
|
||||
assert replay == expected
|
||||
assert (
|
||||
evaluation_admission.validate_evaluation_replay(
|
||||
replay,
|
||||
context_case.context,
|
||||
context_case.port,
|
||||
bundle[4],
|
||||
)
|
||||
== replay.reports
|
||||
)
|
||||
|
||||
|
||||
def test_strict_root_decoder_accepts_only_the_named_exact_v3_contract() -> None:
|
||||
from openultrasast.core import evaluation_admission
|
||||
from openultrasast.core.admission_report import AdmissionReplay
|
||||
from openultrasast.core.evaluation_replay import EvaluationReplayV3
|
||||
|
||||
replay = _assemble(*_inputs(bundle=_bundle_case(), canonical_sources=True))
|
||||
assert (
|
||||
evaluation_admission.decode_evaluation_v3(
|
||||
EVALUATION_ADMISSION_V3_SCHEMA,
|
||||
replay,
|
||||
EvaluationReplayV3,
|
||||
)
|
||||
is replay
|
||||
)
|
||||
|
||||
with pytest.raises(Exception, match="V2|convert|schema"):
|
||||
evaluation_admission.decode_evaluation_v3(
|
||||
"openultrasast.detection-core.admission-replay.v2",
|
||||
object.__new__(AdmissionReplay),
|
||||
EvaluationReplayV3,
|
||||
)
|
||||
with pytest.raises(Exception, match="unknown|schema"):
|
||||
evaluation_admission.decode_evaluation_v3("openultrasast.unknown.v9", replay, EvaluationReplayV3)
|
||||
with pytest.raises(Exception, match="exact|EvaluationReplayV3"):
|
||||
evaluation_admission.decode_evaluation_v3(
|
||||
EVALUATION_ADMISSION_V3_SCHEMA,
|
||||
replay.report_source,
|
||||
EvaluationReplayV3,
|
||||
)
|
||||
|
||||
|
||||
def test_wrong_phase_and_mixed_roots_fail_at_the_facade_boundary() -> None:
|
||||
from openultrasast.core import evaluation_admission
|
||||
from openultrasast.core.admission_review import AdmissionManifestV2
|
||||
from openultrasast.core.evaluation_replay import EvaluationReplayV3
|
||||
|
||||
case = _authority_case()
|
||||
context_case, manifest, feasibility, readiness, _, resolver = case
|
||||
with pytest.raises(Exception, match="plan|exact|V3"):
|
||||
evaluation_admission.preflight_evaluation(
|
||||
object.__new__(AdmissionManifestV2),
|
||||
context_case.context,
|
||||
resolver,
|
||||
)
|
||||
with pytest.raises(Exception, match="feasibility|exact|phase"):
|
||||
evaluation_admission.authorize_evaluation(
|
||||
manifest,
|
||||
object(),
|
||||
readiness,
|
||||
context_case.context,
|
||||
context_case.port,
|
||||
resolver,
|
||||
)
|
||||
|
||||
replay = _assemble(*_inputs(bundle=_bundle_case(), canonical_sources=True))
|
||||
|
||||
class ReplaySubclass(EvaluationReplayV3):
|
||||
"""Wrong exact root used only by this boundary regression."""
|
||||
|
||||
substituted = object.__new__(ReplaySubclass)
|
||||
for field, value in replay.__dict__.items():
|
||||
object.__setattr__(substituted, field, value)
|
||||
with pytest.raises(Exception, match="exact|replay|V3"):
|
||||
evaluation_admission.validate_evaluation_replay(
|
||||
substituted,
|
||||
_bundle_case()[5][0].context,
|
||||
_bundle_case()[5][0].port,
|
||||
_bundle_case()[4],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", ("extra", "missing"))
|
||||
@pytest.mark.parametrize("root_index", (0, 1, 2, 4, 6, 7, 15))
|
||||
def test_every_public_phase_root_requires_exact_declared_instance_fields(root_index: int, mutation: str) -> None:
|
||||
from openultrasast.core import evaluation_admission
|
||||
|
||||
inputs = _inputs(bundle=_bundle_case(), canonical_sources=True)
|
||||
replay = _assemble(*inputs)
|
||||
roots = (*inputs, replay)
|
||||
original = roots[root_index]
|
||||
changed = _raw_copy(original, mutation=mutation)
|
||||
|
||||
with pytest.raises(Exception, match="declared fields|missing|exact|refused"):
|
||||
evaluation_admission.decode_evaluation_v3(
|
||||
EVALUATION_ADMISSION_V3_SCHEMA,
|
||||
changed,
|
||||
type(original),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", ("extra", "missing"))
|
||||
@pytest.mark.parametrize("target", ("receipt", "request"))
|
||||
def test_shared_spend_closes_receipt_and_nested_request_before_validation(target: str, mutation: str) -> None:
|
||||
from openultrasast.core import evaluation_admission
|
||||
|
||||
case = _authority_case()
|
||||
context_case, manifest, feasibility, readiness, _, resolver = case
|
||||
preparation = evaluation_admission.authorize_evaluation(
|
||||
manifest, feasibility, readiness, context_case.context, context_case.port, resolver
|
||||
)
|
||||
receipt = _append_without_precheck(case, preparation)
|
||||
if target == "request":
|
||||
receipt = _raw_copy(receipt, request=_raw_copy(receipt.request, mutation=mutation))
|
||||
else:
|
||||
receipt = _raw_copy(receipt, mutation=mutation)
|
||||
|
||||
with pytest.raises(Exception, match="declared fields|missing|receipt|request|closed"):
|
||||
evaluation_admission.validate_shared_spend(manifest, preparation, receipt, context_case.context, context_case.port)
|
||||
|
||||
|
||||
def _score_with(bundle, canonical_inputs, *, groups=None, readiness=None, weights=None):
|
||||
from openultrasast.core import evaluation_admission
|
||||
|
||||
context_case = bundle[5][0]
|
||||
return evaluation_admission.score_and_replay(
|
||||
bundle[3],
|
||||
canonical_inputs[1],
|
||||
bundle[7],
|
||||
bundle[8],
|
||||
canonical_inputs[6],
|
||||
bundle[1],
|
||||
canonical_inputs[8] if groups is None else groups,
|
||||
canonical_inputs[9].readiness if readiness is None else readiness,
|
||||
context_case.context,
|
||||
context_case.port,
|
||||
bundle[4],
|
||||
aggregate_weights=canonical_inputs[14].weights if weights is None else weights,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", ("extra", "missing"))
|
||||
@pytest.mark.parametrize("target", ("case_group", "case_item", "readiness", "aggregate_weight"))
|
||||
def test_scoring_closes_every_nonroot_phase_input_before_derivation(target: str, mutation: str) -> None:
|
||||
bundle = _bundle_case()
|
||||
inputs = _inputs(bundle=bundle, canonical_sources=True)
|
||||
groups = inputs[8]
|
||||
readiness = inputs[9].readiness
|
||||
aggregate = inputs[14]
|
||||
assert aggregate is not None
|
||||
weights = aggregate.weights
|
||||
if target == "case_group":
|
||||
groups = (_raw_copy(groups[0], mutation=mutation),) + groups[1:]
|
||||
elif target == "case_item":
|
||||
changed_case = _raw_copy(groups[0].cases[0], mutation=mutation)
|
||||
groups = (_raw_copy(groups[0], cases=(changed_case,) + groups[0].cases[1:]),) + groups[1:]
|
||||
elif target == "readiness":
|
||||
readiness = (_raw_copy(readiness[0], mutation=mutation),) + readiness[1:]
|
||||
else:
|
||||
weights = (_raw_copy(weights[0], mutation=mutation),) + weights[1:]
|
||||
|
||||
with pytest.raises(Exception, match="declared fields|missing|readiness|case|weight|closed"):
|
||||
_score_with(bundle, inputs, groups=groups, readiness=readiness, weights=weights)
|
||||
|
||||
|
||||
def test_facade_exposes_no_benchmark_execution_storage_or_presentation_ownership() -> None:
|
||||
from openultrasast.core import evaluation_admission
|
||||
|
||||
forbidden = {
|
||||
"execute_detector",
|
||||
"run_benchmark",
|
||||
"store_observation",
|
||||
"reserve_population",
|
||||
"notify_operator",
|
||||
"render_report",
|
||||
}
|
||||
assert forbidden.isdisjoint(evaluation_admission.__all__)
|
||||
assert all("benchmark" not in name and "presentation" not in name for name in evaluation_admission.__all__)
|
||||
@@ -215,7 +215,8 @@ def test_cutover_refuses_empty_scope_and_migration_compatibility(tmp_path: Path)
|
||||
|
||||
def test_complete_frozen_top_level_surface_is_reported_and_star_is_forbidden(tmp_path: Path) -> None:
|
||||
exports = static_top_level_exports(REPO)
|
||||
assert exports == ("admission", "consumer", "verdict")
|
||||
assert exports == ("admission", "consumer", "evaluation_admission", "verdict")
|
||||
assert {"admission", "consumer", "verdict"} <= set(exports)
|
||||
assert set(exports).isdisjoint(FROZEN_TOP_LEVEL_V1)
|
||||
assert len(FROZEN_TOP_LEVEL_V1) == 38
|
||||
imports = ", ".join(FROZEN_TOP_LEVEL_V1)
|
||||
|
||||
Reference in New Issue
Block a user