Skip to content

fix(rust-lsp): bring the spawn client in line with the lifecycle spec - #102

Merged
avifenesh merged 4 commits into
mainfrom
fix/rust-lsp-spawn-client
Nov 5, 2026
Merged

avifenesh merged 4 commits into
mainfrom
fix/rust-lsp-spawn-client

Conversation

@avifenesh

@avifenesh avifenesh commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #100.

The Rust spawn client (crates/lsp) now follows the lifecycle in agent-knowledge/design/lsp.md sections 5.3 to 5.5 and 8, the way the TypeScript client does. Error codes and messages match the TypeScript side.

What changed

crates/lsp/src/spawn_client.rs is rewritten around background tasks:

  • Writer task. Every message goes through one writer task, so a cancelled call never cuts a message off midway. After the first failed write, nothing more is written.
  • Process watcher. It owns the child, delivers SIGTERM and SIGKILL, and reports the exit to every call still waiting.
  • stderr reader. It always drains the pipe and keeps the last 4 KB.
  • stdout reader. It routes replies and notices a stdout that closes.
  • Start task. It runs initialize, so the start goes on when the caller gives up.

run.rs gives one budget, and one cancel signal, to the start and the operation together.

1. A bounded start

  • Limit. initialize is bounded by DEFAULT_INITIALIZE_TIMEOUT_MS, the 60s session backstop. SpawnLspClient::with_options(SpawnLspClientOptions { initialize_timeout_ms }) overrides it. A server that misses the limit is stopped (SIGTERM, then SIGKILL after 2s).
  • Slow start. The call budget covers the start. A slow start returns TIMEOUT "... while the fake server was starting. The start goes on in the background; retry.", the server keeps starting, and a later call gets server_starting.
  • Failed start after the call gave up. It is reported once to the next call as SERVER_NOT_AVAILABLE with the reason, and the call after that starts fresh.
  • Same-turn exit. A server that exits while starting counts as starting until its start has failed, so no call starts a second server in between.

2. A server exit is noticed

  • During a request. A request in flight when the process exits fails at once with SERVER_CRASHED. The message names the exit code or signal and carries the stderr tail.
  • During the start. An exit or a spawn failure during the start fails at once with SERVER_NOT_AVAILABLE.
  • While idle. A ready server that exits is replaced by the next call.
  • Broken pipes. A broken stdin ("stopped reading its input"), or a stdout that closes while the process lives ("closed its output and stopped answering", after one 2s stop step), retires the server.

LspClient methods now return LspClientError (Crashed, Aborted, Other) instead of String, so run maps a crash to SERVER_CRASHED without parsing text.

3. stderr

It is always drained, and the crash error keeps its last 4 KB. After an exit, the watcher waits up to 100ms for stderr to reach end of file, so the error carries the server's last words. That only takes the full 100ms when another process inherited the pipe.

4. Cancellation

  • LspSessionConfig gains signal: Option<CancelSignal>, the caller's cancel.
  • ensure_server takes a CancelSignal. A cancel releases the caller only; the start goes on.
  • A call whose signal already fired returns "LSP hover was cancelled before it started. Nothing was sent to the fake server." and starts nothing.
  • A cancel during a start or an operation says it was cancelled. The tool's own timeout still says "exceeded Nms".

5. Bounded shutdown (spec 5.4)

  • close_session stops every server in parallel. For each: shutdown raced against the exit (2s), a bounded exit write (2s), up to 2s for the exit, then SIGTERM, SIGKILL 2s later, and a wait for the exit.
  • Nothing is written after the pipe is gone.
  • close_session returns only after every server, retired ones included, has been stopped.

Tests

The Rust tests use the same fake stdio server as the TypeScript tests (packages/lsp/test/fixtures/fake-lsp-server.mjs), so both ports run the same cases. They need node on PATH, which the CI runner has, and run on Linux only, since they read /proc.

tests/spawn_client.rs uses only API that exists on main. These 15 tests fail on main (d0556f9); the tests added in review are under Review changes:

Test main this branch
Request in flight when the server exits TIMEOUT "exceeded 5000ms" SERVER_CRASHED, exit code 1, stderr text
Exit during the start hangs (20s test limit) SERVER_NOT_AVAILABLE, exit code 3, stderr text
Missing binary "No such file or directory (os error 2)" names the spawn: "spawn /path: No such file ..."
Server slower than the call budget first call returns a hover after 800ms TIMEOUT, server_starting, hover, 1 spawn
Start exits after its call gave up hangs TIMEOUT, then SERVER_NOT_AVAILABLE with exit code 3 and stderr, 1 spawn, then a fresh start
Idle server killed IO_ERROR "Broken pipe" hover from a new server
Server closes stdin IO_ERROR "Broken pipe" SERVER_CRASHED "stopped reading its input", then hover from a new server; old one gone after close
Server closes stdout TIMEOUT "exceeded 8000ms" SERVER_CRASHED "closed its output"; new server next call
2 MiB to stderr, then answer hangs hover
2 MiB to stderr, then exit hangs error ends with the last line; tail at most 4 KB
close_session, well-behaved server server still running server got exit and is gone
close_session, server dies on shutdown hangs returns, server gone
close_session, server ignores exit and SIGTERM server still running gone (SIGKILL)
close_session, server closed stdin before answering shutdown server still running gone
File open the server never reads, then close_session hangs TIMEOUT, then close_session returns

