Skip to content

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

fix(lambda): fix in x-ray header (#775)

Nahuel Nucera1808d31696b1
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index 34332feb..aa0ca91f 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -77,6 +77,14 @@ def run():
if not line:
break
event = json.loads(line)
+ # X-Ray active tracing: ministack injects the per-invocation trace
+ # header into the event; pop it into os.environ so the AWS X-Ray SDK
+ # can read _X_AMZN_TRACE_ID on import.
+ _xray_tid = event.pop("_x_amzn_trace_id", None)
+ if _xray_tid:
+ os.environ["_X_AMZN_TRACE_ID"] = _xray_tid
+ elif "_X_AMZN_TRACE_ID" in os.environ:
+ del os.environ["_X_AMZN_TRACE_ID"]
context = type("Context", (), {
"function_name": init.get("function_name", ""),
"memory_limit_in_mb": init.get("memory", 128),
@@ -495,6 +503,15 @@ rl.on("line", async (line) => {
succeed: () => {},
fail: () => {},
};
+ // X-Ray active tracing: ministack injects the per-invocation trace
+ // header into the event; promote it to process.env so the AWS X-Ray SDK
+ // can read _X_AMZN_TRACE_ID on require().
+ if (event._x_amzn_trace_id) {
+ process.env._X_AMZN_TRACE_ID = event._x_amzn_trace_id;
+ } else if ("_X_AMZN_TRACE_ID" in process.env) {
+ delete process.env._X_AMZN_TRACE_ID;
+ }
+ delete event._x_amzn_trace_id;
delete event._request_id;
delete event._function_name;
delete event._memory;
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 9f1bc128..6ec69ba4 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -28,6 +28,7 @@ import asyncio
import base64
import copy
import hashlib
+import secrets
import importlib
import io
import json
@@ -92,6 +93,29 @@ def _emit_lambda_metrics(function_name: str, duration_ms: float,
logger.debug("emit lambda metrics failed", exc_info=True)
+def _xray_trace_id_for_invocation(config: dict, inbound_trace_header: str | None = None) -> str | None:
+ """Return the value to set as ``_X_AMZN_TRACE_ID`` for an invocation.
+
+ AWS Lambda exposes this env var to the runtime when ``TracingConfig.Mode``
+ is ``Active``. Format per AWS X-Ray docs:
+ ``Root=1-<8hex_epoch>-<24hex_random>;Parent=<16hex_random>;Sampled=1``.
+ If the inbound request already carries an ``X-Amzn-Trace-Id`` header (a
+ chained Lambda → Lambda invocation), prefer it so traces stitch across
+ hops; otherwise synthesize a fresh root segment. Returns ``None`` when
+ tracing is not Active and no inbound header is present, so the caller can
+ skip the env-var entirely.
+ """
+ if inbound_trace_header:
+ return inbound_trace_header
+ mode = (config.get("TracingConfig") or {}).get("Mode", "PassThrough")
+ if mode != "Active":
+ return None
+ epoch_hex = format(int(time.time()), "08x")
+ root_random = secrets.token_hex(12) # 24 hex chars
+ parent = secrets.token_hex(8) # 16 hex chars
+ return f"Root=1-{epoch_hex}-{root_random};Parent={parent};Sampled=1"
+
+
def _account_from_arn(arn: str) -> str:
"""Extract the 12-digit account ID from a Lambda function ARN.
@@ -2434,6 +2458,23 @@ def _spawn_lambda_container(config: dict, code_zip: bytes | None):
# Per-invocation durable-execution overlay (no-op when the call isn't
# inside a durable function).
container_env.update(_durable_env_overlay())
+ # NOTE: X-Ray active tracing is NOT supported in the docker RIE
+ # executor. AWS RIE explicitly does not implement X-Ray
+ # (https://github.com/aws/aws-lambda-runtime-interface-emulator —
+ # "The component does not support X-ray and other Lambda integrations
+ # locally") and the RIE container is pooled and reused, so baking
+ # ``_X_AMZN_TRACE_ID`` into ``container_env`` here would be stale on
+ # every reuse anyway. Functions that need X-Ray must use the warm
+ # Python/Node executor (default for those runtimes), the provided
+ # runtime, or the local subprocess executor.
+ if (config.get("TracingConfig") or {}).get("Mode") == "Active":
+ logger.warning(
+ "Lambda %s: TracingConfig.Mode=Active is not supported in the "
+ "docker RIE executor (AWS RIE limitation). _X_AMZN_TRACE_ID will "
+ "not be set in the runtime. Set LAMBDA_EXECUTOR= (empty) to use "
+ "the warm worker, which supports X-Ray.",
+ config.get("FunctionName", "?"),
+ )
# AWS_ENDPOINT_URL set *after* function env so it always points at ministack.
# Replace localhost/127.0.0.1 with host.docker.internal so the container
# can reach the host where ministack is running.
@@ -2897,6 +2938,13 @@ def _execute_function_proxy(func: dict, event: dict, url: str, request_id: str)
"X-Amzn-Lambda-Request-Id": request_id,
"X-Amzn-Lambda-Deadline-Ms": str(int((time.time() + timeout) * 1000)),
}
+ # X-Ray active tracing — pass the trace header to the proxy. The user's
+ # container can translate it to ``_X_AMZN_TRACE_ID`` if their code reads
+ # X-Ray traces. Proxy mode is by definition not a Lambda runtime
+ # emulation, so this is best-effort header forwarding only.
+ _xray_trace_id = _xray_trace_id_for_invocation(config)
+ if _xray_trace_id:
+ headers["X-Amzn-Trace-Id"] = _xray_trace_id
req = urllib.request.Request(url, data=payload, headers=headers, method="POST")
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
@@ -2953,6 +3001,13 @@ def _execute_function_warm(func: dict, event: dict) -> dict:
qualifier = config.get("Version", "$LATEST")
try:
worker = get_or_create_worker(func_name, config, code_zip, qualifier=qualifier)
+ # Inject X-Ray trace header into the event so the worker bootstrap
+ # can set ``_X_AMZN_TRACE_ID`` in os.environ before calling the
+ # handler. Per-invocation, not bake-time, so it can't live in the
+ # worker's spawn env.
+ _xray = _xray_trace_id_for_invocation(config)
+ if _xray:
+ event["_x_amzn_trace_id"] = _xray
result = worker.invoke(event, new_uuid())
if result.get("status") == "ok":
return {"body": result.get("result"), "log": result.get("log", "")}
@@ -3116,6 +3171,13 @@ def _execute_function_provided(func: dict, event: dict) -> dict:
})
proc_env.update(env_vars)
proc_env.update(_durable_env_overlay())
+ # 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
+ # per-segment via ``os.getenv``, so the runtime sees it.
+ _xray_trace_id = _xray_trace_id_for_invocation(config)
+ if _xray_trace_id:
+ proc_env["_X_AMZN_TRACE_ID"] = _xray_trace_id
# 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
@@ -3276,6 +3338,11 @@ def _execute_function_local(func: dict, event: dict) -> dict:
env["AWS_ENDPOINT_URL"] = endpoint
env.update(env_vars)
env.update(_durable_env_overlay())
+ # X-Ray active tracing — one-shot subprocess, env is per-invocation
+ # so a fresh trace ID per call is safe (unlike the pooled RIE).
+ _xray_trace_id = _xray_trace_id_for_invocation(config)
+ if _xray_trace_id:
+ env["_X_AMZN_TRACE_ID"] = _xray_trace_id
cmd = ["node", wrapper_path] if is_node else ["python3", wrapper_path]
proc = subprocess.run(
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index cf22645a..4fab56ce 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -4702,3 +4702,123 @@ def test_lambda_durable_create_function_durable_config_round_trip_with_update(la
finally:
try: lam.delete_function(FunctionName=fname)
except Exception: pass
+
+
+# ---------------------------------------------------------------------------
+# X-Ray active tracing — _X_AMZN_TRACE_ID injection per invocation.
+#
+# Real AWS injects this env var into the runtime when TracingConfig.Mode is
+# Active; the aws-xray-sdk reads it per-segment via os.getenv() and raises
+# "Missing AWS Lambda trace data for X-Ray" on absence. The warm Python
+# executor is the default for python3.* runtimes, so these tests pin its
+# behavior end-to-end. AWS RIE (the docker executor) does NOT support X-Ray
+# upstream, so the corresponding "supported here" guarantee is warm/local/
+# provided only.
+# ---------------------------------------------------------------------------
+
+_XRAY_TRACE_HEADER_RE = (
+ r"^Root=1-[0-9a-f]{8}-[0-9a-f]{24};Parent=[0-9a-f]{16};Sampled=1$"
+)
+
+_XRAY_ECHO_HANDLER = (
+ "import os\n"
+ "def handler(event, context):\n"
+ " return {'trace_id': os.environ.get('_X_AMZN_TRACE_ID', '<UNSET>')}\n"
+)
+
+
+def _create_xray_fn(lam, name: str, mode: str) -> None:
+ lam.create_function(
+ FunctionName=name,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(_XRAY_ECHO_HANDLER)},
+ TracingConfig={"Mode": mode},
+ )
+
+
+def _invoke_trace_id(lam, name: str) -> str:
+ resp = lam.invoke(FunctionName=name, Payload=b"{}")
+ return json.loads(resp["Payload"].read())["trace_id"]
+
+
+def test_lambda_xray_active_injects_trace_id(lam):
+ """TracingConfig.Mode=Active → handler sees a properly-formatted
+ _X_AMZN_TRACE_ID (`Root=1-<8hex>-<24hex>;Parent=<16hex>;Sampled=1`)."""
+ import re as _re
+ fname = f"xray-active-{_uuid_mod.uuid4().hex[:8]}"
+ _create_xray_fn(lam, fname, "Active")
+ try:
+ trace_id = _invoke_trace_id(lam, fname)
+ assert _re.match(_XRAY_TRACE_HEADER_RE, trace_id), trace_id
+ finally:
+ try: lam.delete_function(FunctionName=fname)
+ except Exception: pass
+
+
+def test_lambda_xray_passthrough_does_not_set_trace_id(lam):
+ """TracingConfig.Mode=PassThrough (default) → no _X_AMZN_TRACE_ID. The
+ AWS X-Ray SDK opts itself out when the env var is absent, which is the
+ expected behavior for non-Active functions."""
+ fname = f"xray-pt-{_uuid_mod.uuid4().hex[:8]}"
+ _create_xray_fn(lam, fname, "PassThrough")
+ try:
+ assert _invoke_trace_id(lam, fname) == "<UNSET>"
+ finally:
+ try: lam.delete_function(FunctionName=fname)
+ except Exception: pass
+
+
+def test_lambda_xray_active_fresh_id_per_invocation(lam):
+ """Each invocation gets a distinct trace ID — the warm worker's
+ persistent subprocess must NOT cache the env var across invocations.
+ AWS contract: every Lambda invocation is a new root segment."""
+ import re as _re
+ fname = f"xray-fresh-{_uuid_mod.uuid4().hex[:8]}"
+ _create_xray_fn(lam, fname, "Active")
+ try:
+ t1 = _invoke_trace_id(lam, fname)
+ t2 = _invoke_trace_id(lam, fname)
+ assert _re.match(_XRAY_TRACE_HEADER_RE, t1), t1
+ assert _re.match(_XRAY_TRACE_HEADER_RE, t2), t2
+ assert t1 != t2, f"Trace ID was reused: {t1}"
+ finally:
+ try: lam.delete_function(FunctionName=fname)
+ except Exception: pass
+
+
+def test_lambda_xray_does_not_leak_across_functions(lam):
+ """Active on function A must not leave _X_AMZN_TRACE_ID set when
+ function B (PassThrough) runs afterward — verifies the worker bootstrap
+ clears the env var when no trace ID is injected for the call."""
+ fa = f"xray-leak-a-{_uuid_mod.uuid4().hex[:8]}"
+ fb = f"xray-leak-b-{_uuid_mod.uuid4().hex[:8]}"
+ _create_xray_fn(lam, fa, "Active")
+ _create_xray_fn(lam, fb, "PassThrough")
+ try:
+ # Prime A so its worker has _X_AMZN_TRACE_ID in os.environ.
+ _invoke_trace_id(lam, fa)
+ # B must not see the env var from A's invocation.
+ assert _invoke_trace_id(lam, fb) == "<UNSET>"
+ finally:
+ for f in (fa, fb):
+ try: lam.delete_function(FunctionName=f)
+ except Exception: pass
+
+
+def test_xray_trace_id_helper_unit():
+ """Direct unit test of the helper used by all executors."""
+ import re as _re
+ from ministack.services.lambda_svc import _xray_trace_id_for_invocation
+ # PassThrough / missing → None
+ assert _xray_trace_id_for_invocation({}) is None
+ assert _xray_trace_id_for_invocation({"TracingConfig": {"Mode": "PassThrough"}}) is None
+ # Active → synthesizes proper format
+ h = _xray_trace_id_for_invocation({"TracingConfig": {"Mode": "Active"}})
+ assert _re.match(_XRAY_TRACE_HEADER_RE, h), h
+ # Inbound header propagates regardless of mode (chained Lambda → Lambda
+ # invocation: parent's trace ID stitches into child via header).
+ inbound = "Root=1-12345678-aaaabbbbccccddddeeeeffff;Parent=1111222233334444;Sampled=1"
+ assert _xray_trace_id_for_invocation({}, inbound) == inbound
+ assert _xray_trace_id_for_invocation({"TracingConfig": {"Mode": "Active"}}, inbound) == inbound