Skip to content

fix(lsp): report a server that exits instead of hanging on it - #95

Merged
avifenesh merged 6 commits into
fix/lsp-close-epipefrom
fix/lsp-server-exit
Nov 5, 2026
Merged

avifenesh merged 6 commits into
fix/lsp-close-epipefrom
fix/lsp-server-exit

Conversation

@avifenesh

@avifenesh avifenesh commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #94. Review and land #94 first.

What was wrong

Four places where the spawn client could wait forever or keep a dead server.

  1. In-flight request when the server exits. vscode-jsonrpc rejects pending requests only on dispose(), not when the process exits. A hover in flight when the server died waited for the caller's abort. Through the lsp tool that became TIMEOUT after 30s, not SERVER_CRASHED.
  2. ensureServer during initialize. A server that died before answering initialize left ensureServer pending forever. So did one that stayed alive and never answered. A missing binary rejected with Cannot call write after a stream was destroyed.
  3. Unread stderr. The stderr pipe was created and never read. A server that wrote more than a pipe buffer to stderr blocked, which also stalled its LSP traffic.
  4. Broken stdin after startup. If the server closed its stdin while staying alive, the write failed but the entry stayed ready. Every later call reused it and failed, and it was never re-spawned.

Fix

packages/lsp/src/spawnClient.ts:

  • Every send runs through one helper, call(). When the process exits, the client builds an LspServerExitedError with the exit code or signal and the server's stderr tail. Each in-flight send rejects with it at once. A send that fails because the process is gone reports the exit, not the broken pipe. Sends subscribe to a one-shot notice and unsubscribe when they settle, so a long-lived server holds no reference to finished requests.
  • After the exit, the client waits one event-loop turn before it builds the error. Stderr already in the pipe arrives first, so the error carries the server's last words.
  • ensureServer rejects on exit and on a failed spawn, with the spawn error itself (for example spawn ... ENOENT). initialize is bounded by initializeTimeoutMs. It defaults to DEFAULT_TIMEOUT_MS, the 30s per-operation timeout in design spec section 8. That is the existing tool timeout. The spec's other startup number, SERVER_STARTUP_MAX_WAIT_MS (5s), is the indexing wait before server_starting, not a handshake bound.
  • stderr is always drained. Only the last 4 KB is kept, for the exit error. The spec gives no number for this. 4 KB holds a typical Node stack trace or Rust panic message and stays well under the 10 KB the tool already allows for hover text.
  • A write that finds stdin broken while the process lives retires the server: it is marked crashed and stopped (SIGTERM, then SIGKILL after 2s). The next call starts a new one. closeSession waits for these stops too, even after a re-spawn replaced the entry. A failed initialize also goes through this path, so a server that ignores SIGTERM is still stopped.
  • Entries are now updated in place instead of copied on ready, so each process's handlers only ever touch their own entry.

packages/lsp/src/lsp.ts maps LspServerExitedError to SERVER_CRASHED, as section 5.5 asks for the call that saw the death. LspServerExitedError and SpawnLspClientOptions are exported. Sections 5.3 and 5.5 of the spec describe the new behavior.

Tests

New cases in packages/lsp/test/spawnClient.test.ts, with new fake-server modes. All eight fail on #94's head (e68a4ab) and pass here.

Test #94 head This PR
Server exits during a hover rejects aborted at the 5s signal LspServerExitedError, exit code 1, stderr text; next call re-spawns
Same through the lsp tool TIMEOUT after 5s SERVER_CRASHED with the stderr text
Server closes stdin while alive, then hover same server reused next ensureServer starts a new server; the old one is gone after closeSession
Server exits during initialize hangs (10s test limit) LspServerExitedError, exit code 3
Server never answers initialize (300ms bound) hangs rejects, server stopped
Missing server binary Cannot call write after a stream was destroyed ENOENT
2 MiB to stderr, then answer initialize hangs ready
2 MiB to stderr, then exit hangs error ends with the last line; tail is at most 4 KB

The file passed 10 runs in a row, and 5 more pinned to one CPU.

Real server loop

packages/harness-e2e/test/lsp-transport.test.ts against typescript-language-server: 40 of 40 runs idle and 40 of 40 pinned to one CPU passed, with no unhandled error.

Checks

pnpm test:dependencies, pnpm lint:harness, and turbo run build typecheck test with harness-e2e filtered out all pass. The test file also type-checks under the package's strict settings. No Rust changes.

Review changes (31360e6)

  • The exit-write test tested nothing. It now lets hover run every step that needs no I/O before the abort, so the open is reading the file when the signal fires. With the 2s exit bound removed it fails 3 of 3 runs (10s test limit); with the bound it passes.
  • A broken stdin reported IO_ERROR. The call that finds it now rejects with LspServerCrashedError, the new base class of LspServerExitedError, and the tool returns SERVER_CRASHED with "The next call starts it again." Startup gets the same error, with the EPIPE as cause.
  • Spec 5.5 and the dead crashed branch. An idle exit is re-spawned by the next call, which proceeds; the spec now says so. ensureServer never returned a crashed handle, so the branch in lsp.ts is gone and ServerHandle.state is starting or ready. Third-party clients that returned crashed must throw instead.
  • A server that closes stdout but stays alive. When the connection closes and the process does not exit within one stop step (2s), the server is retired like a broken stdin. Calls waiting on it get SERVER_CRASHED, and the next call starts a new server.
  • ensureServer takes a signal. The lsp tool now creates its timeout before ensureServer and passes the signal, so one budget covers starting the server and the operation. A slow start returns TIMEOUT; the handshake goes on in the background, bounded by initializeTimeoutMs, and the next call gets server_starting. An already-aborted signal spawns nothing. The tool also removes its listener from session.signal when the call ends.
New or tightened test 61f99f3 31360e6
Tool calls against a server that closes stdin on hover hover, IO_ERROR: LSP error: write EPIPE, hover hover, SERVER_CRASHED, hover
Hover on a server that closes stdout and stays alive rejects aborted at the 5s signal LspServerCrashedError after 2s; next call starts a new server; old one gone after closeSession
ensureServer with a 300ms signal on a silent server hangs (10s test limit) rejects aborted; the next call gets the same server as starting
ensureServer with an aborted signal spawns and resolves ready rejects, spawns nothing
Tool call with a 500ms timeout on a silent server hangs TIMEOUT "while the fake server was starting", then server_starting
Broken stdin during startup, and after startup raw write EPIPE LspServerCrashedError with the EPIPE as cause
Idle SIGKILL between two tool calls both return a hover both return a hover (documents spec 5.5; no behavior change)

All spawn-client tests (24) pass; 7 of them fail on 61f99f3. The file passed 10 runs in a row, and 5 more pinned to one CPU. lsp-transport.test.ts passed 40 of 40 runs idle and 40 of 40 pinned to one CPU, with no unhandled error. pnpm test:dependencies, pnpm lint:harness and turbo run build typecheck test without harness-e2e pass.

Review changes (74bcb30, rebased on main)