tests/spawn_client_api.rs (8 tests) and one unit test in spawn_client.rs need the new API (with_options, signal, ensure_server's cancel), so they cannot build on main. Instead, I undid each fix and checked that its test fails:

Fix undone Test Result
exit write unbounded unit test: a write that fills the pipe queued ahead of exit hangs (10s limit)
default initialize limit set to 30s paused-clock test of the default limit fails ("within 30000ms")
watcher marks a starting server crashed calls on every turn while a start exits 2 spawns instead of 1
ensure_server ignores its cancel cancel during the start wrong message, no background start

The other API tests cover:

  • the initialize limit with the server stopped;
  • a missed limit reported once;
  • an already-cancelled call that starts nothing;
  • a cancel during a request ("LSP hover was cancelled.");
  • the relation between the default constants.

Versions

This breaks the public API: LspClient::ensure_server takes a cancel signal, every LspClient method returns LspClientError, and LspSessionConfig has a new public field, which breaks struct literals. So:

  • harness-lsp at 0.2.0 (crates.io has 0.1.1);
  • the harness-tools crate at 0.5.0 (crates.io has 0.4.1), since it re-exports harness-lsp.

Both versions were set by #95 and never published, so they stay: one breaking minor over the published crates. Both READMEs pin that minor. harness-lsp now depends on libc on Unix, for SIGTERM. The npm packages are unchanged.

Spec

Only names change: the spec now says the Rust port exists, and names the Rust equivalents of initializeTimeoutMs and the crash error classes.

Checks

  • cargo test --workspace --locked: 315 passed, 0 failed.
  • cargo clippy -p harness-lsp --all-targets: no warnings in the files this PR touches. The remaining ones were already on main, in format.rs, manifest.rs and tests/lsp.rs.
  • The new and rewritten Rust files are rustfmt-clean. The crate as a whole is not rustfmt-clean on main, so I left the other files as they were.
  • The spawn-client tests (unit tests plus both test files) passed 20 of 20 runs idle and 10 of 10 pinned with taskset -c 0. The unit tests passed 25 of 25 runs on two CPUs each shared with a busy yes. No fake server was left after any run.
  • pnpm test:dependencies, pnpm lint:harness and turbo run build typecheck test without harness-e2e: 39 of 39 tasks.
  • Nothing was written to /tmp.

Review changes (a0d0701)

  • One server per key. ensure_server does the lookup, the spawn and the insert in one critical section; spawning and starting do not await. Concurrent first calls now share one server, and every spawned process is in the map, so close_session stops it.
  • No dead server stays Ready. The start decides readiness under the status lock, together with the liveness check. The watcher marks the exit before it takes that lock, so whichever side runs second sees the other.
  • A dropped client stops its servers. Drop for SpawnLspClient sends SIGKILL to each server. The watcher then reaps the process and the background tasks end, which frees the entry.
  • Versions stay at the unpublished harness-lsp 0.2.0 and harness-tools 0.5.0. crates.io has 0.1.1 and 0.4.1, so that is still one breaking minor. The READMEs and Cargo.lock match.
  • Stops. begin_stop drops finished stops. It marks and registers a stop under the stops lock, so close_session cannot miss one that is just beginning.
  • rustfmt. lib.rs and the touched files are rustfmt-clean.
  • CI. Both Rust jobs (ci.yml and release-rust.yml) set up Node with the pinned actions/setup-node the TypeScript job uses.
  • Parity tests. Three cases the TS suite has:
    • stdin breaks during the start;
    • initialize gets an error reply, and the old process exits late without touching the re-spawned entry;
    • concurrent operations on one file send one didOpen.
  • Paths. file_uri_to_path percent-decodes, as the TS client does.
Test ddacdb3 this branch
8 concurrent first calls on one key, 10 rounds round 0: a call gets IO_ERROR "not ready (state=starting)" from an overwritten server 1 server per round, none left after close; also 16 tasks over 50 rounds
Drop the client without close_session server still running after 1.5s gone
Server exits 100ms after initialized, 300ms test pause before the readiness check stays Ready, no re-spawn (with the old check-then-lock order) start fails with "exited with code 0"; next call spawns
Four stops, then the stop list 4 handles kept at most 1
file:///tmp/a%20b/c%23d.ts /tmp/a%20b/c%23d.ts /tmp/a b/c#d.ts
Parity: stdin breaks during the start, initialize error reply plus late exit, one didOpen pass (behavior was already there) pass

The readiness, stop-list and path tests are unit tests that use test-only access, so each was checked by undoing its fix on this branch: each fails without its fix.

Review changes (9f806fb)

  • The exit-write test orders by events, not time. It uses a new fake-server mode, hold-shutdown-reply. That mode writes got-shutdown when it reads shutdown, stops reading, and answers only once reply-shutdown exists. The test waits for got-shutdown, pushes a pre-built 4 MiB frame straight onto the writer, and only then creates reply-shutdown, so exit is always queued behind the filler. Under load, on two CPUs each shared with a busy yes, the old test failed 6 of 10 runs. The new unit tests passed 25 of 25 runs, and the integration tests 10 of 10. The test still hangs to its 10s limit if the exit bound is removed.

  • The readiness test orders by events too. The test hook now waits for the server to exit, not for 300ms, before the readiness check. With the old check-then-lock order it fails at once.

  • The spawn runs outside the servers lock. The key is claimed under the lock with a Spawning placeholder, so concurrent first calls still share one server: a call that finds the placeholder gets server_starting. The spawn then runs unlocked, and the entry is filled in under the lock. If the spawn fails, the placeholder is removed. If the session closed meanwhile, the new server is stopped. New unit test: a test-only hook blocks one key's spawn for 3s. Another key then starts and gets ready within 2s while the slow spawn is still running. On the previous head, with only the hook added, it times out. The 16-task, 50-round concurrency stress still passes.

  • Process groups. On Unix each server starts in its own process group, and SIGTERM, SIGKILL and Drop signal the group, so the server's own children stop with it. A new fake-server suffix, -with-child, starts a child that ignores SIGTERM. New unit tests:

    • after Drop, the server and its child are gone;
    • for a server that ignores exit and SIGTERM, the final SIGKILL takes its child too.

    With only the leader signalled, both children survive.

  • Handle rebinding is tracked in lsp: an operation can be bound to a replacement server and get IO_ERROR instead of SERVER_CRASHED #103 as the next change.

On 9f806fb the Rust CI job is green and ran every spawn-client test: 7 unit tests, 20 in tests/spawn_client.rs and 8 in tests/spawn_client_api.rs.

Review changes (d5d90ef)

  • close_session waits for a spawn in flight. The Spawning slot holds a channel that closes once its spawn is handled: the server is in the map, or its stop has begun. close_session takes these channels with the map and waits on each, up to one stop step, before it waits for the stops. New unit test: a test-only hook holds one spawn for 500ms while close_session runs, and the server must be gone when it returns. Without the wait it fails: "close_session returned before the spawn ended".
  • The whole group goes with the server. Once the watcher reaps a server, it sends SIGKILL to the server's process group. A child that ignored SIGTERM, or outlived a graceful exit, goes too. New unit test: the server exits on exit, its child ignores SIGTERM, and the child must be gone within 1s of close_session. Without the group kill it fails: "the server's child outlived a graceful exit".
  • Two integration tests run alone. With four copies of the test binary running side by side, a_broken_stdin_... and a_stdin_that_breaks_during_the_start_... failed 5 of 410 runs with TIMEOUT. A new child holds a copy of every pipe end its parent has open until it execs. So a server that another test spawned at that moment still held the read end of the test server's stdin, and under load it held it past the start. The write after the server closed its stdin then succeeded, and no reply came. In a failing run, the fake server scanned /proc right after it closed its stdin and found that reader: a child of the test binary, not yet exec'd, named after another test's thread. These two tests now take a lock that every other test in the binary holds shared.
  • Event waits instead of fixed pauses. The same load showed a third case: a spawn count checked right after a 300ms call that started a server failed 1 of 400 runs, since node had not written its pid yet. The tests now wait for the event: the spawn record, the end of the start (past_start calls until the result is no longer server_starting), or the reap after kill -9. The TypeScript test with the same spawn-count check now polls for it.

Under the same load, after these changes: tests/spawn_client.rs passed 400 of 400 runs and tests/spawn_client_api.rs 200 of 200 (two copies).

The client has the same pipe window. A server that closes its stdin while another server in the same process is being spawned can see its next write succeed. That call then ends at its timeout instead of SERVER_CRASHED.


Note

Medium Risk
Large rewrite of child-process I/O and shutdown paths with a breaking public API, though behavior is spec-driven and heavily covered by new integration tests.

Overview
Brings the Rust harness-lsp spawn client in line with agent-knowledge/design/lsp.md (sections 5.3–5.5 and 8), matching the TypeScript client’s lifecycle and error semantics. spawn_client.rs is rebuilt around background tasks: a single writer queue (no mid-message cuts on cancel), process watcher (exit → fail in-flight calls with stderr tail), stderr drain (last 4 KB), stdout reader (pipe loss → retire server), and a background initialize that can outlive the call that started it.

run.rs applies one timeout/cancel budget to server start plus the operation, distinguishes tool timeout vs session cancel in messages, and maps LspClientError (Crashed, Aborted, Other) to SERVER_CRASHED, TIMEOUT, and SERVER_NOT_AVAILABLE instead of string parsing. close_session now does bounded graceful shutdown (shutdown → exit → SIGTERM → SIGKILL).

Breaking API: LspClient::ensure_server takes a cancel signal; methods return LspClientError; LspSessionConfig adds optional signal; new SpawnLspClientOptions / DEFAULT_INITIALIZE_TIMEOUT_MS. Bumps harness-lsp to 0.3.0 and harness-tools to 0.6.0; adds Unix libc for SIGTERM. Linux integration tests share the TS fake LSP server fixture.

Reviewed by Cursor Bugbot for commit ddacdb3. Configure here.

The Rust spawn client had no initialize bound, did not notice a server
exit, never read stderr, took no cancel for a start, and shut down with
no bounds. It now follows design spec sections 5.3 to 5.5 and 8 the way
the TypeScript client does, with the same error codes and messages.

- The start runs in its own task, bounded by DEFAULT_INITIALIZE_TIMEOUT_MS
  (the 60s session backstop, overridable through SpawnLspClientOptions).
  The call budget covers the start: a slow start returns TIMEOUT and goes
  on, a later call gets server_starting, and a start that fails after its
  call gave up is reported once as SERVER_NOT_AVAILABLE.
- A process watcher fails every waiting call at once when the server
  exits, with the exit code or signal and the stderr tail. A ready server
  that exits while idle is replaced by the next call. A broken stdin, or
  a stdout that closes while the process lives, retires the server.
- stderr is always drained; the last 4 KB is kept.
- LspSessionConfig gains a cancel signal and ensure_server takes one. A
  call cancelled before it started starts nothing.
- close_session stops servers in parallel with bounded steps: shutdown,
  exit, SIGTERM, SIGKILL, and waits for each process. Writes go through
  one writer task, so nothing is cut off midway or written after the pipe
  is gone.

LspClient methods return LspClientError instead of String, which breaks
the public API: harness-lsp goes to 0.3.0 and harness-tools to 0.6.0.

The new tests run the TypeScript fake server, so both ports run the same
cases. The 15 tests that use only main's API all fail on main.

Closes #100

@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.


The rewrite follows the TypeScript lifecycle closely. Two steps that run in a single turn in TypeScript (one synchronous run of the event loop) can interleave under Rust's multi-threaded tokio runtime:

  1. ensure_server checks for an existing entry and inserts the new one under two separate locks, with the spawn (fork/exec) in between. Two parallel first calls for the same language and root both spawn a server. The losing server ends up in neither servers nor stops, so close_session never stops it. That breaks the PR's own promise that every server is stopped.
  2. The start task checks running() outside the status lock, then sets Ready. If the process exits in that window, the entry stays Ready after the exit. From then on, every call for that key returns SERVER_CRASHED and no new server is ever started.

Comment thread crates/lsp/src/spawn_client.rs Outdated
Comment on lines +1129 to +1134
if *cancel.borrow() {
return Err(LspClientError::Aborted);
}

let entry = self.spawn_server(language, root, profile)?;
self.servers.lock().unwrap().insert(key, Arc::clone(&entry));

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.


Race: two parallel first calls can each spawn a server, and one process leaks.

The servers lock is dropped at line 1128 and taken again here. spawn_server runs in between, and it forks and execs. On a multi-threaded runtime, two lsp calls for the same (language, root) can both find no entry, and both spawn a server. An agent sending parallel tool calls on first use, say a hover and a definition together, is the obvious trigger. Then:

  • The losing process leaks. The second insert overwrites the first entry. That entry is now in neither servers nor stops, so close_session never stops its process. watch_process owns the Child and holds an Arc to the entry until the process exits, so kill_on_drop never fires. On main the losing Arc<ServerEntry> owned the Child and was dropped after the call, which killed it.
  • The first caller gets the wrong server. Its hover looks the server up with entry_for(handle), which returns the second entry. That entry is still Starting, so the call fails with IO_ERROR "not ready (state=starting)".

TypeScript doesn't hit this because servers.get … servers.set runs in one synchronous turn.

Fix: keep the servers StdMutex held from the lookup through the insert. spawn_server is synchronous, so that works. Or, after spawning, re-check under the lock and drop or kill the loser.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in a0d0701. ensure_server now holds the servers lock from the lookup through spawn_server, the insert and start, so concurrent first calls on one key share one server and every spawned process is in the map. New test: 8 tasks behind a barrier call lsp hover on one key, 10 rounds, then close_session. It checks one spawned pid per round and none alive afterwards. On ddacdb3 it fails in round 0 with IO_ERROR "not ready (state=starting)"; now it passes, and so does a 16-task, 50-round stress run.

Comment thread crates/lsp/src/spawn_client.rs Outdated
Comment on lines +1000 to +1008
Ok(()) if !entry.running() => Err(entry.wait_gone().await),
Ok(()) => Ok(()),
},
};
match &result {
Ok(()) => {
let mut st = entry.status.lock().unwrap();
if st.state == EntryState::Starting {
st.state = EntryState::Ready;

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.


Race: an exit right after the handshake can leave the entry Ready for good.

Line 1000 checks entry.running(), and lines 1006–1008 later take the status lock to set Ready. In watch_process, the watcher sets exited (line 604) and then, under the status lock, changes the state only if it is Ready (lines 606–609). Possible interleaving:

  1. The start sees running() == true.
  2. The watcher sets exited, finds Starting, and leaves it alone.
  3. The start sets Ready.

The entry is now Ready with the process dead. fire_gone marks it gone 100ms later, but nothing ever sets it to Crashed: retire​/stop are never started for it, and write_failed only waits for the gone reason. From then on ensure_server keeps returning this entry (its state is not Crashed), and ready_entry returns the gone reason. So every later call fails with SERVER_CRASHED "The next call starts it again.", which stops being true. The window is narrow, but once hit it lasts until close_session.

Fix: check running() again after setting Ready, while still holding the status lock, and mark the entry Crashed if the process has exited. Since the watcher sets exited before it takes that lock, one of the two sides is then sure to see the other.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in a0d0701. The start sets Ready only under the status lock, in the same step as the liveness check; a dead process fails the start with its exit instead. The watcher flips exited before it takes that lock, so one side always sees the other. New unit test: a server that exits 100ms after initialized, with a test-only 300ms pause between the handshake and the readiness check. The start fails with "exited with code 0" and the next call spawns a new server. With the old check-then-lock order and the same pause, it stays Ready and never re-spawns.

@cursor cursor 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.

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit ddacdb3. Configure here.

let me = Arc::clone(self);
let handle = tokio::spawn(async move { me.stop().await });
self.stops.lock().unwrap().push(handle);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

close_session can miss in-flight stop

Medium Severity

begin_stop sets stopping and only later pushes the JoinHandle onto stops. close_session treats an already-stopping server as registered and then drains stops. If that drain runs in the gap, the handle is never awaited and close_session returns while the process is still being shut down.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ddacdb3. Configure here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in a0d0701. begin_stop now holds the stops lock while it marks the server stopping and pushes the handle, so close_session, which drains under that lock, either sees the stop or runs before it begins. It also drops finished stops before pushing, and a unit test checks that four failed starts leave at most one handle.

)));
}
Ok(entry)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

