Skip to content

fix(diagnostics): сбрасывать Lazy-кэш диагностик до workspace/diagnostic/refresh#4139

Merged
nixel2007 merged 1 commit into
developfrom
fix/diagnostic-refresh-clears-cache
Jun 17, 2026
Merged

fix(diagnostics): сбрасывать Lazy-кэш диагностик до workspace/diagnostic/refresh#4139
nixel2007 merged 1 commit into
developfrom
fix/diagnostic-refresh-clears-cache

Conversation

@sfaqer

@sfaqer sfaqer commented Jun 16, 2026

Copy link
Copy Markdown
Member

Summary

После наполнения контекста сервера (ServerContextPopulatedEvent) межфайловые диагностики открытых документов (UnusedLocalMethod, EventHandler*, обращения к общим модулям и т.п.) могут устареть, поэтому мы шлём pull-клиенту (VSCode 1.94+ с refreshSupport) запрос workspace/diagnostic/refresh. Однако в pull-ветке мы не сбрасывали Lazy<List<Diagnostic>>-кэш в DocumentContext. Клиент перезапрашивал через textDocument/diagnosticDiagnosticProvider.getDiagnostic(...)documentContext.getDiagnostics()Lazy.getOrCompute() возвращал закэшированное значение, посчитанное до наполнения контекста.

Симптом: диагностики «висят» в редакторе до переоткрытия файла (didOpenrebuildDocument сбрасывает кэш). Раньше работало, потому что push-ветка чистила кэш — но для pull-клиента она не выполняется.

clearDiagnostics() теперь вызывается до выбора ветки — кэш сбрасывается одинаково для pull- и push-клиента, refresh уходит уже после.

Test plan

  • Новый кейс DiagnosticProviderTest.testServerContextPopulatedClearsCachedDiagnosticsForPullClient — проверяет что при pull-клиенте перед refreshDiagnostics() зовётся clearDiagnostics() на каждом открытом документе.
  • Существующие кейсы testServerContextPopulatedRequestsRefreshWhenClientSupportsRefresh / testServerContextPopulatedDoesNotRequestRefreshWhenClientDoesNotSupportRefresh остаются зелёными.
  • Ручная проверка в VSCode 1.94+ на 1С-проекте — открыть .bsl-файл во время индексации, дождаться завершения populateContext: диагностики переактуализируются без необходимости переоткрывать файл.

Summary by CodeRabbit

  • Bug Fixes
    • Improved diagnostic refresh behavior for open documents—cached diagnostics are now consistently cleared before refresh operations are initiated, ensuring accurate and timely code analysis updates.

…tic/refresh

Pull-клиент (VSCode 1.94+) объявляет refreshSupport, мы шлём ему
workspace/diagnostic/refresh, но не чистим Lazy<List<Diagnostic>>-кэш в
DocumentContext. Клиент честно перезапрашивает textDocument/diagnostic,
а получает закэшированное значение, посчитанное до наполнения контекста
(межфайловые диагностики UnusedLocalMethod / EventHandler*, обращения к
общим модулям и т.п. — все «висят» до переоткрытия файла).

clearDiagnostics() теперь вызывается до выбора ветки — и для pull-, и для
push-клиента. Lazy кэш сбрасывается, следующий getDiagnostics() пересчитает
с актуальным реестром типов и индексом.
@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

DiagnosticProvider.refreshDiagnostics(ServerContext) is updated to clear cached diagnostics for all opened documents unconditionally at the method's start, before branching on pull vs. push refresh paths. The pull path gains debug logging with the cleared document count. A new test verifies this behavior for pull-capable clients.

Changes

Diagnostic Cache Clear Refactor