The branch is rebased on main, so this PR's commit list also shows bc23e07 (#98, already on main): the base branch fix/lsp-close-epipe is still at e68a4ab.

  • A slow start outlives the call. The spawn client's initialize bound now defaults to DEFAULT_INITIALIZE_TIMEOUT_MS, the 60s session backstop (spec section 8), which also caps every call's budget. Spec 4, 5.3 and 8 and the changeset say so. Full-scale probe with the defaults and a server that answers initialize after 35s: call 1 at 30.0s TIMEOUT "The start goes on in the background; retry.", call 2 at 31.0s server_starting, call 3 at 36.0s a hover, one spawn. On 31360e6 the same shape gave TIMEOUT twice and two spawns.
  • Changeset is minor for harness-lsp and for the umbrella, which re-exports the narrowed type. It now spells out the break and what an adapter should do instead.
  • Rust port. ServerState::Crashed and the crashed branch in run.rs are gone; ensure_server returns an existing entry's handle directly, as it already did in practice. harness-lsp goes to 0.2.0 and the harness-tools crate, which re-exports it, to 0.5.0. cargo test --workspace --locked passes.
  • Accurate abort messages. The tool tells its own timeout apart from the caller cancelling. A call whose signal is already aborted returns "was cancelled before it started. Nothing was sent to the fake server." and spawns nothing; a call cancelled during a start says it was cancelled.
New test 31360e6 74bcb30
Default initialize bound is above the default call budget fails (no such bound) passes
Server ready after 800ms, initialize bound 3s, call budget 300ms fails on the message only; with these explicit limits the flow already worked TIMEOUT "The start goes on in the background; retry.", server_starting, hover, one spawn
Session signal already aborted TIMEOUT "exceeded 30000ms while the fake server was starting" "was cancelled before it started", no spawn
Session signal aborts at 200ms during a start "exceeded 30000ms ..." "was cancelled while the fake server was starting"

harness-lsp: 57 tests pass; the spawn-client file passed 10 runs in a row and 5 pinned to one CPU. lsp-transport.test.ts passed 40 of 40 idle and 40 of 40 pinned, no unhandled error. pnpm test:dependencies, pnpm lint:harness, turbo run build typecheck test without harness-e2e (39 of 39) and cargo test --workspace --locked pass.

Review changes, round 4 (c1709b5)

Rebased on main (#99). The Rust port gaps that predate this PR are tracked in #100.

  • A start that fails after its call gave up is reported. The failed start's error stays on its server entry until a caller has seen it. The next ensureServer for that key throws it once, so the tool returns SERVER_NOT_AVAILABLE with the reason, and the call after that starts a new server. Spec 5.3 and the changeset say so, and the DEFAULT_INITIALIZE_TIMEOUT_MS JSDoc says the limit must stay above the session's call budget.
  • The default initialize limit is tested directly. A fake-timer test (timers only; the server process stays real) checks that a start is still pending after DEFAULT_TIMEOUT_MS and fails at DEFAULT_INITIALIZE_TIMEOUT_MS. With the client's default set back to 30s, it fails.
  • The cancel-during-start test cancels once the start has begun, through a client wrapper, instead of on a 200ms clock.
  • Crate READMEs pin harness-lsp = "0.2" and harness-tools = "0.5".
New test before after
Silent server, initialize limit 800ms, call budget 300ms: call, wait 1.5s, call, call TIMEOUT, TIMEOUT (second spawn) TIMEOUT, SERVER_NOT_AVAILABLE "did not answer initialize within 800ms" (1 spawn), TIMEOUT (2 spawns)
Server exits with code 3 and "missing config, giving up" 800ms into the start, limit 3s, budget 300ms TIMEOUT, TIMEOUT TIMEOUT, SERVER_NOT_AVAILABLE with exit code 3 and the stderr text, 1 spawn
Default initialize limit, fake timers passes at 28957b2; fails with the default set back to 30s passes

"Before" is 28957b2, the rebased 74bcb30.

Checks on c1709b5: pnpm test:dependencies, pnpm lint:harness, turbo run build typecheck test without harness-e2e (39 of 39, 60 harness-lsp tests), cargo test --workspace --locked (278 passed). Spawn-client file: 20 of 20 runs idle, 25 of 25 pinned to one CPU. lsp-transport.test.ts: 40 of 40 idle, 40 of 40 pinned, no unhandled error.


Note

Medium Risk
Changes core LSP process lifecycle, timeouts, and a breaking public type; incorrect handling could still leak processes or mis-report errors, but behavior is heavily tested.

Overview
Fixes hangs and wrong errors when a spawned language server exits, stalls on initialize, floods stderr, or breaks stdio while the harness still treats it as usable.

The spawn client routes every JSON-RPC send through call(), rejecting in-flight work immediately with LspServerExitedError (exit code/signal plus a 4 KB stderr tail) or LspServerCrashedError for broken pipes. It drains stderr, bounds initialize with DEFAULT_INITIALIZE_TIMEOUT_MS (60s, overridable via createSpawnLspClient), and **retire()**s servers after stdin breaks or stdout closes without exit. ensureServer now accepts the tool call's AbortSignal: slow starts can TIMEOUT while startup continues; a failed start after the caller gave up surfaces once as SERVER_NOT_AVAILABLE.

The lsp orchestrator applies one timeout budget to startup plus the operation, maps crash errors to SERVER_CRASHED, and distinguishes timeout vs cancellation in messages. Breaking: public ServerHandle.state is only starting | ready (Rust ServerState::Crashed removed; 0.2.0 / 0.5.0). Design spec and extensive fake-server tests document the behavior; Vitest runs use an isolated TMPDIR via shared global setup.

Reviewed by Cursor Bugbot for commit c1709b5. Configure here.

Review: revuto stopped at its 3-round limit on this PR, so an independent review gated the landing: #95 (comment) (ready to land, no blocking findings).

@avifenesh
avifenesh added this pull request to stack #96 November 4, 2026 19:43
@cursor

cursor Bot commented Nov 4, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: adcd0cd6-d1ec-42c8-bcbe-664f48e1c030)

@revuto-review revuto-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an auto review done by revuto.


Revuto completed the review and found no evidence-backed concerns.

@avifenesh
avifenesh force-pushed the fix/lsp-server-exit branch from 080032b to 61f99f3 Compare November 4, 2026 19:58
@cursor

cursor Bot commented Nov 4, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: f04bcc54-658e-4ce9-89b0-394943dadb7c)

@revuto-review revuto-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an auto review done by revuto.


Revuto completed the review and found no evidence-backed concerns.

@avifenesh

Copy link
Copy Markdown
Collaborator Author

Verdict: needs changes. One blocking item, and it is a one-line test fix. The runtime changes work as described: every probe below behaved as the PR body says.

Blocking

1. The exit-write test from #94 no longer tests anything. packages/lsp/test/spawnClient.test.ts:152-153, cause at packages/lsp/src/spawnClient.ts:335.