In-flight call misses crash replacement

Medium Severity

ready_entry looks up the server by language and root, not the instance ensure_server just handed back. After a ready crash, a concurrent call can insert a replacement while this call is between ensure_server and the operation, so the operation binds to the new Starting server and returns IO_ERROR instead of SERVER_CRASHED.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ddacdb3. Configure here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Not changed in this PR. Both clients look the server up by key, so a call that sits between ensure_server and its operation while another call replaces a crashed server binds to the replacement, which is still starting, and gets IO_ERROR "not ready". Fixing it means carrying an instance id in ServerHandle on both the TS and Rust sides and reporting the old instance's crash. That is a public-type change on both ports, so I would do it as its own change.

@avifenesh

Copy link
Copy Markdown
Collaborator Author

Verdict: needs changes. Three blocking findings. Two are the ones revuto raised, and I reproduced both. The third is new: dropping the client leaks every server.

The rewrite is careful and close to the TS client. The 15 main-compatible tests fail on main and pass here. Each of the 8 API tests and the unit test fails when its fix is undone. The loops were clean. The blockers sit where the tests do not reach: concurrent calls, and cleanup without close_session.

Blocking

1. Parallel first calls spawn several servers, and the extra ones outlive close_session.
crates/lsp/src/spawn_client.rs:1109-1134. The servers lock is released after the lookup and taken again for the insert, with spawn_server (fork and exec) in between. A later insert overwrites an earlier one. The overwritten entry is in neither servers nor stops, and its watcher owns the Child and holds an Arc to the entry, so nothing ever stops it. This breaks spec 5.2 (one server per language and root) and 12 (concurrent calls share the server). Parallel tool calls on first use, such as a hover and a definition together, hit it.

  • Probe: 8 tasks behind a barrier call ensure_server then hover on one key, 20 rounds. 17 of 20 rounds spawned more than one server. 105 server processes were still running after close_session.
  • Fix: hold the servers lock from the lookup through the insert and start. Both are synchronous. With that change the same probe gives one spawn per round and nothing left running, and the crate's other tests still pass.

