Skip to content

fix: keep a language server running until it is told of the file operations that move its last document - #2076

Merged
lagergren merged 1 commit into
redhat-developer:mainfrom
lagergren:fix/keep-a-language-server-running-until-it-is-told-of-its-file-operations
Nov 21, 2026
Merged

lagergren merged 1 commit into
redhat-developer:mainfrom
lagergren:fix/keep-a-language-server-running-until-it-is-told-of-its-file-operations

Conversation

@lagergren

Copy link
Copy Markdown
Collaborator

What

FileOperationEditSaveTest.testTheServerIsToldOfTheRenameAfterTheSave failed on the 2025.3 job of #2075 (run 44941700678, attempt 1). It waited 60 seconds for workspace/didRenameFiles, which never came. It had failed before, on 2026-11-12, when #1984 raised its wait from 10 to 60 seconds.

Cause

The test renames the only document of its language server, and that document has no editor. Two things happen after the rename, and they race:

  • The notification: AbstractLSPFileListener first saves the documents that the willRenameFiles edit changed, in an invokeLater, and only then sends didRenameFiles.
  • The stop: LSPFileListener checks in the background whether the moved document is open at its new place. It has no editor there, so it isn't connected again. stopIfIdle then stops the language server, which has no document left. In unit-test mode the stop comes at once; otherwise it comes after lastDocumentDisconnectedTimeout.

When the stop wins, sending didRenameFiles starts the language server again. A probe that held the UI thread for 3 seconds after the rename showed it: the server stopped at 3187 ms, didRenameFiles arrived at 3210 ms, and the server was started again at 3213 ms. In the failed CI run, the stop's shutdown timed out during the test (Timeout error while shutdown the language server 'mock-server-id'), and didRenameFiles never arrived.

Fix

afterVfsChange takes a keep-alive lease (LanguageServerItem.keepAlive()) on the language server. It releases the lease once the last did* notification of the file operations has been sent; the notifications are sent in order, so the last one goes after the others. The release runs off the dispatcher thread, because it can stop the language server.

So when a file operation moves a language server's last document, the server now stops after it's told of the operation, not before, and it isn't started again just to be told.

Test

FileOperationEditSaveTest.testTheServerIsToldOfTheRenameOfItsLastDocumentBeforeItStops holds the UI thread for 500 ms after the rename, so that the stop would win. It then checks that the server had one connection when it was told of the rename. Without the fix it had two, because it had been started again.

All file-operation, file-move and keep-alive tests pass (118), and so does the full suite (1,808 tests, 0 failures, 7 skipped).

@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • File rename notifications are now delivered before the associated language server shuts down when its last connected document is renamed. This helps ensure the server receives the rename event and can respond appropriately, avoiding a race between sending the notification and ending the server connection.

The file listener now returns futures for file-operation notifications and holds a language-server lease until the final notification completes. A test checks that the server connection remains active during a rename notification.

Changes: File notification lifecycle

Layer / File(s) Summary
Notification futures and lease lifecycle
src/main/java/com/redhat/devtools/lsp4ij/features/files/AbstractLSPFileListener.java, src/test/java/com/redhat/devtools/lsp4ij/FileOperationEditSaveTest.java
The listener returns futures for create, delete, rename, and watched-file notifications. It releases the language-server lease when the final notification future completes, including when notifications follow document saves. The new test checks the connection count during a rename notification.

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

Change: Bug fix

Suggested reviewers: angelozerr

Merge Risk: Minimal · up to 8fe7b

This change keeps the language server running until it has been told about the rename or move of its last document, so the server no longer stops and restarts just to receive that notification. No concrete merge-blocking defect was found, and the author reports the file-operation, file-move, keep-alive and full test suites passing.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title states the main change: a language server is kept running until it is notified of the file operations that move its last document. The changeset adds a keep-alive lease in AbstractLSPFileLis…
Description check Passed The description explains the failing test, the race between saving documents and stopping an idle language server, the fix that takes a LanguageServerItem.keepAlive() lease in afterVfsChange, and the …
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 states the main change: a language server is kept running until it is notified of the file operations that move its last document. The changeset adds a keep-alive lease in AbstractLSPFileListener and a test for this behavior. The title is specific and matches the change. It is 103 characters, slightly long, but this does not make it unclear.

