diff --git a/.github/scripts/lmi-ci.sh b/.github/scripts/lmi-ci.sh new file mode 100644 index 000000000..61fc2ae4e --- /dev/null +++ b/.github/scripts/lmi-ci.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# Python commands for the shared LMI reusable workflow's stage contract. +set -euo pipefail + +case "${1:?Expected a workflow stage}" in + setup) + uv pip install hatch==1.16.5 + hatch run lmi:shared-setup + ;; + harness) + hatch run lmi:lint + hatch run lmi:python - <<'PYTHON' +from pathlib import Path +import aws_durable_execution_sdk_python as sdk + +source = Path('packages/aws-durable-execution-sdk-python/src').resolve() +assert Path(sdk.__file__).resolve().is_relative_to(source), sdk.__file__ +PYTHON + hatch run lmi:shared-tests --junitxml=lmi_tests/artifacts/unit.xml + ;; + build) hatch run lmi:build ;; + deploy) + hatch run lmi:python -m lmi_tests.deploy deploy \ + --run-id "$LMI_SHARED_RUN_ID" \ + --runtime "$LMI_RUNTIME" --stack-name "$LMI_STACK_NAME" + ;; + run) hatch run lmi:shared ;; + collect) hatch run lmi:python -m lmi_tests.deploy collect ;; + cleanup) hatch run lmi:shared-cleanup ;; + summary) hatch run lmi:python -m lmi_tests.summary ;; + *) printf 'Unknown LMI workflow stage: %s\n' "$1" >&2; exit 2 ;; +esac diff --git a/.github/workflows/lmi-e2e-tests.yml b/.github/workflows/lmi-e2e-tests.yml new file mode 100644 index 000000000..98fe898f1 --- /dev/null +++ b/.github/workflows/lmi-e2e-tests.yml @@ -0,0 +1,46 @@ +name: LMI e2e tests + +on: + push: + branches: [main] + pull_request: + types: [opened, synchronize, reopened] + branches: [main] + paths: + - '.github/workflows/lmi-e2e-tests.yml' + - '.github/scripts/lmi-ci.sh' + - 'lmi_tests/**' + - '!lmi_tests/**/*.md' + - 'packages/aws-durable-execution-sdk-python/src/**' + - 'packages/aws-durable-execution-sdk-python/pyproject.toml' + - 'packages/aws-durable-execution-sdk-python-testing/src/**' + - 'packages/aws-durable-execution-sdk-python-testing/pyproject.toml' + - 'pyproject.toml' + workflow_dispatch: + inputs: + region: + description: Region containing the test LMI capacity provider + default: us-west-2 + type: string + +permissions: + contents: read + +jobs: + lifecycle: + permissions: + contents: read + id-token: write + uses: aws/aws-durable-execution-conformance-tests/.github/workflows/lmi-lifecycle.yml@41878367192be996cb3414939e15270febedb210 + with: + conformance-ref: 41878367192be996cb3414939e15270febedb210 + sdk-script: .github/scripts/lmi-ci.sh + runtime-label: Python 3.14 + lambda-runtime: python3.14 + stack-name: python-lmi-e2e + region: ${{ inputs.region || 'us-west-2' }} + secrets: + TEST_ROLE_ARN: ${{ secrets.TEST_ROLE_ARN }} + TEST_ACCOUNT_ID: ${{ secrets.TEST_ACCOUNT_ID }} + TEST_LAMBDA_EXECUTION_ROLE_ARN: ${{ secrets.TEST_LAMBDA_EXECUTION_ROLE_ARN }} + CAPACITY_PROVIDER_ARN: ${{ secrets.CAPACITY_PROVIDER_ARN }} diff --git a/.gitignore b/.gitignore index 13ccb7ad3..516a14a52 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,5 @@ dist/ **/template.generated.json .env + +/.conformance/ diff --git a/lmi_tests/.gitignore b/lmi_tests/.gitignore new file mode 100644 index 000000000..0d8880bee --- /dev/null +++ b/lmi_tests/.gitignore @@ -0,0 +1,3 @@ +artifacts/ +build/ +__pycache__/ diff --git a/lmi_tests/README.md b/lmi_tests/README.md new file mode 100644 index 000000000..8a085ec00 --- /dev/null +++ b/lmi_tests/README.md @@ -0,0 +1,170 @@ +# Python LMI lifecycle conformance + +This PR adapts the Python SDK to the seven shared lifecycle requirements in +[conformance #186](https://github.com/aws/aws-durable-execution-conformance-tests/pull/186). +The exact dependency is pinned in `shared_contract.py` and the workflow. Each +shared requirement declares one scalar `scenario`; the Python adapter reads the +shared matrix directly rather than maintaining a second requirement catalog. + +| Requirement | Scenario | Target | Invocation roles | +| --- | --- | --- | --- | +| `lmi-lifecycle-1` | `native-overlap` | c2 | victim, peer | +| `lmi-lifecycle-2` | `normal-return` | c1 | victim | +| `lmi-lifecycle-3` | `deadline-during-step` | c1 | victim | +| `lmi-lifecycle-4` | `peer-recovery` | c2 | victim, peer, recovery | +| `lmi-lifecycle-5` | `suspension-retry` | c1 | victim, resume | +| `lmi-lifecycle-6` | `warm-reuse` | c1 | victim, warm | +| `lmi-lifecycle-7` | `normal-failure` | c1 | victim | + +The shared package owns assertions, AWS transport, persistent deployment, scenario +choreography, source normalization, strict reports, scheduling and retirement. +This repository owns the real Python SDK handlers, observation hooks, ZIP build +and thin runtime bindings. The workflow definition also lives in the shared +repository; `.github/workflows/lmi-e2e-tests.yml` calls its pinned +`lmi-lifecycle.yml`, using `.github/scripts/lmi-ci.sh` for Python stage commands. +OTel/exporter tests and the previous Python-specific matrix are deferred. +There is no local conformance profile or validator that replaces a shared rule. + +## Local validation + +Install Hatch and Python 3.14. Clone the shared repository into `.conformance` +and check out the exact `CONFORMANCE_REVISION` from `shared_contract.py`: + +```bash +git clone https://github.com/aws/aws-durable-execution-conformance-tests.git .conformance +git -C .conformance checkout --detach 41878367192be996cb3414939e15270febedb210 +hatch run lmi:shared-setup +hatch run lmi:lint +hatch run lmi:shared-tests +hatch run lmi:build +``` + +`shared-setup` verifies the commit and rejects edited shared package sources. +It installs only the shared core runner. The LMI environment contains the checked +out core SDK and testing library; the Lambda bundle contains the core SDK and +its dependencies plus fixture/observation modules. It does not include the OTel +SDK, an OTel plugin, local catalogs, validators or the shared runner itself. + +Python unit tests cover pinned workflow delegation, the Python artifact/manifest +binding, fixture observations and bootstrap. Shared driver regression tests now +live in the conformance repository and cover case ownership, cancellation, source +normalization, driver ordering and cleanup. + +A local plan preview defaults to `lmi_tests/artifacts/preview` and requires a +new output directory. Run and cleanup use `lmi_tests/artifacts/shared` by default. + +Local e2e tests use the actual public +SDK and its in-process test service, replacing only AWS transport and evidence +storage. They verify checkpoint/replay and preserve genuine admission failures. +These controls do not establish real LMI placement or deployed acceptance. + +## Cloud execution + +Use a dedicated test account with the configured LMI capacity provider and Lambda +execution role. The workflow validates the account before deployment. The +persistent functions use Python 3.14, arm64, 2048 MiB and native concurrency 1 and +2, with one environment each. SDK artifact and configuration digests are retained +in every manifest and checked before invoking either target. + +Run cloud tests through the workflow's `workflow_dispatch` action or a trusted +same-repository PR. Its fixed `lmi-e2e-shared-capacity-provider` concurrency group +serializes cloud jobs across PRs and refs from deployment through final cleanup, +with `cancel-in-progress: false`. GitHub Actions is the only cross-run concurrency +control. Direct CLI calls do not acquire a lock and are not serialized with CI. + +`shared plan` writes the seven-case manifest without invoking functions. `shared +run` writes under `lmi_tests/artifacts/shared/standard/`: the manifest, coverage, +JSON/JUnit reports, launch journal and retained case evidence. Each invocation +uses a case-owned control/evidence prefix derived from `runId` and `caseId`. +The case hash uses only `caseId` within the run prefix. Plans, payloads and evidence +have no additional cohort identifier. Generate new run artifacts with this pinned +revision; inspect or clean up older artifacts with their original adapter revision. A service resume is journaled under +the same durable execution; it is not another driver Invoke. + +Trusted same-repository pull requests and manual workflow runs exercise the cloud +suite. Fork and Dependabot pull requests run only the unprivileged local harness. +There is no S3 lease, fence token or persistent quarantine record. Existing S3 +ownership objects are not read and cannot block a later workflow run. + +## Actual observations and failure handling + +`fixture.py` uses public durable APIs for the scenarios. Its instrumentation +observer captures actual operation IDs, parents, stored outcomes and user-task +lifetimes. The service-client wrapper forwards every SDK request and response; +it never supplies synthetic checkpoints or changes SDK cancellation flags. +The instrumentation observer is a measurement tool, not a plugin conformance test. + +For normal return/failure, the adapter records the actual durable wrapper boundary +and probes the original context after that boundary. The operation probe uses +`DurableContext.step`; the checkpoint probe calls the SDK's +`context.state.create_checkpoint(is_sync=False)` admission path without issuing a +raw Lambda request. SDK closure/revocation errors are recorded as rejection only when no user code +or new SDK request ran. Probes run after both wrapper return and wrapper raise. An accepted checkpoint, another error, or a still-pending operation +remains visible. Probe tasks are tracked separately; a timeout cannot make them +quiescent. Current SDK gaps are failures, not expected passes or exclusions. + +The deadline fixture holds real I/O across the runtime deadline and cooperatively +exits after it. A runtime clock alone never supplies a `platform_timeout` event: +that event requires the original request's service `InvocationCompleted` history. +The recovery victim first waits in a checkpointed preparation step. The driver +starts the peer halfway through the victim's native timeout, verifies the original +cohort and the peer's remaining recovery window, then releases preparation to +admit the fault. Preparation checkpoints the original native request ID, so +service retries keep the same durable sequence without reinjecting the victim's +fault or admission probes. Recovery overlap excludes expired original requests +and their retries. The original peer remains held until recovery completes. A still-running +durable execution is collected as such; terminal-state waiting and stops belong +to retirement after assertions. Releasing a victim fault cannot establish the +preceding cleanup or recovery assertion. + +The warm fixture creates invocation-owned late work inside a step. A later +invocation must find it in the same process; it observes the old callback using +the original request identity. Failure to reuse that process is a placement or +collection failure, not permission to select a replacement victim. + +`shared_evidence.py` supplies Python error expectations and process identity to +the shared source-evidence normalizer. +Service payload wrappers are decoded consistently with checkpoint snapshots; +truncated results are rejected. Replay compares a real resume's initial +checkpoints to the final service history and counts actual user-function entries. +Missing observations are never filled from expected answers. +Each native request writes a final protocol 2 seal after its wrapper and +registered work finish and all captured observations reach S3. A warm owner +can seal after its wrapper returns, while its callback finishes in the reused +process. Lost records, live probes, and a publisher killed at the native +deadline leave the request unsealed. If work still publishes after a seal, +its later sequence invalidates the seal when the driver reads it. + +The fixture stops pre-seal publication once retry and read-back work reaches +five cumulative seconds, after the in-flight write and its read-back finish. +Successful first-attempt uploads do not use that budget. Slow successful +uploads can still consume the 60-second native invocation window. Exhausting +the retry budget leaves collection incomplete without replacing the SDK result. +Late writes after a seal still run so they can invalidate it. The published +workflow pin does not enforce terminal seals. Seal enforcement is tested +against the paired runner. The published pin also uses its original per-operation +replay counts. Logical map inputs and late-only replay effects require the +paired runner's policy support. + +The shared behavior schema asks for one scenario-owned `task_exit`. Other user +and probe tasks remain in the same evidence as `observed_task_start/exit`, with +their original `sourceKind`. The independent retirement snapshot restores all +original task kinds, so a pending task cannot disappear from the audit. +Coordination barriers retain their complete `controlRecords` journal separately +from injected victim `faultsCreated`; releasing a healthy peer is not victim +fault recovery. + +Run `hatch run lmi:shared-cleanup` for manual cleanup of the case manifests. +With the published pin, pass the same `--output` to run and cleanup when +using a custom case output directory. +When recovering an interrupted deployment with a journal-aware conformance +revision, set `LMI_SHARED_RUN_ID` to the run ID recorded in +`lmi_tests/artifacts/deployment-update.json`. Keep the journal in its original +artifact directory until reconciliation completes. +Cleanup releases only the current run's controls and requests stops only for its +identified executions. It validates run, case and function identity before those +requests. It records `NO_CASES`, `CLEANUP_REQUESTED` or `FAILED` in `cleanup.json`; +completed cleanup requests do not claim that every task retired. Assertion and +retirement failures remain in the shared reports. The shared runner can prevent +reuse of an unretired target within the current run, but that state is not stored +as a lock for future workflow runs. diff --git a/lmi_tests/__init__.py b/lmi_tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/lmi_tests/cloud.py b/lmi_tests/cloud.py new file mode 100644 index 000000000..ceb3c2830 --- /dev/null +++ b/lmi_tests/cloud.py @@ -0,0 +1,19 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Python fixture binding to the shared AWS driver.""" + +from aws_durable_execution_conformance_tests.lmi.cloud import Cloud as SharedCloud +from lmi_tests.deploy import ARTIFACTS, manager + + +class Cloud(SharedCloud): + def __init__( + self, manifest, configuration=None, *, artifacts_dir=None, case_context=None + ): + super().__init__( + manifest, + configuration, + artifacts_dir=artifacts_dir or ARTIFACTS, + case_context=case_context, + verify_profile=manager().verify, + ) diff --git a/lmi_tests/deploy.py b/lmi_tests/deploy.py new file mode 100644 index 000000000..5d98fcd63 --- /dev/null +++ b/lmi_tests/deploy.py @@ -0,0 +1,201 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Build the Python fixture and delegate deployment to the shared LMI harness.""" + +import argparse +import hashlib +import json +import os +import re +from pathlib import Path +import shutil +import subprocess +import stat +import sys +import zipfile + +from aws_durable_execution_conformance_tests.lmi.artifacts import ( + clear_run_artifacts, + save, +) +from aws_durable_execution_conformance_tests.lmi.deployment import DeploymentManager +from aws_durable_execution_conformance_tests.lmi.errors import ( + CollectionError, + ProvisioningError, +) +from aws_durable_execution_conformance_tests.lmi.runtime import CONCURRENCIES +from lmi_tests.runtime import RUNTIME +from lmi_tests.shared import verify_install + +ROOT = Path(__file__).resolve().parents[1] +ARTIFACTS = ROOT / "lmi_tests/artifacts" +DEFAULT_STACK = "python-lmi-e2e" + + +def manager(): + return DeploymentManager( + runtime=RUNTIME, + owner="python-sdk-lmi-e2e", + artifacts=ARTIFACTS, + bundle=ROOT / "lmi_tests/build/function.zip", + bucket_prefix="py-lmi-e2e", + ) + + +def require_settled_deployment() -> None: + if (ARTIFACTS / "deployment-update.json").exists(): + raise ProvisioningError( + "Clean up the interrupted deployment before rebuilding or deploying" + ) + + +def build(): + require_settled_deployment() + clear_run_artifacts(ARTIFACTS) + directory = ROOT / "lmi_tests/build" + if directory.exists(): + shutil.rmtree(directory) + directory.mkdir() + # The tested core SDK comes from this checkout; pip resolves its dependencies. + for package in ("aws-durable-execution-sdk-python",): + subprocess.run( + ["hatch", "build", "-t", "wheel", str(directory)], + cwd=ROOT / "packages" / package, + env={k: v for k, v in os.environ.items() if k != "HATCH_ENV_ACTIVE"}, + check=True, + ) + wheels = sorted(directory.glob("*.whl")) + if len(wheels) != 1: + raise ProvisioningError("Expected exactly the checked-out core SDK wheel") + wheel = next(directory.glob("aws_durable_execution_sdk_python-*.whl")) + target = directory / "package" + subprocess.run( + [ + sys.executable, + "-m", + "pip", + "install", + "--only-binary=:all:", + "--platform", + "manylinux2014_aarch64", + "--platform", + "manylinux_2_28_aarch64", + "--python-version", + "3.14", + "--implementation", + "cp", + "--abi", + "cp314", + "--no-compile", + "--target", + str(target), + "--report", + str(directory / "dependencies.json"), + *map(str, wheels), + ], + check=True, + ) + (target / "lmi_tests").mkdir() + for name in ( + "__init__.py", + "fixture.py", + "shared_observations.py", + ): + shutil.copy(ROOT / "lmi_tests" / name, target / "lmi_tests" / name) + artifact = directory / "function.zip" + resolved = json.loads((directory / "dependencies.json").read_text()) + with zipfile.ZipFile(artifact, "w", zipfile.ZIP_DEFLATED) as archive: + for path in sorted(target.rglob("*")): + if path.is_file(): + info = zipfile.ZipInfo(path.relative_to(target).as_posix()) + info.compress_type = zipfile.ZIP_DEFLATED + mode = 0o755 if path.stat().st_mode & 0o111 else 0o644 + info.external_attr = (stat.S_IFREG | mode) << 16 + archive.writestr(info, path.read_bytes()) + save( + ARTIFACTS / "build.json", + { + "commit": subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=ROOT, text=True + ).strip(), + "wheel": wheel.name, + "wheels": { + item.name: hashlib.sha256(item.read_bytes()).hexdigest() + for item in wheels + }, + "dependencies": [ + { + "name": item["metadata"]["name"], + "version": item["metadata"]["version"], + "hashes": item.get("download_info", {}) + .get("archive_info", {}) + .get("hashes", {}), + } + for item in resolved["install"] + ], + "sha256": hashlib.sha256(artifact.read_bytes()).hexdigest(), + }, + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=["build", "deploy", "collect"]) + parser.add_argument("--run-id") + parser.add_argument( + "--checkout", + type=Path, + default=Path( + os.environ.get("LMI_CONFORMANCE_CHECKOUT", str(ROOT / ".conformance")) + ), + ) + parser.add_argument("--stack-name", default=DEFAULT_STACK) + parser.add_argument("--runtime", choices=["python3.14"], default="python3.14") + args = parser.parse_args() + try: + if args.command == "build": + build() + elif args.command == "deploy": + require_settled_deployment() + if not args.run_id or not re.fullmatch(r"[a-z0-9-]{1,24}", args.run_id): + raise ProvisioningError( + "run-id must be 1-24 lowercase letters, digits or hyphens" + ) + if not re.fullmatch(r"[a-z][a-z0-9-]{0,49}", args.stack_name): + raise ProvisioningError( + "stack-name must be 1-50 lowercase letters, digits or hyphens, starting with a letter" + ) + verify_install(args.checkout) + manager().deploy(args) + else: + manifest = json.loads((ARTIFACTS / "manifest.json").read_text()) + expected_run = args.run_id or os.environ.get("LMI_SHARED_RUN_ID") + if expected_run and manifest.get("run") != expected_run: + raise CollectionError( + "Deployment manifest belongs to a different collection run" + ) + functions = manifest["functions"] + name_map = ARTIFACTS / "function-name-map.json" + if ( + (ARTIFACTS / "deployment-update.json").exists() + or set(functions) != set(CONCURRENCIES) + or not name_map.is_file() + or json.loads(name_map.read_text()) + != {key: {RUNTIME.handler: arn} for key, arn in functions.items()} + ): + raise CollectionError( + "Deployment manifest has no verified collection targets" + ) + from lmi_tests.cloud import Cloud + + Cloud(manifest).collect() + except Exception as error: + save( + ARTIFACTS / f"{args.command}-error.json", + {"type": type(error).__name__, "message": str(error)}, + ) + raise + + +if __name__ == "__main__": + main() diff --git a/lmi_tests/fixture.py b/lmi_tests/fixture.py new file mode 100644 index 000000000..a53f64d2e --- /dev/null +++ b/lmi_tests/fixture.py @@ -0,0 +1,977 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Fault-injection handlers for real LMI. Never install these as SDK examples.""" + +from collections.abc import Callable +from contextlib import contextmanager, suppress +from dataclasses import dataclass, field +import fcntl +import hashlib +import json +import os +import threading +import time +from typing import Any +import uuid + +import boto3 +from botocore.config import Config +from botocore.exceptions import BotoCoreError, ClientError + +from aws_durable_execution_sdk_python import StepError, durable_execution +from aws_durable_execution_sdk_python.config import ( + Duration, + MapConfig, + StepConfig, +) +from aws_durable_execution_sdk_python.execution import ( + DurableExecutionInvocationInput, + DurableExecutionInvocationInputWithClient, +) +from aws_durable_execution_sdk_python.lambda_service import ( + LambdaClient, +) +from aws_durable_execution_sdk_python.plugin import ( + DurableInstrumentationPlugin, + InvocationStartInfo, +) +from aws_durable_execution_sdk_python.retries import RetryDecision +from aws_durable_execution_sdk_python.exceptions import ( + BackgroundThreadError, + CheckpointError, + OrphanedChildException, + SuspendExecution, +) +from lmi_tests.shared_observations import ( + LifecycleObservations, +) + + +PROCESS_ID = uuid.uuid4().hex +PUBLICATION_BUDGET_SECONDS = 5.0 +publication_clock = time.monotonic +IO_CONFIG = Config(connect_timeout=2, read_timeout=3, retries={"total_max_attempts": 1}) +NO_RETRY = StepConfig(retry_strategy=lambda _error, _attempt: RetryDecision.no_retry()) + + +def environment_id(path="/tmp/python-lmi-environment"): + """/tmp is shared by the LMI Python workers; lock initialization across processes.""" + with open(path, "a+") as marker: + fcntl.flock(marker, fcntl.LOCK_EX) + marker.seek(0) + value = marker.read().strip() + if not value: + value = uuid.uuid4().hex + marker.write(value) + marker.flush() + os.fsync(marker.fileno()) + return value + + +def resources(): + return {"threads": [{"id": t.ident, "name": t.name} for t in threading.enumerate()]} + + +class Trace: + def __init__(self, payload, context, execution_arn): + self.payload = dict(payload) + for key in ( + "runId", + "caseId", + "role", + "coverageProfile", + "sharedScenario", + "controlPrefix", + ): + if not isinstance(self.payload.get(key), str) or not self.payload[key]: + raise ValueError(f"Shared invocation requires {key}") + run = self.payload["runId"] + if self.payload.get("run", run) != run or run != os.environ["LMI_RUN_ID"]: + raise ValueError("Input belongs to a different deployment") + self.payload["run"] = run + # The deployed fixture bundle omits the conformance package. Match + # its case_key derivation when checking the supplied control namespace. + owner = hashlib.sha256(self.payload["caseId"].encode()).hexdigest()[:20] + if self.payload["controlPrefix"] != f"runs/{run}/cases/{owner}/control/": + raise ValueError("Shared controls must use the case-owned run prefix") + self.context = context + self.s3 = boto3.client("s3", config=IO_CONFIG) + self.bucket = os.environ["LMI_BUCKET"] + # Publication sequences are assigned under the ledger lock. + self.lock = threading.Lock() + # Work registration and seal eligibility share this separate state lock. + self.state_lock = threading.Lock() + self.capture_sequence = 0 + self.publication_seconds = 0.0 + self.active_workers = 0 + self.wrapper_finished = False + self.source_failed = False + self.closed = False + self.sequence = 0 + self.call_sequence = 0 + self.sdk_request_count = 0 + self.durable_context = None + self.identity = { + "run": run, + "commit": os.environ["LMI_COMMIT"], + "marker": self.payload["marker"], + "scenario": self.payload["scenario"], + "execution": execution_arn, + "request": context.aws_request_id, + "environment": environment_id(), + "process": PROCESS_ID, + "pid": os.getpid(), + } + self.identity.update( + { + key: self.payload[key] + for key in ( + "runId", + "caseId", + "role", + "coverageProfile", + "sharedScenario", + "behaviorBudgets", + ) + if key in self.payload + } + ) + self.control_prefix = self.payload["controlPrefix"] + self.deadline_observed_at_ms = time.time() * 1000 + self.remaining_ms = context.get_remaining_time_in_millis() + self.deadline = (self.deadline_observed_at_ms + self.remaining_ms) / 1000 + self.observer = LifecycleObservations(self) + + def emit(self, phase, **fields): + with self.lock: + return self._publish_record(phase, **fields) + + def _publish_record(self, phase: str, **fields: Any) -> dict[str, Any]: + with self.state_lock: + # Once a pre-seal record is lost, further evidence uploads cannot + # certify this request. Avoid repeating a slow failed retry budget. + if self.source_failed and not self.closed: + return {} + try: + event = self._write_record(phase, **fields) + except Exception as error: + self.fail_source(f"Could not publish {phase}", error) + return {} + if not self.closed and self.publication_seconds >= PUBLICATION_BUDGET_SECONDS: + self.fail_source( + "Publication budget exhausted", TimeoutError("Slow evidence storage") + ) + return event + + def fail_source(self, message: str, error: Exception) -> None: + with self.state_lock: + self.source_failed = True + with suppress(OSError, ValueError): + print(f"LMI_TEST_PUBLICATION_ERROR {message}: {error}", flush=True) + + def _write_record(self, phase: str, **fields: Any) -> dict[str, Any]: + self.sequence += 1 + if phase == "CONFORMANCE": + self.capture_sequence += 1 + fields["observation"] = { + **fields["observation"], + "sourceSequence": self.sequence, + "captureSequence": self.capture_sequence, + } + event = { + **self.identity, + "phase": phase, + "sequence": self.sequence, + "time": time.time(), + "deadline": self.deadline, + **fields, + } + content = json.dumps(event) + with suppress(OSError, ValueError): + print("LMI_TEST " + content, flush=True) + key = ( + f"runs/{self.identity['run']}/events/{self.identity['marker']}/" + f"{self.identity['request']}/{self.sequence:06d}.json" + ) + self._commit_record(key, content.encode()) + return event + + def _commit_record(self, key: str, content: bytes) -> None: + started = publication_clock() + failed = False + try: + for attempt in range(2): + try: + self.s3.put_object( + Bucket=self.bucket, + Key=key, + Body=content, + ContentType="application/json", + IfNoneMatch="*", + ) + return + except (BotoCoreError, ClientError) as error: + failed = True + try: + response = self.s3.get_object(Bucket=self.bucket, Key=key) + with response["Body"] as body: + existing = body.read() + except (BotoCoreError, ClientError): + if attempt: + raise error from None + else: + if existing == content: + return + raise ValueError( + f"Evidence record already exists with different content: {key}" + ) from error + finally: + if failed: + self.publication_seconds += publication_clock() - started + + def _seal_if_ready(self) -> None: + with self.state_lock: + if not self.wrapper_finished or self.active_workers: + return + with self.lock: + with self.state_lock: + if self.active_workers or self.source_failed or self.closed: + return + self.closed = True + # This shares the publication boundary with every other record. + self._publish_record( + "SEALED", sourceProtocol=2, throughCapture=self.capture_sequence + ) + + def finish_wrapper(self) -> None: + with self.state_lock: + self.wrapper_finished = True + self._seal_if_ready() + + def _begin_work(self) -> bool: + with self.state_lock: + self.active_workers += 1 + return self.closed + + def _end_work(self) -> None: + with self.state_lock: + self.active_workers -= 1 + self._seal_if_ready() + + @contextmanager + def publishing(self): + # Registration and checking the seal are atomic with seal eligibility. + already_sealed = self._begin_work() + try: + yield already_sealed + finally: + self._end_work() + + def start_worker( + self, operation: Callable[[], None], name: str + ) -> threading.Thread: + def run() -> None: + try: + operation() + except BaseException: + with self.state_lock: + self.source_failed = True + raise + finally: + self._end_work() + + thread = threading.Thread(target=run, daemon=True, name=name) + self._begin_work() + try: + thread.start() + except BaseException: + with self.state_lock: + self.active_workers -= 1 + self.source_failed = True + raise + return thread + + def observe(self, kind, **fields): + if "atMs" not in fields: + fields["atMs"] = time.time_ns() / 1_000_000 + return self.emit("CONFORMANCE", observation={"kind": kind, **fields}) + + def next_call_id(self, kind): + with self.lock: + self.call_sequence += 1 + if kind in {"checkpoint", "poll"}: + self.sdk_request_count += 1 + return f"{self.identity['request']}:{kind}:{self.call_sequence}" + + def released(self, name): + try: + response = self.s3.get_object( + Bucket=self.bucket, Key=self.control_prefix + name + ) + with response["Body"] as body: + state = body.read() + if state not in {b"hold", b"release"}: + raise ValueError(f"Invalid control state for {name}") + return state == b"release" + except (BotoCoreError, ClientError, ValueError) as error: + self.emit("CONTROL_ERROR", gate=name, error=str(error)) + self.observe("control_error", gateId=name, error=str(error)) + raise + + def gate( + self, + name, + *, + effects=False, + attempt=1, + preparation=False, + ): + """Observe normal versus emergency release without changing step results.""" + end = time.monotonic() + 150 + entered = False + held_at_ms = None + task_id = self.next_call_id("io") + native_overlap = self.payload.get("sharedScenario") == "native-overlap" + self.observe("io_start", taskId=task_id, gateId=name) + try: + while True: + # Shared cleanup releases the case abort control first. It must + # not masquerade as a normal measurement release of the target. + if self.released("release-all"): + mode = "emergency" + release_observed_at_ms = time.time_ns() / 1_000_000 + else: + specific_release = self.released(name) + target_observed_at_ms = time.time_ns() / 1_000_000 + # Shared cleanup releases the abort first. If it raced + # the target read, observe it before crediting a normal release. + abort = specific_release and self.released("release-all") + mode = ( + "emergency" if abort else "normal" if specific_release else None + ) + release_observed_at_ms = ( + time.time_ns() / 1_000_000 if abort else target_observed_at_ms + ) + if mode is not None: + if (preparation or native_overlap) and mode == "normal": + # The driver releases these controls only after observing + # live overlap. BLOCKED retains the earlier held-read time. + self.observe( + "barrier_arrived", + gateId=name, + atMs=release_observed_at_ms, + source="cohort-admission", + ) + self.observe( + "fault_released", + gateId=name, + mode=mode, + atMs=release_observed_at_ms, + source="control-poll", + ) + return + if ( + self.payload["scenario"] == "deadline" + and not preparation + and time.time() >= self.deadline + 0.2 + ): + self.observe("cooperative_io_cancelled", source="runtime-deadline") + raise TimeoutError( + "Cooperative fixture I/O crossed the runtime deadline" + ) + if not entered: + held_at_ms = target_observed_at_ms + self.emit("BLOCKED", gate=name) + self.observe("blocked", gateId=name, atMs=held_at_ms) + if not (native_overlap or self.payload.get("preparation_gate")): + self.observe("barrier_arrived", gateId=name, atMs=held_at_ms) + if self.payload["scenario"] == "deadline" and not preparation: + self.observe("work_in_flight", gateId=name, atMs=held_at_ms) + if self.payload.get("role") == "recovery": + self.observe("worker_recovered", atMs=held_at_ms) + if time.monotonic() >= end: + self.emit("ESCAPE", gate=name) + self.observe("escape", gateId=name) + raise TimeoutError( + "Test emergency release; never a passing regression" + ) + if effects: + self.emit( + "EFFECT", operation="blocked-io", gate=name, attempt=attempt + ) + self.observe( + "effect", + operation="blocked-io", + gateId=name, + attempt=attempt, + ) + else: + self.emit("ALIVE", gate=name) + self.observe("alive", gateId=name) + if self.payload.get("role") == "peer": + self.observe("peer_progress", gateId=name) + entered = True + time.sleep(0.2) # fault-injected blocking I/O, not a durable delay + except BaseException as error: + self.emit("IO_INTERRUPTED", gate=name, error=type(error).__name__) + self.observe( + "io_interrupted", + taskId=task_id, + gateId=name, + error=type(error).__name__, + ) + raise + finally: + exited_at = time.time() * 1000 + self.emit("IO_EXIT", gate=name) + self.observe("io_exit", taskId=task_id, gateId=name, atMs=exited_at) + + def body(self, name, value, step=None): + attempt = getattr(step, "attempt", 1) + self.emit("BODY", operation=name, value=value, attempt=attempt) + self.observer.body(name, value, attempt) + return value + + +@dataclass(frozen=True) +class FixtureObserverFactory: + bind: Callable[[dict[str, Any]], Trace] + + def create_plugin(self, info: InvocationStartInfo) -> DurableInstrumentationPlugin: + trace = self.bind(info.execution_input) + return trace.observer + + +class ObservedClient: + """Forward real SDK calls; never fabricate checkpoint acknowledgments. + + Evidence publication is isolated from the backend call: a failed record + can neither discard a successful response nor replace the backend's own + error. A failed record leaves a publication gap and prevents a new seal. + """ + + def __init__(self, client, trace=None): + self.client, self.trace = client, trace + self.initial_polls: list[tuple[float, float]] = [] + + def _record(self, phase, kind, emitted=None, *, prepublished=False, **observed): + if not prepublished: + self.trace.emit(phase, **(emitted or {}), time=observed["atMs"] / 1000) + self.trace.observe(kind, **observed) + + def bind_trace(self, trace) -> None: + self.trace = trace + for start, end in self.initial_polls: + call_id = self.trace.next_call_id("poll") + self._record("POLL_CALL", "poll_call", callId=call_id, atMs=start) + self._record("POLL_EXIT", "poll_exit", callId=call_id, atMs=end) + self.initial_polls.clear() + + def get_execution_state(self, **kwargs): + if self.trace is None: + # The SDK owns pagination. Until its start hook exposes the input, + # retain only the bootstrap poll times, never transport responses. + start = time.time_ns() / 1_000_000 + try: + return self.client.get_execution_state(**kwargs) + finally: + self.initial_polls.append((start, time.time_ns() / 1_000_000)) + + with self.trace.publishing() as sealed: + call_id = self.trace.next_call_id("poll") + if sealed: + self.trace.emit("POLL_CALL") + start = time.time_ns() / 1_000_000 + try: + return self.client.get_execution_state(**kwargs) + finally: + end = time.time_ns() / 1_000_000 + self._record( + "POLL_CALL", + "poll_call", + prepublished=sealed, + callId=call_id, + atMs=start, + ) + self._record("POLL_EXIT", "poll_exit", callId=call_id, atMs=end) + + def checkpoint(self, **kwargs): + updates = [ + { + "id": u.operation_id, + "name": u.name, + "action": u.action.value, + "type": u.operation_type.value, + } + for u in kwargs["updates"] + ] + with self.trace.publishing() as sealed: + call_id = self.trace.next_call_id("checkpoint") + if sealed: + self.trace.emit("CHECKPOINT_CALL", updates=updates) + start = time.time_ns() / 1_000_000 + try: + try: + response = self.client.checkpoint(**kwargs) + finally: + end = time.time_ns() / 1_000_000 + self._record( + "CHECKPOINT_CALL", + "checkpoint_call", + {"updates": updates}, + prepublished=sealed, + callId=call_id, + updates=updates, + atMs=start, + ) + except BaseException as error: + error_type = type(error).__name__ + self._record( + "CHECKPOINT_ERROR", + "checkpoint_error", + {"error": error_type}, + callId=call_id, + error=error_type, + atMs=end, + ) + raise + else: + self._record( + "CHECKPOINT_ACK", + "checkpoint_ack", + {"updates": updates}, + callId=call_id, + operationIds=[item["id"] for item in updates], + source="service", + atMs=end, + ) + return response + finally: + self._record( + "CHECKPOINT_EXIT", "checkpoint_exit", callId=call_id, atMs=end + ) + + +def workflow(event, context, trace): + trace.durable_context = context + with trace.observer.root_scope(): + try: + result = run_workflow(event, context, trace) + except Exception: + trace.observe("root_completed", outcome="FAILED") + raise + else: + trace.observe("root_completed", outcome="SUCCEEDED") + return result + + +def run_workflow(event, context, trace): + marker, scenario = event["marker"], event["scenario"] + if scenario not in { + "success", + "failure", + "barrier", + "deadline", + "replay", + "warm-owner", + "warm-probe", + }: + raise ValueError(f"Unsupported lifecycle fixture: {scenario}") + try: + value = context.step(lambda s: trace.body("success", marker, s), name="success") + if scenario == "failure": + raise ValueError("expected:" + marker) + if scenario in {"barrier", "deadline"}: + original_request = None + if preparation_gate := event.get("preparation_gate"): + + def prepare(_): + trace.gate(preparation_gate, preparation=True) + return trace.identity["request"] + + original_request = context.step( + prepare, name="prepare-recovery", config=NO_RETRY + ) + trace.recovery_original_request = original_request + + def controlled_io(step): + # Fault injection belongs to the selected native invocation. + # This decision is inside the step; replay still consumes the + # same preparation checkpoint and durable operation sequence. + if ( + original_request is not None + and trace.identity["request"] != original_request + ): + trace.observe( + "fault_not_reapplied", originalRequestId=original_request + ) + return None + return trace.gate( + event["gate"], effects=scenario == "deadline", attempt=step.attempt + ) + + context.step(controlled_io, name="controlled-io", config=NO_RETRY) + context.step(lambda s: trace.body("after-io", marker, s), name="after-io") + elif scenario == "warm-owner": + context.step( + lambda _: start_warm_work(trace), + name="start-late-work", + config=NO_RETRY, + ) + elif scenario == "warm-probe": + context.step( + lambda _: release_warm_work(trace), + name="release-late-work", + config=NO_RETRY, + ) + elif scenario == "replay": + + def fail(step): + trace.body("failure", marker, step) + raise ValueError("expected:" + marker) + + try: + context.step(fail, name="failure", config=NO_RETRY) + except StepError as error: + if ( + error.error_type != "ValueError" + or error.message != "expected:" + marker + ): + raise AssertionError( + "Stored step failure has unexpected details" + ) from error + trace.emit( + "STORED_FAILURE", message=error.message, error_type=error.error_type + ) + trace.observe( + "stored_failure", + error={"type": error.error_type, "message": error.message}, + ) + else: + raise AssertionError("Stored step failure returned as a value") + + def retry(step): + trace.body("retry", marker, step) + if step.attempt == 1: + raise ValueError("retry once") + return marker + + retried = context.step( + retry, + name="retry", + config=StepConfig( + retry_strategy=lambda _e, n: ( + RetryDecision.retry(Duration.from_seconds(1)) + if n == 1 + else RetryDecision.no_retry() + ) + ), + ) + if retried != marker: + raise AssertionError("Retried step returned the wrong value") + mapped = context.run_in_child_context( + lambda c: c.map( + [1, 2, 3], + lambda inner, item, _index, _all: inner.step( + lambda step: trace.body("item", item, step), name="item" + ), + name="items", + config=MapConfig(max_concurrency=3), + ), + name="nested", + ) + items = mapped.get_results() + if items != [1, 2, 3] or any(type(item) is not int for item in items): + raise AssertionError("Replayed map returned the wrong items") + parallel = context.parallel( + [ + lambda c: c.step( + lambda step: trace.body("left", ["left", value], step), + name="left", + ), + lambda c: c.step( + lambda step: trace.body("right", ["right", value], step), + name="right", + ), + ], + name="pair", + ) + if parallel.get_results() != [["left", value], ["right", value]]: + raise AssertionError("Replayed parallel returned the wrong values") + context.wait(Duration.from_seconds(2), name="pause") + callback = context.create_callback(name="completion") + if callback.result() != marker: + raise AssertionError("Replayed callback returned the wrong value") + trace.emit("USER_RESULT", value=value) + return value + finally: + exited_at = time.time() * 1000 + trace.emit("USER_EXIT") + trace.observe("user_exit", atMs=exited_at) + + +def admission_probes(trace): + trace.observe("task_start", taskId="admission-probes", source="fixture") + closed = False + body_executed = False + + def body(_): + nonlocal body_executed + body_executed = True + trace.observe("probe_body_executed") + + try: + for probe, operation in ( + ( + "checkpoint", + lambda: trace.durable_context.state.create_checkpoint(is_sync=False), + ), + ( + "operation", + lambda: trace.durable_context.step( + body, name="operation-admission-probe", config=NO_RETRY + ), + ), + ): + trace.observe("probe_enter", probe=probe) + calls_before = trace.sdk_request_count + error_record = None + try: + operation() + except ( + OrphanedChildException, + BackgroundThreadError, + CheckpointError, + SuspendExecution, + ) as error: + # Failed/revoked SDK state can reject by re-raising its stored + # error. It is a rejection only before user code or a new RPC. + outcome = ( + "REJECTED" + if not body_executed and trace.sdk_request_count == calls_before + else "ERROR" + ) + error_record = {"type": type(error).__name__, "message": str(error)} + except BaseException as error: + outcome = "ERROR" + error_record = {"type": type(error).__name__, "message": str(error)} + else: + outcome = "ACCEPTED" + observed_at = time.time_ns() / 1_000_000 + if outcome == "REJECTED" and not closed: + trace.observe( + "admission_closed", atMs=observed_at, source="sdk-rejection" + ) + closed = True + trace.observe( + "admission_probe", + probe=probe, + outcome=outcome, + error=error_record, + atMs=observed_at, + bodyExecuted=body_executed, + newSdkRequests=trace.sdk_request_count - calls_before, + ) + finally: + trace.observe("task_exit", taskId="admission-probes", source="fixture") + + +def start_admission_probes(trace): + # A broken SDK can leave a late operation waiting forever. Keep that real + # task visible to the retirement audit instead of declaring it settled. + thread = trace.start_worker(lambda: admission_probes(trace), "lmi-admission-probes") + # Every probe observation is a separate S3 publication, and the runtime + # freezes this environment as soon as the handler returns. Wait for the + # declared admission budget -- the same window the shared validator allows + # these records to land in -- so a slow put cannot silently truncate the + # ledger or leak this request's sequence into the next invocation. + # A probe that is still pending after that window is a real SDK finding the + # shared validator already reports as a missing post-closure probe, so do + # not add a competing signal here. + budget = trace.payload.get("behaviorBudgets", {}).get("admissionMs", 5000) + thread.join(timeout=max(0.5, budget / 1000)) + + +@dataclass +class WarmWork: + ready: threading.Event = field(default_factory=threading.Event) + observed_during: str | None = None + worker: threading.Thread | None = None + + +WARM_WORK: dict[tuple[str, str], WarmWork] = {} +WARM_LOCK = threading.Lock() + + +def start_warm_work(trace): + key = (trace.payload["runId"], trace.payload["caseId"]) + work = WarmWork() + with WARM_LOCK: + if key in WARM_WORK: + raise ValueError("A warm case cannot replace its original work") + WARM_WORK[key] = work + + def late(): + try: + trace.observe("task_start", taskId="late-callback", source="fixture") + end = time.monotonic() + 120 + while not work.ready.wait(timeout=0.2): + if trace.released("release-all"): + return + if time.monotonic() >= end: + trace.observe( + "observation_error", + message="Original late work never observed warm reuse", + ) + return + trace.observe("late_activity", observedDuringRequestId=work.observed_during) + admission_probes(trace) + finally: + trace.observe("task_exit", taskId="late-callback", source="fixture") + with WARM_LOCK: + WARM_WORK.pop(key, None) + + try: + work.worker = trace.start_worker(late, "lmi-late-callback") + except BaseException: + with WARM_LOCK: + WARM_WORK.pop(key, None) + raise + return None + + +def release_warm_work(trace): + key = (trace.payload["runId"], trace.payload["caseId"]) + with WARM_LOCK: + work = WARM_WORK.get(key) + if work is None: + raise ValueError("Warm request did not reuse the original process") + work.observed_during = trace.identity["request"] + work.ready.set() + # The old invocation owns its callback and seal. Let that work complete + # while this warm invocation is still active and the process can run it. + assert work.worker is not None + budget = trace.payload.get("behaviorBudgets", {}).get("admissionMs", 5000) + work.worker.join(timeout=max(0.5, budget / 1000)) + return None + + +def handler(event, context): + invocation = ( + event + if isinstance(event, DurableExecutionInvocationInputWithClient) + else DurableExecutionInvocationInput.from_json_dict(event) + ) + started_at = time.time_ns() / 1_000_000 + source_client = ( + invocation.service_client + if isinstance(invocation, DurableExecutionInvocationInputWithClient) + else LambdaClient.initialize_client() + ) + client = ObservedClient(source_client) + before = resources() + + def bind_trace(event_input: dict[str, Any]) -> Trace: + if client.trace is not None: + return client.trace + trace = Trace(event_input, context, invocation.durable_execution_arn) + trace.emit("WRAPPER_ENTER", time=started_at / 1000, resources=before) + trace.observe("wrapper_enter", atMs=started_at, resources=before) + trace.observe( + "runtime_deadline", + atMs=trace.deadline_observed_at_ms, + remainingTimeMs=trace.remaining_ms, + deadlineAtMs=trace.deadline * 1000, + source="runtime", + ) + client.bind_trace(trace) + return trace + + # The initial page often has the input. Bind it immediately so failed + # initialization still has a request ledger. Otherwise the SDK will + # provide the input after fetching pages and before running user code. + for operation in invocation.initial_execution_state.operations: + if operation.execution_details and operation.execution_details.input_payload: + bind_trace(json.loads(operation.execution_details.input_payload)) + break + + injected = DurableExecutionInvocationInputWithClient.from_durable_execution_invocation_input( + invocation, client + ) + decorated = durable_execution( + lambda e, c: workflow(e, c, bind_trace(e)), + plugins=[FixtureObserverFactory(bind_trace)], + ) + + def complete(*, result=None, error=None): + trace = client.trace + if trace is None: + return + completed_at_ns = time.time_ns() + if error is None: + phase, kind, outcome = ( + "WRAPPER_RETURN", + "wrapper_return", + result["Status"], + ) + raw = {"status": outcome} + details = {} + else: + phase, kind, outcome = "WRAPPER_RAISE", "wrapper_raise", "THREW" + raw = {"error": type(error).__name__} + details = {"error": {"type": type(error).__name__, "message": str(error)}} + completed_resources = resources() + trace.emit( + phase, + resources=completed_resources, + time=completed_at_ns / 1_000_000_000, + **raw, + ) + trace.observe( + kind, + outcome=outcome, + resources=completed_resources, + atMs=completed_at_ns / 1_000_000, + **details, + ) + if outcome == "PENDING": + trace.observe( + "pending", + atMs=completed_at_ns / 1_000_000, + source="sdk-wrapper", + ) + if needs_admission_probes(trace): + if trace.durable_context is None: + trace.observe( + "observation_error", + message="SDK did not initialize a context for admission probes", + ) + else: + try: + start_admission_probes(trace) + except Exception as probe_error: + trace.fail_source("Could not start admission probes", probe_error) + trace.finish_wrapper() + + try: + result = decorated(injected, context) + except BaseException as error: + complete(error=error) + raise + else: + complete(result=result) + return result + + +def needs_admission_probes(trace: Trace) -> bool: + scenario = trace.payload.get("sharedScenario") + return ( + scenario + in {"normal-return", "normal-failure", "deadline-during-step", "peer-recovery"} + and trace.payload.get("role") == "victim" + and ( + scenario != "peer-recovery" + or trace.identity["request"] + == getattr(trace, "recovery_original_request", None) + ) + ) diff --git a/lmi_tests/runtime.py b/lmi_tests/runtime.py new file mode 100644 index 000000000..019d47b59 --- /dev/null +++ b/lmi_tests/runtime.py @@ -0,0 +1,7 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Python fixture configuration for the shared LMI harness.""" + +from aws_durable_execution_conformance_tests.lmi.runtime import RuntimeDefinition + +RUNTIME = RuntimeDefinition("python", "lmi_tests.fixture.handler") diff --git a/lmi_tests/shared-suite-design.md b/lmi_tests/shared-suite-design.md new file mode 100644 index 000000000..c8a7c9d6b --- /dev/null +++ b/lmi_tests/shared-suite-design.md @@ -0,0 +1,35 @@ +# Shared lifecycle suite ownership + +The Python adapter consumes the seven standard lifecycle requirements pinned by +`shared_contract.py`. Each YAML file in the shared repository has one `scenario`. +Normal return is requirement 2; normal failure is requirement 7. There is no +Python-owned replacement catalog, OTel profile or exporter matrix in this PR. + +The shared repository owns requirement descriptions, roles, minimum native +concurrency, scheduling, behavior validators, AWS transport, deployment, scenario +driving, evidence normalization and strict result aggregation. It also owns the +reusable `lmi-lifecycle.yml` workflow, called at the same pinned SHA as the shared +package. The SDK repository keeps `.github/scripts/lmi-ci.sh` for Python toolchain +and stage commands, and maps each scenario to its real public API fixture and retains +source observations. `make_manifest` reads the shared matrix, uses c1 for +single-worker cases and c2 for overlap/recovery, and preserves every required role. + +The same shared runner handles admission, original launch identity, immutable +case observations and independent retirement auditing. The adapter never replaces +a failed original with a retry, translates a runtime deadline into invented +service evidence, or clears a resource merely because cleanup was attempted. + +The deployed instrumentation uses the public SDK observation hooks plus a +transparent service-client wrapper. It records operations and user-code entries; +it does not change production SDK behavior. Admission probes expose actual SDK +rejections, acceptance and pending work. Local harness tests validate that these +outcomes reach the shared validator accurately; they do not claim real-LMI +acceptance or fix the underlying SDK lifecycle behavior. + +The core-only Lambda bundle excludes driver code and conformance packages. CI +retains the dedicated test-account boundary, trusted-PR condition, exact dependency +pin and run-scoped cleanup. GitHub Actions is the sole cross-run concurrency +guard: the fixed cloud-job group covers deployment, assertions and cleanup, with +`cancel-in-progress: false`. The adapter has no shared-lock module, S3 lease, +fence token or persisted quarantine. The shared runner still schedules individual +cases and reports retirement failures within each run. diff --git a/lmi_tests/shared.py b/lmi_tests/shared.py new file mode 100644 index 000000000..1de6b1e8d --- /dev/null +++ b/lmi_tests/shared.py @@ -0,0 +1,204 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Bootstrap the pinned shared harness and run it with the Python adapter.""" + +from __future__ import annotations +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +from typing import Any, Mapping +from lmi_tests.shared_contract import CONFORMANCE_REVISION + +ROOT = Path(__file__).resolve().parents[1] +ARTIFACTS = ROOT / "lmi_tests/artifacts" +COVERAGE_PROFILES = ("standard",) + + +def verify_checkout(checkout: Path) -> None: + revision = subprocess.check_output( + ["git", "-C", str(checkout), "rev-parse", "HEAD"], text=True + ).strip() + if revision != CONFORMANCE_REVISION: + raise ValueError( + f"Conformance checkout must be pinned to {CONFORMANCE_REVISION}" + ) + changed = subprocess.check_output( + ["git", "-C", str(checkout), "status", "--porcelain", "--", "packages"], + text=True, + ) + if changed: + raise ValueError("Pinned conformance package sources have local changes") + + +def setup(checkout: Path) -> None: + verify_checkout(checkout) + subprocess.run( + [ + sys.executable, + "-m", + "pip", + "install", + "--editable", + str(checkout / "packages/aws-durable-execution-conformance-tests"), + ], + check=True, + ) + + +def verify_install(checkout: Path) -> None: + verify_checkout(checkout) + import aws_durable_execution_conformance_tests as core + + source = ( + checkout.resolve() + / "packages/aws-durable-execution-conformance-tests/src/aws_durable_execution_conformance_tests/__init__.py" + ) + if Path(core.__file__).resolve() != source: + raise ValueError( + "Installed conformance package is not from the pinned checkout source; run shared setup" + ) + + +def make_manifest( + deployment: Mapping[str, Any], coverage: str, directory: Path +) -> dict[str, Any]: + from aws_durable_execution_conformance_tests.lmi.runner import ( + make_manifest as shared_manifest, + ) + from lmi_tests.shared_contract import configuration_identity + + core_wheels = { + name: digest + for name, digest in deployment["wheels"].items() + if name.startswith("aws_durable_execution_sdk_python-") + } + if len(core_wheels) != 1: + raise ValueError("Deployment does not retain an exact SDK wheel identity") + return shared_manifest( + deployment, + coverage, + directory, + runtime="python", + artifact_id="sha256:" + next(iter(core_wheels.values())), + conformance_revision=CONFORMANCE_REVISION, + configuration_identity=configuration_identity, + ) + + +def run(deployment: Mapping[str, Any], directory: Path) -> int: + from aws_durable_execution_conformance_tests.lmi.runner import run as shared_run + + return shared_run( + deployment, + directory, + manifest_factory=make_manifest, + adapter_name="lmi_tests.shared_adapter:create_adapter", + ) + + +def cleanup(deployment: Mapping[str, Any], directory: Path | None) -> int: + from aws_durable_execution_conformance_tests.lmi.runner import ( + cleanup as shared_cleanup, + ) + + return shared_cleanup(deployment, directory) + + +def cleanup_inputs( + manifest: Path, output: Path | None, expected_run: str | None +) -> tuple[dict[str, Any], Path | None]: + from aws_durable_execution_conformance_tests.lmi import ( + deployment as shared_deployment, + ) + from aws_durable_execution_conformance_tests.lmi.errors import CollectionError + + supplied_artifacts = manifest.parent.resolve() + manifest = manifest.resolve() + artifacts = manifest.parent + # Before archival, the active manifest can still link to older artifacts. + # The journal beside the supplied link owns the requested recovery. + if (supplied_artifacts / "deployment-update.json").is_file(): + artifacts = supplied_artifacts + journal = artifacts / "deployment-update.json" + pending_update = journal.is_file() + loader = getattr(shared_deployment, "load_cleanup_manifest", None) + if loader is None and pending_update: + raise CollectionError( + "Use the deployment's conformance revision to recover its journal" + ) + if loader is not None and expected_run: + deployment = loader(artifacts, expected_run, active_manifest=manifest) + else: + deployment = json.loads(manifest.read_text()) + + run = deployment.get("run") + if expected_run and run != expected_run: + raise CollectionError("Deployment manifest belongs to a different CI run") + if loader is None: + return deployment, output or artifacts / "shared" + + if output is None and deployment.get("deploymentArtifactDirectory") != str( + artifacts + ): + pointer = artifacts / "case-output.json" + if pointer.is_file(): + saved = json.loads(pointer.read_text()) + directory = saved.get("directory") + if saved.get("runId") == run and isinstance(directory, str) and directory: + if Path(directory).is_absolute(): + raise CollectionError( + "Specify --output for relocated artifacts with an absolute case output path" + ) + # The shared reconciler verifies journal identity before changing AWS. + # Only completed artifacts may be relocated to their local manifest parent. + if not pending_update: + deployment["deploymentArtifactDirectory"] = str(artifacts) + return deployment, output + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=("setup", "plan", "run", "cleanup")) + parser.add_argument( + "--checkout", + type=Path, + default=Path( + os.environ.get("LMI_CONFORMANCE_CHECKOUT", str(ROOT / ".conformance")) + ), + ) + parser.add_argument("--manifest", type=Path, default=ARTIFACTS / "manifest.json") + parser.add_argument("--output", type=Path) + args = parser.parse_args() + if args.command == "setup": + setup(args.checkout) + return + from aws_durable_execution_conformance_tests.lmi.artifacts import save + from aws_durable_execution_conformance_tests.lmi.errors import CollectionError + + verify_install(args.checkout) + expected_run = os.environ.get("LMI_SHARED_RUN_ID") + if args.command == "cleanup": + deployment, directory = cleanup_inputs(args.manifest, args.output, expected_run) + raise SystemExit(cleanup(deployment, directory)) + + deployment = json.loads(args.manifest.read_text()) + if expected_run and deployment.get("run") != expected_run: + raise CollectionError("Deployment manifest belongs to a different CI run") + + destination = args.output or args.manifest.resolve().parent / ( + "preview" if args.command == "plan" else "shared" + ) + if args.command == "plan": + destination.mkdir(parents=True) + for coverage in COVERAGE_PROFILES: + output = destination / coverage + save(output / "manifest.json", make_manifest(deployment, coverage, output)) + return + raise SystemExit(run(deployment, destination)) + + +if __name__ == "__main__": + main() diff --git a/lmi_tests/shared_adapter.py b/lmi_tests/shared_adapter.py new file mode 100644 index 000000000..0da3220c9 --- /dev/null +++ b/lmi_tests/shared_adapter.py @@ -0,0 +1,19 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Compose the shared LMI adapter with Python fixture policies.""" + +from aws_durable_execution_conformance_tests.lmi.adapter import SharedAdapter +from lmi_tests.cloud import Cloud +from lmi_tests.shared_contract import configuration_identity +from lmi_tests.shared_evidence import build_evidence +from lmi_tests.shared_scenarios import ScenarioDriver + + +def create_adapter(manifest): + return SharedAdapter( + manifest, + cloud_factory=Cloud, + driver_factory=ScenarioDriver, + evidence_builder=build_evidence, + configuration_identity=configuration_identity, + ) diff --git a/lmi_tests/shared_contract.py b/lmi_tests/shared_contract.py new file mode 100644 index 000000000..d3f7a07eb --- /dev/null +++ b/lmi_tests/shared_contract.py @@ -0,0 +1,20 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Pinned runner and verified deployment identities for the SDK adapter.""" + +from __future__ import annotations + +from typing import Any, Mapping + +CONFORMANCE_REPOSITORY = "aws/aws-durable-execution-conformance-tests" +# Updated only with the matching reviewed shared evidence contract. +CONFORMANCE_REVISION = "41878367192be996cb3414939e15270febedb210" + + +def configuration_identity(deployment: Mapping[str, Any], key: str) -> str: + from aws_durable_execution_conformance_tests.lmi.configuration import ( + configuration_identity as identity, + ) + from lmi_tests.runtime import RUNTIME + + return identity(deployment, key, RUNTIME) diff --git a/lmi_tests/shared_evidence.py b/lmi_tests/shared_evidence.py new file mode 100644 index 000000000..34d4d898c --- /dev/null +++ b/lmi_tests/shared_evidence.py @@ -0,0 +1,93 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Python expected outcomes and worker identity for shared evidence normalization.""" + +from collections.abc import Mapping, Sequence +from inspect import signature + +from aws_durable_execution_conformance_tests.lmi.source_evidence import ( + build_evidence as shared_build_evidence, +) + + +# One observed execution per durable operation ID, except for the retry fixture. +# Each map item owns a distinct operation ID despite sharing the name "item". +_EXPECTED_REPLAY_EFFECTS = { + "success": 1, + "failure": 1, + "retry": 2, + "item": 1, + "left": 1, + "right": 1, +} + + +def expected_outcome(item, scenario): + fixture = item.get("payload", {}).get("scenario") + if fixture == "failure": + return { + "status": "FAILED", + "error": { + "type": "ValueError", + "message": "expected:" + item["marker"], + }, + } + elif fixture == "deadline": + # This fixture asserts native deadline/retry behavior. Its logical + # execution may still be active or may finish after normal release. + return { + "allowedStatuses": [ + "RUNNING", + "SUCCEEDED", + "FAILED", + "TIMED_OUT", + "STOPPED", + ] + } + else: + return {"status": "SUCCEEDED", "result": item["marker"]} + + +def replay_effects( + bodies: Sequence[Mapping], +) -> tuple[dict[str, int], list[str]]: + owners: dict[tuple[str, int | None], str] = {} + allowances: dict[str, int] = {} + expected = { + (name, item): count + for name, count in _EXPECTED_REPLAY_EFFECTS.items() + for item in ((1, 2, 3) if name == "item" else (None,)) + } + for body in bodies: + name, identity = body["operation"], body["operationId"] + item = body.get("value") if name == "item" else None + key = (name, item) + if (name == "item" and type(item) is not int) or key not in expected: + allowances.setdefault(identity, 0) + continue + owner = owners.setdefault(key, identity) + allowances.setdefault(identity, expected[key] if identity == owner else 0) + missing = [ + f"item:{item}" if name == "item" else name + for name, item in expected + if (name, item) not in owners + ] + return allowances, missing + + +def build_evidence(context, cloud, *, phase="observations"): + parameters = signature(shared_build_evidence).parameters + options: dict = {} + if "expected_replay_effects" in parameters: + options["expected_replay_effects"] = _EXPECTED_REPLAY_EFFECTS + if "replay_effect_policy" in parameters: + options["replay_effect_policy"] = replay_effects + return shared_build_evidence( + context, + cloud, + runtime="python", + expected_outcome=expected_outcome, + worker_identity=lambda raw: raw["process"], + phase=phase, + **options, + ) diff --git a/lmi_tests/shared_observations.py b/lmi_tests/shared_observations.py new file mode 100644 index 000000000..ad9b6d958 --- /dev/null +++ b/lmi_tests/shared_observations.py @@ -0,0 +1,239 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Invocation-owned evidence from public SDK hooks, without conformance imports.""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping +from contextlib import contextmanager +from dataclasses import dataclass +import threading +from typing import Any, Protocol + +from aws_durable_execution_sdk_python.plugin import ( + DurableInstrumentationPlugin, + InvocationEndInfo, + InvocationStartInfo, + OperationChangeInfo, + OperationEndInfo, + OperationInfo, + OperationStartInfo, + OperationType, + UserFunctionEndInfo, + UserFunctionStartInfo, +) + + +class ObservationSink(Protocol): + """Record SDK observations without importing fixture.Trace.""" + + def observe(self, kind: str, **fields: Any) -> Mapping[str, Any]: ... + + +@dataclass(frozen=True) +class OperationObservation: + operation_id: str + parent_id: str | None + name: str | None + operation_type: str + sub_type: str | None + status: str + replayed: bool + attempt: int | None + result: str | None + error_type: str | None + error_message: str | None + started_at_ms: float | None + ended_at_ms: float | None + + @classmethod + def from_info(cls, info: OperationInfo) -> OperationObservation: + return cls( + operation_id=info.operation_id, + parent_id=info.parent_id, + name=info.name, + operation_type=info.operation_type.value, + sub_type=info.sub_type, + status=info.status.value, + replayed=info.is_replayed, + attempt=info.attempt, + result=info.result, + error_type=info.error.type if info.error else None, + error_message=info.error.message if info.error else None, + started_at_ms=info.start_time.timestamp() * 1000 + if info.start_time + else None, + ended_at_ms=info.end_time.timestamp() * 1000 if info.end_time else None, + ) + + def to_record(self) -> dict[str, Any]: + return { + "operationId": self.operation_id, + "parentId": self.parent_id, + "name": self.name, + "operationType": self.operation_type, + "subType": self.sub_type, + "status": self.status, + "isReplayed": self.replayed, + "attempt": self.attempt, + "serializedResult": self.result, + "error": {"type": self.error_type, "message": self.error_message} + if self.error_type is not None or self.error_message is not None + else None, + "startedAtMs": self.started_at_ms, + "endedAtMs": self.ended_at_ms, + } + + +@dataclass(frozen=True) +class UserTask: + operation: OperationObservation + task_id: str + + +class _ThreadTasks(threading.local): + def __init__(self) -> None: + self.stack: list[UserTask] = [] + + +class LifecycleObservations(DurableInstrumentationPlugin): + """One native invocation's actual operations and active public user scopes.""" + + def __init__(self, sink: ObservationSink) -> None: + self._sink = sink + self._lock = threading.Lock() + self._operations: dict[str, OperationObservation] = {} + self._threads = _ThreadTasks() + self._task_sequence = 0 + + def error(self, message: str) -> None: + self._sink.observe("observation_error", message=message) + + def _remember(self, info: OperationInfo) -> OperationObservation: + operation = OperationObservation.from_info(info) + with self._lock: + self._operations[operation.operation_id] = operation + return operation + + def current(self) -> OperationObservation | None: + return self._threads.stack[-1].operation if self._threads.stack else None + + @contextmanager + def root_scope(self) -> Iterator[None]: + """Observe the actual public handler body; root user hooks do not fire.""" + with self._lock: + roots = [ + item + for item in self._operations.values() + if item.operation_type == OperationType.EXECUTION.value + ] + if len(roots) != 1: + self.error("Handler entry has no unique public invocation root operation") + yield + return + task = UserTask(roots[0], "root") + self._threads.stack.append(task) + self._sink.observe( + "task_start", + taskId="root", + source="public-handler", + **task.operation.to_record(), + ) + try: + yield + finally: + self._threads.stack.pop() + self._sink.observe( + "task_exit", + taskId="root", + operationId=task.operation.operation_id, + source="public-handler", + ) + + def body(self, name: str, value: Any, attempt: int) -> None: + current = self.current() + if ( + current is None + or current.operation_type != OperationType.STEP.value + or current.name != name + ): + self.error(f"Body {name!r} has no matching public STEP hook") + return + if current.attempt != attempt: + self.error(f"Body {name!r} attempt differs from its public STEP hook") + return + self._sink.observe( + "body", + operation=name, + operationId=current.operation_id, + parentId=current.parent_id, + attempt=attempt, + value=value, + ) + + def on_invocation_start(self, info: InvocationStartInfo) -> None: + operations = [ + self._remember(operation) for operation in info.operations.values() + ] + self._sink.observe( + "invocation_start", + requestId=info.request_id, + executionArn=info.execution_arn, + isFirstInvocation=info.is_first_invocation, + operations=[operation.to_record() for operation in operations], + ) + + def on_invocation_end(self, info: InvocationEndInfo) -> None: + operations = [ + self._remember(operation) for operation in info.operations.values() + ] + self._sink.observe( + "invocation_end", + outcome=info.status.value, + operations=[operation.to_record() for operation in operations], + serializedResult=info.execution_result, + error={"type": info.error.type, "message": info.error.message} + if info.error + else None, + ) + + def on_operation_start(self, info: OperationStartInfo) -> None: + operation = self._remember(info) + self._sink.observe("operation_start", **operation.to_record()) + + def on_operation_end(self, info: OperationEndInfo) -> None: + operation = self._remember(info) + self._sink.observe("operation_end", **operation.to_record()) + + def on_operation_change(self, info: OperationChangeInfo) -> None: + changed = [ + self._remember(operation) for operation in info.updated_operations.values() + ] + self._sink.observe( + "operation_change", + operations=[operation.to_record() for operation in changed], + ) + + def on_user_function_start(self, info: UserFunctionStartInfo) -> None: + operation = self._remember(info) + with self._lock: + self._task_sequence += 1 + ordinal = self._task_sequence + task_id = f"user-task-{ordinal}" + self._threads.stack.append(UserTask(operation, task_id)) + self._sink.observe("task_start", taskId=task_id, **operation.to_record()) + + def on_user_function_end(self, info: UserFunctionEndInfo) -> None: + stack = self._threads.stack + if not stack or stack[-1].operation.operation_id != info.operation_id: + self.error("Public user-function end did not match its active start") + return + task = stack.pop() + self._sink.observe( + "task_exit", + taskId=task.task_id, + operationId=info.operation_id, + parentId=info.parent_id, + outcome=info.outcome.value, + attempt=task.operation.attempt, + ) diff --git a/lmi_tests/shared_scenarios.py b/lmi_tests/shared_scenarios.py new file mode 100644 index 000000000..5cdd01716 --- /dev/null +++ b/lmi_tests/shared_scenarios.py @@ -0,0 +1,37 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Bind shared lifecycle choreography to Python fixture entry points.""" + +from aws_durable_execution_conformance_tests.lmi.scenarios import ( + ScenarioDriver as SharedScenarioDriver, +) + +FIXTURES = { + "native-overlap": "barrier", + "normal-return": "success", + "deadline-during-step": "deadline", + "peer-recovery": "deadline", + "suspension-retry": "replay", + "warm-reuse": "warm-owner", + "normal-failure": "failure", +} + + +class ScenarioDriver(SharedScenarioDriver): + def __init__(self, context, cloud, **options): + # The pinned driver releases its reservation on the first PENDING. + # This fixture can resume before reaching the callback. + options.pop("release_capacity", None) + options.pop("reserve_capacity", None) + super().__init__( + context, + cloud, + runtime="python", + fixtures={ + **FIXTURES, + "peer": "barrier", + "recovery": "barrier", + "warm": "warm-probe", + }, + **options, + ) diff --git a/lmi_tests/summary.py b/lmi_tests/summary.py new file mode 100644 index 000000000..b1c0576fd --- /dev/null +++ b/lmi_tests/summary.py @@ -0,0 +1,28 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Render the shared report for the Python fixture's artifact directory.""" + +from inspect import signature +import json +import os +from pathlib import Path +from aws_durable_execution_conformance_tests.lmi.summary import summarize + + +def render(directory: Path, expected_run: str | None) -> str: + if "expected_run" in signature(summarize).parameters: + return summarize(directory, expected_run=expected_run) + if expected_run: + manifest = directory / "manifest.json" + if ( + manifest.is_file() + and json.loads(manifest.read_text()).get("run") != expected_run + ): + return "Deployment identity does not match this run. Current cloud acceptance is unavailable." + return summarize(directory) + + +if __name__ == "__main__": + print( + render(Path(__file__).parent / "artifacts", os.environ.get("LMI_SHARED_RUN_ID")) + ) diff --git a/lmi_tests/tests/e2e/test_peer_recovery_local.py b/lmi_tests/tests/e2e/test_peer_recovery_local.py new file mode 100644 index 000000000..2320ea571 --- /dev/null +++ b/lmi_tests/tests/e2e/test_peer_recovery_local.py @@ -0,0 +1,231 @@ +"""The real SDK checkpoints preparation before the controlled recovery fault.""" + +import json +import time + +import pytest + +from aws_durable_execution_sdk_python_testing import DurableFunctionTestRunner +from lmi_tests import fixture +from lmi_tests.tests.unit.test_shared_observations import install_ledger, shared_payload + + +def test_preparation_gate_precedes_fault_and_keeps_one_original_barrier(monkeypatch): + ledger = install_ledger(monkeypatch) + payload = shared_payload("deadline") + payload.update( + sharedScenario="peer-recovery", preparation_gate="prepare", gate="fault" + ) + prefix = payload["controlPrefix"] + for gate in ("prepare", "fault", "release-all"): + ledger.objects[prefix + gate] = b"hold" + with DurableFunctionTestRunner(handler=fixture.handler) as runner: + arn = runner.run_async(input=json.dumps(payload), execution_timeout=15) + prepared = ledger.wait_for("blocked")["observation"] + assert prepared["gateId"] == "prepare" + assert not [ + e + for e in ledger.observations() + if e["observation"]["kind"] == "barrier_arrived" + ] + assert not [ + e + for e in ledger.observations() + if e["observation"]["kind"] == "work_in_flight" + ] + ledger.objects[prefix + "prepare"] = b"release" + fault = ledger.wait_for("work_in_flight")["observation"] + assert fault["gateId"] == "fault" + ledger.objects[prefix + "fault"] = b"release" + result = runner.wait_for_result(arn, timeout=15) + assert result.result == '"marker"' + observations = [event["observation"] for event in ledger.observations()] + barriers = [event for event in observations if event["kind"] == "barrier_arrived"] + assert len(barriers) == 1 and barriers[0]["gateId"] == "prepare" + released = next( + e + for e in observations + if e["kind"] == "fault_released" and e["gateId"] == "prepare" + ) + assert barriers[0]["atMs"] == released["atMs"] + assert prepared["atMs"] < barriers[0]["atMs"] <= fault["atMs"] + checkpoint = next( + event + for event in observations + if event["kind"] == "checkpoint_ack" + and result.get_step("prepare-recovery").operation_id in event["operationIds"] + ) + assert prepared["atMs"] < checkpoint["atMs"] <= fault["atMs"] + assert not [event for event in observations if event["kind"] == "observation_error"] + + +def test_service_retry_replays_preparation_without_reinjecting_the_original_fault( + monkeypatch, +): + from aws_durable_execution_sdk_python.exceptions import RetryableSerDesError + + ledger = install_ledger(monkeypatch) + payload = shared_payload("deadline") + payload.update( + sharedScenario="peer-recovery", preparation_gate="prepare", gate="fault" + ) + prefix = payload["controlPrefix"] + ledger.objects[prefix + "prepare"] = b"release" + ledger.objects[prefix + "fault"] = b"hold" + ledger.objects[prefix + "release-all"] = b"hold" + gate = fixture.Trace.gate + fault_requests = [] + + def interrupted(trace, name, **options): + if name == "fault": + fault_requests.append(trace.identity["request"]) + # Trigger the SDK's actual invocation-retry path after preparation + # checkpointed, leaving controlled-io incomplete for replay. + raise RetryableSerDesError("transient interruption") + return gate(trace, name, **options) + + monkeypatch.setattr(fixture.Trace, "gate", interrupted) + with DurableFunctionTestRunner(handler=fixture.handler) as runner: + result = runner.run(input=json.dumps(payload), execution_timeout=20) + assert result.result == '"marker"' + assert len(fault_requests) == 1 + observations = ledger.observations() + raised = next( + e["observation"] + for e in observations + if e["request"] == fault_requests[0] + and e["observation"]["kind"] == "wrapper_raise" + ) + original_probes = [ + e["observation"] + for e in observations + if e["request"] == fault_requests[0] + and e["observation"]["kind"] == "admission_probe" + ] + assert original_probes and all(e["atMs"] >= raised["atMs"] for e in original_probes) + skipped = [ + e for e in observations if e["observation"]["kind"] == "fault_not_reapplied" + ] + assert len(skipped) == 1 + assert skipped[0]["request"] != fault_requests[0] + assert skipped[0]["observation"]["originalRequestId"] == fault_requests[0] + assert not [ + e + for e in observations + if e["request"] == skipped[0]["request"] + and e["observation"]["kind"] == "admission_probe" + ] + + +@pytest.mark.parametrize("role", ["peer", "recovery"]) +def test_off_target_cohort_member_uses_normal_control_for_driver_classification( + monkeypatch, role +): + ledger = install_ledger(monkeypatch) + payload = shared_payload("barrier") + payload.update( + role=role, + sharedScenario="peer-recovery", + target_environment="different-environment", + gate=role, + ) + prefix = payload["controlPrefix"] + ledger.objects[prefix + role] = ledger.objects[prefix + "release-all"] = b"hold" + with DurableFunctionTestRunner(handler=fixture.handler) as runner: + arn = runner.run_async(input=json.dumps(payload), execution_timeout=15) + try: + blocked = ledger.wait_for("blocked") + assert blocked["observation"]["gateId"] == role + assert blocked["environment"] != payload["target_environment"] + finally: + ledger.objects[prefix + "release-all"] = b"release" + result = runner.wait_for_result(arn, timeout=15) + assert result.result == '"marker"' + steps = {row["observation"].get("name") for row in ledger.observations()} + assert "controlled-io" in steps + assert "placement-admission" not in steps + assert "misplaced-peer-control" not in steps + + +@pytest.mark.parametrize("aborted", [False, True]) +def test_staggered_native_overlap_attests_only_after_both_heartbeats( + monkeypatch, aborted +): + ledger = install_ledger(monkeypatch) + victim = shared_payload("barrier") + victim.update(sharedScenario="native-overlap", gate="cohort") + peer = {**victim, "role": "peer", "marker": "peer"} + prefix = victim["controlPrefix"] + ledger.objects[prefix + "cohort"] = ledger.objects[prefix + "release-all"] = b"hold" + + def wait_for_pair(): + limit = time.monotonic() + 10 + while time.monotonic() < limit: + raw = ledger.records() + blocked = {row["role"]: row for row in raw if row["phase"] == "BLOCKED"} + if len(blocked) == 2: + peer_blocked = blocked["peer"]["time"] + if { + row["role"] + for row in raw + if row["phase"] == "ALIVE" and row["time"] >= peer_blocked + } == {"victim", "peer"}: + return blocked + time.sleep(0.01) + raise AssertionError("Original cohort did not publish two ordered heartbeats") + + with DurableFunctionTestRunner(handler=fixture.handler) as runner: + original = runner.run_async(input=json.dumps(victim), execution_timeout=15) + try: + ledger.wait_for("alive") + second = runner.run_async(input=json.dumps(peer), execution_timeout=15) + blocked = wait_for_pair() + assert blocked["victim"]["time"] < blocked["peer"]["time"] + assert not any( + row["observation"]["kind"] == "barrier_arrived" + for row in ledger.observations() + ) + gate = "release-all" if aborted else "cohort" + ledger.objects[prefix + gate] = b"release" + assert runner.wait_for_result(original, timeout=15).result == '"marker"' + assert runner.wait_for_result(second, timeout=15).result == '"peer"' + finally: + ledger.objects[prefix + "release-all"] = b"release" + + arrivals = [ + row + for row in ledger.observations() + if row["observation"]["kind"] == "barrier_arrived" + ] + expected_roles = [] if aborted else ["peer", "victim"] + assert sorted(row["role"] for row in arrivals) == expected_roles + assert all( + row["observation"]["atMs"] > blocked["peer"]["time"] * 1000 for row in arrivals + ) + + +def test_lost_io_exit_evidence_preserves_real_gate_completion(monkeypatch): + ledger = install_ledger(monkeypatch) + payload = shared_payload("barrier") + payload["gate"] = "gate" + prefix = payload["controlPrefix"] + ledger.objects[prefix + "gate"] = b"release" + ledger.objects[prefix + "release-all"] = b"hold" + put = ledger.put_object + + def store(**kwargs): + if json.loads(kwargs["Body"])["phase"] == "IO_EXIT": + raise OSError("evidence store unavailable") + return put(**kwargs) + + monkeypatch.setattr(ledger, "put_object", store) + with DurableFunctionTestRunner(handler=fixture.handler) as runner: + result = runner.run(input=json.dumps(payload), execution_timeout=15) + assert result.result == '"marker"' + assert any( + row["observation"]["kind"] == "fault_released" for row in ledger.observations() + ) + assert not any( + row["observation"]["kind"] == "io_exit" for row in ledger.observations() + ) + assert not any(row["phase"] == "SEALED" for row in ledger.records()) diff --git a/lmi_tests/tests/e2e/test_shared_driver_local.py b/lmi_tests/tests/e2e/test_shared_driver_local.py new file mode 100644 index 000000000..ca992130f --- /dev/null +++ b/lmi_tests/tests/e2e/test_shared_driver_local.py @@ -0,0 +1,182 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Exercise shared phase routing against the real SDK's local durable runner. + +This checks public handler/callback/replay behavior, not real-LMI placement or +cloud conformance acceptance. +""" + +from contextlib import nullcontext +import json +from threading import Lock +from unittest.mock import Mock +import time + +from aws_durable_execution_conformance_tests.lmi.coordinator import ( + Profile, + Scenario, + ScenarioContext, +) +from aws_durable_execution_sdk_python import durable_execution +from aws_durable_execution_sdk_python_testing import DurableFunctionTestRunner +from lmi_tests.fixture import workflow +from lmi_tests.shared_scenarios import ScenarioDriver +from lmi_tests.tests.unit.test_shared_observations import ( + install_distinct_local_request_ids, +) + + +class LocalTrace: + def __init__(self): + self.events = [] + self.observer = self + self.payload = {} + self.lock = Lock() + + def root_scope(self): + return nullcontext() + + def observe(self, kind, **fields): + pass + + def emit(self, phase, **fields): + with self.lock: + self.events.append({"phase": phase, "time": time.time(), **fields}) + + def body(self, name, value, step): + self.emit("BODY", operation=name, value=value, attempt=step.attempt) + return value + + def snapshot(self): + with self.lock: + return list(self.events) + + +class LocalService: + """Replace only AWS transport, keeping the actual fixture and SDK runner.""" + + def __init__(self): + self.manifest = {"driverTimeout": 15} + self.trace = LocalTrace() + self.invocations = [] + self.callback_records = [] # Older pinned driver also journals callbacks. + self.result = None + decorated = durable_execution( + lambda event, context: workflow(event, context, self.trace) + ) + + def handler(event, context): + self.trace.emit("WRAPPER_ENTER", request=context.aws_request_id) + result = decorated(event, context) + self.trace.emit( + "WRAPPER_RETURN", + request=context.aws_request_id, + status=result["Status"], + ) + return result + + # Keep service history timestamps comparable to the fixture's wall clock. + self.runner = DurableFunctionTestRunner( + handler, poll_interval=0.01, skip_time=False + ) + + def start(self, fixture, **options): + payload = {"marker": options["marker"], "scenario": fixture} + arn = self.runner.run_async(input=payload) + item = {"arn": arn, "marker": payload["marker"], "runner": self.runner} + self.invocations.append(item) + return item + + def poll(self, predicate, seconds=15, **options): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + observed = predicate() + if observed: + return observed + time.sleep(0.01) + raise AssertionError(options.get("message", "local observation timeout")) + + def phase(self, item, phase, **options): + return self.poll( + lambda: [ + event for event in self.trace.snapshot() if event["phase"] == phase + ], + **options, + ) + + def for_item(self, item): + return self.trace.snapshot() + + def history(self, item): + return self.runner.get_execution_history( + item["arn"], include_execution_data=True + ).to_dict()["Events"] + + def check_active(self): + pass + + def finish(self, item, status="SUCCEEDED"): + self.result = self.runner.wait_for_result(item["arn"], timeout=15) + assert self.result.status.value == status + + +def test_shared_callback_driver_resumes_the_original_public_sdk_execution(monkeypatch): + install_distinct_local_request_ids(monkeypatch) + service = LocalService() + profile = Profile("native-1", "local-function", 1, 1, "local-sdk", "local-config") + context = ScenarioContext( + "local-run", + Scenario( + "callback-case", + "lmi-lifecycle-5", + profile.profile_id, + "suspension-retry", + roles=("victim", "resume"), + ), + profile, + ) + release_capacity = Mock() + reserve_capacity = Mock() + driver = ScenarioDriver( + context, + service, + release_capacity=release_capacity, + reserve_capacity=reserve_capacity, + ) + with service.runner: + driver.start() + driver.place() + driver.execute() + assert len(service.invocations) == 1 + history = service.history(service.invocations[0]) + release_capacity.assert_not_called() + reserve_capacity.assert_not_called() + started = [event for event in history if event["EventType"] == "CallbackStarted"] + succeeded = [ + event for event in history if event["EventType"] == "CallbackSucceeded" + ] + assert len(started) == len(succeeded) == 1 + assert started[0]["Id"] == succeeded[0]["Id"] + assert json.loads(service.result.result) == service.invocations[0]["marker"] + events = service.trace.snapshot() + assert any( + event["phase"] == "WRAPPER_RETURN" and event["status"] == "PENDING" + for event in events + ) + entered = { + event["request"] for event in events if event["phase"] == "WRAPPER_ENTER" + } + completed = { + event["InvocationCompletedDetails"]["RequestId"] + for event in history + if event["EventType"] == "InvocationCompleted" + } + assert len(entered) > 1 + assert entered == completed + bodies = [event for event in events if event["phase"] == "BODY"] + assert sum(event["operation"] == "success" for event in bodies) == 1 + assert sum(event["operation"] == "failure" for event in bodies) == 1 + assert [event["attempt"] for event in bodies if event["operation"] == "retry"] == [ + 1, + 2, + ] diff --git a/lmi_tests/tests/e2e/test_shared_evidence_local.py b/lmi_tests/tests/e2e/test_shared_evidence_local.py new file mode 100644 index 000000000..12ecd1ab5 --- /dev/null +++ b/lmi_tests/tests/e2e/test_shared_evidence_local.py @@ -0,0 +1,374 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Real SDK invocation/replay evidence reaches the shared validator unchanged.""" + +from copy import deepcopy +from inspect import signature +import json +import time + +import pytest +from pathlib import Path + +from aws_durable_execution_conformance_tests.lmi.app import validate +from aws_durable_execution_conformance_tests.lmi.coordinator import ( + Profile, + Scenario, + ScenarioContext, +) +from aws_durable_execution_sdk_python_testing import DurableFunctionTestRunner +from lmi_tests import fixture +from lmi_tests.cloud import Cloud +from lmi_tests.shared_evidence import ( + build_evidence, + expected_outcome, + shared_build_evidence, +) +from lmi_tests.tests.unit.test_shared_observations import install_ledger, shared_payload + + +def test_real_sdk_replay_and_service_history_normalize_for_shared_acceptance( + monkeypatch, tmp_path +): + ledger = install_ledger(monkeypatch) + payload = shared_payload("replay") + payload["sharedScenario"] = "suspension-retry" + payload["behaviorBudgets"] = {"observationGraceMs": 1} + # The shared evidence uses one observation clock, and callback retirement + # is timed from the service history. The local runner's default virtual + # clock skips this fixture's durable wait, which would date service events + # ahead of the wall-clock retirement they are compared against. + with DurableFunctionTestRunner(handler=fixture.handler, skip_time=False) as runner: + arn = runner.run_async(input=json.dumps(payload), execution_timeout=30) + callback = runner.wait_for_callback(arn, name="completion", timeout=20) + runner.send_callback_success(callback, result=b"marker") + result = runner.wait_for_result(arn, timeout=20) + history = runner.get_execution_history( + arn, include_execution_data=True + ).to_dict()["Events"] + evidence, cloud = assemble( + ledger, + result, + history, + payload, + tmp_path, + "lmi-lifecycle-5", + "suspension-retry", + ) + assert evidence["collectionErrors"] == [] + assert validate(evidence) == [] + bodies = [event for event in evidence["events"] if event["kind"] == "body"] + assert len([event for event in bodies if event["operation"] == "success"]) == 1 + nested = { + event["operationId"] + for event in bodies + if event["operation"] in {"item", "left", "right"} + } + assert len(nested) == 5 + counts = { + item["operationId"]: (item["count"], item["expectedCount"]) + for item in evidence["replay"]["sideEffects"] + } + assert all(counts[operation] == (1, 1) for operation in nested) + duplicated = deepcopy(evidence) + repeated = next( + item + for item in duplicated["replay"]["sideEffects"] + if item["operationId"] in nested + ) + repeated["count"] += 1 + assert any("side-effect count" in error for error in validate(duplicated)) + # The installed builder must publish exactly the returned snapshot. + saved = json.loads((cloud.artifacts_dir / "shared-final-evidence.json").read_text()) + assert saved == evidence + + if "replay_effect_policy" in signature(shared_build_evidence).parameters: + from aws_durable_execution_conformance_tests.lmi.evidence import ( + validate_retirement_evidence, + ) + + item = next( + event + for event in bodies + if event["operation"] == "item" and event["value"] == 1 + ) + stream = sorted( + ( + raw + for raw in cloud.events.values() + if raw["request"] == item["requestId"] + ), + key=lambda raw: raw["sequence"], + ) + raw_body = next( + raw + for raw in stream + if raw.get("observation", {}).get("sourceSequence") + == item["sourceSequence"] + ) + seal = stream[-1] + assert seal["phase"] == "SEALED" + seal_key = next(key for key, raw in cloud.events.items() if raw is seal) + sequence = seal["sequence"] + capture = seal["throughCapture"] + 1 + # Inject one witnessed extra execution before the terminal seal, + # preserving independent native completion and retirement records. + cloud.events["extra-observed-item"] = { + **raw_body, + "sequence": sequence, + "observation": { + **raw_body["observation"], + "operationId": "unexpected-repeat", + "sourceSequence": sequence, + "captureSequence": capture, + }, + } + raw_effect = next( + raw + for raw in stream + if raw["phase"] == "BODY" + and raw.get("operation") == "item" + and raw.get("value") == 1 + ) + cloud.events["extra-raw-item"] = {**raw_effect, "sequence": sequence + 1} + cloud.events[seal_key] = { + **seal, + "sequence": sequence + 2, + "throughCapture": capture, + } + partial = build_evidence(cloud.case_context, cloud, phase="partial") + assert { + "operationId": "unexpected-repeat", + "count": 1, + "expectedCount": 0, + } in partial["replay"]["sideEffects"] + assert not partial["replay"].get("missingExpectedEffects") + + observed_duplicate = build_evidence(cloud.case_context, cloud, phase="final") + assert any( + "side-effect count" in error for error in validate(observed_duplicate) + ) + assert validate_retirement_evidence(observed_duplicate) == [] + saved_duplicate = json.loads( + (cloud.artifacts_dir / "shared-final-evidence.json").read_text() + ) + assert saved_duplicate == observed_duplicate + del cloud.events["extra-observed-item"] + del cloud.events["extra-raw-item"] + cloud.events[seal_key] = seal + # Losing a real source object must not turn into an inferred complete stream. + cloud.events.pop(next(iter(cloud.events))) + incomplete = build_evidence(cloud.case_context, cloud, phase="observations") + assert incomplete["collectionErrors"] + assert incomplete["collection"]["watermarks"] == {} + + +def assemble(ledger, result, history, payload, tmp_path, requirement_id, scenario): + raw = ledger.records() + arn = next(e["execution"] for e in raw if e["phase"] == "WRAPPER_ENTER") + profile = Profile( + "c1", "local-function", 1, 1, "actual-local-sdk", "local-config", "reuse-worker" + ) + context = ScenarioContext( + "unit", + Scenario( + "case", + requirement_id, + "c1", + scenario, + roles=("victim", "resume") + if scenario == "suspension-retry" + else ("victim",), + coverage_profile="standard", + behavior_budgets={"observationGraceMs": 1}, + ), + profile, + ) + raw = ledger.records() + entries = sorted( + (event for event in raw if event["phase"] == "WRAPPER_ENTER"), + key=lambda event: event["time"], + ) + roles = {} + for index, event in enumerate(entries): + role = "resume" if index and scenario == "suspension-retry" else "victim" + roles[event["request"]] = role + context.record_attempt(event["request"], role=role, requestId=event["request"]) + cloud = object.__new__(Cloud) + cloud.case_context = context + cloud.manifest = { + "commit": "tested-commit", + "invocationTimeout": 30, + "conformanceRevision": "local-pinned-conformance", + } + cloud.events = {str(index): event for index, event in enumerate(raw)} + cloud.invocations = [ + { + "arn": arn, + "marker": "marker", + "role": "victim", + "payload": payload, + "native_requests": list(roles), + "trace_header": None, + } + ] + cloud.request_roles = roles + cloud.raw_histories = {arn: history} + # These tests read history only after the real local service returns a + # terminal execution result, the same boundary as Cloud.collect. + cloud.terminal_histories = {arn} + actual = {"Status": result.status.value} + if result.result is not None: + actual["Result"] = result.result + if result.error is not None: + actual["Error"] = result.error.to_dict() + cloud.execution_results = {arn: actual} + cloud.control_records = [] + cloud.source_uris = {"memory://actual-sdk-ledger"} + time.sleep(0.002) + cloud.observation_ended_at = time.time() + cloud.retired_at = cloud.observation_ended_at + cloud.artifacts_dir = Path(tmp_path) + evidence = build_evidence(context, cloud, phase="final") + return evidence, cloud + + +@pytest.mark.parametrize( + "requirement_id,scenario,fixture_name,outcome", + [ + ("lmi-lifecycle-2", "normal-return", "success", "SUCCEEDED"), + ("lmi-lifecycle-7", "normal-failure", "failure", "FAILED"), + ], +) +def test_actual_disposal_outcome_and_late_admission_findings_reach_shared_validation( + monkeypatch, tmp_path, requirement_id, scenario, fixture_name, outcome +): + ledger = install_ledger(monkeypatch) + payload = shared_payload(fixture_name) + payload["sharedScenario"] = scenario + with DurableFunctionTestRunner(handler=fixture.handler) as runner: + result = runner.run(input=json.dumps(payload), execution_timeout=15) + arn = next( + e["execution"] for e in ledger.records() if e["phase"] == "WRAPPER_ENTER" + ) + history = runner.get_execution_history( + arn, include_execution_data=True + ).to_dict()["Events"] + assert result.status.value == outcome + evidence, _ = assemble( + ledger, result, history, payload, tmp_path, requirement_id, scenario + ) + victim = evidence["selectedRequests"]["victim"] + original = next( + item for item in evidence["attempts"] if item["requestId"] == victim + ) + assert original["outcome"] == outcome + if outcome == "FAILED": + assert evidence["histories"][0]["error"] == { + "type": "ValueError", + "message": "expected:marker", + } + probes = [e for e in evidence["events"] if e["kind"] == "admission_probe"] + checkpoint_probe = next(e for e in probes if e["probe"] == "checkpoint") + errors = validate(evidence) + if evidence["collectionErrors"]: + assert errors + assert not {event["kind"] for event in evidence["events"]} & { + "observation_error", + "control_error", + } + assert all( + "complete observation window" in error or "Missing ledger seals" in error + for error in evidence["collectionErrors"] + ), errors + elif checkpoint_probe["outcome"] != "REJECTED": + assert any( + "closed invocation admitted a checkpoint probe" in error for error in errors + ) + else: + assert not any( + "closed invocation admitted a checkpoint probe" in error for error in errors + ) + wrapper = next( + event for event in evidence["events"] if event["kind"] == "wrapper_return" + ) + late_dispatch = any( + request["requestId"] == victim + and request["atMs"] > wrapper["atMs"] + and request["outcome"] == "DISPATCHED" + for request in evidence["sdkRequests"] + ) + if late_dispatch: + assert any( + "SDK work after" in error or "SDK request" in error for error in errors + ) + else: + operation = next( + (probe for probe in probes if probe["probe"] == "operation"), None + ) + assert errors == expected_disposal_diagnostics(operation) + + # Test late admission independently of any incomplete collection. The + # published validator checks the collection envelope before the scenario. + admitted = deepcopy(evidence) + admitted["collectionErrors"] = [] + admitted["collection"]["watermarks"] = dict.fromkeys( + ("lifecycle", "sdkRequests", "history"), admitted["observationEndedAtMs"] + ) + checkpoint = next( + event + for event in admitted["events"] + if event["kind"] == "admission_probe" and event["probe"] == "checkpoint" + ) + safe = deepcopy(admitted) + safe["events"] = [ + event for event in safe["events"] if event.get("probe") != "operation" + ] + wrapper_end = next( + event["atMs"] for event in safe["events"] if event["kind"] == "wrapper_return" + ) + safe["sdkRequests"] = [ + request + for request in safe["sdkRequests"] + if request.get("requestId") != victim or request["atMs"] < wrapper_end + ] + synthetic_checkpoint = next( + event + for event in safe["events"] + if event["kind"] == "admission_probe" and event.get("probe") == "checkpoint" + ) + synthetic_checkpoint["outcome"] = "REJECTED" + operation = { + **synthetic_checkpoint, + "probe": "operation", + "outcome": "ACCEPTED", + "sequence": max(event["sequence"] for event in safe["events"]) + 1, + } + safe["events"].append(operation) + assert validate(safe, phase="observations") == expected_disposal_diagnostics( + operation + ) + checkpoint["outcome"] = "ACCEPTED" + assert any( + "closed invocation admitted a checkpoint probe" in error + for error in validate(admitted, phase="observations") + ) + + +def expected_disposal_diagnostics(operation): + if "expected_replay_effects" in signature(shared_build_evidence).parameters: + return [] + if operation is None: + return ["INCOMPLETE: missing post-closure operation admission probe"] + if operation["outcome"] == "REJECTED": + return [] + return ["ASSERTION: closed invocation admitted a operation probe"] + + +@pytest.mark.parametrize("scenario", ["deadline-during-step", "peer-recovery"]) +def test_deadline_fixtures_validate_physical_timeout_independent_of_logical_disposition( + scenario, +): + assert expected_outcome({"payload": {"scenario": "deadline"}}, scenario) == { + "allowedStatuses": ["RUNNING", "SUCCEEDED", "FAILED", "TIMED_OUT", "STOPPED"] + } diff --git a/lmi_tests/tests/e2e/test_shared_observations_local.py b/lmi_tests/tests/e2e/test_shared_observations_local.py new file mode 100644 index 000000000..1db7c6cd1 --- /dev/null +++ b/lmi_tests/tests/e2e/test_shared_observations_local.py @@ -0,0 +1,198 @@ +"""Run the actual Lambda fixture through the public in-process SDK service.""" + +from __future__ import annotations + +import json + +import pytest +from collections import Counter + +from aws_durable_execution_sdk_python_testing import DurableFunctionTestRunner +from lmi_tests import fixture +from lmi_tests.tests.unit.test_shared_observations import install_ledger, shared_payload + + +def values(ledger, kind): + return [ + record["observation"] + for record in ledger.observations() + if record["observation"]["kind"] == kind + ] + + +def assert_sealed(ledger, request): + records = [event for event in ledger.records() if event["request"] == request] + seal = records[-1] + assert seal["phase"] == "SEALED" + assert seal["sourceProtocol"] == 2 + assert "observation" not in seal + assert [event["phase"] for event in records].count("SEALED") == 1 + captures = sorted( + event["observation"]["captureSequence"] + for event in records + if event["phase"] == "CONFORMANCE" + ) + assert captures == list(range(1, seal["throughCapture"] + 1)) + assert [event["sequence"] for event in records] == list(range(1, len(records) + 1)) + return seal + + +def test_actual_fixture_public_hooks_bind_bodies_checkpoints_and_root_lifetime( + monkeypatch, +): + ledger = install_ledger(monkeypatch) + with DurableFunctionTestRunner(handler=fixture.handler) as runner: + result = runner.run(input=json.dumps(shared_payload()), execution_timeout=30) + assert result.result == '"marker"' + assert values(ledger, "observation_error") == [] + assert_sealed(ledger, ledger.records()[0]["request"]) + body = values(ledger, "body") + assert ( + len(body) == 1 + and body[0]["operationId"] == result.get_step("success").operation_id + ) + assert body[0]["parentId"] == result.get_step("success").parent_id + assert body[0]["operationId"] in { + operation + for ack in values(ledger, "checkpoint_ack") + for operation in ack["operationIds"] + } + assert {item["callId"] for item in values(ledger, "checkpoint_call")} == { + item["callId"] for item in values(ledger, "checkpoint_exit") + } + assert {item["taskId"] for item in values(ledger, "task_start")} == { + item["taskId"] for item in values(ledger, "task_exit") + } + assert ( + next(item for item in values(ledger, "task_exit") if item["taskId"] == "root")[ + "atMs" + ] + <= values(ledger, "wrapper_return")[0]["atMs"] + ) + + +def test_actual_service_replay_keeps_operation_identity_and_skips_completed_bodies( + monkeypatch, +): + ledger = install_ledger(monkeypatch) + payload = shared_payload("replay") + with DurableFunctionTestRunner(handler=fixture.handler) as runner: + arn = runner.run_async(input=json.dumps(payload), execution_timeout=30) + callback = runner.wait_for_callback(arn, name="completion", timeout=20) + runner.send_callback_success(callback, result=b"marker") + result = runner.wait_for_result(arn, timeout=20) + assert result.result == '"marker"' + assert values(ledger, "observation_error") == [] + bodies = values(ledger, "body") + assert Counter(item["operation"] for item in bodies) == { + "success": 1, + "failure": 1, + "retry": 2, + "item": 3, + "left": 1, + "right": 1, + } + assert { + item["operationId"] for item in bodies if item["operation"] == "success" + } == {result.get_step("success").operation_id} + starts = values(ledger, "invocation_start") + assert len(starts) >= 2 and any(not item["isFirstInvocation"] for item in starts) + replay = next(item for item in starts if not item["isFirstInvocation"]) + assert any( + item["operationId"] == result.get_step("success").operation_id + and item["status"] == "SUCCEEDED" + for item in replay["operations"] + ) + assert "PENDING" in {item["outcome"] for item in values(ledger, "wrapper_return")} + observations = ledger.observations() + for request in {event["request"] for event in observations}: + assert_sealed(ledger, request) + for record in observations: + if record["observation"]["kind"] != "pending": + continue + wrapper = next( + item["observation"] + for item in observations + if item["request"] == record["request"] + and item["observation"]["kind"] == "wrapper_return" + ) + assert record["observation"]["atMs"] == wrapper["atMs"] + + +def test_warm_invocation_observes_late_work_under_its_original_request(monkeypatch): + from aws_durable_execution_conformance_tests.lmi.artifacts import case_key + + ledger = install_ledger(monkeypatch) + owner = shared_payload("warm-owner") + owner["sharedScenario"] = "warm-reuse" + owner["caseId"] = "local-warm-reuse" + owner["controlPrefix"] = f"runs/unit/cases/{case_key(owner['caseId'])}/control/" + ledger.objects[owner["controlPrefix"] + "release-all"] = b"hold" + warm = {**owner, "scenario": "warm-probe", "role": "warm", "marker": "warm-marker"} + with DurableFunctionTestRunner(handler=fixture.handler) as runner: + first = runner.run(input=json.dumps(owner), execution_timeout=15) + assert not any(event["phase"] == "SEALED" for event in ledger.records()) + second = runner.run(input=json.dumps(warm), execution_timeout=15) + assert first.result == '"marker"' + assert second.result == '"warm-marker"' + raw = ledger.records() + original = next( + e for e in raw if e["phase"] == "WRAPPER_RETURN" and e["role"] == "victim" + ) + entered = next( + e for e in raw if e["phase"] == "WRAPPER_ENTER" and e["role"] == "warm" + ) + ended = next( + e for e in raw if e["phase"] == "WRAPPER_RETURN" and e["role"] == "warm" + ) + late = next( + e for e in raw if e.get("observation", {}).get("kind") == "late_activity" + ) + assert late["request"] == original["request"] + assert late["execution"] == original["execution"] + assert late["observation"]["observedDuringRequestId"] == entered["request"] + assert original["time"] < entered["time"] <= late["time"] <= ended["time"] + assert_sealed(ledger, entered["request"]) + # The real SDK can leave its post-closure operation probe waiting. + # Such an owner must remain unsealed until its own worker exits. + owner_rows = [event for event in raw if event["request"] == original["request"]] + owner_exits = [ + event + for event in owner_rows + if event.get("observation", {}).get("kind") == "task_exit" + and event["observation"].get("taskId") == "late-callback" + ] + assert any(event["phase"] == "SEALED" for event in owner_rows) == bool(owner_exits) + + +@pytest.mark.parametrize("lost_phase", ["WRAPPER_ENTER", "USER_EXIT", "STORED_FAILURE"]) +def test_source_write_failure_preserves_real_suspend_and_resume( + monkeypatch, lost_phase +): + ledger = install_ledger(monkeypatch) + put = ledger.put_object + + def store(**kwargs): + if json.loads(kwargs["Body"])["phase"] == lost_phase: + raise OSError("evidence store unavailable") + return put(**kwargs) + + monkeypatch.setattr(ledger, "put_object", store) + with DurableFunctionTestRunner(handler=fixture.handler) as runner: + arn = runner.run_async( + input=json.dumps(shared_payload("replay")), execution_timeout=30 + ) + callback = runner.wait_for_callback(arn, name="completion", timeout=20) + runner.send_callback_success(callback, result=b"marker") + result = runner.wait_for_result(arn, timeout=20) + history = runner.get_execution_history( + arn, include_execution_data=True + ).to_dict()["Events"] + assert result.result == '"marker"' + completion_ids = { + event["InvocationCompletedDetails"]["RequestId"] + for event in history + if event["EventType"] == "InvocationCompleted" + } + assert len(completion_ids) > 1 + assert not any(row["phase"] == "SEALED" for row in ledger.records()) diff --git a/lmi_tests/tests/unit/support.py b/lmi_tests/tests/unit/support.py new file mode 100644 index 000000000..5640071e9 --- /dev/null +++ b/lmi_tests/tests/unit/support.py @@ -0,0 +1,80 @@ +"""Assert fixed behavior, not the bug. All blocking fixture work has a final release.""" + +import json +import time +from unittest.mock import Mock + + +from aws_durable_execution_sdk_python.execution import ( + DurableExecutionInvocationInputWithClient, + InitialExecutionState, +) +from aws_durable_execution_sdk_python.lambda_service import ( + CheckpointOutput, + CheckpointUpdatedExecutionState, + ContextDetails, + ExecutionDetails, + Operation, + OperationStatus, + OperationType, + StepDetails, +) + + +class MemoryClient: + def checkpoint(self, *, updates, **_kwargs): + changed = [ + Operation( + operation_id=u.operation_id, + operation_type=u.operation_type, + status={ + "START": OperationStatus.STARTED, + "SUCCEED": OperationStatus.SUCCEEDED, + "FAIL": OperationStatus.FAILED, + }[u.action.value], + name=u.name, + parent_id=u.parent_id, + sub_type=u.sub_type, + step_details=StepDetails(result=u.payload, error=u.error) + if u.operation_type == OperationType.STEP + else None, + context_details=ContextDetails(result=u.payload, error=u.error) + if u.operation_type == OperationType.CONTEXT + else None, + ) + for u in updates + ] + return CheckpointOutput( + "next-token", CheckpointUpdatedExecutionState(operations=changed) + ) + + +def invocation(): + return DurableExecutionInvocationInputWithClient( + durable_execution_arn="arn:test:execution/local", + checkpoint_token="token", + initial_execution_state=InitialExecutionState( + operations=[ + Operation( + operation_id="local", + operation_type=OperationType.EXECUTION, + status=OperationStatus.STARTED, + execution_details=ExecutionDetails(input_payload=json.dumps({})), + ) + ], + next_marker="", + ), + service_client=MemoryClient(), + ) + + +def lambda_context(remaining): + context = Mock() + context.aws_request_id = "local-request" + context.client_context = context.identity = context.tenant_id = None + context.invoked_function_arn = "test-function" + context._epoch_deadline_time_in_ms = int(time.time() * 1000) + remaining + context.get_remaining_time_in_millis.side_effect = lambda: ( + context._epoch_deadline_time_in_ms - int(time.time() * 1000) + ) + return context diff --git a/lmi_tests/tests/unit/test_control.py b/lmi_tests/tests/unit/test_control.py new file mode 100644 index 000000000..442e9558a --- /dev/null +++ b/lmi_tests/tests/unit/test_control.py @@ -0,0 +1,175 @@ +"""Regressions for the real-cloud 403 and premature-loser false positives.""" + +import io +import threading +import time +from types import SimpleNamespace +from unittest.mock import Mock + +import boto3 +from botocore.exceptions import ClientError +from botocore.stub import Stubber +import pytest + +from lmi_tests.fixture import Trace +from lmi_tests import fixture + + +@pytest.fixture +def trace(): + value = Trace.__new__(Trace) + value.state_lock, value.capture_sequence = threading.Lock(), 0 + value.source_failed = False + value.publication_seconds = 0.0 + value.closed = False + value.call_sequence, value.sdk_request_count = 0, 0 + value.lock = threading.Lock() + value.observe = Mock() + value.s3 = boto3.client( + "s3", + region_name="us-west-2", + aws_access_key_id="test", + aws_secret_access_key="test", + ) + value.bucket = "test-bucket" + value.identity = {"run": "unit", "request": "unit-request"} + value.payload = {"scenario": "control"} + value.control_prefix = "runs/unit/cases/owner/control/" + value.emit = Mock() + return value + + +@pytest.mark.parametrize("state,released", [(b"hold", False), (b"release", True)]) +def test_control_reads_explicit_state_and_closes_body(trace, state, released): + body = io.BytesIO(state) + with Stubber(trace.s3) as stub: + stub.add_response( + "get_object", + {"Body": body}, + {"Bucket": "test-bucket", "Key": "runs/unit/cases/owner/control/gate"}, + ) + assert trace.released("gate") is released + assert body.closed + trace.emit.assert_not_called() + + +@pytest.mark.parametrize("code,status", [("403", 403), ("NoSuchKey", 404)]) +def test_missing_or_forbidden_control_is_not_a_hold_or_release(trace, code, status): + with Stubber(trace.s3) as stub: + stub.add_client_error( + "get_object", service_error_code=code, http_status_code=status + ) + with pytest.raises(ClientError): + trace.gate("gate", effects=True) + phases = [call.args[0] for call in trace.emit.call_args_list] + assert "CONTROL_ERROR" in phases + assert not {"BLOCKED", "ALIVE", "EFFECT"} & set(phases) + + +def test_invalid_control_content_cannot_release_work(trace): + with Stubber(trace.s3) as stub: + stub.add_response("get_object", {"Body": io.BytesIO(b"unexpected")}) + with pytest.raises(ValueError, match="Invalid control state"): + trace.released("gate") + assert trace.emit.call_args.args[0] == "CONTROL_ERROR" + + +@pytest.mark.parametrize("elapsed,escaped", [(90, False), (180, True)]) +def test_fault_gate_outlives_invocation_deadline_but_remains_bounded( + trace, monkeypatch, elapsed, escaped +): + trace.deadline = 60 + times = iter([0, elapsed]) + trace.released = Mock(side_effect=[False, False, True]) + monkeypatch.setattr( + fixture, + "time", + SimpleNamespace( + monotonic=lambda: next(times), + sleep=lambda _: None, + time=time.time, + time_ns=time.time_ns, + ), + ) + if escaped: + with pytest.raises(TimeoutError, match="emergency release"): + trace.gate("fault", effects=True) + else: + trace.gate("fault", effects=True) + phases = [call.args[0] for call in trace.emit.call_args_list] + assert ("ESCAPE" in phases) is escaped + assert ("EFFECT" in phases) is not escaped + + +def held_deadline_gate( + trace, monkeypatch, *, seconds_past_deadline, monotonic=lambda: 0 +): + """A held deadline-fixture gate polled at a fixed offset from the deadline.""" + trace.payload = {"scenario": "deadline"} + trace.deadline = 1_000.0 + monkeypatch.setattr( + fixture, + "time", + SimpleNamespace( + monotonic=monotonic, + sleep=lambda _: None, + time=lambda: trace.deadline + seconds_past_deadline, + time_ns=time.time_ns, + ), + ) + + +def test_deadline_fixture_cooperatively_exits_held_io_after_the_deadline( + trace, monkeypatch +): + # Lifecycle cases 3 and 4 assert cleanup across a real platform timeout. + # Without this exit the held step outlives the timeout until the 150 s + # escape, which reports a harness failure instead of SDK cleanup. The + # clock jumps past that escape after the first read, so a missing exit + # fails here on the escape's message rather than holding forever. + readings = iter([0]) + held_deadline_gate( + trace, + monkeypatch, + seconds_past_deadline=0.2, + monotonic=lambda: next(readings, 1_000), + ) + trace.released = Mock(return_value=False) + with pytest.raises(TimeoutError, match="crossed the runtime deadline"): + trace.gate("fault", effects=True) + phases = [call.args[0] for call in trace.emit.call_args_list] + assert phases == ["IO_INTERRUPTED", "IO_EXIT"] + + +def test_deadline_exit_waits_one_poll_interval_past_the_deadline(trace, monkeypatch): + # Exiting at the deadline itself could precede the platform's timeout + # record, and the shared validator requires timeout <= task exit. + held_deadline_gate(trace, monkeypatch, seconds_past_deadline=0.1) + trace.released = Mock(side_effect=[False, False, True]) + trace.gate("fault", effects=True) + phases = [call.args[0] for call in trace.emit.call_args_list] + assert "IO_INTERRUPTED" not in phases + assert phases[-1] == "IO_EXIT" + + +def test_preparation_gate_is_not_cancelled_by_the_deadline(trace, monkeypatch): + # Preparation holds the healthy cohort before the fault is admitted; only + # the fault itself may be cut short by the deadline. + held_deadline_gate(trace, monkeypatch, seconds_past_deadline=5) + trace.released = Mock(side_effect=[False, False, True]) + trace.gate("prepare", preparation=True) + phases = [call.args[0] for call in trace.emit.call_args_list] + assert "IO_INTERRUPTED" not in phases + + +def test_emitted_records_are_partitioned_by_case_and_request(trace): + trace.s3 = Mock() + trace.identity = {"run": "unit", "marker": "case", "request": "request"} + trace.sequence = 0 + trace.deadline = 10 + trace.lock = threading.Lock() + Trace.emit(trace, "BODY") + assert ( + trace.s3.put_object.call_args.kwargs["Key"] + == "runs/unit/events/case/request/000001.json" + ) diff --git a/lmi_tests/tests/unit/test_deploy.py b/lmi_tests/tests/unit/test_deploy.py new file mode 100644 index 000000000..e5f312df5 --- /dev/null +++ b/lmi_tests/tests/unit/test_deploy.py @@ -0,0 +1,224 @@ +from pathlib import Path +import json +import stat +import sys +import zipfile +from unittest.mock import Mock +import pytest +from lmi_tests import deploy + + +def test_failed_build_clears_prior_run_before_subprocess( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + artifacts = tmp_path / "lmi_tests/artifacts" + deploy.save(artifacts / "manifest.json", {"run": "previous", "owned": True}) + deploy.save(artifacts / "cleanup.json", {"run": "previous"}) + monkeypatch.setattr(deploy, "ROOT", tmp_path) + monkeypatch.setattr(deploy, "ARTIFACTS", artifacts) + monkeypatch.setattr( + deploy.subprocess, "run", Mock(side_effect=RuntimeError("build failed")) + ) + with pytest.raises(RuntimeError, match="build failed"): + deploy.build() + assert not (artifacts / "manifest.json").exists() + assert not (artifacts / "cleanup.json").exists() + + +def test_manual_cleanup_cannot_use_legacy_run_controls(monkeypatch): + manager = Mock() + monkeypatch.setattr(deploy, "manager", manager) + monkeypatch.setattr(sys, "argv", ["lmi_tests.deploy", "cleanup"]) + with pytest.raises(SystemExit) as error: + deploy.main() + assert error.value.code == 2 + manager.assert_not_called() + + +@pytest.mark.parametrize("command", ["build", "deploy"]) +def test_build_and_deploy_preserve_unresolved_journal(monkeypatch, tmp_path, command): + from aws_durable_execution_conformance_tests.lmi.errors import ProvisioningError + + journal = tmp_path / "deployment-update.json" + journal.write_text('{"run":"current"}') + manifest = tmp_path / "manifest.json" + manifest.write_text('{"run":"previous"}') + monkeypatch.setattr(deploy, "ARTIFACTS", tmp_path) + build_command = Mock() + monkeypatch.setattr(deploy.subprocess, "run", build_command) + + deploy_manager = Mock() + monkeypatch.setattr(deploy, "manager", deploy_manager) + monkeypatch.setattr(sys, "argv", ["lmi_tests.deploy", command]) + with pytest.raises(ProvisioningError, match="before rebuilding or deploying"): + deploy.main() + deploy_manager.assert_not_called() + + assert json.loads(journal.read_text()) == {"run": "current"} + assert json.loads(manifest.read_text()) == {"run": "previous"} + build_command.assert_not_called() + + +@pytest.mark.parametrize( + ("manifest_run", "functions", "pending_update", "map_status", "diagnostic"), + [ + ( + "previous", + {"c1": "test:c1", "c2": "test:c2"}, + True, + "exact", + "different collection run", + ), + ("current", {}, False, "exact", "no verified collection targets"), + ( + "current", + {"c1": "test:c1"}, + False, + "exact", + "no verified collection targets", + ), + ( + "current", + {"c1": "test:c1", "c2": "test:c2"}, + True, + "exact", + "no verified collection targets", + ), + ( + "current", + {"c1": "test:c1", "c2": "test:c2"}, + False, + "absent", + "no verified collection targets", + ), + ( + "current", + {"c1": "test:c1", "c2": "test:c2"}, + False, + "mismatch", + "no verified collection targets", + ), + ("current", {"c1": "test:c1", "c2": "test:c2"}, False, "exact", None), + ], +) +def test_collection_checks_active_run_before_constructing_cloud( + monkeypatch, + tmp_path, + manifest_run, + functions, + pending_update, + map_status, + diagnostic, +): + from aws_durable_execution_conformance_tests.lmi.errors import CollectionError + from lmi_tests import cloud + + manifest = {"run": manifest_run, "functions": functions} + (tmp_path / "manifest.json").write_text(json.dumps(manifest)) + if map_status != "absent": + name_map = { + key: {deploy.RUNTIME.handler: arn} for key, arn in functions.items() + } + if map_status == "mismatch": + name_map["c2"] = {deploy.RUNTIME.handler: "test:stale"} + (tmp_path / "function-name-map.json").write_text(json.dumps(name_map)) + if pending_update: + (tmp_path / "deployment-update.json").write_text('{"run":"current"}') + monkeypatch.setattr(deploy, "ARTIFACTS", tmp_path) + monkeypatch.setattr(sys, "argv", ["lmi_tests.deploy", "collect"]) + monkeypatch.setenv("LMI_SHARED_RUN_ID", "current") + transport = Mock() + monkeypatch.setattr(cloud, "Cloud", transport) + + if diagnostic: + with pytest.raises(CollectionError, match=diagnostic): + deploy.main() + transport.assert_not_called() + else: + deploy.main() + transport.assert_called_once_with(manifest) + transport.return_value.collect.assert_called_once_with() + + +@pytest.mark.parametrize( + "arguments", + [[], ["--run-id", "UPPER"], ["--run-id", "valid", "--stack-name", ".."]], +) +def test_invalid_cli_deploy_does_not_touch_previous_manifest( + monkeypatch, tmp_path, arguments +): + from aws_durable_execution_conformance_tests.lmi.errors import ProvisioningError + + manifest = tmp_path / "manifest.json" + manifest.write_text('{"run":"previous"}') + monkeypatch.setattr(deploy, "ARTIFACTS", tmp_path) + manager = Mock() + monkeypatch.setattr(deploy, "manager", manager) + monkeypatch.setattr(sys, "argv", ["lmi_tests.deploy", "deploy", *arguments]) + with pytest.raises(ProvisioningError): + deploy.main() + assert manifest.read_text() == '{"run":"previous"}' + manager.assert_not_called() + + +def test_finished_bundle_has_lambda_file_modes(monkeypatch, tmp_path): + fixture_files = tmp_path / "lmi_tests" + fixture_files.mkdir() + for name in ("__init__.py", "fixture.py", "shared_observations.py"): + (fixture_files / name).write_text("# fixture") + artifacts = fixture_files / "artifacts" + build = fixture_files / "build" + + def build_or_install(command, **options): + if command[0] == "hatch": + (build / "aws_durable_execution_sdk_python-example.whl").write_bytes( + b"wheel" + ) + else: + target = build / "package" + target.mkdir() + program = target / "helper" + program.write_text("#!/bin/sh") + program.chmod(0o711) + (build / "dependencies.json").write_text('{"install":[]}') + + monkeypatch.setattr(deploy, "ROOT", tmp_path) + monkeypatch.setattr(deploy, "ARTIFACTS", artifacts) + monkeypatch.setattr(deploy.subprocess, "run", build_or_install) + monkeypatch.setattr(deploy.subprocess, "check_output", Mock(return_value="sha")) + + deploy.build() + + with zipfile.ZipFile(build / "function.zip") as archive: + assert ( + stat.S_IMODE(archive.getinfo("lmi_tests/fixture.py").external_attr >> 16) + == 0o644 + ) + assert stat.S_IMODE(archive.getinfo("helper").external_attr >> 16) == 0o755 + + +def test_direct_deploy_requires_pinned_install_before_manager(monkeypatch, tmp_path): + monkeypatch.setattr(deploy, "ARTIFACTS", tmp_path) + checkout = tmp_path / "conformance" + monkeypatch.setattr( + sys, + "argv", + [ + "lmi_tests.deploy", + "deploy", + "--run-id", + "test-1", + "--checkout", + str(checkout), + ], + ) + verify = Mock(side_effect=ValueError("pin mismatch")) + manager = Mock() + monkeypatch.setattr(deploy, "verify_install", verify) + monkeypatch.setattr(deploy, "manager", manager) + + with pytest.raises(ValueError, match="pin mismatch"): + deploy.main() + + verify.assert_called_once_with(checkout) + manager.assert_not_called() diff --git a/lmi_tests/tests/unit/test_fixture.py b/lmi_tests/tests/unit/test_fixture.py new file mode 100644 index 000000000..dc4f6e6a3 --- /dev/null +++ b/lmi_tests/tests/unit/test_fixture.py @@ -0,0 +1,512 @@ +from contextlib import nullcontext +from dataclasses import replace +import json +import subprocess +import sys +from unittest.mock import Mock + +import pytest + +from aws_durable_execution_sdk_python import StepError, durable_execution +from aws_durable_execution_sdk_python.exceptions import GetExecutionStateError +from aws_durable_execution_sdk_python.lambda_service import ( + OperationAction, + OperationType, + OperationUpdate, + StateOutput, +) +from aws_durable_execution_sdk_python_testing import DurableFunctionTestRunner +from lmi_tests.fixture import ObservedClient, workflow +from lmi_tests import fixture +from lmi_tests.tests.unit.test_shared_observations import ( + install_ledger, + shared_payload, +) +from lmi_tests.tests.unit.support import ( + MemoryClient, + invocation, + lambda_context, +) + + +class LocalTrace: + def __init__(self): + self.events = [] + self.observer = Mock() + self.observer.root_scope.side_effect = nullcontext + self.call_sequence = 0 + self.closed = False + self.payload = {"scenario": "checkpoint", "marker": "local"} + + def publishing(self): + return nullcontext(self.closed) + + def emit(self, phase, **fields): + self.events.append({"phase": phase, **fields}) + + def observe(self, kind, **fields): + pass + + def next_call_id(self, kind): + self.call_sequence += 1 + return f"{kind}:{self.call_sequence}" + + def body(self, name, value, step): + self.emit("BODY", operation=name, value=value, attempt=step.attempt) + return value + + def gate(self, name): + self.emit("GATE", name=name) + + +def test_environment_marker_is_shared_across_processes(tmp_path): + path = str(tmp_path / "marker") + workers = [ + subprocess.Popen( + [ + sys.executable, + "-c", + "import sys; from lmi_tests.fixture import environment_id; print(environment_id(sys.argv[1]))", + path, + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + for _ in range(4) + ] + try: + values = [] + for worker in workers: + stdout, stderr = worker.communicate(timeout=15) + assert worker.returncode == 0, stderr + values.append(stdout.strip()) + finally: + for worker in workers: + if worker.poll() is None: + worker.kill() + worker.wait(timeout=5) + assert len(set(values)) == 1 + assert len(values[0]) == 32 + + +def test_checkpoint_proxy_preserves_real_result_and_errors(): + trace, backend = LocalTrace(), Mock() + observed = ObservedClient(backend, trace) + update = OperationUpdate( + "id", + OperationType.STEP, + OperationAction.SUCCEED, + name="checkpoint-loser", + payload="result", + ) + result = observed.checkpoint( + updates=[update], checkpoint_token="secret", durable_execution_arn="arn" + ) + assert result is backend.checkpoint.return_value + backend.checkpoint.assert_called_once_with( + updates=[update], checkpoint_token="secret", durable_execution_arn="arn" + ) + assert [e["phase"] for e in trace.events] == [ + "CHECKPOINT_CALL", + "CHECKPOINT_ACK", + "CHECKPOINT_EXIT", + ] + assert "secret" not in json.dumps(trace.events) + trace.events.clear() + backend.checkpoint.side_effect = RuntimeError("network failure") + with pytest.raises(RuntimeError, match="network failure"): + observed.checkpoint(updates=[update]) + assert [e["phase"] for e in trace.events] == [ + "CHECKPOINT_CALL", + "CHECKPOINT_ERROR", + "CHECKPOINT_EXIT", + ] + + +@pytest.fixture +def producer(monkeypatch): + ledger = install_ledger(monkeypatch) + return fixture.Trace(shared_payload(), lambda_context(30_000), "execution"), ledger + + +def fail_transport_writes(ledger, monkeypatch, *failing): + put = ledger.put_object + + def store(**kwargs): + record = json.loads(kwargs["Body"]) + phase = record.get("observation", {}).get("kind", record["phase"]) + if phase in failing: + raise OSError("evidence store unavailable") + return put(**kwargs) + + monkeypatch.setattr(ledger, "put_object", store) + + +def checkpoint_update(): + return OperationUpdate( + "id", OperationType.STEP, OperationAction.SUCCEED, name="step" + ) + + +@pytest.mark.parametrize( + "failing", + [ + ("CHECKPOINT_CALL", "checkpoint_call"), + ("CHECKPOINT_ACK", "checkpoint_ack"), + ("CHECKPOINT_EXIT", "checkpoint_exit"), + ], +) +def test_checkpoint_evidence_failure_cannot_change_a_successful_checkpoint( + producer, monkeypatch, failing +): + # The SDK must consume the backend's checkpoint token. A failed publication + # is a collection error, never an artificial checkpoint failure. + trace, ledger = producer + backend = Mock() + fail_transport_writes(ledger, monkeypatch, *failing) + result = ObservedClient(backend, trace).checkpoint(updates=[checkpoint_update()]) + assert result is backend.checkpoint.return_value + backend.checkpoint.assert_called_once() + trace.finish_wrapper() + assert trace.source_failed + assert not {"CHECKPOINT_ERROR", "SEALED"} & { + row["phase"] for row in ledger.records() + } + + +def test_checkpoint_evidence_failure_cannot_replace_the_backend_error( + producer, monkeypatch +): + trace, ledger = producer + backend = Mock() + fail_transport_writes(ledger, monkeypatch, "CHECKPOINT_ERROR", "CHECKPOINT_EXIT") + backend.checkpoint.side_effect = RuntimeError("network failure") + with pytest.raises(RuntimeError, match="network failure"): + ObservedClient(backend, trace).checkpoint(updates=[checkpoint_update()]) + + +@pytest.mark.parametrize("failing", ["POLL_CALL", "POLL_EXIT"]) +def test_state_poll_evidence_failure_cannot_change_the_backend_outcome( + producer, monkeypatch, failing +): + trace, ledger = producer + backend = Mock() + fail_transport_writes(ledger, monkeypatch, failing) + observed = ObservedClient(backend, trace) + assert ( + observed.get_execution_state(arn="arn") + is backend.get_execution_state.return_value + ) + backend.get_execution_state.side_effect = RuntimeError("state unavailable") + with pytest.raises(RuntimeError, match="state unavailable"): + observed.get_execution_state(arn="arn") + + +def test_replay_fixture_uses_real_public_apis_and_preserves_outcomes(): + trace = LocalTrace() + handler = durable_execution(lambda e, c: workflow(e, c, trace)) + with DurableFunctionTestRunner(handler, poll_interval=0.01) as runner: + arn = runner.run_async(input={"marker": "local", "scenario": "replay"}) + callback = runner.wait_for_callback(arn, name="completion", timeout=10) + runner.send_callback_success(callback, result=b"local") + result = runner.wait_for_result(arn, timeout=10) + assert result.status.value == "SUCCEEDED" + assert json.loads(result.result) == "local" + bodies = [e for e in trace.events if e["phase"] == "BODY"] + assert sum(e["operation"] == "success" for e in bodies) == 1 + assert sum(e["operation"] == "failure" for e in bodies) == 1 + assert [e["attempt"] for e in bodies if e["operation"] == "retry"] == [1, 2] + failures = [e for e in trace.events if e["phase"] == "STORED_FAILURE"] + assert len(failures) >= 2 + assert all(e["message"] == "expected:local" for e in failures) + + +def test_cloud_entrypoint_unwraps_runtime_event_and_observes_real_wrapper(monkeypatch): + ledger = install_ledger(monkeypatch) + monkeypatch.setattr( + fixture.LambdaClient, "initialize_client", lambda: MemoryClient() + ) + event = invocation().to_json_dict() + event["InitialExecutionState"]["Operations"][0]["ExecutionDetails"][ + "InputPayload" + ] = json.dumps(shared_payload()) + result = fixture.handler(event, lambda_context(30_000)) + assert result["Status"] == "SUCCEEDED" + assert json.loads(result["Result"]) == "marker" + phases = [row["phase"] for row in ledger.records()] + assert phases[0] == "WRAPPER_ENTER" and phases[-1] == "SEALED" + assert phases.index("USER_EXIT") < phases.index("WRAPPER_RETURN") + assert "CHECKPOINT_ACK" in phases + + +@pytest.mark.parametrize( + ("step_result", "diagnostic"), + [ + ("unexpected value", "returned as a value"), + (StepError("wrong", "ValueError"), "unexpected details"), + (StepError("expected:marker", "TypeError"), "unexpected details"), + ], +) +def test_replay_rejects_wrong_delivery_of_stored_failure(step_result, diagnostic): + context = Mock() + context.step.side_effect = ["marker", step_result] + trace = LocalTrace() + with pytest.raises(AssertionError, match=diagnostic): + fixture.run_workflow({"marker": "marker", "scenario": "replay"}, context, trace) + + +def test_fixture_preserves_sdk_pagination_and_early_poll_observations(monkeypatch): + ledger = install_ledger(monkeypatch) + event = invocation() + root = event.initial_execution_state.operations[0] + assert root.execution_details is not None + root = replace( + root, + execution_details=replace( + root.execution_details, input_payload=json.dumps(shared_payload()) + ), + ) + client = event.service_client + client.get_execution_state = Mock(return_value=StateOutput(operations=[root])) + event = replace( + event, + initial_execution_state=replace( + event.initial_execution_state, operations=[], next_marker="page-two" + ), + ) + result = fixture.handler(event, lambda_context(30_000)) + assert result["Status"] == "SUCCEEDED" + assert json.loads(result["Result"]) == "marker" + client.get_execution_state.assert_called_once_with( + durable_execution_arn=event.durable_execution_arn, + checkpoint_token=event.checkpoint_token, + next_marker="page-two", + ) + records = [row["observation"] for row in ledger.observations()] + polls = [ + record for record in records if record["kind"] in {"poll_call", "poll_exit"} + ] + assert [record["kind"] for record in polls] == ["poll_call", "poll_exit"] + assert polls[0]["callId"] == polls[1]["callId"] + assert polls[0]["atMs"] <= polls[1]["atMs"] + assert ledger.records()[-1]["phase"] == "SEALED" + + +@pytest.mark.parametrize("raises", [False, True]) +@pytest.mark.parametrize("broken_stdout", [None, BrokenPipeError, ValueError]) +def test_wrapper_publication_does_not_replace_sdk_result_or_error( + monkeypatch, raises, broken_stdout +): + ledger = install_ledger(monkeypatch) + event = invocation() + root = event.initial_execution_state.operations[0] + assert root.execution_details is not None + root = replace( + root, + execution_details=replace( + root.execution_details, input_payload=json.dumps(shared_payload()) + ), + ) + event = replace( + event, + initial_execution_state=replace( + event.initial_execution_state, operations=[root] + ), + ) + original_error = ValueError("SDK raised") + returned = {"Status": "SUCCEEDED", "Result": '"marker"'} + sdk = Mock(side_effect=original_error) if raises else Mock(return_value=returned) + monkeypatch.setattr(fixture, "durable_execution", Mock(return_value=sdk)) + put = ledger.put_object + + def write(**kwargs): + record = json.loads(kwargs["Body"]) + if record["phase"] == ("WRAPPER_RAISE" if raises else "WRAPPER_RETURN"): + raise OSError("unavailable completion sink") + return put(**kwargs) + + if broken_stdout: + + def broken_print(*args, **kwargs): + raise broken_stdout("logging stream closed") + + monkeypatch.setattr(fixture, "print", broken_print, raising=False) + + monkeypatch.setattr(ledger, "put_object", write) + if raises: + with pytest.raises(ValueError) as error: + fixture.handler(event, lambda_context(30_000)) + assert error.value is original_error + else: + assert fixture.handler(event, lambda_context(30_000)) is returned + assert all( + row["phase"] not in {"WRAPPER_RAISE", "WRAPPER_RETURN", "SEALED"} + for row in ledger.records() + ) + + +@pytest.mark.parametrize("known_payload", [False, True]) +def test_fixture_keeps_sdk_classification_of_failed_initial_fetch( + monkeypatch, known_payload +): + ledger = install_ledger(monkeypatch) + event = invocation() + root = event.initial_execution_state.operations[0] + assert root.execution_details is not None + payload = shared_payload() + payload["sharedScenario"] = "normal-return" + root = replace( + root, + execution_details=replace( + root.execution_details, input_payload=json.dumps(payload) + ), + ) + client = event.service_client + service_error = GetExecutionStateError("page access denied") + monkeypatch.setattr(service_error, "is_retryable", lambda: False) + client.get_execution_state = Mock(side_effect=service_error) + event = replace( + event, + initial_execution_state=replace( + event.initial_execution_state, + operations=[root] if known_payload else [], + next_marker="page-two", + ), + ) + result = fixture.handler(event, lambda_context(30_000)) + assert result["Status"] == "FAILED" + assert result["Error"]["ErrorMessage"] == "page access denied" + client.get_execution_state.assert_called_once() + kinds = [row["observation"]["kind"] for row in ledger.observations()] + assert "admission_probe" not in kinds + if known_payload: + assert {"poll_call", "poll_exit", "wrapper_return", "observation_error"} <= set( + kinds + ) + else: + assert not ledger.records() + + +def test_admission_worker_start_failure_does_not_replace_sdk_return(monkeypatch): + ledger = install_ledger(monkeypatch) + event = invocation() + root = event.initial_execution_state.operations[0] + assert root.execution_details is not None + payload = shared_payload() + payload["sharedScenario"] = "normal-return" + root = replace( + root, + execution_details=replace( + root.execution_details, input_payload=json.dumps(payload) + ), + ) + event = replace( + event, + initial_execution_state=replace( + event.initial_execution_state, operations=[root] + ), + ) + monkeypatch.setattr( + fixture.Trace, + "start_worker", + Mock(side_effect=OSError("worker startup unavailable")), + ) + result = fixture.handler(event, lambda_context(30_000)) + assert result["Status"] == "SUCCEEDED" + assert json.loads(result["Result"]) == "marker" + assert not any(row["phase"] == "SEALED" for row in ledger.records()) + + +@pytest.mark.parametrize( + ("retry", "mapped", "parallel", "diagnostic"), + [ + (None, [1, 2, 3], ["marker", "marker"], "Retried step"), + ("marker", [1, 3], ["marker", "marker"], "Replayed map"), + ("marker", [True, 2, 3], ["marker", "marker"], "Replayed map"), + ( + "marker", + [1, 2, 3], + [["left", "marker"], ["left", "marker"]], + "Replayed parallel", + ), + ], +) +def test_replay_rejects_incomplete_actual_values(retry, mapped, parallel, diagnostic): + context = Mock() + context.step.side_effect = [ + "marker", + StepError("expected:marker", "ValueError"), + retry, + ] + context.run_in_child_context.return_value.get_results.return_value = mapped + context.parallel.return_value.get_results.return_value = parallel + with pytest.raises(AssertionError, match=diagnostic): + fixture.run_workflow( + {"marker": "marker", "scenario": "replay"}, context, LocalTrace() + ) + + +def test_body_publication_failure_does_not_fail_real_sdk_step(monkeypatch): + ledger = install_ledger(monkeypatch) + event = invocation() + root = event.initial_execution_state.operations[0] + assert root.execution_details is not None + root = replace( + root, + execution_details=replace( + root.execution_details, input_payload=json.dumps(shared_payload()) + ), + ) + event = replace( + event, + initial_execution_state=replace( + event.initial_execution_state, operations=[root] + ), + ) + put = ledger.put_object + + def write(**kwargs): + if json.loads(kwargs["Body"])["phase"] == "BODY": + raise OSError("body ledger unavailable") + return put(**kwargs) + + monkeypatch.setattr(ledger, "put_object", write) + result = fixture.handler(event, lambda_context(30_000)) + assert result["Status"] == "SUCCEEDED" + assert json.loads(result["Result"]) == "marker" + assert not any(row["phase"] == "SEALED" for row in ledger.records()) + + +def test_optimized_fixture_still_waits_on_callback(): + script = """ +from unittest.mock import Mock +from aws_durable_execution_sdk_python import StepError +from lmi_tests import fixture +from lmi_tests.tests.unit.test_fixture import LocalTrace + +context = Mock() +context.step.side_effect = ["marker", StepError("expected:marker", "ValueError"), "marker"] +context.run_in_child_context.return_value.get_results.return_value = [1, 2, 3] +context.parallel.return_value.get_results.return_value = [["left", "marker"], ["right", "marker"]] +context.create_callback.return_value.result.return_value = "marker" +fixture.run_workflow({"marker": "marker", "scenario": "replay"}, context, LocalTrace()) +context.create_callback.return_value.result.assert_called_once_with() +context.step.side_effect = ["marker", StepError("expected:marker", "ValueError"), "marker"] +context.create_callback.return_value.result.return_value = "different" +try: + fixture.run_workflow({"marker": "marker", "scenario": "replay"}, context, LocalTrace()) +except AssertionError as error: + if "callback returned the wrong value" not in str(error): + raise +else: + raise RuntimeError("wrong callback result was accepted") +""" + completed = subprocess.run( + [sys.executable, "-O", "-c", script], + capture_output=True, + text=True, + timeout=15, + check=False, + ) + assert completed.returncode == 0, completed.stdout + completed.stderr diff --git a/lmi_tests/tests/unit/test_shared_manifest.py b/lmi_tests/tests/unit/test_shared_manifest.py new file mode 100644 index 000000000..a9b562670 --- /dev/null +++ b/lmi_tests/tests/unit/test_shared_manifest.py @@ -0,0 +1,133 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Plans pin the shared matrix and immutable SDK/deployment inputs.""" + +import json +from unittest.mock import patch + +import pytest + +from aws_durable_execution_conformance_tests.lmi.app import load_manifest +from lmi_tests.shared import make_manifest, verify_checkout +from lmi_tests.shared_contract import CONFORMANCE_REVISION, configuration_identity + + +def deployment(): + return { + "run": "run-1", + "stack": "stack", + "region": "us-west-2", + "account": "123456789012", + "runtime": "python3.14", + "role": "arn:role", + "bucket": "private", + "commit": "sdk-commit", + "provider": "arn:aws:lambda:us-west-2:123456789012:capacity-provider:provider", + "codeSha256": "bundle-sha", + "invocationTimeout": 60, + "executionTimeout": 240, + "driverTimeout": 120, + "concurrencies": {"c1": 1, "c2": 2}, + "functions": { + "c1": "arn:function:c1:$LATEST.PUBLISHED", + "c2": "arn:function:c2:$LATEST.PUBLISHED", + }, + "wheels": { + "aws_durable_execution_sdk_python-3.0.0.whl": "core-sha", + }, + } + + +def test_generated_manifest_covers_the_seven_shared_scenarios(tmp_path): + from aws_durable_execution_conformance_tests.lmi.app import coverage_inventory + + source = deployment() + plan = make_manifest(source, "standard", tmp_path) + assert len(plan["scenarios"]) == 7 + assert "lease" not in plan["sdk"] + assert "sharedLease" not in plan["sdk"]["deployment"] + assert {c["requirement_id"] for c in plan["scenarios"]} == { + f"lmi-lifecycle-{i}" for i in range(1, 8) + } + assert {c["profile_id"] for c in plan["scenarios"]} == {"c1", "c2"} + assert all( + "otel_view" not in c and "export_mode" not in c for c in plan["scenarios"] + ) + assert plan["sdk"]["deployment"]["conformanceRevision"] == CONFORMANCE_REVISION + path = tmp_path / "plan.json" + path.write_text(json.dumps(plan)) + assert load_manifest(path) == plan + assert coverage_inventory(plan)["missing"] == [] + assert ( + next(c for c in plan["scenarios"] if c["scenario"] == "normal-failure")[ + "requirement_id" + ] + == "lmi-lifecycle-7" + ) + plan["sdk"]["deployment"]["commit"] = "mutated" + assert source["commit"] == "sdk-commit" + + +def test_no_unidentified_artifact_can_be_planned(tmp_path): + source = deployment() + source["wheels"] = {} + with pytest.raises(ValueError, match="wheel"): + make_manifest(source, "standard", tmp_path) + + +def test_configuration_identity_changes_with_the_tested_settings(): + source = deployment() + original = configuration_identity(source, "c1") + assert original != configuration_identity(source, "c2") + source["codeSha256"] = "other-bundle" + assert original != configuration_identity(source, "c1") + + +def test_only_the_exact_clean_shared_revision_is_accepted(tmp_path): + with patch("lmi_tests.shared.subprocess.check_output", side_effect=["wrong\n"]): + with pytest.raises(ValueError, match="pinned"): + verify_checkout(tmp_path) + with patch( + "lmi_tests.shared.subprocess.check_output", + side_effect=[CONFORMANCE_REVISION + "\n", " M packages/validator.py\n"], + ): + with pytest.raises(ValueError, match="local changes"): + verify_checkout(tmp_path) + with patch( + "lmi_tests.shared.subprocess.check_output", + side_effect=[CONFORMANCE_REVISION + "\n", ""], + ): + verify_checkout(tmp_path) + + +def test_shared_run_writes_reports_without_an_external_lock(monkeypatch, tmp_path): + from unittest.mock import Mock + from lmi_tests import shared + from aws_durable_execution_conformance_tests.lmi import app + + async def results(plan, adapter_name, *, audit_dir): + assert adapter_name == "lmi_tests.shared_adapter:create_adapter" + assert "lease" not in plan["sdk"] + return [ + { + "case_id": case["case_id"], + "requirement_id": case["requirement_id"], + "profile_id": case["profile_id"], + "status": "PASSED", + "errors": [], + } + for case in plan["scenarios"] + ] + + client = Mock( + side_effect=AssertionError("Run orchestration must not acquire an AWS lock") + ) + from aws_durable_execution_conformance_tests.lmi import runner + + monkeypatch.setattr(runner, "client", client) + monkeypatch.setattr(app, "live_results", results) + output = tmp_path / "run" + assert shared.run(deployment(), output) == 0 + report = json.loads((output / "standard/report.json").read_text()) + assert report["summary"]["passed"] == 7 + client.assert_not_called() diff --git a/lmi_tests/tests/unit/test_shared_observations.py b/lmi_tests/tests/unit/test_shared_observations.py new file mode 100644 index 000000000..2e03e3944 --- /dev/null +++ b/lmi_tests/tests/unit/test_shared_observations.py @@ -0,0 +1,984 @@ +"""Public hook records preserve actual IDs and never fill missing observations.""" + +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from datetime import UTC, datetime +from dataclasses import asdict +from inspect import signature +from itertools import count +import io +import json +import threading +import time +from typing import Any +from unittest.mock import Mock +from types import SimpleNamespace + +from botocore.exceptions import ClientError, ReadTimeoutError +import pytest + +from aws_durable_execution_sdk_python.lambda_service import ( + ErrorObject, + OperationStatus, + StateOutput, +) +from aws_durable_execution_sdk_python.plugin import ( + InvocationStartInfo, + OperationInfo, + OperationType, + UserFunctionEndInfo, + UserFunctionStartInfo, +) +from lmi_tests import fixture +from aws_durable_execution_sdk_python_testing import invoker as local_invoker +from lmi_tests.shared_observations import ( + LifecycleObservations, + OperationObservation, +) +from lmi_tests.tests.unit.support import invocation, lambda_context + + +class MemoryLedger: + """Replace only evidence/control storage; the SDK local service stays real.""" + + def __init__(self) -> None: + self.objects: dict[str, bytes] = {} + self.lock = threading.Lock() + + def put_object(self, *, Bucket, Key, Body, **_kwargs): + with self.lock: + self.objects[Key] = Body + return {} + + def get_object(self, *, Bucket, Key): + with self.lock: + return {"Body": io.BytesIO(self.objects[Key])} + + def records(self) -> list[dict[str, Any]]: + with self.lock: + records = [ + json.loads(body) + for key, body in self.objects.items() + if "/events/" in key + ] + return sorted( + records, key=lambda record: (record["request"], record["sequence"]) + ) + + def observations(self) -> list[dict[str, Any]]: + return [record for record in self.records() if record["phase"] == "CONFORMANCE"] + + def wait_for(self, kind: str, timeout: float = 10) -> dict[str, Any]: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + found = [ + record + for record in self.observations() + if record["observation"]["kind"] == kind + ] + if found: + return found[-1] + time.sleep(0.01) + raise AssertionError(f"No actual {kind} observation") + + +class MemorySink: + def __init__(self) -> None: + self.records: list[dict[str, Any]] = [] + self.lock = threading.Lock() + + def observe(self, kind: str, **fields: Any) -> dict[str, Any]: + value = {"kind": kind, **fields} + with self.lock: + self.records.append(value) + return value + + +def shared_payload(scenario: str = "success") -> dict[str, Any]: + from aws_durable_execution_conformance_tests.lmi.artifacts import case_key + + return { + "runId": "unit", + "caseId": "case", + "role": "victim", + "coverageProfile": "standard", + "sharedScenario": scenario, + "scenario": scenario, + "marker": "marker", + "controlPrefix": f"runs/unit/cases/{case_key('case')}/control/", + "behaviorBudgets": {"observationGraceMs": 1}, + } + + +def install_ledger(monkeypatch) -> MemoryLedger: + ledger = MemoryLedger() + monkeypatch.setenv("LMI_RUN_ID", "unit") + monkeypatch.setenv("LMI_COMMIT", "tested-commit") + monkeypatch.setenv("LMI_BUCKET", "private-evidence") + monkeypatch.delenv("DURABLE_EXECUTION_PLUGINS", raising=False) + monkeypatch.setattr(fixture.boto3, "client", lambda *_args, **_kwargs: ledger) + monkeypatch.setattr(fixture, "environment_id", lambda: "local-environment") + install_distinct_local_request_ids(monkeypatch) + return ledger + + +def install_distinct_local_request_ids(monkeypatch) -> None: + original_context = local_invoker.create_test_lambda_context + requests = count(1) + + def distinct_local_context(**kwargs): + # The stock local service reuses one mock request ID. Supply its runtime + # context before invoking the real fixture, never alter captured evidence. + context = original_context(**kwargs) + return type(context)( + **{**asdict(context), "aws_request_id": f"local-request-{next(requests)}"} + ) + + monkeypatch.setattr( + local_invoker, "create_test_lambda_context", distinct_local_context + ) + + +@pytest.fixture +def producer(monkeypatch): + ledger = install_ledger(monkeypatch) + trace = fixture.Trace(shared_payload(), lambda_context(30_000), "execution") + return trace, ledger + + +def test_seal_counts_successful_observations_in_publication_order(producer): + trace, ledger = producer + trace.observe("first", atMs=20) + trace.observe("second", atMs=10) + trace.finish_wrapper() + rows = ledger.records() + assert [row["phase"] for row in rows] == ["CONFORMANCE", "CONFORMANCE", "SEALED"] + assert [row["observation"]["captureSequence"] for row in rows[:-1]] == [1, 2] + assert [row["observation"]["atMs"] for row in rows[:-1]] == [20, 10] + assert rows[-1]["throughCapture"] == 2 + + +def check_seal_with_installed_consumer(rows, *, valid): + from aws_durable_execution_conformance_tests.lmi import source_evidence + + validator = getattr(source_evidence, "ledger_seal_status", None) + if validator is None: + # The published workflow still uses a consumer without seal support. + return + launch = { + "marker": rows[0]["marker"], + "arn": rows[0]["execution"], + "native_requests": [rows[0]["request"]], + } + if "launches" in signature(validator).parameters: + known, missing, errors = validator(rows, {}, [launch], set()) + else: + known, missing, errors = validator(rows, {}) + assert known == {rows[0]["request"]} + assert not missing + assert bool(errors) is not valid + + +@pytest.mark.parametrize("closed_stdout", [False, True]) +def test_post_seal_poll_reaches_backend_and_invalidates_last_record( + producer, monkeypatch, closed_stdout +): + trace, ledger = producer + trace.emit("WRAPPER_ENTER") + trace.finish_wrapper() + if closed_stdout: + monkeypatch.setattr( + fixture, + "print", + Mock(side_effect=ValueError("closed stdout")), + raising=False, + ) + output = StateOutput() + backend = Mock() + + def poll(**kwargs): + assert [row["phase"] for row in ledger.records()][-2:] == [ + "SEALED", + "POLL_CALL", + ] + return output + + backend.get_execution_state.side_effect = poll + assert ( + fixture.ObservedClient(backend, trace).get_execution_state(next_marker="late") + is output + ) + rows = ledger.records() + assert [row["phase"] for row in rows].count("SEALED") == 1 + assert [row["phase"] for row in rows].count("POLL_CALL") == 1 + assert rows[-1]["observation"]["kind"] == "poll_exit" + check_seal_with_installed_consumer(rows, valid=False) + assert rows[-1]["sequence"] > next( + row["sequence"] for row in rows if row["phase"] == "SEALED" + ) + + +def test_post_seal_checkpoint_reaches_backend_and_is_written_once(producer): + trace, ledger = producer + trace.emit("WRAPPER_ENTER") + trace.finish_wrapper() + backend = Mock() + + def checkpoint(**kwargs): + assert ledger.records()[-1]["phase"] == "CHECKPOINT_CALL" + return "original result" + + backend.checkpoint.side_effect = checkpoint + assert ( + fixture.ObservedClient(backend, trace).checkpoint(updates=[]) + == "original result" + ) + rows = ledger.records() + assert [row["phase"] for row in rows].count("CHECKPOINT_CALL") == 1 + assert rows[-1]["observation"]["kind"] == "checkpoint_exit" + check_seal_with_installed_consumer(rows, valid=False) + + +@pytest.mark.parametrize("method", ["poll", "checkpoint"]) +def test_running_sdk_call_defers_seal_until_exit_record(producer, method): + trace, ledger = producer + trace.emit("WRAPPER_ENTER") + entered = threading.Event() + release = threading.Event() + output = object() + + def backend_call(**kwargs): + entered.set() + assert release.wait(timeout=2) + return output + + client = fixture.ObservedClient( + SimpleNamespace(get_execution_state=backend_call, checkpoint=backend_call), + trace, + ) + call = ( + client.get_execution_state + if method == "poll" + else lambda: client.checkpoint(updates=[]) + ) + with ThreadPoolExecutor(max_workers=1) as executor: + pending = executor.submit(call) + try: + assert entered.wait(timeout=2) + trace.finish_wrapper() + assert [row["phase"] for row in ledger.records()] == ["WRAPPER_ENTER"] + finally: + release.set() + assert pending.result(timeout=2) is output + rows = ledger.records() + assert [row["phase"] for row in rows].count("SEALED") == 1 + assert rows[-2]["observation"]["kind"] == method + "_exit" + assert rows[-1]["phase"] == "SEALED" + check_seal_with_installed_consumer(rows, valid=True) + + +def test_dispatch_timestamp_does_not_include_prior_publication(producer, monkeypatch): + trace, ledger = producer + calls = [] + clock = iter([2_000_000, 3_000_000]) + now = fixture.time.time_ns + + def timestamp(): + return next(clock, now()) + + def poll(**kwargs): + calls.append(len(ledger.records())) + return StateOutput() + + backend = Mock() + backend.get_execution_state.side_effect = poll + monkeypatch.setattr(fixture.time, "time_ns", timestamp) + # Record wall time deterministically at the actual transport boundaries. + client = fixture.ObservedClient(backend, trace) + client.get_execution_state() + assert calls == [0] + observations = [row["observation"] for row in ledger.observations()] + assert observations[0]["atMs"] == 2 + assert observations[1]["atMs"] >= observations[0]["atMs"] + + +def test_late_poll_during_total_publication_loss_remains_unproven( + producer, monkeypatch +): + trace, ledger = producer + trace.emit("WRAPPER_ENTER") + trace.finish_wrapper() + backend = Mock() + monkeypatch.setattr( + trace, "_commit_record", Mock(side_effect=OSError("storage outage")) + ) + assert ( + fixture.ObservedClient(backend, trace).get_execution_state() + is backend.get_execution_state.return_value + ) + backend.get_execution_state.assert_called_once() + # The real consumer still sees the previous seal if every write is lost. + rows = ledger.records() + assert [row["phase"] for row in rows] == ["WRAPPER_ENTER", "SEALED"] + check_seal_with_installed_consumer(rows, valid=True) + + +def test_seal_rechecks_failed_publication_after_waiting_for_writer( + producer, monkeypatch +): + trace, ledger = producer + writing = threading.Event() + ready_to_seal = threading.Event() + release_write = threading.Event() + seal_if_ready = trace._seal_if_ready + + def write(key, body): + writing.set() + assert release_write.wait(timeout=2) + raise OSError("in-flight write failed") + + def finish_write(): + assert trace.emit("LOST_RAW_EVENT") == {} + + def seal(): + ready_to_seal.set() + seal_if_ready() + + monkeypatch.setattr(trace, "_commit_record", write) + monkeypatch.setattr(trace, "_seal_if_ready", seal) + writer = threading.Thread(target=finish_write) + finisher = threading.Thread(target=trace.finish_wrapper) + writer.start() + try: + assert writing.wait(timeout=2) + finisher.start() + assert ready_to_seal.wait(timeout=2) + finally: + release_write.set() + writer.join(timeout=2) + finisher.join(timeout=2) + assert not finisher.is_alive() + assert trace.sequence == 1 + assert not ledger.records() + + +def test_seal_publication_failure_does_not_escape_wrapper(producer, monkeypatch): + trace, ledger = producer + monkeypatch.setattr( + trace, "_commit_record", Mock(side_effect=OSError("write failed")) + ) + trace.finish_wrapper() + assert not ledger.records() + trace._commit_record.assert_called_once() + + +def test_worker_failure_does_not_seal_incomplete_work(producer, monkeypatch): + trace, ledger = producer + monkeypatch.setattr(threading, "excepthook", lambda _: None) + + def fail(): + raise RuntimeError("worker interrupted") + + worker = trace.start_worker(fail, "test-worker") + worker.join(timeout=2) + trace.finish_wrapper() + assert not worker.is_alive() + assert not ledger.records() + + +def test_worker_start_failure_does_not_seal_unstarted_work(producer, monkeypatch): + trace, ledger = producer + monkeypatch.setattr( + threading.Thread, "start", Mock(side_effect=RuntimeError("thread unavailable")) + ) + with pytest.raises(RuntimeError, match="thread unavailable"): + trace.start_worker(lambda: None, "test-worker") + trace.finish_wrapper() + assert trace.active_workers == 0 + assert not ledger.records() + + +def test_release_racing_cleanup_cannot_establish_normal_preparation( + producer, monkeypatch +): + trace, ledger = producer + released = Mock(side_effect=[False, True, True]) + monkeypatch.setattr(trace, "released", released) + assert trace.gate("prepare", preparation=True) is None + assert ( + next( + row["observation"]["mode"] + for row in ledger.observations() + if row["observation"]["kind"] == "fault_released" + ) + == "emergency" + ) + assert [call.args[0] for call in released.call_args_list] == [ + "release-all", + "prepare", + "release-all", + ] + assert not any( + row["observation"]["kind"] == "barrier_arrived" for row in ledger.observations() + ) + + +def test_control_transport_timeout_is_observed_and_reraised(producer, monkeypatch): + trace, ledger = producer + timeout = ReadTimeoutError(endpoint_url="https://s3.example.test") + monkeypatch.setattr(ledger, "get_object", Mock(side_effect=timeout)) + with pytest.raises(ReadTimeoutError) as error: + trace.released("release-all") + assert error.value is timeout + assert [event["phase"] for event in ledger.records()] == [ + "CONTROL_ERROR", + "CONFORMANCE", + ] + assert ledger.observations()[0]["observation"]["kind"] == "control_error" + + +def test_control_publication_error_does_not_replace_timeout(producer, monkeypatch): + trace, ledger = producer + timeout = ReadTimeoutError(endpoint_url="https://s3.example.test") + monkeypatch.setattr(ledger, "get_object", Mock(side_effect=timeout)) + monkeypatch.setattr( + trace, "_commit_record", Mock(side_effect=OSError("source unavailable")) + ) + with pytest.raises(ReadTimeoutError) as error: + trace.released("release-all") + assert error.value is timeout + trace.finish_wrapper() + assert not ledger.records() + + +def test_warm_worker_start_failure_clears_registration(producer, monkeypatch): + trace, _ = producer + monkeypatch.setattr( + trace, "start_worker", Mock(side_effect=OSError("unable to start")) + ) + with pytest.raises(OSError, match="unable to start"): + fixture.start_warm_work(trace) + assert (trace.payload["runId"], trace.payload["caseId"]) not in fixture.WARM_WORK + + +def test_warm_worker_exit_publication_failure_still_clears_registration( + producer, monkeypatch +): + trace, ledger = producer + put = ledger.put_object + + def store(**kwargs): + record = json.loads(kwargs["Body"]) + if record.get("observation", {}).get("kind") == "task_exit": + raise OSError("storage outage") + return put(**kwargs) + + monkeypatch.setattr(ledger, "put_object", store) + monkeypatch.setattr(fixture, "admission_probes", Mock()) + fixture.start_warm_work(trace) + fixture.release_warm_work( + SimpleNamespace(payload=trace.payload, identity={"request": "warm"}) + ) + assert (trace.payload["runId"], trace.payload["caseId"]) not in fixture.WARM_WORK + trace.finish_wrapper() + assert trace.source_failed + assert not any(row["phase"] == "SEALED" for row in ledger.records()) + + +def test_warm_worker_reports_expired_reuse_wait(producer, monkeypatch): + trace, ledger = producer + ledger.objects[trace.control_prefix + "release-all"] = b"hold" + monkeypatch.setattr(fixture.time, "monotonic", Mock(side_effect=[0.0, 121.0])) + fixture.start_warm_work(trace) + worker = fixture.WARM_WORK[(trace.payload["runId"], trace.payload["caseId"])].worker + assert worker is not None + worker.join(timeout=2) + assert not worker.is_alive() + errors = [ + row["observation"] + for row in ledger.observations() + if row["observation"]["kind"] == "observation_error" + ] + assert [error["message"] for error in errors] == [ + "Original late work never observed warm reuse" + ] + + +@pytest.mark.parametrize("aborted", [False, True]) +def test_warm_owner_seals_after_completed_callback_or_abort( + producer, monkeypatch, aborted +): + trace, ledger = producer + prefix = trace.control_prefix + ledger.objects[prefix + "release-all"] = b"hold" + probes = Mock() + monkeypatch.setattr(fixture, "admission_probes", probes) + fixture.start_warm_work(trace) + trace.finish_wrapper() + key = (trace.payload["runId"], trace.payload["caseId"]) + worker = fixture.WARM_WORK[key].worker + assert worker is not None + assert not any(row["phase"] == "SEALED" for row in ledger.records()) + if aborted: + ledger.objects[prefix + "release-all"] = b"release" + else: + fixture.release_warm_work( + SimpleNamespace(payload=trace.payload, identity={"request": "warm"}) + ) + worker.join(timeout=2) + assert not worker.is_alive() + assert key not in fixture.WARM_WORK + assert ledger.records()[-1]["phase"] == "SEALED" + observations = [row["observation"] for row in ledger.observations()] + assert {row["kind"] for row in observations} == ( + {"task_start", "task_exit"} + if aborted + else {"task_start", "task_exit", "late_activity"} + ) + assert probes.call_count == (0 if aborted else 1) + + +def test_seal_waits_for_registered_work_after_wrapper_finish(producer): + trace, ledger = producer + resume = threading.Event() + + def work(): + assert resume.wait(timeout=2) + trace.observe("late_activity") + + worker = trace.start_worker(work, "test-worker") + try: + trace.finish_wrapper() + assert not ledger.records() + finally: + resume.set() + worker.join(timeout=2) + assert not worker.is_alive() + assert [event["phase"] for event in ledger.records()] == ["CONFORMANCE", "SEALED"] + + +@pytest.mark.parametrize("first_write_committed", [False, True]) +def test_lost_write_reuses_the_same_key_and_bytes( + producer, monkeypatch, first_write_committed +): + trace, ledger = producer + real_put, real_get = ledger.put_object, ledger.get_object + puts: list[dict[str, Any]] = [] + + def put(**kwargs): + assert kwargs["IfNoneMatch"] == "*" + puts.append(kwargs) + if len(puts) == 1: + if first_write_committed: + real_put(**kwargs) + raise ReadTimeoutError(endpoint_url="https://s3.example.test") + return real_put(**kwargs) + + def get(**kwargs): + if kwargs["Key"] not in ledger.objects: + raise ClientError({"Error": {"Code": "NoSuchKey"}}, "GetObject") + return real_get(**kwargs) + + monkeypatch.setattr(ledger, "put_object", put) + monkeypatch.setattr(ledger, "get_object", get) + trace.observe("event") + if first_write_committed: + assert len(puts) == 1 + else: + assert puts == [puts[0], puts[0]] + trace.finish_wrapper() + assert [event["phase"] for event in ledger.records()] == ["CONFORMANCE", "SEALED"] + + +def test_permanent_raw_publication_loss_spends_one_retry_budget(producer, monkeypatch): + trace, ledger = producer + + def put(**kwargs): + raise ReadTimeoutError(endpoint_url="https://s3.example.test") + + def get(**kwargs): + raise ClientError({"Error": {"Code": "NoSuchKey"}}, "GetObject") + + slow_put = Mock(side_effect=put) + slow_get = Mock(side_effect=get) + monkeypatch.setattr(ledger, "put_object", slow_put) + monkeypatch.setattr(ledger, "get_object", slow_get) + for _ in range(10): + assert trace.emit("LOST_RAW_EVENT") == {} + trace.finish_wrapper() + assert slow_put.call_count == slow_get.call_count == 2 + assert ledger.records() == [] + + +def test_recovered_storage_after_seal_still_invalidates_it(producer, monkeypatch): + trace, ledger = producer + trace.emit("WRAPPER_ENTER") + trace.finish_wrapper() + with monkeypatch.context() as failed: + failed.setattr( + ledger, "put_object", Mock(side_effect=OSError("temporary failure")) + ) + assert trace.emit("POLL_CALL") == {} + trace.emit("POLL_EXIT") + assert [row["phase"] for row in ledger.records()] == [ + "WRAPPER_ENTER", + "SEALED", + "POLL_EXIT", + ] + check_seal_with_installed_consumer(ledger.records(), valid=False) + + +def test_existing_sequence_with_different_bytes_is_never_replaced( + producer, monkeypatch +): + trace, ledger = producer + existing = b'{"phase": "OTHER_RECORD", "request": "unit", "sequence": 1}' + + def put(**kwargs): + ledger.objects.setdefault(kwargs["Key"], existing) + raise ClientError({"Error": {"Code": "PreconditionFailed"}}, "PutObject") + + monkeypatch.setattr(ledger, "put_object", put) + assert trace.emit("WRAPPER_RETURN") == {} + trace.finish_wrapper() + assert list(ledger.objects.values()) == [existing] + + +def user_info( + operation_id: str, + *, + parent_id: str | None = None, + name: str = "work", + kind: OperationType = OperationType.STEP, +) -> UserFunctionStartInfo: + return UserFunctionStartInfo( + operation_id=operation_id, + operation_type=kind, + sub_type=None, + name=name, + parent_id=parent_id, + start_time=datetime.now(UTC), + is_replayed=False, + status=OperationStatus.STARTED, + attempt=1, + ) + + +def test_missing_body_identity_stays_missing_instead_of_being_guessed() -> None: + sink = MemorySink() + observer = LifecycleObservations(sink) + observer.body("work", "marker", 1) + assert [item["kind"] for item in sink.records] == ["observation_error"] + assert "operationId" not in sink.records[0] + + +@pytest.mark.parametrize("wrong", ["name", "attempt"]) +def test_body_requires_matching_public_step_hook(wrong: str) -> None: + sink = MemorySink() + observer = LifecycleObservations(sink) + observer.on_user_function_start(user_info("actual-id")) + observer.body( + "other" if wrong == "name" else "work", "marker", 2 if wrong == "attempt" else 1 + ) + assert sink.records[-1]["kind"] == "observation_error" + assert not any(item["kind"] == "body" for item in sink.records) + + +def test_concurrent_public_user_scopes_keep_their_actual_operation_ids() -> None: + sink = MemorySink() + observer = LifecycleObservations(sink) + barrier = threading.Barrier(2) + + def body(identity: str) -> None: + info = user_info(identity, parent_id="actual-parent") + observer.on_user_function_start(info) + barrier.wait(timeout=3) + observer.body("work", identity, 1) + observer.on_user_function_end(UserFunctionEndInfo.from_start_info(info, None)) + assert observer.current() is None + + with ThreadPoolExecutor(2) as executor: + list(executor.map(body, ["first-id", "second-id"])) + bodies = [item for item in sink.records if item["kind"] == "body"] + assert {(item["operationId"], item["value"]) for item in bodies} == { + ("first-id", "first-id"), + ("second-id", "second-id"), + } + assert { + item["taskId"] for item in sink.records if item["kind"] == "task_start" + } == {item["taskId"] for item in sink.records if item["kind"] == "task_exit"} + + +def test_unmatched_task_end_remains_visible() -> None: + sink = MemorySink() + observer = LifecycleObservations(sink) + observer.on_user_function_start( + user_info("child-id", parent_id="not-observed", kind=OperationType.CONTEXT) + ) + observer.on_user_function_end( + UserFunctionEndInfo.from_start_info(user_info("wrong-id"), None) + ) + assert sum(item["kind"] == "observation_error" for item in sink.records) == 1 + + +def test_checkpoint_snapshot_does_not_claim_reexecution_or_drop_stored_errors() -> None: + original = OperationInfo( + operation_id="stored-id", + operation_type=OperationType.STEP, + sub_type="Step", + name="failure", + parent_id=None, + start_time=None, + is_replayed=False, + status=OperationStatus.FAILED, + error=ErrorObject( + type="ValueError", message="stored failure", data=None, stack_trace=None + ), + ) + record = OperationObservation.from_info(original).to_record() + assert record["error"] == {"type": "ValueError", "message": "stored failure"} + assert record["startedAtMs"] is None and record["isReplayed"] is False + sink = MemorySink() + observer = LifecycleObservations(sink) + info = InvocationStartInfo( + request_id="actual-request", + execution_arn="actual-execution", + is_first_invocation=False, + operations={"stored-id": original}, + ) + observer.on_invocation_start(info) + assert sink.records[0]["operations"] == [record] + assert not any(item["kind"] == "body" for item in sink.records) + + +def test_trace_records_immutable_case_identity_and_actual_source_sequence( + monkeypatch, +) -> None: + ledger = install_ledger(monkeypatch) + payload = shared_payload() + trace = fixture.Trace(payload, lambda_context(30_000), "actual-execution") + observed_at = time.time() * 1000 - 10 + record = trace.observe("boundary", atMs=observed_at) + assert record["observation"] == { + "kind": "boundary", + "atMs": observed_at, + "sourceSequence": record["sequence"], + "captureSequence": 1, + } + assert record["caseId"] == "case" + assert trace.payload["run"] == "unit" + assert ledger.observations() == [record] + + +@pytest.mark.parametrize( + "field", ["caseId", "role", "controlPrefix", "coverageProfile"] +) +def test_shared_case_cannot_silently_drop_ownership_metadata( + monkeypatch, field: str +) -> None: + ledger = install_ledger(monkeypatch) + payload = shared_payload() + del payload[field] + with pytest.raises(ValueError, match=field): + fixture.Trace(payload, lambda_context(30_000), "execution") + assert ledger.records() == [] + + +@pytest.mark.parametrize( + ("alias", "canonical"), + [("unit", "previous"), ("previous", "unit"), ("previous", "previous")], +) +def test_shared_case_rejects_conflicting_run_alias_before_storage( + monkeypatch, alias, canonical +): + ledger = install_ledger(monkeypatch) + payload = shared_payload() + payload.update(run=alias, runId=canonical) + from aws_durable_execution_conformance_tests.lmi.artifacts import case_key + + payload["controlPrefix"] = ( + f"runs/{canonical}/cases/{case_key(payload['caseId'])}/control/" + ) + storage = Mock(return_value=ledger) + monkeypatch.setattr(fixture.boto3, "client", storage) + with pytest.raises(ValueError, match="different deployment"): + fixture.Trace(payload, lambda_context(30_000), "execution") + storage.assert_not_called() + + +@pytest.mark.parametrize( + "prefix", ["runs/unit/control/", "runs/unit/cases/other/control/"] +) +def test_shared_case_rejects_controls_outside_its_exact_prefix( + monkeypatch, prefix +) -> None: + install_ledger(monkeypatch) + payload = shared_payload() + payload["controlPrefix"] = prefix + with pytest.raises(ValueError, match="case-owned"): + fixture.Trace(payload, lambda_context(30_000), "execution") + + +@pytest.mark.parametrize("mode", ["normal", "emergency"]) +def test_gate_release_reports_observed_provenance_and_keeps_controls_case_owned( + monkeypatch, mode: str +) -> None: + ledger = install_ledger(monkeypatch) + payload = shared_payload() + trace = fixture.Trace(payload, lambda_context(30_000), "execution") + prefix = payload["controlPrefix"] + ledger.objects[prefix + "gate"] = b"release" if mode == "normal" else b"hold" + ledger.objects[prefix + "release-all"] = b"hold" if mode == "normal" else b"release" + ledger.objects["runs/unit/cases/other/control/gate"] = b"hold" + assert trace.gate("gate") is None + assert ledger.objects["runs/unit/cases/other/control/gate"] == b"hold" + observations = [item["observation"] for item in ledger.observations()] + assert [item["kind"] for item in observations] == [ + "io_start", + "fault_released", + "io_exit", + ] + assert observations[0]["taskId"] == observations[-1]["taskId"] + assert observations[1]["mode"] == mode + + +def test_root_scope_requires_the_public_invocation_operation() -> None: + sink = MemorySink() + observer = LifecycleObservations(sink) + with observer.root_scope(): + pass + assert [item["kind"] for item in sink.records] == ["observation_error"] + + +def test_gate_preserves_the_existing_checkpointed_none_result(monkeypatch) -> None: + ledger = install_ledger(monkeypatch) + payload = shared_payload() + ledger.objects[payload["controlPrefix"] + "gate"] = b"release" + ledger.objects[payload["controlPrefix"] + "release-all"] = b"hold" + trace = fixture.Trace(payload, lambda_context(30_000), "execution") + assert trace.gate("gate") is None + + +@pytest.mark.parametrize("method", ["checkpoint", "get_execution_state"]) +def test_failed_real_client_call_keeps_its_dispatch_and_exit_identity( + monkeypatch, method: str +) -> None: + from unittest.mock import Mock + + ledger = install_ledger(monkeypatch) + trace = fixture.Trace(shared_payload(), lambda_context(30_000), "execution") + backend = Mock() + getattr(backend, method).side_effect = OSError("service unavailable") + client = fixture.ObservedClient(backend, trace) + with pytest.raises(OSError, match="service unavailable"): + getattr(client, method)(**({"updates": []} if method == "checkpoint" else {})) + observations = [record["observation"] for record in ledger.observations()] + prefix = "checkpoint" if method == "checkpoint" else "poll" + entered = next(item for item in observations if item["kind"] == prefix + "_call") + exited = next(item for item in observations if item["kind"] == prefix + "_exit") + assert entered["callId"] == exited["callId"] and entered["atMs"] <= exited["atMs"] + assert not any(item["kind"] == "checkpoint_ack" for item in observations) + + +@pytest.mark.parametrize("completed_ns", [1794607984811568141, 1794607984811569459]) +def test_pending_and_wrapper_return_share_one_captured_timestamp( + monkeypatch, completed_ns +): + ledger = install_ledger(monkeypatch) + original = invocation() + payload = original.to_json_dict() + payload["InitialExecutionState"]["Operations"][0]["ExecutionDetails"][ + "InputPayload" + ] = json.dumps(shared_payload()) + injected = fixture.DurableExecutionInvocationInputWithClient.from_durable_execution_invocation_input( + fixture.DurableExecutionInvocationInput.from_json_dict(payload), + original.service_client, + ) + monkeypatch.setattr( + fixture, "time", SimpleNamespace(time=time.time, time_ns=lambda: completed_ns) + ) + monkeypatch.setattr( + fixture, + "durable_execution", + lambda *args, **kwargs: lambda *args: {"Status": "PENDING"}, + ) + assert fixture.handler(injected, lambda_context(30000)) == {"Status": "PENDING"} + observations = [record["observation"] for record in ledger.observations()] + wrapper = next(item for item in observations if item["kind"] == "wrapper_return") + pending = next(item for item in observations if item["kind"] == "pending") + assert pending["atMs"] == wrapper["atMs"] == completed_ns / 1_000_000 + + +@pytest.mark.parametrize("kind", ["checkpoint", "background", "suspend"]) +@pytest.mark.parametrize("effect", ["none", "body", "rpc"]) +def test_stored_sdk_errors_are_rejections_only_before_new_work( + monkeypatch, kind, effect +): + ledger = install_ledger(monkeypatch) + trace = fixture.Trace(shared_payload(), lambda_context(30000), "execution") + errors = { + "checkpoint": lambda: fixture.CheckpointError("Invalid checkpoint token"), + "background": lambda: fixture.BackgroundThreadError( + "failed", ValueError("source") + ), + "suspend": lambda: fixture.SuspendExecution("revoked"), + } + + def checkpoint(**options): + if effect == "rpc": + trace.next_call_id("checkpoint") + raise errors[kind]() + + def step(body, **options): + if effect == "body": + body(None) + if effect == "rpc": + trace.next_call_id("checkpoint") + raise errors[kind]() + + trace.durable_context = SimpleNamespace( + state=SimpleNamespace(create_checkpoint=checkpoint), step=step + ) + fixture.admission_probes(trace) + probes = [ + r["observation"] + for r in ledger.observations() + if r["observation"]["kind"] == "admission_probe" + ] + assert probes[0]["outcome"] == ("ERROR" if effect == "rpc" else "REJECTED") + assert probes[1]["outcome"] == ("REJECTED" if effect == "none" else "ERROR") + + +def test_recovered_evidence_writes_share_an_invocation_budget(producer, monkeypatch): + trace, ledger = producer + ticks = iter([0.0, 3.0, 3.0, 6.0]) + monkeypatch.setattr(fixture, "publication_clock", lambda: next(ticks)) + real_put = ledger.put_object + + def committed_but_timed_out(**kwargs): + real_put(**kwargs) + raise ReadTimeoutError(endpoint_url="https://s3.example.test") + + put = Mock(side_effect=committed_but_timed_out) + monkeypatch.setattr(ledger, "put_object", put) + for index in range(10): + trace.emit("DIAGNOSTIC", index=index) + trace.finish_wrapper() + assert trace.source_failed + assert put.call_count == 2 + assert [event["phase"] for event in ledger.records()] == [ + "DIAGNOSTIC", + "DIAGNOSTIC", + ] + + +def test_healthy_heartbeat_uploads_do_not_spend_retry_budget(producer, monkeypatch): + trace, ledger = producer + ticks = count() + monkeypatch.setattr(fixture, "publication_clock", lambda: next(ticks) * 0.02) + for _ in range(500): + trace.emit("ALIVE") + trace.finish_wrapper() + assert len(ledger.records()) == 501 + assert ledger.records()[-1]["phase"] == "SEALED" diff --git a/lmi_tests/tests/unit/test_shared_workflow.py b/lmi_tests/tests/unit/test_shared_workflow.py new file mode 100644 index 000000000..5ad135e2d --- /dev/null +++ b/lmi_tests/tests/unit/test_shared_workflow.py @@ -0,0 +1,648 @@ +from pathlib import Path +import json +import sys +from unittest.mock import Mock + +import pytest +import yaml +from lmi_tests.shared_contract import CONFORMANCE_REVISION + +ROOT = Path(__file__).resolve().parents[3] + + +def test_shared_setup_bootstraps_before_conformance_is_installed(): + import subprocess + import sys + import textwrap + + script = textwrap.dedent(""" + import importlib.abc + import sys + from pathlib import Path + from unittest.mock import patch + + class NoConformance(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname.startswith('aws_durable_execution_conformance_tests'): + raise AssertionError('bootstrap tried to import uninstalled conformance') + return None + + sys.meta_path.insert(0, NoConformance()) + from lmi_tests import shared + with patch.object(shared, 'verify_checkout') as verify, patch.object(shared.subprocess, 'run') as install: + shared.setup(Path('.conformance')) + verify.assert_called_once_with(Path('.conformance')) + assert install.call_args.args[0][1:4] == ['-m', 'pip', 'install'] + """) + completed = subprocess.run( + [sys.executable, "-c", script], + cwd=ROOT, + capture_output=True, + text=True, + timeout=20, + ) + assert completed.returncode == 0, completed.stdout + completed.stderr + + +def test_workflow_calls_the_pinned_shared_definition(): + workflow = yaml.safe_load( + (ROOT / ".github/workflows/lmi-e2e-tests.yml").read_text() + ) + caller = workflow["jobs"]["lifecycle"] + assert list(workflow["jobs"]) == ["lifecycle"] + assert ( + caller["uses"] + == f"aws/aws-durable-execution-conformance-tests/.github/workflows/lmi-lifecycle.yml@{CONFORMANCE_REVISION}" + ) + assert caller["with"]["conformance-ref"] == CONFORMANCE_REVISION + assert (ROOT / caller["with"]["sdk-script"]).is_file() + assert set(caller["secrets"]) == { + "TEST_ROLE_ARN", + "TEST_ACCOUNT_ID", + "TEST_LAMBDA_EXECUTION_ROLE_ARN", + "CAPACITY_PROVIDER_ARN", + } + triggers = workflow.get("on", workflow.get(True)) + assert set(triggers["pull_request"]["types"]) == { + "opened", + "synchronize", + "reopened", + } + assert triggers["pull_request"]["branches"] == ["main"] + assert set(triggers["pull_request"]["paths"]) == { + ".github/workflows/lmi-e2e-tests.yml", + ".github/scripts/lmi-ci.sh", + "lmi_tests/**", + "!lmi_tests/**/*.md", + "packages/aws-durable-execution-sdk-python/src/**", + "packages/aws-durable-execution-sdk-python/pyproject.toml", + "packages/aws-durable-execution-sdk-python-testing/src/**", + "packages/aws-durable-execution-sdk-python-testing/pyproject.toml", + "pyproject.toml", + } + assert "workflow_dispatch" in triggers + + +def test_stage_dispatch_propagates_failure_and_preserves_deployment_identity(tmp_path): + import os + import subprocess + + fake = tmp_path / "hatch" + fake.write_text( + '#!/bin/bash\nprintf "%s\\n" "$@" > "$CALL_LOG"\nexit "${HATCH_RESULT:-0}"\n' + ) + fake.chmod(0o755) + calls = tmp_path / "calls.txt" + env = { + **os.environ, + "PATH": str(tmp_path) + ":" + os.environ["PATH"], + "CALL_LOG": str(calls), + "LMI_SHARED_RUN_ID": "123-2", + "LMI_RUNTIME": "python3.14", + "LMI_STACK_NAME": "python-lmi-e2e", + } + script = ROOT / ".github/scripts/lmi-ci.sh" + subprocess.run(["bash", str(script), "deploy"], env=env, check=True) + assert calls.read_text().splitlines() == [ + "run", + "lmi:python", + "-m", + "lmi_tests.deploy", + "deploy", + "--run-id", + "123-2", + "--runtime", + "python3.14", + "--stack-name", + "python-lmi-e2e", + ] + failed = subprocess.run( + ["bash", str(script), "run"], env={**env, "HATCH_RESULT": "17"}, check=False + ) + assert failed.returncode == 17 + assert calls.read_text().splitlines() == ["run", "lmi:shared"] + + +def test_plan_preview_leaves_actual_run_directory_unwritten(monkeypatch, tmp_path): + from lmi_tests import shared + + monkeypatch.setattr(shared, "ARTIFACTS", tmp_path) + monkeypatch.setattr(shared, "verify_install", Mock()) + monkeypatch.setattr( + shared, "make_manifest", lambda deployment, coverage, output: deployment + ) + monkeypatch.setattr(shared, "run", Mock(return_value=0)) + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps({"run": "local"})) + args = ["lmi_tests.shared", "plan", "--manifest", str(manifest)] + monkeypatch.setattr(sys, "argv", args) + shared.main() + preview = tmp_path / "preview" + assert sorted(item.name for item in preview.iterdir()) == sorted( + shared.COVERAGE_PROFILES + ) + assert not (tmp_path / "shared").exists() + + args[1] = "run" + with pytest.raises(SystemExit) as exit_status: + shared.main() + assert exit_status.value.code == 0 + shared.run.assert_called_once_with({"run": "local"}, tmp_path / "shared") + + actual_run = tmp_path / "shared" + actual_run.mkdir() + retained = actual_run / "manifest.json" + retained.write_text("retained evidence") + monkeypatch.setattr( + sys, "argv", [*args[:1], "plan", *args[2:], "--output", str(actual_run)] + ) + with pytest.raises(FileExistsError): + shared.main() + assert retained.read_text() == "retained evidence" + + +@pytest.mark.parametrize("explicit_output", [False, True]) +def test_cleanup_loads_requested_recovery_manifest_before_checking_run( + monkeypatch, tmp_path, explicit_output +): + from aws_durable_execution_conformance_tests.lmi import ( + deployment as shared_deployment, + ) + from lmi_tests import shared + + manifest = tmp_path / "custom-manifest.json" + manifest.write_text(json.dumps({"run": "previous"})) + loader = Mock(return_value={"run": "current"}) + monkeypatch.setattr( + shared_deployment, "load_cleanup_manifest", loader, raising=False + ) + monkeypatch.setattr(shared, "verify_install", Mock()) + cleanup = Mock(return_value=0) + monkeypatch.setattr(shared, "cleanup", cleanup) + monkeypatch.setenv("LMI_SHARED_RUN_ID", "current") + argv = ["lmi_tests.shared", "cleanup", "--manifest", str(manifest)] + output = tmp_path / "explicit" if explicit_output else None + if output is not None: + argv.extend(["--output", str(output)]) + monkeypatch.setattr(sys, "argv", argv) + + with pytest.raises(SystemExit) as exit_status: + shared.main() + assert exit_status.value.code == 0 + loader.assert_called_once_with(tmp_path, "current", active_manifest=manifest) + cleanup.assert_called_once_with( + {"run": "current", "deploymentArtifactDirectory": str(tmp_path)}, output + ) + + +def test_pinned_cleanup_still_checks_manifest_run_and_uses_default_output( + monkeypatch, tmp_path +): + from aws_durable_execution_conformance_tests.lmi import ( + deployment as shared_deployment, + ) + from aws_durable_execution_conformance_tests.lmi.errors import CollectionError + from lmi_tests import shared + + monkeypatch.delattr(shared_deployment, "load_cleanup_manifest", raising=False) + monkeypatch.setattr(shared, "ARTIFACTS", tmp_path) + monkeypatch.setattr(shared, "verify_install", Mock()) + cleanup = Mock(return_value=0) + monkeypatch.setattr(shared, "cleanup", cleanup) + monkeypatch.setenv("LMI_SHARED_RUN_ID", "current") + monkeypatch.setattr(sys, "argv", ["lmi_tests.shared", "cleanup"]) + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps({"run": "previous"})) + with pytest.raises(CollectionError, match="different CI run"): + shared.main() + cleanup.assert_not_called() + manifest.write_text(json.dumps({"run": "current"})) + with pytest.raises(SystemExit) as exit_status: + shared.main() + assert exit_status.value.code == 0 + cleanup.assert_called_once_with({"run": "current"}, tmp_path / "shared") + + +@pytest.mark.parametrize("pre_archive", [True, False], ids=["pre-archive", "active"]) +def test_cleanup_routes_receipt_to_its_run(monkeypatch, tmp_path, pre_archive): + from aws_durable_execution_conformance_tests.lmi import ( + deployment as shared_deployment, + ) + from aws_durable_execution_conformance_tests.lmi import runner + from aws_durable_execution_conformance_tests.lmi.artifacts import case_key + from lmi_tests import shared + + if not hasattr(shared_deployment, "load_cleanup_manifest"): + pytest.skip("Published runner predates recovery-manifest lookup") + + manifest = tmp_path / "manifest.json" + deployment = { + "run": "current", + "stack": "stack", + "bucket": "bucket", + "commit": "revision", + "region": "us-west-2", + "deploymentArtifactDirectory": str(tmp_path), + } + output = tmp_path / "custom" + if pre_archive: + manifest.write_text(json.dumps({"run": "previous"})) + (tmp_path / "deployment-update.json").write_text( + json.dumps({**deployment, "recoveryManifest": deployment}) + ) + output.mkdir() + (output / "cleanup.json").write_text(json.dumps({"runId": "previous"})) + receipt = tmp_path / "cleanup" / case_key("current") / "cleanup.json" + else: + manifest.write_text(json.dumps(deployment)) + receipt = output / "cleanup.json" + (tmp_path / "case-output.json").write_text( + json.dumps( + { + "runId": "previous" if pre_archive else "current", + "directory": str(output), + } + ) + ) + reconcile = Mock(return_value="current") + monkeypatch.setattr(runner, "recover_deployment_update", reconcile) + monkeypatch.setattr(shared, "verify_install", Mock()) + monkeypatch.setenv("LMI_SHARED_RUN_ID", "current") + monkeypatch.setattr( + sys, "argv", ["lmi_tests.shared", "cleanup", "--manifest", str(manifest)] + ) + + with pytest.raises(SystemExit) as exit_status: + shared.main() + + assert exit_status.value.code == 0 + assert reconcile.call_args.args[:2] == (deployment, tmp_path) + report = json.loads(receipt.read_text()) + assert report["runId"] == "current" + if pre_archive: + assert json.loads((output / "cleanup.json").read_text()) == { + "runId": "previous" + } + assert not (tmp_path / "shared").exists() + + +def test_legacy_pin_cannot_reconcile_an_existing_journal(monkeypatch, tmp_path): + from aws_durable_execution_conformance_tests.lmi import ( + deployment as shared_deployment, + ) + from aws_durable_execution_conformance_tests.lmi.errors import CollectionError + from lmi_tests import shared + + monkeypatch.delattr(shared_deployment, "load_cleanup_manifest", raising=False) + (tmp_path / "deployment-update.json").write_text(json.dumps({"run": "current"})) + with pytest.raises(CollectionError, match="recover its journal"): + shared.cleanup_inputs(tmp_path / "manifest.json", None, "current") + + +def test_pinned_run_and_cleanup_share_manifest_relative_default(monkeypatch, tmp_path): + from aws_durable_execution_conformance_tests.lmi import ( + deployment as shared_deployment, + ) + from lmi_tests import shared + + monkeypatch.delattr(shared_deployment, "load_cleanup_manifest", raising=False) + monkeypatch.setattr(shared, "verify_install", Mock()) + downloaded = tmp_path / "downloaded" + downloaded.mkdir() + manifest = downloaded / "manifest.json" + manifest.write_text(json.dumps({"run": "current"})) + link = tmp_path / "manifest.json" + link.symlink_to(manifest) + expected_output = downloaded / "shared" + run = Mock(return_value=0) + cleanup = Mock(return_value=0) + monkeypatch.setattr(shared, "run", run) + monkeypatch.setattr(shared, "cleanup", cleanup) + monkeypatch.setenv("LMI_SHARED_RUN_ID", "current") + for command in ("run", "cleanup"): + monkeypatch.setattr( + sys, "argv", ["lmi_tests.shared", command, "--manifest", str(link)] + ) + with pytest.raises(SystemExit) as exit_status: + shared.main() + assert exit_status.value.code == 0 + run.assert_called_once_with({"run": "current"}, expected_output) + cleanup.assert_called_once_with({"run": "current"}, expected_output) + + +def test_recovery_prefers_journal_beside_symlink_to_previous_manifest( + monkeypatch, tmp_path +): + from aws_durable_execution_conformance_tests.lmi import ( + deployment as shared_deployment, + ) + from lmi_tests import shared + + previous = tmp_path / "previous" + previous.mkdir() + manifest = previous / "manifest.json" + manifest.write_text(json.dumps({"run": "previous"})) + link = tmp_path / "manifest.json" + link.symlink_to(manifest) + (tmp_path / "deployment-update.json").write_text(json.dumps({"run": "current"})) + current = {"run": "current", "deploymentArtifactDirectory": str(tmp_path)} + loader = Mock(return_value=current) + monkeypatch.setattr( + shared_deployment, "load_cleanup_manifest", loader, raising=False + ) + assert shared.cleanup_inputs(link, None, "current") == (current, None) + loader.assert_called_once_with(tmp_path, "current", active_manifest=manifest) + + +@pytest.mark.parametrize("nested", [False, True]) +def test_verify_install_rejects_core_outside_pinned_source( + monkeypatch, tmp_path, nested +): + import aws_durable_execution_conformance_tests as core + from lmi_tests import shared + + checkout = tmp_path / "pinned" + verify = Mock() + monkeypatch.setattr(shared, "verify_checkout", verify) + installed = checkout / ".venv/lib/site-packages" if nested else tmp_path / "other" + monkeypatch.setattr( + core, + "__file__", + str(installed / "aws_durable_execution_conformance_tests/__init__.py"), + ) + with pytest.raises(ValueError, match="not from the pinned checkout"): + shared.verify_install(checkout) + verify.assert_called_once_with(checkout) + + +@pytest.mark.parametrize("absolute", [False, True]) +def test_manual_cleanup_relies_on_local_downloaded_artifact_paths( + monkeypatch, tmp_path, absolute +): + from aws_durable_execution_conformance_tests.lmi import ( + deployment as shared_deployment, + ) + from aws_durable_execution_conformance_tests.lmi.errors import CollectionError + from lmi_tests import shared + + manifest = tmp_path / "manifest.json" + manifest.write_text( + json.dumps( + {"run": "current", "deploymentArtifactDirectory": "/previous/artifacts"} + ) + ) + (tmp_path / "case-output.json").write_text( + json.dumps( + { + "runId": "current", + "directory": "/previous/output" if absolute else "custom", + } + ) + ) + loader = Mock() + monkeypatch.setattr( + shared_deployment, "load_cleanup_manifest", loader, raising=False + ) + monkeypatch.setattr(shared, "verify_install", Mock()) + cleanup = Mock(return_value=0) + monkeypatch.setattr(shared, "cleanup", cleanup) + monkeypatch.delenv("LMI_SHARED_RUN_ID", raising=False) + argv = ["lmi_tests.shared", "cleanup", "--manifest", str(manifest)] + monkeypatch.setattr(sys, "argv", argv) + + if absolute: + with pytest.raises(CollectionError, match="Specify --output"): + shared.main() + cleanup.assert_not_called() + argv.extend(["--output", str(tmp_path / "custom")]) + with pytest.raises(SystemExit) as exit_status: + shared.main() + + assert exit_status.value.code == 0 + loader.assert_not_called() + cleanup.assert_called_once_with( + {"run": "current", "deploymentArtifactDirectory": str(tmp_path)}, + tmp_path / "custom" if absolute else None, + ) + + +@pytest.mark.parametrize("modern", [False, True]) +def test_summary_keeps_expected_run_when_using_either_runner( + monkeypatch, tmp_path, modern +): + from lmi_tests import summary + + def current(directory, *, expected_run=None): + return f"{directory.name}:{expected_run}" + + old = Mock(return_value="legacy acceptance") + + def legacy(directory): + return old(directory) + + monkeypatch.setattr(summary, "summarize", current if modern else legacy) + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps({"run": "older"})) + if modern: + assert summary.render(tmp_path, "current") == f"{tmp_path.name}:current" + else: + assert "acceptance is unavailable" in summary.render(tmp_path, "current") + old.assert_not_called() + manifest.write_text(json.dumps({"run": "current"})) + assert summary.render(tmp_path, "current") == "legacy acceptance" + old.assert_called_once_with(tmp_path) + + +def test_pinned_summary_reports_build_failure_without_manifest(monkeypatch, tmp_path): + from lmi_tests import summary + + from aws_durable_execution_conformance_tests.lmi.summary import summarize + + def legacy(directory): + return summarize(directory) + + monkeypatch.setattr(summary, "summarize", legacy) + (tmp_path / "build-error.json").write_text(json.dumps({"type": "BuildError"})) + assert "build-error: BuildError" in summary.render(tmp_path, "current") + + +def test_healthy_peer_and_recovery_require_success(): + from lmi_tests.shared_evidence import expected_outcome + + assert expected_outcome( + {"payload": {"scenario": "barrier"}, "marker": "worker"}, "peer-recovery" + ) == { + "status": "SUCCEEDED", + "result": "worker", + } + + +def test_replay_policy_counts_logical_items_and_keeps_first_allowance(): + from lmi_tests.shared_evidence import replay_effects + + bodies = [ + {"operation": "item", "operationId": "bool", "value": True}, + {"operation": "item", "operationId": "first", "value": 1}, + {"operation": "item", "operationId": "first", "value": 1}, + {"operation": "item", "operationId": "extra", "value": 1}, + {"operation": "item", "operationId": "invalid", "value": 4}, + {"operation": "item", "operationId": "second", "value": 2}, + ] + counts, missing = replay_effects(bodies) + assert counts == {"first": 1, "extra": 0, "invalid": 0, "bool": 0, "second": 1} + assert set(missing) == {"item:3", "success", "failure", "retry", "left", "right"} + + +@pytest.mark.parametrize("capability", ["pinned", "per-name", "policy"]) +def test_python_evidence_binding_passes_only_supported_policy_options( + monkeypatch, capability +): + from lmi_tests import shared_evidence + + evidence = {"collectionErrors": ["preserved example"]} + observations = Mock(return_value=evidence) + + def pinned(*args, **kwargs): + return observations() + + def per_name(*args, expected_replay_effects, **kwargs): + return observations(expected_replay_effects) + + def policy(*args, expected_replay_effects, replay_effect_policy, **kwargs): + return observations(expected_replay_effects, replay_effect_policy) + + monkeypatch.setattr( + shared_evidence, + "shared_build_evidence", + { + "pinned": pinned, + "per-name": per_name, + "policy": policy, + }[capability], + ) + cloud = Mock() + assert shared_evidence.build_evidence(Mock(), cloud) is evidence + if capability == "pinned": + observations.assert_called_once_with() + elif capability == "per-name": + observations.assert_called_once_with(shared_evidence._EXPECTED_REPLAY_EFFECTS) + else: + observations.assert_called_once_with( + shared_evidence._EXPECTED_REPLAY_EFFECTS, shared_evidence.replay_effects + ) + cloud._save.assert_not_called() + + +@pytest.mark.parametrize("local_source", [True, False]) +def test_harness_checks_sdk_provenance_in_lmi_environment(tmp_path, local_source): + import os + import subprocess + + fake = tmp_path / "hatch" + fake.write_text( + '#!/bin/bash\nprintf "%s\n" "$*" >> "$CALL_LOG"\n' + 'if [[ "$*" == "run lmi:python -" ]]; then exec "$TEST_PYTHON" -; fi\n' + ) + fake.chmod(0o755) + calls = tmp_path / "calls.txt" + root = tmp_path / "checkout" + root.mkdir() + source = root / "packages/aws-durable-execution-sdk-python/src" + module = ( + source if local_source else tmp_path / "installed" + ) / "aws_durable_execution_sdk_python" + module.mkdir(parents=True) + (module / "__init__.py").touch() + + completed = subprocess.run( + ["bash", str(ROOT / ".github/scripts/lmi-ci.sh"), "harness"], + cwd=root, + env={ + **os.environ, + "PATH": f"{tmp_path}:{os.environ['PATH']}", + "CALL_LOG": str(calls), + "TEST_PYTHON": sys.executable, + "PYTHONPATH": str(module.parent), + }, + capture_output=True, + text=True, + ) + expected = ["run lmi:lint", "run lmi:python -"] + if local_source: + assert completed.returncode == 0 + expected.append("run lmi:shared-tests --junitxml=lmi_tests/artifacts/unit.xml") + else: + assert completed.returncode != 0 + assert "AssertionError" in completed.stderr + assert str(module) in completed.stderr + assert calls.read_text().splitlines() == expected + + +def test_python_cleanup_stops_execution_from_relocated_case_journal( + monkeypatch, tmp_path +): + from aws_durable_execution_conformance_tests.lmi import artifacts, runner + from lmi_tests import shared + + configuration = "c1" + target = "arn:aws:lambda:us-west-2:123:function:owned:$LATEST.PUBLISHED" + arn = target + "/durable-execution/name/id" + deployment = { + "run": "run", + "bucket": "private", + "region": "us-west-2", + "functions": {configuration: target}, + "deploymentArtifactDirectory": "/old/workspace", + } + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps(deployment)) + coverage = tmp_path / "shared/standard" + journal = ( + coverage + / "source/cases" + / artifacts.case_key("case") + / "invocations/marker.json" + ) + journal.parent.mkdir(parents=True) + journal.write_text( + json.dumps( + { + "payload": {"run": "run", "caseId": "case", "marker": "marker"}, + "function": target, + "arn": arn, + "durableExecutionName": "name", + } + ) + ) + (coverage / "manifest.json").write_text( + json.dumps( + { + "runId": "run", + "sdk": { + "artifacts_dir": "/old/workspace/shared/standard/source", + "artifacts_dir_relative": "source", + }, + "profiles": [{"profile_id": configuration, "resource_id": target}], + "scenarios": [{"case_id": "case", "profile_id": configuration}], + } + ) + ) + storage, service = Mock(), Mock() + storage.get_paginator.return_value.paginate.return_value = [] + service.get_durable_execution.return_value = {"Status": "RUNNING"} + monkeypatch.setattr( + runner, "client", lambda name, _: storage if name == "s3" else service + ) + monkeypatch.setattr(shared, "verify_install", Mock()) + monkeypatch.setenv("LMI_SHARED_RUN_ID", "run") + monkeypatch.setattr( + sys, "argv", ["lmi_tests.shared", "cleanup", "--manifest", str(manifest)] + ) + with pytest.raises(SystemExit) as exit_status: + shared.main() + assert exit_status.value.code == 0 + service.stop_durable_execution.assert_called_once_with(DurableExecutionArn=arn) + assert ( + json.loads((tmp_path / "shared/cleanup.json").read_text())["status"] + == "CLEANUP_REQUESTED" + ) diff --git a/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/model.py b/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/model.py index 052399a1c..1bcd73fb1 100644 --- a/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/model.py +++ b/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/model.py @@ -1339,12 +1339,16 @@ def get_retry_details(self) -> RetryDetails | None: if not self.operation.step_details or not self.operation_update: return None - delay = 0 + delay = None if ( self.operation_update.operation_type == OperationType.STEP - and self.operation_update.step_options + and self.operation_update.action != OperationAction.FAIL ): - delay = self.operation_update.step_options.next_attempt_delay_seconds + options = self.operation_update.step_options + if options is not None: + delay = options.next_attempt_delay_seconds + elif self.operation_update.action == OperationAction.RETRY: + delay = 0 return RetryDetails( current_attempt=self.operation.step_details.attempt, @@ -2354,38 +2358,7 @@ def create_event_started(cls, context: EventCreationContext) -> Event: @classmethod def from_event_with_id(cls, event: Event, event_id: int) -> Event: """Create a new Event from an existing event with updated event_id.""" - return cls( - event_type=event.event_type, - event_timestamp=event.event_timestamp, - sub_type=event.sub_type, - event_id=event_id, - operation_id=event.operation_id, - name=event.name, - parent_id=event.parent_id, - execution_started_details=event.execution_started_details, - execution_succeeded_details=event.execution_succeeded_details, - execution_failed_details=event.execution_failed_details, - execution_timed_out_details=event.execution_timed_out_details, - execution_stopped_details=event.execution_stopped_details, - context_started_details=event.context_started_details, - context_succeeded_details=event.context_succeeded_details, - context_failed_details=event.context_failed_details, - wait_started_details=event.wait_started_details, - wait_succeeded_details=event.wait_succeeded_details, - wait_cancelled_details=event.wait_cancelled_details, - step_started_details=event.step_started_details, - step_succeeded_details=event.step_succeeded_details, - step_failed_details=event.step_failed_details, - chained_invoke_started_details=event.chained_invoke_started_details, - chained_invoke_succeeded_details=event.chained_invoke_succeeded_details, - chained_invoke_failed_details=event.chained_invoke_failed_details, - chained_invoke_timed_out_details=event.chained_invoke_timed_out_details, - chained_invoke_stopped_details=event.chained_invoke_stopped_details, - callback_started_details=event.callback_started_details, - callback_succeeded_details=event.callback_succeeded_details, - callback_failed_details=event.callback_failed_details, - callback_timed_out_details=event.callback_timed_out_details, - ) + return replace(event, event_id=event_id) @classmethod def create_event_terminated(cls, context: EventCreationContext) -> Event: @@ -2763,9 +2736,7 @@ def events_to_operations(events: list[Event]) -> list[Operation]: existing_step.error if existing_step else None ) attempt: int = existing_step.attempt if existing_step else 0 - next_attempt_ts: datetime.datetime | None = ( - existing_step.next_attempt_timestamp if existing_step else None - ) + next_attempt_ts: datetime.datetime | None = None # StepSucceeded provides result if event.step_succeeded_details: diff --git a/packages/aws-durable-execution-sdk-python-testing/tests/empty_error_history_test.py b/packages/aws-durable-execution-sdk-python-testing/tests/empty_error_history_test.py index 42dcbee08..364ea694c 100644 --- a/packages/aws-durable-execution-sdk-python-testing/tests/empty_error_history_test.py +++ b/packages/aws-durable-execution-sdk-python-testing/tests/empty_error_history_test.py @@ -1,6 +1,6 @@ """History and SDK operation state preserve empty error payload presence.""" -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import Any, cast import pytest @@ -22,7 +22,9 @@ GetDurableExecutionHistoryResponse, GetDurableExecutionResponse, StartDurableExecutionInput, + RetryDetails, StepFailedDetails, + StepSucceededDetails, events_to_operations, ) from aws_durable_execution_sdk_python_testing.runner import ( @@ -229,3 +231,52 @@ def test_missing_callback_details_do_not_invent_error_payload() -> None: event = Event.create_callback_event_failed(context) assert event.callback_failed_details is not None assert event.callback_failed_details.error is None + + +@pytest.mark.parametrize("succeeded", [False, True]) +def test_terminal_step_history_clears_previous_retry_deadline(succeeded): + timestamp = datetime(2026, 1, 1, tzinfo=UTC) + retry = Event( + event_type="StepFailed", + event_timestamp=timestamp, + operation_id="operation", + name="retries", + step_failed_details=StepFailedDetails( + retry_details=RetryDetails(current_attempt=1, next_attempt_delay_seconds=1) + ), + ) + first = GetDurableExecutionHistoryResponse(events=[retry]) + (pending,) = events_to_operations(first.events) + assert pending.step_details.next_attempt_timestamp == timestamp + timedelta( + seconds=1 + ) + + terminal = Event( + event_type="StepSucceeded" if succeeded else "StepFailed", + event_timestamp=timestamp + timedelta(seconds=2), + operation_id="operation", + name="retries", + step_succeeded_details=StepSucceededDetails( + retry_details=RetryDetails(current_attempt=2) + ) + if succeeded + else None, + step_failed_details=None + if succeeded + else StepFailedDetails(retry_details=RetryDetails(current_attempt=2)), + ) + history = GetDurableExecutionHistoryResponse.from_dict( + GetDurableExecutionHistoryResponse(events=[retry, terminal]).to_dict() + ) + execution = GetDurableExecutionResponse( + durable_execution_arn="arn:execution", + durable_execution_name="execution", + function_arn="arn:function", + status="SUCCEEDED" if succeeded else "FAILED", + start_timestamp=timestamp, + ) + step = DurableFunctionTestResult.from_execution_history( + execution, history + ).get_step("retries") + assert step.attempt == 2 + assert step.next_attempt_timestamp is None diff --git a/packages/aws-durable-execution-sdk-python-testing/tests/model_test.py b/packages/aws-durable-execution-sdk-python-testing/tests/model_test.py index c4194a93c..1c42e21e5 100644 --- a/packages/aws-durable-execution-sdk-python-testing/tests/model_test.py +++ b/packages/aws-durable-execution-sdk-python-testing/tests/model_test.py @@ -7,9 +7,14 @@ import pytest from aws_durable_execution_sdk_python.lambda_service import ( + Operation, + OperationAction, OperationStatus, OperationSubType, OperationType, + OperationUpdate, + StepDetails, + StepOptions, ) from aws_durable_execution_sdk_python_testing.exceptions import ( @@ -33,6 +38,7 @@ ContextSucceededDetails, ErrorResponse, Event, + EventCreationContext, EventError, EventInput, EventResult, @@ -1524,6 +1530,62 @@ def test_retry_details_with_current_attempt_only(): assert result_data == {"CurrentAttempt": 2} +@pytest.mark.parametrize( + ("action", "step_options", "expected"), + [ + (OperationAction.FAIL, None, {"CurrentAttempt": 1}), + ( + OperationAction.FAIL, + StepOptions(next_attempt_delay_seconds=30), + {"CurrentAttempt": 1}, + ), + (OperationAction.SUCCEED, None, {"CurrentAttempt": 1}), + ( + OperationAction.RETRY, + None, + {"CurrentAttempt": 1, "NextAttemptDelaySeconds": 0}, + ), + ( + OperationAction.RETRY, + StepOptions(next_attempt_delay_seconds=0), + {"CurrentAttempt": 1, "NextAttemptDelaySeconds": 0}, + ), + ], +) +def test_retry_delay_is_published_only_when_another_attempt_is_scheduled( + action: OperationAction, step_options: StepOptions | None, expected: dict[str, int] +) -> None: + context = EventCreationContext( + operation=Operation( + operation_id="step", + operation_type=OperationType.STEP, + status=OperationStatus.FAILED, + step_details=StepDetails(attempt=1), + ), + operation_update=OperationUpdate( + operation_id="step", + operation_type=OperationType.STEP, + action=action, + step_options=step_options, + ), + event_id=1, + durable_execution_arn="execution", + start_durable_execution_input=StartDurableExecutionInput( + account_id="123456789012", + function_name="fixture", + function_qualifier="$LATEST", + execution_name="case", + execution_timeout_seconds=30, + execution_retention_period_days=1, + ), + ) + + details = context.get_retry_details() + + assert details is not None + assert details.to_dict() == expected + + # Tests for ExecutionStartedDetails def test_execution_started_details_serialization(): """Test ExecutionStartedDetails from_dict/to_dict round-trip.""" @@ -3601,6 +3663,22 @@ def test_events_to_operations_treats_empty_sub_type_as_none(): assert events_to_operations([event])[0].sub_type is None +def test_reassigning_invocation_event_id_preserves_completion_details() -> None: + start = datetime.datetime(2023, 1, 1, tzinfo=datetime.UTC) + end = start + datetime.timedelta(seconds=1) + event = Event.create_invocation_completed( + event_id=0, + event_timestamp=end, + start_timestamp=start, + end_timestamp=end, + request_id="req-123", + ) + + actual = Event.from_event_with_id(event, 42) + + assert actual.to_dict() == {**event.to_dict(), "EventId": 42} + + def test_invocation_completed_details_to_json_dict(): """Test InvocationCompletedDetails.to_json_dict() converts datetime to Unix milliseconds.""" start_time = datetime.datetime(2023, 1, 1, 0, 0, 0, 123456, tzinfo=datetime.UTC) diff --git a/pyproject.toml b/pyproject.toml index 63fd318a8..77c666fa2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,6 +4,8 @@ version = "0.0.0" requires-python = ">=3.11" [tool.hatch.envs.default] +# The root coordinates workspace packages; it is not an installable distribution. +skip-install = true workspace.members = ["packages/*"] [tool.hatch.envs.test] @@ -25,6 +27,24 @@ all = "pytest {args}" cov = "pytest --cov-report=term-missing --cov {args}" examples-integration = "pytest --runner-mode=cloud -m example packages/aws-durable-execution-sdk-python-examples/test/ -v {args}" +[tool.hatch.envs.lmi] +detached = true +python = "3.14" +workspace.members = [ + "packages/aws-durable-execution-sdk-python", + "packages/aws-durable-execution-sdk-python-testing", +] +dependencies = ["boto3>=1.43.0", "pytest", "ruff", "build", "mypy"] + +[tool.hatch.envs.lmi.scripts] +unit = "pytest lmi_tests/tests/unit {args}" +lint = "ruff check lmi_tests && ruff format --check lmi_tests" +build = "python -m lmi_tests.deploy build {args}" +shared-setup = "python -m lmi_tests.shared setup {args}" +shared = "python -m lmi_tests.shared run {args}" +shared-cleanup = "python -m lmi_tests.shared cleanup {args}" +shared-tests = "python -m pytest lmi_tests/tests/unit lmi_tests/tests/e2e {args}" + [tool.pytest.ini_options] # Declare custom markers to avoid warnings with --strict-markers addopts = "-v --strict-markers --import-mode=importlib"