mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-04 10:48:19 +00:00
test(detection-core): verify v3 boundaries and growth
This commit is contained in:
@@ -709,7 +709,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
|
|||||||
- _Requirements: 18.2, 18.4, 18.6, 18.7, 18.8, 19.2, 19.3, 19.5, 19.6, 19.7, 19.8, 19.9, 19.10, 19.11, 20.3, 20.5, 20.6, 20.7_
|
- _Requirements: 18.2, 18.4, 18.6, 18.7, 18.8, 19.2, 19.3, 19.5, 19.6, 19.7, 19.8, 19.9, 19.10, 19.11, 20.3, 20.5, 20.6, 20.7_
|
||||||
- _Boundary: V3 Post-Spend and Replay Validation_
|
- _Boundary: V3 Post-Spend and Replay Validation_
|
||||||
- _Depends: 17.2, 17.4_
|
- _Depends: 17.2, 17.4_
|
||||||
- [ ] 18.4 Verify dependency boundaries, complexity caps, and bounded validation growth
|
- [x] 18.4 Verify dependency boundaries, complexity caps, and bounded validation growth
|
||||||
- Verify dependency direction, no V2/V3 aggregate imports across the version boundary, standard-library-only core runtime, and absence of benchmark, analyzer, model-runtime, or proof-execution ownership in V3 modules.
|
- Verify dependency direction, no V2/V3 aggregate imports across the version boundary, standard-library-only core runtime, and absence of benchmark, analyzer, model-runtime, or proof-execution ownership in V3 modules.
|
||||||
- Enforce function and module complexity caps and measure validation growth over increasing arms, scopes, observations, attempt events, cases, and reports.
|
- Enforce function and module complexity caps and measure validation growth over increasing arms, scopes, observations, attempt events, cases, and reports.
|
||||||
- Fail each measurement fixture unless its scoped inputs are readable and nonzero before interpreting timing, count, or clean-result output.
|
- Fail each measurement fixture unless its scoped inputs are readable and nonzero before interpreting timing, count, or clean-result output.
|
||||||
@@ -758,6 +758,7 @@ contract work and use synthetic/in-memory workflow boundaries only.
|
|||||||
- Task 18.1 proves the public V3 facade end to end across two component arms, one combined arm, two family/ecosystem scopes, one shared spend, complete replay validation, ordinary projection/whole deduplication, and exact fitted GO selection.
|
- Task 18.1 proves the public V3 facade end to end across two component arms, one combined arm, two family/ecosystem scopes, one shared spend, complete replay validation, ordinary projection/whole deduplication, and exact fitted GO selection.
|
||||||
- Task 18.2 proves exact owning-layer pre-spend and version refusals with a connected synthetic downstream driver, loud input-read instrumentation, frozen V2 outputs, custody-preserving insufficiency, and zero detector/label/result/quality effects after rejection.
|
- Task 18.2 proves exact owning-layer pre-spend and version refusals with a connected synthetic downstream driver, loud input-read instrumentation, frozen V2 outputs, custody-preserving insufficiency, and zero detector/label/result/quality effects after rejection.
|
||||||
- Task 18.3 proves exact owner-layer post-spend refusals across release, projection, combination, proof, metrics, reports, replay, current source/custody, aggregate, and fitted boundaries with connected authorization-effect instrumentation and all-arm visibility.
|
- Task 18.3 proves exact owner-layer post-spend refusals across release, projection, combination, proof, metrics, reports, replay, current source/custody, aggregate, and fitted boundaries with connected authorization-effect instrumentation and all-arm visibility.
|
||||||
|
- Task 18.4 enforces exact dependency and ownership boundaries across absolute, relative, package-root, wildcard, and near-prefix imports; validates genuine 1/2/4 replay-graph growth with connected bounded operation counts; and keeps all V3 validators within complexity caps.
|
||||||
- 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.
|
||||||
|
|||||||
@@ -122,13 +122,7 @@ def case_outcome_projection_from_value(value: object) -> CaseOutcomeProjectionV3
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _canonical_records(records: object) -> tuple[EvidenceRecord, ...]:
|
def _validate_record(record: EvidenceRecord) -> None:
|
||||||
if type(records) is not tuple or not records:
|
|
||||||
raise CaseOutcomeProjectionError("component evidence records must be a nonempty exact tuple")
|
|
||||||
if any(type(record) is not EvidenceRecord for record in records):
|
|
||||||
raise CaseOutcomeProjectionError("component evidence records must contain exact EvidenceRecord values")
|
|
||||||
validated = records
|
|
||||||
for record in validated:
|
|
||||||
try:
|
try:
|
||||||
if type(record.packet) is not EvidencePacket:
|
if type(record.packet) is not EvidencePacket:
|
||||||
raise CaseOutcomeProjectionError("evidence record packet must use exact EvidencePacket")
|
raise CaseOutcomeProjectionError("evidence record packet must use exact EvidencePacket")
|
||||||
@@ -148,6 +142,16 @@ def _canonical_records(records: object) -> tuple[EvidenceRecord, ...]:
|
|||||||
raise CaseOutcomeProjectionError("component evidence record cannot be revalidated") from exc
|
raise CaseOutcomeProjectionError("component evidence record cannot be revalidated") from exc
|
||||||
if record.record_id != expected_record_id:
|
if record.record_id != expected_record_id:
|
||||||
raise CaseOutcomeProjectionError("evidence record identity cannot be re-derived")
|
raise CaseOutcomeProjectionError("evidence record identity cannot be re-derived")
|
||||||
|
|
||||||
|
|
||||||
|
def _canonical_records(records: object) -> tuple[EvidenceRecord, ...]:
|
||||||
|
if type(records) is not tuple or not records:
|
||||||
|
raise CaseOutcomeProjectionError("component evidence records must be a nonempty exact tuple")
|
||||||
|
if any(type(record) is not EvidenceRecord for record in records):
|
||||||
|
raise CaseOutcomeProjectionError("component evidence records must contain exact EvidenceRecord values")
|
||||||
|
validated = records
|
||||||
|
for record in validated:
|
||||||
|
_validate_record(record)
|
||||||
identities = tuple(record.record_id for record in validated)
|
identities = tuple(record.record_id for record in validated)
|
||||||
if len(set(identities)) != len(identities):
|
if len(set(identities)) != len(identities):
|
||||||
raise CaseOutcomeProjectionError("component evidence record identities must be unique")
|
raise CaseOutcomeProjectionError("component evidence record identities must be unique")
|
||||||
|
|||||||
@@ -209,19 +209,18 @@ class CombinationLineageV3(EvaluationV3Contract, NonAuthorizingV3):
|
|||||||
if type(self.rule) is not CombinationRuleV3:
|
if type(self.rule) is not CombinationRuleV3:
|
||||||
raise CombinationValidationError("lineage rule must use exact CombinationRuleV3")
|
raise CombinationValidationError("lineage rule must use exact CombinationRuleV3")
|
||||||
self.rule.__post_init__()
|
self.rule.__post_init__()
|
||||||
if (
|
_validate_lineage_cases(self.rule, self.combined_cases)
|
||||||
type(self.combined_cases) is not tuple
|
_validate_lineage_observations(self.rule, self.combined_cases, self.component_observation_digests)
|
||||||
or not self.combined_cases
|
_bind(self, "lineage_digest", canonical.content_digest(_value("combination_lineage", _lineage_payload(self))))
|
||||||
or any(type(item) is not CombinedCaseOutcomeV3 for item in self.combined_cases)
|
|
||||||
):
|
|
||||||
raise CombinationValidationError("lineage combined cases must be a nonempty exact tuple")
|
def _validate_lineage_case(rule: CombinationRuleV3, item: CombinedCaseOutcomeV3) -> None:
|
||||||
for item in self.combined_cases:
|
|
||||||
item.__post_init__()
|
item.__post_init__()
|
||||||
if item.key.arm_id != self.rule.combined_arm_id:
|
if item.key.arm_id != rule.combined_arm_id:
|
||||||
raise CombinationValidationError("lineage combined case belongs to another arm")
|
raise CombinationValidationError("lineage combined case belongs to another arm")
|
||||||
if tuple(component.component_arm_id for component in item.components) != self.rule.component_arm_ids:
|
if tuple(component.component_arm_id for component in item.components) != rule.component_arm_ids:
|
||||||
raise CombinationValidationError("lineage components differ from the registered rule")
|
raise CombinationValidationError("lineage components differ from the registered rule")
|
||||||
decision = _decision_row(self.rule, item.components)
|
decision = _decision_row(rule, item.components)
|
||||||
if (item.decision_row_digest, item.normalized_outcome) != (decision.row_digest, decision.combined_outcome):
|
if (item.decision_row_digest, item.normalized_outcome) != (decision.row_digest, decision.combined_outcome):
|
||||||
raise CombinationValidationError("lineage combined outcome differs from deterministic table replay")
|
raise CombinationValidationError("lineage combined outcome differs from deterministic table replay")
|
||||||
projection = CaseOutcomeProjectionV3(
|
projection = CaseOutcomeProjectionV3(
|
||||||
@@ -233,23 +232,27 @@ class CombinationLineageV3(EvaluationV3Contract, NonAuthorizingV3):
|
|||||||
)
|
)
|
||||||
if item.combined_projection_digest != projection.projection_digest:
|
if item.combined_projection_digest != projection.projection_digest:
|
||||||
raise CombinationValidationError("lineage combined projection differs from deterministic table replay")
|
raise CombinationValidationError("lineage combined projection differs from deterministic table replay")
|
||||||
order = tuple(
|
|
||||||
sorted(
|
|
||||||
self.combined_cases,
|
def _validate_lineage_cases(rule: CombinationRuleV3, cases: object) -> None:
|
||||||
key=lambda item: (item.key.scope.family_id, item.key.scope.ecosystem, item.case_input_digest),
|
if type(cases) is not tuple or not cases or any(type(item) is not CombinedCaseOutcomeV3 for item in cases):
|
||||||
)
|
raise CombinationValidationError("lineage combined cases must be a nonempty exact tuple")
|
||||||
)
|
for item in cases:
|
||||||
keys = tuple((item.key.scope, item.case_input_digest) for item in self.combined_cases)
|
_validate_lineage_case(rule, item)
|
||||||
if self.combined_cases != order or len(set(keys)) != len(keys):
|
order = tuple(sorted(cases, key=lambda item: (item.key.scope.family_id, item.key.scope.ecosystem, item.case_input_digest)))
|
||||||
|
keys = tuple((item.key.scope, item.case_input_digest) for item in cases)
|
||||||
|
if cases != order or len(set(keys)) != len(keys):
|
||||||
raise CombinationValidationError("lineage combined cases must be unique and canonical")
|
raise CombinationValidationError("lineage combined cases must be unique and canonical")
|
||||||
expected_observations = _component_observations(self.rule, self.combined_cases)
|
|
||||||
if type(self.component_observation_digests) is not tuple or self.component_observation_digests != expected_observations:
|
|
||||||
|
def _validate_lineage_observations(rule: CombinationRuleV3, cases: tuple[CombinedCaseOutcomeV3, ...], observations: object) -> None:
|
||||||
|
expected = _component_observations(rule, cases)
|
||||||
|
if type(observations) is not tuple or observations != expected:
|
||||||
raise CombinationValidationError("lineage component observation set is incomplete or non-canonical")
|
raise CombinationValidationError("lineage component observation set is incomplete or non-canonical")
|
||||||
if len(set(self.component_observation_digests)) != len(self.component_observation_digests):
|
if len(set(observations)) != len(observations):
|
||||||
raise CombinationValidationError("lineage component observations must be unique across arms")
|
raise CombinationValidationError("lineage component observations must be unique across arms")
|
||||||
for digest in self.component_observation_digests:
|
for digest in observations:
|
||||||
_digest(digest, "component observation digest")
|
_digest(digest, "component observation digest")
|
||||||
_bind(self, "lineage_digest", canonical.content_digest(_value("combination_lineage", _lineage_payload(self))))
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_inputs(
|
def _validate_inputs(
|
||||||
|
|||||||
@@ -184,6 +184,17 @@ def _validate_case_identity(value: ArmAdmissionCaseResultV3) -> None:
|
|||||||
"result_digest",
|
"result_digest",
|
||||||
):
|
):
|
||||||
_digest(getattr(value, field), field)
|
_digest(getattr(value, field), field)
|
||||||
|
_validate_case_projection(value)
|
||||||
|
if type(value.role) is not AdmissionCaseRole:
|
||||||
|
raise EvaluationReleaseError("case role must use exact AdmissionCaseRole")
|
||||||
|
if value.pair_id_digest is not None:
|
||||||
|
_digest(value.pair_id_digest, "pair identity digest")
|
||||||
|
_validate_proof_candidate(value.proof_candidate)
|
||||||
|
if type(value.total_reply_ms) is not int or value.total_reply_ms < 0:
|
||||||
|
raise EvaluationReleaseError("case total reply time must be a non-negative integer")
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_case_projection(value: ArmAdmissionCaseResultV3) -> None:
|
||||||
if type(value.outcome_projection) is not CaseOutcomeProjectionV3:
|
if type(value.outcome_projection) is not CaseOutcomeProjectionV3:
|
||||||
raise EvaluationReleaseError("case outcome projection must use exact CaseOutcomeProjectionV3")
|
raise EvaluationReleaseError("case outcome projection must use exact CaseOutcomeProjectionV3")
|
||||||
try:
|
try:
|
||||||
@@ -192,16 +203,14 @@ def _validate_case_identity(value: ArmAdmissionCaseResultV3) -> None:
|
|||||||
raise EvaluationReleaseError("case outcome projection is malformed") from exc
|
raise EvaluationReleaseError("case outcome projection is malformed") from exc
|
||||||
if value.outcome_projection.case_input_digest != value.case_input_digest:
|
if value.outcome_projection.case_input_digest != value.case_input_digest:
|
||||||
raise EvaluationReleaseError("case outcome projection input identity does not match its released case")
|
raise EvaluationReleaseError("case outcome projection input identity does not match its released case")
|
||||||
if type(value.role) is not AdmissionCaseRole:
|
|
||||||
raise EvaluationReleaseError("case role must use exact AdmissionCaseRole")
|
|
||||||
if value.pair_id_digest is not None:
|
def _validate_proof_candidate(value: ProofCandidateIdentityV3 | None) -> None:
|
||||||
_digest(value.pair_id_digest, "pair identity digest")
|
if value is None:
|
||||||
if value.proof_candidate is not None:
|
return
|
||||||
if type(value.proof_candidate) is not ProofCandidateIdentityV3:
|
if type(value) is not ProofCandidateIdentityV3:
|
||||||
raise EvaluationReleaseError("proof candidate must use exact ProofCandidateIdentityV3")
|
raise EvaluationReleaseError("proof candidate must use exact ProofCandidateIdentityV3")
|
||||||
value.proof_candidate.__post_init__()
|
value.__post_init__()
|
||||||
if type(value.total_reply_ms) is not int or value.total_reply_ms < 0:
|
|
||||||
raise EvaluationReleaseError("case total reply time must be a non-negative integer")
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_case_sequences(value: ArmAdmissionCaseResultV3) -> None:
|
def _validate_case_sequences(value: ArmAdmissionCaseResultV3) -> None:
|
||||||
|
|||||||
@@ -86,7 +86,8 @@ def _reviewed_plan():
|
|||||||
return context_case, manifest, readiness
|
return context_case, manifest, readiness
|
||||||
|
|
||||||
|
|
||||||
def _authority_case():
|
def _authority_case(*, attempt_count: int = 2):
|
||||||
|
assert attempt_count > 0
|
||||||
context_case, plan, readiness = _reviewed_plan()
|
context_case, plan, readiness = _reviewed_plan()
|
||||||
policy = context_case.context.admission_review_policy
|
policy = context_case.context.admission_review_policy
|
||||||
feasibility = derive_evaluation_feasibility(plan, policy, context_case.resolver)
|
feasibility = derive_evaluation_feasibility(plan, policy, context_case.resolver)
|
||||||
@@ -107,7 +108,7 @@ def _authority_case():
|
|||||||
access = ObservationAccessPolicyV3(tuple(PublicStatusFieldV3), False, False, "")
|
access = ObservationAccessPolicyV3(tuple(PublicStatusFieldV3), False, False, "")
|
||||||
predecessor = None
|
predecessor = None
|
||||||
event_refs = []
|
event_refs = []
|
||||||
for index in range(2):
|
for index in range(attempt_count):
|
||||||
event = _event(
|
event = _event(
|
||||||
identity,
|
identity,
|
||||||
PreSpendDispositionV3.SEALED,
|
PreSpendDispositionV3.SEALED,
|
||||||
|
|||||||
@@ -0,0 +1,368 @@
|
|||||||
|
"""Boundary and deterministic validation-growth gates for evaluation admission V3."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ast
|
||||||
|
import copy
|
||||||
|
import io
|
||||||
|
import sys
|
||||||
|
import tokenize
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from test_core_evaluation_end_to_end import _complete_replay
|
||||||
|
|
||||||
|
from openultrasast.core import canonical, evaluation_admission
|
||||||
|
from openultrasast.core.admission_context import AdmissionValidationContext
|
||||||
|
from openultrasast.core.custody import PopulationCustodyLog, PopulationCustodyPort
|
||||||
|
from openultrasast.core.evaluation_replay import EvaluationReplayV3
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parents[1]
|
||||||
|
CORE = REPO / "src/openultrasast/core"
|
||||||
|
V2_AGGREGATE_ROOTS = frozenset({"_admission_replay", "admission", "consumer"})
|
||||||
|
FORBIDDEN_RUNTIME_PREFIXES = (
|
||||||
|
"benchmarks",
|
||||||
|
"dspy",
|
||||||
|
"openultrasast.analyzer",
|
||||||
|
"openultrasast.benchmarks",
|
||||||
|
"openultrasast.hunt",
|
||||||
|
"openultrasast.model_runtime",
|
||||||
|
"openultrasast.proof_execution",
|
||||||
|
"openultrasast.search",
|
||||||
|
"openultrasast.tools",
|
||||||
|
)
|
||||||
|
FORBIDDEN_OWNER_NAMES = frozenset(
|
||||||
|
{
|
||||||
|
"analyze_repository",
|
||||||
|
"execute_detector",
|
||||||
|
"execute_proof",
|
||||||
|
"invoke_model",
|
||||||
|
"load_model_runtime",
|
||||||
|
"run_benchmark",
|
||||||
|
"store_observation",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
LAYERS = (
|
||||||
|
(
|
||||||
|
"_evaluation_measurement_contracts",
|
||||||
|
"_evaluation_arm_configuration",
|
||||||
|
"evaluation_measurement",
|
||||||
|
"evaluation_version",
|
||||||
|
),
|
||||||
|
("_evaluation_plan_review", "evaluation_plan"),
|
||||||
|
("evaluation_feasibility",),
|
||||||
|
("evaluation_case_outcome",),
|
||||||
|
("_evaluation_attempt_validation", "evaluation_attempt", "evaluation_observation"),
|
||||||
|
("evaluation_authority",),
|
||||||
|
("evaluation_spend",),
|
||||||
|
("_evaluation_release_validation", "evaluation_release", "evaluation_case_validation", "evaluation_scoped_metrics"),
|
||||||
|
("_evaluation_proof_plan", "evaluation_proof", "evaluation_combination"),
|
||||||
|
("evaluation_ordinary_projection",),
|
||||||
|
("evaluation_metric_derivation",),
|
||||||
|
("_evaluation_report_validation", "evaluation_report", "evaluation_aggregate"),
|
||||||
|
("_evaluation_replay_report", "evaluation_replay"),
|
||||||
|
("evaluation_replay_validation",),
|
||||||
|
("evaluation_admission",),
|
||||||
|
("_evaluation_fitted_shape", "evaluation_fitted"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class BoundaryReport:
|
||||||
|
modules_read: int
|
||||||
|
bytes_read: int
|
||||||
|
import_edges: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ArtifactCounts:
|
||||||
|
arms: int
|
||||||
|
arm_scopes: int
|
||||||
|
observations: int
|
||||||
|
attempt_events: int
|
||||||
|
cases: int
|
||||||
|
reports: int
|
||||||
|
|
||||||
|
@property
|
||||||
|
def total(self) -> int:
|
||||||
|
return sum((self.arms, self.arm_scopes, self.observations, self.attempt_events, self.cases, self.reports))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class GrowthPoint:
|
||||||
|
component_pairs: int
|
||||||
|
artifacts: ArtifactCounts
|
||||||
|
resolver_reads: int
|
||||||
|
custody_reads: int
|
||||||
|
|
||||||
|
@property
|
||||||
|
def operations(self) -> int:
|
||||||
|
return self.resolver_reads + self.custody_reads
|
||||||
|
|
||||||
|
|
||||||
|
class _CountingResolver:
|
||||||
|
def __init__(self, wrapped: canonical.ContentResolver) -> None:
|
||||||
|
self.wrapped = wrapped
|
||||||
|
self.reads = 0
|
||||||
|
self.bytes_read = 0
|
||||||
|
|
||||||
|
def resolve(self, reference: canonical.ContentRef) -> canonical.ResolvedContent:
|
||||||
|
resolved = self.wrapped.resolve(reference)
|
||||||
|
assert resolved.content, f"validation instrument resolved zero bytes for {reference.artifact_id}"
|
||||||
|
self.reads += 1
|
||||||
|
self.bytes_read += len(resolved.content)
|
||||||
|
return resolved
|
||||||
|
|
||||||
|
|
||||||
|
class _CountingCustody:
|
||||||
|
def __init__(self, wrapped: PopulationCustodyPort) -> None:
|
||||||
|
self.wrapped = wrapped
|
||||||
|
self.reads = 0
|
||||||
|
|
||||||
|
def current_log(self, population_digest: str) -> PopulationCustodyLog:
|
||||||
|
log = self.wrapped.current_log(population_digest)
|
||||||
|
assert log.receipt_count > 0 and log.receipts
|
||||||
|
self.reads += 1
|
||||||
|
return log
|
||||||
|
|
||||||
|
|
||||||
|
def _v3_paths() -> tuple[Path, ...]:
|
||||||
|
paths = tuple(sorted({*CORE.glob("evaluation_*.py"), *CORE.glob("_evaluation_*.py")}))
|
||||||
|
assert paths, "V3 boundary instrument discovered zero modules"
|
||||||
|
expected = {name for layer in LAYERS for name in layer}
|
||||||
|
actual = {path.stem for path in paths}
|
||||||
|
assert actual == expected, f"V3 module authority changed: missing={sorted(expected - actual)}, extra={sorted(actual - expected)}"
|
||||||
|
return paths
|
||||||
|
|
||||||
|
|
||||||
|
def _read_nonzero(path: Path, purpose: str) -> bytes:
|
||||||
|
try:
|
||||||
|
content = path.read_bytes()
|
||||||
|
except OSError as exc:
|
||||||
|
raise AssertionError(f"{purpose} could not read {path.relative_to(REPO)}: {exc}") from exc
|
||||||
|
assert content, f"{purpose} read zero bytes from {path.relative_to(REPO)}"
|
||||||
|
return content
|
||||||
|
|
||||||
|
|
||||||
|
def _import_from_module(node: ast.ImportFrom) -> str:
|
||||||
|
if node.level == 0:
|
||||||
|
assert node.module is not None
|
||||||
|
return node.module
|
||||||
|
package = ("openultrasast", "core")
|
||||||
|
retained = len(package) - (node.level - 1)
|
||||||
|
assert retained > 0, f"relative core import escapes package at line {node.lineno}"
|
||||||
|
parts = (*package[:retained], *((node.module or "").split(".") if node.module else ()))
|
||||||
|
return ".".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _imports(tree: ast.AST) -> tuple[tuple[str, int], ...]:
|
||||||
|
found: list[tuple[str, int]] = []
|
||||||
|
for node in ast.walk(tree):
|
||||||
|
if isinstance(node, ast.Import):
|
||||||
|
found.extend((alias.name, node.lineno) for alias in node.names)
|
||||||
|
elif isinstance(node, ast.ImportFrom):
|
||||||
|
module = _import_from_module(node)
|
||||||
|
if module in {"openultrasast", "openultrasast.core"}:
|
||||||
|
found.extend((f"{module}.{alias.name}", node.lineno) for alias in node.names)
|
||||||
|
elif any(alias.name == "*" for alias in node.names):
|
||||||
|
found.append((f"{module}.*", node.lineno))
|
||||||
|
else:
|
||||||
|
found.append((module, node.lineno))
|
||||||
|
return tuple(found)
|
||||||
|
|
||||||
|
|
||||||
|
def _core_dependency(source: str, imported: str) -> str | None:
|
||||||
|
assert imported != "openultrasast.core", f"core package-root import is forbidden: {source}"
|
||||||
|
if not imported.startswith("openultrasast.core."):
|
||||||
|
return None
|
||||||
|
assert not imported.endswith(".*"), f"core wildcard import is forbidden: {source} -> {imported}"
|
||||||
|
return imported.removeprefix("openultrasast.core.").partition(".")[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _audit_import(source: str, imported: str, line: int, ranks: dict[str, int]) -> None:
|
||||||
|
assert not imported.startswith(FORBIDDEN_RUNTIME_PREFIXES), f"forbidden V3 runtime dependency {source}:{line}: {imported}"
|
||||||
|
root = imported.partition(".")[0]
|
||||||
|
is_core_namespace = imported == "openultrasast.core" or imported.startswith("openultrasast.core.")
|
||||||
|
assert is_core_namespace or root in sys.stdlib_module_names, f"non-standard-library V3 dependency {source}:{line}: {imported}"
|
||||||
|
dependency = _core_dependency(source, imported)
|
||||||
|
if dependency is None:
|
||||||
|
return
|
||||||
|
assert dependency not in V2_AGGREGATE_ROOTS, f"V3 aggregate boundary crossed: {source} -> {dependency}"
|
||||||
|
if dependency in ranks:
|
||||||
|
assert ranks[dependency] <= ranks[source], f"forward V3 dependency {source} -> {dependency}"
|
||||||
|
|
||||||
|
|
||||||
|
def _audit_lower_imports(source: str, tree: ast.AST, v3_names: set[str]) -> None:
|
||||||
|
dependencies = {dependency for imported, _ in _imports(tree) if (dependency := _core_dependency(source, imported)) is not None}
|
||||||
|
crossed = dependencies & v3_names
|
||||||
|
assert not crossed, f"lower core imports V3: {source} -> {sorted(crossed)}"
|
||||||
|
|
||||||
|
|
||||||
|
def _logical_lines(content: bytes) -> int:
|
||||||
|
count = 0
|
||||||
|
has_code = False
|
||||||
|
ignored = {tokenize.ENCODING, tokenize.COMMENT, tokenize.NL, tokenize.INDENT, tokenize.DEDENT}
|
||||||
|
for token in tokenize.tokenize(io.BytesIO(content).readline):
|
||||||
|
if token.type in ignored:
|
||||||
|
continue
|
||||||
|
if token.type == tokenize.NEWLINE:
|
||||||
|
count += int(has_code)
|
||||||
|
has_code = False
|
||||||
|
elif token.type != tokenize.ENDMARKER:
|
||||||
|
has_code = True
|
||||||
|
return count + int(has_code)
|
||||||
|
|
||||||
|
|
||||||
|
def _audit_complexity(path: Path, content: bytes, tree: ast.AST) -> None:
|
||||||
|
assert _logical_lines(content) <= 400, f"V3 module exceeds 400 logical lines: {path.name}"
|
||||||
|
lines = content.splitlines(keepends=True)
|
||||||
|
for node in ast.walk(tree):
|
||||||
|
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.end_lineno:
|
||||||
|
function = b"".join(lines[node.lineno - 1 : node.end_lineno])
|
||||||
|
assert _logical_lines(function) <= 50, f"V3 function exceeds 50 logical lines: {path.name}:{node.name}"
|
||||||
|
|
||||||
|
|
||||||
|
def _audit_v3_boundary() -> BoundaryReport:
|
||||||
|
ranks = {name: rank for rank, layer in enumerate(LAYERS) for name in layer}
|
||||||
|
bytes_read = 0
|
||||||
|
edges = 0
|
||||||
|
for path in _v3_paths():
|
||||||
|
content = _read_nonzero(path, "V3 boundary instrument")
|
||||||
|
bytes_read += len(content)
|
||||||
|
tree = ast.parse(content, filename=path.as_posix())
|
||||||
|
_audit_complexity(path, content, tree)
|
||||||
|
defined = {node.name for node in ast.walk(tree) if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}
|
||||||
|
assert FORBIDDEN_OWNER_NAMES.isdisjoint(defined), f"V3 owns forbidden runtime action in {path.name}"
|
||||||
|
for imported, line in _imports(tree):
|
||||||
|
_audit_import(path.stem, imported, line, ranks)
|
||||||
|
edges += 1
|
||||||
|
v3_paths = set(_v3_paths())
|
||||||
|
v3_names = {path.stem for path in v3_paths}
|
||||||
|
lower_paths = tuple(path for path in sorted(CORE.glob("*.py")) if path not in v3_paths and path.name != "__init__.py")
|
||||||
|
assert lower_paths, "version-boundary instrument discovered zero lower core modules"
|
||||||
|
for path in lower_paths:
|
||||||
|
tree = ast.parse(_read_nonzero(path, "version-boundary instrument"))
|
||||||
|
_audit_lower_imports(path.stem, tree, v3_names)
|
||||||
|
return BoundaryReport(len(_v3_paths()), bytes_read, edges)
|
||||||
|
|
||||||
|
|
||||||
|
def _artifact_counts(replay: EvaluationReplayV3) -> ArtifactCounts:
|
||||||
|
configurations = replay.plan_manifest.declaration.arm_configurations
|
||||||
|
arm_scopes = {(configuration.arm_id, scope) for configuration in configurations for scope in configuration.exact_scopes}
|
||||||
|
counts = ArtifactCounts(
|
||||||
|
len(configurations),
|
||||||
|
len(arm_scopes),
|
||||||
|
len(replay.admission_manifest.observations),
|
||||||
|
len(replay.admission_manifest.attempt_history.events),
|
||||||
|
sum(len(group.cases) for group in replay.cases_by_arm),
|
||||||
|
len(replay.reports),
|
||||||
|
)
|
||||||
|
assert min(counts.arms, counts.arm_scopes, counts.observations, counts.attempt_events, counts.cases, counts.reports) > 0
|
||||||
|
return counts
|
||||||
|
|
||||||
|
|
||||||
|
def _prove_fixture_inputs(replay: EvaluationReplayV3, resolver: canonical.ContentResolver) -> ArtifactCounts:
|
||||||
|
fixture_bytes = _read_nonzero(Path(__file__), "growth fixture instrument")
|
||||||
|
references = tuple(item.observation for item in replay.admission_manifest.observations) + tuple(
|
||||||
|
item.event for item in replay.admission_manifest.attempt_history.events
|
||||||
|
)
|
||||||
|
resolved_bytes = 0
|
||||||
|
for reference in references:
|
||||||
|
content = resolver.resolve(reference).content
|
||||||
|
assert content, f"growth fixture resolved zero bytes for {reference.artifact_id}"
|
||||||
|
resolved_bytes += len(content)
|
||||||
|
receipts = tuple(receipt for group in replay.cases_by_arm for case in group.cases for receipt in case.input_receipts)
|
||||||
|
receipt_bytes = sum(receipt.byte_count for receipt in receipts if receipt.opened)
|
||||||
|
assert references and resolved_bytes > 0 and receipts and receipt_bytes > 0 and len(fixture_bytes) > 0
|
||||||
|
return _artifact_counts(replay)
|
||||||
|
|
||||||
|
|
||||||
|
def _measure_growth(
|
||||||
|
replay: EvaluationReplayV3,
|
||||||
|
context: AdmissionValidationContext,
|
||||||
|
custody: PopulationCustodyPort,
|
||||||
|
resolver: canonical.ContentResolver,
|
||||||
|
component_pairs: int,
|
||||||
|
) -> GrowthPoint:
|
||||||
|
counted_resolver = _CountingResolver(resolver)
|
||||||
|
counted_custody = _CountingCustody(custody)
|
||||||
|
assert evaluation_admission.validate_evaluation_replay(replay, context, counted_custody, counted_resolver) == replay.reports
|
||||||
|
assert counted_resolver.reads > 0 and counted_resolver.bytes_read > 0 and counted_custody.reads > 0
|
||||||
|
return GrowthPoint(component_pairs, _artifact_counts(replay), counted_resolver.reads, counted_custody.reads)
|
||||||
|
|
||||||
|
|
||||||
|
def test_v3_boundary_report_is_clean() -> None:
|
||||||
|
report = _audit_v3_boundary()
|
||||||
|
assert report.modules_read > 0 and report.bytes_read > 0 and report.import_edges > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_aliases_cannot_hide_version_boundary_edges() -> None:
|
||||||
|
ranks = {name: rank for rank, layer in enumerate(LAYERS) for name in layer}
|
||||||
|
v3_names = {name for layer in LAYERS for name in layer}
|
||||||
|
package_import = _imports(ast.parse("from openultrasast import core"))[0]
|
||||||
|
|
||||||
|
assert package_import[0] == "openultrasast.core"
|
||||||
|
with pytest.raises(AssertionError, match="package-root"):
|
||||||
|
_audit_import("evaluation_admission", *package_import, ranks)
|
||||||
|
with pytest.raises(AssertionError, match="package-root"):
|
||||||
|
_audit_lower_imports("lower_module", ast.parse("from openultrasast import core"), v3_names)
|
||||||
|
|
||||||
|
for source in ("from openultrasast.core import admission", "import openultrasast.core.admission"):
|
||||||
|
with pytest.raises(AssertionError, match="aggregate boundary"):
|
||||||
|
_audit_import("evaluation_admission", *_imports(ast.parse(source))[0], ranks)
|
||||||
|
for source in ("from . import admission", "from .admission import authorize_admission"):
|
||||||
|
with pytest.raises(AssertionError, match="aggregate boundary"):
|
||||||
|
_audit_import("evaluation_admission", *_imports(ast.parse(source))[0], ranks)
|
||||||
|
for child in ("evaluation_admission", "_evaluation_replay_report"):
|
||||||
|
for source in (f"from openultrasast.core import {child}", f"import openultrasast.core.{child}"):
|
||||||
|
with pytest.raises(AssertionError, match="lower core imports V3"):
|
||||||
|
_audit_lower_imports("lower_module", ast.parse(source), v3_names)
|
||||||
|
for source in (f"from . import {child}", f"from .{child} import public_symbol"):
|
||||||
|
with pytest.raises(AssertionError, match="lower core imports V3"):
|
||||||
|
_audit_lower_imports("lower_module", ast.parse(source), v3_names)
|
||||||
|
for source in ("from openultrasast.core import *", "from openultrasast.core.evaluation_admission import *"):
|
||||||
|
imported = _imports(ast.parse(source))[0]
|
||||||
|
with pytest.raises(AssertionError, match="wildcard"):
|
||||||
|
_audit_import("evaluation_admission", *imported, ranks)
|
||||||
|
with pytest.raises(AssertionError, match="wildcard"):
|
||||||
|
_audit_lower_imports("lower_module", ast.parse(source), v3_names)
|
||||||
|
|
||||||
|
for imported in ("openultrasast.coreevil", "openultrasast.core_extra", "openultrasast.corex.vendor"):
|
||||||
|
with pytest.raises(AssertionError, match="non-standard-library"):
|
||||||
|
_audit_import("evaluation_admission", imported, 1, ranks)
|
||||||
|
|
||||||
|
direct_child = _imports(ast.parse("from openultrasast.core import evaluation_replay_validation"))[0]
|
||||||
|
_audit_import("evaluation_admission", *direct_child, ranks)
|
||||||
|
relative_child = _imports(ast.parse("from . import evaluation_replay_validation"))[0]
|
||||||
|
_audit_import("evaluation_admission", *relative_child, ranks)
|
||||||
|
for source in (
|
||||||
|
"from openultrasast.core import canonical",
|
||||||
|
"import openultrasast.core.canonical",
|
||||||
|
"from . import canonical",
|
||||||
|
"from .canonical import digest",
|
||||||
|
):
|
||||||
|
_audit_lower_imports("lower_module", ast.parse(source), v3_names)
|
||||||
|
|
||||||
|
|
||||||
|
def test_replay_validation_work_is_bounded_by_supplied_artifacts(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
fixtures = tuple(_complete_replay(monkeypatch, component_pairs=size) for size in (1, 2, 4))
|
||||||
|
points = []
|
||||||
|
for size, completed in zip((1, 2, 4), fixtures, strict=True):
|
||||||
|
bundle, replay, *_ = completed
|
||||||
|
context, custody, resolver = bundle[5][0].context, bundle[5][0].port, bundle[4]
|
||||||
|
assert _prove_fixture_inputs(replay, resolver) == _artifact_counts(replay)
|
||||||
|
points.append(_measure_growth(replay, context, custody, resolver, size))
|
||||||
|
|
||||||
|
expected = [ArtifactCounts(3 * size, 6 * size, 6 * size, 2 * size, 18 * size, 3 * size) for size in (1, 2, 4)]
|
||||||
|
assert [point.artifacts for point in points] == expected
|
||||||
|
assert len({completed[1].replay_digest for completed in fixtures}) == 3
|
||||||
|
assert points[0].operations < points[1].operations < points[2].operations
|
||||||
|
assert all(point.operations <= points[0].operations * point.component_pairs for point in points)
|
||||||
|
|
||||||
|
bundle, replay, *_ = fixtures[-1]
|
||||||
|
context, custody, resolver = bundle[5][0].context, bundle[5][0].port, bundle[4]
|
||||||
|
corrupted = copy.copy(replay)
|
||||||
|
object.__setattr__(corrupted, "replay_digest", "0" * 64)
|
||||||
|
with pytest.raises(Exception, match="digest|canonical|replay|derivation"):
|
||||||
|
evaluation_admission.validate_evaluation_replay(corrupted, context, custody, resolver)
|
||||||
@@ -65,9 +65,49 @@ def _expanded_configuration(configuration, scopes, fitted_configuration_digest):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _multi_family_plan(plan, scopes, fitted_configuration_digest):
|
def _group_arm_id(arm_id, group):
|
||||||
|
return arm_id if group == 0 else f"{arm_id}-{group + 1}"
|
||||||
|
|
||||||
|
|
||||||
|
def _clone_configuration(configuration, scopes, fitted_configuration_digest, group):
|
||||||
|
expanded = _expanded_configuration(configuration, scopes, fitted_configuration_digest)
|
||||||
|
arm_id = _group_arm_id(expanded.arm_id, group)
|
||||||
|
policies = tuple(
|
||||||
|
replace(
|
||||||
|
policy,
|
||||||
|
key=ArmScopeKey(arm_id, policy.key.scope),
|
||||||
|
rules=tuple(replace(rule, key=ArmScopeKey(arm_id, rule.key.scope), rule_digest="") for rule in policy.rules),
|
||||||
|
policy_digest="",
|
||||||
|
)
|
||||||
|
for policy in expanded.denominator_policies
|
||||||
|
)
|
||||||
|
thresholds = tuple(replace(row, key=ArmScopeKey(arm_id, row.key.scope), threshold_digest="") for row in expanded.thresholds)
|
||||||
|
sufficiency = tuple(replace(row, key=ArmScopeKey(arm_id, row.key.scope), rule_digest="") for row in expanded.sufficiency_rules)
|
||||||
|
rule = expanded.combination_rule
|
||||||
|
if rule is not None:
|
||||||
|
rule = replace(
|
||||||
|
rule,
|
||||||
|
combined_arm_id=arm_id,
|
||||||
|
component_arm_ids=tuple(_group_arm_id(item, group) for item in rule.component_arm_ids),
|
||||||
|
rule_digest="",
|
||||||
|
)
|
||||||
|
return replace(
|
||||||
|
expanded,
|
||||||
|
arm_id=arm_id,
|
||||||
|
denominator_policies=policies,
|
||||||
|
thresholds=thresholds,
|
||||||
|
sufficiency_rules=sufficiency,
|
||||||
|
combination_rule=rule,
|
||||||
|
configuration_identity_digest="",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _multi_family_plan(plan, scopes, fitted_configuration_digest, *, component_pairs=1):
|
||||||
|
assert component_pairs > 0
|
||||||
configurations = tuple(
|
configurations = tuple(
|
||||||
_expanded_configuration(configuration, scopes, fitted_configuration_digest) for configuration in plan.declaration.arm_configurations
|
_clone_configuration(configuration, scopes, fitted_configuration_digest, group)
|
||||||
|
for group in range(component_pairs)
|
||||||
|
for configuration in plan.declaration.arm_configurations
|
||||||
)
|
)
|
||||||
inputs = tuple(sorted({slot.input_identity_digest for slot in plan.declaration.expected_observation_slots}))
|
inputs = tuple(sorted({slot.input_identity_digest for slot in plan.declaration.expected_observation_slots}))
|
||||||
declaration = create_evaluation_plan_declaration(
|
declaration = create_evaluation_plan_declaration(
|
||||||
@@ -95,18 +135,18 @@ def _multi_family_plan(plan, scopes, fitted_configuration_digest):
|
|||||||
return _review_plan_draft(draft, plan.review)
|
return _review_plan_draft(draft, plan.review)
|
||||||
|
|
||||||
|
|
||||||
def _authority_case(plan, context_case, readiness):
|
def _authority_case(plan, context_case, readiness, *, attempt_count=2):
|
||||||
original = authority_fixtures._reviewed_plan
|
original = authority_fixtures._reviewed_plan
|
||||||
authority_fixtures._reviewed_plan = lambda: (context_case, plan, readiness)
|
authority_fixtures._reviewed_plan = lambda: (context_case, plan, readiness)
|
||||||
try:
|
try:
|
||||||
return authority_fixtures._authority_case()
|
return authority_fixtures._authority_case(attempt_count=attempt_count)
|
||||||
finally:
|
finally:
|
||||||
authority_fixtures._reviewed_plan = original
|
authority_fixtures._reviewed_plan = original
|
||||||
|
|
||||||
|
|
||||||
def _expanded_review_capacity(context_case):
|
def _expanded_review_capacity(context_case, *, component_pairs=1):
|
||||||
old = context_case.context.admission_review_policy
|
old = context_case.context.admission_review_policy
|
||||||
maximum_bytes = 16_384
|
maximum_bytes = 16_384 * component_pairs
|
||||||
policy = replace(
|
policy = replace(
|
||||||
old,
|
old,
|
||||||
maximum_evidence_bytes=maximum_bytes,
|
maximum_evidence_bytes=maximum_bytes,
|
||||||
@@ -183,7 +223,7 @@ def _fitted_inputs(bundle, program, program_lineage, training_ref, training_reso
|
|||||||
return probe_input, fitting_lineage, holdout, _merge(bundle[4], probe_resolver, holdout_resolver)
|
return probe_input, fitting_lineage, holdout, _merge(bundle[4], probe_resolver, holdout_resolver)
|
||||||
|
|
||||||
|
|
||||||
def _complete_replay(monkeypatch):
|
def _complete_replay(monkeypatch, *, component_pairs=1):
|
||||||
from openultrasast.core import evaluation_admission
|
from openultrasast.core import evaluation_admission
|
||||||
|
|
||||||
context_case, plan, readiness = authority_fixtures._reviewed_plan()
|
context_case, plan, readiness = authority_fixtures._reviewed_plan()
|
||||||
@@ -192,10 +232,13 @@ def _complete_replay(monkeypatch):
|
|||||||
training_ref, training_resolver = _population_manifest(training_repositories, "e2e-training-population")
|
training_ref, training_resolver = _population_manifest(training_repositories, "e2e-training-population")
|
||||||
program, program_lineage = _fitted_program(context_case, training_ref)
|
program, program_lineage = _fitted_program(context_case, training_ref)
|
||||||
context_case = _with_program(context_case, program, program_lineage)
|
context_case = _with_program(context_case, program, program_lineage)
|
||||||
context_case = _expanded_review_capacity(context_case)
|
context_case = _expanded_review_capacity(context_case, component_pairs=component_pairs)
|
||||||
scopes = tuple(sorted((ScopeKey("reference-family", "python"), ScopeKey("other-family", "javascript"))))
|
scopes = tuple(sorted((ScopeKey("reference-family", "python"), ScopeKey("other-family", "javascript"))))
|
||||||
reviewed_plan = _multi_family_plan(plan, scopes, program.configuration_digest)
|
reviewed_plan = _multi_family_plan(plan, scopes, program.configuration_digest, component_pairs=component_pairs)
|
||||||
bundle = _public_bundle(monkeypatch, _authority_case(reviewed_plan, context_case, readiness))
|
bundle = _public_bundle(
|
||||||
|
monkeypatch,
|
||||||
|
_authority_case(reviewed_plan, context_case, readiness, attempt_count=2 * component_pairs),
|
||||||
|
)
|
||||||
|
|
||||||
reviewed_case = bundle[5]
|
reviewed_case = bundle[5]
|
||||||
readiness_by_digest = {item.result_digest: item for item in reviewed_case[3]}
|
readiness_by_digest = {item.result_digest: item for item in reviewed_case[3]}
|
||||||
|
|||||||
Reference in New Issue
Block a user