2. A server that exits right after the handshake can stay Ready for good.
spawn_client.rs:1000 checks running(); 1006-1008 take the status lock later and set Ready. The watcher sets exited, then changes the state under the lock only if it is Ready (604-610). If the exit lands between the two, the entry is Ready with a dead process. ensure_server keeps returning it, ready_entry returns the gone reason, and every later call gets SERVER_CRASHED "The next call starts it again." No new server ever starts.

  • Probe: a server that answers initialize and exits 100ms after initialized, with a 300ms sleep injected before that lock to widen the window. 4 calls gave 4 SERVER_CRASHED and 1 spawn. Without the sleep the same server is replaced on every call (4 spawns). The window is narrow, but once hit it lasts until close_session.
  • Fix: decide under the status lock: Ready if running(), else Crashed. The watcher flips exited before it takes the lock, so one side always sees the other.

3. Dropping the client without close_session leaves every server running. New against main.
spawn_client.rs:936-948 spawns the watcher and the stdout reader with an Arc<ServerEntry>. The entry owns the kill and writer senders (120-121), so neither channel closes. The watcher waits on child.wait() forever, the server's stdin stays open, and kill_on_drop fires only when the runtime shuts down. On main the entry owned the Child, so dropping the client killed the server. A host that drops a session per conversation now keeps one language server per session.

  • Probe: start a server through lsp, drop the session and the client, wait 1.5s. On main the process is gone. On this branch it is still running.
  • Fix: impl Drop for SpawnLspClient that sends KillSignal::Kill to each entry, or have the tasks hold a Weak. The Drop version makes the probe pass.

Please add all three probes as tests. Each fails on this branch today.

Not blocking

  1. Versions. crates.io has harness-lsp 0.1.1 and harness-tools 0.4.1, and the last tag is rust-v0.4.1. So 0.2.0 and 0.5.0 from 28957b2 were never published, and that bump already marks a breaking release. This PR can stay on 0.2.0 and 0.5.0 (crates/lsp/Cargo.toml:3, crates/harness-tools/Cargo.toml:3, both READMEs). 0.3.0 and 0.6.0 skip versions nobody can depend on. Fine either way if a bump per PR is the convention. Cargo.lock matches, and --locked builds.
  2. stops only grows during a session. spawn_client.rs:378 pushes a JoinHandle for each retired server, and only close_session drains them. A server that crashes on every call adds one per call. The TS client removes a stop when it settles. retain(|h| !h.is_finished()) before the push is enough.
  3. rustfmt. crates/lsp/src/lib.rs was rustfmt-clean on main. The new pub use types::{...} line (lib.rs:30) is 120 characters, and rustfmt reflows it.
  4. CI needs node but does not set it up. The Rust job (.github/workflows/ci.yml:52-68) has no setup-node step. It works today because the runner image ships Node; the new tests did run and pass there. A pinned actions/setup-node step keeps a runner image change from breaking it.
  5. Cases the TS suite covers and the Rust suite does not. Stdin breaking during the start (close-stdin-on-initialize). initialize answered with an error, and the old process exiting late after its key got a new server (reject-initialize-slow-exit). One didOpen for concurrent operations on the same file. The fake server already has these modes.
  6. Outside this PR. file_uri_to_path (spawn_client.rs:698) strips file:// without percent-decoding; the TS side decodes. A location in a path with a space comes back with %20 and an empty preview. Worth a follow-up issue.

Parity and concurrency checked

  • Messages and codes match the TS client: the exit and crash errors (code or signal, stderr tail, "The next call starts it again."), the missed initialize bound, "stopped reading its input", "closed its output and stopped answering", the three cancel and timeout messages, and Failed to start ... server: with SERVER_NOT_AVAILABLE.
  • Two differences, both fine. TS reports any error from a call whose signal fired as TIMEOUT, while Rust keeps a crash as SERVER_CRASHED. Rust sends $/cancelRequest on abort, which spec 8 asks for and the TS client does not do.
  • No lock is held across .await. They are all std mutexes inside Send futures, so the compiler enforces it. The watch channels check the current value before they wait, so I found no lost wakeup. I found no panic path: spawn errors, missing pipes and closed channels all return errors.
  • AGENTS.md: no tool description or schema changed, the spec edit only names the Rust equivalents, and the messages now match the TS client. So no new model e2e run is due.

What I ran

Own worktree at ddacdb3. Scratch, TMPDIR and the target dir on disk.

  • cargo test --workspace --locked: 302 passed, 0 failed.
  • tests/spawn_client.rs and tests/common/mod.rs copied onto main (d0556f9): 15 of 15 fail, 6 of them at the 20s limit, as the PR table says.
  • Undid one fix at a time and ran its test. Each failed: exit write unbounded (unit test, 10s limit); client default limit 30s (paused-clock test); constant at 30s (constants test); watcher marks a starting server crashed (2 spawns); ensure_server ignores its cancel (wrong message); no check for an already-cancelled call (wrong message); cancel reported as a timeout; a missed limit not stored for the next call.
  • New tests (unit test and both files): 20 of 20 runs idle, 10 of 10 pinned with taskset -c 0, no fake server left after any run. Pinned, tests/spawn_client.rs takes about 14.5s, against a 20s limit per test.
  • cargo clippy -p harness-lsp --all-targets: no warnings in the touched files. The 4 left are on main too.
  • cargo check -p harness-lsp --all-targets for x86_64-pc-windows-gnu and x86_64-apple-darwin: clean, so the libc gate and the Linux-only test gates hold.
  • rustfmt --check on each touched file, compared with main.
  • The three probes above, then the three fixes sketched in my worktree: probes pass and all harness-lsp tests still pass. Nothing pushed.
  • CI: Rust and TypeScript green, and the Rust job ran the 15 + 8 + 1 new tests. revuto: two inline comments, both confirmed above.

