From 6d66501192ae34c76c1a5d92ce7fb05fb6b1c34b Mon Sep 17 00:00:00 2001 From: Marius Ciepluch <11855163+norandom@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:16:54 +0100 Subject: [PATCH] feat(valid-detection-benchmark): 10.4 select and ingest third reviewed cohort --- .../specs/valid-detection-benchmark/tasks.md | 2 +- benchmarks/valid/cohort_ingestion.py | 2 +- benchmarks/valid/cohort_selection.py | 578 ++++++++++++++++++ benchmarks/valid/cohort_selection_store.py | 147 +++++ tests/cohort_ingestion_fixtures.py | 171 +++++- .../test_valid_benchmark_cohort_selection.py | 367 +++++++++++ ..._valid_benchmark_third_cohort_ingestion.py | 299 +++++++++ 7 files changed, 1563 insertions(+), 3 deletions(-) create mode 100644 benchmarks/valid/cohort_selection.py create mode 100644 benchmarks/valid/cohort_selection_store.py create mode 100644 tests/test_valid_benchmark_cohort_selection.py create mode 100644 tests/test_valid_benchmark_third_cohort_ingestion.py diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index 6db04cb2..c7d60812 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -329,7 +329,7 @@ - _Requirements: 1.1, 1.5, 1.6, 1.8, 2.3, 2.4, 2.5, 2.6, 4.1, 4.2_ - _Boundary: Review Authority, Replacement Population Sourcing_ - _Depends: 10.1_ -- [ ] 10.4 Ingest a third bounded independently reviewed cohort +- [x] 10.4 Ingest a third bounded independently reviewed cohort - Accept one externally supplied batch of at most twenty candidate review records under the same identity, review, reachability, exact-scope, reservation, and exclusion rules. - Select the pending queue batch needed to preserve both ecosystems and progress the accepted set toward at least two vulnerability families without changing review policy after seeing labels. - Do not fabricate or self-approve missing reviews; leave this bounded cohort pending when its external records are unavailable. diff --git a/benchmarks/valid/cohort_ingestion.py b/benchmarks/valid/cohort_ingestion.py index fac5898c..6bcfc37e 100644 --- a/benchmarks/valid/cohort_ingestion.py +++ b/benchmarks/valid/cohort_ingestion.py @@ -105,7 +105,7 @@ _CLOSED_OUTCOME_REASONS = _CLOSED_RECORD_REASONS | frozenset(item.value for item _REASON_TEXT = { CohortRecordExclusionReason.RECORD_UNREADABLE: "external review record bytes are unreadable", CohortRecordExclusionReason.RECORD_SCHEMA_MISMATCH: "external review record does not match its closed schema", - CohortRecordExclusionReason.QUEUE_ENTRY_UNKNOWN: "record does not answer a pending Python review queue entry", + CohortRecordExclusionReason.QUEUE_ENTRY_UNKNOWN: "record does not answer a pending cohort review queue entry", CohortRecordExclusionReason.CANDIDATE_EVIDENCE_MISSING: "reviewed candidate evidence is absent from the exact input set", CohortRecordExclusionReason.REVIEW_EVIDENCE_INVALID: "external review attestations fail authority validation", CohortRecordExclusionReason.DUPLICATE_RECORD: "queue entry is already answered by another record in this batch", diff --git a/benchmarks/valid/cohort_selection.py b/benchmarks/valid/cohort_selection.py new file mode 100644 index 00000000..4be12746 --- /dev/null +++ b/benchmarks/valid/cohort_selection.py @@ -0,0 +1,578 @@ +"""Outcome-blind selection of the next bounded cohort batch over pending queues. + +Selection may read pending queue state, the accepted-cohort ledger, and the +frozen review-policy digests already recorded on that ledger. Families +represented in the accepted ledger are facts of recorded human reviews: they +drive ecosystem and family-gap coverage only, never a change of review +policy, and no machine result enters this module or its durable bytes. +""" + +from __future__ import annotations + +import re +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, replace +from enum import StrEnum + +from benchmarks.valid.cohort_ingestion import ( + COHORT_BATCH_CAP, + MINIMUM_ACCEPTED_POSITIVES, + CohortBatchOutcomeV1, + ingest_javascript_cohort_batch, + ingest_python_cohort_batch, +) +from benchmarks.valid.fix_site_catalog import FixSiteCandidateV1 +from benchmarks.valid.sourcing_queue import ( + EcosystemReviewQueueV1, + ReviewQueueEntryV1, + SourcingQueueStateV1, + ecosystem_review_queue, + sourcing_queue_state, +) +from openultrasast.core.canonical import JsonValue, canonical_bytes, content_digest + +COHORT_SELECTION_SCHEMA = "openultrasast.valid-detection-benchmark.cohort-selection.v1" +REQUIRED_DISTINCT_FAMILIES = 2 +COHORT_SELECTION_ECOSYSTEMS = ("javascript", "python") +_DIGEST = re.compile(r"[0-9a-f]{64}") +_FAMILY = re.compile(r"[a-z0-9][a-z0-9_]{0,127}") + + +class CohortSelectionStatus(StrEnum): + SELECTED = "selected" + REFUSED = "refused" + + +class CohortSelectionReason(StrEnum): + """Closed decision vocabulary naming the ecosystem or family gap served.""" + + MISSING_ECOSYSTEM_SELECTED = "missing_ecosystem_selected" + FAMILY_GAP_SELECTED = "family_gap_selected" + BALANCED_PROGRESS_SELECTED = "balanced_progress_selected" + NO_PENDING_ENTRIES = "no_pending_entries" + CENSUS_MISMATCH = "census_mismatch" + POLICY_MISMATCH = "policy_mismatch" + + +class CohortSelectionStateReason(StrEnum): + STATE_UNREADABLE = "state_unreadable" + STATE_MISMATCH = "state_mismatch" + + +_REFUSAL_REASONS = frozenset( + { + CohortSelectionReason.NO_PENDING_ENTRIES, + CohortSelectionReason.CENSUS_MISMATCH, + CohortSelectionReason.POLICY_MISMATCH, + } +) + +_STATE_REASON_TEXT = { + CohortSelectionStateReason.STATE_UNREADABLE: "cohort selection bytes are unreadable", + CohortSelectionStateReason.STATE_MISMATCH: "cohort selection state does not match its canonical schema", +} + + +class CohortSelectionStateError(ValueError): + """Closed selection refusal carrying one structural reason.""" + + def __init__(self, reason: CohortSelectionStateReason) -> None: + self.reason = reason + super().__init__(_STATE_REASON_TEXT[reason]) + + +def _mismatch() -> CohortSelectionStateError: + return CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) + + +@dataclass(frozen=True) +class CohortSelectionV1: + ecosystem: str | None + selected_entries: tuple[str, ...] + targeted_families: tuple[str, ...] + queue_digest: str | None + census_digest: str + ecosystem_policy_digest: str + ground_truth_policy_digest: str + prior_batch_digests: tuple[str, ...] + accepted_families: tuple[str, ...] + accepted_by_ecosystem: tuple[tuple[str, int], ...] + status: CohortSelectionStatus + reason: CohortSelectionReason + selection_digest: str + + def __post_init__(self) -> None: + _validate_selection(self) + + +@dataclass(frozen=True) +class _LedgerFacts: + batch_digests: tuple[str, ...] + families: tuple[str, ...] + families_by_ecosystem: Mapping[str, frozenset[str]] + accepted_by_ecosystem: Mapping[str, int] + census_digests: tuple[str, ...] + policy_pairs: tuple[tuple[str, str], ...] + + +def _closed_digest(value: object) -> str: + if not isinstance(value, str) or _DIGEST.fullmatch(value) is None: + raise _mismatch() + return value + + +def _closed_vocabulary(values: object, pattern: re.Pattern[str]) -> tuple[str, ...]: + if not isinstance(values, tuple) or not all(isinstance(item, str) for item in values): + raise _mismatch() + ordered = tuple(sorted(set(values))) + if ordered != values or any(pattern.fullmatch(item) is None for item in ordered): + raise _mismatch() + return values + + +def _closed_counts(pairs: object) -> tuple[tuple[str, int], ...]: + if not isinstance(pairs, tuple): + raise _mismatch() + ecosystems = [] + for pair in pairs: + if not isinstance(pair, tuple) or len(pair) != 2: + raise _mismatch() + ecosystem, count = pair + if ecosystem not in COHORT_SELECTION_ECOSYSTEMS or type(count) is not int or count < 0: + raise _mismatch() + ecosystems.append(ecosystem) + if ecosystems != sorted(ecosystems) or len(set(ecosystems)) != len(ecosystems): + raise _mismatch() + return pairs + + +def _validate_selection(item: CohortSelectionV1) -> None: + if not isinstance(item.status, CohortSelectionStatus) or not isinstance(item.reason, CohortSelectionReason): + raise _mismatch() + if item.selection_digest: + _closed_digest(item.selection_digest) + for digest_value in (item.census_digest, item.ecosystem_policy_digest, item.ground_truth_policy_digest): + _closed_digest(digest_value) + _closed_vocabulary(item.prior_batch_digests, _DIGEST) + _closed_vocabulary(item.accepted_families, _FAMILY) + _closed_vocabulary(item.targeted_families, _FAMILY) + _closed_counts(item.accepted_by_ecosystem) + if item.status is CohortSelectionStatus.SELECTED: + _validate_selected(item) + else: + _validate_refused(item) + + +def _validate_selected(item: CohortSelectionV1) -> None: + if item.ecosystem not in COHORT_SELECTION_ECOSYSTEMS or item.reason in _REFUSAL_REASONS: + raise _mismatch() + _closed_digest(item.queue_digest) + _closed_vocabulary(item.selected_entries, _DIGEST) + if not 1 <= len(item.selected_entries) <= COHORT_BATCH_CAP: + raise _mismatch() + + +def _validate_refused(item: CohortSelectionV1) -> None: + if item.reason not in _REFUSAL_REASONS: + raise _mismatch() + if item.ecosystem is not None or item.queue_digest is not None or item.selected_entries or item.targeted_families: + raise _mismatch() + + +def _count_value(pairs: tuple[tuple[str, int], ...]) -> tuple[dict[str, JsonValue], ...]: + return tuple({"ecosystem": ecosystem, "accepted_positives": count} for ecosystem, count in pairs) + + +def _selection_value(item: CohortSelectionV1, *, include_digest: bool) -> dict[str, JsonValue]: + value: dict[str, JsonValue] = { + "schema_version": COHORT_SELECTION_SCHEMA, + "ecosystem": item.ecosystem, + "selected_entries": item.selected_entries, + "targeted_families": item.targeted_families, + "queue_digest": item.queue_digest, + "census_digest": item.census_digest, + "ecosystem_policy_digest": item.ecosystem_policy_digest, + "ground_truth_policy_digest": item.ground_truth_policy_digest, + "prior_batch_digests": item.prior_batch_digests, + "accepted_families": item.accepted_families, + "accepted_by_ecosystem": _count_value(item.accepted_by_ecosystem), + "status": item.status.value, + "reason": item.reason.value, + } + if include_digest: + value["selection_digest"] = item.selection_digest + return value + + +def cohort_selection_value(item: CohortSelectionV1) -> dict[str, JsonValue]: + """Canonical selection payload used for durable persistence and exact rereads.""" + return _selection_value(item, include_digest=True) + + +def cohort_selection_bytes(item: CohortSelectionV1) -> bytes: + """Encode a digest-consistent selection decision as canonical bytes.""" + if item.selection_digest != content_digest(_selection_value(item, include_digest=False)): + raise _mismatch() + return canonical_bytes(cohort_selection_value(item)) + + +def cohort_selection( + *, + ecosystem: str | None, + selected_entries: Iterable[str], + targeted_families: Iterable[str], + queue_digest: str | None, + census_digest: str, + ecosystem_policy_digest: str, + ground_truth_policy_digest: str, + prior_batch_digests: Iterable[str], + accepted_families: Iterable[str], + accepted_by_ecosystem: Mapping[str, int], + status: CohortSelectionStatus, + reason: CohortSelectionReason, +) -> CohortSelectionV1: + """Assemble one durable selection decision bound to its exact inputs.""" + draft = CohortSelectionV1( + ecosystem, + tuple(sorted(set(selected_entries))), + tuple(sorted(set(targeted_families))), + queue_digest, + census_digest, + ecosystem_policy_digest, + ground_truth_policy_digest, + tuple(sorted(set(prior_batch_digests))), + tuple(sorted(set(accepted_families))), + tuple((ecosystem, accepted_by_ecosystem[ecosystem]) for ecosystem in sorted(accepted_by_ecosystem)), + status, + reason, + "", + ) + return replace(draft, selection_digest=content_digest(_selection_value(draft, include_digest=False))) + + +def _ledger_facts(batches: Sequence[CohortBatchOutcomeV1]) -> _LedgerFacts: + """Derive family and ecosystem facts from recorded review evidence only.""" + digests: set[str] = set() + families: set[str] = set() + by_ecosystem: dict[str, frozenset[str]] = {} + counts: dict[str, int] = {} + censuses: set[str] = set() + policies: set[tuple[str, str]] = set() + for batch in batches: + try: + ecosystem = batch.ecosystem + if ecosystem not in COHORT_SELECTION_ECOSYSTEMS: + raise _mismatch() + census = _closed_digest(batch.census_digest) + eco_policy = _closed_digest(batch.ecosystem_policy_digest) + gt_policy = _closed_digest(batch.ground_truth_policy_digest) + digests.add(_closed_digest(batch.batch_digest)) + batch_families: set[str] = set() + for positive in batch.accepted_positives: + for scope in positive.verified_scopes: + if scope.ecosystem.value != ecosystem: + raise _mismatch() + batch_families.add(scope.vulnerability_family) + except (AttributeError, TypeError, ValueError) as error: + raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error + censuses.add(census) + policies.add((eco_policy, gt_policy)) + families.update(batch_families) + by_ecosystem[ecosystem] = frozenset(batch_families | by_ecosystem.get(ecosystem, frozenset())) + counts[ecosystem] = counts.get(ecosystem, 0) + len(batch.accepted_positives) + return _LedgerFacts( + tuple(sorted(digests)), + tuple(sorted(families)), + by_ecosystem, + counts, + tuple(sorted(censuses)), + tuple(sorted(policies)), + ) + + +def _queue_for(state: SourcingQueueStateV1, ecosystem: str) -> EcosystemReviewQueueV1: + """Fetch one ecosystem queue, failing closed on a malformed state.""" + try: + queue = state.python_queue if ecosystem == "python" else state.javascript_queue + if queue.ecosystem != ecosystem: + raise _mismatch() + except (AttributeError, TypeError, ValueError) as error: + raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error + return queue + + +def _answered_entries( + state: SourcingQueueStateV1, + batches: Sequence[CohortBatchOutcomeV1], +) -> dict[str, frozenset[str]]: + """Entry digests each ecosystem queue has already surrendered to a ledger batch.""" + queued = { + ecosystem: {entry.entry_digest for entry in _queue_for(state, ecosystem).entries} + for ecosystem in COHORT_SELECTION_ECOSYSTEMS + } + answered: dict[str, set[str]] = {ecosystem: set() for ecosystem in COHORT_SELECTION_ECOSYSTEMS} + for batch in batches: + try: + ecosystem = batch.ecosystem + pending = set(batch.pending_entries) + except (AttributeError, TypeError, ValueError) as error: + raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error + if ecosystem in answered: + answered[ecosystem] |= queued[ecosystem] - pending + return {ecosystem: frozenset(digests) for ecosystem, digests in answered.items()} + + +def _pending_for( + state: SourcingQueueStateV1, + answered: Mapping[str, frozenset[str]], + ecosystem: str, +) -> tuple[ReviewQueueEntryV1, ...]: + """Pending entries of one ecosystem queue in canonical digest order.""" + entries = _queue_for(state, ecosystem).entries + consumed = answered.get(ecosystem, frozenset()) + return tuple(entry for entry in entries if entry.entry_digest not in consumed) + + +def _ecosystem_rank( + pending: Sequence[ReviewQueueEntryV1], + ecosystem: str, + facts: _LedgerFacts, +) -> tuple[int, int, int, int, str]: + """Rank one ecosystem by gap facts of record, never by how reviews resolved.""" + missing_ecosystem = facts.accepted_by_ecosystem.get(ecosystem, 0) == 0 + new_family_pending = any(entry.family.vulnerability_family not in facts.families for entry in pending) + gap_class = 0 if (len(facts.families) < REQUIRED_DISTINCT_FAMILIES and new_family_pending) else 1 + feasible = 0 if len(pending) >= MINIMUM_ACCEPTED_POSITIVES else 1 + coverage = len(facts.families_by_ecosystem.get(ecosystem, frozenset())) + return (0 if missing_ecosystem else 1, gap_class, feasible, coverage, ecosystem) + + +def _selected_entries( + pending: Sequence[ReviewQueueEntryV1], + represented: frozenset[str], +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Pending entries with family-gap priority, bounded by the cohort cap.""" + prioritized = sorted( + pending, + key=lambda entry: (entry.family.vulnerability_family in represented, entry.entry_digest), + ) + chosen = prioritized[:COHORT_BATCH_CAP] + return ( + tuple(entry.entry_digest for entry in chosen), + tuple(sorted({entry.family.vulnerability_family for entry in chosen} - represented)), + ) + + +def _decision_reason(ecosystem: str, facts: _LedgerFacts, targeted: tuple[str, ...]) -> CohortSelectionReason: + if facts.accepted_by_ecosystem.get(ecosystem, 0) == 0: + return CohortSelectionReason.MISSING_ECOSYSTEM_SELECTED + if len(facts.families) < REQUIRED_DISTINCT_FAMILIES and targeted: + return CohortSelectionReason.FAMILY_GAP_SELECTED + return CohortSelectionReason.BALANCED_PROGRESS_SELECTED + + +def _census_refused(facts: _LedgerFacts, state_census: str) -> bool: + return len(facts.census_digests) > 1 or (bool(facts.census_digests) and facts.census_digests[0] != state_census) + + +def _policy_refused(facts: _LedgerFacts, expected: tuple[str, str]) -> bool: + return any(pair != expected for pair in facts.policy_pairs) + + +def _refused( + reason: CohortSelectionReason, + facts: _LedgerFacts, + *, + census_digest: str, + ecosystem_policy_digest: str, + ground_truth_policy_digest: str, +) -> CohortSelectionV1: + """Bind one closed refusal to the exact ledger facts it examined.""" + return cohort_selection( + ecosystem=None, + selected_entries=(), + targeted_families=(), + queue_digest=None, + census_digest=census_digest, + ecosystem_policy_digest=ecosystem_policy_digest, + ground_truth_policy_digest=ground_truth_policy_digest, + prior_batch_digests=facts.batch_digests, + accepted_families=facts.families, + accepted_by_ecosystem=facts.accepted_by_ecosystem, + status=CohortSelectionStatus.REFUSED, + reason=reason, + ) + + +def select_third_cohort_batch( + *, + state: SourcingQueueStateV1, + accepted_batches: Sequence[CohortBatchOutcomeV1], + expected_ecosystem_policy_digest: str, + expected_ground_truth_policy_digest: str, +) -> CohortSelectionV1: + """Select the next bounded cohort batch from one shared reservation snapshot. + + The durable decision is a function of pending queue state, the accepted + ledger's recorded family facts, and the frozen policy digests; how many + reviews passed or failed cannot re-weight it. + """ + facts = _ledger_facts(accepted_batches) + try: + census = _closed_digest(state.census_digest) + eco_policy = _closed_digest(expected_ecosystem_policy_digest) + gt_policy = _closed_digest(expected_ground_truth_policy_digest) + except (AttributeError, TypeError, ValueError) as error: + raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error + if _census_refused(facts, census): + return _refused( + CohortSelectionReason.CENSUS_MISMATCH, + facts, + census_digest=census, + ecosystem_policy_digest=eco_policy, + ground_truth_policy_digest=gt_policy, + ) + if _policy_refused(facts, (eco_policy, gt_policy)): + return _refused( + CohortSelectionReason.POLICY_MISMATCH, + facts, + census_digest=census, + ecosystem_policy_digest=eco_policy, + ground_truth_policy_digest=gt_policy, + ) + try: + answered = _answered_entries(state, accepted_batches) + ranked = sorted( + _ecosystem_rank(_pending_for(state, answered, ecosystem), ecosystem, facts) + for ecosystem in COHORT_SELECTION_ECOSYSTEMS + ) + for rank in ranked: + ecosystem = rank[4] + pending = _pending_for(state, answered, ecosystem) + if not pending: + continue + chosen, targeted = _selected_entries(pending, facts.families_by_ecosystem.get(ecosystem, frozenset())) + return cohort_selection( + ecosystem=ecosystem, + selected_entries=chosen, + targeted_families=targeted, + queue_digest=_queue_for(state, ecosystem).queue_digest, + census_digest=census, + ecosystem_policy_digest=eco_policy, + ground_truth_policy_digest=gt_policy, + prior_batch_digests=facts.batch_digests, + accepted_families=facts.families, + accepted_by_ecosystem=facts.accepted_by_ecosystem, + status=CohortSelectionStatus.SELECTED, + reason=_decision_reason(ecosystem, facts, targeted), + ) + except CohortSelectionStateError: + raise + except (AttributeError, TypeError, ValueError) as error: + raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error + return _refused( + CohortSelectionReason.NO_PENDING_ENTRIES, + facts, + census_digest=census, + ecosystem_policy_digest=eco_policy, + ground_truth_policy_digest=gt_policy, + ) + + +def _require_selection_binding( + selection: CohortSelectionV1, + state: SourcingQueueStateV1, + expected_ecosystem_policy_digest: str, + expected_ground_truth_policy_digest: str, +) -> EcosystemReviewQueueV1: + if selection.status is not CohortSelectionStatus.SELECTED or selection.ecosystem not in COHORT_SELECTION_ECOSYSTEMS: + raise _mismatch() + if ( + selection.census_digest != state.census_digest + or selection.ecosystem_policy_digest != expected_ecosystem_policy_digest + or selection.ground_truth_policy_digest != expected_ground_truth_policy_digest + ): + raise _mismatch() + full = _queue_for(state, selection.ecosystem) + if selection.queue_digest != full.queue_digest: + raise _mismatch() + return full + + +def _narrowed_queue(selection: CohortSelectionV1, full: EcosystemReviewQueueV1) -> EcosystemReviewQueueV1: + wanted = set(selection.selected_entries) + kept = tuple(entry for entry in full.entries if entry.entry_digest in wanted) + if {entry.entry_digest for entry in kept} != wanted: + raise _mismatch() + return ecosystem_review_queue(full.ecosystem, cap=full.cap, policy_digest=full.policy_digest, entries=kept) + + +def _selection_state( + selection: CohortSelectionV1, + state: SourcingQueueStateV1, + *, + expected_ecosystem_policy_digest: str, + expected_ground_truth_policy_digest: str, +) -> SourcingQueueStateV1: + """Narrow the selected ecosystem queue to exactly the selected entries.""" + try: + full = _require_selection_binding( + selection, state, expected_ecosystem_policy_digest, expected_ground_truth_policy_digest + ) + narrowed = _narrowed_queue(selection, full) + python_queue = narrowed if selection.ecosystem == "python" else state.python_queue + javascript_queue = narrowed if selection.ecosystem == "javascript" else state.javascript_queue + return sourcing_queue_state( + python_queue=python_queue, + javascript_queue=javascript_queue, + exclusions=state.exclusions, + census_digest=state.census_digest, + policy_digest=state.policy_digest, + ) + except CohortSelectionStateError: + raise + except (AttributeError, TypeError, ValueError) as error: + raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error + + +def ingest_third_cohort_batch( + records: Sequence[bytes], + *, + selection: CohortSelectionV1, + state: SourcingQueueStateV1, + candidates_by_digest: Mapping[str, FixSiteCandidateV1], + expected_ecosystem_policy_digest: str, + expected_ground_truth_policy_digest: str, +) -> CohortBatchOutcomeV1: + """Ingest the selected bounded third cohort through the committed machinery.""" + narrowed = _selection_state( + selection, + state, + expected_ecosystem_policy_digest=expected_ecosystem_policy_digest, + expected_ground_truth_policy_digest=expected_ground_truth_policy_digest, + ) + ingest = ingest_python_cohort_batch if selection.ecosystem == "python" else ingest_javascript_cohort_batch + return ingest( + records, + state=narrowed, + candidates_by_digest=candidates_by_digest, + expected_ecosystem_policy_digest=expected_ecosystem_policy_digest, + expected_ground_truth_policy_digest=expected_ground_truth_policy_digest, + ) + + +__all__ = [ + "COHORT_SELECTION_ECOSYSTEMS", + "COHORT_SELECTION_SCHEMA", + "CohortSelectionReason", + "CohortSelectionStateError", + "CohortSelectionStateReason", + "CohortSelectionStatus", + "CohortSelectionV1", + "REQUIRED_DISTINCT_FAMILIES", + "cohort_selection", + "cohort_selection_bytes", + "cohort_selection_value", + "ingest_third_cohort_batch", + "select_third_cohort_batch", +] diff --git a/benchmarks/valid/cohort_selection_store.py b/benchmarks/valid/cohort_selection_store.py new file mode 100644 index 00000000..1b95efd0 --- /dev/null +++ b/benchmarks/valid/cohort_selection_store.py @@ -0,0 +1,147 @@ +"""Durable persistence, hostile decode, and replay for cohort selection decisions.""" + +from __future__ import annotations + +import json +import math +from typing import Any + +from benchmarks.valid.artifact_repository import ArtifactReadAuthority, S3ArtifactRepository +from benchmarks.valid.cohort_selection import ( + COHORT_SELECTION_SCHEMA, + CohortSelectionReason, + CohortSelectionStateError, + CohortSelectionStateReason, + CohortSelectionStatus, + CohortSelectionV1, + cohort_selection, + cohort_selection_bytes, + cohort_selection_value, +) +from benchmarks.valid.replacement_artifact_contract import ( + ArtifactAccessClass, + ArtifactKind, + ArtifactReference, + artifact_reference, + canonical_artifact_bytes, +) +from openultrasast.core.canonical import canonical_bytes + +_SELECTION_KEYS = frozenset( + { + "schema_version", + "ecosystem", + "selected_entries", + "targeted_families", + "queue_digest", + "census_digest", + "ecosystem_policy_digest", + "ground_truth_policy_digest", + "prior_batch_digests", + "accepted_families", + "accepted_by_ecosystem", + "status", + "reason", + "selection_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 CohortSelectionStateError(CohortSelectionStateReason.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 CohortSelectionStateError(CohortSelectionStateReason.STATE_UNREADABLE) from None + if not isinstance(value, dict) or canonical != content: + raise CohortSelectionStateError(CohortSelectionStateReason.STATE_UNREADABLE) + return value + + +def decode_cohort_selection(content: bytes) -> CohortSelectionV1: + """Rebuild one selection decision only from canonical, digest-consistent bytes.""" + value = _decoded_value(content) + if set(value) != _SELECTION_KEYS or value["schema_version"] != COHORT_SELECTION_SCHEMA: + raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) + try: + selection = cohort_selection( + ecosystem=value["ecosystem"], + selected_entries=tuple(value["selected_entries"]), + targeted_families=tuple(value["targeted_families"]), + queue_digest=value["queue_digest"], + census_digest=value["census_digest"], + ecosystem_policy_digest=value["ecosystem_policy_digest"], + ground_truth_policy_digest=value["ground_truth_policy_digest"], + prior_batch_digests=tuple(value["prior_batch_digests"]), + accepted_families=tuple(value["accepted_families"]), + accepted_by_ecosystem={item["ecosystem"]: item["accepted_positives"] for item in value["accepted_by_ecosystem"]}, + status=CohortSelectionStatus(value["status"]), + reason=CohortSelectionReason(value["reason"]), + ) + except (AttributeError, KeyError, TypeError, ValueError) as error: + raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error + if cohort_selection_bytes(selection) != content: + raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) + return selection + + +def persist_cohort_selection(store: S3ArtifactRepository, selection: CohortSelectionV1) -> ArtifactReference: + """Persist one durable selection decision bound to the reservation snapshot.""" + content = canonical_artifact_bytes( + ArtifactKind.POPULATION, + cohort_selection_value(selection), + access_class=ArtifactAccessClass.OPERATOR_SAFE, + provenance_digest=selection.census_digest, + ) + return store.put_if_absent(content, reference=artifact_reference(content)) + + +def resume_cohort_selection( + store: S3ArtifactRepository, + reference: ArtifactReference, + *, + authority: ArtifactReadAuthority, + expected_access_policy_digest: str, +) -> CohortSelectionV1: + """Resume one selection decision 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 CohortSelectionStateError(CohortSelectionStateReason.STATE_UNREADABLE) from None + return decode_cohort_selection(content) + + +__all__ = [ + "decode_cohort_selection", + "persist_cohort_selection", + "resume_cohort_selection", +] diff --git a/tests/cohort_ingestion_fixtures.py b/tests/cohort_ingestion_fixtures.py index aaffa55c..194272a8 100644 --- a/tests/cohort_ingestion_fixtures.py +++ b/tests/cohort_ingestion_fixtures.py @@ -15,7 +15,12 @@ from dataclasses import replace from typing import Any from benchmarks.valid.catalog import candidate_request -from benchmarks.valid.cohort_ingestion import EXTERNAL_REVIEW_RECORD_SCHEMA +from benchmarks.valid.cohort_ingestion import ( + EXTERNAL_REVIEW_RECORD_SCHEMA, + CohortBatchOutcomeV1, + ingest_javascript_cohort_batch, + ingest_python_cohort_batch, +) from benchmarks.valid.ecosystem_review import ( EcosystemReviewAttestationV1, EcosystemReviewDecision, @@ -53,6 +58,12 @@ PYTHON_COUNT = 12 JAVASCRIPT_NAMES = tuple(f"js-{index:02d}" for index in range(10)) TYPESCRIPT_NAMES = ("ts-00", "ts-01") JAVASCRIPT_COUNT = len(JAVASCRIPT_NAMES) + len(TYPESCRIPT_NAMES) +COMBINED_PYTHON_NAMES = tuple(f"py-{index:02d}" for index in range(PYTHON_COUNT)) +COMBINED_JAVASCRIPT_NAMES = (*JAVASCRIPT_NAMES, *TYPESCRIPT_NAMES) +THIRD_PYTHON_NAMES = tuple(f"py3-{index:02d}" for index in range(12)) +THIRD_JAVASCRIPT_NAMES = (*(f"js3-{index:02d}" for index in range(10)), "ts3-00", "ts3-01") +SINGLE_FAMILY_PYTHON_NAMES = tuple(f"pyinj-{index:02d}" for index in range(12)) +SINGLE_FAMILY_JAVASCRIPT_NAMES = tuple(f"jsinj-{index:02d}" for index in range(12)) _APPS: dict[str, dict[str, Any]] = {} for _index in range(PYTHON_COUNT): @@ -125,10 +136,88 @@ for _name, _path, _function, _family, _cwe in ( "vulnerable": f"export function {_function}(input: string) {{\n return eval(input);\n}}\n", "fixed": f"export function {_function}(input: string) {{\n return String(input);\n}}\n", } +for _index in range(12): + _apps_key = f"pyinj-{_index:02d}" + _APPS[_apps_key] = { + "url": f"https://github.com/fixture/cohort-{_apps_key}", + "repo": f"fixture/cohort-{_apps_key}", + "path": f"pkg/inj_{_index:02d}.py", + "function": f"invoke_{_index:02d}", + "language": "python", + "hint": "python", + "family": "injection", + "cwe": "CWE-94", + "vulnerable": f"def invoke_{_index:02d}(query):\n return eval(query)\n", + "fixed": f"def invoke_{_index:02d}(query):\n return str(query)\n", + } +for _index in range(12): + _apps_key = f"jsinj-{_index:02d}" + _APPS[_apps_key] = { + "url": f"https://github.com/fixture/cohort-{_apps_key}", + "repo": f"fixture/cohort-{_apps_key}", + "path": f"lib/inj_{_index:02d}.js", + "function": f"render_{_index:02d}", + "language": "javascript", + "hint": "javascript", + "family": "injection", + "cwe": "CWE-94", + "vulnerable": f"function render_{_index:02d}(input) {{\n return eval(input);\n}}\n", + "fixed": f"function render_{_index:02d}(input) {{\n return String(input);\n}}\n", + } +for _index in range(12): + _family = "deserialization" if _index % 2 == 0 else "ssrf" + _apps_key = f"py3-{_index:02d}" + _APPS[_apps_key] = { + "url": f"https://github.com/fixture/cohort-{_apps_key}", + "repo": f"fixture/cohort-{_apps_key}", + "path": f"app/third_{_index:02d}.py", + "function": f"dispatch_{_index:02d}", + "language": "python", + "hint": "python", + "family": _family, + "cwe": "CWE-502" if _family == "deserialization" else "CWE-918", + "vulnerable": f"def dispatch_{_index:02d}(payload):\n return eval(payload)\n", + "fixed": f"def dispatch_{_index:02d}(payload):\n return str(payload)\n", + } +for _index in range(10): + _family = "prototype_pollution" if _index % 2 == 0 else "output_encoding" + _apps_key = f"js3-{_index:02d}" + _APPS[_apps_key] = { + "url": f"https://github.com/fixture/cohort-{_apps_key}", + "repo": f"fixture/cohort-{_apps_key}", + "path": f"lib/third_{_index:02d}.js", + "function": f"merge_{_index:02d}", + "language": "javascript", + "hint": "javascript", + "family": _family, + "cwe": "CWE-1321" if _family == "prototype_pollution" else "CWE-79", + "vulnerable": f"function merge_{_index:02d}(input) {{\n return eval(input);\n}}\n", + "fixed": f"function merge_{_index:02d}(input) {{\n return String(input);\n}}\n", + } +for _name, _function, _family, _cwe in ( + ("ts3-00", "loadPayload", "deserialization", "CWE-502"), + ("ts3-01", "fetchTarget", "ssrf", "CWE-918"), +): + _APPS[_name] = { + "url": f"https://github.com/fixture/cohort-{_name}", + "repo": f"fixture/cohort-{_name}", + "path": f"src/{_name}.ts", + "function": _function, + "language": "typescript", + "hint": "javascript", + "family": _family, + "cwe": _cwe, + "vulnerable": f"export function {_function}(input: string) {{\n return eval(input);\n}}\n", + "fixed": f"export function {_function}(input: string) {{\n return String(input);\n}}\n", + } _STABLE_APP_ORDER = ("js-00", "js-01", *(f"py-{index:02d}" for index in range(PYTHON_COUNT))) _NEW_APP_ORDER = (*JAVASCRIPT_NAMES[2:], *TYPESCRIPT_NAMES) _REVISIONS = {name: (f"{5000 + index * 2:040x}", f"{5001 + index * 2:040x}") for index, name in enumerate(_STABLE_APP_ORDER)} _REVISIONS.update({name: (f"{6000 + index * 2:040x}", f"{6001 + index * 2:040x}") for index, name in enumerate(_NEW_APP_ORDER)}) +_THIRD_ORDER = (*THIRD_PYTHON_NAMES, *THIRD_JAVASCRIPT_NAMES) +_REVISIONS.update({name: (f"{7000 + index * 2:040x}", f"{7001 + index * 2:040x}") for index, name in enumerate(_THIRD_ORDER)}) +_SINGLE_FAMILY_ORDER = (*SINGLE_FAMILY_PYTHON_NAMES, *SINGLE_FAMILY_JAVASCRIPT_NAMES) +_REVISIONS.update({name: (f"{8000 + index * 2:040x}", f"{8001 + index * 2:040x}") for index, name in enumerate(_SINGLE_FAMILY_ORDER)}) READ_POLICY = bytes_digest(b"cohort-ingestion-read-policy-fixture") @@ -430,7 +519,80 @@ def model_only_assistance_digest() -> str: return verify.model_assistance_digest(record) +def candidate_for(name: str, resolver_: RepositoryIdentityResolver) -> FixSiteCandidateV1: + """Build one fix-site candidate for a named fixture app.""" + return next(iter(candidates_for([request_for(name)], resolver_).values())) + + +def replacement_cohort_state( + python_names: tuple[str, ...] = (*COMBINED_PYTHON_NAMES, *THIRD_PYTHON_NAMES), + javascript_names: tuple[str, ...] = (*COMBINED_JAVASCRIPT_NAMES, *THIRD_JAVASCRIPT_NAMES), + *, + per_ecosystem_cap: int | None = None, + resolver_: RepositoryIdentityResolver | None = None, + authority_: ReservationAuthority | None = None, +) -> tuple[SourcingQueueStateV1, RepositoryIdentityResolver]: + """One shared queue state carrying the ingested cohorts and the pending third. + + Every cohort round reads this same state, so the accepted ledger and the + pending queues always share one reservation-census snapshot. + """ + resolved = resolver_ or resolver() + cap = per_ecosystem_cap or max(len(python_names), len(javascript_names)) + state = build_sourcing_queue( + [request_for(name) for name in (*python_names, *javascript_names)], + reader=FakeReader(), + resolver=resolved, + authority=authority_ or authority(resolved), + policy=sourcing_queue_policy(per_ecosystem_cap=cap, required_families=2), + enumeration_actor=ENUMERATION_ACTOR, + enumeration_reviewer=ENUMERATION_REVIEWER, + ) + return state, resolved + + +def ingested_replacement_ledger( + state: SourcingQueueStateV1, + resolved: RepositoryIdentityResolver, + *, + python_names: tuple[str, ...] = COMBINED_PYTHON_NAMES, + javascript_names: tuple[str, ...] = COMBINED_JAVASCRIPT_NAMES, + weakened_python: int = 0, + weakened_javascript: int = 0, +) -> tuple[CohortBatchOutcomeV1, ...]: + """Ingest the committed first cohorts against one shared queue state.""" + batches: list[CohortBatchOutcomeV1] = [] + rounds = ( + ("python", python_names, weakened_python, ingest_python_cohort_batch), + ("javascript", javascript_names, weakened_javascript, ingest_javascript_cohort_batch), + ) + for ecosystem, names, weakened, ingest in rounds: + if not names: + continue + queue = state.python_queue if ecosystem == "python" else state.javascript_queue + by_candidate = {entry.candidate_digest: entry for entry in queue.entries} + candidates = {name: candidate_for(name, resolved) for name in names} + records = [] + for index, name in enumerate(names): + candidate = candidates[name] + entry = by_candidate[candidate.candidate_digest] + changes = {"in_repository_reachable": False} if index < weakened else None + records.append(reviewed_record(entry, candidate, ecosystem=ecosystem, gt_changes=changes)[0]) + batches.append( + ingest( + records, + state=state, + candidates_by_digest={item.candidate_digest: item for item in candidates.values()}, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + ) + return tuple(batches) + + __all__ = [ + "COMBINED_JAVASCRIPT_NAMES", + "COMBINED_PYTHON_NAMES", "ECOSYSTEM_POLICY", "ECOSYSTEM_PRODUCER", "ECOSYSTEM_REVIEWER", @@ -443,16 +605,23 @@ __all__ = [ "PYTHON_COUNT", "READ_POLICY", "RepositoryEcosystemReviewV1", + "SINGLE_FAMILY_JAVASCRIPT_NAMES", + "SINGLE_FAMILY_PYTHON_NAMES", + "THIRD_JAVASCRIPT_NAMES", + "THIRD_PYTHON_NAMES", "TYPESCRIPT_NAMES", "authority", + "candidate_for", "candidates_for", "case_for", + "ingested_replacement_ledger", "javascript_cohort_state", "javascript_entries", "javascript_request_names", "model_only_assistance_digest", "python_cohort_state", "python_entries", + "replacement_cohort_state", "request_for", "resolver", "reviewed_record", diff --git a/tests/test_valid_benchmark_cohort_selection.py b/tests/test_valid_benchmark_cohort_selection.py new file mode 100644 index 00000000..5100b665 --- /dev/null +++ b/tests/test_valid_benchmark_cohort_selection.py @@ -0,0 +1,367 @@ +"""Outcome-blind selection of the third bounded cohort batch over pending queues.""" + +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, + GROUND_TRUTH_POLICY, + READ_POLICY, + SINGLE_FAMILY_JAVASCRIPT_NAMES, + SINGLE_FAMILY_PYTHON_NAMES, + THIRD_JAVASCRIPT_NAMES, + THIRD_PYTHON_NAMES, + _Client, + _read_authority, + _settings, + authority, + ingested_replacement_ledger, + replacement_cohort_state, + resolver, +) + +from benchmarks.valid.artifact_repository import S3ArtifactRepository # noqa: E402 +from benchmarks.valid.cohort_selection import ( # noqa: E402 + COHORT_BATCH_CAP, + CohortSelectionReason, + CohortSelectionStateError, + CohortSelectionStateReason, + CohortSelectionStatus, + cohort_selection, + cohort_selection_bytes, + select_third_cohort_batch, +) +from benchmarks.valid.cohort_selection_store import ( # noqa: E402 + decode_cohort_selection, + persist_cohort_selection, + resume_cohort_selection, +) +from benchmarks.valid.replacement_artifact_contract import ArtifactAccessClass, ArtifactKind, validate_artifact # noqa: E402 +from benchmarks.valid.reservation import legacy_reservation_source # noqa: E402 +from benchmarks.valid.sourcing_queue import ecosystem_review_queue, sourcing_queue_policy, sourcing_queue_state # noqa: E402 +from openultrasast.core.canonical import content_digest # noqa: E402 + +THIRD_PYTHON_FAMILIES = {"deserialization", "ssrf"} + + +@pytest.fixture(autouse=True) +def offline(monkeypatch): + def forbidden(*args, **kwargs): + pytest.fail("network or SZZ was invoked") + + import socket + + from benchmarks.unseen import extract + + monkeypatch.setattr(socket, "create_connection", forbidden) + monkeypatch.setattr(socket.socket, "connect", forbidden) + monkeypatch.setattr(extract, "introducing", forbidden) + monkeypatch.setattr(extract.Git, "blame", forbidden) + + +def _select(state, ledger, *, eco=ECOSYSTEM_POLICY, gt=GROUND_TRUTH_POLICY): + return select_third_cohort_batch( + state=state, + accepted_batches=ledger, + expected_ecosystem_policy_digest=eco, + expected_ground_truth_policy_digest=gt, + ) + + +def _prepared(): + state, resolved = replacement_cohort_state() + ledger = ingested_replacement_ledger(state, resolved) + return state, resolved, ledger + + +def test_selection_balances_family_coverage_across_both_ecosystems(): + state, resolved, ledger = _prepared() + assert {batch.ecosystem for batch in ledger} == {"python", "javascript"} + + selection = _select(state, ledger) + + assert selection.status is CohortSelectionStatus.SELECTED + assert selection.ecosystem == "python" + assert selection.reason is CohortSelectionReason.BALANCED_PROGRESS_SELECTED + expected = sorted( + entry.entry_digest for entry in state.python_queue.entries if entry.family.vulnerability_family in THIRD_PYTHON_FAMILIES + ) + assert selection.selected_entries == tuple(expected) + assert selection.targeted_families == ("deserialization", "ssrf") + assert selection.accepted_families == ("injection", "output_encoding", "path_traversal") + assert dict(selection.accepted_by_ecosystem) == {"javascript": 12, "python": 12} + assert selection.census_digest == state.census_digest + assert selection.queue_digest == state.python_queue.queue_digest + assert selection.prior_batch_digests == tuple(sorted(batch.batch_digest for batch in ledger)) + assert decode_cohort_selection(cohort_selection_bytes(selection)) == selection + + +def test_selection_targets_a_missing_ecosystem_to_preserve_both(): + state, resolved = replacement_cohort_state() + ledger = ingested_replacement_ledger(state, resolved, javascript_names=()) + + selection = _select(state, ledger) + + assert selection.status is CohortSelectionStatus.SELECTED + assert selection.ecosystem == "javascript" + assert selection.reason is CohortSelectionReason.MISSING_ECOSYSTEM_SELECTED + assert dict(selection.accepted_by_ecosystem) == {"python": 12} + pending = sorted(state.javascript_queue.entries, key=lambda entry: entry.entry_digest) + assert selection.selected_entries == tuple(entry.entry_digest for entry in pending[:COHORT_BATCH_CAP]) + assert selection.targeted_families == tuple( + sorted({entry.family.vulnerability_family for entry in pending[:COHORT_BATCH_CAP]}) + ) + + +def test_selection_targets_the_second_vulnerability_family_gap(): + state, resolved = replacement_cohort_state( + python_names=("py-01", "py-03", *SINGLE_FAMILY_PYTHON_NAMES, *THIRD_PYTHON_NAMES), + javascript_names=("js-01", *SINGLE_FAMILY_JAVASCRIPT_NAMES, *THIRD_JAVASCRIPT_NAMES), + ) + ledger = ingested_replacement_ledger( + state, + resolved, + python_names=("py-01", "py-03", *SINGLE_FAMILY_PYTHON_NAMES), + javascript_names=("js-01", *SINGLE_FAMILY_JAVASCRIPT_NAMES), + weakened_python=2, + weakened_javascript=1, + ) + ledger_families = { + scope.vulnerability_family + for batch in ledger + for item in batch.accepted_positives + for scope in item.verified_scopes + } + assert ledger_families == {"injection"} + + selection = _select(state, ledger) + + assert selection.status is CohortSelectionStatus.SELECTED + assert selection.reason is CohortSelectionReason.FAMILY_GAP_SELECTED + assert selection.ecosystem == "javascript" + assert selection.targeted_families == ("deserialization", "output_encoding", "prototype_pollution", "ssrf") + js_batch = next(batch for batch in ledger if batch.ecosystem == "javascript") + pending = set(js_batch.pending_entries) + assert set(selection.selected_entries) == pending + typescript = [entry for entry in state.javascript_queue.entries if entry.observed_language == "typescript"] + assert typescript and all(entry.entry_digest in pending for entry in typescript) + assert all(entry.canonical_ecosystem == "javascript" for entry in typescript) + + +def test_selection_ignores_how_many_reviews_passed(): + state, resolved = replacement_cohort_state() + full = ingested_replacement_ledger(state, resolved) + thinned = ingested_replacement_ledger(state, resolved, weakened_python=2) + assert len(thinned[0].accepted_positives) < len(full[0].accepted_positives) + + chosen = _select(state, full) + other = _select(state, thinned) + + assert (chosen.status, chosen.reason, chosen.ecosystem) == (other.status, other.reason, other.ecosystem) + assert chosen.selected_entries == other.selected_entries + assert chosen.targeted_families == other.targeted_families + assert chosen.selection_digest != other.selection_digest + + +def test_selection_refuses_a_reweighted_policy_after_judgments(): + state, resolved, ledger = _prepared() + + changed = _select(state, ledger, eco=content_digest({"policy": "reweighted-after-outcomes"})) + frozen = _select(state, ledger) + + assert changed.status is CohortSelectionStatus.REFUSED + assert changed.reason is CohortSelectionReason.POLICY_MISMATCH + assert changed.selected_entries == () and changed.targeted_families == () + assert frozen.status is CohortSelectionStatus.SELECTED + + +def test_selection_refuses_a_stale_reservation_census(): + state, resolved, ledger = _prepared() + reserved = legacy_reservation_source( + resolved, repository="https://github.com/fixture/cohort-pyinj-00", source_digest="c" * 64 + ) + stale_state, _ = replacement_cohort_state(authority_=authority(resolver(), legacy=(reserved,))) + assert stale_state.census_digest != state.census_digest + assert [entry.entry_digest for entry in stale_state.python_queue.entries] == [ + entry.entry_digest for entry in state.python_queue.entries + ] + + selection = _select(stale_state, ledger) + + assert selection.status is CohortSelectionStatus.REFUSED + assert selection.reason is CohortSelectionReason.CENSUS_MISMATCH + assert selection.census_digest == stale_state.census_digest + assert decode_cohort_selection(cohort_selection_bytes(selection)) == selection + + +def test_selection_without_pending_entries_refuses_closed(): + state, _, ledger = _prepared() + policy = sourcing_queue_policy(per_ecosystem_cap=1) + empty = sourcing_queue_state( + python_queue=ecosystem_review_queue("python", cap=1, policy_digest=policy.policy_digest, entries=()), + javascript_queue=ecosystem_review_queue("javascript", cap=1, policy_digest=policy.policy_digest, entries=()), + exclusions=(), + census_digest=state.census_digest, + policy_digest=policy.policy_digest, + ) + + selection = _select(empty, ledger) + + assert selection.status is CohortSelectionStatus.REFUSED + assert selection.reason is CohortSelectionReason.NO_PENDING_ENTRIES + assert selection.ecosystem is None and selection.queue_digest is None + assert decode_cohort_selection(cohort_selection_bytes(selection)) == selection + + +def test_selection_is_deterministic_across_permutations(): + forward, resolved = replacement_cohort_state() + backward, _ = replacement_cohort_state( + python_names=tuple(reversed((*COMBINED_PYTHON_NAMES, *THIRD_PYTHON_NAMES))), + javascript_names=tuple(reversed((*COMBINED_JAVASCRIPT_NAMES, *THIRD_JAVASCRIPT_NAMES))), + ) + assert forward.state_digest == backward.state_digest + ledger = ingested_replacement_ledger(forward, resolved) + + assert _select(forward, ledger) == _select(backward, ledger) + + +def test_selection_caps_at_twenty_preferring_family_gaps(): + state, resolved = replacement_cohort_state( + python_names=(*COMBINED_PYTHON_NAMES, *THIRD_PYTHON_NAMES, *SINGLE_FAMILY_PYTHON_NAMES), + ) + ledger = ingested_replacement_ledger(state, resolved) + + selection = _select(state, ledger) + + assert selection.status is CohortSelectionStatus.SELECTED + assert selection.ecosystem == "python" + assert len(selection.selected_entries) == COHORT_BATCH_CAP + gap_entries = { + entry.entry_digest + for entry in state.python_queue.entries + if entry.family.vulnerability_family in {"deserialization", "ssrf"} + } + assert gap_entries <= set(selection.selected_entries) + python_batch = next(batch for batch in ledger if batch.ecosystem == "python") + unselected = [ + entry + for entry in state.python_queue.entries + if entry.entry_digest in set(python_batch.pending_entries) + and entry.entry_digest not in set(selection.selected_entries) + ] + assert len(unselected) == 4 + assert {entry.family.vulnerability_family for entry in unselected} == {"injection"} + + +def test_selection_decodes_hostile_bytes_and_persists_durably(): + state, resolved, ledger = _prepared() + selection = _select(state, ledger) + content = cohort_selection_bytes(selection) + assert content and decode_cohort_selection(content) == selection + + 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, "reason": "no_pending_entries"}, 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(CohortSelectionStateError): + decode_cohort_selection(bad) + + client = _Client() + store = S3ArtifactRepository(_settings(), client) + reference = persist_cohort_selection(store, selection) + assert persist_cohort_selection(store, selection) == 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_cohort_selection( + S3ArtifactRepository(_settings(), client), reference, authority=_read_authority(), expected_access_policy_digest=READ_POLICY + ) + assert resumed == selection + assert cohort_selection_bytes(resumed) == content + + +def test_malformed_ledgers_and_states_fail_closed(): + state, _, ledger = _prepared() + forged_census = replace(ledger[0], census_digest="z" * 64) + wrong_ecosystem = replace(ledger[0], ecosystem="typescript") + for bad in (None, {"ecosystem": "python"}, forged_census, wrong_ecosystem): + with pytest.raises(CohortSelectionStateError) as error: + _select(state, (bad,)) + assert error.value.reason is CohortSelectionStateReason.STATE_MISMATCH + + with pytest.raises(CohortSelectionStateError): + _select({"python_queue": ()}, ledger) + + +def test_selection_module_and_outputs_avoid_out_of_scope_machinery(): + root = Path(__file__).resolve().parents[1] + for name in ("benchmarks/valid/cohort_selection.py", "benchmarks/valid/cohort_selection_store.py"): + source = (root / name).read_bytes() + for forbidden in (b"admission", b"detector", b"observation", b"label", b"verdict", b"score"): + assert forbidden not in source, f"{name} references out-of-scope machinery: {forbidden!r}" + + state, resolved, ledger = _prepared() + content = cohort_selection_bytes(_select(state, ledger)) + for forbidden in (b"admission", b"detector", b"observation", b"label", b"verdict", b"score"): + assert forbidden not in content + + stale = (root / "benchmarks/valid/cohort_ingestion.py").read_bytes() + assert b"pending Python review queue entry" not in stale + + +def test_refused_selections_never_carry_entries_or_families(): + state, resolved, ledger = _prepared() + refused = _select(state, ledger, gt=content_digest({"policy": "changed"})) + rebuilt = cohort_selection( + ecosystem=refused.ecosystem, + selected_entries=refused.selected_entries, + targeted_families=refused.targeted_families, + queue_digest=refused.queue_digest, + census_digest=refused.census_digest, + ecosystem_policy_digest=refused.ecosystem_policy_digest, + ground_truth_policy_digest=refused.ground_truth_policy_digest, + prior_batch_digests=refused.prior_batch_digests, + accepted_families=refused.accepted_families, + accepted_by_ecosystem=dict(refused.accepted_by_ecosystem), + status=refused.status, + reason=refused.reason, + ) + assert rebuilt == refused + with pytest.raises(CohortSelectionStateError): + cohort_selection( + ecosystem=None, + selected_entries=(), + targeted_families=(), + queue_digest=None, + census_digest=refused.census_digest, + ecosystem_policy_digest=refused.ecosystem_policy_digest, + ground_truth_policy_digest=refused.ground_truth_policy_digest, + prior_batch_digests=refused.prior_batch_digests, + accepted_families=refused.accepted_families, + accepted_by_ecosystem=dict(refused.accepted_by_ecosystem), + status=CohortSelectionStatus.SELECTED, + reason=refused.reason, + ) diff --git a/tests/test_valid_benchmark_third_cohort_ingestion.py b/tests/test_valid_benchmark_third_cohort_ingestion.py new file mode 100644 index 00000000..e156668f --- /dev/null +++ b/tests/test_valid_benchmark_third_cohort_ingestion.py @@ -0,0 +1,299 @@ +"""Bounded ingestion of the third independently reviewed replacement cohort.""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from cohort_ingestion_fixtures import ( # noqa: E402 + COMBINED_PYTHON_NAMES, + ECOSYSTEM_POLICY, + GROUND_TRUTH_POLICY, + SINGLE_FAMILY_PYTHON_NAMES, + THIRD_JAVASCRIPT_NAMES, + THIRD_PYTHON_NAMES, + candidate_for, + ingested_replacement_ledger, + model_only_assistance_digest, + replacement_cohort_state, + reviewed_record, +) + +from benchmarks.valid.cohort_ingestion import ( # noqa: E402 + COHORT_BATCH_CAP, + MINIMUM_ACCEPTED_POSITIVES, + CohortBatchStatus, + CohortInsufficientReason, + cohort_batch_bytes, +) +from benchmarks.valid.cohort_selection import ( # noqa: E402 + CohortSelectionStateError, + CohortSelectionStateReason, + CohortSelectionStatus, + cohort_selection, + cohort_selection_bytes, + ingest_third_cohort_batch, + select_third_cohort_batch, +) +from benchmarks.valid.ground_truth_review import VerifiedScope # noqa: E402 +from openultrasast.core.canonical import bytes_digest # noqa: E402 + + +@pytest.fixture(autouse=True) +def offline(monkeypatch): + def forbidden(*args, **kwargs): + pytest.fail("network or SZZ was invoked") + + import socket + + from benchmarks.unseen import extract + + monkeypatch.setattr(socket, "create_connection", forbidden) + monkeypatch.setattr(socket.socket, "connect", forbidden) + monkeypatch.setattr(extract, "introducing", forbidden) + monkeypatch.setattr(extract.Git, "blame", forbidden) + + +def _select(state, ledger): + return select_third_cohort_batch( + state=state, + accepted_batches=ledger, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + + +def _candidates(resolved, names): + candidates = {} + for name in names: + candidate = candidate_for(name, resolved) + candidates[candidate.candidate_digest] = candidate + return candidates + + +def _prepared(): + state, resolved = replacement_cohort_state() + ledger = ingested_replacement_ledger(state, resolved) + selection = _select(state, ledger) + candidates = _candidates(resolved, (*THIRD_PYTHON_NAMES, *THIRD_JAVASCRIPT_NAMES)) + return state, resolved, ledger, selection, candidates + + +def _selected_entries(state, selection): + wanted = set(selection.selected_entries) + queue = state.python_queue if selection.ecosystem == "python" else state.javascript_queue + return [entry for entry in queue.entries if entry.entry_digest in wanted] + + +def _ingest(records, selection, state, candidates): + return ingest_third_cohort_batch( + records, + selection=selection, + state=state, + candidates_by_digest=candidates, + expected_ecosystem_policy_digest=ECOSYSTEM_POLICY, + expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY, + ) + + +def test_third_cohort_contributes_ten_accepted_reachable_positives_and_replays(): + state, resolved, ledger, selection, candidates = _prepared() + assert selection.status is CohortSelectionStatus.SELECTED + entries = _selected_entries(state, selection) + assert MINIMUM_ACCEPTED_POSITIVES <= len(entries) <= COHORT_BATCH_CAP + records = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries] + + outcome = _ingest(records, selection, state, candidates) + + assert outcome.status is CohortBatchStatus.ACCEPTED + assert outcome.insufficient_reason is None + assert len(outcome.accepted_positives) == len(entries) >= MINIMUM_ACCEPTED_POSITIVES + assert outcome.pending_entries == () + assert all(item.status.value == "accepted" for item in outcome.record_outcomes) + assert all( + scope.ecosystem.value == "python" for positive in outcome.accepted_positives for scope in positive.verified_scopes + ) + assert {scope.vulnerability_family for p in outcome.accepted_positives for scope in p.verified_scopes} == { + "deserialization", + "ssrf", + } + assert outcome.census_digest == state.census_digest + assert outcome.queue_digest != state.python_queue.queue_digest + + replayed = _ingest(list(reversed(records)), selection, state, candidates) + assert replayed == outcome + assert replayed.batch_digest == outcome.batch_digest + + combined = [*ledger[0].accepted_positives, *ledger[1].accepted_positives, *outcome.accepted_positives] + assert {batch.ecosystem for batch in ledger} == {"python", "javascript"} + assert len({item.change_identity_digest for item in combined}) == len(combined) == 36 + assert len(combined) < 40 + assert dict(selection.accepted_by_ecosystem) == {"javascript": 12, "python": 12} + + +def test_third_cohort_stays_pending_without_external_records(): + state, resolved, ledger, selection, candidates = _prepared() + entries = _selected_entries(state, selection) + records = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries] + + empty = _ingest([], selection, state, candidates) + assert empty.status is CohortBatchStatus.INSUFFICIENT + assert empty.insufficient_reason is CohortInsufficientReason.BATCH_EMPTY + assert empty.accepted_positives == () + assert empty.pending_entries == selection.selected_entries + + partial = _ingest(records[:3], selection, state, candidates) + assert partial.status is CohortBatchStatus.INSUFFICIENT + assert partial.insufficient_reason is CohortInsufficientReason.INSUFFICIENT_ACCEPTED_POSITIVES + assert len(partial.accepted_positives) == 3 + answered = {item.queue_entry_digest for item in partial.record_outcomes if item.queue_entry_digest is not None} + assert partial.pending_entries == tuple(sorted(set(selection.selected_entries) - answered)) + + +def test_records_outside_the_selected_batch_are_excluded_closed(): + python_names = (*COMBINED_PYTHON_NAMES, *THIRD_PYTHON_NAMES, *SINGLE_FAMILY_PYTHON_NAMES) + state, resolved = replacement_cohort_state(python_names=python_names) + ledger = ingested_replacement_ledger(state, resolved) + selection = _select(state, ledger) + candidates = _candidates(resolved, python_names) + + entries = _selected_entries(state, selection) + assert len(entries) == COHORT_BATCH_CAP + python_batch = next(batch for batch in ledger if batch.ecosystem == "python") + outside = [ + entry + for entry in state.python_queue.entries + if entry.entry_digest in set(python_batch.pending_entries) + and entry.entry_digest not in set(selection.selected_entries) + ] + assert len(outside) == 4 + assert {entry.family.vulnerability_family for entry in outside} == {"injection"} + outsider = reviewed_record(outside[0], candidates[outside[0].candidate_digest])[0] + records = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries[:-1]] + [outsider] + + outcome = _ingest(records, selection, state, candidates) + + assert outcome.status is CohortBatchStatus.ACCEPTED + assert len(outcome.accepted_positives) == COHORT_BATCH_CAP - 1 + unknown = [item for item in outcome.record_outcomes if item.reason == "queue_entry_unknown"] + assert len(unknown) == 1 + assert unknown[0].queue_entry_digest == outside[0].entry_digest + assert unknown[0].record_digest == bytes_digest(outsider) + assert outside[0].entry_digest not in outcome.pending_entries + + +def test_every_accepted_and_excluded_record_replays_from_external_evidence(): + state, resolved, ledger, selection, candidates = _prepared() + entries = _selected_entries(state, selection) + weakened = [ + {"conflict_disclosed": False}, + {"defect_present": None}, + {"in_repository_reachable": False}, + {"verified_scopes": ()}, + {"policy_satisfied": False}, + {"reviewer_identity": f"producer-{entries[5].family.advisory_locator}@example.invalid"}, + { + "defect_present": None, + "fix_addresses": None, + "in_repository_reachable": None, + "model_assistance_digest": model_only_assistance_digest(), + }, + {"verified_scopes": (VerifiedScope("injection", "javascript"),)}, + ] + records = [] + expected = {} + for index, entry in enumerate(entries): + changes = weakened[index] if index < len(weakened) else None + if index == len(entries) - 1: + own = entry.family.vulnerability_family + second = "ssrf" if own != "ssrf" else "deserialization" + changes = {"verified_scopes": (VerifiedScope(own, "python"), VerifiedScope(second, "python"))} + content, review = reviewed_record(entry, candidates[entry.candidate_digest], gt_changes=changes) + records.append(content) + expected[entry.entry_digest] = review + + outcome = _ingest(records, selection, state, candidates) + replayed = _ingest(list(reversed(records)), selection, state, candidates) + assert replayed == outcome + assert replayed.batch_digest == outcome.batch_digest + + by_entry = {item.queue_entry_digest: item for item in outcome.record_outcomes if item.queue_entry_digest is not None} + for entry in entries: + review = expected[entry.entry_digest] + item = by_entry[entry.entry_digest] + assert item.ground_truth_review_digest == review.review_digest + if review.verified_scopes: + assert item.status.value == "accepted" + assert review.in_repository_reachable is True + else: + assert item.status.value == "excluded" + assert item.reason == review.exclusion_reason.value + + assert outcome.status is CohortBatchStatus.INSUFFICIENT + assert outcome.insufficient_reason is CohortInsufficientReason.INSUFFICIENT_ACCEPTED_POSITIVES + multi_scope = [positive for positive in outcome.accepted_positives if len(positive.verified_scopes) == 2] + assert len(multi_scope) == 1 + families = {scope.vulnerability_family for scope in multi_scope[0].verified_scopes} + assert len(families) == 2 and families <= {"deserialization", "ssrf"} + assert all(scope.ecosystem.value == "python" for scope in multi_scope[0].verified_scopes) + assert len({item.change_identity_digest for item in outcome.accepted_positives}) == len(outcome.accepted_positives) + + +def test_selection_binding_guard_refuses_mismatched_selections(): + state, resolved, ledger, selection, candidates = _prepared() + refused = _select(state, ledger) + assert refused.status is CohortSelectionStatus.SELECTED + + other, _ = replacement_cohort_state(python_names=(*COMBINED_PYTHON_NAMES,)) + with pytest.raises(CohortSelectionStateError) as error: + _ingest([], selection, other, candidates) + assert error.value.reason is CohortSelectionStateReason.STATE_MISMATCH + + forged_entry = cohort_selection( + ecosystem="python", + selected_entries=("f" * 64,), + targeted_families=("deserialization",), + queue_digest=selection.queue_digest, + census_digest=selection.census_digest, + ecosystem_policy_digest=ECOSYSTEM_POLICY, + ground_truth_policy_digest=GROUND_TRUTH_POLICY, + prior_batch_digests=selection.prior_batch_digests, + accepted_families=selection.accepted_families, + accepted_by_ecosystem=dict(selection.accepted_by_ecosystem), + status=CohortSelectionStatus.SELECTED, + reason=selection.reason, + ) + wrong_queue = cohort_selection( + ecosystem="python", + selected_entries=selection.selected_entries, + targeted_families=selection.targeted_families, + queue_digest="e" * 64, + census_digest=selection.census_digest, + ecosystem_policy_digest=ECOSYSTEM_POLICY, + ground_truth_policy_digest=GROUND_TRUTH_POLICY, + prior_batch_digests=selection.prior_batch_digests, + accepted_families=selection.accepted_families, + accepted_by_ecosystem=dict(selection.accepted_by_ecosystem), + status=CohortSelectionStatus.SELECTED, + reason=selection.reason, + ) + for bad in (forged_entry, wrong_queue): + with pytest.raises(CohortSelectionStateError) as error: + _ingest([], bad, state, candidates) + assert error.value.reason is CohortSelectionStateReason.STATE_MISMATCH + + +def test_third_cohort_outputs_carry_no_out_of_scope_machinery(): + state, resolved, ledger, selection, candidates = _prepared() + entries = _selected_entries(state, selection) + records = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries] + outcome = _ingest(records, selection, state, candidates) + assert outcome.status is CohortBatchStatus.ACCEPTED + + for content in (cohort_batch_bytes(outcome), cohort_selection_bytes(selection)): + for forbidden in (b"admission", b"detector", b"observation", b"label", b"verdict", b"score"): + assert forbidden not in content