Skip to content

fix: 32 diagnostics or more with nested, equal or separate ranges no longer fail with "Comparison method violates its general contract!" - #2328

Merged
lagergren merged 2 commits into
redhat-developer:mainfrom
lagergren:fix/diagnostics-sort-contract
Nov 28, 2026

Conversation

@lagergren

@lagergren lagergren commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #2323

With 32 diagnostics or more whose ranges are nested, equal or separate, LSPDiagnosticsForServer.toMap failed with IllegalArgumentException: Comparison method violates its general contract!, as in the report. A diagnostic without a range made a list fail in the same way, with a NullPointerException. Two
commits, for a rebase merge, for 0.30.2. Both bugs are already in 0.30.1.

Behaviour change

Before After
A list of 32 diagnostics or more, published or pulled, whose ranges are nested, equal or separate, could fail with Comparison method violates its general contract!. Its diagnostics weren't shown: the file kept those it had before, or none, and the same list failed each time it came. All the diagnostics are shown. They are grouped for their quick fixes as before: a diagnostic joins the group of one whose range contains its own.
A diagnostic without a range, or without the start or the end of its range, or a null diagnostic, made the whole list of an opened file fail with a NullPointerException, so none of it was shown. A null diagnostic made the list of a closed file fail too, and an error without a range made a closed file a problem file in the Project view. Such a diagnostic is ignored, in an opened and a closed file, and the others of the list are shown. LSP requires a range, and LSP4IJ already ignores a diagnostic whose range doesn't fit the document when it shows it.

1. fix: the order of the diagnostics

Cause.
toMap sorts the diagnostics, then groups them by covered range: each diagnostic joins the first group whose range contains its own, and a group asks for its quick fixes once. The comparator returned -1 when the first range contained the second, and 1 otherwise. It never returned 0, so it wasn't an order:

  • a range came before itself;
  • of two equal ranges, each came before the other;
  • of two separate ranges, each came after the other.

TimSort checks the order only once it merges runs, from 32 elements on, hence the threshold in the report.

Fix. The diagnostics are sorted by the start of their range, and those with the same start the longest first (CONTAINING_RANGE_FIRST). It is a total order, and a range that contains another comes first, as the grouping needs: such a range starts no later, and with the same start ends no earlier.

The comparator proposed in the issue sorts by severity first, and of the same start the shortest range first. A contained diagnostic would then come before the one that contains it, and start a group of its own, so the two would ask for their quick fixes separately.

Tests.

Test Old comparator Fix
testManyDiagnosticsWithNestedOverlappingAndEqualRangesAreAllKept: update with 32 diagnostics whose ranges are nested, equal, overlapping, separate and empty fails: IllegalArgumentException: Comparison method violates its general contract! passes
testADiagnosticComesBeforeTheDiagnosticsWhoseRangeItsRangeContains: no diagnostic comes after one whose range contains its own, also for two diagnostics in either order fails with the same exception passes

The 32 ranges come from a throwaway search with java.util.Random: seed 10 is one of 3 among the first 35 seeds that broke the old comparator. For the run with the old comparator, the old lambda replaced CONTAINING_RANGE_FIRST.

2. fix: a diagnostic without a range

LSP requires a range for each diagnostic, but LSP4J's JSON parser accepts one without it, one whose range lacks its
start or end, and a null diagnostic in the list. Every report reaches LSPDiagnosticsForServer.update for an opened
file, or ClosedDocument.updateDiagnostics for a closed one, and both now drop such a diagnostic first, with
LSPDiagnosticUtils.withRange. A list whose diagnostics all have a range is used as it is.

Test Without the commit With it
LSPDiagnosticsForServerTest.testADiagnosticWithoutARangeIsIgnoredAndTheOthersAreKept: two diagnostics with ranges, an error without a range, a null and an error without the start of its range fails: NullPointerException: Cannot invoke "org.eclipse.lsp4j.Range.getStart()" because the return value of "org.eclipse.lsp4j.Diagnostic.getRange()" is null passes: the two are kept, the file has no error, and the same list again is no change
ClosedDocumentDiagnosticsTest.aDiagnosticWithoutARangeIsIgnoredAndTheOthersAreKept fails: NullPointerException, in List.copyOf passes
ClosedDocumentDiagnosticsTest.aReportWithOnlyDiagnosticsWithoutARangeRemovesTheDiagnosticsOfItsProvider fails: the error without a range is kept passes

Test runs

Headless, with the counts from the JUnit XMLs:

Classes IntelliJ Tests Failures
The 8 classes of features.diagnostics, ClosedDocumentDiagnosticsTest, ClosedDocumentProblemTest and LSPLazyCodeActionsTest IC 2024.2 102 0
The 8 classes of features.diagnostics, and LSPLazyCodeActionsTest, with the first commit IU 2026.3 90 0
LSPDiagnosticsForServerTest, ClosedDocumentDiagnosticsTest, ClosedDocumentProblemTest and LSPLazyCodeActionsTest IU 2026.3 23 0

The first CI run, of the first commit alone, failed LanguageServerProcessNodesTest.testADisposedLanguageServerExpiresItsCannotStartNotification
on Linux, a test of the LSP console that this PR doesn't touch. It races with the start that it makes fail; a fix of
the test follows in a PR of its own.

…longer fail with "Comparison method violates its general contract!"

The diagnostics of a file are grouped by covered range: each diagnostic joins the first group whose range contains its
own, so that the quick fixes of a group are asked for once. They were sorted first, so that a diagnostic comes before
those whose range its range contains, with a comparator that returned -1 when the first range contained the second, and
1 otherwise. That isn't an order: it never returned 0, so a range came before itself, two equal ranges each came before
the other, and two separate ranges each came after the other. TimSort finds that out once it merges runs, from 32
diagnostics on, and failed with "IllegalArgumentException: Comparison method violates its general contract!". The
diagnostics that the language server published weren't shown then: the file kept those it had before, or none, and the
same list failed each time it was published.

The diagnostics are now sorted by the start of their range, and those with the same start the longest first. That is a
total order, in which a range comes before the ranges that it contains, as the grouping needs.

The new test publishes 32 diagnostics whose ranges are nested, equal, overlapping, separate and empty. With the old
comparator, it fails with the exception of the report. A second test checks that no diagnostic comes after one whose
range contains its own.

Fixes redhat-developer#2323
@coderabbitai

coderabbitai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Diagnostics with overlapping or nested ranges are now ordered consistently, with containing ranges shown before the ranges they contain. Diagnostics with equal, disjoint, and empty ranges continue to be retained.
    • Diagnostics without a usable range are excluded from results. If a report contains only diagnostics without usable ranges, its previous results are cleared, and those entries do not cause the document to report errors.

Diagnostic updates filter out null diagnostics and diagnostics without complete ranges. The diagnostic comparator orders ranges by start position ascending, then end position descending. Tests cover filtering, cache clearing, error reporting, and ordering across varied ranges.

Changes: Diagnostic processing

Layer / File(s) Summary
Filter diagnostics without usable ranges
src/main/java/com/redhat/devtools/lsp4ij/features/diagnostics/LSPDiagnosticUtils.java, src/main/java/com/redhat/devtools/lsp4ij/ClosedDocument.java, src/main/java/com/redhat/devtools/lsp4ij/features/diagnostics/LSPDiagnosticsForServer.java, src/test/java/com/redhat/devtools/lsp4ij/ClosedDocumentDiagnosticsTest.java, src/test/java/com/redhat/devtools/lsp4ij/features/diagnostics/LSPDiagnosticsForServerTest.java
withRange retains only non-null diagnostics with non-null ranges, starts, and ends. Open and closed document updates use this filter. Tests check retention, cache clearing, and error reporting.
Order diagnostics by range position
src/main/java/com/redhat/devtools/lsp4ij/features/diagnostics/LSPDiagnosticsForServer.java, src/test/java/com/redhat/devtools/lsp4ij/features/diagnostics/LSPDiagnosticsForServerTest.java
The comparator orders start positions ascending and end positions descending. Tests check containment ordering and varied range relationships.

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

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: angelozerr, hgschmie

Merge Risk: Minimal · up to 8ee7f