… drop

Address review on the Rust spawn client.

- ensure_server does the lookup, the spawn and the insert in one critical
  section. Concurrent first calls on one key started several servers,
  and the overwritten ones were never stopped, not even by close_session.
- The start decides readiness under the status lock, together with the
  liveness check. A server that exited between the check and setting
  Ready stayed Ready for good, so no call ever re-spawned it.
- Dropping the client without close_session sends SIGKILL to each server.
  The background tasks kept the entries alive, so a dropped client left
  every server running.
- begin_stop drops finished stops, and marks and registers a stop under
  one lock, so close_session cannot miss a stop that is just beginning.
- file_uri_to_path percent-decodes, as the TypeScript client does.
- Versions stay at the unpublished 0.2.0 and 0.5.0, one breaking minor
  over crates.io's 0.1.1 and 0.4.1.
- The Rust CI and release jobs set up Node, which the tests need.
- Parity tests with the TypeScript suite: stdin breaking during the
  start, an error reply to initialize plus a late exit of the old
  process, and one didOpen for concurrent operations on one file.
@avifenesh

Copy link
Copy Markdown
Collaborator Author

Re #102 (comment): all nine points are in a0d0701.

  1. One server per key. ensure_server holds the servers lock from the lookup through the spawn, the insert and start (none of them awaits). New test: 8 tasks behind a barrier call lsp hover on one key, 10 rounds, then close_session, then count the spawned pids and the ones still alive. On ddacdb3 round 0 already fails: a call gets IO_ERROR "not ready (state=starting)" from the overwritten server. Now every round has 1 server and none left running. A larger stress run, 16 tasks over 50 rounds, also passes.

  2. Readiness under the lock. The start sets Ready only under the status lock and only if the process still runs; otherwise the start fails with the exit. The watcher flips exited before it takes that lock. New unit test with a test-only 300ms pause between the handshake and the readiness check, and a server that exits 100ms after initialized: the start fails with "exited with code 0" and the next call spawns. With the old check-then-lock order and the same pause, the server stays Ready and nothing re-spawns.

  3. Drop. impl Drop for SpawnLspClient sends SIGKILL to each server. The watcher reaps it, then the background tasks end and free the entry. New test: hover, then drop the session and the client, and the server is gone within 1.5s. On ddacdb3 it is still running.

  4. Versions are back to 0.2.0 and 0.5.0, with READMEs and Cargo.lock to match.

  5. Stops. begin_stop drops finished stops before it pushes a new one. New unit test: four failed starts, then at most 1 stop handle kept (4 without the prune).

  6. rustfmt. lib.rs, and every touched file, is rustfmt-clean.

  7. CI. The Rust job in ci.yml, and the publish job in release-rust.yml, which runs the same tests, set up Node with the pinned actions/setup-node the TypeScript job uses.

  8. Parity tests added:

    • stdin breaks during the start: SERVER_NOT_AVAILABLE "stopped reading its input";
    • initialize answered with an error, then the old process exits late and the re-spawned server stays in place;
    • one didOpen for concurrent operations on one file.

    All three already passed on ddacdb3. They pin behavior that was there.

  9. Paths. file_uri_to_path parses the URI and percent-decodes it, like the TS client. Unit test: file:///tmp/a%20b/c%23d.ts reads as /tmp/a b/c#d.ts; it read /tmp/a%20b/c%23d.ts before.

Each unit-only test (2, 5, 9) fails with its fix undone on this branch.

Bugbot's two threads: the stop-registration gap is fixed with point 5, since a stop is now marked and registered under the stops lock. The handle-to-instance gap is not changed here. Both clients look the server up by key, and fixing it needs an instance id in ServerHandle on both sides. I would do that as its own change.

Reran on a0d0701: cargo test --workspace --locked (310 passed), cargo clippy -p harness-lsp --all-targets (no warnings in touched files; the four left are on main too), rustfmt on the touched files, pnpm test:dependencies, pnpm lint:harness and turbo run build typecheck test without harness-e2e (39 of 39). The Rust spawn-client tests (unit tests and both test files) passed 20 of 20 runs idle and 10 of 10 pinned with taskset -c 0, with no fake server left after any run.

@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 finding: the Rust CI job is red on a0d0701, from a timing race in a unit test. The nine points from the last review are fixed. I reproduced the three earlier blockers on ddacdb3, and each one is gone on a0d0701.

Blocking

1. CI is red: the_exit_write_is_bounded_when_a_queued_write_fills_the_pipe races the fake server's 200ms delay.
crates/lsp/src/spawn_client.rs:1434-1492, assertion at 1489. In run 41956438911 the Rust job fails here after 0.25s: "exit cannot be written behind a blocked write". cargo test stops at the first failing binary, so tests/spawn_client.rs and tests/spawn_client_api.rs, the three new integration tests included, did not run in CI on this head.

  • Cause. The test sleeps 50ms after shutdown (1472), then builds a 4 MB didOpen and needs it in the writer queue before the server answers shutdown 200ms later (fake-lsp-server.mjs:158). In a debug build, building and serializing that message takes about 80ms locally. Timeline from an instrumented copy: shutdown queued at 0, filler queued at +130ms, reply at +201ms. That leaves about 70ms. On a slower runner, with the new unit tests starting node servers next to it, the reply wins: exit is written first, and request_exit returns true. The client is right; the test's ordering assumption is not.
  • Repro. Clean head, taskset -c 5,6, with a busy yes pinned to each of the two CPUs: 6 of 10 runs fail, each in 0.25s, as in CI. The instrumented run shows the reply at 246.5ms, exit queued at 246.6ms, and the filler queued at 248.2ms. Without the busy processes, 30 runs on 4 CPUs and 30 on 2 CPUs all pass, so local loops do not catch it.
  • The test body is unchanged since ddacdb3. It passed in CI there, when it was the only unit test. It now runs next to three new ones.
  • Fix. Make the order independent of time. For example, build the framed bytes before request_exit and push the WriteJob onto entry.writer directly, so queueing takes microseconds. Better still, have stop-reading-after-shutdown answer only once a marker file exists, and create the file after the filler is queued. Then get a green Rust job that runs the integration tests.

The last review's points, rechecked

