mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-04 02:38:18 +00:00
feat(valid-detection-benchmark): probe custody store capabilities
This commit is contained in:
@@ -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")
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user