Skip to content

perf(references): компактный индекс поиска вхождения по позиции#4259

Merged
nixel2007 merged 1 commit into
developfrom
perf/reference-index-position-lookup
Jul 11, 2026
Merged

perf(references): компактный индекс поиска вхождения по позиции#4259
nixel2007 merged 1 commit into
developfrom
perf/reference-index-position-lookup

Conversation

@sfaqer

@sfaqer sfaqer commented Jul 11, 2026

Copy link
Copy Markdown
Member

Суть

Вторичный индекс LocationRepository для findByPosition хранил Map<URI, Map<Integer, Set<SymbolOccurrence>>> — отдельное CHM-множество на каждую строку кода с вхождением. На больших проектах это доминирующая статья расхода памяти индекса ссылок.

Заменено на ленивый отсортированный по началу диапазона снимок вхождений документа (SymbolOccurrence[]) + бинарный поиск. Диапазоны вхождений непересекающиеся (инвариант, на который опиралась и старая реализация), поэтому единственный кандидат — вхождение с наибольшим началом диапазона, не превосходящим позицию. Снимок сбрасывается при любом изменении вхождений URI (updateLocation/delete) и пересобирается при первом следующем поиске; updateLocation больше не раскладывает вхождение по строкам.

Замер

analyze УПП (~9 500 модулей, 2.5 млн вхождений), jcmd GC.class_histogram (live-объекты):

Метрика До После
Инстансы ConcurrentHashMap 1.52 млн 14 тыс.
Узлы CHM$Node 10 млн 5.9 млн
Таблицы Node[] 175 МБ 43 МБ
Live heap всего (вместе с #4260 при холодном кэше) 3.76 ГБ 2.94 ГБ

Экономия этого PR — примерно −450 МБ на УПП. SARIF-отчёт эквивалентен базовому (идентичные счётчики по всем правилам, размер байт в байт), время анализа не выросло (2:34 → 2:21).

Проверки

  • полный ./gradlew test: 3 582 теста, 0 упавших (существующие LocationRepositoryTest покрывают разводку двух вхождений на одной строке и сверку бинарного поиска с линейным сканом);
  • функциональная сверка SARIF на УПП (см. выше).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Performance Improvements

    • Improved symbol and reference lookups by using a more efficient position-search strategy.
    • Repeated searches now reuse prepared location data until relevant locations change.
  • Bug Fixes

    • Improved accuracy when identifying the symbol or reference containing a requested position.
    • Location data is refreshed automatically after updates or deletions.

Вторичный индекс LocationRepository для findByPosition хранил
Map<URI, Map<Integer, Set<SymbolOccurrence>>> с отдельным
ConcurrentHashMap-множеством на каждую строку кода с вхождением. На больших
проектах это доминирующая статья расхода памяти индекса ссылок: на УПП
(~9500 модулей, 2.5M вхождений) — ~1.5M инстансов ConcurrentHashMap,
175 МБ таблиц Node[], ~4.6M boxed Integer; суммарно ~450 МБ.

Вместо карты «строка → множество» — ленивый отсортированный по началу
диапазона снимок вхождений документа (SymbolOccurrence[]) и бинарный поиск.
Диапазоны вхождений непересекающиеся, поэтому единственный кандидат —
вхождение с наибольшим началом диапазона, не превосходящим позицию. Снимок
сбрасывается при любом изменении вхождений URI и пересобирается при первом
следующем поиске; updateLocation больше не раскладывает вхождение по строкам.

Замер (analyze УПП, jcmd GC.class_histogram, live): инстансы CHM
1.52M → 14K, узлы CHM 10M → 5.9M, таблицы Node[] 175 → 43 МБ; SARIF-отчёт
эквивалентен базовому (идентичные счётчики правил), время анализа не выросло
(2:34 → 2:21).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

LocationRepository replaces per-line location indexing with lazily built, per-URI sorted snapshots. Position queries use binary search and containment checks, while location updates and deletions invalidate affected snapshots.

Changes

Location lookup

Layer / File(s) Summary
Sorted occurrence snapshot
src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/LocationRepository.java
Adds per-URI sorted SymbolOccurrence[] snapshots and ordering support, replacing the previous line-based index.
Binary position lookup and cache invalidation
src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/LocationRepository.java
Uses binary search to find candidate ranges, verifies containment, and clears cached snapshots after updates or deletions.

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

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% 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
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 Title clearly matches the main change: replacing the position lookup index with a compact, cached search structure.
✨ 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/reference-index-position-lookup

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 Jul 11, 2026

Copy link
Copy Markdown
Contributor

Test Results

 3 612 files  ±0   3 612 suites  ±0   1h 41m 36s ⏱️ + 4m 13s
 3 582 tests ±0   3 564 ✅ ±0   18 💤 ±0  0 ❌ ±0 
21 492 runs  ±0  21 380 ✅ ±0  112 💤 ±0  0 ❌ ±0 

Results for commit 898b04f. ± Comparison against base commit 61640a0.

♻️ This comment has been updated with latest results.

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