Skip to content

fix: send a language server the notifications queued before its stop ahead of its shutdown - #2099

Merged
lagergren merged 1 commit into
redhat-developer:mainfrom
lagergren:fix/send-the-queued-notifications-before-the-shutdown
Nov 22, 2026
Merged

lagergren merged 1 commit into
redhat-developer:mainfrom
lagergren:fix/send-the-queued-notifications-before-the-shutdown

Conversation

@lagergren

@lagergren lagergren commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

What

SelectedEditorConnectionTest.testATabThatClosesWhileItsSelectionWaitsForTheServerLeavesTheFileDisconnected fails now and then with "the closed file must end disconnected":

The server reads the file's didOpen and never its didClose, even after 10 s. #2019 had replaced a 2 s wait with 10 s waits, but the test kept failing, as no wait fixes it: it's a race in the stop of a language server, older than #2076 and #2096.

Cause

The file is the only document of its language server:

  1. When its tab's connection is released, the file is disconnected, and its didClose is queued on the dispatcher.
  2. The disconnection then stops the server: at once in tests, after lastDocumentDisconnectedTimeout otherwise.
  3. The stop sent shutdown and exit from a pooled thread without waiting for the dispatcher, then closed the connection.

When the dispatcher was a few milliseconds late, the didClose went out after the shutdown, which LSP forbids, and after the connection had closed, so the server never read it. A trace of a failing run under load showed it: shutdown sent, shutdown and exit read, connection closed, and only then the didClose dispatched.

Change

Before it sends shutdown, the stop of LanguageServerWrapper now waits until the dispatcher has handed the notifications queued before the stop to the message writer. So a server is told of the close of its last document before it is told to shut down.

  • It waits for a second at most, as it already does for the message writer before it closes the connection. After that, the stop goes on as before.
  • It doesn't wait when the project closes, which stops the server at once, as before.
  • A stop cancels the initialization of its server, so notifications held back until the server is initialized don't keep it waiting.

The failure message of the test now lists the didOpen and didClose notifications of the file that the server read.

Test

  • testTheServerReadsTheDidCloseOfItsLastFileBeforeItStops holds the dispatcher while the last tab of the server closes, and frees it 200 ms later. It fails without the change and passes with it.
  • Before the change, the flaky test failed once in 451 runs under CPU load. After it, the flaky test and the new test passed 400 times each under load, 100 of them on 2025.3, with no failure.
  • 22 related test classes, such as the document move, the stop and the notification order tests, passed 5 times (1,100 tests).
  • The full suite passed: 1,845 tests, 0 failures, 7 skipped.
  • It also fixes LanguageServerInstancesTest.testAMovedFileWhoseEditorClosesAsItIsAskedForAgainIsNotConnected, which failed on main at 30cb393 (2026-11-18, 2026.3) and on a fork run of fix: link the tab stops and placeholders of a snippet by their index, not by their text #2082 (2026-11-22, 2025.3), each after its full 10 s wait. It's the same race: the test's disconnection of the last document queues the didClose and stops the server, whose shutdown went out first. With the dispatcher held 200 ms before the didClose, that test fails 5 of 5 times without this change, and passes 5 of 5 times with it.

Not changed

SocketLanguageServerTest.testAStopSendsTheExitNotificationBeforeItClosesTheConnection also failed on macOS 3 times, all before #2064. It's a different cause, and not a lost exit: in each failure exit arrived, and then the editor that the test opened connected again after the stop and started the server again. #2064 fixed the test, and it hasn't failed in the 51 runs since.

…ahead of its shutdown

SelectedEditorConnectionTest.testATabThatClosesWhileItsSelectionWaitsForTheServerLeavesTheFileDisconnected
failed on CI with "the closed file must end disconnected" (2025.3 on 2026-11-19, macOS on 2026-11-22):
the server read the file's didOpen, and never its didClose.

The file is the server's last document. Its disconnection queues the didClose on the dispatcher and
then stops the server, at once in tests and after lastDocumentDisconnectedTimeout otherwise. The stop
sent shutdown and exit from a pooled thread without waiting for the dispatcher, then closed the
connection. When the dispatcher was a few milliseconds late, the didClose went out after the shutdown,
which LSP forbids, and after the connection closed, so the server never read it.

The stop now waits, for a second at most, until the dispatcher has handed the notifications queued
before it to the message writer, and only then sends the shutdown.

