mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
feat(valid-detection-benchmark): 10.2 ingest bounded reviewed Python cohort
This commit is contained in:
@@ -311,7 +311,7 @@
|
||||
- Done when independent reviewers receive canonical evidence packages with no model verdict presented as authority and a restart reproduces the same pending queue identities.
|
||||
- _Requirements: 1.1, 1.2, 1.5, 1.8, 2.1, 2.2, 4.1, 4.4, 7.4, 7.5_
|
||||
- _Boundary: Replacement Population Sourcing_
|
||||
- [ ] 10.2 Ingest the first bounded independently reviewed Python cohort
|
||||
- [x] 10.2 Ingest the first bounded independently reviewed Python cohort
|
||||
- Accept only externally supplied review records with distinct producer/reviewer identities, policy satisfaction, conflict disclosure, required ground-truth judgments, reachability, canonical ecosystem, and exact verified scopes.
|
||||
- Limit this ingestion unit to one supplied batch of at most twenty candidate review records.
|
||||
- Record every exclusion and insufficiency reason without fabricating or self-approving missing reviews.
|
||||
@@ -450,3 +450,4 @@
|
||||
- R1 final validation (2026-11-21): the pre-existing decoders behind the operator read path predate the hostile-decode discipline and lack it — `replacement_artifact_contract.py:207` (json.loads with no parse_constant/finite parse_float/RecursionError), plus `workflow_outcome._decode_canonical` (workflow_outcome.py:394) and `workflow_journal._decode_canonical` (workflow_journal.py:379); 9.3 review reproduced an unhandled RecursionError through them (closed at the run.py boundary only). Owner: task 11.1 (validation harness) or the next task owning `replacement_artifact_contract.py`; 9.3's boundary-level closure is interim.
|
||||
- R1 final validation (2026-11-21), minor drift items: two module-local `OPERATOR_READ_POLICY_DIGEST` constants exist (`admission_replay.py` "scoped-replay-operator-read-policy" vs `run.py` "operator-command-read-policy" — caller-side only, no artifact-key coupling); `sealed_retry.py` imports the private `_reference_value` from `sealed_diagnostics` (not in `__all__`); 9.2's `score_replacement_replay` and 8.5's `derive_scoped_replay` are parallel wrappers over the same core `score_and_replay` (the admission path uses 8.5's; 9.2's seam is the 10/11+ product surface). Revisit when 11.x wires the entry points.
|
||||
- Task 10.1 review: `sourcing_queue_build._request_order` sorts by (url, advisory_locator, reachability_digest, model_digest) with a stable sort, so two distinct candidates tying on all four keys get cap selection decided by input order (restart reproducibility still holds — decode is canonical-bytes-bound — but permutation-rebuild determinism does not). The next task owning that module (10.2+) should extend the sort key with the remaining content digests or refuse tied-but-distinct requests closed. Also noted: an `INSUFFICIENT_FAMILIES` refusal does not durably persist that attempt's exclusions (10.2 owns review-record exclusion durability).
|
||||
- Task 10.2 review (2026-11-22): both 10.1 fold-ins landed (7-key `_request_order` discriminating old four-key ties + `InsufficientFamiliesRefusal.attempt_exclusions` durable persistence). Residual, forwarded to the next owner of `sourcing_queue_build.py`: distinct candidates differing only in non-digest fix-site scalars (path/function under identical repo/advisory/reachability/manifest/license digests) still tie on all seven keys and get cap selection by input order (round-1 reviewer reproduced divergent state digests across permutations); fix is fix-site scalars in the key or a closed refusal of residual ties. Optional hardening forwarded for the cohort modules: `project_accepted_ground_truth` call sits outside a closed-refusal wrapper (defense-in-depth only; unreachable with a consistent queue), and `decode_cohort_batch` accepts self-consistent forgeries whose `pending_entries`/`outcome.queue_entry_digest` are non-digest strings (downstream matching fails closed; a digest check would match sibling-field rigor). Real Python cohort remains PENDING external review records — the 10.2 done criterion is fixture-verified only.
|
||||
|
||||
@@ -0,0 +1,572 @@
|
||||
"""Bounded ingestion of externally reviewed Python cohort batches.
|
||||
|
||||
One ingestion unit consumes a single supplied batch of at most twenty external
|
||||
review records against the pending Python review queue. Every acceptance comes
|
||||
only from the committed review authorities revalidating the external
|
||||
attestations; missing, partial, or refused reviews are recorded as closed
|
||||
per-record exclusions or pending entries and are never self-approved.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from dataclasses import dataclass, field, replace
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
from benchmarks.valid.ecosystem_review import (
|
||||
EcosystemReviewAttestationV1,
|
||||
EcosystemReviewDecision,
|
||||
EcosystemReviewError,
|
||||
RepositoryEcosystemReviewV1,
|
||||
review_repository_ecosystem,
|
||||
)
|
||||
from benchmarks.valid.fix_site_catalog import FixSiteCandidateV1
|
||||
from benchmarks.valid.ground_truth_review import (
|
||||
AcceptedGroundTruthV1,
|
||||
GroundTruthAttestationV1,
|
||||
GroundTruthExclusionReason,
|
||||
GroundTruthReviewError,
|
||||
GroundTruthReviewV1,
|
||||
GroundTruthStatus,
|
||||
VerifiedScope,
|
||||
project_accepted_ground_truth,
|
||||
review_ground_truth,
|
||||
)
|
||||
from benchmarks.valid.sourcing_queue import ReviewQueueEntryV1, SourcingQueueStateV1
|
||||
from openultrasast.core.canonical import JsonValue, bytes_digest, canonical_bytes, content_digest
|
||||
|
||||
EXTERNAL_REVIEW_RECORD_SCHEMA = "openultrasast.valid-detection-benchmark.external-review-record.v1"
|
||||
COHORT_BATCH_SCHEMA = "openultrasast.valid-detection-benchmark.python-cohort-batch.v1"
|
||||
COHORT_BATCH_CAP = 20
|
||||
MINIMUM_ACCEPTED_POSITIVES = 10
|
||||
_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||
_RECORD_KEYS = frozenset({"schema_version", "queue_entry_digest", "ecosystem_attestation", "ground_truth_attestation"})
|
||||
_ECOSYSTEM_ATTESTATION_KEYS = frozenset(
|
||||
{"candidate_digest", "source_evidence_digest", "producer_identity", "reviewer_identity", "conflict_disclosed",
|
||||
"policy_digest", "policy_satisfied", "decision"}
|
||||
)
|
||||
_GROUND_TRUTH_ATTESTATION_KEYS = frozenset(
|
||||
{"candidate_digest", "ecosystem_review_digest", "producer_identity", "reviewer_identity", "conflict_disclosed",
|
||||
"policy_digest", "policy_satisfied", "defect_present", "fix_addresses", "in_repository_reachable",
|
||||
"verified_scopes", "model_assistance_digest"}
|
||||
)
|
||||
_CLOSED_RECORD_REASONS = frozenset(item.value for item in GroundTruthExclusionReason)
|
||||
|
||||
|
||||
class CohortRecordExclusionReason(StrEnum):
|
||||
"""Closed per-record exclusion causes inside one bounded ingestion unit."""
|
||||
|
||||
RECORD_UNREADABLE = "record_unreadable"
|
||||
RECORD_SCHEMA_MISMATCH = "record_schema_mismatch"
|
||||
QUEUE_ENTRY_UNKNOWN = "queue_entry_unknown"
|
||||
CANDIDATE_EVIDENCE_MISSING = "candidate_evidence_missing"
|
||||
REVIEW_EVIDENCE_INVALID = "review_evidence_invalid"
|
||||
DUPLICATE_RECORD = "duplicate_record"
|
||||
CONFLICTING_ACCEPTED_REVIEW = "conflicting_accepted_review"
|
||||
BATCH_UNIT_REFUSED = "batch_unit_refused"
|
||||
|
||||
|
||||
class CohortRecordStatus(StrEnum):
|
||||
ACCEPTED = "accepted"
|
||||
EXCLUDED = "excluded"
|
||||
|
||||
|
||||
class CohortInsufficientReason(StrEnum):
|
||||
"""Closed whole-batch insufficiency causes; none of these is a clean pass."""
|
||||
|
||||
BATCH_EMPTY = "batch_empty"
|
||||
BATCH_CAP_EXCEEDED = "batch_cap_exceeded"
|
||||
PYTHON_QUEUE_EMPTY = "python_queue_empty"
|
||||
INSUFFICIENT_ACCEPTED_POSITIVES = "insufficient_accepted_positives"
|
||||
|
||||
|
||||
class CohortBatchStatus(StrEnum):
|
||||
ACCEPTED = "accepted"
|
||||
INSUFFICIENT = "insufficient"
|
||||
|
||||
|
||||
class CohortStateReason(StrEnum):
|
||||
STATE_UNREADABLE = "state_unreadable"
|
||||
STATE_MISMATCH = "state_mismatch"
|
||||
|
||||
|
||||
_CLOSED_OUTCOME_REASONS = _CLOSED_RECORD_REASONS | frozenset(item.value for item in CohortRecordExclusionReason)
|
||||
|
||||
|
||||
_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.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",
|
||||
CohortRecordExclusionReason.CONFLICTING_ACCEPTED_REVIEW: "change identity has conflicting accepted reviews",
|
||||
CohortRecordExclusionReason.BATCH_UNIT_REFUSED: "ingestion unit refused the whole over-cap batch",
|
||||
CohortStateReason.STATE_UNREADABLE: "cohort batch state bytes are unreadable",
|
||||
CohortStateReason.STATE_MISMATCH: "cohort batch state does not match its canonical schema",
|
||||
}
|
||||
|
||||
|
||||
class CohortIngestionError(ValueError):
|
||||
"""Closed per-record refusal carrying one exclusion reason."""
|
||||
|
||||
def __init__(self, reason: CohortRecordExclusionReason) -> None:
|
||||
self.reason = reason
|
||||
super().__init__(_REASON_TEXT[reason])
|
||||
|
||||
|
||||
class CohortStateError(ValueError):
|
||||
"""Closed batch-state refusal carrying one reason."""
|
||||
|
||||
def __init__(self, reason: CohortStateReason) -> None:
|
||||
self.reason = reason
|
||||
super().__init__(_REASON_TEXT[reason])
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CohortRecordOutcomeV1:
|
||||
record_digest: str
|
||||
queue_entry_digest: str | None
|
||||
ground_truth_review_digest: str | None
|
||||
status: CohortRecordStatus
|
||||
reason: str | None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.record_digest, str) or _DIGEST.fullmatch(self.record_digest) is None:
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
if not isinstance(self.status, CohortRecordStatus):
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
if self.status is CohortRecordStatus.ACCEPTED:
|
||||
if self.reason is not None:
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
elif self.reason not in _CLOSED_OUTCOME_REASONS:
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CohortBatchOutcomeV1:
|
||||
ecosystem: str
|
||||
queue_digest: str
|
||||
census_digest: str
|
||||
ecosystem_policy_digest: str
|
||||
ground_truth_policy_digest: str
|
||||
record_outcomes: tuple[CohortRecordOutcomeV1, ...]
|
||||
pending_entries: tuple[str, ...]
|
||||
accepted_positives: tuple[AcceptedGroundTruthV1, ...]
|
||||
minimum_accepted_positives: int
|
||||
status: CohortBatchStatus
|
||||
insufficient_reason: CohortInsufficientReason | None
|
||||
batch_digest: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Reviewed:
|
||||
outcome: CohortRecordOutcomeV1
|
||||
entry_digest: str | None
|
||||
review: GroundTruthReviewV1 | None
|
||||
ecosystem: RepositoryEcosystemReviewV1 | None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _BatchState:
|
||||
entries: dict[str, ReviewQueueEntryV1]
|
||||
candidates_by_digest: Mapping[str, FixSiteCandidateV1]
|
||||
ecosystem_policy_digest: str
|
||||
ground_truth_policy_digest: str
|
||||
outcomes: list[CohortRecordOutcomeV1] = field(default_factory=list)
|
||||
accepted_reviews: list[GroundTruthReviewV1] = field(default_factory=list)
|
||||
accepted_by_change: dict[str, AcceptedGroundTruthV1] = field(default_factory=dict)
|
||||
ecosystem_reviews: dict[str, RepositoryEcosystemReviewV1] = field(default_factory=dict)
|
||||
answered: set[str] = field(default_factory=set)
|
||||
|
||||
|
||||
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_record(content: bytes) -> dict[str, Any]:
|
||||
"""Hostile decode: no constants, finite floats, bounded recursion, canonical bytes."""
|
||||
if not isinstance(content, bytes) or not content:
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.RECORD_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 CohortIngestionError(CohortRecordExclusionReason.RECORD_UNREADABLE) from None
|
||||
if not isinstance(value, dict) or canonical != content:
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.RECORD_UNREADABLE)
|
||||
return value
|
||||
|
||||
|
||||
def _record_payload(content: bytes) -> dict[str, Any]:
|
||||
value = _decoded_record(content)
|
||||
if set(value) != _RECORD_KEYS or value["schema_version"] != EXTERNAL_REVIEW_RECORD_SCHEMA:
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.RECORD_SCHEMA_MISMATCH)
|
||||
return value
|
||||
|
||||
|
||||
def _entry_digest(payload: Mapping[str, Any]) -> str:
|
||||
digest = payload["queue_entry_digest"]
|
||||
if not isinstance(digest, str) or _DIGEST.fullmatch(digest) is None:
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.RECORD_SCHEMA_MISMATCH)
|
||||
return digest
|
||||
|
||||
|
||||
def _mapping_with_keys(value: Any, keys: frozenset[str]) -> Mapping[str, Any]:
|
||||
if not isinstance(value, dict) or set(value) != keys:
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.RECORD_SCHEMA_MISMATCH)
|
||||
return value
|
||||
|
||||
|
||||
def _ecosystem_attestation(value: Any) -> EcosystemReviewAttestationV1:
|
||||
item = _mapping_with_keys(value, _ECOSYSTEM_ATTESTATION_KEYS)
|
||||
try:
|
||||
return EcosystemReviewAttestationV1(
|
||||
item["candidate_digest"],
|
||||
item["source_evidence_digest"],
|
||||
item["producer_identity"],
|
||||
item["reviewer_identity"],
|
||||
item["conflict_disclosed"],
|
||||
item["policy_digest"],
|
||||
item["policy_satisfied"],
|
||||
EcosystemReviewDecision(item["decision"]),
|
||||
)
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.RECORD_SCHEMA_MISMATCH) from None
|
||||
|
||||
|
||||
def _verified_scopes(value: Any) -> tuple[VerifiedScope, ...]:
|
||||
if not isinstance(value, tuple):
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.RECORD_SCHEMA_MISMATCH)
|
||||
try:
|
||||
return tuple(VerifiedScope(item["vulnerability_family"], item["ecosystem"]) for item in value)
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.RECORD_SCHEMA_MISMATCH) from None
|
||||
|
||||
|
||||
def _ground_truth_attestation(value: Any) -> GroundTruthAttestationV1:
|
||||
item = _mapping_with_keys(value, _GROUND_TRUTH_ATTESTATION_KEYS)
|
||||
try:
|
||||
return GroundTruthAttestationV1(
|
||||
candidate_digest=item["candidate_digest"],
|
||||
ecosystem_review_digest=item["ecosystem_review_digest"],
|
||||
producer_identity=item["producer_identity"],
|
||||
reviewer_identity=item["reviewer_identity"],
|
||||
conflict_disclosed=item["conflict_disclosed"],
|
||||
policy_digest=item["policy_digest"],
|
||||
policy_satisfied=item["policy_satisfied"],
|
||||
defect_present=item["defect_present"],
|
||||
fix_addresses=item["fix_addresses"],
|
||||
in_repository_reachable=item["in_repository_reachable"],
|
||||
verified_scopes=_verified_scopes(item["verified_scopes"]),
|
||||
model_assistance_digest=item["model_assistance_digest"],
|
||||
)
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.RECORD_SCHEMA_MISMATCH) from None
|
||||
|
||||
|
||||
def decode_external_record(content: bytes) -> dict[str, Any]:
|
||||
"""Decode one external review record after hostile-byte validation."""
|
||||
return _record_payload(content)
|
||||
|
||||
|
||||
def _review_pair(
|
||||
payload: Mapping[str, Any],
|
||||
candidate: FixSiteCandidateV1,
|
||||
batch: _BatchState,
|
||||
) -> tuple[RepositoryEcosystemReviewV1, GroundTruthReviewV1]:
|
||||
try:
|
||||
ecosystem = review_repository_ecosystem(
|
||||
candidate,
|
||||
_ecosystem_attestation(payload["ecosystem_attestation"]),
|
||||
expected_policy_digest=batch.ecosystem_policy_digest,
|
||||
)
|
||||
review = review_ground_truth(
|
||||
candidate,
|
||||
ecosystem,
|
||||
_ground_truth_attestation(payload["ground_truth_attestation"]),
|
||||
expected_ecosystem_policy_digest=batch.ecosystem_policy_digest,
|
||||
expected_ground_truth_policy_digest=batch.ground_truth_policy_digest,
|
||||
)
|
||||
except (EcosystemReviewError, GroundTruthReviewError):
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.REVIEW_EVIDENCE_INVALID) from None
|
||||
return ecosystem, review
|
||||
|
||||
|
||||
def _excluded(record_digest: str, entry_digest: str | None, reason: str) -> _Reviewed:
|
||||
outcome = CohortRecordOutcomeV1(record_digest, entry_digest, None, CohortRecordStatus.EXCLUDED, reason)
|
||||
return _Reviewed(outcome, entry_digest, None, None)
|
||||
|
||||
|
||||
def _accepted_outcome(
|
||||
record_digest: str,
|
||||
entry_digest: str,
|
||||
review: GroundTruthReviewV1,
|
||||
ecosystem: RepositoryEcosystemReviewV1,
|
||||
batch: _BatchState,
|
||||
) -> _Reviewed:
|
||||
projected = AcceptedGroundTruthV1(
|
||||
review.change_identity_digest,
|
||||
review.candidate_digest,
|
||||
review.ecosystem_review_digest,
|
||||
review.review_digest,
|
||||
review.verified_scopes,
|
||||
)
|
||||
existing = batch.accepted_by_change.get(review.change_identity_digest)
|
||||
if existing is not None and existing != projected:
|
||||
return _excluded(record_digest, entry_digest, CohortRecordExclusionReason.CONFLICTING_ACCEPTED_REVIEW.value)
|
||||
batch.accepted_by_change[review.change_identity_digest] = projected
|
||||
batch.accepted_reviews.append(review)
|
||||
outcome = CohortRecordOutcomeV1(record_digest, entry_digest, review.review_digest, CohortRecordStatus.ACCEPTED, None)
|
||||
return _Reviewed(outcome, entry_digest, review, ecosystem)
|
||||
|
||||
|
||||
def _review_record(content: bytes, batch: _BatchState) -> _Reviewed:
|
||||
record_digest = bytes_digest(content)
|
||||
entry_digest: str | None = None
|
||||
try:
|
||||
payload = _record_payload(content)
|
||||
entry_digest = _entry_digest(payload)
|
||||
entry = batch.entries.get(entry_digest)
|
||||
if entry is None:
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.QUEUE_ENTRY_UNKNOWN)
|
||||
if entry_digest in batch.answered:
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.DUPLICATE_RECORD)
|
||||
candidate = batch.candidates_by_digest.get(entry.candidate_digest)
|
||||
if candidate is None:
|
||||
raise CohortIngestionError(CohortRecordExclusionReason.CANDIDATE_EVIDENCE_MISSING)
|
||||
ecosystem, review = _review_pair(payload, candidate, batch)
|
||||
except CohortIngestionError as error:
|
||||
return _excluded(record_digest, entry_digest, error.reason.value)
|
||||
batch.answered.add(entry_digest)
|
||||
batch.ecosystem_reviews[ecosystem.review_digest] = ecosystem
|
||||
if review.status is GroundTruthStatus.EXCLUDED:
|
||||
assert review.exclusion_reason is not None
|
||||
outcome = CohortRecordOutcomeV1(
|
||||
record_digest, entry_digest, review.review_digest, CohortRecordStatus.EXCLUDED, review.exclusion_reason.value
|
||||
)
|
||||
return _Reviewed(outcome, entry_digest, review, ecosystem)
|
||||
return _accepted_outcome(record_digest, entry_digest, review, ecosystem, batch)
|
||||
|
||||
|
||||
def _batch_status(
|
||||
record_count: int,
|
||||
accepted_count: int,
|
||||
queue_entry_count: int,
|
||||
) -> tuple[CohortBatchStatus, CohortInsufficientReason | None]:
|
||||
if queue_entry_count == 0:
|
||||
return CohortBatchStatus.INSUFFICIENT, CohortInsufficientReason.PYTHON_QUEUE_EMPTY
|
||||
if record_count == 0:
|
||||
return CohortBatchStatus.INSUFFICIENT, CohortInsufficientReason.BATCH_EMPTY
|
||||
if accepted_count < MINIMUM_ACCEPTED_POSITIVES:
|
||||
return CohortBatchStatus.INSUFFICIENT, CohortInsufficientReason.INSUFFICIENT_ACCEPTED_POSITIVES
|
||||
return CohortBatchStatus.ACCEPTED, None
|
||||
|
||||
|
||||
def _closed_digest(value: object) -> str:
|
||||
if not isinstance(value, str) or _DIGEST.fullmatch(value) is None:
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
return value
|
||||
|
||||
|
||||
def cohort_batch(
|
||||
*,
|
||||
queue_digest: str,
|
||||
census_digest: str,
|
||||
ecosystem_policy_digest: str,
|
||||
ground_truth_policy_digest: str,
|
||||
record_outcomes: Iterable[CohortRecordOutcomeV1],
|
||||
pending_entries: Iterable[str],
|
||||
accepted_positives: Iterable[AcceptedGroundTruthV1],
|
||||
status: CohortBatchStatus,
|
||||
insufficient_reason: CohortInsufficientReason | None,
|
||||
) -> CohortBatchOutcomeV1:
|
||||
"""Assemble one bounded Python cohort batch bound to its exact queue and census."""
|
||||
if not isinstance(status, CohortBatchStatus):
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
accepted_tuple = tuple(accepted_positives)
|
||||
if status is CohortBatchStatus.ACCEPTED and (insufficient_reason is not None or len(accepted_tuple) < MINIMUM_ACCEPTED_POSITIVES):
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
if status is CohortBatchStatus.INSUFFICIENT and insufficient_reason is None:
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
accepted = tuple(sorted(accepted_tuple, key=lambda item: item.change_identity_digest))
|
||||
draft = CohortBatchOutcomeV1(
|
||||
"python",
|
||||
_closed_digest(queue_digest),
|
||||
_closed_digest(census_digest),
|
||||
_closed_digest(ecosystem_policy_digest),
|
||||
_closed_digest(ground_truth_policy_digest),
|
||||
tuple(sorted(record_outcomes, key=lambda item: item.record_digest)),
|
||||
tuple(sorted(set(pending_entries))),
|
||||
accepted,
|
||||
MINIMUM_ACCEPTED_POSITIVES,
|
||||
status,
|
||||
insufficient_reason,
|
||||
"",
|
||||
)
|
||||
return replace(draft, batch_digest=content_digest(_batch_value(draft, include_digest=False)))
|
||||
|
||||
|
||||
def _record_outcome_value(item: CohortRecordOutcomeV1) -> dict[str, JsonValue]:
|
||||
return {
|
||||
"record_digest": item.record_digest,
|
||||
"queue_entry_digest": item.queue_entry_digest,
|
||||
"ground_truth_review_digest": item.ground_truth_review_digest,
|
||||
"status": item.status.value,
|
||||
"reason": item.reason,
|
||||
}
|
||||
|
||||
|
||||
def _scope_values(scopes: tuple[VerifiedScope, ...]) -> tuple[dict[str, JsonValue], ...]:
|
||||
return tuple(
|
||||
{"vulnerability_family": scope.vulnerability_family, "ecosystem": scope.ecosystem.value} for scope in scopes
|
||||
)
|
||||
|
||||
|
||||
def _accepted_value(item: AcceptedGroundTruthV1) -> dict[str, JsonValue]:
|
||||
return {
|
||||
"change_identity_digest": item.change_identity_digest,
|
||||
"candidate_digest": item.candidate_digest,
|
||||
"ecosystem_review_digest": item.ecosystem_review_digest,
|
||||
"ground_truth_review_digest": item.ground_truth_review_digest,
|
||||
"verified_scopes": _scope_values(item.verified_scopes),
|
||||
}
|
||||
|
||||
|
||||
def cohort_batch_value(outcome: CohortBatchOutcomeV1) -> dict[str, JsonValue]:
|
||||
"""Canonical batch payload used for durable persistence and exact rereads."""
|
||||
return {
|
||||
"schema_version": COHORT_BATCH_SCHEMA,
|
||||
"ecosystem": outcome.ecosystem,
|
||||
"queue_digest": outcome.queue_digest,
|
||||
"census_digest": outcome.census_digest,
|
||||
"ecosystem_policy_digest": outcome.ecosystem_policy_digest,
|
||||
"ground_truth_policy_digest": outcome.ground_truth_policy_digest,
|
||||
"record_outcomes": tuple(_record_outcome_value(item) for item in outcome.record_outcomes),
|
||||
"pending_entries": outcome.pending_entries,
|
||||
"accepted_positives": tuple(_accepted_value(item) for item in outcome.accepted_positives),
|
||||
"minimum_accepted_positives": outcome.minimum_accepted_positives,
|
||||
"status": outcome.status.value,
|
||||
"insufficient_reason": outcome.insufficient_reason.value if outcome.insufficient_reason is not None else None,
|
||||
"batch_digest": outcome.batch_digest,
|
||||
}
|
||||
|
||||
|
||||
def _batch_value(outcome: CohortBatchOutcomeV1, *, include_digest: bool) -> dict[str, JsonValue]:
|
||||
value = cohort_batch_value(outcome)
|
||||
if not include_digest:
|
||||
value.pop("batch_digest")
|
||||
return value
|
||||
|
||||
|
||||
def cohort_batch_bytes(outcome: CohortBatchOutcomeV1) -> bytes:
|
||||
"""Encode a digest-consistent batch outcome as canonical bytes."""
|
||||
if outcome.batch_digest != content_digest(_batch_value(outcome, include_digest=False)):
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
return canonical_bytes(cohort_batch_value(outcome))
|
||||
|
||||
|
||||
def _refused_batch(state: SourcingQueueStateV1, ordered: Sequence[bytes], batch: _BatchState) -> CohortBatchOutcomeV1:
|
||||
outcomes = [
|
||||
CohortRecordOutcomeV1(
|
||||
bytes_digest(content), None, None, CohortRecordStatus.EXCLUDED, CohortRecordExclusionReason.BATCH_UNIT_REFUSED.value
|
||||
)
|
||||
for content in ordered
|
||||
]
|
||||
return cohort_batch(
|
||||
queue_digest=state.python_queue.queue_digest,
|
||||
census_digest=state.census_digest,
|
||||
ecosystem_policy_digest=batch.ecosystem_policy_digest,
|
||||
ground_truth_policy_digest=batch.ground_truth_policy_digest,
|
||||
record_outcomes=outcomes,
|
||||
pending_entries=tuple(batch.entries),
|
||||
accepted_positives=(),
|
||||
status=CohortBatchStatus.INSUFFICIENT,
|
||||
insufficient_reason=CohortInsufficientReason.BATCH_CAP_EXCEEDED,
|
||||
)
|
||||
|
||||
|
||||
def ingest_python_cohort_batch(
|
||||
records: Sequence[bytes],
|
||||
*,
|
||||
state: SourcingQueueStateV1,
|
||||
candidates_by_digest: Mapping[str, FixSiteCandidateV1],
|
||||
expected_ecosystem_policy_digest: str,
|
||||
expected_ground_truth_policy_digest: str,
|
||||
) -> CohortBatchOutcomeV1:
|
||||
"""Ingest one supplied batch of at most twenty external Python review records."""
|
||||
for content in records:
|
||||
if not isinstance(content, bytes):
|
||||
raise ValueError("external review records must be supplied as bytes")
|
||||
batch = _BatchState(
|
||||
{entry.entry_digest: entry for entry in state.python_queue.entries},
|
||||
candidates_by_digest,
|
||||
expected_ecosystem_policy_digest,
|
||||
expected_ground_truth_policy_digest,
|
||||
)
|
||||
ordered = tuple(sorted(records, key=bytes_digest))
|
||||
if len(ordered) > COHORT_BATCH_CAP:
|
||||
return _refused_batch(state, ordered, batch)
|
||||
for content in ordered:
|
||||
batch.outcomes.append(_review_record(content, batch).outcome)
|
||||
accepted_positives = project_accepted_ground_truth(
|
||||
batch.accepted_reviews,
|
||||
candidates_by_digest=candidates_by_digest,
|
||||
ecosystem_reviews_by_digest=dict(batch.ecosystem_reviews),
|
||||
expected_ecosystem_policy_digest=expected_ecosystem_policy_digest,
|
||||
expected_ground_truth_policy_digest=expected_ground_truth_policy_digest,
|
||||
)
|
||||
status, reason = _batch_status(len(ordered), len(accepted_positives), len(batch.entries))
|
||||
return cohort_batch(
|
||||
queue_digest=state.python_queue.queue_digest,
|
||||
census_digest=state.census_digest,
|
||||
ecosystem_policy_digest=expected_ecosystem_policy_digest,
|
||||
ground_truth_policy_digest=expected_ground_truth_policy_digest,
|
||||
record_outcomes=batch.outcomes,
|
||||
pending_entries=sorted(batch.entries.keys() - batch.answered),
|
||||
accepted_positives=accepted_positives,
|
||||
status=status,
|
||||
insufficient_reason=reason,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"COHORT_BATCH_CAP",
|
||||
"COHORT_BATCH_SCHEMA",
|
||||
"CohortBatchOutcomeV1",
|
||||
"CohortBatchStatus",
|
||||
"CohortIngestionError",
|
||||
"CohortInsufficientReason",
|
||||
"CohortRecordExclusionReason",
|
||||
"CohortRecordOutcomeV1",
|
||||
"CohortRecordStatus",
|
||||
"CohortStateError",
|
||||
"CohortStateReason",
|
||||
"EXTERNAL_REVIEW_RECORD_SCHEMA",
|
||||
"MINIMUM_ACCEPTED_POSITIVES",
|
||||
"cohort_batch",
|
||||
"cohort_batch_bytes",
|
||||
"cohort_batch_value",
|
||||
"decode_external_record",
|
||||
"ingest_python_cohort_batch",
|
||||
]
|
||||
@@ -0,0 +1,238 @@
|
||||
"""Durable persistence, hostile decode, and replay for cohort batch ingestion."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from benchmarks.valid.artifact_repository import ArtifactReadAuthority, S3ArtifactRepository
|
||||
from benchmarks.valid.cohort_ingestion import (
|
||||
COHORT_BATCH_SCHEMA,
|
||||
CohortBatchOutcomeV1,
|
||||
CohortBatchStatus,
|
||||
CohortInsufficientReason,
|
||||
CohortRecordOutcomeV1,
|
||||
CohortRecordStatus,
|
||||
CohortStateError,
|
||||
CohortStateReason,
|
||||
cohort_batch,
|
||||
cohort_batch_bytes,
|
||||
cohort_batch_value,
|
||||
decode_external_record,
|
||||
)
|
||||
from benchmarks.valid.ground_truth_review import AcceptedGroundTruthV1, VerifiedScope
|
||||
from benchmarks.valid.replacement_artifact_contract import (
|
||||
ArtifactAccessClass,
|
||||
ArtifactKind,
|
||||
ArtifactReference,
|
||||
artifact_reference,
|
||||
canonical_artifact_bytes,
|
||||
)
|
||||
from benchmarks.valid.sourcing_queue import QueueExclusionV1, SourcingQueueReason
|
||||
from openultrasast.core.canonical import JsonValue, bytes_digest, canonical_bytes
|
||||
|
||||
REFUSED_QUEUE_EXCLUSIONS_SCHEMA = "openultrasast.valid-detection-benchmark.refused-queue-exclusions.v1"
|
||||
_BATCH_KEYS = frozenset(
|
||||
{"schema_version", "ecosystem", "queue_digest", "census_digest", "ecosystem_policy_digest", "ground_truth_policy_digest",
|
||||
"record_outcomes", "pending_entries", "accepted_positives", "minimum_accepted_positives", "status",
|
||||
"insufficient_reason", "batch_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 CohortStateError(CohortStateReason.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 CohortStateError(CohortStateReason.STATE_UNREADABLE) from None
|
||||
if not isinstance(value, dict) or canonical != content:
|
||||
raise CohortStateError(CohortStateReason.STATE_UNREADABLE)
|
||||
return value
|
||||
|
||||
|
||||
def _record_outcome_from_value(item: Any) -> CohortRecordOutcomeV1:
|
||||
return CohortRecordOutcomeV1(
|
||||
item["record_digest"],
|
||||
item["queue_entry_digest"],
|
||||
item["ground_truth_review_digest"],
|
||||
CohortRecordStatus(item["status"]),
|
||||
item["reason"],
|
||||
)
|
||||
|
||||
|
||||
def _accepted_from_value(item: Any) -> AcceptedGroundTruthV1:
|
||||
return AcceptedGroundTruthV1(
|
||||
item["change_identity_digest"],
|
||||
item["candidate_digest"],
|
||||
item["ecosystem_review_digest"],
|
||||
item["ground_truth_review_digest"],
|
||||
tuple(VerifiedScope(scope["vulnerability_family"], scope["ecosystem"]) for scope in item["verified_scopes"]),
|
||||
)
|
||||
|
||||
|
||||
def decode_cohort_batch(content: bytes) -> CohortBatchOutcomeV1:
|
||||
"""Rebuild one batch outcome only from canonical, digest-consistent bytes."""
|
||||
value = _decoded_value(content)
|
||||
if set(value) != _BATCH_KEYS or value["schema_version"] != COHORT_BATCH_SCHEMA:
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
try:
|
||||
reason = None if value["insufficient_reason"] is None else CohortInsufficientReason(value["insufficient_reason"])
|
||||
outcome = cohort_batch(
|
||||
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"],
|
||||
record_outcomes=tuple(_record_outcome_from_value(item) for item in value["record_outcomes"]),
|
||||
pending_entries=tuple(value["pending_entries"]),
|
||||
accepted_positives=tuple(_accepted_from_value(item) for item in value["accepted_positives"]),
|
||||
status=CohortBatchStatus(value["status"]),
|
||||
insufficient_reason=reason,
|
||||
)
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH) from None
|
||||
if cohort_batch_bytes(outcome) != content:
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
return outcome
|
||||
|
||||
|
||||
def persist_cohort_batch(store: S3ArtifactRepository, outcome: CohortBatchOutcomeV1) -> ArtifactReference:
|
||||
"""Persist one accepted or refused batch outcome as a durable review artifact."""
|
||||
content = canonical_artifact_bytes(
|
||||
ArtifactKind.REVIEW,
|
||||
cohort_batch_value(outcome),
|
||||
access_class=ArtifactAccessClass.OPERATOR_SAFE,
|
||||
provenance_digest=outcome.queue_digest,
|
||||
)
|
||||
return store.put_if_absent(content, reference=artifact_reference(content))
|
||||
|
||||
|
||||
def resume_cohort_batch(
|
||||
store: S3ArtifactRepository,
|
||||
reference: ArtifactReference,
|
||||
*,
|
||||
authority: ArtifactReadAuthority,
|
||||
expected_access_policy_digest: str,
|
||||
) -> CohortBatchOutcomeV1:
|
||||
"""Resume one batch outcome from the durable store after restart or scratch loss."""
|
||||
accepted = store.get(
|
||||
reference,
|
||||
expected_kind=ArtifactKind.REVIEW,
|
||||
authority=authority,
|
||||
expected_access_policy_digest=expected_access_policy_digest,
|
||||
)
|
||||
try:
|
||||
content = canonical_bytes(_converted(accepted.artifact.payload))
|
||||
except (TypeError, ValueError, RecursionError):
|
||||
raise CohortStateError(CohortStateReason.STATE_UNREADABLE) from None
|
||||
return decode_cohort_batch(content)
|
||||
|
||||
|
||||
def publish_external_review_records(store: S3ArtifactRepository, records: Sequence[bytes]) -> tuple[ArtifactReference, ...]:
|
||||
"""Persist canonical external review record bytes as durable governed evidence.
|
||||
|
||||
Records that fail hostile decode are not publishable as payloads; they stay
|
||||
ledgered by digest and closed reason inside the persisted batch outcome.
|
||||
"""
|
||||
references = []
|
||||
for content in records:
|
||||
payload = decode_external_record(content)
|
||||
artifact = canonical_artifact_bytes(
|
||||
ArtifactKind.REVIEW,
|
||||
payload,
|
||||
access_class=ArtifactAccessClass.OPERATOR_SAFE,
|
||||
provenance_digest=bytes_digest(content),
|
||||
)
|
||||
references.append(store.put_if_absent(artifact, reference=artifact_reference(artifact)))
|
||||
return tuple(references)
|
||||
|
||||
|
||||
def read_external_review_records(
|
||||
store: S3ArtifactRepository,
|
||||
references: Sequence[ArtifactReference],
|
||||
*,
|
||||
authority: ArtifactReadAuthority,
|
||||
expected_access_policy_digest: str,
|
||||
) -> tuple[bytes, ...]:
|
||||
"""Read canonical external review record bytes back from the durable store."""
|
||||
contents = []
|
||||
for reference in references:
|
||||
accepted = store.get(
|
||||
reference,
|
||||
expected_kind=ArtifactKind.REVIEW,
|
||||
authority=authority,
|
||||
expected_access_policy_digest=expected_access_policy_digest,
|
||||
)
|
||||
try:
|
||||
contents.append(canonical_bytes(_converted(accepted.artifact.payload)))
|
||||
except (TypeError, ValueError, RecursionError):
|
||||
raise CohortStateError(CohortStateReason.STATE_UNREADABLE) from None
|
||||
return tuple(contents)
|
||||
|
||||
|
||||
def _queue_exclusion_value(item: QueueExclusionV1) -> dict[str, JsonValue]:
|
||||
if not isinstance(item.reason, SourcingQueueReason):
|
||||
raise CohortStateError(CohortStateReason.STATE_MISMATCH)
|
||||
return {
|
||||
"advisory_locator": item.advisory_locator,
|
||||
"repository": item.repository,
|
||||
"candidate_digest": item.candidate_digest,
|
||||
"reason": item.reason.value,
|
||||
"exclusion_digest": item.exclusion_digest,
|
||||
}
|
||||
|
||||
|
||||
def persist_refused_queue_exclusions(
|
||||
store: S3ArtifactRepository,
|
||||
exclusions: Sequence[QueueExclusionV1],
|
||||
*,
|
||||
policy_digest: str,
|
||||
) -> ArtifactReference:
|
||||
"""Durably record a refused sourcing attempt's exclusions with closed reasons."""
|
||||
payload: dict[str, JsonValue] = {
|
||||
"schema_version": REFUSED_QUEUE_EXCLUSIONS_SCHEMA,
|
||||
"exclusions": tuple(_queue_exclusion_value(item) for item in exclusions),
|
||||
"policy_digest": policy_digest,
|
||||
}
|
||||
content = canonical_artifact_bytes(
|
||||
ArtifactKind.POPULATION,
|
||||
payload,
|
||||
access_class=ArtifactAccessClass.PUBLIC,
|
||||
provenance_digest=policy_digest,
|
||||
)
|
||||
return store.put_if_absent(content, reference=artifact_reference(content))
|
||||
|
||||
|
||||
__all__ = [
|
||||
"REFUSED_QUEUE_EXCLUSIONS_SCHEMA",
|
||||
"decode_cohort_batch",
|
||||
"persist_cohort_batch",
|
||||
"persist_refused_queue_exclusions",
|
||||
"publish_external_review_records",
|
||||
"read_external_review_records",
|
||||
"resume_cohort_batch",
|
||||
]
|
||||
@@ -35,6 +35,18 @@ ENUMERATION_EVENT_SOURCE = "valid-benchmark-sourcing-queue"
|
||||
_LANGUAGE_ECOSYSTEM = {"javascript": "javascript", "python": "python", "typescript": "javascript"}
|
||||
|
||||
|
||||
class InsufficientFamiliesRefusal(SourcingQueueError):
|
||||
"""Insufficient-families refusal carrying the attempt's exclusions.
|
||||
|
||||
Task 10.1 review fold-in: a refused build must not silently discard the
|
||||
exclusions it already derived; callers persist them durably.
|
||||
"""
|
||||
|
||||
def __init__(self, exclusions: Sequence[QueueExclusionV1]) -> None:
|
||||
super().__init__(SourcingQueueReason.INSUFFICIENT_FAMILIES)
|
||||
self.attempt_exclusions = tuple(exclusions)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Outcome:
|
||||
advisory_locator: str
|
||||
@@ -78,9 +90,24 @@ def _resolve_outcome(
|
||||
return _Outcome(locator, network.canonical_repository, ecosystem, candidate, None)
|
||||
|
||||
|
||||
def _request_order(request: SourcingCandidateRequest) -> tuple[str, str, str, str]:
|
||||
def _request_order(request: SourcingCandidateRequest) -> tuple[str, ...]:
|
||||
"""Content-bound order: every remaining evidence digest breaks ties.
|
||||
|
||||
Task 10.1 review fold-in: distinct candidates tying on the first four keys
|
||||
used to be ordered by input position, so cap selection was
|
||||
permutation-sensitive; the advisory, package-manifest, and license digests
|
||||
make the order a function of content only.
|
||||
"""
|
||||
digest = request.model_assistance_digest or ""
|
||||
return (str(request.case.get("url", "")), request.family.advisory_locator, request.reachability.evidence_digest, digest)
|
||||
return (
|
||||
str(request.case.get("url", "")),
|
||||
request.family.advisory_locator,
|
||||
request.reachability.evidence_digest,
|
||||
digest,
|
||||
request.family.advisory_digest,
|
||||
request.package_evidence.manifest.content_digest,
|
||||
request.license_evidence.source.content_digest,
|
||||
)
|
||||
|
||||
|
||||
def _entry(outcome: _Outcome, request: SourcingCandidateRequest) -> ReviewQueueEntryV1:
|
||||
@@ -162,7 +189,7 @@ def build_sourcing_queue(
|
||||
filled[ecosystem].append(_entry(outcome, request))
|
||||
families = {entry.family.vulnerability_family for group in filled.values() for entry in group}
|
||||
if len(families) < policy.required_families:
|
||||
raise SourcingQueueError(SourcingQueueReason.INSUFFICIENT_FAMILIES) from None
|
||||
raise InsufficientFamiliesRefusal(exclusions) from None
|
||||
entries = (*filled["python"], *filled["javascript"])
|
||||
_record_enumeration(authority, resolver, entries, policy=policy, actor=enumeration_actor, reviewer=enumeration_reviewer)
|
||||
return sourcing_queue_state(
|
||||
@@ -187,4 +214,4 @@ def _exclusion(outcome: _Outcome, reason: SourcingQueueReason) -> QueueExclusion
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["ENUMERATION_EVENT_SOURCE", "build_sourcing_queue"]
|
||||
__all__ = ["ENUMERATION_EVENT_SOURCE", "InsufficientFamiliesRefusal", "build_sourcing_queue"]
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
"""Attestation-fixture apparatus for bounded Python cohort ingestion tests.
|
||||
|
||||
External review records are supplied as untrusted canonical bytes built with the
|
||||
same independently reviewed attestation convention as the committed review
|
||||
authority tests: distinct producer and reviewer identities, real policy and
|
||||
conflict-disclosure machinery, and digest-bound evidence. Nothing here fabricates
|
||||
reviewer judgment; every mutation deliberately weakens one attestation so the
|
||||
ingestion boundary has to record the closed exclusion itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
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.ecosystem_review import (
|
||||
EcosystemReviewAttestationV1,
|
||||
EcosystemReviewDecision,
|
||||
RepositoryEcosystemReviewV1,
|
||||
review_repository_ecosystem,
|
||||
)
|
||||
from benchmarks.valid.fix_site_catalog import (
|
||||
EvidenceRef,
|
||||
FixSiteCandidateV1,
|
||||
LicenseEvidence,
|
||||
PackageEcosystemEvidence,
|
||||
build_fix_site_candidate,
|
||||
)
|
||||
from benchmarks.valid.ground_truth_review import GroundTruthAttestationV1, GroundTruthReviewV1, VerifiedScope, review_ground_truth
|
||||
from benchmarks.valid.reservation import RepositoryIdentityResolver, ReservationAuthority
|
||||
from benchmarks.valid.reservation_identity import build_network_identity
|
||||
from benchmarks.valid.sourcing_queue import (
|
||||
ReviewQueueEntryV1,
|
||||
SourcingQueueStateV1,
|
||||
family_evidence,
|
||||
reachability_evidence,
|
||||
sourcing_candidate_request,
|
||||
sourcing_queue_policy,
|
||||
)
|
||||
from benchmarks.valid.sourcing_queue_build import build_sourcing_queue
|
||||
from openultrasast.core.canonical import bytes_digest, canonical_bytes, content_digest
|
||||
|
||||
ECOSYSTEM_POLICY = content_digest({"policy": "ecosystem-review-fixture-v1"})
|
||||
GROUND_TRUTH_POLICY = content_digest({"policy": "ground-truth-review-fixture-v1"})
|
||||
ENUMERATION_ACTOR = "[email protected]"
|
||||
ENUMERATION_REVIEWER = "[email protected]"
|
||||
ECOSYSTEM_PRODUCER = "[email protected]"
|
||||
ECOSYSTEM_REVIEWER = "[email protected]"
|
||||
PYTHON_COUNT = 12
|
||||
|
||||
_APPS: dict[str, dict[str, Any]] = {}
|
||||
for _index in range(PYTHON_COUNT):
|
||||
_family = "injection" if _index % 2 == 0 else "path_traversal"
|
||||
_apps_key = f"py-{_index:02d}"
|
||||
_APPS[_apps_key] = {
|
||||
"url": f"https://github.com/fixture/cohort-{_apps_key}",
|
||||
"repo": f"fixture/cohort-{_apps_key}",
|
||||
"path": "app.py",
|
||||
"function": f"handler_{_index:02d}",
|
||||
"language": "python",
|
||||
"hint": "python",
|
||||
"family": _family,
|
||||
"cwe": "CWE-94" if _family == "injection" else "CWE-22",
|
||||
"vulnerable": f"def handler_{_index:02d}(query):\n return eval(query)\n",
|
||||
"fixed": f"def handler_{_index:02d}(query):\n return str(query)\n",
|
||||
}
|
||||
_APPS["js-00"] = {
|
||||
"url": "https://github.com/fixture/cohort-js-00",
|
||||
"repo": "fixture/cohort-js-00",
|
||||
"path": "lib/index.js",
|
||||
"function": "sanitize",
|
||||
"language": "javascript",
|
||||
"hint": "javascript",
|
||||
"family": "injection",
|
||||
"cwe": "CWE-94",
|
||||
"vulnerable": "function sanitize(input) {\n return eval(input);\n}\n",
|
||||
"fixed": "function sanitize(input) {\n return String(input);\n}\n",
|
||||
}
|
||||
_APPS["js-01"] = {
|
||||
"url": "https://github.com/fixture/cohort-js-01",
|
||||
"repo": "fixture/cohort-js-01",
|
||||
"path": "src/validate.js",
|
||||
"function": "validate",
|
||||
"language": "javascript",
|
||||
"hint": "javascript",
|
||||
"family": "output_encoding",
|
||||
"cwe": "CWE-79",
|
||||
"vulnerable": "function validate(input) {\n return eval(input);\n}\n",
|
||||
"fixed": "function validate(input) {\n return String(input);\n}\n",
|
||||
}
|
||||
_REVISIONS = {name: (f"{5000 + index * 2:040x}", f"{5001 + index * 2:040x}") for index, name in enumerate(sorted(_APPS))}
|
||||
READ_POLICY = bytes_digest(b"cohort-ingestion-read-policy-fixture")
|
||||
|
||||
|
||||
class FakeReader:
|
||||
"""FixSiteReader over pinned synthetic snapshots, both sides nonzero."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._blobs: dict[tuple[str, str], str] = {}
|
||||
self._parents: dict[str, tuple[str, ...]] = {}
|
||||
for name, app in _APPS.items():
|
||||
parent, fix = _REVISIONS[name]
|
||||
self._blobs[(parent, app["path"])] = app["vulnerable"]
|
||||
self._blobs[(fix, app["path"])] = app["fixed"]
|
||||
self._parents[fix] = (parent,)
|
||||
|
||||
def parents(self, revision: str) -> tuple[str, ...]:
|
||||
return self._parents.get(revision, ())
|
||||
|
||||
def blob(self, revision: str, path: str) -> str | None:
|
||||
return self._blobs.get((revision, path))
|
||||
|
||||
|
||||
class _Client:
|
||||
def __init__(self) -> None:
|
||||
self.objects: dict[tuple[str, str], bytes] = {}
|
||||
|
||||
def put_object(self, **kwargs: object) -> dict[str, object]:
|
||||
key = (str(kwargs["Bucket"]), str(kwargs["Key"]))
|
||||
if kwargs.get("IfNoneMatch") != "*":
|
||||
raise AssertionError("conditional create was not requested")
|
||||
if key in self.objects:
|
||||
raise _ProviderConflict
|
||||
body = kwargs["Body"]
|
||||
assert isinstance(body, bytes)
|
||||
self.objects[key] = body
|
||||
return {"ETag": "opaque-storage-token"}
|
||||
|
||||
def get_object(self, **kwargs: object) -> dict[str, object]:
|
||||
key = (str(kwargs["Bucket"]), str(kwargs["Key"]))
|
||||
if key not in self.objects:
|
||||
raise _ProviderMissing
|
||||
return {"Body": io.BytesIO(self.objects[key]), "ContentLength": len(self.objects[key])}
|
||||
|
||||
|
||||
class _ProviderConflict(Exception):
|
||||
response = {"Error": {"Code": "ConditionalRequestConflict", "Message": "provider-secret"}}
|
||||
|
||||
|
||||
class _ProviderMissing(Exception):
|
||||
response = {"Error": {"Code": "NoSuchKey", "Message": "provider-secret"}}
|
||||
|
||||
|
||||
def _settings():
|
||||
from benchmarks.valid.store_configuration import StorePurpose, StoreSettings
|
||||
|
||||
return StoreSettings(
|
||||
StorePurpose.DURABLE,
|
||||
"https://store.internal.invalid:9000",
|
||||
"valid-benchmark-durable",
|
||||
"ACCESS-SECRET",
|
||||
"SECRET-SECRET",
|
||||
"eu-test-1",
|
||||
"SESSION-SECRET",
|
||||
)
|
||||
|
||||
|
||||
def _read_authority():
|
||||
from benchmarks.valid.artifact_repository import ArtifactActorRole, artifact_read_authority
|
||||
|
||||
return artifact_read_authority(ArtifactActorRole.OPERATOR, (), READ_POLICY, expected_access_policy_digest=READ_POLICY)
|
||||
|
||||
|
||||
def case_for(name: str, **changes: Any) -> dict[str, Any]:
|
||||
app = _APPS[name]
|
||||
parent, fix = _REVISIONS[name]
|
||||
case = {
|
||||
"id": f"{name}-case",
|
||||
"repo": app["repo"],
|
||||
"url": app["url"],
|
||||
"advisory": f"GHSA-cohort-{name}",
|
||||
"cwe": app["cwe"],
|
||||
"family": app["family"],
|
||||
"language": app["language"],
|
||||
"commit": fix,
|
||||
"parent": parent,
|
||||
"path": app["path"],
|
||||
"function": app["function"],
|
||||
"advisory_text": f"Cohort fixture advisory for {name} describing the defect.",
|
||||
}
|
||||
case.update(changes)
|
||||
return case
|
||||
|
||||
|
||||
def request_for(name: str, **changes: Any):
|
||||
app = _APPS[name]
|
||||
case_changes = {key: value for key, value in changes.items() if key != "advisory_text"}
|
||||
advisory_text = changes.get("advisory_text", f"Cohort fixture advisory for {name} describing the defect.")
|
||||
return sourcing_candidate_request(
|
||||
case_for(name, advisory_text=advisory_text, **case_changes),
|
||||
family=family_evidence(
|
||||
vulnerability_family=app["family"],
|
||||
cwe=app["cwe"],
|
||||
advisory_locator=f"GHSA-cohort-{name}",
|
||||
advisory_text=advisory_text,
|
||||
),
|
||||
reachability=reachability_evidence(entry_point=f"route:/run/{name}", evidence=f"route:/run/{name}"),
|
||||
package_evidence=PackageEcosystemEvidence(app["hint"], EvidenceRef("requirements.txt", content_digest({"manifest": name}), 27)),
|
||||
license_evidence=LicenseEvidence("MIT", EvidenceRef("LICENSE", content_digest({"license": name}), 21)),
|
||||
)
|
||||
|
||||
|
||||
def resolver() -> RepositoryIdentityResolver:
|
||||
return RepositoryIdentityResolver(build_network_identity(app["url"]) for app in _APPS.values())
|
||||
|
||||
|
||||
def authority(resolver_: RepositoryIdentityResolver, legacy: tuple = ()) -> ReservationAuthority:
|
||||
return ReservationAuthority(resolver_, legacy_sources=tuple(legacy))
|
||||
|
||||
|
||||
def python_cohort_state(
|
||||
requests: list | None = None,
|
||||
*,
|
||||
resolver_: RepositoryIdentityResolver | None = None,
|
||||
authority_: ReservationAuthority | None = None,
|
||||
per_ecosystem_cap: int = 20,
|
||||
) -> tuple[SourcingQueueStateV1, RepositoryIdentityResolver]:
|
||||
resolved = resolver_ or resolver()
|
||||
state = build_sourcing_queue(
|
||||
requests or [request_for(f"py-{index:02d}") for index in range(PYTHON_COUNT)] + [request_for("js-00")],
|
||||
reader=FakeReader(),
|
||||
resolver=resolved,
|
||||
authority=authority_ or authority(resolved),
|
||||
policy=sourcing_queue_policy(per_ecosystem_cap=per_ecosystem_cap, required_families=2),
|
||||
enumeration_actor=ENUMERATION_ACTOR,
|
||||
enumeration_reviewer=ENUMERATION_REVIEWER,
|
||||
)
|
||||
return state, resolved
|
||||
|
||||
|
||||
def candidates_for(requests: list, resolver_: RepositoryIdentityResolver) -> dict[str, FixSiteCandidateV1]:
|
||||
result: dict[str, FixSiteCandidateV1] = {}
|
||||
for request in requests:
|
||||
fix_request = candidate_request(
|
||||
request.case,
|
||||
resolver=resolver_,
|
||||
package_evidence=request.package_evidence,
|
||||
license_evidence=request.license_evidence,
|
||||
)
|
||||
candidate = build_fix_site_candidate(FakeReader(), fix_request)
|
||||
result[candidate.candidate_digest] = candidate
|
||||
return result
|
||||
|
||||
|
||||
def python_entries(state: SourcingQueueStateV1) -> list[ReviewQueueEntryV1]:
|
||||
return [*state.python_queue.entries]
|
||||
|
||||
|
||||
def _eco_value(att: EcosystemReviewAttestationV1) -> dict[str, Any]:
|
||||
return {
|
||||
"candidate_digest": att.candidate_digest,
|
||||
"source_evidence_digest": att.source_evidence_digest,
|
||||
"producer_identity": att.producer_identity,
|
||||
"reviewer_identity": att.reviewer_identity,
|
||||
"conflict_disclosed": att.conflict_disclosed,
|
||||
"policy_digest": att.policy_digest,
|
||||
"policy_satisfied": att.policy_satisfied,
|
||||
"decision": att.decision.value,
|
||||
}
|
||||
|
||||
|
||||
def _gt_value(att: GroundTruthAttestationV1) -> dict[str, Any]:
|
||||
return {
|
||||
"candidate_digest": att.candidate_digest,
|
||||
"ecosystem_review_digest": att.ecosystem_review_digest,
|
||||
"producer_identity": att.producer_identity,
|
||||
"reviewer_identity": att.reviewer_identity,
|
||||
"conflict_disclosed": att.conflict_disclosed,
|
||||
"policy_digest": att.policy_digest,
|
||||
"policy_satisfied": att.policy_satisfied,
|
||||
"defect_present": att.defect_present,
|
||||
"fix_addresses": att.fix_addresses,
|
||||
"in_repository_reachable": att.in_repository_reachable,
|
||||
"verified_scopes": tuple(
|
||||
{"vulnerability_family": scope.vulnerability_family, "ecosystem": scope.ecosystem.value} for scope in att.verified_scopes
|
||||
),
|
||||
"model_assistance_digest": att.model_assistance_digest,
|
||||
}
|
||||
|
||||
|
||||
def reviewed_record(
|
||||
entry: ReviewQueueEntryV1,
|
||||
candidate: FixSiteCandidateV1,
|
||||
*,
|
||||
eco_changes: dict[str, Any] | None = None,
|
||||
gt_changes: dict[str, Any] | None = None,
|
||||
entry_digest: str | None = None,
|
||||
record_extra: dict[str, Any] | None = None,
|
||||
derive_review: bool = True,
|
||||
) -> tuple[bytes, GroundTruthReviewV1 | None]:
|
||||
"""Build one external review record and the review the authorities derive from it."""
|
||||
locator = entry.family.advisory_locator
|
||||
eco = replace(
|
||||
EcosystemReviewAttestationV1(
|
||||
candidate_digest=candidate.candidate_digest,
|
||||
source_evidence_digest=candidate.source_evidence.evidence_digest,
|
||||
producer_identity=ECOSYSTEM_PRODUCER,
|
||||
reviewer_identity=ECOSYSTEM_REVIEWER,
|
||||
conflict_disclosed=True,
|
||||
policy_digest=ECOSYSTEM_POLICY,
|
||||
policy_satisfied=True,
|
||||
decision=EcosystemReviewDecision.PYTHON,
|
||||
),
|
||||
**(eco_changes or {}),
|
||||
)
|
||||
ecosystem = review_repository_ecosystem(candidate, eco, expected_policy_digest=ECOSYSTEM_POLICY)
|
||||
ground_truth = replace(
|
||||
GroundTruthAttestationV1(
|
||||
candidate_digest=candidate.candidate_digest,
|
||||
ecosystem_review_digest=ecosystem.review_digest,
|
||||
producer_identity=f"producer-{locator}@example.invalid",
|
||||
reviewer_identity=f"reviewer-{locator}@example.invalid",
|
||||
conflict_disclosed=True,
|
||||
policy_digest=GROUND_TRUTH_POLICY,
|
||||
policy_satisfied=True,
|
||||
defect_present=True,
|
||||
fix_addresses=True,
|
||||
in_repository_reachable=True,
|
||||
verified_scopes=(VerifiedScope(entry.family.vulnerability_family, "python"),),
|
||||
model_assistance_digest=None,
|
||||
),
|
||||
**(gt_changes or {}),
|
||||
)
|
||||
review = None
|
||||
if derive_review:
|
||||
review = review_ground_truth(
|
||||
candidate,
|
||||
ecosystem,
|
||||
ground_truth,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
payload: dict[str, Any] = {
|
||||
"schema_version": EXTERNAL_REVIEW_RECORD_SCHEMA,
|
||||
"queue_entry_digest": entry_digest or entry.entry_digest,
|
||||
"ecosystem_attestation": _eco_value(eco),
|
||||
"ground_truth_attestation": _gt_value(ground_truth),
|
||||
}
|
||||
payload.update(record_extra or {})
|
||||
return canonical_bytes(payload), review
|
||||
|
||||
|
||||
def model_only_assistance_digest() -> str:
|
||||
from benchmarks.valid import verify
|
||||
|
||||
record = {
|
||||
"id": "model-only-fixture",
|
||||
"vulnerable_pre_fix": True,
|
||||
"fix_addresses_it": True,
|
||||
"reachable_in_repo": True,
|
||||
"entry_point": "route:/run/model-only",
|
||||
"confidence": 0.91,
|
||||
"model": "stub",
|
||||
"advisory_cited": True,
|
||||
}
|
||||
return verify.model_assistance_digest(record)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ECOSYSTEM_POLICY",
|
||||
"ECOSYSTEM_PRODUCER",
|
||||
"ECOSYSTEM_REVIEWER",
|
||||
"ENUMERATION_ACTOR",
|
||||
"ENUMERATION_REVIEWER",
|
||||
"GROUND_TRUTH_POLICY",
|
||||
"FakeReader",
|
||||
"PYTHON_COUNT",
|
||||
"READ_POLICY",
|
||||
"RepositoryEcosystemReviewV1",
|
||||
"authority",
|
||||
"candidates_for",
|
||||
"case_for",
|
||||
"model_only_assistance_digest",
|
||||
"python_cohort_state",
|
||||
"python_entries",
|
||||
"request_for",
|
||||
"resolver",
|
||||
"reviewed_record",
|
||||
]
|
||||
@@ -0,0 +1,359 @@
|
||||
"""Bounded ingestion of the first independently reviewed Python cohort."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
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
|
||||
ECOSYSTEM_POLICY,
|
||||
GROUND_TRUTH_POLICY,
|
||||
PYTHON_COUNT,
|
||||
FakeReader,
|
||||
authority,
|
||||
candidates_for,
|
||||
model_only_assistance_digest,
|
||||
python_cohort_state,
|
||||
python_entries,
|
||||
request_for,
|
||||
resolver,
|
||||
reviewed_record,
|
||||
)
|
||||
|
||||
from benchmarks.valid.cohort_ingestion import ( # noqa: E402
|
||||
COHORT_BATCH_CAP,
|
||||
MINIMUM_ACCEPTED_POSITIVES,
|
||||
CohortBatchStatus,
|
||||
CohortInsufficientReason,
|
||||
cohort_batch_bytes,
|
||||
ingest_python_cohort_batch,
|
||||
)
|
||||
from benchmarks.valid.ecosystem_review import EcosystemReviewDecision # noqa: E402
|
||||
from benchmarks.valid.ground_truth_review import GroundTruthStatus, VerifiedScope # noqa: E402
|
||||
from benchmarks.valid.reservation import legacy_reservation_source # noqa: E402
|
||||
from benchmarks.valid.sourcing_queue import SourcingQueueReason, sourcing_queue_policy # noqa: E402
|
||||
from benchmarks.valid.sourcing_queue_build import InsufficientFamiliesRefusal, build_sourcing_queue # noqa: E402
|
||||
from openultrasast.core.canonical import bytes_digest # noqa: E402
|
||||
|
||||
ENUMERATION_ACTOR = "[email protected]"
|
||||
ENUMERATION_REVIEWER = "[email protected]"
|
||||
|
||||
|
||||
@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 _ingest(records, state, candidates):
|
||||
return ingest_python_cohort_batch(
|
||||
records,
|
||||
state=state,
|
||||
candidates_by_digest=candidates,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
|
||||
|
||||
def _prepared():
|
||||
state, resolved = python_cohort_state()
|
||||
requests = [request_for(f"py-{index:02d}") for index in range(PYTHON_COUNT)] + [request_for("js-00")]
|
||||
return state, candidates_for(requests, resolved)
|
||||
|
||||
|
||||
def _good_records(state, candidates):
|
||||
return [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in python_entries(state)]
|
||||
|
||||
|
||||
def _by_reason(outcome):
|
||||
return {item.reason: item for item in outcome.record_outcomes if item.reason is not None}
|
||||
|
||||
|
||||
def _built(requests, *, cap=20, authority_=None, resolver_=None):
|
||||
resolved = resolver_ or resolver()
|
||||
return build_sourcing_queue(
|
||||
requests,
|
||||
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,
|
||||
)
|
||||
|
||||
|
||||
def test_first_bounded_python_batch_reaches_ten_accepted_reachable_positives():
|
||||
state, candidates = _prepared()
|
||||
records = _good_records(state, candidates)
|
||||
|
||||
assert len(records) == PYTHON_COUNT <= COHORT_BATCH_CAP
|
||||
outcome = _ingest(records, state, candidates)
|
||||
|
||||
assert outcome.status is CohortBatchStatus.ACCEPTED
|
||||
assert outcome.insufficient_reason is None
|
||||
assert len(outcome.accepted_positives) == PYTHON_COUNT >= MINIMUM_ACCEPTED_POSITIVES
|
||||
assert outcome.pending_entries == ()
|
||||
assert all(item.status.value == "accepted" for item in outcome.record_outcomes)
|
||||
families = {scope.vulnerability_family for positive in outcome.accepted_positives for scope in positive.verified_scopes}
|
||||
assert len(families) >= 2
|
||||
assert all(scope.ecosystem.value == "python" for positive in outcome.accepted_positives for scope in positive.verified_scopes)
|
||||
assert outcome.census_digest == state.census_digest
|
||||
assert outcome.queue_digest == state.python_queue.queue_digest
|
||||
|
||||
shuffled = list(reversed(records))
|
||||
replayed = _ingest(shuffled, state, candidates)
|
||||
assert replayed == outcome
|
||||
assert replayed.batch_digest == outcome.batch_digest
|
||||
|
||||
|
||||
def test_every_accepted_and_excluded_candidate_replays_from_external_review_evidence():
|
||||
state, candidates = _prepared()
|
||||
entries = python_entries(state)
|
||||
weak = {
|
||||
"conflict_disclosure_missing": {"conflict_disclosed": False},
|
||||
"judgment_missing": {"defect_present": None},
|
||||
"judgment_rejected": {"in_repository_reachable": False},
|
||||
"missing_scope": {"verified_scopes": ()},
|
||||
"policy_unsatisfied": {"policy_satisfied": False},
|
||||
}
|
||||
records = []
|
||||
expected = {}
|
||||
for index, entry in enumerate(entries):
|
||||
key = sorted(weak)[index] if index < len(weak) else None
|
||||
changes = dict(weak[key]) if key else None
|
||||
if index == len(weak):
|
||||
changes = {"reviewer_identity": f"producer-{entry.family.advisory_locator}@example.invalid"}
|
||||
content, review = reviewed_record(entry, candidates[entry.candidate_digest], gt_changes=changes)
|
||||
records.append(content)
|
||||
expected[entry.entry_digest] = review
|
||||
unknown = reviewed_record(entries[0], candidates[entries[0].candidate_digest], entry_digest="0" * 64)[0]
|
||||
records.append(unknown)
|
||||
|
||||
outcome = _ingest(records, state, candidates)
|
||||
replayed = _ingest(list(reversed(records)), state, candidates)
|
||||
assert replayed == outcome
|
||||
assert replayed.batch_digest == outcome.batch_digest
|
||||
assert any(item.record_digest == bytes_digest(unknown) for item in outcome.record_outcomes)
|
||||
|
||||
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.status is GroundTruthStatus.ACCEPTED:
|
||||
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
|
||||
|
||||
|
||||
def test_review_policy_failures_are_recorded_never_fabricated():
|
||||
state, candidates = _prepared()
|
||||
entries = python_entries(state)
|
||||
|
||||
def self_review_for(entry):
|
||||
return {"reviewer_identity": f"producer-{entry.family.advisory_locator}@example.invalid"}
|
||||
|
||||
cases = [
|
||||
({"decision": EcosystemReviewDecision.JAVASCRIPT}, lambda entry: {}),
|
||||
(None, self_review_for),
|
||||
(None, lambda entry: {"conflict_disclosed": False}),
|
||||
(None, lambda entry: {"policy_satisfied": False}),
|
||||
(None, lambda entry: {"defect_present": None}),
|
||||
(None, lambda entry: {"in_repository_reachable": False}),
|
||||
(None, lambda entry: {"defect_present": None, "fix_addresses": None, "in_repository_reachable": None,
|
||||
"model_assistance_digest": model_only_assistance_digest()}),
|
||||
(None, lambda entry: {"verified_scopes": ()}),
|
||||
(None, lambda entry: {"verified_scopes": (VerifiedScope("injection", "javascript"),)}),
|
||||
]
|
||||
records = []
|
||||
expected_reasons = []
|
||||
for entry, (eco_changes, gt_builder) in zip(entries, cases, strict=False):
|
||||
content, review = reviewed_record(entry, candidates[entry.candidate_digest], eco_changes=eco_changes, gt_changes=gt_builder(entry))
|
||||
records.append(content)
|
||||
expected_reasons.append(review.exclusion_reason.value)
|
||||
|
||||
outcome = _ingest(records, state, candidates)
|
||||
|
||||
assert outcome.status is CohortBatchStatus.INSUFFICIENT
|
||||
assert outcome.insufficient_reason is CohortInsufficientReason.INSUFFICIENT_ACCEPTED_POSITIVES
|
||||
assert outcome.accepted_positives == ()
|
||||
assert sorted(expected_reasons) == sorted(item.reason for item in outcome.record_outcomes)
|
||||
assert outcome.pending_entries == tuple(sorted(entry.entry_digest for entry in entries[len(cases):]))
|
||||
|
||||
|
||||
def test_unknown_entry_missing_candidate_and_duplicate_records_are_closed():
|
||||
state, candidates = _prepared()
|
||||
entries = python_entries(state)
|
||||
js_entry = state.javascript_queue.entries[0]
|
||||
js_record = reviewed_record(js_entry, candidates[js_entry.candidate_digest])[0]
|
||||
unknown = reviewed_record(entries[0], candidates[entries[0].candidate_digest], entry_digest="1" * 64)[0]
|
||||
good, _ = reviewed_record(entries[1], candidates[entries[1].candidate_digest])
|
||||
thinned = dict(candidates)
|
||||
del thinned[entries[2].candidate_digest]
|
||||
missing, _ = reviewed_record(entries[2], candidates[entries[2].candidate_digest])
|
||||
|
||||
outcome = _ingest([js_record, unknown, good, good, missing], state, thinned)
|
||||
|
||||
reasons = _by_reason(outcome)
|
||||
unknown_digests = {item.queue_entry_digest for item in outcome.record_outcomes if item.reason == "queue_entry_unknown"}
|
||||
assert unknown_digests == {js_entry.entry_digest, "1" * 64}
|
||||
assert reasons["duplicate_record"].queue_entry_digest == entries[1].entry_digest
|
||||
assert reasons["candidate_evidence_missing"].queue_entry_digest == entries[2].entry_digest
|
||||
assert entries[0].entry_digest in outcome.pending_entries
|
||||
assert len(outcome.pending_entries) == len(entries) - 1
|
||||
|
||||
|
||||
def test_stale_review_evidence_is_refused_closed():
|
||||
state, candidates = _prepared()
|
||||
entries = python_entries(state)
|
||||
stale, _ = reviewed_record(
|
||||
entries[0], candidates[entries[0].candidate_digest], gt_changes={"candidate_digest": "2" * 64}, derive_review=False
|
||||
)
|
||||
wrong_policy, _ = reviewed_record(
|
||||
entries[1], candidates[entries[1].candidate_digest], gt_changes={"policy_digest": ECOSYSTEM_POLICY}, derive_review=False
|
||||
)
|
||||
|
||||
outcome = _ingest([stale, wrong_policy], state, candidates)
|
||||
|
||||
reasons = _by_reason(outcome)
|
||||
assert reasons["review_evidence_invalid"].queue_entry_digest == entries[0].entry_digest
|
||||
assert [item.reason for item in outcome.record_outcomes].count("review_evidence_invalid") == 2
|
||||
|
||||
|
||||
def test_external_records_are_hostile_decoded_and_label_blind():
|
||||
state, candidates = _prepared()
|
||||
entries = python_entries(state)
|
||||
good, _ = reviewed_record(entries[0], candidates[entries[0].candidate_digest])
|
||||
spaced = json.dumps(json.loads(good), sort_keys=True, indent=1).encode("utf-8")
|
||||
wrong_schema = json.dumps({**json.loads(good), "schema_version": "other.v1"}, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
labeled = json.dumps({**json.loads(good), "verdict": "accepted"}, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
|
||||
outcome = _ingest(
|
||||
[b"", b"not json at all", b'{"x":NaN}', b'{"x":1e999}', b'{"k":' + b"[" * 20000 + b"]" * 20000 + b"}",
|
||||
spaced, wrong_schema, labeled],
|
||||
state,
|
||||
candidates,
|
||||
)
|
||||
|
||||
assert outcome.record_outcomes and all(item.status.value == "excluded" for item in outcome.record_outcomes)
|
||||
assert sum(1 for item in outcome.record_outcomes if item.reason == "record_unreadable") == 6
|
||||
assert sum(1 for item in outcome.record_outcomes if item.reason == "record_schema_mismatch") == 2
|
||||
assert outcome.pending_entries == tuple(sorted(entry.entry_digest for entry in entries))
|
||||
assert outcome.status is CohortBatchStatus.INSUFFICIENT
|
||||
assert outcome.insufficient_reason is CohortInsufficientReason.INSUFFICIENT_ACCEPTED_POSITIVES
|
||||
|
||||
|
||||
def test_ingestion_module_and_outputs_are_label_blind():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
for name in ("benchmarks/valid/cohort_ingestion.py", "benchmarks/valid/cohort_ingestion_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, candidates = _prepared()
|
||||
content = cohort_batch_bytes(_ingest(_good_records(state, candidates), state, candidates))
|
||||
for forbidden in (b"admission", b"detector", b"observation", b"label", b"verdict", b"score"):
|
||||
assert forbidden not in content
|
||||
|
||||
|
||||
def test_zero_input_batches_are_refused_not_clean():
|
||||
state, candidates = _prepared()
|
||||
empty = _ingest([], state, candidates)
|
||||
assert empty.status is CohortBatchStatus.INSUFFICIENT
|
||||
assert empty.insufficient_reason is CohortInsufficientReason.BATCH_EMPTY
|
||||
assert empty.record_outcomes == () and empty.accepted_positives == ()
|
||||
|
||||
js_only, js_resolver = python_cohort_state([request_for("js-00"), request_for("js-01")])
|
||||
assert js_only.python_queue.entries == ()
|
||||
js_candidates = candidates_for([request_for("js-00"), request_for("js-01")], js_resolver)
|
||||
entry = js_only.javascript_queue.entries[0]
|
||||
record, _ = reviewed_record(entry, js_candidates[entry.candidate_digest])
|
||||
outcome = _ingest([record], js_only, js_candidates)
|
||||
assert outcome.status is CohortBatchStatus.INSUFFICIENT
|
||||
assert outcome.insufficient_reason is CohortInsufficientReason.PYTHON_QUEUE_EMPTY
|
||||
|
||||
|
||||
def test_batch_cap_refuses_over_twenty_records_with_every_record_ledgered():
|
||||
state, candidates = _prepared()
|
||||
records = _good_records(state, candidates)
|
||||
while len(records) <= COHORT_BATCH_CAP:
|
||||
records.append(records[0])
|
||||
records = records[: COHORT_BATCH_CAP + 1]
|
||||
|
||||
outcome = _ingest(records, state, candidates)
|
||||
|
||||
assert outcome.status is CohortBatchStatus.INSUFFICIENT
|
||||
assert outcome.insufficient_reason is CohortInsufficientReason.BATCH_CAP_EXCEEDED
|
||||
assert len(outcome.record_outcomes) == COHORT_BATCH_CAP + 1
|
||||
assert {item.reason for item in outcome.record_outcomes} == {"batch_unit_refused"}
|
||||
assert outcome.accepted_positives == ()
|
||||
assert outcome.pending_entries == tuple(sorted(entry.entry_digest for entry in python_entries(state)))
|
||||
|
||||
|
||||
def test_reserved_repositories_cannot_reenter_through_a_record():
|
||||
resolved = resolver()
|
||||
py_url = "https://github.com/fixture/cohort-py-00"
|
||||
legacy = (legacy_reservation_source(resolved, repository=py_url, source_digest="a" * 64),)
|
||||
reserved_authority = authority(resolved, legacy=legacy)
|
||||
requests = [request_for(f"py-{index:02d}") for index in range(1, PYTHON_COUNT)] + [request_for("js-00")]
|
||||
state = _built(requests, authority_=reserved_authority, resolver_=resolved)
|
||||
candidates = candidates_for(requests, resolved)
|
||||
assert len(reserved_authority.current_census().reserved_network_digests) == 1
|
||||
assert py_url not in {entry.canonical_repository for entry in python_entries(state)}
|
||||
|
||||
reserved_candidate = next(iter(candidates_for([request_for("py-00")], resolved).values()))
|
||||
entry = python_entries(state)[0]
|
||||
forged, _ = reviewed_record(entry, reserved_candidate)
|
||||
good_without_entry = [
|
||||
reviewed_record(item, candidates[item.candidate_digest])[0] for item in python_entries(state)[1:]
|
||||
]
|
||||
outcome = _ingest([forged, *good_without_entry], state, candidates)
|
||||
|
||||
assert outcome.status is CohortBatchStatus.ACCEPTED
|
||||
assert len(outcome.accepted_positives) == PYTHON_COUNT - 2
|
||||
assert all(positive.candidate_digest != reserved_candidate.candidate_digest for positive in outcome.accepted_positives)
|
||||
assert outcome.census_digest == state.census_digest
|
||||
assert _by_reason(outcome)["review_evidence_invalid"].queue_entry_digest == entry.entry_digest
|
||||
assert entry.entry_digest in outcome.pending_entries
|
||||
|
||||
|
||||
def test_insufficient_families_refusal_carries_its_attempt_exclusions():
|
||||
requests = [request_for("py-00"), request_for("py-00"), request_for("py-02")]
|
||||
with pytest.raises(InsufficientFamiliesRefusal) as error:
|
||||
_built(requests)
|
||||
assert error.value.reason is SourcingQueueReason.INSUFFICIENT_FAMILIES
|
||||
attempt = error.value.attempt_exclusions
|
||||
assert len(attempt) == 1
|
||||
assert attempt[0].reason is SourcingQueueReason.DUPLICATE_CANDIDATE
|
||||
|
||||
|
||||
def test_tied_but_distinct_requests_order_by_remaining_content_digests():
|
||||
from benchmarks.valid.sourcing_queue import pending_queue_identities
|
||||
|
||||
first = request_for("py-00", advisory_text="Tied advisory body one.")
|
||||
second = request_for("py-00", advisory_text="Tied advisory body two.")
|
||||
assert first.family.advisory_digest != second.family.advisory_digest
|
||||
|
||||
forward = _built([first, second, request_for("js-01")], cap=1)
|
||||
backward = _built([second, first, request_for("js-01")], cap=1)
|
||||
|
||||
assert forward.state_digest == backward.state_digest
|
||||
assert pending_queue_identities(forward) == pending_queue_identities(backward)
|
||||
assert forward.exclusions == backward.exclusions
|
||||
assert len(forward.python_queue.entries) == 1
|
||||
assert {item.reason for item in forward.exclusions} == {SourcingQueueReason.QUEUE_CAP_EXCEEDED}
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Durable persistence and replay for the bounded Python cohort batch."""
|
||||
|
||||
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
|
||||
ECOSYSTEM_POLICY,
|
||||
GROUND_TRUTH_POLICY,
|
||||
PYTHON_COUNT,
|
||||
READ_POLICY,
|
||||
FakeReader,
|
||||
_Client,
|
||||
_read_authority,
|
||||
_settings,
|
||||
authority,
|
||||
candidates_for,
|
||||
python_cohort_state,
|
||||
python_entries,
|
||||
request_for,
|
||||
resolver,
|
||||
reviewed_record,
|
||||
)
|
||||
|
||||
from benchmarks.valid import cohort_ingestion_store # noqa: E402
|
||||
from benchmarks.valid.artifact_repository import S3ArtifactRepository # noqa: E402
|
||||
from benchmarks.valid.cohort_ingestion import ( # noqa: E402
|
||||
CohortBatchStatus,
|
||||
CohortInsufficientReason,
|
||||
cohort_batch_bytes,
|
||||
ingest_python_cohort_batch,
|
||||
)
|
||||
from benchmarks.valid.replacement_artifact_contract import ArtifactAccessClass, ArtifactKind, validate_artifact # noqa: E402
|
||||
from benchmarks.valid.sourcing_queue import SourcingQueueReason, sourcing_queue_policy # noqa: E402
|
||||
from benchmarks.valid.sourcing_queue_build import InsufficientFamiliesRefusal, build_sourcing_queue # 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 _ingest(records, state, candidates):
|
||||
return ingest_python_cohort_batch(
|
||||
records,
|
||||
state=state,
|
||||
candidates_by_digest=candidates,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
|
||||
|
||||
def _prepared():
|
||||
state, resolved = python_cohort_state()
|
||||
requests = [request_for(f"py-{index:02d}") for index in range(PYTHON_COUNT)] + [request_for("js-00")]
|
||||
return state, candidates_for(requests, resolved)
|
||||
|
||||
|
||||
def _records(state, candidates):
|
||||
return [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in python_entries(state)]
|
||||
|
||||
|
||||
def test_accepted_batch_persists_resumes_and_replays_from_durable_evidence():
|
||||
client = _Client()
|
||||
store = S3ArtifactRepository(_settings(), client)
|
||||
state, candidates = _prepared()
|
||||
records = _records(state, candidates)
|
||||
outcome = _ingest(records, state, candidates)
|
||||
assert outcome.status is CohortBatchStatus.ACCEPTED
|
||||
|
||||
record_references = cohort_ingestion_store.publish_external_review_records(store, records)
|
||||
reference = cohort_ingestion_store.persist_cohort_batch(store, outcome)
|
||||
assert cohort_ingestion_store.persist_cohort_batch(store, outcome) == reference
|
||||
accepted = store.get(
|
||||
reference, expected_kind=ArtifactKind.REVIEW, authority=_read_authority(), expected_access_policy_digest=READ_POLICY
|
||||
)
|
||||
validate_artifact(accepted.content, reference=reference)
|
||||
assert reference.access_class is ArtifactAccessClass.OPERATOR_SAFE
|
||||
|
||||
restarted = S3ArtifactRepository(_settings(), client)
|
||||
resumed = cohort_ingestion_store.resume_cohort_batch(
|
||||
restarted, reference, authority=_read_authority(), expected_access_policy_digest=READ_POLICY
|
||||
)
|
||||
assert resumed == outcome
|
||||
assert cohort_batch_bytes(resumed) == cohort_batch_bytes(outcome)
|
||||
|
||||
reread = cohort_ingestion_store.read_external_review_records(
|
||||
restarted, record_references, authority=_read_authority(), expected_access_policy_digest=READ_POLICY
|
||||
)
|
||||
replayed = _ingest(reread, state, candidates)
|
||||
assert replayed == outcome
|
||||
assert replayed.batch_digest == outcome.batch_digest
|
||||
|
||||
|
||||
def test_refused_batches_durably_persist_their_exclusions():
|
||||
store = S3ArtifactRepository(_settings(), _Client())
|
||||
state, candidates = _prepared()
|
||||
entries = python_entries(state)
|
||||
weak = [
|
||||
reviewed_record(entries[0], candidates[entries[0].candidate_digest], gt_changes={"defect_present": None}),
|
||||
reviewed_record(entries[1], candidates[entries[1].candidate_digest], gt_changes={"conflict_disclosed": False}),
|
||||
]
|
||||
good = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries[2:5]]
|
||||
outcome = _ingest([weak[0][0], weak[1][0], *good], state, candidates)
|
||||
|
||||
assert outcome.status is CohortBatchStatus.INSUFFICIENT
|
||||
assert outcome.insufficient_reason is CohortInsufficientReason.INSUFFICIENT_ACCEPTED_POSITIVES
|
||||
reference = cohort_ingestion_store.persist_cohort_batch(store, outcome)
|
||||
|
||||
resumed = cohort_ingestion_store.resume_cohort_batch(
|
||||
store, reference, authority=_read_authority(), expected_access_policy_digest=READ_POLICY
|
||||
)
|
||||
assert resumed == outcome
|
||||
reasons = {item.reason for item in resumed.record_outcomes if item.reason is not None}
|
||||
assert reasons == {"missing_human_judgment", "conflict_disclosure_missing"}
|
||||
assert len(resumed.accepted_positives) == 3
|
||||
assert len(resumed.pending_entries) == len(entries) - 5
|
||||
|
||||
|
||||
def test_insufficient_families_refusal_persists_its_exclusions_durably():
|
||||
store = S3ArtifactRepository(_settings(), _Client())
|
||||
resolved = resolver()
|
||||
requests = [request_for("py-00"), request_for("py-00"), request_for("py-02")]
|
||||
with pytest.raises(InsufficientFamiliesRefusal) as error:
|
||||
build_sourcing_queue(
|
||||
requests,
|
||||
reader=FakeReader(),
|
||||
resolver=resolved,
|
||||
authority=authority(resolved),
|
||||
policy=sourcing_queue_policy(per_ecosystem_cap=20, required_families=2),
|
||||
enumeration_actor="[email protected]",
|
||||
enumeration_reviewer="[email protected]",
|
||||
)
|
||||
attempt = error.value.attempt_exclusions
|
||||
assert len(attempt) == 1
|
||||
|
||||
reference = cohort_ingestion_store.persist_refused_queue_exclusions(
|
||||
store, attempt, policy_digest=sourcing_queue_policy(per_ecosystem_cap=20).policy_digest
|
||||
)
|
||||
accepted = store.get(
|
||||
reference, expected_kind=ArtifactKind.POPULATION, authority=_read_authority(), expected_access_policy_digest=READ_POLICY
|
||||
)
|
||||
payload = accepted.artifact.payload
|
||||
assert payload["exclusions"]
|
||||
persisted = payload["exclusions"][0]
|
||||
assert persisted["reason"] == SourcingQueueReason.DUPLICATE_CANDIDATE.value
|
||||
assert persisted["exclusion_digest"] == attempt[0].exclusion_digest
|
||||
|
||||
|
||||
def test_batch_outcome_decode_refuses_hostile_and_tampered_bytes():
|
||||
state, candidates = _prepared()
|
||||
outcome = _ingest(_records(state, candidates), state, candidates)
|
||||
content = cohort_batch_bytes(outcome)
|
||||
decode = cohort_ingestion_store.decode_cohort_batch
|
||||
|
||||
with pytest.raises(cohort_ingestion_store.CohortStateError):
|
||||
decode(b"")
|
||||
with pytest.raises(cohort_ingestion_store.CohortStateError):
|
||||
decode(b"not json at all")
|
||||
with pytest.raises(cohort_ingestion_store.CohortStateError):
|
||||
decode(b'{"schema_version":"openultrasast.valid-detection-benchmark.python-cohort-batch.v1","x":NaN}')
|
||||
with pytest.raises(cohort_ingestion_store.CohortStateError):
|
||||
decode(b'{"k":' + b"[" * 20000 + b"]" * 20000 + b"}")
|
||||
assert decode(content) == outcome
|
||||
|
||||
import json
|
||||
|
||||
tampered = json.loads(content)
|
||||
tampered["batch_digest"] = "0" * 64
|
||||
tampered_bytes = json.dumps(tampered, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
||||
with pytest.raises(cohort_ingestion_store.CohortStateError):
|
||||
decode(tampered_bytes)
|
||||
|
||||
truncated = json.loads(content)
|
||||
truncated["accepted_positives"] = truncated["accepted_positives"][:1]
|
||||
truncated_bytes = json.dumps(truncated, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
||||
with pytest.raises(cohort_ingestion_store.CohortStateError):
|
||||
decode(truncated_bytes)
|
||||
|
||||
|
||||
def test_batch_outcome_decode_closes_bogus_insufficient_reason_as_state_mismatch():
|
||||
state, candidates = _prepared()
|
||||
entries = python_entries(state)
|
||||
weak = [
|
||||
reviewed_record(entries[0], candidates[entries[0].candidate_digest], gt_changes={"defect_present": None}),
|
||||
reviewed_record(entries[1], candidates[entries[1].candidate_digest], gt_changes={"conflict_disclosed": False}),
|
||||
]
|
||||
good = [reviewed_record(entry, candidates[entry.candidate_digest])[0] for entry in entries[2:5]]
|
||||
outcome = _ingest([weak[0][0], weak[1][0], *good], state, candidates)
|
||||
assert outcome.status is CohortBatchStatus.INSUFFICIENT
|
||||
|
||||
import json
|
||||
|
||||
tampered = json.loads(cohort_batch_bytes(outcome))
|
||||
tampered["insufficient_reason"] = "bogus_reason"
|
||||
tampered_bytes = json.dumps(tampered, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
||||
with pytest.raises(cohort_ingestion_store.CohortStateError) as error:
|
||||
cohort_ingestion_store.decode_cohort_batch(tampered_bytes)
|
||||
assert error.value.reason is cohort_ingestion_store.CohortStateReason.STATE_MISMATCH
|
||||
Reference in New Issue
Block a user