requireReady is now async, and every operation awaits it before withAbort (:371, :397, :449, :500). The test calls hover and aborts in the same tick. The abort now lands before hover reaches the open, so no didOpen is queued, the exit write never waits behind it, and the test passes without the bound it was written for.

Evidence. I removed the within(...) around the exit write (:534):

Code under test Test as written
#94's spawnClient.ts hangs to the 10 s limit, 2 of 2 runs
this PR's spawnClient.ts passes, 3 of 3 runs

A replay of the test steps against that build shows why. As written, closeSession returns after 2.2 s (5 of 5). With one tick before the abort, it hangs (5 of 5).

Fix: let hover reach the open before the abort.

const op = client.hover(handle, file, POS, controller.signal);
// requireReady is async: let hover start the open before the abort.
await new Promise((resolve) => process.nextTick(resolve));
controller.abort();

With that line, the test fails 5 of 5 against the unbounded build, and passes 10 of 10 unpinned and 5 of 5 pinned on this PR. Keeping requireReady synchronous for a healthy entry would also work.

Non-blocking

  1. The call that finds a broken stdin reports IO_ERROR. spawnClient.ts:163 retires the server, and the next call re-spawns it. But the call itself returns IO_ERROR: LSP error: write EPIPE (lsp.ts:291). Three tool calls against a server that closes stdin on hover return hover, IO_ERROR: LSP error: write EPIPE, hover. A model that reads IO_ERROR gets no hint that a retry works. Rejecting with an error that lsp.ts maps to SERVER_CRASHED ("The next call starts it again.") would match the other death paths.
  2. Spec 5.5, first bullet (agent-knowledge/design/lsp.md:320) does not match the code. A server that exits while idle is re-spawned by the next call's ensureServer, and that call succeeds: I SIGKILLed the server between two tool calls, and both returned a hover. No call gets SERVER_CRASHED, and the handle.state === "crashed" branch (lsp.ts:178) cannot fire with the spawn client. This predates the PR. The PR edits 5.5 anyway, so one sentence fixes it.
  3. A server that closes stdout but stays alive is never retired. This is the read-side twin of the broken-stdin fix. In a probe the first hover times out. Every later call fails with Connection is closed. (IO_ERROR), and ensureServer keeps returning the same server until closeSession. Retiring on conn.onClose would cover it. It is rare, so a follow-up is fine.
  4. ensureServer takes no signal. session.signal cannot cancel a slow initialize, which waits up to initializeTimeoutMs (30 s by default). The bound holds, so this is an interface follow-up, not a bug here.

Temp dirs in /tmp

This should not be fixed in #95. The leak is not limited to lsp. One full turbo run test left 220 directories in the temp dir: write 43, skill 38, read 36, glob 34, grep 28, bash 21, lsp 18, and 2 from the tools package's ledger test. The new spawn-client tests already remove theirs. One separate change across all packages is cleaner than an lsp-only patch in a PR about server exits. Either clean up in each package's test helper, or use a vitest global setup that points TMPDIR at a per-run directory and removes it.

Checked and fine

  • In-flight request on exit rejects at once with LspServerExitedError: during didOpen (6 ms, exit code 2, stderr text), during hover, after initialize, on initialized, and with an old handle after an idle SIGKILL (was killed by SIGKILL). On fix(lsp): stop language servers without racing their exit #94 the didOpen and post-initialize cases never settle.
  • No unhandled rejection in any probe. They run as plain Node scripts with no unhandledRejection listener, so one would exit 1. Cases: already-aborted signal on all six operations (nothing sent), abort mid-request, abort and then server death 400 ms after the abort, every death above, and closeSession during initialize, during a hover and during a blocked didOpen. Also two concurrent closeSession calls, and closeSession while a retired server is still stopping.
  • closeSession: during initialize, ensureServer rejects with was killed by SIGTERM and the server is gone in 4 ms. During a hover, the hover rejects with the exit error. During a blocked didOpen, it returns after the 2 s shutdown bound. With a retired server that ignores SIGTERM, it returns after 2.0 s with that server gone, so the stops set works. No server was left running after any probe or test run.
  • Timers: every probe script exits within 11 ms of its last line. within clears its timer on every path.
  • stderr: appendTail keeps at most 4096 bytes. The flood tests pass in every loop, pinned too.
  • Tool codes: death during an operation gives SERVER_CRASHED with the stderr tail. initialize with no answer in 300 ms gives SERVER_NOT_AVAILABLE "did not answer initialize within 300ms". A missing binary gives SERVER_NOT_AVAILABLE with spawn ... ENOENT.
  • conn.dispose() now runs from both markGone and stopServer. That is safe: vscode-jsonrpc 10 returns early from a second dispose().
  • The changeset and spec sections 5.3 and 5.5 match the code, apart from item 3. The umbrella package re-exports LspServerExitedError through export *.

What I ran

  • pnpm test:dependencies, pnpm lint:harness, and turbo run build typecheck test --filter='!@agent-sh/harness-e2e' --force: all pass, 39 of 39 tasks. harness-lsp has 47 tests.
  • The 8 new tests against fix(lsp): stop language servers without racing their exit #94's head (e68a4ab): all 8 fail, in 2 of 2 runs unpinned and 1 of 1 pinned. The 10 tests from fix(lsp): stop language servers without racing their exit #94 pass there.
  • spawnClient.test.ts on this PR: all 18 tests pass in 20 of 20 runs unpinned and 10 of 10 pinned with taskset -c 0. No unhandled error, and no server left running after a run.
  • packages/harness-e2e/test/lsp-transport.test.ts against typescript-language-server: 40 of 40 runs pass unpinned and 40 of 40 pinned to one CPU. No log shows an unhandled error, EPIPE or ERR_STREAM_DESTROYED.
  • Every probe above ran unpinned and pinned with the same outcomes. The one pinned difference came from my fake server, which answered a queued hover before it finished exiting.
  • CI: TypeScript, Rust and CodeQL pass. revuto approved 61f99f3. Bugbot did not run (usage limit).

@avifenesh
avifenesh deleted the branch fix/lsp-close-epipe November 4, 2026 21:18
@avifenesh avifenesh closed this Nov 4, 2026
@avifenesh avifenesh reopened this Nov 4, 2026
@cursor

cursor Bot commented Nov 4, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: 4903a2ac-b175-44e4-a8b1-24386102ebdb)

@cursor

cursor Bot commented Nov 4, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: f3bd179b-1bbf-4a15-8e36-468b3537fd74)

@avifenesh

Copy link
Copy Markdown
Collaborator Author

