Skip to content

Commit 94cad70

Browse files
committed
fix(vscode): stop the LSP restarting on unrelated configuration changes
The extension restarted the language server on every configuration change in the editor and allowed those restarts to overlap, which showed up as `Client got disposed and can't be restarted` plus a stream of `command '...' already exists` errors. Two changes: 1. Filter the configuration event. `extension.ts` subscribed to `workspace.onDidChangeConfiguration`, which fires for every setting in the editor including ones written by other extensions, and restarted unconditionally. It now restarts only when a section the server reads is affected — `sqlmesh` (`projectPaths`, `lspEntrypoint`) or `python.defaultInterpreterPath`. This is why running any python command in a VS Code terminal killed the extension: the Python extension touches its own settings in response, and that was enough to restart the server. It also explains why running a copy of the same interpreter from a different path did not reproduce it, and why a subshell, `su`, `uvx` or a notebook did not either — none of those make the Python extension write a setting. 2. Serialize restarts. `restart()` stops a client and starts another, so concurrent restarts leave the outgoing client's command registrations colliding with the incoming one's and leave requests aimed at a client that has already been disposed. Restarts now run one at a time, with triggers that arrive mid-restart collapsing into a single rerun rather than queueing one restart each. An explicit restart is never downgraded to an automatic one when the two are coalesced. Both helpers are kept free of `vscode` imports so they are covered by `vitest` in the `test-vscode` stage. Fixes #5920 Fixes #5642 Signed-off-by: Adegbite Ayoade <tripleaceme@gmail.com>
1 parent 7e4f83e commit 94cad70

5 files changed

Lines changed: 286 additions & 2 deletions

File tree

‎vscode/extension/src/extension.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ import {
2424
traceError,
2525
} from './utilities/common/log'
2626
import { onDidChangePythonInterpreter } from './utilities/common/python'
27+
import { requiresLspRestart } from './utilities/common/configurationChange'
28+
import { coalesceAsync } from './utilities/coalesceAsync'
2729
import { sleep } from './utilities/sleep'
2830
import { handleError } from './utilities/errors'
2931

@@ -65,7 +67,16 @@ export async function activate(context: vscode.ExtensionContext) {
6567
),
6668
)
6769

