Skip to content

fix(types): отношения наследования и индекс ссылок не ждут блокировок чужих документов - #4542

Merged
nixel2007 merged 1 commit into
developfrom
fix/type-relations-without-document-locks
Sep 26, 2026
Merged

nixel2007 merged 1 commit into
developfrom
fix/type-relations-without-document-locks

Conversation

@sfaqer

@sfaqer sfaqer commented Sep 26, 2026 •

Copy link
Copy Markdown
Member

Что было

MCP-сервер на рабочей области самого bsl-language-server намертво вставал на заполнении: не отвечал ни один инструмент. JVM сама находит взаимоблокировку в дампе потоков (jcmd Thread.print -l) — два потока прохода доразрешения типов возврата:

  • resolve-return-types-…-27 в MethodReturnTypeIndexer.recomputeLoading держит на запись блокировку документа A и перечитывает его. Слушатель изменения содержимого OScriptModuleMembersProvider сбрасывает члены наследников A и обходит их через TypeRelations.subtypes → ServerContext.getDocument(B) — ждёт блокировку чтения B;
  • resolve-return-types-…-24 то же самое делает с B и ждёт A.

В репозитории есть фикстура с циклом наследования (oscript-libraries/cycle-lib: ЦиклА ↔ ЦиклБ), поэтому на нём это и всплыло; на обычном проекте хватает пары «родитель — наследник», которые перечитываются одновременно.

Причина

Та же, что в #4536: код, который вызывается под блокировкой записи одного документа, ждёт блокировку чтения другого. В слушателях изменения содержимого таких мест два:

  • TypeRelations берёт документы наследников, реализаторов и родителя через getDocument;
  • ReferenceIndexFiller — документ класса библиотеки у Новый Класс() и у обращения к модулю библиотеки (два класса, ссылающихся друг на друга, встают так же).

Исправление

Оба берут документ через getDocumentNoLock — метод контекста как раз для такого случая; так же берут чужие документы ReferenceIndex и reference-finder'ы. Нужно здесь только дерево символов, а у него своя блокировка внутри документа. URI в TypeRelations приходят из TypeRelationIndex, который и сам собирается по карте документов без блокировок, а второй путь разрешения родителя (через реестр типов) блокировок не брал и раньше.

getDocument с блокировкой не тронут: она защищает запросы редактора от недоинициализированного документа (de0ee2491f). TypeService.definingSymbol тоже берёт документ с блокировкой, но его зовут только запросы редактора (ссылки на документы, инлей-хинты), которые блокировок не держат, — его не трогал.

Проверка

  • TypeRelationsLockTest: блокировку наследника на запись держит тестовый поток, обход наследников идёт на другом. Без правки — таймаут 30 с, с правкой — наследник найден.
  • ReferenceIndexFillerLockTest: то же для заполнения индекса ссылок при Новый Класс() и блокировке класса.
  • MCP по stdio на рабочей области bsl-language-server (джарник вместе с fix(types): сборка индексов «ОСени» не ждёт блокировок документов #4536 и fix(context): конфигурация читается до параллельного заполнения рабочей области #4543 — исправлением чтения конфигурации): 8 запусков подряд, register_workspace_folder отвечает за 11–17 с, зависаний нет. Без исправления конфигурации зависание остаётся, но уже другое: JVM показывает цикл через Lazy конфигурации, без блокировок документов.
  • OneUnit по MCP (тот же джарник): регистрация 11 с, analyze_file по ИсполнительИзоляции.os — 2,3 с.
  • cleanTest check — зелёный.

Связано: #4536 (сборка индексов «ОСени» — тот же класс ошибки, первый найденный путь).

🤖 Generated with Claude Code

… чужих документов

Перечитанный документ в слушателях изменения содержимого — под блокировкой
записи — обходит наследников (OScriptModuleMembersProvider → TypeRelations.subtypes)
и заполняет индекс ссылок с обращением к классам библиотек (ReferenceIndexFiller).
Оба брали чужой документ через getDocument, ждущий его блокировку чтения. Два
потока прохода доразрешения, перечитывающие родителя и наследника (или два
класса, ссылающихся друг на друга), вставали друг против друга.

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

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

coderabbitai Bot commented Sep 26, 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: cbbcfa86-cf15-4619-bf0e-e599d03d2c38

📥 Commits

Reviewing files that changed from the base of the PR and between 67d2fbc and 42923ac.

📒 Files selected for processing (4)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFiller.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/extends_/TypeRelations.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFillerLockTest.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/extends_/TypeRelationsLockTest.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.


📝 Walkthrough

Walkthrough

Reference indexing and type relationship queries now retrieve documents without waiting for document locks. New lock tests cover constructor reference indexing and subtype lookup while the relevant documents are write-locked.

Changes

Non-blocking document lookups

Layer / File(s) Summary
Reference indexing lookups
src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFiller.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFillerLockTest.java
Constructor and module-type lookup use getDocumentNoLock. A test checks that reference filling indexes a constructor while its library class is write-locked.
Type relationship lookups
src/main/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/extends_/TypeRelations.java, src/test/java/com/github/_1c_syntax/bsl/languageserver/types/oscript/extends_/TypeRelationsLockTest.java
Subtype, interface closure, implementor expansion, and library URI lookups use getDocumentNoLock. A test checks subtype lookup while a subtype document is write-locked.

Priority: ⬇️ Low

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

Change: Bug fix

Suggested reviewers: nixel2007

Merge Risk: ⚪ Minimal · up to 42923

The changed lookups have no identified issue requiring a fix before merge. Normal checks remain appropriate.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 42923

The new lookups avoid a cross-document lock cycle that can stall the language server. They may read an earlier document state during an update, but the reviewed paths do not show a new security boundary crossing or privileged operation. The effect of such reads on every downstream consumer is not fully established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The directly evidenced availability and consistency effects are within a workspace’s document relationships and reference index. No new credential, network, deployment, or cross-workspace authority path was identified in the reviewed lookup flow.

Trust Boundaries and Controls

  • observed — Library names supplied through parsed source are resolved to registered library URIs before the changed document reads; reference replacement remains keyed to the source document URI.

Resilience and Maintainability Implications

  • inferred — Removing the target document’s read-lock acquisition breaks the described cross-document lock-wait path. Concurrent rebuild or removal can still affect which relationship state a query sees; a security-sensitive downstream use of that state was not established.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: cross-document inheritance and reference-index lookups no longer wait for locks held by other documents.
  • 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.

@sonarqubecloud

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

 4 182 files   4 182 suites   1h 5m 35s ⏱️
 4 370 tests  4 297 ✅  73 💤 0 ❌
26 220 runs  25 774 ✅ 446 💤 0 ❌

Results for commit 42923ac.

♻️ This comment has been updated with latest results.

@nixel2007
nixel2007 merged commit 6106795 into develop Sep 26, 2026
42 checks passed
@nixel2007
nixel2007 deleted the fix/type-relations-without-document-locks branch September 26, 2026 08:20
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