Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
perf(lambda): reuse local provided runtime environments (#1673)
Jay Janssen9d01f2a4f531
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1c30aef3..c4f691b5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Changed+- **Lambda — warm local custom runtimes** — `provided.*` bootstraps now reuse the existing subprocess worker pool instead of restarting on every invocation. Each invocation receives its request metadata through the Lambda Runtime API, concurrent calls use separate workers, and failed environments are cleaned up before reuse. Durable invocations retain their one-shot executor; Docker, image, and proxy execution are unchanged.+### Fixed- **CloudFormation — an `AWS::ApiGateway::Method`'s `MethodResponses` and `IntegrationResponses` are provisioned** — the provisioner read the method and integration properties and discarded both response lists, so every REST API deployed from a template lost its mapped response headers. The visible casualty was the CDK's `defaultCorsPreflightOptions`, whose generated `OPTIONS` method returns the `Access-Control-Allow-*` headers through a MOCK integration's `responseParameters`: the preflight answered without a single CORS header and the browser blocked the request. That became load-bearing once `COGNITO_USER_POOLS` authorizers were enforced in 1.5.10, because the preflight can no longer fall through to a proxy integration and be answered by the application's own CORS middleware. Both lists are now provisioned onto the method, where the existing request-time mapping picks them up, and a stack update reprovisions them from the template. Contributed by @ppettitau.diff --git a/README.md b/README.mdindex fcfc7e14..b9fa79ed 100644--- a/README.md+++ b/README.md@@ -401,7 +401,7 @@ subnet = ec2.create_subnet(| **SNS** | CreateTopic, DeleteTopic, ListTopics, GetTopicAttributes, SetTopicAttributes, Subscribe, Unsubscribe, ListSubscriptions, ListSubscriptionsByTopic, GetSubscriptionAttributes, SetSubscriptionAttributes, ConfirmSubscription, Publish, PublishBatch, TagResource, UntagResource, ListTagsForResource, CreatePlatformApplication, ListPlatformApplications, GetPlatformApplicationAttributes, SetPlatformApplicationAttributes, CreatePlatformEndpoint, GetEndpointAttributes, SetEndpointAttributes, DeleteEndpoint, DeletePlatformApplication | SNS→SQS fanout delivery; SNS→Lambda fanout (asynchronous delivery); FIFO topics with 5-minute deduplication, sequence numbers, content-based deduplication, and subscription validation; mobile-push endpoint lifecycle with device-token dedup and `Publish` to platform-endpoint `TargetArn` || **DynamoDB** | CreateTable, UpdateTable, DeleteTable, DescribeTable, ListTables, PutItem, GetItem, DeleteItem, UpdateItem, Query, Scan, BatchWriteItem, BatchGetItem, TransactWriteItems, TransactGetItems, DescribeTimeToLive, UpdateTimeToLive, DescribeContinuousBackups, UpdateContinuousBackups, DescribeEndpoints, TagResource, UntagResource, ListTagsOfResource, EnableKinesisStreamingDestination, DisableKinesisStreamingDestination, DescribeKinesisStreamingDestination, UpdateKinesisStreamingDestination | TTL enforced via thread-safe background reaper (60s cadence); DynamoDB Streams — `StreamSpecification` emits INSERT/MODIFY/REMOVE records on all write operations, respects `StreamViewType`; Kinesis streaming destinations (`aws_dynamodb_kinesis_streaming_destination`) fan item mutations out into any Kinesis stream by ARN while the destination is ACTIVE || **DynamoDB Streams** | ListStreams, DescribeStream, GetShardIterator, GetRecords | Reads records emitted by the main DynamoDB service via `boto3.client("dynamodbstreams")` — single synthetic shard per stream; `TRIM_HORIZON`/`LATEST`/`AT_SEQUENCE_NUMBER`/`AFTER_SEQUENCE_NUMBER` iterator types; `NEW_AND_OLD_IMAGES`, `NEW_IMAGE`, `OLD_IMAGE`, `KEYS_ONLY` view types; opaque base64 iterator tokens |-| **Lambda** | CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, GetPolicy, ListVersionsByFunction, PublishVersion, CreateAlias, GetAlias, UpdateAlias, DeleteAlias, ListAliases, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PutFunctionConcurrency, GetFunctionConcurrency, DeleteFunctionConcurrency, PutFunctionEventInvokeConfig, GetFunctionEventInvokeConfig, DeleteFunctionEventInvokeConfig, PublishLayerVersion, GetLayerVersion, GetLayerVersionByArn, ListLayerVersions, DeleteLayerVersion, ListLayers, AddLayerVersionPermission, RemoveLayerVersionPermission, GetLayerVersionPolicy, CheckpointDurableExecution, GetDurableExecution, GetDurableExecutionState, GetDurableExecutionHistory, ListDurableExecutionsByFunction, StopDurableExecution, SendDurableExecutionCallbackSuccess, SendDurableExecutionCallbackFailure, SendDurableExecutionCallbackHeartbeat | Python and Node.js runtimes execute with warm worker pool; `provided.al2023`/`provided.al2` runtimes execute via Docker RIE (Go, Rust, C++ support); `Publish=True` creates immutable numbered versions; Code via `ZipFile`, `S3Bucket`/`S3Key` (with optional `S3ObjectVersion`), or `ImageUri` (Docker image); `PackageType: Image` pulls and invokes user-provided Docker images via Lambda RIE; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD; Aliases; Concurrency; EventInvokeConfig; **SnapStart** — `SnapStart.ApplyOn=PublishedVersions` round-trips on `CreateFunction`/`UpdateFunctionConfiguration` (Java 11+/Python 3.12+/.NET 8+ and container images, per AWS's constraints); publishing a version initializes its execution environment then and there, so the version reports `OptimizationStatus: On`, walks `Pending` → `Active`, answers `ResourceConflictException` while `Pending`, fails the publish on a broken init, and runs `snapshot-restore-py` before-snapshot/after-restore hooks during init (Python); **Durable Functions** — `CreateFunction` accepts `DurableConfig`; checkpoint/state/history/list/stop ops at the preview API (`2025-12-01`); external `SendCallback{Success,Failure,Heartbeat}` resume the SDK across invocations; resume scheduler fires WAIT expiries, callback timeouts, and step-retry backoffs; verified against the official `aws-durable-execution-sdk-python` and `aws-durable-execution-sdk-java`; **X-Ray active tracing** — `TracingConfig.Mode=Active` injects `_X_AMZN_TRACE_ID` (`Root=1-<hex>-<hex>;Parent=<hex>;Sampled=1`) into the runtime per invocation so the AWS X-Ray SDK runs without `Missing AWS Lambda trace data`; supported on the warm Python / Node executor, provided runtimes, and the local subprocess fallback (docker RIE upstream does not implement X-Ray and is logged but unsupported) |+| **Lambda** | CreateFunction, DeleteFunction, GetFunction, GetFunctionConfiguration, ListFunctions, Invoke, UpdateFunctionCode, UpdateFunctionConfiguration, AddPermission, RemovePermission, GetPolicy, ListVersionsByFunction, PublishVersion, CreateAlias, GetAlias, UpdateAlias, DeleteAlias, ListAliases, TagResource, UntagResource, ListTags, CreateEventSourceMapping, DeleteEventSourceMapping, GetEventSourceMapping, ListEventSourceMappings, UpdateEventSourceMapping, CreateFunctionUrlConfig, GetFunctionUrlConfig, UpdateFunctionUrlConfig, DeleteFunctionUrlConfig, ListFunctionUrlConfigs, PutFunctionConcurrency, GetFunctionConcurrency, DeleteFunctionConcurrency, PutFunctionEventInvokeConfig, GetFunctionEventInvokeConfig, DeleteFunctionEventInvokeConfig, PublishLayerVersion, GetLayerVersion, GetLayerVersionByArn, ListLayerVersions, DeleteLayerVersion, ListLayers, AddLayerVersionPermission, RemoveLayerVersionPermission, GetLayerVersionPolicy, CheckpointDurableExecution, GetDurableExecution, GetDurableExecutionState, GetDurableExecutionHistory, ListDurableExecutionsByFunction, StopDurableExecution, SendDurableExecutionCallbackSuccess, SendDurableExecutionCallbackFailure, SendDurableExecutionCallbackHeartbeat | Python and Node.js runtimes execute with warm worker pool; `provided.al2023`/`provided.al2` runtimes reuse local bootstrap processes via the Lambda Runtime API (Go, Rust, C++ support), or use Docker RIE when configured; `Publish=True` creates immutable numbered versions; Code via `ZipFile`, `S3Bucket`/`S3Key` (with optional `S3ObjectVersion`), or `ImageUri` (Docker image); `PackageType: Image` pulls and invokes user-provided Docker images via Lambda RIE; SQS, Kinesis, and DynamoDB Streams event source mappings; Function URL CRUD; Lambda Layers CRUD; Aliases; Concurrency; EventInvokeConfig; **SnapStart** — `SnapStart.ApplyOn=PublishedVersions` round-trips on `CreateFunction`/`UpdateFunctionConfiguration` (Java 11+/Python 3.12+/.NET 8+ and container images, per AWS's constraints); publishing a version initializes its execution environment then and there, so the version reports `OptimizationStatus: On`, walks `Pending` → `Active`, answers `ResourceConflictException` while `Pending`, fails the publish on a broken init, and runs `snapshot-restore-py` before-snapshot/after-restore hooks during init (Python); **Durable Functions** — `CreateFunction` accepts `DurableConfig`; checkpoint/state/history/list/stop ops at the preview API (`2025-12-01`); external `SendCallback{Success,Failure,Heartbeat}` resume the SDK across invocations; resume scheduler fires WAIT expiries, callback timeouts, and step-retry backoffs; verified against the official `aws-durable-execution-sdk-python` and `aws-durable-execution-sdk-java`; **X-Ray active tracing** — `TracingConfig.Mode=Active` injects `_X_AMZN_TRACE_ID` (`Root=1-<hex>-<hex>;Parent=<hex>;Sampled=1`) into the runtime per invocation so the AWS X-Ray SDK runs without `Missing AWS Lambda trace data`; supported on the warm Python / Node executor, provided runtimes, and the local subprocess fallback (docker RIE upstream does not implement X-Ray and is logged but unsupported) || **IAM** | CreateUser, GetUser, ListUsers, DeleteUser, CreateRole, GetRole, ListRoles, DeleteRole, UpdateRoleDescription, PutRolePermissionsBoundary, DeleteRolePermissionsBoundary, CreatePolicy, GetPolicy, DeletePolicy, AttachRolePolicy, DetachRolePolicy, PutRolePolicy, GetRolePolicy, DeleteRolePolicy, ListRolePolicies, ListAttachedRolePolicies, CreateAccessKey, ListAccessKeys, DeleteAccessKey, UpdateAccessKey, GetAccessKeyLastUsed, CreateInstanceProfile, GetInstanceProfile, DeleteInstanceProfile, AddRoleToInstanceProfile, RemoveRoleFromInstanceProfile, ListInstanceProfiles, TagInstanceProfile, UntagInstanceProfile, ListInstanceProfileTags, CreateGroup, GetGroup, AddUserToGroup, RemoveUserFromGroup, AttachGroupPolicy, DetachGroupPolicy, ListAttachedGroupPolicies, PutGroupPolicy, GetGroupPolicy, DeleteGroupPolicy, ListGroupPolicies, CreateServiceLinkedRole, DeleteServiceLinkedRole, GetServiceLinkedRoleDeletionStatus, CreateOpenIDConnectProvider, ListOpenIDConnectProviders, CreateSAMLProvider, GetSAMLProvider, ListSAMLProviders, UpdateSAMLProvider, DeleteSAMLProvider, CreateLoginProfile, GetLoginProfile, UpdateLoginProfile, DeleteLoginProfile, CreateVirtualMFADevice, EnableMFADevice, DeactivateMFADevice, ResyncMFADevice, ListMFADevices, ListVirtualMFADevices, DeleteVirtualMFADevice, GetAccountAuthorizationDetails, GenerateServiceLastAccessedDetails, GetServiceLastAccessedDetails, TagRole, UntagRole, TagUser, UntagUser, TagPolicy, UntagPolicy, GenerateCredentialReport, GetCredentialReport, GetAccountSummary, GetAccountPasswordPolicy, UpdateAccountPasswordPolicy, DeleteAccountPasswordPolicy, ListAccountAliases, CreateAccountAlias, DeleteAccountAlias | Role descriptions and permissions boundaries round-trip through role reads; boundaries support put/delete updates. || **STS** | GetCallerIdentity, AssumeRole, GetSessionToken, AssumeRoleWithWebIdentity | || **IMDS** (EC2 Instance Metadata) | `PUT /latest/api/token`, `GET /latest/meta-data/instance-id`, `GET /latest/meta-data/iam/security-credentials/`, `GET /latest/meta-data/iam/security-credentials/<role>`, `GET /latest/meta-data/iam/info`, `GET /latest/meta-data/placement/{region,availability-zone,...}`, `GET /latest/dynamic/instance-identity/document` | IMDSv1 + IMDSv2; default credential chain falls through to a `ministack-instance-role` document with `ASIA*` session creds. Point SDKs at ministack via `AWS_EC2_METADATA_SERVICE_ENDPOINT=http://localhost:4566` (or `ec2_metadata_service_endpoint` in `~/.aws/config`); set `MINISTACK_IMDS_V2_REQUIRED=1` to require the token PUT |@@ -840,13 +840,14 @@ end-to-end without any client config.| `MINISTACK_OPENSEARCH_ENDPOINT` | _(unset)_ | If set (e.g. `localhost:9200`), every domain returns this endpoint instead of spawning a per-domain container — useful when you bring your own cluster || `PERSIST_STATE` | `0` | Set `1` to persist service state across restarts || `STATE_DIR` | `/tmp/ministack-state` | Directory for persisted state files |-| `LAMBDA_EXECUTOR` | `local` | Lambda execution mode: `local` (subprocess) or `docker` (container). `provided` runtimes and `PackageType: Image` always use Docker |+| `LAMBDA_EXECUTOR` | `local` | Lambda execution mode: `local` (subprocess, including `provided.*`) or `docker` (container). `PackageType: Image` always uses Docker || `LAMBDA_STRICT` | `0` | Set `1` for AWS-fidelity mode: every Lambda invocation runs in a Docker container via the AWS RIE image; in-process fallbacks are disabled. Missing Docker surfaces as `Runtime.DockerUnavailable` instead of degrading to a subprocess. Opt-in because the default install doesn't require Docker || `LAMBDA_DOCKER_NETWORK` | _(unset)_ | Legacy alias for `DOCKER_NETWORK` (Lambda only). Prefer `DOCKER_NETWORK` which covers all services || `LAMBDA_DOCKER_FLAGS` | _(unset)_ | Extra `docker run` flags injected into Lambda containers (matches LocalStack). Supports `-e` / `-v` / `--dns` / `--network` / `--cap-add` / `-m` / `--shm-size` / `--tmpfs` / `--add-host` / `--security-opt` / `--privileged` / `--read-only`. Useful for TLS proxies, custom CAs, and routed dev networks || `CODEBUILD_DOCKER_FLAGS` | _(unset)_ | Extra `docker run` flags for the CodeBuild local-agent container, same syntax and parser as `LAMBDA_DOCKER_FLAGS`. On an SELinux-enforcing host the agent needs `--security-opt label=disable` to reach the Docker socket it is handed || `MINISTACK_IMAGE_PREFIX` | _(unset)_ | Private-registry prefix prepended to every nested container image (RDS postgres/mysql/mariadb, ElastiCache redis/memcached, EKS k3s, Lambda runtimes). Testcontainers' `hub.image.name.prefix` is auto-forwarded into this var by the Java/Python modules || `LAMBDA_WARM_TTL_SECONDS` | `300` | How long an idle warm Lambda container stays in the pool before the reaper evicts it |+| `LAMBDA_PROVIDED_INIT_TIMEOUT` | `20` | Seconds a local warm `provided.*` bootstrap has to issue its first Runtime API `/next` request || `LAMBDA_ACCOUNT_CONCURRENCY` | `0` | Account-level concurrent-invocation cap (0 = unbounded). Match real AWS by setting to `1000`. Used to simulate `ConcurrentInvocationLimitExceeded` throttles || `SFN_MOCK_CONFIG` | _(unset)_ | Path to JSON file for Step Functions mock testing; compatible with AWS SFN Local format. Also accepts `LOCALSTACK_SFN_MOCK_CONFIG` || `ATHENA_ENGINE` | `auto` | SQL engine for Athena: `auto`, `duckdb`, `mock` |@@ -949,7 +950,7 @@ docker run -p 4566:4566 \### Lambda in Docker-Set `LAMBDA_EXECUTOR=docker` to run every Lambda invocation inside an AWS-supplied runtime container instead of a local subprocess. `provided.*` runtimes and `PackageType: Image` always use Docker regardless of this setting.+Set `LAMBDA_EXECUTOR=docker` to run every Lambda invocation inside an AWS-supplied runtime container instead of a local subprocess. `PackageType: Image` always uses Docker regardless of this setting. With the default local executor, `provided.*` runs the deployment's `bootstrap` directly; the executable must be compatible with the MiniStack host's OS and architecture. Use the Docker executor for bootstraps that require the AWS runtime image.Supported runtimes and the AWS public ECR images MiniStack pulls for them:@@ -1099,7 +1100,9 @@ aws --endpoint-url=http://localhost:4566 eks delete-cluster --name my-cluster### Lambda Warm Starts-MiniStack keeps Python and Node.js Lambda functions warm between invocations. After the first call (cold start), the handler module stays loaded in a persistent subprocess. Subsequent calls skip the import/require step, matching real AWS warm-start behaviour and making test suites significantly faster.+MiniStack keeps Python, Node.js, and `provided.*` Lambda functions warm between invocations with the local executor. After the first call (cold start), the handler module or custom-runtime bootstrap stays alive in a persistent subprocess. Subsequent calls skip initialization, matching real AWS warm-start behaviour and making test suites significantly faster.++Custom runtimes receive each event through the Lambda Runtime API's long-polling `/runtime/invocation/next` endpoint, with a fresh request ID, deadline, and X-Ray trace header. Concurrent invocations lease separate workers; function updates and deletion invalidate the workers. A timeout or crashed bootstrap is discarded so the next invocation starts a fresh process. Durable invocations retain the one-shot executor because their execution context changes per call. Docker, container-image, and proxy execution are unchanged.### Lambda Node.js Runtimesdiff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.pyindex 26e3a132..26a54d1d 100644--- a/ministack/core/lambda_runtime.py+++ b/ministack/core/lambda_runtime.py@@ -12,6 +12,7 @@ import jsonimport loggingimport osimport queue+import reimport shutilimport subprocessimport sys@@ -1431,6 +1432,17 @@ def _worker_key(func_name: str, config: dict, qualifier: str) -> str:return f"{account}:{region}:{func_name}:{qualifier}"+def _worker_class_for(config: dict):+ """Pick the execution environment implementation for a function's runtime.++ ``provided.*`` speaks the HTTP Lambda Runtime API; python/nodejs speak the+ JSON-line stdio protocol of the bundled worker scripts.+ """+ if str(config.get("Runtime", "")).startswith("provided"):+ return ProvidedWorker+ return Worker++def acquire_worker(func_name: str, config: dict, code_zip: bytes,qualifier: str = "$LATEST", max_concurrency: int | None = None):"""Lease a free execution environment for this function.@@ -1466,7 +1478,7 @@ def acquire_worker(func_name: str, config: dict, code_zip: bytes,return worker, "reused"if cap and len(entries) >= cap:return None, "func_cap"- worker = Worker(func_name, config, code_zip)+ worker = _worker_class_for(config)(func_name, config, code_zip)worker.in_use = Trueworker.last_used = time.time()entries.append(worker)@@ -1598,3 +1610,503 @@ def reset():doomed = [w for entries in _workers.values() for w in entries]_workers.clear()kill_workers(doomed)+++# ---------------------------------------------------------------------------+# provided.* (Go / Rust / custom runtime) warm worker+# ---------------------------------------------------------------------------++# Seconds the bootstrap binary gets to complete its cold start and issue its+# first GET /runtime/invocation/next before we give up on the environment.+_PROVIDED_INIT_TIMEOUT = float(os.environ.get("LAMBDA_PROVIDED_INIT_TIMEOUT", "20"))++# How often init/invocation waits check whether the bootstrap is still alive.+_PROVIDED_POLL = 0.05++# Log lines buffered per environment between drains; the oldest are dropped+# rather than letting a chatty handler grow the buffer without bound.+_PROVIDED_LOG_MAX_LINES = 10000++# /2018-06-01/runtime/invocation/<request-id>/{response,error}+_INVOCATION_RESULT_RE = re.compile(r"/runtime/invocation/([^/]+)/(response|error)/?$")+++class ProvidedWorker(Worker):+ """A reusable execution environment for a ``provided.*`` Lambda.++ ``lambda_svc._execute_function_provided`` starts the bootstrap binary,+ serves exactly one ``/runtime/invocation/next``, and kills the process —+ so every invocation pays a full cold start. The Lambda Runtime API is+ already a long-poll loop, which is precisely how real Lambda reuses an+ environment: hold the HTTP server and the process open and the same binary+ picks up the next event off ``/next``.++ Reuses ``Worker``'s pool bookkeeping (lease/release, idle reaping,+ invalidation on code update); only the spawn and invoke mechanics differ,+ because a custom runtime speaks HTTP rather than the JSON-line stdio+ protocol the Python/Node worker scripts use.++ Each running environment is a *generation*: ``_spawn`` creates one (server,+ process, log pump, event queue), ``_teardown`` destroys it. A generation's+ queues are captured by its own handler threads, and results are accepted+ only for the current generation's in-flight request ID, so a timed-out or+ crashed environment cannot feed the invocation that replaces it.+ """++ def __init__(self, func_name: str, config: dict, code_zip: bytes):+ super().__init__(func_name, config, code_zip)+ self._server = None+ self._server_thread = None+ self._log_thread = None+ # One in-flight invocation at a time: the pool leases a worker+ # exclusively (``in_use``), so a second event can never be queued+ # behind a first on the same environment — matching AWS, where+ # concurrent invocations get separate environments.+ self._pending: queue.Queue = queue.Queue(maxsize=1)+ self._result: dict = {}+ self._response_ready = threading.Event()+ self._init_error = None+ self._first_poll = threading.Event()+ # Set by the first /next poll or by an /init/error POST, so the init+ # wait is not a fixed sleep.+ self._init_settled = threading.Event()+ self._stopping = True+ # Guards state shared with the Runtime API handler threads. Distinct+ # from ``self._lock``, which is held across a whole invocation.+ self._state_lock = threading.Lock()+ self._generation = 0+ self._current_request_id = None++ # -- State transitions driven by the Runtime API handler threads ------++ def _mark_first_poll(self, generation: int) -> bool:+ with self._state_lock:+ if generation != self._generation or self._stopping:+ return False+ self._first_poll.set()+ self._init_settled.set()+ return True++ def _record_init_error(self, generation: int, payload) -> None:+ with self._state_lock:+ if generation != self._generation:+ return+ self._init_error = payload+ self._init_settled.set()+ if self._current_request_id is not None:+ # Init can fail on a respawn an invocation is waiting on: fail+ # it now instead of at the timeout.+ self._current_request_id = None+ self._result = {"error": payload}+ self._response_ready.set()++ def _record_result(self, generation: int, request_id: str, kind: str,+ payload) -> bool:+ """Accept a ``/response`` or ``/error`` POST for the in-flight request.++ False means the ID is not the one we handed out: a duplicate, or a late+ POST from an environment already torn down, whose result must not reach+ the invocation that replaced it.+ """+ with self._state_lock:+ if generation != self._generation:+ return False+ if not self._current_request_id or request_id != self._current_request_id:+ return False+ self._current_request_id = None+ self._result = ({"error": payload} if kind == "error"+ else {"response": payload})+ self._response_ready.set()+ return True++ def _build_handler_class(self, generation: int, pending: queue.Queue):+ worker = self++ import http.server++ class RuntimeAPIHandler(http.server.BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, fmt, *args):+ pass++ def _read_body(self):+ encoding = self.headers.get("Transfer-Encoding", "")+ if "chunked" in encoding.lower():+ chunks = []+ while True:+ size = int(self.rfile.readline().strip(), 16)+ if size == 0:+ self.rfile.readline()+ break+ chunks.append(self.rfile.read(size))+ self.rfile.readline()+ return b"".join(chunks)+ length = int(self.headers.get("Content-Length", 0))+ return self.rfile.read(length) if length else b""++ def _respond(self, code: int, body: bytes = b""):+ self.send_response(code)+ if body:+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ if body:+ self.wfile.write(body)++ def _stopped(self):+ self._respond(500, b'{"errorMessage":"execution environment stopped"}')++ def do_GET(self):+ if "/runtime/invocation/next" not in self.path:+ self._respond(404)+ return+ # Reaching /next means init finished; the binary long-polls+ # here between invocations exactly as on AWS.+ if not worker._mark_first_poll(generation):+ self._stopped()+ return+ while True:+ if worker._stopping or generation != worker._generation:+ # Tell a runtime left over from a dead generation to+ # exit rather than serve the live environment's events.+ self._stopped()+ return+ try:+ request_id, event, deadline_ms, trace_id = pending.get(+ timeout=0.1)+ break+ except queue.Empty:+ continue+ payload = json.dumps(event).encode()+ self.send_response(200)+ self.send_header("Lambda-Runtime-Aws-Request-Id", request_id)+ self.send_header("Lambda-Runtime-Deadline-Ms", str(deadline_ms))+ self.send_header(+ "Lambda-Runtime-Invoked-Function-Arn",+ worker.config.get("FunctionArn", ""),+ )+ if trace_id:+ # The Runtime API header is how AWS hands X-Ray context to+ # a custom runtime per invocation. The one-shot executor+ # used a spawn-time env var, which a reused environment+ # cannot do — this is both warm-safe and closer to AWS.+ self.send_header("Lambda-Runtime-Trace-Id", trace_id)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def do_POST(self):+ body = self._read_body()+ try:+ parsed = json.loads(body)+ except json.JSONDecodeError:+ parsed = body.decode("utf-8", errors="replace")++ if "/runtime/init/error" in self.path:+ worker._record_init_error(generation, parsed)+ self._respond(202)+ return++ match = _INVOCATION_RESULT_RE.search(self.path)+ if not match:+ self._respond(404)+ return+ request_id, kind = match.group(1), match.group(2)+ if not worker._record_result(generation, request_id, kind, parsed):+ self._respond(400, json.dumps({+ "errorMessage": f"Invalid request ID: {request_id}",+ "errorType": "InvalidRequestID",+ }).encode())+ return+ self._respond(202)++ return RuntimeAPIHandler++ # -- Logs -------------------------------------------------------------++ def _pump_output(self, stream, log_queue: queue.Queue) -> None:+ """Drain the bootstrap's output into ``log_queue`` for its whole life.++ stdout and stderr are merged into one pipe (a custom runtime logs to+ either) and read continuously: an undrained pipe fills at ~64KiB and+ blocks the bootstrap on its next write. The queue belongs to one+ generation, so a dying environment's tail never mixes into the next.+ """+ try:+ for raw in iter(stream.readline, b""):+ if not raw:+ break+ if isinstance(raw, bytes):+ raw = raw.decode("utf-8", errors="replace")+ line = raw.rstrip("\r\n")+ try:+ log_queue.put_nowait(line)+ except queue.Full:+ # Drop the oldest, never block: blocking here would stall+ # the pipe this thread exists to drain.+ try:+ log_queue.get_nowait()+ except queue.Empty:+ pass+ try:+ log_queue.put_nowait(line)+ except queue.Full:+ pass+ except Exception:+ pass+ finally:+ try:+ stream.close()+ except Exception:+ pass++ # -- Lifecycle --------------------------------------------------------++ def _spawn(self):+ import socketserver++ from ministack.services.lambda_svc import (+ _provided_code_lock,+ _provided_runtime_code_dir,+ _provided_worker_env,+ )++ # A respawn used to abandon the previous generation's HTTP server,+ # thread and listening socket — one leaked set per bootstrap crash.+ self._teardown()++ code_dir = _provided_runtime_code_dir(self.code_zip)+ bootstrap_path = os.path.join(code_dir, "bootstrap")+ if not os.path.exists(bootstrap_path):+ raise RuntimeError("no bootstrap binary found")++ pending: queue.Queue = queue.Queue(maxsize=1)+ log_queue: queue.Queue = queue.Queue(maxsize=_PROVIDED_LOG_MAX_LINES)+ with self._state_lock:+ self._generation += 1+ generation = self._generation+ self._stopping = False+ self._first_poll.clear()+ self._init_settled.clear()+ self._init_error = None+ self._result = {}+ self._response_ready.clear()+ self._current_request_id = None+ self._pending = pending+ self._stderr_queue = log_queue++ class _QuietThreadingServer(socketserver.ThreadingTCPServer):+ daemon_threads = True+ allow_reuse_address = True++ def handle_error(self, request, client_address):+ _, exc, _ = sys.exc_info()+ if isinstance(exc, (BrokenPipeError, ConnectionResetError,+ ConnectionAbortedError)):+ return+ super().handle_error(request, client_address)++ try:+ # Threading server: /next long-polls, so a single-threaded server+ # would wedge the response POST behind the next poll.+ self._server = _QuietThreadingServer(+ ("127.0.0.1", 0), self._build_handler_class(generation, pending))+ port = self._server.server_address[1]+ self._server_thread = threading.Thread(+ target=self._server.serve_forever, kwargs={"poll_interval": 0.1},+ daemon=True, name=f"provided-api-{self.func_name}")+ self._server_thread.start()++ proc_env = _provided_worker_env(self.config, code_dir, port)++ # Spawn under the code lock: no fork may overlap an extraction write+ # elsewhere, or the child inherits the open write fd and execve fails+ # with ETXTBSY (#1051).+ with _provided_code_lock:+ self._proc = subprocess.Popen(+ [bootstrap_path],+ cwd=code_dir,+ env=proc_env,+ stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ )++ self._log_thread = threading.Thread(+ target=self._pump_output, args=(self._proc.stdout, log_queue),+ daemon=True, name=f"provided-log-{self.func_name}")+ self._log_thread.start()+ self._stderr_thread = self._log_thread++ self._await_init()+ except BaseException:+ # Never leave a half-built environment behind.+ self._teardown()+ raise++ self._start_time = time.time()+ logger.info("Lambda provided-runtime environment spawned for %s (cold start)",+ self.func_name)++ def _await_init(self) -> None:+ """Wait for the bootstrap to reach /next, bounded and interruptible.++ Returns as soon as init settles: a first poll, an /init/error POST, or+ the process exiting. Only a live but silent binary waits out+ ``_PROVIDED_INIT_TIMEOUT``.+ """+ deadline = time.monotonic() + _PROVIDED_INIT_TIMEOUT+ while not self._init_settled.wait(_PROVIDED_POLL):+ exit_code = self._proc.poll() if self._proc is not None else -1+ if exit_code is not None:+ raise RuntimeError(+ f"bootstrap exited during init with code {exit_code}"+ f"{self._init_log_suffix()}")+ if time.monotonic() >= deadline:+ raise RuntimeError(+ f"bootstrap did not reach the Runtime API within "+ f"{_PROVIDED_INIT_TIMEOUT:g}s{self._init_log_suffix()}")+ if self._init_error is not None:+ raise RuntimeError(f"init error: {self._init_error}")++ def _init_log_suffix(self) -> str:+ log = self._drain_stderr_bounded(first_line_wait=0.1)+ return f": {log}" if log else ""++ def invoke(self, event: dict, request_id: str, *, trace_id: str = None) -> dict:+ """Run one invocation on this environment.++ ``trace_id`` is per-invocation X-Ray context, passed separately rather+ than through a reserved key in ``event``: the payload belongs to the+ caller. It leaves as the ``Lambda-Runtime-Trace-Id`` header, where a+ custom runtime expects it.+ """+ with self._lock:+ cold = False+ if self._proc is None or self._proc.poll() is not None:+ self._spawn()+ cold = True+ self._cold = False++ timeout = self.config.get("Timeout", 30)+ generation = self._generation++ with self._state_lock:+ self._result = {}+ self._response_ready.clear()+ self._current_request_id = request_id+ pending = self._pending+ deadline_ms = int((time.time() + timeout) * 1000)+ pending.put((request_id, event, deadline_ms, trace_id))++ deadline = time.monotonic() + timeout+ failure = None+ while not self._response_ready.wait(+ min(_PROVIDED_POLL, max(0.0, deadline - time.monotonic()))):+ proc = self._proc+ if proc is None or proc.poll() is not None:+ # The process can exit after sending its response but+ # before the HTTP handler thread records it.+ if self._response_ready.wait(_PROVIDED_POLL):+ break+ failure = "Runtime exited before returning a response"+ break+ if time.monotonic() >= deadline:+ failure = f"Task timed out after {timeout}.00 seconds"+ break+ if failure is not None:+ logger.warning("Lambda %s: %s", self.func_name, failure)+ self._teardown()+ return {+ "status": "error",+ "error": failure,+ "error_payload": {"errorMessage": failure, "errorType": "Runtime.ExitError"},+ "cold_start": cold,+ "log": self._drain_stderr(),+ }++ with self._state_lock:+ result, self._result = self._result, {}+ self._current_request_id = None+ init_failed = self._init_error is not None+ log = self._drain_stderr_bounded()+ # An environment whose process is gone cannot serve the next+ # invocation; drop it now so its server and threads go with it.+ died = (self._proc is None or self._proc.poll() is not None+ or generation != self._generation)++ if "error" in result:+ # A handler error does not poison the environment on AWS — the+ # runtime reports it and goes back to polling /next. Only an+ # init failure (or a dead process) means it is unusable.+ if init_failed or died:+ self._teardown()+ err = result["error"]+ return {+ "status": "error",+ "error": (err.get("errorMessage") if isinstance(err, dict)+ else str(err)),+ "error_payload": err,+ "cold_start": cold,+ "log": log,+ }++ if died:+ self._teardown()++ return {+ "status": "ok",+ "result": result.get("response"),+ "cold_start": cold,+ "log": log,+ }++ def _teardown(self):+ """Destroy the current generation: process, server, threads.++ Idempotent. Buffered log lines are kept so the invocation that+ triggered the teardown can still report them.+ """+ with self._state_lock:+ self._stopping = True+ self._current_request_id = None+ proc, self._proc = self._proc, None+ _signal(proc)+ _collect(proc, time.monotonic() + _REAP_GRACE)+ self._shutdown_server()+ self._join_log_thread()++ def _join_log_thread(self) -> None:+ thread, self._log_thread = self._log_thread, None+ self._stderr_thread = None+ # The pipe closes with the process, so the pump ends on its own; the+ # join only keeps it from outliving the generation.+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout=1.0)++ def _shutdown_server(self):+ server, self._server = self._server, None+ thread, self._server_thread = self._server_thread, None+ if server is not None:+ try:+ server.shutdown()+ except Exception:+ pass+ try:+ server.server_close()+ except Exception:+ pass+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout=2.0)++ def _discard_tmpdir(self):+ # kill_workers() reaps the process and then calls this; piggyback the+ # server teardown so a reaped worker leaves no listening socket or+ # thread behind. The code dir is the shared content-addressed cache+ # from _provided_runtime_code_dir — nothing to remove here.+ with self._state_lock:+ self._stopping = True+ self._shutdown_server()+ self._join_log_thread()diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex da6f54b1..d19cd7d2 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -4836,7 +4836,14 @@ def _execute_function_dispatch(func: dict, config: dict, event: dict,else:runtime = config.get("Runtime", "python3.12")if runtime.startswith("provided"):- result = _execute_function_provided(func, event)+ # Durable invocations need a per-call environment (the+ # DurableExecutionArn / CheckpointToken change every invoke), and a+ # reused environment's env is fixed at spawn — so they keep the+ # one-shot executor, exactly as durable python/nodejs does above.+ if _durable_ctx.get():+ result = _execute_function_provided(func, event)+ else:+ result = _execute_function_provided_warm(func, event, request_id)elif (runtime.startswith("python") or runtime.startswith("nodejs")) \and not _durable_ctx.get():# Warm pool reuses worker subprocesses whose env was fixed at@@ -5051,6 +5058,98 @@ def _execute_function_warm(func: dict, event: dict) -> dict:release_worker(worker)+def _provided_worker_env(config: dict, code_dir: str, port: int) -> dict:+ """Build the process environment for a ``provided.*`` bootstrap binary.++ Shared by the one-shot executor and the warm ``ProvidedWorker`` so the two+ paths cannot drift. Per-invocation values (X-Ray trace ID) are deliberately+ absent: a reused environment cannot carry them in env, and the Runtime API+ has headers for exactly that. The one-shot executor adds its per-call+ overlays after calling this helper. Custom runtimes have no Python/Node+ shim to propagate MiniStack's per-call recursion depth; the one-shot path+ retains its legacy spawn-time depth overlay instead of freezing it here.+ """+ env_vars = _runtime_env_vars(config)+ proc_env = dict(os.environ)+ proc_env.update({+ "AWS_LAMBDA_RUNTIME_API": f"127.0.0.1:{port}",+ "AWS_DEFAULT_REGION": get_region(),+ "AWS_REGION": get_region(),+ "AWS_LAMBDA_FUNCTION_NAME": config.get("FunctionName", "unknown"),+ "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": str(config.get("MemorySize", 128)),+ "AWS_LAMBDA_FUNCTION_VERSION": config.get("Version", "$LATEST"),+ "AWS_LAMBDA_LOG_STREAM_NAME": new_uuid(),+ "LAMBDA_TASK_ROOT": code_dir,+ "_HANDLER": config.get("Handler", "bootstrap"),+ })+ proc_env.update(execution_credentials(config))+ proc_env.update(env_vars)+ proc_env.update(_durable_env_overlay())+ # Override AWS_ENDPOINT_URL *after* function env vars so Lambda binaries+ # always call back to this MiniStack instance.+ endpoint = os.environ.get("AWS_ENDPOINT_URL", "")+ if not endpoint:+ hostname = os.environ.get("LOCALSTACK_HOSTNAME", "")+ if hostname:+ endpoint = _normalize_endpoint_url(hostname)+ if endpoint:+ proc_env["AWS_ENDPOINT_URL"] = endpoint+ return proc_env+++def _execute_function_provided_warm(func: dict, event: dict,+ request_id: str | None = None) -> dict:+ """Execute a ``provided.*`` Lambda on a pooled, reused environment."""+ config = func.get("config") or func+ code_zip = func.get("code_zip")+ if not code_zip:+ return {"body": {"statusCode": 200, "body": "Mock response - no code deployed"}}++ func_name = config.get("FunctionName", "unknown")+ qualifier = config.get("Version", "$LATEST")+ _ensure_reaper_thread()+ worker, reason = acquire_worker(func_name, config, code_zip, qualifier=qualifier)+ if worker is None and reason == "func_cap":+ return _throttle_response(+ reason_code="ReservedFunctionConcurrentInvocationLimitExceeded",+ msg=f"Rate Exceeded: function {func_name} warm-worker ceiling reached",+ )+ try:+ # Invocation metadata belongs in Runtime API headers, not in the user+ # payload (which need not be a dict and may contain similarly named keys).+ result = worker.invoke(+ event, request_id or new_uuid(),+ trace_id=_xray_trace_id_for_invocation(config),+ )+ if result.get("status") == "ok":+ return {"body": result.get("result"), "log": result.get("log", "")}+ payload = result.get("error_payload")+ if isinstance(payload, dict):+ return {"body": payload, "error": True, "log": result.get("log", "")}+ error_msg = result.get("error", "Unknown error")+ error_type = ("Runtime.ExitError" if "timed out" in error_msg.lower()+ else "Runtime.HandlerError")+ return {+ "body": {"errorMessage": error_msg, "errorType": error_type},+ "error": True,+ "log": result.get("log", ""),+ }+ except Exception as e:+ logger.error("Warm provided-runtime execution error for %s: %s", func_name, e)+ account, region = _account_region_from_function_config(config)+ invalidate_worker(func_name, qualifier=qualifier, account=account, region=region)+ worker = None # invalidation already removed and reaped the worker+ # Do not transparently invoke again: the handler may already have+ # performed side effects before its environment failed.+ return {+ "body": {"errorMessage": str(e), "errorType": type(e).__name__},+ "error": True,+ "log": "",+ }+ finally:+ release_worker(worker)++def _execute_function_provided(func: dict, event: dict) -> dict:"""Execute a provided-runtime Lambda (Go/Rust binary) via a minimal Lambda Runtime API."""config = func.get("config") or func@@ -5059,7 +5158,6 @@ def _execute_function_provided(func: dict, event: dict) -> dict:return {"body": {"statusCode": 200, "body": "Mock response - no code deployed"}}timeout = config.get("Timeout", 30)- env_vars = _runtime_env_vars(config)try:import http.server@@ -5164,22 +5262,7 @@ def _execute_function_provided(func: dict, event: dict) -> dict:server_ready.wait(timeout=5)try:- # Build environment for the Lambda binary- proc_env = dict(os.environ)- proc_env.update({- "AWS_LAMBDA_RUNTIME_API": f"127.0.0.1:{port}",- "AWS_DEFAULT_REGION": get_region(),- "AWS_REGION": get_region(),- "AWS_LAMBDA_FUNCTION_NAME": config.get("FunctionName", "unknown"),- "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": str(config.get("MemorySize", 128)),- "AWS_LAMBDA_FUNCTION_VERSION": config.get("Version", "$LATEST"),- "AWS_LAMBDA_LOG_STREAM_NAME": new_uuid(),- "LAMBDA_TASK_ROOT": code_dir,- "_HANDLER": config.get("Handler", "bootstrap"),- })- proc_env.update(execution_credentials(config))- proc_env.update(env_vars)- proc_env.update(_durable_env_overlay())+ proc_env = _provided_worker_env(config, code_dir, port)# X-Ray active tracing. ``_execute_function_provided`` builds# ``proc_env`` per-invocation, so a per-call trace ID is safe# here (unlike the RIE pool). aws-xray-sdk reads this env var@@ -5188,19 +5271,6 @@ def _execute_function_provided(func: dict, event: dict) -> dict:if _xray_trace_id:proc_env["_X_AMZN_TRACE_ID"] = _xray_trace_idproc_env[INVOKE_DEPTH_ENV] = str(_invoke_depth.get())- # Override AWS_ENDPOINT_URL *after* function env vars so- # Lambda binaries always call back to this MiniStack- # instance. Function-level env vars may carry the- # host-mapped URL which is unreachable from inside the- # container.- endpoint = os.environ.get("AWS_ENDPOINT_URL", "")- if not endpoint:- hostname = os.environ.get("LOCALSTACK_HOSTNAME", "")- if hostname:- endpoint = _normalize_endpoint_url(hostname)- if endpoint:- proc_env["AWS_ENDPOINT_URL"] = endpoint-# Spawn under the code lock: no fork may overlap an extraction# write elsewhere, or the child inherits the open write fd and# execve fails with ETXTBSY (#1051).diff --git a/tests/test_lambda_provided_dispatch.py b/tests/test_lambda_provided_dispatch.pynew file mode 100644index 00000000..cdda61fe--- /dev/null+++ b/tests/test_lambda_provided_dispatch.py@@ -0,0 +1,187 @@+"""Local custom-runtime routing and pool integration; no running server required."""++import time+from unittest.mock import Mock++import pytest++from ministack.core import lambda_runtime+from ministack.services import lambda_svc+++def _config(account="111122223333", region="us-east-1", version="$LATEST"):+ return {+ "FunctionName": "provided-pool-test",+ "FunctionArn": f"arn:aws:lambda:{region}:{account}:function:provided-pool-test",+ "Runtime": "provided.al2023",+ "Version": version,+ "Timeout": 2,+ "Handler": "bootstrap",+ }+++def isolated_pool(monkeypatch):+ monkeypatch.setattr(lambda_runtime, "_workers", {})+ monkeypatch.setattr(lambda_svc, "_ensure_reaper_thread", lambda: None)+ try:+ yield+ finally:+ lambda_runtime.reset()++[email protected]("event", [+ {"_x_amzn_trace_id": "user data", "value": 1}, [1, 2], "text", None,+])+def test_provided_metadata_does_not_mutate_payload(monkeypatch, event):+ worker = Mock()+ worker.invoke.return_value = {"status": "ok", "result": event, "log": "handler log"}+ monkeypatch.setattr(lambda_svc, "_ensure_reaper_thread", lambda: None)+ monkeypatch.setattr(lambda_svc, "acquire_worker", Mock(return_value=(worker, "spawn")))+ release = Mock()+ monkeypatch.setattr(lambda_svc, "release_worker", release)+ monkeypatch.setattr(lambda_svc, "_xray_trace_id_for_invocation", lambda config: "trace-1")+ result = lambda_svc._execute_function_provided_warm(+ {"config": _config(), "code_zip": b"zip"}, event, "request-1",+ )+ worker.invoke.assert_called_once_with(event, "request-1", trace_id="trace-1")+ release.assert_called_once_with(worker)+ assert result == {"body": event, "log": "handler log"}+ if isinstance(event, dict):+ assert event["_x_amzn_trace_id"] == "user data"+++def test_provided_failure_is_scoped_and_not_retried(monkeypatch, isolated_pool):+ config = _config()+ failed, _ = lambda_runtime.acquire_worker(config["FunctionName"], config, b"zip")+ lambda_runtime.release_worker(failed)+ fail = Mock(side_effect=RuntimeError("bootstrap crashed"))+ monkeypatch.setattr(failed, "invoke", fail)+ unrelated = []+ for account, region, version in [+ ("999900001111", "us-east-1", "$LATEST"),+ ("111122223333", "eu-west-1", "$LATEST"),+ ("111122223333", "us-east-1", "1"),+ ]:+ other = _config(account, region, version)+ worker, _ = lambda_runtime.acquire_worker(+ other["FunctionName"], other, b"zip", qualifier=version,+ )+ unrelated.append(worker)+ fallback = Mock()+ monkeypatch.setattr(lambda_svc, "_execute_function_provided", fallback)+ result = lambda_svc._execute_function_provided_warm({"config": config, "code_zip": b"zip"}, {})+ assert result["error"] is True+ assert result["body"]["errorMessage"] == "bootstrap crashed"+ assert fail.call_count == 1+ fallback.assert_not_called()+ remaining = [w for entries in lambda_runtime._workers.values() for w in entries]+ assert remaining == unrelated+ assert all(w.in_use for w in unrelated)+++def test_provided_concurrent_leases_and_reuse(isolated_pool):+ config = _config()+ first, _ = lambda_runtime.acquire_worker(config["FunctionName"], config, b"zip")+ second, _ = lambda_runtime.acquire_worker(config["FunctionName"], config, b"zip")+ assert isinstance(first, lambda_runtime.ProvidedWorker)+ assert isinstance(second, lambda_runtime.ProvidedWorker)+ assert first is not second+ lambda_runtime.release_worker(first)+ reused, reason = lambda_runtime.acquire_worker(config["FunctionName"], config, b"zip")+ assert reused is first+ assert reason == "reused"+ lambda_runtime.release_worker(reused)+ lambda_runtime.release_worker(second)++[email protected]("mode,target", [+ ("local", "_execute_function_provided_warm"),+ ("durable", "_execute_function_provided"),+ ("docker", "_execute_function_docker"),+ ("strict", "_execute_function_docker"),+ ("image", "_execute_function_docker"),+ ("proxy", "_execute_function_proxy"),+])+def test_provided_dispatch_preserves_other_executors(monkeypatch, mode, target):+ monkeypatch.setattr(lambda_svc, "LAMBDA_EXECUTOR", "docker" if mode == "docker" else "local")+ monkeypatch.setattr(lambda_svc, "LAMBDA_STRICT", mode == "strict")+ monkeypatch.setattr(lambda_svc, "_proxy_url_for", lambda config: "http://proxy" if mode == "proxy" else None)+ monkeypatch.setattr(lambda_svc, "_emit_lambda_logs", Mock())+ names = ["_execute_function_provided_warm", "_execute_function_provided",+ "_execute_function_docker", "_execute_function_proxy"]+ executors = {name: Mock(return_value={"body": name}) for name in names}+ for name, executor in executors.items():+ monkeypatch.setattr(lambda_svc, name, executor)+ config = _config()+ if mode == "image":+ config.update(PackageType="Image", ImageUri="example:latest")+ func = {"config": config, "code_zip": b"zip"}+ token = lambda_svc._durable_ctx.set({"test": True} if mode == "durable" else None)+ try:+ result = lambda_svc._execute_function_dispatch(func, config, {}, "request-1", time.time())+ finally:+ lambda_svc._durable_ctx.reset(token)+ assert result == {"body": target}+ for name, executor in executors.items():+ assert executor.call_count == (1 if name == target else 0)+ if mode == "local":+ executors[target].assert_called_once_with(func, {}, "request-1")+++def test_provided_env_keeps_function_vars_and_endpoint_precedence(monkeypatch):+ config = _config()+ config.update(MemorySize=256, Environment={"Variables": {+ "CUSTOM": "value", "AWS_ENDPOINT_URL": "http://wrong:4566",+ }})+ monkeypatch.setenv("AWS_ENDPOINT_URL", "http://ministack:4566")+ monkeypatch.setattr(lambda_svc, "get_region", lambda: "us-east-1")+ token = lambda_svc._durable_ctx.set(None)+ try:+ env = lambda_svc._provided_worker_env(config, "/code", 12345)+ finally:+ lambda_svc._durable_ctx.reset(token)+ assert env["AWS_LAMBDA_RUNTIME_API"] == "127.0.0.1:12345"+ assert env["AWS_LAMBDA_FUNCTION_NAME"] == config["FunctionName"]+ assert env["AWS_LAMBDA_FUNCTION_MEMORY_SIZE"] == "256"+ assert env["AWS_ACCESS_KEY_ID"] == "111122223333"+ assert env["AWS_REGION"] == "us-east-1"+ assert env["LAMBDA_TASK_ROOT"] == "/code"+ assert env["CUSTOM"] == "value"+ assert env["AWS_ENDPOINT_URL"] == "http://ministack:4566"+++def test_provided_env_uses_execution_role_credentials(monkeypatch):+ config = _config()+ credentials = {+ "AWS_ACCESS_KEY_ID": "ASIATESTROLE",+ "AWS_SECRET_ACCESS_KEY": "role-secret",+ "AWS_SESSION_TOKEN": "role-session",+ }+ resolve = Mock(return_value=credentials)+ monkeypatch.setattr(lambda_svc, "execution_credentials", resolve)+ env = lambda_svc._provided_worker_env(config, "/code", 12345)+ resolve.assert_called_once_with(config)+ assert {key: env[key] for key in credentials} == credentials++[email protected]("operation", ["code", "configuration", "delete"])+def test_function_changes_invalidate_provided_workers(monkeypatch, isolated_pool, operation):+ config = _config()+ name = config["FunctionName"]+ monkeypatch.setattr(lambda_svc, "_functions", {name: {"config": config, "code_zip": b"zip"}})+ monkeypatch.setattr(lambda_svc, "get_account_id", lambda: "111122223333")+ monkeypatch.setattr(lambda_svc, "get_region", lambda: "us-east-1")+ monkeypatch.setattr(lambda_svc, "_pool_kill_function", Mock())+ monkeypatch.setattr(lambda_svc, "_sweep_extract_cache", Mock())+ monkeypatch.setattr(lambda_svc, "_schedule_state_transition", Mock())+ worker, _ = lambda_runtime.acquire_worker(name, config, b"zip")+ lambda_runtime.release_worker(worker)+ if operation == "code":+ result = lambda_svc._update_code(name, {})+ elif operation == "configuration":+ result = lambda_svc._update_config(name, {"Environment": {"Variables": {"UPDATED": "yes"}}})+ else:+ result = lambda_svc._delete_function(name, {})+ assert result[0] in (200, 204)+ assert not lambda_runtime._workersdiff --git a/tests/test_lambda_provided_worker.py b/tests/test_lambda_provided_worker.pynew file mode 100644index 00000000..f5498c66--- /dev/null+++ b/tests/test_lambda_provided_worker.py@@ -0,0 +1,745 @@+"""+Unit tests for the warm ``provided.*`` execution environment+(``ministack.core.lambda_runtime.ProvidedWorker``).++Every test drives a *real* bootstrap: a stdlib-only Python script that speaks+the Lambda Runtime API over ``AWS_LAMBDA_RUNTIME_API`` exactly as a Go or Rust+binary would. No Go toolchain, no Docker and no running MiniStack are needed.++Coverage:+ * environment reuse across invocations, with per-invocation trace context+ * the caller's event is never mutated to carry the trace ID+ * continuous draining of stdout *and* stderr (a pipe that fills would+ otherwise wedge the bootstrap), plus the bounded log buffer+ * a crashed bootstrap is replaced, and its server/socket/threads go with it+ * init errors and instant exits fail fast instead of burning the init timeout+ * a timed-out invocation tears the environment down and the next one recovers+ * stale / duplicate / cross-generation request IDs are rejected (400)+ * teardown leaves no process, listening socket or thread behind+"""++import socket+import sys+import threading+import time+import zipfile+from io import BytesIO++import pytest++from ministack.core import lambda_runtime+from ministack.core.lambda_runtime import (+ ProvidedWorker,+ acquire_worker,+ kill_workers,+ release_worker,+ reset,+)++# ---------------------------------------------------------------------------+# Bootstrap fixtures (stdlib only, run by the host Python interpreter)+# ---------------------------------------------------------------------------++_PREAMBLE = '''#!{python}+import json, os, sys, time, urllib.request, urllib.error++API = os.environ["AWS_LAMBDA_RUNTIME_API"]+PORT = int(API.rsplit(":", 1)[1])+++def _call(path, data=None, method=None):+ url = "http://%s/2018-06-01%s" % (API, path)+ req = urllib.request.Request(url, data=data, method=method)+ try:+ resp = urllib.request.urlopen(req, timeout=30)+ return resp.getcode(), resp.headers, resp.read()+ except urllib.error.HTTPError as exc:+ return exc.code, exc.headers, exc.read()+++def next_invocation():+ code, headers, body = _call("/runtime/invocation/next")+ if code != 200:+ raise SystemExit(0)+ return headers, json.loads(body or b"null")+++def post_response(rid, payload):+ return _call("/runtime/invocation/%s/response" % rid,+ data=json.dumps(payload).encode(), method="POST")[0]+++def post_error(rid, payload):+ return _call("/runtime/invocation/%s/error" % rid,+ data=json.dumps(payload).encode(), method="POST")[0]+++def post_init_error(payload):+ return _call("/runtime/init/error",+ data=json.dumps(payload).encode(), method="POST")[0]+'''+++def _bootstrap(body: str) -> bytes:+ """Zip a bootstrap script whose body follows the Runtime API preamble."""+ script = _PREAMBLE.format(python=sys.executable) + "\n" + body+ buf = BytesIO()+ with zipfile.ZipFile(buf, "w") as archive:+ archive.writestr("bootstrap", script)+ return buf.getvalue()+++ECHO_BOOTSTRAP = _bootstrap('''+n = 0+while True:+ headers, event = next_invocation()+ n += 1+ rid = headers["Lambda-Runtime-Aws-Request-Id"]+ post_response(rid, {+ "pid": os.getpid(),+ "n": n,+ "port": PORT,+ "event": event,+ "request_id": rid,+ "trace": headers.get("Lambda-Runtime-Trace-Id"),+ "arn": headers.get("Lambda-Runtime-Invoked-Function-Arn"),+ "deadline": headers.get("Lambda-Runtime-Deadline-Ms"),+ })+''')+++def _config(**overrides):+ config = {+ "Runtime": "provided.al2023",+ "Handler": "bootstrap",+ "FunctionName": "provided-fn",+ "FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:provided-fn",+ "Timeout": 10,+ "MemorySize": 128,+ }+ config.update(overrides)+ return config++[email protected](autouse=True)+def isolated_runtime(monkeypatch, tmp_path):+ from ministack.services import lambda_svc++ monkeypatch.setattr(lambda_runtime, "_workers", {})+ monkeypatch.setattr(lambda_svc, "_PROVIDED_CODE_CACHE", str(tmp_path / "code"))+ monkeypatch.setattr(lambda_svc, "_provided_code_dirs", {})+ yield+ reset()+++def worker_factory():+ """Build ProvidedWorkers and guarantee they are torn down."""+ built: list = []++ def _make(code_zip: bytes, **config_overrides) -> ProvidedWorker:+ worker = ProvidedWorker("provided-fn", _config(**config_overrides), code_zip)+ built.append(worker)+ return worker++ yield _make+ kill_workers(built)+ reset()+++def _port_is_closed(port: int) -> bool:+ for _ in range(50):+ sock = socket.socket()+ sock.settimeout(0.5)+ try:+ sock.connect(("127.0.0.1", port))+ except OSError:+ return True+ finally:+ sock.close()+ time.sleep(0.05)+ return False+++# ---------------------------------------------------------------------------+# Reuse + per-invocation trace context+# ---------------------------------------------------------------------------+++def test_environment_is_reused_and_trace_is_per_invocation(worker_factory):+ """Second invocation lands on the same process, with its own trace ID."""+ worker = worker_factory(ECHO_BOOTSTRAP)++ first = worker.invoke({"k": 1}, "req-1", trace_id="Root=1-aaa;Sampled=1")+ second = worker.invoke({"k": 2}, "req-2", trace_id="Root=1-bbb;Sampled=1")+ third = worker.invoke({"k": 3}, "req-3")++ assert first["status"] == "ok" and second["status"] == "ok"+ assert first["cold_start"] is True+ assert second["cold_start"] is False and third["cold_start"] is False++ assert first["result"]["pid"] == second["result"]["pid"] == third["result"]["pid"]+ assert [r["result"]["n"] for r in (first, second, third)] == [1, 2, 3]++ # Request IDs and trace IDs are per invocation, never carried over.+ assert first["result"]["request_id"] == "req-1"+ assert second["result"]["request_id"] == "req-2"+ assert first["result"]["trace"] == "Root=1-aaa;Sampled=1"+ assert second["result"]["trace"] == "Root=1-bbb;Sampled=1"+ assert third["result"]["trace"] is None+ assert first["result"]["arn"] == worker.config["FunctionArn"]+++def test_trace_id_does_not_touch_the_event_payload(worker_factory):+ """The event is the caller's; trace context rides the Runtime API header.++ A user event that happens to contain the key the old implementation+ reserved must reach the handler untouched.+ """+ worker = worker_factory(ECHO_BOOTSTRAP)+ event = {"_x_amzn_trace_id": "user-supplied", "hello": "world"}++ result = worker.invoke(event, "req-1", trace_id="Root=1-ccc")++ assert result["status"] == "ok"+ # Delivered verbatim ...+ assert result["result"]["event"] == {+ "_x_amzn_trace_id": "user-supplied", "hello": "world"}+ # ... and the header carries the real trace ID.+ assert result["result"]["trace"] == "Root=1-ccc"+ # The caller's dict was not mutated.+ assert event == {"_x_amzn_trace_id": "user-supplied", "hello": "world"}+++# ---------------------------------------------------------------------------+# Logs: both pipes drained continuously, buffer bounded+# ---------------------------------------------------------------------------+++CHATTY_BOOTSTRAP = _bootstrap('''+LINE = "x" * 120+while True:+ headers, event = next_invocation()+ rid = headers["Lambda-Runtime-Aws-Request-Id"]+ count = event["lines"]+ for i in range(count):+ sys.stdout.write("OUT-%d %s\\n" % (i, LINE))+ sys.stderr.write("ERR-%d %s\\n" % (i, LINE))+ sys.stdout.flush()+ sys.stderr.flush()+ time.sleep(0.2)+ post_response(rid, {"logged": count})+''')+++def test_large_log_volume_does_not_wedge_the_bootstrap(worker_factory):+ """~500KB across both pipes: an undrained pipe would block the child.++ stdout is drained as logs too — a custom runtime writes there — and both+ streams are merged into one log buffer.+ """+ worker = worker_factory(CHATTY_BOOTSTRAP, Timeout=30)++ result = worker.invoke({"lines": 2000}, "req-1")++ assert result["status"] == "ok"+ assert result["result"] == {"logged": 2000}+ log = result["log"]+ assert "OUT-0 " in log and "ERR-0 " in log+ assert "OUT-1999 " in log and "ERR-1999 " in log++ # And the environment survives it.+ again = worker.invoke({"lines": 1}, "req-2")+ assert again["status"] == "ok"+ assert again["cold_start"] is False+++def test_log_buffer_is_bounded_and_keeps_the_newest_lines(worker_factory, monkeypatch):+ monkeypatch.setattr(lambda_runtime, "_PROVIDED_LOG_MAX_LINES", 50)+ worker = worker_factory(CHATTY_BOOTSTRAP, Timeout=30)++ result = worker.invoke({"lines": 400}, "req-1")++ assert result["status"] == "ok"+ lines = [line for line in result["log"].splitlines() if line]+ assert len(lines) <= 50+ # Oldest dropped, newest kept.+ assert "OUT-0 " not in result["log"]+ assert any(line.startswith("ERR-399 ") or line.startswith("OUT-399 ")+ for line in lines)+++# ---------------------------------------------------------------------------+# Crash / restart+# ---------------------------------------------------------------------------+++CRASH_BOOTSTRAP = _bootstrap('''+headers, event = next_invocation()+rid = headers["Lambda-Runtime-Aws-Request-Id"]+post_response(rid, {"pid": os.getpid(), "port": PORT})+sys.stderr.write("bye\\n")+sys.stderr.flush()+os._exit(9)+''')+++def test_crashed_bootstrap_is_replaced_without_leaking_its_server(worker_factory):+ worker = worker_factory(CRASH_BOOTSTRAP)+ threads_before = threading.active_count()++ first = worker.invoke({}, "req-1")+ assert first["status"] == "ok"+ first_port = first["result"]["port"]+ first_pid = first["result"]["pid"]++ # The bootstrap exits right after responding; the next invocation gets a+ # brand new environment, and the dead one's HTTP server is gone.+ second = worker.invoke({}, "req-2")+ assert second["status"] == "ok"+ assert second["cold_start"] is True+ assert second["result"]["pid"] != first_pid+ assert second["result"]["port"] != first_port+ assert _port_is_closed(first_port), "leaked Runtime API server from dead generation"++ worker.kill()+ assert _port_is_closed(second["result"]["port"])+ # Two generations, no accumulated threads.+ for _ in range(50):+ if threading.active_count() <= threads_before + 1:+ break+ time.sleep(0.1)+ assert threading.active_count() <= threads_before + 1+++# ---------------------------------------------------------------------------+# Init failures are detected promptly+# ---------------------------------------------------------------------------+++INIT_ERROR_BOOTSTRAP = _bootstrap('''+sys.stderr.write("init blew up\\n")+sys.stderr.flush()+post_init_error({"errorMessage": "cannot load config", "errorType": "Init.Error"})+sys.exit(1)+''')++INSTANT_EXIT_BOOTSTRAP = _bootstrap('''+sys.stderr.write("missing shared library\\n")+sys.stderr.flush()+sys.exit(3)+''')+++def test_init_error_fails_fast_and_leaves_nothing_running(worker_factory):+ worker = worker_factory(INIT_ERROR_BOOTSTRAP)++ started = time.monotonic()+ with pytest.raises(RuntimeError, match="init error"):+ worker.invoke({}, "req-1")+ elapsed = time.monotonic() - started++ assert elapsed < lambda_runtime._PROVIDED_INIT_TIMEOUT / 2+ assert worker._proc is None+ assert worker._server is None+ assert worker._server_thread is None+++def test_bootstrap_that_exits_immediately_fails_fast(worker_factory):+ worker = worker_factory(INSTANT_EXIT_BOOTSTRAP)++ started = time.monotonic()+ with pytest.raises(RuntimeError, match="exited during init with code 3"):+ worker.invoke({}, "req-1")+ elapsed = time.monotonic() - started++ assert elapsed < lambda_runtime._PROVIDED_INIT_TIMEOUT / 2+ assert worker._proc is None and worker._server is None+++def test_init_timeout_is_bounded(worker_factory, monkeypatch):+ """A binary that starts but never polls /next is given up on."""+ monkeypatch.setattr(lambda_runtime, "_PROVIDED_INIT_TIMEOUT", 1.0)+ silent = _bootstrap('time.sleep(60)\n')+ worker = worker_factory(silent)++ started = time.monotonic()+ with pytest.raises(RuntimeError, match="did not reach the Runtime API"):+ worker.invoke({}, "req-1")+ elapsed = time.monotonic() - started++ assert 1.0 <= elapsed < 8.0+ assert worker._proc is None and worker._server is None+++# ---------------------------------------------------------------------------+# Timeout + recovery+# ---------------------------------------------------------------------------+++SLOW_ONCE_BOOTSTRAP_TEMPLATE = '''+MARKER = {marker!r}+while True:+ headers, event = next_invocation()+ rid = headers["Lambda-Runtime-Aws-Request-Id"]+ if not os.path.exists(MARKER):+ open(MARKER, "w").close()+ sys.stderr.write("going to sleep\\n")+ sys.stderr.flush()+ time.sleep(30)+ post_response(rid, {{"pid": os.getpid(), "port": PORT}})+'''+++def test_timeout_kills_environment_and_next_invocation_recovers(worker_factory, tmp_path):+ marker = str(tmp_path / "slept")+ worker = worker_factory(+ _bootstrap(SLOW_ONCE_BOOTSTRAP_TEMPLATE.format(marker=marker)),+ Timeout=1,+ )++ started = time.monotonic()+ timed_out = worker.invoke({}, "req-1")+ elapsed = time.monotonic() - started++ assert timed_out["status"] == "error"+ assert timed_out["error"] == "Task timed out after 1.00 seconds"+ assert "going to sleep" in timed_out["log"]+ assert elapsed < 8.0+ assert worker._proc is None and worker._server is None++ # A fresh environment serves the next invocation, and the marker makes the+ # replacement take the fast path.+ recovered = worker.invoke({}, "req-2")+ assert recovered["status"] == "ok"+ assert recovered["cold_start"] is True+++# ---------------------------------------------------------------------------+# Request-ID validation and stale-response isolation+# ---------------------------------------------------------------------------+++BAD_REQUEST_ID_BOOTSTRAP = _bootstrap('''+while True:+ headers, event = next_invocation()+ rid = headers["Lambda-Runtime-Aws-Request-Id"]+ codes = {+ "bogus": post_response("not-a-real-request-id", {"stolen": True}),+ "empty": post_error("", {"errorMessage": "nope"}),+ }+ codes["real"] = post_response(rid, {"codes": codes, "request_id": rid})+ if codes["real"] != 202:+ post_error(rid, {"errorMessage": "response rejected: %s" % codes})+''')+++def test_unknown_request_ids_are_rejected_not_delivered(worker_factory):+ worker = worker_factory(BAD_REQUEST_ID_BOOTSTRAP)++ result = worker.invoke({}, "req-1")++ assert result["status"] == "ok"+ # The forged IDs got 400s; only the real one was accepted.+ assert result["result"]["codes"] == {"bogus": 400, "empty": 404}+ assert result["result"]["request_id"] == "req-1"+++DUPLICATE_RESPONSE_BOOTSTRAP = _bootstrap('''+while True:+ headers, event = next_invocation()+ rid = headers["Lambda-Runtime-Aws-Request-Id"]+ first = post_response(rid, {"which": "first"})+ second = post_response(rid, {"which": "second", "first_code": first})+ sys.stderr.write("dup-code=%s\\n" % second)+ sys.stderr.flush()+''')+++def test_duplicate_response_for_same_request_id_is_rejected(worker_factory):+ worker = worker_factory(DUPLICATE_RESPONSE_BOOTSTRAP)++ first = worker.invoke({}, "req-1")+ assert first["status"] == "ok"+ assert first["result"] == {"which": "first"}++ # The duplicate got a 400 and, crucially, did not become the *next*+ # invocation's result.+ second = worker.invoke({}, "req-2")+ assert second["status"] == "ok"+ assert second["result"] == {"which": "first"}+ assert "dup-code=400" in "\n".join([first["log"], second["log"]])+++def test_results_from_a_dead_generation_are_ignored():+ """A late POST from a torn-down environment cannot satisfy its successor."""+ worker = ProvidedWorker("provided-fn", _config(), b"")+ worker._generation = 7+ worker._current_request_id = "req-live"++ # Same request ID, previous generation.+ assert worker._record_result(6, "req-live", "response", {"stale": True}) is False+ assert worker._response_ready.is_set() is False+ assert worker._result == {}++ # Wrong request ID, current generation.+ assert worker._record_result(7, "req-old", "response", {"stale": True}) is False+ assert worker._response_ready.is_set() is False++ # The live one is accepted exactly once.+ assert worker._record_result(7, "req-live", "response", {"ok": True}) is True+ assert worker._result == {"response": {"ok": True}}+ assert worker._record_result(7, "req-live", "response", {"again": True}) is False+ assert worker._result == {"response": {"ok": True}}+++def test_init_error_from_a_dead_generation_is_ignored():+ worker = ProvidedWorker("provided-fn", _config(), b"")+ worker._generation = 3++ worker._record_init_error(2, {"errorMessage": "stale"})+ assert worker._init_error is None+ assert worker._init_settled.is_set() is False++ worker._record_init_error(3, {"errorMessage": "live"})+ assert worker._init_error == {"errorMessage": "live"}+ assert worker._init_settled.is_set() is True+++# ---------------------------------------------------------------------------+# Cleanup / pool contract+# ---------------------------------------------------------------------------+++def test_kill_reaps_process_server_and_threads(worker_factory):+ worker = worker_factory(ECHO_BOOTSTRAP)+ threads_before = threading.active_count()++ result = worker.invoke({}, "req-1")+ port = result["result"]["port"]+ proc = worker._proc+ log_thread = worker._log_thread+ assert proc.poll() is None++ worker.kill()++ assert proc.poll() is not None, "bootstrap process not reaped"+ assert worker._proc is None+ assert worker._server is None and worker._server_thread is None+ assert worker._log_thread is None+ assert _port_is_closed(port), "Runtime API socket still listening after kill"+ log_thread.join(timeout=2.0)+ assert not log_thread.is_alive()+ for _ in range(50):+ if threading.active_count() <= threads_before:+ break+ time.sleep(0.1)+ assert threading.active_count() <= threads_before+++def test_pool_contract_lease_reuse_and_reset():+ """provided.* functions use the same acquire/release pool as the rest."""+ config = _config()+ try:+ worker, reason = acquire_worker("provided-fn", config, ECHO_BOOTSTRAP)+ assert isinstance(worker, ProvidedWorker)+ assert reason == "spawn"+ assert worker.in_use is True++ first = worker.invoke({}, "req-1")+ assert first["status"] == "ok"+ port = first["result"]["port"]++ # A second lease while the first is held gets a *separate* environment.+ other, other_reason = acquire_worker("provided-fn", config, ECHO_BOOTSTRAP)+ assert other is not worker and other_reason == "spawn"+ release_worker(other)++ release_worker(worker)+ again, reason = acquire_worker("provided-fn", config, ECHO_BOOTSTRAP)+ assert reason == "reused"+ assert again is worker+ assert again.invoke({}, "req-2")["result"]["port"] == port+ release_worker(again)+ finally:+ reset()++ assert _port_is_closed(port)+++def test_concurrent_invocations_use_separate_leased_environments():+ """Two leases run at the same time on two processes, results not crossed."""+ config = _config()+ barrier = threading.Barrier(2, timeout=30)+ results: dict = {}++ try:+ workers = []+ for _ in range(2):+ worker, reason = acquire_worker("provided-fn", config, ECHO_BOOTSTRAP)+ assert reason == "spawn"+ workers.append(worker)++ def _run(index, worker):+ barrier.wait()+ results[index] = worker.invoke({"i": index}, f"req-{index}",+ trace_id=f"Root=1-{index}")++ threads = [threading.Thread(target=_run, args=(i, w))+ for i, w in enumerate(workers)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=60)+ assert not thread.is_alive()++ assert set(results) == {0, 1}+ assert all(r["status"] == "ok" for r in results.values())+ assert results[0]["result"]["pid"] != results[1]["result"]["pid"]+ for index, result in results.items():+ assert result["result"]["event"] == {"i": index}+ assert result["result"]["request_id"] == f"req-{index}"+ assert result["result"]["trace"] == f"Root=1-{index}"+ for worker in workers:+ release_worker(worker)+ finally:+ reset()++ for result in results.values():+ assert _port_is_closed(result["result"]["port"])+++def test_idle_reaper_and_reset_release_provided_environments():+ config = _config()+ try:+ first, _ = acquire_worker("provided-fn", config, ECHO_BOOTSTRAP)+ second, _ = acquire_worker("provided-fn", config, ECHO_BOOTSTRAP)+ ports = [w.invoke({}, "req-1")["result"]["port"] for w in (first, second)]+ procs = [first._proc, second._proc]+ release_worker(first)+ release_worker(second)++ # ttl=0 reaps every surplus environment; the first per key stays warm.+ assert lambda_runtime.reap_idle_workers(ttl=0) == 1+ assert procs[1].poll() is not None+ assert _port_is_closed(ports[1])+ assert second._server is None+ assert procs[0].poll() is None++ reset()+ assert procs[0].poll() is not None+ assert _port_is_closed(ports[0])+ assert first._server is None and first._log_thread is None+ finally:+ reset()+++def test_invoke_signature_keeps_trace_out_of_the_positional_contract():+ """``trace_id`` is keyword-only, so no caller can pass it as the event."""+ import inspect++ sig = inspect.signature(ProvidedWorker.invoke)+ assert list(sig.parameters) == ["self", "event", "request_id", "trace_id"]+ assert sig.parameters["trace_id"].kind is inspect.Parameter.KEYWORD_ONLY+ assert sig.parameters["trace_id"].default is None+++def test_json_only_bootstrap_output_is_not_parsed_as_protocol(worker_factory):+ """stdout is logs, not a protocol channel: JSON there must not confuse us."""+ noisy = _bootstrap('''+while True:+ headers, event = next_invocation()+ rid = headers["Lambda-Runtime-Aws-Request-Id"]+ sys.stdout.write(json.dumps({"status": "ok", "result": "from-stdout"}) + "\\n")+ sys.stdout.flush()+ post_response(rid, {"real": True})+''')+ worker = worker_factory(noisy)++ result = worker.invoke({}, "req-1")++ assert result["status"] == "ok"+ assert result["result"] == {"real": True}+ assert "from-stdout" in result["log"]+++def test_handler_error_does_not_poison_warm_environment(worker_factory):+ code = _bootstrap('''+n = 0+while True:+ headers, event = next_invocation()+ n += 1+ rid = headers["Lambda-Runtime-Aws-Request-Id"]+ if event.get("fail"):+ post_error(rid, {"errorMessage": "handler failed", "errorType": "Test.Error"})+ else:+ post_response(rid, {"n": n})+''')+ worker = worker_factory(code)+ failed = worker.invoke({"fail": True}, "req-1")+ assert failed["status"] == "error"+ assert failed["error_payload"]["errorType"] == "Test.Error"+ recovered = worker.invoke({}, "req-2")+ assert recovered["status"] == "ok"+ assert recovered["cold_start"] is False+ assert recovered["result"] == {"n": 2}+++def test_exit_during_invocation_fails_without_waiting_for_timeout(worker_factory):+ worker = worker_factory(_bootstrap('''+next_invocation()+sys.stderr.write("crashed during handler\\n")+sys.stderr.flush()+sys.exit(9)+'''), Timeout=30)+ started = time.monotonic()+ result = worker.invoke({}, "req-1")+ assert time.monotonic() - started < 8+ assert result["status"] == "error"+ assert result["error_payload"]["errorType"] == "Runtime.ExitError"+ assert "crashed during handler" in result["log"]+ assert worker._proc is None and worker._server is None+++def test_response_recorded_just_after_process_exit_is_preserved(worker_factory, monkeypatch):+ from unittest.mock import Mock++ worker = worker_factory(ECHO_BOOTSTRAP)+ proc = Mock()+ statuses = iter([None, 0])+ proc.poll.side_effect = lambda: next(statuses, 0)+ worker._proc = proc+ ready = Mock()+ waits = iter([False, True])++ def wait(timeout):+ settled = next(waits)+ if settled:+ worker._result = {"response": {"ok": True}}+ return settled++ ready.wait.side_effect = wait+ worker._response_ready = ready+ monkeypatch.setattr(worker, "_drain_stderr_bounded", lambda: "")+ result = worker.invoke({}, "req-1")+ assert result["status"] == "ok"+ assert result["result"] == {"ok": True}+ assert ready.wait.call_count == 2+ assert worker._proc is None+++def test_spawn_failure_closes_the_already_started_server(worker_factory, monkeypatch):+ worker = worker_factory(ECHO_BOOTSTRAP)+ resources = []++ def failed_popen(*args, **kwargs):+ resources.extend([worker._server, worker._server_thread])+ raise OSError("cannot execute bootstrap")++ monkeypatch.setattr(lambda_runtime.subprocess, "Popen", failed_popen)+ with pytest.raises(OSError, match="cannot execute bootstrap"):+ worker.invoke({}, "req-1")+ server, thread = resources+ assert server.fileno() == -1+ assert not thread.is_alive()+ assert worker._proc is None and worker._server is None