Case ddacdb3 a0d0701
8 tasks behind a barrier, ensure_server then hover on one key, 20 rounds 18 of 20 rounds spawned more than one server. 126 spawned, 106 still running after close_session, 424 tokio tasks left 1 server per round. 20 spawned, 0 running, 0 tasks left
Same through lsp, 20 rounds 20 of 20 rounds. 152 spawned, 132 running. Calls got IO_ERROR "not ready (state=starting)" 1 per round, 0 running. 20 hovers, 140 server_starting
Exit 100ms after initialized, 300ms pause injected before the readiness step, 4 calls 1 spawn. 4 x SERVER_CRASHED "exited with code 0. The next call starts it again." 4 spawns. 4 x SERVER_NOT_AVAILABLE "Failed to start fake server: ... exited with code 0."
Drop session and client after a hover server alive at 1.5s and at 5s, 4 tasks left gone by 1.5s, 0 tasks left
Drop the client from a plain thread alive at 1.5s gone
Drop while a start runs after its caller gave up alive at 1.5s, 4 tasks left gone, 0 tasks left
  • New integration tests copied onto ddacdb3: the concurrency test fails in round 0 and the drop test fails; the three parity tests pass there, as the reply says.
  • Each unit-only fix undone on a0d0701 makes its test fail: readiness checked before the lock (the handle comes back Ready), no prune, no percent-decoding.
  • Versions: crates.io has harness-lsp 0.1.1 and harness-tools 0.4.1. The branch has 0.2.0 and 0.5.0, the harness-lsp pin in crates/harness-tools/Cargo.toml is 0.2.0, and the READMEs and Cargo.lock match.
  • Stops: begin_stop (368) marks and pushes under the stops lock, so Bugbot's registration gap is closed, and finished stops are pruned.
  • rustfmt: the 9 touched .rs files are clean. The remaining diffs are in fence.rs, manifest.rs and schema.rs, which this PR does not touch.
  • CI files: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 is v6.5.0, and the v6 tag points at it. Same pin and Node 26 as the TypeScript job.

Lock and Drop

  • The servers critical section in ensure_server (1159-1185) has no .await. The future is Send through async_trait, so a guard held across one would not compile.
  • Lock order: servers then status (ensure_server), stops then status (begin_stop). Nothing takes servers or stops while it holds status. The watcher, the start task, the stop task and close_session never take servers while holding another lock. No cycle.
  • Readiness (1025): the watcher sets exited before it locks status, and the start reads exited under status, so one side always sees the other.
  • Drop (1134) uses get_mut: no lock, nothing that blocks, and a poisoned map is recovered. The unbounded send needs no runtime. Dropped from a plain thread, the server is gone in 1.5s. With the runtime shut down first, dropping the client does not panic. The server was already killed by kill_on_drop and stays a zombie until the host reaps it, as on ddacdb3.
  • Stress: 16 tasks x 50 rounds, and 8 x 20 pinned to one CPU, pass with no hang and nothing left running.

