mirror of
https://github.com/norandom/OpenUltraSAST.git
synced 2026-12-04 02:38:18 +00:00
feat(valid-detection-benchmark): freeze exact observation checkpoints
This commit is contained in:
@@ -183,7 +183,7 @@
|
|||||||
- Done when an adapter receives all required label-blind inputs and tests prove no forbidden reference, byte sequence, credential, or environment variable crosses the process boundary.
|
- Done when an adapter receives all required label-blind inputs and tests prove no forbidden reference, byte sequence, credential, or environment variable crosses the process boundary.
|
||||||
- _Requirements: 5.3, 5.5, 5.6, 9.1, 10.3, 10.4, 10.6_
|
- _Requirements: 5.3, 5.5, 5.6, 9.1, 10.3, 10.4, 10.6_
|
||||||
- _Boundary: Isolated Arm Executor_
|
- _Boundary: Isolated Arm Executor_
|
||||||
- [ ] 6.4 Freeze complete observations with nonzero execution receipts and exact resume
|
- [x] 6.4 Freeze complete observations with nonzero execution receipts and exact resume
|
||||||
- Record nonzero reads, required-stage execution, runtime, budgets, degradations, input-set identity, and output identity in a canonical execution receipt.
|
- Record nonzero reads, required-stage execution, runtime, budgets, degradations, input-set identity, and output identity in a canonical execution receipt.
|
||||||
- Validate and durably freeze one custodian-sealed observation set for every planned component arm before spend.
|
- Validate and durably freeze one custodian-sealed observation set for every planned component arm before spend.
|
||||||
- Reuse only an exact digest-matching completed checkpoint; never treat a missing/mismatched checkpoint as complete or silently rerun a completed arm under the same plan.
|
- Reuse only an exact digest-matching completed checkpoint; never treat a missing/mismatched checkpoint as complete or silently rerun a completed arm under the same plan.
|
||||||
@@ -432,3 +432,4 @@
|
|||||||
- Task 6.1 delegates plan and baseline algebra exclusively to detection-core V3 while binding separate arm roles and lifecycle identity; every parked-arm factory, validator, and serializer path re-resolves an exact independently reviewed strategy-decision authority, and access control remains unconditionally excluded.
|
- Task 6.1 delegates plan and baseline algebra exclusively to detection-core V3 while binding separate arm roles and lifecycle identity; every parked-arm factory, validator, and serializer path re-resolves an exact independently reviewed strategy-decision authority, and access control remains unconditionally excluded.
|
||||||
- Task 6.2 derives closed UNION or INTERSECTION observations only from complete scope-compatible component sets, preserves every component independently, and retains proof continuity only when all anchors match and the exact proof scope belongs to the combined arm; deterministic re-derivation rejects forged or unrelated proof authority.
|
- Task 6.2 derives closed UNION or INTERSECTION observations only from complete scope-compatible component sets, preserves every component independently, and retains proof continuity only when all anchors match and the exact proof scope belongs to the combined arm; deterministic re-derivation rejects forged or unrelated proof authority.
|
||||||
- Task 6.3 builds identical ordered component bundles only after controller-side revalidation of the exact registered plan and a metadata-only execution-source projection freshly derived from reviewed Task 4.3/4.4 and ordinary-selection authorities; adapters receive only sanitized label-blind data, and every authorizing serialization/execution path rejects rehashed source or plan substitutions without opening sealed material.
|
- Task 6.3 builds identical ordered component bundles only after controller-side revalidation of the exact registered plan and a metadata-only execution-source projection freshly derived from reviewed Task 4.3/4.4 and ordinary-selection authorities; adapters receive only sanitized label-blind data, and every authorizing serialization/execution path rejects rehashed source or plan substitutions without opening sealed material.
|
||||||
|
- Task 6.4 freezes one exact custodian-sealed core V3 observation checkpoint per component only after canonical nonzero read/stage receipts and exact repository readback; construction, freeze, and resume bind the completed process outcome and every bundle/read identity, while missing, incomplete, or mismatched checkpoints remain impaired without rerunning the adapter.
|
||||||
|
|||||||
@@ -0,0 +1,517 @@
|
|||||||
|
"""Durable custodian-sealed checkpoints for isolated component observations."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from enum import StrEnum
|
||||||
|
from typing import Protocol, cast
|
||||||
|
|
||||||
|
from benchmarks.valid.arm_contract import RegisteredEvaluationPlanV1
|
||||||
|
from benchmarks.valid.artifact_repository import (
|
||||||
|
ArtifactReadAuthority,
|
||||||
|
ArtifactRepositoryError,
|
||||||
|
ArtifactRepositoryReason,
|
||||||
|
S3ArtifactRepository,
|
||||||
|
)
|
||||||
|
from benchmarks.valid.isolated_execution import ArmProcessOutcomeV1
|
||||||
|
from benchmarks.valid.isolated_execution_bundle import (
|
||||||
|
LabelBlindExecutionBundleV1,
|
||||||
|
label_blind_execution_bundle_bytes,
|
||||||
|
)
|
||||||
|
from benchmarks.valid.observation_receipt import (
|
||||||
|
ExecutionDegradation,
|
||||||
|
ExecutionReceiptError,
|
||||||
|
ExecutionReceiptV1,
|
||||||
|
InputReadReceiptV1,
|
||||||
|
ReceiptReason,
|
||||||
|
ReceiptStatus,
|
||||||
|
StageExecutionReceiptV1,
|
||||||
|
build_execution_receipt,
|
||||||
|
execution_receipt_from_value,
|
||||||
|
execution_receipt_value,
|
||||||
|
validate_execution_receipt_for_bundle,
|
||||||
|
)
|
||||||
|
from benchmarks.valid.ordinary_change_contract import OrdinarySelectionV1
|
||||||
|
from benchmarks.valid.population_label_blind_contract import LabelBlindPopulationManifestV3
|
||||||
|
from benchmarks.valid.population_material_contract import PublicPopulationMaterialManifestV1
|
||||||
|
from benchmarks.valid.replacement_artifact_contract import (
|
||||||
|
ArtifactAccessClass,
|
||||||
|
ArtifactKind,
|
||||||
|
ArtifactReference,
|
||||||
|
artifact_reference,
|
||||||
|
canonical_artifact_bytes,
|
||||||
|
)
|
||||||
|
from openultrasast.core import canonical
|
||||||
|
from openultrasast.core.canonical import ContentResolver, JsonValue
|
||||||
|
from openultrasast.core.evaluation_measurement import ArmConfigurationV3, ArmKindV3
|
||||||
|
from openultrasast.core.evaluation_observation import (
|
||||||
|
ArmObservationSetV3,
|
||||||
|
EvaluationObservationError,
|
||||||
|
decode_arm_observation_set,
|
||||||
|
encode_arm_observation_set,
|
||||||
|
)
|
||||||
|
from openultrasast.core.evaluation_plan import ExpectedObservationSlotV3
|
||||||
|
from openultrasast.core.factpack import ReviewIndependencePolicy
|
||||||
|
|
||||||
|
CHECKPOINT_SCHEMA = "openultrasast.valid-detection-benchmark.component-observation-checkpoint.v1"
|
||||||
|
OBSERVATION_OUTPUT_SCHEMA = "openultrasast.valid-detection-benchmark.component-observation-output.v1"
|
||||||
|
_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||||
|
_CHECKPOINT_FIELDS = frozenset(
|
||||||
|
{
|
||||||
|
"schema_version",
|
||||||
|
"status",
|
||||||
|
"checkpoint_digest",
|
||||||
|
"plan_digest",
|
||||||
|
"registration_digest",
|
||||||
|
"arm_id",
|
||||||
|
"bundle_digest",
|
||||||
|
"budget_digest",
|
||||||
|
"environment_digest",
|
||||||
|
"input_set_digest",
|
||||||
|
"output_destination_digest",
|
||||||
|
"output_digest",
|
||||||
|
"receipt_digest",
|
||||||
|
"observation_set_digest",
|
||||||
|
"execution_receipt",
|
||||||
|
"observations",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class CheckpointStatus(StrEnum):
|
||||||
|
COMPLETE = "complete"
|
||||||
|
IMPAIRED = "impaired"
|
||||||
|
|
||||||
|
|
||||||
|
class CheckpointReason(StrEnum):
|
||||||
|
NONE = "none"
|
||||||
|
BUNDLE_INVALID = "bundle_invalid"
|
||||||
|
ADAPTER_FAILURE = "adapter_failure"
|
||||||
|
CAPTURE_INVALID = "capture_invalid"
|
||||||
|
RECEIPT_IMPAIRED = "receipt_impaired"
|
||||||
|
RECEIPT_MISMATCH = "receipt_mismatch"
|
||||||
|
OBSERVATION_INVALID = "observation_invalid"
|
||||||
|
ARTIFACT_WRITE_FAILED = "artifact_write_failed"
|
||||||
|
ARTIFACT_READBACK_FAILED = "artifact_readback_failed"
|
||||||
|
CHECKPOINT_MISSING = "checkpoint_missing"
|
||||||
|
CHECKPOINT_UNAVAILABLE = "checkpoint_unavailable"
|
||||||
|
CHECKPOINT_MISMATCH = "checkpoint_mismatch"
|
||||||
|
CHECKPOINT_INCOMPLETE = "checkpoint_incomplete"
|
||||||
|
|
||||||
|
|
||||||
|
class ObservationCheckpointError(ValueError):
|
||||||
|
"""Checkpoint contracts are malformed or do not bind exact execution."""
|
||||||
|
|
||||||
|
|
||||||
|
class _IncompleteCheckpointError(ObservationCheckpointError):
|
||||||
|
"""A structurally valid checkpoint contains an impaired execution receipt."""
|
||||||
|
|
||||||
|
|
||||||
|
def _digest(value: object, field: str, *, optional: bool = False) -> str:
|
||||||
|
if optional and value == "":
|
||||||
|
return ""
|
||||||
|
if type(value) is not str or _DIGEST.fullmatch(value) is None:
|
||||||
|
raise ObservationCheckpointError(f"{field} must be a full lowercase SHA-256 digest")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ArmExecutionCaptureV1:
|
||||||
|
process_outcome: ArmProcessOutcomeV1
|
||||||
|
input_reads: tuple[InputReadReceiptV1, ...]
|
||||||
|
stage_executions: tuple[StageExecutionReceiptV1, ...]
|
||||||
|
degradations: tuple[ExecutionDegradation, ...]
|
||||||
|
observations: tuple[ArmObservationSetV3, ...]
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if type(self) is not ArmExecutionCaptureV1 or type(self.process_outcome) is not ArmProcessOutcomeV1:
|
||||||
|
raise ObservationCheckpointError("capture must use exact execution contracts")
|
||||||
|
self.process_outcome.__post_init__()
|
||||||
|
if type(self.input_reads) is not tuple or any(type(row) is not InputReadReceiptV1 for row in self.input_reads):
|
||||||
|
raise ObservationCheckpointError("capture input reads must use exact receipt values")
|
||||||
|
if type(self.stage_executions) is not tuple or any(type(row) is not StageExecutionReceiptV1 for row in self.stage_executions):
|
||||||
|
raise ObservationCheckpointError("capture stages must use exact receipt values")
|
||||||
|
if type(self.degradations) is not tuple or any(type(row) is not ExecutionDegradation for row in self.degradations):
|
||||||
|
raise ObservationCheckpointError("capture degradations must use exact closed values")
|
||||||
|
if type(self.observations) is not tuple or any(type(row) is not ArmObservationSetV3 for row in self.observations):
|
||||||
|
raise ObservationCheckpointError("capture observations must use exact core V3 values")
|
||||||
|
|
||||||
|
|
||||||
|
class ObservationCheckpointAdapter(Protocol):
|
||||||
|
def execute(self, bundle: LabelBlindExecutionBundleV1) -> ArmExecutionCaptureV1: ...
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CheckpointSelectorV1:
|
||||||
|
reference: ArtifactReference
|
||||||
|
checkpoint_digest: str
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if type(self) is not CheckpointSelectorV1 or type(self.reference) is not ArtifactReference:
|
||||||
|
raise ObservationCheckpointError("checkpoint selector must use exact reference contracts")
|
||||||
|
self.reference.__post_init__()
|
||||||
|
if self.reference.artifact_kind is not ArtifactKind.OBSERVATION:
|
||||||
|
raise ObservationCheckpointError("checkpoint selector must reference an observation artifact")
|
||||||
|
if self.reference.access_class is not ArtifactAccessClass.CUSTODIAN_SEALED:
|
||||||
|
raise ObservationCheckpointError("checkpoint selector must reference custodian-sealed content")
|
||||||
|
_digest(self.checkpoint_digest, "selected checkpoint")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ArmCheckpointResultV1:
|
||||||
|
status: CheckpointStatus
|
||||||
|
reason: CheckpointReason
|
||||||
|
plan_digest: str
|
||||||
|
arm_id: str
|
||||||
|
checkpoint_digest: str
|
||||||
|
reference: ArtifactReference | None
|
||||||
|
result_digest: str
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if (
|
||||||
|
type(self) is not ArmCheckpointResultV1
|
||||||
|
or type(self.status) is not CheckpointStatus
|
||||||
|
or type(self.reason) is not CheckpointReason
|
||||||
|
):
|
||||||
|
raise ObservationCheckpointError("checkpoint result must use exact closed contracts")
|
||||||
|
_digest(self.plan_digest, "result plan")
|
||||||
|
if type(self.arm_id) is not str or not self.arm_id:
|
||||||
|
raise ObservationCheckpointError("result arm id must be nonempty")
|
||||||
|
if self.status is CheckpointStatus.COMPLETE:
|
||||||
|
if self.reason is not CheckpointReason.NONE or type(self.reference) is not ArtifactReference:
|
||||||
|
raise ObservationCheckpointError("complete checkpoint result requires one exact reference")
|
||||||
|
CheckpointSelectorV1(self.reference, self.checkpoint_digest)
|
||||||
|
elif self.reason is CheckpointReason.NONE or self.reference is not None or self.checkpoint_digest:
|
||||||
|
raise ObservationCheckpointError("impaired checkpoint result cannot claim complete content")
|
||||||
|
expected = canonical.content_digest(_result_value(self, include_digest=False))
|
||||||
|
if not self.result_digest:
|
||||||
|
object.__setattr__(self, "result_digest", expected)
|
||||||
|
elif _digest(self.result_digest, "checkpoint result") != expected:
|
||||||
|
raise ObservationCheckpointError("checkpoint result digest does not match content")
|
||||||
|
|
||||||
|
|
||||||
|
def _reference_value(reference: ArtifactReference) -> dict[str, JsonValue]:
|
||||||
|
return {
|
||||||
|
"artifact_kind": reference.artifact_kind.value,
|
||||||
|
"access_class": reference.access_class.value,
|
||||||
|
"content_digest": reference.content_digest,
|
||||||
|
"byte_length": reference.byte_length,
|
||||||
|
"provenance_digest": reference.provenance_digest,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _result_value(value: ArmCheckpointResultV1, *, include_digest: bool) -> dict[str, JsonValue]:
|
||||||
|
result: dict[str, JsonValue] = {
|
||||||
|
"status": value.status.value,
|
||||||
|
"reason": value.reason.value,
|
||||||
|
"plan_digest": value.plan_digest,
|
||||||
|
"arm_id": value.arm_id,
|
||||||
|
"checkpoint_digest": value.checkpoint_digest or None,
|
||||||
|
"reference": None if value.reference is None else _reference_value(value.reference),
|
||||||
|
}
|
||||||
|
if include_digest:
|
||||||
|
result["result_digest"] = value.result_digest
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _impaired(bundle: LabelBlindExecutionBundleV1, reason: CheckpointReason) -> ArmCheckpointResultV1:
|
||||||
|
return ArmCheckpointResultV1(CheckpointStatus.IMPAIRED, reason, bundle.plan_digest, bundle.arm.arm_id, "", None, "")
|
||||||
|
|
||||||
|
|
||||||
|
def component_observation_output_bytes(observations: tuple[ArmObservationSetV3, ...]) -> bytes:
|
||||||
|
if type(observations) is not tuple or not observations or any(type(row) is not ArmObservationSetV3 for row in observations):
|
||||||
|
raise ObservationCheckpointError("component output must contain nonempty exact core V3 observations")
|
||||||
|
documents = tuple(encode_arm_observation_set(row).decode("utf-8") for row in observations)
|
||||||
|
return canonical.canonical_bytes({"schema_version": OBSERVATION_OUTPUT_SCHEMA, "observations": documents})
|
||||||
|
|
||||||
|
|
||||||
|
def _expected_slots(
|
||||||
|
plan: RegisteredEvaluationPlanV1,
|
||||||
|
bundle: LabelBlindExecutionBundleV1,
|
||||||
|
) -> tuple[ExpectedObservationSlotV3, ...]:
|
||||||
|
return tuple(row for row in plan.declaration.expected_observation_slots if row.arm_id == bundle.arm.arm_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _configuration(plan: RegisteredEvaluationPlanV1, arm_id: str) -> ArmConfigurationV3:
|
||||||
|
rows = tuple(row for row in plan.declaration.arm_configurations if row.arm_id == arm_id)
|
||||||
|
if len(rows) != 1 or rows[0].kind is not ArmKindV3.COMPONENT:
|
||||||
|
raise ObservationCheckpointError("checkpoint arm must resolve to one planned component")
|
||||||
|
return rows[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_observations(
|
||||||
|
plan: RegisteredEvaluationPlanV1,
|
||||||
|
bundle: LabelBlindExecutionBundleV1,
|
||||||
|
receipt: ExecutionReceiptV1,
|
||||||
|
observations: tuple[ArmObservationSetV3, ...],
|
||||||
|
) -> str:
|
||||||
|
slots = _expected_slots(plan, bundle)
|
||||||
|
configuration = _configuration(plan, bundle.arm.arm_id)
|
||||||
|
if tuple(row.slot_digest for row in observations) != tuple(row.slot_digest for row in slots):
|
||||||
|
raise ObservationCheckpointError("observations do not equal every expected component slot")
|
||||||
|
expected_inputs = tuple(row.input_identity_digest for row in bundle.case_inputs)
|
||||||
|
if tuple(row.input_identity_digest for row in observations) != expected_inputs:
|
||||||
|
raise ObservationCheckpointError("observations do not equal the ordered component input set")
|
||||||
|
for slot, row in zip(slots, observations, strict=True):
|
||||||
|
row.__post_init__()
|
||||||
|
expected = (
|
||||||
|
slot.arm_id,
|
||||||
|
slot.input_identity_digest,
|
||||||
|
slot.execution_identity,
|
||||||
|
configuration.registered_budget_digest,
|
||||||
|
configuration.configuration_identity_digest,
|
||||||
|
receipt.input_read_evidence_digest,
|
||||||
|
receipt.stage_execution_evidence_digest,
|
||||||
|
)
|
||||||
|
actual = (
|
||||||
|
row.arm_id,
|
||||||
|
row.input_identity_digest,
|
||||||
|
row.execution_identity,
|
||||||
|
row.registered_budget_digest,
|
||||||
|
row.configuration_digest,
|
||||||
|
row.input_read_evidence_digest,
|
||||||
|
row.stage_execution_evidence_digest,
|
||||||
|
)
|
||||||
|
if actual != expected:
|
||||||
|
raise ObservationCheckpointError("observation identity or instrument evidence differs from its planned slot")
|
||||||
|
if any(case.outcome_projection.policy is not configuration.case_outcome_policy for case in row.cases):
|
||||||
|
raise ObservationCheckpointError("observation outcome policy differs from the registered component")
|
||||||
|
output = component_observation_output_bytes(observations)
|
||||||
|
if canonical.bytes_digest(output) != receipt.output_digest or len(output) != receipt.output_bytes:
|
||||||
|
raise ObservationCheckpointError("observation output identity differs from the execution receipt")
|
||||||
|
return canonical.content_digest(
|
||||||
|
{"schema_version": CHECKPOINT_SCHEMA, "observation_digests": tuple(row.observation_digest for row in observations)}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _checkpoint_identity(
|
||||||
|
bundle: LabelBlindExecutionBundleV1,
|
||||||
|
receipt: ExecutionReceiptV1,
|
||||||
|
observation_set_digest: str,
|
||||||
|
) -> dict[str, JsonValue]:
|
||||||
|
return {
|
||||||
|
"schema_version": CHECKPOINT_SCHEMA,
|
||||||
|
"plan_digest": bundle.plan_digest,
|
||||||
|
"registration_digest": bundle.arm.registration_digest,
|
||||||
|
"arm_id": bundle.arm.arm_id,
|
||||||
|
"bundle_digest": bundle.bundle_digest,
|
||||||
|
"budget_digest": bundle.budget.budget_digest,
|
||||||
|
"environment_digest": bundle.environment.environment_digest,
|
||||||
|
"input_set_digest": bundle.input_set_digest,
|
||||||
|
"output_destination_digest": bundle.output_destination.destination_digest,
|
||||||
|
"output_digest": receipt.output_digest,
|
||||||
|
"receipt_digest": receipt.receipt_digest,
|
||||||
|
"observation_set_digest": observation_set_digest,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _checkpoint_payload(
|
||||||
|
bundle: LabelBlindExecutionBundleV1,
|
||||||
|
receipt: ExecutionReceiptV1,
|
||||||
|
observations: tuple[ArmObservationSetV3, ...],
|
||||||
|
observation_set_digest: str,
|
||||||
|
) -> tuple[dict[str, JsonValue], str]:
|
||||||
|
identity = _checkpoint_identity(bundle, receipt, observation_set_digest)
|
||||||
|
checkpoint_digest = canonical.content_digest(identity)
|
||||||
|
documents = tuple(encode_arm_observation_set(row).decode("utf-8") for row in observations)
|
||||||
|
return (
|
||||||
|
{
|
||||||
|
**identity,
|
||||||
|
"status": CheckpointStatus.COMPLETE.value,
|
||||||
|
"checkpoint_digest": checkpoint_digest,
|
||||||
|
"execution_receipt": execution_receipt_value(receipt),
|
||||||
|
"observations": documents,
|
||||||
|
},
|
||||||
|
checkpoint_digest,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _freeze(
|
||||||
|
plan: RegisteredEvaluationPlanV1,
|
||||||
|
bundle: LabelBlindExecutionBundleV1,
|
||||||
|
capture: ArmExecutionCaptureV1,
|
||||||
|
repository: S3ArtifactRepository,
|
||||||
|
authority: ArtifactReadAuthority,
|
||||||
|
access_policy_digest: str,
|
||||||
|
) -> ArmCheckpointResultV1:
|
||||||
|
try:
|
||||||
|
receipt = build_execution_receipt(
|
||||||
|
bundle, capture.process_outcome, capture.input_reads, capture.stage_executions, capture.degradations
|
||||||
|
)
|
||||||
|
except (ExecutionReceiptError, TypeError, ValueError):
|
||||||
|
return _impaired(bundle, CheckpointReason.CAPTURE_INVALID)
|
||||||
|
if receipt.status is not ReceiptStatus.COMPLETED:
|
||||||
|
return _impaired(bundle, CheckpointReason.RECEIPT_IMPAIRED)
|
||||||
|
try:
|
||||||
|
validate_execution_receipt_for_bundle(bundle, receipt)
|
||||||
|
except ExecutionReceiptError:
|
||||||
|
return _impaired(bundle, CheckpointReason.RECEIPT_MISMATCH)
|
||||||
|
try:
|
||||||
|
observation_set_digest = _validate_observations(plan, bundle, receipt, capture.observations)
|
||||||
|
payload, checkpoint_digest = _checkpoint_payload(bundle, receipt, capture.observations, observation_set_digest)
|
||||||
|
content = canonical_artifact_bytes(
|
||||||
|
ArtifactKind.OBSERVATION,
|
||||||
|
payload,
|
||||||
|
access_class=ArtifactAccessClass.CUSTODIAN_SEALED,
|
||||||
|
provenance_digest=checkpoint_digest,
|
||||||
|
)
|
||||||
|
reference = artifact_reference(content)
|
||||||
|
except (ObservationCheckpointError, EvaluationObservationError, TypeError, ValueError):
|
||||||
|
return _impaired(bundle, CheckpointReason.OBSERVATION_INVALID)
|
||||||
|
try:
|
||||||
|
repository.put_if_absent(content, reference=reference)
|
||||||
|
except ArtifactRepositoryError:
|
||||||
|
return _impaired(bundle, CheckpointReason.ARTIFACT_WRITE_FAILED)
|
||||||
|
try:
|
||||||
|
accepted = repository.get(
|
||||||
|
reference,
|
||||||
|
expected_kind=ArtifactKind.OBSERVATION,
|
||||||
|
authority=authority,
|
||||||
|
expected_access_policy_digest=access_policy_digest,
|
||||||
|
)
|
||||||
|
except ArtifactRepositoryError:
|
||||||
|
return _impaired(bundle, CheckpointReason.ARTIFACT_READBACK_FAILED)
|
||||||
|
if accepted.content != content or accepted.reference != reference:
|
||||||
|
return _impaired(bundle, CheckpointReason.ARTIFACT_READBACK_FAILED)
|
||||||
|
return ArmCheckpointResultV1(
|
||||||
|
CheckpointStatus.COMPLETE,
|
||||||
|
CheckpointReason.NONE,
|
||||||
|
bundle.plan_digest,
|
||||||
|
bundle.arm.arm_id,
|
||||||
|
checkpoint_digest,
|
||||||
|
reference,
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_checkpoint(payload: object) -> tuple[dict[str, object], ExecutionReceiptV1, tuple[ArmObservationSetV3, ...]]:
|
||||||
|
if (
|
||||||
|
type(payload) is not dict
|
||||||
|
or frozenset(payload) != _CHECKPOINT_FIELDS
|
||||||
|
or payload.get("schema_version") != CHECKPOINT_SCHEMA
|
||||||
|
or payload.get("status") != CheckpointStatus.COMPLETE.value
|
||||||
|
):
|
||||||
|
raise ObservationCheckpointError("checkpoint is not complete")
|
||||||
|
try:
|
||||||
|
receipt = execution_receipt_from_value(payload["execution_receipt"])
|
||||||
|
documents = cast(tuple[object, ...] | list[object], payload["observations"])
|
||||||
|
observations = tuple(decode_arm_observation_set(cast(str, row).encode("utf-8")) for row in documents)
|
||||||
|
except (KeyError, TypeError, ValueError, ExecutionReceiptError, EvaluationObservationError):
|
||||||
|
raise ObservationCheckpointError("checkpoint content is malformed") from None
|
||||||
|
if receipt.status is not ReceiptStatus.COMPLETED or receipt.reason is not ReceiptReason.NONE:
|
||||||
|
raise _IncompleteCheckpointError("checkpoint execution receipt is impaired")
|
||||||
|
return payload, receipt, observations
|
||||||
|
|
||||||
|
|
||||||
|
def _resume(
|
||||||
|
plan: RegisteredEvaluationPlanV1,
|
||||||
|
bundle: LabelBlindExecutionBundleV1,
|
||||||
|
selector: CheckpointSelectorV1,
|
||||||
|
repository: S3ArtifactRepository,
|
||||||
|
authority: ArtifactReadAuthority,
|
||||||
|
access_policy_digest: str,
|
||||||
|
) -> ArmCheckpointResultV1:
|
||||||
|
try:
|
||||||
|
accepted = repository.get(
|
||||||
|
selector.reference,
|
||||||
|
expected_kind=ArtifactKind.OBSERVATION,
|
||||||
|
authority=authority,
|
||||||
|
expected_access_policy_digest=access_policy_digest,
|
||||||
|
)
|
||||||
|
except ArtifactRepositoryError as error:
|
||||||
|
reason = (
|
||||||
|
CheckpointReason.CHECKPOINT_MISSING
|
||||||
|
if error.reason is ArtifactRepositoryReason.NOT_FOUND
|
||||||
|
else CheckpointReason.CHECKPOINT_UNAVAILABLE
|
||||||
|
)
|
||||||
|
return _impaired(bundle, reason)
|
||||||
|
try:
|
||||||
|
payload, receipt, observations = _decode_checkpoint(accepted.artifact.payload)
|
||||||
|
validate_execution_receipt_for_bundle(bundle, receipt)
|
||||||
|
observation_set_digest = _validate_observations(plan, bundle, receipt, observations)
|
||||||
|
expected_identity = _checkpoint_identity(bundle, receipt, observation_set_digest)
|
||||||
|
expected_digest = canonical.content_digest(expected_identity)
|
||||||
|
if (
|
||||||
|
selector.checkpoint_digest != expected_digest
|
||||||
|
or selector.reference != accepted.reference
|
||||||
|
or selector.reference.provenance_digest != expected_digest
|
||||||
|
or payload.get("checkpoint_digest") != expected_digest
|
||||||
|
or any(payload.get(key) != value for key, value in expected_identity.items())
|
||||||
|
):
|
||||||
|
raise ObservationCheckpointError("checkpoint identity mismatch")
|
||||||
|
except _IncompleteCheckpointError:
|
||||||
|
return _impaired(bundle, CheckpointReason.CHECKPOINT_INCOMPLETE)
|
||||||
|
except (ObservationCheckpointError, ExecutionReceiptError, EvaluationObservationError, TypeError, ValueError):
|
||||||
|
return _impaired(bundle, CheckpointReason.CHECKPOINT_MISMATCH)
|
||||||
|
return ArmCheckpointResultV1(
|
||||||
|
CheckpointStatus.COMPLETE,
|
||||||
|
CheckpointReason.NONE,
|
||||||
|
bundle.plan_digest,
|
||||||
|
bundle.arm.arm_id,
|
||||||
|
selector.checkpoint_digest,
|
||||||
|
selector.reference,
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def execute_or_resume_component(
|
||||||
|
plan: RegisteredEvaluationPlanV1,
|
||||||
|
bundle: LabelBlindExecutionBundleV1,
|
||||||
|
adapter: ObservationCheckpointAdapter,
|
||||||
|
repository: S3ArtifactRepository,
|
||||||
|
authority: ArtifactReadAuthority,
|
||||||
|
access_policy_digest: str,
|
||||||
|
manifest: LabelBlindPopulationManifestV3,
|
||||||
|
public_material_manifest: PublicPopulationMaterialManifestV1,
|
||||||
|
selection: OrdinarySelectionV1,
|
||||||
|
*,
|
||||||
|
checkpoint: CheckpointSelectorV1 | None = None,
|
||||||
|
strategy_review_policy: ReviewIndependencePolicy | None = None,
|
||||||
|
strategy_resolver: ContentResolver | None = None,
|
||||||
|
) -> ArmCheckpointResultV1:
|
||||||
|
"""Execute once or resolve only the exact caller-selected completed checkpoint."""
|
||||||
|
try:
|
||||||
|
label_blind_execution_bundle_bytes(
|
||||||
|
plan,
|
||||||
|
bundle,
|
||||||
|
manifest,
|
||||||
|
public_material_manifest,
|
||||||
|
selection,
|
||||||
|
strategy_review_policy=strategy_review_policy,
|
||||||
|
strategy_resolver=strategy_resolver,
|
||||||
|
)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return _impaired(bundle, CheckpointReason.BUNDLE_INVALID)
|
||||||
|
if checkpoint is not None:
|
||||||
|
try:
|
||||||
|
checkpoint.__post_init__()
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return _impaired(bundle, CheckpointReason.CHECKPOINT_MISMATCH)
|
||||||
|
return _resume(plan, bundle, checkpoint, repository, authority, access_policy_digest)
|
||||||
|
try:
|
||||||
|
capture = adapter.execute(bundle)
|
||||||
|
except Exception:
|
||||||
|
return _impaired(bundle, CheckpointReason.ADAPTER_FAILURE)
|
||||||
|
if type(capture) is not ArmExecutionCaptureV1:
|
||||||
|
return _impaired(bundle, CheckpointReason.CAPTURE_INVALID)
|
||||||
|
try:
|
||||||
|
capture.__post_init__()
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return _impaired(bundle, CheckpointReason.CAPTURE_INVALID)
|
||||||
|
return _freeze(plan, bundle, capture, repository, authority, access_policy_digest)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"CHECKPOINT_SCHEMA",
|
||||||
|
"OBSERVATION_OUTPUT_SCHEMA",
|
||||||
|
"ArmCheckpointResultV1",
|
||||||
|
"ArmExecutionCaptureV1",
|
||||||
|
"CheckpointReason",
|
||||||
|
"CheckpointSelectorV1",
|
||||||
|
"CheckpointStatus",
|
||||||
|
"ObservationCheckpointAdapter",
|
||||||
|
"ObservationCheckpointError",
|
||||||
|
"component_observation_output_bytes",
|
||||||
|
"execute_or_resume_component",
|
||||||
|
]
|
||||||
@@ -0,0 +1,621 @@
|
|||||||
|
"""Closed nonzero execution receipts for one isolated component arm."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from enum import StrEnum
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
|
from benchmarks.valid.isolated_execution import (
|
||||||
|
ArmProcessOutcomeV1,
|
||||||
|
ProcessOutcomeReason,
|
||||||
|
ProcessOutcomeStatus,
|
||||||
|
)
|
||||||
|
from benchmarks.valid.isolated_execution_bundle import LabelBlindExecutionBundleV1
|
||||||
|
from openultrasast.core import canonical
|
||||||
|
from openultrasast.core.canonical import JsonValue
|
||||||
|
|
||||||
|
EXECUTION_RECEIPT_SCHEMA = "openultrasast.valid-detection-benchmark.execution-receipt.v1"
|
||||||
|
_DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||||
|
_OPAQUE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}")
|
||||||
|
_READ_FIELDS = frozenset({"input_identity_digest", "expected_bytes", "bytes_read", "status", "read_digest"})
|
||||||
|
_STAGE_FIELDS = frozenset({"stage", "status", "evidence_digest", "stage_digest"})
|
||||||
|
_RECEIPT_FIELDS = frozenset(
|
||||||
|
{
|
||||||
|
"schema_version",
|
||||||
|
"plan_digest",
|
||||||
|
"registration_digest",
|
||||||
|
"bundle_digest",
|
||||||
|
"arm_id",
|
||||||
|
"input_set_digest",
|
||||||
|
"budget_digest",
|
||||||
|
"environment_digest",
|
||||||
|
"output_destination_digest",
|
||||||
|
"outcome_digest",
|
||||||
|
"output_digest",
|
||||||
|
"output_bytes",
|
||||||
|
"runtime_ms",
|
||||||
|
"deadline_seconds",
|
||||||
|
"memory_bytes",
|
||||||
|
"disk_bytes",
|
||||||
|
"maximum_output_bytes",
|
||||||
|
"input_reads",
|
||||||
|
"stage_executions",
|
||||||
|
"degradations",
|
||||||
|
"status",
|
||||||
|
"reason",
|
||||||
|
"input_read_evidence_digest",
|
||||||
|
"stage_execution_evidence_digest",
|
||||||
|
"receipt_digest",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ReceiptStatus(StrEnum):
|
||||||
|
COMPLETED = "completed"
|
||||||
|
IMPAIRED = "impaired"
|
||||||
|
|
||||||
|
|
||||||
|
class ReceiptReason(StrEnum):
|
||||||
|
NONE = "none"
|
||||||
|
INPUT_UNREADABLE = "input_unreadable"
|
||||||
|
INPUT_EMPTY = "input_empty"
|
||||||
|
INPUT_SKIPPED = "input_skipped"
|
||||||
|
INPUT_PARTIAL = "input_partial"
|
||||||
|
INPUT_SET_INCOMPLETE = "input_set_incomplete"
|
||||||
|
REQUIRED_STAGE_SKIPPED = "required_stage_skipped"
|
||||||
|
REQUIRED_STAGE_FAILED = "required_stage_failed"
|
||||||
|
PREMATURE_TERMINATION = "premature_termination"
|
||||||
|
PROCESS_IMPAIRED = "process_impaired"
|
||||||
|
BUDGET_EXHAUSTED = "budget_exhausted"
|
||||||
|
OUTPUT_EMPTY = "output_empty"
|
||||||
|
OUTPUT_INVALID = "output_invalid"
|
||||||
|
IDENTITY_MISMATCH = "identity_mismatch"
|
||||||
|
|
||||||
|
|
||||||
|
class InputReadStatus(StrEnum):
|
||||||
|
COMPLETED = "completed"
|
||||||
|
UNREADABLE = "unreadable"
|
||||||
|
EMPTY = "empty"
|
||||||
|
SKIPPED = "skipped"
|
||||||
|
PARTIAL = "partial"
|
||||||
|
|
||||||
|
|
||||||
|
class RequiredExecutionStage(StrEnum):
|
||||||
|
INPUT_READ = "input_read"
|
||||||
|
ANALYZE = "analyze"
|
||||||
|
OUTPUT_WRITE = "output_write"
|
||||||
|
|
||||||
|
|
||||||
|
class StageExecutionStatus(StrEnum):
|
||||||
|
COMPLETED = "completed"
|
||||||
|
SKIPPED = "skipped"
|
||||||
|
FAILED = "failed"
|
||||||
|
PREMATURE = "premature"
|
||||||
|
|
||||||
|
|
||||||
|
class ExecutionDegradation(StrEnum):
|
||||||
|
ANALYZER_DEGRADED = "analyzer_degraded"
|
||||||
|
FACT_SOURCE_DEGRADED = "fact_source_degraded"
|
||||||
|
MODEL_FALLBACK = "model_fallback"
|
||||||
|
|
||||||
|
|
||||||
|
class ExecutionReceiptError(ValueError):
|
||||||
|
"""Receipt bytes or evidence are malformed or cross-bound."""
|
||||||
|
|
||||||
|
|
||||||
|
def _digest(value: object, field: str, *, optional: bool = False) -> str:
|
||||||
|
if optional and value == "":
|
||||||
|
return ""
|
||||||
|
if type(value) is not str or _DIGEST.fullmatch(value) is None:
|
||||||
|
raise ExecutionReceiptError(f"{field} must be a full lowercase SHA-256 digest")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _opaque(value: object, field: str) -> str:
|
||||||
|
if type(value) is not str or _OPAQUE.fullmatch(value) is None:
|
||||||
|
raise ExecutionReceiptError(f"{field} must be an opaque identifier")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _integer(value: object, field: str, maximum: int, *, positive: bool = False) -> int:
|
||||||
|
minimum = 1 if positive else 0
|
||||||
|
if type(value) is not int or not minimum <= value <= maximum:
|
||||||
|
raise ExecutionReceiptError(f"{field} must be a bounded integer")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _bind(value: object, field: str, expected: str) -> None:
|
||||||
|
actual = getattr(value, field)
|
||||||
|
if actual == "":
|
||||||
|
object.__setattr__(value, field, expected)
|
||||||
|
elif _digest(actual, field) != expected:
|
||||||
|
raise ExecutionReceiptError(f"{field} does not match canonical content")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class InputReadReceiptV1:
|
||||||
|
input_identity_digest: str
|
||||||
|
expected_bytes: int
|
||||||
|
bytes_read: int
|
||||||
|
status: InputReadStatus
|
||||||
|
read_digest: str
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if type(self) is not InputReadReceiptV1 or type(self.status) is not InputReadStatus:
|
||||||
|
raise ExecutionReceiptError("input read must use exact closed receipt types")
|
||||||
|
_digest(self.input_identity_digest, "input identity")
|
||||||
|
_integer(self.expected_bytes, "expected input bytes", 1 << 34, positive=True)
|
||||||
|
_integer(self.bytes_read, "input bytes read", self.expected_bytes)
|
||||||
|
if self.status is InputReadStatus.COMPLETED and self.bytes_read != self.expected_bytes:
|
||||||
|
raise ExecutionReceiptError("completed input read must consume the exact nonzero input")
|
||||||
|
if self.status is InputReadStatus.PARTIAL and not 0 < self.bytes_read < self.expected_bytes:
|
||||||
|
raise ExecutionReceiptError("partial input read must be nonzero and incomplete")
|
||||||
|
if self.status not in {InputReadStatus.COMPLETED, InputReadStatus.PARTIAL} and self.bytes_read != 0:
|
||||||
|
raise ExecutionReceiptError("unreadable, empty, or skipped input cannot claim bytes")
|
||||||
|
_bind(self, "read_digest", canonical.content_digest(_read_value(self, include_digest=False)))
|
||||||
|
|
||||||
|
|
||||||
|
def _read_value(value: InputReadReceiptV1, *, include_digest: bool) -> dict[str, JsonValue]:
|
||||||
|
result: dict[str, JsonValue] = {
|
||||||
|
"input_identity_digest": value.input_identity_digest,
|
||||||
|
"expected_bytes": value.expected_bytes,
|
||||||
|
"bytes_read": value.bytes_read,
|
||||||
|
"status": value.status.value,
|
||||||
|
}
|
||||||
|
if include_digest:
|
||||||
|
result["read_digest"] = value.read_digest
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class StageExecutionReceiptV1:
|
||||||
|
stage: RequiredExecutionStage
|
||||||
|
status: StageExecutionStatus
|
||||||
|
evidence_digest: str
|
||||||
|
stage_digest: str
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if (
|
||||||
|
type(self) is not StageExecutionReceiptV1
|
||||||
|
or type(self.stage) is not RequiredExecutionStage
|
||||||
|
or type(self.status) is not StageExecutionStatus
|
||||||
|
):
|
||||||
|
raise ExecutionReceiptError("stage receipt must use exact closed receipt types")
|
||||||
|
_digest(self.evidence_digest, "stage evidence", optional=self.status is not StageExecutionStatus.COMPLETED)
|
||||||
|
if self.status is StageExecutionStatus.COMPLETED and not self.evidence_digest:
|
||||||
|
raise ExecutionReceiptError("completed stage requires nonzero evidence")
|
||||||
|
if self.status is not StageExecutionStatus.COMPLETED and self.evidence_digest:
|
||||||
|
raise ExecutionReceiptError("incomplete stage cannot claim completion evidence")
|
||||||
|
_bind(self, "stage_digest", canonical.content_digest(_stage_value(self, include_digest=False)))
|
||||||
|
|
||||||
|
|
||||||
|
def _stage_value(value: StageExecutionReceiptV1, *, include_digest: bool) -> dict[str, JsonValue]:
|
||||||
|
result: dict[str, JsonValue] = {
|
||||||
|
"stage": value.stage.value,
|
||||||
|
"status": value.status.value,
|
||||||
|
"evidence_digest": value.evidence_digest or None,
|
||||||
|
}
|
||||||
|
if include_digest:
|
||||||
|
result["stage_digest"] = value.stage_digest
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def input_read_evidence_digest(reads: tuple[InputReadReceiptV1, ...]) -> str:
|
||||||
|
if type(reads) is not tuple or any(type(row) is not InputReadReceiptV1 for row in reads):
|
||||||
|
raise ExecutionReceiptError("input reads must be an exact tuple")
|
||||||
|
for row in reads:
|
||||||
|
row.__post_init__()
|
||||||
|
return canonical.content_digest(
|
||||||
|
{"schema_version": EXECUTION_RECEIPT_SCHEMA, "input_read_digests": tuple(row.read_digest for row in reads)}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def stage_execution_evidence_digest(stages: tuple[StageExecutionReceiptV1, ...]) -> str:
|
||||||
|
if type(stages) is not tuple or any(type(row) is not StageExecutionReceiptV1 for row in stages):
|
||||||
|
raise ExecutionReceiptError("stage receipts must be an exact tuple")
|
||||||
|
for row in stages:
|
||||||
|
row.__post_init__()
|
||||||
|
return canonical.content_digest(
|
||||||
|
{"schema_version": EXECUTION_RECEIPT_SCHEMA, "stage_digests": tuple(row.stage_digest for row in stages)}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ExecutionReceiptV1:
|
||||||
|
plan_digest: str
|
||||||
|
registration_digest: str
|
||||||
|
bundle_digest: str
|
||||||
|
arm_id: str
|
||||||
|
input_set_digest: str
|
||||||
|
budget_digest: str
|
||||||
|
environment_digest: str
|
||||||
|
output_destination_digest: str
|
||||||
|
outcome_digest: str
|
||||||
|
output_digest: str
|
||||||
|
output_bytes: int
|
||||||
|
runtime_ms: int
|
||||||
|
deadline_seconds: int
|
||||||
|
memory_bytes: int
|
||||||
|
disk_bytes: int
|
||||||
|
maximum_output_bytes: int
|
||||||
|
input_reads: tuple[InputReadReceiptV1, ...]
|
||||||
|
stage_executions: tuple[StageExecutionReceiptV1, ...]
|
||||||
|
degradations: tuple[ExecutionDegradation, ...]
|
||||||
|
status: ReceiptStatus
|
||||||
|
reason: ReceiptReason
|
||||||
|
input_read_evidence_digest: str
|
||||||
|
stage_execution_evidence_digest: str
|
||||||
|
receipt_digest: str
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
_validate_receipt_types(self)
|
||||||
|
for item, field in _receipt_digests(self):
|
||||||
|
_digest(item, field, optional=field == "output")
|
||||||
|
_opaque(self.arm_id, "receipt arm id")
|
||||||
|
_validate_receipt_bounds(self)
|
||||||
|
_validate_evidence_rows(self)
|
||||||
|
if self.input_read_evidence_digest != input_read_evidence_digest(self.input_reads):
|
||||||
|
raise ExecutionReceiptError("input-read evidence digest does not match rows")
|
||||||
|
if self.stage_execution_evidence_digest != stage_execution_evidence_digest(self.stage_executions):
|
||||||
|
raise ExecutionReceiptError("stage-execution evidence digest does not match rows")
|
||||||
|
_validate_receipt_state(self)
|
||||||
|
_validate_completed_outcome_binding(self)
|
||||||
|
_bind(self, "receipt_digest", canonical.content_digest(_receipt_value(self, include_digest=False)))
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_receipt_types(value: ExecutionReceiptV1) -> None:
|
||||||
|
if type(value) is not ExecutionReceiptV1:
|
||||||
|
raise ExecutionReceiptError("receipt must use exact ExecutionReceiptV1")
|
||||||
|
if type(value.status) is not ReceiptStatus or type(value.reason) is not ReceiptReason:
|
||||||
|
raise ExecutionReceiptError("receipt must use closed status and reason enums")
|
||||||
|
if type(value.degradations) is not tuple or any(type(row) is not ExecutionDegradation for row in value.degradations):
|
||||||
|
raise ExecutionReceiptError("receipt degradations must use a closed exact tuple")
|
||||||
|
if value.degradations != tuple(sorted(set(value.degradations), key=lambda row: row.value)):
|
||||||
|
raise ExecutionReceiptError("receipt degradations must be unique and canonical")
|
||||||
|
|
||||||
|
|
||||||
|
def _receipt_digests(value: ExecutionReceiptV1) -> tuple[tuple[str, str], ...]:
|
||||||
|
return (
|
||||||
|
(value.plan_digest, "plan"),
|
||||||
|
(value.registration_digest, "registration"),
|
||||||
|
(value.bundle_digest, "bundle"),
|
||||||
|
(value.input_set_digest, "input set"),
|
||||||
|
(value.budget_digest, "budget"),
|
||||||
|
(value.environment_digest, "environment"),
|
||||||
|
(value.output_destination_digest, "output destination"),
|
||||||
|
(value.outcome_digest, "process outcome"),
|
||||||
|
(value.output_digest, "output"),
|
||||||
|
(value.input_read_evidence_digest, "input-read evidence"),
|
||||||
|
(value.stage_execution_evidence_digest, "stage-execution evidence"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_receipt_bounds(value: ExecutionReceiptV1) -> None:
|
||||||
|
_integer(value.output_bytes, "output bytes", 64 * 1024 * 1024)
|
||||||
|
_integer(value.runtime_ms, "runtime", 86_400_000)
|
||||||
|
_integer(value.deadline_seconds, "deadline", 86_400, positive=True)
|
||||||
|
_integer(value.memory_bytes, "memory budget", 1 << 40, positive=True)
|
||||||
|
_integer(value.disk_bytes, "disk budget", 1 << 42, positive=True)
|
||||||
|
_integer(value.maximum_output_bytes, "output budget", 64 * 1024 * 1024, positive=True)
|
||||||
|
if value.output_bytes > value.maximum_output_bytes:
|
||||||
|
raise ExecutionReceiptError("output exceeds the registered bound")
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_evidence_rows(value: ExecutionReceiptV1) -> None:
|
||||||
|
if type(value.input_reads) is not tuple or any(type(row) is not InputReadReceiptV1 for row in value.input_reads):
|
||||||
|
raise ExecutionReceiptError("input reads must use exact receipt values")
|
||||||
|
if len({row.input_identity_digest for row in value.input_reads}) != len(value.input_reads):
|
||||||
|
raise ExecutionReceiptError("input reads must use unique identities")
|
||||||
|
if type(value.stage_executions) is not tuple or any(type(row) is not StageExecutionReceiptV1 for row in value.stage_executions):
|
||||||
|
raise ExecutionReceiptError("stage executions must use exact receipt values")
|
||||||
|
if tuple(row.stage for row in value.stage_executions) != tuple(RequiredExecutionStage):
|
||||||
|
raise ExecutionReceiptError("stage executions must equal every required stage in canonical order")
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_receipt_state(value: ExecutionReceiptV1) -> None:
|
||||||
|
if value.status is ReceiptStatus.IMPAIRED:
|
||||||
|
if value.reason is ReceiptReason.NONE:
|
||||||
|
raise ExecutionReceiptError("impaired receipt requires a closed reason")
|
||||||
|
return
|
||||||
|
complete = (
|
||||||
|
value.reason is ReceiptReason.NONE
|
||||||
|
and bool(value.input_reads)
|
||||||
|
and all(row.status is InputReadStatus.COMPLETED and row.bytes_read > 0 for row in value.input_reads)
|
||||||
|
and all(row.status is StageExecutionStatus.COMPLETED for row in value.stage_executions)
|
||||||
|
and bool(value.output_digest)
|
||||||
|
and value.output_bytes > 0
|
||||||
|
and value.runtime_ms <= value.deadline_seconds * 1000
|
||||||
|
)
|
||||||
|
if not complete:
|
||||||
|
raise ExecutionReceiptError("completed receipt lacks nonzero reads, required stages, output, or budget compliance")
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_completed_outcome_binding(value: ExecutionReceiptV1) -> None:
|
||||||
|
if value.status is not ReceiptStatus.COMPLETED:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
ArmProcessOutcomeV1(
|
||||||
|
value.bundle_digest,
|
||||||
|
value.arm_id,
|
||||||
|
ProcessOutcomeStatus.COMPLETED,
|
||||||
|
ProcessOutcomeReason.NONE,
|
||||||
|
value.runtime_ms,
|
||||||
|
value.output_digest,
|
||||||
|
value.output_bytes,
|
||||||
|
value.outcome_digest,
|
||||||
|
)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ExecutionReceiptError("completed receipt outcome digest does not match its recorded process outcome") from None
|
||||||
|
|
||||||
|
|
||||||
|
def _receipt_value(value: ExecutionReceiptV1, *, include_digest: bool) -> dict[str, JsonValue]:
|
||||||
|
result: dict[str, JsonValue] = {
|
||||||
|
"schema_version": EXECUTION_RECEIPT_SCHEMA,
|
||||||
|
"plan_digest": value.plan_digest,
|
||||||
|
"registration_digest": value.registration_digest,
|
||||||
|
"bundle_digest": value.bundle_digest,
|
||||||
|
"arm_id": value.arm_id,
|
||||||
|
"input_set_digest": value.input_set_digest,
|
||||||
|
"budget_digest": value.budget_digest,
|
||||||
|
"environment_digest": value.environment_digest,
|
||||||
|
"output_destination_digest": value.output_destination_digest,
|
||||||
|
"outcome_digest": value.outcome_digest,
|
||||||
|
"output_digest": value.output_digest or None,
|
||||||
|
"output_bytes": value.output_bytes,
|
||||||
|
"runtime_ms": value.runtime_ms,
|
||||||
|
"deadline_seconds": value.deadline_seconds,
|
||||||
|
"memory_bytes": value.memory_bytes,
|
||||||
|
"disk_bytes": value.disk_bytes,
|
||||||
|
"maximum_output_bytes": value.maximum_output_bytes,
|
||||||
|
"input_reads": tuple(_read_value(row, include_digest=True) for row in value.input_reads),
|
||||||
|
"stage_executions": tuple(_stage_value(row, include_digest=True) for row in value.stage_executions),
|
||||||
|
"degradations": tuple(row.value for row in value.degradations),
|
||||||
|
"status": value.status.value,
|
||||||
|
"reason": value.reason.value,
|
||||||
|
"input_read_evidence_digest": value.input_read_evidence_digest,
|
||||||
|
"stage_execution_evidence_digest": value.stage_execution_evidence_digest,
|
||||||
|
}
|
||||||
|
if include_digest:
|
||||||
|
result["receipt_digest"] = value.receipt_digest
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def execution_receipt_bytes(value: ExecutionReceiptV1) -> bytes:
|
||||||
|
value.__post_init__()
|
||||||
|
return canonical.canonical_bytes(_receipt_value(value, include_digest=True))
|
||||||
|
|
||||||
|
|
||||||
|
def _reason_for_rows(bundle: LabelBlindExecutionBundleV1, reads: tuple[InputReadReceiptV1, ...]) -> ReceiptReason:
|
||||||
|
expected = tuple((row.input_identity_digest, row.code_reference.byte_length) for row in bundle.case_inputs)
|
||||||
|
actual = tuple((row.input_identity_digest, row.expected_bytes) for row in reads)
|
||||||
|
if actual != expected:
|
||||||
|
return ReceiptReason.INPUT_SET_INCOMPLETE
|
||||||
|
mapping = {
|
||||||
|
InputReadStatus.UNREADABLE: ReceiptReason.INPUT_UNREADABLE,
|
||||||
|
InputReadStatus.EMPTY: ReceiptReason.INPUT_EMPTY,
|
||||||
|
InputReadStatus.SKIPPED: ReceiptReason.INPUT_SKIPPED,
|
||||||
|
InputReadStatus.PARTIAL: ReceiptReason.INPUT_PARTIAL,
|
||||||
|
}
|
||||||
|
return next((mapping[row.status] for row in reads if row.status in mapping), ReceiptReason.NONE)
|
||||||
|
|
||||||
|
|
||||||
|
def _reason_for_stages(stages: tuple[StageExecutionReceiptV1, ...]) -> ReceiptReason:
|
||||||
|
if tuple(row.stage for row in stages) != tuple(RequiredExecutionStage):
|
||||||
|
return ReceiptReason.REQUIRED_STAGE_SKIPPED
|
||||||
|
mapping = {
|
||||||
|
StageExecutionStatus.SKIPPED: ReceiptReason.REQUIRED_STAGE_SKIPPED,
|
||||||
|
StageExecutionStatus.FAILED: ReceiptReason.REQUIRED_STAGE_FAILED,
|
||||||
|
StageExecutionStatus.PREMATURE: ReceiptReason.PREMATURE_TERMINATION,
|
||||||
|
}
|
||||||
|
return next((mapping[row.status] for row in stages if row.status in mapping), ReceiptReason.NONE)
|
||||||
|
|
||||||
|
|
||||||
|
def build_execution_receipt(
|
||||||
|
bundle: LabelBlindExecutionBundleV1,
|
||||||
|
outcome: ArmProcessOutcomeV1,
|
||||||
|
reads: tuple[InputReadReceiptV1, ...],
|
||||||
|
stages: tuple[StageExecutionReceiptV1, ...],
|
||||||
|
degradations: tuple[ExecutionDegradation, ...] = (),
|
||||||
|
) -> ExecutionReceiptV1:
|
||||||
|
"""Canonicalize instrument evidence and close every incomplete state."""
|
||||||
|
bundle.__post_init__()
|
||||||
|
identity_matches = type(outcome) is ArmProcessOutcomeV1
|
||||||
|
try:
|
||||||
|
outcome.__post_init__()
|
||||||
|
except (AttributeError, TypeError, ValueError):
|
||||||
|
identity_matches = False
|
||||||
|
if identity_matches:
|
||||||
|
identity_matches = outcome.bundle_digest == bundle.bundle_digest and outcome.arm_id == bundle.arm.arm_id
|
||||||
|
reason = ReceiptReason.IDENTITY_MISMATCH if not identity_matches else ReceiptReason.NONE
|
||||||
|
if reason is ReceiptReason.NONE and outcome.status is ProcessOutcomeStatus.IMPAIRED:
|
||||||
|
reason = ReceiptReason.PROCESS_IMPAIRED
|
||||||
|
if reason is ReceiptReason.NONE:
|
||||||
|
reason = _reason_for_rows(bundle, reads)
|
||||||
|
if reason is ReceiptReason.NONE:
|
||||||
|
reason = _reason_for_stages(stages)
|
||||||
|
if reason is ReceiptReason.NONE and outcome.runtime_ms > bundle.budget.deadline_seconds * 1000:
|
||||||
|
reason = ReceiptReason.BUDGET_EXHAUSTED
|
||||||
|
if reason is ReceiptReason.NONE and (outcome.output_bytes == 0 or not outcome.output_digest):
|
||||||
|
reason = ReceiptReason.OUTPUT_EMPTY
|
||||||
|
status = ReceiptStatus.COMPLETED if reason is ReceiptReason.NONE else ReceiptStatus.IMPAIRED
|
||||||
|
return ExecutionReceiptV1(
|
||||||
|
bundle.plan_digest,
|
||||||
|
bundle.arm.registration_digest,
|
||||||
|
bundle.bundle_digest,
|
||||||
|
bundle.arm.arm_id,
|
||||||
|
bundle.input_set_digest,
|
||||||
|
bundle.budget.budget_digest,
|
||||||
|
bundle.environment.environment_digest,
|
||||||
|
bundle.output_destination.destination_digest,
|
||||||
|
outcome.outcome_digest,
|
||||||
|
outcome.output_digest,
|
||||||
|
outcome.output_bytes,
|
||||||
|
outcome.runtime_ms,
|
||||||
|
bundle.budget.deadline_seconds,
|
||||||
|
bundle.budget.memory_bytes,
|
||||||
|
bundle.budget.disk_bytes,
|
||||||
|
bundle.budget.maximum_output_bytes,
|
||||||
|
reads,
|
||||||
|
stages,
|
||||||
|
degradations,
|
||||||
|
status,
|
||||||
|
reason,
|
||||||
|
input_read_evidence_digest(reads),
|
||||||
|
stage_execution_evidence_digest(stages),
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_execution_receipt_for_bundle(
|
||||||
|
bundle: LabelBlindExecutionBundleV1,
|
||||||
|
receipt: ExecutionReceiptV1,
|
||||||
|
) -> None:
|
||||||
|
"""Require one receipt to bind every current bundle identity and input read."""
|
||||||
|
if type(bundle) is not LabelBlindExecutionBundleV1 or type(receipt) is not ExecutionReceiptV1:
|
||||||
|
raise ExecutionReceiptError("receipt validation requires exact execution contracts")
|
||||||
|
bundle.__post_init__()
|
||||||
|
receipt.__post_init__()
|
||||||
|
expected_identity = (
|
||||||
|
bundle.plan_digest,
|
||||||
|
bundle.arm.registration_digest,
|
||||||
|
bundle.bundle_digest,
|
||||||
|
bundle.arm.arm_id,
|
||||||
|
bundle.input_set_digest,
|
||||||
|
bundle.budget.budget_digest,
|
||||||
|
bundle.budget.deadline_seconds,
|
||||||
|
bundle.budget.memory_bytes,
|
||||||
|
bundle.budget.disk_bytes,
|
||||||
|
bundle.budget.maximum_output_bytes,
|
||||||
|
bundle.environment.environment_digest,
|
||||||
|
bundle.output_destination.destination_digest,
|
||||||
|
)
|
||||||
|
actual_identity = (
|
||||||
|
receipt.plan_digest,
|
||||||
|
receipt.registration_digest,
|
||||||
|
receipt.bundle_digest,
|
||||||
|
receipt.arm_id,
|
||||||
|
receipt.input_set_digest,
|
||||||
|
receipt.budget_digest,
|
||||||
|
receipt.deadline_seconds,
|
||||||
|
receipt.memory_bytes,
|
||||||
|
receipt.disk_bytes,
|
||||||
|
receipt.maximum_output_bytes,
|
||||||
|
receipt.environment_digest,
|
||||||
|
receipt.output_destination_digest,
|
||||||
|
)
|
||||||
|
expected_reads = tuple((row.input_identity_digest, row.code_reference.byte_length) for row in bundle.case_inputs)
|
||||||
|
actual_reads = tuple((row.input_identity_digest, row.expected_bytes) for row in receipt.input_reads)
|
||||||
|
if actual_identity != expected_identity or actual_reads != expected_reads:
|
||||||
|
raise ExecutionReceiptError("execution receipt does not bind the exact current bundle")
|
||||||
|
_validate_completed_outcome_binding(receipt)
|
||||||
|
|
||||||
|
|
||||||
|
def execution_receipt_value(value: ExecutionReceiptV1) -> dict[str, JsonValue]:
|
||||||
|
value.__post_init__()
|
||||||
|
return _receipt_value(value, include_digest=True)
|
||||||
|
|
||||||
|
|
||||||
|
def execution_receipt_from_value(value: object) -> ExecutionReceiptV1:
|
||||||
|
if type(value) is not dict or frozenset(value) != _RECEIPT_FIELDS or value.get("schema_version") != EXECUTION_RECEIPT_SCHEMA:
|
||||||
|
raise ExecutionReceiptError("execution receipt must be an exact object")
|
||||||
|
try:
|
||||||
|
read_values = cast(object, value["input_reads"])
|
||||||
|
stage_values = cast(object, value["stage_executions"])
|
||||||
|
if type(read_values) is not list and type(read_values) is not tuple:
|
||||||
|
raise ExecutionReceiptError("execution input-read fields are malformed")
|
||||||
|
if type(stage_values) is not list and type(stage_values) is not tuple:
|
||||||
|
raise ExecutionReceiptError("execution stage fields are malformed")
|
||||||
|
read_rows = cast(list[object] | tuple[object, ...], read_values)
|
||||||
|
stage_rows = cast(list[object] | tuple[object, ...], stage_values)
|
||||||
|
if any(type(row) is not dict or frozenset(row) != _READ_FIELDS for row in read_rows):
|
||||||
|
raise ExecutionReceiptError("execution input-read fields are malformed")
|
||||||
|
if any(type(row) is not dict or frozenset(row) != _STAGE_FIELDS for row in stage_rows):
|
||||||
|
raise ExecutionReceiptError("execution stage fields are malformed")
|
||||||
|
reads = tuple(
|
||||||
|
InputReadReceiptV1(
|
||||||
|
cast(str, row["input_identity_digest"]),
|
||||||
|
cast(int, row["expected_bytes"]),
|
||||||
|
cast(int, row["bytes_read"]),
|
||||||
|
InputReadStatus(cast(str, row["status"])),
|
||||||
|
cast(str, row["read_digest"]),
|
||||||
|
)
|
||||||
|
for row in cast(list[dict[str, object]] | tuple[dict[str, object], ...], read_rows)
|
||||||
|
)
|
||||||
|
stages = tuple(
|
||||||
|
StageExecutionReceiptV1(
|
||||||
|
RequiredExecutionStage(cast(str, row["stage"])),
|
||||||
|
StageExecutionStatus(cast(str, row["status"])),
|
||||||
|
cast(str | None, row["evidence_digest"]) or "",
|
||||||
|
cast(str, row["stage_digest"]),
|
||||||
|
)
|
||||||
|
for row in cast(list[dict[str, object]] | tuple[dict[str, object], ...], stage_rows)
|
||||||
|
)
|
||||||
|
return ExecutionReceiptV1(
|
||||||
|
plan_digest=cast(str, value["plan_digest"]),
|
||||||
|
registration_digest=cast(str, value["registration_digest"]),
|
||||||
|
bundle_digest=cast(str, value["bundle_digest"]),
|
||||||
|
arm_id=cast(str, value["arm_id"]),
|
||||||
|
input_set_digest=cast(str, value["input_set_digest"]),
|
||||||
|
budget_digest=cast(str, value["budget_digest"]),
|
||||||
|
environment_digest=cast(str, value["environment_digest"]),
|
||||||
|
output_destination_digest=cast(str, value["output_destination_digest"]),
|
||||||
|
outcome_digest=cast(str, value["outcome_digest"]),
|
||||||
|
output_digest=cast(str | None, value["output_digest"]) or "",
|
||||||
|
output_bytes=cast(int, value["output_bytes"]),
|
||||||
|
runtime_ms=cast(int, value["runtime_ms"]),
|
||||||
|
deadline_seconds=cast(int, value["deadline_seconds"]),
|
||||||
|
memory_bytes=cast(int, value["memory_bytes"]),
|
||||||
|
disk_bytes=cast(int, value["disk_bytes"]),
|
||||||
|
maximum_output_bytes=cast(int, value["maximum_output_bytes"]),
|
||||||
|
input_reads=reads,
|
||||||
|
stage_executions=stages,
|
||||||
|
degradations=tuple(ExecutionDegradation(row) for row in cast(list[str], value["degradations"])),
|
||||||
|
status=ReceiptStatus(cast(str, value["status"])),
|
||||||
|
reason=ReceiptReason(cast(str, value["reason"])),
|
||||||
|
input_read_evidence_digest=cast(str, value["input_read_evidence_digest"]),
|
||||||
|
stage_execution_evidence_digest=cast(str, value["stage_execution_evidence_digest"]),
|
||||||
|
receipt_digest=cast(str, value["receipt_digest"]),
|
||||||
|
)
|
||||||
|
except (KeyError, TypeError, ValueError, ExecutionReceiptError) as exc:
|
||||||
|
if isinstance(exc, ExecutionReceiptError):
|
||||||
|
raise
|
||||||
|
raise ExecutionReceiptError("execution receipt fields are malformed") from None
|
||||||
|
|
||||||
|
|
||||||
|
def decode_execution_receipt(content: bytes) -> ExecutionReceiptV1:
|
||||||
|
if type(content) is not bytes or not content:
|
||||||
|
raise ExecutionReceiptError("execution receipt bytes must be nonzero")
|
||||||
|
try:
|
||||||
|
value = json.loads(content)
|
||||||
|
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||||
|
raise ExecutionReceiptError("execution receipt bytes are malformed") from None
|
||||||
|
receipt = execution_receipt_from_value(value)
|
||||||
|
if execution_receipt_bytes(receipt) != content:
|
||||||
|
raise ExecutionReceiptError("execution receipt bytes are not canonical")
|
||||||
|
return receipt
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"EXECUTION_RECEIPT_SCHEMA",
|
||||||
|
"ExecutionDegradation",
|
||||||
|
"ExecutionReceiptError",
|
||||||
|
"ExecutionReceiptV1",
|
||||||
|
"InputReadReceiptV1",
|
||||||
|
"InputReadStatus",
|
||||||
|
"ReceiptReason",
|
||||||
|
"ReceiptStatus",
|
||||||
|
"RequiredExecutionStage",
|
||||||
|
"StageExecutionReceiptV1",
|
||||||
|
"StageExecutionStatus",
|
||||||
|
"build_execution_receipt",
|
||||||
|
"decode_execution_receipt",
|
||||||
|
"execution_receipt_bytes",
|
||||||
|
"execution_receipt_from_value",
|
||||||
|
"execution_receipt_value",
|
||||||
|
"input_read_evidence_digest",
|
||||||
|
"stage_execution_evidence_digest",
|
||||||
|
"validate_execution_receipt_for_bundle",
|
||||||
|
]
|
||||||
@@ -0,0 +1,664 @@
|
|||||||
|
"""Task 6.4 nonzero receipts and exact component-observation checkpoints."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from collections.abc import Callable
|
||||||
|
from dataclasses import fields, replace
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
|
|
||||||
|
from test_valid_benchmark_artifact_repository import ( # noqa: E402
|
||||||
|
_authority,
|
||||||
|
_Client,
|
||||||
|
_repo,
|
||||||
|
)
|
||||||
|
from test_valid_benchmark_artifact_repository import (
|
||||||
|
_digest as _artifact_digest,
|
||||||
|
)
|
||||||
|
from test_valid_benchmark_isolated_executor import _authorities, _bundles, _digest, _plan # noqa: E402
|
||||||
|
|
||||||
|
from benchmarks.valid import artifact_repository as repository # noqa: E402
|
||||||
|
from benchmarks.valid import isolated_execution as execution # noqa: E402
|
||||||
|
from benchmarks.valid import observation_checkpoint as checkpoint # noqa: E402
|
||||||
|
from benchmarks.valid import observation_receipt as receipt # noqa: E402
|
||||||
|
from benchmarks.valid.replacement_artifact_contract import ( # noqa: E402
|
||||||
|
ArtifactAccessClass,
|
||||||
|
ArtifactKind,
|
||||||
|
artifact_reference,
|
||||||
|
canonical_artifact_bytes,
|
||||||
|
)
|
||||||
|
from openultrasast.core.evaluation_observation import ArmObservationSetV3 # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def _reads(bundle, status=receipt.InputReadStatus.COMPLETED):
|
||||||
|
rows = []
|
||||||
|
for item in bundle.case_inputs:
|
||||||
|
expected = item.code_reference.byte_length
|
||||||
|
count = expected if status is receipt.InputReadStatus.COMPLETED else 0
|
||||||
|
if status is receipt.InputReadStatus.PARTIAL:
|
||||||
|
count = max(1, expected - 1)
|
||||||
|
rows.append(receipt.InputReadReceiptV1(item.input_identity_digest, expected, count, status, ""))
|
||||||
|
return tuple(rows)
|
||||||
|
|
||||||
|
|
||||||
|
def _stages(status=receipt.StageExecutionStatus.COMPLETED):
|
||||||
|
return tuple(
|
||||||
|
receipt.StageExecutionReceiptV1(
|
||||||
|
stage,
|
||||||
|
status,
|
||||||
|
_digest(f"stage-{stage.value}") if status is receipt.StageExecutionStatus.COMPLETED else "",
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
for stage in receipt.RequiredExecutionStage
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _observations(bundle, *, reads=None, stages=None):
|
||||||
|
plan = _plan()
|
||||||
|
reads = _reads(bundle) if reads is None else reads
|
||||||
|
stages = _stages() if stages is None else stages
|
||||||
|
configuration = next(row for row in plan.declaration.arm_configurations if row.arm_id == bundle.arm.arm_id)
|
||||||
|
slots = tuple(row for row in plan.declaration.expected_observation_slots if row.arm_id == bundle.arm.arm_id)
|
||||||
|
return tuple(
|
||||||
|
ArmObservationSetV3(
|
||||||
|
slot.slot_digest,
|
||||||
|
slot.arm_id,
|
||||||
|
slot.input_identity_digest,
|
||||||
|
slot.execution_identity,
|
||||||
|
configuration.registered_budget_digest,
|
||||||
|
configuration.configuration_identity_digest,
|
||||||
|
receipt.input_read_evidence_digest(reads),
|
||||||
|
receipt.stage_execution_evidence_digest(stages),
|
||||||
|
(),
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
for slot in slots
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _capture(
|
||||||
|
bundle,
|
||||||
|
*,
|
||||||
|
read_status=receipt.InputReadStatus.COMPLETED,
|
||||||
|
stage_status=receipt.StageExecutionStatus.COMPLETED,
|
||||||
|
observations=None,
|
||||||
|
output=None,
|
||||||
|
):
|
||||||
|
reads = _reads(bundle, read_status)
|
||||||
|
stages = _stages(stage_status)
|
||||||
|
values = _observations(bundle, reads=reads, stages=stages) if observations is None else observations
|
||||||
|
content = checkpoint.component_observation_output_bytes(values) if output is None else output
|
||||||
|
outcome = execution.completed_adapter_outcome(bundle, content, runtime_ms=7)
|
||||||
|
return checkpoint.ArmExecutionCaptureV1(outcome, reads, stages, (), values)
|
||||||
|
|
||||||
|
|
||||||
|
class _Adapter:
|
||||||
|
def __init__(self, factory: Callable = _capture) -> None:
|
||||||
|
self.factory = factory
|
||||||
|
self.calls = []
|
||||||
|
|
||||||
|
def execute(self, bundle):
|
||||||
|
self.calls.append(bundle)
|
||||||
|
return self.factory(bundle)
|
||||||
|
|
||||||
|
|
||||||
|
def _custodian():
|
||||||
|
return _authority(
|
||||||
|
repository.ArtifactActorRole.CUSTODIAN,
|
||||||
|
(repository.ArtifactReadPermission.CUSTODIAN_SEALED,),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _run(bundle, adapter, client, *, selector=None, authority=None):
|
||||||
|
manifest, public, selection = _authorities()
|
||||||
|
return checkpoint.execute_or_resume_component(
|
||||||
|
_plan(),
|
||||||
|
bundle,
|
||||||
|
adapter,
|
||||||
|
_repo(client),
|
||||||
|
_custodian() if authority is None else authority,
|
||||||
|
_artifact_digest("read-policy"),
|
||||||
|
manifest,
|
||||||
|
public,
|
||||||
|
selection,
|
||||||
|
checkpoint=selector,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _frozen(bundle=None):
|
||||||
|
bundle = _bundles()[0] if bundle is None else bundle
|
||||||
|
client = _Client()
|
||||||
|
adapter = _Adapter()
|
||||||
|
result = _run(bundle, adapter, client)
|
||||||
|
assert result.status is checkpoint.CheckpointStatus.COMPLETE
|
||||||
|
assert result.reference is not None
|
||||||
|
return bundle, client, adapter, result
|
||||||
|
|
||||||
|
|
||||||
|
def _completed_receipt(bundle, *, reads=None):
|
||||||
|
reads = _reads(bundle) if reads is None else reads
|
||||||
|
stages = _stages()
|
||||||
|
observations = _observations(bundle, reads=reads, stages=stages)
|
||||||
|
output = checkpoint.component_observation_output_bytes(observations)
|
||||||
|
outcome = execution.completed_adapter_outcome(bundle, output, runtime_ms=7)
|
||||||
|
value = receipt.build_execution_receipt(bundle, outcome, reads, stages)
|
||||||
|
assert value.status is receipt.ReceiptStatus.COMPLETED
|
||||||
|
return value, observations
|
||||||
|
|
||||||
|
|
||||||
|
def _sealed_selector(bundle, value, observations):
|
||||||
|
observation_set_digest = checkpoint._validate_observations(_plan(), bundle, value, observations)
|
||||||
|
payload, checkpoint_digest = checkpoint._checkpoint_payload(bundle, value, observations, observation_set_digest)
|
||||||
|
content = canonical_artifact_bytes(
|
||||||
|
ArtifactKind.OBSERVATION,
|
||||||
|
payload,
|
||||||
|
access_class=ArtifactAccessClass.CUSTODIAN_SEALED,
|
||||||
|
provenance_digest=checkpoint_digest,
|
||||||
|
)
|
||||||
|
reference = artifact_reference(content)
|
||||||
|
client = _Client()
|
||||||
|
_repo(client).put_if_absent(content, reference=reference)
|
||||||
|
return client, checkpoint.CheckpointSelectorV1(reference, checkpoint_digest)
|
||||||
|
|
||||||
|
|
||||||
|
def _unchecked_receipt(value, **changes):
|
||||||
|
forged = object.__new__(receipt.ExecutionReceiptV1)
|
||||||
|
for field in fields(receipt.ExecutionReceiptV1):
|
||||||
|
object.__setattr__(forged, field.name, changes.get(field.name, getattr(value, field.name)))
|
||||||
|
return forged
|
||||||
|
|
||||||
|
|
||||||
|
def _forged_receipt_value(value):
|
||||||
|
document = receipt.execution_receipt_value(value)
|
||||||
|
document["outcome_digest"] = _digest("foreign-outcome")
|
||||||
|
unsigned = dict(document)
|
||||||
|
unsigned.pop("receipt_digest")
|
||||||
|
document["receipt_digest"] = execution.canonical.content_digest(unsigned)
|
||||||
|
return document
|
||||||
|
|
||||||
|
|
||||||
|
def _completed_outcome_digest(value, **changes):
|
||||||
|
outcome = execution.ArmProcessOutcomeV1(
|
||||||
|
changes.get("bundle_digest", value.bundle_digest),
|
||||||
|
changes.get("arm_id", value.arm_id),
|
||||||
|
execution.ProcessOutcomeStatus.COMPLETED,
|
||||||
|
execution.ProcessOutcomeReason.NONE,
|
||||||
|
changes.get("runtime_ms", value.runtime_ms),
|
||||||
|
changes.get("output_digest", value.output_digest),
|
||||||
|
changes.get("output_bytes", value.output_bytes),
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
return outcome.outcome_digest
|
||||||
|
|
||||||
|
|
||||||
|
def _checkpoint_identity_from_payload(payload):
|
||||||
|
return {
|
||||||
|
key: payload[key]
|
||||||
|
for key in (
|
||||||
|
"schema_version",
|
||||||
|
"plan_digest",
|
||||||
|
"registration_digest",
|
||||||
|
"arm_id",
|
||||||
|
"bundle_digest",
|
||||||
|
"budget_digest",
|
||||||
|
"environment_digest",
|
||||||
|
"input_set_digest",
|
||||||
|
"output_destination_digest",
|
||||||
|
"output_digest",
|
||||||
|
"receipt_digest",
|
||||||
|
"observation_set_digest",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_complete_nonzero_receipt_is_written_and_read_back_as_custodian_sealed() -> None:
|
||||||
|
bundle, client, adapter, result = _frozen()
|
||||||
|
assert adapter.calls == [bundle]
|
||||||
|
assert result.reason is checkpoint.CheckpointReason.NONE
|
||||||
|
assert result.reference.artifact_kind is ArtifactKind.OBSERVATION
|
||||||
|
assert result.reference.access_class is ArtifactAccessClass.CUSTODIAN_SEALED
|
||||||
|
assert result.reference.provenance_digest == result.checkpoint_digest
|
||||||
|
assert len(client.put_calls) == 1
|
||||||
|
assert len(client.get_calls) >= 1
|
||||||
|
accepted = _repo(client).get(
|
||||||
|
result.reference,
|
||||||
|
expected_kind=ArtifactKind.OBSERVATION,
|
||||||
|
authority=_custodian(),
|
||||||
|
expected_access_policy_digest=_artifact_digest("read-policy"),
|
||||||
|
)
|
||||||
|
stored = receipt.execution_receipt_from_value(accepted.artifact.payload["execution_receipt"])
|
||||||
|
assert stored.status is receipt.ReceiptStatus.COMPLETED
|
||||||
|
assert all(row.bytes_read == row.expected_bytes > 0 for row in stored.input_reads)
|
||||||
|
assert all(row.status is receipt.StageExecutionStatus.COMPLETED for row in stored.stage_executions)
|
||||||
|
assert stored.runtime_ms == 7
|
||||||
|
assert stored.budget_digest == bundle.budget.budget_digest
|
||||||
|
assert stored.output_digest and stored.output_bytes > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_planned_component_freezes_separately_and_combined_arm_never_executes() -> None:
|
||||||
|
client = _Client()
|
||||||
|
adapter = _Adapter()
|
||||||
|
results = tuple(_run(bundle, adapter, client) for bundle in _bundles())
|
||||||
|
assert tuple(row.arm_id for row in results) == ("arm-experimental", "arm-shipped")
|
||||||
|
assert all(row.status is checkpoint.CheckpointStatus.COMPLETE for row in results)
|
||||||
|
assert len({row.checkpoint_digest for row in results}) == 2
|
||||||
|
assert tuple(row.arm.arm_id for row in adapter.calls) == ("arm-experimental", "arm-shipped")
|
||||||
|
assert "arm-combined" not in {row.arm.arm_id for row in adapter.calls}
|
||||||
|
|
||||||
|
|
||||||
|
def test_exact_resume_reuses_completed_checkpoint_without_adapter_call() -> None:
|
||||||
|
bundle, client, _, first = _frozen()
|
||||||
|
adapter = _Adapter(lambda _: (_ for _ in ()).throw(AssertionError("adapter must not run")))
|
||||||
|
selector = checkpoint.CheckpointSelectorV1(first.reference, first.checkpoint_digest)
|
||||||
|
resumed = _run(bundle, adapter, client, selector=selector)
|
||||||
|
assert resumed == first
|
||||||
|
assert adapter.calls == []
|
||||||
|
assert len(client.put_calls) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_completed_receipt_construction_and_deserialization_reject_foreign_outcome_digest() -> None:
|
||||||
|
value, _ = _completed_receipt(_bundles()[0])
|
||||||
|
with pytest.raises(receipt.ExecutionReceiptError):
|
||||||
|
replace(value, outcome_digest=_digest("foreign-outcome"), receipt_digest="")
|
||||||
|
with pytest.raises(receipt.ExecutionReceiptError):
|
||||||
|
receipt.execution_receipt_from_value(_forged_receipt_value(value))
|
||||||
|
|
||||||
|
|
||||||
|
def test_exact_resume_refuses_digest_consistent_foreign_outcome_without_adapter_call() -> None:
|
||||||
|
bundle, client, _, frozen = _frozen()
|
||||||
|
accepted = _repo(client).get(
|
||||||
|
frozen.reference,
|
||||||
|
expected_kind=ArtifactKind.OBSERVATION,
|
||||||
|
authority=_custodian(),
|
||||||
|
expected_access_policy_digest=_artifact_digest("read-policy"),
|
||||||
|
)
|
||||||
|
payload = dict(accepted.artifact.payload)
|
||||||
|
payload["execution_receipt"] = _forged_receipt_value(receipt.execution_receipt_from_value(payload["execution_receipt"]))
|
||||||
|
payload["receipt_digest"] = payload["execution_receipt"]["receipt_digest"]
|
||||||
|
checkpoint_digest = execution.canonical.content_digest(_checkpoint_identity_from_payload(payload))
|
||||||
|
payload["checkpoint_digest"] = checkpoint_digest
|
||||||
|
content = canonical_artifact_bytes(
|
||||||
|
ArtifactKind.OBSERVATION,
|
||||||
|
payload,
|
||||||
|
access_class=ArtifactAccessClass.CUSTODIAN_SEALED,
|
||||||
|
provenance_digest=checkpoint_digest,
|
||||||
|
)
|
||||||
|
reference = artifact_reference(content)
|
||||||
|
forged_client = _Client()
|
||||||
|
_repo(forged_client).put_if_absent(content, reference=reference)
|
||||||
|
adapter = _Adapter()
|
||||||
|
|
||||||
|
resumed = _run(
|
||||||
|
bundle,
|
||||||
|
adapter,
|
||||||
|
forged_client,
|
||||||
|
selector=checkpoint.CheckpointSelectorV1(reference, checkpoint_digest),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert resumed.status is checkpoint.CheckpointStatus.IMPAIRED
|
||||||
|
assert resumed.reason is checkpoint.CheckpointReason.CHECKPOINT_MISMATCH
|
||||||
|
assert adapter.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_freeze_refuses_foreign_outcome_digest_before_persistence(monkeypatch) -> None:
|
||||||
|
bundle = _bundles()[0]
|
||||||
|
value, _ = _completed_receipt(bundle)
|
||||||
|
forged = _unchecked_receipt(value, outcome_digest=_digest("foreign-outcome"), receipt_digest="")
|
||||||
|
monkeypatch.setattr(checkpoint, "build_execution_receipt", lambda *args, **kwargs: forged)
|
||||||
|
client = _Client()
|
||||||
|
adapter = _Adapter()
|
||||||
|
|
||||||
|
result = _run(bundle, adapter, client)
|
||||||
|
|
||||||
|
assert result.status is checkpoint.CheckpointStatus.IMPAIRED
|
||||||
|
assert result.reason is checkpoint.CheckpointReason.RECEIPT_MISMATCH
|
||||||
|
assert adapter.calls == [bundle]
|
||||||
|
assert client.put_calls == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("field", "foreign"),
|
||||||
|
(
|
||||||
|
("plan_digest", "foreign-plan"),
|
||||||
|
("registration_digest", "foreign-registration"),
|
||||||
|
("bundle_digest", "foreign-bundle"),
|
||||||
|
("arm_id", "foreign-arm"),
|
||||||
|
("input_set_digest", "foreign-input-set"),
|
||||||
|
("budget_digest", "foreign-budget"),
|
||||||
|
("environment_digest", "foreign-environment"),
|
||||||
|
("output_destination_digest", "foreign-output-destination"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def test_exact_resume_refuses_completed_receipt_from_foreign_execution_identity(field, foreign) -> None:
|
||||||
|
bundle = _bundles()[0]
|
||||||
|
value, observations = _completed_receipt(bundle)
|
||||||
|
changes = {field: _digest(foreign)}
|
||||||
|
changes["outcome_digest"] = _completed_outcome_digest(value, **changes)
|
||||||
|
changed = replace(value, **changes, receipt_digest="")
|
||||||
|
client, selector = _sealed_selector(bundle, changed, observations)
|
||||||
|
adapter = _Adapter()
|
||||||
|
|
||||||
|
resumed = _run(bundle, adapter, client, selector=selector)
|
||||||
|
|
||||||
|
assert resumed.status is checkpoint.CheckpointStatus.IMPAIRED
|
||||||
|
assert resumed.reason is checkpoint.CheckpointReason.CHECKPOINT_MISMATCH
|
||||||
|
assert adapter.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("field", "foreign"),
|
||||||
|
(
|
||||||
|
("deadline_seconds", 121),
|
||||||
|
("memory_bytes", 512 * 1024 * 1024 + 1),
|
||||||
|
("disk_bytes", 1024 * 1024 * 1024 + 1),
|
||||||
|
("maximum_output_bytes", 4 * 1024 * 1024 + 1),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def test_exact_resume_refuses_completed_receipt_with_changed_budget_value(field, foreign) -> None:
|
||||||
|
bundle = _bundles()[0]
|
||||||
|
value, observations = _completed_receipt(bundle)
|
||||||
|
changed = replace(value, **{field: foreign, "receipt_digest": ""})
|
||||||
|
client, selector = _sealed_selector(bundle, changed, observations)
|
||||||
|
adapter = _Adapter()
|
||||||
|
|
||||||
|
resumed = _run(bundle, adapter, client, selector=selector)
|
||||||
|
|
||||||
|
assert resumed.status is checkpoint.CheckpointStatus.IMPAIRED
|
||||||
|
assert resumed.reason is checkpoint.CheckpointReason.CHECKPOINT_MISMATCH
|
||||||
|
assert adapter.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mutation", ("identity", "expected_bytes", "order", "missing", "extra"))
|
||||||
|
def test_exact_resume_refuses_completed_receipt_with_changed_input_read_set(mutation: str) -> None:
|
||||||
|
bundle = _bundles()[0]
|
||||||
|
rows = _reads(bundle)
|
||||||
|
if mutation == "identity":
|
||||||
|
rows = (replace(rows[0], input_identity_digest=_digest("foreign-read"), read_digest=""), *rows[1:])
|
||||||
|
elif mutation == "expected_bytes":
|
||||||
|
rows = (replace(rows[0], expected_bytes=rows[0].expected_bytes + 1, bytes_read=rows[0].bytes_read + 1, read_digest=""), *rows[1:])
|
||||||
|
elif mutation == "order":
|
||||||
|
rows = tuple(reversed(rows))
|
||||||
|
elif mutation == "missing":
|
||||||
|
rows = rows[:-1]
|
||||||
|
else:
|
||||||
|
rows = (*rows, receipt.InputReadReceiptV1(_digest("extra-read"), 1, 1, receipt.InputReadStatus.COMPLETED, ""))
|
||||||
|
value, observations = _completed_receipt(bundle)
|
||||||
|
observations = _observations(bundle, reads=rows, stages=_stages())
|
||||||
|
output = checkpoint.component_observation_output_bytes(observations)
|
||||||
|
changes = {
|
||||||
|
"output_digest": execution.canonical.bytes_digest(output),
|
||||||
|
"output_bytes": len(output),
|
||||||
|
}
|
||||||
|
changed = replace(
|
||||||
|
value,
|
||||||
|
input_reads=rows,
|
||||||
|
input_read_evidence_digest=receipt.input_read_evidence_digest(rows),
|
||||||
|
**changes,
|
||||||
|
outcome_digest=_completed_outcome_digest(value, **changes),
|
||||||
|
receipt_digest="",
|
||||||
|
)
|
||||||
|
client, selector = _sealed_selector(bundle, changed, observations)
|
||||||
|
adapter = _Adapter()
|
||||||
|
|
||||||
|
resumed = _run(bundle, adapter, client, selector=selector)
|
||||||
|
|
||||||
|
assert resumed.status is checkpoint.CheckpointStatus.IMPAIRED
|
||||||
|
assert resumed.reason is checkpoint.CheckpointReason.CHECKPOINT_MISMATCH
|
||||||
|
assert adapter.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("read_status", "stage_status"),
|
||||||
|
(
|
||||||
|
(receipt.InputReadStatus.SKIPPED, receipt.StageExecutionStatus.COMPLETED),
|
||||||
|
(receipt.InputReadStatus.EMPTY, receipt.StageExecutionStatus.COMPLETED),
|
||||||
|
(receipt.InputReadStatus.COMPLETED, receipt.StageExecutionStatus.FAILED),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
def test_exact_resume_refuses_digest_consistent_checkpoint_with_impaired_nested_receipt(
|
||||||
|
read_status,
|
||||||
|
stage_status,
|
||||||
|
) -> None:
|
||||||
|
bundle = _bundles()[0]
|
||||||
|
reads = _reads(bundle, read_status)
|
||||||
|
stages = _stages(stage_status)
|
||||||
|
observations = _observations(bundle, reads=reads, stages=stages)
|
||||||
|
output = checkpoint.component_observation_output_bytes(observations)
|
||||||
|
outcome = execution.completed_adapter_outcome(bundle, output, runtime_ms=7)
|
||||||
|
impaired_receipt = receipt.build_execution_receipt(bundle, outcome, reads, stages)
|
||||||
|
assert impaired_receipt.status is receipt.ReceiptStatus.IMPAIRED
|
||||||
|
observation_set_digest = checkpoint._validate_observations(_plan(), bundle, impaired_receipt, observations)
|
||||||
|
payload, checkpoint_digest = checkpoint._checkpoint_payload(
|
||||||
|
bundle,
|
||||||
|
impaired_receipt,
|
||||||
|
observations,
|
||||||
|
observation_set_digest,
|
||||||
|
)
|
||||||
|
content = canonical_artifact_bytes(
|
||||||
|
ArtifactKind.OBSERVATION,
|
||||||
|
payload,
|
||||||
|
access_class=ArtifactAccessClass.CUSTODIAN_SEALED,
|
||||||
|
provenance_digest=checkpoint_digest,
|
||||||
|
)
|
||||||
|
reference = artifact_reference(content)
|
||||||
|
client = _Client()
|
||||||
|
_repo(client).put_if_absent(content, reference=reference)
|
||||||
|
adapter = _Adapter()
|
||||||
|
|
||||||
|
resumed = _run(
|
||||||
|
bundle,
|
||||||
|
adapter,
|
||||||
|
client,
|
||||||
|
selector=checkpoint.CheckpointSelectorV1(reference, checkpoint_digest),
|
||||||
|
)
|
||||||
|
|
||||||
|
assert resumed.status is checkpoint.CheckpointStatus.IMPAIRED
|
||||||
|
assert resumed.reason is checkpoint.CheckpointReason.CHECKPOINT_INCOMPLETE
|
||||||
|
assert resumed.reference is None
|
||||||
|
assert adapter.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_or_digest_mismatched_resume_is_impaired_and_never_reruns() -> None:
|
||||||
|
bundle = _bundles()[0]
|
||||||
|
_, _, _, existing = _frozen(bundle)
|
||||||
|
missing_adapter = _Adapter()
|
||||||
|
missing = _run(
|
||||||
|
bundle,
|
||||||
|
missing_adapter,
|
||||||
|
_Client(),
|
||||||
|
selector=checkpoint.CheckpointSelectorV1(existing.reference, existing.checkpoint_digest),
|
||||||
|
)
|
||||||
|
assert missing.reason is checkpoint.CheckpointReason.CHECKPOINT_MISSING
|
||||||
|
assert missing_adapter.calls == []
|
||||||
|
|
||||||
|
_, client, _, frozen = _frozen(bundle)
|
||||||
|
mismatch_adapter = _Adapter()
|
||||||
|
mismatch = _run(
|
||||||
|
bundle,
|
||||||
|
mismatch_adapter,
|
||||||
|
client,
|
||||||
|
selector=checkpoint.CheckpointSelectorV1(frozen.reference, _digest("other-checkpoint")),
|
||||||
|
)
|
||||||
|
assert mismatch.reason is checkpoint.CheckpointReason.CHECKPOINT_MISMATCH
|
||||||
|
assert mismatch_adapter.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("changed", ("budget", "environment", "output"))
|
||||||
|
def test_changed_execution_identity_cannot_resume_old_checkpoint(changed: str) -> None:
|
||||||
|
bundle, client, _, frozen = _frozen()
|
||||||
|
if changed == "budget":
|
||||||
|
budget = replace(bundle.budget, deadline_seconds=bundle.budget.deadline_seconds + 1, budget_digest="")
|
||||||
|
current = replace(bundle, budget=budget, bundle_digest="")
|
||||||
|
elif changed == "environment":
|
||||||
|
environment = execution.build_execution_environment(execution.ExecutionAdapterKind.DOCKER)
|
||||||
|
current = replace(bundle, environment=environment, bundle_digest="")
|
||||||
|
else:
|
||||||
|
destination = replace(bundle.output_destination, namespace_digest=_digest("changed-output"), destination_digest="")
|
||||||
|
current = replace(bundle, output_destination=destination, bundle_digest="")
|
||||||
|
adapter = _Adapter()
|
||||||
|
result = _run(
|
||||||
|
current,
|
||||||
|
adapter,
|
||||||
|
client,
|
||||||
|
selector=checkpoint.CheckpointSelectorV1(frozen.reference, frozen.checkpoint_digest),
|
||||||
|
)
|
||||||
|
assert result.status is checkpoint.CheckpointStatus.IMPAIRED
|
||||||
|
assert result.reason is checkpoint.CheckpointReason.CHECKPOINT_MISMATCH
|
||||||
|
assert adapter.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("status", tuple(receipt.InputReadStatus)[1:])
|
||||||
|
def test_unreadable_empty_skipped_or_partial_input_never_freezes_clean(status) -> None:
|
||||||
|
result = _run(_bundles()[0], _Adapter(lambda bundle: _capture(bundle, read_status=status)), _Client())
|
||||||
|
assert result.status is checkpoint.CheckpointStatus.IMPAIRED
|
||||||
|
assert result.reason is checkpoint.CheckpointReason.RECEIPT_IMPAIRED
|
||||||
|
assert result.reference is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("status", tuple(receipt.StageExecutionStatus)[1:])
|
||||||
|
def test_skipped_failed_or_premature_required_stage_never_freezes_clean(status) -> None:
|
||||||
|
result = _run(_bundles()[0], _Adapter(lambda bundle: _capture(bundle, stage_status=status)), _Client())
|
||||||
|
assert result.status is checkpoint.CheckpointStatus.IMPAIRED
|
||||||
|
assert result.reason is checkpoint.CheckpointReason.RECEIPT_IMPAIRED
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_partial_cross_arm_or_changed_output_observations_are_impaired() -> None:
|
||||||
|
first, second = _bundles()
|
||||||
|
mutations = (
|
||||||
|
lambda bundle: _capture(bundle, observations=_observations(bundle)[:-1]),
|
||||||
|
lambda bundle: _capture(bundle, observations=_observations(second)),
|
||||||
|
lambda bundle: _capture(bundle, output=b"different-output"),
|
||||||
|
)
|
||||||
|
for mutation in mutations:
|
||||||
|
result = _run(first, _Adapter(mutation), _Client())
|
||||||
|
assert result.status is checkpoint.CheckpointStatus.IMPAIRED
|
||||||
|
assert result.reason is checkpoint.CheckpointReason.OBSERVATION_INVALID
|
||||||
|
|
||||||
|
|
||||||
|
def test_zero_output_and_process_impairment_never_create_checkpoint() -> None:
|
||||||
|
def impaired(bundle):
|
||||||
|
reads = _reads(bundle)
|
||||||
|
stages = _stages()
|
||||||
|
outcome = execution.impaired_adapter_outcome(bundle, execution.ProcessOutcomeReason.PROCESS_FAILURE, runtime_ms=1)
|
||||||
|
return checkpoint.ArmExecutionCaptureV1(outcome, reads, stages, (), _observations(bundle))
|
||||||
|
|
||||||
|
client = _Client()
|
||||||
|
result = _run(_bundles()[0], _Adapter(impaired), client)
|
||||||
|
assert result.reason is checkpoint.CheckpointReason.RECEIPT_IMPAIRED
|
||||||
|
assert client.put_calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_freeze_revalidates_completed_receipt_against_current_bundle(monkeypatch) -> None:
|
||||||
|
bundle = _bundles()[0]
|
||||||
|
foreign, _ = _completed_receipt(bundle)
|
||||||
|
foreign = replace(foreign, environment_digest=_digest("foreign-environment"), receipt_digest="")
|
||||||
|
monkeypatch.setattr(checkpoint, "build_execution_receipt", lambda *args, **kwargs: foreign)
|
||||||
|
client = _Client()
|
||||||
|
adapter = _Adapter()
|
||||||
|
|
||||||
|
result = _run(bundle, adapter, client)
|
||||||
|
|
||||||
|
assert result.status is checkpoint.CheckpointStatus.IMPAIRED
|
||||||
|
assert result.reason is checkpoint.CheckpointReason.RECEIPT_MISMATCH
|
||||||
|
assert adapter.calls == [bundle]
|
||||||
|
assert client.put_calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_repository_write_readback_and_unauthorized_read_are_closed() -> None:
|
||||||
|
unauthorized = _authority(repository.ArtifactActorRole.DETECTOR)
|
||||||
|
client = _Client()
|
||||||
|
result = _run(_bundles()[0], _Adapter(), client, authority=unauthorized)
|
||||||
|
assert result.reason is checkpoint.CheckpointReason.ARTIFACT_READBACK_FAILED
|
||||||
|
assert result.reference is None
|
||||||
|
assert len(client.put_calls) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_provider_exception_is_redacted_and_has_no_exception_chain() -> None:
|
||||||
|
class Exploding:
|
||||||
|
def execute(self, bundle):
|
||||||
|
raise RuntimeError("private-canary password=/restricted/repository")
|
||||||
|
|
||||||
|
result = _run(_bundles()[0], Exploding(), _Client())
|
||||||
|
assert result.reason is checkpoint.CheckpointReason.ADAPTER_FAILURE
|
||||||
|
assert "private" not in str(result)
|
||||||
|
assert "restricted" not in str(result)
|
||||||
|
|
||||||
|
|
||||||
|
def test_receipt_and_checkpoint_direct_construction_bypasses_are_rejected() -> None:
|
||||||
|
bundle = _bundles()[0]
|
||||||
|
capture = _capture(bundle)
|
||||||
|
value = receipt.build_execution_receipt(bundle, capture.process_outcome, capture.input_reads, capture.stage_executions)
|
||||||
|
with pytest.raises(receipt.ExecutionReceiptError):
|
||||||
|
replace(value, status=receipt.ReceiptStatus.COMPLETED, reason=receipt.ReceiptReason.INPUT_EMPTY, receipt_digest="")
|
||||||
|
serialized = receipt.execution_receipt_value(value)
|
||||||
|
serialized["unexpected"] = "bypass"
|
||||||
|
with pytest.raises(receipt.ExecutionReceiptError):
|
||||||
|
receipt.execution_receipt_from_value(serialized)
|
||||||
|
with pytest.raises(checkpoint.ObservationCheckpointError):
|
||||||
|
checkpoint.ArmCheckpointResultV1(
|
||||||
|
checkpoint.CheckpointStatus.COMPLETE,
|
||||||
|
checkpoint.CheckpointReason.NONE,
|
||||||
|
bundle.plan_digest,
|
||||||
|
bundle.arm.arm_id,
|
||||||
|
_digest("checkpoint"),
|
||||||
|
None,
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_serialized_checkpoint_extra_field_is_impaired_without_adapter_call() -> None:
|
||||||
|
bundle, client, _, frozen = _frozen()
|
||||||
|
accepted = _repo(client).get(
|
||||||
|
frozen.reference,
|
||||||
|
expected_kind=ArtifactKind.OBSERVATION,
|
||||||
|
authority=_custodian(),
|
||||||
|
expected_access_policy_digest=_artifact_digest("read-policy"),
|
||||||
|
)
|
||||||
|
payload = dict(accepted.artifact.payload)
|
||||||
|
payload["unexpected"] = "bypass"
|
||||||
|
content = canonical_artifact_bytes(
|
||||||
|
ArtifactKind.OBSERVATION,
|
||||||
|
payload,
|
||||||
|
access_class=ArtifactAccessClass.CUSTODIAN_SEALED,
|
||||||
|
provenance_digest=frozen.checkpoint_digest,
|
||||||
|
)
|
||||||
|
changed_reference = artifact_reference(content)
|
||||||
|
changed_client = _Client()
|
||||||
|
_repo(changed_client).put_if_absent(content, reference=changed_reference)
|
||||||
|
adapter = _Adapter()
|
||||||
|
|
||||||
|
result = _run(
|
||||||
|
bundle,
|
||||||
|
adapter,
|
||||||
|
changed_client,
|
||||||
|
selector=checkpoint.CheckpointSelectorV1(changed_reference, frozen.checkpoint_digest),
|
||||||
|
)
|
||||||
|
assert result.reason is checkpoint.CheckpointReason.CHECKPOINT_MISMATCH
|
||||||
|
assert adapter.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_serialization_surfaces_are_closed_and_contain_no_labels_paths_or_secrets() -> None:
|
||||||
|
bundle, client, _, frozen = _frozen()
|
||||||
|
accepted = _repo(client).get(
|
||||||
|
frozen.reference,
|
||||||
|
expected_kind=ArtifactKind.OBSERVATION,
|
||||||
|
authority=_custodian(),
|
||||||
|
expected_access_policy_digest=_artifact_digest("read-policy"),
|
||||||
|
)
|
||||||
|
content = accepted.content.lower()
|
||||||
|
for forbidden in (b"label", b"expected_outcome", b"password", b"secret", b"/home/", b"repository content"):
|
||||||
|
assert forbidden not in content
|
||||||
|
assert {field.name for field in fields(checkpoint.ArmCheckpointResultV1)} == {
|
||||||
|
"status",
|
||||||
|
"reason",
|
||||||
|
"plan_digest",
|
||||||
|
"arm_id",
|
||||||
|
"checkpoint_digest",
|
||||||
|
"reference",
|
||||||
|
"result_digest",
|
||||||
|
}
|
||||||
|
assert bundle.arm.arm_id.encode() in content
|
||||||
Reference in New Issue
Block a user