Skip to content

perf(references): компактный SymbolOccurrence через short-координаты#4276

Merged
nixel2007 merged 2 commits into
developfrom
perf/symboloccurrence-short-based
Jul 15, 2026
Merged

perf(references): компактный SymbolOccurrence через short-координаты#4276
nixel2007 merged 2 commits into
developfrom
perf/symboloccurrence-short-based

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jul 15, 2026

Copy link
Copy Markdown
Member

Описание

Профилирование analyze на большой конфигурации (cpm, ~13k файлов) показало, что
SymbolOccurrence — крупнейший объект приложения в reference-индексе: ~6 млн экземпляров,
~239 МБ живого heap
(40 байт/шт при сжатых указателях), под доминатором WorkspaceBeanScope
ReferenceIndex.

Координаты диапазона в подавляющем большинстве файлов укладываются в short. Зеркалю уже
принятую в проекте оптимизацию VariableSymbol (Int/Short-реализации):

  • SymbolOccurrencesealed interface с фабрикой of(...);
  • ShortBasedSymbolOccurrence (4×short) для обычных координат, IntBasedSymbolOccurrence
    (4×int) для файлов со строками/столбцами > Short.MAX_VALUE;
  • аксессоры координат по-прежнему возвращают int — публичный API не меняется.

Замеры

JMH (SymbolOccurrenceCreate, -prof gc): 40 → 32 байта/экземпляр (−20 %).

shortBased gc.alloc.rate.norm throughput
false (int) 40.000 B/op 237.8M ops/s
true (short) 32.000 B/op 283.9M ops/s

cpm analyze (develop vs ветка), jmap -histo:live:

метрика before after
SymbolOccurrence (класс) 239 МБ (6.0M×40B) ≈192 МБ (5.85M short×32B + int) → −47 МБ
peak RSS 7734 МБ 7590 МБ (−144)
wall-clock 138.1 с 138.0 с (без изменений)
CPU (JFR ExecutionSample) 29 661 29 336 (шум)

Чистый выигрыш по памяти без стоимости по CPU/wall.

Связанные задачи

Closes

Чеклист

Общие

  • Ветка PR обновлена из develop
  • Отладочные, закомментированные и прочие, не имеющие смысла участки кода удалены
  • Изменения покрыты тестами (SymbolOccurrenceTest + существующие тесты reference-индекса)
  • Обязательные действия перед коммитом выполнены (gradlew precommit) — прогонял test + spotlessCheck

Дополнительно

  • SymbolOccurrenceTest: выбор реализации (short / граница Short.MAX_VALUE / int-фолбэк),
    equals/hashCode/compareTo (в т.ч. кросс-реализационно), реконструкция range()/startPosition().
  • ~2 % вхождений (файлы > 32767 строк/колонок) корректно уходят в IntBased.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Improvements

    • Symbol occurrence handling now automatically uses a compact representation for typical coordinates and supports larger line or character positions when needed.
    • Existing range, position, comparison, equality, and hashing behavior remains consistent across both representations.
  • Tests

    • Added coverage for coordinate selection, range reconstruction, positioning, comparison, equality, and hashing.
  • Refactor

    • Updated the symbol occurrence model to support multiple coordinate representations while preserving the existing creation API.

nixel2007 and others added 2 commits July 15, 2026 18:41
Профилирование analyze на большой конфигурации (cpm, ~13k файлов) показало, что
SymbolOccurrence — крупнейший объект приложения в reference-индексе: ~6 млн
экземпляров, ~239 МБ живого heap (40 байт/шт при сжатых указателях).

Координаты диапазона (строка/столбец начала и конца) в подавляющем большинстве
файлов укладываются в short. Зеркалим уже принятую в проекте оптимизацию
VariableSymbol (Int/Short-реализации): SymbolOccurrence становится sealed-интерфейсом
с фабрикой of(...), которая выбирает ShortBasedSymbolOccurrence (4×short) для обычных
координат и IntBasedSymbolOccurrence (4×int) для файлов со строками/столбцами
> Short.MAX_VALUE. Аксессоры координат по-прежнему возвращают int, публичный API не
меняется.

JOL: 40 → 32 байта на экземпляр (-20%); на 6 млн вхождений ≈ -48 МБ живого heap.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HLvkKQCwBjTHwuZ4EGBQK6
Микробенчмарк создания SymbolOccurrence через фабрику of(): параметр shortBased
переключает координаты между укладывающимися в short и выходящими за его пределы.
С -prof gc подтверждает 40 → 32 байта на экземпляр (gc.alloc.rate.norm).

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

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

