diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index afbe0aad..c1d0fca3 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -345,7 +345,7 @@ - _Requirements: 1.1, 1.2, 1.3, 1.5, 1.6, 1.7, 2.3, 2.4, 2.5, 2.6, 4.1, 4.2, 4.10_ - _Boundary: Review Authority, Replacement Population Sourcing_ - _Depends: 10.4_ -- [ ] 10.6 Draw and validate the full ordinary-change population +- [x] 10.6 Draw and validate the full ordinary-change population - Draw at least twenty eligible same-repository first-parent ordinary pushes for each accepted positive, excluding fixes and every reviewed contaminated change. - Persist the deterministic draw, ecosystem identity, provenance, exclusion, and reservation evidence without opening detector observations or tuning on admission labels. - Prove each input repository and selected change is readable and nonzero before accepting a draw count. diff --git a/benchmarks/valid/ordinary_draw.py b/benchmarks/valid/ordinary_draw.py new file mode 100644 index 00000000..071191b6 --- /dev/null +++ b/benchmarks/valid/ordinary_draw.py @@ -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"] diff --git a/benchmarks/valid/ordinary_draw_contract.py b/benchmarks/valid/ordinary_draw_contract.py new file mode 100644 index 00000000..ed47766e --- /dev/null +++ b/benchmarks/valid/ordinary_draw_contract.py @@ -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", +] diff --git a/benchmarks/valid/ordinary_draw_store.py b/benchmarks/valid/ordinary_draw_store.py new file mode 100644 index 00000000..9c9d6b9d --- /dev/null +++ b/benchmarks/valid/ordinary_draw_store.py @@ -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", +] diff --git a/tests/test_valid_benchmark_ordinary_draw.py b/tests/test_valid_benchmark_ordinary_draw.py new file mode 100644 index 00000000..cf4d0109 --- /dev/null +++ b/tests/test_valid_benchmark_ordinary_draw.py @@ -0,0 +1,735 @@ +"""Ordinary-change population draws over the closed replacement positive set.""" + +from __future__ import annotations + +import json +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from cohort_ingestion_fixtures import ( # noqa: E402 + COMBINED_JAVASCRIPT_NAMES, + COMBINED_PYTHON_NAMES, + ECOSYSTEM_POLICY, + ENUMERATION_ACTOR, + ENUMERATION_REVIEWER, + FOURTH_JAVASCRIPT_NAMES, + GROUND_TRUTH_POLICY, + READ_POLICY, + THIRD_PYTHON_NAMES, + FakeReader, + _Client, + _read_authority, + _settings, + authority, + candidate_for, + case_for, + ingested_replacement_ledger, + replacement_cohort_state, + request_for, + resolver, + reviewed_record, +) + +from benchmarks.valid.artifact_repository import S3ArtifactRepository # noqa: E402 +from benchmarks.valid.catalog import candidate_request # noqa: E402 +from benchmarks.valid.cohort_ingestion import ( # noqa: E402 + CohortBatchStatus, + ingest_javascript_cohort_batch, + ingest_python_cohort_batch, +) +from benchmarks.valid.cohort_selection import ( # noqa: E402 + ingest_fourth_cohort_batch, + ingest_third_cohort_batch, + select_fourth_cohort_batch, + select_third_cohort_batch, +) +from benchmarks.valid.fix_site_catalog import build_fix_site_candidate # noqa: E402 +from benchmarks.valid.ordinary_change_contract import ( # noqa: E402 + ContaminationTiming, + OrdinaryExclusionReason, + reviewed_contamination, +) +from benchmarks.valid.ordinary_draw import ( # noqa: E402 + MINIMUM_ORDINARY_PER_POSITIVE, + OrdinaryDrawError, + OrdinaryDrawReason, + OrdinaryDrawRule, + OrdinaryPopulationHistorySource, + draw_ordinary_population, +) +from benchmarks.valid.ordinary_draw_contract import ( # noqa: E402 + ORDINARY_POPULATION_DRAW_SCHEMA, + OrdinaryDrawStateError, + OrdinaryDrawStateReason, + ordinary_population_draw, + ordinary_population_draw_bytes, +) +from benchmarks.valid.ordinary_draw_store import ( # noqa: E402 + decode_ordinary_population_draw, + persist_ordinary_population_draw, + resume_ordinary_population_draw, +) +from benchmarks.valid.replacement_artifact_contract import ( # noqa: E402 + ArtifactAccessClass, + ArtifactKind, + validate_artifact, +) +from benchmarks.valid.reservation import ReservationAuthority, legacy_reservation_source # noqa: E402 +from benchmarks.valid.sourcing_queue import sourcing_queue_policy # noqa: E402 +from benchmarks.valid.sourcing_queue_build import build_sourcing_queue # noqa: E402 +from openultrasast.core.canonical import content_digest # noqa: E402 + +LEAN_PYTHON = tuple(f"py-{index:02d}" for index in range(10)) +LEAN_JAVASCRIPT = tuple(f"js-{index:02d}" for index in range(10)) +LEAN_THIRD_PYTHON = tuple(f"py3-{index:02d}" for index in range(10)) +LEAN_THIRD_JAVASCRIPT = tuple(f"js3-{index:02d}" for index in range(10)) +LEAN_NAMES = (*LEAN_PYTHON, *LEAN_JAVASCRIPT, *LEAN_THIRD_PYTHON, *LEAN_THIRD_JAVASCRIPT) +CLOSED_PYTHON_NAMES = (*COMBINED_PYTHON_NAMES, *THIRD_PYTHON_NAMES) +CLOSED_JAVASCRIPT_NAMES = (*COMBINED_JAVASCRIPT_NAMES, *FOURTH_JAVASCRIPT_NAMES) +FULL_NAMES = (*CLOSED_PYTHON_NAMES, *CLOSED_JAVASCRIPT_NAMES) +ORDINARY_DEPTH = 26 +DRAW_POLICY = content_digest({"policy": "ordinary-population-draw-v1", "required_per_positive": MINIMUM_ORDINARY_PER_POSITIVE}) +SOURCE = content_digest({"source": "fixture-ordinary-first-parent-histories"}) +CONTAMINATION_POLICY = content_digest({"policy": "contamination-review-v1"}) +SECOND_PARENT = f"{0xF50000:040x}" +SECOND_FIX = f"{0xF50001:040x}" + + +@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) + + +class OrdinaryFixtureHistory: + """Synthetic first-parent ordinary histories below each fixture vulnerable parent.""" + + def __init__(self, names, *, depth=ORDINARY_DEPTH, inserted=None, contents=None): + self._parents: dict[str, tuple[str, ...]] = {} + self._changes: dict[str, bytes] = {} + self._repositories: dict[str, bytes] = {} + for index, name in enumerate(sorted(names)): + row = case_for(name) + parent = row["parent"] + self._repositories[row["url"]] = f"repository-manifest:{name}".encode() + prefix = [parent, *(inserted or {}).get(name, ())] + chain = [*prefix] + [f"{0xF00000 + index * (depth + 8) + step:040x}" for step in range(depth)] + self._parents[row["commit"]] = (parent,) + for position, revision in enumerate(chain): + following = chain[position + 1] if position + 1 < len(chain) else "" + self._parents[revision] = (following,) if following else () + content: bytes | None + if revision in (contents or {}): + content = contents[revision] + elif revision == parent: + content = f"snapshot:{name}:vulnerable".encode() + elif revision in prefix[1:]: + content = None + else: + content = f"ordinary:{name}:{position}".encode() + if content is not None: + self._changes[revision] = content + + def parents(self, revision: str) -> tuple[str, ...]: + return self._parents.get(revision, ()) + + def change_bytes(self, revision: str) -> bytes | None: + return self._changes.get(revision) + + def repository_bytes(self, canonical_repository: str) -> bytes | None: + return self._repositories.get(canonical_repository) + + +class LabelLadenReader: + """History reader carrying released label and detector-observation markers.""" + + def __init__(self, inner: OrdinaryFixtureHistory) -> None: + self._inner = inner + self.released_admission_labels = b"released-label-marker" + self.detector_observations = b"detector-observation-marker" + + def parents(self, revision: str) -> tuple[str, ...]: + return self._inner.parents(revision) + + def change_bytes(self, revision: str) -> bytes | None: + return self._inner.change_bytes(revision) + + def repository_bytes(self, canonical_repository: str) -> bytes | None: + return self._inner.repository_bytes(canonical_repository) + + +class SharedRepoReader(FakeReader): + """Fixture reader extended with a second reviewed change inside repo py-00.""" + + def __init__(self) -> None: + super().__init__() + self._blobs[(SECOND_PARENT, "app/second.py")] = "def helper(query):\n return eval(query)\n" + self._blobs[(SECOND_FIX, "app/second.py")] = "def helper(query):\n return str(query)\n" + self._parents[SECOND_FIX] = (SECOND_PARENT,) + + +def _second_change_request(): + return request_for( + "py-00", + path="app/second.py", + function="helper", + advisory="GHSA-cohort-py-00-second", + commit=SECOND_FIX, + parent=SECOND_PARENT, + ) + + +def _candidate(request, resolved, reader=None): + fix_request = candidate_request( + request.case, + resolver=resolved, + package_evidence=request.package_evidence, + license_evidence=request.license_evidence, + ) + return build_fix_site_candidate(reader or FakeReader(), fix_request) + + +def _lean_state(): + return replacement_cohort_state( + python_names=(*LEAN_PYTHON, *LEAN_THIRD_PYTHON), + javascript_names=(*LEAN_JAVASCRIPT, *LEAN_THIRD_JAVASCRIPT), + ) + + +def _batch_for(state, resolved, names, ecosystem, extra_requests=()): + queue = state.python_queue if ecosystem == "python" else state.javascript_queue + candidates = {} + for name in names: + candidate = candidate_for(name, resolved) + candidates[candidate.candidate_digest] = candidate + for request in extra_requests: + candidate = _candidate(request, resolved, SharedRepoReader()) + candidates[candidate.candidate_digest] = candidate + by_candidate = {entry.candidate_digest: entry for entry in queue.entries} + records = [reviewed_record(by_candidate[digest], candidates[digest], ecosystem=ecosystem)[0] for digest in candidates] + ingest = ingest_python_cohort_batch if ecosystem == "python" else ingest_javascript_cohort_batch + return ( + ingest( + records, + state=state, + candidates_by_digest=candidates, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ), + candidates, + ) + + +def _lean_batches(state, resolved): + rounds = ( + ("python", LEAN_PYTHON), + ("javascript", LEAN_JAVASCRIPT), + ("python", LEAN_THIRD_PYTHON), + ("javascript", LEAN_THIRD_JAVASCRIPT), + ) + return tuple(_batch_for(state, resolved, names, ecosystem)[0] for ecosystem, names in rounds) + + +def _draw( + batches, + resolved, + history, + *, + names=LEAN_NAMES, + reviews=(), + excluded_reviews=(), + census=None, + required=MINIMUM_ORDINARY_PER_POSITIVE, + extra_candidates=(), + reader=None, +): + candidates = {} + for name in names: + candidate = candidate_for(name, resolved) + candidates[candidate.candidate_digest] = candidate + for candidate in extra_candidates: + candidates[candidate.candidate_digest] = candidate + sources = {} + for candidate in candidates.values(): + history_reader = reader if reader is not None else history + sources[candidate.network_identity_digest] = OrdinaryPopulationHistorySource( + history_reader, + candidate.canonical_repository, + candidate.network_identity_digest, + SOURCE, + ) + return draw_ordinary_population( + batches, + candidates_by_digest=candidates, + history_by_network=sources, + contamination_reviews=reviews, + excluded_reviews=excluded_reviews, + reservation_census=census if census is not None else authority(resolved).current_census(), + required_per_positive=required, + policy_digest=DRAW_POLICY, + ) + + +def _contamination(name: str, tip: str, timing=ContaminationTiming.PRE_FREEZE): + return reviewed_contamination( + network_identity_digest=candidate_for(name, resolver()).network_identity_digest, + tip_revision=tip, + timing=timing, + evidence_digest=content_digest({"contamination": tip}), + producer_identity="contamination-producer@example.invalid", + reviewer_identity="contamination-reviewer@example.invalid", + conflict_disclosed=True, + policy_digest=CONTAMINATION_POLICY, + ) + + +def _excluded_review(name: str, resolved): + candidate = candidate_for(name, resolved) + state, _ = _lean_state() + queue = state.python_queue if case_for(name)["repo"].startswith("fixture/cohort-py") else state.javascript_queue + entry = next(item for item in queue.entries if item.candidate_digest == candidate.candidate_digest) + return reviewed_record(entry, candidate, gt_changes={"defect_present": False})[1] + + +def _fields(draw): + return dict( + required_per_positive=draw.required_per_positive, + policy_digest=draw.policy_digest, + closure_digest=draw.closure_digest, + reservation_census_digest=draw.reservation_census_digest, + positive_change_digests=draw.positive_change_digests, + per_positive_counts=draw.per_positive_counts, + repository_receipts=draw.repository_receipts, + fix_exclusions=draw.fix_exclusions, + pushes=draw.pushes, + assignments=draw.assignments, + exclusions=draw.exclusions, + provenance=draw.provenance, + ) + + +def _full_closed_batches(): + state, resolved = replacement_cohort_state( + python_names=CLOSED_PYTHON_NAMES, + javascript_names=CLOSED_JAVASCRIPT_NAMES, + ) + candidates = {name: candidate_for(name, resolved) for name in FULL_NAMES} + by_digest = {candidate.candidate_digest: candidate for candidate in candidates.values()} + ledger = ingested_replacement_ledger(state, resolved) + third_selection = select_third_cohort_batch( + state=state, + accepted_batches=ledger, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + third_entries = [entry for entry in state.python_queue.entries if entry.entry_digest in set(third_selection.selected_entries)] + third = ingest_third_cohort_batch( + [reviewed_record(entry, by_digest[entry.candidate_digest])[0] for entry in third_entries], + selection=third_selection, + state=state, + candidates_by_digest=by_digest, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + ledger = (*ledger, third) + fourth_selection = select_fourth_cohort_batch( + state=state, + accepted_batches=ledger, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + fourth_entries = [ + entry for entry in state.javascript_queue.entries if entry.entry_digest in set(fourth_selection.selected_entries) + ] + fourth = ingest_fourth_cohort_batch( + [reviewed_record(entry, by_digest[entry.candidate_digest], ecosystem="javascript")[0] for entry in fourth_entries], + selection=fourth_selection, + state=state, + candidates_by_digest=by_digest, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + return (*ledger, fourth), resolved + + +def test_every_accepted_positive_draws_twenty_eligible_pushes(): + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + assert all(batch.status is CohortBatchStatus.ACCEPTED for batch in batches) + history = OrdinaryFixtureHistory(LEAN_NAMES) + draw = _draw(batches, resolved, history) + + assert len(draw.per_positive_counts) == 40 + assert all(count == MINIMUM_ORDINARY_PER_POSITIVE for _, count in draw.per_positive_counts) + assert len(draw.assignments) == 40 * MINIMUM_ORDINARY_PER_POSITIVE + assert len(draw.pushes) == 40 * MINIMUM_ORDINARY_PER_POSITIVE + assert len(set(draw.pushes)) == len(draw.pushes) + assert all(push.change_byte_length > 0 for push in draw.pushes) + assert all(receipt.byte_length > 0 for receipt in draw.repository_receipts) + assert len(draw.repository_receipts) == 40 + + eligible = { + (row.network_identity_digest, row.tip_revision) + for row in draw.provenance + if row.rule is OrdinaryDrawRule.ELIGIBLE_FIRST_PARENT_ORDINARY + } + for push in draw.pushes: + row = next( + item + for item in draw.provenance + if item.rule is OrdinaryDrawRule.ELIGIBLE_FIRST_PARENT_ORDINARY + and (item.network_identity_digest, item.tip_revision) == (push.network_identity_digest, push.tip_revision) + ) + assert row.evidence_digest == push.push_digest + assert eligible == {(push.network_identity_digest, push.tip_revision) for push in draw.pushes} + + ecosystems = { + candidate_for(name, resolved).network_identity_digest: ("python" if name.startswith(("py-", "py3-")) else "javascript") + for name in LEAN_NAMES + } + assert all(push.ecosystem.value == ecosystems[push.network_identity_digest] for push in draw.pushes) + assert decode_ordinary_population_draw(ordinary_population_draw_bytes(draw)) == draw + + +def test_draw_is_deterministic_and_permutation_invariant(): + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + history = OrdinaryFixtureHistory(LEAN_NAMES) + first = _draw(batches, resolved, history) + second = _draw(tuple(reversed(batches)), resolved, history) + + assert ordinary_population_draw_bytes(first) == ordinary_population_draw_bytes(second) + assert first.draw_digest == second.draw_digest + assert first.provenance_digest == second.provenance_digest + + +def test_draw_is_label_blind_and_detector_blind(monkeypatch): + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + plain = _draw(batches, resolved, OrdinaryFixtureHistory(LEAN_NAMES)) + monkeypatch.setenv("VALID_BENCHMARK_ADMISSION_LABELS", "released-label-marker") + monkeypatch.setenv("VALID_BENCHMARK_DETECTOR_OBSERVATIONS", "detector-observation-marker") + laden = _draw(batches, resolved, OrdinaryFixtureHistory(LEAN_NAMES), reader=LabelLadenReader(OrdinaryFixtureHistory(LEAN_NAMES))) + + assert ordinary_population_draw_bytes(plain) == ordinary_population_draw_bytes(laden) + value = json.loads(ordinary_population_draw_bytes(plain)) + assert set(value) == { + "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", + } + assert value["schema_version"] == ORDINARY_POPULATION_DRAW_SCHEMA + assert not any("label" in key or "observation" in key for key in value) + + +def test_draw_excludes_contaminated_and_reviewed_excluded_changes(): + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + history = OrdinaryFixtureHistory(LEAN_NAMES) + py_parent = case_for("py-00")["parent"] + js_parent = case_for("js-00")["parent"] + excluded_review = _excluded_review("js-00", resolved) + assert excluded_review.status.value == "excluded" + + draw = _draw( + batches, + resolved, + history, + reviews=(_contamination("py-00", py_parent),), + excluded_reviews=(excluded_review,), + ) + + py_network = candidate_for("py-00", resolved).network_identity_digest + js_network = candidate_for("js-00", resolved).network_identity_digest + assert all((push.network_identity_digest, push.tip_revision) != (py_network, py_parent) for push in draw.pushes) + assert all((push.network_identity_digest, push.tip_revision) != (js_network, js_parent) for push in draw.pushes) + assert len(draw.exclusions) == 1 + assert draw.exclusions[0].reason is OrdinaryExclusionReason.REVIEWED_SECURITY_DEFECT + rules = {(row.network_identity_digest, row.tip_revision, row.rule) for row in draw.provenance} + assert (py_network, py_parent, OrdinaryDrawRule.EXCLUDED_REVIEWED_CONTAMINATION) in rules + assert (js_network, js_parent, OrdinaryDrawRule.EXCLUDED_REVIEWED_CHANGE) in rules + for row in draw.provenance: + if row.rule is OrdinaryDrawRule.EXCLUDED_REVIEWED_CHANGE: + assert row.evidence_digest == excluded_review.review_digest + counts = dict(draw.per_positive_counts) + assert all(count >= MINIMUM_ORDINARY_PER_POSITIVE for count in counts.values()) + + +def test_draw_refuses_unapplied_and_post_freeze_exclusion_evidence(): + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + history = OrdinaryFixtureHistory(LEAN_NAMES) + + with pytest.raises(OrdinaryDrawError) as error: + _draw(batches, resolved, history, reviews=(_contamination("py-00", "e" * 40),)) + assert error.value.reason is OrdinaryDrawReason.CONFLICTING_EXCLUSION_EVIDENCE + + with pytest.raises(OrdinaryDrawError) as error: + _draw( + batches, + resolved, + history, + reviews=(_contamination("py-00", case_for("py-00")["parent"], ContaminationTiming.POST_FREEZE),), + ) + assert error.value.reason is OrdinaryDrawReason.POST_FREEZE_CONTAMINATION + + +def test_shared_repository_pushes_are_drawn_once_and_fixes_are_excluded_mid_walk(): + resolved = resolver() + requests = [request_for(name) for name in (*LEAN_PYTHON, *LEAN_JAVASCRIPT, *LEAN_THIRD_PYTHON, *LEAN_THIRD_JAVASCRIPT)] + requests.append(_second_change_request()) + state = build_sourcing_queue( + requests, + reader=SharedRepoReader(), + resolver=resolved, + authority=authority(resolved), + policy=sourcing_queue_policy(per_ecosystem_cap=25, required_families=2), + enumeration_actor=ENUMERATION_ACTOR, + enumeration_reviewer=ENUMERATION_REVIEWER, + ) + python_batch, python_candidates = _batch_for(state, resolved, LEAN_PYTHON, "python", extra_requests=(_second_change_request(),)) + other = ( + _batch_for(state, resolved, LEAN_JAVASCRIPT, "javascript")[0], + _batch_for(state, resolved, LEAN_THIRD_PYTHON, "python")[0], + _batch_for(state, resolved, LEAN_THIRD_JAVASCRIPT, "javascript")[0], + ) + batches = (python_batch, *other) + assert len(batches) == 4 + + history = OrdinaryFixtureHistory( + (*LEAN_PYTHON, *LEAN_JAVASCRIPT, *LEAN_THIRD_PYTHON, *LEAN_THIRD_JAVASCRIPT), + inserted={"py-00": (SECOND_FIX, SECOND_PARENT)}, + contents={SECOND_PARENT: b"snapshot:py-00:second-vulnerable"}, + ) + draw = _draw(batches, resolved, history, extra_candidates=python_candidates.values()) + + assert len(draw.per_positive_counts) == 41 + assert all(count == MINIMUM_ORDINARY_PER_POSITIVE for _, count in draw.per_positive_counts) + assert len(draw.assignments) == 41 * MINIMUM_ORDINARY_PER_POSITIVE + assert len(draw.pushes) == 39 * MINIMUM_ORDINARY_PER_POSITIVE + MINIMUM_ORDINARY_PER_POSITIVE + 1 + py_network = candidate_for("py-00", resolved).network_identity_digest + shared = [push for push in draw.pushes if push.network_identity_digest == py_network] + assert len(shared) == MINIMUM_ORDINARY_PER_POSITIVE + 1 + assert all(push.tip_revision != SECOND_FIX for push in draw.pushes) + second_digest = next(candidate.candidate_digest for candidate in python_candidates.values() if candidate.fixed.revision == SECOND_FIX) + second_positive = next(positive for positive in python_batch.accepted_positives if positive.candidate_digest == second_digest) + fix_rows = [row for row in draw.provenance if row.rule is OrdinaryDrawRule.EXCLUDED_ACCEPTED_FIX] + assert any(row.tip_revision == SECOND_FIX and row.network_identity_digest == py_network for row in fix_rows) + assert any(row.evidence_digest == second_positive.ground_truth_review_digest for row in fix_rows) + + +def test_draw_refuses_insufficient_histories_closed(): + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + + with pytest.raises(OrdinaryDrawError) as error: + _draw(batches, resolved, OrdinaryFixtureHistory(LEAN_NAMES, depth=18)) + assert error.value.reason is OrdinaryDrawReason.INSUFFICIENT_HISTORY + assert "18 of 20" in str(error.value) + + class ShallowHistory(OrdinaryFixtureHistory): + def __init__(self) -> None: + super().__init__(LEAN_NAMES) + fixes = {case_for(name)["commit"] for name in LEAN_NAMES} + self._parents = {revision: edges for revision, edges in self._parents.items() if revision in fixes} + + with pytest.raises(OrdinaryDrawError) as error: + _draw(batches, resolved, ShallowHistory()) + assert error.value.reason is OrdinaryDrawReason.INSUFFICIENT_HISTORY + assert "0 of 20" in str(error.value) + + +def test_draw_proves_repositories_and_changes_readable_and_nonzero(): + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + py_repo = case_for("py-00")["url"] + py_parent = case_for("py-00")["parent"] + + missing = OrdinaryFixtureHistory(LEAN_NAMES) + del missing._repositories[py_repo] + with pytest.raises(OrdinaryDrawError) as error: + _draw(batches, resolved, missing) + assert error.value.reason is OrdinaryDrawReason.REPOSITORY_UNREADABLE + + empty = OrdinaryFixtureHistory(LEAN_NAMES) + empty._repositories[py_repo] = b"" + with pytest.raises(OrdinaryDrawError) as error: + _draw(batches, resolved, empty) + assert error.value.reason is OrdinaryDrawReason.REPOSITORY_UNREADABLE + + unreadable = OrdinaryFixtureHistory(LEAN_NAMES) + del unreadable._changes[py_parent] + with pytest.raises(OrdinaryDrawError) as error: + _draw(batches, resolved, unreadable) + assert error.value.reason is OrdinaryDrawReason.HISTORY_UNREADABLE + + zero = OrdinaryFixtureHistory(LEAN_NAMES) + zero._changes[py_parent] = b"" + with pytest.raises(OrdinaryDrawError) as error: + _draw(batches, resolved, zero) + assert error.value.reason is OrdinaryDrawReason.HISTORY_UNREADABLE + + unbound = OrdinaryFixtureHistory(LEAN_NAMES) + unbound._parents[case_for("py-00")["commit"]] = ("d" * 40,) + with pytest.raises(OrdinaryDrawError) as error: + _draw(batches, resolved, unbound) + assert error.value.reason is OrdinaryDrawReason.HISTORY_UNBOUND + + +def test_draw_refuses_reserved_repositories_and_unclosed_sets(): + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + history = OrdinaryFixtureHistory(LEAN_NAMES) + + legacy = legacy_reservation_source( + resolved, + repository=case_for("py-00")["url"], + source_digest=content_digest({"legacy-pilot": "py-00"}), + ) + reserved_census = ReservationAuthority(resolved, legacy_sources=(legacy,)).current_census() + assert candidate_for("py-00", resolved).network_identity_digest in reserved_census.reserved_network_digests + with pytest.raises(OrdinaryDrawError) as error: + _draw(batches, resolved, history, census=reserved_census) + assert error.value.reason is OrdinaryDrawReason.RESERVED_REPOSITORY + + with pytest.raises(OrdinaryDrawError) as error: + _draw(batches[:2], resolved, history) + assert error.value.reason is OrdinaryDrawReason.POSITIVE_SET_NOT_CLOSED + + candidates = {name: candidate_for(name, resolved) for name in LEAN_NAMES} + sources = { + candidate.network_identity_digest: OrdinaryPopulationHistorySource( + history, + candidate.canonical_repository, + candidate.network_identity_digest, + SOURCE, + ) + for candidate in candidates.values() + } + del candidates["py3-00"] + with pytest.raises(OrdinaryDrawError) as error: + draw_ordinary_population( + batches, + candidates_by_digest={candidate.candidate_digest: candidate for candidate in candidates.values()}, + history_by_network=sources, + reservation_census=authority(resolved).current_census(), + required_per_positive=MINIMUM_ORDINARY_PER_POSITIVE, + policy_digest=DRAW_POLICY, + ) + assert error.value.reason is OrdinaryDrawReason.CANDIDATE_MISSING + + with pytest.raises(OrdinaryDrawError) as error: + _draw(batches, resolved, history, required=19) + assert error.value.reason is OrdinaryDrawReason.INVALID_REQUEST + + +def test_draw_assembler_fails_closed_on_impossible_combinations(): + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + draw = _draw(batches, resolved, OrdinaryFixtureHistory(LEAN_NAMES)) + based = _fields(draw) + + assert ordinary_population_draw(**based).draw_digest == draw.draw_digest + short_counts = (*based["per_positive_counts"][:-1], (based["per_positive_counts"][-1][0], 19)) + duplicate_pushes = (*based["pushes"], based["pushes"][0]) + mutations = ( + {"per_positive_counts": short_counts}, + {"pushes": based["pushes"][:-1]}, + {"pushes": duplicate_pushes}, + {"repository_receipts": (replace(based["repository_receipts"][0], byte_length=0), *based["repository_receipts"][1:])}, + {"provenance": tuple(row for row in based["provenance"] if row.rule is not OrdinaryDrawRule.ELIGIBLE_FIRST_PARENT_ORDINARY)}, + {"reservation_census_digest": "z" * 64}, + {"positive_change_digests": based["positive_change_digests"][:-1]}, + {"assignments": based["assignments"][:-1]}, + ) + for changes in mutations: + with pytest.raises(OrdinaryDrawStateError) as error: + ordinary_population_draw(**{**based, **changes}) + assert error.value.reason is OrdinaryDrawStateReason.STATE_MISMATCH + + forged_rows = tuple(replace(row, rule="forged_rule") for row in draw.provenance) + with pytest.raises(OrdinaryDrawStateError) as error: + replace(draw, provenance=forged_rows) + assert error.value.reason is OrdinaryDrawStateReason.STATE_MISMATCH + + malformed_fix = (replace(based["fix_exclusions"][0], fixed_revision="not-a-revision"), *based["fix_exclusions"][1:]) + with pytest.raises(OrdinaryDrawStateError) as error: + ordinary_population_draw(**{**based, "fix_exclusions": malformed_fix}) + assert error.value.reason is OrdinaryDrawStateReason.STATE_MISMATCH + + +def test_draw_decode_is_hostile_and_persists_durably(): + state, resolved = _lean_state() + batches = _lean_batches(state, resolved) + draw = _draw(batches, resolved, OrdinaryFixtureHistory(LEAN_NAMES)) + content = ordinary_population_draw_bytes(draw) + assert content and decode_ordinary_population_draw(content) == draw + + good = json.loads(content) + spaced = json.dumps(good, sort_keys=True, indent=1).encode("utf-8") + wrong_schema = json.dumps({**good, "schema_version": "other.v1"}, sort_keys=True, separators=(",", ":")).encode("utf-8") + tampered = json.dumps({**good, "required_per_positive": 19}, sort_keys=True, separators=(",", ":")).encode("utf-8") + for bad in ( + b"", + b"not json at all", + b'{"x":NaN}', + b'{"x":1e999}', + b'{"k":' + b"[" * 20000 + b"]" * 20000 + b"}", + spaced, + wrong_schema, + tampered, + ): + with pytest.raises(OrdinaryDrawStateError): + decode_ordinary_population_draw(bad) + + client = _Client() + store = S3ArtifactRepository(_settings(), client) + reference = persist_ordinary_population_draw(store, draw) + assert persist_ordinary_population_draw(store, draw) == reference + accepted = store.get( + reference, expected_kind=ArtifactKind.POPULATION, authority=_read_authority(), expected_access_policy_digest=READ_POLICY + ) + validate_artifact(accepted.content, reference=reference) + assert reference.access_class is ArtifactAccessClass.OPERATOR_SAFE + + resumed = resume_ordinary_population_draw( + S3ArtifactRepository(_settings(), client), reference, authority=_read_authority(), expected_access_policy_digest=READ_POLICY + ) + assert resumed == draw + assert ordinary_population_draw_bytes(resumed) == content + + +def test_full_closed_set_draw_reproduces_from_durable_evidence_after_restart(): + batches, resolved = _full_closed_batches() + assert len(batches) == 4 + history = OrdinaryFixtureHistory(FULL_NAMES) + draw = _draw(batches, resolved, history, names=FULL_NAMES) + + assert len(draw.per_positive_counts) == 48 + assert all(count >= MINIMUM_ORDINARY_PER_POSITIVE for _, count in draw.per_positive_counts) + assert len(draw.assignments) == 48 * MINIMUM_ORDINARY_PER_POSITIVE + + client = _Client() + store = S3ArtifactRepository(_settings(), client) + reference = persist_ordinary_population_draw(store, draw) + restarted = resume_ordinary_population_draw( + S3ArtifactRepository(_settings(), client), reference, authority=_read_authority(), expected_access_policy_digest=READ_POLICY + ) + assert restarted == draw + content = ordinary_population_draw_bytes(draw) + assert ordinary_population_draw_bytes(restarted) == content + assert decode_ordinary_population_draw(content) == restarted