mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-03 02:08:18 +00:00
feat(valid-detection-benchmark): classify and freeze canonical population
This commit is contained in:
@@ -105,7 +105,7 @@
|
||||
- Done when the same source and policy reproduce the draw, cross-ecosystem substitution fails, and every accepted positive contributes the required eligible ordinary-change count.
|
||||
- _Requirements: 3.1, 3.2, 3.4, 3.5, 3.6_
|
||||
- _Boundary: Population Freezer_
|
||||
- [ ] 4.2 Classify and freeze the canonical population
|
||||
- [x] 4.2 Classify and freeze the canonical population
|
||||
- Consume only accepted ecosystem and ground-truth reviews plus the authoritative reservation census.
|
||||
- Bind selections, ordinary draws, exclusions, review sets, provenance, policies, scope census, and new population/freeze identities into a deterministic freeze.
|
||||
- Classify fewer than forty accepted positives, a missing ecosystem, missing second family, or infeasible claimed scope as development pilot or insufficient rather than admission.
|
||||
@@ -422,3 +422,4 @@
|
||||
- Task 3.2 revalidates externally governed ecosystem reviews against exact candidate/evidence/policy identities, derives closed accepted/insufficient outcomes, and enforces a repository↔network bijection before projecting canonical Python or JavaScript ecosystems.
|
||||
- Task 3.3 revalidates exact candidate and ecosystem authorities, derives accepted/excluded ground truth from explicit independent human judgments, keeps model assistance non-authoritative, and projects each change once while preserving all verified exact scopes.
|
||||
- Task 4.1 deterministically draws at least twenty same-network first-parent ordinary pushes per accepted positive, globally excludes every accepted fix revision, stores shared pushes once, and routes reviewed contamination to exclusion or terminal retirement according to freeze timing.
|
||||
- Task 4.2 classifies and freezes only exact reviewed authorities against the Reservation Authority's current census snapshot; admission requires at least forty positives across Python and JavaScript and two families, while stale censuses, split networks, and insufficient scope remain non-authorizing.
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
"""Replacement population classification from exact reviewed authorities."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import replace
|
||||
|
||||
from benchmarks.valid.ecosystem_review import CanonicalEcosystem
|
||||
from benchmarks.valid.ground_truth_review import AcceptedGroundTruthV1, project_accepted_ground_truth
|
||||
from benchmarks.valid.ordinary_change_contract import OrdinarySelectionV1, ReviewedPositiveInput, ordinary_selection_bytes
|
||||
from benchmarks.valid.population_freeze_contract import (
|
||||
MINIMUM_ADMISSION_POSITIVES,
|
||||
PopulationClass,
|
||||
PopulationClassificationReason,
|
||||
PopulationFreezeConflict,
|
||||
PopulationFreezeError,
|
||||
PopulationFreezeV3,
|
||||
PopulationScopeCountV1,
|
||||
ScopeMinimumV1,
|
||||
_freeze_value,
|
||||
_population_value,
|
||||
accept_population_freeze,
|
||||
population_freeze_bytes,
|
||||
)
|
||||
from benchmarks.valid.reservation import ReservationAuthority, ReservationCensusV1, ReservationError, census_bytes
|
||||
from openultrasast.core.canonical import content_digest
|
||||
|
||||
|
||||
def _canonical_minimums(values: Iterable[ScopeMinimumV1]) -> tuple[ScopeMinimumV1, ...]:
|
||||
try:
|
||||
return tuple(sorted(set(ScopeMinimumV1(item.vulnerability_family, item.ecosystem, item.minimum_count) for item in values)))
|
||||
except (AttributeError, TypeError) as error:
|
||||
raise PopulationFreezeError("population scope minimums are malformed") from error
|
||||
|
||||
|
||||
def _canonical_exclusions(values: Iterable[tuple[str, int]]) -> tuple[tuple[str, int], ...]:
|
||||
supplied = tuple(values)
|
||||
result = tuple(sorted(set(supplied)))
|
||||
if len(result) != len(supplied):
|
||||
raise PopulationFreezeError("population exclusion counts are duplicated")
|
||||
return result
|
||||
|
||||
|
||||
def _validated_inputs(
|
||||
positives: Iterable[ReviewedPositiveInput],
|
||||
ecosystem_policy: str,
|
||||
ground_truth_policy: str,
|
||||
) -> tuple[tuple[ReviewedPositiveInput, ...], tuple[AcceptedGroundTruthV1, ...]]:
|
||||
items = tuple(positives)
|
||||
candidates = {item.candidate.candidate_digest: item.candidate for item in items}
|
||||
ecosystems = {item.ecosystem_review.review_digest: item.ecosystem_review for item in items}
|
||||
reviews = tuple(item.ground_truth_review for item in items)
|
||||
if len(candidates) != len(items) or len(ecosystems) != len(items) or len({item.review_digest for item in reviews}) != len(items):
|
||||
raise PopulationFreezeError("population reviewed positive identities are duplicated")
|
||||
try:
|
||||
accepted = project_accepted_ground_truth(
|
||||
reviews,
|
||||
candidates_by_digest=candidates,
|
||||
ecosystem_reviews_by_digest=ecosystems,
|
||||
expected_ecosystem_policy_digest=ecosystem_policy,
|
||||
expected_ground_truth_policy_digest=ground_truth_policy,
|
||||
)
|
||||
except ValueError as error:
|
||||
raise PopulationFreezeError("population positive review authority is invalid") from error
|
||||
if len(accepted) != len(items):
|
||||
raise PopulationFreezeError("population contains excluded or conflicting positive reviews")
|
||||
by_change = {item.ground_truth_review.change_identity_digest: item for item in items}
|
||||
if len(by_change) != len(items) or set(by_change) != {item.change_identity_digest for item in accepted}:
|
||||
raise PopulationFreezeError("population accepted change identities do not match exact reviews")
|
||||
return tuple(by_change[key] for key in sorted(by_change)), accepted
|
||||
|
||||
|
||||
def _validate_reservation(
|
||||
items: tuple[ReviewedPositiveInput, ...],
|
||||
census: ReservationCensusV1,
|
||||
authority: ReservationAuthority,
|
||||
) -> None:
|
||||
try:
|
||||
census_bytes(census)
|
||||
except ReservationError as error:
|
||||
raise PopulationFreezeError("reservation census is invalid") from error
|
||||
reserved = set(census.reserved_network_digests)
|
||||
for item in items:
|
||||
try:
|
||||
resolved = authority.resolve_repository(item.candidate.canonical_repository)
|
||||
except ReservationError as error:
|
||||
raise PopulationFreezeError("population repository is absent from reviewed identity authority") from error
|
||||
if (resolved.canonical_repository, resolved.network_identity_digest) != (
|
||||
item.candidate.canonical_repository,
|
||||
item.candidate.network_identity_digest,
|
||||
):
|
||||
raise PopulationFreezeError("population candidate conflicts with resolved repository identity")
|
||||
if resolved.network_identity_digest in reserved:
|
||||
raise PopulationFreezeError("population positive repository is permanently reserved")
|
||||
|
||||
|
||||
def _require_current_reservation(census: ReservationCensusV1, authority: ReservationAuthority) -> None:
|
||||
try:
|
||||
authority.require_current_census(census)
|
||||
except ReservationError as error:
|
||||
raise PopulationFreezeError("reservation census is not the current authoritative snapshot") from error
|
||||
|
||||
|
||||
def _validate_ordinary(selection: OrdinarySelectionV1, items: tuple[ReviewedPositiveInput, ...]) -> None:
|
||||
try:
|
||||
ordinary_selection_bytes(selection)
|
||||
except ValueError as error:
|
||||
raise PopulationFreezeError("ordinary selection is invalid") from error
|
||||
changes = tuple(item.ground_truth_review.change_identity_digest for item in items)
|
||||
if selection.positive_change_digests != changes:
|
||||
raise PopulationFreezeError("ordinary selection does not bind the exact positive set")
|
||||
fixes = {
|
||||
(item.network_identity_digest, item.fixed_revision, item.positive_change_digest, item.ground_truth_review_digest)
|
||||
for item in selection.fix_exclusions
|
||||
}
|
||||
expected = {
|
||||
(
|
||||
item.candidate.network_identity_digest,
|
||||
item.candidate.fixed.revision,
|
||||
item.ground_truth_review.change_identity_digest,
|
||||
item.ground_truth_review.review_digest,
|
||||
)
|
||||
for item in items
|
||||
}
|
||||
if fixes != expected:
|
||||
raise PopulationFreezeError("ordinary accepted-fix authority does not match reviewed positives")
|
||||
authorities = {
|
||||
item.ground_truth_review.change_identity_digest: (
|
||||
item.candidate.network_identity_digest,
|
||||
item.ecosystem_review.ecosystem,
|
||||
)
|
||||
for item in items
|
||||
}
|
||||
for assignment in selection.assignments:
|
||||
if authorities.get(assignment.positive_change_digest) != (
|
||||
assignment.network_identity_digest,
|
||||
assignment.ecosystem,
|
||||
):
|
||||
raise PopulationFreezeError("ordinary assignment crosses reviewed repository or ecosystem authority")
|
||||
|
||||
|
||||
def _scope_census(accepted: tuple[AcceptedGroundTruthV1, ...]) -> tuple[PopulationScopeCountV1, ...]:
|
||||
counts: Counter[tuple[str, CanonicalEcosystem]] = Counter()
|
||||
for item in accepted:
|
||||
counts.update((scope.vulnerability_family, scope.ecosystem) for scope in item.verified_scopes)
|
||||
return tuple(PopulationScopeCountV1(family, ecosystem, count) for (family, ecosystem), count in sorted(counts.items()))
|
||||
|
||||
|
||||
def _classification(
|
||||
positive_count: int,
|
||||
ecosystems: tuple[CanonicalEcosystem, ...],
|
||||
families: tuple[str, ...],
|
||||
census: tuple[PopulationScopeCountV1, ...],
|
||||
minimums: tuple[ScopeMinimumV1, ...],
|
||||
) -> tuple[PopulationClass, tuple[PopulationClassificationReason, ...]]:
|
||||
reasons: set[PopulationClassificationReason] = set()
|
||||
if positive_count < MINIMUM_ADMISSION_POSITIVES:
|
||||
reasons.add(PopulationClassificationReason.BELOW_MINIMUM_POSITIVES)
|
||||
if set(ecosystems) != {CanonicalEcosystem.PYTHON, CanonicalEcosystem.JAVASCRIPT}:
|
||||
reasons.add(PopulationClassificationReason.MISSING_ECOSYSTEM)
|
||||
if len(families) < 2:
|
||||
reasons.add(PopulationClassificationReason.MISSING_SECOND_FAMILY)
|
||||
counts = {(item.vulnerability_family, item.ecosystem): item.count for item in census}
|
||||
if any(counts.get((item.vulnerability_family, item.ecosystem), 0) < item.minimum_count for item in minimums):
|
||||
reasons.add(PopulationClassificationReason.SCOPE_MINIMUM_UNMET)
|
||||
ordered = tuple(sorted(reasons, key=lambda item: item.value))
|
||||
if not ordered:
|
||||
return PopulationClass.ADMISSION, ()
|
||||
if ordered == (PopulationClassificationReason.BELOW_MINIMUM_POSITIVES,):
|
||||
return PopulationClass.DEVELOPMENT_PILOT, ordered
|
||||
return PopulationClass.INSUFFICIENT, ordered
|
||||
|
||||
|
||||
def _draft_freeze(
|
||||
items: tuple[ReviewedPositiveInput, ...],
|
||||
accepted: tuple[AcceptedGroundTruthV1, ...],
|
||||
ordinary: OrdinarySelectionV1,
|
||||
census: ReservationCensusV1,
|
||||
minimums: tuple[ScopeMinimumV1, ...],
|
||||
exclusions: tuple[tuple[str, int], ...],
|
||||
source_provenance: str,
|
||||
ecosystem_policy: str,
|
||||
ground_truth_policy: str,
|
||||
freeze_policy: str,
|
||||
) -> PopulationFreezeV3:
|
||||
scopes = _scope_census(accepted)
|
||||
ecosystems = tuple(sorted({scope.ecosystem for item in accepted for scope in item.verified_scopes}, key=lambda item: item.value))
|
||||
families = tuple(sorted({scope.vulnerability_family for item in accepted for scope in item.verified_scopes}))
|
||||
population_class, reasons = _classification(len(accepted), ecosystems, families, scopes, minimums)
|
||||
changes = tuple(item.change_identity_digest for item in accepted)
|
||||
ecosystem_reviews = tuple(sorted(item.ecosystem_review.review_digest for item in items))
|
||||
ground_truth_reviews = tuple(sorted(item.ground_truth_review.review_digest for item in items))
|
||||
return PopulationFreezeV3(
|
||||
population_class,
|
||||
reasons,
|
||||
len(accepted),
|
||||
ecosystems,
|
||||
families,
|
||||
scopes,
|
||||
minimums,
|
||||
changes,
|
||||
content_digest(
|
||||
{"accepted_changes": changes, "scope_census": tuple((x.vulnerability_family, x.ecosystem.value, x.count) for x in scopes)}
|
||||
),
|
||||
ecosystem_reviews,
|
||||
ground_truth_reviews,
|
||||
content_digest({"ecosystem_reviews": ecosystem_reviews, "ground_truth_reviews": ground_truth_reviews}),
|
||||
ordinary.selection_digest,
|
||||
census.census_digest,
|
||||
exclusions,
|
||||
source_provenance,
|
||||
ecosystem_policy,
|
||||
ground_truth_policy,
|
||||
freeze_policy,
|
||||
"",
|
||||
"",
|
||||
)
|
||||
|
||||
|
||||
def freeze_population(
|
||||
positives: Iterable[ReviewedPositiveInput],
|
||||
*,
|
||||
ordinary_selection: OrdinarySelectionV1,
|
||||
reservation_census: ReservationCensusV1,
|
||||
reservation_authority: ReservationAuthority,
|
||||
scope_minimums: Iterable[ScopeMinimumV1] = (),
|
||||
exclusion_counts: Iterable[tuple[str, int]] = (),
|
||||
source_provenance_digest: str,
|
||||
freeze_policy_digest: str,
|
||||
expected_ecosystem_policy_digest: str,
|
||||
expected_ground_truth_policy_digest: str,
|
||||
forbidden_historical_identities: Iterable[str] = (),
|
||||
) -> PopulationFreezeV3:
|
||||
"""Build one deterministic new replacement freeze from exact authorities."""
|
||||
_require_current_reservation(reservation_census, reservation_authority)
|
||||
items, accepted = _validated_inputs(positives, expected_ecosystem_policy_digest, expected_ground_truth_policy_digest)
|
||||
_validate_reservation(items, reservation_census, reservation_authority)
|
||||
_validate_ordinary(ordinary_selection, items)
|
||||
draft = _draft_freeze(
|
||||
items,
|
||||
accepted,
|
||||
ordinary_selection,
|
||||
reservation_census,
|
||||
_canonical_minimums(scope_minimums),
|
||||
_canonical_exclusions(exclusion_counts),
|
||||
source_provenance_digest,
|
||||
expected_ecosystem_policy_digest,
|
||||
expected_ground_truth_policy_digest,
|
||||
freeze_policy_digest,
|
||||
)
|
||||
with_population = replace(draft, population_digest=content_digest(_population_value(draft)))
|
||||
freeze = replace(with_population, freeze_digest=content_digest(_freeze_value(with_population, include_digest=False)))
|
||||
forbidden = set(forbidden_historical_identities)
|
||||
if freeze.population_digest in forbidden or freeze.freeze_digest in forbidden:
|
||||
raise PopulationFreezeError("replacement population reuses a historical identity")
|
||||
population_freeze_bytes(freeze)
|
||||
_require_current_reservation(reservation_census, reservation_authority)
|
||||
return freeze
|
||||
|
||||
|
||||
def validate_population_freeze(
|
||||
freeze: PopulationFreezeV3,
|
||||
positives: Iterable[ReviewedPositiveInput],
|
||||
*,
|
||||
ordinary_selection: OrdinarySelectionV1,
|
||||
reservation_census: ReservationCensusV1,
|
||||
reservation_authority: ReservationAuthority,
|
||||
scope_minimums: Iterable[ScopeMinimumV1] = (),
|
||||
exclusion_counts: Iterable[tuple[str, int]] = (),
|
||||
source_provenance_digest: str,
|
||||
freeze_policy_digest: str,
|
||||
expected_ecosystem_policy_digest: str,
|
||||
expected_ground_truth_policy_digest: str,
|
||||
forbidden_historical_identities: Iterable[str] = (),
|
||||
) -> bytes:
|
||||
_require_current_reservation(reservation_census, reservation_authority)
|
||||
expected = freeze_population(
|
||||
positives,
|
||||
ordinary_selection=ordinary_selection,
|
||||
reservation_census=reservation_census,
|
||||
reservation_authority=reservation_authority,
|
||||
scope_minimums=scope_minimums,
|
||||
exclusion_counts=exclusion_counts,
|
||||
source_provenance_digest=source_provenance_digest,
|
||||
freeze_policy_digest=freeze_policy_digest,
|
||||
expected_ecosystem_policy_digest=expected_ecosystem_policy_digest,
|
||||
expected_ground_truth_policy_digest=expected_ground_truth_policy_digest,
|
||||
forbidden_historical_identities=forbidden_historical_identities,
|
||||
)
|
||||
if expected != freeze:
|
||||
raise PopulationFreezeError("population freeze does not reproduce from exact authorities")
|
||||
content = population_freeze_bytes(freeze)
|
||||
_require_current_reservation(reservation_census, reservation_authority)
|
||||
return content
|
||||
|
||||
|
||||
__all__ = [
|
||||
"PopulationClass",
|
||||
"PopulationClassificationReason",
|
||||
"PopulationFreezeConflict",
|
||||
"PopulationFreezeError",
|
||||
"PopulationFreezeV3",
|
||||
"PopulationScopeCountV1",
|
||||
"ScopeMinimumV1",
|
||||
"accept_population_freeze",
|
||||
"freeze_population",
|
||||
"population_freeze_bytes",
|
||||
"validate_population_freeze",
|
||||
]
|
||||
@@ -0,0 +1,303 @@
|
||||
"""Canonical contracts for replacement population classification and freeze."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
|
||||
from benchmarks.valid.ecosystem_review import CanonicalEcosystem
|
||||
from openultrasast.core.canonical import JsonValue, canonical_bytes, content_digest
|
||||
|
||||
POPULATION_FREEZE_SCHEMA = "openultrasast.valid-detection-benchmark.population-freeze.v3"
|
||||
POPULATION_IDENTITY_SCHEMA = "openultrasast.valid-detection-benchmark.population-identity.v3"
|
||||
MINIMUM_ADMISSION_POSITIVES = 40
|
||||
_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||
_FAMILY = re.compile(r"[a-z0-9][a-z0-9_]{0,127}")
|
||||
|
||||
|
||||
class PopulationFreezeError(ValueError):
|
||||
"""Population inputs or freeze identity are invalid."""
|
||||
|
||||
|
||||
class PopulationFreezeConflict(PopulationFreezeError):
|
||||
"""One freeze identity was presented with different canonical bytes."""
|
||||
|
||||
|
||||
class PopulationClass(StrEnum):
|
||||
DEVELOPMENT_PILOT = "development_pilot"
|
||||
INSUFFICIENT = "insufficient"
|
||||
ADMISSION = "admission"
|
||||
|
||||
|
||||
class PopulationClassificationReason(StrEnum):
|
||||
BELOW_MINIMUM_POSITIVES = "below_minimum_positives"
|
||||
MISSING_ECOSYSTEM = "missing_ecosystem"
|
||||
MISSING_SECOND_FAMILY = "missing_second_family"
|
||||
SCOPE_MINIMUM_UNMET = "scope_minimum_unmet"
|
||||
|
||||
|
||||
@dataclass(frozen=True, order=True)
|
||||
class ScopeMinimumV1:
|
||||
vulnerability_family: str
|
||||
ecosystem: CanonicalEcosystem
|
||||
minimum_count: int
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "vulnerability_family", _family(self.vulnerability_family))
|
||||
object.__setattr__(self, "ecosystem", _ecosystem(self.ecosystem))
|
||||
if isinstance(self.minimum_count, bool) or not isinstance(self.minimum_count, int) or self.minimum_count <= 0:
|
||||
raise PopulationFreezeError("scope minimum must be a positive integer")
|
||||
|
||||
|
||||
@dataclass(frozen=True, order=True)
|
||||
class PopulationScopeCountV1:
|
||||
vulnerability_family: str
|
||||
ecosystem: CanonicalEcosystem
|
||||
count: int
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "vulnerability_family", _family(self.vulnerability_family))
|
||||
object.__setattr__(self, "ecosystem", _ecosystem(self.ecosystem))
|
||||
if isinstance(self.count, bool) or not isinstance(self.count, int) or self.count <= 0:
|
||||
raise PopulationFreezeError("population scope count must be positive")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PopulationFreezeV3:
|
||||
population_class: PopulationClass
|
||||
classification_reasons: tuple[PopulationClassificationReason, ...]
|
||||
positive_count: int
|
||||
ecosystems: tuple[CanonicalEcosystem, ...]
|
||||
families: tuple[str, ...]
|
||||
scope_census: tuple[PopulationScopeCountV1, ...]
|
||||
scope_minimums: tuple[ScopeMinimumV1, ...]
|
||||
positive_change_digests: tuple[str, ...]
|
||||
positive_selection_digest: str
|
||||
ecosystem_review_digests: tuple[str, ...]
|
||||
ground_truth_review_digests: tuple[str, ...]
|
||||
review_set_digest: str
|
||||
ordinary_selection_digest: str
|
||||
reservation_census_digest: str
|
||||
exclusion_counts: tuple[tuple[str, int], ...]
|
||||
source_provenance_digest: str
|
||||
ecosystem_policy_digest: str
|
||||
ground_truth_policy_digest: str
|
||||
freeze_policy_digest: str
|
||||
population_digest: str
|
||||
freeze_digest: str
|
||||
|
||||
|
||||
def _digest(value: object, field: str) -> str:
|
||||
if not isinstance(value, str) or _DIGEST.fullmatch(value) is None:
|
||||
raise PopulationFreezeError(f"{field} must be a full lowercase SHA-256 digest")
|
||||
return value
|
||||
|
||||
|
||||
def _family(value: object) -> str:
|
||||
if not isinstance(value, str) or _FAMILY.fullmatch(value) is None:
|
||||
raise PopulationFreezeError("vulnerability family must be a canonical evidence label")
|
||||
return value
|
||||
|
||||
|
||||
def _ecosystem(value: object) -> CanonicalEcosystem:
|
||||
if isinstance(value, CanonicalEcosystem):
|
||||
return value
|
||||
if not isinstance(value, str):
|
||||
raise PopulationFreezeError("canonical ecosystem is unsupported")
|
||||
try:
|
||||
return CanonicalEcosystem(value)
|
||||
except (TypeError, ValueError) as error:
|
||||
raise PopulationFreezeError("canonical ecosystem is unsupported") from error
|
||||
|
||||
|
||||
def _scope_value(scope: PopulationScopeCountV1 | ScopeMinimumV1) -> dict[str, JsonValue]:
|
||||
value: dict[str, JsonValue] = {
|
||||
"vulnerability_family": _family(scope.vulnerability_family),
|
||||
"ecosystem": _ecosystem(scope.ecosystem).value,
|
||||
}
|
||||
if isinstance(scope, PopulationScopeCountV1):
|
||||
value["count"] = scope.count
|
||||
else:
|
||||
value["minimum_count"] = scope.minimum_count
|
||||
return value
|
||||
|
||||
|
||||
def _exclusions(values: tuple[tuple[str, int], ...]) -> None:
|
||||
if values != tuple(sorted(set(values))):
|
||||
raise PopulationFreezeError("population exclusion counts are not canonical")
|
||||
for reason, count in values:
|
||||
if not isinstance(reason, str) or not _FAMILY.fullmatch(reason):
|
||||
raise PopulationFreezeError("population exclusion reason is not canonical")
|
||||
if isinstance(count, bool) or not isinstance(count, int) or count < 0:
|
||||
raise PopulationFreezeError("population exclusion count is invalid")
|
||||
|
||||
|
||||
def _canonical_digests(values: tuple[str, ...], field: str) -> None:
|
||||
if values != tuple(sorted(set(values))):
|
||||
raise PopulationFreezeError(f"{field} identities are not canonical")
|
||||
for value in values:
|
||||
_digest(value, field)
|
||||
|
||||
|
||||
def _population_value(freeze: PopulationFreezeV3) -> dict[str, JsonValue]:
|
||||
return {
|
||||
"schema_version": POPULATION_IDENTITY_SCHEMA,
|
||||
"positive_change_digests": freeze.positive_change_digests,
|
||||
"positive_selection_digest": freeze.positive_selection_digest,
|
||||
"ecosystem_review_digests": freeze.ecosystem_review_digests,
|
||||
"ground_truth_review_digests": freeze.ground_truth_review_digests,
|
||||
"review_set_digest": freeze.review_set_digest,
|
||||
"ordinary_selection_digest": freeze.ordinary_selection_digest,
|
||||
"reservation_census_digest": freeze.reservation_census_digest,
|
||||
"exclusion_counts": freeze.exclusion_counts,
|
||||
"source_provenance_digest": freeze.source_provenance_digest,
|
||||
"ecosystem_policy_digest": freeze.ecosystem_policy_digest,
|
||||
"ground_truth_policy_digest": freeze.ground_truth_policy_digest,
|
||||
"freeze_policy_digest": freeze.freeze_policy_digest,
|
||||
}
|
||||
|
||||
|
||||
def _freeze_value(freeze: PopulationFreezeV3, *, include_digest: bool) -> dict[str, JsonValue]:
|
||||
value: dict[str, JsonValue] = {
|
||||
"schema_version": POPULATION_FREEZE_SCHEMA,
|
||||
"population_class": PopulationClass(freeze.population_class).value,
|
||||
"classification_reasons": tuple(PopulationClassificationReason(item).value for item in freeze.classification_reasons),
|
||||
"positive_count": freeze.positive_count,
|
||||
"ecosystems": tuple(_ecosystem(item).value for item in freeze.ecosystems),
|
||||
"families": freeze.families,
|
||||
"scope_census": tuple(_scope_value(item) for item in freeze.scope_census),
|
||||
"scope_minimums": tuple(_scope_value(item) for item in freeze.scope_minimums),
|
||||
**_population_value(freeze),
|
||||
"population_digest": freeze.population_digest,
|
||||
}
|
||||
if include_digest:
|
||||
value["freeze_digest"] = freeze.freeze_digest
|
||||
return value
|
||||
|
||||
|
||||
def _validate_collections(freeze: PopulationFreezeV3) -> None:
|
||||
if isinstance(freeze.positive_count, bool) or freeze.positive_count != len(freeze.positive_change_digests):
|
||||
raise PopulationFreezeError("population positive count does not match identities")
|
||||
_canonical_digests(freeze.positive_change_digests, "positive change")
|
||||
_canonical_digests(freeze.ecosystem_review_digests, "ecosystem review")
|
||||
_canonical_digests(freeze.ground_truth_review_digests, "ground-truth review")
|
||||
if freeze.ecosystems != tuple(sorted(set(freeze.ecosystems), key=lambda item: item.value)):
|
||||
raise PopulationFreezeError("population ecosystems are not canonical")
|
||||
if freeze.families != tuple(sorted(set(freeze.families))) or any(_family(item) != item for item in freeze.families):
|
||||
raise PopulationFreezeError("population families are not canonical")
|
||||
if freeze.scope_census != tuple(sorted(set(freeze.scope_census))):
|
||||
raise PopulationFreezeError("population scope census is not canonical")
|
||||
if freeze.scope_minimums != tuple(sorted(set(freeze.scope_minimums))):
|
||||
raise PopulationFreezeError("population scope minimums are not canonical")
|
||||
minimum_keys = {(item.vulnerability_family, item.ecosystem) for item in freeze.scope_minimums}
|
||||
if len(minimum_keys) != len(freeze.scope_minimums):
|
||||
raise PopulationFreezeError("population scope has conflicting minimums")
|
||||
_exclusions(freeze.exclusion_counts)
|
||||
if len({reason for reason, _ in freeze.exclusion_counts}) != len(freeze.exclusion_counts):
|
||||
raise PopulationFreezeError("population exclusion reason has conflicting counts")
|
||||
reasons = tuple(sorted(set(freeze.classification_reasons), key=lambda item: item.value))
|
||||
if freeze.classification_reasons != reasons:
|
||||
raise PopulationFreezeError("population classification reasons are not canonical")
|
||||
|
||||
|
||||
def _validate_scope_shape(freeze: PopulationFreezeV3) -> None:
|
||||
scoped_ecosystems = tuple(sorted({item.ecosystem for item in freeze.scope_census}, key=lambda item: item.value))
|
||||
scoped_families = tuple(sorted({item.vulnerability_family for item in freeze.scope_census}))
|
||||
if (freeze.ecosystems, freeze.families) != (scoped_ecosystems, scoped_families):
|
||||
raise PopulationFreezeError("population ecosystem or family census does not match exact scopes")
|
||||
if any(item.count > freeze.positive_count for item in freeze.scope_census):
|
||||
raise PopulationFreezeError("population scope count exceeds whole positive count")
|
||||
if len(freeze.ecosystem_review_digests) != freeze.positive_count or len(freeze.ground_truth_review_digests) != freeze.positive_count:
|
||||
raise PopulationFreezeError("population review sets do not cover every positive")
|
||||
|
||||
|
||||
def _validate_identity_bindings(freeze: PopulationFreezeV3) -> None:
|
||||
expected_positive = content_digest(
|
||||
{
|
||||
"accepted_changes": freeze.positive_change_digests,
|
||||
"scope_census": tuple((item.vulnerability_family, item.ecosystem.value, item.count) for item in freeze.scope_census),
|
||||
}
|
||||
)
|
||||
expected_reviews = content_digest(
|
||||
{
|
||||
"ecosystem_reviews": freeze.ecosystem_review_digests,
|
||||
"ground_truth_reviews": freeze.ground_truth_review_digests,
|
||||
}
|
||||
)
|
||||
if freeze.positive_selection_digest != expected_positive or freeze.review_set_digest != expected_reviews:
|
||||
raise PopulationFreezeError("population selection or review-set identity does not match")
|
||||
|
||||
|
||||
def _expected_classification(
|
||||
freeze: PopulationFreezeV3,
|
||||
) -> tuple[PopulationClass, tuple[PopulationClassificationReason, ...]]:
|
||||
reasons: set[PopulationClassificationReason] = set()
|
||||
if freeze.positive_count < MINIMUM_ADMISSION_POSITIVES:
|
||||
reasons.add(PopulationClassificationReason.BELOW_MINIMUM_POSITIVES)
|
||||
if set(freeze.ecosystems) != {CanonicalEcosystem.PYTHON, CanonicalEcosystem.JAVASCRIPT}:
|
||||
reasons.add(PopulationClassificationReason.MISSING_ECOSYSTEM)
|
||||
if len(freeze.families) < 2:
|
||||
reasons.add(PopulationClassificationReason.MISSING_SECOND_FAMILY)
|
||||
counts = {(item.vulnerability_family, item.ecosystem): item.count for item in freeze.scope_census}
|
||||
if any(counts.get((item.vulnerability_family, item.ecosystem), 0) < item.minimum_count for item in freeze.scope_minimums):
|
||||
reasons.add(PopulationClassificationReason.SCOPE_MINIMUM_UNMET)
|
||||
ordered = tuple(sorted(reasons, key=lambda item: item.value))
|
||||
expected_class = PopulationClass.ADMISSION
|
||||
if ordered == (PopulationClassificationReason.BELOW_MINIMUM_POSITIVES,):
|
||||
expected_class = PopulationClass.DEVELOPMENT_PILOT
|
||||
elif ordered:
|
||||
expected_class = PopulationClass.INSUFFICIENT
|
||||
return expected_class, ordered
|
||||
|
||||
|
||||
def _validate_derived(freeze: PopulationFreezeV3) -> None:
|
||||
_validate_scope_shape(freeze)
|
||||
_validate_identity_bindings(freeze)
|
||||
expected_class, ordered = _expected_classification(freeze)
|
||||
if (freeze.population_class, freeze.classification_reasons) != (expected_class, ordered):
|
||||
raise PopulationFreezeError("population classification does not match its exact census")
|
||||
|
||||
|
||||
def population_freeze_bytes(freeze: PopulationFreezeV3) -> bytes:
|
||||
"""Validate and encode a canonical replacement freeze."""
|
||||
_validate_collections(freeze)
|
||||
_validate_derived(freeze)
|
||||
for value, field in (
|
||||
(freeze.positive_selection_digest, "positive selection"),
|
||||
(freeze.review_set_digest, "review set"),
|
||||
(freeze.ordinary_selection_digest, "ordinary selection"),
|
||||
(freeze.reservation_census_digest, "reservation census"),
|
||||
(freeze.source_provenance_digest, "source provenance"),
|
||||
(freeze.ecosystem_policy_digest, "ecosystem policy"),
|
||||
(freeze.ground_truth_policy_digest, "ground-truth policy"),
|
||||
(freeze.freeze_policy_digest, "freeze policy"),
|
||||
(freeze.population_digest, "population"),
|
||||
(freeze.freeze_digest, "freeze"),
|
||||
):
|
||||
_digest(value, field)
|
||||
if freeze.population_digest != content_digest(_population_value(freeze)):
|
||||
raise PopulationFreezeError("population digest does not match exact selections and authorities")
|
||||
if freeze.freeze_digest != content_digest(_freeze_value(freeze, include_digest=False)):
|
||||
raise PopulationFreezeError("freeze digest does not match canonical freeze")
|
||||
return canonical_bytes(_freeze_value(freeze, include_digest=True))
|
||||
|
||||
|
||||
def accept_population_freeze(freeze: PopulationFreezeV3, *, existing_content: bytes | None = None) -> bytes:
|
||||
content = population_freeze_bytes(freeze)
|
||||
if existing_content is not None and existing_content != content:
|
||||
raise PopulationFreezeConflict("same freeze identity resolves to different bytes")
|
||||
return content
|
||||
|
||||
|
||||
__all__ = [
|
||||
"PopulationClass",
|
||||
"PopulationClassificationReason",
|
||||
"PopulationFreezeConflict",
|
||||
"PopulationFreezeError",
|
||||
"PopulationFreezeV3",
|
||||
"PopulationScopeCountV1",
|
||||
"ScopeMinimumV1",
|
||||
"accept_population_freeze",
|
||||
"population_freeze_bytes",
|
||||
]
|
||||
@@ -373,6 +373,18 @@ class ReservationAuthority:
|
||||
content_digest(_census_value(draft, include_digest=False)),
|
||||
)
|
||||
|
||||
def current_census(self) -> ReservationCensusV1:
|
||||
"""Project the exact census from all state accepted by this authority."""
|
||||
return self.project_census(self._accepted_bytes_by_digest.values())
|
||||
|
||||
def require_current_census(self, census: ReservationCensusV1) -> ReservationCensusV1:
|
||||
"""Require a supplied census to equal the authority's current snapshot."""
|
||||
census_bytes(census)
|
||||
current = self.current_census()
|
||||
if census != current:
|
||||
raise ReservationConflict("reservation census is not the current authoritative snapshot")
|
||||
return current
|
||||
|
||||
def append_influence(self, content: bytes) -> ReservationCensusV1:
|
||||
event = decode_influence_event(content)
|
||||
existing = self._accepted_bytes_by_digest.get(event.event_digest)
|
||||
@@ -380,7 +392,7 @@ class ReservationAuthority:
|
||||
raise ReservationConflict("same event identity has different bytes")
|
||||
self._accepted_events((content,))
|
||||
self._accepted_bytes_by_digest[event.event_digest] = content
|
||||
return self.project_census(self._accepted_bytes_by_digest.values())
|
||||
return self.current_census()
|
||||
|
||||
def is_reserved(self, repository: str, census: ReservationCensusV1) -> bool:
|
||||
census_bytes(census)
|
||||
|
||||
@@ -0,0 +1,582 @@
|
||||
"""Canonical replacement population classification and freeze tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from benchmarks.valid import population_freeze as freezer # noqa: E402
|
||||
from benchmarks.valid.ecosystem_review import ( # noqa: E402
|
||||
CanonicalEcosystem,
|
||||
EcosystemReviewAttestationV1,
|
||||
EcosystemReviewDecision,
|
||||
review_repository_ecosystem,
|
||||
)
|
||||
from benchmarks.valid.fix_site_catalog import ( # noqa: E402
|
||||
EvidenceRef,
|
||||
FixSiteRequest,
|
||||
LicenseEvidence,
|
||||
PackageEcosystemEvidence,
|
||||
SourceEvidence,
|
||||
build_fix_site_candidate,
|
||||
)
|
||||
from benchmarks.valid.ground_truth_review import ( # noqa: E402
|
||||
GroundTruthAttestationV1,
|
||||
VerifiedScope,
|
||||
review_ground_truth,
|
||||
)
|
||||
from benchmarks.valid.ordinary_change_contract import ( # noqa: E402
|
||||
OrdinaryDrawAssignmentV1,
|
||||
OrdinaryFixExclusionV1,
|
||||
OrdinaryPushV1,
|
||||
OrdinarySelectionV1,
|
||||
ReviewedPositiveInput,
|
||||
_fix_exclusion_value,
|
||||
_push_value,
|
||||
_selection_value,
|
||||
)
|
||||
from benchmarks.valid.reservation import ( # noqa: E402
|
||||
InfluenceDisposition,
|
||||
InfluenceKind,
|
||||
RepositoryIdentityResolver,
|
||||
ReservationAuthority,
|
||||
ReservationCensusV1,
|
||||
_census_value,
|
||||
reviewed_influence_event,
|
||||
)
|
||||
from benchmarks.valid.reservation_identity import RepositoryNetworkIdentity, build_network_identity # noqa: E402
|
||||
from openultrasast.core.canonical import content_digest # noqa: E402
|
||||
|
||||
ECOSYSTEM_POLICY = content_digest({"policy": "ecosystem-v1"})
|
||||
GROUND_TRUTH_POLICY = content_digest({"policy": "ground-truth-v1"})
|
||||
FREEZE_POLICY = content_digest({"policy": "population-freeze-v1", "minimum": 40})
|
||||
DRAW_POLICY = content_digest({"policy": "ordinary-first-parent-v1", "required": 20})
|
||||
PROVENANCE = content_digest({"source": "reviewed-fixture-set"})
|
||||
RESERVATION_POLICY = content_digest({"policy": "reservation-review-v1"})
|
||||
RESERVATION_SUBJECT = content_digest({"subject": "population-source"})
|
||||
|
||||
|
||||
class _Reader:
|
||||
def __init__(self, parent: str, fixed: str, path: str, language: str) -> None:
|
||||
self.parent, self.fixed, self.path, self.language = parent, fixed, path, language
|
||||
|
||||
def parents(self, revision: str) -> tuple[str, ...]:
|
||||
return (self.parent,) if revision == self.fixed else ()
|
||||
|
||||
def blob(self, revision: str, path: str) -> str | None:
|
||||
if path != self.path:
|
||||
return None
|
||||
marker = "before" if revision == self.parent else "after" if revision == self.fixed else None
|
||||
if marker is None:
|
||||
return None
|
||||
if self.language == "python":
|
||||
return f'def handle():\n return "{marker}"\n'
|
||||
return f'function handle() {{ return "{marker}"; }}\n'
|
||||
|
||||
|
||||
def _positive(index: int, ecosystem: CanonicalEcosystem, family: str, *, extra_family: str | None = None) -> ReviewedPositiveInput:
|
||||
owner = "python-app" if ecosystem is CanonicalEcosystem.PYTHON else "javascript-app"
|
||||
network = build_network_identity(f"https://github.com/example/{owner}")
|
||||
parent = f"{index * 2 + 1:040x}"
|
||||
fixed = f"{index * 2 + 2:040x}"
|
||||
language = "python" if ecosystem is CanonicalEcosystem.PYTHON else "javascript"
|
||||
path = "src/app.py" if language == "python" else "src/app.js"
|
||||
manifest = "pyproject.toml" if language == "python" else "package.json"
|
||||
candidate = build_fix_site_candidate(
|
||||
_Reader(parent, fixed, path, language),
|
||||
FixSiteRequest(
|
||||
network,
|
||||
parent,
|
||||
fixed,
|
||||
path,
|
||||
"handle",
|
||||
language,
|
||||
PackageEcosystemEvidence(language, EvidenceRef(manifest, content_digest({"manifest": index}), 10)),
|
||||
LicenseEvidence("Apache-2.0", EvidenceRef("LICENSE", content_digest({"license": index}), 10)),
|
||||
SourceEvidence("security_advisory", f"fixture://advisory/{index}", content_digest({"advisory": index})),
|
||||
content_digest({"parent": parent, "fixed": fixed}),
|
||||
),
|
||||
)
|
||||
decision = EcosystemReviewDecision.PYTHON if ecosystem is CanonicalEcosystem.PYTHON else EcosystemReviewDecision.JAVASCRIPT
|
||||
eco = review_repository_ecosystem(
|
||||
candidate,
|
||||
EcosystemReviewAttestationV1(
|
||||
candidate.candidate_digest,
|
||||
candidate.source_evidence.evidence_digest,
|
||||
f"ecosystem-producer-{index}",
|
||||
f"ecosystem-reviewer-{index}",
|
||||
True,
|
||||
ECOSYSTEM_POLICY,
|
||||
True,
|
||||
decision,
|
||||
),
|
||||
expected_policy_digest=ECOSYSTEM_POLICY,
|
||||
)
|
||||
scopes = [VerifiedScope(family, ecosystem)]
|
||||
if extra_family is not None:
|
||||
scopes.append(VerifiedScope(extra_family, ecosystem))
|
||||
truth = review_ground_truth(
|
||||
candidate,
|
||||
eco,
|
||||
GroundTruthAttestationV1(
|
||||
candidate.candidate_digest,
|
||||
eco.review_digest,
|
||||
f"truth-producer-{index}",
|
||||
f"truth-reviewer-{index}",
|
||||
True,
|
||||
GROUND_TRUTH_POLICY,
|
||||
True,
|
||||
True,
|
||||
True,
|
||||
True,
|
||||
tuple(scopes),
|
||||
),
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
return ReviewedPositiveInput(candidate, eco, truth)
|
||||
|
||||
|
||||
def _positives(count: int = 40, *, one_ecosystem: bool = False, one_family: bool = False) -> tuple[ReviewedPositiveInput, ...]:
|
||||
values = []
|
||||
for index in range(count):
|
||||
ecosystem = CanonicalEcosystem.PYTHON if one_ecosystem or index < (count + 1) // 2 else CanonicalEcosystem.JAVASCRIPT
|
||||
family = "injection" if one_family or index % 2 == 0 else "path_traversal"
|
||||
values.append(_positive(index, ecosystem, family, extra_family="output_encoding" if index == 0 and not one_family else None))
|
||||
return tuple(values)
|
||||
|
||||
|
||||
def _selection(positives: tuple[ReviewedPositiveInput, ...]) -> OrdinarySelectionV1:
|
||||
pushes: list[OrdinaryPushV1] = []
|
||||
assignments: list[OrdinaryDrawAssignmentV1] = []
|
||||
by_network: dict[str, tuple[str, CanonicalEcosystem]] = {}
|
||||
for item in positives:
|
||||
by_network[item.candidate.network_identity_digest] = (item.candidate.canonical_repository, item.ecosystem_review.ecosystem) # type: ignore[assignment]
|
||||
for network_index, (network, (repository, ecosystem)) in enumerate(sorted(by_network.items())):
|
||||
for index in range(20):
|
||||
base = f"{9000 + network_index * 100 + index * 2:040x}"
|
||||
tip = f"{9001 + network_index * 100 + index * 2:040x}"
|
||||
push_draft = OrdinaryPushV1(
|
||||
repository,
|
||||
network,
|
||||
ecosystem,
|
||||
base,
|
||||
tip,
|
||||
8,
|
||||
content_digest({"change": tip}),
|
||||
content_digest({"history": network}),
|
||||
"",
|
||||
)
|
||||
pushes.append(replace(push_draft, push_digest=content_digest(_push_value(push_draft, include_digest=False))))
|
||||
push_by_network: dict[str, list[OrdinaryPushV1]] = {}
|
||||
for push in pushes:
|
||||
push_by_network.setdefault(push.network_identity_digest, []).append(push)
|
||||
fix_exclusions = []
|
||||
positive_digests = []
|
||||
for item in positives:
|
||||
change = item.ground_truth_review.change_identity_digest
|
||||
positive_digests.append(change)
|
||||
fix_exclusions.append(
|
||||
OrdinaryFixExclusionV1(
|
||||
item.candidate.network_identity_digest,
|
||||
item.candidate.fixed.revision,
|
||||
change,
|
||||
item.ground_truth_review.review_digest,
|
||||
)
|
||||
)
|
||||
for push in push_by_network[item.candidate.network_identity_digest]:
|
||||
assignments.append(OrdinaryDrawAssignmentV1(change, push.network_identity_digest, push.ecosystem, push.push_digest))
|
||||
fix_exclusions = sorted(fix_exclusions)
|
||||
provenance = content_digest(
|
||||
{
|
||||
"history_sources": tuple(
|
||||
sorted({(push.canonical_repository, push.network_identity_digest, push.history_source_digest) for push in pushes})
|
||||
),
|
||||
"accepted_fix_exclusions": tuple(_fix_exclusion_value(item) for item in fix_exclusions),
|
||||
"policy_digest": DRAW_POLICY,
|
||||
}
|
||||
)
|
||||
selection_draft = OrdinarySelectionV1(
|
||||
20,
|
||||
DRAW_POLICY,
|
||||
tuple(sorted(positive_digests)),
|
||||
tuple(fix_exclusions),
|
||||
tuple(sorted(pushes, key=lambda item: item.push_digest)),
|
||||
tuple(sorted(assignments)),
|
||||
(),
|
||||
provenance,
|
||||
"",
|
||||
)
|
||||
return replace(
|
||||
selection_draft,
|
||||
selection_digest=content_digest(_selection_value(selection_draft, include_digest=False)),
|
||||
)
|
||||
|
||||
|
||||
def _census(*reserved: str) -> ReservationCensusV1:
|
||||
draft = ReservationCensusV1(tuple(sorted(reserved)), (), (), "")
|
||||
return replace(draft, census_digest=content_digest(_census_value(draft, include_digest=False)))
|
||||
|
||||
|
||||
def _resolver(
|
||||
positives: tuple[ReviewedPositiveInput, ...],
|
||||
*overrides: RepositoryNetworkIdentity,
|
||||
) -> RepositoryIdentityResolver:
|
||||
networks = {item.candidate.canonical_repository: build_network_identity(item.candidate.canonical_repository) for item in positives}
|
||||
networks.update({item.canonical_repository: item for item in overrides})
|
||||
return RepositoryIdentityResolver(networks.values())
|
||||
|
||||
|
||||
def _authority(
|
||||
positives: tuple[ReviewedPositiveInput, ...],
|
||||
*overrides: RepositoryNetworkIdentity,
|
||||
) -> ReservationAuthority:
|
||||
return ReservationAuthority(_resolver(positives, *overrides))
|
||||
|
||||
|
||||
def _influence_event(
|
||||
positives: tuple[ReviewedPositiveInput, ...],
|
||||
resolver: RepositoryIdentityResolver,
|
||||
disposition: InfluenceDisposition,
|
||||
kind: InfluenceKind,
|
||||
) -> bytes:
|
||||
return reviewed_influence_event(
|
||||
resolver,
|
||||
repository=positives[0].candidate.canonical_repository,
|
||||
event_source=f"freeze-regression-{disposition.value}",
|
||||
disposition=disposition,
|
||||
influence_kind=kind,
|
||||
subject_digest=RESERVATION_SUBJECT,
|
||||
actor_identity="reservation-producer",
|
||||
reviewer_identity="reservation-reviewer",
|
||||
conflict_disclosed=True,
|
||||
policy_digest=RESERVATION_POLICY,
|
||||
)
|
||||
|
||||
|
||||
def _freeze(
|
||||
positives: tuple[ReviewedPositiveInput, ...],
|
||||
*,
|
||||
census: ReservationCensusV1 | None = None,
|
||||
authority: ReservationAuthority | None = None,
|
||||
minimums: tuple[freezer.ScopeMinimumV1, ...] = (),
|
||||
) -> freezer.PopulationFreezeV3:
|
||||
return freezer.freeze_population(
|
||||
positives,
|
||||
ordinary_selection=_selection(positives),
|
||||
reservation_census=census or _census(),
|
||||
reservation_authority=authority or _authority(positives),
|
||||
scope_minimums=minimums,
|
||||
exclusion_counts=(("review_excluded", 3),),
|
||||
source_provenance_digest=PROVENANCE,
|
||||
freeze_policy_digest=FREEZE_POLICY,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
|
||||
|
||||
def test_forty_two_ecosystem_two_family_population_is_admission_and_deterministic() -> None:
|
||||
positives = _positives()
|
||||
first = _freeze(positives)
|
||||
second = _freeze(tuple(reversed(positives)))
|
||||
|
||||
assert freezer.population_freeze_bytes(first) == freezer.population_freeze_bytes(second)
|
||||
assert first.population_class is freezer.PopulationClass.ADMISSION
|
||||
assert first.classification_reasons == ()
|
||||
assert first.positive_count == 40
|
||||
assert first.ecosystems == (CanonicalEcosystem.JAVASCRIPT, CanonicalEcosystem.PYTHON)
|
||||
assert first.families == ("injection", "output_encoding", "path_traversal")
|
||||
assert sum(item.count for item in first.scope_census) == 41
|
||||
|
||||
|
||||
def test_thirty_nine_is_development_pilot_not_admission() -> None:
|
||||
freeze = _freeze(_positives(39))
|
||||
assert freeze.population_class is freezer.PopulationClass.DEVELOPMENT_PILOT
|
||||
assert freezer.PopulationClassificationReason.BELOW_MINIMUM_POSITIVES in freeze.classification_reasons
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"positives,reason",
|
||||
(
|
||||
(_positives(one_ecosystem=True), freezer.PopulationClassificationReason.MISSING_ECOSYSTEM),
|
||||
(_positives(one_family=True), freezer.PopulationClassificationReason.MISSING_SECOND_FAMILY),
|
||||
),
|
||||
)
|
||||
def test_missing_ecosystem_or_second_family_is_insufficient(
|
||||
positives: tuple[ReviewedPositiveInput, ...], reason: freezer.PopulationClassificationReason
|
||||
) -> None:
|
||||
freeze = _freeze(positives)
|
||||
assert freeze.population_class is freezer.PopulationClass.INSUFFICIENT
|
||||
assert reason in freeze.classification_reasons
|
||||
|
||||
|
||||
def test_infeasible_claimed_scope_is_insufficient() -> None:
|
||||
positives = _positives()
|
||||
freeze = _freeze(
|
||||
positives,
|
||||
minimums=(freezer.ScopeMinimumV1("injection", CanonicalEcosystem.PYTHON, 30),),
|
||||
)
|
||||
assert freeze.population_class is freezer.PopulationClass.INSUFFICIENT
|
||||
assert freezer.PopulationClassificationReason.SCOPE_MINIMUM_UNMET in freeze.classification_reasons
|
||||
|
||||
|
||||
def test_reserved_repository_is_refused_before_freeze() -> None:
|
||||
positives = _positives()
|
||||
resolver = _resolver(positives)
|
||||
authority = ReservationAuthority(resolver)
|
||||
census = authority.append_influence(
|
||||
_influence_event(
|
||||
positives,
|
||||
resolver,
|
||||
InfluenceDisposition.INFLUENCED,
|
||||
InfluenceKind.POPULATION_SELECTION,
|
||||
)
|
||||
)
|
||||
with pytest.raises(freezer.PopulationFreezeError, match="reserved"):
|
||||
_freeze(positives, census=census, authority=authority)
|
||||
|
||||
|
||||
def test_reserved_reviewed_network_cannot_be_split_by_candidate_identity() -> None:
|
||||
positives = _positives()
|
||||
reviewed_network = build_network_identity(
|
||||
positives[0].candidate.canonical_repository,
|
||||
aliases=("https://github.com/example/python-app-former",),
|
||||
forks=("https://github.com/example/python-app-fork",),
|
||||
)
|
||||
resolver = _resolver(positives, reviewed_network)
|
||||
authority = ReservationAuthority(resolver)
|
||||
census = authority.append_influence(
|
||||
_influence_event(
|
||||
positives,
|
||||
resolver,
|
||||
InfluenceDisposition.INFLUENCED,
|
||||
InfluenceKind.POPULATION_SELECTION,
|
||||
)
|
||||
)
|
||||
assert positives[0].candidate.network_identity_digest != reviewed_network.network_identity_digest
|
||||
with pytest.raises(freezer.PopulationFreezeError, match="reserved|resolved|identity"):
|
||||
freezer.freeze_population(
|
||||
positives,
|
||||
ordinary_selection=_selection(positives),
|
||||
reservation_census=census,
|
||||
reservation_authority=authority,
|
||||
source_provenance_digest=PROVENANCE,
|
||||
freeze_policy_digest=FREEZE_POLICY,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
|
||||
|
||||
def test_candidate_split_identity_is_refused_even_when_reviewed_network_is_not_reserved() -> None:
|
||||
positives = _positives()
|
||||
reviewed_network = build_network_identity(
|
||||
positives[0].candidate.canonical_repository,
|
||||
aliases=("https://github.com/example/python-app-former",),
|
||||
)
|
||||
with pytest.raises(freezer.PopulationFreezeError, match="resolved repository identity"):
|
||||
freezer.freeze_population(
|
||||
positives,
|
||||
ordinary_selection=_selection(positives),
|
||||
reservation_census=_census(),
|
||||
reservation_authority=_authority(positives, reviewed_network),
|
||||
source_provenance_digest=PROVENANCE,
|
||||
freeze_policy_digest=FREEZE_POLICY,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"disposition,kind",
|
||||
(
|
||||
(InfluenceDisposition.INFLUENCED, InfluenceKind.POPULATION_SELECTION),
|
||||
(InfluenceDisposition.ENUMERATED_ONLY, InfluenceKind.ENUMERATION),
|
||||
),
|
||||
)
|
||||
def test_stale_census_after_reviewed_event_is_refused(
|
||||
disposition: InfluenceDisposition,
|
||||
kind: InfluenceKind,
|
||||
) -> None:
|
||||
positives = _positives()
|
||||
resolver = _resolver(positives)
|
||||
authority = ReservationAuthority(resolver)
|
||||
stale_census = _census()
|
||||
authority.append_influence(_influence_event(positives, resolver, disposition, kind))
|
||||
|
||||
with pytest.raises(freezer.PopulationFreezeError, match="current|authoritative|snapshot"):
|
||||
freezer.freeze_population(
|
||||
positives,
|
||||
ordinary_selection=_selection(positives),
|
||||
reservation_census=stale_census,
|
||||
reservation_authority=authority,
|
||||
source_provenance_digest=PROVENANCE,
|
||||
freeze_policy_digest=FREEZE_POLICY,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
|
||||
|
||||
def test_later_authority_append_invalidates_replay_without_rewriting_freeze() -> None:
|
||||
positives = _positives()
|
||||
resolver = _resolver(positives)
|
||||
authority = ReservationAuthority(resolver)
|
||||
census = _census()
|
||||
selection = _selection(positives)
|
||||
freeze = freezer.freeze_population(
|
||||
positives,
|
||||
ordinary_selection=selection,
|
||||
reservation_census=census,
|
||||
reservation_authority=authority,
|
||||
source_provenance_digest=PROVENANCE,
|
||||
freeze_policy_digest=FREEZE_POLICY,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
frozen_bytes = freezer.population_freeze_bytes(freeze)
|
||||
authority.append_influence(
|
||||
_influence_event(
|
||||
positives,
|
||||
resolver,
|
||||
InfluenceDisposition.ENUMERATED_ONLY,
|
||||
InfluenceKind.ENUMERATION,
|
||||
)
|
||||
)
|
||||
|
||||
with pytest.raises(freezer.PopulationFreezeError, match="current|authoritative|snapshot"):
|
||||
freezer.validate_population_freeze(
|
||||
freeze,
|
||||
positives,
|
||||
ordinary_selection=selection,
|
||||
reservation_census=census,
|
||||
reservation_authority=authority,
|
||||
source_provenance_digest=PROVENANCE,
|
||||
freeze_policy_digest=FREEZE_POLICY,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
assert freezer.population_freeze_bytes(freeze) == frozen_bytes
|
||||
|
||||
|
||||
def test_ordinary_selection_must_bind_exact_positive_set() -> None:
|
||||
positives = _positives()
|
||||
selection = _selection(positives[:-1])
|
||||
with pytest.raises(freezer.PopulationFreezeError, match="ordinary|positive"):
|
||||
freezer.freeze_population(
|
||||
positives,
|
||||
ordinary_selection=selection,
|
||||
reservation_census=_census(),
|
||||
reservation_authority=_authority(positives),
|
||||
source_provenance_digest=PROVENANCE,
|
||||
freeze_policy_digest=FREEZE_POLICY,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
|
||||
|
||||
def test_structurally_valid_cross_ecosystem_ordinary_substitution_is_refused() -> None:
|
||||
positives = _positives()
|
||||
selection = _selection(positives)
|
||||
javascript_network = next(
|
||||
item.candidate.network_identity_digest for item in positives if item.ecosystem_review.ecosystem is CanonicalEcosystem.JAVASCRIPT
|
||||
)
|
||||
digest_map: dict[str, str] = {}
|
||||
pushes = []
|
||||
for push in selection.pushes:
|
||||
if push.network_identity_digest != javascript_network:
|
||||
pushes.append(push)
|
||||
continue
|
||||
push_draft = replace(push, ecosystem=CanonicalEcosystem.PYTHON, push_digest="")
|
||||
forged_push = replace(
|
||||
push_draft,
|
||||
push_digest=content_digest(_push_value(push_draft, include_digest=False)),
|
||||
)
|
||||
digest_map[push.push_digest] = forged_push.push_digest
|
||||
pushes.append(forged_push)
|
||||
assignments = tuple(
|
||||
replace(
|
||||
item,
|
||||
ecosystem=CanonicalEcosystem.PYTHON,
|
||||
push_digest=digest_map[item.push_digest],
|
||||
)
|
||||
if item.network_identity_digest == javascript_network
|
||||
else item
|
||||
for item in selection.assignments
|
||||
)
|
||||
selection_draft = replace(
|
||||
selection,
|
||||
pushes=tuple(sorted(pushes, key=lambda item: item.push_digest)),
|
||||
assignments=tuple(sorted(assignments)),
|
||||
selection_digest="",
|
||||
)
|
||||
forged_selection = replace(
|
||||
selection_draft,
|
||||
selection_digest=content_digest(_selection_value(selection_draft, include_digest=False)),
|
||||
)
|
||||
with pytest.raises(freezer.PopulationFreezeError, match="ecosystem"):
|
||||
freezer.freeze_population(
|
||||
positives,
|
||||
ordinary_selection=forged_selection,
|
||||
reservation_census=_census(),
|
||||
reservation_authority=_authority(positives),
|
||||
source_provenance_digest=PROVENANCE,
|
||||
freeze_policy_digest=FREEZE_POLICY,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
|
||||
|
||||
def test_same_identity_different_bytes_and_historical_identity_reuse_are_refused() -> None:
|
||||
freeze = _freeze(_positives())
|
||||
content = freezer.accept_population_freeze(freeze)
|
||||
assert freezer.accept_population_freeze(freeze, existing_content=content) == content
|
||||
with pytest.raises(freezer.PopulationFreezeConflict, match="different bytes"):
|
||||
freezer.accept_population_freeze(freeze, existing_content=content + b"\n")
|
||||
with pytest.raises(freezer.PopulationFreezeError, match="historical"):
|
||||
freezer.freeze_population(
|
||||
_positives(),
|
||||
ordinary_selection=_selection(_positives()),
|
||||
reservation_census=_census(),
|
||||
reservation_authority=_authority(_positives()),
|
||||
exclusion_counts=(("review_excluded", 3),),
|
||||
source_provenance_digest=PROVENANCE,
|
||||
freeze_policy_digest=FREEZE_POLICY,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
forbidden_historical_identities=(freeze.population_digest,),
|
||||
)
|
||||
|
||||
|
||||
def test_rehashed_classification_cannot_replay_against_exact_authorities() -> None:
|
||||
positives = _positives()
|
||||
selection = _selection(positives)
|
||||
freeze = _freeze(positives)
|
||||
forged = replace(
|
||||
freeze,
|
||||
population_class=freezer.PopulationClass.INSUFFICIENT,
|
||||
classification_reasons=(freezer.PopulationClassificationReason.SCOPE_MINIMUM_UNMET,),
|
||||
freeze_digest="",
|
||||
)
|
||||
forged = replace(
|
||||
forged,
|
||||
freeze_digest=content_digest(freezer._freeze_value(forged, include_digest=False)),
|
||||
)
|
||||
with pytest.raises(freezer.PopulationFreezeError, match="classification"):
|
||||
freezer.population_freeze_bytes(forged)
|
||||
with pytest.raises(freezer.PopulationFreezeError, match="reproduce"):
|
||||
freezer.validate_population_freeze(
|
||||
forged,
|
||||
positives,
|
||||
ordinary_selection=selection,
|
||||
reservation_census=_census(),
|
||||
reservation_authority=_authority(positives),
|
||||
exclusion_counts=(("review_excluded", 3),),
|
||||
source_provenance_digest=PROVENANCE,
|
||||
freeze_policy_digest=FREEZE_POLICY,
|
||||
expected_ecosystem_policy_digest=ECOSYSTEM_POLICY,
|
||||
expected_ground_truth_policy_digest=GROUND_TRUTH_POLICY,
|
||||
)
|
||||
@@ -19,7 +19,7 @@ SUBJECT = content_digest({"subject": "selection-evidence"})
|
||||
LEGACY = content_digest({"legacy": "authoritative-reservation"})
|
||||
|
||||
|
||||
def _network(*, canonical: str = "https://github.com/acme/core"):
|
||||
def _network(*, canonical: str = "https://github.com/acme/core") -> reservation.RepositoryNetworkIdentity:
|
||||
return reservation.build_network_identity(
|
||||
canonical,
|
||||
aliases=("https://github.com/ACME/core.git",),
|
||||
@@ -30,7 +30,7 @@ def _network(*, canonical: str = "https://github.com/acme/core"):
|
||||
|
||||
|
||||
def _event(
|
||||
resolver,
|
||||
resolver: reservation.RepositoryIdentityResolver,
|
||||
*,
|
||||
repository: str = "https://github.com/acme/core",
|
||||
disposition: reservation.InfluenceDisposition = reservation.InfluenceDisposition.INFLUENCED,
|
||||
@@ -107,6 +107,26 @@ def test_equal_events_are_idempotent() -> None:
|
||||
assert len(second.accepted_event_digests) == 1
|
||||
|
||||
|
||||
def test_current_census_includes_legacy_and_equal_appends_are_idempotent() -> None:
|
||||
resolver = reservation.RepositoryIdentityResolver((_network(),))
|
||||
legacy = reservation.legacy_reservation_source(
|
||||
resolver,
|
||||
repository="https://github.com/acme/old-core",
|
||||
source_digest=LEGACY,
|
||||
)
|
||||
authority = reservation.ReservationAuthority(resolver, legacy_sources=(legacy,))
|
||||
initial = authority.current_census()
|
||||
event = _event(resolver)
|
||||
|
||||
first = authority.append_influence(event)
|
||||
second = authority.append_influence(bytes(event))
|
||||
|
||||
assert initial.legacy_source_digests == (legacy.legacy_source_digest,)
|
||||
assert first == second == authority.current_census()
|
||||
assert len(second.accepted_event_digests) == 1
|
||||
authority.require_current_census(second)
|
||||
|
||||
|
||||
def test_census_is_deterministic_from_complete_event_set() -> None:
|
||||
resolver = reservation.RepositoryIdentityResolver((_network(),))
|
||||
authority = reservation.ReservationAuthority(resolver)
|
||||
|
||||
Reference in New Issue
Block a user