Skip to content

perf(rust-lsp): share sealed Rust stdlib and isolate per-file work arena - #3211

Merged
DeusData merged 2 commits into
DeusData:mainfrom
GDemay:fix/rust-lsp-scratch-finalize-arena
Dec 6, 2026
Merged

DeusData merged 2 commits into
DeusData:mainfrom
GDemay:fix/rust-lsp-scratch-finalize-arena

Conversation

@GDemay

@GDemay GDemay commented Dec 6, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Every .rs file extracted in Pass 1 calls cbm_run_rust_lsp(a, result, ...) with result->arena (which stays alive across the pipeline until the file result is freed). Previously:

  1. cbm_rust_stdlib_register() re-registered all 276 types and 1,753 functions (580,432 B) into every per-file and cross-file registry AND prematurely called cbm_registry_finalize(reg) (143,632 B of hash buckets/entries), before any local/project definitions were even added.
  2. cbm_rust_build_local_registry() and cbm_run_rust_lsp_with_manifest() allocated the local registry, builder maps (type_idx, trait_names), temporary type indexes, finalized hash tables (143,848 B), and AST walk scratch directly into the caller's result->arena — retaining 946,312 B (~924 KiB) per 8-line Rust file (~1.89 GB across 2,000 Rust files).
  3. cbm_rust_build_cross_registry() allocated temporary CBMRustLSPDef conversion arrays sized to total mixed-language def_count (plus type_idx / trait_names / split return-type buffers) directly into the long-lived shared cross-file registry arena.

Fix

  1. Process-shared sealed Rust stdlib (internal/cbm/lsp/rust_lsp.c, mirroring go_lsp.c):
    • Build and finalize the Rust stdlib + crate seed once per process into a sealed (read_only = true), lock-free CAS-published registry (rust_stdlib_shared()), chained via reg->fallback in both local and cross-file builders (with OOM fallback to direct registration).
    • Remove the premature cbm_registry_finalize(reg) in internal/cbm/lsp/generated/rust_stdlib_data.c.
    • Update all chain-crossing lookups (RustTraitNameIndex, rust_registry_lookup_trait_impl_method, rust_lookup_method_in_trait, rust_find_sole_trait_impl, and the three free-function short-name iterators) to traverse reg -> reg->fallback accurately — walking links directly for Rust method buckets so inherent and distinct trait-impl methods sharing a QN are never falsely shadowed, and storing trait QNs in RustTraitNameIndex so indices stay valid as reg->types grows.
    • Add copy-on-write (rust_ensure_mutable_type) for impl Trait for StdType (and guard method auto-stub registration against reg->fallback) so attaching a project trait to a stdlib type (e.g., std.path.PathBuf with DerefTarget:std.path.Path) preserves existing stdlib metadata and never mutates the shared fallback.
    • Expose a CBM_ENABLE_TEST_SEAMS build counter (cbm_rust_stdlib_test_build_count()) for counted regression testing.
  2. Per-file work_arena isolation (internal/cbm/lsp/rust_lsp.h, internal/cbm/lsp/rust_lsp.c):
    • Run local registry construction, cbm_registry_finalize(&reg), sealing (reg.read_only = true), and rust_lsp_process_file() inside a per-call work_arena.
    • Behaviour note (neg_memo): sealing the per-file registry (reg.read_only = true) in cbm_run_rust_lsp_with_manifest() (and cbm_run_rust_lsp_cross_with_manifest()) also switches on the negative-lookup memos (ctx->neg_memo, gated on reg->read_only) on the Pass-1 per-file path, matching the Tier-2 cross-file path. The negative memos are documented as pure once the registry is sealed, and graph output remains identical.
    • Copy only emitted CBMResolvedCall entries (rust_copy_resolved_calls, also reused by cbm_batch_rust_lsp_cross) and route synthetic macro/operator CBMCall injections (ctx.syn_calls_arena) into the caller's result arena before destroying work_arena. Static literal strategy/reason strings stay zero-copy (while scratch-arena-owned reasons such as lsp_callable_alias / lsp_callable_value_reference are still duplicated) and caller_qn is copied once per enclosing function.
  3. Scratch arenas for builder temporaries:
    • Keep type_idx, trait_names, tail memos, normalized trait lookup keys, split return-type scratch, and cbm_rust_build_cross_registry()'s Rust-only rdefs conversion buffer in lazy scratch arenas destroyed before return.

Verification

Reproduce-first baseline failures on upstream/main (e00c82dc)

  • rustlsp_stdlib_register_defers_finalize FAIL tests/test_rust_lsp.c:6298: reg.func_qn_buckets is not NULL
  • rustlsp_per_file_finalize_keeps_indexes_out_of_result_arena FAIL tests/test_rust_lsp.c:6355: run_bytes (946312) not < build_bytes + idx_bytes (942496)

Deterministic arena measurements (cbm_arena_total())

Metric (8-line Rust fixture, 4 resolved calls) upstream/main (e00c82dc) After (ea7fc5f2) Change
cbm_run_rust_lsp() retained in result->arena 946,312 B 528 B (smaller still after c806337a string dedup) -99.94% (1,792× smaller)
cbm_rust_build_local_registry() retained in caller arena 724,064 B+ (incl. 277 types / 1,756 funcs) 15,192 B (1 type / 3 funcs + shared fallback) -97.9%
cbm_rust_build_cross_registry() (10,000 C + 2 Rust defs) ~1,924,000 B 15,104 B (1 type / 1 func + shared fallback) -99.2%

Throughput on 2 vCPU Ubuntu 24.04 (ASan+UBSan -O1): cbm_run_rust_lsp() completes 200 iterations in 151.54 ms (0.758 ms/file), and a cold 8-thread concurrent race (8 threads × 25 extractions) on g_rust_stdlib_shared passed with 0 errors.

Local gates & tests run

  • Added 6 deterministic tests in tests/test_rust_lsp.c (counters and structural assertions only, no timing):
    • rustlsp_stdlib_register_defers_finalize
    • rustlsp_per_file_work_arena_and_shared_stdlib
    • rustlsp_shared_stdlib_cow_isolates_foreign_trait_impls
    • rustlsp_per_file_work_arena_preserves_synthetic_calls
    • rustlsp_shared_stdlib_builds_once_across_files
    • rustlsp_copy_resolved_calls_dedups_caller_and_preserves_arena_reason
  • ASan + UBSan:
    • rust_lsp, registry, arena, mem, repro_lsp_ordered_signatures, lsp_resolution_probe, repro_reference_precision, repro_lsp_ordered_local (984/984 PASS)
    • rust_lsp, pipeline (748/748 PASS)
  • bash scripts/check-no-test-skips.sh — PASS
  • make -f Makefile.cbm lint-no-suppress lint-memory-core lint-vendored-scanners — PASS
  • bash scripts/check-dco.sh upstream/main..HEAD — PASS

Authored with AI assistance on behalf of @GDemay; commits carry Guillaume's DCO sign-off.

@GDemay
GDemay requested a review from DeusData as a code owner December 6, 2026 10:10
Stop re-registering and double-finalizing the 2,029-entry Rust stdlib +
crate seed into every file's pipeline-lifetime result->arena:

1. Build and finalize the Rust stdlib seed once per process into a sealed
   (`read_only = true`), lock-free CAS-published registry (`rust_stdlib_shared`)
   that local and cross-file registries chain to via `reg->fallback` (matching
   `go_lsp.c`), with copy-on-write on `impl Trait for StdType` so foreign
   impls never mutate the shared fallback.
2. Remove the premature `cbm_registry_finalize(reg)` call at the end of
   `cbm_rust_stdlib_register()` so direct callers never pay for duplicate
   hash-table construction before adding project definitions.
3. Isolate `cbm_run_rust_lsp_with_manifest()` in a per-call `work_arena`
   (sealing the local registry to enable `neg_memo`), deep-copying only
   emitted resolved calls and synthetic macro/operator calls into the caller's
   result arena; move temporary builder maps/conversion buffers in local and
   cross-file registry builders into lazy scratch arenas destroyed before return.

On an 8-line Rust fixture, retained bytes in `result->arena` drop from
946,312 B to 528 B (-99.94%, 1,792x reduction) with identical resolved calls.

Signed-off-by: Guillaume Demay <guillaumedemay@hotmail.fr>
@GDemay
GDemay force-pushed the fix/rust-lsp-scratch-finalize-arena branch from d7cdac1 to ea7fc5f Compare December 6, 2026 10:54
@GDemay GDemay changed the title fix(rust-lsp): finalize per-file Rust LSP registry into scratch idx_arena perf(rust-lsp): share sealed Rust stdlib and isolate per-file work arena Dec 6, 2026
@DeusData

DeusData commented Dec 6, 2026

Copy link
Copy Markdown
Owner

Thank you, @GDemay, this is a substantial one and it holds up well. Building the Rust stdlib once, publishing it with the same acquire/compare-and-swap pattern the Go engine already uses, and reaching it through reg->fallback from each file's own registry keeps the shared registry immutable: ctx->registry stays const, copy-on-write for stdlib types allocates a new embedded array instead of writing in place, and the only new static points at process-lifetime data, never into a per-file arena. The per-file work arena is destroyed only after rust_copy_resolved_calls deep-copies the results, and synthetic calls go to the caller's arena.

We also checked the graph: the six Rust repositories we score with compiler-built call truth (cargo, tokio, meilisearch, diesel, qdrant, tauri) come out with 0 pairs gained and 0 lost, and the full edge sets of cargo (126k edges) and qdrant (267k) are identical.

A few requests before it lands:

  1. A counted "built once" test. The tests check pointer identity across two calls and that the stdlib isn't copied into each file, but nothing counts work. Because of the compare-and-swap, up to T threads may each build a copy on first use, so the real contract is "published once, zero builds afterwards". Could you add a build counter under CBM_ENABLE_TEST_SEAMS and assert that its delta is 0 over four more files after the first, and that each per-file registry's type_count + func_count equals that file's own definitions? Counters only, no timing.
  2. Description: please mention that sealing the per-file registry also switches on the negative memos on the Pass-1 per-file path. They're documented as pure, and the score agrees, but it's a behaviour change worth stating.
  3. Optional: rust_copy_resolved_calls now duplicates caller_qn, strategy and reason for every call. The latter two are usually literals, and caller_qn could be copied once per function. That keeps very call-heavy files from eating into the per-file saving.
  4. Nit: a short comment on why cbm_registry_type_for_update isn't reused here would help the next reader.

Thanks again, great work on the memory side of the Rust engine!

…trings

Address review feedback on DeusData#3211:
- Add a CBM_ENABLE_TEST_SEAMS build counter (cbm_rust_stdlib_test_build_count)
  and a deterministic counted test asserting zero additional stdlib builds
  across four subsequent files and exact per-file type_count + func_count.
- Keep static literal strategy/reason pointers zero-copy in
  rust_copy_resolved_calls (while duplicating scratch-arena-owned reasons)
  and copy caller_qn once per enclosing function.
- Document why rust_ensure_mutable_type does not reuse
  cbm_registry_type_for_update.

Signed-off-by: Guillaume Demay <guillaumedemay@hotmail.fr>
@GDemay

GDemay commented Dec 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review and corpus verification, @DeusData! All four items are addressed in c806337a and the updated PR description:

  1. Counted "built once" test (CBM_ENABLE_TEST_SEAMS): added an atomic build counter (cbm_rust_stdlib_test_build_count()) incremented on shared-stdlib builds (and the OOM fallback) and rustlsp_shared_stdlib_builds_once_across_files, which asserts a 0 counter delta across four subsequent files after the first publish and verifies each per-file registry's type_count, func_count, and type_count + func_count match that file's own definitions (counters only, no timing).
  2. PR description: explicitly noted that sealing the per-file registry (reg.read_only = true) also activates ctx->neg_memo on the Pass-1 per-file path (and standalone per-file cross path).
  3. Avoid redundant string copies in rust_copy_resolved_calls: static literal strategy and reason strings now stay zero-copy (while scratch-arena-owned reasons such as lsp_callable_alias and lsp_callable_value_reference are still duplicated out of src_arena), and caller_qn is copied once per enclosing function via a 4-entry stack cache. Covered by rustlsp_copy_resolved_calls_dedups_caller_and_preserves_arena_reason.
  4. Comment on rust_ensure_mutable_type: documented why cbm_registry_type_for_update isn't reused during construction (unfinalized reg would linearly scan reg->types and leave type_idx stale, it returns NULL on miss instead of auto-stubbing external types, and Rust only replaces embedded_types rather than mutating field_types).

Local verification: scripts/test.sh --suites rust_lsp,registry,arena,mem,repro_lsp_ordered_signatures,lsp_resolution_probe,repro_reference_precision,repro_lsp_ordered_local (984/984 PASS), scripts/test.sh --suites rust_lsp,pipeline (748/748 PASS), scripts/check-no-test-skips.sh, lint-no-suppress, lint-memory-core, lint-vendored-scanners, and check-dco.sh all pass.

Authored with AI assistance on behalf of @GDemay; commits carry Guillaume's DCO sign-off.

@DeusData
DeusData merged commit 8633025 into DeusData:main Dec 6, 2026
26 checks passed
@DeusData

DeusData commented Dec 6, 2026

Copy link
Copy Markdown
Owner

Merged in 8633025. Thank you, @GDemay! The counted test pins "built once" exactly as we hoped: zero stdlib builds after the first publish across five files, with each file's registry holding only its own definitions. The string deduplication is a nice bonus. We re-ran the comparison on the final head, and the six Rust truth repositories and the full cargo and qdrant edge sets, strategy and confidence included, are still identical. Much appreciated!

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