testTheServerReadsTheDidCloseOfItsLastFileBeforeItStops holds the dispatcher while the last file
closes: it fails without the change and passes with it.
@lagergren lagergren added this to the 0.30.2 milestone Nov 22, 2026
@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Improved language server shutdown handling so queued file notifications can be processed before shutdown, helping ensure files are properly disconnected when a server stops.
    • Improved reliability when closing a tab while its language server is still initializing.

Shutdown now waits briefly for the last queued notification on the current connection before starting server shutdown. Tests cover closing a tab during connection selection and closing the server’s last file while notification dispatch is blocked.

Changes: Server shutdown notification ordering

Layer / File(s) Summary
Capture and await queued notifications
src/main/java/com/redhat/devtools/lsp4ij/LanguageServerWrapper.java, src/test/java/com/redhat/devtools/lsp4ij/SelectedEditorConnectionTest.java
The wrapper passes the current connection’s last queued notification future to asynchronous shutdown and waits up to one second before starting the shutdown sequence. The tests check file disconnection and server stopping when notification dispatch is blocked, and report the file’s ordered open/close notifications on failure.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: angelozerr

Merge Risk: Minimal · up to fd984

This change makes server stop wait up to one second for the last queued document notification, such as didClose, before sending shutdown. That prevents the shutdown race described in the PR. No concrete defect was found, and the change looks safe to merge.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: LanguageServerWrapper now waits for queued notifications (such as didClose) to be dispatched before a stop sends shutdown. It is a fix and uses the conventional prefix…
Description check Passed The description explains the race, the cause, the change to LanguageServerWrapper stop, the bounded one-second wait, the test changes, and the verification. It directly matches the changeset and the r…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: LanguageServerWrapper now waits for queued notifications (such as didClose) to be dispatched before a stop sends shutdown. It is a fix and uses the conventional prefix. It is concise and specific.

Full details: Description check

Explanation

The description explains the race, the cause, the change to LanguageServerWrapper stop, the bounded one-second wait, the test changes, and the verification. It directly matches the changeset and the raw summary.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: caebaba4-afbc-4754-a7f4-a8e977e4a747
Commits

Reviewing files that changed from the base of the PR and between a82a94e and fd984ea.

Files selected for processing: 2

  • src/main/java/com/redhat/devtools/lsp4ij/LanguageServerWrapper.java
  • src/test/java/com/redhat/devtools/lsp4ij/SelectedEditorConnectionTest.java

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

@lagergren lagergren added the bug Something isn't working label Nov 22, 2026
@codecov

codecov Bot commented Nov 22, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 46.66667% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 50.40%. Comparing base (1b44654) to head (fd984ea).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
.../redhat/devtools/lsp4ij/LanguageServerWrapper.java 46.66% 7 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2099      +/-   ##
==========================================
+ Coverage   50.34%   50.40%   +0.05%     
==========================================
  Files         816      816              
  Lines       33785    33829      +44     
  Branches     6962     6963       +1     