Re #95 (comment): all five points are addressed in 31360e6.

  1. Exit-write test. It now waits one process.nextTick before the abort, so hover has run every step that needs no I/O and the open is reading the file. With the 2s exit bound removed it fails 3 of 3 runs at the 10s limit; with the bound it passes 3 of 3, and in every loop below.
  2. Broken stdin reported IO_ERROR. The call that finds stdin broken now rejects with LspServerCrashedError (new base class of LspServerExitedError), and lsp.ts maps it to SERVER_CRASHED with "The next call starts it again." New tool-level test: three calls against a server that closes stdin on hover return hover, SERVER_CRASHED, hover. On 61f99f3 the middle one is IO_ERROR: LSP error: write EPIPE.
  3. Spec 5.5 and the dead branch. The spec now says an idle exit is re-spawned by the next call, which proceeds, and that a call that sees the death gets SERVER_CRASHED. The handle.state === "crashed" branch is gone and ServerHandle.state is starting or ready. This one changes no behavior, so its test (idle SIGKILL between two tool calls, both return a hover) passes on 61f99f3 too; the type narrowing is checked by tsc.
  4. Stdout closed, process alive. On conn.onClose, if the process does not exit within one stop step (2s), the server is retired and calls waiting on it get SERVER_CRASHED. New test: a server that closes stdout on hover. On 61f99f3 the hover waits for its 5s signal; now it rejects with "closed its output" after 2s, the next ensureServer starts a new server, and the old one is gone after closeSession.
  5. ensureServer signal. ensureServer takes signal, and lsp.ts passes the call's signal, so one budget covers the start and the operation. An abort releases the caller; the handshake goes on, bounded by initializeTimeoutMs, and the next call gets server_starting. An already-aborted signal spawns nothing. New tests: a 300ms signal on a silent server (61f99f3 hangs; now rejects aborted and the next call gets the same server as starting), an aborted signal (61f99f3 spawns and resolves ready; now nothing is spawned), and a tool call with a 500ms timeout on a silent server (61f99f3 hangs; now TIMEOUT then server_starting).

Startup with a broken stdin now also rejects with LspServerCrashedError, with the EPIPE as cause; the #94 test asserts that.

The temp-dir cleanup goes in a separate PR to main, as you suggested.

Reran: harness-lsp build, typecheck and tests (53 pass, 24 in the spawn-client file). pnpm test:dependencies, pnpm lint:harness and turbo run build typecheck test without harness-e2e pass (39 of 39 tasks). The spawn-client file passed 10 runs in a row and 5 pinned to one CPU. lsp-transport.test.ts passed 40 of 40 idle and 40 of 40 pinned, with no unhandled error.

@revuto-review revuto-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an auto review done by revuto.


Revuto completed the review and found no evidence-backed concerns.

A full test run left about 220 directories in the system temp dir:
write, skill, read, glob, grep, bash and lsp test helpers create one per
test and never remove it, and the tools package's ledger test leaves two.
Turbo's strict env mode also dropped TMPDIR, so the tests wrote to /tmp
even when TMPDIR pointed elsewhere.

Every package's vitest config now runs scripts/vitest-temp-dir.ts as a
global setup. It creates a fresh directory under the inherited temp dir,
points TMPDIR at it for the run, and removes it when the run ends. That
covers what the helpers create, what source code under test writes
through os.tmpdir(), and caches dependencies keep there. core and tools
get a vitest config for it. turbo.json passes TMPDIR through to tasks
and lists the setup script as a global dependency.
@avifenesh

Copy link
Copy Markdown
Collaborator Author

Verdict: needs changes. Two blocking items, both small. All five earlier findings are fixed, and each fix's test fails on 61f99f3 and passes on 31360e6.

Blocking

1. With the default timeouts, a slow start does not keep starting. packages/lsp/src/lsp.ts:188, cause at packages/lsp/src/spawnClient.ts:97. The same claim is in spawnClient.ts:382-384, spec agent-knowledge/design/lsp.md:377 and .changeset/lsp-server-exit.md:5.

The tool's budget is DEFAULT_TIMEOUT_MS (30 s), and so is the default initializeTimeoutMs. The tool's timer starts first, so the call returns TIMEOUT with "Retry; the server keeps starting in the background." A few ms later the initialize bound fires and stops the server. The next call spawns a new server and waits the full budget again. No call ever gets server_starting, and the model is told to retry something that cannot succeed.

Probe: a fake server that answers initialize after 35 s, default client, default session, calls 1 s apart.

Call Result on 31360e6 Servers spawned
1 (at 30 s) TIMEOUT "... keeps starting in the background." 1
2 (at 61 s) TIMEOUT, same text 2

Same shape at small scale (both bounds 500 ms, server answers after 800 ms, calls 200 ms apart): TIMEOUT three times, three spawns. On 61f99f3 those calls return SERVER_NOT_AVAILABLE "did not answer initialize within 500ms", which is true. With the initialize bound above the call budget (3 s against 500 ms) the new path works as described: TIMEOUT, server_starting, then a hover, one spawn.

Spec 5.3 (lsp.md:310) also still says the tool returns SERVER_NOT_AVAILABLE when the initialize bound passes. With the defaults the call's own TIMEOUT always wins.

Fix: default the initialize bound above the tool's budget, so the start can outlive the call that began it. SESSION_BACKSTOP_MS (60 s, spec section 8) is an existing number. Then update 5.3, section 8 and the changeset. A test that pins the relation between the two defaults keeps it from coming back. If the bound should stay at 30 s, the message should not promise that the server keeps starting.

2. The changeset bump is patch for a breaking type change. .changeset/lsp-server-exit.md:2, packages/lsp/src/types.ts:62.

Narrowing ServerHandle.state breaks compile for code that compares it with "crashed" (TS2367) and for an LspClient adapter that returns it (TS2322). I type-checked a small consumer against both builds' .d.ts: both errors on 31360e6, clean on 61f99f3. The package advertises a pluggable LspClient, and ^0.9.2 picks up 0.9.3 by itself. On 0.x, minor is the bump that signals a break.

Nothing I could find relies on "crashed". In the repo, no TypeScript reads it after this PR. The downstream repos I could check use only lsp and createSpawnLspClient. So the risk is low, but the label should be minor.

Non-blocking

  1. The Rust port keeps crashed. The spec now says state is never crashed (lsp.md:320, :410). crates/lsp/src/types.rs:59 still has ServerState::Crashed, and crates/lsp/src/run.rs:170 still has the branch this PR removed from lsp.ts. The spec is the cross-language source, so a follow-up issue for the Rust port, or a note in 5.5, would keep them from drifting.
  2. An already-aborted call signal gets the same text with nothing started. spawnClient.ts:228 throws before it spawns, and lsp.ts:171 plus :188 report TIMEOUT "exceeded 30000ms while the fake server was starting ... keeps starting in the background" after 2 ms, with no server spawned. The caller has already cancelled, so few models will read it.

Earlier findings, rechecked

  1. Exit-write test. I removed the within(...) around the exit write (spawnClient.ts:589). The new test hangs to its 10 s limit, 3 of 3 runs unpinned and 5 of 5 pinned. The 61f99f3 version of the test passes 3 of 3 against the same change, so the nextTick is what makes it test the bound. One tick is enough: Node drains the microtask queue before the tick runs, so hover has reached readFile before the abort.
  2. Broken stdin. The tool-level test returns IO_ERROR for the middle call on 61f99f3 and SERVER_CRASHED here.
  3. Spec 5.5 and the dead branch. 5.5 matches the code. The idle-SIGKILL test passes on both heads, as the reply says.
  4. Stdout closed. On 61f99f3 the hover ends with "aborted" after 5 s. Here it rejects with "closed its output" after 2 s, the next ensureServer starts a new server, and the old one is gone after closeSession.
  5. ensureServer signal. On 61f99f3 two of the three new tests time out at 10 s and the aborted-signal one resolves ready. All pass here.

