feat(valid-detection-benchmark): probe custody store capabilities

This commit is contained in:
Marius Ciepluch
2026-11-17 15:52:05 +01:00
parent b8a7e66cd6
commit 7f1539a7ca
6 changed files with 1397 additions and 1 deletions
@@ -144,7 +144,7 @@
- Done when deleting scratch state and restarting reproduces every accepted identity, projection, and decision from durable objects alone.
- _Requirements: 7.4, 7.5, 7.7, 8.6, 10.1, 10.2_
- _Boundary: Artifact Repository_
- [ ] 5.3 (P) Probe conditional custody and retention capabilities
- [x] 5.3 (P) Probe conditional custody and retention capabilities
- Exercise conditional head creation, conditional update, two concurrent writers with one winner, version visibility, exact committed-successor reread, and restart recovery.
- Verify both current and noncurrent transient expiry against the pre-registered deadlines without changing store configuration.
- Prove nonzero probe inputs and fail loudly on unsupported, ambiguous, prematurely terminated, or unreadable responses.
@@ -427,3 +427,4 @@
- Task 4.4 derives the exact label-blind input set from the frozen positive and ordinary-selection authorities, uses detection-core V3's canonical input-set identity, and accepts review only through a rederived independence policy plus resolvable conflict-disclosure evidence.
- Task 5.1 persists replacement-authorizing artifacts under deterministic digest keys with conditional create and strict readback; access is policy-bound before fetch, and provider failures cross the repository boundary only as closed reason codes without retained exception diagnostics.
- Task 5.2 rebuilds exact caller-selected durable projection roots and ordered members from the object store alone; canonical root-envelope binding, mixed-access population recovery, and explicit optional expiry prevent forged authority, latest-value selection, and unintended terminal-artifact expiration.
- Task 5.3 gates real-population admission on a canonical report bound to exact store namespaces and a typed retention profile; negative conditional-write proofs, distinct visible versions, bound pre-deadline current/noncurrent evidence, and closed handling of null IDs, delete markers, and provider ambiguity prevent plausible-but-unsupported capability passes.
+296
View File
@@ -0,0 +1,296 @@
"""Canonical capability report and retention-state contracts."""
from __future__ import annotations
import re
from dataclasses import dataclass, replace
from enum import StrEnum
from benchmarks.valid.store_configuration import RetentionProfile
from openultrasast.core.canonical import JsonValue, bytes_digest, canonical_bytes
CUSTODY_CAPABILITY_REPORT_SCHEMA = "openultrasast.valid-detection-benchmark.custody-capability.v1"
RETENTION_PROBE_STATE_SCHEMA = "openultrasast.valid-detection-benchmark.retention-probe-state.v1"
_DIGEST = re.compile(r"[0-9a-f]{64}")
class ProbeResultName(StrEnum):
CONDITIONAL_CREATE = "conditional_create"
CONDITIONAL_UPDATE = "conditional_update"
CONCURRENT_SINGLE_WINNER = "concurrent_single_winner"
VERSION_VISIBILITY = "version_visibility"
COMMITTED_SUCCESSOR_REREAD = "committed_successor_reread"
RESTART_RECOVERY = "restart_recovery"
CURRENT_EXPIRY = "current_expiry"
NONCURRENT_EXPIRY = "noncurrent_expiry"
MANDATORY_PROBE_RESULTS = tuple(ProbeResultName)
class ProbeResultStatus(StrEnum):
PASSED = "passed"
PENDING = "pending"
FAILED = "failed"
class ProbeResultReason(StrEnum):
NONE = "none"
DEADLINE_PENDING = "deadline_pending"
CONDITIONAL_CREATE_UNSUPPORTED = "conditional_create_unsupported"
CONDITIONAL_UPDATE_UNSUPPORTED = "conditional_update_unsupported"
CONFLICT_NOT_ENFORCED = "conflict_not_enforced"
VERSION_NOT_VISIBLE = "version_not_visible"
READBACK_MISMATCH = "readback_mismatch"
RESTART_MISMATCH = "restart_mismatch"
PREMATURE_EXPIRY = "premature_expiry"
EXPIRY_DEADLINE_MISSED = "expiry_deadline_missed"
UNREADABLE_RESPONSE = "unreadable_response"
STORE_FAILURE = "store_failure"
DEPENDENCY_FAILED = "dependency_failed"
PRESENCE_EVIDENCE_MISSING = "presence_evidence_missing"
class CustodyCapabilityStatus(StrEnum):
READY = "ready"
PENDING = "pending"
UNSUPPORTED = "unsupported"
INSTRUMENT_FAILURE = "instrument_failure"
class CustodyProbeErrorReason(StrEnum):
INVALID_INPUT = "invalid_input"
STATE_MISMATCH = "state_mismatch"
STORE_FAILURE = "store_failure"
UNREADABLE_RESPONSE = "unreadable_response"
class CustodyCapabilityError(RuntimeError):
def __init__(self, reason: CustodyProbeErrorReason) -> None:
self.reason = reason
super().__init__(f"custody_capability_{reason.value}")
class RealPopulationAdmissionDisabled(RuntimeError):
"""A closed capability report cannot authorize a real population."""
@dataclass(frozen=True)
class RetentionProbeState:
schema_version: str
input_digest: str
input_bytes_read: int
started_at_epoch: int
durable_store_identity: str
transient_store_identity: str
transient_bucket: str
current_key: str
current_version_id: str
current_deadline_epoch: int
noncurrent_key: str
noncurrent_version_id: str
successor_version_id: str
noncurrent_deadline_epoch: int
state_digest: str
@dataclass(frozen=True)
class ProbeResult:
name: ProbeResultName
status: ProbeResultStatus
reason: ProbeResultReason
@dataclass(frozen=True)
class CustodyCapabilityReport:
schema_version: str
status: CustodyCapabilityStatus
input_digest: str
input_bytes_read: int
durable_store_identity: str
transient_store_identity: str
retention_profile_digest: str
retention_state_digest: str
results: tuple[ProbeResult, ...]
report_digest: str
@property
def may_admit_real_population(self) -> bool:
return self.status is CustodyCapabilityStatus.READY and all(result.status is ProbeResultStatus.PASSED for result in self.results)
def passed_result(name: ProbeResultName) -> ProbeResult:
return ProbeResult(name, ProbeResultStatus.PASSED, ProbeResultReason.NONE)
def failed_result(name: ProbeResultName, reason: ProbeResultReason) -> ProbeResult:
return ProbeResult(name, ProbeResultStatus.FAILED, reason)
def retention_state_value(state: RetentionProbeState) -> dict[str, JsonValue]:
return {
"schema_version": state.schema_version,
"input_digest": state.input_digest,
"input_bytes_read": state.input_bytes_read,
"started_at_epoch": state.started_at_epoch,
"durable_store_identity": state.durable_store_identity,
"transient_store_identity": state.transient_store_identity,
"transient_bucket": state.transient_bucket,
"current_key": state.current_key,
"current_version_id": state.current_version_id,
"current_deadline_epoch": state.current_deadline_epoch,
"noncurrent_key": state.noncurrent_key,
"noncurrent_version_id": state.noncurrent_version_id,
"successor_version_id": state.successor_version_id,
"noncurrent_deadline_epoch": state.noncurrent_deadline_epoch,
}
def derive_retention_state_digest(state: RetentionProbeState) -> str:
return bytes_digest(canonical_bytes(retention_state_value(state)))
def retention_profile_digest(profile: RetentionProfile) -> str:
value: JsonValue = {
"purpose": profile.purpose.value,
"versioning_required": profile.versioning_required,
"conditional_create_required": profile.conditional_create_required,
"conditional_update_required": profile.conditional_update_required,
"current_version_expiry_days": profile.current_version_expiry_days,
"noncurrent_version_expiry_days": profile.noncurrent_version_expiry_days,
}
return bytes_digest(canonical_bytes(value))
def _result_value(result: ProbeResult) -> dict[str, JsonValue]:
return {"name": result.name.value, "status": result.status.value, "reason": result.reason.value}
def _report_value(report: CustodyCapabilityReport) -> dict[str, JsonValue]:
return {
"schema_version": report.schema_version,
"status": report.status.value,
"input_digest": report.input_digest,
"input_bytes_read": report.input_bytes_read,
"durable_store_identity": report.durable_store_identity,
"transient_store_identity": report.transient_store_identity,
"retention_profile_digest": report.retention_profile_digest,
"retention_state_digest": report.retention_state_digest,
"results": tuple(_result_value(result) for result in report.results),
}
def _status_for_results(results: tuple[ProbeResult, ...]) -> CustodyCapabilityStatus:
instrument_reasons = {ProbeResultReason.STORE_FAILURE, ProbeResultReason.UNREADABLE_RESPONSE}
if any(result.reason in instrument_reasons for result in results):
return CustodyCapabilityStatus.INSTRUMENT_FAILURE
if any(result.status is ProbeResultStatus.FAILED for result in results):
return CustodyCapabilityStatus.UNSUPPORTED
if any(result.status is ProbeResultStatus.PENDING for result in results):
return CustodyCapabilityStatus.PENDING
return CustodyCapabilityStatus.READY
def build_capability_report(
input_digest: str,
input_bytes_read: int,
profile: RetentionProfile,
state: RetentionProbeState,
results: tuple[ProbeResult, ...],
) -> CustodyCapabilityReport:
draft = CustodyCapabilityReport(
CUSTODY_CAPABILITY_REPORT_SCHEMA,
_status_for_results(results),
input_digest,
input_bytes_read,
state.durable_store_identity,
state.transient_store_identity,
retention_profile_digest(profile),
state.state_digest,
results,
"",
)
return replace(draft, report_digest=bytes_digest(canonical_bytes(_report_value(draft))))
def _valid_result(result: ProbeResult) -> bool:
if type(result.name) is not ProbeResultName:
return False
if type(result.status) is not ProbeResultStatus or type(result.reason) is not ProbeResultReason:
return False
if result.status is ProbeResultStatus.PASSED:
return result.reason is ProbeResultReason.NONE
if result.status is ProbeResultStatus.PENDING:
return result.name in {ProbeResultName.CURRENT_EXPIRY, ProbeResultName.NONCURRENT_EXPIRY} and (
result.reason is ProbeResultReason.DEADLINE_PENDING
)
return result.reason not in {ProbeResultReason.NONE, ProbeResultReason.DEADLINE_PENDING}
def _valid_report(report: CustodyCapabilityReport) -> bool:
valid_types = type(report) is CustodyCapabilityReport and all(type(item) is ProbeResult for item in report.results)
if not valid_types:
return False
return (
report.schema_version == CUSTODY_CAPABILITY_REPORT_SCHEMA
and type(report.input_bytes_read) is int
and report.input_bytes_read > 0
and _DIGEST.fullmatch(report.input_digest) is not None
and _DIGEST.fullmatch(report.durable_store_identity) is not None
and _DIGEST.fullmatch(report.transient_store_identity) is not None
and _DIGEST.fullmatch(report.retention_profile_digest) is not None
and _DIGEST.fullmatch(report.retention_state_digest) is not None
and _DIGEST.fullmatch(report.report_digest) is not None
and tuple(item.name for item in report.results) == MANDATORY_PROBE_RESULTS
and all(_valid_result(item) for item in report.results)
and report.status is _status_for_results(report.results)
and report.report_digest == bytes_digest(canonical_bytes(_report_value(report)))
)
def canonical_custody_capability_report_bytes(report: CustodyCapabilityReport) -> bytes:
if not _valid_report(report):
raise CustodyCapabilityError(CustodyProbeErrorReason.STATE_MISMATCH)
return canonical_bytes({**_report_value(report), "report_digest": report.report_digest})
def prior_presence_results(
report: CustodyCapabilityReport,
*,
input_digest: str,
input_bytes_read: int,
state: RetentionProbeState,
profile_digest: str,
) -> tuple[ProbeResult, ...] | None:
if not _valid_report(report) or report.status is not CustodyCapabilityStatus.PENDING:
return None
identities_match = (
report.input_digest == input_digest
and report.input_bytes_read == input_bytes_read
and report.durable_store_identity == state.durable_store_identity
and report.transient_store_identity == state.transient_store_identity
and report.retention_profile_digest == profile_digest
and report.retention_state_digest == state.state_digest
)
durable_passed = all(item.status is ProbeResultStatus.PASSED for item in report.results[:6])
retention_pending = all(item.status is ProbeResultStatus.PENDING for item in report.results[6:])
return report.results[:6] if identities_match and durable_passed and retention_pending else None
def require_real_population_admission(
report: CustodyCapabilityReport,
expected_durable_store_identity: str,
expected_transient_store_identity: str,
expected_retention_profile: RetentionProfile,
) -> None:
if type(report) is not CustodyCapabilityReport:
raise RealPopulationAdmissionDisabled("real_population_admission_disabled")
stores_match = (
report.durable_store_identity == expected_durable_store_identity
and report.transient_store_identity == expected_transient_store_identity
)
profile_matches = type(expected_retention_profile) is RetentionProfile and (
report.retention_profile_digest == retention_profile_digest(expected_retention_profile)
)
if not _valid_report(report) or not stores_match or not profile_matches or not report.may_admit_real_population:
raise RealPopulationAdmissionDisabled("real_population_admission_disabled")
+162
View File
@@ -0,0 +1,162 @@
"""Strict S3 data-plane I/O for custody capability probes."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Protocol, cast
from benchmarks.valid.custody_probe_contract import (
CustodyCapabilityError,
CustodyProbeErrorReason,
ProbeResultReason,
)
from benchmarks.valid.store_configuration import StoreSettings
from openultrasast.core.canonical import JsonValue, bytes_digest, canonical_bytes
_PRECONDITION_CODES = frozenset({"409", "412", "ConditionalRequestConflict", "PreconditionFailed"})
_NOT_FOUND_CODES = frozenset({"404", "NoSuchKey", "NotFound", "NoSuchVersion"})
class S3CustodyProbeClient(Protocol):
def put_object(self, **kwargs: object) -> Mapping[str, object]: ...
def get_object(self, **kwargs: object) -> Mapping[str, object]: ...
def list_object_versions(self, **kwargs: object) -> Mapping[str, object]: ...
@dataclass(frozen=True)
class WriteReceipt:
version_id: str
storage_token: str
@dataclass(frozen=True)
class WriteAttempt:
receipt: WriteReceipt | None
is_conflict: bool
reason: ProbeResultReason
@dataclass(frozen=True)
class ReadAttempt:
body: bytes | None
receipt: WriteReceipt | None
is_absent: bool
reason: ProbeResultReason
def _provider_code(error: Exception) -> str:
try:
response = getattr(error, "response", None)
details = response.get("Error") if isinstance(response, Mapping) else None
code = details.get("Code", "") if isinstance(details, Mapping) else getattr(error, "code", "")
except Exception:
return ""
return code if isinstance(code, str) else str(code) if type(code) is int else ""
def valid_epoch(value: object) -> bool:
return type(value) is int and value > 0
def valid_version_id(value: object) -> bool:
return isinstance(value, str) and bool(value) and value != "null"
def probe_input(value: bytes) -> tuple[str, int]:
if type(value) is not bytes or not value:
raise CustodyCapabilityError(CustodyProbeErrorReason.INVALID_INPUT)
return bytes_digest(value), len(value)
def probe_body(kind: str, input_digest: str, sequence: int) -> bytes:
value: JsonValue = {"input_digest": input_digest, "kind": kind, "sequence": sequence}
return canonical_bytes(value)
class ProbeIO:
def __init__(self, settings: StoreSettings, client: S3CustodyProbeClient) -> None:
self.settings = settings
self.client = client
def write(self, key: str, body: bytes, *, absent: bool = False, token: str | None = None) -> WriteAttempt:
request: dict[str, object] = {"Bucket": self.settings.bucket, "Key": key, "Body": body}
if absent:
request["IfNoneMatch"] = "*"
if token is not None:
request["IfMatch"] = token
provider_code = ""
try:
response = self.client.put_object(**request)
except Exception as error:
provider_code = _provider_code(error)
response = None
if response is None:
return WriteAttempt(None, provider_code in _PRECONDITION_CODES, ProbeResultReason.STORE_FAILURE)
if not isinstance(response, Mapping):
return WriteAttempt(None, False, ProbeResultReason.UNREADABLE_RESPONSE)
version_id, storage_token = response.get("VersionId"), response.get("ETag")
if not valid_version_id(version_id) or not isinstance(storage_token, str) or not storage_token:
return WriteAttempt(None, False, ProbeResultReason.UNREADABLE_RESPONSE)
return WriteAttempt(WriteReceipt(cast(str, version_id), storage_token), False, ProbeResultReason.NONE)
def read(self, key: str, version_id: str | None = None) -> ReadAttempt:
request: dict[str, object] = {"Bucket": self.settings.bucket, "Key": key}
if version_id is not None:
request["VersionId"] = version_id
provider_code = ""
try:
response = self.client.get_object(**request)
except Exception as error:
provider_code = _provider_code(error)
response = None
if response is None:
is_absent = provider_code in _NOT_FOUND_CODES
reason = ProbeResultReason.NONE if is_absent else ProbeResultReason.STORE_FAILURE
return ReadAttempt(None, None, is_absent, reason)
return self._decode_read(response)
@staticmethod
def _decode_read(response: Mapping[str, object]) -> ReadAttempt:
body_source = response.get("Body")
try:
body = body_source.read() if hasattr(body_source, "read") else body_source
except Exception:
body = None
version_id, storage_token, length = response.get("VersionId"), response.get("ETag"), response.get("ContentLength")
valid = (
isinstance(body, bytes)
and bool(body)
and type(length) is int
and length == len(body)
and valid_version_id(version_id)
and isinstance(storage_token, str)
and bool(storage_token)
)
if not valid:
return ReadAttempt(None, None, False, ProbeResultReason.UNREADABLE_RESPONSE)
receipt = WriteReceipt(cast(str, version_id), cast(str, storage_token))
return ReadAttempt(cast(bytes, body), receipt, False, ProbeResultReason.NONE)
def version_ids(self, key: str) -> tuple[tuple[str, ...] | None, ProbeResultReason]:
try:
response = self.client.list_object_versions(Bucket=self.settings.bucket, Prefix=key)
except Exception:
return None, ProbeResultReason.STORE_FAILURE
if not isinstance(response, Mapping) or response.get("IsTruncated") is not False:
return None, ProbeResultReason.UNREADABLE_RESPONSE
versions = response.get("Versions", [])
markers = response.get("DeleteMarkers", [])
if not isinstance(versions, list) or not isinstance(markers, list) or markers:
return None, ProbeResultReason.UNREADABLE_RESPONSE
version_ids: list[str] = []
for item in versions:
if not isinstance(item, Mapping) or item.get("Key") != key:
return None, ProbeResultReason.UNREADABLE_RESPONSE
version_id = item.get("VersionId")
if not valid_version_id(version_id):
return None, ProbeResultReason.UNREADABLE_RESPONSE
version_ids.append(cast(str, version_id))
return tuple(version_ids), ProbeResultReason.NONE
+389
View File
@@ -0,0 +1,389 @@
"""Runtime capability probe for durable benchmark custody storage."""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from dataclasses import replace
from typing import cast
from benchmarks.valid.custody_probe_contract import (
RETENTION_PROBE_STATE_SCHEMA,
CustodyCapabilityError,
CustodyCapabilityReport,
CustodyProbeErrorReason,
ProbeResult,
ProbeResultName,
ProbeResultReason,
ProbeResultStatus,
RetentionProbeState,
build_capability_report,
derive_retention_state_digest,
failed_result,
passed_result,
prior_presence_results,
retention_profile_digest,
)
from benchmarks.valid.custody_probe_io import (
ProbeIO,
ReadAttempt,
S3CustodyProbeClient,
WriteAttempt,
WriteReceipt,
probe_body,
probe_input,
valid_epoch,
valid_version_id,
)
from benchmarks.valid.store_configuration import RetentionProfile, StorePurpose, StoreSettings, store_namespace_identity
from openultrasast.core.canonical import bytes_digest, canonical_bytes
_DAY_SECONDS = 86_400
class S3CustodyCapabilityProbe:
"""Probe data-plane guarantees without changing store configuration."""
def __init__(
self,
durable_settings: StoreSettings,
durable_client: S3CustodyProbeClient,
transient_settings: StoreSettings,
transient_client: S3CustodyProbeClient,
transient_profile: RetentionProfile,
) -> None:
valid = (
type(durable_settings) is StoreSettings
and durable_settings.purpose is StorePurpose.DURABLE
and type(transient_settings) is StoreSettings
and transient_settings.purpose is StorePurpose.TRANSIENT
and type(transient_profile) is RetentionProfile
and transient_profile.purpose is StorePurpose.TRANSIENT
)
if not valid:
raise CustodyCapabilityError(CustodyProbeErrorReason.INVALID_INPUT)
self._durable = ProbeIO(durable_settings, durable_client)
self._transient = ProbeIO(transient_settings, transient_client)
self._durable_client = durable_client
self._profile = transient_profile
self._durable_identity = store_namespace_identity(durable_settings)
self._transient_identity = store_namespace_identity(transient_settings)
if self._durable_identity == self._transient_identity:
raise CustodyCapabilityError(CustodyProbeErrorReason.INVALID_INPUT)
def prepare_retention_probe(self, input_bytes: bytes, current_epoch: int) -> RetentionProbeState:
input_digest, input_bytes_read = probe_input(input_bytes)
if not valid_epoch(current_epoch):
raise CustodyCapabilityError(CustodyProbeErrorReason.INVALID_INPUT)
base = f"runs/capability-probes/{bytes_digest(canonical_bytes((input_digest, current_epoch)))}"
current_key, noncurrent_key = f"{base}/current.json", f"{base}/noncurrent.json"
current_body = probe_body("retention-current", input_digest, 0)
successor_body = probe_body("retention-successor", input_digest, 1)
current = self._transient.write(current_key, current_body, absent=True)
prior = self._transient.write(noncurrent_key, probe_body("retention-noncurrent", input_digest, 0), absent=True)
if current.receipt is None or prior.receipt is None:
self._raise_prepare_failure(current, prior)
current_receipt, prior_receipt = cast(WriteReceipt, current.receipt), cast(WriteReceipt, prior.receipt)
successor = self._transient.write(
noncurrent_key,
successor_body,
token=prior_receipt.storage_token,
)
if successor.receipt is None:
self._raise_prepare_failure(successor)
successor_receipt = cast(WriteReceipt, successor.receipt)
self._validate_retention_seed(
current_key,
current_body,
current_receipt,
noncurrent_key,
successor_body,
successor_receipt,
prior_receipt.version_id,
)
return self._retention_state(
input_digest,
input_bytes_read,
current_epoch,
current_key,
current_receipt,
noncurrent_key,
prior_receipt,
successor_receipt,
)
def _retention_state(
self,
input_digest: str,
input_bytes_read: int,
current_epoch: int,
current_key: str,
current: WriteReceipt,
noncurrent_key: str,
prior: WriteReceipt,
successor: WriteReceipt,
) -> RetentionProbeState:
current_days = self._profile.current_version_expiry_days
noncurrent_days = self._profile.noncurrent_version_expiry_days
assert current_days is not None and noncurrent_days is not None
draft = RetentionProbeState(
RETENTION_PROBE_STATE_SCHEMA,
input_digest,
input_bytes_read,
current_epoch,
self._durable_identity,
self._transient_identity,
self._transient.settings.bucket,
current_key,
current.version_id,
current_epoch + current_days * _DAY_SECONDS,
noncurrent_key,
prior.version_id,
successor.version_id,
current_epoch + noncurrent_days * _DAY_SECONDS,
"",
)
return replace(draft, state_digest=derive_retention_state_digest(draft))
def _validate_retention_seed(
self,
current_key: str,
current_body: bytes,
current: WriteReceipt,
noncurrent_key: str,
successor_body: bytes,
successor: WriteReceipt,
prior_version_id: str,
) -> None:
current_read = self._transient.read(current_key)
successor_read = self._transient.read(noncurrent_key)
versions, reason = self._transient.version_ids(noncurrent_key)
reads_match = (
current_read.body == current_body
and current_read.receipt == current
and successor_read.body == successor_body
and successor_read.receipt == successor
)
expected_versions = (prior_version_id, successor.version_id)
versions_match = versions is not None and self._has_exact_versions(versions, expected_versions)
if reads_match and versions_match:
return
if reason is ProbeResultReason.STORE_FAILURE:
raise CustodyCapabilityError(CustodyProbeErrorReason.STORE_FAILURE)
raise CustodyCapabilityError(CustodyProbeErrorReason.UNREADABLE_RESPONSE)
@staticmethod
def _raise_prepare_failure(*attempts: WriteAttempt) -> None:
reason = CustodyProbeErrorReason.STORE_FAILURE
if any(item.reason is ProbeResultReason.UNREADABLE_RESPONSE for item in attempts):
reason = CustodyProbeErrorReason.UNREADABLE_RESPONSE
raise CustodyCapabilityError(reason)
def probe(
self,
input_bytes: bytes,
state: RetentionProbeState,
current_epoch: int,
*,
prior_report: CustodyCapabilityReport | None = None,
) -> CustodyCapabilityReport:
input_digest, input_bytes_read = probe_input(input_bytes)
self._validate_state(state, input_digest, input_bytes_read)
if not valid_epoch(current_epoch):
raise CustodyCapabilityError(CustodyProbeErrorReason.INVALID_INPUT)
durable_results = self._durable_results(input_digest, input_bytes_read, state, prior_report)
retention_results = self._probe_retention(state, current_epoch)
if prior_report is None and current_epoch >= min(state.current_deadline_epoch, state.noncurrent_deadline_epoch):
retention_results = [
item
if item.reason in {ProbeResultReason.STORE_FAILURE, ProbeResultReason.UNREADABLE_RESPONSE}
else failed_result(item.name, ProbeResultReason.PRESENCE_EVIDENCE_MISSING)
for item in retention_results
]
results = [*durable_results, *retention_results]
return build_capability_report(input_digest, input_bytes_read, self._profile, state, tuple(results))
def _durable_results(
self,
input_digest: str,
input_bytes_read: int,
state: RetentionProbeState,
prior_report: CustodyCapabilityReport | None,
) -> list[ProbeResult]:
if prior_report is None:
return self._probe_durable(input_digest, state.state_digest)
results = prior_presence_results(
prior_report,
input_digest=input_digest,
input_bytes_read=input_bytes_read,
state=state,
profile_digest=retention_profile_digest(self._profile),
)
if results is None:
raise CustodyCapabilityError(CustodyProbeErrorReason.STATE_MISMATCH)
return list(results)
def _validate_state(self, state: RetentionProbeState, input_digest: str, input_bytes_read: int) -> None:
if type(state) is not RetentionProbeState or not valid_epoch(state.started_at_epoch):
raise CustodyCapabilityError(CustodyProbeErrorReason.STATE_MISMATCH)
current_days = self._profile.current_version_expiry_days
noncurrent_days = self._profile.noncurrent_version_expiry_days
expected_base = f"runs/capability-probes/{bytes_digest(canonical_bytes((input_digest, state.started_at_epoch)))}"
valid = (
state.schema_version == RETENTION_PROBE_STATE_SCHEMA
and state.input_digest == input_digest
and state.input_bytes_read == input_bytes_read
and state.durable_store_identity == self._durable_identity
and state.transient_store_identity == self._transient_identity
and state.transient_bucket == self._transient.settings.bucket
and state.state_digest == derive_retention_state_digest(state)
and state.current_key == f"{expected_base}/current.json"
and state.noncurrent_key == f"{expected_base}/noncurrent.json"
and valid_version_id(state.current_version_id)
and valid_version_id(state.noncurrent_version_id)
and valid_version_id(state.successor_version_id)
and state.noncurrent_version_id != state.successor_version_id
and current_days is not None
and noncurrent_days is not None
and state.current_deadline_epoch == state.started_at_epoch + current_days * _DAY_SECONDS
and state.noncurrent_deadline_epoch == state.started_at_epoch + noncurrent_days * _DAY_SECONDS
)
if not valid:
raise CustodyCapabilityError(CustodyProbeErrorReason.STATE_MISMATCH)
def _probe_durable(self, input_digest: str, state_digest: str) -> list[ProbeResult]:
key = f"custody/capability-probes/{bytes_digest(canonical_bytes((input_digest, state_digest)))}/head.json"
first_body = probe_body("durable-head", input_digest, 0)
first = self._durable.write(key, first_body, absent=True)
if first.receipt is None:
reason = self._write_reason(first, ProbeResultReason.CONDITIONAL_CREATE_UNSUPPORTED)
return [failed_result(ProbeResultName.CONDITIONAL_CREATE, reason), *self._dependent_results()]
duplicate = self._durable.write(key, probe_body("durable-duplicate", input_digest, 0), absent=True)
original = self._durable.read(key)
original_matches = original.body == first_body and original.receipt == first.receipt
if not duplicate.is_conflict or not original_matches:
reason = self._write_reason(duplicate, ProbeResultReason.CONDITIONAL_CREATE_UNSUPPORTED)
if original.reason is not ProbeResultReason.NONE:
reason = original.reason
elif duplicate.is_conflict and not original_matches:
reason = ProbeResultReason.READBACK_MISMATCH
return [failed_result(ProbeResultName.CONDITIONAL_CREATE, reason), *self._dependent_results()]
results = [passed_result(ProbeResultName.CONDITIONAL_CREATE)]
second_body = probe_body("durable-head", input_digest, 1)
second = self._durable.write(key, second_body, token=first.receipt.storage_token)
if second.receipt is None:
reason = self._write_reason(second, ProbeResultReason.CONDITIONAL_UPDATE_UNSUPPORTED)
return [*results, failed_result(ProbeResultName.CONDITIONAL_UPDATE, reason), *self._dependent_results(skip=1)]
results.append(passed_result(ProbeResultName.CONDITIONAL_UPDATE))
race = self._race(key, input_digest, second.receipt.storage_token)
results.append(race[0])
if race[1] is None:
return [*results, *self._dependent_results(skip=2)]
winner, winner_body = race[1]
versions, reason = self._durable.version_ids(key)
expected_versions = (first.receipt.version_id, second.receipt.version_id, winner.version_id)
if versions is None:
results.append(failed_result(ProbeResultName.VERSION_VISIBILITY, reason))
elif not self._has_exact_versions(versions, expected_versions):
results.append(failed_result(ProbeResultName.VERSION_VISIBILITY, ProbeResultReason.VERSION_NOT_VISIBLE))
else:
results.append(passed_result(ProbeResultName.VERSION_VISIBILITY))
readback = self._durable.read(key)
results.append(self._read_result(ProbeResultName.COMMITTED_SUCCESSOR_REREAD, readback, winner, winner_body))
restarted = ProbeIO(self._durable.settings, self._durable_client).read(key)
restart = self._read_result(ProbeResultName.RESTART_RECOVERY, restarted, winner, winner_body)
if restart.reason is ProbeResultReason.READBACK_MISMATCH:
restart = failed_result(ProbeResultName.RESTART_RECOVERY, ProbeResultReason.RESTART_MISMATCH)
results.append(restart)
return results
@staticmethod
def _has_exact_versions(versions: tuple[str, ...], expected: tuple[str, ...]) -> bool:
return len(expected) == len(set(expected)) and len(versions) == len(expected) and set(versions) == set(expected)
@staticmethod
def _write_reason(attempt: WriteAttempt, unsupported: ProbeResultReason) -> ProbeResultReason:
if attempt.is_conflict:
return unsupported
if attempt.reason in {ProbeResultReason.STORE_FAILURE, ProbeResultReason.UNREADABLE_RESPONSE}:
return attempt.reason
return unsupported
@staticmethod
def _dependent_results(skip: int = 0) -> list[ProbeResult]:
names = tuple(ProbeResultName)[2 + skip : 6]
return [failed_result(name, ProbeResultReason.DEPENDENCY_FAILED) for name in names]
def _race(self, key: str, input_digest: str, token: str) -> tuple[ProbeResult, tuple[WriteReceipt, bytes] | None]:
bodies = (probe_body("durable-race-a", input_digest, 2), probe_body("durable-race-b", input_digest, 2))
with ThreadPoolExecutor(max_workers=2) as executor:
attempts = tuple(executor.map(lambda body: self._durable.write(key, body, token=token), bodies))
winners = tuple((item.receipt, body) for item, body in zip(attempts, bodies, strict=True) if item.receipt is not None)
conflicts = sum(item.is_conflict for item in attempts)
if len(winners) == 1 and conflicts == 1:
return passed_result(ProbeResultName.CONCURRENT_SINGLE_WINNER), winners[0]
if any(item.reason is ProbeResultReason.UNREADABLE_RESPONSE for item in attempts):
reason = ProbeResultReason.UNREADABLE_RESPONSE
elif any(item.reason is ProbeResultReason.STORE_FAILURE and not item.is_conflict for item in attempts):
reason = ProbeResultReason.STORE_FAILURE
else:
reason = ProbeResultReason.CONFLICT_NOT_ENFORCED
return failed_result(ProbeResultName.CONCURRENT_SINGLE_WINNER, reason), None
@staticmethod
def _read_result(name: ProbeResultName, read: ReadAttempt, receipt: WriteReceipt, body: bytes) -> ProbeResult:
if read.reason is not ProbeResultReason.NONE:
return failed_result(name, read.reason)
if read.is_absent or read.body != body or read.receipt != receipt:
return failed_result(name, ProbeResultReason.READBACK_MISMATCH)
return passed_result(name)
def _probe_retention(self, state: RetentionProbeState, current_epoch: int) -> list[ProbeResult]:
expected = probe_body("retention-current", state.input_digest, 0)
current = self._transient.read(state.current_key)
if current_epoch < state.current_deadline_epoch:
current_result = self._before_current_deadline(current, state, expected)
else:
current_result = self._after_current_deadline(current)
versions, reason = self._transient.version_ids(state.noncurrent_key)
noncurrent_result = self._noncurrent_result(versions, reason, state, current_epoch)
return [current_result, noncurrent_result]
@staticmethod
def _before_current_deadline(read: ReadAttempt, state: RetentionProbeState, expected: bytes) -> ProbeResult:
if read.reason is not ProbeResultReason.NONE:
return failed_result(ProbeResultName.CURRENT_EXPIRY, read.reason)
if read.is_absent:
return failed_result(ProbeResultName.CURRENT_EXPIRY, ProbeResultReason.PREMATURE_EXPIRY)
if read.body != expected or read.receipt is None or read.receipt.version_id != state.current_version_id:
return failed_result(ProbeResultName.CURRENT_EXPIRY, ProbeResultReason.READBACK_MISMATCH)
return ProbeResult(ProbeResultName.CURRENT_EXPIRY, ProbeResultStatus.PENDING, ProbeResultReason.DEADLINE_PENDING)
@staticmethod
def _after_current_deadline(read: ReadAttempt) -> ProbeResult:
if read.reason is not ProbeResultReason.NONE:
return failed_result(ProbeResultName.CURRENT_EXPIRY, read.reason)
if read.is_absent:
return passed_result(ProbeResultName.CURRENT_EXPIRY)
return failed_result(ProbeResultName.CURRENT_EXPIRY, ProbeResultReason.EXPIRY_DEADLINE_MISSED)
@staticmethod
def _noncurrent_result(
versions: tuple[str, ...] | None,
reason: ProbeResultReason,
state: RetentionProbeState,
current_epoch: int,
) -> ProbeResult:
if versions is None:
return failed_result(ProbeResultName.NONCURRENT_EXPIRY, reason)
is_visible = state.noncurrent_version_id in versions
if current_epoch < state.noncurrent_deadline_epoch:
if not is_visible:
return failed_result(ProbeResultName.NONCURRENT_EXPIRY, ProbeResultReason.PREMATURE_EXPIRY)
return ProbeResult(
ProbeResultName.NONCURRENT_EXPIRY,
ProbeResultStatus.PENDING,
ProbeResultReason.DEADLINE_PENDING,
)
if is_visible:
return failed_result(ProbeResultName.NONCURRENT_EXPIRY, ProbeResultReason.EXPIRY_DEADLINE_MISSED)
return passed_result(ProbeResultName.NONCURRENT_EXPIRY)
+15
View File
@@ -303,6 +303,21 @@ def _same_namespace(durable: StoreSettings, transient: StoreSettings) -> bool:
return _endpoint_namespace(durable.endpoint) == _endpoint_namespace(transient.endpoint) and durable.bucket == transient.bucket
def store_namespace_identity(settings: StoreSettings) -> str:
"""Bind one non-secret purpose namespace without serializing runtime values."""
if type(settings) is not StoreSettings:
raise StoreConfigurationError(StorePurpose.DURABLE, StoreConfigurationReason.INVALID, ("store_settings",))
try:
endpoint_namespace = _endpoint_namespace(settings.endpoint)
except ValueError:
raise StoreConfigurationError(settings.purpose, StoreConfigurationReason.INVALID, ("endpoint",)) from None
value: JsonValue = {
"endpoint_namespace": endpoint_namespace,
"bucket": settings.bucket,
}
return bytes_digest(canonical_bytes(value))
def _positive_days(value: object) -> bool:
return not isinstance(value, bool) and isinstance(value, int) and value > 0
+533
View File
@@ -0,0 +1,533 @@
"""Durable custody capability and retention probe tests."""
from __future__ import annotations
import io
import json
import sys
import threading
import traceback
from dataclasses import replace
from hashlib import sha256
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from benchmarks.valid import custody_probe_contract as contract # noqa: E402
from benchmarks.valid import custody_store as custody # noqa: E402
from benchmarks.valid.custody_probe_io import ProbeIO # noqa: E402
from benchmarks.valid.store_configuration import ( # noqa: E402
RetentionProfile,
StorePurpose,
StoreSettings,
store_namespace_identity,
)
class _ProviderError(Exception):
def __init__(self, code: str, secret: str = "provider password=/home/private") -> None:
self.response = {"Error": {"Code": code, "Message": secret}}
super().__init__(secret)
class _Version:
def __init__(self, version_id: str, body: bytes, etag: str) -> None:
self.version_id = version_id
self.body = body
self.etag = etag
class _Client:
def __init__(self) -> None:
self._lock = threading.Lock()
self._next_version = 1
self.versions: dict[tuple[str, str], list[_Version]] = {}
self.hidden_current: set[tuple[str, str]] = set()
self.calls: list[str] = []
self.allow_two_winners = False
self.ignore_if_none_match = False
self.invalid_read = False
self.provider_failure = False
self.fixed_version_id: str | None = None
self.exact_delete_marker_version_id: str | None = None
self.version_listing_overrides: dict[str, object] = {}
def put_object(self, **kwargs: object) -> dict[str, object]:
self.calls.append("put_object")
if self.provider_failure:
raise _ProviderError("InternalError")
bucket, key = str(kwargs["Bucket"]), str(kwargs["Key"])
body = kwargs["Body"]
assert isinstance(body, bytes)
with self._lock:
versions = self.versions.setdefault((bucket, key), [])
current = versions[-1] if versions and (bucket, key) not in self.hidden_current else None
if kwargs.get("IfNoneMatch") == "*" and current is not None and not self.ignore_if_none_match:
raise _ProviderError("PreconditionFailed")
expected = kwargs.get("IfMatch")
if expected is not None and not self.allow_two_winners:
if current is None or current.etag != expected:
raise _ProviderError("PreconditionFailed")
version_id = self.fixed_version_id or f"version-{self._next_version}"
self._next_version += 1
etag = sha256(body + version_id.encode()).hexdigest()
versions.append(_Version(version_id, body, etag))
self.hidden_current.discard((bucket, key))
return {"VersionId": version_id, "ETag": etag}
def get_object(self, **kwargs: object) -> dict[str, object]:
self.calls.append("get_object")
if self.provider_failure:
raise _ProviderError("InternalError")
bucket, key = str(kwargs["Bucket"]), str(kwargs["Key"])
if (bucket, key) in self.hidden_current:
raise _ProviderError("NoSuchKey")
versions = self.versions.get((bucket, key), [])
requested = kwargs.get("VersionId")
matching = [item for item in versions if requested is None or item.version_id == requested]
if not matching:
raise _ProviderError("NoSuchKey")
version = matching[-1]
if self.invalid_read:
return {"Body": io.BytesIO(b""), "ContentLength": 0}
return {
"Body": io.BytesIO(version.body),
"ContentLength": len(version.body),
"VersionId": version.version_id,
"ETag": version.etag,
}
def list_object_versions(self, **kwargs: object) -> dict[str, object]:
self.calls.append("list_object_versions")
bucket, key = str(kwargs["Bucket"]), str(kwargs["Prefix"])
versions = self.versions.get((bucket, key), [])
values = [
{
"Key": key,
"VersionId": item.version_id,
"ETag": item.etag,
"Size": len(item.body),
"IsLatest": index == len(versions) - 1 and (bucket, key) not in self.hidden_current,
}
for index, item in enumerate(versions)
]
markers: list[object] = []
if self.exact_delete_marker_version_id is not None:
markers.append({"Key": key, "VersionId": self.exact_delete_marker_version_id})
response: dict[str, object] = {"Versions": values, "DeleteMarkers": markers, "IsTruncated": False}
response.update(self.version_listing_overrides)
return response
def expire_current(self, bucket: str, key: str) -> None:
self.hidden_current.add((bucket, key))
def expire_version(self, bucket: str, key: str, version_id: str) -> None:
versions = self.versions[(bucket, key)]
self.versions[(bucket, key)] = [item for item in versions if item.version_id != version_id]
def _settings(purpose: StorePurpose) -> StoreSettings:
suffix = purpose.value
return StoreSettings(
purpose,
f"https://{suffix}.invalid:9000",
f"valid-benchmark-{suffix}",
"ACCESS-SECRET",
"SECRET-SECRET",
)
def _profile() -> RetentionProfile:
return RetentionProfile(
StorePurpose.TRANSIENT,
versioning_required=True,
conditional_create_required=True,
conditional_update_required=True,
current_version_expiry_days=2,
noncurrent_version_expiry_days=1,
)
def _service(durable: _Client, transient: _Client) -> custody.S3CustodyCapabilityProbe:
return custody.S3CustodyCapabilityProbe(
_settings(StorePurpose.DURABLE),
durable,
_settings(StorePurpose.TRANSIENT),
transient,
_profile(),
)
def _finish_retention(client: _Client, state: contract.RetentionProbeState) -> None:
client.expire_current(state.transient_bucket, state.current_key)
client.expire_version(state.transient_bucket, state.noncurrent_key, state.noncurrent_version_id)
def _expected_store_identities() -> tuple[str, str]:
return (
store_namespace_identity(_settings(StorePurpose.DURABLE)),
store_namespace_identity(_settings(StorePurpose.TRANSIENT)),
)
def test_store_identity_binds_namespace_without_credentials() -> None:
durable = _settings(StorePurpose.DURABLE)
rotated = StoreSettings(
StorePurpose.DURABLE,
durable.endpoint,
durable.bucket,
"ROTATED-ACCESS",
"ROTATED-SECRET",
)
assert store_namespace_identity(durable) == store_namespace_identity(rotated)
assert durable.access_key_id not in store_namespace_identity(durable)
assert durable.secret_access_key not in store_namespace_identity(durable)
def test_probe_passes_every_mandatory_result_after_recorded_expiry() -> None:
durable, transient = _Client(), _Client()
service = _service(durable, transient)
probe_input = b"nonzero-custody-capability-input"
state = service.prepare_retention_probe(probe_input, current_epoch=1_000)
pending = service.probe(probe_input, state, current_epoch=1_001)
_finish_retention(transient, state)
report = service.probe(
probe_input,
state,
current_epoch=state.current_deadline_epoch,
prior_report=pending,
)
assert report.status is contract.CustodyCapabilityStatus.READY
assert report.input_bytes_read == len(probe_input)
assert tuple(result.name for result in report.results) == tuple(contract.MANDATORY_PROBE_RESULTS)
assert all(result.status is contract.ProbeResultStatus.PASSED for result in report.results)
assert report.may_admit_real_population is True
contract.require_real_population_admission(report, *_expected_store_identities(), _profile())
encoded = contract.canonical_custody_capability_report_bytes(report)
payload = json.loads(encoded)
assert payload["schema_version"] == contract.CUSTODY_CAPABILITY_REPORT_SCHEMA
assert payload["input_bytes_read"] == len(probe_input)
assert payload["report_digest"] == report.report_digest
assert set(durable.calls + transient.calls) <= {"put_object", "get_object", "list_object_versions"}
def test_before_deadlines_is_pending_and_cannot_authorize_admission() -> None:
durable, transient = _Client(), _Client()
service = _service(durable, transient)
probe_input = b"pending-retention-input"
state = service.prepare_retention_probe(probe_input, current_epoch=2_000)
report = service.probe(probe_input, state, current_epoch=2_001)
assert report.status is contract.CustodyCapabilityStatus.PENDING
retention = {result.name: result for result in report.results}
assert retention[contract.ProbeResultName.CURRENT_EXPIRY].status is contract.ProbeResultStatus.PENDING
assert retention[contract.ProbeResultName.NONCURRENT_EXPIRY].status is contract.ProbeResultStatus.PENDING
assert report.may_admit_real_population is False
with pytest.raises(contract.RealPopulationAdmissionDisabled):
contract.require_real_population_admission(report, *_expected_store_identities(), _profile())
@pytest.mark.parametrize("expired", ("current", "noncurrent"))
def test_premature_retention_is_a_failed_measurement(expired: str) -> None:
durable, transient = _Client(), _Client()
service = _service(durable, transient)
probe_input = f"premature-{expired}".encode()
state = service.prepare_retention_probe(probe_input, current_epoch=3_000)
if expired == "current":
transient.expire_current(state.transient_bucket, state.current_key)
else:
transient.expire_version(state.transient_bucket, state.noncurrent_key, state.noncurrent_version_id)
report = service.probe(probe_input, state, current_epoch=3_001)
assert report.status is contract.CustodyCapabilityStatus.UNSUPPORTED
result = next(item for item in report.results if item.name.value == f"{expired}_expiry")
assert result.reason is contract.ProbeResultReason.PREMATURE_EXPIRY
assert report.may_admit_real_population is False
def test_expiry_deadline_miss_is_failed_not_pending() -> None:
service = _service(_Client(), _Client())
probe_input = b"deadline-miss"
state = service.prepare_retention_probe(probe_input, current_epoch=4_000)
pending = service.probe(probe_input, state, current_epoch=4_001)
report = service.probe(probe_input, state, state.current_deadline_epoch, prior_report=pending)
assert report.status is contract.CustodyCapabilityStatus.UNSUPPORTED
reasons = {item.reason for item in report.results}
assert contract.ProbeResultReason.EXPIRY_DEADLINE_MISSED in reasons
def test_two_writer_ambiguity_disables_admission() -> None:
durable, transient = _Client(), _Client()
durable.allow_two_winners = True
service = _service(durable, transient)
probe_input = b"two-writer-ambiguity"
state = service.prepare_retention_probe(probe_input, current_epoch=5_000)
_finish_retention(transient, state)
report = service.probe(probe_input, state, current_epoch=state.current_deadline_epoch)
result = next(item for item in report.results if item.name is contract.ProbeResultName.CONCURRENT_SINGLE_WINNER)
assert result.status is contract.ProbeResultStatus.FAILED
assert result.reason is contract.ProbeResultReason.CONFLICT_NOT_ENFORCED
assert report.status is contract.CustodyCapabilityStatus.UNSUPPORTED
def test_ignored_conditional_create_is_detected_and_cannot_authorize() -> None:
durable, transient = _Client(), _Client()
durable.ignore_if_none_match = True
service = _service(durable, transient)
probe_input = b"ignored-if-none-match"
state = service.prepare_retention_probe(probe_input, current_epoch=5_500)
report = service.probe(probe_input, state, current_epoch=5_501)
result = next(item for item in report.results if item.name is contract.ProbeResultName.CONDITIONAL_CREATE)
assert result.status is contract.ProbeResultStatus.FAILED
assert result.reason is contract.ProbeResultReason.CONDITIONAL_CREATE_UNSUPPORTED
assert report.may_admit_real_population is False
def test_constant_durable_version_id_fails_visibility_and_admission() -> None:
durable, transient = _Client(), _Client()
durable.fixed_version_id = "constant-version"
service = _service(durable, transient)
probe_input = b"constant-durable-version"
state = service.prepare_retention_probe(probe_input, current_epoch=5_600)
report = service.probe(probe_input, state, current_epoch=5_601)
visibility = next(item for item in report.results if item.name is contract.ProbeResultName.VERSION_VISIBILITY)
assert visibility.status is contract.ProbeResultStatus.FAILED
assert report.may_admit_real_population is False
@pytest.mark.parametrize("version_id", ("constant-version", "null"))
def test_transient_version_id_without_real_succession_fails_preparation(version_id: str) -> None:
transient = _Client()
transient.fixed_version_id = version_id
with pytest.raises(contract.CustodyCapabilityError) as caught:
_service(_Client(), transient).prepare_retention_probe(b"invalid-transient-version", current_epoch=5_650)
assert caught.value.reason is contract.CustodyProbeErrorReason.UNREADABLE_RESPONSE
def test_final_retention_without_bound_predeadline_presence_cannot_be_ready() -> None:
durable, transient = _Client(), _Client()
service = _service(durable, transient)
probe_input = b"missing-presence-evidence"
state = service.prepare_retention_probe(probe_input, current_epoch=5_700)
_finish_retention(transient, state)
report = service.probe(probe_input, state, current_epoch=state.current_deadline_epoch)
assert report.status is contract.CustodyCapabilityStatus.UNSUPPORTED
retention = report.results[-2:]
assert all(item.reason is contract.ProbeResultReason.PRESENCE_EVIDENCE_MISSING for item in retention)
@pytest.mark.parametrize(
"delete_markers",
(
[{"Key": "probe-key", "VersionId": "null"}],
[{"Key": "probe-key", "VersionId": "marker-1"}],
[{"Key": "wrong-key", "VersionId": "marker-1"}],
["malformed-marker"],
),
)
def test_version_listing_rejects_every_delete_marker(delete_markers: list[object]) -> None:
client = _Client()
client.version_listing_overrides["DeleteMarkers"] = delete_markers
version_ids, reason = ProbeIO(_settings(StorePurpose.DURABLE), client).version_ids("probe-key")
assert version_ids is None
assert reason is contract.ProbeResultReason.UNREADABLE_RESPONSE
@pytest.mark.parametrize(
"listing_overrides",
(
{"IsTruncated": True},
{"Versions": [{"Key": "wrong-key", "VersionId": "version-1"}]},
{"Versions": [{"Key": "probe-key", "VersionId": "null"}]},
{"Versions": ["malformed-version"]},
),
)
def test_version_listing_rejects_ambiguous_or_malformed_versions(listing_overrides: dict[str, object]) -> None:
client = _Client()
client.version_listing_overrides.update(listing_overrides)
version_ids, reason = ProbeIO(_settings(StorePurpose.DURABLE), client).version_ids("probe-key")
assert version_ids is None
assert reason is contract.ProbeResultReason.UNREADABLE_RESPONSE
def test_null_delete_marker_is_instrument_failure_and_cannot_authorize() -> None:
durable, transient = _Client(), _Client()
service = _service(durable, transient)
probe_input = b"null-delete-marker"
state = service.prepare_retention_probe(probe_input, current_epoch=5_800)
durable.exact_delete_marker_version_id = "null"
report = service.probe(probe_input, state, current_epoch=5_801)
assert report.status is contract.CustodyCapabilityStatus.INSTRUMENT_FAILURE
assert report.may_admit_real_population is False
assert contract.ProbeResultReason.UNREADABLE_RESPONSE in {item.reason for item in report.results}
with pytest.raises(contract.RealPopulationAdmissionDisabled):
contract.require_real_population_admission(report, *_expected_store_identities(), _profile())
def test_unreadable_response_is_instrument_failure_and_diagnostics_are_closed() -> None:
durable, transient = _Client(), _Client()
service = _service(durable, transient)
probe_input = b"unreadable-response"
state = service.prepare_retention_probe(probe_input, current_epoch=6_000)
_finish_retention(transient, state)
durable.invalid_read = True
report = service.probe(probe_input, state, current_epoch=state.current_deadline_epoch)
assert report.status is contract.CustodyCapabilityStatus.INSTRUMENT_FAILURE
assert contract.ProbeResultReason.UNREADABLE_RESPONSE in {item.reason for item in report.results}
rendered = repr(report) + str(report)
assert "password" not in rendered
assert "/home/private" not in rendered
def test_provider_exceptions_do_not_escape_in_report_or_exception_chain() -> None:
durable, transient = _Client(), _Client()
transient.provider_failure = True
with pytest.raises(contract.CustodyCapabilityError) as caught:
_service(durable, transient).prepare_retention_probe(b"provider-failure", current_epoch=7_000)
rendered = "".join(traceback.format_exception(caught.value))
assert caught.value.reason is contract.CustodyProbeErrorReason.STORE_FAILURE
assert "password" not in rendered
assert "/home/private" not in rendered
assert caught.value.__cause__ is None
assert caught.value.__context__ is None
@pytest.mark.parametrize("probe_input", (b"", bytearray(b"not-bytes")))
def test_empty_or_invalid_probe_input_fails_before_store_access(probe_input: object) -> None:
durable, transient = _Client(), _Client()
with pytest.raises(contract.CustodyCapabilityError) as caught:
_service(durable, transient).prepare_retention_probe(probe_input, current_epoch=8_000) # type: ignore[arg-type]
assert caught.value.reason is contract.CustodyProbeErrorReason.INVALID_INPUT
assert durable.calls == transient.calls == []
def test_tampered_or_mismatched_retention_state_is_refused() -> None:
durable, transient = _Client(), _Client()
service = _service(durable, transient)
state = service.prepare_retention_probe(b"state-binding", current_epoch=9_000)
with pytest.raises(contract.CustodyCapabilityError) as mismatched:
service.probe(b"different-input", state, current_epoch=9_001)
assert mismatched.value.reason is contract.CustodyProbeErrorReason.STATE_MISMATCH
state.__dict__["current_key"] = "runs/forged/current.json"
with pytest.raises(contract.CustodyCapabilityError) as tampered:
service.probe(b"state-binding", state, current_epoch=9_001)
assert tampered.value.reason is contract.CustodyProbeErrorReason.STATE_MISMATCH
@pytest.mark.parametrize("invalid_versions", ("null", "aliased"))
def test_rehashed_invalid_retention_version_state_is_refused(invalid_versions: str) -> None:
service = _service(_Client(), _Client())
probe_input = b"invalid-version-state"
state = service.prepare_retention_probe(probe_input, current_epoch=9_500)
if invalid_versions == "null":
forged = replace(state, noncurrent_version_id="null", state_digest="")
else:
forged = replace(state, successor_version_id=state.noncurrent_version_id, state_digest="")
forged = replace(forged, state_digest=contract.derive_retention_state_digest(forged))
with pytest.raises(contract.CustodyCapabilityError) as caught:
service.probe(probe_input, forged, current_epoch=9_501)
assert caught.value.reason is contract.CustodyProbeErrorReason.STATE_MISMATCH
def test_report_validation_rejects_missing_result_or_forged_digest() -> None:
durable, transient = _Client(), _Client()
service = _service(durable, transient)
probe_input = b"report-validation"
state = service.prepare_retention_probe(probe_input, current_epoch=10_000)
pending = service.probe(probe_input, state, current_epoch=10_001)
_finish_retention(transient, state)
report = service.probe(probe_input, state, state.current_deadline_epoch, prior_report=pending)
report.__dict__["results"] = report.results[:-1]
with pytest.raises(contract.RealPopulationAdmissionDisabled):
contract.require_real_population_admission(report, *_expected_store_identities(), _profile())
clean_report = service.probe(b"second-report-input", service.prepare_retention_probe(b"second-report-input", 20_000), 20_001)
clean_report.__dict__["report_digest"] = "0" * 64
with pytest.raises(contract.RealPopulationAdmissionDisabled):
contract.require_real_population_admission(clean_report, *_expected_store_identities(), _profile())
def test_report_cannot_be_substituted_across_store_namespaces() -> None:
durable, transient = _Client(), _Client()
service = _service(durable, transient)
probe_input = b"namespace-binding"
state = service.prepare_retention_probe(probe_input, current_epoch=30_000)
pending = service.probe(probe_input, state, current_epoch=30_001)
_finish_retention(transient, state)
report = service.probe(probe_input, state, state.current_deadline_epoch, prior_report=pending)
alternate = StoreSettings(
StorePurpose.DURABLE,
"https://other-durable.invalid:9000",
"other-valid-benchmark-durable",
"OTHER-ACCESS",
"OTHER-SECRET",
)
with pytest.raises(contract.RealPopulationAdmissionDisabled):
contract.require_real_population_admission(
report,
store_namespace_identity(alternate),
_expected_store_identities()[1],
_profile(),
)
@pytest.mark.parametrize(
"mismatched_profile",
(
replace(_profile(), current_version_expiry_days=3),
replace(_profile(), noncurrent_version_expiry_days=2),
),
)
def test_ready_report_requires_exact_typed_retention_profile(mismatched_profile: RetentionProfile) -> None:
durable, transient = _Client(), _Client()
service = _service(durable, transient)
probe_input = b"retention-policy-binding"
state = service.prepare_retention_probe(probe_input, current_epoch=40_000)
pending = service.probe(probe_input, state, current_epoch=40_001)
_finish_retention(transient, state)
report = service.probe(probe_input, state, state.current_deadline_epoch, prior_report=pending)
with pytest.raises(contract.RealPopulationAdmissionDisabled):
contract.require_real_population_admission(
report,
*_expected_store_identities(),
mismatched_profile,
)
contract.require_real_population_admission(report, *_expected_store_identities(), _profile())