diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index fe3ddcb3..755d9671 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -176,14 +176,13 @@ - Done when component results remain independently reportable, missing or mismatched components block combination, and no combined arm acquires unrelated proof authority. - _Requirements: 9.1, 9.2, 9.3, 9.4, 9.5_ - _Boundary: Combination Planner_ -- [ ] 6.3 Build the isolated label-blind execution bundle and adapter boundary +- [x] 6.3 Build the isolated label-blind execution bundle and adapter boundary - Materialize identical ordered case/input identities, code/change references, arm registration, budgets, environment identity, and output destination for each planned component arm. - Launch only through an isolated local, Docker, or AX adapter with an allowlisted environment and no custody, private-label, sealed-label, review, expected-outcome, model-secret, or store-admin credentials. - Keep execution-plane back-pressure and health external while recording bounded benchmark process outcomes. - 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_ - _Boundary: Isolated Arm Executor_ - - _Blocked: debug attempted twice, still failing — public bundle serialization and execution revalidate the registered plan but do not rederive the execution-source projection from the exact reviewed public-material manifest, artifact-set identity, and ordinary-selection authority, so rehashed source-authority substitutions remain accepted._ - [ ] 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. - Validate and durably freeze one custodian-sealed observation set for every planned component arm before spend. @@ -432,4 +431,4 @@ - Task 5.4 persists one canonical AVAILABLE head and permits only its direct AVAILABLE-to-SPENT successor through capability-gated conditional writes; domain digests govern state while advancing version and ETag tokens prove storage concurrency and exact rereads before any caller may expose labels. - 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.3 remains blocked after two debug rounds: the label-free source projection and exact plan authority are implemented and mechanically green, but every public serializer/executor path must still rederive that projection from the exact reviewed Task 4.3/4.4 source authorities to reject rehashed source-identity substitution. +- 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. diff --git a/benchmarks/valid/isolated_execution.py b/benchmarks/valid/isolated_execution.py new file mode 100644 index 00000000..fde6632e --- /dev/null +++ b/benchmarks/valid/isolated_execution.py @@ -0,0 +1,315 @@ +"""Isolated label-blind adapter execution and closed process outcomes.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Protocol + +from benchmarks.valid.arm_contract import RegisteredEvaluationPlanV1 +from benchmarks.valid.isolated_execution_bundle import ( + LabelBlindExecutionBundleV1, + label_blind_execution_bundle_bytes, +) +from benchmarks.valid.isolated_execution_bundle import ( + build_component_execution_bundles as build_component_execution_bundles, +) +from benchmarks.valid.isolated_execution_bundle import ( + build_execution_environment as build_execution_environment, +) +from benchmarks.valid.isolated_execution_bundle import ( + execution_environment_bytes as execution_environment_bytes, +) +from benchmarks.valid.isolated_execution_contract import ( + PROCESS_OUTCOME_SCHEMA, + IsolatedExecutionError, + ProcessOutcomeReason, + ProcessOutcomeStatus, + _bind_digest, + _digest, + _opaque, + _positive, +) +from benchmarks.valid.isolated_execution_contract import ( + SAFE_EXECUTION_ENVIRONMENT as SAFE_EXECUTION_ENVIRONMENT, +) +from benchmarks.valid.isolated_execution_contract import ( + ArmExecutionBudgetV1 as ArmExecutionBudgetV1, +) +from benchmarks.valid.isolated_execution_contract import ( + ComponentArmExecutionV1 as ComponentArmExecutionV1, +) +from benchmarks.valid.isolated_execution_contract import ( + ExecutionAdapterKind as ExecutionAdapterKind, +) +from benchmarks.valid.isolated_execution_contract import ( + ExecutionEnvironmentV1 as ExecutionEnvironmentV1, +) +from benchmarks.valid.isolated_execution_contract import ( + LabelBlindCaseInputV1 as LabelBlindCaseInputV1, +) +from benchmarks.valid.isolated_execution_contract import ( + OutputDestinationV1 as OutputDestinationV1, +) +from benchmarks.valid.isolated_execution_plan import ( + ComponentConfigurationAuthorityV1 as ComponentConfigurationAuthorityV1, +) +from benchmarks.valid.isolated_execution_plan import ( + ExecutionPlanArmBindingV1 as ExecutionPlanArmBindingV1, +) +from benchmarks.valid.isolated_execution_plan import ( + ExecutionPlanProjectionV1 as ExecutionPlanProjectionV1, +) +from benchmarks.valid.isolated_execution_source import ( + ExecutionSourceProjectionV1 as ExecutionSourceProjectionV1, +) +from benchmarks.valid.isolated_execution_source import ( + ExecutionSourceRecordV1 as ExecutionSourceRecordV1, +) +from benchmarks.valid.isolated_execution_source import ( + build_execution_source_projection as build_execution_source_projection, +) +from benchmarks.valid.isolated_execution_source import ( + execution_source_projection_bytes as execution_source_projection_bytes, +) +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 openultrasast.core import canonical +from openultrasast.core.canonical import ContentResolver, JsonValue +from openultrasast.core.factpack import ReviewIndependencePolicy + + +@dataclass(frozen=True) +class ArmProcessOutcomeV1: + bundle_digest: str + arm_id: str + status: ProcessOutcomeStatus + reason: ProcessOutcomeReason + runtime_ms: int + output_digest: str + output_bytes: int + outcome_digest: str + + def __post_init__(self) -> None: + if type(self) is not ArmProcessOutcomeV1: + raise IsolatedExecutionError("process outcome must use exact ArmProcessOutcomeV1") + _digest(self.bundle_digest, "outcome bundle") + _opaque(self.arm_id, "outcome arm id") + if type(self.status) is not ProcessOutcomeStatus or type(self.reason) is not ProcessOutcomeReason: + raise IsolatedExecutionError("process outcome must use closed status and reason enums") + if type(self.runtime_ms) is not int or not 0 <= self.runtime_ms <= 86_400_000: + raise IsolatedExecutionError("runtime must be a bounded nonnegative integer") + _validate_outcome_state(self) + _bind_digest(self, "outcome_digest", canonical.content_digest(_outcome_value(self, include_digest=False))) + + +def _validate_outcome_state(outcome: ArmProcessOutcomeV1) -> None: + if outcome.status is ProcessOutcomeStatus.COMPLETED: + if outcome.reason is not ProcessOutcomeReason.NONE: + raise IsolatedExecutionError("completed outcome must use the none reason") + _digest(outcome.output_digest, "output") + _positive(outcome.output_bytes, "output bytes", 64 * 1024 * 1024) + return + if outcome.reason is ProcessOutcomeReason.NONE: + raise IsolatedExecutionError("impaired outcome requires a closed reason") + if outcome.output_digest != "" or outcome.output_bytes != 0: + raise IsolatedExecutionError("impaired outcome cannot claim detector output") + + +def _outcome_value(outcome: ArmProcessOutcomeV1, *, include_digest: bool) -> dict[str, JsonValue]: + value: dict[str, JsonValue] = { + "schema_version": PROCESS_OUTCOME_SCHEMA, + "bundle_digest": outcome.bundle_digest, + "arm_id": outcome.arm_id, + "status": outcome.status.value, + "reason": outcome.reason.value, + "runtime_ms": outcome.runtime_ms, + "output_digest": outcome.output_digest or None, + "output_bytes": outcome.output_bytes, + } + if include_digest: + value["outcome_digest"] = outcome.outcome_digest + return value + + +def completed_adapter_outcome( + bundle: LabelBlindExecutionBundleV1, + output: bytes, + *, + runtime_ms: int, +) -> ArmProcessOutcomeV1: + bundle.__post_init__() + if type(output) is not bytes or not output or len(output) > bundle.budget.maximum_output_bytes: + raise IsolatedExecutionError("adapter output must be nonempty and within the registered bound") + return ArmProcessOutcomeV1( + bundle.bundle_digest, + bundle.arm.arm_id, + ProcessOutcomeStatus.COMPLETED, + ProcessOutcomeReason.NONE, + runtime_ms, + canonical.bytes_digest(output), + len(output), + "", + ) + + +def impaired_adapter_outcome( + bundle: LabelBlindExecutionBundleV1, + reason: ProcessOutcomeReason, + *, + runtime_ms: int, +) -> ArmProcessOutcomeV1: + bundle.__post_init__() + if type(reason) is not ProcessOutcomeReason or reason is ProcessOutcomeReason.NONE: + raise IsolatedExecutionError("impairment requires a closed non-none reason") + return ArmProcessOutcomeV1( + bundle.bundle_digest, + bundle.arm.arm_id, + ProcessOutcomeStatus.IMPAIRED, + reason, + runtime_ms, + "", + 0, + "", + ) + + +def arm_process_outcome_bytes( + plan: RegisteredEvaluationPlanV1, + bundle: LabelBlindExecutionBundleV1, + outcome: ArmProcessOutcomeV1, + manifest: LabelBlindPopulationManifestV3, + public_material_manifest: PublicPopulationMaterialManifestV1, + selection: OrdinarySelectionV1, + *, + strategy_review_policy: ReviewIndependencePolicy | None = None, + strategy_resolver: ContentResolver | None = None, +) -> bytes: + label_blind_execution_bundle_bytes( + plan, + bundle, + manifest, + public_material_manifest, + selection, + strategy_review_policy=strategy_review_policy, + strategy_resolver=strategy_resolver, + ) + if type(outcome) is not ArmProcessOutcomeV1: + raise IsolatedExecutionError("process outcome must use exact ArmProcessOutcomeV1") + outcome.__post_init__() + if outcome.bundle_digest != bundle.bundle_digest or outcome.arm_id != bundle.arm.arm_id: + raise IsolatedExecutionError("process outcome does not bind the authoritative bundle") + return canonical.canonical_bytes(_outcome_value(outcome, include_digest=True)) + + +class IsolatedExecutionAdapter(Protocol): + def execute(self, bundle: LabelBlindExecutionBundleV1) -> ArmProcessOutcomeV1: ... + + +def _valid_adapter_outcome( + outcome: object, + bundle: LabelBlindExecutionBundleV1, +) -> ArmProcessOutcomeV1 | None: + if type(outcome) is not ArmProcessOutcomeV1: + return None + try: + outcome.__post_init__() + except (TypeError, ValueError): + return None + if outcome.bundle_digest != bundle.bundle_digest or outcome.arm_id != bundle.arm.arm_id: + return None + if outcome.runtime_ms > bundle.budget.deadline_seconds * 1000: + return None + if outcome.output_bytes > bundle.budget.maximum_output_bytes: + return None + return outcome + + +def _execute_one( + bundle: LabelBlindExecutionBundleV1, + adapter: IsolatedExecutionAdapter, +) -> ArmProcessOutcomeV1: + failed = False + try: + candidate = adapter.execute(bundle) + except Exception: # Adapter diagnostics are deliberately not retained. + failed = True + candidate = None + if failed: + return impaired_adapter_outcome(bundle, ProcessOutcomeReason.PROCESS_FAILURE, runtime_ms=0) + valid = _valid_adapter_outcome(candidate, bundle) + if valid is None: + return impaired_adapter_outcome(bundle, ProcessOutcomeReason.OUTPUT_INVALID, runtime_ms=0) + return valid + + +def execute_component_bundles( + plan: RegisteredEvaluationPlanV1, + bundles: tuple[LabelBlindExecutionBundleV1, ...], + adapter: IsolatedExecutionAdapter, + manifest: LabelBlindPopulationManifestV3, + public_material_manifest: PublicPopulationMaterialManifestV1, + selection: OrdinarySelectionV1, + *, + strategy_review_policy: ReviewIndependencePolicy | None = None, + strategy_resolver: ContentResolver | None = None, +) -> tuple[ArmProcessOutcomeV1, ...]: + if type(bundles) is not tuple or not bundles: + raise IsolatedExecutionError("component bundles must be a nonempty tuple") + if any(type(row) is not LabelBlindExecutionBundleV1 for row in bundles): + raise IsolatedExecutionError("component bundles must use exact bundle values") + for row in bundles: + label_blind_execution_bundle_bytes( + plan, + row, + manifest, + public_material_manifest, + selection, + strategy_review_policy=strategy_review_policy, + strategy_resolver=strategy_resolver, + ) + if tuple(row.arm.arm_id for row in bundles) != tuple(sorted({row.arm.arm_id for row in bundles})): + raise IsolatedExecutionError("component bundles must be unique and canonical") + first = bundles[0] + if any( + row.case_inputs is not first.case_inputs + or row.source_projection is not first.source_projection + or row.input_set_digest != first.input_set_digest + or row.plan_digest != first.plan_digest + or row.manifest_digest != first.manifest_digest + for row in bundles + ): + raise IsolatedExecutionError("component bundles must share one exact plan and ordered input set") + return tuple(_execute_one(row, adapter) for row in bundles) + + +__all__ = [ + "ArmExecutionBudgetV1", + "ArmProcessOutcomeV1", + "ComponentArmExecutionV1", + "ComponentConfigurationAuthorityV1", + "ExecutionAdapterKind", + "ExecutionEnvironmentV1", + "ExecutionPlanArmBindingV1", + "ExecutionPlanProjectionV1", + "ExecutionSourceProjectionV1", + "ExecutionSourceRecordV1", + "IsolatedExecutionAdapter", + "IsolatedExecutionError", + "LabelBlindCaseInputV1", + "LabelBlindExecutionBundleV1", + "OutputDestinationV1", + "ProcessOutcomeReason", + "ProcessOutcomeStatus", + "SAFE_EXECUTION_ENVIRONMENT", + "arm_process_outcome_bytes", + "build_component_execution_bundles", + "build_execution_environment", + "build_execution_source_projection", + "completed_adapter_outcome", + "execute_component_bundles", + "execution_environment_bytes", + "execution_source_projection_bytes", + "impaired_adapter_outcome", + "label_blind_execution_bundle_bytes", +] diff --git a/benchmarks/valid/isolated_execution_bundle.py b/benchmarks/valid/isolated_execution_bundle.py new file mode 100644 index 00000000..17588fa5 --- /dev/null +++ b/benchmarks/valid/isolated_execution_bundle.py @@ -0,0 +1,329 @@ +"""Canonical label-blind component bundle construction and validation.""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass + +from benchmarks.valid.arm_contract import RegisteredEvaluationPlanV1 +from benchmarks.valid.isolated_execution_contract import ( + BUNDLE_SCHEMA, + SAFE_EXECUTION_ENVIRONMENT, + ArmExecutionBudgetV1, + ComponentArmExecutionV1, + ExecutionAdapterKind, + ExecutionEnvironmentV1, + IsolatedExecutionError, + LabelBlindCaseInputV1, + OutputDestinationV1, + _arm_value, + _bind_digest, + _budget_value, + _case_value, + _destination_value, + _digest, + _environment_value, +) +from benchmarks.valid.isolated_execution_plan import ( + ExecutionPlanProjectionV1, + component_arm_from_projection, + project_execution_plan, +) +from benchmarks.valid.isolated_execution_plan import ( + _projection_value as _plan_projection_value, +) +from benchmarks.valid.isolated_execution_source import ( + ExecutionSourceProjectionV1, + build_execution_source_projection, + validate_execution_cases, +) +from benchmarks.valid.isolated_execution_source import ( + _projection_value as _source_projection_value, +) +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 openultrasast.core import canonical +from openultrasast.core.canonical import ContentResolver, JsonValue +from openultrasast.core.evaluation_measurement import ArmKindV3 +from openultrasast.core.factpack import ReviewIndependencePolicy + + +@dataclass(frozen=True) +class LabelBlindExecutionBundleV1: + plan_digest: str + declaration_digest: str + population_digest: str + freeze_digest: str + manifest_digest: str + input_set_digest: str + source_projection: ExecutionSourceProjectionV1 + plan_projection: ExecutionPlanProjectionV1 + arm: ComponentArmExecutionV1 + case_inputs: tuple[LabelBlindCaseInputV1, ...] + budget: ArmExecutionBudgetV1 + environment: ExecutionEnvironmentV1 + output_destination: OutputDestinationV1 + bundle_digest: str + + def __post_init__(self) -> None: + if type(self) is not LabelBlindExecutionBundleV1: + raise IsolatedExecutionError("bundle must use exact LabelBlindExecutionBundleV1") + for item, field in ( + (self.plan_digest, "plan"), + (self.declaration_digest, "declaration"), + (self.population_digest, "population"), + (self.freeze_digest, "freeze"), + (self.manifest_digest, "manifest"), + (self.input_set_digest, "input set"), + ): + _digest(item, field) + _validate_bundle_members(self) + _bind_digest(self, "bundle_digest", canonical.content_digest(_bundle_value(self, include_digest=False))) + + +def _validate_bundle_members(bundle: LabelBlindExecutionBundleV1) -> None: + if type(bundle.source_projection) is not ExecutionSourceProjectionV1: + raise IsolatedExecutionError("bundle source must use exact ExecutionSourceProjectionV1") + bundle.source_projection.__post_init__() + if ( + bundle.source_projection.label_blind_manifest_digest != bundle.manifest_digest + or bundle.source_projection.input_set_digest != bundle.input_set_digest + ): + raise IsolatedExecutionError("bundle source projection does not match the reviewed input authority") + if type(bundle.plan_projection) is not ExecutionPlanProjectionV1: + raise IsolatedExecutionError("bundle plan must use exact ExecutionPlanProjectionV1") + bundle.plan_projection.__post_init__() + expected_arm = component_arm_from_projection(bundle.plan_projection) + if type(bundle.arm) is not ComponentArmExecutionV1 or bundle.arm != expected_arm: + raise IsolatedExecutionError("bundle arm is not the exact registered plan component") + validate_execution_cases(bundle.case_inputs, bundle.source_projection) + _validate_bundle_resources(bundle) + + +def _validate_bundle_resources(bundle: LabelBlindExecutionBundleV1) -> None: + if type(bundle.budget) is not ArmExecutionBudgetV1: + raise IsolatedExecutionError("bundle budget must use exact ArmExecutionBudgetV1") + if type(bundle.environment) is not ExecutionEnvironmentV1: + raise IsolatedExecutionError("bundle environment must use exact ExecutionEnvironmentV1") + if type(bundle.output_destination) is not OutputDestinationV1: + raise IsolatedExecutionError("bundle destination must use exact OutputDestinationV1") + bundle.budget.__post_init__() + bundle.environment.__post_init__() + bundle.output_destination.__post_init__() + projection = bundle.plan_projection + if ( + bundle.plan_digest != projection.plan_digest + or bundle.declaration_digest != projection.declaration_digest + or bundle.population_digest != projection.population_digest + or bundle.freeze_digest != projection.freeze_digest + or bundle.input_set_digest != projection.input_set_digest + ): + raise IsolatedExecutionError("bundle identities do not match the validated execution plan") + arm_id = bundle.arm.arm_id + if bundle.budget.arm_id != arm_id or bundle.output_destination.arm_id != arm_id: + raise IsolatedExecutionError("bundle resources do not bind the same component arm") + if bundle.output_destination.plan_digest != bundle.plan_digest: + raise IsolatedExecutionError("output destination does not bind the plan") + if bundle.budget.registered_budget_digest != bundle.arm.registered_budget_digest: + raise IsolatedExecutionError("execution budget does not match the registered budget") + if bundle.output_destination.maximum_output_bytes != bundle.budget.maximum_output_bytes: + raise IsolatedExecutionError("output destination does not match the execution budget") + + +def _bundle_value(bundle: LabelBlindExecutionBundleV1, *, include_digest: bool) -> dict[str, JsonValue]: + value: dict[str, JsonValue] = { + "schema_version": BUNDLE_SCHEMA, + "plan_digest": bundle.plan_digest, + "declaration_digest": bundle.declaration_digest, + "population_digest": bundle.population_digest, + "freeze_digest": bundle.freeze_digest, + "manifest_digest": bundle.manifest_digest, + "input_set_digest": bundle.input_set_digest, + "source_projection": _source_projection_value(bundle.source_projection, include_digest=True), + "plan_projection": _plan_projection_value(bundle.plan_projection, include_digest=True), + "arm": _arm_value(bundle.arm, include_digest=True), + "case_inputs": tuple(_case_value(row, include_digest=True) for row in bundle.case_inputs), + "budget": _budget_value(bundle.budget, include_digest=True), + "environment": _environment_value(bundle.environment, include_digest=True), + "output_destination": _destination_value(bundle.output_destination, include_digest=True), + } + if include_digest: + value["bundle_digest"] = bundle.bundle_digest + return value + + +def validate_bundle_for_plan( + plan: RegisteredEvaluationPlanV1, + bundle: LabelBlindExecutionBundleV1, + manifest: LabelBlindPopulationManifestV3, + public_material_manifest: PublicPopulationMaterialManifestV1, + selection: OrdinarySelectionV1, + *, + strategy_review_policy: ReviewIndependencePolicy | None = None, + strategy_resolver: ContentResolver | None = None, +) -> None: + if type(bundle) is not LabelBlindExecutionBundleV1: + raise IsolatedExecutionError("bundle must use exact LabelBlindExecutionBundleV1") + expected_plan = project_execution_plan( + plan, + bundle.arm.arm_id, + strategy_review_policy=strategy_review_policy, + strategy_resolver=strategy_resolver, + ) + expected_source = build_execution_source_projection( + manifest, + public_material_manifest, + selection, + ) + bundle.__post_init__() + if bundle.plan_projection != expected_plan: + raise IsolatedExecutionError("bundle projection is not derived from the authoritative registered plan") + if bundle.source_projection != expected_source: + raise IsolatedExecutionError("bundle source is not derived from the authoritative reviewed inputs") + + +def label_blind_execution_bundle_bytes( + plan: RegisteredEvaluationPlanV1, + bundle: LabelBlindExecutionBundleV1, + manifest: LabelBlindPopulationManifestV3, + public_material_manifest: PublicPopulationMaterialManifestV1, + selection: OrdinarySelectionV1, + *, + strategy_review_policy: ReviewIndependencePolicy | None = None, + strategy_resolver: ContentResolver | None = None, +) -> bytes: + validate_bundle_for_plan( + plan, + bundle, + manifest, + public_material_manifest, + selection, + strategy_review_policy=strategy_review_policy, + strategy_resolver=strategy_resolver, + ) + return canonical.canonical_bytes(_bundle_value(bundle, include_digest=True)) + + +def build_execution_environment( + adapter_kind: ExecutionAdapterKind, + _ambient: Mapping[str, str] | None = None, +) -> ExecutionEnvironmentV1: + if type(adapter_kind) is not ExecutionAdapterKind: + raise IsolatedExecutionError("adapter kind must use the closed ExecutionAdapterKind enum") + return ExecutionEnvironmentV1(adapter_kind, tuple(sorted(SAFE_EXECUTION_ENVIRONMENT.items())), "") + + +def execution_environment_bytes(environment: ExecutionEnvironmentV1) -> bytes: + if type(environment) is not ExecutionEnvironmentV1: + raise IsolatedExecutionError("environment must use exact ExecutionEnvironmentV1") + environment.__post_init__() + return canonical.canonical_bytes(_environment_value(environment, include_digest=True)) + + +def _budget_map( + budgets: tuple[ArmExecutionBudgetV1, ...], + component_ids: tuple[str, ...], +) -> dict[str, ArmExecutionBudgetV1]: + if type(budgets) is not tuple or any(type(row) is not ArmExecutionBudgetV1 for row in budgets): + raise IsolatedExecutionError("budgets must use an exact tuple of ArmExecutionBudgetV1 values") + for row in budgets: + row.__post_init__() + if tuple(sorted(row.arm_id for row in budgets)) != component_ids: + raise IsolatedExecutionError("budgets must occur exactly once for every component arm") + return {row.arm_id: row for row in budgets} + + +def build_component_execution_bundles( + plan: RegisteredEvaluationPlanV1, + manifest: LabelBlindPopulationManifestV3, + selection: OrdinarySelectionV1, + public_material_manifest: PublicPopulationMaterialManifestV1, + cases: tuple[LabelBlindCaseInputV1, ...], + budgets: tuple[ArmExecutionBudgetV1, ...], + *, + adapter_kind: ExecutionAdapterKind, + output_namespace_digest: str, + strategy_review_policy: ReviewIndependencePolicy | None = None, + strategy_resolver: ContentResolver | None = None, +) -> tuple[LabelBlindExecutionBundleV1, ...]: + source_projection = build_execution_source_projection(manifest, public_material_manifest, selection) + shared_cases = validate_execution_cases(cases, source_projection) + namespace = _digest(output_namespace_digest, "output namespace") + registrations = tuple( + sorted( + (row for row in plan.registrations if row.configuration.kind is ArmKindV3.COMPONENT), + key=lambda row: row.arm_id, + ) + ) + if not registrations: + raise IsolatedExecutionError("plan must contain at least one component arm") + component_ids = tuple(row.arm_id for row in registrations) + budget_by_arm = _budget_map(budgets, component_ids) + environment = build_execution_environment(adapter_kind) + projections = tuple( + project_execution_plan( + plan, + row.arm_id, + strategy_review_policy=strategy_review_policy, + strategy_resolver=strategy_resolver, + ) + for row in registrations + ) + if any( + (item.population_digest, item.freeze_digest, item.input_set_digest) + != (manifest.population_digest, manifest.freeze_digest, manifest.input_set_digest) + for item in projections + ): + raise IsolatedExecutionError("registered plan does not match the reviewed label-blind manifest") + return tuple( + _build_bundle( + manifest, + source_projection, + projection, + shared_cases, + budget_by_arm[projection.target_configuration.arm_id], + environment, + namespace, + ) + for projection in projections + ) + + +def _build_bundle( + manifest: LabelBlindPopulationManifestV3, + source_projection: ExecutionSourceProjectionV1, + projection: ExecutionPlanProjectionV1, + cases: tuple[LabelBlindCaseInputV1, ...], + budget: ArmExecutionBudgetV1, + environment: ExecutionEnvironmentV1, + namespace: str, +) -> LabelBlindExecutionBundleV1: + arm = component_arm_from_projection(projection) + destination = OutputDestinationV1(projection.plan_digest, arm.arm_id, namespace, budget.maximum_output_bytes, "") + return LabelBlindExecutionBundleV1( + projection.plan_digest, + projection.declaration_digest, + manifest.population_digest, + manifest.freeze_digest, + manifest.manifest_digest, + manifest.input_set_digest, + source_projection, + projection, + arm, + cases, + budget, + environment, + destination, + "", + ) + + +__all__ = [ + "LabelBlindExecutionBundleV1", + "build_component_execution_bundles", + "build_execution_environment", + "execution_environment_bytes", + "label_blind_execution_bundle_bytes", + "validate_bundle_for_plan", +] diff --git a/benchmarks/valid/isolated_execution_contract.py b/benchmarks/valid/isolated_execution_contract.py new file mode 100644 index 00000000..2bc39b5a --- /dev/null +++ b/benchmarks/valid/isolated_execution_contract.py @@ -0,0 +1,311 @@ +"""Closed label-blind bundle and process-outcome contracts.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from enum import StrEnum + +from benchmarks.valid.arm_contract import ArmRole +from benchmarks.valid.replacement_artifact_contract import ( + ArtifactAccessClass, + ArtifactKind, + ArtifactReference, +) +from openultrasast.core import canonical +from openultrasast.core.canonical import JsonValue +from openultrasast.core.evaluation_measurement import ArmKindV3, ScopeKey + +BUNDLE_SCHEMA = "openultrasast.valid-detection-benchmark.label-blind-execution-bundle.v1" +ENVIRONMENT_SCHEMA = "openultrasast.valid-detection-benchmark.execution-environment.v1" +PROCESS_OUTCOME_SCHEMA = "openultrasast.valid-detection-benchmark.arm-process-outcome.v1" +SAFE_EXECUTION_ENVIRONMENT: dict[str, str] = { + "LANG": "C.UTF-8", + "LC_ALL": "C.UTF-8", + "PATH": "/usr/local/bin:/usr/bin:/bin", + "PYTHONUNBUFFERED": "1", + "TZ": "UTC", +} +_DIGEST = re.compile(r"[0-9a-f]{64}") +_OPAQUE_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}") + + +class IsolatedExecutionError(ValueError): + """An execution value crosses or weakens the label-blind boundary.""" + + +class ExecutionAdapterKind(StrEnum): + LOCAL = "local" + DOCKER = "docker" + AX = "ax" + + +class ProcessOutcomeStatus(StrEnum): + COMPLETED = "completed" + IMPAIRED = "impaired" + + +class ProcessOutcomeReason(StrEnum): + NONE = "none" + BACKPRESSURE = "backpressure" + DEADLINE = "deadline" + BUDGET_EXHAUSTED = "budget_exhausted" + RESOURCE_LIMIT = "resource_limit" + PROCESS_FAILURE = "process_failure" + OUTPUT_INVALID = "output_invalid" + + +def _digest(value: object, field: str) -> str: + if type(value) is not str or _DIGEST.fullmatch(value) is None: + raise IsolatedExecutionError(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_ID.fullmatch(value) is None: + raise IsolatedExecutionError(f"{field} must be an opaque identifier") + return value + + +def _positive(value: object, field: str, maximum: int) -> int: + if type(value) is not int or not 0 < value <= maximum: + raise IsolatedExecutionError(f"{field} must be a bounded positive integer") + return value + + +def _reference_value(reference: ArtifactReference) -> dict[str, JsonValue]: + if type(reference) is not ArtifactReference: + raise IsolatedExecutionError("code reference must use exact ArtifactReference") + reference.__post_init__() + if reference.artifact_kind is not ArtifactKind.POPULATION: + raise IsolatedExecutionError("code reference must be a population artifact") + if reference.access_class not in {ArtifactAccessClass.PUBLIC, ArtifactAccessClass.PRIVATE}: + raise IsolatedExecutionError("sealed or operator artifacts cannot cross the execution boundary") + _opaque(reference.content_digest, "code content digest") + _opaque(reference.provenance_digest, "code provenance digest") + return { + "artifact_kind": reference.artifact_kind.value, + "access_class": reference.access_class.value, + "content_digest": reference.content_digest, + "byte_length": _positive(reference.byte_length, "code byte length", 1 << 34), + "provenance_digest": reference.provenance_digest, + } + + +@dataclass(frozen=True) +class LabelBlindCaseInputV1: + input_identity_digest: str + change_input_digest: str + code_reference: ArtifactReference + case_digest: str + + def __post_init__(self) -> None: + if type(self) is not LabelBlindCaseInputV1: + raise IsolatedExecutionError("case input must use exact LabelBlindCaseInputV1") + _digest(self.input_identity_digest, "input identity") + _digest(self.change_input_digest, "change input") + expected = canonical.content_digest(_case_value(self, include_digest=False)) + _bind_digest(self, "case_digest", expected) + + +def _case_value(value: LabelBlindCaseInputV1, *, include_digest: bool) -> dict[str, JsonValue]: + result: dict[str, JsonValue] = { + "input_identity_digest": _digest(value.input_identity_digest, "input identity"), + "change_input_digest": _digest(value.change_input_digest, "change input"), + "code_reference": _reference_value(value.code_reference), + } + if include_digest: + result["case_digest"] = _digest(value.case_digest, "case") + return result + + +@dataclass(frozen=True) +class ComponentArmExecutionV1: + arm_id: str + role: ArmRole + registration_digest: str + configuration_kind: ArmKindV3 + configuration_identity_digest: str + analyzer_identity: str + fact_set_digest: str + configuration_digest: str + judgment_vocabulary_digest: str + outcome_mapping_digest: str + registered_budget_digest: str + execution_identity: str + exact_scopes: tuple[ScopeKey, ...] + execution_arm_digest: str + + def __post_init__(self) -> None: + if type(self) is not ComponentArmExecutionV1: + raise IsolatedExecutionError("execution arm must use exact ComponentArmExecutionV1") + _opaque(self.arm_id, "arm id") + if type(self.role) is not ArmRole or self.role is ArmRole.COMBINED: + raise IsolatedExecutionError("only shipped or experimental component arms may execute") + if type(self.configuration_kind) is not ArmKindV3 or self.configuration_kind is not ArmKindV3.COMPONENT: + raise IsolatedExecutionError("execution arm must be a component configuration") + _opaque(self.analyzer_identity, "analyzer identity") + _opaque(self.execution_identity, "execution identity") + for item, field in ( + (self.registration_digest, "registration"), + (self.configuration_identity_digest, "configuration identity"), + (self.fact_set_digest, "fact set"), + (self.configuration_digest, "configuration"), + (self.judgment_vocabulary_digest, "judgment vocabulary"), + (self.outcome_mapping_digest, "outcome mapping"), + (self.registered_budget_digest, "registered budget"), + ): + _digest(item, field) + if type(self.exact_scopes) is not tuple or not self.exact_scopes: + raise IsolatedExecutionError("execution scopes must be a nonempty tuple") + if any(type(item) is not ScopeKey for item in self.exact_scopes) or self.exact_scopes != tuple(sorted(set(self.exact_scopes))): + raise IsolatedExecutionError("execution scopes must be exact, unique, and canonical") + expected = canonical.content_digest(_arm_value(self, include_digest=False)) + _bind_digest(self, "execution_arm_digest", expected) + + +def _scope_value(value: ScopeKey) -> dict[str, JsonValue]: + value.__post_init__() + return {"family_id": value.family_id, "ecosystem": value.ecosystem} + + +def _arm_value(value: ComponentArmExecutionV1, *, include_digest: bool) -> dict[str, JsonValue]: + result: dict[str, JsonValue] = { + "arm_id": value.arm_id, + "role": value.role.value, + "registration_digest": value.registration_digest, + "configuration_kind": value.configuration_kind.value, + "configuration_identity_digest": value.configuration_identity_digest, + "analyzer_identity": value.analyzer_identity, + "fact_set_digest": value.fact_set_digest, + "configuration_digest": value.configuration_digest, + "judgment_vocabulary_digest": value.judgment_vocabulary_digest, + "outcome_mapping_digest": value.outcome_mapping_digest, + "registered_budget_digest": value.registered_budget_digest, + "execution_identity": value.execution_identity, + "exact_scopes": tuple(_scope_value(item) for item in value.exact_scopes), + } + if include_digest: + result["execution_arm_digest"] = value.execution_arm_digest + return result + + +@dataclass(frozen=True) +class ArmExecutionBudgetV1: + arm_id: str + registered_budget_digest: str + deadline_seconds: int + memory_bytes: int + disk_bytes: int + maximum_output_bytes: int + budget_digest: str + + def __post_init__(self) -> None: + if type(self) is not ArmExecutionBudgetV1: + raise IsolatedExecutionError("budget must use exact ArmExecutionBudgetV1") + _opaque(self.arm_id, "budget arm id") + _digest(self.registered_budget_digest, "registered budget") + _positive(self.deadline_seconds, "deadline seconds", 86_400) + _positive(self.memory_bytes, "memory bytes", 1 << 40) + _positive(self.disk_bytes, "disk bytes", 1 << 42) + _positive(self.maximum_output_bytes, "maximum output bytes", 64 * 1024 * 1024) + expected = canonical.content_digest(_budget_value(self, include_digest=False)) + _bind_digest(self, "budget_digest", expected) + + +def _budget_value(value: ArmExecutionBudgetV1, *, include_digest: bool) -> dict[str, JsonValue]: + result: dict[str, JsonValue] = { + "arm_id": value.arm_id, + "registered_budget_digest": value.registered_budget_digest, + "deadline_seconds": value.deadline_seconds, + "memory_bytes": value.memory_bytes, + "disk_bytes": value.disk_bytes, + "maximum_output_bytes": value.maximum_output_bytes, + } + if include_digest: + result["budget_digest"] = value.budget_digest + return result + + +@dataclass(frozen=True) +class ExecutionEnvironmentV1: + adapter_kind: ExecutionAdapterKind + variables: tuple[tuple[str, str], ...] + environment_digest: str + + def __post_init__(self) -> None: + if type(self) is not ExecutionEnvironmentV1 or type(self.adapter_kind) is not ExecutionAdapterKind: + raise IsolatedExecutionError("environment must use exact closed execution types") + if type(self.variables) is not tuple or any(type(item) is not tuple or len(item) != 2 for item in self.variables): + raise IsolatedExecutionError("environment variables must use an exact tuple") + if self.variables != tuple(sorted(SAFE_EXECUTION_ENVIRONMENT.items())): + raise IsolatedExecutionError("environment variables must equal the closed safe allowlist") + expected = canonical.content_digest(_environment_value(self, include_digest=False)) + _bind_digest(self, "environment_digest", expected) + + +def _environment_value(value: ExecutionEnvironmentV1, *, include_digest: bool) -> dict[str, JsonValue]: + result: dict[str, JsonValue] = { + "schema_version": ENVIRONMENT_SCHEMA, + "adapter_kind": value.adapter_kind.value, + "variables": tuple({"name": name, "value": item} for name, item in value.variables), + } + if include_digest: + result["environment_digest"] = value.environment_digest + return result + + +@dataclass(frozen=True) +class OutputDestinationV1: + plan_digest: str + arm_id: str + namespace_digest: str + maximum_output_bytes: int + destination_digest: str + + def __post_init__(self) -> None: + if type(self) is not OutputDestinationV1: + raise IsolatedExecutionError("output destination must use exact OutputDestinationV1") + _digest(self.plan_digest, "output plan") + _opaque(self.arm_id, "output arm id") + _digest(self.namespace_digest, "output namespace") + _positive(self.maximum_output_bytes, "maximum output bytes", 64 * 1024 * 1024) + expected = canonical.content_digest(_destination_value(self, include_digest=False)) + _bind_digest(self, "destination_digest", expected) + + +def _destination_value(value: OutputDestinationV1, *, include_digest: bool) -> dict[str, JsonValue]: + result: dict[str, JsonValue] = { + "plan_digest": value.plan_digest, + "arm_id": value.arm_id, + "namespace_digest": value.namespace_digest, + "maximum_output_bytes": value.maximum_output_bytes, + } + if include_digest: + result["destination_digest"] = value.destination_digest + return result + + +def _bind_digest(value: object, field: str, expected: str) -> None: + actual = getattr(value, field) + if actual == "": + object.__setattr__(value, field, expected) + elif _digest(actual, field) != expected: + raise IsolatedExecutionError(f"{field} does not match canonical content") + + +__all__ = [ + "ArmExecutionBudgetV1", + "BUNDLE_SCHEMA", + "ComponentArmExecutionV1", + "ENVIRONMENT_SCHEMA", + "ExecutionAdapterKind", + "ExecutionEnvironmentV1", + "IsolatedExecutionError", + "LabelBlindCaseInputV1", + "OutputDestinationV1", + "PROCESS_OUTCOME_SCHEMA", + "ProcessOutcomeReason", + "ProcessOutcomeStatus", + "SAFE_EXECUTION_ENVIRONMENT", +] diff --git a/benchmarks/valid/isolated_execution_plan.py b/benchmarks/valid/isolated_execution_plan.py new file mode 100644 index 00000000..6d067105 --- /dev/null +++ b/benchmarks/valid/isolated_execution_plan.py @@ -0,0 +1,332 @@ +"""Review-free execution-plan projection derived from exact core authority.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from benchmarks.valid.arm_contract import ( + ArmLifecycleState, + ArmRole, + RegisteredEvaluationPlanV1, + validate_registered_evaluation_plan, +) +from benchmarks.valid.isolated_execution_contract import ( + ComponentArmExecutionV1, + IsolatedExecutionError, + _bind_digest, + _digest, + _opaque, + _scope_value, +) +from openultrasast.core import canonical +from openultrasast.core.canonical import ContentResolver, JsonValue +from openultrasast.core.evaluation_measurement import ArmConfigurationV3, ArmKindV3, ScopeKey +from openultrasast.core.factpack import ReviewIndependencePolicy + +EXECUTION_PLAN_PROJECTION_SCHEMA = "openultrasast.valid-detection-benchmark.execution-plan-projection.v1" +EXECUTION_PLAN_ARM_BINDING_SCHEMA = "openultrasast.valid-detection-benchmark.execution-plan-arm-binding.v1" +COMPONENT_CONFIGURATION_AUTHORITY_SCHEMA = "openultrasast.valid-detection-benchmark.component-configuration-authority.v1" +_ROLE_ORDER = {ArmRole.SHIPPED: 0, ArmRole.EXPERIMENTAL: 1, ArmRole.COMBINED: 2} + + +@dataclass(frozen=True) +class ExecutionPlanArmBindingV1: + arm_id: str + role: ArmRole + lifecycle_state: ArmLifecycleState + registration_digest: str + configuration_identity_digest: str + binding_digest: str + + def __post_init__(self) -> None: + if type(self) is not ExecutionPlanArmBindingV1: + raise IsolatedExecutionError("plan arm must use exact ExecutionPlanArmBindingV1") + _opaque(self.arm_id, "plan arm id") + if type(self.role) is not ArmRole or type(self.lifecycle_state) is not ArmLifecycleState: + raise IsolatedExecutionError("plan arm must use closed role and lifecycle values") + _digest(self.registration_digest, "plan registration") + _digest(self.configuration_identity_digest, "plan configuration") + _bind_digest(self, "binding_digest", canonical.content_digest(_binding_value(self, include_digest=False))) + + +def _binding_value(binding: ExecutionPlanArmBindingV1, *, include_digest: bool) -> dict[str, JsonValue]: + value: dict[str, JsonValue] = { + "schema_version": EXECUTION_PLAN_ARM_BINDING_SCHEMA, + "arm_id": binding.arm_id, + "role": binding.role.value, + "lifecycle_state": binding.lifecycle_state.value, + "registration_digest": binding.registration_digest, + "configuration_identity_digest": binding.configuration_identity_digest, + } + if include_digest: + value["binding_digest"] = binding.binding_digest + return value + + +@dataclass(frozen=True) +class ComponentConfigurationAuthorityV1: + arm_id: str + exact_scopes: tuple[ScopeKey, ...] + policy_digests: tuple[str, ...] + threshold_digests: tuple[str, ...] + sufficiency_digests: tuple[str, ...] + judgment_vocabulary_digest: str + analyzer_identity: str + fact_set_digest: str + configuration_digest: str + registered_budget_digest: str + execution_identity: str + outcome_mapping_digest: str + configuration_identity_digest: str + authority_digest: str + + def __post_init__(self) -> None: + if type(self) is not ComponentConfigurationAuthorityV1: + raise IsolatedExecutionError("configuration authority must use its exact V1 type") + _opaque(self.arm_id, "configuration arm id") + _opaque(self.analyzer_identity, "analyzer identity") + _opaque(self.execution_identity, "execution identity") + _validate_scopes_and_digests(self) + _digest(self.configuration_identity_digest, "configuration identity") + _bind_digest(self, "authority_digest", canonical.content_digest(_authority_value(self, include_digest=False))) + + +def _validate_scopes_and_digests(authority: ComponentConfigurationAuthorityV1) -> None: + if authority.exact_scopes != tuple(sorted(set(authority.exact_scopes))) or not authority.exact_scopes: + raise IsolatedExecutionError("configuration scopes must be nonempty and canonical") + if any(type(scope) is not ScopeKey for scope in authority.exact_scopes): + raise IsolatedExecutionError("configuration scopes must use exact ScopeKey values") + digest_groups = (authority.policy_digests, authority.threshold_digests, authority.sufficiency_digests) + if any(type(group) is not tuple or not group for group in digest_groups): + raise IsolatedExecutionError("configuration digest groups must be nonempty tuples") + for item in (*digest_groups[0], *digest_groups[1], *digest_groups[2]): + _digest(item, "configuration member") + for item, field in ( + (authority.judgment_vocabulary_digest, "judgment vocabulary"), + (authority.fact_set_digest, "fact set"), + (authority.configuration_digest, "configuration"), + (authority.registered_budget_digest, "registered budget"), + (authority.outcome_mapping_digest, "outcome mapping"), + ): + _digest(item, field) + + +def _configuration_payload(authority: ComponentConfigurationAuthorityV1) -> dict[str, JsonValue]: + return { + "arm_id": authority.arm_id, + "kind": ArmKindV3.COMPONENT.value, + "exact_scopes": tuple(_scope_value(scope) for scope in authority.exact_scopes), + "policy_digests": authority.policy_digests, + "threshold_digests": authority.threshold_digests, + "sufficiency_digests": authority.sufficiency_digests, + "judgment_vocabulary_digest": authority.judgment_vocabulary_digest, + "analyzer_identity": authority.analyzer_identity, + "fact_set_digest": authority.fact_set_digest, + "configuration_digest": authority.configuration_digest, + "registered_budget_digest": authority.registered_budget_digest, + "execution_identity": authority.execution_identity, + "outcome_mapping_digest": authority.outcome_mapping_digest, + "case_outcome_policy": "unanimous_evidence", + "combination_rule_digest": None, + } + + +def _authority_value( + authority: ComponentConfigurationAuthorityV1, + *, + include_digest: bool, +) -> dict[str, JsonValue]: + value = _configuration_payload(authority) + value["schema_version"] = COMPONENT_CONFIGURATION_AUTHORITY_SCHEMA + value["configuration_identity_digest"] = authority.configuration_identity_digest + if include_digest: + value["authority_digest"] = authority.authority_digest + return value + + +@dataclass(frozen=True) +class ExecutionPlanProjectionV1: + population_digest: str + freeze_digest: str + input_set_digest: str + arm_bindings: tuple[ExecutionPlanArmBindingV1, ...] + configuration_identity_digests: tuple[str, ...] + expected_slot_digests: tuple[str, ...] + baseline_digests: tuple[str, ...] + declaration_digest: str + plan_digest: str + target_configuration: ComponentConfigurationAuthorityV1 + projection_digest: str + + def __post_init__(self) -> None: + if type(self) is not ExecutionPlanProjectionV1: + raise IsolatedExecutionError("execution plan must use exact ExecutionPlanProjectionV1") + for item, field in ( + (self.population_digest, "plan population"), + (self.freeze_digest, "plan freeze"), + (self.input_set_digest, "plan input set"), + ): + _digest(item, field) + _validate_projection_members(self) + _validate_projection_target(self) + _bind_digest(self, "projection_digest", canonical.content_digest(_projection_value(self, include_digest=False))) + + +def _validate_projection_members(projection: ExecutionPlanProjectionV1) -> None: + if type(projection.arm_bindings) is not tuple or not projection.arm_bindings: + raise IsolatedExecutionError("plan arm bindings must be a nonempty tuple") + for binding in projection.arm_bindings: + if type(binding) is not ExecutionPlanArmBindingV1: + raise IsolatedExecutionError("plan arm bindings must use exact V1 values") + binding.__post_init__() + keys = tuple((_ROLE_ORDER[row.role], row.arm_id) for row in projection.arm_bindings) + if keys != tuple(sorted(keys)) or len({row.arm_id for row in projection.arm_bindings}) != len(keys): + raise IsolatedExecutionError("plan arm bindings must be unique and registry-canonical") + for group in ( + projection.configuration_identity_digests, + projection.expected_slot_digests, + projection.baseline_digests, + ): + if type(group) is not tuple or not group: + raise IsolatedExecutionError("plan digest vectors must be nonempty tuples") + for item in group: + _digest(item, "plan vector member") + expected_configurations = tuple( + row.configuration_identity_digest for row in sorted(projection.arm_bindings, key=lambda row: row.arm_id) + ) + if projection.configuration_identity_digests != expected_configurations: + raise IsolatedExecutionError("plan configuration vector does not match registered arms") + + +def _validate_projection_target(projection: ExecutionPlanProjectionV1) -> None: + _digest(projection.declaration_digest, "plan declaration") + _digest(projection.plan_digest, "plan") + projection.target_configuration.__post_init__() + binding = _target_binding(projection) + if binding.lifecycle_state is not ArmLifecycleState.ACTIVE or binding.role is ArmRole.COMBINED: + raise IsolatedExecutionError("only an active component registration may cross execution") + if binding.configuration_identity_digest != projection.target_configuration.configuration_identity_digest: + raise IsolatedExecutionError("target configuration does not match its plan registration") + + +def _target_binding(projection: ExecutionPlanProjectionV1) -> ExecutionPlanArmBindingV1: + matches = tuple(row for row in projection.arm_bindings if row.arm_id == projection.target_configuration.arm_id) + if len(matches) != 1: + raise IsolatedExecutionError("target component must occur exactly once in the plan") + return matches[0] + + +def _projection_value(projection: ExecutionPlanProjectionV1, *, include_digest: bool) -> dict[str, JsonValue]: + value: dict[str, JsonValue] = { + "schema_version": EXECUTION_PLAN_PROJECTION_SCHEMA, + "population_digest": projection.population_digest, + "freeze_digest": projection.freeze_digest, + "input_set_digest": projection.input_set_digest, + "arm_bindings": tuple(_binding_value(row, include_digest=True) for row in projection.arm_bindings), + "configuration_identity_digests": projection.configuration_identity_digests, + "expected_slot_digests": projection.expected_slot_digests, + "baseline_digests": projection.baseline_digests, + "declaration_digest": projection.declaration_digest, + "plan_digest": projection.plan_digest, + "target_configuration": _authority_value(projection.target_configuration, include_digest=True), + } + if include_digest: + value["projection_digest"] = projection.projection_digest + return value + + +def _configuration_authority(configuration: ArmConfigurationV3) -> ComponentConfigurationAuthorityV1: + if type(configuration) is not ArmConfigurationV3 or configuration.kind is not ArmKindV3.COMPONENT: + raise IsolatedExecutionError("execution target must be an exact component configuration") + configuration.__post_init__() + return ComponentConfigurationAuthorityV1( + configuration.arm_id, + configuration.exact_scopes, + tuple(row.policy_digest for row in configuration.denominator_policies), + tuple(row.threshold_digest for row in configuration.thresholds), + tuple(row.rule_digest for row in configuration.sufficiency_rules), + configuration.judgment_vocabulary_digest, + configuration.analyzer_identity, + configuration.fact_set_digest, + configuration.configuration_digest, + configuration.registered_budget_digest, + configuration.execution_identity, + configuration.outcome_mapping_digest, + configuration.configuration_identity_digest, + "", + ) + + +def project_execution_plan( + plan: RegisteredEvaluationPlanV1, + target_arm_id: str, + *, + strategy_review_policy: ReviewIndependencePolicy | None = None, + strategy_resolver: ContentResolver | None = None, +) -> ExecutionPlanProjectionV1: + validate_registered_evaluation_plan( + plan, + strategy_review_policy=strategy_review_policy, + strategy_resolver=strategy_resolver, + ) + registrations = {row.arm_id: row for row in plan.registrations} + if target_arm_id not in registrations: + raise IsolatedExecutionError("target arm is absent from the registered plan") + target = registrations[target_arm_id] + bindings = tuple( + ExecutionPlanArmBindingV1( + row.arm_id, + row.role, + row.lifecycle_state, + row.registration_digest, + row.configuration.configuration_identity_digest, + "", + ) + for row in plan.registrations + ) + return ExecutionPlanProjectionV1( + plan.declaration.population_digest, + plan.declaration.freeze_digest, + plan.declaration.input_set_digest, + bindings, + tuple(row.configuration_identity_digest for row in plan.declaration.arm_configurations), + tuple(row.slot_digest for row in plan.declaration.expected_observation_slots), + tuple(row.baseline_digest for row in plan.baselines), + plan.declaration.declaration_digest, + plan.plan_digest, + _configuration_authority(target.configuration), + "", + ) + + +def component_arm_from_projection(projection: ExecutionPlanProjectionV1) -> ComponentArmExecutionV1: + projection.__post_init__() + binding = _target_binding(projection) + authority = projection.target_configuration + return ComponentArmExecutionV1( + authority.arm_id, + binding.role, + binding.registration_digest, + ArmKindV3.COMPONENT, + authority.configuration_identity_digest, + authority.analyzer_identity, + authority.fact_set_digest, + authority.configuration_digest, + authority.judgment_vocabulary_digest, + authority.outcome_mapping_digest, + authority.registered_budget_digest, + authority.execution_identity, + authority.exact_scopes, + "", + ) + + +__all__ = [ + "ComponentConfigurationAuthorityV1", + "EXECUTION_PLAN_ARM_BINDING_SCHEMA", + "EXECUTION_PLAN_PROJECTION_SCHEMA", + "ExecutionPlanArmBindingV1", + "ExecutionPlanProjectionV1", + "component_arm_from_projection", + "project_execution_plan", +] diff --git a/benchmarks/valid/isolated_execution_source.py b/benchmarks/valid/isolated_execution_source.py new file mode 100644 index 00000000..8578e6f3 --- /dev/null +++ b/benchmarks/valid/isolated_execution_source.py @@ -0,0 +1,306 @@ +"""Metadata-only source authority for isolated label-blind execution.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from benchmarks.valid.isolated_execution_contract import ( + IsolatedExecutionError, + LabelBlindCaseInputV1, + _bind_digest, + _digest, + _positive, +) +from benchmarks.valid.ordinary_change_contract import ( + OrdinaryPushV1, + OrdinarySelectionV1, + ordinary_selection_bytes, +) +from benchmarks.valid.population_label_blind_contract import ( + LabelBlindPopulationManifestV3, + label_blind_population_manifest_bytes, +) +from benchmarks.valid.population_material_contract import ( + PublicPopulationMaterialManifestV1, + _manifest_value, + _validate_manifest_counts, +) +from benchmarks.valid.replacement_artifact_contract import ArtifactAccessClass +from openultrasast.core import canonical +from openultrasast.core.canonical import JsonValue +from openultrasast.core.evaluation_plan import derive_evaluation_input_set_digest + +EXECUTION_SOURCE_SCHEMA = "openultrasast.valid-detection-benchmark.execution-source-projection.v1" + + +@dataclass(frozen=True, order=True) +class ExecutionSourceRecordV1: + input_identity_digest: str + change_input_digest: str + source_digest: str + byte_length: int + provenance_digest: str + access_class: ArtifactAccessClass + + def __post_init__(self) -> None: + if type(self) is not ExecutionSourceRecordV1: + raise IsolatedExecutionError("execution source must use exact ExecutionSourceRecordV1") + for item, field in ( + (self.input_identity_digest, "source input identity"), + (self.change_input_digest, "source change input"), + (self.source_digest, "source content"), + (self.provenance_digest, "source provenance"), + ): + _digest(item, field) + _positive(self.byte_length, "source byte length", 1 << 34) + if type(self.access_class) is not ArtifactAccessClass or self.access_class not in { + ArtifactAccessClass.PUBLIC, + ArtifactAccessClass.PRIVATE, + }: + raise IsolatedExecutionError("execution source access must be public or private") + + +def _source_value(source: ExecutionSourceRecordV1) -> dict[str, JsonValue]: + source.__post_init__() + return { + "input_identity_digest": source.input_identity_digest, + "change_input_digest": source.change_input_digest, + "source_digest": source.source_digest, + "byte_length": source.byte_length, + "provenance_digest": source.provenance_digest, + "access_class": source.access_class.value, + } + + +@dataclass(frozen=True) +class ExecutionSourceProjectionV1: + label_blind_manifest_digest: str + public_material_manifest_digest: str + material_artifact_set_digest: str + ordinary_selection_digest: str + input_set_digest: str + sources: tuple[ExecutionSourceRecordV1, ...] + projection_digest: str + + def __post_init__(self) -> None: + if type(self) is not ExecutionSourceProjectionV1: + raise IsolatedExecutionError("source projection must use exact ExecutionSourceProjectionV1") + for item, field in ( + (self.label_blind_manifest_digest, "label-blind manifest"), + (self.public_material_manifest_digest, "public material manifest"), + (self.material_artifact_set_digest, "reviewed material artifact set"), + (self.ordinary_selection_digest, "ordinary selection"), + (self.input_set_digest, "source input set"), + ): + _digest(item, field) + _validate_source_rows(self.sources, self.input_set_digest) + expected = canonical.content_digest(_projection_value(self, include_digest=False)) + _bind_digest(self, "projection_digest", expected) + + +def _validate_source_rows(sources: tuple[ExecutionSourceRecordV1, ...], input_set_digest: str) -> None: + if type(sources) is not tuple or not sources: + raise IsolatedExecutionError("source projection must contain a nonempty exact tuple") + if any(type(row) is not ExecutionSourceRecordV1 for row in sources): + raise IsolatedExecutionError("source projection contains a non-exact source record") + for row in sources: + row.__post_init__() + identities = tuple(row.input_identity_digest for row in sources) + if identities != tuple(sorted(set(identities))): + raise IsolatedExecutionError("source projection identities must be unique and canonical") + if derive_evaluation_input_set_digest(identities) != input_set_digest: + raise IsolatedExecutionError("source projection does not match its input-set identity") + + +def _projection_value( + projection: ExecutionSourceProjectionV1, + *, + include_digest: bool, +) -> dict[str, JsonValue]: + value: dict[str, JsonValue] = { + "schema_version": EXECUTION_SOURCE_SCHEMA, + "label_blind_manifest_digest": projection.label_blind_manifest_digest, + "public_material_manifest_digest": projection.public_material_manifest_digest, + "material_artifact_set_digest": projection.material_artifact_set_digest, + "ordinary_selection_digest": projection.ordinary_selection_digest, + "input_set_digest": projection.input_set_digest, + "sources": tuple(_source_value(row) for row in projection.sources), + } + if include_digest: + value["projection_digest"] = projection.projection_digest + return value + + +def execution_source_projection_bytes(projection: ExecutionSourceProjectionV1) -> bytes: + if type(projection) is not ExecutionSourceProjectionV1: + raise IsolatedExecutionError("source projection must use exact ExecutionSourceProjectionV1") + projection.__post_init__() + return canonical.canonical_bytes(_projection_value(projection, include_digest=True)) + + +def _public_manifest_bytes(manifest: PublicPopulationMaterialManifestV1) -> bytes: + if type(manifest) is not PublicPopulationMaterialManifestV1: + raise IsolatedExecutionError("source authority must use exact PublicPopulationMaterialManifestV1") + if manifest.public_sources != tuple(sorted(set(manifest.public_sources))): + raise IsolatedExecutionError("public source metadata is not canonical") + if manifest.private_refs != tuple(sorted(set(manifest.private_refs))): + raise IsolatedExecutionError("private source metadata is not canonical") + if manifest.positive_change_digests != tuple(sorted(set(manifest.positive_change_digests))): + raise IsolatedExecutionError("positive source identities are not canonical") + try: + _validate_manifest_counts(manifest) + value = _manifest_value(manifest, include_digest=False) + if canonical.content_digest(value) != manifest.manifest_digest: + raise IsolatedExecutionError("public material manifest digest does not match") + return canonical.canonical_bytes(_manifest_value(manifest, include_digest=True)) + except (TypeError, ValueError) as error: + raise IsolatedExecutionError("public material manifest metadata is invalid") from error + + +def _positive_sources( + manifest: PublicPopulationMaterialManifestV1, +) -> dict[str, ExecutionSourceRecordV1]: + result = { + row.change_digest: ExecutionSourceRecordV1( + row.change_digest, + row.change_digest, + row.source_digest, + row.byte_length, + row.object_digest, + ArtifactAccessClass.PUBLIC, + ) + for row in manifest.public_sources + } + result.update( + { + row.change_digest: ExecutionSourceRecordV1( + row.change_digest, + row.change_digest, + row.source_digest, + row.byte_length, + manifest.private_object_digest, + ArtifactAccessClass.PRIVATE, + ) + for row in manifest.private_refs + } + ) + if tuple(sorted(result)) != manifest.positive_change_digests: + raise IsolatedExecutionError("public material metadata does not cover the exact positive set") + return result + + +def _ordinary_source(push: OrdinaryPushV1) -> ExecutionSourceRecordV1: + return ExecutionSourceRecordV1( + push.push_digest, + push.change_content_digest, + push.change_content_digest, + push.change_byte_length, + push.history_source_digest, + ArtifactAccessClass.PRIVATE, + ) + + +def _source_records( + manifest: LabelBlindPopulationManifestV3, + public_manifest: PublicPopulationMaterialManifestV1, + selection: OrdinarySelectionV1, +) -> tuple[ExecutionSourceRecordV1, ...]: + result = _positive_sources(public_manifest) + if tuple(sorted(result)) != selection.positive_change_digests: + raise IsolatedExecutionError("ordinary selection does not match the exact positive source set") + for push in selection.pushes: + if push.push_digest in result: + raise IsolatedExecutionError("one input identity maps to more than one source") + result[push.push_digest] = _ordinary_source(push) + if tuple(sorted(result)) != manifest.input_digests: + raise IsolatedExecutionError("source metadata does not reconstruct the reviewed input identities") + return tuple(result[item] for item in manifest.input_digests) + + +def build_execution_source_projection( + manifest: LabelBlindPopulationManifestV3, + public_material_manifest: PublicPopulationMaterialManifestV1, + selection: OrdinarySelectionV1, +) -> ExecutionSourceProjectionV1: + """Derive adapter source authority without accepting or opening material bytes.""" + try: + if not label_blind_population_manifest_bytes(manifest): + raise IsolatedExecutionError("label-blind manifest bytes must be nonempty") + if not _public_manifest_bytes(public_material_manifest): + raise IsolatedExecutionError("public material manifest bytes must be nonempty") + if type(selection) is not OrdinarySelectionV1 or not ordinary_selection_bytes(selection): + raise IsolatedExecutionError("ordinary selection authority is invalid or empty") + except (TypeError, ValueError) as error: + raise IsolatedExecutionError("execution source authority metadata is invalid") from error + _validate_authority_bindings(manifest, public_material_manifest, selection) + sources = _source_records(manifest, public_material_manifest, selection) + return ExecutionSourceProjectionV1( + manifest.manifest_digest, + public_material_manifest.manifest_digest, + manifest.material_artifact_set_digest, + selection.selection_digest, + manifest.input_set_digest, + sources, + "", + ) + + +def _validate_authority_bindings( + manifest: LabelBlindPopulationManifestV3, + public_manifest: PublicPopulationMaterialManifestV1, + selection: OrdinarySelectionV1, +) -> None: + if (public_manifest.population_digest, public_manifest.freeze_digest) != ( + manifest.population_digest, + manifest.freeze_digest, + ): + raise IsolatedExecutionError("public material manifest does not bind the reviewed population") + if public_manifest.manifest_digest != manifest.public_material_manifest_digest: + raise IsolatedExecutionError("public material manifest does not match the reviewed identity") + if selection.selection_digest != manifest.ordinary_selection_digest: + raise IsolatedExecutionError("ordinary selection does not match the reviewed identity") + if derive_evaluation_input_set_digest(manifest.input_digests) != manifest.input_set_digest: + raise IsolatedExecutionError("reviewed input identities do not match their input-set identity") + + +def validate_execution_cases( + cases: tuple[LabelBlindCaseInputV1, ...], + projection: ExecutionSourceProjectionV1, +) -> tuple[LabelBlindCaseInputV1, ...]: + if type(cases) is not tuple or not cases: + raise IsolatedExecutionError("case inputs must be a nonempty tuple") + if any(type(row) is not LabelBlindCaseInputV1 for row in cases): + raise IsolatedExecutionError("case inputs must use exact LabelBlindCaseInputV1 values") + projection.__post_init__() + identities = tuple(row.input_identity_digest for row in cases) + expected = tuple(row.input_identity_digest for row in projection.sources) + if identities != expected: + raise IsolatedExecutionError("case inputs must exactly equal the source projection identities") + for case, source in zip(cases, projection.sources, strict=True): + case.__post_init__() + _validate_case_source(case, source) + return cases + + +def _validate_case_source(case: LabelBlindCaseInputV1, source: ExecutionSourceRecordV1) -> None: + reference = case.code_reference + if case.change_input_digest != source.change_input_digest: + raise IsolatedExecutionError("case change does not match the source authority") + if reference.content_digest != source.source_digest: + raise IsolatedExecutionError("case source digest does not match the source authority") + if reference.byte_length != source.byte_length: + raise IsolatedExecutionError("case source length does not match the source authority") + if reference.provenance_digest != source.provenance_digest: + raise IsolatedExecutionError("case provenance does not match the source authority") + if reference.access_class is not source.access_class: + raise IsolatedExecutionError("case access does not match the source authority") + + +__all__ = [ + "EXECUTION_SOURCE_SCHEMA", + "ExecutionSourceProjectionV1", + "ExecutionSourceRecordV1", + "build_execution_source_projection", + "execution_source_projection_bytes", + "validate_execution_cases", +] diff --git a/tests/test_valid_benchmark_isolated_executor.py b/tests/test_valid_benchmark_isolated_executor.py new file mode 100644 index 00000000..5ac14ea0 --- /dev/null +++ b/tests/test_valid_benchmark_isolated_executor.py @@ -0,0 +1,370 @@ +"""Task 6.3 isolated label-blind execution boundary tests.""" + +from __future__ import annotations + +import json +import sys +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_arm_registry import _digest, _registrations +from test_valid_benchmark_label_blind_manifest import _reviewed + +from benchmarks.valid import arm_contract as registry +from benchmarks.valid import isolated_execution as execution +from benchmarks.valid.replacement_artifact_contract import ( + ArtifactAccessClass, + ArtifactKind, + ArtifactReference, +) +from openultrasast.core.evaluation_measurement import ArmKindV3 +from openultrasast.core.evaluation_plan import derive_evaluation_input_set_digest + + +def _plan(manifest=None) -> registry.RegisteredEvaluationPlanV1: + manifest = _reviewed()[-1] if manifest is None else manifest + return registry.register_evaluation_plan( + registrations=_registrations(), + population_digest=manifest.population_digest, + freeze_digest=manifest.freeze_digest, + input_set_digest=derive_evaluation_input_set_digest(manifest.input_digests), + input_identity_digests=manifest.input_digests, + ) + + +def _case( + input_digest: str, + *, + change_digest: str | None = None, + reference_digest: str | None = None, + byte_length: int = 128, + provenance_digest: str | None = None, + access: ArtifactAccessClass = ArtifactAccessClass.PUBLIC, +) -> execution.LabelBlindCaseInputV1: + change = input_digest if change_digest is None else change_digest + reference = ArtifactReference( + ArtifactKind.POPULATION, + reference_digest or change, + byte_length, + provenance_digest or _digest(f"provenance-{input_digest}"), + access, + ) + return execution.LabelBlindCaseInputV1(input_digest, change, reference, "") + + +def _cases(manifest=None) -> tuple[execution.LabelBlindCaseInputV1, ...]: + _, selection, partition, *_, reviewed = _reviewed() + manifest = reviewed if manifest is None else manifest + pushes = {row.push_digest: row for row in selection.pushes} + public = {row.change_digest: row for row in partition.manifest.public_sources} + private = {row.change_digest: row for row in partition.manifest.private_refs} + return tuple( + _case( + item, + change_digest=pushes[item].change_content_digest, + byte_length=pushes[item].change_byte_length, + provenance_digest=pushes[item].history_source_digest, + access=ArtifactAccessClass.PRIVATE, + ) + if item in pushes + else _case( + item, + reference_digest=(public[item].source_digest if item in public else private[item].source_digest), + byte_length=(public[item].byte_length if item in public else private[item].byte_length), + provenance_digest=(public[item].object_digest if item in public else partition.manifest.private_object_digest), + access=(ArtifactAccessClass.PUBLIC if item in public else ArtifactAccessClass.PRIVATE), + ) + for item in manifest.input_digests + ) + + +def _budgets(plan: registry.RegisteredEvaluationPlanV1) -> tuple[execution.ArmExecutionBudgetV1, ...]: + return tuple( + execution.ArmExecutionBudgetV1( + row.arm_id, + row.configuration.registered_budget_digest, + 120, + 512 * 1024 * 1024, + 1024 * 1024 * 1024, + 4 * 1024 * 1024, + "", + ) + for row in plan.registrations + if row.configuration.kind is ArmKindV3.COMPONENT + ) + + +def _bundles( + *, + adapter_kind: execution.ExecutionAdapterKind = execution.ExecutionAdapterKind.LOCAL, +) -> tuple[execution.LabelBlindExecutionBundleV1, ...]: + _, selection, partition, *_, manifest = _reviewed() + plan = _plan(manifest) + return execution.build_component_execution_bundles( + plan, + manifest, + selection, + partition.manifest, + _cases(manifest), + _budgets(plan), + adapter_kind=adapter_kind, + output_namespace_digest=_digest("observation-output-namespace"), + ) + + +def _authorities(): + _, selection, partition, *_, manifest = _reviewed() + return manifest, partition.manifest, selection + + +def test_component_bundles_share_exact_ordered_label_blind_inputs() -> None: + bundles = _bundles() + + assert tuple(row.arm.arm_id for row in bundles) == ("arm-experimental", "arm-shipped") + assert all(row.case_inputs is bundles[0].case_inputs for row in bundles) + assert tuple(item.input_identity_digest for item in bundles[0].case_inputs) == _reviewed()[-1].input_digests + assert all(row.input_set_digest == _reviewed()[-1].input_set_digest for row in bundles) + assert all(row.arm.role is not registry.ArmRole.COMBINED for row in bundles) + assert all(row.arm.configuration_kind is ArmKindV3.COMPONENT for row in bundles) + + +def test_bundle_has_no_label_custody_review_or_secret_surface() -> None: + bundles = _bundles(adapter_kind=execution.ExecutionAdapterKind.AX) + plan = _plan() + forbidden_fields = { + "label", + "labels", + "expected_outcome", + "finding", + "custody", + "review", + "strategy_decision_authority", + "credentials", + "secret", + "endpoint", + "path", + } + for bundle in bundles: + content = execution.label_blind_execution_bundle_bytes(plan, bundle, *_authorities()) + decoded = json.loads(content) + assert forbidden_fields.isdisjoint(decoded) + assert not any(name in forbidden_fields for name in (field.name for field in fields(bundle))) + for sentinel in ( + b"sealed label", + b"expected_outcome", + b"password=", + b"api_key", + b"strategy_decision", + b"/home/", + b"s3://", + ): + assert sentinel not in content.lower() + + +@pytest.mark.parametrize("access", (ArtifactAccessClass.CUSTODIAN_SEALED, ArtifactAccessClass.OPERATOR_SAFE)) +def test_sealed_or_operator_references_cannot_enter_case_inputs(access: ArtifactAccessClass) -> None: + with pytest.raises(execution.IsolatedExecutionError): + _case(_reviewed()[-1].input_digests[0], access=access) + + +@pytest.mark.parametrize( + "mutation", + ("missing", "extra", "duplicate", "order", "zero", "wrong_input", "wrong_change", "wrong_provenance"), +) +def test_bundle_builder_rejects_incomplete_or_changed_input_set(mutation: str) -> None: + manifest = _reviewed()[-1] + selection = _reviewed()[1] + partition = _reviewed()[2] + plan = _plan(manifest) + cases = _cases(manifest) + with pytest.raises((execution.IsolatedExecutionError, ValueError)): + if mutation == "missing": + cases = cases[:-1] + elif mutation == "extra": + cases = (*cases, _case(_digest("extra-input"))) + elif mutation == "duplicate": + cases = (*cases[:-1], cases[0]) + elif mutation == "order": + cases = tuple(reversed(cases)) + elif mutation == "zero": + reference = replace(cases[0].code_reference, byte_length=0) + cases = (replace(cases[0], code_reference=reference, case_digest=""), *cases[1:]) + elif mutation == "wrong_input": + cases = (replace(cases[0], input_identity_digest=_digest("wrong-input"), case_digest=""), *cases[1:]) + elif mutation == "wrong_change": + changed = _digest("wrong-change") + reference = replace(cases[0].code_reference, content_digest=changed) + cases = (replace(cases[0], change_input_digest=changed, code_reference=reference, case_digest=""), *cases[1:]) + else: + reference = replace(cases[0].code_reference, provenance_digest=_digest("wrong-provenance")) + cases = (replace(cases[0], code_reference=reference, case_digest=""), *cases[1:]) + execution.build_component_execution_bundles( + plan, + manifest, + selection, + partition.manifest, + cases, + _budgets(plan), + adapter_kind=execution.ExecutionAdapterKind.LOCAL, + output_namespace_digest=_digest("output"), + ) + + +def test_environment_is_fixed_and_does_not_inherit_ambient_or_aliases() -> None: + tainted = { + "PATH": "/attacker/bin", + "OPENAI_API_KEY": "model-secret", + "openai_api_key": "alias-secret", + "AWS_SECRET_ACCESS_KEY": "store-secret", + "CORPUS_S3_SECRET_KEY": "admin-secret", + "LABEL_BYTES": "private-label", + "REVIEW_TOKEN": "review-secret", + "OUSAST_CUSTODY_TOKEN": "custody-secret", + } + environment = execution.build_execution_environment(execution.ExecutionAdapterKind.DOCKER, tainted) + + assert dict(environment.variables) == execution.SAFE_EXECUTION_ENVIRONMENT + assert not (set(tainted) - {"PATH"}).intersection(dict(environment.variables)) + assert dict(environment.variables)["PATH"] != tainted["PATH"] + content = execution.execution_environment_bytes(environment) + assert all(value.encode() not in content for value in tainted.values()) + + +def test_environment_contract_rejects_direct_allowlist_bypass() -> None: + with pytest.raises(execution.IsolatedExecutionError): + execution.ExecutionEnvironmentV1( + execution.ExecutionAdapterKind.LOCAL, + (("MODEL_PROVIDER_TOKEN", "private-canary"),), + "", + ) + + +@pytest.mark.parametrize("field_name", ("deadline_seconds", "memory_bytes", "disk_bytes", "maximum_output_bytes")) +def test_budget_is_positive_bounded_and_bound_to_registered_arm(field_name: str) -> None: + plan = _plan() + selection = _reviewed()[1] + partition = _reviewed()[2] + budget = _budgets(plan)[0] + with pytest.raises(execution.IsolatedExecutionError): + replace(budget, **{field_name: 0}, budget_digest="") + wrong = replace(budget, registered_budget_digest=_digest("wrong-budget"), budget_digest="") + with pytest.raises(execution.IsolatedExecutionError): + execution.build_component_execution_bundles( + plan, + _reviewed()[-1], + selection, + partition.manifest, + _cases(), + (wrong, *_budgets(plan)[1:]), + adapter_kind=execution.ExecutionAdapterKind.LOCAL, + output_namespace_digest=_digest("output"), + ) + + +class _Adapter: + def __init__(self, *, reason: execution.ProcessOutcomeReason = execution.ProcessOutcomeReason.NONE) -> None: + self.reason = reason + self.calls: list[execution.LabelBlindExecutionBundleV1] = [] + + def execute(self, bundle: execution.LabelBlindExecutionBundleV1) -> execution.ArmProcessOutcomeV1: + self.calls.append(bundle) + if self.reason is not execution.ProcessOutcomeReason.NONE: + return execution.impaired_adapter_outcome(bundle, self.reason, runtime_ms=3) + return execution.completed_adapter_outcome(bundle, b"detector-output", runtime_ms=7) + + +def test_adapter_runs_once_per_component_and_never_for_combined_arm() -> None: + bundles = _bundles() + adapter = _Adapter() + + outcomes = execution.execute_component_bundles(_plan(), bundles, adapter, *_authorities()) + + assert tuple(row.arm_id for row in outcomes) == ("arm-experimental", "arm-shipped") + assert adapter.calls == list(bundles) + assert all(row.status is execution.ProcessOutcomeStatus.COMPLETED for row in outcomes) + + +@pytest.mark.parametrize( + "reason", + ( + execution.ProcessOutcomeReason.BACKPRESSURE, + execution.ProcessOutcomeReason.DEADLINE, + execution.ProcessOutcomeReason.BUDGET_EXHAUSTED, + execution.ProcessOutcomeReason.RESOURCE_LIMIT, + execution.ProcessOutcomeReason.PROCESS_FAILURE, + ), +) +def test_adapter_impairment_is_closed_and_does_not_attribute_infrastructure(reason: execution.ProcessOutcomeReason) -> None: + adapter = _Adapter(reason=reason) + plan = _plan() + bundles = _bundles(adapter_kind=execution.ExecutionAdapterKind.AX) + outcomes = execution.execute_component_bundles(plan, bundles, adapter, *_authorities()) + content = b"".join( + execution.arm_process_outcome_bytes(plan, bundle, row, *_authorities()) for bundle, row in zip(bundles, outcomes, strict=True) + ) + + assert all(row.status is execution.ProcessOutcomeStatus.IMPAIRED and row.reason is reason for row in outcomes) + for forbidden in (b"cluster", b"worker", b"network", b"node", b"k3s", b"exception"): + assert forbidden not in content.lower() + + +class _FailingAdapter: + def execute(self, bundle: execution.LabelBlindExecutionBundleV1) -> execution.ArmProcessOutcomeV1: + raise RuntimeError("provider-diagnostic private-canary /restricted/location") + + +def test_adapter_exception_becomes_closed_outcome_without_diagnostic_retention() -> None: + plan = _plan() + bundles = _bundles() + outcomes = execution.execute_component_bundles(plan, bundles, _FailingAdapter(), *_authorities()) + content = b"".join( + execution.arm_process_outcome_bytes(plan, bundle, row, *_authorities()) for bundle, row in zip(bundles, outcomes, strict=True) + ) + + assert all(row.reason is execution.ProcessOutcomeReason.PROCESS_FAILURE for row in outcomes) + assert b"provider" not in content and b"private" not in content + + +class _CrossArmAdapter: + def execute(self, bundle: execution.LabelBlindExecutionBundleV1) -> execution.ArmProcessOutcomeV1: + outcome = execution.completed_adapter_outcome(bundle, b"detector-output", runtime_ms=1) + return replace(outcome, arm_id="different-arm", outcome_digest="") + + +def test_adapter_cannot_return_an_outcome_for_a_different_arm() -> None: + outcomes = execution.execute_component_bundles( + _plan(), + _bundles(), + _CrossArmAdapter(), + *_authorities(), + ) + + assert all(row.reason is execution.ProcessOutcomeReason.OUTPUT_INVALID for row in outcomes) + + +def test_direct_bundle_and_outcome_mutation_is_rejected_by_serialization() -> None: + bundle = _bundles()[0] + plan = _plan() + with pytest.raises(execution.IsolatedExecutionError): + execution.label_blind_execution_bundle_bytes( + plan, + replace(bundle, plan_digest=_digest("wrong-plan"), bundle_digest=""), + *_authorities(), + ) + outcome = execution.completed_adapter_outcome(bundle, b"output", runtime_ms=1) + with pytest.raises(execution.IsolatedExecutionError): + execution.arm_process_outcome_bytes( + plan, + bundle, + replace(outcome, output_bytes=0, outcome_digest=""), + *_authorities(), + ) + + +def test_execution_boundary_has_no_label_or_custody_hook() -> None: + public = {name for name in execution.__all__ if not name.startswith("_")} + assert not any(token in name.lower() for name in public for token in ("label_loader", "custody", "review", "credential")) diff --git a/tests/test_valid_benchmark_isolated_executor_authority.py b/tests/test_valid_benchmark_isolated_executor_authority.py new file mode 100644 index 00000000..3fb5aeeb --- /dev/null +++ b/tests/test_valid_benchmark_isolated_executor_authority.py @@ -0,0 +1,380 @@ +"""Authority regressions for the Task 6.3 isolated executor.""" + +from __future__ import annotations + +import inspect +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from test_valid_benchmark_arm_registry import _digest, _registrations +from test_valid_benchmark_isolated_executor import _authorities, _budgets, _bundles, _cases, _plan +from test_valid_benchmark_label_blind_manifest import _reviewed + +from benchmarks.valid import arm_contract as registry +from benchmarks.valid import isolated_execution as execution +from benchmarks.valid import isolated_execution_bundle as execution_bundle +from benchmarks.valid import isolated_execution_source as execution_source +from benchmarks.valid import ordinary_change_contract as ordinary_contract +from benchmarks.valid import population_material_contract as material_contract +from benchmarks.valid import population_materials as materials +from benchmarks.valid.replacement_artifact_contract import ( + ArtifactAccessClass, + ArtifactKind, + ArtifactReference, +) +from openultrasast.core import canonical + + +def test_bundle_serialization_rejects_canonical_arm_substitution_under_original_plan() -> None: + bundle = _bundles()[0] + attacker_arm = replace(bundle.arm, analyzer_identity="attacker-analyzer", execution_arm_digest="") + + with pytest.raises(execution.IsolatedExecutionError): + attacker_bundle = replace(bundle, arm=attacker_arm, bundle_digest="") + execution.label_blind_execution_bundle_bytes(_plan(), attacker_bundle, *_authorities()) + + +def test_real_ordinary_push_keeps_distinct_case_and_change_identities() -> None: + _, selection, *_ = _reviewed() + push = selection.pushes[0] + assert push.push_digest != push.change_content_digest + reference = ArtifactReference( + ArtifactKind.POPULATION, + push.change_content_digest, + push.change_byte_length, + push.history_source_digest, + ArtifactAccessClass.PRIVATE, + ) + + case = execution.LabelBlindCaseInputV1(push.push_digest, push.change_content_digest, reference, "") + + assert case.input_identity_digest == push.push_digest + assert case.change_input_digest == push.change_content_digest + + +def test_controller_serializer_requires_exact_registered_plan_authority() -> None: + parameters = inspect.signature(execution.label_blind_execution_bundle_bytes).parameters + + assert { + "plan", + "manifest", + "public_material_manifest", + "selection", + } <= parameters.keys() + + +def test_controller_rejects_bundle_derived_from_different_valid_analyzer_plan() -> None: + _, selection, partition, *_, manifest = _reviewed() + original = _plan(manifest) + registrations = list(_registrations()) + target_index = next(index for index, row in enumerate(registrations) if row.arm_id == "arm-experimental") + target = registrations[target_index] + changed_configuration = replace( + target.configuration, + analyzer_identity="attacker-analyzer", + configuration_identity_digest="", + ) + registrations[target_index] = replace(target, configuration=changed_configuration, registration_digest="") + forged = registry.register_evaluation_plan( + registrations=tuple(registrations), + population_digest=manifest.population_digest, + freeze_digest=manifest.freeze_digest, + input_set_digest=manifest.input_set_digest, + input_identity_digests=manifest.input_digests, + ) + forged_bundle = execution.build_component_execution_bundles( + forged, + manifest, + selection, + partition.manifest, + _cases(manifest), + _budgets(forged), + adapter_kind=execution.ExecutionAdapterKind.LOCAL, + output_namespace_digest=_digest("output"), + )[0] + + with pytest.raises(execution.IsolatedExecutionError): + execution.label_blind_execution_bundle_bytes( + original, + forged_bundle, + manifest, + partition.manifest, + selection, + ) + + +@pytest.mark.parametrize("mutation", ("stale", "missing", "extra")) +def test_controller_rejects_rehashed_projection_with_changed_baseline_vector(mutation: str) -> None: + bundle = _bundles()[0] + projection = bundle.plan_projection + if mutation == "missing": + baselines = projection.baseline_digests[:-1] + elif mutation == "extra": + baselines = (*projection.baseline_digests, _digest("extra-baseline")) + else: + baselines = (_digest("stale-baseline"), *projection.baseline_digests[1:]) + plan_value = { + "schema_version": registry.REGISTERED_PLAN_SCHEMA, + "registration_digests": tuple(row.registration_digest for row in projection.arm_bindings), + "declaration_digest": projection.declaration_digest, + "baseline_digests": baselines, + } + changed_projection = replace( + projection, + baseline_digests=baselines, + plan_digest=canonical.content_digest(plan_value), + projection_digest="", + ) + destination = replace( + bundle.output_destination, + plan_digest=changed_projection.plan_digest, + destination_digest="", + ) + changed_bundle = replace( + bundle, + plan_projection=changed_projection, + plan_digest=changed_projection.plan_digest, + output_destination=destination, + bundle_digest="", + ) + + with pytest.raises(execution.IsolatedExecutionError): + execution.label_blind_execution_bundle_bytes(_plan(), changed_bundle, *_authorities()) + + +@pytest.mark.parametrize("mutation", ("source", "length", "provenance", "access", "swapped")) +def test_positive_reference_cannot_detach_from_material_authority(mutation: str) -> None: + _, selection, partition, *_, manifest = _reviewed() + plan = _plan(manifest) + cases = _cases(manifest) + positives = tuple(index for index, case in enumerate(cases) if case.input_identity_digest in selection.positive_change_digests) + positive = positives[0] + reference = cases[positive].code_reference + if mutation == "source": + changed_reference = replace(reference, content_digest=_digest("wrong-source")) + elif mutation == "length": + changed_reference = replace(reference, byte_length=1) + elif mutation == "provenance": + changed_reference = replace(reference, provenance_digest=_digest("wrong-source-provenance")) + elif mutation == "access": + changed_reference = replace(reference, access_class=ArtifactAccessClass.PRIVATE) + else: + changed_reference = cases[positives[1]].code_reference + changed_case = replace(cases[positive], code_reference=changed_reference, case_digest="") + changed_cases = (*cases[:positive], changed_case, *cases[positive + 1 :]) + + with pytest.raises(execution.IsolatedExecutionError): + execution.build_component_execution_bundles( + plan, + manifest, + selection, + partition.manifest, + changed_cases, + _budgets(plan), + adapter_kind=execution.ExecutionAdapterKind.LOCAL, + output_namespace_digest=_digest("output"), + ) + + +def test_execution_source_projection_and_bundles_never_open_sealed_material( + monkeypatch: pytest.MonkeyPatch, +) -> None: + _, selection, partition, *_, manifest = _reviewed() + sealed_byte_count = sum(len(row.label_content) + len(row.judgment_content) for row in partition.sealed_label_records) + assert sealed_byte_count > 0 + plan = _plan(manifest) + cases = _cases(manifest) + budgets = _budgets(plan) + calls: list[str] = [] + + def fail_if_called(name: str): + def fail(*_args, **_kwargs): + calls.append(name) + raise AssertionError(f"forbidden sealed-material hook called: {name}") + + return fail + + for module, name in ( + (material_contract, "sealed_label_object_bytes"), + (material_contract, "_label_record_value"), + (materials, "sealed_label_object_bytes"), + (materials, "material_artifact_bytes"), + (materials, "resolve_sealed_labels"), + ): + monkeypatch.setattr(module, name, fail_if_called(name)) + + projection = execution.build_execution_source_projection( + manifest, + partition.manifest, + selection, + ) + bundles = execution.build_component_execution_bundles( + plan, + manifest, + selection, + partition.manifest, + cases, + budgets, + adapter_kind=execution.ExecutionAdapterKind.LOCAL, + output_namespace_digest=_digest("zero-access-output"), + ) + + assert len(bundles) == 2 + assert all(bundle.source_projection == projection for bundle in bundles) + assert calls == [] + + +def test_execution_bundle_import_and_signature_exclude_full_material_authority() -> None: + parameters = inspect.signature(execution.build_component_execution_bundles).parameters + source = inspect.getsource(execution_bundle) + + assert "public_material_manifest" in parameters + assert "material_partition" not in parameters + for forbidden in ( + "PopulationMaterialPartitionV1", + "PrivateSourceRecordV1", + "SealedLabelRecordV1", + "IndependenceAttestation", + ): + assert forbidden not in source + + +@pytest.mark.parametrize("mutation", ("public_manifest", "artifact_set", "input_set")) +def test_execution_source_authority_identity_mutation_is_rejected(mutation: str) -> None: + _, selection, partition, *_, manifest = _reviewed() + if mutation == "public_manifest": + changed_public_manifest = replace( + partition.manifest, + manifest_digest=_digest("wrong-public-manifest"), + ) + with pytest.raises(execution.IsolatedExecutionError): + execution.build_execution_source_projection( + manifest, + changed_public_manifest, + selection, + ) + return + + bundle = _bundles()[0] + with pytest.raises(execution.IsolatedExecutionError): + changed_projection = replace( + bundle.source_projection, + **{"material_artifact_set_digest" if mutation == "artifact_set" else "input_set_digest": _digest(f"wrong-{mutation}")}, + ) + execution.label_blind_execution_bundle_bytes( + _plan(), + replace(bundle, source_projection=changed_projection, bundle_digest=""), + *_authorities(), + ) + + +@pytest.mark.parametrize( + "field_name", + ( + "public_material_manifest_digest", + "material_artifact_set_digest", + "ordinary_selection_digest", + ), +) +def test_rehashed_source_projection_cannot_replace_controller_authority(field_name: str) -> None: + bundle = _bundles()[0] + changed_projection = replace( + bundle.source_projection, + **{field_name: _digest(f"attacker-{field_name}"), "projection_digest": ""}, + ) + attacker_bundle = replace( + bundle, + source_projection=changed_projection, + bundle_digest="", + ) + + with pytest.raises(execution.IsolatedExecutionError): + execution.label_blind_execution_bundle_bytes(_plan(), attacker_bundle, *_authorities()) + + +def _different_valid_selection(selection: ordinary_contract.OrdinarySelectionV1) -> ordinary_contract.OrdinarySelectionV1: + policy_digest = _digest("different-valid-selection-policy") + provenance_digest = canonical.content_digest( + { + "history_sources": tuple( + sorted({(push.canonical_repository, push.network_identity_digest, push.history_source_digest) for push in selection.pushes}) + ), + "accepted_fix_exclusions": tuple(ordinary_contract._fix_exclusion_value(item) for item in selection.fix_exclusions), + "policy_digest": policy_digest, + } + ) + changed = replace( + selection, + policy_digest=policy_digest, + provenance_digest=provenance_digest, + selection_digest="", + ) + return replace( + changed, + selection_digest=canonical.content_digest(ordinary_contract._selection_value(changed, include_digest=False)), + ) + + +@pytest.mark.parametrize("authority", ("public_manifest", "ordinary_selection")) +def test_bundle_rejects_different_internally_valid_source_authority(authority: str) -> None: + manifest, public_manifest, selection = _authorities() + if authority == "public_manifest": + changed = replace( + public_manifest, + partition_policy_digest=_digest("different-valid-partition-policy"), + manifest_digest="", + ) + public_manifest = replace( + changed, + manifest_digest=canonical.content_digest(material_contract._manifest_value(changed, include_digest=False)), + ) + assert execution_source._public_manifest_bytes(public_manifest) + else: + selection = _different_valid_selection(selection) + assert ordinary_contract.ordinary_selection_bytes(selection) + + with pytest.raises(execution.IsolatedExecutionError): + execution.label_blind_execution_bundle_bytes( + _plan(), + _bundles()[0], + manifest, + public_manifest, + selection, + ) + + +class _NeverExecuteAdapter: + def execute(self, _bundle: execution.LabelBlindExecutionBundleV1) -> execution.ArmProcessOutcomeV1: + raise AssertionError("source authority substitution reached the adapter") + + +@pytest.mark.parametrize("boundary", ("outcome", "execution")) +def test_rehashed_source_projection_is_rejected_at_controller_boundaries(boundary: str) -> None: + bundle = _bundles()[0] + changed_projection = replace( + bundle.source_projection, + material_artifact_set_digest=_digest("attacker-boundary-artifact-set"), + projection_digest="", + ) + attacker_bundle = replace(bundle, source_projection=changed_projection, bundle_digest="") + with pytest.raises(execution.IsolatedExecutionError): + if boundary == "outcome": + outcome = execution.completed_adapter_outcome(attacker_bundle, b"output", runtime_ms=1) + execution.arm_process_outcome_bytes( + _plan(), + attacker_bundle, + outcome, + *_authorities(), + ) + else: + execution.execute_component_bundles( + _plan(), + (attacker_bundle,), + _NeverExecuteAdapter(), + *_authorities(), + )