Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
Fix O(n^2) overload resolution in the C/C++ cross-LSP registry (#410)
Martin Vogel02d27743d9b6
diff --git a/internal/cbm/lsp/type_registry.c b/internal/cbm/lsp/type_registry.cindex 1fc9c011f..3d00cf4da 100644--- a/internal/cbm/lsp/type_registry.c+++ b/internal/cbm/lsp/type_registry.c@@ -320,6 +320,49 @@ const CBMRegisteredFunc* cbm_registry_lookup_method_by_args(const CBMTypeRegistrconst CBMRegisteredFunc* first_match = NULL;const CBMRegisteredFunc* range_match = NULL;++ // Hashed path when finalized: walk only the (receiver,name) overload chain+ // instead of every registered func. The chain holds exactly the funcs whose+ // (receiver_type, short_name) hash to this key, so results are identical to+ // the linear scan below — just O(overloads) instead of O(func_count). This+ // matters on project-wide registries: a header with thousands of method+ // calls × tens of thousands of registered funcs was O(calls×funcs) (#410).+ if (reg->method_buckets && reg->method_bucket_count > 0) {+ // The chain is in descending registration order, but the linear scan+ // resolves ties by LOWEST registration index (first exact match, else+ // first range match, else first match). Track the lowest index in each+ // category so the hashed path returns the identical func.+ int exact_pi = -1, range_pi = -1, first_pi = -1;+ uint64_t h = fnv1a_pair(receiver_qn, method_name);+ int slot = (int)(h & (uint64_t)(reg->method_bucket_count - 1));+ for (int idx = reg->method_buckets[slot]; idx >= 0;+ idx = reg->method_entries[idx].next_index) {+ if (reg->method_entries[idx].hash != h) continue;+ int pi = reg->method_entries[idx].payload_index;+ const CBMRegisteredFunc* f = ®->funcs[pi];+ if (!f->receiver_type || !f->short_name ||+ strcmp(f->receiver_type, receiver_qn) != 0 ||+ strcmp(f->short_name, method_name) != 0) continue;+ if (first_pi < 0 || pi < first_pi) first_pi = pi;+ int pc = count_func_params(f);+ if (pc == arg_count) {+ if (exact_pi < 0 || pi < exact_pi) exact_pi = pi;+ continue;+ }+ int min_pc = (f->min_params >= 0) ? f->min_params : pc;+ if (arg_count >= min_pc && arg_count <= pc) {+ if (range_pi < 0 || pi < range_pi) range_pi = pi;+ }+ }+ int sel = exact_pi >= 0 ? exact_pi : (range_pi >= 0 ? range_pi : first_pi);+ if (sel >= 0) return ®->funcs[sel];+ if (reg->fallback) {+ return cbm_registry_lookup_method_by_args(reg->fallback, receiver_qn, method_name,+ arg_count);+ }+ return NULL;+ }+for (int i = 0; i < reg->func_count; i++) {const CBMRegisteredFunc* f = ®->funcs[i];if (f->receiver_type && f->short_name &&@@ -423,6 +466,44 @@ const CBMRegisteredFunc* cbm_registry_lookup_method_by_types(const CBMTypeRegistint best_score = 0;const CBMRegisteredFunc* first_match = NULL;+ // Hashed path when finalized: score only the (receiver,name) overload chain+ // instead of every registered func. Identical result set to the linear scan+ // below (same membership test), but O(overloads) instead of O(func_count) —+ // the hot per-call lookup that made large-header resolve O(calls×funcs)+ // (#410: a 10989-def header took ~34s/file in the resolve phase).+ if (reg->method_buckets && reg->method_bucket_count > 0) {+ // The chain is in descending registration order. The linear scan keeps+ // the first (lowest-index) func at the best score (strict '>'), and+ // falls back to the lowest-index match. Track lowest index per category+ // so the hashed path returns the identical func.+ int best_pi = -1, first_pi = -1;+ uint64_t h = fnv1a_pair(receiver_qn, method_name);+ int slot = (int)(h & (uint64_t)(reg->method_bucket_count - 1));+ for (int idx = reg->method_buckets[slot]; idx >= 0;+ idx = reg->method_entries[idx].next_index) {+ if (reg->method_entries[idx].hash != h) continue;+ int pi = reg->method_entries[idx].payload_index;+ const CBMRegisteredFunc* f = ®->funcs[pi];+ if (!f->receiver_type || !f->short_name ||+ strcmp(f->receiver_type, receiver_qn) != 0 ||+ strcmp(f->short_name, method_name) != 0) continue;+ if (first_pi < 0 || pi < first_pi) first_pi = pi;+ int s = score_overload_match(f, arg_types, arg_count);+ if (s > best_score || (s == best_score && best_pi >= 0 && pi < best_pi)) {+ best_score = s; best_pi = pi;+ }+ }+ // best_score starts at 0; a score of 0 means "wrong arg count" → no+ // match, exactly as the linear scan (which never sets best on s==0).+ int sel = (best_pi >= 0 && best_score > 0) ? best_pi : first_pi;+ if (sel >= 0) return ®->funcs[sel];+ if (reg->fallback) {+ return cbm_registry_lookup_method_by_types(reg->fallback, receiver_qn, method_name,+ arg_types, arg_count);+ }+ return NULL;+ }+for (int i = 0; i < reg->func_count; i++) {const CBMRegisteredFunc* f = ®->funcs[i];if (f->receiver_type && f->short_name &&@@ -461,6 +542,34 @@ const CBMRegisteredFunc* cbm_registry_lookup_symbol_by_types(const CBMTypeRegistint best_score = 0;const CBMRegisteredFunc* first_match = NULL;+ // Hashed path when finalized: walk only the QN overload chain. The func QN+ // index chains every func sharing a qualified_name, so this scores the exact+ // same overload set as the linear scan, in O(overloads) not O(func_count).+ if (reg->func_qn_buckets && reg->func_qn_bucket_count > 0) {+ int best_pi = -1, first_pi = -1;+ uint64_t h = fnv1a(buf);+ int slot = (int)(h & (uint64_t)(reg->func_qn_bucket_count - 1));+ for (int idx = reg->func_qn_buckets[slot]; idx >= 0;+ idx = reg->func_qn_entries[idx].next_index) {+ if (reg->func_qn_entries[idx].hash != h) continue;+ int pi = reg->func_qn_entries[idx].payload_index;+ const CBMRegisteredFunc* f = ®->funcs[pi];+ if (!f->qualified_name || strcmp(f->qualified_name, buf) != 0) continue;+ if (first_pi < 0 || pi < first_pi) first_pi = pi;+ int s = score_overload_match(f, arg_types, arg_count);+ if (s > best_score || (s == best_score && best_pi >= 0 && pi < best_pi)) {+ best_score = s; best_pi = pi;+ }+ }+ int sel = (best_pi >= 0 && best_score > 0) ? best_pi : first_pi;+ if (sel >= 0) return ®->funcs[sel];+ if (reg->fallback) {+ return cbm_registry_lookup_symbol_by_types(reg->fallback, package_qn, name,+ arg_types, arg_count);+ }+ return NULL;+ }+for (int i = 0; i < reg->func_count; i++) {const CBMRegisteredFunc* f = ®->funcs[i];if (strcmp(f->qualified_name, buf) == 0) {@@ -493,6 +602,38 @@ const CBMRegisteredFunc* cbm_registry_lookup_symbol_by_args(const CBMTypeRegistrconst CBMRegisteredFunc* first_match = NULL;const CBMRegisteredFunc* range_match = NULL;++ // Hashed path when finalized: walk only the QN overload chain (see+ // cbm_registry_lookup_symbol_by_types). O(overloads) not O(func_count).+ if (reg->func_qn_buckets && reg->func_qn_bucket_count > 0) {+ int exact_pi = -1, range_pi = -1, first_pi = -1;+ uint64_t h = fnv1a(buf);+ int slot = (int)(h & (uint64_t)(reg->func_qn_bucket_count - 1));+ for (int idx = reg->func_qn_buckets[slot]; idx >= 0;+ idx = reg->func_qn_entries[idx].next_index) {+ if (reg->func_qn_entries[idx].hash != h) continue;+ int pi = reg->func_qn_entries[idx].payload_index;+ const CBMRegisteredFunc* f = ®->funcs[pi];+ if (!f->qualified_name || strcmp(f->qualified_name, buf) != 0) continue;+ if (first_pi < 0 || pi < first_pi) first_pi = pi;+ int pc = count_func_params(f);+ if (pc == arg_count) {+ if (exact_pi < 0 || pi < exact_pi) exact_pi = pi;+ continue;+ }+ int min_pc = (f->min_params >= 0) ? f->min_params : pc;+ if (arg_count >= min_pc && arg_count <= pc) {+ if (range_pi < 0 || pi < range_pi) range_pi = pi;+ }+ }+ int sel = exact_pi >= 0 ? exact_pi : (range_pi >= 0 ? range_pi : first_pi);+ if (sel >= 0) return ®->funcs[sel];+ if (reg->fallback) {+ return cbm_registry_lookup_symbol_by_args(reg->fallback, package_qn, name, arg_count);+ }+ return NULL;+ }+for (int i = 0; i < reg->func_count; i++) {const CBMRegisteredFunc* f = ®->funcs[i];if (strcmp(f->qualified_name, buf) == 0) {diff --git a/scripts/test.sh b/scripts/test.shindex 918033a9a..cfe3cc265 100755--- a/scripts/test.sh+++ b/scripts/test.sh@@ -60,4 +60,13 @@ scripts/clean.sh# Step 2 + 3: Build and run tests (with arch prefix on macOS)$ARCH_PREFIX make -j"$NPROC" -f Makefile.cbm test $MAKE_ARGS+# Step 4: C++ large-TU index-hang regression guard (#410). Runs the PROD binary+# in a subprocess with a wall-clock timeout — a hang must fail, not block the run.+# Opt-in via CBM_RUN_HANG_TEST=1 (it needs the prod binary, which the ASan unit+# run above does not build). Skipped by default so the fast unit run stays fast.+if [ "${CBM_RUN_HANG_TEST:-0}" = "1" ]; then+ echo "=== Step 4: C++ index-hang regression (#410) ==="+ bash "$ROOT/tests/test_cpp_index_hang.sh"+fi+echo "=== All tests passed ==="diff --git a/tests/test_cpp_index_hang.sh b/tests/test_cpp_index_hang.shnew file mode 100755index 000000000..0c23e6b9a--- /dev/null+++ b/tests/test_cpp_index_hang.sh@@ -0,0 +1,112 @@+#!/usr/bin/env bash+# test_cpp_index_hang.sh — SCALE-TIER regression guard for issue #410:+# "won't finish indexing big C++ codebases".+#+# Root cause: the C/C++ cross-LSP resolve looked up method/symbol overloads with+# a LINEAR scan over the whole project's registered funcs (cbm_registry_lookup_+# method_by_types / _by_args / lookup_symbol_by_* in type_registry.c). On a large+# translation unit (the reported Model.hpp had 10989 defs) this made the per-file+# resolve O(calls × project_funcs) — ~34s for ONE header — so a repo with many+# big headers never finished indexing.+#+# The hang only manifests at SCALE, so this test:+# 1. generates a single large synthetic C++ header whose classes call each+# other's methods (thousands of method-call sites + thousands of registered+# methods → triggers the O(n^2) before the fix),+# 2. runs the PROD binary `cli index_repository` on it in a SUBPROCESS with a+# hard wall-clock timeout (perl alarm — no coreutils `timeout` on macOS),+# 3. FAILS if indexing exceeds the timeout (i.e. hangs), passes if it finishes.+#+# The fixture is tuned to complete in a couple of seconds AFTER the fix while+# blowing well past the timeout on the unfixed O(n^2) code.+#+# This mirrors the fork+WIFSIGNALED crash-isolation pattern, but for a hang:+# a runaway index must never block the test runner.+#+# Usage:+# bash tests/test_cpp_index_hang.sh+# CBM_HANG_TIMEOUT=60 CBM_HANG_CLASSES=6000 bash tests/test_cpp_index_hang.sh++set -uo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+BIN="$ROOT/build/c/codebase-memory-mcp"++# Number of classes/methods in the synthetic TU. Each class has a method that+# calls the next class's method by value-of-known-type → routes through the+# linear overload-lookup hot path. 5000 is enough to make the unfixed code take+# minutes while the fixed code stays well under a couple of seconds.+CLASSES="${CBM_HANG_CLASSES:-5000}"+# Wall-clock budget. The fixed index finishes in ~1-3s; the unfixed O(n^2) needs+# minutes. 45s gives huge head-room for the fixed path on a loaded laptop while+# still catching the hang.+TIMEOUT="${CBM_HANG_TIMEOUT:-45}"++if [ ! -x "$BIN" ]; then+ echo "[hang] building prod binary ..."+ (cd "$ROOT" && ./scripts/build.sh) || { echo "[hang] FAIL — build failed"; exit 1; }+fi+[ -x "$BIN" ] || { echo "[hang] FAIL — binary not found at $BIN"; exit 1; }++WORK="$(mktemp -d)"+trap 'rm -rf "$WORK"; rm -f "$HOME/.cache/codebase-memory-mcp/$PROJ.db"* 2>/dev/null' EXIT++HDR="$WORK/model.hpp"+SRC="$WORK/main.cpp"++echo "[hang] generating synthetic TU: $CLASSES classes/methods ..."+# Header: a chain of classes C0..CN. Each Ck has a method work() that constructs+# the next class and calls its work(). Member calls (obj.work()) on a known local+# type go through cbm_registry_lookup_method_by_types — the O(project_funcs) scan.+{+ echo '#pragma once'+ echo 'namespace model {'+ for ((k=0; k<CLASSES; k++)); do+ next=$(( (k + 1) % CLASSES ))+ printf 'class C%d {\n public:\n int work();\n int run() { C%d n; return n.work(); }\n};\n' "$k" "$next"+ done+ echo '} // namespace model'+} > "$HDR"++# A .cpp that defines the out-of-line work() bodies, each calling the next+# class's run() — more cross-method call sites to hammer the resolve walk.+{+ echo '#include "model.hpp"'+ echo 'namespace model {'+ for ((k=0; k<CLASSES; k++)); do+ next=$(( (k + 1) % CLASSES ))+ printf 'int C%d::work() { C%d m; return m.run(); }\n' "$k" "$next"+ done+ echo '} // namespace model'+} > "$SRC"++PROJ="$(printf '%s' "$WORK" | sed 's#^/##; s#[^A-Za-z0-9._-]#-#g')"+rm -f "$HOME/.cache/codebase-memory-mcp/$PROJ.db"* 2>/dev/null++echo "[hang] indexing with ${TIMEOUT}s wall-clock budget ..."+START=$(date +%s)+# perl alarm = portable `timeout`: SIGALRM after $TIMEOUT seconds. exec replaces+# the perl process with the binary so the alarm fires against the index run.+perl -e 'alarm shift; exec @ARGV or exit 127' \+ "$TIMEOUT" "$BIN" cli index_repository "{\"repo_path\":\"$WORK\"}" >/dev/null 2>&1+RC=$?+END=$(date +%s)+ELAPSED=$(( END - START ))++# perl's exec'd child inherits the alarm; SIGALRM (14) → exit code 128+14 = 142.+if [ "$RC" -eq 142 ]; then+ echo "[hang] FAIL — index_repository did not finish within ${TIMEOUT}s (HANG, #410 regression)"+ echo "[hang] elapsed=${ELAPSED}s classes=${CLASSES}"+ exit 1+fi+if [ "$RC" -ge 128 ]; then+ echo "[hang] FAIL — index crashed by signal (exit=$RC, signal=$((RC - 128)))"+ exit 1+fi+if [ "$RC" -ne 0 ]; then+ echo "[hang] FAIL — index_repository exited non-zero (exit=$RC)"+ exit 1+fi++echo "[hang] PASS — index finished in ${ELAPSED}s (<${TIMEOUT}s budget), classes=${CLASSES}"+exit 0