Skip to content

Commit 17b9a67

Browse files
gselzerclaude
andcommitted
code-lsp: don't sync documents gone stale while a process starts
Requests and diagnoses wait for the process to start, which can take long. They then synced the document as it was when they were made: so the process could be told stale text, or a document closed meanwhile (and so open it anew). Now they sync it only if still open at that version, checked under its lock, which closing it takes too; skipped requests are answered with nothing, rather than left pending. Shutting down also cancels documents' pending diagnoses, which would otherwise start the process anew. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent cda4eea commit 17b9a67

3 files changed

Lines changed: 184 additions & 18 deletions

File tree

‎scijava-code-lsp/src/main/java/org/scijava/code/lsp/server/ProcessLanguageServer.java‎

Lines changed: 56 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030
package org.scijava.code.lsp.server;
3131

32+
import java.util.ArrayList;
3233
import java.util.List;
3334
import java.util.Map;
3435
import java.util.concurrent.CompletableFuture;
@@ -123,8 +124,9 @@ public CompletableFuture<InitializeResult> initialize(
123124

124125
@Override
125126
public CompletableFuture<Object> shutdown() {
126-
slot.running().ifPresent(s -> docs.keySet().forEach(s::close));
127-
docs.clear();
127+
// NB: Closing each document also cancels its pending diagnosis, which
128+
// would otherwise start the process anew.
129+
new ArrayList<>(docs.keySet()).forEach(this::close);
128130
return CompletableFuture.completedFuture(null);
129131
}
130132

@@ -162,10 +164,7 @@ public void didChange(final DidChangeTextDocumentParams params) {
162164

163165
@Override
164166
public void didClose(final DidCloseTextDocumentParams params) {
165-
final String uri = params.getTextDocument().getUri();
166-
final Doc doc = docs.remove(uri);
167-
if (doc != null && doc.pending != null) doc.pending.cancel(false);
168-
slot.running().ifPresent(s -> s.close(uri));
167+
close(params.getTextDocument().getUri());
169168
}
170169

171170
@Override
@@ -269,7 +268,15 @@ private <T> CompletableFuture<T> request(final String uri,
269268
final CompletableFuture<T> answer = new CompletableFuture<>();
270269
slot.process().thenAccept(s -> {
271270
if (answer.isDone()) return;
272-
final CompletableFuture<T> raw = s.request(uri, item.getText(), request);
271+
final CompletableFuture<T> raw;
272+
// NB: The process may have taken long to start (see current).
273+
synchronized (doc) {
274+
if (stale(uri, doc, item.getVersion())) {
275+
answer.complete(null);
276+
return;
277+
}
278+
raw = s.request(uri, item.getText(), request);
279+
}
273280
answer.whenComplete((r, error) -> {
274281
if (answer.isCancelled()) raw.cancel(true);
275282
});
@@ -306,16 +313,49 @@ private void changed(final String uri, final String text,
306313
private void diagnose(final Doc doc, final TextDocumentItem item) {
307314
final String uri = item.getUri();
308315
final int version = item.getVersion();
309-
slot.process().thenCompose(s -> s.diagnostics(uri, item.getText()))
310-
.orTimeout(DIAGNOSE_TIMEOUT, TimeUnit.MILLISECONDS).thenAccept(found -> {
311-
final LanguageClient c = client;
312-
// NB: Only if still current.
313-
if (docs.get(uri) != doc || doc.version != version || c == null) {
314-
return;
316+
slot.process().thenCompose(s -> {
317+
// NB: The process may have taken long to start (see current).
318+
synchronized (doc) {
319+
if (stale(uri, doc, version)) {
320+
return CompletableFuture.completedFuture(null);
315321
}
316-
c.publishDiagnostics(new PublishDiagnosticsParams(uri, found,
317-
version));
318-
});
322+
return s.diagnostics(uri, item.getText());
323+
}
324+
}).orTimeout(DIAGNOSE_TIMEOUT, TimeUnit.MILLISECONDS).thenAccept(found -> {
325+
final LanguageClient c = client;
326+
// NB: Only if still current, as it may have changed meanwhile.
327+
synchronized (doc) {
328+
if (stale(uri, doc, version) || c == null) return;
329+
}
330+
c.publishDiagnostics(new PublishDiagnosticsParams(uri, found,
331+
version));
332+
});
333+
}
334+
335+
/**
336+
* Whether a document is still open, at the given version: whether it may be
337+
* synced as it was then. NB: Not so, by the time a process that took long to
338+
* start is asked: syncing it then would give the process stale text, or
339+
* open it anew once closed. Callers hold its lock, until done syncing it.
340+
*/
341+
private boolean stale(final String uri, final Doc doc, final int version)
342+
{
343+
return docs.get(uri) != doc || doc.version != version;
344+
}
345+
346+
/**
347+
* Forgets a document, cancelling its pending diagnosis; and closes it in
348+
* the process, if running.
349+
*/
350+
private void close(final String uri) {
351+
final Doc doc = docs.remove(uri);
352+
if (doc == null) return;
353+
// NB: Under its lock, so that whatever syncs it (see current) does so
354+
// either before (and is then closed) or not at all.
355+
synchronized (doc) {
356+
if (doc.pending != null) doc.pending.cancel(false);
357+
slot.running().ifPresent(s -> s.close(uri));
358+
}
319359
}
320360

321361
private static final class Doc {

‎scijava-code-lsp/src/test/java/org/scijava/code/lsp/server/FakeServers.java‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ public Process start(final Environment env) throws IOException {
127127
final PipedOutputStream serverOut = new PipedOutputStream(clientIn);
128128
final PipedInputStream serverIn = new PipedInputStream(1 << 16);
129129
final PipedOutputStream clientOut = new PipedOutputStream(serverIn);
130-
final Server server = new Server();
130+
final Server server = newServer();
131131
final org.eclipse.lsp4j.jsonrpc.Launcher<org.eclipse.lsp4j.services.LanguageClient> launcher =
132132
LSPLauncher.createServerLauncher(server, serverIn, serverOut);
133133
server.client = launcher.getRemoteProxy();
@@ -193,10 +193,15 @@ public Object initializationOptions(final Environment env) {
193193
public String rootUri(final Environment env) {
194194
return "file:///scripts";
195195
}
196+
197+
/** Makes the server to start (e.g. one of a kind of its own). */
198+
Server newServer() {
199+
return new Server();
200+
}
196201
}
197202

198203
/** A language server knowing a few things about json. */
199-
static final class Server implements LanguageServer, TextDocumentService,
204+
static class Server implements LanguageServer, TextDocumentService,
200205
WorkspaceService
201206
{
202207

‎scijava-code-lsp/src/test/java/org/scijava/code/lsp/server/ProcessLanguageServerTest.java‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,15 +46,21 @@
4646
import java.util.concurrent.CopyOnWriteArrayList;
4747
import java.util.concurrent.TimeUnit;
4848

49+
import org.eclipse.lsp4j.CompletionParams;
50+
import org.eclipse.lsp4j.DidChangeTextDocumentParams;
4951
import org.eclipse.lsp4j.DidCloseTextDocumentParams;
5052
import org.eclipse.lsp4j.InitializeParams;
53+
import org.eclipse.lsp4j.InitializeResult;
5154
import org.eclipse.lsp4j.MessageActionItem;
5255
import org.eclipse.lsp4j.MessageParams;
56+
import org.eclipse.lsp4j.Position;
5357
import org.eclipse.lsp4j.PublishDiagnosticsParams;
5458
import org.eclipse.lsp4j.ServerCapabilities;
5559
import org.eclipse.lsp4j.ShowMessageRequestParams;
60+
import org.eclipse.lsp4j.TextDocumentContentChangeEvent;
5661
import org.eclipse.lsp4j.TextDocumentIdentifier;
5762
import org.eclipse.lsp4j.TextDocumentSyncKind;
63+
import org.eclipse.lsp4j.VersionedTextDocumentIdentifier;
5864
import org.eclipse.lsp4j.services.LanguageClient;
5965
import org.junit.jupiter.api.AfterEach;
6066
import org.junit.jupiter.api.BeforeEach;
@@ -206,8 +212,123 @@ public Process start(final Environment env) throws IOException {
206212
}
207213
}
208214

215+
/**
216+
* Tests that a request about a document closed while the process starts is
217+
* answered (with nothing), without opening the document in the process.
218+
*/
219+
@Test
220+
public void testClosedDuringStartup() throws Exception {
221+
final DelayingLauncher launcher = new DelayingLauncher();
222+
final ServerProcesses delayed = servers(launcher);
223+
try {
224+
final ProcessLanguageServer s = (ProcessLanguageServer) delayed.server(
225+
ENV);
226+
final String uri = "untitled:/l.py";
227+
open(s, uri, "x");
228+
// Asked while the process starts...
229+
final CompletableFuture<?> answer = s.completion(new CompletionParams(
230+
new TextDocumentIdentifier(uri), new Position(0, 1)));
231+
final DelayedFakeServer late = launcher.server();
232+
// ...then closed, before it has finished starting.
233+
s.didClose(new DidCloseTextDocumentParams(new TextDocumentIdentifier(
234+
uri)));
235+
late.finishInitializing();
236+
assertNull(answer.get(10, TimeUnit.SECONDS));
237+
assertFalse(late.texts.containsKey(uri));
238+
}
239+
finally {
240+
delayed.shutdown();
241+
}
242+
}
243+
244+
/**
245+
* Sometimes language server startup is slow.
246+
* This test ensures that, when multiple changes are made
247+
* during server startup, only the most recent change is sent
248+
* to the server.
249+
*/
250+
@Test
251+
public void testChangedDuringStartup() throws Exception {
252+
final DelayingLauncher launcher = new DelayingLauncher();
253+
final ServerProcesses delayed = servers(launcher);
254+
try {
255+
final ProcessLanguageServer s = (ProcessLanguageServer) delayed.server(
256+
ENV);
257+
final List<PublishDiagnosticsParams> published = connect(s);
258+
final String uri = "untitled:/l.py";
259+
open(s, uri, "old");
260+
// Version 1's diagnosis waits for the process to start...
261+
final DelayedFakeServer late = launcher.server();
262+
s.didChange(new DidChangeTextDocumentParams(
263+
new VersionedTextDocumentIdentifier(uri, 2), Collections.singletonList(
264+
new TextDocumentContentChangeEvent("new"))));
265+
// ...as does version 2's, once the pause after the change has passed.
266+
// NB: No sign of that but time.
267+
Thread.sleep(3 * PAUSE);
268+
late.finishInitializing();
269+
// Once version 2's problems are published, the process has it...
270+
waitFor(() -> published.stream().anyMatch(p -> p.getVersion() == 2));
271+
// ...and was never told version 1, which had become stale.
272+
assertEquals("new", late.texts.get(uri));
273+
assertEquals(Collections.singletonList("open " + uri + " 1"),
274+
late.events);
275+
}
276+
finally {
277+
delayed.shutdown();
278+
}
279+
}
280+
209281
// -- Helper methods --
210282

283+
/**
284+
* How long a document must stay unchanged before its problems are asked
285+
* for, as {@link ProcessLanguageServer} has it.
286+
*/
287+
private static final long PAUSE = Long.getLong("scijava.lsp.pause", 300);
288+
289+
/** Processes started by the given launcher. */
290+
private static ServerProcesses servers(final FakeServers.Launcher launcher) {
291+
return new ServerProcesses(launcher, new StderrLogService(), 60_000, 2,
292+
System::currentTimeMillis);
293+
}
294+
295+
/** Starts fake servers that finish initializing only once told. */
296+
private static final class DelayingLauncher extends FakeServers.Launcher {
297+
298+
@Override
299+
FakeServers.Server newServer() {
300+
return new DelayedFakeServer();
301+
}
302+
303+
/** The server started first, once started. */
304+
DelayedFakeServer server() throws InterruptedException {
305+
waitFor(() -> !started.isEmpty());
306+
return (DelayedFakeServer) started.get(0);
307+
}
308+
}
309+
310+
/**
311+
* A fake server that finishes initializing only once told, as a process
312+
* that is slow to start does: until then, its process is still starting.
313+
*/
314+
private static final class DelayedFakeServer extends FakeServers.Server {
315+
316+
private final CompletableFuture<InitializeResult> initFuture =
317+
new CompletableFuture<>();
318+
319+
@Override
320+
public CompletableFuture<InitializeResult> initialize(
321+
final InitializeParams params)
322+
{
323+
return initFuture;
324+
}
325+
326+
/** Finishes the initialize request, as the fake server would have. */
327+
void finishInitializing() {
328+
initFuture.complete(super.initialize(null).join());
329+
}
330+
}
331+
211332
/**
212333
* Connects a client to a server, as an editor would.
213334
*

0 commit comments

Comments
 (0)