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
fix(lambda): pass configured timeout to Docker RIE (#1857)
gakuto-cw21cba4b10253f1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 10274004..6f2aacb5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **Lambda — Docker executor honors timeouts above 300 seconds** — pass the configured `Timeout` to AWS RIE through `AWS_LAMBDA_FUNCTION_TIMEOUT`, preventing its default 300-second limit from ending longer invocations early. Timeout updates recycle warm containers so the RIE deadline follows the new configuration (#1844).- **KMS — `GenerateDataKey` returns `KeyMaterialId`** — requests without `Recipient` now include the identifier of the wrapping key material. The identifier remains stable across requests and persistence reloads, and changes when the wrapping material changes. Fixes #1853.### Addeddiff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 029999fc..9ee26f0c 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -341,6 +341,7 @@ _RESERVED_RUNTIME_ENV_VARS = {"AWS_SESSION_TOKEN","AWS_LAMBDA_FUNCTION_NAME","AWS_LAMBDA_FUNCTION_MEMORY_SIZE",+ "AWS_LAMBDA_FUNCTION_TIMEOUT","AWS_LAMBDA_FUNCTION_VERSION","AWS_LAMBDA_LOG_STREAM_NAME","AWS_LAMBDA_RUNTIME_API",@@ -2911,7 +2912,7 @@ def _update_config(name: str, data: dict):config["StateReasonCode"] = "Updating"config["RevisionId"] = new_uuid()# AWS-match: UpdateFunctionConfiguration recycles the init container when- # spawn-time inputs change (Runtime/Handler/Layers/Env/MemorySize/Arch/+ # spawn-time inputs change (Runtime/Handler/Timeout/Layers/Env/MemorySize/Arch/# VpcConfig/FileSystemConfigs). The ministack warm-pool key is just# account:func:qualifier, so a stale worker would keep serving with the# pre-update layers/env. Invalidate to force a fresh worker on next invoke,@@ -2919,7 +2920,7 @@ def _update_config(name: str, data: dict):# UpdateFunctionConfiguration(Layers=[...]) leaves the previously-warm# worker without the new layer extracted on disk (issue #816)._WORKER_AFFECTING = {- "Runtime", "Handler", "Layers", "Environment", "MemorySize",+ "Runtime", "Handler", "Timeout", "Layers", "Environment", "MemorySize","Architectures", "VpcConfig", "FileSystemConfigs",}if any(k in data for k in _WORKER_AFFECTING):@@ -4404,6 +4405,8 @@ def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,"AWS_LAMBDA_LOG_STREAM_NAME": new_uuid(),"_LAMBDA_FUNCTION_ARN": config.get("FunctionArn", ""),"_LAMBDA_TIMEOUT": str(timeout),+ # AWS RIE uses this name and otherwise limits invocations to 300s.+ "AWS_LAMBDA_FUNCTION_TIMEOUT": str(timeout),}container_env.update(execution_credentials(config))if is_provided:diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 986222b0..74432706 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -7594,7 +7594,7 @@ def test_lambda_invoke_emits_cloudwatch_logs_nodejs(lam, logs):# ──────────────────── host.docker.internal → host-gateway ────────────────────-def _spawn_capture_run_kwargs(monkeypatch, *, endpoint, docker_flags=""):+def _spawn_capture_run_kwargs(monkeypatch, *, endpoint, docker_flags="", config_overrides=None):"""Spawn one Lambda container against fakes and return the docker kwargs.Captures both entry points: the DinD path uses ``containers.create`` (code@@ -7619,16 +7619,68 @@ def _spawn_capture_run_kwargs(monkeypatch, *, endpoint, docker_flags=""):fake_client.images.get = MagicMock()monkeypatch.setattr(lsvc, "_get_docker_client", lambda: fake_client)- lsvc._spawn_lambda_container(- {"FunctionName": "test-hg-fn", "Runtime": "python3.12",- "Handler": "index.handler", "PackageType": "Zip", "Timeout": 3,- "MemorySize": 128,- "FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:test-hg-fn"},- _make_zip("def handler(e, c): pass"),- )+ config = {+ "FunctionName": "test-hg-fn", "Runtime": "python3.12",+ "Handler": "index.handler", "PackageType": "Zip", "Timeout": 3,+ "MemorySize": 128,+ "FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:test-hg-fn",+ }+ config.update(config_overrides or {})+ lsvc._spawn_lambda_container(config, _make_zip("def handler(e, c): pass"))return captured[email protected]("timeout", [3, 301, 900])[email protected]("package_type", ["Zip", "Image"])[email protected]("in_container", [False, True])+def test_lambda_container_passes_configured_timeout_to_rie(monkeypatch, timeout, package_type, in_container):+ """RIE reads AWS_LAMBDA_FUNCTION_TIMEOUT, otherwise it defaults to 300s (#1844)."""+ monkeypatch.setattr(lsvc, "_running_in_container", lambda: in_container)+ captured = _spawn_capture_run_kwargs(+ monkeypatch, endpoint="http://localhost:4566",+ config_overrides={+ "Timeout": timeout,+ "PackageType": package_type,+ "ImageUri": "public.ecr.aws/lambda/python:3.12",+ "Environment": {"Variables": {+ "AWS_LAMBDA_FUNCTION_TIMEOUT": "1",+ "_LAMBDA_TIMEOUT": "1",+ }},+ },+ )+ assert captured["environment"]["AWS_LAMBDA_FUNCTION_TIMEOUT"] == str(timeout)+ assert captured["environment"]["_LAMBDA_TIMEOUT"] == str(timeout)++[email protected]("package_type", ["Zip", "Image"])[email protected]("old_timeout,new_timeout", [(3, 10), (10, 3)])+def test_lambda_timeout_update_evicts_warm_container(monkeypatch, package_type, old_timeout, new_timeout):+ """A warm RIE container must not keep its previous invocation deadline."""+ name = f"lam-timeout-update-{_uuid_mod.uuid4().hex[:8]}"+ config = {+ "FunctionName": name, "Timeout": old_timeout, "PackageType": package_type,+ "FunctionArn": f"arn:aws:lambda:us-east-1:000000000000:function:{name}",+ "ImageUri": "public.ecr.aws/lambda/python:3.12",+ }+ monkeypatch.setattr(lsvc, "_functions", {name: {"config": config}})+ monkeypatch.setattr(lsvc, "invalidate_worker", Mock())+ monkeypatch.setattr(lsvc, "_schedule_state_transition", Mock())+ key = lsvc._warm_pool_key(name, config)+ container = _mk_container()+ entry = lsvc._pool_register(key, container, None)+ lsvc._pool_release(entry)++ response = lsvc._update_config(name, {"Timeout": new_timeout})++ assert response[0] == 200+ assert config["Timeout"] == new_timeout+ acquired, reason = lsvc._pool_acquire(key, max_concurrency=None)+ assert acquired is None+ assert reason == "spawn"+ container.stop.assert_called_once()+ container.remove.assert_called_once()++def test_lambda_container_maps_host_docker_internal_to_host_gateway(monkeypatch):"""A container pointed at host.docker.internal gets the name mapped.@@ -10821,6 +10873,71 @@ def test_lambda_invoke_returns_a_rie_init_error_to_the_caller(monkeypatch):assert json.loads(body)["errorType"] == "Runtime.ImportModuleError"+ os.environ.get("LAMBDA_EXECUTOR", "").lower() != "docker",+ reason="requires LAMBDA_EXECUTOR=docker and Docker daemon",+)[email protected]_plane+def test_lambda_docker_rie_uses_configured_deadline(lam):+ """Check the real RIE deadline without waiting for its old 300s limit (#1844)."""+ fname = f"lam-rie-deadline-{_uuid_mod.uuid4().hex[:8]}"+ lam.create_function(+ FunctionName=fname, Runtime="python3.12", Handler="index.handler",+ Role=_LAMBDA_ROLE, Timeout=900,+ Code={"ZipFile": _make_zip(+ "def handler(event, context):\n"+ " return {'remaining_ms': context.get_remaining_time_in_millis()}\n"+ )},+ )+ try:+ # Both cold and warm invocations must receive the configured deadline.+ for _ in range(2):+ resp, payload = _invoke_lambda_payload(lam, fname, {})+ assert not resp.get("FunctionError"), payload+ assert 850_000 < payload["remaining_ms"] <= 900_000, payload+ finally:+ lam.delete_function(FunctionName=fname)+++ os.environ.get("LAMBDA_EXECUTOR", "").lower() != "docker",+ reason="requires LAMBDA_EXECUTOR=docker and Docker daemon",+)[email protected]_plane[email protected]("old_timeout,new_timeout", [(3, 10), (10, 3)])+def test_lambda_docker_timeout_update_changes_rie_deadline(lam, old_timeout, new_timeout):+ """Timeout updates replace the warm container and reach the real RIE."""+ fname = f"lam-rie-update-{_uuid_mod.uuid4().hex[:8]}"+ lam.create_function(+ FunctionName=fname, Runtime="python3.12", Handler="index.handler",+ Role=_LAMBDA_ROLE, Timeout=old_timeout,+ Code={"ZipFile": _make_zip(+ "import time\n"+ "def handler(event, context):\n"+ " remaining = context.get_remaining_time_in_millis()\n"+ " time.sleep(event.get('sleep', 0))\n"+ " return {'remaining_ms': remaining, 'ok': True}\n"+ )},+ )+ try:+ resp, payload = _invoke_lambda_payload(lam, fname, {})+ assert not resp.get("FunctionError"), payload+ assert payload["ok"] is True+ lam.update_function_configuration(FunctionName=fname, Timeout=new_timeout)+ lam.get_waiter("function_updated_v2").wait(+ FunctionName=fname, WaiterConfig={"Delay": 1, "MaxAttempts": 10},+ )+ resp, payload = _invoke_lambda_payload(lam, fname, {})+ assert not resp.get("FunctionError"), payload+ assert new_timeout * 500 < payload["remaining_ms"] <= new_timeout * 1000, payload+ if new_timeout > old_timeout:+ resp, payload = _invoke_lambda_payload(lam, fname, {"sleep": old_timeout + 1})+ assert not resp.get("FunctionError"), payload+ assert isinstance(payload, dict) and payload.get("ok") is True, payload+ finally:+ lam.delete_function(FunctionName=fname)++@pytest.mark.skipif(os.environ.get("LAMBDA_EXECUTOR", "").lower() != "docker",reason="requires LAMBDA_EXECUTOR=docker and Docker daemon",@@ -13700,7 +13817,7 @@ def test_provided_env_uses_execution_role_credentials(monkeypatch):assert {key: env[key] for key in credentials} == credentials[email protected]("operation", ["code", "configuration", "delete"])[email protected]("operation", ["code", "configuration", "timeout", "delete"])def test_function_changes_invalidate_provided_workers(monkeypatch, isolated_pool, operation):config = _provided_dispatch_config()name = config["FunctionName"]@@ -13716,6 +13833,8 @@ def test_function_changes_invalidate_provided_workers(monkeypatch, isolated_poolresult = lambda_svc._update_code(name, {})elif operation == "configuration":result = lambda_svc._update_config(name, {"Environment": {"Variables": {"UPDATED": "yes"}}})+ elif operation == "timeout":+ result = lambda_svc._update_config(name, {"Timeout": config["Timeout"] + 1})else:result = lambda_svc._delete_function(name, {})assert result[0] in (200, 204)