feat(valid-detection-benchmark): 10.2 ingest bounded reviewed Python cohort

This commit is contained in:
Marius Ciepluch
2026-11-22 10:25:59 +01:00
parent 34344234d5
commit 825e680804
7 changed files with 1798 additions and 5 deletions
+382
View File
@@ -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