The new spawn-client file against 61f99f3's source: 7 of 24 tests fail. They are the five new tests for items 2, 4 and 5, and the two #94 tests that now expect LspServerCrashedError. The tests for items 1 and 3 pass there, as expected.

Paths probed

Plain Node scripts against the built dist, with a fake server that dies or stalls at each stage. Each recorded unhandled rejections and printed the active handles at the end.

  • Listeners. session.signal has 0 abort listeners after a hover, after a TIMEOUT during start, after SERVER_CRASHED, and after both pipes closed.
  • Death after initialize, on initialized, on didOpen. SERVER_CRASHED with the exit code, plus the stderr tail for didOpen. The next call starts a new server.
  • closeSession during initialize. Returns in 3 ms. ensureServer rejects with "was killed by SIGTERM" and no server is left. Also fine after an aborted ensureServer (2 ms), and with a tool call in flight (SERVER_NOT_AVAILABLE "killed by SIGTERM").
  • Stdout closed, SIGTERM ignored. The call gets SERVER_CRASHED after 2 s, the next call starts a new server, and closeSession returns in 2.0 s with both gone. With closeSession before the 2 s retire, it also returns in 2.0 s, the server is gone, and nothing fires afterwards.
  • No unhandled rejection in any probe. Every script exited within 1 ms of its last line, so no timer was left.

What I ran

  • turbo run build typecheck test --filter='!@agent-sh/harness-e2e' --force: 39 of 39 tasks, 53 tests in harness-lsp. pnpm test:dependencies and pnpm lint:harness pass.
  • spawnClient.test.ts: 20 of 20 runs idle and 10 of 10 pinned with taskset -c 0, 24 tests each. No unhandled error, and no server left after any run.
  • packages/harness-e2e/test/lsp-transport.test.ts against typescript-language-server: 30 of 30 idle and 30 of 30 pinned. No unhandled error, no EPIPE or ERR_STREAM_DESTROYED in any log, no server left.
  • CI: TypeScript, Rust and CodeQL pass on 31360e6. revuto approved 31360e6. Bugbot did not run (usage limit).

webfetch.test.ts shares one handler across tests and only tests that
call setHandler replace it. "allows public IP" relies on the default, so
under a shuffled order it saw whatever the previous test installed and
failed (vitest --sequence.shuffle, seeds 7, 11, 13 and 17 of 12 tried).
beforeEach now restores the default handler.
@avifenesh
avifenesh force-pushed the fix/lsp-server-exit branch from 31360e6 to 74bcb30 Compare November 4, 2026 22:24
@cursor

cursor Bot commented Nov 4, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: 49f2498d-9211-4882-b622-cfd29bd9388c)

@avifenesh

Copy link
Copy Markdown
Collaborator Author

Re #95 (comment): addressed in 74bcb30, rebased on main. The commit list now also shows bc23e07 (#98, already on main), because the base branch is still at e68a4ab.

  1. Slow start. The initialize bound defaults to DEFAULT_INITIALIZE_TIMEOUT_MS, the 60s session backstop, which also caps every call's budget. Spec 4, 5.3 and 8 and the changeset match. A test pins that the default bound is above the default call budget (fails on 31360e6: no such bound). A scaled test (bound 3s, budget 300ms, server ready at 800ms) checks TIMEOUT, server_starting, hover, one spawn. Your full-scale shape, run once with the defaults and a 35s server: TIMEOUT at 30.0s with "The start goes on in the background; retry.", server_starting at 31.0s, a hover at 36.0s, one spawn.
  2. Changeset is minor for harness-lsp and for harness-tools, which re-exports the type. It names the break and says an adapter should throw LspServerCrashedError instead.
  3. Rust port. ServerState::Crashed and the run.rs branch are removed; ensure_server returns an existing entry's handle directly, which is what it did before since nothing set Crashed. harness-lsp 0.2.0, harness-tools crate 0.5.0 (it re-exports harness-lsp), Cargo.lock updated. cargo test --workspace --locked passes.
  4. Aborted signal. The tool now tracks whether its own timer fired. An already-aborted signal returns "LSP hover was cancelled before it started. Nothing was sent to the fake server." with no spawn; a cancel during a start or an operation says it was cancelled. The code stays TIMEOUT, as before, since there is no cancel code. Two new tests, both failing on 31360e6.

Reran on 74bcb30: pnpm test:dependencies, pnpm lint:harness, turbo run build typecheck test without harness-e2e (39 of 39, 57 harness-lsp tests), cargo test --workspace --locked. Spawn-client file 10 of 10 runs and 5 of 5 pinned. lsp-transport.test.ts 40 of 40 idle and 40 of 40 pinned, no unhandled error.

@avifenesh

Copy link
Copy Markdown
Collaborator Author

Verdict: needs changes. Three blocking items, all small. All four points from the last review are fixed, and nothing from earlier rounds regressed.

Blocking

1. When a start fails after its first call has left, no call reports why. packages/lsp/src/spawnClient.ts:383-387 drops the error, and spawnClient.ts:226 starts a new server on the next call. Spec 5.3 (agent-knowledge/design/lsp.md:311) says the tool returns SERVER_NOT_AVAILABLE with the reason when the process exits. That holds only while the first call is still waiting.

The background start is new in this PR. If it ends in an exit or at the initialize limit, the error (exit code, stderr tail, "did not answer initialize within ...") goes to starting.catch(() => {}). The next call finds the entry crashed, spawns a new server and waits its whole budget again. The model sees TIMEOUT "The start goes on in the background; retry." and server_starting, over and over, and never the server's last words. With the defaults this hits a server that hangs in initialize, or one that dies 30 to 60 s into it.

Probes against the built dist, scaled down (initialize limit 1 s or 3 s, call budget 300 ms, calls 200 ms apart):

Server Calls over about 3 s Spawns SERVER_NOT_AVAILABLE
Never answers initialize (limit 1 s) 13 calls: 4 TIMEOUT, each followed by server_starting until the limit stops that server; retryMs climbs to 30000 4 never
Writes "missing config, giving up" to stderr and exits with code 3 at 800 ms (limit 3 s) 8 calls: 3 TIMEOUT, each followed by server_starting until the server exits 3 never; the stderr text is in no result

Suggested fix: when starting rejects and no caller got the error, keep it on the key (and drop it in closeSession). The next ensureServer for that key throws it once instead of spawning, so that call returns SERVER_NOT_AVAILABLE with the reason, and the call after it starts a new server. Then add a line to 5.3. A test: the scaled case above with a server that exits during a background start, expecting TIMEOUT, then SERVER_NOT_AVAILABLE with the exit code and stderr text.