Layer / File(s) Summary
Unconditional cache clear in refreshDiagnostics
src/main/java/.../providers/DiagnosticProvider.java
Cache clearing for opened documents is moved outside the push-only branch so it runs before both the pull-refresh (workspace/diagnostic/refresh) and push recomputation paths. The pull path also gains a debug log statement with the count of cleared documents.
New pull-client cache-clear test
src/test/java/.../providers/DiagnosticProviderTest.java
Adds testServerContextPopulatedClearsCachedDiagnosticsForPullClient, which stubs two opened DocumentContext instances, enables refresh support, connects a mock LanguageClient, and asserts clearDiagnostics() is called once per document and refreshDiagnostics() is called once on the client.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • 1c-syntax/bsl-language-server#4057: Modifies the same DiagnosticProvider.refreshDiagnostics() method to trigger workspace/diagnostic/refresh after context initialization based on client support, directly adjacent to the logic changed here.

Poem

🐰 Hop, hop, clear the stash,
Before the refresh makes a dash!
Pull or push, the cache goes first,
No stale diagnostics to burst.
The burrow's tidy, tests pass too —
A cleaner server, through and through! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: clearing the Lazy diagnostics cache before workspace/diagnostic/refresh requests, which is the core fix addressing the caching issue described in the PR objectives.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/diagnostic-refresh-clears-cache

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProviderTest.java (1)

242-245: ⚡ Quick win

Assert ordering between cache clear and client refresh.

This test verifies both actions happened, but not that clearDiagnostics() occurs before refreshDiagnostics(), which is the core behavior this PR protects.

Proposed test hardening
+import org.mockito.InOrder;
 ...
   void testServerContextPopulatedClearsCachedDiagnosticsForPullClient() {
@@
     // then
-    verify(openedA, times(1)).clearDiagnostics();
-    verify(openedB, times(1)).clearDiagnostics();
-    verify(languageClient, times(1)).refreshDiagnostics();
+    verify(openedA, times(1)).clearDiagnostics();
+    verify(openedB, times(1)).clearDiagnostics();
+    verify(languageClient, times(1)).refreshDiagnostics();
+
+    InOrder inOrder = org.mockito.Mockito.inOrder(openedA, openedB, languageClient);
+    inOrder.verify(openedA).clearDiagnostics();
+    inOrder.verify(openedB).clearDiagnostics();
+    inOrder.verify(languageClient).refreshDiagnostics();
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProviderTest.java`
around lines 242 - 245, The test verifies that clearDiagnostics() and
refreshDiagnostics() are called but does not enforce that clearDiagnostics()
occurs before refreshDiagnostics(), which is the critical behavior being tested.
Replace the separate verify statements with Mockito's InOrder verifier to assert
the correct execution sequence: first clearDiagnostics() on openedA and openedB,
then refreshDiagnostics() on languageClient. This ensures the test validates the
ordering requirement, not just the fact that both methods are called.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProviderTest.java`:
- Around line 242-245: The test verifies that clearDiagnostics() and
refreshDiagnostics() are called but does not enforce that clearDiagnostics()
occurs before refreshDiagnostics(), which is the critical behavior being tested.
Replace the separate verify statements with Mockito's InOrder verifier to assert
the correct execution sequence: first clearDiagnostics() on openedA and openedB,
then refreshDiagnostics() on languageClient. This ensures the test validates the
ordering requirement, not just the fact that both methods are called.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e4411ac7-52c1-498f-b70f-57474e8086b3

📥 Commits

Reviewing files that changed from the base of the PR and between 6c985d8 and 204925c.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProvider.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProviderTest.java

@sonarqubecloud

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Jun 16, 2026

Copy link
Copy Markdown
Contributor

Test Results

 3 468 files  ±0   3 468 suites  ±0   1h 42m 22s ⏱️ + 6m 46s
 3 483 tests +1   3 465 ✅ +1   18 💤 ±0  0 ❌ ±0 
20 898 runs  +6  20 786 ✅ +6  112 💤 ±0  0 ❌ ±0 

Results for commit 204925c. ± Comparison against base commit 6c985d8.

♻️ This comment has been updated with latest results.

@sfaqer
sfaqer requested a review from nixel2007 June 17, 2026 00:38
@nixel2007
nixel2007 merged commit 06a9a64 into develop Jun 17, 2026
43 checks passed
@nixel2007
nixel2007 deleted the fix/diagnostic-refresh-clears-cache branch June 17, 2026 06:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants