Skip to content

Commit 72d560d

Browse files
gselzerclaude
andcommitted
code-lsp: fail starts waiting on a shutdown
ServerProcesses.shutdown() stopped the starter with shutdownNow(), which drops queued starts without completing their futures, so whoever waited on them waited forever. Now it fails the starts not yet done at once, and asking for a process afterwards fails rather than throwing. A start that finishes anyway shuts its process down itself, and a start interrupted by the shutdown is not warned of. A failed start is noted before its future fails, so its users wait out the retry delay from the right time. The fake servers' process says it has no children, so destroying it does not throw, and the delayed fake server is shared by both tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 17b9a67 commit 72d560d

5 files changed

Lines changed: 176 additions & 67 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,8 @@ public void shutdown() {
253253

254254
/** Destroy the process and all of its descendants. */
255255
private static void destroy(final Process process) {
256-
// Destroy any children (some langauge servers are wrappers around other processes)
256+
// Destroy any children (some language servers are wrappers around other
257+
// processes).
257258
process.descendants().forEach(ProcessHandle::destroy);
258259
// Then destroy the given process.
259260
process.destroy();

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

Lines changed: 60 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@
3434
import java.util.List;
3535
import java.util.Map;
3636
import java.util.Optional;
37+
import java.util.concurrent.CancellationException;
3738
import java.util.concurrent.CompletableFuture;
38-
import java.util.concurrent.CompletionException;
3939
import java.util.concurrent.ExecutorService;
4040
import java.util.concurrent.Executors;
4141
import java.util.concurrent.ScheduledExecutorService;
@@ -90,6 +90,9 @@ final class ServerProcesses {
9090
/** Stops idle servers. */
9191
private final ScheduledExecutorService reaper;
9292

93+
/** Whether all servers were stopped, for good (see {@link #shutdown}). */
94+
private boolean shutdown;
95+
9396
/**
9497
* Servers stopped after ten minutes unused, four at most (or as the system
9598
* properties {@code scijava.lsp.idle}, in ms, and {@code scijava.lsp.max}
@@ -136,16 +139,21 @@ synchronized Slot slot(final Environment env) {
136139
return known != null ? known : new Slot(env);
137140
}
138141

139-
/** Stops all servers. */
142+
/** Stops all servers, for good: none are started after. */
140143
synchronized void shutdown() {
144+
shutdown = true;
141145
reaper.shutdownNow();
142-
for (final Slot slot : slots.values()) {
146+
// NB: A copy, as failing a start forgets its slot (see Slot.start).
147+
for (final Slot slot : new ArrayList<>(slots.values())) {
143148
final CompletableFuture<ServerProcess> s = slot.server;
144149
if (s == null) continue;
145-
// NB: Not via the starter, which stops next (dropping what it has not
146-
// begun): those started, now; those starting, once started.
150+
// NB: Those started, now. Those starting fail at once, as their waiters
151+
// must not wait on the starter, which stops next (dropping what it has
152+
// not begun); a start that finishes anyway shuts its process down
153+
// itself (see Slot.start).
147154
if (s.isDone()) s.thenAccept(ServerProcess::shutdown);
148-
else s.thenAcceptAsync(ServerProcess::shutdown);
155+
else s.completeExceptionally(new CancellationException(
156+
"Shutting down all servers"));
149157
slot.server = null;
150158
}
151159
slots.clear();
@@ -220,10 +228,16 @@ private Slot(final Environment env) {
220228
/**
221229
* Gets the process, starting it if needed. Never blocks.
222230
*
223-
* @return The process, once started; fails if it could not be.
231+
* @return The process, once started; fails if it could not be, or if all
232+
* servers were shut down.
224233
*/
225234
CompletableFuture<ServerProcess> process() {
226235
synchronized (ServerProcesses.this) {
236+
// NB: Shut down? Then no starter to start one, nor slots to keep it.
237+
if (shutdown) {
238+
return CompletableFuture.failedFuture(new CancellationException(
239+
"All servers were shut down"));
240+
}
227241
// NB: Replaced while this one had no process? Ask that one.
228242
final Slot known = slots.get(env);
229243
if (known != null && known != this) return known.process();
@@ -256,30 +270,52 @@ private void stop() {
256270

257271
private void start() {
258272
failed = -1;
259-
final CompletableFuture<ServerProcess> s = CompletableFuture
260-
.supplyAsync(() -> {
261-
try {
262-
log.debug("Starting " + launcher.language() +
263-
" language server for " + env);
264-
return ServerProcess.start(launcher, env, log, INIT_TIMEOUT);
273+
final CompletableFuture<ServerProcess> s = new CompletableFuture<>();
274+
server = s;
275+
starter.execute(() -> {
276+
try {
277+
log.debug("Starting " + launcher.language() +
278+
" language server for " + env);
279+
final ServerProcess p = ServerProcess.start(launcher, env, log,
280+
INIT_TIMEOUT);
281+
if (!s.complete(p)) {
282+
// Already failed by a shutdown, so no one else will stop it.
283+
p.shutdown();
265284
}
266-
catch (final Exception exc) {
285+
}
286+
catch (final Throwable t) {
287+
if (noteFailure(s)) {
288+
// Could not start (e.g. the process failed, or did not
289+
// initialize in time): say so (it waits before trying again).
290+
s.completeExceptionally(t);
267291
log.warn("Could not start " + launcher.language() +
268-
" language server for " + env, exc);
269-
throw new CompletionException(exc);
292+
" language server for " + env, t);
270293
}
271-
}, starter);
272-
// NB: Before the callback, which runs at once if the start failed.
273-
server = s;
274-
s.whenComplete((started, error) -> {
275-
if (error == null) return;
276-
synchronized (ServerProcesses.this) {
277-
if (server != s) return;
294+
else {
295+
// NB: Interrupted by a shutdown, which failed it already:
296+
// nothing to warn of, nor note (its slot is gone).
297+
}
298+
}
299+
});
300+
}
301+
302+
/**
303+
* Notes that the given start failed, before its users can see it (lest
304+
* they ask again too soon), unless replaced since.
305+
*
306+
* @return Whether it failed by itself; false if a shutdown failed it
307+
* first.
308+
*/
309+
private boolean noteFailure(final CompletableFuture<ServerProcess> s) {
310+
synchronized (ServerProcesses.this) {
311+
if (s.isDone()) return false;
312+
if (server == s) {
278313
failed = clock.getAsLong();
279314
// NB: Holds no process. Its users still wait out RETRY_DELAY.
280315
slots.remove(env, this);
281316
}
282-
});
317+
return true;
318+
}
283319
}
284320

285321
/** The process, if started (successfully); null otherwise. */

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

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
import java.util.concurrent.CompletableFuture;
4343
import java.util.concurrent.CopyOnWriteArrayList;
4444
import java.util.concurrent.TimeUnit;
45+
import java.util.stream.Stream;
4546

4647
import org.eclipse.lsp4j.CompletionItem;
4748
import org.eclipse.lsp4j.CompletionItemKind;
@@ -167,6 +168,13 @@ public int waitFor() throws InterruptedException {
167168
return 0;
168169
}
169170

171+
@Override
172+
public Stream<ProcessHandle> descendants() {
173+
// NB: Not a process of the operating system, so none of its
174+
// own (where the default would throw).
175+
return Stream.empty();
176+
}
177+
170178
@Override
171179
public void destroy() {
172180
server.alive = false;
@@ -329,4 +337,46 @@ private static CompletionItem item(final String label,
329337
return item;
330338
}
331339
}
340+
341+
/** Starts fake servers that finish initializing only once told. */
342+
static final class DelayingLauncher extends Launcher {
343+
344+
@Override
345+
Server newServer() {
346+
return new DelayedFakeServer();
347+
}
348+
349+
/**
350+
* Waits until the first server has started: created, but (until told)
351+
* not yet initialized, so its process is still starting.
352+
*
353+
* @return That server.
354+
*/
355+
DelayedFakeServer awaitStart() throws InterruptedException {
356+
waitFor(() -> !started.isEmpty());
357+
return (DelayedFakeServer) started.get(0);
358+
}
359+
}
360+
361+
/**
362+
* A fake server that finishes initializing only once told, as a process
363+
* that is slow to start does: until then, its process is still starting.
364+
*/
365+
static final class DelayedFakeServer extends Server {
366+
367+
private final CompletableFuture<InitializeResult> initFuture =
368+
new CompletableFuture<>();
369+
370+
@Override
371+
public CompletableFuture<InitializeResult> initialize(
372+
final InitializeParams params)
373+
{
374+
return initFuture;
375+
}
376+
377+
/** Finishes the initialize request, as the fake server would have. */
378+
void finishInitializing() {
379+
initFuture.complete(super.initialize(null).join());
380+
}
381+
}
332382
}

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

Lines changed: 6 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@
5050
import org.eclipse.lsp4j.DidChangeTextDocumentParams;
5151
import org.eclipse.lsp4j.DidCloseTextDocumentParams;
5252
import org.eclipse.lsp4j.InitializeParams;
53-
import org.eclipse.lsp4j.InitializeResult;
5453
import org.eclipse.lsp4j.MessageActionItem;
5554
import org.eclipse.lsp4j.MessageParams;
5655
import org.eclipse.lsp4j.Position;
@@ -218,7 +217,8 @@ public Process start(final Environment env) throws IOException {
218217
*/
219218
@Test
220219
public void testClosedDuringStartup() throws Exception {
221-
final DelayingLauncher launcher = new DelayingLauncher();
220+
final FakeServers.DelayingLauncher launcher =
221+
new FakeServers.DelayingLauncher();
222222
final ServerProcesses delayed = servers(launcher);
223223
try {
224224
final ProcessLanguageServer s = (ProcessLanguageServer) delayed.server(
@@ -228,7 +228,7 @@ public void testClosedDuringStartup() throws Exception {
228228
// Asked while the process starts...
229229
final CompletableFuture<?> answer = s.completion(new CompletionParams(
230230
new TextDocumentIdentifier(uri), new Position(0, 1)));
231-
final DelayedFakeServer late = launcher.server();
231+
final FakeServers.DelayedFakeServer late = launcher.awaitStart();
232232
// ...then closed, before it has finished starting.
233233
s.didClose(new DidCloseTextDocumentParams(new TextDocumentIdentifier(
234234
uri)));
@@ -249,7 +249,8 @@ public void testClosedDuringStartup() throws Exception {
249249
*/
250250
@Test
251251
public void testChangedDuringStartup() throws Exception {
252-
final DelayingLauncher launcher = new DelayingLauncher();
252+
final FakeServers.DelayingLauncher launcher =
253+
new FakeServers.DelayingLauncher();
253254
final ServerProcesses delayed = servers(launcher);
254255
try {
255256
final ProcessLanguageServer s = (ProcessLanguageServer) delayed.server(
@@ -258,7 +259,7 @@ public void testChangedDuringStartup() throws Exception {
258259
final String uri = "untitled:/l.py";
259260
open(s, uri, "old");
260261
// Version 1's diagnosis waits for the process to start...
261-
final DelayedFakeServer late = launcher.server();
262+
final FakeServers.DelayedFakeServer late = launcher.awaitStart();
262263
s.didChange(new DidChangeTextDocumentParams(
263264
new VersionedTextDocumentIdentifier(uri, 2), Collections.singletonList(
264265
new TextDocumentContentChangeEvent("new"))));
@@ -292,43 +293,6 @@ private static ServerProcesses servers(final FakeServers.Launcher launcher) {
292293
System::currentTimeMillis);
293294
}
294295

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-
332296
/**
333297
* Connects a client to a server, as an editor would.
334298
*

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

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import static org.junit.jupiter.api.Assertions.assertNotSame;
3535
import static org.junit.jupiter.api.Assertions.assertSame;
3636
import static org.junit.jupiter.api.Assertions.assertThrows;
37+
import static org.junit.jupiter.api.Assertions.assertTrue;
3738
import static org.scijava.code.lsp.server.FakeServers.ENV;
3839
import static org.scijava.code.lsp.server.FakeServers.waitFor;
3940

@@ -42,6 +43,7 @@
4243
import java.util.Collections;
4344
import java.util.List;
4445
import java.util.Optional;
46+
import java.util.concurrent.CancellationException;
4547
import java.util.concurrent.CompletableFuture;
4648
import java.util.concurrent.ExecutionException;
4749
import java.util.concurrent.TimeUnit;
@@ -212,6 +214,62 @@ public void testTooMany() throws Exception {
212214
assertSame(first, a.running().get());
213215
}
214216

217+
/**
218+
* Tests that shutting down fails, at once, the processes still starting,
219+
* and those waiting to start: rather than leaving their users waiting.
220+
*/
221+
@Test
222+
public void testShutdownFailsStarting() throws Exception {
223+
final FakeServers.DelayingLauncher delaying =
224+
new FakeServers.DelayingLauncher();
225+
final ServerProcesses processes = new ServerProcesses(delaying,
226+
new StderrLogService(), 60_000, 2, now::get);
227+
// One process starts. Once it is starting, it won't finish (since we
228+
// never call DelayedFakeServer.finishInitializing), which means...
229+
final CompletableFuture<ServerProcess> starting = processes.slot(ENV)
230+
.process();
231+
delaying.awaitStart();
232+
// ...starting a second will wait its turn.
233+
final CompletableFuture<ServerProcess> waiting = processes.slot(ENV
234+
.withPaths(Collections.singletonList("/b"))).process();
235+
// Now shut down all processes.
236+
processes.shutdown();
237+
// Both should fail, at once.
238+
assertThrows(CancellationException.class, () -> waiting.getNow(null));
239+
assertThrows(CancellationException.class, () -> starting.getNow(null));
240+
// NB: The one waiting was never started at all.
241+
assertEquals(1, delaying.started.size());
242+
}
243+
244+
/**
245+
* Tests that shutting down stops a process still starting, rather than
246+
* leaving it running.
247+
*/
248+
@Test
249+
public void testShutdownStopsStarting() throws Exception {
250+
final FakeServers.DelayingLauncher delaying =
251+
new FakeServers.DelayingLauncher();
252+
final ServerProcesses delayed = new ServerProcesses(delaying,
253+
new StderrLogService(), 60_000, 2, now::get);
254+
delayed.slot(ENV).process();
255+
final FakeServers.DelayedFakeServer late = delaying.awaitStart();
256+
delayed.shutdown();
257+
// NB: Stopped while it waits to be initialized, by the interruption of
258+
// its start; or, should it finish starting anyway, once it has.
259+
late.finishInitializing();
260+
waitFor(() -> !late.alive);
261+
}
262+
263+
/** Tests that once shut down, no process is started: asking fails. */
264+
@Test
265+
public void testNoneAfterShutdown() throws Exception {
266+
final ServerProcesses.Slot slot = servers.slot(ENV);
267+
servers.shutdown();
268+
assertThrows(CancellationException.class, () -> slot.process().getNow(
269+
null));
270+
assertTrue(started.isEmpty());
271+
}
272+
215273
/**
216274
* Tests that a process that fails to initialize is stopped, and that
217275
* any children it started are stopped as well.

0 commit comments

Comments
 (0)