mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 18:28:19 +00:00
feat(valid-detection-benchmark): 10.6 draw and validate ordinary-change population
This commit is contained in:
@@ -0,0 +1,420 @@
|
||||
"""Deterministic first-parent ordinary-change draws for the closed positive set.
|
||||
|
||||
The draw consumes only the durable accepted cohort ledgers whose combined
|
||||
closure is closed, the reviewed reservation census, and committed exclusion
|
||||
evidence. Each accepted positive receives its own first-parent ordinary walk
|
||||
below the exact vulnerable parent, with the fixes and every reviewed
|
||||
contaminated or excluded change refused by a closed rule before any count is
|
||||
accepted. No detector observation or admission label is ever opened here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
from benchmarks.valid.cohort_ingestion import CohortBatchOutcomeV1, CohortBatchStatus
|
||||
from benchmarks.valid.ecosystem_review import CanonicalEcosystem
|
||||
from benchmarks.valid.fix_site_catalog import FixSiteCandidateV1
|
||||
from benchmarks.valid.ground_truth_review import GroundTruthReviewV1, GroundTruthStatus
|
||||
from benchmarks.valid.ordinary_change_contract import (
|
||||
ContaminationTiming,
|
||||
OrdinaryContaminationReviewV1,
|
||||
OrdinaryDrawAssignmentV1,
|
||||
OrdinaryExclusionReason,
|
||||
OrdinaryExclusionV1,
|
||||
OrdinaryFixExclusionV1,
|
||||
OrdinaryPushV1,
|
||||
_digest,
|
||||
_push_value,
|
||||
_revision,
|
||||
contamination_review_bytes,
|
||||
)
|
||||
from benchmarks.valid.ordinary_draw_contract import (
|
||||
MINIMUM_ORDINARY_PER_POSITIVE,
|
||||
OrdinaryDrawError,
|
||||
OrdinaryDrawProvenanceV1,
|
||||
OrdinaryDrawReason,
|
||||
OrdinaryDrawRule,
|
||||
OrdinaryPopulationDrawV1,
|
||||
OrdinaryPopulationHistorySource,
|
||||
OrdinaryRepositoryReceiptV1,
|
||||
ordinary_population_draw,
|
||||
)
|
||||
from benchmarks.valid.positive_set_closure import (
|
||||
PositiveSetClosureStateError,
|
||||
PositiveSetClosureStatus,
|
||||
project_positive_set_closure,
|
||||
)
|
||||
from benchmarks.valid.reservation import ReservationCensusV1, ReservationError, census_bytes
|
||||
from openultrasast.core.canonical import bytes_digest, content_digest
|
||||
|
||||
|
||||
def _refused(reason: OrdinaryDrawReason, detail: str = "") -> OrdinaryDrawError:
|
||||
return OrdinaryDrawError(reason, detail)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _PositiveFacts:
|
||||
change_identity_digest: str
|
||||
candidate_digest: str
|
||||
ground_truth_review_digest: str
|
||||
canonical_repository: str
|
||||
network_identity_digest: str
|
||||
vulnerable_revision: str
|
||||
fixed_revision: str
|
||||
ecosystem: CanonicalEcosystem
|
||||
|
||||
|
||||
def _positive_facts(
|
||||
batches: Sequence[CohortBatchOutcomeV1],
|
||||
candidates_by_digest: Mapping[str, FixSiteCandidateV1],
|
||||
) -> tuple[_PositiveFacts, ...]:
|
||||
"""Derive per-positive repository facts only from accepted ledger evidence."""
|
||||
by_change: dict[str, _PositiveFacts] = {}
|
||||
try:
|
||||
for batch in batches:
|
||||
if batch.status is not CohortBatchStatus.ACCEPTED:
|
||||
continue
|
||||
ecosystem = CanonicalEcosystem(batch.ecosystem)
|
||||
for positive in batch.accepted_positives:
|
||||
candidate = candidates_by_digest.get(positive.candidate_digest)
|
||||
if candidate is None:
|
||||
raise _refused(OrdinaryDrawReason.CANDIDATE_MISSING)
|
||||
fact = _PositiveFacts(
|
||||
positive.change_identity_digest,
|
||||
positive.candidate_digest,
|
||||
positive.ground_truth_review_digest,
|
||||
candidate.canonical_repository,
|
||||
candidate.network_identity_digest,
|
||||
candidate.vulnerable.revision,
|
||||
candidate.fixed.revision,
|
||||
ecosystem,
|
||||
)
|
||||
existing = by_change.setdefault(fact.change_identity_digest, fact)
|
||||
if existing != fact:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST)
|
||||
except OrdinaryDrawError:
|
||||
raise
|
||||
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST) from error
|
||||
return tuple(sorted(by_change.values(), key=lambda fact: fact.change_identity_digest))
|
||||
|
||||
|
||||
def _require_single_ecosystem(facts: Sequence[_PositiveFacts]) -> None:
|
||||
seen: dict[str, CanonicalEcosystem] = {}
|
||||
for fact in facts:
|
||||
existing = seen.setdefault(fact.network_identity_digest, fact.ecosystem)
|
||||
if existing != fact.ecosystem:
|
||||
raise _refused(OrdinaryDrawReason.ECOSYSTEM_SPLIT)
|
||||
|
||||
|
||||
def _require_unreserved(facts: Sequence[_PositiveFacts], census: ReservationCensusV1) -> None:
|
||||
reserved = set(census.reserved_network_digests)
|
||||
for fact in facts:
|
||||
if fact.network_identity_digest in reserved:
|
||||
raise _refused(OrdinaryDrawReason.RESERVED_REPOSITORY)
|
||||
|
||||
|
||||
def _contamination_index(reviews: Iterable[OrdinaryContaminationReviewV1]) -> dict[tuple[str, str], OrdinaryContaminationReviewV1]:
|
||||
index: dict[tuple[str, str], OrdinaryContaminationReviewV1] = {}
|
||||
for review in reviews:
|
||||
try:
|
||||
contamination_review_bytes(review)
|
||||
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST) from error
|
||||
if review.timing is not ContaminationTiming.PRE_FREEZE:
|
||||
raise _refused(OrdinaryDrawReason.POST_FREEZE_CONTAMINATION)
|
||||
key = (review.network_identity_digest, review.tip_revision)
|
||||
existing = index.get(key)
|
||||
if existing is not None and existing != review:
|
||||
raise _refused(OrdinaryDrawReason.CONFLICTING_EXCLUSION_EVIDENCE)
|
||||
index[key] = review
|
||||
return index
|
||||
|
||||
|
||||
def _excluded_review_index(reviews: Iterable[GroundTruthReviewV1]) -> dict[tuple[str, str], str]:
|
||||
index: dict[tuple[str, str], str] = {}
|
||||
for review in reviews:
|
||||
try:
|
||||
if review.status is not GroundTruthStatus.EXCLUDED or review.exclusion_reason is None:
|
||||
raise TypeError("excluded review required")
|
||||
_digest(review.network_identity_digest, "review network identity digest")
|
||||
_digest(review.review_digest, "review digest")
|
||||
for revision in (review.vulnerable_revision, review.fixed_revision):
|
||||
_revision(revision, "reviewed revision")
|
||||
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST) from error
|
||||
for revision in (review.vulnerable_revision, review.fixed_revision):
|
||||
key = (review.network_identity_digest, revision)
|
||||
existing = index.get(key)
|
||||
if existing is not None and existing != review.review_digest:
|
||||
raise _refused(OrdinaryDrawReason.CONFLICTING_EXCLUSION_EVIDENCE)
|
||||
index[key] = review.review_digest
|
||||
return index
|
||||
|
||||
|
||||
def _fix_ledger(facts: Sequence[_PositiveFacts]) -> tuple[tuple[OrdinaryFixExclusionV1, ...], dict[tuple[str, str], str]]:
|
||||
exclusions: set[OrdinaryFixExclusionV1] = set()
|
||||
keys: dict[tuple[str, str], str] = {}
|
||||
for fact in facts:
|
||||
exclusion = OrdinaryFixExclusionV1(
|
||||
fact.network_identity_digest,
|
||||
fact.fixed_revision,
|
||||
fact.change_identity_digest,
|
||||
fact.ground_truth_review_digest,
|
||||
)
|
||||
exclusions.add(exclusion)
|
||||
keys[(fact.network_identity_digest, fact.fixed_revision)] = fact.ground_truth_review_digest
|
||||
ordered = tuple(sorted(exclusions))
|
||||
if len(ordered) != len(facts):
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST)
|
||||
return ordered, keys
|
||||
|
||||
|
||||
def _sources_and_receipts(
|
||||
facts: Sequence[_PositiveFacts],
|
||||
history_by_network: Mapping[str, OrdinaryPopulationHistorySource],
|
||||
) -> tuple[dict[str, OrdinaryPopulationHistorySource], tuple[OrdinaryRepositoryReceiptV1, ...]]:
|
||||
sources: dict[str, OrdinaryPopulationHistorySource] = {}
|
||||
receipts: dict[str, OrdinaryRepositoryReceiptV1] = {}
|
||||
for fact in facts:
|
||||
source = history_by_network.get(fact.network_identity_digest)
|
||||
if source is None:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST)
|
||||
if (source.canonical_repository, source.network_identity_digest) != (
|
||||
fact.canonical_repository,
|
||||
fact.network_identity_digest,
|
||||
):
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST)
|
||||
try:
|
||||
_digest(source.source_digest, "history source digest")
|
||||
except (AttributeError, TypeError, ValueError) as error:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST) from error
|
||||
sources[fact.network_identity_digest] = source
|
||||
if fact.network_identity_digest not in receipts:
|
||||
manifest = source.reader.repository_bytes(fact.canonical_repository)
|
||||
if not isinstance(manifest, bytes) or not manifest:
|
||||
raise _refused(OrdinaryDrawReason.REPOSITORY_UNREADABLE)
|
||||
receipts[fact.network_identity_digest] = OrdinaryRepositoryReceiptV1(
|
||||
fact.canonical_repository,
|
||||
fact.network_identity_digest,
|
||||
len(manifest),
|
||||
bytes_digest(manifest),
|
||||
)
|
||||
return sources, tuple(sorted(receipts.values()))
|
||||
|
||||
|
||||
def _ordinary_push(
|
||||
fact: _PositiveFacts,
|
||||
source: OrdinaryPopulationHistorySource,
|
||||
base: str,
|
||||
tip: str,
|
||||
content: bytes,
|
||||
) -> OrdinaryPushV1:
|
||||
try:
|
||||
draft = OrdinaryPushV1(
|
||||
fact.canonical_repository,
|
||||
fact.network_identity_digest,
|
||||
fact.ecosystem,
|
||||
base,
|
||||
tip,
|
||||
len(content),
|
||||
bytes_digest(content),
|
||||
source.source_digest,
|
||||
"",
|
||||
)
|
||||
return OrdinaryPushV1(**{**vars(draft), "push_digest": content_digest(_push_value(draft, include_digest=False))})
|
||||
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST) from error
|
||||
|
||||
|
||||
def _row(network: str, tip: str, rule: OrdinaryDrawRule, evidence: str) -> OrdinaryDrawProvenanceV1:
|
||||
return OrdinaryDrawProvenanceV1(network, tip, rule, evidence)
|
||||
|
||||
|
||||
def _first_parent(value: object) -> str:
|
||||
try:
|
||||
return _revision(value, "ordinary first parent")
|
||||
except (AttributeError, TypeError, ValueError) as error:
|
||||
raise _refused(OrdinaryDrawReason.HISTORY_UNREADABLE) from error
|
||||
|
||||
|
||||
def _consider_tip(
|
||||
fact: _PositiveFacts,
|
||||
source: OrdinaryPopulationHistorySource,
|
||||
base: str,
|
||||
tip: str,
|
||||
*,
|
||||
fix_keys: Mapping[tuple[str, str], str],
|
||||
contamination: Mapping[tuple[str, str], OrdinaryContaminationReviewV1],
|
||||
excluded_reviews: Mapping[tuple[str, str], str],
|
||||
) -> tuple[OrdinaryPushV1 | None, OrdinaryDrawProvenanceV1, OrdinaryExclusionV1 | None]:
|
||||
network = fact.network_identity_digest
|
||||
key = (network, tip)
|
||||
if key in fix_keys:
|
||||
return None, _row(network, tip, OrdinaryDrawRule.EXCLUDED_ACCEPTED_FIX, fix_keys[key]), None
|
||||
content = source.reader.change_bytes(tip)
|
||||
if not isinstance(content, bytes) or not content:
|
||||
raise _refused(OrdinaryDrawReason.HISTORY_UNREADABLE)
|
||||
review = contamination.get(key)
|
||||
excluded = excluded_reviews.get(key)
|
||||
if review is not None and excluded is not None:
|
||||
raise _refused(OrdinaryDrawReason.CONFLICTING_EXCLUSION_EVIDENCE)
|
||||
if review is not None:
|
||||
exclusion = OrdinaryExclusionV1(network, tip, OrdinaryExclusionReason.REVIEWED_SECURITY_DEFECT, review.review_digest)
|
||||
return None, _row(network, tip, OrdinaryDrawRule.EXCLUDED_REVIEWED_CONTAMINATION, review.review_digest), exclusion
|
||||
if excluded is not None:
|
||||
return None, _row(network, tip, OrdinaryDrawRule.EXCLUDED_REVIEWED_CHANGE, excluded), None
|
||||
push = _ordinary_push(fact, source, base, tip, content)
|
||||
return push, _row(network, tip, OrdinaryDrawRule.ELIGIBLE_FIRST_PARENT_ORDINARY, push.push_digest), None
|
||||
|
||||
|
||||
def _walk_positive(
|
||||
fact: _PositiveFacts,
|
||||
source: OrdinaryPopulationHistorySource,
|
||||
*,
|
||||
fix_keys: Mapping[tuple[str, str], str],
|
||||
contamination: Mapping[tuple[str, str], OrdinaryContaminationReviewV1],
|
||||
excluded_reviews: Mapping[tuple[str, str], str],
|
||||
required: int,
|
||||
) -> tuple[list[OrdinaryPushV1], set[OrdinaryDrawProvenanceV1], set[OrdinaryExclusionV1]]:
|
||||
parents = tuple(source.reader.parents(fact.fixed_revision))
|
||||
if not parents or parents[0] != fact.vulnerable_revision:
|
||||
raise _refused(OrdinaryDrawReason.HISTORY_UNBOUND)
|
||||
pushes: list[OrdinaryPushV1] = []
|
||||
provenance: set[OrdinaryDrawProvenanceV1] = set()
|
||||
exclusions: set[OrdinaryExclusionV1] = set()
|
||||
tip = fact.vulnerable_revision
|
||||
seen = {fact.fixed_revision}
|
||||
while len(pushes) < required:
|
||||
if tip in seen:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST)
|
||||
seen.add(tip)
|
||||
ancestors = tuple(source.reader.parents(tip))
|
||||
if not ancestors:
|
||||
break
|
||||
base = _first_parent(ancestors[0])
|
||||
push, row, exclusion = _consider_tip(
|
||||
fact,
|
||||
source,
|
||||
base,
|
||||
tip,
|
||||
fix_keys=fix_keys,
|
||||
contamination=contamination,
|
||||
excluded_reviews=excluded_reviews,
|
||||
)
|
||||
if push is not None:
|
||||
pushes.append(push)
|
||||
if exclusion is not None:
|
||||
exclusions.add(exclusion)
|
||||
provenance.add(row)
|
||||
tip = base
|
||||
if len(pushes) < required:
|
||||
raise _refused(OrdinaryDrawReason.INSUFFICIENT_HISTORY, f" supplies {len(pushes)} of {required}")
|
||||
return pushes, provenance, exclusions
|
||||
|
||||
|
||||
def _collect_draws(
|
||||
facts: Sequence[_PositiveFacts],
|
||||
sources: Mapping[str, OrdinaryPopulationHistorySource],
|
||||
*,
|
||||
fix_keys: Mapping[tuple[str, str], str],
|
||||
contamination: Mapping[tuple[str, str], OrdinaryContaminationReviewV1],
|
||||
excluded_reviews: Mapping[tuple[str, str], str],
|
||||
required: int,
|
||||
) -> tuple[dict[str, OrdinaryPushV1], set[OrdinaryDrawAssignmentV1], set[OrdinaryDrawProvenanceV1], set[OrdinaryExclusionV1]]:
|
||||
pushes_by_digest: dict[str, OrdinaryPushV1] = {}
|
||||
assignments: set[OrdinaryDrawAssignmentV1] = set()
|
||||
provenance: set[OrdinaryDrawProvenanceV1] = set()
|
||||
exclusions: set[OrdinaryExclusionV1] = set()
|
||||
for fact in facts:
|
||||
drawn, rows, excluded = _walk_positive(
|
||||
fact,
|
||||
sources[fact.network_identity_digest],
|
||||
fix_keys=fix_keys,
|
||||
contamination=contamination,
|
||||
excluded_reviews=excluded_reviews,
|
||||
required=required,
|
||||
)
|
||||
for push in drawn:
|
||||
existing = pushes_by_digest.get(push.push_digest)
|
||||
if existing is not None and existing != push:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST)
|
||||
pushes_by_digest[push.push_digest] = push
|
||||
assignments.add(
|
||||
OrdinaryDrawAssignmentV1(fact.change_identity_digest, fact.network_identity_digest, fact.ecosystem, push.push_digest)
|
||||
)
|
||||
provenance.update(rows)
|
||||
exclusions.update(excluded)
|
||||
supplied = {review.review_digest for review in contamination.values()}
|
||||
applied = {row.contamination_review_digest for row in exclusions}
|
||||
if supplied != applied:
|
||||
raise _refused(OrdinaryDrawReason.CONFLICTING_EXCLUSION_EVIDENCE)
|
||||
return pushes_by_digest, assignments, provenance, exclusions
|
||||
|
||||
|
||||
def draw_ordinary_population(
|
||||
batches: Sequence[CohortBatchOutcomeV1],
|
||||
*,
|
||||
candidates_by_digest: Mapping[str, FixSiteCandidateV1],
|
||||
history_by_network: Mapping[str, OrdinaryPopulationHistorySource],
|
||||
contamination_reviews: Iterable[OrdinaryContaminationReviewV1] = (),
|
||||
excluded_reviews: Iterable[GroundTruthReviewV1] = (),
|
||||
reservation_census: ReservationCensusV1,
|
||||
required_per_positive: int = MINIMUM_ORDINARY_PER_POSITIVE,
|
||||
policy_digest: str,
|
||||
) -> OrdinaryPopulationDrawV1:
|
||||
"""Draw the ordinary population for every accepted positive of a closed set.
|
||||
|
||||
The draw is label-blind and detector-blind by construction: only durable
|
||||
accepted ledger facts, reviewed exclusion evidence, the reservation census,
|
||||
and readable nonzero first-parent histories enter the walk.
|
||||
"""
|
||||
if type(required_per_positive) is not int or required_per_positive < MINIMUM_ORDINARY_PER_POSITIVE:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST)
|
||||
try:
|
||||
census_bytes(reservation_census)
|
||||
policy = _digest(policy_digest, "ordinary population draw policy digest")
|
||||
except (AttributeError, ReservationError, TypeError, ValueError) as error:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST) from error
|
||||
try:
|
||||
closure = project_positive_set_closure(batches)
|
||||
except PositiveSetClosureStateError as error:
|
||||
raise _refused(OrdinaryDrawReason.INVALID_REQUEST) from error
|
||||
if closure.status is not PositiveSetClosureStatus.CLOSED:
|
||||
raise _refused(OrdinaryDrawReason.POSITIVE_SET_NOT_CLOSED)
|
||||
facts = _positive_facts(batches, candidates_by_digest)
|
||||
_require_single_ecosystem(facts)
|
||||
_require_unreserved(facts, reservation_census)
|
||||
contamination = _contamination_index(contamination_reviews)
|
||||
excluded_index = _excluded_review_index(excluded_reviews)
|
||||
fix_exclusions, fix_keys = _fix_ledger(facts)
|
||||
sources, receipts = _sources_and_receipts(facts, history_by_network)
|
||||
pushes, assignments, provenance, exclusions = _collect_draws(
|
||||
facts,
|
||||
sources,
|
||||
fix_keys=fix_keys,
|
||||
contamination=contamination,
|
||||
excluded_reviews=excluded_index,
|
||||
required=required_per_positive,
|
||||
)
|
||||
counts = Counter(row.positive_change_digest for row in assignments)
|
||||
return ordinary_population_draw(
|
||||
required_per_positive=required_per_positive,
|
||||
policy_digest=policy,
|
||||
closure_digest=closure.closure_digest,
|
||||
reservation_census_digest=reservation_census.census_digest,
|
||||
positive_change_digests=tuple(sorted(counts)),
|
||||
per_positive_counts=tuple((digest, counts[digest]) for digest in sorted(counts)),
|
||||
repository_receipts=receipts,
|
||||
fix_exclusions=fix_exclusions,
|
||||
pushes=tuple(pushes[key] for key in sorted(pushes)),
|
||||
assignments=tuple(sorted(assignments)),
|
||||
exclusions=tuple(sorted(exclusions)),
|
||||
provenance=tuple(sorted(provenance)),
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["OrdinaryPopulationHistorySource", "draw_ordinary_population"]
|
||||
@@ -0,0 +1,402 @@
|
||||
"""Canonical contracts for ordinary population draws over the closed positive set.
|
||||
|
||||
This module owns the closed vocabulary, dataclasses, canonical value encoding,
|
||||
digest binding, and assembler for one ordinary-change population draw. The
|
||||
drawing machinery lives in ``ordinary_draw``; durable persistence lives in
|
||||
``ordinary_draw_store``. No detector observation or admission label appears in
|
||||
any serialized field.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass, replace
|
||||
from enum import StrEnum
|
||||
from typing import Protocol
|
||||
|
||||
from benchmarks.valid.ecosystem_review import CanonicalEcosystem
|
||||
from benchmarks.valid.ordinary_change_contract import (
|
||||
OrdinaryDrawAssignmentV1,
|
||||
OrdinaryExclusionV1,
|
||||
OrdinaryFixExclusionV1,
|
||||
OrdinaryPushV1,
|
||||
_assignment_value,
|
||||
_exclusion_value,
|
||||
_fix_exclusion_value,
|
||||
_push_value,
|
||||
_revision,
|
||||
)
|
||||
from openultrasast.core.canonical import JsonValue, canonical_bytes, content_digest
|
||||
|
||||
ORDINARY_POPULATION_DRAW_SCHEMA = "openultrasast.valid-detection-benchmark.ordinary-population-draw.v1"
|
||||
MINIMUM_ORDINARY_PER_POSITIVE = 20
|
||||
_HEX_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||
|
||||
|
||||
class OrdinaryDrawReason(StrEnum):
|
||||
"""Closed draw refusal reasons; no free-form failure text is serializable."""
|
||||
|
||||
INVALID_REQUEST = "invalid_request"
|
||||
POSITIVE_SET_NOT_CLOSED = "positive_set_not_closed"
|
||||
CANDIDATE_MISSING = "candidate_missing"
|
||||
RESERVED_REPOSITORY = "reserved_repository"
|
||||
REPOSITORY_UNREADABLE = "repository_unreadable"
|
||||
HISTORY_UNBOUND = "history_unbound"
|
||||
HISTORY_UNREADABLE = "history_unreadable"
|
||||
INSUFFICIENT_HISTORY = "insufficient_history"
|
||||
ECOSYSTEM_SPLIT = "ecosystem_split"
|
||||
CONFLICTING_EXCLUSION_EVIDENCE = "conflicting_exclusion_evidence"
|
||||
POST_FREEZE_CONTAMINATION = "post_freeze_contamination"
|
||||
|
||||
|
||||
class OrdinaryDrawError(RuntimeError):
|
||||
"""Refuse one draw step with a closed reason and no caller content."""
|
||||
|
||||
def __init__(self, reason: OrdinaryDrawReason, detail: str = "") -> None:
|
||||
self.reason = reason
|
||||
super().__init__(f"ordinary_draw_{reason.value}{detail}")
|
||||
|
||||
|
||||
class OrdinaryDrawStateReason(StrEnum):
|
||||
STATE_UNREADABLE = "state_unreadable"
|
||||
STATE_MISMATCH = "state_mismatch"
|
||||
|
||||
|
||||
class OrdinaryDrawStateError(ValueError):
|
||||
"""Closed draw-state refusal carrying one structural reason."""
|
||||
|
||||
def __init__(self, reason: OrdinaryDrawStateReason) -> None:
|
||||
self.reason = reason
|
||||
super().__init__(f"ordinary draw state {reason.value}")
|
||||
|
||||
|
||||
def _mismatch() -> OrdinaryDrawStateError:
|
||||
return OrdinaryDrawStateError(OrdinaryDrawStateReason.STATE_MISMATCH)
|
||||
|
||||
|
||||
class OrdinaryDrawRule(StrEnum):
|
||||
"""Closed eligibility rules recorded for every considered change."""
|
||||
|
||||
ELIGIBLE_FIRST_PARENT_ORDINARY = "eligible_first_parent_ordinary"
|
||||
EXCLUDED_ACCEPTED_FIX = "excluded_accepted_fix"
|
||||
EXCLUDED_REVIEWED_CONTAMINATION = "excluded_reviewed_contamination"
|
||||
EXCLUDED_REVIEWED_CHANGE = "excluded_reviewed_change"
|
||||
|
||||
|
||||
@dataclass(frozen=True, order=True)
|
||||
class OrdinaryDrawProvenanceV1:
|
||||
network_identity_digest: str
|
||||
tip_revision: str
|
||||
rule: OrdinaryDrawRule
|
||||
evidence_digest: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, order=True)
|
||||
class OrdinaryRepositoryReceiptV1:
|
||||
canonical_repository: str
|
||||
network_identity_digest: str
|
||||
byte_length: int
|
||||
repository_content_digest: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OrdinaryPopulationDrawV1:
|
||||
required_per_positive: int
|
||||
policy_digest: str
|
||||
closure_digest: str
|
||||
reservation_census_digest: str
|
||||
positive_change_digests: tuple[str, ...]
|
||||
per_positive_counts: tuple[tuple[str, int], ...]
|
||||
repository_receipts: tuple[OrdinaryRepositoryReceiptV1, ...]
|
||||
fix_exclusions: tuple[OrdinaryFixExclusionV1, ...]
|
||||
pushes: tuple[OrdinaryPushV1, ...]
|
||||
assignments: tuple[OrdinaryDrawAssignmentV1, ...]
|
||||
exclusions: tuple[OrdinaryExclusionV1, ...]
|
||||
provenance: tuple[OrdinaryDrawProvenanceV1, ...]
|
||||
provenance_digest: str
|
||||
draw_digest: str
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_validate_draw(self)
|
||||
|
||||
|
||||
class OrdinaryPopulationHistoryReader(Protocol):
|
||||
def parents(self, revision: str) -> Sequence[str]: ...
|
||||
|
||||
def change_bytes(self, revision: str) -> bytes | None: ...
|
||||
|
||||
def repository_bytes(self, canonical_repository: str) -> bytes | None: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OrdinaryPopulationHistorySource:
|
||||
reader: OrdinaryPopulationHistoryReader
|
||||
canonical_repository: str
|
||||
network_identity_digest: str
|
||||
source_digest: str
|
||||
|
||||
|
||||
def _closed_digest(value: object) -> str:
|
||||
if type(value) is not str or _HEX_DIGEST.fullmatch(value) is None:
|
||||
raise _mismatch()
|
||||
return value
|
||||
|
||||
|
||||
def _closed_text(value: object) -> str:
|
||||
if type(value) is not str or not value or len(value) > 200:
|
||||
raise _mismatch()
|
||||
return value
|
||||
|
||||
|
||||
def _rule_value(row: OrdinaryDrawProvenanceV1) -> dict[str, JsonValue]:
|
||||
return {
|
||||
"network_identity_digest": _closed_digest(row.network_identity_digest),
|
||||
"tip_revision": _revision(row.tip_revision, "provenance tip revision"),
|
||||
"rule": OrdinaryDrawRule(row.rule).value,
|
||||
"evidence_digest": _closed_digest(row.evidence_digest),
|
||||
}
|
||||
|
||||
|
||||
def _receipt_value(receipt: OrdinaryRepositoryReceiptV1) -> dict[str, JsonValue]:
|
||||
if type(receipt.byte_length) is not int or receipt.byte_length <= 0:
|
||||
raise _mismatch()
|
||||
return {
|
||||
"canonical_repository": _closed_text(receipt.canonical_repository),
|
||||
"network_identity_digest": _closed_digest(receipt.network_identity_digest),
|
||||
"byte_length": receipt.byte_length,
|
||||
"repository_content_digest": _closed_digest(receipt.repository_content_digest),
|
||||
}
|
||||
|
||||
|
||||
def _count_value(pairs: tuple[tuple[str, int], ...]) -> tuple[dict[str, JsonValue], ...]:
|
||||
return tuple({"change_identity_digest": digest, "eligible_pushes": count} for digest, count in pairs)
|
||||
|
||||
|
||||
def _draw_value(item: OrdinaryPopulationDrawV1, *, include_digest: bool) -> dict[str, JsonValue]:
|
||||
value: dict[str, JsonValue] = {
|
||||
"schema_version": ORDINARY_POPULATION_DRAW_SCHEMA,
|
||||
"required_per_positive": item.required_per_positive,
|
||||
"policy_digest": item.policy_digest,
|
||||
"closure_digest": item.closure_digest,
|
||||
"reservation_census_digest": item.reservation_census_digest,
|
||||
"positive_change_digests": item.positive_change_digests,
|
||||
"per_positive_counts": _count_value(item.per_positive_counts),
|
||||
"repository_receipts": tuple(_receipt_value(receipt) for receipt in item.repository_receipts),
|
||||
"fix_exclusions": tuple(_fix_exclusion_value(row) for row in item.fix_exclusions),
|
||||
"pushes": tuple(_push_value(push, include_digest=True) for push in item.pushes),
|
||||
"assignments": tuple(_assignment_value(row) for row in item.assignments),
|
||||
"exclusions": tuple(_exclusion_value(row) for row in item.exclusions),
|
||||
"provenance": tuple(_rule_value(row) for row in item.provenance),
|
||||
"provenance_digest": item.provenance_digest,
|
||||
}
|
||||
if include_digest:
|
||||
value["draw_digest"] = item.draw_digest
|
||||
return value
|
||||
|
||||
|
||||
def _validate_scalars(item: OrdinaryPopulationDrawV1) -> None:
|
||||
if type(item.required_per_positive) is not int or item.required_per_positive < MINIMUM_ORDINARY_PER_POSITIVE:
|
||||
raise _mismatch()
|
||||
for field in ("policy_digest", "closure_digest", "reservation_census_digest", "provenance_digest", "draw_digest"):
|
||||
if getattr(item, field):
|
||||
_closed_digest(getattr(item, field))
|
||||
if item.positive_change_digests != tuple(sorted(set(item.positive_change_digests))):
|
||||
raise _mismatch()
|
||||
for digest in item.positive_change_digests:
|
||||
_closed_digest(digest)
|
||||
for pair in item.per_positive_counts:
|
||||
if type(pair) is not tuple or len(pair) != 2 or type(pair[1]) is not int or pair[1] < item.required_per_positive:
|
||||
raise _mismatch()
|
||||
_closed_digest(pair[0])
|
||||
if tuple(digest for digest, _ in item.per_positive_counts) != tuple(sorted({digest for digest, _ in item.per_positive_counts})):
|
||||
raise _mismatch()
|
||||
if set(digest for digest, _ in item.per_positive_counts) != set(item.positive_change_digests):
|
||||
raise _mismatch()
|
||||
|
||||
|
||||
def _validate_collections(item: OrdinaryPopulationDrawV1) -> None:
|
||||
if item.repository_receipts != tuple(sorted(set(item.repository_receipts))):
|
||||
raise _mismatch()
|
||||
if len({receipt.network_identity_digest for receipt in item.repository_receipts}) != len(item.repository_receipts):
|
||||
raise _mismatch()
|
||||
if item.fix_exclusions != tuple(sorted(set(item.fix_exclusions))):
|
||||
raise _mismatch()
|
||||
if item.pushes != tuple(sorted(set(item.pushes), key=lambda push: push.push_digest)):
|
||||
raise _mismatch()
|
||||
if item.assignments != tuple(sorted(set(item.assignments))):
|
||||
raise _mismatch()
|
||||
if item.exclusions != tuple(sorted(set(item.exclusions))):
|
||||
raise _mismatch()
|
||||
if item.provenance != tuple(sorted(set(item.provenance))):
|
||||
raise _mismatch()
|
||||
|
||||
|
||||
def _validate_bindings(item: OrdinaryPopulationDrawV1) -> None:
|
||||
pushes = {push.push_digest: push for push in item.pushes}
|
||||
for push in item.pushes:
|
||||
if push.push_digest != content_digest(_push_value(push, include_digest=False)):
|
||||
raise _mismatch()
|
||||
counts = Counter(row.positive_change_digest for row in item.assignments)
|
||||
for row in item.assignments:
|
||||
bound = pushes.get(row.push_digest)
|
||||
if bound is None or (row.network_identity_digest, row.ecosystem) != (bound.network_identity_digest, bound.ecosystem):
|
||||
raise _mismatch()
|
||||
if dict(item.per_positive_counts) != dict(sorted(counts.items())):
|
||||
raise _mismatch()
|
||||
fixed_positives = tuple(sorted(row.positive_change_digest for row in item.fix_exclusions))
|
||||
if fixed_positives != item.positive_change_digests:
|
||||
raise _mismatch()
|
||||
if set(counts) != set(item.positive_change_digests):
|
||||
raise _mismatch()
|
||||
ecosystems: dict[str, str] = {}
|
||||
for push in item.pushes:
|
||||
ecosystem = CanonicalEcosystem(push.ecosystem).value
|
||||
if ecosystems.setdefault(push.network_identity_digest, ecosystem) != ecosystem:
|
||||
raise _mismatch()
|
||||
|
||||
|
||||
def _validate_provenance_rows(item: OrdinaryPopulationDrawV1) -> None:
|
||||
eligible_rule = OrdinaryDrawRule.ELIGIBLE_FIRST_PARENT_ORDINARY
|
||||
eligible = {
|
||||
(row.network_identity_digest, row.tip_revision): row.evidence_digest
|
||||
for row in item.provenance
|
||||
if row.rule is eligible_rule
|
||||
}
|
||||
if set(eligible) != {(push.network_identity_digest, push.tip_revision) for push in item.pushes}:
|
||||
raise _mismatch()
|
||||
for push in item.pushes:
|
||||
if eligible[(push.network_identity_digest, push.tip_revision)] != push.push_digest:
|
||||
raise _mismatch()
|
||||
refused = {
|
||||
(row.network_identity_digest, row.tip_revision)
|
||||
for row in item.provenance
|
||||
if row.rule is not eligible_rule
|
||||
}
|
||||
if refused & set(eligible):
|
||||
raise _mismatch()
|
||||
selected = {(push.network_identity_digest, push.tip_revision) for push in item.pushes}
|
||||
excluded = {(row.network_identity_digest, row.tip_revision) for row in item.exclusions}
|
||||
fixed = {(row.network_identity_digest, row.fixed_revision) for row in item.fix_exclusions}
|
||||
if selected & (excluded | fixed):
|
||||
raise _mismatch()
|
||||
|
||||
|
||||
def _provenance_binding(item: OrdinaryPopulationDrawV1) -> str:
|
||||
eligible_rule = OrdinaryDrawRule.ELIGIBLE_FIRST_PARENT_ORDINARY
|
||||
reviewed_evidence = tuple(sorted({row.evidence_digest for row in item.provenance if row.rule is not eligible_rule}))
|
||||
return content_digest(
|
||||
{
|
||||
"history_sources": tuple(
|
||||
sorted({(push.canonical_repository, push.network_identity_digest, push.history_source_digest) for push in item.pushes})
|
||||
),
|
||||
"repository_receipts": tuple(_receipt_value(receipt) for receipt in item.repository_receipts),
|
||||
"accepted_fix_exclusions": tuple(_fix_exclusion_value(row) for row in item.fix_exclusions),
|
||||
"reviewed_exclusion_evidence": reviewed_evidence,
|
||||
"reservation_census_digest": item.reservation_census_digest,
|
||||
"closure_digest": item.closure_digest,
|
||||
"policy_digest": item.policy_digest,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _validate_draw(item: OrdinaryPopulationDrawV1) -> None:
|
||||
try:
|
||||
_validate_scalars(item)
|
||||
_validate_collections(item)
|
||||
_validate_bindings(item)
|
||||
_validate_provenance_rows(item)
|
||||
if item.provenance_digest and item.provenance_digest != _provenance_binding(item):
|
||||
raise _mismatch()
|
||||
except OrdinaryDrawStateError:
|
||||
raise
|
||||
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||
raise _mismatch() from error
|
||||
|
||||
|
||||
def ordinary_population_draw_value(item: OrdinaryPopulationDrawV1) -> dict[str, JsonValue]:
|
||||
"""Canonical draw payload used for durable persistence and exact rereads."""
|
||||
try:
|
||||
return _draw_value(item, include_digest=True)
|
||||
except OrdinaryDrawStateError:
|
||||
raise
|
||||
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||
raise _mismatch() from error
|
||||
|
||||
|
||||
def ordinary_population_draw_bytes(item: OrdinaryPopulationDrawV1) -> bytes:
|
||||
"""Encode a digest-consistent draw decision as canonical bytes."""
|
||||
try:
|
||||
if item.draw_digest != content_digest(_draw_value(item, include_digest=False)):
|
||||
raise _mismatch()
|
||||
if item.provenance_digest != _provenance_binding(item):
|
||||
raise _mismatch()
|
||||
return canonical_bytes(_draw_value(item, include_digest=True))
|
||||
except OrdinaryDrawStateError:
|
||||
raise
|
||||
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||
raise _mismatch() from error
|
||||
|
||||
|
||||
def ordinary_population_draw(
|
||||
*,
|
||||
required_per_positive: int,
|
||||
policy_digest: str,
|
||||
closure_digest: str,
|
||||
reservation_census_digest: str,
|
||||
positive_change_digests: Iterable[str],
|
||||
per_positive_counts: Iterable[tuple[str, int]],
|
||||
repository_receipts: Iterable[OrdinaryRepositoryReceiptV1],
|
||||
fix_exclusions: Iterable[OrdinaryFixExclusionV1],
|
||||
pushes: Iterable[OrdinaryPushV1],
|
||||
assignments: Iterable[OrdinaryDrawAssignmentV1],
|
||||
exclusions: Iterable[OrdinaryExclusionV1],
|
||||
provenance: Iterable[OrdinaryDrawProvenanceV1],
|
||||
) -> OrdinaryPopulationDrawV1:
|
||||
"""Assemble one durable ordinary-change draw bound to its exact evidence."""
|
||||
try:
|
||||
draft = OrdinaryPopulationDrawV1(
|
||||
required_per_positive,
|
||||
policy_digest,
|
||||
closure_digest,
|
||||
reservation_census_digest,
|
||||
tuple(positive_change_digests),
|
||||
tuple(per_positive_counts),
|
||||
tuple(repository_receipts),
|
||||
tuple(fix_exclusions),
|
||||
tuple(pushes),
|
||||
tuple(assignments),
|
||||
tuple(exclusions),
|
||||
tuple(provenance),
|
||||
"",
|
||||
"",
|
||||
)
|
||||
except OrdinaryDrawStateError:
|
||||
raise
|
||||
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||
raise _mismatch() from error
|
||||
try:
|
||||
bound = replace(draft, provenance_digest=_provenance_binding(draft))
|
||||
return replace(bound, draw_digest=content_digest(_draw_value(bound, include_digest=False)))
|
||||
except OrdinaryDrawStateError:
|
||||
raise
|
||||
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||
raise _mismatch() from error
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MINIMUM_ORDINARY_PER_POSITIVE",
|
||||
"ORDINARY_POPULATION_DRAW_SCHEMA",
|
||||
"OrdinaryDrawError",
|
||||
"OrdinaryDrawProvenanceV1",
|
||||
"OrdinaryDrawReason",
|
||||
"OrdinaryDrawRule",
|
||||
"OrdinaryDrawStateError",
|
||||
"OrdinaryDrawStateReason",
|
||||
"OrdinaryPopulationDrawV1",
|
||||
"OrdinaryPopulationHistorySource",
|
||||
"ordinary_population_draw",
|
||||
"ordinary_population_draw_bytes",
|
||||
"ordinary_population_draw_value",
|
||||
]
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Durable persistence, hostile decode, and replay for ordinary population draws."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
from benchmarks.valid.artifact_repository import ArtifactReadAuthority, S3ArtifactRepository
|
||||
from benchmarks.valid.ecosystem_review import CanonicalEcosystem
|
||||
from benchmarks.valid.ordinary_change_contract import (
|
||||
OrdinaryDrawAssignmentV1,
|
||||
OrdinaryExclusionReason,
|
||||
OrdinaryExclusionV1,
|
||||
OrdinaryFixExclusionV1,
|
||||
OrdinaryPushV1,
|
||||
)
|
||||
from benchmarks.valid.ordinary_draw_contract import (
|
||||
ORDINARY_POPULATION_DRAW_SCHEMA,
|
||||
OrdinaryDrawProvenanceV1,
|
||||
OrdinaryDrawRule,
|
||||
OrdinaryDrawStateError,
|
||||
OrdinaryDrawStateReason,
|
||||
OrdinaryPopulationDrawV1,
|
||||
OrdinaryRepositoryReceiptV1,
|
||||
ordinary_population_draw,
|
||||
ordinary_population_draw_bytes,
|
||||
ordinary_population_draw_value,
|
||||
)
|
||||
from benchmarks.valid.replacement_artifact_contract import (
|
||||
ArtifactAccessClass,
|
||||
ArtifactKind,
|
||||
ArtifactReference,
|
||||
artifact_reference,
|
||||
canonical_artifact_bytes,
|
||||
)
|
||||
from openultrasast.core.canonical import canonical_bytes
|
||||
|
||||
_DRAW_KEYS = frozenset(
|
||||
{
|
||||
"schema_version",
|
||||
"required_per_positive",
|
||||
"policy_digest",
|
||||
"closure_digest",
|
||||
"reservation_census_digest",
|
||||
"positive_change_digests",
|
||||
"per_positive_counts",
|
||||
"repository_receipts",
|
||||
"fix_exclusions",
|
||||
"pushes",
|
||||
"assignments",
|
||||
"exclusions",
|
||||
"provenance",
|
||||
"provenance_digest",
|
||||
"draw_digest",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
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_value(content: bytes) -> dict[str, Any]:
|
||||
"""Hostile decode: no constants, finite floats, bounded recursion, canonical bytes."""
|
||||
if not isinstance(content, bytes) or not content:
|
||||
raise OrdinaryDrawStateError(OrdinaryDrawStateReason.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 OrdinaryDrawStateError(OrdinaryDrawStateReason.STATE_UNREADABLE) from None
|
||||
if not isinstance(value, dict) or canonical != content:
|
||||
raise OrdinaryDrawStateError(OrdinaryDrawStateReason.STATE_UNREADABLE)
|
||||
return value
|
||||
|
||||
|
||||
def _push(item: Any) -> OrdinaryPushV1:
|
||||
return OrdinaryPushV1(
|
||||
item["canonical_repository"],
|
||||
item["network_identity_digest"],
|
||||
CanonicalEcosystem(item["ecosystem"]),
|
||||
item["base_revision"],
|
||||
item["tip_revision"],
|
||||
item["change_byte_length"],
|
||||
item["change_content_digest"],
|
||||
item["history_source_digest"],
|
||||
item["push_digest"],
|
||||
)
|
||||
|
||||
|
||||
def _decoded_draw(value: dict[str, Any]) -> OrdinaryPopulationDrawV1:
|
||||
return ordinary_population_draw(
|
||||
required_per_positive=value["required_per_positive"],
|
||||
policy_digest=value["policy_digest"],
|
||||
closure_digest=value["closure_digest"],
|
||||
reservation_census_digest=value["reservation_census_digest"],
|
||||
positive_change_digests=tuple(value["positive_change_digests"]),
|
||||
per_positive_counts=tuple((item["change_identity_digest"], item["eligible_pushes"]) for item in value["per_positive_counts"]),
|
||||
repository_receipts=tuple(
|
||||
OrdinaryRepositoryReceiptV1(
|
||||
item["canonical_repository"],
|
||||
item["network_identity_digest"],
|
||||
item["byte_length"],
|
||||
item["repository_content_digest"],
|
||||
)
|
||||
for item in value["repository_receipts"]
|
||||
),
|
||||
fix_exclusions=tuple(
|
||||
OrdinaryFixExclusionV1(
|
||||
item["network_identity_digest"],
|
||||
item["fixed_revision"],
|
||||
item["positive_change_digest"],
|
||||
item["ground_truth_review_digest"],
|
||||
)
|
||||
for item in value["fix_exclusions"]
|
||||
),
|
||||
pushes=tuple(_push(item) for item in value["pushes"]),
|
||||
assignments=tuple(
|
||||
OrdinaryDrawAssignmentV1(
|
||||
item["positive_change_digest"],
|
||||
item["network_identity_digest"],
|
||||
CanonicalEcosystem(item["ecosystem"]),
|
||||
item["push_digest"],
|
||||
)
|
||||
for item in value["assignments"]
|
||||
),
|
||||
exclusions=tuple(
|
||||
OrdinaryExclusionV1(
|
||||
item["network_identity_digest"],
|
||||
item["tip_revision"],
|
||||
OrdinaryExclusionReason(item["reason"]),
|
||||
item["contamination_review_digest"],
|
||||
)
|
||||
for item in value["exclusions"]
|
||||
),
|
||||
provenance=tuple(
|
||||
OrdinaryDrawProvenanceV1(
|
||||
item["network_identity_digest"],
|
||||
item["tip_revision"],
|
||||
OrdinaryDrawRule(item["rule"]),
|
||||
item["evidence_digest"],
|
||||
)
|
||||
for item in value["provenance"]
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def decode_ordinary_population_draw(content: bytes) -> OrdinaryPopulationDrawV1:
|
||||
"""Rebuild one ordinary population draw only from canonical, digest-consistent bytes."""
|
||||
value = _decoded_value(content)
|
||||
if set(value) != _DRAW_KEYS or value["schema_version"] != ORDINARY_POPULATION_DRAW_SCHEMA:
|
||||
raise OrdinaryDrawStateError(OrdinaryDrawStateReason.STATE_MISMATCH)
|
||||
try:
|
||||
draw = _decoded_draw(value)
|
||||
except OrdinaryDrawStateError:
|
||||
raise
|
||||
except (AttributeError, KeyError, TypeError, ValueError) as error:
|
||||
raise OrdinaryDrawStateError(OrdinaryDrawStateReason.STATE_MISMATCH) from error
|
||||
if ordinary_population_draw_bytes(draw) != content:
|
||||
raise OrdinaryDrawStateError(OrdinaryDrawStateReason.STATE_MISMATCH)
|
||||
return draw
|
||||
|
||||
|
||||
def persist_ordinary_population_draw(store: S3ArtifactRepository, draw: OrdinaryPopulationDrawV1) -> ArtifactReference:
|
||||
"""Persist one durable ordinary population draw bound to the evidence it examined."""
|
||||
content = canonical_artifact_bytes(
|
||||
ArtifactKind.POPULATION,
|
||||
ordinary_population_draw_value(draw),
|
||||
access_class=ArtifactAccessClass.OPERATOR_SAFE,
|
||||
provenance_digest=draw.draw_digest,
|
||||
)
|
||||
return store.put_if_absent(content, reference=artifact_reference(content))
|
||||
|
||||
|
||||
def resume_ordinary_population_draw(
|
||||
store: S3ArtifactRepository,
|
||||
reference: ArtifactReference,
|
||||
*,
|
||||
authority: ArtifactReadAuthority,
|
||||
expected_access_policy_digest: str,
|
||||
) -> OrdinaryPopulationDrawV1:
|
||||
"""Resume one ordinary population draw 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 OrdinaryDrawStateError(OrdinaryDrawStateReason.STATE_UNREADABLE) from None
|
||||
return decode_ordinary_population_draw(content)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"decode_ordinary_population_draw",
|
||||
"persist_ordinary_population_draw",
|
||||
"resume_ordinary_population_draw",
|
||||
]
|
||||
Reference in New Issue
Block a user