Not blocking

  1. The servers lock now covers Command::spawn, so other keys wait for it (1181). ensure_server on a ready key while 30 other keys start, three runs: p99.9 at most 1us, max 12 to 15ms in each run. On ddacdb3 the max was under 0.2ms. With timing added, the critical section takes 0.2 to 0.6ms, and 2 of 31 spawns took 14 to 15ms inside Command::spawn itself. Fine for a cost paid once per key. The edge case: a command whose exec blocks (a binary on a hung mount) now stalls every LSP call on every key, on a std mutex inside tokio workers. Inserting a Spawning placeholder under the lock and spawning outside it would remove that, if it ever matters.
  2. Handle rebinding (left open). Fine to land separately. The TS client also looks the server up by key (packages/lsp/src/spawnClient.ts:417-418), and so does main, so this PR adds no gap. The window is narrow: a crash, plus a second call that starts the replacement, between ensure_server and the operation. The cost is an IO_ERROR "not ready (state=starting)" with no retry hint, where SERVER_CRASHED is due. No issue tracks it yet; please open one before this lands.
  3. Drop sends SIGKILL with no SIGTERM step. A server with children of its own (tsserver under typescript-language-server, rust-analyzer's proc-macro server) can leave them behind. Main did the same through kill_on_drop, so this is no regression. Optional: send Term, and when Handle::try_current() finds a runtime, spawn the usual escalation.
  4. Another fixed delay against a fixed pause. a_server_that_exits_right_after_the_handshake_is_not_kept_ready (1368) needs the server to exit within the 300ms hook pause (1380), and it exits 100ms after initialized. That is a 200ms margin. It passed in CI, but after finding 1, a 1s pause costs little.

What I ran

Own worktrees at a0d0701 and ddacdb3. Scratch, TMPDIR and target dirs on disk.

  • cargo test --workspace --locked: 310 passed.
  • Spawn-client tests (4 unit, 20 in spawn_client.rs, 8 in spawn_client_api.rs): 20 of 20 runs idle, 10 of 10 pinned with taskset -c 0, no fake server left after any run.
  • LSP_STRESS_TASKS=16 LSP_STRESS_ROUNDS=50 on the concurrency test: pass. 8 x 20 pinned: pass.
  • The probes in the table, on both heads, from a probe file outside the PR that only prints counts. The readiness probe used an env-driven pause added to each head in place.
  • The CI repro and the instrumented timeline above.
  • cargo clippy -p harness-lsp --all-targets: 4 warnings, all in untouched files (format.rs, manifest.rs, tests/lsp.rs).
  • rustfmt --check on the touched files.
  • cargo check -p harness-lsp --all-targets for x86_64-pc-windows-gnu and x86_64-apple-darwin: clean.
  • pnpm test:dependencies, pnpm lint:harness, and turbo run build typecheck test without harness-e2e: 39 of 39. The TS lsp suite (61 tests) passes with the fixture change.
  • CI: TypeScript and CodeQL pass, Rust fails (finding 1). revuto approved a0d0701 and its check passes. Bugbot's two threads were on ddacdb3: the stop one is fixed, and the handle one is finding 3.
  • AGENTS.md: a0d0701 changes no tool description, schema or message, so no model e2e run is due.

Address re-review on the Rust spawn client.

- The exit-write test raced the fake server's 200ms shutdown reply: on
  a busy runner the reply won and `exit` was written ahead of the
  filler, which made CI red. It now orders by events. A new fake-server
  mode, hold-shutdown-reply, answers shutdown only once a marker file
  exists. The test waits until the server has read shutdown, pushes a
  pre-built frame onto the writer, then creates the marker.
- The readiness test hook waits for the server to exit instead of
  sleeping.
- ensure_server claims a key with a Spawning placeholder under the lock
  and spawns outside it, so one key still has one server, but a slow
  exec on one key no longer holds up every other key. A concurrent call
  that finds the placeholder gets server_starting. A failed spawn drops
  the placeholder, and a spawn that outlives a closed session is stopped.
- On Unix each server runs in its own process group, and SIGTERM,
  SIGKILL and Drop signal the group, so the server's children stop with
  it. The fake server gains a -with-child suffix for the tests.

@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.


Shutdown can return before an outstanding spawn is stopped, and process-group cleanup misses descendants when the server exits first.

Comment thread crates/lsp/src/spawn_client.rs Outdated
.drain()
.filter_map(|(_, slot)| match slot {
Slot::Server(e) => Some(e),
Slot::Spawning(_) => None,

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.


[P2] Wait for outstanding spawns before completing shutdown. If close_session runs while spawn_server is outside the lock, this branch discards its placeholder and the stop list can be empty, so shutdown returns immediately. The spawn subsequently completes and only then registers retirement at line 1242. A process can therefore start or remain alive after close_session returns, violating the shutdown guarantee in section 5.4. Track spawn completion in the slot and await its resulting cleanup during close.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in d5d90ef. The Spawning slot now holds a channel that closes once its spawn is handled: the server is in the map, or its stop has begun. close_session takes these channels with the map and waits on each, up to one stop step (2s), before it waits for the stops. The stop of a spawn that lost its slot is then in the list close_session waits on.

New unit test close_session_waits_for_a_spawn_in_flight: a test-only hook holds one spawn for 500ms, and close_session runs during it. When close_session returns, the spawned server must be gone. With the wait removed, it fails: "close_session returned before the spawn ended".

tokio::select! {
s = child.wait() => break s.ok(),
Some(k) = kills.recv() => match k {
KillSignal::Term => signal_server(&mut child, false),

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.


[P2] Clean up the process group even when its leader exits first. Group SIGTERM can terminate the server while a descendant ignores it; child.wait() then ends this watcher, and stop() observes the leader's exit and skips SIGKILL. Graceful shutdown skips group signalling entirely: the new well-behaved-with-child fixture explicitly exits on exit, leaving its child's interval running indefinitely after close_session. The new tests cover Drop and a stubborn leader, which miss both paths. Track group cleanup independently of the leader's lifetime.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in d5d90ef. Once the watcher reaps the server, it sends SIGKILL to the server's process group. A child still in the group goes too, however the server ended: on exit, on its own, or on a group SIGTERM that the child ignored.

New unit test a_graceful_exit_does_not_leave_the_server_s_children: the server exits on exit and has a child that ignores SIGTERM. After close_session, the child must be gone within 1s. Without the group kill it fails: "the server's child outlived a graceful exit".

@avifenesh

Copy link
Copy Markdown
Collaborator Author

Re #102 (comment): addressed in 9f806fb. The Rust CI job is green on it (run 41963228710) and ran every spawn-client test: 7 unit tests, 20 in tests/spawn_client.rs and 8 in tests/spawn_client_api.rs.

  1. Exit-write test. It now orders by events. New fake-server mode hold-shutdown-reply: it writes got-shutdown when it reads shutdown, stops reading, and answers only once reply-shutdown exists. The test waits for got-shutdown, pushes a pre-built 4 MiB frame straight onto entry.writer, and then creates reply-shutdown. exit is therefore always queued behind the filler. The TS suite is unaffected; it keeps using stop-reading-after-shutdown, and its 61 tests pass. Under your load setup (taskset -c 5,6, a busy yes pinned to each CPU), the old unit tests failed 6 of 10 runs, all on this test. The new unit tests passed 25 of 25 under the same load, and the integration tests 10 of 10. With the exit bound removed, the new test hangs to its 10s limit.

  2. Readiness test. The hook now waits for the server to exit before the readiness check, instead of a 300ms pause. With the old check-then-lock order it fails at once.

  3. Spawn outside the lock. ensure_server claims the key with a Spawning placeholder under the lock, spawns outside it, then fills in the entry under the lock.

    • A concurrent call that finds the placeholder gets server_starting.
    • A failed spawn drops the placeholder.
    • A spawn that finishes after close_session took the map is stopped.

    New unit test: a test-only hook blocks one key's spawn for 3s on its thread, and another key gets a ready server within 2s while that spawn still runs. On a0d0701 with only the hook added, the other key waits and the test times out. The 16-task, 50-round concurrency stress passes.

  4. Process groups. On Unix each server starts in its own process group (process_group(0)). SIGTERM, SIGKILL and Drop signal the group. New fake-server suffix -with-child starts a child that ignores SIGTERM. Two new unit tests:

    • dropping the client stops the server and its child;
    • close_session on a server that ignores exit and SIGTERM takes its child with the final SIGKILL.

    With only the leader signalled, both children survive.

  5. Handle rebinding: lsp: an operation can be bound to a replacement server and get IO_ERROR instead of SERVER_CRASHED #103, marked as the next change.

Reran on 9f806fb:

  • cargo test --workspace --locked: 313 passed.
  • clippy: no warnings in touched files.
  • rustfmt: the touched files are clean.
  • cargo check -p harness-lsp --all-targets for x86_64-pc-windows-gnu and x86_64-apple-darwin: clean.
  • pnpm test:dependencies, pnpm lint:harness, and turbo run build typecheck test without harness-e2e: 39 of 39.
  • Spawn-client tests: 20 of 20 runs idle and 10 of 10 pinned with taskset -c 0, plus the load loops above. No fake server was left after any run.

Address the two review findings on 9f806fb, and test flakes under load.

- close_session waits, up to one stop step, for each spawn still
  running outside the lock. The Spawning slot holds a channel that
  closes once the spawn is handled, so the stop of a spawn that lost
  its slot is in the list close_session waits on.
- Once the watcher reaps a server, it sends SIGKILL to the server's
  process group. A child that ignored SIGTERM, or outlived a graceful
  exit, goes with the server.
- Two integration tests need the write after the fake server closed
  its stdin to fail. A server that another test spawned at the same
  moment could still hold that stdin, as a child that had not exec'd
  yet, and under load for longer than the start took. Those two tests
  now run alone; every other test holds the same lock shared.
- Tests wait for events instead of fixed pauses: the spawn record of a
  new server, the end of a start, the reap after kill -9. The TS test
  with the same spawn-count check polls for it too.
@avifenesh

Copy link
Copy Markdown
Collaborator Author

d5d90ef addresses revuto's two findings on 9f806fb and three test flakes that showed under load.

  1. close_session waits for a spawn in flight (fix(rust-lsp): bring the spawn client in line with the lifecycle spec #102 (comment)). The Spawning slot holds a channel that closes once its spawn is handled. close_session waits on each, up to one stop step, before it waits for the stops. The new unit test fails without the wait.

  2. The group goes when the leader exits (fix(rust-lsp): bring the spawn client in line with the lifecycle spec #102 (comment)). After the watcher reaps the server, it sends SIGKILL to the server's process group. The new unit test, a graceful exit whose child ignores SIGTERM, fails without it.

  3. Test flakes under load. I ran four copies of tests/spawn_client.rs side by side.

    • The two tests that need the write after the fake server closed its stdin to fail timed out in 5 of 410 runs. A server that another test spawned at that moment, still a child that had not exec'd, held the read end of the test server's stdin. The fake server found it by scanning /proc right after it closed its stdin, in a failing run. These two tests now run alone, under a lock every other test holds shared.
    • A spawn count checked right after a 300ms call failed 1 of 400 runs, before node had written its pid. The tests now wait for events instead of fixed pauses. The TS test with the same check polls for it.

    After: 400 of 400 runs of tests/spawn_client.rs, and 200 of 200 of tests/spawn_client_api.rs in two copies, under the same load.

The client has the same pipe window: a server that closes its stdin while another server in the process is being spawned can see its next write succeed, and that call ends at its timeout instead of SERVER_CRASHED.

Reran on d5d90ef:

  • cargo test --workspace --locked: 315 passed.
  • clippy: no warnings in touched files.
  • rustfmt: the touched files are clean.
  • cargo check -p harness-lsp --all-targets for x86_64-pc-windows-gnu and x86_64-apple-darwin: clean.
  • pnpm test:dependencies, pnpm lint:harness, and turbo run build typecheck test without harness-e2e: 39 of 39.
  • Concurrency stress, 16 tasks over 50 rounds: pass.
  • Spawn-client tests: 20 of 20 runs idle, 10 of 10 pinned with taskset -c 0. The unit tests passed 25 of 25 on two CPUs each shared with a busy yes. No fake server was left after any run.

@avifenesh

Copy link
Copy Markdown
Collaborator Author

Ready to land.

No blockers. The last two commits fix both revuto findings on 9f806fb. Each new test fails with its fix undone, and the loops were clean. Six follow-ups below. None breaks the spec or a test today.

Earlier points, rechecked

  • Spawn in flight at close (revuto on 9f806fb): fixed. With the wait removed, close_session_waits_for_a_spawn_in_flight fails: "close_session returned before the spawn ended", 0 spawns seen.
  • Group cleanup when the leader exits first (revuto on 9f806fb): fixed. Without the SIGKILL after the reap, a_graceful_exit_does_not_leave_the_server_s_children fails: "the server's child outlived a graceful exit".
  • Spawn outside the lock (9f806fb): with the spawn held under the servers lock again, a_slow_spawn_on_one_key_does_not_hold_up_another_key fails: "another key waited for the slow spawn".
  • Group signals (9f806fb): with signals sent to the leader only and no kill after the reap, the drop test, the final-SIGKILL test and the graceful-exit test all fail. The child outlives the server each time.
  • The a0d0701 fixes (one server per key, readiness under the lock, Drop, pruned stops, percent-decoded paths) are untouched by the last two commits and their tests still pass. Bugbot's handle thread is lsp: an operation can be bound to a replacement server and get IO_ERROR instead of SERVER_CRASHED #103.

Placeholder, close and signals: checked

  • No .await runs between the claim (spawn_client.rs:1248) and the block that resolves it (1253-1282). spawn_server is synchronous. So a dropped ensure_server future cannot leave a placeholder behind, and _handled always drops.
  • A failed spawn removes only its own placeholder (the claim number). A spawn that lost its slot retires its server before _handled drops, so its stop is in stops before close_session wakes.
  • Lock order is unchanged: servers then status, stops then status. No guard is held across an await.
  • signal_server (522) runs only inside the watcher's select loop, before child.wait() returns. The leader is at most a zombie there, so its pid and group id are still held.
  • The SPAWNS lock covers every test in tests/spawn_client.rs, kill9 included. cargo test runs the test binaries one after another, and the pipe race needs a fork in the same process. Under nextest each test is its own process: the lock does nothing there, and the race cannot happen there either. I did not rerun the four-copy load that showed the flake.

Follow-ups (not blocking)

  1. close_session waits for spawns one at a time. spawn_client.rs:1426-1428. Each spawn in flight gets its own 2s timeout, in turn. With N hung execs, for example several servers on one hung mount, close takes up to 2s x N instead of one stop step. Spec 5.4 has servers stop in parallel. Fix: one deadline for all of them (timeout_at), or join the waits.

  2. The kill after the reap can, in theory, hit a reused group id. spawn_client.rs:615-622. The comment holds while a group member is left: the group id stays taken. When none is left, the id is free as soon as child.wait() reaps the leader. A new process that got the same pid and made itself a group leader in that window would get SIGKILL. That needs a full pid wrap within microseconds, so it is not a practical risk. A precise version signals the group before the reap: wait for the exit with a pidfd or waitid(WNOWAIT), kill the group, then reap.

  3. Servers leave the host's process group. spawn_client.rs:962. With process_group(0), a Ctrl-C in the host's terminal, or a supervisor that kills the host's group, no longer reaches the servers or their children. They now rely on stdin EOF, or the processId check, to notice the host is gone. harness-lsp-cli keeps its client in a static (src/bin/cli.rs:67-70) and never calls close_session. At exit only kill_on_drop fires, and it signals the leader alone, so a server's children stay behind. The CLI could call close_session on stdin EOF and on SIGINT and SIGTERM.

  4. Spec and TS do not describe the group behavior. The Rust client now signals the group, and SIGKILLs it after any exit, a clean exit included. The TS client signals the process only (packages/lsp/src/spawnClient.ts:248, 643-645) and leaves a server's children running after a clean exit. Spec 5.4 says neither. A helper that a server means to keep, started without setsid, now dies with it. That is a sound default, but it is a choice the spec should state. AGENTS.md has spec and code move together: one line in 5.4, plus an issue for the TS side (detached: true and process.kill(-pid)), keeps the ports aligned. Cheap enough to add here.

  5. Two tests still read the pid file right after a short bound. tests/spawn_client.rs:327 (500ms call budget) and tests/spawn_client_api.rs:90 (300ms initialize limit). If node has not written pid when the bound passes, fake.pid() panics on a missing file. That is the same race d5d90ef fixed for the spawn count. I could not trigger it: 5 of 5 runs of each passed with the test on one CPU shared with six busy loops. Waiting for the pid file first, as the unit tests do for child-pid, closes it.

  6. Smaller items.

    • concurrent_first_calls_share_one_server_and_close_stops_every_process (tests/spawn_client.rs:368-369) still sleeps 300ms before it counts servers. An extra server that starts slowly records its pid late, so under load the check can pass when it should fail. It cannot flake; it can only miss.
    • If spawn_server panics after the claim, the Spawning slot stays, and every later call on that key gets server_starting until close_session. Today that takes a poisoned mutex or tokio::spawn outside a runtime. A small drop guard on the claim would clear the slot.
    • For lsp: an operation can be bound to a replacement server and get IO_ERROR instead of SERVER_CRASHED #103: while a placeholder is in the map, an operation that holds the old handle gets IO_ERROR "LSP error: no server entry for fake|/root" (spawn_client.rs:1109-1117). That is a second message for the gap the issue describes, next to "not ready (state=starting)". Worth adding to the issue.

What I ran

Own worktrees at d5d90ef. Scratch, TMPDIR and target dirs on disk.

  • cargo test -p harness-lsp --locked: 9 unit tests, then 16, 20 and 8 integration tests. All pass.
  • Spawn-client tests (the 9 unit tests, tests/spawn_client.rs, tests/spawn_client_api.rs) looped 10 times: 10 of 10 pass, no fake server left after any run.
  • Undid one fix at a time on a second worktree and ran the tests that cover it. The unmodified head passes all five tests first.
Fix undone Test Result
close_session waits for spawns in flight close_session_waits_for_a_spawn_in_flight fails, 0 spawns seen
SIGKILL to the group after the reap a_graceful_exit_does_not_leave_the_server_s_children fails, child left
Group signals (leader only, no kill after the reap) the drop, final-kill and graceful-exit unit tests all 3 fail, child left
Spawn outside the servers lock a_slow_spawn_on_one_key_does_not_hold_up_another_key fails at its 2s limit
  • Follow-up 5: the two tests on one CPU shared with six busy loops, 5 runs each: all pass.
  • cargo clippy -p harness-lsp --all-targets --locked: 4 warnings, all in files this PR does not touch (format.rs, manifest.rs, tests/lsp.rs).
  • cargo fmt -p harness-lsp --check: diffs only in untouched files (bin/cli.rs, fence.rs, manifest.rs, schema.rs, tests/lsp.rs). Every touched file is clean.
  • cargo check --workspace --all-targets --locked: clean, so harness-tools builds on the new API.
  • CI on d5d90ef: Rust, TypeScript and CodeQL pass. The revuto check fails because it hit its round limit, not on a finding.
  • AGENTS.md: the last two commits add one message, for a spawn that races close_session. No tool description or schema changed, so no model e2e run is due.

@avifenesh
avifenesh merged commit d5d90ef into main Nov 5, 2026
6 of 7 checks passed
@avifenesh
avifenesh deleted the fix/rust-lsp-spawn-client branch November 5, 2026 06:47
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.

Rust lsp port: initialize bound, exit detection, stderr and shutdown per the design spec

1 participant