This change stops diagnostic processing from crashing when many diagnostics have nested, overlapping, or identical ranges. It also ignores diagnostics that lack a usable range. The change is small, tested, and easy to revert, so merge risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the two fixes: the ordering failure with 32 or more diagnostics (nested, equal or separate ranges) and the 'Comparison method violates its general contract!' exception. The changeset m…
Description check Passed The description covers the changeset in detail. It explains the comparator cause and fix, the new withRange filtering for diagnostics without ranges in LSPDiagnosticsForServer and ClosedDocument, the …
Linked Issues check Passed [#2323] The issue requires that processing 32 or more diagnostics no longer throws Comparison method violates its general contract!, including nested, overlapping, and identical ranges. At head 8ee7…
Out of Scope Changes check Passed The whole-PR change touches LSPDiagnosticsForServer.java (comparator replacement and withRange filtering in update), LSPDiagnosticUtils.java (new withRange helper and its imports), `ClosedDo…
Full details: Title check

Explanation

The title names the two fixes: the ordering failure with 32 or more diagnostics (nested, equal or separate ranges) and the 'Comparison method violates its general contract!' exception. The changeset matches this: it replaces the range comparator in LSPDiagnosticsForServer and adds tests for it. The title omits the second fix (filtering diagnostics without a range), but that is secondary and the title does not claim otherwise.

Full details: Description check

Explanation

The description covers the changeset in detail. It explains the comparator cause and fix, the new withRange filtering for diagnostics without ranges in LSPDiagnosticsForServer and ClosedDocument, the related tests, and the test runs. It also links issue #2323.

Full details: Linked Issues check

Explanation

[#2323] The issue requires that processing 32 or more diagnostics no longer throws Comparison method violates its general contract!, including nested, overlapping, and identical ranges. At head 8ee7f17, LSPDiagnosticsForServer.CONTAINING_RANGE_FIRST compares range start ascending, then range end descending. Ties occur only for identical ranges, so the comparator is a total preorder and TimSort cannot report a contract violation. The grouping in toMap still works: a containing range starts no later and, with the same start, ends no earlier, so it sorts first and collects the diagnostics it contains. The issue lists nullable fields as edge cases. At head, update calls LSPDiagnosticUtils.withRange, which drops null diagnostics and diagnostics with a null range, start, or end before grouping. This closes the null-range gap noted in the previous review. ClosedDocument.updateDiagnostics applies the same filter, per the summary. The issue's comparator is illustrative, and the PR does not need to adopt it. The PR reports two new unit tests and headless runs with 0 failures. I verified the comparator and filter in source. I did not read the test files or the ClosedDocument source, because the whole-PR diff was unavailable and the ClosedDocument file read was not made.

Full details: Out of Scope Changes check

Explanation

The whole-PR change touches LSPDiagnosticsForServer.java (comparator replacement and withRange filtering in update), LSPDiagnosticUtils.java (new withRange helper and its imports), ClosedDocument.java (the same filter on the closed-document path, and a parameter rename from diagnostics to reported), and three test classes. The comparator and filter implement #2323. The closed-document filter follows the issue's nullable-field edge cases for the same diagnostic lists. The parameter rename is a minor, related edit inside the changed method. The test changes verify these behaviors. The rest of LSPDiagnosticUtils (problem reporting, clearing) is not in the summary's list of changes, so it is treated as pre-existing. I did not read the whole-PR diff or the ClosedDocument source directly, so this verdict rests on the summary and the head source for the two files read.

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: ac1f260a-7306-49c3-994a-145e27a626fb
Commits

Reviewing files that changed from the base of the PR and between f1a89ec and 8ee7f17.

Files selected for processing: 5

  • src/main/java/com/redhat/devtools/lsp4ij/ClosedDocument.java
  • src/main/java/com/redhat/devtools/lsp4ij/features/diagnostics/LSPDiagnosticUtils.java
  • src/main/java/com/redhat/devtools/lsp4ij/features/diagnostics/LSPDiagnosticsForServer.java
  • src/test/java/com/redhat/devtools/lsp4ij/ClosedDocumentDiagnosticsTest.java
  • src/test/java/com/redhat/devtools/lsp4ij/features/diagnostics/LSPDiagnosticsForServerTest.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 28, 2026
…ther diagnostics of its list

LSP requires a range for each diagnostic, but LSP4J's JSON parser accepts a diagnostic without one, or without the
start or the end of its range, and a null diagnostic in the list. Such a diagnostic made the grouping of the
diagnostics of an opened file fail with a NullPointerException, so none of the list was shown, as with redhat-developer#2323. A null
diagnostic made the cache of a closed file fail too, in List.copyOf, and an error without a range made a closed file a
problem file in the Project view.

Both now ignore such a diagnostic (LSPDiagnosticUtils.withRange), which can't be placed in the file, as LSP4IJ already
ignores a diagnostic whose range doesn't fit the document when it shows it. The others of the list are kept. A list
whose diagnostics all have a range is used as it is.

Refs redhat-developer#2323
@codecov

codecov Bot commented Nov 28, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.30769% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 58.62%. Comparing base (0c5aa98) to head (8ee7f17).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...sp4ij/features/diagnostics/LSPDiagnosticUtils.java 80.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2328      +/-   ##
==========================================
- Coverage   58.63%   58.62%   -0.01%     
==========================================
  Files         849      849              
  Lines       36704    36713       +9     
  Branches     7606     7608       +2     
==========================================
+ Hits        21520    21524       +4     
- Misses      12183    12185       +2     
- Partials     3001     3004       +3     

☔ 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 this to the 0.30.2 milestone Nov 28, 2026
@lagergren

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 28, 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 0fd429a into redhat-developer:main Nov 28, 2026
12 checks passed
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.

"IllegalArgumentException: Comparison method violates its general contract!" in LSPDiagnosticsForServer.toMap

1 participant