feat(valid-detection-benchmark): 10.5 ingest fourth cohort and close positive set

This commit is contained in:
Marius Ciepluch
2026-11-22 20:12:03 +01:00
parent 6d66501192
commit c2b5f5bc92
7 changed files with 1439 additions and 3 deletions
+289 -2
View File
@@ -18,10 +18,13 @@ from benchmarks.valid.cohort_ingestion import (
COHORT_BATCH_CAP,
MINIMUM_ACCEPTED_POSITIVES,
CohortBatchOutcomeV1,
CohortRecordOutcomeV1,
CohortRecordStatus,
ingest_javascript_cohort_batch,
ingest_python_cohort_batch,
)
from benchmarks.valid.fix_site_catalog import FixSiteCandidateV1
from benchmarks.valid.ground_truth_review import GroundTruthExclusionReason
from benchmarks.valid.sourcing_queue import (
EcosystemReviewQueueV1,
ReviewQueueEntryV1,
@@ -49,9 +52,11 @@ class CohortSelectionReason(StrEnum):
MISSING_ECOSYSTEM_SELECTED = "missing_ecosystem_selected"
FAMILY_GAP_SELECTED = "family_gap_selected"
BALANCED_PROGRESS_SELECTED = "balanced_progress_selected"
CLOSURE_GAP_SELECTED = "closure_gap_selected"
NO_PENDING_ENTRIES = "no_pending_entries"
CENSUS_MISMATCH = "census_mismatch"
POLICY_MISMATCH = "policy_mismatch"
GAP_UNCLOSABLE = "gap_unclosable"
class CohortSelectionStateReason(StrEnum):
@@ -64,6 +69,7 @@ _REFUSAL_REASONS = frozenset(
CohortSelectionReason.NO_PENDING_ENTRIES,
CohortSelectionReason.CENSUS_MISMATCH,
CohortSelectionReason.POLICY_MISMATCH,
CohortSelectionReason.GAP_UNCLOSABLE,
}
)
@@ -479,6 +485,241 @@ def select_third_cohort_batch(
)
_REVIEW_RESOLVED_REASONS = frozenset(item.value for item in GroundTruthExclusionReason)
def _review_resolved(outcome: CohortRecordOutcomeV1) -> bool:
"""True when one external record resolved its queue entry through review."""
if outcome.queue_entry_digest is None:
return False
if outcome.status is CohortRecordStatus.ACCEPTED:
return True
return outcome.reason in _REVIEW_RESOLVED_REASONS
def _pending_by_ecosystem(
state: SourcingQueueStateV1,
batches: Sequence[CohortBatchOutcomeV1],
) -> dict[str, tuple[ReviewQueueEntryV1, ...]]:
"""Pending entries per ecosystem from every batch's resolved records.
A record resolves its entry only through the committed review machinery:
accepted positives and review-level exclusions answer the entry, while
unreadable or evidence-invalid records leave it pending. A narrowed
selection batch therefore surrenders exactly the entries its records
resolved, never the whole shared queue.
"""
queued = {
ecosystem: {entry.entry_digest for entry in _queue_for(state, ecosystem).entries}
for ecosystem in COHORT_SELECTION_ECOSYSTEMS
}
answered: dict[str, set[str]] = {ecosystem: set() for ecosystem in COHORT_SELECTION_ECOSYSTEMS}
for batch in batches:
ecosystem = batch.ecosystem
if ecosystem not in answered:
continue
for outcome in batch.record_outcomes:
if _review_resolved(outcome) and outcome.queue_entry_digest in queued[ecosystem]:
answered[ecosystem].add(outcome.queue_entry_digest)
return {
ecosystem: tuple(
entry for entry in _queue_for(state, ecosystem).entries if entry.entry_digest not in answered[ecosystem]
)
for ecosystem in COHORT_SELECTION_ECOSYSTEMS
}
def _ecosystem_gap(facts: _LedgerFacts) -> tuple[str, ...]:
"""Canonical ecosystems with no accepted positive recorded yet."""
return tuple(
ecosystem for ecosystem in COHORT_SELECTION_ECOSYSTEMS if facts.accepted_by_ecosystem.get(ecosystem, 0) == 0
)
def _fourth_ecosystem(
pending_by: Mapping[str, Sequence[ReviewQueueEntryV1]],
facts: _LedgerFacts,
ecosystem_gap: Sequence[str],
) -> str | None:
"""One ecosystem whose pending batch can close the remaining gap, else None.
A gap-closing batch must be able to contribute the per-batch minimum of
accepted positives; a family gap additionally needs a pending entry from a
family no accepted review has recorded yet.
"""
for ecosystem in ecosystem_gap or COHORT_SELECTION_ECOSYSTEMS:
pending = pending_by[ecosystem]
if len(pending) < MINIMUM_ACCEPTED_POSITIVES:
continue
if not ecosystem_gap and all(entry.family.vulnerability_family in facts.families for entry in pending):
continue
return ecosystem
return None
def _fourth_selected(
state: SourcingQueueStateV1,
ecosystem: str,
reason: CohortSelectionReason,
pending: Sequence[ReviewQueueEntryV1],
facts: _LedgerFacts,
*,
family_gap: bool,
census: str,
eco_policy: str,
gt_policy: str,
) -> CohortSelectionV1:
"""Bind one selected fourth-round batch to the gap facts it serves."""
base = facts.families_by_ecosystem.get(ecosystem, frozenset())
represented = frozenset(facts.families) if family_gap else frozenset(base)
chosen, targeted = _selected_entries(pending, represented)
return cohort_selection(
ecosystem=ecosystem,
selected_entries=chosen,
targeted_families=targeted,
queue_digest=_queue_for(state, ecosystem).queue_digest,
census_digest=census,
ecosystem_policy_digest=eco_policy,
ground_truth_policy_digest=gt_policy,
prior_batch_digests=facts.batch_digests,
accepted_families=facts.families,
accepted_by_ecosystem=facts.accepted_by_ecosystem,
status=CohortSelectionStatus.SELECTED,
reason=reason,
)
def _gap_closing_selection(
state: SourcingQueueStateV1,
pending_by: Mapping[str, Sequence[ReviewQueueEntryV1]],
facts: _LedgerFacts,
*,
census: str,
eco_policy: str,
gt_policy: str,
) -> CohortSelectionV1 | None:
"""Selection closing a remaining ecosystem or family gap, or a closed refusal."""
ecosystem_gap = _ecosystem_gap(facts)
family_gap = len(facts.families) < REQUIRED_DISTINCT_FAMILIES
if not (ecosystem_gap or family_gap):
return None
ecosystem = _fourth_ecosystem(pending_by, facts, ecosystem_gap)
if ecosystem is None:
return _refused(
CohortSelectionReason.GAP_UNCLOSABLE,
facts,
census_digest=census,
ecosystem_policy_digest=eco_policy,
ground_truth_policy_digest=gt_policy,
)
reason = (
CohortSelectionReason.MISSING_ECOSYSTEM_SELECTED if ecosystem_gap else CohortSelectionReason.CLOSURE_GAP_SELECTED
)
return _fourth_selected(
state,
ecosystem,
reason,
pending_by[ecosystem],
facts,
family_gap=family_gap,
census=census,
eco_policy=eco_policy,
gt_policy=gt_policy,
)
def _fourth_decision(
state: SourcingQueueStateV1,
accepted_batches: Sequence[CohortBatchOutcomeV1],
facts: _LedgerFacts,
*,
census: str,
eco_policy: str,
gt_policy: str,
) -> CohortSelectionV1:
try:
pending_by = _pending_by_ecosystem(state, accepted_batches)
if not any(pending_by.values()):
return _refused(
CohortSelectionReason.NO_PENDING_ENTRIES,
facts,
census_digest=census,
ecosystem_policy_digest=eco_policy,
ground_truth_policy_digest=gt_policy,
)
closing = _gap_closing_selection(state, pending_by, facts, census=census, eco_policy=eco_policy, gt_policy=gt_policy)
if closing is not None:
return closing
ranked = sorted(
_ecosystem_rank(pending_by[ecosystem], ecosystem, facts) for ecosystem in COHORT_SELECTION_ECOSYSTEMS
)
for rank in ranked:
ecosystem = rank[4]
if pending_by[ecosystem]:
return _fourth_selected(
state,
ecosystem,
CohortSelectionReason.BALANCED_PROGRESS_SELECTED,
pending_by[ecosystem],
facts,
family_gap=False,
census=census,
eco_policy=eco_policy,
gt_policy=gt_policy,
)
except CohortSelectionStateError:
raise
except (AttributeError, TypeError, ValueError) as error:
raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error
return _refused(
CohortSelectionReason.NO_PENDING_ENTRIES,
facts,
census_digest=census,
ecosystem_policy_digest=eco_policy,
ground_truth_policy_digest=gt_policy,
)
def select_fourth_cohort_batch(
*,
state: SourcingQueueStateV1,
accepted_batches: Sequence[CohortBatchOutcomeV1],
expected_ecosystem_policy_digest: str,
expected_ground_truth_policy_digest: str,
) -> CohortSelectionV1:
"""Select the gap-closing fourth cohort batch from one shared reservation snapshot.
The fourth round must close any remaining ecosystem or family gap: it
targets the gap when a feasible pending batch exists and refuses with a
closed reason when no pending batch can close it, never substituting a
batch that would leave the gap open.
"""
facts = _ledger_facts(accepted_batches)
try:
census = _closed_digest(state.census_digest)
eco_policy = _closed_digest(expected_ecosystem_policy_digest)
gt_policy = _closed_digest(expected_ground_truth_policy_digest)
except (AttributeError, TypeError, ValueError) as error:
raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error
if _census_refused(facts, census):
return _refused(
CohortSelectionReason.CENSUS_MISMATCH,
facts,
census_digest=census,
ecosystem_policy_digest=eco_policy,
ground_truth_policy_digest=gt_policy,
)
if _policy_refused(facts, (eco_policy, gt_policy)):
return _refused(
CohortSelectionReason.POLICY_MISMATCH,
facts,
census_digest=census,
ecosystem_policy_digest=eco_policy,
ground_truth_policy_digest=gt_policy,
)
return _fourth_decision(state, accepted_batches, facts, census=census, eco_policy=eco_policy, gt_policy=gt_policy)
def _require_selection_binding(
selection: CohortSelectionV1,
state: SourcingQueueStateV1,
@@ -535,7 +776,7 @@ def _selection_state(
raise CohortSelectionStateError(CohortSelectionStateReason.STATE_MISMATCH) from error
def ingest_third_cohort_batch(
def _ingest_selected_cohort_batch(
records: Sequence[bytes],
*,
selection: CohortSelectionV1,
@@ -544,7 +785,7 @@ def ingest_third_cohort_batch(
expected_ecosystem_policy_digest: str,
expected_ground_truth_policy_digest: str,
) -> CohortBatchOutcomeV1:
"""Ingest the selected bounded third cohort through the committed machinery."""
"""Ingest one selected bounded cohort batch through the committed machinery."""
narrowed = _selection_state(
selection,
state,
@@ -561,6 +802,50 @@ def ingest_third_cohort_batch(
)
def ingest_third_cohort_batch(
records: Sequence[bytes],
*,
selection: CohortSelectionV1,
state: SourcingQueueStateV1,
candidates_by_digest: Mapping[str, FixSiteCandidateV1],
expected_ecosystem_policy_digest: str,
expected_ground_truth_policy_digest: str,
) -> CohortBatchOutcomeV1:
"""Ingest the selected bounded third cohort through the committed machinery."""
return _ingest_selected_cohort_batch(
records,
selection=selection,
state=state,
candidates_by_digest=candidates_by_digest,
expected_ecosystem_policy_digest=expected_ecosystem_policy_digest,
expected_ground_truth_policy_digest=expected_ground_truth_policy_digest,
)
def ingest_fourth_cohort_batch(
records: Sequence[bytes],
*,
selection: CohortSelectionV1,
state: SourcingQueueStateV1,
candidates_by_digest: Mapping[str, FixSiteCandidateV1],
expected_ecosystem_policy_digest: str,
expected_ground_truth_policy_digest: str,
) -> CohortBatchOutcomeV1:
"""Ingest the selected bounded fourth cohort under the unchanged review policy.
Scope verification never moves: acceptance still flows only through the
committed review authorities over the narrowed selected queue.
"""
return _ingest_selected_cohort_batch(
records,
selection=selection,
state=state,
candidates_by_digest=candidates_by_digest,
expected_ecosystem_policy_digest=expected_ecosystem_policy_digest,
expected_ground_truth_policy_digest=expected_ground_truth_policy_digest,
)
__all__ = [
"COHORT_SELECTION_ECOSYSTEMS",
"COHORT_SELECTION_SCHEMA",
@@ -573,6 +858,8 @@ __all__ = [
"cohort_selection",
"cohort_selection_bytes",
"cohort_selection_value",
"ingest_fourth_cohort_batch",
"ingest_third_cohort_batch",
"select_fourth_cohort_batch",
"select_third_cohort_batch",
]
+329
View File
@@ -0,0 +1,329 @@
"""Combined closure of the replacement positive set over durable cohort ledgers.
The closure projection reads only accepted review evidence already recorded on
cohort batch outcomes: families, ecosystems, and positive counts are facts of
recorded human reviews. Every accepted positive is reachable by construction
because acceptance exists only through the committed review machinery, which
requires the in-repository reachability judgment; no scope is granted here and
an unverified family or ecosystem stays impossible without a new external
review record.
"""
from __future__ import annotations
import re
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass, replace
from enum import StrEnum
from benchmarks.valid.cohort_ingestion import (
CohortBatchOutcomeV1,
CohortBatchStatus,
CohortStateError,
cohort_batch_bytes,
)
from benchmarks.valid.cohort_selection import COHORT_SELECTION_ECOSYSTEMS, REQUIRED_DISTINCT_FAMILIES
from benchmarks.valid.ground_truth_review import AcceptedGroundTruthV1
from openultrasast.core.canonical import JsonValue, canonical_bytes, content_digest
POSITIVE_SET_CLOSURE_SCHEMA = "openultrasast.valid-detection-benchmark.positive-set-closure.v1"
COMBINED_POSITIVE_FLOOR = 40
_DIGEST = re.compile(r"[0-9a-f]{64}")
_FAMILY = re.compile(r"[a-z0-9][a-z0-9_]{0,127}")
class PositiveSetClosureStatus(StrEnum):
CLOSED = "closed"
INSUFFICIENT = "insufficient"
class PositiveSetClosureReason(StrEnum):
"""Closed decision vocabulary naming which closure gate closed or failed."""
ALL_GAPS_CLOSED = "all_gaps_closed"
NO_ACCEPTED_BATCHES = "no_accepted_batches"
INSUFFICIENT_TOTAL_POSITIVES = "insufficient_total_positives"
MISSING_ECOSYSTEM = "missing_ecosystem"
INSUFFICIENT_FAMILIES = "insufficient_families"
_INSUFFICIENCY_REASONS = frozenset(
{
PositiveSetClosureReason.NO_ACCEPTED_BATCHES,
PositiveSetClosureReason.INSUFFICIENT_TOTAL_POSITIVES,
PositiveSetClosureReason.MISSING_ECOSYSTEM,
PositiveSetClosureReason.INSUFFICIENT_FAMILIES,
}
)
class PositiveSetClosureStateReason(StrEnum):
STATE_UNREADABLE = "state_unreadable"
STATE_MISMATCH = "state_mismatch"
_STATE_REASON_TEXT = {
PositiveSetClosureStateReason.STATE_UNREADABLE: "positive set closure bytes are unreadable",
PositiveSetClosureStateReason.STATE_MISMATCH: "positive set closure state does not match its canonical schema",
}
class PositiveSetClosureStateError(ValueError):
"""Closed closure refusal carrying one structural reason."""
def __init__(self, reason: PositiveSetClosureStateReason) -> None:
self.reason = reason
super().__init__(_STATE_REASON_TEXT[reason])
def _mismatch() -> PositiveSetClosureStateError:
return PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH)
@dataclass(frozen=True)
class PositiveSetClosureV1:
batch_digests: tuple[str, ...]
accepted_batch_digests: tuple[str, ...]
total_accepted_positives: int
positives_by_ecosystem: tuple[tuple[str, int], ...]
accepted_families: tuple[str, ...]
status: PositiveSetClosureStatus
reason: PositiveSetClosureReason
closure_digest: str
def __post_init__(self) -> None:
_validate_closure(self)
@dataclass(frozen=True)
class _ClosureFacts:
batch_digests: tuple[str, ...]
accepted_batch_digests: tuple[str, ...]
families: tuple[str, ...]
counts: tuple[tuple[str, int], ...]
total: int
def _closed_digest(value: object) -> str:
if not isinstance(value, str) or _DIGEST.fullmatch(value) is None:
raise _mismatch()
return value
def _closed_vocabulary(values: object, pattern: re.Pattern[str]) -> tuple[str, ...]:
if not isinstance(values, tuple) or not all(isinstance(item, str) for item in values):
raise _mismatch()
ordered = tuple(sorted(set(values)))
if ordered != values or any(pattern.fullmatch(item) is None for item in ordered):
raise _mismatch()
return values
def _closed_counts(pairs: object) -> tuple[tuple[str, int], ...]:
if not isinstance(pairs, tuple) or tuple(ecosystem for ecosystem, _ in pairs) != COHORT_SELECTION_ECOSYSTEMS:
raise _mismatch()
for _, count in pairs:
if type(count) is not int or count < 0:
raise _mismatch()
return pairs
def _gates(item: PositiveSetClosureV1) -> tuple[bool, bool, bool]:
total_ok = item.total_accepted_positives >= COMBINED_POSITIVE_FLOOR
ecosystems_ok = all(count > 0 for _, count in item.positives_by_ecosystem)
families_ok = len(item.accepted_families) >= REQUIRED_DISTINCT_FAMILIES
return total_ok, ecosystems_ok, families_ok
def _validate_closure(item: PositiveSetClosureV1) -> None:
if not isinstance(item.status, PositiveSetClosureStatus) or not isinstance(item.reason, PositiveSetClosureReason):
raise _mismatch()
if item.closure_digest:
_closed_digest(item.closure_digest)
_closed_vocabulary(item.batch_digests, _DIGEST)
_closed_vocabulary(item.accepted_batch_digests, _DIGEST)
if not set(item.accepted_batch_digests) <= set(item.batch_digests):
raise _mismatch()
_closed_vocabulary(item.accepted_families, _FAMILY)
_closed_counts(item.positives_by_ecosystem)
if item.total_accepted_positives < 0 or item.total_accepted_positives != sum(
count for _, count in item.positives_by_ecosystem
):
raise _mismatch()
if bool(item.accepted_batch_digests) != (item.total_accepted_positives > 0):
raise _mismatch()
total_ok, ecosystems_ok, families_ok = _gates(item)
if item.status is PositiveSetClosureStatus.CLOSED:
if item.reason is not PositiveSetClosureReason.ALL_GAPS_CLOSED or not (total_ok and ecosystems_ok and families_ok):
raise _mismatch()
else:
if item.reason not in _INSUFFICIENCY_REASONS or (total_ok and ecosystems_ok and families_ok):
raise _mismatch()
if item.reason is PositiveSetClosureReason.NO_ACCEPTED_BATCHES and item.total_accepted_positives != 0:
raise _mismatch()
def _count_value(pairs: tuple[tuple[str, int], ...]) -> tuple[dict[str, JsonValue], ...]:
return tuple({"ecosystem": ecosystem, "accepted_positives": count} for ecosystem, count in pairs)
def _closure_value(item: PositiveSetClosureV1, *, include_digest: bool) -> dict[str, JsonValue]:
value: dict[str, JsonValue] = {
"schema_version": POSITIVE_SET_CLOSURE_SCHEMA,
"batch_digests": item.batch_digests,
"accepted_batch_digests": item.accepted_batch_digests,
"total_accepted_positives": item.total_accepted_positives,
"positives_by_ecosystem": _count_value(item.positives_by_ecosystem),
"accepted_families": item.accepted_families,
"status": item.status.value,
"reason": item.reason.value,
}
if include_digest:
value["closure_digest"] = item.closure_digest
return value
def positive_set_closure_value(item: PositiveSetClosureV1) -> dict[str, JsonValue]:
"""Canonical closure payload used for durable persistence and exact rereads."""
return _closure_value(item, include_digest=True)
def positive_set_closure_bytes(item: PositiveSetClosureV1) -> bytes:
"""Encode a digest-consistent closure decision as canonical bytes."""
if item.closure_digest != content_digest(_closure_value(item, include_digest=False)):
raise _mismatch()
return canonical_bytes(positive_set_closure_value(item))
def positive_set_closure(
*,
batch_digests: Iterable[str],
accepted_batch_digests: Iterable[str],
total_accepted_positives: int,
positives_by_ecosystem: Mapping[str, int],
accepted_families: Iterable[str],
status: PositiveSetClosureStatus,
reason: PositiveSetClosureReason,
) -> PositiveSetClosureV1:
"""Assemble one durable closure decision bound to its exact ledger facts."""
try:
counts = tuple((ecosystem, positives_by_ecosystem[ecosystem]) for ecosystem in COHORT_SELECTION_ECOSYSTEMS)
draft = PositiveSetClosureV1(
tuple(sorted(set(batch_digests))),
tuple(sorted(set(accepted_batch_digests))),
total_accepted_positives,
counts,
tuple(sorted(set(accepted_families))),
status,
reason,
"",
)
except PositiveSetClosureStateError:
raise
except (AttributeError, KeyError, TypeError, ValueError) as error:
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH) from error
return replace(draft, closure_digest=content_digest(_closure_value(draft, include_digest=False)))
def _require_replayable(batch: CohortBatchOutcomeV1) -> None:
"""Prove one ledger batch re-encodes to its recorded digest before use."""
try:
cohort_batch_bytes(batch)
for positive in batch.accepted_positives:
if not positive.verified_scopes:
raise _mismatch()
for scope in positive.verified_scopes:
if scope.ecosystem.value != batch.ecosystem:
raise _mismatch()
except PositiveSetClosureStateError:
raise
except (CohortStateError, AttributeError, KeyError, TypeError, ValueError) as error:
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH) from error
def _closure_facts(batches: Sequence[CohortBatchOutcomeV1]) -> _ClosureFacts:
"""Derive combined facts from replay-verified accepted cohort evidence."""
digests: set[str] = set()
accepted_digests: set[str] = set()
families: set[str] = set()
counts = {ecosystem: 0 for ecosystem in COHORT_SELECTION_ECOSYSTEMS}
by_change: dict[str, AcceptedGroundTruthV1] = {}
for batch in batches:
_require_replayable(batch)
digests.add(_closed_digest(batch.batch_digest))
if batch.status is not CohortBatchStatus.ACCEPTED:
continue
accepted_digests.add(batch.batch_digest)
for positive in batch.accepted_positives:
existing = by_change.get(positive.change_identity_digest)
if existing is not None and existing != positive:
raise _mismatch()
if existing is None:
by_change[positive.change_identity_digest] = positive
counts[batch.ecosystem] += 1
for scope in positive.verified_scopes:
families.add(scope.vulnerability_family)
return _ClosureFacts(
tuple(sorted(digests)),
tuple(sorted(accepted_digests)),
tuple(sorted(families)),
tuple((ecosystem, counts[ecosystem]) for ecosystem in COHORT_SELECTION_ECOSYSTEMS),
len(by_change),
)
def _closure_reason(facts: _ClosureFacts) -> PositiveSetClosureReason:
if not facts.accepted_batch_digests:
return PositiveSetClosureReason.NO_ACCEPTED_BATCHES
if facts.total < COMBINED_POSITIVE_FLOOR:
return PositiveSetClosureReason.INSUFFICIENT_TOTAL_POSITIVES
if any(count == 0 for _, count in facts.counts):
return PositiveSetClosureReason.MISSING_ECOSYSTEM
if len(facts.families) < REQUIRED_DISTINCT_FAMILIES:
return PositiveSetClosureReason.INSUFFICIENT_FAMILIES
return PositiveSetClosureReason.ALL_GAPS_CLOSED
def project_positive_set_closure(batches: Sequence[CohortBatchOutcomeV1]) -> PositiveSetClosureV1:
"""Close the combined positive set over durable accepted cohort ledgers.
Only accepted ingestion units contribute positives: an insufficient batch
is a refused unit whose partial records never lower the closure bar. A
gap-remaining set stays insufficient with a closed reason instead of being
reported closed.
"""
try:
facts = _closure_facts(batches)
except PositiveSetClosureStateError:
raise
except (AttributeError, TypeError, ValueError) as error:
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH) from error
reason = _closure_reason(facts)
if reason is PositiveSetClosureReason.ALL_GAPS_CLOSED:
status = PositiveSetClosureStatus.CLOSED
else:
status = PositiveSetClosureStatus.INSUFFICIENT
return positive_set_closure(
batch_digests=facts.batch_digests,
accepted_batch_digests=facts.accepted_batch_digests,
total_accepted_positives=facts.total,
positives_by_ecosystem=dict(facts.counts),
accepted_families=facts.families,
status=status,
reason=reason,
)
__all__ = [
"COMBINED_POSITIVE_FLOOR",
"POSITIVE_SET_CLOSURE_SCHEMA",
"PositiveSetClosureReason",
"PositiveSetClosureStateError",
"PositiveSetClosureStateReason",
"PositiveSetClosureStatus",
"PositiveSetClosureV1",
"positive_set_closure",
"positive_set_closure_bytes",
"positive_set_closure_value",
"project_positive_set_closure",
]
@@ -0,0 +1,137 @@
"""Durable persistence, hostile decode, and replay for positive-set closure decisions."""
from __future__ import annotations
import json
import math
from typing import Any
from benchmarks.valid.artifact_repository import ArtifactReadAuthority, S3ArtifactRepository
from benchmarks.valid.positive_set_closure import (
POSITIVE_SET_CLOSURE_SCHEMA,
PositiveSetClosureReason,
PositiveSetClosureStateError,
PositiveSetClosureStateReason,
PositiveSetClosureStatus,
PositiveSetClosureV1,
positive_set_closure,
positive_set_closure_bytes,
positive_set_closure_value,
)
from benchmarks.valid.replacement_artifact_contract import (
ArtifactAccessClass,
ArtifactKind,
ArtifactReference,
artifact_reference,
canonical_artifact_bytes,
)
from openultrasast.core.canonical import canonical_bytes
_CLOSURE_KEYS = frozenset(
{
"schema_version",
"batch_digests",
"accepted_batch_digests",
"total_accepted_positives",
"positives_by_ecosystem",
"accepted_families",
"status",
"reason",
"closure_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 PositiveSetClosureStateError(PositiveSetClosureStateReason.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 PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_UNREADABLE) from None
if not isinstance(value, dict) or canonical != content:
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_UNREADABLE)
return value
def decode_positive_set_closure(content: bytes) -> PositiveSetClosureV1:
"""Rebuild one closure decision only from canonical, digest-consistent bytes."""
value = _decoded_value(content)
if set(value) != _CLOSURE_KEYS or value["schema_version"] != POSITIVE_SET_CLOSURE_SCHEMA:
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH)
try:
closure = positive_set_closure(
batch_digests=tuple(value["batch_digests"]),
accepted_batch_digests=tuple(value["accepted_batch_digests"]),
total_accepted_positives=value["total_accepted_positives"],
positives_by_ecosystem={item["ecosystem"]: item["accepted_positives"] for item in value["positives_by_ecosystem"]},
accepted_families=tuple(value["accepted_families"]),
status=PositiveSetClosureStatus(value["status"]),
reason=PositiveSetClosureReason(value["reason"]),
)
except (AttributeError, KeyError, TypeError, ValueError) as error:
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH) from error
if positive_set_closure_bytes(closure) != content:
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_MISMATCH)
return closure
def persist_positive_set_closure(store: S3ArtifactRepository, closure: PositiveSetClosureV1) -> ArtifactReference:
"""Persist one durable closure decision bound to the ledger facts it examined."""
content = canonical_artifact_bytes(
ArtifactKind.POPULATION,
positive_set_closure_value(closure),
access_class=ArtifactAccessClass.OPERATOR_SAFE,
provenance_digest=closure.closure_digest,
)
return store.put_if_absent(content, reference=artifact_reference(content))
def resume_positive_set_closure(
store: S3ArtifactRepository,
reference: ArtifactReference,
*,
authority: ArtifactReadAuthority,
expected_access_policy_digest: str,
) -> PositiveSetClosureV1:
"""Resume one closure decision from the durable store after restart."""
accepted = store.get(
reference,
expected_kind=ArtifactKind.POPULATION,
authority=authority,
expected_access_policy_digest=expected_access_policy_digest,
)
try:
content = canonical_bytes(_converted(accepted.artifact.payload))
except (TypeError, ValueError, RecursionError):
raise PositiveSetClosureStateError(PositiveSetClosureStateReason.STATE_UNREADABLE) from None
return decode_positive_set_closure(content)
__all__ = [
"decode_positive_set_closure",
"persist_positive_set_closure",
"resume_positive_set_closure",
]