NemoClaw icon indicating copy to clipboard operation
NemoClaw copied to clipboard

[CLI&UX] logs --follow passes both log sources through untagged, so any multi-line subsystem output is unattributable

Open Dongni-Yang opened this issue 3 months ago • 2 comments

Description

nemoclaw <name> logs --follow streams its two log sources with stdio: "inherit" (src/lib/actions/sandbox/logs.ts, streamSandboxFollowLogs), a raw passthrough with no line-level processing. Every line is therefore attributable only if the underlying source already tagged it. When any in-sandbox process writes multi-line output whose continuation lines carry no tag, those lines reach the stream unattributable.

#10325 is one instance of this: an OpenClaw config-warning banner contributed 8 unattributable lines out of 252. PR #10331 removes that specific trigger from NemoClaw's generated config, and openclaw/openclaw#129842 tracks the upstream emitter. Neither makes the stream robust: any future multi-line output from any wrapped subsystem reproduces the same failure, and the P0 case asserting per-line attribution is a contract about NemoClaw's own stream, so it should not depend on every wrapped subsystem behaving correctly forever.

This issue tracks the defensive fix: tag lines from the source NemoClaw owns, so attribution is a property of the stream rather than an assumption about its producers.

Second, unreported instance

The same gap exists without --follow. buildSandboxOpenclawGatewayLogsArgs is shared by both paths (src/lib/domain/sandbox/logs.ts), and the non-follow path already pipes both sources and merges them through mergeTailLogLines, which already tracks each line's source via ScoredLine.sourceIndex. So plain nemoclaw <name> logs is equally unattributable today, and the plumbing to fix it there already exists.

Prior art in this repo

  • #7314 → PR #7322 fixed exactly this bug class for NemoClaw's own registration banner, by tagging at the emitter's write site: process.stderr.write(\[gateway] ${line}\n`) (nemoclaw/src/index.ts), pinned by nemoclaw/src/register.test.ts`. That worked because NemoClaw owned the emitter; here it does not.
  • NemoClaw already ships a per-line tagger for this very log file: sed -u 's/^/[gateway-log:] /' in scripts/nemoclaw-start.sh, and similarly in agents/hermes/start.sh.
  • src/lib/sandbox/create-stream.ts already implements the pending-buffer / split-on-newline / flush-partial pattern this needs.
  • deps.writeStdout already exists as a seam in SandboxLogsRuntimeDeps and is already stubbed by three tests; it is simply unused in the follow path.

Expected Result

Every line logs --follow (and logs) emits carries a source tag, regardless of how the producing subsystem formats multi-line output.

Notes for whoever picks this up

I ran an adversarial design pass on this, including a runtime prototype. Two findings a naive implementation gets wrong — recording them so they are not rediscovered the hard way:

1. Do not gate on an "is this line attributable?" heuristic. A predicate that accepts any bracketed token or any word: prefix silently passes through lines that carry no source at all, including the banner lines this is meant to catch. Tag by source identity instead: the gateway tail child is the gateway source by construction, so tag every line it emits. Skip exactly one case by literal match, not heuristic — after stripping a leading timestamp that parseLineTimestamp recognizes, pass through byte-identical if the remainder already starts with [gateway] (idempotence, plus the #7322 banner shape). Leave genuinely empty lines untagged.

Note /tmp/gateway.log is fd 1 and fd 2 of openclaw gateway run (scripts/nemoclaw-start.sh does dup2(fd, 1) / dup2(fd, 2) before execvpe), so this source is raw Node process output — banners, Node warnings, uncaught-exception stack traces — not a structured log.

2. Gating source completion on both exit and stdout end hangs logs --follow forever when a descendant holds the gateway child's stdout write end. The existing 2000 ms forcedExitTimer does not save you: it is reachable only from requestExitAfterSignal and never fires on a natural child death. Arm a separate per-source drain grace timer on exit that destroys the stream and settles, cleared by end. A red-before-fix test can use a fake child of sh -c "printf 'banner\n'; (sleep 60) & exit 0" and assert the CLI exits within the grace window.

Also: do not let EPIPE overwrite the child's exit status (nemoclaw logs -f | head currently exits 141); and do not implement this as an in-sandbox sh -c "tail ... | sed ...", because the pipeline's exit status becomes sed's — POSIX sh/dash has no pipefail — which silently defeats the result.status !== 0 "OpenClaw log source unavailable" classification, and it would break the argv assertions in src/lib/actions/sandbox/logs.test.ts, test/cli/logs.test.ts, and test/cli/logs-documented-invocations.test.ts.

Two more implementation notes: the existing test fakes (createExitedChild, makeSpawnChild) are bare EventEmitters with no .stdout, so the code must tolerate child.stdout being absent; and terminal agents skip the gateway source entirely (shouldIncludeGatewayLogSource).

Estimated size: roughly 40-55 lines in the follow path, plus about 5 in mergeTailLogLines for the non-follow path, ideally sharing one tagger.

Refs #10325

Dongni-Yang avatar Aug 26 '26 03:08 Dongni-Yang

Ran the design to completion and adversarially verified it (three independent reviewers, one of which built the change in a throwaway checkout and measured the result). Recording the concrete design and the two defects the review found, so an implementer starts from the corrected version rather than the naive one.

Design

Tag at the relay boundary, on one source only.

The untagged lines can only come from the OpenClaw gateway-log source. scripts/nemoclaw-start.sh already pipes tail -F /tmp/gateway.log through sed -u 's/^/[gateway-log:] /' into PID 1 stderr, so the copy reaching the OpenShell source is already prefixed; the raw copy is the sandbox exec -- tail /tmp/gateway.log child built in src/lib/domain/sandbox/logs.ts. Scoping to that one source removes the double-tagging hazard by construction — the OpenShell source is never read, never rewritten, and keeps stdio: "inherit".

Tag string: [gateway]. It satisfies the issue's own attributability definition; the repo already writes literally [gateway] ${line} into this same stream at nemoclaw/src/index.ts (#7314/#7322); it matches the native gateway line shape; and it is true — the line came from that sandbox's OpenClaw gateway log. Rejected [gateway-log:] (that is a filterable docker-logs marker for a different purpose) and [nemoclaw] (invents a subsystem, and describes the relayer rather than the origin).

Insert the tag after any leading timestamp that parseLineTimestamp recognizes, so mergeTailLogLines' ^-anchored timestamp regexes still match and the chronological merge contract is preserved.

Rejected: continuation-line inheritance (the model in src/lib/domain/sandbox/logs.test.ts). Timestamp inheritance is safe — a continuation genuinely happened at the previous line's time — but subsystem inheritance is a guess. The gateway log carries several subsystems, so a config-warning banner following a [telegram] line would be labelled [telegram], which is worse than a constant. Inheritance also has no answer when tail -n N starts mid-banner.

Files: src/lib/domain/sandbox/logs.ts (~42 lines: the tag constant plus pure helpers), src/lib/actions/sandbox/logs.ts (~32: one call-site change for the non-follow path, plus an optional per-source tag and a line buffer for the follow path), and their two test files. Argv is never rewritten, so the sh -c "... | sed" pipefail trap is avoided and the existing argv assertions stay green. child.stdout is read with optional chaining so the bare-EventEmitter test fakes keep working.

Two defects the review found

Defect 1 (major): do not gate on an "is this line attributable?" heuristic.

A predicate accepting any bracketed token or any word: prefix silently passes through lines carrying no source at all — including banner lines this is meant to catch. Tag by source identity instead: the gateway tail child is the gateway source by construction, so tag every line it emits, and skip exactly one case by literal match — after stripping a recognized leading timestamp, pass through byte-identical if the remainder already starts with [gateway] (idempotence, plus the #7322 banner shape). Leave genuinely empty lines untagged. Coverage then becomes 100% by construction instead of depending on the reporter's unknown QA regex.

Worth knowing: /tmp/gateway.log is fd 1 and fd 2 of openclaw gateway run (nemoclaw-start.sh does dup2(fd, 1) / dup2(fd, 2) before execvpe), so this source is raw Node process output — banners, Node warnings, uncaught-exception stack traces — not a structured log.

Defect 2 (fatal, measured): requiring stdout end for source completion hangs logs --follow forever.

Once completion is gated on stdout end, any descendant inheriting the gateway child's stdout write end keeps end from firing, so markSourceDone never runs. The existing 2000 ms forcedExitTimer does not bound this: it is created only inside requestExitAfterSignal, reachable only from the SIGINT/SIGTERM handlers, and never fires on a natural child death.

Measured with an openshell stub whose sandbox branch backgrounds a survivor before exiting cleanly:

( sleep 30 ) &                        # grandchild inherits stdout, outlives the child
printf '%s\n' 'gateway banner line'
exit 0
  • pristine build: prints both lines, OpenClaw log source stopped (exit 0), exit 0, ~1s
  • naive design build: prints both lines, then hangs — killed by timeout 12 at 12s, no bound, no diagnostic

This is exactly the shape of the chosen source (openshell sandbox exec -- tail -F ...), so it is not a hypothetical.

Repair: make completion end OR a bounded timer, never end alone. On the piped source's exit, arm a short drain timer (a named constant around 200 ms is enough to close the exit-before-final-data window; do not reuse the 2000 ms signal timer, which does not exist on this path). Have both end and the timer call one idempotent finish that flushes the pending partial line, calls child.stdout?.destroy() — this is the part that makes a lingering grandchild harmless, by releasing the read end — and then markSourceDone. Keep requestExitAfterSignal's existing 2000 ms timer as-is for Ctrl-C.

Also: do not let EPIPE overwrite the child's exit status (nemoclaw logs -f | head currently exits 141).

Test-breakage sweep

Built the design plus repairs in a throwaway checkout and ran the seven relevant test files unmodified. Exactly one existing assertion breaks, and it is a correct break: src/lib/actions/sandbox/logs.test.ts "enables audit logs, reads both log sources, and writes merged output" moves from "[1] gateway\n[2] openshell\n" to "[1] [gateway] gateway\n[2] openshell\n" — the fixture gateway line is genuinely unattributable, and the untouched OpenShell line proves the second source is not rewritten. Everything else green, including test/cli/logs.test.ts over four consecutive runs with no flake. npm run typecheck:cli clean. No budget breach.

Two red-before-fix tests are worth adding beyond the obvious ones: the banner-tagging assertion above, and a process-level test using the backgrounded-survivor stub asserting the CLI exits within the grace window — that second one is the regression guard for Defect 2 and neither the existing suite nor the naive design has it.

Dongni-Yang avatar Aug 26 '26 03:08 Dongni-Yang

Implemented in #10342.

Both defects the design review found are handled: tagging is by source identity rather than an attributability heuristic, and source completion is stdout end OR a bounded drain timer rather than end alone. The hang case is covered by a new unit test that I confirmed is a true red→green — removing just the drain timer makes it time out.

Both paths are fixed, so plain nemoclaw <name> logs is attributable too, not only --follow.

Dongni-Yang avatar Aug 26 '26 04:08 Dongni-Yang