Skip to content

perf(semantic_db): a name-keyed member use reads the owner's by-name bucket - #1458

Open
mareklangiewicz wants to merge 3 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:perf-member-use-named
Open

mareklangiewicz wants to merge 3 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:perf-member-use-named

Conversation

@mareklangiewicz

Copy link
Copy Markdown
Contributor

Summary

Resolving a member use is cubic in the size of a module class. resolve_member_id ends by scanning every member of each resolved owner for the one whose key matches, and members_of_owner merges a module owner's canonical bucket with a nested iter().any dedup, O(N²) per call:

build_file_references          once per member use: N
  resolve_member_id
    members_of_owner           every member of the owner
      merge_canonical_members  raw × canonical dedup: N²

A Name key now reads the owner's by-name bucket:

 // semantic_db/query.rs, resolve_member_id
     for resolved in resolve_owner_set(db, owner.clone()) {
-        for member in members_of_owner(db, resolved).iter() {
+        let members = match &member_use.key {
+            LuaMemberKey::Name(name) => members_of_owner_named(db, resolved, name.clone()),
+            _ => members_of_owner(db, resolved),
+        };
+        for member in members.iter() {

The two lists hold the same members. Each OwnerMembers bucket's by_key lists hold the same members as all, in the same insertion order, keyed by the member's own LuaMemberKey. The canonical bucket is built the same way, and the merge dedups by (id, file_id), so filtering by key commutes with it. The key check inside the loop stays. Other keys keep the full scan.

Evidence

emmylua_check with an empty config on one generated file: ---@class C, ---@field x integer, local C = {}, N one-line methods, return C. CPU time, one run each:

N method body main 1460735 this PR
2000 return 1 (no member read) 0.34 s 0.34 s
1000 return C.x 0.65 s 0.26 s
2000 return C.x 3.55 s 0.42 s
2000 return self.x 3.75 s 0.81 s
4000 return self.x 25.61 s 1.99 s
  • Before: test_many_member_reads_on_a_module_class_stay_fast (new, check/test/assign_type_mismatch_test.rs) has 1500 self.x methods and a 5 s ntest timeout. It asserts that the one assign-type-mismatch is on local s = C.x (---@type string), so C.x still resolves to its @field. With main's query.rs the test binary timed out at 5.00 s in 5 of 5 runs.
    After: it passes in 0.71 to 0.74 s (debug build). All 1994 emmylua_code_analysis tests pass, as do cargo fmt and clippy.
  • Plugin corpus (emmylua_check, empty config, 54 Neovim plugin trees that finish on main): 57305 → 57306. The 11 changed lines are assign-type-mismatch on record literals in blink.cmp, diffview.nvim and gitsigns.nvim, files where main itself varies run to run (three runs of main differ by 9 to 13 hits there). Total time over those trees, one run each: 54.0 s → 53.4 s.

Merge Danger

Door: two-way

A different list from the same index on one existing path. Reverting it brings back the scan.

Blast Radius: member resolution

The named bucket is the full list filtered by key, so the member found is the same. One difference is possible in principle: when an owner's by-name index bucket is empty, the named path falls back to the owner file's FileFacts, while the full path does so only when the whole owner bucket is empty. The corpus above shows no changed diagnostic.

🤖 Generated with Claude Code

https://claude.ai/code/session_018NxUUPwEiW13FMdt1RXj4N

…bucket

`resolve_member_id`'s last loop scanned every member of each resolved owner
to find the one whose key matches, and `members_of_owner` merges a module
owner's canonical bucket with a nested `iter().any` dedup, O(N^2) per call.
N member reads on an N-member module class were O(N^3) per file: 4000
methods reading `self.x` took 25.6 s, now 2.0 s.

For a `Name` key it now asks `members_of_owner_named`. Each owner bucket's
by-key list holds the same members, in the same order, as its full list
filtered by key, and the canonical merge dedups by `(id, file_id)`, so
filtering commutes with it. Other keys keep the full scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUPwEiW13FMdt1RXj4N

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary

The performance optimization is sound in principle: switching a name-keyed lookup from a full scan to a by-name bucket is the right fix for the O(N³) blowup. The test is well-constructed and the enable_only guard is a nice touch for debug builds. A few points warrant attention.

1. Behavioral equivalence assumption is unverified (correctness risk — medium)

The comment asserts members_of_owner_named yields "the same members, in the same order" as the full list filtered by name. This is the critical invariant, but the diff doesn't show the implementation of members_of_owner_named. If the bucket is, e.g., an IndexMap keyed differently, a HashSet, or sorted differently from members_of_owner, the returned order could differ.

  • Impact: the member.id.clone() return and downstream member_facts selection may pick a different member from before when multiple members share a name (overloads, merged declarations, base/derived members with the same name). Resolution results could silently change.
  • Recommendation: confirm ordering parity explicitly, and ideally add a test with duplicate method names across declarations to lock it in.

2. name.clone() inside the per-use loop (minor perf regression risk)

LuaMemberKey::Name(name) => members_of_owner_named(db, resolved, name.clone()),

This is inside a loop over resolve_owner_set, so the name is cloned once per owner. That's usually cheap, but consider passing &str (or &LuaMemberKey) if members_of_owner_named can take a borrowed key — it avoids per-owner allocation in what is a hot path (this is the very function being optimized for performance).

3. The test doesn't actually prove the old code was O(N³) / that this is a regression guard for the right thing

  • The test validates correctness (C.x resolves to the @field, one diagnostic at the expected line) and speed (#[ntest::timeout(5000)]).
  • Concern: a 5s timeout is very loose. The stated failure mode was O(N³) over 1500 methods; if the optimization regressed to an intermediate O(N²), the test might still pass comfortably. Consider tightening the class size or timeout so the test fails fast on a real regression. Wall-clock timeouts are also flaky on loaded CI machines — a few microseconds-per-op bound is more robust, or at minimum document the expected margin.
  • The comment "3 header lines … then local s = C.x" assumes exact line counting. assert_eq!(lines, [METHODS + 4]) is correct given the constructed src, but it's brittle to any future header change. Fine for a test, just note the coupling.

4. Test relies on enable_only side effect — isolation

ws.analysis.diagnostic.enable_only(...) mutates the analysis config on the shared ws. Since ws is local to the test this is fine, but if VirtualWorkspace is reused/cached across tests, this could leak state. Confirm new() gives a fresh instance (it appears to, so likely fine).

5. Missing coverage for the fallback path

The _ => members_of_owner(db, resolved) arm (index keys, method keys, etc.) is unchanged but now adjacent to new logic. Since the hot path was name-based, existing tests likely cover index keys — but it's worth a quick check that no test regressed on member resolution for integer/other keys, given this function is central.

6. Minor style: comment density

The two comments are helpful and accurate. Just make sure the "same members, in the same order" claim in the code comment matches reality (see #1) — an inaccurate comment here is worse than none, as it asserts an invariant reviewers will trust.


Verdict

Direction is correct and the fix is valuable. Blocking concern: verify ordering/identity parity of members_of_owner_named vs. filtered members_of_owner (especially under duplicate names), and consider tightening the timeout to make the regression guard meaningful. The clone() and test-brittleness items are non-blocking nits.

…d by name

Pins the invariant `resolve_member_id` now relies on, for a module owner with
a member another file adds through `require` (so the canonical merge runs),
repeated `f` declarations, and an `@field` beside a runtime member of one name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUPwEiW13FMdt1RXj4N
@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Thanks. Point by point:

  1. Order and equivalence. Now pinned by a test, p10_named_members_are_the_full_list_filtered_by_name (5350e92). For a module owner with a member that another file adds through require (the test asserts that it reaches the owner, so the canonical merge runs), repeated C:f declarations, and an @field x beside a runtime C.x, members_of_owner_named(owner, n) equals members_of_owner(owner) filtered by n, in order, as (file_id, id) pairs. This follows from the index: each OwnerMembers bucket builds its by_key lists from the same insertion order as all, keyed by the member's own LuaMemberKey, and merge_canonical_members dedups by (id, file_id). The key check inside the loop stays.
  2. name.clone() is a SmolStr clone: inline for short names, a refcount bump otherwise, with no allocation. It happens once per resolved owner (usually one or two), not once per member.
  3. Timeout. It is not loose for this case. With main's query.rs the test binary timed out at 5.00 s in 5 of 5 runs; with this PR it takes 0.71 to 0.74 s (debug). A quadratic regression would show at 1500 methods as well: main's 2000-method self.x file is 3.75 s in release. The line assertion is tied to the generated source on purpose: it is what proves the one hit is C.x.
  4. VirtualWorkspace::new() builds a fresh workspace per test, so enable_only stays local to it.
  5. Other keys keep members_of_owner unchanged. All 1994 emmylua_code_analysis tests pass, and the plugin corpus shows no change beyond main's own run-to-run noise (see the description).

@mareklangiewicz
mareklangiewicz marked this pull request as ready for review November 24, 2026 13:36
@CppCXY

CppCXY commented Nov 30, 2026

Copy link
Copy Markdown
Member

please resolve the conflict

Upstream deleted semantic_db/phase_tests/ (92d2e12, "clean and
migrate test"); this branch's p10 test
(p10_named_members_are_the_full_list_filtered_by_name) moves to
semantic_db/tests/query_tests.rs as
test_named_members_are_the_full_list_filtered_by_name, on that file's
setup() plus the main workspace at portable_test_root(). In
assign_type_mismatch_test.rs both sides appended a test; kept both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUQZHt6a5njk8trY5BZ
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