Skip to content

fix(types): одноимённые модули OneScript не вешают дорасчёт типов возвращаемых значений - #4574

Merged
nixel2007 merged 2 commits into
developfrom
fix/oscript-members-without-waiting
Oct 1, 2026
Merged

nixel2007 merged 2 commits into
developfrom
fix/oscript-members-without-waiting

Conversation

@sfaqer

@sfaqer sfaqer commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

Что было

На CollectionOS сервер вставал на «Дорассчитываем типы возвращаемых значений...» и больше не отвечал. В дампе потоков JVM сама находит взаимную блокировку (Found one Java-level deadlock): два потока resolve-return-types-* перестраивают по документу и ждут друг друга. analyze --srcDir G:/git/CollectionOS зависает так же, примерно через 70 с.

Причина

В oscript_modules/collectionos лежит установленная копия самой библиотеки. Исходник и копия регистрируются одним типом (у CollectionOS 67 таких пар), и члены этого типа собираются по деревьям символов обоих файлов.

Цикл:

  1. MethodReturnTypeIndexer.recomputeLoading перестраивает документ A с диска. DocumentContext.rebuild строит дерево символов под computeLock документа.
  2. VariableSymbolComputer.visitLValue сверяет голое присваивание с членами self-типа: isBareSelfProperty → TypeRegistry.findMember → источники членов типа.
  3. Один из источников — OScriptModuleMembersProvider.collectMembers двойника B. Он зовёт B.getSymbolTree(), а это @Locked("computeLock").
  4. Параллельно другой поток перестраивает B и точно так же ждёт дерево A.

Javadoc isBareSelfProperty исходил из того, что члены self-типа берутся из реестра, а не из деревьев модулей. Для OneScript-типов это не так: их члены, признак определения аннотации и родитель класса читаются из деревьев модулей.

Исправление

  • DocumentContext.getSymbolTreeNoLock() — последнее построенное дерево без ожидания идущего перестроения. Дерево присваивается только в rebuild, поле стало volatile.
  • На нём теперь работают:
    • OScriptModuleMembersProvider.collectMembers / collectConstructors;
    • OScriptMetaAnnotationResolver.isAnnotationDefinition;
    • OScriptExtends.constructorAnnotations (родитель и интерфейсы).
  • Во время перестроения документа читается его прежнее дерево. В кэше членов оно не остаётся: событие изменения содержимого после rebuild сбрасывает члены типов документа и его наследников (invalidateMembersOfDocumentAndSubtypes).

Проверка

  • OScriptTwinModulesLockTest на фикстуре twins-lib (библиотека и её копия в oscript_modules). Тестовый поток держит блокировку двойника, первый документ перестраивается на diagnosticComputerExecutor, ожидание — get(30 s). Без исправления тест падает по таймауту.
  • Моки DocumentContext в пяти тестах (OScriptModuleMembersProviderTest, OScriptMetaAnnotationResolverTest, AutumnBeanIndexTest, AutumnCollectionIndexTest, AutumnInjectionPointIndexTest) получили заглушку getSymbolTreeNoLock() рядом с getSymbolTree().
  • analyze --srcDir G:/git/CollectionOS: на develop зависает; с исправлением четыре прогона по 23–29 с. Между прогонами отчёты различаются одним замечанием Typo.
  • cleanTest check локально зелёный.

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

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Reduced delays when module information is refreshed while a related module is also being updated.
    • Improved the availability of symbol and member information during background rebuilds, helping updates complete without waiting indefinitely for another module.
    • Improved access to module members, constructors, and annotation information while related modules are being rebuilt.

…вращаемых значений

Исходник библиотеки и её же копия в oscript_modules регистрируются одним типом,
и члены этого типа собираются по деревьям обоих файлов. Строя дерево символов под
блокировкой документа, модуль сверяет голые присваивания с членами self-типа — то
есть читает дерево двойника. Проход доразрешения перестраивает документы
параллельно: два двойника ждали друг друга бесконечно (CollectionOS).

Источники членов и признаки наследования/аннотаций OneScript читают дерево чужого
документа без ожидания его перестроения (DocumentContext.getSymbolTreeNoLock).
Прежнее дерево в памятке членов не залипает: перестроение сбрасывает члены типа.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: 1c-syntax/bsl-language-server/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 3e925cdc-32a3-4ea3-bf7a-7b131517b3c4

📥 Commits

Reviewing files that changed from the base of the PR and between d9e28f5 and 9f0b130.

📒 Files selected for processing (1)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

DocumentContext stores its symbol tree in an AtomicReference and adds a non-locking accessor. OScript lookups use that accessor. Tests update their mocks and verify that a module rebuild completes while its twin module’s computation lock is held.

Changes

Symbol tree reads

Layer / File(s) Summary
Store and expose the current symbol tree
src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java
symbolTree is now an AtomicReference. The locked accessor returns its current value, and getSymbolTreeNoLock() returns that value without waiting for the computation lock. Rebuilds publish updates through the reference, and metric computation reads from it.
Use non-locking reads in OScript lookups
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/OScriptModuleMembersProvider.java, src/main/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/annotations/OScriptMetaAnnotationResolver.java, src/main/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/extends_/OScriptExtends.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/OScriptModuleMembersProviderTest.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/annotations/OScriptMetaAnnotationResolverTest.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/autumn/*
OScript member, constructor, annotation-definition, and parent-annotation lookups use getSymbolTreeNoLock(). Related test setups stub the new accessor.
Test rebuild during twin-module lock contention
src/test/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/OScriptTwinModulesLockTest.java
The integration test holds the twin module’s computation lock during another module’s rebuild. It verifies that the rebuild completes and updates the symbol tree.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: nixel2007

Merge Risk: ⚪ Minimal · up to 9f0b1

OScript lookups can read the last-published tree without waiting on a peer rebuild lock, while completed rebuilds publish the new tree atomically. The supplied contention test covers this path, and no concrete merge-blocking regression is established.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 9f0b1

The change addresses a cross-document deadlock by allowing lookups to use the last completed symbol tree. The reviewed paths handle internal code-analysis metadata, but concurrent lookups may briefly use an older tree, and recovery and downstream effects are not fully established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated change in exposure is to in-process, cross-document analysis of source-code metadata. Attacker control of that metadata, tenant scope, and any downstream privileged sink remain unestablished.

Trust Boundaries and Controls

  • observed — DocumentContext still owns publication, and the inspected new consumers read metadata rather than changing document state or exercising an observed authorization control.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.63% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 10 files. 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 clearly describes the main fix: preventing same-named OneScript modules from hanging during recalculation of return-value types. It is specific and consistent with the reported objectives an…
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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.

…то volatile

Sonar (java:S3077) не принимает volatile у ссылки на изменяемый тип. Дерево
заменяется целиком, поэтому семантика та же: чтение без блокировки видит
последнее построенное дерево.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sonarqubecloud

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown
Contributor

Test Results

 4 284 files  +6   4 284 suites  +6   1h 0m 43s ⏱️ - 6m 59s
 4 459 tests +1   4 370 ✅ +1   89 💤 ±0  0 ❌ ±0 
26 754 runs  +6  26 212 ✅ +6  542 💤 ±0  0 ❌ ±0 

Results for commit 9f0b130. ± Comparison against base commit 7bee672.

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