This also covers a boundary the defaults leave open. DEFAULT_INITIALIZE_TIMEOUT_MS is a fixed 60 s, but the call budget comes from the session (lsp.ts:163-167). A session with defaultTimeoutMs: 60_000 makes the two equal, and the last round's bug returns: with both at 500 ms and a server that answers after 800 ms, each of three calls gets TIMEOUT "The start goes on in the background; retry.", and each starts a new server. With the fix above, the second call would at least say the server did not answer in time. The JSDoc at constants.ts:4-10 could also say the limit must stay above the session's call budget.

2. No test fails when the fix itself is reverted. packages/lsp/test/spawnClient.test.ts:607-611 compares the constants, and the scaled test at :613 passes initializeTimeoutMs: 3_000 explicitly. I changed spawnClient.ts:98 back to options.initializeTimeoutMs ?? DEFAULT_TIMEOUT_MS: all 28 spawn-client tests pass.

A test that checks the default the client actually uses, with fake setTimeout only (the child process and its pipes stay real):

it("bounds initialize by DEFAULT_INITIALIZE_TIMEOUT_MS by default", async () => {
  const client = createSpawnLspClient();
  vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
  try {
    const outcome = client
      .ensureServer({ language: "fake", root, profile: fakeProfile("silent-on-initialize", root) })
      .then(() => "ready", (e: unknown) => (e as Error).message);
    let settled: string | undefined;
    void outcome.then((m) => (settled = m));
    await vi.advanceTimersByTimeAsync(DEFAULT_TIMEOUT_MS + 1);
    expect(settled).toBeUndefined();
    await vi.advanceTimersByTimeAsync(DEFAULT_INITIALIZE_TIMEOUT_MS - DEFAULT_TIMEOUT_MS);
    expect(await outcome).toContain(`within ${DEFAULT_INITIALIZE_TIMEOUT_MS}ms`);
  } finally {
    vi.useRealTimers();
    await client.closeSession();
  }
}, HANG_LIMIT_MS);

It passes on 74bcb30 (10 of 10 runs idle, 5 of 5 pinned to one CPU) and fails on the reverted line ("did not answer initialize within 30000ms" after 30 s of fake time). It runs in well under a second.

3. The new cancel-during-start test is flaky on a busy CPU. packages/lsp/test/spawnClient.test.ts:668 creates AbortSignal.timeout(200) in makeSession, before lsp runs. When the call takes longer than 200 ms to reach its abort check, it gets the other message. It failed 1 of 25 runs of the file pinned with taskset -c 0 while the machine was busy, and in none of 20 idle runs:

- "message": StringContaining "was cancelled while the fake server was starting",
+ "message": "LSP hover was cancelled before it started. Nothing was sent to the fake server.",

Abort once the start has begun, not on a clock. For example, wrap the client so ensureServer aborts the session's controller right after it starts the server:

const inner = createSpawnLspClient();
const cancel = new AbortController();
const client: LspClient = {
  ...inner,
  ensureServer: (args) => {
    const starting = inner.ensureServer(args);
    cancel.abort();
    return starting;
  },
};
// makeSession(root, client, { ..., signal: cancel.signal }); closeSession on `inner`.

That version passed 10 of 10 runs pinned and fails on 31360e6 with the old message.

Non-blocking

  1. Crate READMEs still pin the old minor. crates/lsp/README.md:11 says harness-lsp = "0.1" and crates/harness-tools/README.md:11 says harness-tools = "0.4". Every other crate README matches its crate's minor. With the bumps they should be "0.2" and "0.5".
  2. The Rust port lacks what the spec now describes. crates/lsp/src/spawn_client.rs:455 has no initialize limit and nothing notices a server exit, while the spec table (lsp.md:253) and 5.3 and 5.5 describe both. This predates the PR, and removing Crashed changes no Rust behavior. A follow-up issue would keep the port from drifting further.
  3. revuto did not review 74bcb30. Its check is red because the PR reached the 3-round limit. This is not a finding on the code, but the check needs a manual decision before landing.

The last review's points

  1. Slow start. Full scale, real defaults, a server that answers initialize after 35 s: TIMEOUT at 30.0 s with "The start goes on in the background; retry.", server_starting at 31.0 s, a hover at 36.0 s, one spawn, no server left, no unhandled rejection, no active handle at the end. Spec 4, 5.3 and 8 and the changeset say 60 s.
  2. Changeset. minor for @agent-sh/harness-lsp and @agent-sh/harness-tools. changeset status plans both at 0.10.0 (they are linked). No other published package depends on harness-lsp; harness-e2e is private and ignored.
  3. Rust port. ServerState::Crashed and the run.rs branch are gone; nothing in crates/ names it any more. harness-lsp 0.2.0 and harness-tools 0.5.0 fit: crates.io has 0.1.1 and 0.4.1, the variant removal breaks a match on it, and harness-tools re-exports the crate (pub use harness_lsp as lsp). harness-tools is the only crate that depends on harness-lsp, and nothing depends on harness-tools. Cargo.lock matches (--locked passes).
  4. Aborted signal. "LSP hover was cancelled before it started. Nothing was sent to the fake server." in 0 ms, no spawn, 0 abort listeners on session.signal. A cancel during a start says "was cancelled while the fake server was starting"; the start goes on and the next call gets server_starting, then a hover from the same server. A cancel during a hover gets "LSP hover was cancelled."

New tests against 31360e6's source: all 4 new tests fail (the constant is missing; the scaled test on the message only; both cancel tests on the message). The other 24 pass. On 74bcb30 all 28 pass.

Earlier rounds, rechecked

