fix(cli): stop railyard logs from buffering an unbounded tail in memory
`run()` always appended every stdout/stderr chunk from a child process onto accumulator strings, even for `railyard logs` (wraps `wrangler tail`), which only ever reads the exit code and can stream for hours -- so a long session held every log line it had ever printed in memory for no reason. Added a `capture` option (default true, unchanged for deploy/rollback which do need the text back) and set `capture: false` for logs. Load-tested the fix for real: a new fake-wrangler `tail` fixture that behaves like the real thing (streams until killed, never exits on its own), a 4,000-line end-to-end `railyard logs` test (every line still streamed live, saved token redacted, --format/--status forwarded correctly), a Ctrl+C-style signal-stop test, and a direct run() test proving capture:false keeps result.stdout/stderr empty across 20,000 printed lines while capture:true is unchanged. 28/28 CLI tests passing (23 pre-existing + 5 new). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
32d8482958
commit
2e9ca56c36
@ -279,3 +279,53 @@ Until then this is fully built and dark, same gating pattern as every other
|
||||
3 (Faultline/Rago fold), 8/9 (`vcglass` repo), 10 (`videogen` repo), 13
|
||||
(Switchyard catalog browser), 14 (console setup-wizard script), 15 (Insights
|
||||
per-site event pooling).
|
||||
|
||||
## Round 4 (2026-10-24) -- `railyard logs` load-tested against a long-running tail
|
||||
|
||||
Picked up the one remaining item the per-app spec addendum flagged as not
|
||||
done: "`railyard logs` (added 2026-10-22) is the newest command, not yet
|
||||
load-tested against a long-running tail." It had zero test coverage of any
|
||||
kind before this round (`test/cli.test.mjs` never called it; the fake
|
||||
wrangler fixture had no `tail` case).
|
||||
|
||||
Load-testing it for real (not just reading the code) surfaced a genuine bug:
|
||||
`run()` (`packages/cli/src/run.mjs`) unconditionally appended every stdout/
|
||||
stderr chunk onto a `stdout`/`stderr` string for the life of the child
|
||||
process. `deploy`/`rollback` need that (`parseDeployOutput` reads it back),
|
||||
but `logs` only ever reads `result.code` -- so a `railyard logs` left
|
||||
streaming a busy Worker for hours would hold every log line it had ever
|
||||
printed in memory, growing without bound, for no reason (the text is thrown
|
||||
away the moment the tail ends).
|
||||
|
||||
Fixed with a new `capture` option on `run()` (default `true`, unchanged
|
||||
behavior for every existing caller): `logs()` now passes `capture: false`,
|
||||
so chunks still reach the live `echo` callback (and the terminal) exactly as
|
||||
before, but are never appended to the accumulator strings.
|
||||
|
||||
Verified, not just asserted:
|
||||
- `packages/cli/test/run.test.mjs` (new) -- spawns a real child printing
|
||||
20,000 lines; with `capture: true` (unchanged default) `result.stdout`
|
||||
contains all 20,000 lines as before; with `capture: false` every line
|
||||
still reaches `echo` live but `result.stdout`/`stderr` stay `""`. Also
|
||||
covers the spawn-error (`ENOENT`) path with `capture: false`.
|
||||
- `packages/cli/test/fixtures/fake-wrangler.mjs` -- added a `tail` case that
|
||||
behaves like the real `wrangler tail` (streams until killed, never exits
|
||||
on its own) so the CLI's actual `logs()` code path -- not a stand-in --
|
||||
gets exercised: `FAKE_WRANGLER_TAIL_LINES` controls how many lines it
|
||||
prints, `FAKE_WRANGLER_TAIL_SELF_SIGTERM=1` has it send itself `SIGTERM`
|
||||
(the same way a terminal's Ctrl+C would) instead of exiting normally.
|
||||
- `packages/cli/test/cli.test.mjs` (new tests) -- ran `railyard logs`
|
||||
end-to-end through a long (4,000-line) tail and confirmed every line was
|
||||
still streamed live (capture:false drops nothing), that the saved login
|
||||
token riding in the fake stream was redacted in what reached the
|
||||
terminal (never printed in the clear), and that the real
|
||||
`--format`/`--status` flags were forwarded to `wrangler tail` correctly.
|
||||
A second test ends a tail mid-stream with a self-sent `SIGTERM` (the
|
||||
Ctrl+C case) and confirms it is reported as a clean stop (exit 0, no
|
||||
`ERR` line), not a failure.
|
||||
- Full suite: `npm test` in `packages/cli` -- 28/28 passing (23 pre-existing
|
||||
+ 5 new), including every existing deploy/rollback/link/ci/domains test
|
||||
unaffected by the `capture` default staying `true` everywhere else.
|
||||
|
||||
No deploy/secrets/owner-gated step -- this is a CLI bug fix plus its tests,
|
||||
committed directly.
|
||||
|
||||
@ -264,8 +264,10 @@ not confirmed serving real traffic.
|
||||
against `apps/console`'s `/api/v1/*`.
|
||||
- Auth: device-code flow (`POST /api/v1/device/code` → poll
|
||||
`/api/v1/device/token`), token cached in `~/.railyard/credentials.json`.
|
||||
- Remaining: none blocking; `railyard logs` (added 2026-10-22) is the
|
||||
newest command, not yet load-tested against a long-running tail.
|
||||
- Remaining: none blocking; `railyard logs` (added 2026-10-22) was
|
||||
load-tested against a long-running tail 2026-10-24 (see
|
||||
`BUILD-LOG-2026-10-23.md` "Round 4") -- found and fixed a real unbounded-
|
||||
memory bug in `run()`'s output capture, now covered by tests.
|
||||
|
||||
### Core: Rithub/Gitea + CI runner (`apps/gitea`, live `git.ereboslab.com`)
|
||||
- Pages: stock Gitea 1.23 UI (repos/issues/PRs/Actions/Packages/Wiki) +
|
||||
|
||||
@ -197,6 +197,9 @@ export async function logs(ctx, opts) {
|
||||
cwd: dir,
|
||||
env: ctx.env,
|
||||
echo: (s) => ctx.out(redact(s, [creds.token]).replace(/\n$/, "")),
|
||||
// A tail can run for hours; only the exit code is ever read below, so never
|
||||
// accumulate the streamed text (see run.mjs's `capture` doc comment).
|
||||
capture: false,
|
||||
});
|
||||
// A Ctrl+C mid-stream ends the child by signal, not a bad exit code: that is how a
|
||||
// tail is meant to stop, not a failure (run() reports it as code 0, signal set).
|
||||
|
||||
@ -12,21 +12,30 @@ export function tool(env, name) {
|
||||
throw new Error(`unknown tool ${name}`);
|
||||
}
|
||||
|
||||
/** Run and capture output; echo it live when `echo` is set (through `redactFn`). */
|
||||
export function run(cmd, args, { cwd, env, echo, redactFn = (s) => s, inherit = false } = {}) {
|
||||
/**
|
||||
* Run and capture output; echo it live when `echo` is set (through `redactFn`).
|
||||
*
|
||||
* `capture: false` (the default is `true`) skips accumulating stdout/stderr into
|
||||
* strings at all: a short-lived command like `deploy` needs the full text back
|
||||
* (`parseDeployOutput` reads it), but a long-running stream like `logs` (which
|
||||
* only ever reads `result.code`) must not grow those strings without bound for
|
||||
* as long as the tail stays open — a `railyard logs` left running overnight on a
|
||||
* busy Worker would otherwise hold every log line it ever printed in memory.
|
||||
*/
|
||||
export function run(cmd, args, { cwd, env, echo, redactFn = (s) => s, inherit = false, capture = true } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn(cmd, args, { cwd, env, stdio: inherit ? "inherit" : ["inherit", "pipe", "pipe"] });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout?.on("data", (b) => {
|
||||
stdout += b;
|
||||
if (capture) stdout += b;
|
||||
if (echo) echo(redactFn(String(b)));
|
||||
});
|
||||
child.stderr?.on("data", (b) => {
|
||||
stderr += b;
|
||||
if (capture) stderr += b;
|
||||
if (echo) echo(redactFn(String(b)));
|
||||
});
|
||||
child.on("error", (err) => resolve({ code: 127, stdout, stderr: `${stderr}${err.message}` }));
|
||||
child.on("error", (err) => resolve({ code: 127, stdout, stderr: capture ? `${stderr}${err.message}` : err.message }));
|
||||
// `signal` is set instead of `code` when the child was killed (e.g. Ctrl+C on a tail);
|
||||
// callers that care about a clean stop (not a crash) can tell the two apart.
|
||||
child.on("close", (code, signal) => resolve({ code: code ?? (signal ? 0 : 1), stdout, stderr, signal }));
|
||||
|
||||
@ -172,3 +172,32 @@ test("deploy without login says what to do", async () => {
|
||||
assert.equal(await main(["deploy"], c.c), 1);
|
||||
assert.deepEqual(c.lines, ["ERR Run railyard login first."]);
|
||||
});
|
||||
|
||||
// `railyard logs` wraps `wrangler tail`, a stream that can run for hours. These
|
||||
// load-test it the way the PLAN-2026-10-23-DEEP.md addendum flagged as not yet
|
||||
// done: a long stream of lines (so a naive implementation that buffers the
|
||||
// whole thing would show it) and a Ctrl+C-style signal stop mid-stream.
|
||||
test("logs: a long tail streams every line live, redacts the saved token, and never fails on a normal end", async () => {
|
||||
const { token } = JSON.parse(readFileSync(join(TMP, "config/credentials.json"), "utf8"));
|
||||
const dir = project("logger", { "index.html": "<h1>x</h1>" });
|
||||
const lines = 4000;
|
||||
const c = ctx(dir, { FAKE_WRANGLER_LOGGED_IN: "1", FAKE_WRANGLER_TAIL_LINES: String(lines), FAKE_WRANGLER_TAIL_SECRET: token });
|
||||
assert.equal(await main(["logs", "--format", "json", "--status", "error"], c.c), 0, c.lines.join("\n"));
|
||||
assert.equal(c.lines[0], "Streaming logger. Stop with Ctrl+C.");
|
||||
// Every line wrangler printed reached the terminal (nothing dropped by capture:false)...
|
||||
const streamed = c.lines.slice(1).join("\n");
|
||||
assert.equal((streamed.match(/"line":/g) ?? []).length, lines);
|
||||
// ...the saved token never appears in the clear...
|
||||
assert.ok(!streamed.includes(token), "token redacted");
|
||||
assert.ok(streamed.includes("[redacted]"), "redaction placeholder present");
|
||||
const call = wranglerCalls().at(-1);
|
||||
assert.equal(call.cmd, "tail");
|
||||
assert.deepEqual(call.rest, ["--name", "logger", "--format", "json", "--status", "error"]);
|
||||
});
|
||||
|
||||
test("logs: a Ctrl+C-style signal mid-stream ends the command cleanly, not as a failure", async () => {
|
||||
const dir = project("logger2", { "index.html": "<h1>x</h1>" });
|
||||
const c = ctx(dir, { FAKE_WRANGLER_LOGGED_IN: "1", FAKE_WRANGLER_TAIL_LINES: "3", FAKE_WRANGLER_TAIL_SELF_SIGTERM: "1" });
|
||||
assert.equal(await main(["logs"], c.c), 0, c.lines.join("\n"));
|
||||
assert.ok(!c.lines.some((l) => l.startsWith("ERR")), "a signal stop is not reported as an error");
|
||||
});
|
||||
|
||||
25
packages/cli/test/fixtures/fake-wrangler.mjs
vendored
25
packages/cli/test/fixtures/fake-wrangler.mjs
vendored
@ -40,5 +40,26 @@ if (cmd === "rollback") {
|
||||
console.log(`\nCurrent Version ID: ${rest[0]}`);
|
||||
process.exit(0);
|
||||
}
|
||||
console.error(`fake wrangler: unknown command ${cmd}`);
|
||||
process.exit(1);
|
||||
if (cmd === "tail") {
|
||||
// Stands in for `wrangler tail`'s real behaviour: it streams until something
|
||||
// kills it, it never exits on its own. Used to load-test `railyard logs`
|
||||
// against a long-running stream (many lines, one carrying a secret to prove
|
||||
// redaction still runs per-chunk) and against a Ctrl+C-style signal stop
|
||||
// (FAKE_WRANGLER_TAIL_SELF_SIGTERM simulates the terminal sending SIGTERM to
|
||||
// this child, the same way Ctrl+C would, without a second process to send it).
|
||||
const n = Number(process.env.FAKE_WRANGLER_TAIL_LINES ?? "0");
|
||||
const secret = process.env.FAKE_WRANGLER_TAIL_SECRET ?? "";
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
// The secret rides on the very first line (whole in the first small write,
|
||||
// nowhere near a pipe chunk boundary) so the redaction assertion below can't
|
||||
// flake on the token happening to straddle two separate `data` events.
|
||||
console.log(JSON.stringify({ line: i, message: i === 0 && secret ? `token ${secret} seen` : `log line ${i}` }));
|
||||
}
|
||||
if (process.env.FAKE_WRANGLER_TAIL_SELF_SIGTERM === "1") process.kill(process.pid, "SIGTERM");
|
||||
else if (n > 0) process.exit(0);
|
||||
else setInterval(() => {}, 1000); // hang like a real tail until the parent kills us
|
||||
process.exitCode = 0;
|
||||
} else {
|
||||
console.error(`fake wrangler: unknown command ${cmd}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
37
packages/cli/test/run.test.mjs
Normal file
37
packages/cli/test/run.test.mjs
Normal file
@ -0,0 +1,37 @@
|
||||
// run()'s `capture` option: a long-running stream (railyard logs wraps `wrangler
|
||||
// tail`, which can run for hours) must never buffer the text it prints into
|
||||
// memory just because something eventually checks the exit code.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { run } from "../src/run.mjs";
|
||||
|
||||
const LINES = 20_000;
|
||||
const printLines = `for (let i = 0; i < ${LINES}; i++) { process.stdout.write("line " + i + "\\n"); }`;
|
||||
|
||||
test("capture: true (the default) still returns the full output, as deploy/rollback need", async () => {
|
||||
const seen = [];
|
||||
const r = await run(process.execPath, ["-e", printLines], { env: process.env, echo: (s) => seen.push(s) });
|
||||
assert.equal(r.code, 0);
|
||||
assert.equal(r.stdout.split("\n").filter(Boolean).length, LINES);
|
||||
assert.ok(seen.length > 0, "echo still fires with capture on");
|
||||
});
|
||||
|
||||
test("capture: false streams the same output through `echo` but never buffers it", async () => {
|
||||
const seen = [];
|
||||
const r = await run(process.execPath, ["-e", printLines], { env: process.env, echo: (s) => seen.push(s), capture: false });
|
||||
assert.equal(r.code, 0);
|
||||
// The whole point: unlike the capture:true run above, stdout/stderr stay empty
|
||||
// no matter how much the child prints, so a day-long `railyard logs` tail
|
||||
// never grows these strings.
|
||||
assert.equal(r.stdout, "");
|
||||
assert.equal(r.stderr, "");
|
||||
// But every line still reached the caller live -- nothing was silently dropped.
|
||||
assert.equal(seen.join("").split("\n").filter(Boolean).length, LINES);
|
||||
});
|
||||
|
||||
test("capture: false still reports a spawn error (node:child_process ENOENT), just without buffered text", async () => {
|
||||
const r = await run("railyard-definitely-not-a-real-binary", [], { env: process.env, capture: false });
|
||||
assert.equal(r.code, 127);
|
||||
assert.match(r.stderr, /ENOENT/);
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user