Full details: Description check

Explanation

The description explains the failing test, the race between saving documents and stopping an idle language server, the fix that takes a LanguageServerItem.keepAlive() lease in afterVfsChange, and the new test testTheServerIsToldOfTheRenameOfItsLastDocumentBeforeItStops. This matches 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: 0b0212fb-7a4c-4cf2-a7f1-050ed4e92ba0
Commits

Reviewing files that changed from the base of the PR and between 1ca4edb and 8fe7b90.

Files selected for processing: 2

  • src/main/java/com/redhat/devtools/lsp4ij/features/files/AbstractLSPFileListener.java
  • src/test/java/com/redhat/devtools/lsp4ij/FileOperationEditSaveTest.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.

@codecov

codecov Bot commented Nov 21, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 57.14286% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 50.17%. Comparing base (1ca4edb) to head (8fe7b90).

Files with missing lines Patch % Lines
...lsp4ij/features/files/AbstractLSPFileListener.java 57.14% 9 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2076      +/-   ##
==========================================
- Coverage   50.19%   50.17%   -0.03%     
==========================================
  Files         814      814              
  Lines       33590    33595       +5     
  Branches     6914     5244    -1670     
==========================================
- Hits        16861    16856       -5     
- Misses      14088    14094       +6     
- Partials     2641     2645       +4     

☔ 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 21, 2026 •

Copy link
Copy Markdown
Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

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 added this to the 0.30.2 milestone Nov 21, 2026
@lagergren
lagergren merged commit fec9c4f into redhat-developer:main Nov 21, 2026
9 checks passed
@lagergren lagergren added the bug Something isn't working label Nov 22, 2026
lagergren added a commit that referenced this pull request Nov 22, 2026
…cument again (#2095)

## 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 #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.
lagergren added a commit that referenced this pull request Nov 22, 2026
…ahead of its shutdown (#2099)

## What

`SelectedEditorConnectionTest.testATabThatClosesWhileItsSelectionWaitsForTheServerLeavesTheFileDisconnected` fails now and then with "the closed file must end disconnected":
- on 2025.3 on 2026-11-19;
- on macOS in [run 45039702394](https://github.com/redhat-developer/lsp4ij/actions/runs/45039702394) of #2096 on 2026-11-22.

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 #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.
lagergren added a commit that referenced this pull request Nov 23, 2026
… its open documents again (#2119)

Fixes #2133

#2128, whose fix `testTheReconnectionOfARestartEndsWhenTheRestartIsStopped` needs to be stable, is merged, and so is `main` into this branch (3336fea): the 10 related classes pass on it (189 tests).

## What

`WatchedFilesTest.testTheWatchersOfAStoppedServerAreDropped` failed on `main` on Windows ([run 45057940746](https://github.com/redhat-developer/lsp4ij/actions/runs/45057940746)). Right after `restart()`, `getLanguageServers()` returned no language server for the open file.

**Verdict: a real bug in LSP4IJ, not in the test.** The end of a keep-alive lease stopped the restarted server while it was still starting.

## Cause

Since #2076, a file operation keeps its language server alive with a lease until the server is told of it:
1. The test creates a file just before the restart, so that lease ended after the restart had begun.
2. The restart's stop disconnects the open documents, and the restarted server connects them again only once it has initialized, so it had none yet.
3. The end of the lease found nothing keeping it alive, and stopped it. That cancelled its start, and the request waiting for it got nothing.

A trace of a failure under load:

```
133.585ms [EDT]      restart begin
134.789ms [EDT]      start NEW ATTEMPT                    (restart)
142.027ms [FJ]       getLanguageServers matched … status=starting   (the test's connect)
142.291ms [pooled 4] stop … status=starting
      at maybeShutdown ← decrementKeepAlive ← LanguageServerItem$1.dispose ← AbstractLSPFileListener.sendThenRelease
142.347ms            initialized server=null error=CancellationException
```

In tests the stop is immediate. In the IDE it comes after `lastDocumentDisconnectedTimeout` (5 s by default), so it stops a restarted server that takes longer than that to initialize.

## Change

- A restart holds off the stops for idleness from before its stop until the open documents are connected again, or until its start fails or is stopped. A start that connects again the documents of a connection that ended does so too.
- A stop asked for meanwhile, as by the end of a lease, is then decided: the server stops only if nothing keeps it alive by then. A restarted server that no stop was asked for keeps running, as before, so a server that `LanguageServerManager.start()` or the console's Restart starts without an open document isn't stopped.
- Leases are counted as before, once for the language server, whatever connection they were taken on. That's the contract of the public `LanguageServerItem.keepAlive()`: a lease is a demand on the server as an open document is, and an open document keeps a restarted server running. `LanguageServerItem` doesn't change.
- The hold of a start that connects the documents of an ended connection again also ends when a stop replaces that start (d4efe26). The stop cancels `initializeFuture`, which then runs neither the reconnection nor the failure handler, so later stops for idleness would have waited forever. That hold exists only in this PR, so this changes nothing against `main`.
- `LanguageServiceAccessor.sendDidOpenAndRefreshEditorFeatureForOpenedFiles` (package-private) returns a future that completes once each open file is connected, or its connection failed or was cancelled.

The first commit of this PR tied the end of a lease to the connection it was taken on. The second one replaces that, after CodeRabbit's review: it broke the lease contract, and left a restarted server running after its last lease ended when a lease from before the restart outlived one taken after it.

## Behaviour change

A lease that ends, or another reason to stop for idleness that comes, while a language server restarts no longer stops it before it has connected its open documents again. Nothing else changes for users or plugins.

## Test

`KeepAliveDuringPendingStopTest`:

| Test | Checks |
|---|---|
| `testALeaseThatEndsAsTheServerRestartsLetsItStartBeforeItStops` | The flaky test's order: the request made during the restart isn't ended by the end of the lease, and the server starts before the deferred stop for idleness stops it, as it has no document. Fails on `main`. Since 769eb34 it no longer asserts which server the request gets: in unit-test mode the deferred stop comes at once and can come before the request reads the server, which failed it on CI twice. |
| `testALeaseHeldAcrossARestartKeepsTheRestartedServerRunningUntilItEnds` | CodeRabbit's order: the end of a lease taken after the restart doesn't stop the server while one from before is held; the end of that one does. |
| `testALeaseTakenAfterARestartStopsTheServerWithoutDocumentWhenItEnds` | A lease on the restarted server still stops it when it ends. |
| `testALeaseTakenBeforeTheServerStartsKeepsItRunningAndStopsItWhenItEnds` | A lease from before the first start. |
| `testARestartedServerWithoutDocumentOrLeaseKeepsRunning` | As on `main`. |
| `testTheReconnectionOfARestartEndsWhenItsStartFails`, `…WhenTheRestartIsStopped` | The hold ends when the restart's start fails or is stopped. |
| `testTheReconnectionOfAStartForAnEndedConnectionEndsWhenTheStartIsStopped` | The hold of a start that connects an ended connection's documents again ends when a stop replaces it. Fails before d4efe26. |

- **With a probe** that delays the lease's release 100 ms and the restarted start 300 ms, `WatchedFilesTest` fails 5 of 5 runs on `main` and passes 5 of 5 with the change.
- **10 related classes** (187 tests after d4efe26: the keep-alive, watched files, move, file operation, restart and instance tests) pass on 2024.2, 2025.3 and IU 2026.3, and also merged with today's `main`.
- **The full suite passes:** 1866 tests, 0 failures, 7 skipped.
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