Probes against the built dist, each recording unhandled rejections, abort listeners on session.signal, active handles and live server pids at the end:

  • Death at each stage. Exit during initialize: SERVER_NOT_AVAILABLE with exit code 3 and the stderr text. Exit during hover: SERVER_CRASHED with exit code 1 and the stderr text. Stdin closed: hover, SERVER_CRASHED "stopped reading its input (write EPIPE)", hover. Stdout closed: SERVER_CRASHED "closed its output" after about 2 s, and the next call starts a new server.
  • closeSession during a start: returns in 4 ms; the call gets SERVER_NOT_AVAILABLE "killed by SIGTERM". During a hover: the hover gets SERVER_CRASHED with exit code 0.
  • In every probe: no unhandled rejection, 0 listeners, no live server, and no timer left (only the probe's own stdout and stderr pipes).

What I ran

  • pnpm test:dependencies and pnpm lint:harness pass.
  • turbo run build typecheck test --filter='!@agent-sh/harness-e2e' --force: 39 of 39 tasks.
  • cargo test --workspace --locked: 278 passed, 0 failed.
  • spawnClient.test.ts (28 tests): 20 of 20 runs idle and 24 of 25 pinned with taskset -c 0; the one failure is item 3. No unhandled error in any log, and no server left after any run.
  • packages/harness-e2e/test/lsp-transport.test.ts against typescript-language-server: 30 of 30 idle and 30 of 30 pinned. No unhandled error, EPIPE or ERR_STREAM_DESTROYED in any log, and no server left.
  • CI: TypeScript, Rust and CodeQL pass on 74bcb30. Bugbot did not run (usage limit).

Four ways the spawn client could wait forever or lose a server:

A request in flight when the server process exited waited for the
caller's abort, because vscode-jsonrpc rejects pending requests only on
dispose. Every send now runs through one helper that rejects at once
with LspServerExitedError once the process is gone. The error carries
the exit code or signal and the server's last stderr output, and the
lsp tool returns it as SERVER_CRASHED for that call.

ensureServer waited forever when the server died during initialize, and
had no bound on a server that never answered. It now rejects on exit or
on a failed spawn (the spawn error, for example ENOENT), and initialize
is bounded by the per-operation timeout, DEFAULT_TIMEOUT_MS from design
spec section 8. createSpawnLspClient takes initializeTimeoutMs to
override it.

The server's stderr pipe was never read, so a server that wrote enough
to it blocked. The client now drains it and keeps the last 4 KB for the
exit error.

A server whose stdin broke after startup stayed marked ready and was
never re-spawned. A write that finds stdin broken while the process
lives now marks the server crashed and stops it; closeSession waits for
that stop too.

Each case has a fake-server test that fails on the parent branch and
passes here.
Address review on the server-exit fix.

The exit-write test aborted in the same tick as the hover. With
requireReady async, the abort landed before the open started, so the
test passed without the exit bound. It now lets the hover run every
step that needs no I/O before the abort, and fails again with the bound
removed.

A call that found stdin broken returned IO_ERROR although the client had
already retired the server. It now rejects with LspServerCrashedError,
the new base class of LspServerExitedError, and the tool reports
SERVER_CRASHED.

A server that closed stdout but stayed alive was never retired, so every
later call failed with "Connection is closed". When the connection
closes and the process does not exit within one stop step (2s), the
server is retired the same way and calls waiting on it get
SERVER_CRASHED.

ensureServer takes the call's signal. The lsp tool's timeout now covers
starting the server: a slow start returns TIMEOUT, the handshake goes
on in the background, and the next call gets server_starting.

ensureServer never returned a crashed handle, so the tool's crashed
branch could not fire. The branch is gone, ServerHandle.state is
starting or ready, and design spec section 5.5 now says an idle exit is
re-spawned by the next call.
…ancelled

Address review on the follow-up.

With the defaults, the call budget and the initialize bound were both
30s. The call's timer fired first and returned TIMEOUT saying the server
keeps starting, and the initialize bound then stopped that server, so a
server slower than 30s never finished starting. The initialize bound now
defaults to DEFAULT_INITIALIZE_TIMEOUT_MS, the 60s session backstop,
which also caps every call's budget. A test pins that relation, and a
scaled-down test checks the flow: TIMEOUT, then server_starting, then
the result, from one spawn.

The tool now tells its own timeout apart from the caller cancelling. A
call whose signal is already aborted says it was cancelled before it
started and sends nothing; one cancelled during a start or an operation
says it was cancelled.

Narrowing ServerHandle.state breaks consumer compiles, so the changeset
is minor for harness-lsp and the umbrella.

The Rust port matches the spec: ServerState has no Crashed variant and
run has no crashed branch. harness-lsp goes to 0.2.0 and the
harness-tools crate, which re-exports it, to 0.5.0.
Address review on the follow-up.

When the call that began a start gave up, a later failure of that start
(an exit, or the initialize limit) was dropped, and the next call quietly
spawned a new server. The model saw TIMEOUT and server_starting over and
over, never the exit code or stderr. The failed start's error now stays
on its server entry until a caller has seen it. The next ensureServer for
that key throws it once, so the tool returns SERVER_NOT_AVAILABLE with
the reason, and the call after that starts a new server. Design spec 5.3
says so, and that the initialize limit must stay above the call budget.

A fake-timer test checks the client's default initialize limit itself,
so reverting the default fails a test. The cancel-during-start test now
cancels once the start has begun instead of on a 200ms clock, which a
busy machine could beat.

The crate READMEs pin harness-lsp 0.2 and harness-tools 0.5.
@avifenesh
avifenesh force-pushed the fix/lsp-server-exit branch from 74bcb30 to c1709b5 Compare November 4, 2026 23:27
@cursor

cursor Bot commented Nov 4, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: 7cc5a992-f141-4a44-b4e6-ae7157ea64b8)

@avifenesh

Copy link
Copy Markdown
Collaborator Author

Re #95 (comment): addressed in c1709b5, rebased on main (#99).

  1. Background start failures are reported. The failed start's error stays on its server entry until a caller has seen it. The next ensureServer for that key throws it once and drops the entry, so the tool returns SERVER_NOT_AVAILABLE with the reason, and the call after that starts a new server. closeSession drops it with the rest. Both of your reproductions are tests now and fail on 28957b2 (the rebased 74bcb30):
    • silent server, limit 800ms, budget 300ms: TIMEOUT, then after 1.5s SERVER_NOT_AVAILABLE "did not answer initialize within 800ms" with one spawn, then a fresh start (TIMEOUT, two spawns). Before: TIMEOUT, TIMEOUT.
    • server that exits with code 3 and "missing config, giving up" 800ms into the start, limit 3s: TIMEOUT, then SERVER_NOT_AVAILABLE with "exited with code 3" and the stderr text, one spawn. Before: TIMEOUT, TIMEOUT.
      Spec 5.3 and the changeset describe it, and the DEFAULT_INITIALIZE_TIMEOUT_MS JSDoc and 5.3 say the limit must stay above the session's call budget. At the equal-budget boundary the next call now gets the reason instead of another silent spawn.
  2. The default is tested. Your fake-timer test is in, as written. It passes here and fails with the client's default set back to 30s ("expected 'Language server for fake did not answ…' to be undefined").
  3. Cancel test. It now cancels from a client wrapper right after ensureServer starts the server, as you sketched.
  4. READMEs pin harness-lsp = "0.2" and harness-tools = "0.5".
  5. Rust port: Rust lsp port: initialize bound, exit detection, stderr and shutdown per the design spec #100 describes the gaps (no initialize bound, no exit detection, unread stderr, no start cancellation, unbounded shutdown) with spec references. Not implemented here.

Reran on c1709b5: pnpm test:dependencies, pnpm lint:harness, turbo run build typecheck test without harness-e2e (39 of 39, 60 harness-lsp tests), cargo test --workspace --locked (278 passed). Spawn-client file (31 tests): 20 of 20 runs idle and 25 of 25 pinned to one CPU. lsp-transport.test.ts: 40 of 40 idle and 40 of 40 pinned, no unhandled error. The box was loaded during these runs (load about 20 to 28 on 20 cores).

@avifenesh

Copy link
Copy Markdown
Collaborator Author

Verdict: ready to land. All four points from the last review are fixed, and each new test fails without its fix. Nothing from earlier rounds regressed. Three non-blocking notes; the first is a small gap in the new report.