==========================================
+ Hits        17008    17050      +42     
- Misses      14129    14138       +9     
+ Partials     2648     2641       -7     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lagergren

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@lagergren

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@lagergren

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@lagergren
lagergren merged commit cf01997 into redhat-developer:main Nov 22, 2026
11 checks passed
lagergren added a commit that referenced this pull request Nov 23, 2026
… as the cancel of its request (#2104)

## What

`ServerStopPendingWorkspaceSymbolTest.testARequestToAServerWhichStopsBeforeTheRequestIsKeptForTheStopIsCancelled` fails now and then:

    junit.framework.AssertionFailedError: The request must be cancelled, as no later stop of its server cancels it

It failed once on CI, on the `Test (ubuntu-latest, 2025.3)` job of a fork run of #2091, which changes neither workspace/symbol nor the stop. Under CPU load it fails in about 4 of 1000 runs.

**Verdict: the test is wrong; LSP4IJ isn't.** The test expected one of two correct endings of a cancelled request.

## Cause

The test sends `workspace/symbol` to a language server that never answers, stops the server, and calls `cancelOnStop`, which cancels the request because the server is no longer the current one. It then checked `request.isCancelled()`.

LSP4J's `JsonRpcRequestFuture.cancel` sends `$/cancelRequest` first, and cancels the future after:
- when LSP4J on the server side reads `$/cancelRequest`, it cancels the server's future and answers the request with a RequestCancelled error (-32800);
- if the client reads that answer between the two steps, the answer ends the request with a `ResponseErrorException`;
- the cancel then does nothing, and `isCancelled()` is false.

Usually the test thread is faster, or the stop closes the connection before the answer comes back.

A failing run under load, with temporary traces (ms from the call of `cancelOnStop`):

     +0.00  test thread    calls cancelOnStop
     +0.69  writer         writes $/cancelRequest for request 4
     +2.83  listener       reads the answer to 4: error -32800 "The request (id: 4, method: 'workspace/symbol') has been cancelled"
     +4.33  stop           closes the connection
     +4.88  test thread    returns from sending $/cancelRequest and cancels the future, too late
     +4.94  test thread    cancelOnStop returns: cancelled=false, done=true

LSP4IJ itself handles both endings. `CancellationSupport.execute` takes a RequestCancelled error as it takes a `CancellationException`: the request gives no result and shows no error. So the search ends with the symbols of the other language servers either way, which the other test of the class checks.

## Change

The test accepts both endings: the request is cancelled, or it ended with the RequestCancelled answer of the server, checked with `CancellationUtil.isRequestCancelledException`, as `CancellationSupport` does. A request that isn't done still fails the test. That's the case the test is for: a request kept for a stop that has already happened.

## Test

- **With a probe:** a temporary 300 ms delay in the test thread after it queues `$/cancelRequest`, with the mock server's shutdown held so the connection stays open. The server's answer then always comes first: 20 of 20 runs fail before the change, and 20 of 20 pass after.
- **Under load, without the probe:** 24 busy processes on 10 cores, the test repeated 1000 times in one JVM, before and after at the same time. 4 failures before, 0 after.
- **With #2085, #2095 and #2099 merged in:** the test file merges without conflicts, and the test passes 1000 of 1000 times under the same load.
- **Related classes:** `ServerStopPendingWorkspaceSymbolTest`, the other workspace/symbol tests and the stop tests (11 classes, 42 tests) pass on 2024.2 and 2025.3.
- **The full suite passes:** 1847 tests, 0 failures, 7 skipped (Windows-only and disabled tests).

## Found, not changed

The traces show the stop writing `$/cancelRequest` after `shutdown`. LSP allows only `exit` after `shutdown`.
- It happens for a late `cancelOnStop`, as here, and it can happen for `cancelPendingRequests()` in the `finally` of `stop()`, which runs after the shutdown has been submitted.
- #2099 doesn't cover it: `$/cancelRequest` goes through LSP4J's `RemoteEndpoint`, not LSP4IJ's notification dispatcher.
- A fix would end the requests of a stopped language server locally, without sending `$/cancelRequest`.

It has no effect that users see, and it doesn't cause this failure, so it would be a PR of its own.
lagergren added a commit that referenced this pull request Nov 23, 2026
…tdown request (#2105)

## What

A stopping language server was often sent `$/cancelRequest` after its `shutdown` request, which LSP forbids: only the `exit` notification may follow `shutdown`. On `main`, the new test sees the language server read `shutdown`, `$/cancelRequest`, `exit` on each of the four paths it covers. The investigation of the flaky test of #2104 found it.

## Cause

LSP4J sends `$/cancelRequest` when a request is cancelled. A stopping language server has its requests cancelled after `shutdown` in four ways:

- **The stop's own cancel:** the stop cancels the requests kept for it, as `workspace/symbol`, in the `finally` of `stop()`. That runs after it has started the shutdown on another thread, which usually sends `shutdown` first.
- **A late `cancelOnStop`:** it cancels at once a request that comes after the stop.
- **The file supports:** the stop disposes the supports of the files, which cancel their pending requests, as a hover, in a read action that runs later.
- **A feature:** a feature cancels its request while the language server shuts down, as when the user types on.

## Change

The messages of a connection are queued to the message writer under one lock, which notes when the `shutdown` request is queued. A `$/cancelRequest` queued after it is dropped, and not traced.
- The request still ends cancelled: LSP4J cancels its future once it has handed over the notification.
- A request cancelled before the `shutdown` request, as while the language server runs, still sends `$/cancelRequest`.

## Behaviour changes

- The LSP console no longer shows those dropped `$/cancelRequest` messages, as they're no longer sent.
- A request cancelled after `shutdown` now always ends with a `CancellationException`. Before, the language server's RequestCancelled answer could come first. LSP4IJ takes both as no result, so nothing else changes.

## Test

`CancelRequestAfterShutdownTest` records the messages that the mock language server reads, in order, and lets the server read everything sent before the connection closes. The shutdown answer is held, and a listener holds the stop's `$/cancelRequest` until the server has read `shutdown`, so the order is fixed without sleeps.

- **The four paths:** a request cancelled by a feature after `shutdown`, a late `cancelOnStop`, a request kept for the stop, and a hover ended by the stop. The language server reads nothing but `exit` after `shutdown`. On `main`, each fails 20 of 20 runs, with `expected:<[shutdown, exit]> but was:<[shutdown, $/cancelRequest, exit]>`. With the change, each passes 20 of 20.
- **The control:** a request cancelled while the language server runs still sends `$/cancelRequest`, which the server reads, and it cancels its request.
- **Under CPU load:** the stop, workspace/symbol, workspace diagnostics and tracing tests, repeated 10 times, pass (870 tests).
- **With #2085, #2099 and #2104 merged in:** the branches merge without conflicts, and the 17 related classes pass (117 tests).
- **The full suite passes:** 1853 tests, 0 failures, 7 skipped (Windows-only and disabled tests).

## Related

- **#2099** orders the notifications of the dispatcher, as a `didClose`, before `shutdown`. This change keeps cancels from going after it. They cover different messages, and cancels queued during #2099's wait still go out before `shutdown`.
- **#2104** is still needed: a cancel queued before `shutdown` can still be answered with RequestCancelled before its future is cancelled.
lagergren added a commit that referenced this pull request Nov 23, 2026
…own request (#2151)

Fixes #2145

## What

`CancelRequestAfterShutdownTest.testARequestCancelledOnceTheShutdownIsSentSendsNoCancelRequest` failed on main's CI at 1e40358 (run 45186700307, `Test (ubuntu-latest)`, IC 2024.2):

    The language server must read nothing but exit after shutdown expected:<[shutdown, exit]> but was:<[shutdown, textDocument/codeLens, exit]>

**Verdict: a bug in LSP4IJ, not only in the test.** LSP allows only the `exit` notification after `shutdown`. #2105 stopped `$/cancelRequest` from going out after `shutdown`, but any other request or notification that a feature sent then was still written. Here the request came from the code vision of the test's editor.

## Cause

The code vision of an editor gets the language servers of its file, then sends `textDocument/codeLens` from another thread (`thenComposeAsync` in `LSPCodeLensSupport`). If the language server stops between the two, the request is written after `shutdown`. The stop's disposal of the file supports doesn't prevent it: `codeLens(params)` is sent before `CancellationSupport.execute` sees that its support is cancelled. Such a request then stayed pending until the language server answered it, or something cancelled it.

The test doesn't switch code vision off, so the editor's background `textDocument/codeLens` can land in that window. That happens rarely: 300 runs under CPU load on macOS passed. With two temporary probes (a 1 s delay before the codeLens request, and a 2 s delay between `shutdown` and `exit`), main fails 10 of 10 with the CI message.

## Change

The messages of a connection were already queued to the message writer under one lock, which notes when `shutdown` is queued (#2105). After that, only `exit` and the responses to the language server's own requests are queued:
- **A request** ends at once with a `CancellationException`, the same way the requests of a stopped language server end. LSP4J completes a request's future with the exception that its send throws. It isn't traced or written.
- **A notification** is dropped and isn't traced, as `$/cancelRequest` already was.
- **Nothing queued before `shutdown` changes:** the writer keeps its order, and the notifications that #2099 sends ahead of `shutdown` are queued before it.

A message is checked before it's traced and again when it's queued. If `shutdown` is queued between the two checks, a message other than `$/cancelRequest` is traced but not written. Requests are still traced before they're queued, so that a request's trace stays ahead of its answer's.

## Behaviour change

A request sent to a language server after its `shutdown` request is now cancelled at once without being sent, and no notification other than `exit` is sent after `shutdown`. Before, the request was written, and it stayed pending until the language server answered it or something cancelled it. A notification was written too.

Callers see the same outcome as for the requests of a stopped language server: `CancellationSupport` takes the `CancellationException` as no result, and `awaitWithCheckCanceled` as a `ProcessCanceledException`. Nothing new is logged. No API changes.

## Test

`CancelRequestAfterShutdownTest` gets three tests. Each holds the shutdown answer so that the connection stays open after `shutdown`:
- **A request sent after `shutdown`** is cancelled at once, and the language server reads `shutdown`, `exit`. On main it fails: the request isn't cancelled, and it's written.
- **A notification sent after `shutdown`** isn't sent. On main it fails with `but was:<[shutdown, workspace/didChangeConfiguration, exit]>`.
- **The answer to a `workspace/configuration` request** that the language server sends after `shutdown` is still sent. This one passes on main and with the change.

Other runs:
- **#2105's tests** are unchanged and pass.
- **With the probes:** main fails 10 of 10 with `[shutdown, textDocument/codeLens, exit]`. With the change, 10 of 10 pass, and each run still sends its delayed codeLens request.
- **Under CPU load** (16 busy processes on 10 cores, without probes): the flaky test passes 300 of 300 runs, and the whole class 40 of 40 (320 tests), all in one JVM. Main passed 300 of 300 there too, so a loop alone doesn't reproduce the race on macOS.
- **Related classes** (`CancelRequestAfterShutdownTest`, `ServerStopPendingRequestsTest`, `ServerStopPendingWorkspaceSymbolTest`, `LanguageServerWrapperDisposeWhileStartingTest`, `LanguageServerWrapperRestartTest`, `SelectedEditorConnectionTest`, `LanguageServerInstancesTest`, `LanguageServerManagerInstancesTest`, `KeepAliveDuringPendingStopTest`, `EditorRefreshBatchTest`, `ServerStartFailureTest`, `SocketLanguageServerTest`, `LanguageServerDisposeFailureTest`, `RejectedLanguageServerTest`): 193 tests, 0 failures, 0 skipped on each of IC 2024.2, 2025.3 and IU 2026.3.
- **Full suite:** 2067 tests, 0 failures, 7 skipped (Windows-only and disabled tests), on IC 2024.2.
lagergren added a commit that referenced this pull request Nov 24, 2026
…rflowed, and retry a refused download for a minute (#2175)

## What

Main's last CI run, for 436b029, failed on Windows before any test ran:

```
Could not GET 'https://repo.maven.apache.org/maven2/org/jetbrains/kotlin/kotlin-gradle-plugins-bom/2.3.21/kotlin-gradle-plugins-bom-2.3.21.pom'.
> Received status code 429 from server: Too Many Requests
```

The job had no cache to start from: setup-gradle said "Gradle User Home cache not found. Will initialize empty.", so it
downloaded every dependency again.

**Why there was no cache:** the repository's Actions cache holds 12.2 GB, over GitHub's 10 GB per repository. Every
entry in it was saved in the 20 minutes before this PR, all on main. The biggest are `gradle-transforms` entries of 3.9,
3.3 and 0.9 GB. They are the IDEs that the IntelliJ Platform Gradle plugin extracts as Gradle artifact transforms, one
per job and platform version. Each push to main saves them again for the 5 test jobs, the plugin build and the
verifier. GitHub then evicts the oldest entries, the other jobs' downloads among them, and the next run of those jobs
fetches everything from Maven Central and JetBrains again.

## Change

- **The cache:** every `setup-gradle` step leaves `caches/transforms-4` and `caches/*/transforms` out of the Actions
  cache, with `gradle-home-cache-excludes`. setup-gradle deletes them before it saves. These are ci.yml, buildZip.yml,
  IJ.yml, IJ-latest.yml (3 steps), nightly.yml and release.yml.
  - The downloads themselves stay cached (`gradle-dependencies`, now 1.3 to 2 GB an entry), so the entries fit in
    10 GB, and Gradle extracts an IDE again from its cached download without a network access.
  - Locally the IDEs are in `caches/9.9.2/transforms/*/transformed/extracted`.
- **Retries:** Gradle 9.9.2 already retries a download refused with a server error or a 429
  (`NetworkingIssueVerifier`), but only 3 times, 1 and 2 seconds apart. `gradle.properties` raises that to 6 times, 2,
  4, 8, 16 and 32 seconds apart, with `systemProp.org.gradle.internal.network.retry.max.attempts` and `.initial.backOff`,
  which `NetworkOperationBackOffAndRetry` reads. A local build prints them back as 6 and 2000 from an init script.

## The other CI failures this week

I went through the 22 failed "Java CI with Gradle" runs since 2026-11-17:
- **6 were a real break**, fixed by #2138: `InstallerTaskRegistryInitializeTest` failed on every job after #2102.
- **Most of the rest were flaky tests, since fixed:**
  - `LanguageServerManagerInstancesTest` by #2120;
  - `CancelRequestAfterShutdownTest` by #2162;
  - `SocketLanguageServerTest` by #2064;
  - `SelectedEditorConnectionTest` and `FileDocumentMoveTest` by the fixes of #2099 and #2095.
- **Seen once and not fixed:** `WatchedFilesTest` (Windows, 2026-11-22) and `LanguageServerInstancesTest` (2026.3,
  2026-11-18).
- **Since 2026-11-23 14:00 UTC:** 36 runs passed, and the only failure was this 429.

## Check

A pull request reads the cache but doesn't write it, so this PR's own CI can't show the saving. After the merge, the
next run on main should leave the repository's cache under 10 GB, and the run after it should restore each job's entry.
I'll check both.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant