Skip to content

fix: keep a language server running while a move connects its last document again - #2095

Merged
lagergren merged 1 commit into
redhat-developer:mainfrom
lagergren:fix/keep-a-language-server-running-while-a-move-reconnects-its-document
Nov 22, 2026
Merged

lagergren merged 1 commit into
redhat-developer:mainfrom
lagergren:fix/keep-a-language-server-running-while-a-move-reconnects-its-document

Conversation

@lagergren

Copy link
Copy Markdown
Collaborator

What

FileDocumentMoveTest.testAMoveReconnectsTheFileOfALanguageServerWithoutFileOperations fails now and then on CI: on main at 36a8efe (run 45033794640) and on #2087 (run 45032590151, 2025.3). It waits 10 seconds for the moved file to be closed and opened again, and the didOpen at the new place never comes. It started after #2076.

Cause

A move disconnects the document of the moved file, which sends didClose, and connects it again once the write action is done. Until then, the language server has no document.

#2076 takes a lease on the language server until the server has been told of the move. With no document left, the end of that lease stops the server, and in unit-test mode the stop comes at once. So every move of an open file stopped the server and started it again. Traces showed the stop 0.3 ms after the move scheduled its reconnection, and the reconnection reaching the server about 21 ms later.

When the stop comes after the reconnection has taken the running server, but before it has registered the document, connectDocument drops the connection, and the file stays disconnected at its new place. Locally, code vision connected it again about 250 ms later, and restarted the server. On CI, nothing did within the 10 seconds.

Outside unit-test mode, the stop waits for lastDocumentDisconnectedTimeout, and the reconnection cancels it. The effect there is a stop timer set for nothing, and a restart if a document matcher takes longer than the timeout to answer.

Change

LSPFileListener.reconnectMovedDocument holds a keep-alive lease on the language server, from the moment that the move disconnects the document until the document is connected again, or it's clear that it won't be: closed, no longer matched, left out by the client features, a failed matcher, moved to another instance, or a connection that throws. Where it called stopIfIdle on its own server before, it now ends the lease. Ending the lease stops the server if it has no document left, so a server whose last document doesn't come back still stops, after it's told of the move, as #2076 intends.

FileDocumentMoveTest:

  • reconnectAfter checks that the move didn't stop the language server, and its timeout message says which notification is missing.
  • testALanguageServerKeepsRunningUntilTheMoveOfItsLastDocumentConnectsItAgain ends a lease while the reconnection of the moved document waits for its connection: the window that CI hit.

Test

  • Before the change: the new check fails in all 5 tests that use reconnectAfter, and the new test fails too. With the AbstractLSPFileListener from before fix: keep a language server running until it is told of the file operations that move its last document #2076, the 5 pass, and only the new test fails.
  • After the change:
    • FileDocumentMoveTest, DirectoryDocumentMoveTest, FileOperationEditSaveTest and FileOperationRefactoringTest passed 30 times on 2024.2 (990 tests) and 15 times on 2025.3 (495 tests), with 0 failures.
    • All the tests under com.redhat.devtools.lsp4ij pass: 1,845 tests, 0 failures, 0 errors, 7 skipped.

…cument again

FileDocumentMoveTest.testAMoveReconnectsTheFileOfALanguageServerWithoutFileOperations
has failed on CI since redhat-developer#2076: the moved file got no didOpen at its new place
within 10 seconds.

A move disconnects the document of the moved file and connects it again
after its write action. Until then the language server has no document. The
lease that redhat-developer#2076 takes until the server is told of the move ends in that
time, and its end stops the server, at once in unit-test mode. Locally, every
move test stopped the server and started it again. When the stop comes after
the reconnection has taken the running server, the reconnection is dropped
and the file is not connected at its new place.

The move now holds a lease of its own from the disconnection until the
document is connected again, or it is clear that it won't be. The server
stops after that if it has no document left.
@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 stability when documents are moved. Reconnection now handles files that close or move again during the process, while preventing the server from stopping unexpectedly during a move. Connection failures are also handled more reliably, helping keep document and server state consistent.

The moved-document reconnect flow now holds a language-server lease while it determines the document’s server and reconnects. It releases the lease on exit paths and handles stale connections when the document closes or moves again. Tests cover a queued reconnect and verify the server instance remains unchanged.

Changes: Moved-document reconnect

Layer / File(s) Summary
Lease ownership and server matching
src/main/java/com/redhat/devtools/lsp4ij/LSPFileListener.java
The listener acquires a lease before matching the moved document. It releases the lease on early exits, matcher errors, and when it selects a different server.
Reconnect completion and validation
src/main/java/com/redhat/devtools/lsp4ij/LSPFileListener.java, src/test/java/com/redhat/devtools/lsp4ij/FileDocumentMoveTest.java
The reconnect path releases the lease after connection attempts and handles documents that close or move during the attempt. The test covers a queued reconnect and checks that the server instance remains unchanged.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: d-biehl, angelozerr

Merge Risk: Minimal · up to 64b3f

This change keeps a language server alive while a moved document reconnects, which fixes an intermittent failure where the file stayed disconnected at its new location. No actionable merge-blocking risk was found. The remaining edge case, a matcher that never answers, depends on extension behavior and is minor.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: a language server is kept running while a move reconnects its last document. The raw summary shows a keep-alive lease added to LSPFileListener.reconnectMovedDocument, …
Description check Passed The description covers the failing test, the cause (a lease ending during the move gap stops the server before reconnection), the code change in LSPFileListener, the test updates, and the test results…
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: a language server is kept running while a move reconnects its last document. The raw summary shows a keep-alive lease added to LSPFileListener.reconnectMovedDocument, which matches the title. The fix prefix is accurate for a bug fix.

Full details: Description check

Explanation

The description covers the failing test, the cause (a lease ending during the move gap stops the server before reconnection), the code change in LSPFileListener, the test updates, and the test results. It relates directly to the changeset.

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: aebd1220-1ff2-4569-bdce-148d8c8b2f1d
Commits

Reviewing files that changed from the base of the PR and between 1b44654 and 64b3f4a.

Files selected for processing: 2

  • src/main/java/com/redhat/devtools/lsp4ij/LSPFileListener.java
  • src/test/java/com/redhat/devtools/lsp4ij/FileDocumentMoveTest.java

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

@codecov

codecov Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 60.00000% with 14 lines in your changes missing coverage. Please review.
✅ Project coverage is 50.36%. Comparing base (f680eb2) to head (64b3f4a).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
...va/com/redhat/devtools/lsp4ij/LSPFileListener.java 60.00% 9 Missing and 5 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2095      +/-   ##
==========================================
+ Coverage   50.33%   50.36%   +0.02%     
==========================================
  Files         816      816              
  Lines       33785    33794       +9     
  Branches     6962     6962              
==========================================
+ Hits        17006    17020      +14     
+ Misses      14130    14126       -4     
+ Partials     2649     2648       -1     

☔ 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 lagergren added the bug Something isn't working label Nov 22, 2026
@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 a158c02 into redhat-developer:main Nov 22, 2026
9 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 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