feat(valid-detection-benchmark): 10.7 freeze and causally bind replacement baseline

This commit is contained in:
Marius Ciepluch
2026-11-22 22:27:09 +01:00
parent 93ebea7b93
commit c587f25bb3
4 changed files with 1583 additions and 1 deletions
@@ -353,7 +353,7 @@
- _Requirements: 3.1, 3.2, 3.4, 3.5, 7.1, 7.4, 7.5_
- _Boundary: Population Freezer, Replacement Population Sourcing_
- _Depends: 10.5_
- [ ] 10.7 Freeze and causally bind the exact replacement baseline
- [x] 10.7 Freeze and causally bind the exact replacement baseline
- Freeze the reviewed population under new population/freeze identities, build the independently reviewed label-blind manifest, and persist public/private/sealed partitions.
- Append the reviewed replacement-binding lifecycle event naming the exact withdrawal, population, and freeze identities.
- Re-run permanent reservation, lifecycle eligibility, and store capability checks without registering real arms, running core preflight, or spending labels.
@@ -0,0 +1,649 @@
"""Integration freeze and causal binding of the exact replacement baseline.
This module closes task group 10: it composes the committed population,
review, material, lifecycle, reservation, and store authorities into the one
binding that turns the closed replacement population into an active baseline.
It registers no evaluation arms, runs no core preflight, and never spends
labels; every check it performs is read-only against exact reviewed evidence.
"""
from __future__ import annotations
import re
from collections.abc import Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass
from enum import StrEnum
from pathlib import Path
from benchmarks.valid.cohort_ingestion import CohortBatchOutcomeV1
from benchmarks.valid.historical_authorization import HistoricalWithdrawalV1, withdrawal_bytes
from benchmarks.valid.lifecycle import (
BaselineLifecycleAuthority,
PopulationLifecycleProjectionV1,
decode_lifecycle_event,
reviewed_replacement_event,
withdrawn_event,
)
from benchmarks.valid.ordinary_change_contract import (
OrdinarySelectionV1,
ReviewedPositiveInput,
_fix_exclusion_value,
_selection_value,
ordinary_selection_bytes,
)
from benchmarks.valid.ordinary_draw_contract import OrdinaryPopulationDrawV1, ordinary_population_draw_bytes
from benchmarks.valid.population_freeze import PopulationFreezeV3, freeze_population, population_freeze_bytes
from benchmarks.valid.population_freeze_contract import PopulationClass, ScopeMinimumV1
from benchmarks.valid.population_label_blind import (
IndependenceAttestation,
LabelBlindPopulationDraftV3,
LabelBlindPopulationManifestV3,
ReviewIndependencePolicy,
build_label_blind_population_draft,
review_label_blind_population_manifest,
validate_label_blind_population_manifest,
)
from benchmarks.valid.population_material_contract import PopulationMaterialInputV1
from benchmarks.valid.population_materials import PopulationMaterialPartitionV1, build_population_material_partition
from benchmarks.valid.positive_set_closure import (
PositiveSetClosureStateError,
PositiveSetClosureStatus,
PositiveSetClosureV1,
project_positive_set_closure,
)
from benchmarks.valid.replacement_artifact_contract import canonical_json_bytes
from benchmarks.valid.reservation import ReservationAuthority, ReservationCensusV1, ReservationError, census_bytes
from benchmarks.valid.reservation_guard import (
PRODUCTION_GUARD_SCAN_ROOTS,
ExactReservationSourceV1,
ReplacementReservationAcceptanceV1,
scan_permanent_reservations,
validate_replacement_population,
)
from benchmarks.valid.store_configuration import StoreCapabilityEvidence, StorePurpose, assess_store_startup, require_store_startup
from openultrasast.core import canonical
from openultrasast.core.canonical import JsonValue, content_digest
from openultrasast.core.custody import PopulationCustodyLog, PopulationStatus
REPLACEMENT_BASELINE_BINDING_SCHEMA = "openultrasast.valid-detection-benchmark.replacement-baseline-binding.v1"
_DIGEST = re.compile(r"[0-9a-f]{64}")
class ReplacementBindingReason(StrEnum):
"""Closed binding refusal reasons; no free-form failure text is serializable."""
INVALID_REQUEST = "invalid_request"
POSITIVE_SET_NOT_CLOSED = "positive_set_not_closed"
ORDINARY_DRAW_REFUSED = "ordinary_draw_refused"
FREEZE_REFUSED = "freeze_refused"
POPULATION_NOT_ADMISSION_CLASS = "population_not_admission_class"
MATERIAL_PARTITION_REFUSED = "material_partition_refused"
MANIFEST_UNREVIEWED = "manifest_unreviewed"
MANIFEST_UNRESOLVED = "manifest_unresolved"
LIFECYCLE_REFUSED = "lifecycle_refused"
RESERVATION_REFUSED = "reservation_refused"
STORE_CAPABILITY_MISSING = "store_capability_missing"
CUSTODY_NOT_AVAILABLE = "custody_not_available"
class ReplacementBindingError(RuntimeError):
"""Refuse one binding step with a closed reason and no caller content."""
def __init__(self, reason: ReplacementBindingReason) -> None:
self.reason = reason
super().__init__(f"replacement_binding_{reason.value}")
class ReplacementBindingStateReason(StrEnum):
STATE_UNREADABLE = "state_unreadable"
STATE_MISMATCH = "state_mismatch"
class ReplacementBindingStateError(ValueError):
"""Closed binding-state refusal carrying one structural reason."""
def __init__(self, reason: ReplacementBindingStateReason) -> None:
self.reason = reason
super().__init__(f"replacement binding state {reason.value}")
def _mismatch() -> ReplacementBindingStateError:
return ReplacementBindingStateError(ReplacementBindingStateReason.STATE_MISMATCH)
def _refused(reason: ReplacementBindingReason) -> ReplacementBindingError:
return ReplacementBindingError(reason)
@dataclass(frozen=True)
class ReplacementBaselineBindingV1:
"""Identities of every authority the exact replacement baseline binds."""
historical_withdrawal_digest: str
population_digest: str
freeze_digest: str
closure_digest: str
ordinary_draw_digest: str
ordinary_selection_digest: str
material_manifest_digest: str
private_object_digest: str
sealed_label_digest: str
manifest_digest: str
reservation_census_digest: str
guard_report_digest: str
acceptance_digest: str
lifecycle_projection_digest: str
binding_digest: str
_BINDING_FIELDS = (
"historical_withdrawal_digest",
"population_digest",
"freeze_digest",
"closure_digest",
"ordinary_draw_digest",
"ordinary_selection_digest",
"material_manifest_digest",
"private_object_digest",
"sealed_label_digest",
"manifest_digest",
"reservation_census_digest",
"guard_report_digest",
"acceptance_digest",
"lifecycle_projection_digest",
)
def _binding_value(binding: ReplacementBaselineBindingV1, *, include_digest: bool) -> dict[str, JsonValue]:
value: dict[str, JsonValue] = {"schema_version": REPLACEMENT_BASELINE_BINDING_SCHEMA}
value.update({field: getattr(binding, field) for field in _BINDING_FIELDS})
if include_digest:
value["binding_digest"] = binding.binding_digest
return value
def _validate_binding(binding: ReplacementBaselineBindingV1) -> None:
if type(binding) is not ReplacementBaselineBindingV1:
raise _mismatch()
for field in (*_BINDING_FIELDS, "binding_digest"):
value = getattr(binding, field)
if not isinstance(value, str) or _DIGEST.fullmatch(value) is None:
raise _mismatch()
def replacement_baseline_binding_bytes(binding: ReplacementBaselineBindingV1) -> bytes:
"""Encode one digest-consistent binding record as canonical bytes."""
_validate_binding(binding)
if binding.binding_digest != content_digest(_binding_value(binding, include_digest=False)):
raise _mismatch()
return canonical_json_bytes(_binding_value(binding, include_digest=True))
@dataclass(frozen=True)
class _FreezeValidator:
"""Exact-identity freeze validator for the material partition boundary."""
expected: PopulationFreezeV3
def validate(self, freeze: PopulationFreezeV3) -> bytes:
if freeze != self.expected:
raise ValueError("freeze does not replay from exact authorities")
return population_freeze_bytes(freeze)
def _selection_provenance(draw: OrdinaryPopulationDrawV1) -> str:
return content_digest(
{
"history_sources": tuple(
sorted(
{
(push.canonical_repository, push.network_identity_digest, push.history_source_digest)
for push in draw.pushes
}
)
),
"accepted_fix_exclusions": tuple(_fix_exclusion_value(item) for item in draw.fix_exclusions),
"policy_digest": draw.policy_digest,
}
)
def ordinary_selection_from_draw(draw: OrdinaryPopulationDrawV1) -> OrdinarySelectionV1:
"""Bridge one validated ordinary population draw into the freeze-bound selection."""
if type(draw) is not OrdinaryPopulationDrawV1:
raise _refused(ReplacementBindingReason.ORDINARY_DRAW_REFUSED)
try:
content = ordinary_population_draw_bytes(draw)
draft = OrdinarySelectionV1(
draw.required_per_positive,
draw.policy_digest,
draw.positive_change_digests,
draw.fix_exclusions,
draw.pushes,
draw.assignments,
draw.exclusions,
_selection_provenance(draw),
"",
)
selection = OrdinarySelectionV1(
**{**vars(draft), "selection_digest": content_digest(_selection_value(draft, include_digest=False))}
)
ordinary_selection_bytes(selection)
except (AttributeError, KeyError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.ORDINARY_DRAW_REFUSED) from error
if not content:
raise _refused(ReplacementBindingReason.ORDINARY_DRAW_REFUSED)
return selection
def freeze_replacement_baseline(
positives: Iterable[ReviewedPositiveInput],
*,
ordinary_selection: OrdinarySelectionV1,
reservation_census: ReservationCensusV1,
reservation_authority: ReservationAuthority,
scope_minimums: Iterable[ScopeMinimumV1] = (),
exclusion_counts: Iterable[tuple[str, int]] = (),
source_provenance_digest: str,
freeze_policy_digest: str,
expected_ecosystem_policy_digest: str,
expected_ground_truth_policy_digest: str,
forbidden_historical_identities: Iterable[str] = (),
) -> PopulationFreezeV3:
"""Freeze the reviewed population under new identities via the population authority."""
try:
return freeze_population(
positives,
ordinary_selection=ordinary_selection,
reservation_census=reservation_census,
reservation_authority=reservation_authority,
scope_minimums=scope_minimums,
exclusion_counts=exclusion_counts,
source_provenance_digest=source_provenance_digest,
freeze_policy_digest=freeze_policy_digest,
expected_ecosystem_policy_digest=expected_ecosystem_policy_digest,
expected_ground_truth_policy_digest=expected_ground_truth_policy_digest,
forbidden_historical_identities=forbidden_historical_identities,
)
except (AttributeError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.FREEZE_REFUSED) from error
def replacement_lifecycle_events(
historical_withdrawal: HistoricalWithdrawalV1,
*,
population_digest: str,
freeze_digest: str,
producer_identity: str,
reviewer_identity: str,
policy_digest: str,
) -> tuple[bytes, bytes]:
"""Build the reviewed withdrawal root and exact replacement-binding event."""
try:
withdrawal_bytes(historical_withdrawal)
root = withdrawn_event(historical_withdrawal)
root_event = decode_lifecycle_event(root)
if root_event.historical_withdrawal_digest is None:
raise _refused(ReplacementBindingReason.LIFECYCLE_REFUSED)
replacement = reviewed_replacement_event(
predecessor_digest=root_event.event_digest,
historical_withdrawal_digest=root_event.historical_withdrawal_digest,
population_digest=population_digest,
freeze_digest=freeze_digest,
producer_identity=producer_identity,
reviewer_identity=reviewer_identity,
conflict_disclosed=True,
policy_digest=policy_digest,
)
except (AttributeError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.LIFECYCLE_REFUSED) from error
return root, replacement
def _required_capabilities(
store_environ: Mapping[str, str],
capability_evidence: Mapping[StorePurpose, StoreCapabilityEvidence],
) -> None:
try:
require_store_startup(assess_store_startup(store_environ, capability_evidence))
except (RuntimeError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.STORE_CAPABILITY_MISSING) from error
def _validated_census(census: ReservationCensusV1) -> None:
try:
content = census_bytes(census)
except (AttributeError, ReservationError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.INVALID_REQUEST) from error
if not content:
raise _refused(ReplacementBindingReason.INVALID_REQUEST)
def _current_census(census: ReservationCensusV1, authority: ReservationAuthority) -> None:
try:
authority.require_current_census(census)
except (AttributeError, ReservationError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.RESERVATION_REFUSED) from error
def _closed_positive_set(batches: Sequence[CohortBatchOutcomeV1], draw: OrdinaryPopulationDrawV1) -> PositiveSetClosureV1:
try:
closure = project_positive_set_closure(batches)
except (PositiveSetClosureStateError, AttributeError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.INVALID_REQUEST) from error
if closure.status is not PositiveSetClosureStatus.CLOSED or closure.closure_digest != draw.closure_digest:
raise _refused(ReplacementBindingReason.POSITIVE_SET_NOT_CLOSED)
return closure
def _frozen_baseline(
positives: Sequence[ReviewedPositiveInput],
selection: OrdinarySelectionV1,
census: ReservationCensusV1,
authority: ReservationAuthority,
*,
scope_minimums: Iterable[ScopeMinimumV1],
exclusion_counts: Iterable[tuple[str, int]],
source_provenance_digest: str,
freeze_policy_digest: str,
expected_ecosystem_policy_digest: str,
expected_ground_truth_policy_digest: str,
forbidden_historical_identities: Iterable[str],
) -> PopulationFreezeV3:
freeze = freeze_replacement_baseline(
positives,
ordinary_selection=selection,
reservation_census=census,
reservation_authority=authority,
scope_minimums=scope_minimums,
exclusion_counts=exclusion_counts,
source_provenance_digest=source_provenance_digest,
freeze_policy_digest=freeze_policy_digest,
expected_ecosystem_policy_digest=expected_ecosystem_policy_digest,
expected_ground_truth_policy_digest=expected_ground_truth_policy_digest,
forbidden_historical_identities=forbidden_historical_identities,
)
if freeze.population_class is not PopulationClass.ADMISSION:
raise _refused(ReplacementBindingReason.POPULATION_NOT_ADMISSION_CLASS)
return freeze
def _partitioned_materials(
freeze: PopulationFreezeV3,
material_inputs: Iterable[PopulationMaterialInputV1],
partition_policy_digest: str,
) -> PopulationMaterialPartitionV1:
try:
return build_population_material_partition(
freeze,
material_inputs,
freeze_validator=_FreezeValidator(freeze),
partition_policy_digest=partition_policy_digest,
)
except (AttributeError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.MATERIAL_PARTITION_REFUSED) from error
def _reviewed_manifest(
freeze: PopulationFreezeV3,
partition: PopulationMaterialPartitionV1,
selection: OrdinarySelectionV1,
review: Callable[[LabelBlindPopulationDraftV3], IndependenceAttestation],
policy: ReviewIndependencePolicy,
resolver: canonical.ContentResolver,
) -> LabelBlindPopulationManifestV3:
try:
draft = build_label_blind_population_draft(freeze, partition, selection)
except (AttributeError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.MANIFEST_UNRESOLVED) from error
try:
attestation = review(draft)
except ReplacementBindingError:
raise
except Exception as error:
raise _refused(ReplacementBindingReason.MANIFEST_UNREVIEWED) from error
try:
manifest = review_label_blind_population_manifest(draft, attestation, policy, resolver)
except (AttributeError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.MANIFEST_UNREVIEWED) from error
try:
content = validate_label_blind_population_manifest(manifest, freeze, partition, selection, attestation, policy, resolver)
except (AttributeError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.MANIFEST_UNRESOLVED) from error
if not content:
raise _refused(ReplacementBindingReason.MANIFEST_UNRESOLVED)
return manifest
def _bound_lifecycle(
historical_withdrawal: HistoricalWithdrawalV1,
freeze: PopulationFreezeV3,
producer_identity: str,
reviewer_identity: str,
policy_digest: str,
) -> tuple[BaselineLifecycleAuthority, PopulationLifecycleProjectionV1]:
try:
root, replacement = replacement_lifecycle_events(
historical_withdrawal,
population_digest=freeze.population_digest,
freeze_digest=freeze.freeze_digest,
producer_identity=producer_identity,
reviewer_identity=reviewer_identity,
policy_digest=policy_digest,
)
authority = BaselineLifecycleAuthority()
authority.append(root)
projection = authority.append(replacement)
eligible = authority.require_admission_eligible(freeze.population_digest, freeze.freeze_digest)
except ReplacementBindingError:
raise
except (AttributeError, KeyError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.LIFECYCLE_REFUSED) from error
if projection != eligible:
raise _refused(ReplacementBindingReason.LIFECYCLE_REFUSED)
return authority, projection
def _accepted_reservation(
guard_scan_root: Path,
positives: Sequence[ReviewedPositiveInput],
freeze: PopulationFreezeV3,
projection: PopulationLifecycleProjectionV1,
census: ReservationCensusV1,
authority: ReservationAuthority,
historical_withdrawal: HistoricalWithdrawalV1,
reservation_sources: tuple[ExactReservationSourceV1, ...],
) -> ReplacementReservationAcceptanceV1:
try:
repositories = tuple(sorted({item.candidate.canonical_repository for item in positives}))
requests = tuple((entry.path, entry.content_digest) for entry in historical_withdrawal.candidate.entries)
report = scan_permanent_reservations(
guard_scan_root,
scan_roots=PRODUCTION_GUARD_SCAN_ROOTS,
authority=authority,
census=census,
reservation_sources=reservation_sources,
historical_withdrawal=historical_withdrawal,
)
return validate_replacement_population(
guard_scan_root,
repositories=repositories,
population_digest=freeze.population_digest,
freeze_digest=freeze.freeze_digest,
lifecycle=projection,
guard_report=report,
authority=authority,
census=census,
historical_withdrawal=historical_withdrawal,
reservation_sources=reservation_sources,
historical_requests=requests,
)
except (AttributeError, KeyError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.RESERVATION_REFUSED) from error
def _reverified(
lifecycle_authority: BaselineLifecycleAuthority,
reservation_authority: ReservationAuthority,
census: ReservationCensusV1,
freeze: PopulationFreezeV3,
store_environ: Mapping[str, str],
capability_evidence: Mapping[StorePurpose, StoreCapabilityEvidence],
) -> None:
_required_capabilities(store_environ, capability_evidence)
_current_census(census, reservation_authority)
try:
lifecycle_authority.require_admission_eligible(freeze.population_digest, freeze.freeze_digest)
except (AttributeError, TypeError, ValueError) as error:
raise _refused(ReplacementBindingReason.LIFECYCLE_REFUSED) from error
def _baseline_binding(
historical_withdrawal: HistoricalWithdrawalV1,
freeze: PopulationFreezeV3,
closure: PositiveSetClosureV1,
draw: OrdinaryPopulationDrawV1,
selection: OrdinarySelectionV1,
partition: PopulationMaterialPartitionV1,
manifest: LabelBlindPopulationManifestV3,
census: ReservationCensusV1,
acceptance: ReplacementReservationAcceptanceV1,
projection: PopulationLifecycleProjectionV1,
) -> ReplacementBaselineBindingV1:
draft = ReplacementBaselineBindingV1(
historical_withdrawal.withdrawal_digest,
freeze.population_digest,
freeze.freeze_digest,
closure.closure_digest,
draw.draw_digest,
selection.selection_digest,
partition.manifest.manifest_digest,
partition.manifest.private_object_digest,
partition.manifest.sealed_label_digest,
manifest.manifest_digest,
census.census_digest,
acceptance.guard_report_digest,
acceptance.acceptance_digest,
projection.projection_digest,
"",
)
binding = ReplacementBaselineBindingV1(
**{**vars(draft), "binding_digest": content_digest(_binding_value(draft, include_digest=False))}
)
replacement_baseline_binding_bytes(binding)
return binding
def bind_replacement_baseline(
positives: Iterable[ReviewedPositiveInput],
batches: Sequence[CohortBatchOutcomeV1],
*,
ordinary_draw: OrdinaryPopulationDrawV1,
reservation_census: ReservationCensusV1,
reservation_authority: ReservationAuthority,
material_inputs: Iterable[PopulationMaterialInputV1],
partition_policy_digest: str,
manifest_review: Callable[[LabelBlindPopulationDraftV3], IndependenceAttestation],
manifest_policy: ReviewIndependencePolicy,
disclosure_resolver: canonical.ContentResolver,
historical_withdrawal: HistoricalWithdrawalV1,
binding_producer_identity: str,
binding_reviewer_identity: str,
binding_policy_digest: str,
guard_scan_root: Path,
guard_reservation_sources: tuple[ExactReservationSourceV1, ...] = (),
scope_minimums: Iterable[ScopeMinimumV1] = (),
exclusion_counts: Iterable[tuple[str, int]] = (),
source_provenance_digest: str,
freeze_policy_digest: str,
expected_ecosystem_policy_digest: str,
expected_ground_truth_policy_digest: str,
forbidden_historical_identities: Iterable[str] = (),
store_environ: Mapping[str, str],
capability_evidence: Mapping[StorePurpose, StoreCapabilityEvidence],
) -> ReplacementBaselineBindingV1:
"""Freeze, review, partition, and causally bind the exact replacement baseline.
The binding composes only committed authorities, re-runs the permanent
reservation, lifecycle, and store capability checks read-only, and never
registers an arm, executes a plan, or releases label bytes.
"""
if type(ordinary_draw) is not OrdinaryPopulationDrawV1:
raise _refused(ReplacementBindingReason.INVALID_REQUEST)
reviewed_inputs = tuple(positives)
_required_capabilities(store_environ, capability_evidence)
_validated_census(reservation_census)
_current_census(reservation_census, reservation_authority)
closure = _closed_positive_set(batches, ordinary_draw)
selection = ordinary_selection_from_draw(ordinary_draw)
if ordinary_draw.reservation_census_digest != reservation_census.census_digest:
raise _refused(ReplacementBindingReason.ORDINARY_DRAW_REFUSED)
freeze = _frozen_baseline(
reviewed_inputs,
selection,
reservation_census,
reservation_authority,
scope_minimums=scope_minimums,
exclusion_counts=exclusion_counts,
source_provenance_digest=source_provenance_digest,
freeze_policy_digest=freeze_policy_digest,
expected_ecosystem_policy_digest=expected_ecosystem_policy_digest,
expected_ground_truth_policy_digest=expected_ground_truth_policy_digest,
forbidden_historical_identities=forbidden_historical_identities,
)
partition = _partitioned_materials(freeze, material_inputs, partition_policy_digest)
manifest = _reviewed_manifest(freeze, partition, selection, manifest_review, manifest_policy, disclosure_resolver)
lifecycle_authority, projection = _bound_lifecycle(
historical_withdrawal,
freeze,
binding_producer_identity,
binding_reviewer_identity,
binding_policy_digest,
)
acceptance = _accepted_reservation(
guard_scan_root,
reviewed_inputs,
freeze,
projection,
reservation_census,
reservation_authority,
historical_withdrawal,
guard_reservation_sources,
)
_reverified(lifecycle_authority, reservation_authority, reservation_census, freeze, store_environ, capability_evidence)
return _baseline_binding(
historical_withdrawal, freeze, closure, ordinary_draw, selection, partition, manifest, reservation_census, acceptance, projection
)
def require_baseline_custody_available(
binding: ReplacementBaselineBindingV1,
custody_log: PopulationCustodyLog,
) -> None:
"""Prove the bound population is still untouched without spending labels."""
replacement_baseline_binding_bytes(binding)
if type(custody_log) is not PopulationCustodyLog:
raise _refused(ReplacementBindingReason.CUSTODY_NOT_AVAILABLE)
if (
custody_log.population_digest != binding.population_digest
or custody_log.status is not PopulationStatus.AVAILABLE
or custody_log.receipt_count != 0
or custody_log.receipts
):
raise _refused(ReplacementBindingReason.CUSTODY_NOT_AVAILABLE)
__all__ = [
"REPLACEMENT_BASELINE_BINDING_SCHEMA",
"ReplacementBaselineBindingV1",
"ReplacementBindingError",
"ReplacementBindingReason",
"ReplacementBindingStateError",
"ReplacementBindingStateReason",
"bind_replacement_baseline",
"freeze_replacement_baseline",
"ordinary_selection_from_draw",
"replacement_baseline_binding_bytes",
"replacement_lifecycle_events",
"require_baseline_custody_available",
]
@@ -0,0 +1,223 @@
"""Durable persistence, hostile decode, and replay for the replacement binding.
The binding record, the freeze, the reviewed label-blind manifest, the
partitioned material objects, and the lifecycle events persist under the
committed artifact-access conventions: public metadata is PUBLIC, private
source material is PRIVATE, sealed labels are CUSTODIAN_SEALED, and operator
records are OPERATOR_SAFE. Every durable decode is hostile: no constants,
finite floats, bounded recursion, and canonical bytes only.
"""
from __future__ import annotations
import json
import math
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any
from benchmarks.valid.artifact_repository import ArtifactReadAuthority, S3ArtifactRepository
from benchmarks.valid.lifecycle import decode_lifecycle_event
from benchmarks.valid.population_freeze import PopulationFreezeV3, population_freeze_bytes
from benchmarks.valid.population_label_blind import (
LabelBlindPopulationManifestV3,
label_blind_population_manifest_bytes,
)
from benchmarks.valid.population_materials import (
PopulationMaterialPartitionV1,
private_object_bytes,
public_manifest_bytes,
sealed_label_object_bytes,
)
from benchmarks.valid.replacement_artifact_contract import (
ArtifactAccessClass,
ArtifactKind,
ArtifactReference,
artifact_reference,
canonical_artifact_bytes,
)
from benchmarks.valid.replacement_freeze_binding import (
REPLACEMENT_BASELINE_BINDING_SCHEMA,
ReplacementBaselineBindingV1,
ReplacementBindingStateError,
ReplacementBindingStateReason,
replacement_baseline_binding_bytes,
)
from openultrasast.core.canonical import canonical_bytes
_BINDING_KEYS = frozenset({*("schema_version", "binding_digest"), *ReplacementBaselineBindingV1.__dataclass_fields__})
def _reject_constant(name: str) -> None:
raise ValueError(name)
def _finite_float(text: str) -> float:
value = float(text)
if not math.isfinite(value):
raise ValueError(text)
return value
def _converted(value: Any) -> Any:
if isinstance(value, list):
return tuple(_converted(item) for item in value)
if isinstance(value, dict):
return {str(key): _converted(item) for key, item in value.items()}
return value
def _decoded_mapping(content: bytes) -> dict[str, Any]:
"""Hostile decode: no constants, finite floats, bounded recursion, canonical bytes."""
if not isinstance(content, bytes) or not content:
raise ReplacementBindingStateError(ReplacementBindingStateReason.STATE_UNREADABLE)
try:
parsed = json.loads(content, parse_constant=_reject_constant, parse_float=_finite_float)
value = _converted(parsed)
canonical = canonical_bytes(value)
except (UnicodeError, json.JSONDecodeError, ValueError, RecursionError):
raise ReplacementBindingStateError(ReplacementBindingStateReason.STATE_UNREADABLE) from None
if not isinstance(value, dict) or canonical != content:
raise ReplacementBindingStateError(ReplacementBindingStateReason.STATE_UNREADABLE)
return value
def decode_replacement_baseline_binding(content: bytes) -> ReplacementBaselineBindingV1:
"""Rebuild one binding record only from canonical, digest-consistent bytes."""
value = _decoded_mapping(content)
if set(value) != _BINDING_KEYS or value["schema_version"] != REPLACEMENT_BASELINE_BINDING_SCHEMA:
raise ReplacementBindingStateError(ReplacementBindingStateReason.STATE_MISMATCH)
try:
binding = ReplacementBaselineBindingV1(*(value[field] for field in ReplacementBaselineBindingV1.__dataclass_fields__))
except (AttributeError, KeyError, TypeError, ValueError) as error:
raise ReplacementBindingStateError(ReplacementBindingStateReason.STATE_MISMATCH) from error
if replacement_baseline_binding_bytes(binding) != content:
raise ReplacementBindingStateError(ReplacementBindingStateReason.STATE_MISMATCH)
return binding
@dataclass(frozen=True)
class ReplacementBaselineReferencesV1:
"""Durable references for every persisted replacement-baseline artifact."""
freeze: ArtifactReference
manifest: ArtifactReference
public_manifest: ArtifactReference
private_object: ArtifactReference
sealed_labels: ArtifactReference
lifecycle_events: tuple[ArtifactReference, ...]
binding: ArtifactReference
def _persist(
store: S3ArtifactRepository,
content: bytes,
*,
kind: ArtifactKind,
access: ArtifactAccessClass,
provenance_digest: str,
) -> ArtifactReference:
payload = _decoded_mapping(content)
artifact = canonical_artifact_bytes(kind, payload, access_class=access, provenance_digest=provenance_digest)
return store.put_if_absent(artifact, reference=artifact_reference(artifact))
def _persist_event(store: S3ArtifactRepository, content: bytes) -> ArtifactReference:
try:
event = decode_lifecycle_event(content)
except (AttributeError, TypeError, ValueError) as error:
raise ReplacementBindingStateError(ReplacementBindingStateReason.STATE_MISMATCH) from error
return _persist(
store,
content,
kind=ArtifactKind.LIFECYCLE,
access=ArtifactAccessClass.OPERATOR_SAFE,
provenance_digest=event.event_digest,
)
def persist_replacement_baseline(
store: S3ArtifactRepository,
*,
binding: ReplacementBaselineBindingV1,
freeze: PopulationFreezeV3,
manifest: LabelBlindPopulationManifestV3,
partition: PopulationMaterialPartitionV1,
lifecycle_events: Sequence[bytes],
) -> ReplacementBaselineReferencesV1:
"""Persist the bound baseline under exact public/private/sealed access classes."""
material = partition.manifest
return ReplacementBaselineReferencesV1(
_persist(
store,
population_freeze_bytes(freeze),
kind=ArtifactKind.POPULATION,
access=ArtifactAccessClass.OPERATOR_SAFE,
provenance_digest=freeze.freeze_digest,
),
_persist(
store,
label_blind_population_manifest_bytes(manifest),
kind=ArtifactKind.POPULATION,
access=ArtifactAccessClass.OPERATOR_SAFE,
provenance_digest=manifest.manifest_digest,
),
_persist(
store,
public_manifest_bytes(partition),
kind=ArtifactKind.POPULATION,
access=ArtifactAccessClass.PUBLIC,
provenance_digest=material.manifest_digest,
),
_persist(
store,
private_object_bytes(partition),
kind=ArtifactKind.POPULATION,
access=ArtifactAccessClass.PRIVATE,
provenance_digest=material.private_object_digest,
),
_persist(
store,
sealed_label_object_bytes(partition),
kind=ArtifactKind.POPULATION,
access=ArtifactAccessClass.CUSTODIAN_SEALED,
provenance_digest=material.sealed_label_digest,
),
tuple(_persist_event(store, event) for event in lifecycle_events),
_persist(
store,
replacement_baseline_binding_bytes(binding),
kind=ArtifactKind.POPULATION,
access=ArtifactAccessClass.OPERATOR_SAFE,
provenance_digest=binding.binding_digest,
),
)
def resume_replacement_baseline_binding(
store: S3ArtifactRepository,
reference: ArtifactReference,
*,
authority: ArtifactReadAuthority,
expected_access_policy_digest: str,
) -> ReplacementBaselineBindingV1:
"""Resume one replacement binding from the durable store after restart."""
accepted = store.get(
reference,
expected_kind=ArtifactKind.POPULATION,
authority=authority,
expected_access_policy_digest=expected_access_policy_digest,
)
try:
content = canonical_bytes(_converted(accepted.artifact.payload))
except (TypeError, ValueError, RecursionError):
raise ReplacementBindingStateError(ReplacementBindingStateReason.STATE_UNREADABLE) from None
return decode_replacement_baseline_binding(content)
__all__ = [
"ReplacementBaselineReferencesV1",
"decode_replacement_baseline_binding",
"persist_replacement_baseline",
"resume_replacement_baseline_binding",
]
@@ -0,0 +1,710 @@
"""Replacement baseline freeze and causal binding integration (task 10.7).
The suite drives the complete synthetic pipeline -- fixtures, four reviewed
cohorts, positive-set closure, the validated ordinary draw -- into the one
integration freeze that closes group 10: new population/freeze identities, the
independently reviewed label-blind manifest, persisted public/private/sealed
partitions, the reviewed replacement-binding lifecycle event, and the read-only
reservation, lifecycle, capability, and custody rechecks. Every refusal path is
adversarial: a lowered bar can never produce a binding.
"""
from __future__ import annotations
import hashlib
import json
import shutil
import sys
from dataclasses import replace
from functools import lru_cache
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from cohort_ingestion_fixtures import ( # noqa: E402
_APPS,
ECOSYSTEM_POLICY,
ECOSYSTEM_PRODUCER,
ECOSYSTEM_REVIEWER,
GROUND_TRUTH_POLICY,
READ_POLICY,
_Client,
_read_authority,
_settings,
candidate_for,
case_for,
)
from detection_core_fixtures import stored_artifact # noqa: E402
from test_valid_benchmark_ordinary_draw import ( # noqa: E402
DRAW_POLICY,
FULL_NAMES,
SOURCE,
OrdinaryFixtureHistory,
_full_closed_batches,
)
from benchmarks.valid import historical_authorization as historical # noqa: E402
from benchmarks.valid import (
lifecycle, # noqa: E402
reservation, # noqa: E402
)
from benchmarks.valid import population_label_blind as label_blind # noqa: E402
from benchmarks.valid import population_materials as materials # noqa: E402
from benchmarks.valid import replacement_freeze_binding as binding_module # noqa: E402
from benchmarks.valid import replacement_freeze_binding_store as binding_store # noqa: E402
from benchmarks.valid.artifact_repository import ( # noqa: E402
ArtifactActorRole,
ArtifactReadPermission,
ArtifactRepositoryReason,
S3ArtifactRepository,
artifact_read_authority,
)
from benchmarks.valid.artifact_repository import ArtifactRepositoryError as StoreReadError # noqa: E402
from benchmarks.valid.cohort_ingestion import CohortBatchStatus # noqa: E402
from benchmarks.valid.ecosystem_review import ( # noqa: E402
EcosystemReviewAttestationV1,
EcosystemReviewDecision,
review_repository_ecosystem,
)
from benchmarks.valid.ground_truth_review import ( # noqa: E402
GroundTruthAttestationV1,
GroundTruthStatus,
VerifiedScope,
review_ground_truth,
)
from benchmarks.valid.ordinary_change_contract import ReviewedPositiveInput # noqa: E402
from benchmarks.valid.ordinary_draw import ( # noqa: E402
MINIMUM_ORDINARY_PER_POSITIVE,
OrdinaryPopulationHistorySource,
draw_ordinary_population,
)
from benchmarks.valid.ordinary_draw_contract import ordinary_population_draw_bytes # noqa: E402
from benchmarks.valid.ordinary_draw_store import decode_ordinary_population_draw # noqa: E402
from benchmarks.valid.positive_set_closure import PositiveSetClosureStatus, project_positive_set_closure # noqa: E402
from benchmarks.valid.replacement_artifact_contract import ArtifactAccessClass, canonical_json_bytes # noqa: E402
from benchmarks.valid.store_configuration import StoreCapabilityEvidence, StorePurpose # noqa: E402
from openultrasast.core.canonical import content_digest # noqa: E402
from openultrasast.core.custody import PopulationStatus, empty_population_custody_log # noqa: E402
from openultrasast.core.factpack import ( # noqa: E402
IndependenceAttestation,
ReviewIndependencePolicy,
derive_independence_attestation_digest,
derive_review_independence_policy_digest,
)
ROOT = Path(__file__).resolve().parents[1]
HISTORICAL_POLICY = content_digest({"policy": "historical-review-v1"})
BINDING_POLICY = content_digest({"policy": "replacement-binding-review-v1"})
BINDING_PRODUCER = "[email protected]"
BINDING_REVIEWER = "[email protected]"
PARTITION_POLICY = content_digest({"policy": "material-partition-policy-v1"})
FREEZE_POLICY = content_digest({"policy": "population-freeze-v1", "minimum": 40})
PROVENANCE = content_digest({"source": "replacement-fixture-pipeline"})
RESERVED_REPOSITORY = "https://github.com/acme/reserved"
MANIFEST_PRODUCER = content_digest({"identity": "manifest-producer"})
MANIFEST_REVIEWER = content_digest({"identity": "manifest-reviewer"})
CUSTODIAN = content_digest({"identity": "fixture-custodian"})
def _reviewed(name: str, resolved) -> ReviewedPositiveInput:
"""Rebuild the exact reviewed input the cohort ledger accepted for one name."""
ecosystem = "python" if case_for(name)["repo"].startswith("fixture/cohort-py") else "javascript"
candidate = candidate_for(name, resolved)
eco = review_repository_ecosystem(
candidate,
EcosystemReviewAttestationV1(
candidate.candidate_digest,
candidate.source_evidence.evidence_digest,
ECOSYSTEM_PRODUCER,
ECOSYSTEM_REVIEWER,
True,
ECOSYSTEM_POLICY,
True,
EcosystemReviewDecision(ecosystem),
),
expected_policy_digest=ECOSYSTEM_POLICY,
)
locator = f"GHSA-cohort-{name}"
truth = review_ground_truth(
candidate,
eco,
GroundTruthAttestationV1(
candidate.candidate_digest,
eco.review_digest,
f"producer-{locator}@example.invalid",
f"reviewer-{locator}@example.invalid",
True,
GROUND_TRUTH_POLICY,
True,
True,
True,
True,
(VerifiedScope(case_for(name)["family"], ecosystem),),
None,
),
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
)
assert truth.status is GroundTruthStatus.ACCEPTED
return ReviewedPositiveInput(candidate, eco, truth)
@lru_cache(maxsize=1)
def _pipeline():
batches, resolved = _full_closed_batches()
reviewed = tuple(_reviewed(name, resolved) for name in FULL_NAMES)
ledger_changes = {
positive.change_identity_digest
for batch in batches
if batch.status is CohortBatchStatus.ACCEPTED
for positive in batch.accepted_positives
}
assert {item.ground_truth_review.change_identity_digest for item in reviewed} == ledger_changes
return batches, resolved, reviewed
def _networks():
networks = [reservation.build_network_identity(app["url"]) for app in _APPS.values()]
networks.append(reservation.build_network_identity(RESERVED_REPOSITORY))
return reservation.RepositoryIdentityResolver(networks)
def _reserved_authority():
resolved = _networks()
legacy = reservation.legacy_reservation_source(
resolved,
repository=RESERVED_REPOSITORY,
source_digest=content_digest({"legacy": "reserved-history"}),
)
authority = reservation.ReservationAuthority(resolved, legacy_sources=(legacy,))
return resolved, authority, authority.current_census()
@lru_cache(maxsize=1)
def _draw(census_key: str = "reserved"):
batches, _, _ = _pipeline()
resolved, authority, census = _reserved_authority()
history = OrdinaryFixtureHistory(FULL_NAMES)
candidates = {name: candidate_for(name, resolved) for name in FULL_NAMES}
by_digest = {item.candidate_digest: item for item in candidates.values()}
sources = {
item.network_identity_digest: OrdinaryPopulationHistorySource(
history, item.canonical_repository, item.network_identity_digest, SOURCE
)
for item in by_digest.values()
}
draw = draw_ordinary_population(
batches,
candidates_by_digest=by_digest,
history_by_network=sources,
reservation_census=census,
required_per_positive=MINIMUM_ORDINARY_PER_POSITIVE,
policy_digest=DRAW_POLICY,
)
return draw, resolved, authority, census
def _manifest_review(draft: label_blind.LabelBlindPopulationDraftV3) -> IndependenceAttestation:
disclosure, _ = stored_artifact(b'{"conflicts":[]}', artifact_id="binding-conflicts")
seeded = IndependenceAttestation(
draft.draft_digest,
MANIFEST_PRODUCER,
MANIFEST_REVIEWER,
disclosure,
"0" * 64,
)
return replace(seeded, attestation_digest=derive_independence_attestation_digest(seeded))
def _manifest_policy() -> ReviewIndependencePolicy:
digest = derive_review_independence_policy_digest((MANIFEST_REVIEWER,), (), ("trusted-store",), 4096)
return ReviewIndependencePolicy((MANIFEST_REVIEWER,), (), ("trusted-store",), 4096, digest)
def _environment() -> dict[str, str]:
return {
"VALID_BENCHMARK_DURABLE_S3_ENDPOINT": "https://durable.invalid:9000",
"VALID_BENCHMARK_DURABLE_S3_BUCKET": "valid-benchmark-durable",
"VALID_BENCHMARK_DURABLE_AWS_ACCESS_KEY_ID": "durable-key",
"VALID_BENCHMARK_DURABLE_AWS_SECRET_ACCESS_KEY": "durable-secret",
"VALID_BENCHMARK_TRANSIENT_S3_ENDPOINT": "https://transient.invalid:9000",
"VALID_BENCHMARK_TRANSIENT_S3_BUCKET": "valid-benchmark-runs",
"VALID_BENCHMARK_TRANSIENT_AWS_ACCESS_KEY_ID": "transient-key",
"VALID_BENCHMARK_TRANSIENT_AWS_SECRET_ACCESS_KEY": "transient-secret",
}
def _evidence(purpose: StorePurpose, *, versioning: bool = True) -> StoreCapabilityEvidence:
current = None if purpose is StorePurpose.DURABLE else 14
noncurrent = 30 if purpose is StorePurpose.DURABLE else 1
return StoreCapabilityEvidence(
purpose=purpose,
versioning_enabled=versioning,
conditional_create=True,
conditional_update=True,
current_version_expiry_days=current,
noncurrent_version_expiry_days=noncurrent,
)
def _capabilities(*, versioning: bool = True) -> dict[StorePurpose, StoreCapabilityEvidence]:
return {purpose: _evidence(purpose, versioning=versioning) for purpose in StorePurpose}
def _material_inputs(changes) -> tuple[materials.PopulationMaterialInputV1, ...]:
return tuple(
materials.PopulationMaterialInputV1(
change,
materials.LicenseClass.PERMISSIVE if index % 5 else materials.LicenseClass.NON_PERMISSIVE,
"Apache-2.0" if index % 5 else "BUSL-1.1",
f"public source {index}".encode(),
f"sealed label {index}".encode(),
f"sealed review {index}".encode(),
index % 5 == 1,
)
for index, change in enumerate(changes)
)
def _historical_review(subject: str) -> bytes:
value: dict[str, object] = {
"schema_version": historical.HISTORICAL_REVIEW_SCHEMA,
"subject_digest": subject,
"decision": "authorize_exact_historical_audit",
"producer_identity": "custodian",
"reviewer_identity": "historical-reviewer",
"conflict_disclosed": True,
"policy_digest": HISTORICAL_POLICY,
}
value["review_digest"] = content_digest(value)
return canonical_json_bytes(value)
def _withdrawal(guard_root: Path) -> historical.HistoricalWithdrawalV1:
inventory = historical.pinned_historical_inventory(guard_root)
candidate = historical.build_withdrawal_candidate(inventory)
return historical.accept_reviewed_withdrawal(candidate, _historical_review(candidate.candidate_digest))
def _bind(
guard_root: Path,
*,
positives=None,
batches=None,
draw=None,
census=None,
review=None,
capabilities=None,
minimums=(),
forbidden=(),
):
draw_value, resolved, authority, bound_census = _draw()
batches_value, _, reviewed = _pipeline()
disclosure, resolver = stored_artifact(b'{"conflicts":[]}', artifact_id="binding-conflicts")
return binding_module.bind_replacement_baseline(
positives if positives is not None else reviewed,
batches if batches is not None else batches_value,
ordinary_draw=draw if draw is not None else draw_value,
reservation_census=census if census is not None else bound_census,
reservation_authority=authority,
material_inputs=_material_inputs(draw_value.positive_change_digests),
partition_policy_digest=PARTITION_POLICY,
manifest_review=review if review is not None else _manifest_review,
manifest_policy=_manifest_policy(),
disclosure_resolver=resolver,
historical_withdrawal=_withdrawal(guard_root),
binding_producer_identity=BINDING_PRODUCER,
binding_reviewer_identity=BINDING_REVIEWER,
binding_policy_digest=BINDING_POLICY,
guard_scan_root=guard_root,
scope_minimums=minimums,
exclusion_counts=(("review_excluded", 2),),
source_provenance_digest=PROVENANCE,
freeze_policy_digest=FREEZE_POLICY,
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
forbidden_historical_identities=forbidden,
store_environ=_environment(),
capability_evidence=capabilities if capabilities is not None else _capabilities(),
)
class _ExactValidator:
def __init__(self, expected) -> None:
self.expected = expected
def validate(self, freeze) -> bytes:
from benchmarks.valid.population_freeze import population_freeze_bytes
if freeze != self.expected:
raise materials.PopulationMaterialError("freeze does not replay from exact authorities")
return population_freeze_bytes(freeze)
def _binding_artifacts(guard_root: Path, binding):
"""Independently re-derive every artifact the binding names."""
draw, _, _, census = _draw()
_, _, reviewed = _pipeline()
selection = binding_module.ordinary_selection_from_draw(draw)
freeze = binding_module.freeze_replacement_baseline(
reviewed,
ordinary_selection=selection,
reservation_census=census,
reservation_authority=_reserved_authority()[1],
exclusion_counts=(("review_excluded", 2),),
source_provenance_digest=PROVENANCE,
freeze_policy_digest=FREEZE_POLICY,
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
)
partition = materials.build_population_material_partition(
freeze,
_material_inputs(freeze.positive_change_digests),
freeze_validator=_ExactValidator(freeze),
partition_policy_digest=PARTITION_POLICY,
)
draft = label_blind.build_label_blind_population_draft(freeze, partition, selection)
disclosure, resolver = stored_artifact(b'{"conflicts":[]}', artifact_id="binding-conflicts")
manifest = label_blind.review_label_blind_population_manifest(draft, _manifest_review(draft), _manifest_policy(), resolver)
return draw, selection, freeze, partition, manifest
@pytest.fixture()
def guard_root(tmp_path: Path) -> Path:
for relative in historical.PINNED_HISTORICAL_DIGESTS:
target = tmp_path / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ROOT / relative, target)
for name in ("benchmarks", "src", "tests", "plane"):
(tmp_path / name).mkdir(exist_ok=True)
return tmp_path
@pytest.fixture(autouse=True)
def offline(monkeypatch):
def forbidden(*args, **kwargs):
pytest.fail("network or SZZ was invoked")
import socket
from benchmarks.unseen import extract
monkeypatch.setattr(socket, "create_connection", forbidden)
monkeypatch.setattr(socket.socket, "connect", forbidden)
monkeypatch.setattr(extract, "introducing", forbidden)
monkeypatch.setattr(extract.Git, "blame", forbidden)
def test_pipeline_closes_with_forty_eight_reviewed_positives() -> None:
batches, _, reviewed = _pipeline()
closure = project_positive_set_closure(batches)
draw, _, _, _ = _draw()
assert closure.status is PositiveSetClosureStatus.CLOSED
assert closure.total_accepted_positives == 48
assert len(reviewed) == 48
assert {item.ground_truth_review.change_identity_digest for item in reviewed} == set(draw.positive_change_digests)
def test_pipeline_freeze_is_admission_class_under_new_identities(guard_root) -> None:
_, _, _, census = _draw()
_, _, reviewed = _pipeline()
draw, selection, freeze, partition, manifest = _binding_artifacts(guard_root, None)
pilot = json.loads((ROOT / "benchmarks/valid/pilot/freeze-valid.json").read_text())
assert freeze.population_class is binding_module.PopulationClass.ADMISSION
assert freeze.positive_count == 48
assert freeze.reservation_census_digest == census.census_digest
assert selection.selection_digest == freeze.ordinary_selection_digest
assert (freeze.population_digest, freeze.freeze_digest) != (None, pilot["freeze_digest"])
assert freeze.freeze_digest != pilot["freeze_digest"]
def test_binding_names_every_independently_derived_artifact(guard_root) -> None:
binding = _bind(guard_root)
draw, selection, freeze, partition, manifest = _binding_artifacts(guard_root, binding)
withdrawal = _withdrawal(guard_root)
_, _, _, census = _draw()
assert binding.population_digest == freeze.population_digest
assert binding.freeze_digest == freeze.freeze_digest
assert binding.closure_digest == project_positive_set_closure(_pipeline()[0]).closure_digest
assert binding.ordinary_draw_digest == draw.draw_digest
assert binding.ordinary_selection_digest == selection.selection_digest
assert binding.material_manifest_digest == partition.manifest.manifest_digest
assert binding.private_object_digest == partition.manifest.private_object_digest
assert binding.sealed_label_digest == partition.manifest.sealed_label_digest
assert binding.manifest_digest == manifest.manifest_digest
assert binding.reservation_census_digest == census.census_digest
assert binding.historical_withdrawal_digest == withdrawal.withdrawal_digest
content = binding_module.replacement_baseline_binding_bytes(binding)
assert content and binding_store.decode_replacement_baseline_binding(content) == binding
def test_binding_replays_byte_identically_from_permuted_inputs(guard_root) -> None:
batches, _, reviewed = _pipeline()
first = _bind(guard_root)
second = _bind(guard_root, positives=tuple(reversed(reviewed)), batches=tuple(reversed(batches)))
assert binding_module.replacement_baseline_binding_bytes(first) == binding_module.replacement_baseline_binding_bytes(second)
assert first.binding_digest == second.binding_digest
def test_lifecycle_event_binds_exact_withdrawal_population_and_freeze(guard_root) -> None:
binding = _bind(guard_root)
withdrawal = _withdrawal(guard_root)
root_event, replacement_event = binding_module.replacement_lifecycle_events(
withdrawal,
population_digest=binding.population_digest,
freeze_digest=binding.freeze_digest,
producer_identity=BINDING_PRODUCER,
reviewer_identity=BINDING_REVIEWER,
policy_digest=BINDING_POLICY,
)
authority = lifecycle.BaselineLifecycleAuthority()
root = authority.append(root_event)
decoded = lifecycle.decode_lifecycle_event(replacement_event)
projection = authority.append(replacement_event)
assert root.state is lifecycle.PopulationLifecycleState.REPLACEMENT_PENDING
assert decoded.kind is lifecycle.PopulationLifecycleKind.REPLACEMENT_BOUND
assert decoded.predecessor_digest == lifecycle.decode_lifecycle_event(root_event).event_digest
assert decoded.historical_withdrawal_digest == withdrawal.withdrawal_digest
assert (decoded.population_digest, decoded.freeze_digest) == (binding.population_digest, binding.freeze_digest)
assert projection.state is lifecycle.PopulationLifecycleState.REPLACEMENT_COMPLETE
assert projection.admission_eligible
assert binding.lifecycle_projection_digest == projection.projection_digest
assert authority.require_admission_eligible(binding.population_digest, binding.freeze_digest) == projection
def test_historical_pilot_remains_withdrawn_and_byte_identical(guard_root) -> None:
before = {path: (ROOT / path).read_bytes() for path in historical.PINNED_HISTORICAL_DIGESTS}
withdrawal = _withdrawal(guard_root)
binding = _bind(guard_root)
for path, content in before.items():
assert (ROOT / path).read_bytes() == content
assert hashlib.sha256(content).hexdigest() == historical.PINNED_HISTORICAL_DIGESTS[path]
assert historical.pinned_historical_inventory(ROOT).inventory_digest == withdrawal.inventory_digest
assert binding.historical_withdrawal_digest == withdrawal.withdrawal_digest
with pytest.raises(historical.HistoricalAuthorizationError):
historical.require_current_qualification(withdrawal)
rebuilt = historical.build_withdrawal_candidate(historical.pinned_historical_inventory(guard_root))
assert historical.accept_reviewed_withdrawal(rebuilt, _historical_review(rebuilt.candidate_digest)) == withdrawal
def test_label_blind_manifest_resolves_exactly_and_stays_label_blind(guard_root) -> None:
binding = _bind(guard_root)
_, selection, freeze, partition, manifest = _binding_artifacts(guard_root, binding)
disclosure, resolver = stored_artifact(b'{"conflicts":[]}', artifact_id="binding-conflicts")
content = label_blind.validate_label_blind_population_manifest(
manifest, freeze, partition, selection, _manifest_review(
label_blind.build_label_blind_population_draft(freeze, partition, selection)
), _manifest_policy(), resolver
)
assert content == label_blind.label_blind_population_manifest_bytes(manifest)
assert manifest.manifest_digest == binding.manifest_digest
assert manifest.positive_count == 48
assert manifest.input_count == 48 + 48 * MINIMUM_ORDINARY_PER_POSITIVE
value = json.loads(content)
assert not any("label" in key or "judg" in key or "verdict" in key for key in value)
assert set(manifest.input_digests) == {
*freeze.positive_change_digests,
*(push.push_digest for push in selection.pushes),
}
def test_partitions_persist_under_public_private_and_sealed_access(guard_root) -> None:
binding = _bind(guard_root)
_, _, freeze, partition, manifest = _binding_artifacts(guard_root, binding)
events = binding_module.replacement_lifecycle_events(
_withdrawal(guard_root),
population_digest=binding.population_digest,
freeze_digest=binding.freeze_digest,
producer_identity=BINDING_PRODUCER,
reviewer_identity=BINDING_REVIEWER,
policy_digest=BINDING_POLICY,
)
store = S3ArtifactRepository(_settings(), _Client())
references = binding_store.persist_replacement_baseline(
store, binding=binding, freeze=freeze, manifest=manifest, partition=partition, lifecycle_events=events
)
operator = _read_authority()
custodian = artifact_read_authority(
ArtifactActorRole.CUSTODIAN,
(ArtifactReadPermission.PRIVATE, ArtifactReadPermission.CUSTODIAN_SEALED),
READ_POLICY,
expected_access_policy_digest=READ_POLICY,
)
assert references.public_manifest.access_class is ArtifactAccessClass.PUBLIC
assert references.private_object.access_class is ArtifactAccessClass.PRIVATE
assert references.sealed_labels.access_class is ArtifactAccessClass.CUSTODIAN_SEALED
assert references.binding.access_class is ArtifactAccessClass.OPERATOR_SAFE
public_read = store.get(
references.public_manifest,
expected_kind=references.public_manifest.artifact_kind,
authority=operator,
expected_access_policy_digest=READ_POLICY,
)
serialized = json.dumps(public_read.artifact.payload)
assert "label_base64" not in serialized and "judgment_base64" not in serialized
assert b"sealed label" not in serialized.encode() and b"sealed review" not in serialized.encode()
for reference in (references.sealed_labels, references.private_object):
with pytest.raises(StoreReadError) as error:
store.get(reference, expected_kind=reference.artifact_kind, authority=operator, expected_access_policy_digest=READ_POLICY)
assert error.value.reason is ArtifactRepositoryReason.NOT_AUTHORIZED
sealed_read = store.get(
references.sealed_labels,
expected_kind=references.sealed_labels.artifact_kind,
authority=custodian,
expected_access_policy_digest=READ_POLICY,
)
assert sealed_read.artifact.access_class is ArtifactAccessClass.CUSTODIAN_SEALED
resumed = binding_store.resume_replacement_baseline_binding(
store, references.binding, authority=operator, expected_access_policy_digest=READ_POLICY
)
assert resumed == binding
def test_unclosed_positive_set_is_refused(guard_root) -> None:
batches, _, _ = _pipeline()
with pytest.raises(binding_module.ReplacementBindingError) as error:
_bind(guard_root, batches=batches[:2])
assert error.value.reason is binding_module.ReplacementBindingReason.POSITIVE_SET_NOT_CLOSED
def test_draw_bound_to_a_different_census_is_refused(guard_root) -> None:
batches, _, _ = _pipeline()
resolved = _networks()
plain = reservation.ReservationAuthority(resolved)
plain_census = plain.current_census()
history = OrdinaryFixtureHistory(FULL_NAMES)
candidates = {name: candidate_for(name, resolved) for name in FULL_NAMES}
by_digest = {item.candidate_digest: item for item in candidates.values()}
sources = {
item.network_identity_digest: OrdinaryPopulationHistorySource(
history, item.canonical_repository, item.network_identity_digest, SOURCE
)
for item in by_digest.values()
}
foreign = draw_ordinary_population(
batches,
candidates_by_digest=by_digest,
history_by_network=sources,
reservation_census=plain_census,
required_per_positive=MINIMUM_ORDINARY_PER_POSITIVE,
policy_digest=DRAW_POLICY,
)
assert foreign.reservation_census_digest != _draw()[3].census_digest
with pytest.raises(binding_module.ReplacementBindingError) as error:
_bind(guard_root, draw=foreign)
assert error.value.reason is binding_module.ReplacementBindingReason.ORDINARY_DRAW_REFUSED
def test_truncated_draw_bytes_fail_hostile_decode_before_any_binding(guard_root) -> None:
draw, _, _, _ = _draw()
content = ordinary_population_draw_bytes(draw)
with pytest.raises(Exception) as error:
decode_ordinary_population_draw(content[:-8])
assert isinstance(error.value, ValueError)
def test_unreviewed_manifest_is_refused(guard_root) -> None:
def self_reviewed(draft: label_blind.LabelBlindPopulationDraftV3) -> IndependenceAttestation:
review = _manifest_review(draft)
return replace(review, producer_identity=review.reviewer_identity)
def stale(draft: label_blind.LabelBlindPopulationDraftV3) -> IndependenceAttestation:
return _manifest_review(replace(draft, draft_digest="1" * 64 if draft.draft_digest[0] != "1" else "2" * 64))
for review in (self_reviewed, stale):
with pytest.raises(binding_module.ReplacementBindingError) as error:
_bind(guard_root, review=review)
assert error.value.reason is binding_module.ReplacementBindingReason.MANIFEST_UNREVIEWED
def test_missing_store_capability_is_refused(guard_root) -> None:
with pytest.raises(binding_module.ReplacementBindingError) as error:
_bind(guard_root, capabilities=_capabilities(versioning=False))
assert error.value.reason is binding_module.ReplacementBindingReason.STORE_CAPABILITY_MISSING
def test_infeasible_scope_minimum_cannot_bind_as_the_replacement(guard_root) -> None:
minimums = (binding_module.ScopeMinimumV1("injection", "python", 999),)
with pytest.raises(binding_module.ReplacementBindingError) as error:
_bind(guard_root, minimums=minimums)
assert error.value.reason is binding_module.ReplacementBindingReason.POPULATION_NOT_ADMISSION_CLASS
def test_historical_identity_reuse_is_refused(guard_root) -> None:
binding = _bind(guard_root)
pilot = json.loads((ROOT / "benchmarks/valid/pilot/freeze-valid.json").read_text())
assert binding.freeze_digest != pilot["freeze_digest"]
with pytest.raises(binding_module.ReplacementBindingError) as error:
_bind(guard_root, forbidden=(binding.population_digest, binding.freeze_digest, pilot["freeze_digest"]))
assert error.value.reason is binding_module.ReplacementBindingReason.FREEZE_REFUSED
def test_doctored_reservation_census_is_refused(guard_root) -> None:
_, _, census = _reserved_authority()
stale = replace(census, reserved_network_digests=(*census.reserved_network_digests, "3" * 64))
with pytest.raises(binding_module.ReplacementBindingError) as error:
_bind(guard_root, census=stale)
assert error.value.reason is binding_module.ReplacementBindingReason.INVALID_REQUEST
def test_no_admission_run_consumed_labels_and_custody_stays_available(guard_root, monkeypatch) -> None:
def forbidden(*args, **kwargs):
pytest.fail("admission authority was invoked during the replacement binding")
from benchmarks.valid.admission_orchestrator import AdmissionOrchestrator
from benchmarks.valid.durable_custody_store import S3DurableCustodyStore
monkeypatch.setattr(AdmissionOrchestrator, "preflight", forbidden)
monkeypatch.setattr(S3DurableCustodyStore, "compare_and_swap", forbidden)
source = (ROOT / "benchmarks/valid/replacement_freeze_binding.py").read_text()
for forbidden_symbol in (
"admission_orchestrator",
"admission_execution",
"admission_spend",
"arm_contract",
"compare_and_swap",
"record_population_use",
"authorize_evaluation",
"decode_arm_observation_set",
):
assert forbidden_symbol not in source
binding = _bind(guard_root)
log = empty_population_custody_log(binding.population_digest, CUSTODIAN)
binding_module.require_baseline_custody_available(binding, log)
assert log.status is PopulationStatus.AVAILABLE
assert log.receipt_count == 0 and log.receipts == ()
spent = replace(log, receipt_count=1)
with pytest.raises(binding_module.ReplacementBindingError) as error:
binding_module.require_baseline_custody_available(binding, spent)
assert error.value.reason is binding_module.ReplacementBindingReason.CUSTODY_NOT_AVAILABLE
other = empty_population_custody_log("4" * 64, CUSTODIAN)
with pytest.raises(binding_module.ReplacementBindingError):
binding_module.require_baseline_custody_available(binding, other)
def test_binding_decode_refuses_hostile_and_noncanonical_bytes(guard_root) -> None:
binding = _bind(guard_root)
good = binding_module.replacement_baseline_binding_bytes(binding)
for content in (b"", b"{", good + b" ", b'{"schema_version": "x", "value": NaN}'):
with pytest.raises(binding_module.ReplacementBindingStateError):
binding_store.decode_replacement_baseline_binding(content)
assert binding_store.decode_replacement_baseline_binding(good) == binding