Non-blocking

1. A call in the event-loop turn of the exit misses the stored error. When the child exits, packages/lsp/src/spawnClient.ts:309 sets state = "crashed" at once. The start rejects only one turn later, since markGone runs in setImmediate (:313). Until then unreportedStartError is unset. A call that reaches ensureServer in that turn gets past :232 and :236 and starts a new server. The old start's error then lands on an entry that is no longer in servers, and no call reports it.

Probe against dist with slow-die-on-initialize: the first ensureServer aborted at once, then ensureServer on every setImmediate tick. The call in the exit turn spawned a second server, and the first start's reason never came back (2 of 2 runs). The same loop on setTimeout(0) got "exited with code 3" once and no second spawn (2 of 2).

A real call lands there only when its last await before ensureServer (the permission hook or findLspRoot) resolves in the same poll phase as the exit. So it is rare, and that call gets the old behavior: a fresh start, no hang, no leak. A fix: while the start is pending, treat an entry that exited as still starting. For example, set crashed in the exit handler only for a ready server, or let ensureServer wait on the pending start under its signal. The setImmediate loop gives a deterministic test: expect the exit text and one spawn.

2. Spec text around the new report.

  • 5.5's first bullet (agent-knowledge/design/lsp.md:321) says the next call replaces a server that exits while no call uses it. That now holds only for a ready server. A start that exits in the background is reported first (5.3).
  • Section 8's first bullet (lsp.md:378) says the next call gets server_starting or a result. It can now also get SERVER_NOT_AVAILABLE.
  • The SERVER_NOT_AVAILABLE row (lsp.md:238) still lists only a missing .lsp.json entry.
  • The changeset's new sentence names the exit code, signal and stderr tail, but not the missed initialize bound that 5.3 lists.

3. The message says "Failed to spawn" for a server that did spawn. packages/lsp/src/lsp.ts:210 prefixes every start failure with "Failed to spawn fake server:". The prefix predates this PR, but it now also fronts the delayed reports, for example "Failed to spawn fake server: Language server for fake did not answer initialize within 800ms." A model can read that as a missing binary. "Failed to start" fits every case.

The last review's points

  1. Background start failures. The two new tests cover the bound and the exit. The probes below cover the orders.
  2. Default bound. The fake-timer test passes on c1709b5. With the default set back to 30000 it fails: "expected 'Language server for fake did not answ…' to be undefined".
  3. Cancel test. The wrapper aborts after ensureServer has begun, so the cancel cannot land before the start. The change is test-only, so the test also passes on 28957b2's source. It fails when the cancel branch at lsp.ts:201 gives the timed-out message. No failure in any loop below.
  4. READMEs. harness-lsp = "0.2" and harness-tools = "0.5" match the crates, and every crate README matches its crate's minor. Rust lsp port: initialize bound, exit detection, stderr and shutdown per the design spec #100 is open and lists the Rust gaps.

Each new test without its fix

c1709b5's spawnClient.test.ts and fixture, 31 tests:

Source Result
28957b2's packages/lsp/src 2 failed: both background-failure tests get TIMEOUT instead of SERVER_NOT_AVAILABLE
c1709b5, client default set back to 30000 1 failed: the fake-timer test
c1709b5, cancel message forced to the timed-out one 1 failed: the cancel test
c1709b5, entry.unreportedStartError = e (:392) removed 2 failed: both background-failure tests
c1709b5, servers.delete(k) (:238) removed, so the error repeats 1 failed: the "once" test gets SERVER_NOT_AVAILABLE again
c1709b5 31 passed

Stored report, in each order

Probes against the built dist, initialize limit 800 ms and call budget 300 ms unless noted. Each one records unhandled rejections, abort listeners on session.signal, active resources and live server pids at the end.

  • Once, with a call during the start: TIMEOUT, then server_starting. After the limit: SERVER_NOT_AVAILABLE "did not answer initialize within 800ms. The next call starts it again." with 1 spawn. Then TIMEOUT from a new start (2 spawns), then server_starting.
  • Four calls at once after the failure: one SERVER_NOT_AVAILABLE, one TIMEOUT from a new start, two server_starting. 2 spawns.
  • closeSession while stored: returns in 0 ms with no live server. The next call starts fresh (TIMEOUT, 2 spawns), with no stale report.
  • Stored, then an already-aborted signal: "cancelled before it started", no spawn, 0 listeners. ensureServer called directly with that signal throws "aborted". The error stays: the next call gets it, and the call after that starts fresh.
  • The reason: exit code 3 with "missing config, giving up"; a SIGKILL from outside gives "was killed by SIGKILL"; the bound gives "did not answer initialize within 800ms".
  • A later successful start: a failed start (answer after 5 s), its report, then a hover from a new server, and another hover. The ready server killed while idle: the next call starts fresh and returns a hover. No stale report.
  • Equal budgets (500 ms and 500 ms): TIMEOUT, then SERVER_NOT_AVAILABLE "within 500ms", then a fresh start, as 5.3 says.
  • The exit turn: note 1.

In every probe: no unhandled rejection, no live server, no active resource left, 0 listeners.

Earlier rounds, rechecked

  • Already-aborted signal: "cancelled before it started" in 2 ms, no pid file, 0 listeners.
  • Death at each stage. Exit during initialize: SERVER_NOT_AVAILABLE with exit code 3 and the stderr text. Exit during hover: SERVER_CRASHED with exit code 1 and the stderr text, and the next call starts a new server. Stdin closed: hover, SERVER_CRASHED "stopped reading its input (write EPIPE)", hover. Stdout closed: SERVER_CRASHED "closed its output" after about 2 s, and the next call starts a new server.
  • closeSession: during a start, it returns in 4 ms and the call gets SERVER_NOT_AVAILABLE "killed by SIGTERM". During a background start, 3 ms, and the next call starts fresh. During a hover, 5 ms, and the hover gets SERVER_CRASHED with exit code 0.
  • Cancel during a hover: "LSP hover was cancelled.", 0 listeners.

What I ran

  • pnpm test:dependencies (3 of 3) and pnpm lint:harness (4 of 4) pass.
  • turbo run build typecheck test --filter='!@agent-sh/harness-e2e' --force: 39 of 39 tasks, 60 harness-lsp tests.
  • cargo test --workspace --locked: 278 passed, 0 failed.
  • changeset status: @agent-sh/harness-lsp and @agent-sh/harness-tools at minor.
  • spawnClient.test.ts (31 tests): 20 of 20 runs unpinned and 25 of 25 pinned with taskset -c 0. The unpinned runs ran on a busy machine; the load fell during the pinned runs.
  • packages/harness-e2e/test/lsp-transport.test.ts against typescript-language-server: 30 of 30 unpinned and 30 of 30 pinned.
  • In every loop run: no unhandled error, EPIPE or ERR_STREAM_DESTROYED in the log, and no server left after the run.
  • CI on c1709b5: TypeScript, Rust and CodeQL pass. revuto is red at its round limit, which is not a finding. Bugbot skipped.

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.

1 participant