Skip to content

perf(types): идемпотентная регистрация member-source в MetadataCollectionSpecializer#4189

Merged
nixel2007 merged 1 commit into
developfrom
perf/membersource-idempotent
Jun 22, 2026
Merged

perf(types): идемпотентная регистрация member-source в MetadataCollectionSpecializer#4189
nixel2007 merged 1 commit into
developfrom
perf/membersource-idempotent

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jun 22, 2026

Copy link
Copy Markdown
Member

Что и зачем

Обход дерева метаданных в MetadataCollectionSpecializer приходит к одному и тому же per-owner synthetic-типу многократно (общие имена табличных частей, общий element-type), а TypeRegistry.registerMemberSource добавляет источник без дедупликации (computeIfAbsent(...).add(...)). В итоге ~429K списков member-source держат ~6.7M лямбд (~14 дублей на тип), а getMembers материализует ~14-кратно избыточный граф членов, удерживаемый в membersCache.

Профилирование (JFR + heap dump + Eclipse MAT) показало, что TypeRegistry удерживает ~52% живого хипа, а весь 6-млн кластер MemberDescriptor/TypeSet/BilingualString/лямбд — это и есть эта дублирующая материализация.

Изменение

registerPerOwner помечает уже обработанные ref в рамках одного specialize() и не регистрирует источники повторно. Регистрация детерминирована по path-кодированному имени ref, поэтому повторная обработка была чисто избыточной — выход getMembers и так дедуплицируется putIfAbsent по имени.

Замер (analyze на nixel2007/cpm)

структура (было ~6M) baseline этот PR
MemberDescriptor 6.01M 442K
TypeSet 6.04M 475K
BilingualString 6.19M 617K
member-source лямбды ~6.7M ~450K
метрика baseline этот PR
live heap 5.04 ГБ 2.95 ГБ (−41.5%)
LambdaForm.invokeExact (CPU на дублях) 7.6% исчезает из топа
Object[] allocation pressure 74% 49%

Соотношение 6.01M/442K ≈ 13.6× — ровно фактор дублирования. JSON-отчёт analyze побайтно идентичен baseline.

✅ Валидация

MetadataCollectionSpecializerTest (12 тестов, HBK-gated через BSL_LANGUAGE_SERVER_RUN_HBK_TESTS=true) прогнан локально на реальном HBK — 12/12 PASS на этой ветке и в комбинации A+B+C. Тесты покрывают per-MDO/per-collection специализацию, табличные части и рекурсию по под-владельцам (tabularSectionGetsRecursivePerSectionType) — ровно там, где работает гард дедупа. Плюс JSON-отчёт analyze побайтно идентичен baseline.

Крупнейший из трёх независимых перф-патчей; #A и #C складываются поверх.

🤖 Generated with Claude Code

…tionSpecializer

Обход дерева метаданных приходит к одному и тому же per-owner synthetic-типу
многократно (общие имена табличных частей, общий element-type), а
TypeRegistry.registerMemberSource добавляет источник без дедупликации
(computeIfAbsent(...).add(...)). В итоге ~429K списков member-source держали
~6.7M лямбд (~14 дублей на тип), а getMembers материализовал ~14-кратно
избыточный граф членов, удерживаемый в membersCache.

registerPerOwner теперь помечает уже обработанные ref в рамках одного
specialize() и не регистрирует источники повторно. Регистрация детерминирована
по path-кодированному имени ref, поэтому повторная обработка была чисто
избыточной — выход getMembers и так дедуплицируется putIfAbsent по имени.

Замер на nixel2007/cpm (analyze): MemberDescriptor 6.01M → 442K, TypeSet
6.04M → 475K, BilingualString 6.19M → 617K (ровно ~13.6×, совпало с оценкой
дублей); live heap 5.04 ГБ → 2.95 ГБ (-41.5%); CPU на дублирующих
member-source лямбдах (LambdaForm.invokeExact 7.6%) исчезает; Object[]
allocation pressure 74% → 49%. JSON-отчёт побайтно идентичен baseline.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01EWA4hy5YvUBU1CXkdr4npc
@coderabbitai

coderabbitai Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

MetadataCollectionSpecializer gains a Set<TypeRef> registeredOwners (backed by HashSet) that is cleared at the start of each specialize() call. In registerPerOwner, a set-membership check now causes an early return when the same per-owner type ref has already been registered during the current traversal, preventing duplicate TypeRegistry#registerMemberSource calls.

Changes

Per-owner registration deduplication

Layer / File(s) Summary
registeredOwners field declaration and import
...types/registry/MetadataCollectionSpecializer.java
Adds java.util.HashSet import and declares a private Set<TypeRef> registeredOwners field with a comment describing its deduplication purpose.
Clear on specialize() and guard in registerPerOwner
...types/registry/MetadataCollectionSpecializer.java
Calls registeredOwners.clear() before the specialization traversal and adds an early-return guard in registerPerOwner using registeredOwners.add(perOwnerRef), skipping re-registration of already-seen per-owner refs.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

🐇 A set to remember each owner I've seen,
No double-registering — keeps the code clean!
One clear() at the start, one add() as the gate,
Repeats hop right past, they arrive a bit late.
The registry rests, no duplicates remain! 🌿

🚥 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%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main change: introducing idempotent registration of member sources in MetadataCollectionSpecializer to eliminate redundant processing.
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.

✏️ 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 perf/membersource-idempotent

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: 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/registry/MetadataCollectionSpecializer.java`:
- Around line 316-324: The `registeredOwners` field is mutable shared state in a
WorkspaceScope component that lacks thread-safety guarantees. Since
WorkspaceScope does not serialize method invocations, the `specialize()` method
can be called concurrently by multiple threads, causing race conditions when
`clear()` and `add()` operations execute on this HashSet. Either add
synchronization and document that `specialize()` must be invoked serially within
a workspace, or refactor `registeredOwners` from a class-level field to a local
variable declared within the `specialize()` method scope so each invocation has
its own dedup state.
🪄 Autofix (Beta)

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

Run ID: 5264b748-5668-4f78-8f56-7fa82eb72bf8

📥 Commits

Reviewing files that changed from the base of the PR and between 49181d7 and 4392509.

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

@nixel2007

Copy link
Copy Markdown
Member Author

Прогнал MetadataCollectionSpecializerTest локально на реальном HBK (BSL_LANGUAGE_SERVER_RUN_HBK_TESTS=true): 12/12 PASS на этой ветке. Включая tabularSectionGetsRecursivePerSectionType и per-MDO/per-collection кейсы — рекурсия по под-владельцам, где работает гард, отрабатывает корректно. Метаданная модель членов не сломана.

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