diff --git a/.kiro/specs/detection-core/tasks.md b/.kiro/specs/detection-core/tasks.md index 6973f391..f05bb753 100644 --- a/.kiro/specs/detection-core/tasks.md +++ b/.kiro/specs/detection-core/tasks.md @@ -621,7 +621,7 @@ contract work and use synthetic/in-memory workflow boundaries only. - _Requirements: 18.1, 18.2, 18.4_ - _Boundary: Evaluation Scoped Metrics_ - _Depends: 15.4, 15.6_ -- [ ] 16.2 Project ordinary pushes by ecosystem and deduplicate whole coverage +- [x] 16.2 Project ordinary pushes by ecosystem and deduplicate whole coverage - Count each eligible ordinary push once for every family claimed by the arm in the push's reviewed ecosystem and never in another ecosystem. - Deduplicate one underlying push once in whole-population coverage even when it contributes to several verified scope denominators. - Reconcile projected ordinary counts and global unique-push counts back to the reviewed census and released identities. @@ -747,6 +747,7 @@ contract work and use synthetic/in-memory workflow boundaries only. - Task 15.5 derives non-authorizing per-case combination lineage only from canonical released bindings, requires identical scope/input case sets, and replays the registered complete table in exact component-arm order while retaining every contributing identity. - Task 15.6 binds proof application to the exact independently reviewed plan and release, derives combined retention only from complete released component lineage, and validates absent or inconclusive proof without permitting candidate creation, substitution, or transfer. - Task 16.1 revalidates exact released record scope and canonically rederives verdicts and coverage before producing non-authorizing arm-family-ecosystem partitions, preventing packet, claim, satisfaction, silence, funnel, pair, and precision evidence from crossing scope boundaries. +- Task 16.2 reconciles exact ordinary-push identity sets within each reviewed ecosystem, refuses cross-ecosystem reuse, and derives whole-population coverage from the globally deduplicated released push union. - 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. diff --git a/src/openultrasast/core/evaluation_ordinary_projection.py b/src/openultrasast/core/evaluation_ordinary_projection.py new file mode 100644 index 00000000..52dcf4da --- /dev/null +++ b/src/openultrasast/core/evaluation_ordinary_projection.py @@ -0,0 +1,339 @@ +"""Non-authorizing ordinary-push projection and whole-population identity for V3.""" + +from __future__ import annotations + +import re +from collections import defaultdict +from collections.abc import Sequence +from dataclasses import dataclass +from typing import ClassVar + +from openultrasast.core import canonical +from openultrasast.core.admission_case import AdmissionCaseRole +from openultrasast.core.admission_context import AdmissionValidationContext +from openultrasast.core.custody import PopulationCustodyPort, PopulationUseReceipt +from openultrasast.core.evaluation_authority import EvaluationAdmissionAuthorityV3, EvaluationAdmissionManifestV3 +from openultrasast.core.evaluation_measurement import ArmScopeKey +from openultrasast.core.evaluation_plan import PopulationCensusV3 +from openultrasast.core.evaluation_release import AdmissionCaseReleaseV3, ArmAdmissionCasesV3 +from openultrasast.core.evaluation_scoped_metrics import ScopedQualityPartitionV3, partition_scoped_quality_evidence_v3 +from openultrasast.core.evaluation_spend import EvaluationPreparationV3, EvaluationSpendBindingV3 +from openultrasast.core.evaluation_version import ( + EVALUATION_ADMISSION_V3_SCHEMA, + EvaluationV3Contract, + NonAuthorizingV3, + require_exact_v3_contract, +) + +_DIGEST = re.compile(r"[0-9a-f]{64}") +_VALUE_SCHEMA = "openultrasast.detection-core.evaluation-ordinary-projection.v3" + + +class EvaluationOrdinaryProjectionError(ValueError): + """Released ordinary pushes cannot be reconciled to reviewed scope and census.""" + + +def _digest(value: object, field: str) -> str: + if type(value) is not str or _DIGEST.fullmatch(value) is None: + raise EvaluationOrdinaryProjectionError(f"{field} must be a full lowercase SHA-256 digest") + return value + + +def _count(value: object, field: str) -> int: + if type(value) is not int or value < 0: + raise EvaluationOrdinaryProjectionError(f"{field} must be a non-negative exact integer") + return value + + +def _value(kind: str, payload: canonical.JsonValue) -> canonical.JsonValue: + return {"schema_version": _VALUE_SCHEMA, "kind": kind, "payload": payload} + + +def _bind_digest(value: object, field: str, expected: str) -> None: + actual = getattr(value, field) + if actual == "": + object.__setattr__(value, field, expected) + return + _digest(actual, field) + if actual != expected: + raise EvaluationOrdinaryProjectionError(f"{field} does not match canonical content") + + +@dataclass(frozen=True, order=True) +class OrdinaryPushCaseV3(EvaluationV3Contract, NonAuthorizingV3): + """One released ordinary case contributing to one exact scope.""" + + __evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA + key: ArmScopeKey + case_id_digest: str + binding_digest: str + underlying_push_digest: str + identity_digest: str + + def __post_init__(self) -> None: + require_exact_v3_contract(self, OrdinaryPushCaseV3, field="ordinary push case") + if type(self.key) is not ArmScopeKey: + raise EvaluationOrdinaryProjectionError("ordinary push case key must use exact ArmScopeKey") + self.key.__post_init__() + payload: canonical.JsonValue = { + "key": {"arm_id": self.key.arm_id, "family_id": self.key.scope.family_id, "ecosystem": self.key.scope.ecosystem}, + "case_id_digest": _digest(self.case_id_digest, "ordinary case identity"), + "binding_digest": _digest(self.binding_digest, "ordinary binding identity"), + "underlying_push_digest": _digest(self.underlying_push_digest, "ordinary underlying push identity"), + } + _bind_digest(self, "identity_digest", canonical.content_digest(_value("ordinary_push_case", payload))) + + +@dataclass(frozen=True) +class ScopedOrdinaryProjectionV3(EvaluationV3Contract, NonAuthorizingV3): + """Canonical ordinary cases projected into one exact arm scope.""" + + __evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA + key: ArmScopeKey + cases: tuple[OrdinaryPushCaseV3, ...] + ordinary_push_count: int + projection_digest: str + + def __post_init__(self) -> None: + require_exact_v3_contract(self, ScopedOrdinaryProjectionV3, field="scoped ordinary projection") + if type(self.key) is not ArmScopeKey or type(self.cases) is not tuple: + raise EvaluationOrdinaryProjectionError("scoped ordinary projection requires exact key and case tuple") + self.key.__post_init__() + if any(type(case) is not OrdinaryPushCaseV3 for case in self.cases): + raise EvaluationOrdinaryProjectionError("scoped ordinary cases must use exact OrdinaryPushCaseV3 values") + for case in self.cases: + case.__post_init__() + expected = tuple(sorted(self.cases, key=lambda case: (case.underlying_push_digest, case.case_id_digest))) + if self.cases != expected or any(case.key != self.key for case in self.cases): + raise EvaluationOrdinaryProjectionError("scoped ordinary cases must use canonical same-key order") + pushes = tuple(case.underlying_push_digest for case in self.cases) + if len(set(pushes)) != len(pushes): + raise EvaluationOrdinaryProjectionError("one ordinary push may contribute only once to an exact scope") + if _count(self.ordinary_push_count, "scoped ordinary push count") != len(pushes): + raise EvaluationOrdinaryProjectionError("scoped ordinary push count differs from released identities") + payload = {"key": _key_value(self.key), "case_identity_digests": tuple(case.identity_digest for case in self.cases)} + _bind_digest(self, "projection_digest", canonical.content_digest(_value("scoped_ordinary_projection", payload))) + + +@dataclass(frozen=True) +class WholePopulationProjectionV3(EvaluationV3Contract, NonAuthorizingV3): + """One globally deduplicated set of released underlying pushes.""" + + __evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA + underlying_push_digests: tuple[str, ...] + underlying_push_count: int + projection_digest: str + + def __post_init__(self) -> None: + require_exact_v3_contract(self, WholePopulationProjectionV3, field="whole population projection") + if type(self.underlying_push_digests) is not tuple: + raise EvaluationOrdinaryProjectionError("whole underlying pushes must use an exact tuple") + for digest in self.underlying_push_digests: + _digest(digest, "whole underlying push identity") + if self.underlying_push_digests != tuple(sorted(set(self.underlying_push_digests))): + raise EvaluationOrdinaryProjectionError("whole underlying pushes must be unique and canonical") + if _count(self.underlying_push_count, "whole underlying push count") != len(self.underlying_push_digests): + raise EvaluationOrdinaryProjectionError("whole underlying push count differs from released identities") + payload = {"underlying_push_digests": self.underlying_push_digests} + _bind_digest(self, "projection_digest", canonical.content_digest(_value("whole_population_projection", payload))) + + +@dataclass(frozen=True) +class EvaluationOrdinaryProjectionV3(EvaluationV3Contract, NonAuthorizingV3): + """Reviewed-census-bound scoped ordinary and whole-population projection.""" + + __evaluation_v3_contract_schema__: ClassVar[str] = EVALUATION_ADMISSION_V3_SCHEMA + census_digest: str + scoped_projections: tuple[ScopedOrdinaryProjectionV3, ...] + whole_population: WholePopulationProjectionV3 + projection_digest: str + + def __post_init__(self) -> None: + require_exact_v3_contract(self, EvaluationOrdinaryProjectionV3, field="evaluation ordinary projection") + _digest(self.census_digest, "reviewed census identity") + if type(self.scoped_projections) is not tuple or not self.scoped_projections: + raise EvaluationOrdinaryProjectionError("scoped projections must be a nonempty exact tuple") + if any(type(row) is not ScopedOrdinaryProjectionV3 for row in self.scoped_projections): + raise EvaluationOrdinaryProjectionError("scoped projections must use exact values") + for row in self.scoped_projections: + row.__post_init__() + keys = tuple(row.key for row in self.scoped_projections) + if keys != tuple(sorted(set(keys))): + raise EvaluationOrdinaryProjectionError("scoped projections must have unique canonical keys") + if type(self.whole_population) is not WholePopulationProjectionV3: + raise EvaluationOrdinaryProjectionError("whole population projection must use the exact V3 value") + self.whole_population.__post_init__() + _validate_ecosystem_projection(self.scoped_projections) + ordinary_pushes = {case.underlying_push_digest for row in self.scoped_projections for case in row.cases} + if not ordinary_pushes <= set(self.whole_population.underlying_push_digests): + raise EvaluationOrdinaryProjectionError("ordinary projection escapes whole-population coverage") + payload: canonical.JsonValue = { + "census_digest": self.census_digest, + "scoped_projection_digests": tuple(row.projection_digest for row in self.scoped_projections), + "whole_population_projection_digest": self.whole_population.projection_digest, + } + _bind_digest(self, "projection_digest", canonical.content_digest(_value("evaluation_ordinary_projection", payload))) + + +def _key_value(key: ArmScopeKey) -> canonical.JsonValue: + return {"arm_id": key.arm_id, "family_id": key.scope.family_id, "ecosystem": key.scope.ecosystem} + + +def _exact_inputs( + census: PopulationCensusV3, + planned_keys: tuple[ArmScopeKey, ...], + ordinary_cases: tuple[OrdinaryPushCaseV3, ...], + whole_pushes: tuple[str, ...], +) -> None: + if type(census) is not PopulationCensusV3: + raise EvaluationOrdinaryProjectionError("census must use exact PopulationCensusV3") + census.__post_init__() + if type(planned_keys) is not tuple or any(type(key) is not ArmScopeKey for key in planned_keys): + raise EvaluationOrdinaryProjectionError("planned keys must use an exact tuple of ArmScopeKey") + if planned_keys != tuple(sorted(set(planned_keys))) or not planned_keys: + raise EvaluationOrdinaryProjectionError("planned keys must be nonempty, unique, and canonical") + if type(ordinary_cases) is not tuple or any(type(case) is not OrdinaryPushCaseV3 for case in ordinary_cases): + raise EvaluationOrdinaryProjectionError("ordinary cases must use an exact tuple of OrdinaryPushCaseV3") + for case in ordinary_cases: + case.__post_init__() + expected = tuple(sorted(ordinary_cases, key=lambda case: (case.key, case.underlying_push_digest, case.case_id_digest))) + if ordinary_cases != expected: + raise EvaluationOrdinaryProjectionError("ordinary cases must use canonical key and push order") + if type(whole_pushes) is not tuple: + raise EvaluationOrdinaryProjectionError("whole underlying pushes must use an exact tuple") + + +def _census_counts(census: PopulationCensusV3, keys: tuple[ArmScopeKey, ...]) -> dict[str, int]: + expected_ecosystems = tuple(sorted({key.scope.ecosystem for key in keys})) + rows = {row.ecosystem: row.ordinary_push_count for row in census.ordinary_rows} + if tuple(sorted(rows)) != expected_ecosystems: + raise EvaluationOrdinaryProjectionError("ordinary census ecosystems differ from planned exact scopes") + return rows + + +def _scoped_rows( + keys: tuple[ArmScopeKey, ...], + cases: tuple[OrdinaryPushCaseV3, ...], + counts: dict[str, int], +) -> tuple[ScopedOrdinaryProjectionV3, ...]: + cases_by_key: dict[ArmScopeKey, list[OrdinaryPushCaseV3]] = defaultdict(list) + for case in cases: + if case.key not in keys: + raise EvaluationOrdinaryProjectionError("ordinary case belongs to an unplanned exact scope") + cases_by_key[case.key].append(case) + rows = [] + for key in keys: + selected = tuple(sorted(cases_by_key[key], key=lambda case: (case.underlying_push_digest, case.case_id_digest))) + row = ScopedOrdinaryProjectionV3(key, selected, len(selected), "") + if row.ordinary_push_count != counts[key.scope.ecosystem]: + raise EvaluationOrdinaryProjectionError("scoped ordinary identities differ from the reviewed ordinary census") + rows.append(row) + return tuple(rows) + + +def _validate_ecosystem_projection(rows: tuple[ScopedOrdinaryProjectionV3, ...]) -> None: + sets_by_ecosystem: dict[str, list[set[str]]] = defaultdict(list) + ecosystem_by_push: dict[str, str] = {} + for row in rows: + ecosystem = row.key.scope.ecosystem + pushes = {case.underlying_push_digest for case in row.cases} + sets_by_ecosystem[ecosystem].append(pushes) + for push in pushes: + previous = ecosystem_by_push.setdefault(push, ecosystem) + if previous != ecosystem: + raise EvaluationOrdinaryProjectionError("an ordinary push cannot project into another ecosystem") + for push_sets in sets_by_ecosystem.values(): + if any(pushes != push_sets[0] for pushes in push_sets[1:]): + raise EvaluationOrdinaryProjectionError("every same-ecosystem scope must project the identical eligible ordinary push set") + + +def _derive_ordinary_push_projection_v3( + census: PopulationCensusV3, + planned_keys: tuple[ArmScopeKey, ...], + ordinary_cases: tuple[OrdinaryPushCaseV3, ...], + whole_underlying_push_digests: tuple[str, ...], +) -> EvaluationOrdinaryProjectionV3: + """Derive a non-authorizing projection from already validated release identities.""" + _exact_inputs(census, planned_keys, ordinary_cases, whole_underlying_push_digests) + counts = _census_counts(census, planned_keys) + rows = _scoped_rows(planned_keys, ordinary_cases, counts) + _validate_ecosystem_projection(rows) + whole = WholePopulationProjectionV3( + whole_underlying_push_digests, + len(whole_underlying_push_digests), + "", + ) + ordinary_pushes = {case.underlying_push_digest for case in ordinary_cases} + if not ordinary_pushes <= set(whole.underlying_push_digests): + raise EvaluationOrdinaryProjectionError("ordinary projection contains an identity outside whole-population coverage") + if whole.underlying_push_count != census.whole_underlying_push_count: + raise EvaluationOrdinaryProjectionError("released identities differ from the reviewed whole-population census") + return EvaluationOrdinaryProjectionV3(census.census_digest, rows, whole, "") + + +def _released_projection_inputs( + release: AdmissionCaseReleaseV3, + cases_by_arm: tuple[ArmAdmissionCasesV3, ...], + partitions: tuple[ScopedQualityPartitionV3, ...], +) -> tuple[tuple[ArmScopeKey, ...], tuple[OrdinaryPushCaseV3, ...], tuple[str, ...]]: + bindings = {(binding.key, binding.case_id_digest): binding for binding in release.bindings} + cases = tuple(case for group in cases_by_arm for case in group.cases) + roles_by_push: dict[str, set[AdmissionCaseRole]] = defaultdict(set) + ecosystems_by_push: dict[str, set[str]] = defaultdict(set) + for case in cases: + roles_by_push[case.underlying_push_digest].add(case.role) + ecosystems_by_push[case.underlying_push_digest].add(case.key.scope.ecosystem) + if any(len(roles) != 1 for roles in roles_by_push.values()): + raise EvaluationOrdinaryProjectionError("one underlying push cannot carry different released roles") + if any(len(ecosystems) != 1 for ecosystems in ecosystems_by_push.values()): + raise EvaluationOrdinaryProjectionError("one underlying push cannot cross reviewed ecosystems") + planned_keys = tuple(row.key for row in partitions) + ordinary = [] + for case in cases: + if case.role is AdmissionCaseRole.ORDINARY: + binding = bindings.get((case.key, case.case_id_digest)) + if binding is None: + raise EvaluationOrdinaryProjectionError("ordinary released case lacks its exact binding identity") + ordinary.append(OrdinaryPushCaseV3(case.key, case.case_id_digest, binding.binding_digest, case.underlying_push_digest, "")) + ordered = tuple(sorted(ordinary, key=lambda case: (case.key, case.underlying_push_digest, case.case_id_digest))) + whole = tuple(sorted(roles_by_push)) + return planned_keys, ordered, whole + + +def project_ordinary_pushes_v3( + manifest: EvaluationAdmissionManifestV3, + authority: EvaluationAdmissionAuthorityV3, + preparation: EvaluationPreparationV3, + receipt: PopulationUseReceipt, + spend: EvaluationSpendBindingV3, + release: AdmissionCaseReleaseV3, + cases_by_arm: Sequence[ArmAdmissionCasesV3], + context: AdmissionValidationContext, + custody: PopulationCustodyPort, + resolver: canonical.ContentResolver, +) -> EvaluationOrdinaryProjectionV3: + """Validate the complete release graph before projecting ordinary and whole identities.""" + try: + if type(cases_by_arm) is not tuple: + raise EvaluationOrdinaryProjectionError("cases_by_arm must use an exact tuple") + partitions = partition_scoped_quality_evidence_v3( + manifest, authority, preparation, receipt, spend, release, cases_by_arm, context, custody, resolver + ) + keys, ordinary, whole = _released_projection_inputs(release, cases_by_arm, partitions) + return _derive_ordinary_push_projection_v3(manifest.plan_manifest.census, keys, ordinary, whole) + except EvaluationOrdinaryProjectionError: + raise + except (canonical.ArtifactResolutionError, canonical.ArtifactValidationError): + raise + except (AttributeError, KeyError, LookupError, TypeError, ValueError) as exc: + raise EvaluationOrdinaryProjectionError(f"ordinary projection refused by reviewed release: {exc}") from exc + + +__all__ = [ + "EvaluationOrdinaryProjectionError", + "EvaluationOrdinaryProjectionV3", + "OrdinaryPushCaseV3", + "ScopedOrdinaryProjectionV3", + "WholePopulationProjectionV3", + "project_ordinary_pushes_v3", +] diff --git a/tests/test_core_evaluation_case_validation.py b/tests/test_core_evaluation_case_validation.py index 3461b134..70b1db46 100644 --- a/tests/test_core_evaluation_case_validation.py +++ b/tests/test_core_evaluation_case_validation.py @@ -150,7 +150,7 @@ def _contract_catalog_context(context_case): return replace(context_case, context=context) -def _rekey_configuration(configuration, scope: ScopeKey): +def _rekey_configuration(configuration, scope: ScopeKey, *, minimum_ordinary_pushes=None, relaxed_precision=False): key = ArmScopeKey(configuration.arm_id, scope) policies = tuple( replace( @@ -162,7 +162,24 @@ def _rekey_configuration(configuration, scope: ScopeKey): for policy in configuration.denominator_policies ) thresholds = tuple(replace(row, key=key, threshold_digest="") for row in configuration.thresholds) - sufficiency = tuple(replace(row, key=key, rule_digest="") for row in configuration.sufficiency_rules) + sufficiency = tuple( + replace( + row, + key=key, + minimum_ordinary_pushes=(row.minimum_ordinary_pushes if minimum_ordinary_pushes is None else minimum_ordinary_pushes), + precision_rules=tuple( + replace( + precision, + maximum_wilson_width=100.0 if relaxed_precision else precision.maximum_wilson_width, + minimum_denominator=1 if relaxed_precision else precision.minimum_denominator, + rule_digest="", + ) + for precision in row.precision_rules + ), + rule_digest="", + ) + for row in configuration.sufficiency_rules + ) return replace( configuration, exact_scopes=(scope,), @@ -173,16 +190,17 @@ def _rekey_configuration(configuration, scope: ScopeKey): ) -def _reviewed_scoped_census(plan, scopes): +def _reviewed_scoped_census(plan, scopes, *, ordinary_count=None, whole_count=None): template_row = plan.census.scope_rows[0] scope_rows = tuple(replace(template_row, scope=scope) for scope in sorted(set(scopes.values()))) ecosystems = tuple(sorted({scope.ecosystem for scope in scopes.values()})) - ordinary_count = plan.census.whole_underlying_push_count // len(ecosystems) - ordinary_rows = tuple(EcosystemOrdinaryCensusV3(ecosystem, ordinary_count) for ecosystem in ecosystems) + per_ecosystem = plan.census.whole_underlying_push_count // len(ecosystems) if ordinary_count is None else ordinary_count + ordinary_rows = tuple(EcosystemOrdinaryCensusV3(ecosystem, per_ecosystem) for ecosystem in ecosystems) census_draft = replace( plan.census, scope_rows=scope_rows, ordinary_rows=ordinary_rows, + whole_underlying_push_count=(plan.census.whole_underlying_push_count if whole_count is None else whole_count), payload_digest="0" * 64, census_digest="0" * 64, ) @@ -200,8 +218,24 @@ def _reviewed_scoped_census(plan, scopes): return replace(census_reviewed, census_digest=derive_evaluation_census_digest(census_reviewed)) -def _reviewed_scoped_plan(plan, scopes): - configurations = tuple(_rekey_configuration(row, scopes[row.arm_id]) for row in plan.declaration.arm_configurations) +def _reviewed_scoped_plan( + plan, + scopes, + *, + ordinary_count=None, + whole_count=None, + minimum_ordinary_pushes=None, + relaxed_precision=False, +): + configurations = tuple( + _rekey_configuration( + row, + scopes[row.arm_id], + minimum_ordinary_pushes=minimum_ordinary_pushes, + relaxed_precision=relaxed_precision, + ) + for row in plan.declaration.arm_configurations + ) inputs = tuple(sorted({slot.input_identity_digest for slot in plan.declaration.expected_observation_slots})) declaration = create_evaluation_plan_declaration( population_digest=plan.declaration.population_digest, @@ -214,7 +248,7 @@ def _reviewed_scoped_plan(plan, scopes): plan, declaration=declaration, baselines=derive_evaluation_baselines(declaration), - census=_reviewed_scoped_census(plan, scopes), + census=_reviewed_scoped_census(plan, scopes, ordinary_count=ordinary_count, whole_count=whole_count), payload_digest="0" * 64, manifest_digest="0" * 64, ) @@ -232,10 +266,24 @@ def _reviewed_scoped_plan(plan, scopes): return replace(plan_reviewed, manifest_digest=derive_evaluation_plan_manifest_digest(plan_reviewed)) -def _scoped_authority_case(scopes): +def _scoped_authority_case( + scopes, + *, + ordinary_count=None, + whole_count=None, + minimum_ordinary_pushes=None, + relaxed_precision=False, +): context_case, plan, readiness = authority_fixtures._reviewed_plan() context_case = _contract_catalog_context(context_case) - multi_plan = _reviewed_scoped_plan(plan, scopes) + multi_plan = _reviewed_scoped_plan( + plan, + scopes, + ordinary_count=ordinary_count, + whole_count=whole_count, + minimum_ordinary_pushes=minimum_ordinary_pushes, + relaxed_precision=relaxed_precision, + ) original = authority_fixtures._reviewed_plan authority_fixtures._reviewed_plan = lambda: (context_case, multi_plan, readiness) try: @@ -259,6 +307,20 @@ def _multi_scope_authority_case(): ) +def _ordinary_projection_authority_case(): + return _scoped_authority_case( + { + "arm-a": ScopeKey("reference-family", "python"), + "arm-b": ScopeKey("reference-family", "javascript"), + "arm-combined": ScopeKey("reference-family", "python"), + }, + ordinary_count=1, + whole_count=6, + minimum_ordinary_pushes=1, + relaxed_precision=True, + ) + + def _contract_for_scope(context_case, scope: ScopeKey, *, family_version: str | None = None, family_id: str | None = None): selected_family = family_id or scope.family_id selected_version = family_version or ("2" if scope.ecosystem == "javascript" else "1") @@ -583,6 +645,7 @@ def _bundle( projection_mutation: str | None = None, evidence_mutation: str | None = None, summary_mutation: str | None = None, + shared_underlying_by_ecosystem: bool = False, ): setup = _setup() authority_case = authority_case or _reference_authority_case() @@ -591,6 +654,14 @@ def _bundle( draft_cases, extra_artifacts = _draft_cases( setup, authority_case, configurations, projection_mutation, evidence_mutation, summary_mutation ) + if shared_underlying_by_ecosystem: + draft_cases = { + arm_id: tuple( + replace(case, underlying_push_digest=_digest(f"underlying-push-{case.key.scope.ecosystem}-{index}")) + for index, case in enumerate(cases) + ) + for arm_id, cases in draft_cases.items() + } artifacts = {**authority_case[5].artifacts, **setup.resolver.artifacts, **extra_artifacts} sealed, observations, observation_by_arm = _sealed_observations(manifest, configurations, draft_cases, artifacts) diff --git a/tests/test_core_evaluation_ordinary_projection.py b/tests/test_core_evaluation_ordinary_projection.py new file mode 100644 index 00000000..3d0cdd06 --- /dev/null +++ b/tests/test_core_evaluation_ordinary_projection.py @@ -0,0 +1,179 @@ +"""Ecosystem-scoped ordinary projection and whole-push deduplication for V3.""" + +from __future__ import annotations + +from dataclasses import replace + +import pytest +from test_core_evaluation_case_validation import ( + _bundle, + _digest, + _multi_scope_authority_case, + _ordinary_projection_authority_case, +) + +from openultrasast.core.evaluation_measurement import ArmScopeKey, ScopeKey +from openultrasast.core.evaluation_plan import EcosystemOrdinaryCensusV3 + + +def _project(bundle): + from openultrasast.core.evaluation_ordinary_projection import project_ordinary_pushes_v3 + + reviewed_case = bundle[5] + return project_ordinary_pushes_v3( + bundle[3], + bundle[6], + bundle[7], + bundle[8], + bundle[9], + bundle[1], + bundle[2], + reviewed_case[0].context, + reviewed_case[0].port, + bundle[4], + ) + + +def _valid_bundle(): + return _bundle( + authority_case=_ordinary_projection_authority_case(), + shared_underlying_by_ecosystem=True, + ) + + +def _identity(key: ArmScopeKey, label: str, push: str): + from openultrasast.core.evaluation_ordinary_projection import OrdinaryPushCaseV3 + + return OrdinaryPushCaseV3(key, _digest(f"case-{label}"), _digest(f"binding-{label}"), _digest(push), "") + + +def _derive(census, keys, identities, whole): + from openultrasast.core.evaluation_ordinary_projection import _derive_ordinary_push_projection_v3 + + return _derive_ordinary_push_projection_v3(census, keys, identities, whole) + + +def test_reviewed_projection_reconciles_each_scope_and_deduplicates_whole_pushes() -> None: + bundle = _valid_bundle() + projection = _project(bundle) + + assert tuple(row.key for row in projection.scoped_projections) == ( + ArmScopeKey("arm-a", ScopeKey("reference-family", "python")), + ArmScopeKey("arm-b", ScopeKey("reference-family", "javascript")), + ArmScopeKey("arm-combined", ScopeKey("reference-family", "python")), + ) + assert all(row.ordinary_push_count == 1 for row in projection.scoped_projections) + python_rows = tuple(row for row in projection.scoped_projections if row.key.scope.ecosystem == "python") + javascript_row = next(row for row in projection.scoped_projections if row.key.scope.ecosystem == "javascript") + assert {row.cases[0].underlying_push_digest for row in python_rows} == {_digest("underlying-push-python-2")} + assert javascript_row.cases[0].underlying_push_digest == _digest("underlying-push-javascript-2") + assert projection.whole_population.underlying_push_count == 6 + assert len(projection.whole_population.underlying_push_digests) == 6 + assert projection.census_digest == bundle[3].plan_manifest.census.census_digest + + +def test_one_arm_projects_the_same_ordinary_push_once_into_each_same_ecosystem_family() -> None: + bundle = _valid_bundle() + census = replace( + bundle[3].plan_manifest.census, + scope_rows=bundle[3].plan_manifest.census.scope_rows[:1], + ordinary_rows=(EcosystemOrdinaryCensusV3("python", 1),), + whole_underlying_push_count=1, + ) + first = ArmScopeKey("arm-a", ScopeKey("family-a", "python")) + second = ArmScopeKey("arm-a", ScopeKey("family-b", "python")) + push = "same-ecosystem-ordinary" + + projection = _derive( + census, + (first, second), + (_identity(first, "a", push), _identity(second, "b", push)), + (_digest(push),), + ) + + assert tuple(row.ordinary_push_count for row in projection.scoped_projections) == (1, 1) + assert projection.whole_population.underlying_push_count == 1 + + +def test_same_ecosystem_scopes_must_project_the_identical_eligible_push_set() -> None: + bundle = _valid_bundle() + census = replace( + bundle[3].plan_manifest.census, + scope_rows=bundle[3].plan_manifest.census.scope_rows[:1], + ordinary_rows=(EcosystemOrdinaryCensusV3("python", 1),), + whole_underlying_push_count=2, + ) + first = ArmScopeKey("arm-a", ScopeKey("family-a", "python")) + second = ArmScopeKey("arm-b", ScopeKey("family-b", "python")) + + with pytest.raises(ValueError, match="eligible ordinary push set"): + _derive( + census, + (first, second), + (_identity(first, "a", "push-a"), _identity(second, "b", "push-b")), + (_digest("push-a"), _digest("push-b")), + ) + + +def test_underlying_ordinary_push_cannot_project_into_another_ecosystem() -> None: + bundle = _valid_bundle() + census = replace( + bundle[3].plan_manifest.census, + ordinary_rows=(EcosystemOrdinaryCensusV3("javascript", 1), EcosystemOrdinaryCensusV3("python", 1)), + whole_underlying_push_count=2, + ) + javascript = ArmScopeKey("arm-a", ScopeKey("family-a", "javascript")) + python = ArmScopeKey("arm-b", ScopeKey("family-b", "python")) + + with pytest.raises(ValueError, match="another ecosystem"): + _derive( + census, + (javascript, python), + (_identity(javascript, "js", "shared-push"), _identity(python, "py", "shared-push")), + tuple(sorted((_digest("shared-push"), _digest("other-push")))), + ) + + +def test_scoped_and_whole_counts_must_match_the_reviewed_census() -> None: + bundle = _valid_bundle() + key = ArmScopeKey("arm-a", ScopeKey("family-a", "python")) + census = replace( + bundle[3].plan_manifest.census, + scope_rows=bundle[3].plan_manifest.census.scope_rows[:1], + ordinary_rows=(EcosystemOrdinaryCensusV3("python", 2),), + whole_underlying_push_count=2, + ) + identity = _identity(key, "a", "push-a") + + with pytest.raises(ValueError, match="ordinary census"): + _derive(census, (key,), (identity,), (_digest("push-a"), _digest("push-b"))) + with pytest.raises(ValueError, match="whole-population census"): + _derive(replace(census, ordinary_rows=(EcosystemOrdinaryCensusV3("python", 1),)), (key,), (identity,), (_digest("push-a"),)) + + +def test_full_release_with_unreconciled_census_is_refused() -> None: + bundle = _bundle(authority_case=_multi_scope_authority_case()) + + with pytest.raises(ValueError, match="census"): + _project(bundle) + + +def test_projection_contracts_are_non_authorizing_and_require_exact_collections() -> None: + from openultrasast.core.evaluation_ordinary_projection import EvaluationOrdinaryProjectionV3 + + projection = _project(_valid_bundle()) + assert not {"metrics", "gate", "decision", "authorization"} & EvaluationOrdinaryProjectionV3.__dataclass_fields__.keys() + with pytest.raises(ValueError, match="exact tuple"): + _derive( + _valid_bundle()[3].plan_manifest.census, + list(row.key for row in projection.scoped_projections), # type: ignore[arg-type] + (), + (), + ) + + +def test_v2_whole_population_metric_contract_is_unchanged() -> None: + from openultrasast.core.admission_metrics import AdmissionMetricEvidence + + assert "whole_population_case_count" in AdmissionMetricEvidence.__dataclass_fields__ + assert "whole_population_funnel" in AdmissionMetricEvidence.__dataclass_fields__