SymbolOccurrence was changed from a record to a sealed interface with short- and int-based record implementations. Factory methods now select storage by coordinate bounds, with tests and a JMH benchmark covering both representations.

Changes

Symbol occurrence storage

Layer / File(s) Summary
Occurrence contract and factory
src/main/.../references/model/SymbolOccurrence.java
Defines shared accessors and default behavior, exposes the comparator, and selects short- or int-based implementations through overloaded factories.
Coordinate storage implementations
src/main/.../references/model/ShortBasedSymbolOccurrence.java, src/main/.../references/model/IntBasedSymbolOccurrence.java
Adds record implementations using short or int coordinate fields while exposing integer accessors.
Selection validation and benchmark
src/test/.../references/model/SymbolOccurrenceTest.java, src/jmh/.../references/SymbolOccurrenceCreate.java
Tests implementation selection, boundaries, reconstructed positions, equality, hashing, and ordering; benchmarks creation for both representations.

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

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant SymbolOccurrence
  participant ShortBasedSymbolOccurrence
  participant IntBasedSymbolOccurrence

  Caller->>SymbolOccurrence: of(occurrenceType, symbol, uri, coordinates)
  SymbolOccurrence->>SymbolOccurrence: evaluate fitsShort(coordinates)
  alt coordinates fit short
    SymbolOccurrence->>ShortBasedSymbolOccurrence: construct occurrence
    ShortBasedSymbolOccurrence-->>Caller: SymbolOccurrence
  else coordinates exceed short
    SymbolOccurrence->>IntBasedSymbolOccurrence: construct occurrence
    IntBasedSymbolOccurrence-->>Caller: SymbolOccurrence
  end
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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: compacting SymbolOccurrence storage with short coordinates in references.
✨ 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/symboloccurrence-short-based

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.

🧹 Nitpick comments (1)
src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/ShortBasedSymbolOccurrence.java (1)

46-54: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make record implementations package-private to enforce encapsulation.

Both records are strictly meant to be instantiated via the SymbolOccurrence.of() factory, which fully abstracts the storage selection. Keeping the records public allows direct instantiation from outside the package, which bypasses the factory and could lead to logically identical occurrences having different runtime classes (resulting in inconsistent equals() and hashCode() behavior despite compareTo() == 0).

Since the SymbolOccurrence sealed interface is public, its permitted implementations can securely safely remain package-private to hide the internal storage optimizations.

  • src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/ShortBasedSymbolOccurrence.java#L46-L54: remove the public modifier to make the record package-private.
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/IntBasedSymbolOccurrence.java#L40-L48: remove the public modifier to make the record package-private.
🤖 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/references/model/ShortBasedSymbolOccurrence.java`
around lines 46 - 54, Make both record implementations package-private by
removing the public modifier from ShortBasedSymbolOccurrence in
src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/ShortBasedSymbolOccurrence.java:46-54
and IntBasedSymbolOccurrence in
src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/IntBasedSymbolOccurrence.java:40-48,
ensuring callers use the public SymbolOccurrence.of() factory.
🤖 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/references/model/ShortBasedSymbolOccurrence.java`:
- Around line 46-54: Make both record implementations package-private by
removing the public modifier from ShortBasedSymbolOccurrence in
src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/ShortBasedSymbolOccurrence.java:46-54
and IntBasedSymbolOccurrence in
src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/IntBasedSymbolOccurrence.java:40-48,
ensuring callers use the public SymbolOccurrence.of() factory.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b5d6d6a4-88ff-463f-852d-5c2f5b7b642a

📥 Commits

Reviewing files that changed from the base of the PR and between 308c22e and 85c3ca0.

📒 Files selected for processing (5)
  • src/jmh/java/com/github/_1c_syntax/bsl/languageserver/references/SymbolOccurrenceCreate.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/IntBasedSymbolOccurrence.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/ShortBasedSymbolOccurrence.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/SymbolOccurrence.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/references/model/SymbolOccurrenceTest.java

@nixel2007
nixel2007 enabled auto-merge July 15, 2026 17:07
@sonarqubecloud

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown
Contributor

Test Results

 3 648 files  + 6   3 648 suites  +6   2h 2m 0s ⏱️ + 26m 41s
 3 616 tests + 6   3 598 ✅ + 6   18 💤 ±0  0 ❌ ±0 
21 696 runs  +36  21 584 ✅ +36  112 💤 ±0  0 ❌ ±0 

Results for commit 85c3ca0. ± Comparison against base commit 308c22e.

@nixel2007
nixel2007 merged commit 3ea4712 into develop Jul 15, 2026
43 checks passed
@nixel2007
nixel2007 deleted the perf/symboloccurrence-short-based branch July 15, 2026 17:35
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