Skip to content

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

fix(lambda): report docker/RIE handler failures as Unhandled (#1348)

iot-rocket4e3b90255375
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 59c21fa9..d3d640c5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **CloudWatch Logs — `GetLogGroupFields`** — returns field names found in recent stored events with a rough presence percent (`logGroupFields: [{name, percent}]`). Honors `logGroupName` or `logGroupIdentifier`, optional `time` (±8 minutes) or the default last 15 minutes, system `@*` fields, and flattened JSON message keys.
### Fixed
+- **Lambda — uncaught handler exceptions report `X-Amz-Function-Error: Unhandled`** — the Docker/RIE executor read the error class off a response header the RIE never sets, so every failure was reported `Handled` and API Gateway consumers keying off the 502-for-Unhandled contract never took the error path. Headerless payloads are now classified by shape: the runtime's error serialization reports `Unhandled`, an HTTP-style envelope with `statusCode` stays `Handled`. Contributed by @iot-rocket.
- **IoT — `CreateThingType` is idempotent for identical re-creates** — re-creating an existing thing type always returned `ResourceAlreadyExistsException`, so a retried request or a re-run provisioning script failed where AWS succeeds. The same `thingTypeProperties` now return the existing ids — absent, `null` and empty compare equal, `searchableAttributes` is unordered — and only a real mismatch keeps the `409`, as `CreateThing` already did. Contributed by @iot-rocket.
- **EC2 — `RevokeSecurityGroupIngress` / `RevokeSecurityGroupEgress` honour `SecurityGroupRuleIds`** — both read only `IpPermissions`, so a revoke by rule id (as Terraform does) returned `Return=true` while removing nothing, leaving the rule in place forever. Ids now resolve against the group's `sgr-*` rules, which are removed with their tags and echoed in `revokedSecurityGroupRuleSet`; one unknown id rejects the whole call with `InvalidSecurityGroupRuleId.NotFound`. Contributed by @iot-rocket.
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 20475224..1fdfd076 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -3145,6 +3145,38 @@ def _docker_cp_dir(container, src_dir: str, dest_dir: str, arcname: str = "."):
container.put_archive(dest_dir, buf)
+def _classify_function_error(parsed, err_header: str) -> str | None:
+ """Classify an RIE response body/header as a function error.
+
+ Returns ``"Unhandled"``, ``"Handled"``, or ``None`` when the response is
+ not an error at all. If 'X-Amz-Function-Error' /
+ 'Lambda-Runtime-Function-Error-Type' is set the error flag passes
+ through as Unhandled. Observed on the RIE bundled with the current
+ public.ecr.aws/lambda/{python:3.12,nodejs:22,provided:al2023} images, no
+ error header is returned on the invocation response — not for a raised
+ handler exception, and not even when a custom runtime POSTs to
+ /runtime/invocation/<id>/error with its own error-type header — so
+ classification falls back to the payload shape.
+
+ The runtime's own error serialization is {errorType, errorMessage} plus
+ a per-runtime traceback field whose key and presence vary: Python sends
+ "stackTrace", empty for init failures such as Runtime.ImportModuleError;
+ Node.js sends "trace"; Go and the provided.* runtimes send neither. So
+ any error-shaped payload counts as the runtime's (→ Unhandled, matching
+ real AWS) unless it also carries a statusCode, which marks an HTTP-style
+ envelope the handler returned itself (→ Handled). A handler that returns
+ a bare {errorType, errorMessage} dict is indistinguishable from a
+ Go-style runtime error over this wire and is reported Unhandled; the
+ misreport that actually breaks consumers is the other direction, since
+ API Gateway keys its 502 contract off Unhandled.
+ """
+ if err_header:
+ return "Unhandled"
+ if not (isinstance(parsed, dict) and parsed.get("errorType")):
+ return None
+ return "Handled" if "statusCode" in parsed else "Unhandled"
+
+
def _invoke_rie(container, event: dict, timeout: int) -> dict:
"""POST event to a running RIE container's HTTP endpoint."""
import urllib.request
@@ -3193,18 +3225,13 @@ def _invoke_rie(container, event: dict, timeout: int) -> dict:
except json.JSONDecodeError:
parsed = body
logs = container.logs(stdout=True, stderr=True, since=invoke_time).decode("utf-8", errors="replace").strip()
- # RIE sets 'Lambda-Runtime-Function-Error-Type' (or bare
- # 'X-Amz-Function-Error') when the handler raised an unhandled
- # exception. If it's set we surface the error flag + propagate the
- # exact AWS-style marker so _invoke can emit the right header.
err_header = (resp.headers.get("X-Amz-Function-Error")
or resp.headers.get("Lambda-Runtime-Function-Error-Type") or "")
result = {"body": parsed, "log": logs}
- if err_header or (isinstance(parsed, dict) and parsed.get("errorType")):
- # errorType without an X-Amz header means the handler returned
- # an error-shaped payload itself — AWS signals this as Handled.
+ function_error = _classify_function_error(parsed, err_header)
+ if function_error is not None:
result["error"] = True
- result["function_error"] = "Unhandled" if err_header else "Handled"
+ result["function_error"] = function_error
return result
except (urllib.error.URLError, ConnectionRefusedError, OSError):
time.sleep(0.1)
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index f2a18e6e..510c9bd4 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -1740,6 +1740,107 @@ def test_lambda_invoke_log_includes_user_output_and_traceback_on_error(lam):
lam.delete_function(FunctionName=fname)
+def test_lambda_uncaught_exception_is_unhandled_function_error(lam):
+ """An uncaught exception in the handler must surface FunctionError=Unhandled
+ (real AWS reserves Handled for errors the runtime reports as handled), with
+ an error-shaped payload. This pins the default local executor, which already
+ behaved this way — it is the contract the docker/RIE classifier was corrected
+ to match, and the docker path is pinned by the LAMBDA_EXECUTOR=docker variant
+ below plus the _classify_function_error unit tests."""
+ fname = f"lam-unhandled-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "def handler(event, context):\n"
+ " raise TypeError('bad-type-from-handler')\n"
+ )
+
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)},
+ )
+
+ try:
+ resp = lam.invoke(FunctionName=fname, Payload=json.dumps({}))
+ assert resp["StatusCode"] == 200
+ assert resp.get("FunctionError") == "Unhandled", resp.get("FunctionError")
+ payload = json.loads(resp["Payload"].read())
+ assert isinstance(payload, dict), payload
+ assert payload.get("errorType"), payload
+ assert "bad-type-from-handler" in payload.get("errorMessage", ""), payload
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+ os.environ.get("LAMBDA_EXECUTOR", "").lower() == "docker",
+ reason="docker/RIE path cannot distinguish a returned error-shaped dict "
+ "from a Go-style runtime error without the RIE header; it reports "
+ "Unhandled there, erring towards the 502-for-Unhandled contract",
+)
+def test_lambda_returned_error_shaped_dict_is_not_a_function_error(lam):
+ """A handler that *returns* an {errorType, errorMessage} dict without raising
+ produced a normal successful invocation on real AWS: the dict is just the
+ payload and NO X-Amz-Function-Error header is set."""
+ fname = f"lam-errshape-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "def handler(event, context):\n"
+ " return {'errorType': 'X', 'errorMessage': 'y'}\n"
+ )
+
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)},
+ )
+
+ try:
+ resp = lam.invoke(FunctionName=fname, Payload=json.dumps({}))
+ assert resp["StatusCode"] == 200
+ assert "FunctionError" not in resp, resp.get("FunctionError")
+ payload = json.loads(resp["Payload"].read())
+ assert payload == {"errorType": "X", "errorMessage": "y"}
+ 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_uncaught_exception_is_unhandled_function_error(lam):
+ """Docker/RIE executor variant: the RIE does not set an error header in
+ practice, so the classifier must recognise the runtime's uncaught-exception
+ payload shape ({errorType, errorMessage, stackTrace}, no statusCode) as
+ Unhandled rather than defaulting to Handled."""
+ fname = f"lam-docker-unhandled-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "def handler(event, context):\n"
+ " raise TypeError('bad-type-from-docker-handler')\n"
+ )
+
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)},
+ )
+
+ try:
+ resp = lam.invoke(FunctionName=fname, Payload=json.dumps({}))
+ assert resp["StatusCode"] == 200
+ assert resp.get("FunctionError") == "Unhandled", resp.get("FunctionError")
+ payload = json.loads(resp["Payload"].read())
+ assert payload.get("errorType") == "TypeError", payload
+ assert payload.get("stackTrace"), payload
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
def test_lambda_warm_invoke_with_stderr_logging(lam):
"""Warm invoke should succeed repeatedly even when the worker writes to stderr."""
fname = f"lam-warm-stderr-{_uuid_mod.uuid4().hex[:8]}"
@@ -6024,25 +6125,80 @@ def test_event_stream_encode_roundtrip():
assert event.payload == b"hello-world"
-def test_invoke_rie_classifies_unhandled_vs_handled():
- """If RIE returns X-Amz-Function-Error header the result carries
- function_error='Unhandled'. A handler-returned errorType with no RIE
- header should produce 'Handled'."""
- # The classification logic lives inside _invoke_rie; unit-test by
- # simulating what that branch does via a tiny inline replica.
- parsed_error_payload = {"errorType": "E", "errorMessage": "m"}
-
- # Case 1: RIE header present → Unhandled
- has_header = True
- if has_header or (isinstance(parsed_error_payload, dict) and parsed_error_payload.get("errorType")):
- classification = "Unhandled" if has_header else "Handled"
- assert classification == "Unhandled"
-
- # Case 2: No RIE header, but body has errorType → Handled
- has_header = False
- if has_header or (isinstance(parsed_error_payload, dict) and parsed_error_payload.get("errorType")):
- classification = "Unhandled" if has_header else "Handled"
- assert classification == "Handled"
+def test_classify_function_error_header_present_is_unhandled():
+ """An RIE error header always wins: Unhandled regardless of payload shape."""
+ assert lsvc._classify_function_error({"errorType": "E", "errorMessage": "m"}, "Unhandled") == "Unhandled"
+ # Even a non-dict body is Unhandled when the header says so.
+ assert lsvc._classify_function_error("boom", "Unhandled") == "Unhandled"
+
+
+def test_classify_function_error_python_traceback_shape_is_unhandled():
+ """No header + the python3.12 runtime's uncaught-exception serialization
+ (errorType/errorMessage/stackTrace, no statusCode) → Unhandled."""
+ payload = {
+ "errorMessage": "bad-type-from-handler",
+ "errorType": "TypeError",
+ "requestId": "f5657518-62cc-48d1-826e-736c5e8bbeab",
+ "stackTrace": [" File \"/var/task/index.py\", line 2, in handler\n"],
+ }
+ assert lsvc._classify_function_error(payload, "") == "Unhandled"
+
+
+def test_classify_function_error_python_import_error_is_unhandled():
+ """A broken zip or a wrong Handler makes the python runtime report
+ Runtime.ImportModuleError with an EMPTY stackTrace — classification keys on
+ the shape, not on the traceback being non-empty."""
+ payload = {
+ "errorMessage": "Unable to import module 'nosuchmodule': No module named 'nosuchmodule'",
+ "errorType": "Runtime.ImportModuleError",
+ "requestId": "",
+ "stackTrace": [],
+ }
+ assert lsvc._classify_function_error(payload, "") == "Unhandled"
+
+
+def test_classify_function_error_node_trace_shape_is_unhandled():
+ """The nodejs runtime names its traceback field "trace", not "stackTrace"
+ (as stepfunctions._call_lambda also documents), so keying on stackTrace
+ alone would misreport every raised Node error as Handled."""
+ payload = {
+ "errorType": "TypeError",
+ "errorMessage": "bad-type-from-node",
+ "trace": [
+ "TypeError: bad-type-from-node",
+ " at Runtime.handler (file:///var/task/index.mjs:1:44)",
+ ],
+ }
+ assert lsvc._classify_function_error(payload, "") == "Unhandled"
+
+
+def test_classify_function_error_without_any_trace_field_is_unhandled():
+ """Go and the provided.* runtimes report errors with no traceback field at
+ all — including when the runtime POSTs its own error-type header to
+ /runtime/invocation/<id>/error, which the RIE does not forward."""
+ payload = {"errorMessage": "bad-from-custom-runtime", "errorType": "MyCustomError"}
+ assert lsvc._classify_function_error(payload, "") == "Unhandled"
+
+
+def test_classify_function_error_statuscode_payload_is_handled():
+ """No header + an HTTP-style dict carrying statusCode → Handled: an
+ envelope the handler returned itself, not the runtime's error shape."""
+ payload = {
+ "errorType": "E",
+ "errorMessage": "m",
+ "stackTrace": ["tb"],
+ "statusCode": 502,
+ }
+ assert lsvc._classify_function_error(payload, "") == "Handled"
+
+
+def test_classify_function_error_non_error_payloads_are_none():
+ """No header + a body without errorType (dict, non-dict, or unparsed
+ string) is not a function error at all."""
+ assert lsvc._classify_function_error({"statusCode": 200, "body": "ok"}, "") is None
+ assert lsvc._classify_function_error("plain text body", "") is None
+ assert lsvc._classify_function_error(None, "") is None
+ assert lsvc._classify_function_error({"errorType": ""}, "") is None
def _invoke_with_log_output(monkeypatch, headers, log_output):