Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(lambda): report RIE init failures and timeouts, don't retry them (#1374)

iot-rocket43e5c9e87619
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index f485403c..189c904b 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -3181,6 +3181,78 @@ def _classify_function_error(parsed, err_header: str) -> str | None:
return "Handled" if "statusCode" in parsed else "Unhandled"
+# A container that never answers is a failed cold start, not a slow one: RIE
+# starts listening within a second or two. Cap the reconnect phase so a
+# function with a long Timeout (900s is legal) cannot hold its caller for
+# fifteen minutes. A request that is actually in flight is bounded separately
+# by urlopen(timeout=timeout).
+_RIE_CONNECT_RETRY_SECONDS = 30.0
+
+
+def _rie_failure_is_retryable(exc: BaseException) -> bool:
+ """Is a failed RIE request worth retrying while the container comes up?
+
+ Only a connection-level failure means "not listening yet". The two
+ terminal cases both look like `OSError` and used to be retried:
+
+ * `HTTPError` — the runtime answered. RIE reports a failed INIT (a handler
+ module that will not import, a stale layer) as a 502 carrying the error
+ payload, and every retry runs INIT again and fails the same way.
+ * a bare `TimeoutError` — the request was accepted and the handler ran past
+ the function's timeout. `URLError` wrapping a timeout is the connect
+ phase, so that one stays retryable.
+ """
+ if isinstance(exc, urllib.error.HTTPError):
+ return False
+ if isinstance(exc, urllib.error.URLError):
+ return True
+ return not isinstance(exc, TimeoutError)
+
+
+def _rie_terminal_result(exc: BaseException, timeout: int, logs: str) -> dict:
+ """Shape a terminal RIE failure as AWS shapes it: a function error.
+
+ AWS answers `Invoke` with HTTP 200, `X-Amz-Function-Error: Unhandled` and
+ the error payload in the body; `function_error` here is what makes the
+ caller emit that header.
+
+ The timeout case carries an extra `timeout` key — an internal signal to
+ `_execute_function_docker` that this container must not go back in the warm
+ pool. It is popped there and never reaches a caller's result.
+ """
+ if isinstance(exc, urllib.error.HTTPError):
+ raw = ""
+ try:
+ raw = exc.read().decode("utf-8", errors="replace")
+ except Exception:
+ pass
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError:
+ parsed = None
+ if isinstance(parsed, dict) and parsed.get("errorMessage"):
+ body = parsed
+ else:
+ err_type = exc.headers.get("Lambda-Runtime-Function-Error-Type") if exc.headers else None
+ body = {
+ "errorMessage": f"Lambda RIE returned HTTP {exc.code}: {raw[:500]}",
+ "errorType": err_type or "Runtime.ExitError",
+ }
+ return {"body": body, "error": True, "function_error": "Unhandled", "log": logs}
+ # Read timeout on an accepted POST: the handler ran past its Timeout. The
+ # message and errorType are what the local (~`_execute_function_local`) and
+ # catch-all docker paths already emit for a timeout, so every executor
+ # agrees on one shape.
+ body = {
+ "errorMessage": f"Task timed out after {timeout}.00 seconds",
+ "errorType": "Runtime.ExitError",
+ }
+ return {
+ "body": body, "error": True, "function_error": "Unhandled",
+ "log": logs, "timeout": True,
+ }
+
+
def _invoke_rie(container, event: dict, timeout: int) -> dict:
"""POST event to a running RIE container's HTTP endpoint."""
import urllib.request
@@ -3192,10 +3264,14 @@ def _invoke_rie(container, event: dict, timeout: int) -> dict:
if isinstance(event, dict) and event.get("ResponseURL"):
event = {**event, "ResponseURL": _rewrite_host_for_container(event["ResponseURL"])}
max_attempts = int(timeout * 10) + 20
+ connect_deadline = time.time() + min(timeout + 2.0, _RIE_CONNECT_RETRY_SECONDS)
for _attempt in range(max_attempts):
+ if time.time() > connect_deadline:
+ break
container.reload()
if container.status != "running":
break
+ attempt_start = time.time()
try:
networks = container.attrs.get("NetworkSettings", {}).get("Networks", {})
# Try Docker network first (container-to-container)
@@ -3237,10 +3313,15 @@ def _invoke_rie(container, event: dict, timeout: int) -> dict:
result["error"] = True
result["function_error"] = function_error
return result
- except (urllib.error.URLError, ConnectionRefusedError, OSError):
+ except (urllib.error.URLError, ConnectionRefusedError, OSError) as exc:
+ if not _rie_failure_is_retryable(exc):
+ logs = container.logs(
+ stdout=True, stderr=True, since=attempt_start
+ ).decode("utf-8", errors="replace").strip()
+ return _rie_terminal_result(exc, timeout, logs)
time.sleep(0.1)
continue
- # Timed out
+ # Never became reachable
stdout = container.logs(stdout=True, stderr=True).decode("utf-8", errors="replace").strip()
return {
"body": {"errorMessage": f"Lambda RIE failed: {stdout[:500]}", "errorType": "Runtime.ExitError"},
@@ -3660,7 +3741,21 @@ def _execute_function_docker(func: dict, event: dict) -> dict:
try:
result = _invoke_rie(entry["container"], event, timeout)
- if result.get("error") and not _is_container_running(entry["container"]):
+ # `timeout` is _invoke_rie's internal signal to this function; pop it so
+ # only the caller-facing keys survive into the invoke response.
+ if result.pop("timeout", False):
+ # Task timed out: AWS terminates the execution environment. Ours
+ # still has the handler running inside the RIE, so returning the
+ # container to the pool would queue the next invocation behind a
+ # zombie handler. Recycle it — off the response path, because the
+ # stop (SIGTERM grace + SIGKILL) takes seconds and the caller
+ # should see the timeout at the timeout mark, as on AWS.
+ threading.Thread(
+ target=_pool_remove, args=(entry,), daemon=True,
+ name="ministack-lambda-timeout-reaper",
+ ).start()
+ entry = None
+ elif result.get("error") and not _is_container_running(entry["container"]):
# Container died during invocation — evict so next caller doesn't pick a corpse
_pool_remove(entry)
entry = None
diff --git a/tests/conftest.py b/tests/conftest.py
index a3ac0831..3085ea99 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -70,6 +70,10 @@ _SERIAL_TESTS = {
"tests/test_stepfunctions.py::test_sfn_wait_scale_zero_does_not_timeout_lambda_tasks",
"tests/test_stepfunctions.py::test_sfn_wait_scale_zero_skips_wait",
"tests/test_rds.py::test_rds_lambda_network_connectivity",
+ # Docker-executor Lambda timeout (skipped unless LAMBDA_EXECUTOR=docker):
+ # cold-starts a container and asserts a wall-clock bound (< 9s for a
+ # Timeout=3 function), which parallel container churn breaks.
+ "tests/test_lambda.py::test_lambda_docker_timeout_returns_task_timed_out_promptly",
"tests/test_elasticache.py::test_elasticache_lambda_network_connectivity",
# API Gateway execute-api → Lambda invoke under tight urlopen / WS recv
# timeouts. These pass cleanly when run serially but are sensitive to
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 61f9ff75..56ef6668 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -9174,6 +9174,397 @@ def test_invoke_rie_rewrites_custom_resource_response_url():
assert event["ResponseURL"] == "http://localhost:4566/_ministack/cfn-response/tok"
+# ---------------------------------------------------------------------------
+# RIE invoke — an init failure is terminal, a cold start is not
+# ---------------------------------------------------------------------------
+
+
+class _RieFakeContainer:
+ """Minimal docker-py container stand-in for the RIE invoke path."""
+
+ status = "running"
+ attrs = {"NetworkSettings": {"Networks": {}}}
+ ports = {"8080/tcp": [{"HostPort": "12345"}]}
+
+ def reload(self):
+ pass
+
+ def logs(self, **_kw):
+ return b"[ERROR] Runtime.ImportModuleError"
+
+
+_INIT_ERROR_PAYLOAD = {
+ "errorMessage": "Unable to import module 'index': No module named 'missing_dep'",
+ "errorType": "Runtime.ImportModuleError",
+ "requestId": "",
+ "stackTrace": [],
+}
+
+
+def _rie_init_error(url):
+ """The 502 AWS RIE answers with when the handler module will not import."""
+ return _urlerr.HTTPError(
+ url,
+ 502,
+ "Bad Gateway",
+ {"Lambda-Runtime-Function-Error-Type": "Runtime.ImportModuleError"},
+ io.BytesIO(json.dumps(_INIT_ERROR_PAYLOAD).encode()),
+ )
+
+
+ "exc,retryable",
+ [
+ (_urlerr.HTTPError("http://x", 502, "Bad Gateway", {}, io.BytesIO(b"{}")), False),
+ (TimeoutError("timed out"), False),
+ (_urlerr.URLError(ConnectionRefusedError(111, "Connection refused")), True),
+ (_urlerr.URLError(TimeoutError("connect timed out")), True),
+ (ConnectionResetError(104, "Connection reset by peer"), True),
+ (OSError("no route to host"), True),
+ ],
+)
+def test_rie_failure_is_retryable_classification(exc, retryable):
+ """Only a connection-level failure means the container is still coming up."""
+ from ministack.services.lambda_svc import _rie_failure_is_retryable
+
+ assert _rie_failure_is_retryable(exc) is retryable
+
+
+def test_invoke_rie_reports_an_init_error_instead_of_retrying_it():
+ """A reported init error is terminal: one request, and the payload survives.
+
+ RIE answers a failed INIT with a 502 — an `HTTPError`, which is a subclass
+ of `URLError` and so used to land in the connection-refused retry arm. Every
+ retry re-ran INIT and failed identically, for `Timeout * 10 + 20` attempts.
+ """
+ from ministack.services.lambda_svc import _invoke_rie
+
+ calls = []
+
+ def _fake_urlopen(req, timeout=None):
+ calls.append(req.full_url)
+ raise _rie_init_error(req.full_url)
+
+ started = time.time()
+ with patch("urllib.request.urlopen", _fake_urlopen):
+ # Timeout=900 is legal on AWS, and used to buy 9020 retries at 0.1s.
+ result = _invoke_rie(_RieFakeContainer(), {"k": "v"}, timeout=900)
+ elapsed = time.time() - started
+
+ assert len(calls) == 1
+ assert elapsed < 5
+ assert result["error"] is True
+ assert result["function_error"] == "Unhandled"
+ assert result["body"] == _INIT_ERROR_PAYLOAD
+ assert "Runtime.ImportModuleError" in result["log"]
+
+
+def test_invoke_rie_still_retries_a_container_that_is_still_starting():
+ """The cold-start retry stays: a refused connection is not a function error."""
+ from ministack.services.lambda_svc import _invoke_rie
+
+ calls = []
+
+ class _FakeResp:
+ headers = {}
+
+ def read(self):
+ return json.dumps({"ok": True}).encode()
+
+ def _fake_urlopen(req, timeout=None):
+ calls.append(req.full_url)
+ if len(calls) < 3:
+ raise _urlerr.URLError(ConnectionRefusedError(111, "Connection refused"))
+ return _FakeResp()
+
+ with patch("urllib.request.urlopen", _fake_urlopen):
+ result = _invoke_rie(_RieFakeContainer(), {"k": "v"}, timeout=5)
+
+ assert len(calls) == 3
+ assert result["body"] == {"ok": True}
+ assert "error" not in result
+
+
+def test_invoke_rie_does_not_re_run_a_handler_that_timed_out():
+ """A read timeout means the handler ran; re-POSTing it just runs it again."""
+ from ministack.services.lambda_svc import _invoke_rie
+
+ calls = []
+
+ def _fake_urlopen(req, timeout=None):
+ calls.append(req.full_url)
+ raise TimeoutError("timed out")
+
+ with patch("urllib.request.urlopen", _fake_urlopen):
+ result = _invoke_rie(_RieFakeContainer(), {"k": "v"}, timeout=3)
+
+ assert len(calls) == 1
+ assert result["error"] is True
+ assert result["function_error"] == "Unhandled"
+ # The message and type the local and catch-all docker paths already emit.
+ assert result["body"] == {
+ "errorMessage": "Task timed out after 3.00 seconds",
+ "errorType": "Runtime.ExitError",
+ }
+ # Internal signal to _execute_function_docker: do not pool this container.
+ assert result["timeout"] is True
+
+
+def test_invoke_rie_reports_a_non_json_502_body():
+ """A 502 whose body is not the RIE error payload still reports a function error.
+
+ RIE answers a failed INIT with JSON, but a 502 can also come from something
+ else in front of the port (a proxy, a half-written body). The fallback keeps
+ the response shape and carries the header's error type when there is one.
+ """
+ from ministack.services.lambda_svc import _invoke_rie
+
+ def _fake_urlopen(req, timeout=None):
+ raise _urlerr.HTTPError(
+ req.full_url, 502, "Bad Gateway",
+ {"Lambda-Runtime-Function-Error-Type": "Runtime.InvalidEntrypoint"},
+ io.BytesIO(b"<html>502 Bad Gateway</html>"),
+ )
+
+ with patch("urllib.request.urlopen", _fake_urlopen):
+ result = _invoke_rie(_RieFakeContainer(), {"k": "v"}, timeout=3)
+
+ assert result["error"] is True
+ assert result["function_error"] == "Unhandled"
+ assert result["body"]["errorType"] == "Runtime.InvalidEntrypoint"
+ assert "502" in result["body"]["errorMessage"]
+ assert "<html>502 Bad Gateway</html>" in result["body"]["errorMessage"]
+ # Not a timeout — the container is answering, so it stays poolable.
+ assert "timeout" not in result
+
+
+def test_invoke_rie_non_json_502_without_an_error_type_header():
+ """No error-type header either: the shape holds, with the generic type."""
+ from ministack.services.lambda_svc import _invoke_rie
+
+ def _fake_urlopen(req, timeout=None):
+ raise _urlerr.HTTPError(
+ req.full_url, 502, "Bad Gateway", {}, io.BytesIO(b"not json"),
+ )
+
+ with patch("urllib.request.urlopen", _fake_urlopen):
+ result = _invoke_rie(_RieFakeContainer(), {"k": "v"}, timeout=3)
+
+ assert result["body"] == {
+ "errorMessage": "Lambda RIE returned HTTP 502: not json",
+ "errorType": "Runtime.ExitError",
+ }
+
+
+def test_lambda_docker_timeout_recycles_the_container(monkeypatch):
+ """A timed-out container is discarded, not handed to the next invocation.
+
+ Its handler is still running inside the RIE, so pooling it would queue the
+ next invocation behind a zombie. AWS terminates the execution environment
+ on a timeout; this is the same bargain — the next call cold-starts.
+ """
+ from ministack.services import lambda_svc as lsvc
+
+ name = f"lam-timeout-recycle-{_uuid_mod.uuid4().hex[:8]}"
+ config = {
+ "FunctionName": name,
+ "Runtime": "python3.12",
+ "Handler": "index.handler",
+ "Timeout": 3,
+ "FunctionArn": f"arn:aws:lambda:us-east-1:000000000000:function:{name}",
+ }
+ spawned = []
+ removed = []
+
+ def _fake_spawn(*_a, **_kw):
+ container = _RieFakeContainer()
+ spawned.append(container)
+ return container, None
+
+ monkeypatch.setattr(lsvc, "LAMBDA_EXECUTOR", "docker")
+ monkeypatch.setattr(lsvc, "_docker_available", True)
+ monkeypatch.setattr(lsvc, "_get_docker_client", lambda: object())
+ monkeypatch.setattr(lsvc, "_ensure_reaper_thread", lambda: None)
+ monkeypatch.setattr(lsvc, "_spawn_lambda_container", _fake_spawn)
+ monkeypatch.setattr(lsvc, "_kill_pool_entry", lambda entry: removed.append(entry))
+
+ def _fake_urlopen(req, timeout=None):
+ raise TimeoutError("timed out")
+
+ try:
+ with patch("urllib.request.urlopen", _fake_urlopen):
+ first = lsvc._execute_function_docker(
+ {"config": config, "code_zip": b"zip"}, {}
+ )
+ second = lsvc._execute_function_docker(
+ {"config": config, "code_zip": b"zip"}, {}
+ )
+ finally:
+ lsvc._pool_kill_function("000000000000", name)
+
+ for result in (first, second):
+ assert result["error"] is True
+ assert result["body"]["errorType"] == "Runtime.ExitError"
+ assert result["body"]["errorMessage"] == "Task timed out after 3.00 seconds"
+ # The recycle signal is internal and must not reach the caller.
+ assert "timeout" not in result
+
+ # The reaper runs off the response path, so wait for it rather than racing.
+ deadline = time.time() + 5
+ while len(removed) < 2 and time.time() < deadline:
+ time.sleep(0.05)
+
+ assert len(spawned) == 2, "second invoke reused the timed-out container"
+ assert spawned[0] is not spawned[1]
+ assert len(removed) == 2, "timed-out containers were not torn down"
+
+
+def test_invoke_rie_gives_up_on_an_unreachable_container(monkeypatch):
+ """An endless refusal is bounded by the reconnect deadline, not by Timeout."""
+ from ministack.services import lambda_svc as lsvc
+
+ monkeypatch.setattr(lsvc, "_RIE_CONNECT_RETRY_SECONDS", 0.5)
+
+ def _fake_urlopen(req, timeout=None):
+ raise _urlerr.URLError(ConnectionRefusedError(111, "Connection refused"))
+
+ started = time.time()
+ with patch("urllib.request.urlopen", _fake_urlopen):
+ result = lsvc._invoke_rie(_RieFakeContainer(), {"k": "v"}, timeout=900)
+ elapsed = time.time() - started
+
+ assert elapsed < 5
+ assert result["error"] is True
+ assert result["body"]["errorType"] == "Runtime.ExitError"
+
+
+def test_lambda_invoke_returns_a_rie_init_error_to_the_caller(monkeypatch):
+ """End to end: Invoke answers 200 + X-Amz-Function-Error, and answers now."""
+ from ministack.services import lambda_svc as lsvc
+
+ name = f"lam-init-error-{_uuid_mod.uuid4().hex[:8]}"
+ config = {
+ "FunctionName": name,
+ "Runtime": "python3.12",
+ "Handler": "index.handler",
+ "Timeout": 900,
+ "FunctionArn": f"arn:aws:lambda:us-east-1:000000000000:function:{name}",
+ }
+ monkeypatch.setattr(lsvc, "LAMBDA_EXECUTOR", "docker")
+ # Pin the docker branch: _get_docker_client() returning None (no daemon on
+ # the runner) would silently fall back to the warm executor and test nothing.
+ monkeypatch.setattr(lsvc, "_docker_available", True)
+ monkeypatch.setattr(lsvc, "_get_docker_client", lambda: object())
+ monkeypatch.setattr(lsvc, "_ensure_reaper_thread", lambda: None)
+ monkeypatch.setattr(
+ lsvc, "_spawn_lambda_container", lambda *_a, **_kw: (_RieFakeContainer(), None)
+ )
+ monkeypatch.setattr(lsvc, "_emit_lambda_metrics", lambda *a, **kw: None)
+ monkeypatch.setitem(
+ lsvc._functions, name,
+ {"config": config, "code_zip": b"zip", "versions": {}},
+ )
+
+ def _fake_urlopen(req, timeout=None):
+ raise _rie_init_error(req.full_url)
+
+ started = time.time()
+ try:
+ with patch("urllib.request.urlopen", _fake_urlopen):
+ status, headers, body = asyncio.run(lsvc._invoke(name, {}, {}))
+ finally:
+ lsvc._pool_kill_function("000000000000", name)
+ elapsed = time.time() - started
+
+ assert elapsed < 5
+ assert status == 200
+ assert headers["X-Amz-Function-Error"] == "Unhandled"
+ assert json.loads(body)["errorType"] == "Runtime.ImportModuleError"
+
+
+ os.environ.get("LAMBDA_EXECUTOR", "").lower() != "docker",
+ reason="requires LAMBDA_EXECUTOR=docker and Docker daemon",
+)
+def test_lambda_docker_timeout_returns_task_timed_out_promptly(lam):
+ """The real RIE end of the timeout story: one AWS-style error, promptly.
+
+ The read timeout must not fall into the cold-start connection poll and
+ re-POST — which re-runs the handler — up to ``timeout * 10 + 20`` times.
+ """
+ fname = f"lam-docker-sleeper-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "import time\n"
+ "def handler(event, context):\n"
+ " time.sleep(event.get('sleep', 0))\n"
+ " return {'slept': event.get('sleep', 0)}\n"
+ )
+ lam.create_function(
+ FunctionName=fname, Runtime="python3.12", Handler="index.handler",
+ Role=_LAMBDA_ROLE, Code={"ZipFile": _make_zip(code)}, Timeout=3,
+ )
+ try:
+ # Warm the container so the timing below excludes the cold start.
+ resp, payload = _invoke_lambda_payload(lam, fname, {"sleep": 0})
+ assert payload == {"slept": 0}
+
+ started = time.time()
+ resp, payload = _invoke_lambda_payload(lam, fname, {"sleep": 10})
+ elapsed = time.time() - started
+ assert resp.get("FunctionError") == "Unhandled"
+ assert payload["errorMessage"] == "Task timed out after 3.00 seconds"
+ assert payload["errorType"] == "Runtime.ExitError"
+ # One timeout, not a retry storm (broken code took 4x+ the Timeout and
+ # surfaced a raw "Lambda RIE failed" instead).
+ assert elapsed < 9, f"timeout took {elapsed:.1f}s — retry storm?"
+
+ # The timed-out container is recycled, and the function stays usable.
+ resp, payload = _invoke_lambda_payload(lam, fname, {"sleep": 0})
+ assert not resp.get("FunctionError"), payload
+ assert payload == {"slept": 0}
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+ os.environ.get("LAMBDA_EXECUTOR", "").lower() != "docker",
+ reason="requires LAMBDA_EXECUTOR=docker and Docker daemon",
+)
+def test_lambda_docker_init_error_is_reported_not_retried(lam):
+ """The real RIE end of the same story: a handler that cannot import.
+
+ RIE answers such an invocation with a 502 and re-runs INIT on every
+ retry, so this used to spin at ten invocations a second for the whole
+ of `Timeout` before answering.
+ """
+ fname = f"lam-init-err-{_uuid_mod.uuid4().hex[:8]}"
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(
+ "import missing_dep_xyz\n\n"
+ "def handler(event, context):\n"
+ " return {'ok': True}\n"
+ )},
+ Timeout=120,
+ )
+ try:
+ started = time.time()
+ resp = lam.invoke(FunctionName=fname, Payload=b"{}")
+ elapsed = time.time() - started
+
+ assert elapsed < 60, "invoke did not return promptly"
+ assert resp["StatusCode"] == 200
+ assert resp["FunctionError"] == "Unhandled"
+ payload = json.loads(resp["Payload"].read())
+ assert payload["errorType"] == "Runtime.ImportModuleError"
+ assert "missing_dep_xyz" in payload["errorMessage"]
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
def _ddb_stream_record(seq, stream_arn, created_at=None):
return {
"eventID": str(seq),