Skip to content

fix(#631): thread runId from CLI to MCP for exact log lookup - #635

Merged
admarble merged 2 commits into
mainfrom
feature/631-fix-mcp-log-file-lookup-races-on-concurrent-runs-a
May 13, 2026
Merged

admarble merged 2 commits into
mainfrom
feature/631-fix-mcp-log-file-lookup-races-on-concurrent-runs-a

Conversation

@admarble

Copy link
Copy Markdown
Contributor

Summary

Fixes readLatestRunLog in src/mcp/tools/run.ts returning the wrong log file under two scenarios:

  1. Concurrent sequant_run calls. Both filenames passed the 5-minute recency filter, and .sort().reverse() returned whichever filename was lexicographically latest — the wrong run could return another run's results.
  2. Stale same-issue log. A prior run's log within the 5-minute window was returned when the new log wasn't yet visible on disk (fsync lag, slow filesystem, write buffer).

Shared root cause: MCP had no way to identify which log file belonged to this subprocess.

The fix threads the runId end-to-end:

  • emitRunIdLine(runId) in src/lib/workflow/batch-executor.ts writes SEQUANT_RUN_ID:<uuid>\n to stderr (gated on SEQUANT_ORCHESTRATOR, mirroring emitProgressLine).
  • run-orchestrator.ts calls it immediately after logWriter.initialize() so the line precedes any SEQUANT_PROGRESS event.
  • MCP run.ts captures the line via the existing stderr line-buffer (now always-on so capture works regardless of whether the client passes a progressToken) and uses a new readRunLogById(runId) helper that matches by exact endsWith(-<runId>.json) suffix.
  • Fallback to readLatestRunLog(runStartTime) preserves today's behavior on older CLIs and on lookup miss — no new failure mode (AC-4).

Carved out from #508 per the 2026-04-09 architecture review; the parent in-process MCP rewrite remains parked.

AC Verification

AC Description Status Evidence
AC-1 CLI emits SEQUANT_RUN_ID:<uuid> once on stderr, before any SEQUANT_PROGRESS event ✅ emitRunIdLine in batch-executor.ts; called in run-orchestrator.ts right after logWriter.initialize(). Test: emitRunIdLine (#631 AC-1) > should be emittable before emitProgressLine (ordering invariant)
AC-2 readRunLogById(runId) added; exact filename suffix match; returns null if absent ✅ src/mcp/tools/run.ts:readRunLogById. Tests in readRunLogById (#631 AC-2, AC-5, AC-6) describe block
AC-3 MCP captures SEQUANT_RUN_ID and uses readRunLogById when available ✅ handleLine routes runId lines to capturedRunId; readlog path at run.ts uses capturedRunId first
AC-4 Fallback to readLatestRunLog(runStartTime) when runId not captured ✅ capturedRunId !== null ? await readRunLogById(...) : null) ?? await readLatestRunLog(...) — fallback also fires on lookup miss
AC-5 Two concurrent sequant_run calls return their own logs ✅ Test: should return the caller's own log when concurrent run logs coexist — both filenames pass the time filter but lookup returns the caller's own log
AC-6 Stale same-issue log inside 5-min window is not returned for a fresh run ✅ Test: should not return a stale same-issue log when looked up by fresh runId — stale file is lexicographically later, would have won under readLatestRunLog; runId lookup ignores it

Test plan

  • npm run build — clean
  • npm run lint — clean
  • npx vitest run src/mcp src/lib/workflow src/commands/run.test.ts — 1100 passed
  • npx vitest run __tests__/integration/mcp-e2e.integration.test.ts __tests__/integration/run-orchestrator.integration.test.ts — 19 passed
  • New tests: parseRunIdLine (4), readRunLogById (6 including AC-5 + AC-6 race fixtures), emitRunIdLine (3 including ordering invariant)

Closes #631

`readLatestRunLog` matched the wrong run-log under two scenarios:

1. Concurrent `sequant_run` calls — both filenames passed the 5-minute
   recency filter, and `.sort().reverse()` returned whichever was
   lexicographically latest.
2. Stale same-issue log — a prior run's log within the 5-minute window
   was returned when fsync lag meant the new log wasn't on disk yet.

Shared root cause: the MCP server had no way to identify which log file
belonged to the subprocess it just spawned.

Fix threads the runId end-to-end:

- `emitRunIdLine(runId)` in `batch-executor.ts` writes
  `SEQUANT_RUN_ID:<uuid>\n` to stderr (gated on `SEQUANT_ORCHESTRATOR`,
  mirroring `emitProgressLine`).
- `run-orchestrator.ts` calls it immediately after `logWriter.initialize()`
  so the line precedes any `SEQUANT_PROGRESS` event.
- MCP `run.ts` captures the line via the existing stderr line-buffer
  (now always-on so capture works without a `progressToken`) and uses a
  new `readRunLogById(runId)` helper that matches by exact filename
  suffix.
- Fallback to `readLatestRunLog(runStartTime)` preserves behavior on
  older CLIs (no runId emitted) and on lookup miss — no new failure
  mode.
…k logging

Refactor inline closure state out of `registerRunTool` so the runId-capture
and lookup-fallback paths can be exercised directly by tests. Adds
observability for the silent fallback path identified in QA Gap 3.

Changes:

- Extract `createRunIdCapture()` factory from the `registerRunTool` closure.
  Returns `{ routeLine, getCapturedRunId }`; `routeLine` captures the first
  valid runId line and otherwise delegates to `parseProgressLine`,
  returning the parsed event for the caller to emit.
- Extract `resolveRunLog(capturedRunId, runStartTime)` from the inline
  `readRunLogById ?? readLatestRunLog` chain at the spawn-result site.
  When a captured runId is set but `readRunLogById` returns null
  (corrupted file, slow fsync), emit
  `[mcp:run] runId <id> lookup miss — falling back to readLatestRunLog`
  on the MCP server's own stderr (`console.error`) so the silent
  fallback is observable.
- Update `hasProgressToken` comment to document its surviving purpose
  (gates `onProgress` timeout-reset only; no longer gates the buffer).

Test coverage added (14 new, total 77/77 in run.test.ts):

- `createRunIdCapture`: capture semantics, only-first-wins, fall-through
  to progress parsing, before- and after-capture paths.
- `createRunIdCapture + createLineBuffer` integration: chunk-boundary
  reconstruction, end-to-end AC-5 (two concurrent captures resolve to
  their own logs even when the wrong filename would win `.sort().reverse()`),
  end-to-end AC-6 (stale same-issue log is not returned; `readFile`
  throws on the stale path so regressions fail loudly).
- `resolveRunLog`: hit path (no debug line), miss-with-fallback path
  (debug line includes runId), null-capturedRunId path (no debug line),
  both-null path (returns null).
@admarble
admarble merged commit a104bea into main May 13, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(mcp): log-file lookup races on concurrent runs and stale same-issue logs

1 participant