Skip to content

fix(types): пустое значение функции доразрешается после наполнения - #4449

Merged
nixel2007 merged 10 commits into
developfrom
fix/recompute-empty-return-types
Aug 12, 2026
Merged

nixel2007 merged 10 commits into
developfrom
fix/recompute-empty-return-types

Conversation

@nixel2007

@nixel2007 nixel2007 commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

Ссылка на #4429.

Причина

ExpressionTypeInferencer.methodReturnType помечает расчёт неполным только тогда, когда вызванный метод разрешился в символ, но ещё не посчитан. Если вызов не разрешился вообще — потому что модуль, в который он ведёт, при наполнении области ещё не зарегистрирован, — эта ветка не выполняется: ни consulted, ни sawMissing. Значение функции сохраняется пустым и помечается посчитанным навсегда.

Кому не повезло, решает порядок параллельного наполнения — он разный от запуска к запуску. Это и есть недетерминизм из #4429.

Замерено дампом содержимого индекса после наполнения на двух прогонах ssl_3_1: расходится ~420 строк из 5731, из них около сотни — ровно этот случай, «пусто в одном запуске, значение в другом». Пример: ВариантыОтчетовСлужебный.КлючЗамеров возвращает результат ОбщегоНазначения.СократитьСтрокуКонтрольнойСуммой; вызванная функция в обоих запусках Строка, а вызывающая — то Строка, то пусто.

Правка

Доразрешение. Пустое значение функции, посчитанное при наполнении, ставится в очередь общего прохода. Проход пересчитывает его, когда область наполнена и все имена разрешаются одинаково. Повторно откладывать нечего: в самом проходе пустое значение уже окончательное, поэтому доразрешение стоит ровно один пересчёт на метод (на ssl_3_1 это ~950 методов в ~260 документах).

Ярусы. Это стоит времени: проход вырос с ~0,5 с до ~6 с. Профиль (async-profiler, wall) показал 40 % на повторный разбор документов и 57 % на сам вывод, причём внутри вывода профиль плоский — горячей точки нет. Зато проход остаётся единственной фазой, где ядра простаивают, поэтому компоненты сильной связности разложены по ярусам: компонента попадает на ярус следующий за наибольшим ярусом тех, от кого она зависит, а внутри яруса зависимостей нет по построению. На ssl_3_1 ярусов семь, а компонент в первом 143 из 271. Пул взят тот, чьи воркеры несут рабочую область, иначе бины workspace-скоупа из чужого потока не достаются.

Предел по памяти. Разом разобранных документов не больше MAX_DOCUMENTS_IN_MEMORY — столько же проход и так себе позволяет, доводя до неподвижной точки один цикл. Считать по ширине пула нельзя: она берётся из числа ядер, и на широкой машине проход держал бы разобранными десятки документов. Компоненты из нескольких документов считаются по одной.

Замеры

Бенчмарк CI, сравнение с базой ветки ba3ff614f:

коммит что бенчмарк
ba3ff614f база (мерж #4448) 98,20 с
e72845d9 доразрешение пустых 107,66 с (+9,46)
e9f3205+0c458ca + ярусы 103,63 с (+5,43)
2a9018cb4 + предел по памяти 105,47 с (+7,27)

Детерминизм, 4 прогона ssl_3_1, конфиг только с диагностиками системы типов:

расхождения между парами прогонов мерцающих строк
develop 82–294 342
доразрешение 58–160 181
+ ярусы 52–99 131

Пик живого набора на ssl_3_1 от параллели не вырос заметно: один лишний разом разобранный документ стоит около 7,5 МБ, разброс между прогонами больше этой величины.

Ноль расхождений не достигнут — остаток разбирается дальше.

Что проверено и отвергнуто замером

  • Помечать неполноту по любому неразрешившемуся имени вместо эвристики «пусто»: проход 37–40 с — неразрешённых имён в коде много, и они откладываются волна за волной.
  • + с неизвестным левым операндом → пусто вместо числа: расхождение индекса выросло с 256 до 625, пустота расползается по цепочкам.
  • Чтение дерева символов без замка (@Locked-геттер держит 30 % времени воркеров в профиле): в пределах шума, семантику конкурентности менять не стал.
  • Пересчёт всех методов документа после прохода и постановка потребителей в очередь (рабочий список Килдалла): мерцающих 804 и 1155 против 342 — любой рост объёма пересчёта увеличивает разброс, потому что шаг прохода не монотонен.

Summary by CodeRabbit

  • Bug Fixes
    • Improved function return type inference during workspace initialization.
    • Return types that are initially unavailable are recomputed after additional workspace context becomes available.
    • Improved resolution performance by processing independent work in parallel while preserving dependency order.
    • Enhanced handling of complex dependencies, incomplete type information, and multi-document cycles.
    • Workspace indexing now provides more reliable results as documents are loaded and analyzed.
    • Added progress updates during return-type analysis for better visibility into indexing progress.

Расчёт считает себя неполным, только если вызванный метод разрешился в символ,
но ещё не посчитан. Вызов в модуль, до которого при наполнении области очередь
ещё не дошла, не разрешается ни во что — сообщить о пропущенном некому, и
значение функции остаётся пустым навсегда. Повезло методу или нет, решает
порядок параллельного наполнения, разный от запуска к запуску.

Посчитанное при наполнении пустое значение функции теперь доразрешается общим
проходом. Повторно откладывать нечего: в самом проходе область наполнена, и
пустое значение уже окончательно.

На ssl_3_1 (4 прогона, только диагностики системы типов): мерцающих строк
342 -> 181, расхождения между парами прогонов 82-294 -> 58-160.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 190e91a3-8cc0-4521-8889-400bd80b5caa

📥 Commits

Reviewing files that changed from the base of the PR and between 8010eb8 and 6309d36.

📒 Files selected for processing (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java

📝 Walkthrough

Walkthrough

MethodReturnTypeIndexer now resolves independent dependency tiers concurrently with bounded document loading. Cyclic components remain sequential. Empty inferred return types are deferred and recomputed after workspace population.

Changes

Method return type resolution

Layer / File(s) Summary
Configure bounded resolution executor
src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/ExecutorConfiguration.java, src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java
Adds a workspace-scoped executor for asynchronous return-type resolution. The indexer keeps the document-memory limit private and uses it to bound resolution resources.
Tiered concurrent resolution
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java
The indexer builds dependency tiers and resolves independent components asynchronously under a semaphore limit. Multi-document cyclic components remain sequential. Progress and elapsed-time logging are updated.
Defer and validate empty return types
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexerTest.java
Empty inferred return types are deferred outside maintenance mode. Method tracking updates are atomic. The regression test verifies recomputation to STRING after workspace population.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Workspace as Workspace resolution
  participant Indexer as MethodReturnTypeIndexer
  participant Executor as resolveReturnTypesExecutor
  participant Components as Dependency components
  Workspace->>Indexer: Resolve deferred workspace types
  Indexer->>Components: Build dependency tiers
  Indexer->>Executor: Submit independent components
  Executor->>Components: Resolve components under semaphore limit
  Indexer->>Components: Resolve cyclic components sequentially
  Components-->>Indexer: Return resolved method types
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Заголовок точно описывает основное исправление: повторное разрешение пустого значения функции после наполнения контекста.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ 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/recompute-empty-return-types

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.

@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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/test/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexerTest.java (1)

173-190: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the single deferred recomputation.

The test verifies the final STRING value, but it does not verify that the new empty-result path caused one deferred inference. Because clearInvocations(inferencer) runs before the deferred pass, add verify(inferencer, times(1)).computeReturnTypes(sourceMethod) after handleServerContextPopulated.

The PR objective specifies one recomputation after workspace population.

Proposed test assertion
     indexer.handleServerContextPopulated(new ServerContextPopulatedEvent(serverContextOf(source)));
 
+    verify(inferencer, times(1)).computeReturnTypes(sourceMethod);
     // then: пустое значение пересчитано. Иначе функция навсегда осталась бы без типа, а
🤖 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/types/index/MethodReturnTypeIndexerTest.java`
around lines 173 - 190, Update
emptyValuedFunctionIsRecomputedAfterWorkspaceIsPopulated to verify exactly one
deferred inference after handleServerContextPopulated by asserting
inferencer.computeReturnTypes(sourceMethod) was called once. Keep the existing
final STRING return-type assertion unchanged.
🤖 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.

Inline comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java`:
- Around line 326-334: The empty return-type recomputation behavior in
MethodReturnTypeIndexer must be documented in both documentation locales. Update
the relevant documentation under docs/ and docs/en/ to state when empty computed
types are added to pending and recomputed, keeping the two locale versions
aligned.
- Around line 326-334: Update resolveAll and the surrounding
MethodReturnTypeIndexer dependency-processing flow so that when a pending
method’s computed return type changes, all dependent methods are enqueued for
recomputation, including dependents not already in pending. Preserve the
existing empty-type handling and add a regression test covering a source
changing from empty to STRING and its non-pending consumer receiving the updated
type.
- Around line 326-334: The pending-method deferral in
MethodReturnTypeIndexer.store must only run during workspace population, so gate
the empty-result pending.add(method) path on the population state rather than
merely !maintenance. Update clear(URI) to remove all queued methods belonging to
that URI along with indexed and methodsByUri entries, preventing obsolete
MethodSymbol recomputation. Add a regression test covering an edit before
population completes.

---

Nitpick comments:
In
`@src/test/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexerTest.java`:
- Around line 173-190: Update
emptyValuedFunctionIsRecomputedAfterWorkspaceIsPopulated to verify exactly one
deferred inference after handleServerContextPopulated by asserting
inferencer.computeReturnTypes(sourceMethod) was called once. Keep the existing
final STRING return-type assertion unchanged.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 310a1dc0-01b6-4ee2-97d7-901d3740a3fa

📥 Commits

Reviewing files that changed from the base of the PR and between ba3ff61 and e72845d.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexerTest.java

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

 4 086 files  ±0   4 086 suites  ±0   50m 19s ⏱️ - 6m 13s
 4 236 tests +1   4 165 ✅ +1   71 💤 ±0  0 ❌ ±0 
25 416 runs  +6  24 986 ✅ +6  430 💤 ±0  0 ❌ ±0 

Results for commit 708a6a2. ± Comparison against base commit ba3ff61.

♻️ This comment has been updated with latest results.

nixel2007 and others added 2 commits August 12, 2026 08:14
Компоненты одного яруса независимы по построению: документы у них разные, и
каждая берёт замки только своих. Считать их последовательно незачем — проход
единственная фаза, где ядра простаивают.

На ssl_3_1 ярусов семь, а компонент в первом 143 из 271.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q
Проход — единственная фаза, где время не видно ни по чему другому.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q
nixel2007 and others added 2 commits August 12, 2026 09:09
Компонента из нескольких документов держит их разобранными до неподвижной
точки. Считая такие компоненты одновременно, проход множил бы предел держимых
документов на ширину пула — сотня разобранных документов упрётся в память.
Теперь одновременно разобранных не больше ширины пула.

Компонент с несколькими документами единицы: на ssl_3_1 документов в ярусах
всего на три больше, чем компонент.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q
Ширина пула берётся из числа ядер, поэтому «параллельно, сколько влезет»
означало бы на широкой машине десятки разом разобранных документов. Дерево
разбора — самое тяжёлое, что есть у документа, и счёт должен идти по
документам, а не по потокам.

Предел равен MAX_DOCUMENTS_IN_MEMORY: столько же проход и так позволяет себе,
доводя до неподвижной точки один цикл. На ssl_3_1 предел почти не связывает
(8 против ширины 11) и по времени прохода не виден: медиана трёх прогонов
7805 мс без предела против 7977 мс с ним.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q

@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.

Actionable comments posted: 1

🤖 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.

Inline comments:
In
`@src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java`:
- Around line 507-509: Make document-associated method registration and
invalidation atomic by updating both registration paths around
rememberMethodOfUri and the inferred return-type registration at lines 305-306
and 316-318 to use methodsByUri.compute(uri, ...), adding the method/type to the
per-URI collection within that computation. Update clear(URI) to use the same
compute-based coordination so removal cannot interleave between collection
lookup and insertion, while preserving existing indexed cleanup behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 4d8f3745-ba51-4ea2-a89a-b2348b57575c

📥 Commits

Reviewing files that changed from the base of the PR and between e72845d and 2a9018c.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexerTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexerTest.java

Проход запускается слушателем события наполнения, то есть изнутри задачи пула
наполнения. Класть туда же собственные задачи означает занимать пул, который
сейчас занят.

Ширина нового пула ограничена числом разом разобранных документов: работа
прохода упирается в них, а не в число ядер, и лишние воркеры только заняли бы
стеки.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q

@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/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/ExecutorConfiguration.java (1)

115-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add JavaDoc for the new public bean method.

resolveReturnTypesExecutor() is public and currently has only // comments. Add JavaDoc that states the workspace scope, dedicated executor purpose, parallelism bound, returned executor, and shutdown side effect. Keep caller and ordering rationale in a normal implementation comment.

As per coding guidelines: “Javadoc классов и методов должен описывать контракт: параметры, результат, инварианты и побочные эффекты, но не вызывающие стороны, порядок вызовов или CLI-сценарии.”

🤖 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/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/ExecutorConfiguration.java`
around lines 115 - 125, Add JavaDoc to the public resolveReturnTypesExecutor()
method documenting its workspace scope, dedicated executor purpose, parallelism
limit, returned ExecutorService, and shutdown side effect. Move the existing
caller and ordering rationale to a regular implementation comment, keeping
contract details separate from invocation and ordering explanations.

Source: Coding guidelines

🤖 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/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/ExecutorConfiguration.java`:
- Around line 115-125: Add JavaDoc to the public resolveReturnTypesExecutor()
method documenting its workspace scope, dedicated executor purpose, parallelism
limit, returned ExecutorService, and shutdown side effect. Move the existing
caller and ordering rationale to a regular implementation comment, keeping
contract details separate from invocation and ordering explanations.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 00a2830c-8241-4da1-9a5f-0be70433db6d

📥 Commits

Reviewing files that changed from the base of the PR and between 2a9018c and 91bff13.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/ExecutorConfiguration.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java

Ограничивать ширину числом разом разобранных документов незачем: предел держат
разрешения семафора, а пулы рабочей области заводятся по одному правилу.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q
@nixel2007

Copy link
Copy Markdown
Member Author

Замеры на итоговой голове 74c3c3c64.

Бенчмарк CI: 103,64 с (мин 102,77, макс 104,35, stddev 0,80) против базы ba3ff614f = 98,20 с, то есть +5,44 с.

коммит что бенчмарк против базы
ba3ff614f база (мерж #4448) 98,20 —
e72845d9 доразрешение пустых 107,66 +9,46
2a9018cb4 + ярусы + предел по памяти 105,47 +7,27
74c3c3c64 + свой пул у прохода 103,64 +5,44

Отдельный пул вернул 1,84 с, которые до того съела защита памяти: проход сабмитил задачи в пул, внутри воркера которого сам же и работал.

Детерминизм на той же голове, 4 прогона ssl_3_1:

сборка расхождения между парами прогонов мерцающих строк
develop 82–294 342
доразрешение 58–160 181
+ ярусы 52–99 131
итоговая голова 19–118 143

143 против 131 — в пределах гуляния метрики; разделение пулов и предел по памяти на детерминизм не повлияли.

Список методов документа брался из карты отдельно, а пополнялся после: очистка
документа успевала выкинуть список между этими шагами. Метод оставался
помеченным как посчитанный, но недостижимым из учёта, и снять пометку было
уже некому — после перечитывания файла его значение считалось бы актуальным.

Обе точки регистрации теперь пополняют список внутри compute по URI.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q

@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/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java (1)

321-340: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Use a non-copying per-URI collection for repeated registrations.

rememberMethodsOfUri appends to CopyOnWriteArrayList and does not remove duplicates. Repeated registrations copy the whole list and cause duplicate recomputation in recomputeLoaded. Use a concurrent set or publish one immutable snapshot per batch.

Based on learnings: repeated method symbols can be registered during parsing, deferred resolution, and propagation; use a set instead of CopyOnWriteArrayList to avoid copying the collection for each duplicate insertion.

🤖 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/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java`
around lines 321 - 340, Update rememberMethodsOfUri to store each URI’s methods
in a concurrent set rather than a CopyOnWriteArrayList, preserving atomic
compute-based updates in methodsByUri. Ensure repeated MethodSymbol
registrations are deduplicated while retaining safe concurrent access for
recomputeLoaded.

Source: Learnings

🔇 Additional comments (7)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java (6)

362-370: Invalidate queued methods when a document changes.

!maintenance is true during ordinary content changes, not only during initial workspace population. An empty result from a normal edit is therefore queued. clear(URI) removes the method from indexed and methodsByUri, but leaves the old MethodSymbol in pending; a later population event can recompute a stale symbol. Track population state separately from maintenance and remove or version queued methods during invalidation.


513-534: Requeue consumers after a deferred source changes.

resolveAll processes only methods already in pending. If a source method changes from TypeSet.EMPTY to a concrete type during maintenance, an already-indexed consumer can retain its old return type. This loop does not enqueue dependent methods or call propagate. Enqueue dependent methods or documents after each changed component and add a regression test for the empty-to-concrete transition.


105-114: 🎯 Functional Correctness

⚠️ Unverified finding
Sandbox verification was unavailable.

Verify that @Qualifier reaches the generated constructor.

MethodReturnTypeIndexer uses Lombok @RequiredArgsConstructor, but the qualifier is declared on the field. ExecutorConfiguration defines several ExecutorService beans. If Lombok does not copy @Qualifier to the generated constructor parameter, Spring can fail during context creation because the dependency is ambiguous. Confirm lombok.copyableAnnotations or use an explicitly qualified constructor parameter.


527-533: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

⚠️ Unverified finding
Sandbox verification was unavailable.

Do not block ForkJoinPool workers on the semaphore.

When a tier has more than MAX_DOCUMENTS_IN_MEMORY single-document components, excess tasks enter Semaphore.acquireUninterruptibly() and occupy ForkJoinPool workers. The pool cannot compensate for this raw blocking call. On a pool wider than eight workers, this can exhaust worker slots and stall nested work or sharply reduce throughput. Use ForkJoinPool.managedBlock with a ManagedBlocker, or submit only bounded batches.

Also applies to: 550-562


604-616: 🎯 Functional Correctness

⚠️ Unverified finding
Sandbox verification was unavailable.

Verify that progress reporting supports concurrent ticks.

Independent components run concurrently, and resolveComponent calls progressReporter.tick() from each worker. Confirm that WorkDoneProgressReporter.tick() is thread-safe. Otherwise progress updates can race or fail.


41-41: LGTM!

Also applies to: 52-63, 93-97, 225-225, 241-242, 310-310, 479-496, 565-594

src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/ExecutorConfiguration.java (1)

41-41: LGTM!

Also applies to: 52-63, 93-96, 114-120, 174-175, 225-225, 241-242

🤖 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/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java`:
- Around line 321-340: Update rememberMethodsOfUri to store each URI’s methods
in a concurrent set rather than a CopyOnWriteArrayList, preserving atomic
compute-based updates in methodsByUri. Ensure repeated MethodSymbol
registrations are deduplicated while retaining safe concurrent access for
recomputeLoaded.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7ae297c5-9586-420b-bac0-bdd0ae8788ba

📥 Commits

Reviewing files that changed from the base of the PR and between 91bff13 and 8010eb8.

📒 Files selected for processing (2)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/ExecutorConfiguration.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java

nixel2007 and others added 2 commits August 12, 2026 12:14
Счётчик крутился перед расчётом компоненты, то есть сообщал о готовности того,
что ещё не начато. С ярусом, который считается сразу многими потоками, полоса
на его старте показывала бы готовым весь ярус.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q
Единица работы прохода — документ: он загружается, на нём пересчитываются его
отложенные методы, и он отпускается. Методов в документе сколько угодно, и счёт
по ним давал пачку отсчётов подряд на одну единицу работы.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q
@sonarqubecloud

Copy link
Copy Markdown

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.

1 participant