Skip to content

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

fix(lambda): redirect Node fd-1 writes off warm-worker stdout (#1093) (#1094)

vvaide1d2c81d12987
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3b0cd4a..2303f61c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **Lambda — Node warm-worker invoke no longer fails on fd 1 writes** — `fs.writeSync` / `fs.write` on stdout bypassed the existing `process.stdout.write` redirect to stderr (#373), so sync loggers (e.g. pino with `{ sync: true }`) could emit on the JSON-line protocol channel and surface false `Runtime.HandlerError` / `Unknown error` responses even when the handler succeeded. The Node worker bootstrap now redirects fd 1 through `fs.writeSync` / `fs.write`, and the warm-worker stdout reader accepts only protocol lines whose `status` is `ok` or `error`. Reported by @kofuk (#1093).
- **Cognito — `ListUsers` `status` filter matched against the wrong field** — `Filter='status = "Enabled"'`/`"Disabled"` was compared against `UserStatus` (the confirmation-state enum: `CONFIRMED`, `FORCE_CHANGE_PASSWORD`, `UNCONFIRMED`, etc.), which never equals the literal string `"Enabled"`/`"Disabled"`. As a result, filtering by `status` always returned an empty list, regardless of how many users existed or their actual enabled/disabled state. `status` now correctly reflects the account's `Enabled` boolean toggled by `AdminEnableUser`/`AdminDisableUser`, matching real AWS Cognito's `ListUsers` Filter semantics. Contributed by @jey-mfv.
### Added
- **IoT — MQTT publishes are routed through topic rules to Lambda** — an MQTT/`iot-data` publish is now matched against each account's topic rules by the rule's `FROM '<topic filter>'` clause (with `+`/`#` wildcards), and every matching enabled rule's `lambda` actions are invoked asynchronously with the message payload as the event (`SELECT *`). Basic Ingest is supported: a publish to `$aws/rules/<ruleName>` is delivered straight to that rule's actions and bypasses pub/sub. Disabled rules are skipped.
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index 5812a4c7..2d48c406 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -162,11 +162,26 @@ const url = require("url");
const Module = require("module");
// Redirect stdout to stderr so stdout stays clean for JSON-line protocol
+const fs = require("fs");
const _realStdoutWrite = process.stdout.write.bind(process.stdout);
const _stderrWrite = process.stderr.write.bind(process.stderr);
process.stdout.write = function(chunk, encoding, callback) {
return _stderrWrite(chunk, encoding, callback);
};
+const _stdoutFd = process.stdout.fd;
+const _realWriteSync = fs.writeSync.bind(fs);
+const _realWrite = fs.write.bind(fs);
+function _isStdoutFd(fd) {
+ return fd === 1 || fd === _stdoutFd;
+}
+fs.writeSync = function(fd, ...args) {
+ if (_isStdoutFd(fd)) fd = 2;
+ return _realWriteSync(fd, ...args);
+};
+fs.write = function(fd, ...args) {
+ if (_isStdoutFd(fd)) fd = 2;
+ return _realWrite(fd, ...args);
+};
// Synthetic AWS SDK v3 stubs — real AWS Lambda (Node.js 18+) ships these
// built-in, but the host runtime does not. Try the real package first so
@@ -924,8 +939,9 @@ class Worker:
if response_line.startswith("{"):
try:
response = json.loads(response_line)
- result_box.append(response)
- return
+ if response.get("status") in ("ok", "error"):
+ result_box.append(response)
+ return
except json.JSONDecodeError:
continue
result_box.append({"status": "error", "error": "No JSON response from worker after 200 lines"})
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index f2351047..81a53738 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -1,4 +1,5 @@
import asyncio
+import contextlib
import io
import json
import os
@@ -29,6 +30,33 @@ def _make_zip_js(code: str, filename: str = "index.js") -> bytes:
zf.writestr(filename, code)
return buf.getvalue()
+
+def _nodejs_lambda(lam, code, *, prefix="lam-node", runtime="nodejs20.x"):
+ """Create a Node.js zip Lambda for the test, delete it on exit."""
+ fname = f"{prefix}-{_uuid_mod.uuid4().hex[:8]}"
+ lam.create_function(
+ FunctionName=fname,
+ Runtime=runtime,
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip_js(code, "index.js")},
+ )
+ try:
+ yield fname
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def _invoke_lambda_payload(lam, fname, payload=None, **invoke_kw):
+ """Invoke a function and return (response, parsed payload)."""
+ resp = lam.invoke(
+ FunctionName=fname,
+ Payload=json.dumps(payload if payload is not None else {}),
+ **invoke_kw,
+ )
+ return resp, json.loads(resp["Payload"].read())
+
_LAMBDA_CODE = 'def handler(event, context):\n return {"statusCode": 200, "body": "ok"}\n'
_LAMBDA_CODE_V2 = 'def handler(event, context):\n return {"statusCode": 200, "body": "v2"}\n'
@@ -1893,6 +1921,99 @@ def test_lambda_nodejs_callback_handler(lam):
assert payload["cb"] is True
assert payload["val"] == 7
+
+def test_lambda_nodejs_fd_write_sync_invoke_succeeds(lam):
+ """fs.writeSync(1) logging must not fail the invocation (issue #1093)."""
+ code = (
+ "exports.handler = async () => {\n"
+ " require('fs').writeSync(1, 'hi\\n');\n"
+ " return { ok: true };\n"
+ "};\n"
+ )
+ with _nodejs_lambda(lam, code, prefix="lam-node-fdsync") as fname:
+ resp, payload = _invoke_lambda_payload(lam, fname)
+ assert resp["StatusCode"] == 200
+ assert "FunctionError" not in resp
+ assert payload == {"ok": True}
+
+
+def test_lambda_nodejs_fd_write_sync_warm_reinvoke(lam):
+ """Warm re-invoke after fd-1 logging must keep returning the handler result."""
+ code = (
+ "let n = 0;\n"
+ "exports.handler = async () => {\n"
+ " require('fs').writeSync(1, 'tick\\n');\n"
+ " return { count: ++n };\n"
+ "};\n"
+ )
+ with _nodejs_lambda(lam, code, prefix="lam-node-fdsync-warm") as fname:
+ first, body1 = _invoke_lambda_payload(lam, fname)
+ second, body2 = _invoke_lambda_payload(lam, fname)
+ assert "FunctionError" not in first
+ assert "FunctionError" not in second
+ assert body1 == {"count": 1}
+ assert body2 == {"count": 2}
+
+
+def test_lambda_nodejs_pino_style_json_log_invoke_succeeds(lam):
+ """Structured JSON logs on fd 1 (pino sync) must not break invoke."""
+ import base64
+
+ marker = f"PINO-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "exports.handler = async () => {\n"
+ f" require('fs').writeSync(1, JSON.stringify({{level:30,msg:'{marker}'}}) + '\\n');\n"
+ " return { ok: true };\n"
+ "};\n"
+ )
+ with _nodejs_lambda(lam, code, prefix="lam-node-pino") as fname:
+ resp, payload = _invoke_lambda_payload(lam, fname, LogType="Tail")
+ assert resp["StatusCode"] == 200
+ assert "FunctionError" not in resp
+ assert payload == {"ok": True}
+
+ log_result = resp.get("LogResult", "")
+ assert log_result, "stdout logging should appear in execution logs"
+ decoded = base64.b64decode(log_result).decode("utf-8")
+ assert marker in decoded
+
+
+def test_lambda_nodejs_fd_write_sync_no_log_type(lam):
+ """Default invoke must return the handler payload even when fd 1 is written."""
+ code = (
+ "exports.handler = async () => {\n"
+ " require('fs').writeSync(1, 'noise\\n');\n"
+ " return { ok: true };\n"
+ "};\n"
+ )
+ with _nodejs_lambda(lam, code, prefix="lam-node-fdsync-notail") as fname:
+ resp, payload = _invoke_lambda_payload(lam, fname)
+ assert resp["StatusCode"] == 200
+ assert "FunctionError" not in resp
+ assert payload == {"ok": True}
+
+
+def test_lambda_nodejs_fd_write_and_console_log_invoke_succeeds(lam):
+ """console.log and fd-1 writes in one handler must both work."""
+ import base64
+
+ marker = f"MIXED-{_uuid_mod.uuid4().hex[:8]}"
+ code = (
+ "exports.handler = async () => {\n"
+ f" console.log('{marker}-console');\n"
+ " require('fs').writeSync(1, 'sync-line\\n');\n"
+ " return { mixed: true };\n"
+ "};\n"
+ )
+ with _nodejs_lambda(lam, code, prefix="lam-node-mixed-log") as fname:
+ resp, payload = _invoke_lambda_payload(lam, fname, LogType="Tail")
+ assert "FunctionError" not in resp
+ assert payload == {"mixed": True}
+ decoded = base64.b64decode(resp["LogResult"]).decode("utf-8")
+ assert marker in decoded
+ assert "sync-line" in decoded
+
+
def test_lambda_nodejs_env_vars_at_spawn(lam):
"""Lambda env vars are available at process startup (NODE_OPTIONS, etc.)."""
code = (
@@ -5916,6 +6037,89 @@ def _run_nodejs_worker(handler_js, event_payload=None, env_extra=None):
shutil.rmtree(tmpdir, ignore_errors=True)
+def test_nodejs_worker_fd_write_sync_succeeds():
+ """fs.writeSync(1) must not break the worker protocol (issue #1093)."""
+ handler_js = """\
+exports.handler = async () => {
+ require('fs').writeSync(1, 'hi\\n');
+ return { ok: true };
+};
+"""
+ result = _run_nodejs_worker(handler_js)
+ assert result.get("status") == "ok", result
+ assert result["result"] == {"ok": True}
+
+
+def test_nodejs_worker_fs_write_async_succeeds():
+ """fs.write(1, ...) must be redirected like fs.writeSync."""
+ handler_js = """\
+const fs = require('fs');
+exports.handler = async () => {
+ await new Promise((resolve, reject) => {
+ fs.write(1, 'async\\n', (err) => (err ? reject(err) : resolve()));
+ });
+ return { async: true };
+};
+"""
+ result = _run_nodejs_worker(handler_js)
+ assert result.get("status") == "ok", result
+ assert result["result"] == {"async": True}
+
+
+def test_nodejs_worker_fd_write_stdout_fd_succeeds():
+ """Writes via process.stdout.fd must be treated as stdout."""
+ handler_js = """\
+exports.handler = async () => {
+ require('fs').writeSync(process.stdout.fd, 'via-fd\\n');
+ return { viaFd: true };
+};
+"""
+ result = _run_nodejs_worker(handler_js)
+ assert result.get("status") == "ok", result
+ assert result["result"] == {"viaFd": True}
+
+
+def test_nodejs_worker_fd_write_many_lines_succeeds():
+ """Many fd-1 writes in one invocation must not break the worker."""
+ handler_js = """\
+exports.handler = async () => {
+ const fs = require('fs');
+ for (let i = 0; i < 20; i++) fs.writeSync(1, `line-${i}\\n`);
+ return { lines: 20 };
+};
+"""
+ result = _run_nodejs_worker(handler_js)
+ assert result.get("status") == "ok", result
+ assert result["result"] == {"lines": 20}
+
+
+def test_nodejs_worker_json_log_with_status_field_succeeds():
+ """JSON logs with an unrelated status field must not break invoke."""
+ handler_js = """\
+exports.handler = async () => {
+ const entry = JSON.stringify({ status: 200, message: 'logged' });
+ require('fs').writeSync(1, entry + '\\n');
+ return { ok: true };
+};
+"""
+ result = _run_nodejs_worker(handler_js)
+ assert result.get("status") == "ok", result
+ assert result["result"] == {"ok": True}
+
+
+def test_nodejs_worker_fd_write_then_handler_error():
+ """Logging to fd 1 must not mask a real handler failure."""
+ handler_js = """\
+exports.handler = async () => {
+ require('fs').writeSync(1, 'before-throw\\n');
+ throw new Error('on purpose');
+};
+"""
+ result = _run_nodejs_worker(handler_js)
+ assert result.get("status") == "error", result
+ assert "on purpose" in result.get("error", "")
+
+
def test_nodejs_worker_aws_sdk_v3_stub_resolves():
"""@aws-sdk/client-lambda, @aws-sdk/client-sfn, @aws-sdk/client-ssm resolve.
diff --git a/tests/test_lambda_runtime_worker.py b/tests/test_lambda_runtime_worker.py
index a0d01cae..d0d7864b 100644
--- a/tests/test_lambda_runtime_worker.py
+++ b/tests/test_lambda_runtime_worker.py
@@ -42,6 +42,26 @@ def _spawn_proc():
return proc
+def _protocol_line(status, **fields):
+ return json.dumps({"status": status, **fields}) + "\n"
+
+
+def _mock_worker(stdout_lines):
+ worker = Worker("test-fn", _config(), b"ignored-zip")
+ proc = MagicMock()
+ proc.poll.return_value = None
+ proc.stdout.readline.side_effect = list(stdout_lines)
+ proc.stdin = MagicMock()
+ proc.stderr = iter([])
+ worker._proc = proc
+ return worker, proc
+
+
+def _invoke_worker(stdout_lines, request_id="req"):
+ worker, proc = _mock_worker(stdout_lines)
+ return worker.invoke({}, request_id=request_id), proc, worker
+
+
# ---------------------------------------------------------------------------
# Test 1: tmpdir is cleaned up on respawn
# ---------------------------------------------------------------------------
@@ -114,26 +134,109 @@ def test_tmpdir_cleaned_before_respawn():
def test_process_terminated_on_error_response():
- """invoke() must call proc.terminate() when the handler returns status=error.
+ """invoke() must call proc.terminate() when the handler returns status=error."""
+ error_line = _protocol_line("error", error="handler blew up")
+ result, proc, worker = _invoke_worker([error_line], request_id="req-001")
- Verifies the fix: the worker subprocess is terminated rather than silently
- orphaned when _read_response() receives {"status": "error"}.
- """
- worker = Worker("test-fn", _config(), b"ignored-zip")
+ assert result["status"] == "error", "invoke() should surface the error status"
+ proc.terminate.assert_called_once_with()
+ assert worker._proc is None, "_proc must be cleared after an error response"
- proc = MagicMock()
- proc.poll.return_value = None # process appears alive when invoke() checks it
- error_line = json.dumps({"status": "error", "error": "handler blew up"}) + "\n"
- proc.stdout.readline.side_effect = [error_line]
- proc.stdin = MagicMock()
- proc.stderr = iter([])
+def test_invoke_ignores_json_logs_on_stdout():
+ """Pino-style JSON on fd 1 must not be mistaken for the protocol response."""
+ ok_line = _protocol_line("ok", result={"ok": True})
+ log_line = json.dumps({"level": 30, "msg": "hi"}) + "\n"
+ result, _, _ = _invoke_worker([log_line, ok_line])
- # Pre-set _proc so invoke() skips _spawn() entirely
- worker._proc = proc
+ assert result["status"] == "ok"
+ assert result["result"] == {"ok": True}
- result = worker.invoke({"key": "val"}, request_id="req-001")
- assert result["status"] == "error", "invoke() should surface the error status"
+def test_invoke_ignores_raw_text_on_stdout():
+ """Plain fd-1 writes must not prevent reading the protocol response."""
+ ok_line = _protocol_line("ok", result={"ok": True})
+ result, _, _ = _invoke_worker(["hi\n", ok_line])
+
+ assert result["status"] == "ok"
+ assert result["result"] == {"ok": True}
+
+
+def test_invoke_ignores_json_with_unrelated_status_key():
+ """HTTP-style JSON logs with a status code must not end the read loop."""
+ junk = json.dumps({"status": 200, "message": "ok"}) + "\n"
+ ok_line = _protocol_line("ok", result={"n": 1})
+ result, _, _ = _invoke_worker([junk, ok_line])
+
+ assert result["status"] == "ok"
+ assert result["result"] == {"n": 1}
+
+
+def test_invoke_ignores_many_log_lines_before_protocol():
+ """A burst of structured logs must not hide the real protocol line."""
+ logs = [
+ json.dumps({"level": 30, "msg": f"line-{i}"}) + "\n"
+ for i in range(8)
+ ]
+ ok_line = _protocol_line("ok", result={"done": True})
+ result, _, _ = _invoke_worker(logs + [ok_line])
+
+ assert result["status"] == "ok"
+ assert result["result"] == {"done": True}
+
+
+def test_invoke_skips_malformed_json_lines():
+ """Broken JSON on stdout must be ignored, not treated as the response."""
+ ok_line = _protocol_line("ok", result={})
+ result, _, _ = _invoke_worker(['{"truncated":\n', ok_line])
+
+ assert result["status"] == "ok"
+
+
+def test_invoke_skips_empty_lines():
+ """Blank lines between junk output and the protocol line are ignored."""
+ ok_line = _protocol_line("ok", result={"x": 1})
+ result, _, _ = _invoke_worker(["\n", "noise\n", "\n", ok_line])
+
+ assert result["status"] == "ok"
+ assert result["result"] == {"x": 1}
+
+
+def test_invoke_skips_ready_status_during_invoke():
+ """Init-only ready messages must not satisfy an invocation read."""
+ ready = _protocol_line("ready", cold=False)
+ ok_line = _protocol_line("ok", result={"v": 2})
+ result, _, _ = _invoke_worker([ready, ok_line])
+
+ assert result["status"] == "ok"
+ assert result["result"] == {"v": 2}
+
+
+def test_invoke_still_surfaces_protocol_error():
+ """Protocol error lines must still fail the invocation."""
+ error_line = _protocol_line("error", error="boom")
+ result, proc, _ = _invoke_worker([error_line])
+
+ assert result["status"] == "error"
+ assert result["error"] == "boom"
proc.terminate.assert_called_once_with()
- assert worker._proc is None, "_proc must be cleared after an error response"
+
+
+def test_invoke_error_after_junk_stdout():
+ """Handler errors must win even when stdout already has log noise."""
+ junk = json.dumps({"level": 50, "msg": "warn"}) + "\n"
+ err_line = _protocol_line("error", error="fail")
+ result, proc, _ = _invoke_worker([junk, "oops\n", err_line])
+
+ assert result["status"] == "error"
+ assert result["error"] == "fail"
+ proc.terminate.assert_called_once_with()
+
+
+def test_invoke_gives_up_after_max_lines():
+ """Stop after 200 non-protocol lines instead of hanging forever."""
+ worker, proc = _mock_worker(["noise\n"] * 201)
+ result = worker.invoke({}, request_id="req-max")
+
+ assert result["status"] == "error"
+ assert "No JSON response" in result["error"]