Repository navigation
fix(types): пустое значение функции доразрешается после наполнения - #4449
Conversation
Расчёт считает себя неполным, только если вызванный метод разрешился в символ, но ещё не посчитан. Вызов в модуль, до которого при наполнении области очередь ещё не дошла, не разрешается ни во что — сообщить о пропущенном некому, и значение функции остаётся пустым навсегда. Повезло методу или нет, решает порядок параллельного наполнения, разный от запуска к запуску. Посчитанное при наполнении пустое значение функции теперь доразрешается общим проходом. Повторно откладывать нечего: в самом проходе область наполнена, и пустое значение уже окончательно. На 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
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthrough
ChangesMethod return type resolution
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 winAssert the single deferred recomputation.
The test verifies the final
STRINGvalue, but it does not verify that the new empty-result path caused one deferred inference. BecauseclearInvocations(inferencer)runs before the deferred pass, addverify(inferencer, times(1)).computeReturnTypes(sourceMethod)afterhandleServerContextPopulated.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
📒 Files selected for processing (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.javasrc/test/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexerTest.java
Компоненты одного яруса независимы по построению: документы у них разные, и каждая берёт замки только своих. Считать их последовательно незачем — проход единственная фаза, где ядра простаивают. На 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
Компонента из нескольких документов держит их разобранными до неподвижной точки. Считая такие компоненты одновременно, проход множил бы предел держимых документов на ширину пула — сотня разобранных документов упрётся в память. Теперь одновременно разобранных не больше ширины пула. Компонент с несколькими документами единицы: на 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
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.javasrc/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
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/ExecutorConfiguration.java (1)
115-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd 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
📒 Files selected for processing (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/ExecutorConfiguration.javasrc/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
|
Замеры на итоговой голове Бенчмарк CI: 103,64 с (мин 102,77, макс 104,35, stddev 0,80) против базы
Отдельный пул вернул 1,84 с, которые до того съела защита памяти: проход сабмитил задачи в пул, внутри воркера которого сам же и работал. Детерминизм на той же голове, 4 прогона ssl_3_1:
143 против 131 — в пределах гуляния метрики; разделение пулов и предел по памяти на детерминизм не повлияли. |
Список методов документа брался из карты отдельно, а пополнялся после: очистка документа успевала выкинуть список между этими шагами. Метод оставался помеченным как посчитанный, но недостижимым из учёта, и снять пометку было уже некому — после перечитывания файла его значение считалось бы актуальным. Обе точки регистрации теперь пополняют список внутри compute по URI. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/index/MethodReturnTypeIndexer.java (1)
321-340: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winUse a non-copying per-URI collection for repeated registrations.
rememberMethodsOfUriappends toCopyOnWriteArrayListand does not remove duplicates. Repeated registrations copy the whole list and cause duplicate recomputation inrecomputeLoaded. 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
CopyOnWriteArrayListto 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.
!maintenanceis 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 fromindexedandmethodsByUri, but leaves the oldMethodSymbolinpending; a later population event can recompute a stale symbol. Track population state separately frommaintenanceand remove or version queued methods during invalidation.
513-534: Requeue consumers after a deferred source changes.
resolveAllprocesses only methods already inpending. If a source method changes fromTypeSet.EMPTYto a concrete type during maintenance, an already-indexed consumer can retain its old return type. This loop does not enqueue dependent methods or callpropagate. 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
@Qualifierreaches the generated constructor.
MethodReturnTypeIndexeruses Lombok@RequiredArgsConstructor, but the qualifier is declared on the field.ExecutorConfigurationdefines severalExecutorServicebeans. If Lombok does not copy@Qualifierto the generated constructor parameter, Spring can fail during context creation because the dependency is ambiguous. Confirmlombok.copyableAnnotationsor 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_MEMORYsingle-document components, excess tasks enterSemaphore.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. UseForkJoinPool.managedBlockwith aManagedBlocker, 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
resolveComponentcallsprogressReporter.tick()from each worker. Confirm thatWorkDoneProgressReporter.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
📒 Files selected for processing (2)
src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/ExecutorConfiguration.javasrc/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
Единица работы прохода — документ: он загружается, на нём пересчитываются его отложенные методы, и он отпускается. Методов в документе сколько угодно, и счёт по ним давал пачку отсчётов подряд на одну единицу работы. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017cu7S3zYn7n6GMsdYf5v1q
|



Ссылка на #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:ba3ff614fe72845d9e9f3205+0c458ca2a9018cb4Детерминизм, 4 прогона ssl_3_1, конфиг только с диагностиками системы типов:
Пик живого набора на ssl_3_1 от параллели не вырос заметно: один лишний разом разобранный документ стоит около 7,5 МБ, разброс между прогонами больше этой величины.
Ноль расхождений не достигнут — остаток разбирается дальше.
Что проверено и отвергнуто замером
+с неизвестным левым операндом → пусто вместо числа: расхождение индекса выросло с 256 до 625, пустота расползается по цепочкам.@Locked-геттер держит 30 % времени воркеров в профиле): в пределах шума, семантику конкурентности менять не стал.Summary by CodeRabbit