Skip to content

Commit ca3eeee

Browse files
committed
fix(opencode): contain LSP writes to exited language servers
1 parent 355a0bc commit ca3eeee

3 files changed

Lines changed: 177 additions & 2 deletions

File tree

‎packages/opencode/src/lsp/client.ts‎

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import path from "path"
2+
import { Writable } from "node:stream"
23
import { pathToFileURL, fileURLToPath } from "url"
34
import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node"
45
import type { Diagnostic as VSCodeDiagnostic } from "vscode-languageserver-types"
@@ -127,13 +128,30 @@ export async function create(input: {
127128
directory: string
128129
instance: InstanceContext
129130
}) {
130-
const instance = input.instance
131+
const safeStdin = safeWritable(input.server.process.stdin)
132+
safeStdin.on("error", () => {})
131133

132134
const connection = createMessageConnection(
133135
new StreamMessageReader(input.server.process.stdout as any),
134-
new StreamMessageWriter(input.server.process.stdin as any),
136+
new StreamMessageWriter(safeStdin as any),
135137
)
136138
input.server.process.stderr?.resume()
139+
140+
// --- Liveness ---
141+
// A language server process can exit (crash or shutdown) while we still hold its
142+
// connection. Writing JSON-RPC to its destroyed stdin rejects, and an unowned
143+
// rejection terminates the worker ("Worker has been terminated"). Track death so
144+
// the pool can evict this client and we never write to a dead server.
145+
let closed = false
146+
const closeListeners = new Set<() => void>()
147+
const markClosed = () => {
148+
if (closed) return
149+
closed = true
150+
for (const listener of [...closeListeners]) listener()
151+
}
152+
connection.onClose(markClosed)
153+
connection.onError(markClosed)
154+
input.server.process.once("exit", markClosed)
137155
// --- Connection state ---
138156

139157
const pushDiagnostics = new Map<string, Diagnostic[]>()
@@ -550,8 +568,17 @@ export async function create(input: {
550568
get connection() {
551569
return connection
552570
},
571+
get closed() {
572+
return closed
573+
},
574+
onClose(listener: () => void) {
575+
closeListeners.add(listener)
576+
return () => closeListeners.delete(listener)
577+
},
553578
notify: {
554579
async open(request: { path: string }) {
580+
// Never write to a server whose process has exited.
581+
if (closed) return files[request.path]?.version ?? 0
555582
request.path = Filesystem.normalizePath(
556583
path.isAbsolute(request.path) ? request.path : path.resolve(input.directory, request.path),
557584
)
@@ -638,6 +665,7 @@ export async function create(input: {
638665
await waitForFullDiagnostics({ path: normalizedPath, version: request.version, after: request.after })
639666
},
640667
async shutdown() {
668+
markClosed()
641669
connection.end()
642670
connection.dispose()
643671
await Process.stop(input.server.process)
@@ -647,4 +675,27 @@ export async function create(input: {
647675
return result
648676
}
649677

678+
// Wrap a language server's stdin so a write after the process exits resolves as a
679+
// no-op instead of throwing an unowned rejection. vscode-jsonrpc emits writes we
680+
// never await (for example $/cancelRequest when a request is cancelled or times
681+
// out), so a dead-server write cannot be caught at our call sites; the failure has
682+
// to be contained here at the stream boundary, otherwise it becomes an unhandled
683+
// rejection that terminates the worker.
684+
export function safeWritable(stream: NodeJS.WritableStream | null | undefined) {
685+
const target = stream as (NodeJS.WritableStream & { destroyed?: boolean; writableEnded?: boolean }) | null | undefined
686+
return new Writable({
687+
write(chunk, encoding, callback) {
688+
if (!target || target.destroyed || target.writableEnded) {
689+
callback()
690+
return
691+
}
692+
try {
693+
target.write(chunk, encoding as BufferEncoding, () => callback())
694+
} catch {
695+
callback()
696+
}
697+
},
698+
})
699+
}
700+
650701
export * as LSPClient from "./client"

‎packages/opencode/src/lsp/lsp.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,13 @@ export const layer = Layer.effect(
250250
}
251251

252252
s.clients.push(client)
253+
// Evict the client when its server process dies so we never hand out a
254+
// client that would write to a destroyed stream. Leaving it out of the
255+
// pool lets a fresh server spawn on the next request (auto-recovery).
256+
client.onClose(() => {
257+
const index = s.clients.indexOf(client)
258+
if (index >= 0) s.clients.splice(index, 1)
259+
})
253260
return client
254261
}
255262

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import { describe, expect, test } from "bun:test"
2+
import path from "path"
3+
import { PassThrough } from "node:stream"
4+
import { withTestInstance } from "../fixture/fixture"
5+
import { LSPClient, safeWritable } from "@/lsp/client"
6+
import * as LSPServer from "@/lsp/server"
7+
8+
function spawnFakeServer() {
9+
const { spawn } = require("child_process")
10+
const serverPath = path.join(__dirname, "../fixture/lsp/fake-lsp-server.js")
11+
return {
12+
process: spawn(process.execPath, [serverPath], {
13+
stdio: "pipe",
14+
}),
15+
}
16+
}
17+
18+
function createClient(handle: { process: unknown }) {
19+
return withTestInstance({
20+
directory: process.cwd(),
21+
fn: (ctx) =>
22+
LSPClient.create({
23+
serverID: "fake",
24+
server: handle as unknown as LSPServer.Handle,
25+
root: process.cwd(),
26+
directory: process.cwd(),
27+
instance: ctx,
28+
}),
29+
})
30+
}
31+
32+
describe("LSPClient dead server", () => {
33+
// Regression: a write to a language server whose stdin has been destroyed must
34+
// resolve as a no-op instead of erroring. vscode-jsonrpc emits writes we never
35+
// await (e.g. $/cancelRequest on request cancellation), so the failure is
36+
// uncatchable at the call site and previously terminated the worker ("Worker has
37+
// been terminated"). safeWritable must contain it at the stream boundary.
38+
test("safeWritable swallows writes to a destroyed stream instead of erroring", async () => {
39+
const destroyed = new PassThrough()
40+
destroyed.destroy()
41+
await new Promise((resolve) => setImmediate(resolve))
42+
expect(destroyed.destroyed).toBe(true)
43+
44+
// The raw stream errors on write after destroy (the source of the rejection).
45+
const rawError = await new Promise<Error | null>((resolve) => {
46+
try {
47+
destroyed.write(Buffer.from("x"), (err) => resolve(err ?? null))
48+
} catch (err) {
49+
resolve(err as Error)
50+
}
51+
})
52+
expect(rawError).not.toBeNull()
53+
54+
// The wrapper completes the write callback with no error.
55+
const wrapped = safeWritable(destroyed)
56+
const wrappedError = await new Promise<Error | null>((resolve, reject) => {
57+
const timer = setTimeout(() => reject(new Error("write callback never fired")), 1000)
58+
wrapped.write(Buffer.from("hello"), (err) => {
59+
clearTimeout(timer)
60+
resolve(err ?? null)
61+
})
62+
})
63+
expect(wrappedError).toBeNull()
64+
})
65+
66+
// The wrapper must still forward writes to a live stream unchanged.
67+
test("safeWritable forwards writes to a live stream", async () => {
68+
const live = new PassThrough()
69+
const received = new Promise<string>((resolve) => {
70+
live.once("data", (chunk) => resolve(chunk.toString()))
71+
})
72+
const wrapped = safeWritable(live)
73+
wrapped.write(Buffer.from("payload"))
74+
expect(await received).toBe("payload")
75+
})
76+
77+
// Regression: when the server process exits, the client must report closed and
78+
// notify listeners, so the pool can evict it and stop handing out a dead client.
79+
test("marks the client closed and notifies listeners when the server process exits", async () => {
80+
const handle = spawnFakeServer() as any
81+
const client = await createClient(handle)
82+
83+
let notified = false
84+
client.onClose(() => {
85+
notified = true
86+
})
87+
88+
await new Promise<void>((resolve) => {
89+
handle.process.once("exit", () => resolve())
90+
handle.process.kill("SIGKILL")
91+
})
92+
await new Promise((resolve) => setTimeout(resolve, 100))
93+
94+
expect(client.closed).toBe(true)
95+
expect(notified).toBe(true)
96+
97+
await client.shutdown().catch(() => {})
98+
})
99+
100+
// After the server exits, notify.open must short-circuit instead of writing to a
101+
// dead server (and must not throw or reject).
102+
test("notify.open is a no-op after the server process exits", async () => {
103+
const handle = spawnFakeServer() as any
104+
const client = await createClient(handle)
105+
106+
await new Promise<void>((resolve) => {
107+
handle.process.once("exit", () => resolve())
108+
handle.process.kill("SIGKILL")
109+
})
110+
await new Promise((resolve) => setTimeout(resolve, 100))
111+
112+
expect(client.closed).toBe(true)
113+
await expect(client.notify.open({ path: path.join(process.cwd(), "package.json") })).resolves.toBeDefined()
114+
115+
await client.shutdown().catch(() => {})
116+
})
117+
})

0 commit comments

Comments
 (0)