68-
const restartLsp = async (invokedByUser = false): Promise<void> => {
70+
/**
71+
* Set when a restart was asked for explicitly, so that a user-invoked restart
72+
* coalesced together with an automatic one is still treated as user-invoked.
73+
*/
74+
let restartInvokedByUser = false
75+
76+
const runRestart = async (): Promise<void> => {
77+
const invokedByUser = restartInvokedByUser
78+
restartInvokedByUser = false
79+
6980
if (!lspClient) {
7081
lspClient = new LSPClient()
7182
}
@@ -95,6 +106,18 @@ export async function activate(context: vscode.ExtensionContext) {
95106
context.subscriptions.push(testControllerDisposable)
96107
}
97108

109+
/**
110+
* Restarts are serialized: a client disposing while the next one starts up
111+
* leaves colliding command registrations and requests aimed at a disposed
112+
* client, which is what surfaced as constant crashes.
113+
*/
114+
const restartLspSerialized = coalesceAsync(runRestart)
115+
116+
const restartLsp = async (invokedByUser = false): Promise<void> => {
117+
restartInvokedByUser = restartInvokedByUser || invokedByUser
118+
await restartLspSerialized()
119+
}
120+
98121
// commands needing the restart helper
99122
context.subscriptions.push(
100123
vscode.commands.registerCommand(
@@ -191,7 +214,13 @@ export async function activate(context: vscode.ExtensionContext) {
191214

192215
context.subscriptions.push(
193216
onDidChangePythonInterpreter(() => restartLsp()),
194-
onDidChangeConfiguration(() => restartLsp()),
217+
// Only restart for settings the server actually reads. This event fires for
218+
// every setting in the editor, including ones written by other extensions.
219+
onDidChangeConfiguration(event => {
220+
if (requiresLspRestart(event)) {
221+
void restartLsp()
222+
}
223+
}),
195224
)
196225

197226
if (!lspClient.hasCompletionCapability()) {
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { coalesceAsync } from './coalesceAsync'
3+
4+
/**
5+
* Let pending microtasks run. A rerun is scheduled off the promise of the run
6+
* that precedes it, so it starts a few hops after that run settles.
7+
*/
8+
const flush = () => new Promise<void>(resolve => setTimeout(resolve, 0))
9+
10+
/** A task that only settles when the test releases it. */
11+
function deferredTask() {
12+
let release: (() => void) | undefined
13+
let rejectWith: ((error: Error) => void) | undefined
14+
let calls = 0
15+
16+
const run = () => {
17+
calls += 1
18+
return new Promise<void>((resolve, reject) => {
19+
release = resolve
20+
rejectWith = reject
21+
})
22+
}
23+
24+
return {
25+
run,
26+
get calls() {
27+
return calls
28+
},
29+
release: () => release?.(),
30+
reject: (error: Error) => rejectWith?.(error),
31+
}
32+
}
33+
34+
describe('coalesceAsync', () => {
35+
it('runs the task immediately when idle', async () => {
36+
const task = deferredTask()
37+
const run = coalesceAsync(task.run)
38+
39+
const first = run()
40+
expect(task.calls).toBe(1)
41+
42+
task.release()
43+
await first
44+
})
45+
46+
// A burst of triggers used to start a restart per event, which left clients
47+
// disposing and starting concurrently. See #5642.
48+
it('collapses every call made while running into a single rerun', async () => {
49+
const task = deferredTask()
50+
const run = coalesceAsync(task.run)
51+
52+
const first = run()
53+
expect(task.calls).toBe(1)
54+
55+
const queued = [run(), run(), run(), run()]
56+
expect(task.calls).toBe(1)
57+
58+
task.release()
59+
await first
60+
await flush()
61+
62+
// Exactly one rerun is scheduled, no matter how many calls arrived.
63+
expect(task.calls).toBe(2)
64+
65+
task.release()
66+
await Promise.all(queued)
67+
await flush()
68+
expect(task.calls).toBe(2)
69+
})
70+
71+
it('runs again for calls made after the previous run finished', async () => {
72+
const task = deferredTask()
73+
const run = coalesceAsync(task.run)
74+
75+
const first = run()
76+
task.release()
77+
await first
78+
expect(task.calls).toBe(1)
79+
80+
const second = run()
81+
expect(task.calls).toBe(2)
82+
task.release()
83+
await second
84+
})
85+
86+
it('resolves the callers that were coalesced together', async () => {
87+
const task = deferredTask()
88+
const run = coalesceAsync(task.run)
89+
90+
const first = run()
91+
const queued = [run(), run()]
92+
93+
task.release()
94+
await first
95+
// The rerun has to be in flight before it can be released.
96+
await flush()
97+
task.release()
98+
99+
await expect(Promise.all(queued)).resolves.toEqual([undefined, undefined])
100+
})
101+
102+
it('surfaces a failure without wedging later calls', async () => {
103+
const task = deferredTask()
104+
const run = coalesceAsync(task.run)
105+
106+
const first = run()
107+
task.reject(new Error('restart failed'))
108+
await expect(first).rejects.toThrow('restart failed')
109+
110+
const second = run()
111+
expect(task.calls).toBe(2)
112+
task.release()
113+
await second
114+
})
115+
})
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Serialize an async task so it never overlaps with itself, collapsing any
3+
* calls that arrive while it is running into a single rerun.
4+
*
5+
* Restarting the language server means stopping a client and starting another.
6+
* Letting two of those interleave leaves commands registered by the outgoing
7+
* client colliding with the incoming one, and leaves requests addressed to a
8+
* client that has already been disposed. Queueing one run per trigger would
9+
* only spread the same problem out over time, so queued triggers collapse into
10+
* one rerun: all the caller wants is for the task to have run after its
11+
* request, not for it to run once per request.
12+
*
13+
* @param task The task to serialize.
14+
* @returns A function that resolves once the task has run for that call.
15+
*/
16+
export function coalesceAsync(task: () => Promise<void>): () => Promise<void> {
17+
let running: Promise<void> | undefined
18+
let queued: Promise<void> | undefined
19+
20+
const start = async (): Promise<void> => {
21+
try {
22+
await task()
23+
} finally {
24+
running = undefined
25+
}
26+
}
27+
28+
return (): Promise<void> => {
29+
if (!running) {
30+
running = start()
31+
return running
32+
}
33+
34+
// A rerun is already scheduled, so this call is satisfied by that one.
35+
if (!queued) {
36+
queued = running
37+
// A failed run must not stop the rerun that was asked for; the caller
38+
// waiting on the failed run is the one that sees the error.
39+
.catch(() => undefined)
40+
.then(() => {
41+
queued = undefined
42+
running = start()
43+
return running
44+
})
45+
}
46+
47+
return queued
48+
}
49+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { requiresLspRestart } from './configurationChange'
3+
4+
/**
5+
* Build a stand-in for `vscode.ConfigurationChangeEvent` from the settings that
6+
* changed. VS Code reports a section as affected when the changed key is the
7+
* section itself or sits underneath it.
8+
*/
9+
const changed = (...keys: string[]) => ({
10+
affectsConfiguration: (section: string) =>
11+
keys.some(key => key === section || key.startsWith(`${section}.`)),
12+
})
13+
14+
describe('requiresLspRestart', () => {
15+
it('restarts when a sqlmesh setting changes', () => {
16+
expect(requiresLspRestart(changed('sqlmesh.projectPaths'))).toBe(true)
17+
expect(requiresLspRestart(changed('sqlmesh.lspEntrypoint'))).toBe(true)
18+
})
19+
20+
it('restarts when the python interpreter changes', () => {
21+
expect(requiresLspRestart(changed('python.defaultInterpreterPath'))).toBe(
22+
true,
23+
)
24+
})
25+
26+
// The LSP used to restart on every configuration change in the editor, so
27+
// anything that wrote a setting took the extension down with it. See #5920.
28+
it('ignores settings the language server does not read', () => {
29+
expect(requiresLspRestart(changed('editor.fontSize'))).toBe(false)
30+
expect(requiresLspRestart(changed('workbench.colorTheme'))).toBe(false)
31+
expect(requiresLspRestart(changed('files.autoSave'))).toBe(false)
32+
})
33+
34+
// Running any python command in a VS Code terminal makes the Python
35+
// extension touch its own terminal settings, which is what made the
36+
// extension crash whenever sqlmesh was run in the terminal. See #5642.
37+
it('ignores python settings unrelated to the interpreter', () => {
38+
expect(
39+
requiresLspRestart(changed('python.terminal.activateEnvironment')),
40+
).toBe(false)
41+
expect(
42+
requiresLspRestart(changed('python.analysis.typeCheckingMode')),
43+
).toBe(false)
44+
expect(requiresLspRestart(changed('terminal.integrated.env.linux'))).toBe(
45+
false,
46+
)
47+
})
48+
49+
it('does not restart when nothing relevant changed', () => {
50+
expect(requiresLspRestart(changed())).toBe(false)
51+
})
52+
53+
it('restarts when a relevant setting changes alongside irrelevant ones', () => {
54+
expect(
55+
requiresLspRestart(changed('editor.fontSize', 'sqlmesh.projectPaths')),
56+
).toBe(true)
57+
})
58+
})
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Configuration sections the language server reads, so a change to any of them
3+
* needs the server restarted to take effect.
4+
*
5+
* `sqlmesh` covers `sqlmesh.projectPaths` and `sqlmesh.lspEntrypoint`, both of
6+
* which decide how the server is launched. The interpreter path matters because
7+
* the server runs inside that interpreter.
8+
*/
9+
export const RESTART_CONFIGURATION_SECTIONS = [
10+
'sqlmesh',
11+
'python.defaultInterpreterPath',
12+
]
13+
14+
/**
15+
* The part of `vscode.ConfigurationChangeEvent` this module needs. Declared
16+
* structurally so the check stays unit testable without the VS Code runtime.
17+
*/
18+
export interface ConfigurationChange {
19+
affectsConfiguration(section: string): boolean
20+
}
21+
22+
/**
23+
* Whether a configuration change affects a setting the language server reads.
24+
*
25+
* `workspace.onDidChangeConfiguration` fires for every setting in the editor,
26+
* including ones written by other extensions, so the event has to be filtered
27+
* before it triggers a restart.
28+
*/
29+
export function requiresLspRestart(event: ConfigurationChange): boolean {
30+
return RESTART_CONFIGURATION_SECTIONS.some(section =>
31+
event.affectsConfiguration(section),
32+
)
33+
}

0 commit comments

Comments
 (0)