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(pipeline): score importance over the staging store on the delta route
Martin Vogel396ac348b5ab
diff --git a/src/pipeline/pass_importance.c b/src/pipeline/pass_importance.cindex a727ddee0..c544d0a10 100644--- a/src/pipeline/pass_importance.c+++ b/src/pipeline/pass_importance.c@@ -60,7 +60,9 @@#include "foundation/hash_table.h"#include "foundation/log.h"#include "foundation/compat.h"+#include "store/store.h"#include "cbm.h"+#include "sqlite3.h"#include <ctype.h>#include <math.h>@@ -75,6 +77,7 @@* Never reset here: callers snapshot before/after so nested runs compose. */_Atomic uint64_t g_importance_nodes = 0;_Atomic uint64_t g_importance_name_visits = 0;+_Atomic uint64_t g_importance_store_rows = 0;enum {CBM_IMPORTANCE_GENERIC_MIN_FILES = 5, /* name defined in >= N files -> generic */@@ -212,37 +215,39 @@ static const char *imp_find_key(const char *json, const char *key) {return NULL;}-/* Write the numeric "importance" key into a node's properties JSON object.+/* Produce a copy of `json` carrying the numeric "importance" key set to+ * `score`, or NULL if `json` is not a JSON object (caller leaves it alone) or+ * on allocation failure. Caller owns the result.*- * IDEMPOTENT BY CONTRACT. The incremental path rehydrates nodes straight out- * of the store (cbm_gbuf_load_from_db), and those nodes ALREADY carry an- * "importance" key from the previous run. A pure append would emit- * {"importance":1.0,...,"importance":2.0} — silent property corruption that- * no build or schema check would catch. So: overwrite an existing key in- * place, append only when the key is genuinely absent.+ * IDEMPOTENT BY CONTRACT. Nodes reach this function already carrying an+ * "importance" key on every re-scoring route: the legacy-partial incremental+ * path rehydrates them via cbm_gbuf_load_from_db, and the store-level+ * recompute reads them straight out of SQLite. A pure append would emit+ * {"importance":1.0,...,"importance":2.0} — silent property corruption that no+ * build or schema check would catch. So: overwrite an existing key in place,+ * append only when the key is genuinely absent.*- * A properties_json that is not a JSON object is left untouched. */-void cbm_pipeline_importance_append_prop(cbm_gbuf_node_t *node, double score) {- if (!node) {- return;- }- const char *old = node->properties_json ? node->properties_json : "{}";+ * SINGLE DEFINITION. Both scoring routes (the in-memory gbuf pass and the+ * SQL-level store recompute) write through this one function, so the JSON+ * shape cannot drift between them. */+char *cbm_pipeline_importance_set_prop(const char *json, double score) {+ const char *old = json ? json : "{}";size_t olen = strlen(old);if (olen < 2 || old[olen - 1] != '}') {- return; /* not a JSON object — leave untouched */+ return NULL; /* not a JSON object — leave untouched */}char val[CBM_SZ_32];int vn = snprintf(val, sizeof(val), "%.6f", score);if (vn < 0 || (size_t)vn >= sizeof(val)) {- return;+ return NULL;}const char *k = imp_find_key(old, "importance");if (k) {const char *colon = strchr(k, ':');if (!colon) {- return; /* imp_find_key guarantees one, but never trust a raw scan */+ return NULL; /* imp_find_key guarantees one, but never trust a raw scan */}const char *v = colon + 1;while (isspace((unsigned char)*v)) {@@ -250,37 +255,77 @@ void cbm_pipeline_importance_append_prop(cbm_gbuf_node_t *node, double score) {}const char *vend = imp_value_end(v);if (!vend) {- return;+ return NULL;}size_t head = (size_t)(v - old);size_t tail = strlen(vend);char *neu = malloc(head + (size_t)vn + tail + 1);if (!neu) {- return;+ return NULL;}memcpy(neu, old, head);memcpy(neu + head, val, (size_t)vn);memcpy(neu + head + (size_t)vn, vend, tail + 1);- free(node->properties_json);- node->properties_json = neu;- return;+ return neu;}char frag[CBM_SZ_64];int fn = snprintf(frag, sizeof(frag), "%s\"importance\":%s}", (olen == 2) ? "" : ",", val);if (fn < 0 || (size_t)fn >= sizeof(frag)) {- return;+ return NULL;}char *neu = malloc(olen - 1 + (size_t)fn + 1);if (!neu) {- return;+ return NULL;}memcpy(neu, old, olen - 1); /* copy without the trailing '}' */memcpy(neu + olen - 1, frag, (size_t)fn + 1);+ return neu;+}++/* gbuf-node convenience wrapper around cbm_pipeline_importance_set_prop. */+void cbm_pipeline_importance_append_prop(cbm_gbuf_node_t *node, double score) {+ if (!node) {+ return;+ }+ char *neu = cbm_pipeline_importance_set_prop(node->properties_json, score);+ if (!neu) {+ return;+ }free(node->properties_json);node->properties_json = neu;}+/* ── The scoring rule ─────────────────────────────────────────────────+ *+ * SINGLE DEFINITION, deliberately. There are two routes that score nodes —+ * the in-memory gbuf pass (full index, legacy-partial incremental) and the+ * SQL-level recompute over the staging store (closure-delta incremental) —+ * and they gather their inputs very differently. Only the GATHERING differs;+ * the rule itself lives here alone, so the two routes cannot drift apart in+ * what a score means. The equivalence test in tests/test_importance.c guards+ * the remaining freedom: that both gatherings produce the same inputs for the+ * same graph. */+double cbm_pipeline_importance_score(const cbm_importance_inputs_t *in) {+ if (!in) {+ return 0.0;+ }+ double score = sqrt((double)(in->num_refs > 0 ? in->num_refs : 0));+ if (name_is_private(in->name)) {+ score *= CBM_IMPORTANCE_PRIV_MUL;+ }+ if (in->name_distinct_files >= CBM_IMPORTANCE_GENERIC_MIN_FILES) {+ score *= CBM_IMPORTANCE_GENERIC_MUL;+ }+ if (name_is_distinctive(in->name)) {+ score *= CBM_IMPORTANCE_DISTINCT_MUL;+ }+ if (cbm_is_test_path(in->file_path) || in->tests_target) {+ score *= CBM_IMPORTANCE_TEST_MUL;+ }+ return score;+}+/* ── Distinct-file counting (the linear core) ─────────────────────────── */typedef struct {@@ -367,24 +412,16 @@ void cbm_pipeline_pass_importance(cbm_pipeline_ctx_t *ctx) {for (int i = 0; i < count; i++) {cbm_gbuf_node_t *n = (cbm_gbuf_node_t *)nodes[i];- int num_refs =- incoming_edge_count(gb, n->id, "CALLS") + incoming_edge_count(gb, n->id, "USAGE");- double score = sqrt((double)num_refs);-- if (name_is_private(n->name)) {- score *= CBM_IMPORTANCE_PRIV_MUL;- }- if (imp_distinct_file_count(gb, n->name, &ix) >= CBM_IMPORTANCE_GENERIC_MIN_FILES) {- score *= CBM_IMPORTANCE_GENERIC_MUL;- }- if (name_is_distinctive(n->name)) {- score *= CBM_IMPORTANCE_DISTINCT_MUL;- }- if (cbm_is_test_path(n->file_path) || incoming_edge_count(gb, n->id, "TESTS") > 0) {- score *= CBM_IMPORTANCE_TEST_MUL;- }-- cbm_pipeline_importance_append_prop(n, score);+ /* Gather only — the rule itself lives in one place. */+ cbm_importance_inputs_t in = {+ .name = n->name,+ .file_path = n->file_path,+ .num_refs = incoming_edge_count(gb, n->id, "CALLS") ++ incoming_edge_count(gb, n->id, "USAGE"),+ .name_distinct_files = imp_distinct_file_count(gb, n->name, &ix),+ .tests_target = incoming_edge_count(gb, n->id, "TESTS") > 0,+ };+ cbm_pipeline_importance_append_prop(n, cbm_pipeline_importance_score(&in));updated++;}}@@ -394,3 +431,126 @@ void cbm_pipeline_pass_importance(cbm_pipeline_ctx_t *ctx) {atomic_fetch_add_explicit(&g_importance_nodes, updated, memory_order_relaxed);cbm_log_info("pass.importance", "symbols", itoa_imp(updated));}++/* ── Store-level recompute (closure-delta incremental) ────────────────+ *+ * WHY THIS EXISTS. The closure-delta route never materialises the project+ * graph in RAM: cbm_delta_preseed fills the delta gbuf with *proxy* nodes+ * (id, label, name, qn, file_path — no edges, empty properties), and only the+ * re-extracted files' symbols carry real edges. Scoring there reads a+ * near-zero in-degree for a symbol referenced hundreds of times project-wide,+ * and cbm_delta_patch then persists exactly those fresh rows. Loading the full+ * graph to fix that would give back the point of the delta route, so the+ * recompute runs where the complete graph already exists: in SQL, over the+ * staging store, AFTER cbm_delta_patch has inserted the new nodes and+ * re-linked the snapshotted inbound edges.+ *+ * WHY IT CANNOT DRIFT FROM THE IN-MEMORY PASS. The scoring rule and the JSON+ * write-back are not reimplemented here. They are registered as SQLite+ * user-defined functions that call cbm_pipeline_importance_score() and+ * cbm_pipeline_importance_set_prop() — the same C code the gbuf pass runs.+ * SQL supplies only the three aggregates (in-degree, TESTS presence, distinct+ * files per name), each one indexed GROUP BY. What remains free is the+ * GATHERING, and the full-vs-incremental equivalence test guards that.+ *+ * The whole project is rescored, not just the changed files: distinct-files-+ * per-name is a global input, so editing one file can legitimately move a name+ * across the generic-name threshold for every other definition of that name. A+ * scoped recompute would leave those stale — and would fail the equivalence+ * test, correctly. */++/* UDF: cbm_imp_score(name, file_path, num_refs, name_files, tests_target). */+static void sql_importance_score(sqlite3_context *c, int argc, sqlite3_value **argv) {+ if (argc != 5) {+ sqlite3_result_error(c, "cbm_imp_score arity", -1);+ return;+ }+ cbm_importance_inputs_t in = {+ .name = (const char *)sqlite3_value_text(argv[0]),+ .file_path = (const char *)sqlite3_value_text(argv[1]),+ .num_refs = sqlite3_value_int(argv[2]),+ .name_distinct_files = sqlite3_value_int(argv[3]),+ .tests_target = sqlite3_value_int(argv[4]) != 0,+ };+ sqlite3_result_double(c, cbm_pipeline_importance_score(&in));+}++/* UDF: cbm_imp_set(properties, score) → properties with "importance" set.+ * A non-object blob yields NULL; the UPDATE's COALESCE then leaves that row+ * untouched — the same tolerance the in-memory writer has. */+static void sql_importance_set(sqlite3_context *c, int argc, sqlite3_value **argv) {+ if (argc != 2) {+ sqlite3_result_error(c, "cbm_imp_set arity", -1);+ return;+ }+ const char *props = (const char *)sqlite3_value_text(argv[0]);+ char *neu = cbm_pipeline_importance_set_prop(props, sqlite3_value_double(argv[1]));+ if (!neu) {+ sqlite3_result_null(c);+ return;+ }+ sqlite3_result_text(c, neu, -1, SQLITE_TRANSIENT);+ free(neu);+}++/* The aggregate CTE is MATERIALIZED on purpose: it reads `nodes` while the+ * UPDATE writes `nodes`, and materialising settles that ordering explicitly+ * rather than relying on the planner to choose it. */+static const char *const kImportanceRecomputeSQL =+ "WITH agg AS MATERIALIZED ("+ " SELECT n.id AS id,"+ " cbm_imp_score(n.name, n.file_path, COALESCE(d.refs, 0),"+ " COALESCE(f.files, 0), COALESCE(d.tests, 0)) AS score"+ " FROM nodes n"+ " LEFT JOIN (SELECT target_id AS id,"+ " SUM(CASE WHEN type IN ('CALLS','USAGE') THEN 1 ELSE 0 END) AS refs,"+ " SUM(CASE WHEN type = 'TESTS' THEN 1 ELSE 0 END) AS tests"+ " FROM edges WHERE project = ?1 GROUP BY target_id) d ON d.id = n.id"+ " LEFT JOIN (SELECT name, COUNT(DISTINCT file_path) AS files"+ " FROM nodes WHERE project = ?1 GROUP BY name) f ON f.name = n.name"+ " WHERE n.project = ?1 AND n.label IN ('Function','Method','Class')"+ ")"+ "UPDATE nodes SET properties = COALESCE(cbm_imp_set(properties, agg.score), properties)"+ " FROM agg WHERE nodes.id = agg.id";++int cbm_pipeline_importance_recompute_store(cbm_store_t *store, const char *project) {+ if (!store || !project) {+ return -1;+ }+ sqlite3 *db = cbm_store_get_db(store);+ if (!db) {+ return -1;+ }+ if (sqlite3_create_function(db, "cbm_imp_score", 5, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,+ sql_importance_score, NULL, NULL) != SQLITE_OK ||+ sqlite3_create_function(db, "cbm_imp_set", 2, SQLITE_UTF8 | SQLITE_DETERMINISTIC, NULL,+ sql_importance_set, NULL, NULL) != SQLITE_OK) {+ cbm_log_error("importance.store_udf_failed", "err", sqlite3_errmsg(db));+ return -1;+ }+ if (cbm_store_begin(store) != CBM_STORE_OK) {+ return -1;+ }+ sqlite3_stmt *st = NULL;+ if (sqlite3_prepare_v2(db, kImportanceRecomputeSQL, -1, &st, NULL) != SQLITE_OK) {+ cbm_log_error("importance.store_prepare_failed", "err", sqlite3_errmsg(db));+ cbm_store_rollback(store);+ return -1;+ }+ sqlite3_bind_text(st, 1, project, -1, SQLITE_TRANSIENT);+ int step_rc = sqlite3_step(st);+ sqlite3_finalize(st);+ if (step_rc != SQLITE_DONE) {+ cbm_log_error("importance.store_step_failed", "err", sqlite3_errmsg(db));+ cbm_store_rollback(store);+ return -1;+ }+ int changed = sqlite3_changes(db);+ if (cbm_store_commit(store) != CBM_STORE_OK) {+ return -1;+ }+ uint64_t rows = (uint64_t)(changed > 0 ? changed : 0);+ atomic_fetch_add_explicit(&g_importance_store_rows, rows, memory_order_relaxed);+ cbm_log_info("pass.importance_store", "symbols", itoa_imp(rows));+ return 0;+}diff --git a/src/pipeline/pipeline_incremental.c b/src/pipeline/pipeline_incremental.cindex 5de6bfd6a..4ff89aa42 100644--- a/src/pipeline/pipeline_incremental.c+++ b/src/pipeline/pipeline_incremental.c@@ -1410,9 +1410,15 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed}}-/* Run post-extraction passes (tests, decorator tags, configlink). */+/* Run post-extraction passes (tests, decorator tags, configlink).+ *+ * score_importance: false on the closure-delta route, whose ctx->gbuf is a+ * PROXY buffer — cbm_delta_preseed fills it with id/label/name/qn/file_path+ * and no project-wide edges, so an in-memory score there would read a+ * near-zero in-degree and cbm_delta_patch would persist it. That route scores+ * in SQL instead, after the patch; see cbm_pipeline_importance_recompute_store. */static int run_postpasses(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_files, int ci,- const char *project) {+ const char *project, bool score_importance) {struct timespec t;cbm_clock_gettime(CLOCK_MONOTONIC, &t);@@ -1457,16 +1463,22 @@ static int run_postpasses(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_file}}- /* Importance last, in EVERY mode — same ordering rule as the full path:- * it reads CALLS/USAGE (re-extraction, above) and TESTS (pass_tests, first- * in this function). The graph here is the rehydrated whole-project buffer,- * so nodes outside the changed set already carry an "importance" key from- * the previous run; cbm_pipeline_importance_append_prop overwrites it in- * place rather than appending a duplicate. */- cbm_clock_gettime(CLOCK_MONOTONIC, &t);- cbm_pipeline_pass_importance(ctx);- cbm_log_info("pass.timing", "pass", "incr_importance", "elapsed_ms",- itoa_buf((int)elapsed_ms(t)));+ /* Importance last, in EVERY mode — same ordering rule as the full path: it+ * reads CALLS/USAGE (re-extraction, above) and TESTS (pass_tests, first in+ * this function).+ *+ * ONLY on the legacy-partial route, where ctx->gbuf really is the whole+ * project rehydrated by cbm_gbuf_load_from_db — those nodes already carry+ * an "importance" key from the previous run, and the write-back overwrites+ * it in place rather than appending a duplicate. The closure-delta route+ * passes score_importance = false and rescores in SQL after its patch,+ * because its buffer holds proxies without project-wide edges. */+ if (score_importance) {+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ cbm_pipeline_pass_importance(ctx);+ cbm_log_info("pass.timing", "pass", "incr_importance", "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));+ }if (cbm_pipeline_check_cancel(ctx)) {return CBM_NOT_FOUND;}@@ -2158,7 +2170,7 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const charphase_rc = cbm_pipeline_check_cancel(&ctx);}if (phase_rc == 0) {- phase_rc = run_postpasses(&ctx, changed_files, ci, project);+ phase_rc = run_postpasses(&ctx, changed_files, ci, project, false);}if (ctx.return_type_table) {for (int i = 0; i < ctx.return_type_table->count; i++) {@@ -2183,6 +2195,23 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const char}cbm_log_info("delta.patch_done", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));+ /* Importance, in SQL, over the now-complete staging graph. This is the+ * FIRST point on this route where the whole project is queryable: the+ * patch has just inserted the repaired files' nodes AND re-linked the+ * snapshotted inbound edges, so in-degree is finally correct. Scoring+ * earlier — in run_postpasses, off the proxy buffer — would persist a+ * near-zero score for any heavily-referenced symbol in a changed file.+ * A failure here is a delta-route failure: `result` still holds+ * FORCE_FULL_REINDEX, so the run degrades to a correct full rebuild+ * rather than publishing wrong scores. */+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);+ if (cbm_pipeline_importance_recompute_store(staging, project) != 0) {+ cbm_log_error("delta.err", "phase", "importance_recompute");+ goto out;+ }+ cbm_log_info("pass.timing", "pass", "delta_importance_store", "elapsed_ms",+ itoa_buf((int)elapsed_ms(t)));+/* Coverage: previous failure rows for files not re-extracted + this* run's fresh entries — same merge the legacy tail performs. */cbm_file_error_t *run_errs = NULL;@@ -2713,7 +2742,7 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_filphase_rc = cbm_pipeline_check_cancel(&ctx);}if (phase_rc == 0) {- phase_rc = run_postpasses(&ctx, changed_files, ci, project);+ phase_rc = run_postpasses(&ctx, changed_files, ci, project, true);}/* Free ObjectScript tables built by pass_calls during run_extract_resolve. */diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.hindex a25573733..e686ac3b7 100644--- a/src/pipeline/pipeline_internal.h+++ b/src/pipeline/pipeline_internal.h@@ -641,12 +641,39 @@ void cbm_pipeline_pass_complexity(cbm_pipeline_ctx_t *ctx);* post-pass sequence. */void cbm_pipeline_pass_importance(cbm_pipeline_ctx_t *ctx);-/* Write the numeric "importance" key into a node's properties JSON object.- * IDEMPOTENT: an existing key is overwritten in place, never appended twice —- * the incremental path re-scores nodes rehydrated from the store that already- * carry the key. Non-static so the idempotence contract is directly testable. */+/* Gathered inputs for one symbol. Each scoring route fills this its own way+ * (gbuf lookups, or SQL aggregates) and then calls the ONE rule below. */+typedef struct {+ const char *name;+ const char *file_path;+ int num_refs; /* incoming CALLS + USAGE */+ int name_distinct_files; /* distinct files the NAME is defined in */+ bool tests_target; /* has an incoming TESTS edge */+} cbm_importance_inputs_t;++/* THE scoring rule — single definition, shared by every route, so the two+ * gathering strategies cannot drift apart in what a score means. */+double cbm_pipeline_importance_score(const cbm_importance_inputs_t *in);++/* Produce a copy of `json` with the numeric "importance" key set to `score`,+ * or NULL when `json` is not a JSON object or allocation fails. Caller owns+ * the result. IDEMPOTENT: an existing key is overwritten in place, never+ * appended twice — every re-scoring route sees nodes that already carry it.+ * Single definition, shared by the in-memory and SQL writers alike. */+char *cbm_pipeline_importance_set_prop(const char *json, double score);++/* gbuf-node convenience wrapper around cbm_pipeline_importance_set_prop. */void cbm_pipeline_importance_append_prop(cbm_gbuf_node_t *node, double score);+/* Recompute importance for an ENTIRE project directly in a store, in SQL.+ * Used by the closure-delta incremental route, whose in-RAM graph is a proxy+ * buffer with no project-wide edges — scoring there would persist a near-zero+ * in-degree for heavily-referenced symbols in the changed files. Must be+ * called on the STAGING store AFTER cbm_delta_patch has merged nodes and+ * re-linked inbound edges. Returns 0 on success; the caller treats failure as+ * a delta-route failure and falls back to a full rebuild. */+int cbm_pipeline_importance_recompute_store(cbm_store_t *store, const char *project);+/* Work counters for the importance pass (pass_importance.c). Deltas are read* by the complexity suite's linearity gate; never reset by the pass itself, so* nested/repeated runs compose. g_importance_name_visits counts same-name-group@@ -654,6 +681,9 @@ void cbm_pipeline_importance_append_prop(cbm_gbuf_node_t *node, double score);* superlinear if the per-distinct-name memoization is ever lost. */extern _Atomic uint64_t g_importance_nodes;extern _Atomic uint64_t g_importance_name_visits;+/* Rows rescored by the SQL-level store recompute. Lets a test prove the+ * closure-delta route actually took that path instead of passing vacuously. */+extern _Atomic uint64_t g_importance_store_rows;/* ── Env URL scanner (pass_envscan.c) ────────────────────────────── */diff --git a/tests/test_importance.c b/tests/test_importance.cindex 9452a49e9..afaf41a3c 100644--- a/tests/test_importance.c+++ b/tests/test_importance.c@@ -101,6 +101,97 @@ static int imp_check_label(cbm_store_t *s, const char *project, const char *labereturn bad == 0 ? count : -1;}+/* ── Store-level score readout (for the closure-delta tests) ──────────── */++typedef struct {+ char **qns;+ double *scores;+ int count;+} ImpScoreSet;++static void imp_scores_free(ImpScoreSet *set) {+ for (int i = 0; i < set->count; i++) {+ free(set->qns[i]);+ }+ free(set->qns);+ free(set->scores);+ set->qns = NULL;+ set->scores = NULL;+ set->count = 0;+}++/* Collect (qualified_name -> importance) for every scored label in a store. */+static int imp_collect_scores(const char *db_path, const char *project, ImpScoreSet *out) {+ static const char *const kLabels[] = {"Function", "Method", "Class"};+ memset(out, 0, sizeof(*out));+ cbm_store_t *s = cbm_store_open_path(db_path);+ if (!s) {+ return -1;+ }+ int rc = 0;+ for (int li = 0; li < 3; li++) {+ cbm_node_t *nodes = NULL;+ int n = 0;+ if (cbm_store_find_nodes_by_label(s, project, kLabels[li], &nodes, &n) != CBM_STORE_OK) {+ rc = -1;+ break;+ }+ char **qns = realloc(out->qns, (size_t)(out->count + n) * sizeof(*qns));+ double *sc = realloc(out->scores, (size_t)(out->count + n) * sizeof(*sc));+ if (n > 0 && (!qns || !sc)) {+ cbm_store_free_nodes(nodes, n);+ rc = -1;+ break;+ }+ if (qns) {+ out->qns = qns;+ }+ if (sc) {+ out->scores = sc;+ }+ for (int i = 0; i < n; i++) {+ out->qns[out->count] = strdup(nodes[i].qualified_name ? nodes[i].qualified_name : "");+ out->scores[out->count] = imp_value(nodes[i].properties_json);+ out->count++;+ }+ cbm_store_free_nodes(nodes, n);+ }+ cbm_store_close(s);+ return rc;+}++static double imp_score_of(const ImpScoreSet *set, const char *qn_suffix) {+ for (int i = 0; i < set->count; i++) {+ size_t l = strlen(set->qns[i]);+ size_t k = strlen(qn_suffix);+ if (l >= k && strcmp(set->qns[i] + (l - k), qn_suffix) == 0) {+ return set->scores[i];+ }+ }+ return -999.0;+}++/* Write a fixture whose `helper` in hot.py is called from `callers` other+ * files — the inbound edges that only exist project-wide, never in a delta+ * buffer. `tag` lets the caller perturb hot.py to force a re-parse. */+static int imp_write_hot_fixture(const char *root, int callers, const char *tag) {+ char body[256];+ snprintf(body, sizeof(body), "%sdef helper():\n return 1\n", tag);+ if (th_write_file(TH_PATH(root, "hot.py"), body) != 0) {+ return -1;+ }+ for (int i = 0; i < callers; i++) {+ char rel[64];+ char src[192];+ snprintf(rel, sizeof(rel), "c%d.py", i);+ snprintf(src, sizeof(src), "import hot\n\ndef use%d():\n return hot.helper()\n", i);+ if (th_write_file(TH_PATH(root, rel), src) != 0) {+ return -1;+ }+ }+ return 0;+}+/* ── Registration: the pass must actually execute ─────────────────────── *//* A miscounted PREDUMP_PASS_COUNT silently drops the last-registered pass.@@ -577,6 +668,181 @@ TEST(importance_second_index_run_keeps_exactly_one_key) {PASS();}+/* ── Closure-delta route: the graph is only complete in the store ─────── */++/* REGRESSION. `helper` lives in hot.py and is called from 25 other files. Edit+ * hot.py and re-index: the closure-delta route purges hot.py's rows, rebuilds+ * them from a PROXY buffer that holds no project-wide edges, and persists what+ * it computed. Scoring off that buffer sees in-degree 0 and stores 0.0 for a+ * symbol with 25 real callers. The fix rescores in SQL after cbm_delta_patch+ * has re-linked the snapshotted inbound edges. */+TEST(importance_closure_delta_keeps_referenced_symbol_sane) {+ enum { CALLERS = 25 };+ char *tmp = th_mktempdir("cbm_imp_delta");+ if (!tmp) {+ FAIL("tmpdir");+ }+ char root[512];+ snprintf(root, sizeof(root), "%s", tmp);+ char *tmp2 = th_mktempdir("cbm_imp_deltadb");+ if (!tmp2) {+ th_rmtree(root);+ FAIL("tmpdir2");+ }+ char dbdir[512];+ snprintf(dbdir, sizeof(dbdir), "%s", tmp2);++ ASSERT_EQ(imp_write_hot_fixture(root, CALLERS, ""), 0);++ char db_path[600];+ snprintf(db_path, sizeof(db_path), "%s/graph.db", dbdir);+ cbm_pipeline_t *p1 = cbm_pipeline_new(root, db_path, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p1);+ ASSERT_EQ(cbm_pipeline_run(p1), 0);+ char project[256];+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(p1));+ cbm_pipeline_free(p1);++ ImpScoreSet before = {0};+ ASSERT_EQ(imp_collect_scores(db_path, project, &before), 0);+ double full_score = imp_score_of(&before, "helper");+ printf(" full-index helper score %.6f (expect sqrt(%d) = %.6f)\n", full_score, CALLERS,+ sqrt((double)CALLERS));+ /* Non-vacuous: the callers really produced edges. If this is 0 the fixture+ * stopped exercising the bug and the test below would prove nothing. */+ ASSERT_TRUE(full_score > 1.0);+ imp_scores_free(&before);++ /* Touch hot.py so the delta route has exactly one file to repair. */+ ASSERT_EQ(imp_write_hot_fixture(root, CALLERS, "# touched\n"), 0);++ uint64_t sql0 = atomic_load_explicit(&g_importance_store_rows, memory_order_relaxed);+ cbm_pipeline_t *p2 = cbm_pipeline_new(root, db_path, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p2);+ ASSERT_EQ(cbm_pipeline_run(p2), 0);+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();+ cbm_pipeline_free(p2);+ uint64_t sql_rows = atomic_load_explicit(&g_importance_store_rows, memory_order_relaxed) - sql0;++ /* Route proof — without it a fall-back to a full reindex would repair the+ * score for the wrong reason and the test would pass vacuously. */+ printf(" route=%d (closure_repair=%d) sql_rescored_rows=%llu\n", (int)route,+ (int)CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR, (unsigned long long)sql_rows);+ ASSERT_EQ((int)route, (int)CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);++ ImpScoreSet after = {0};+ ASSERT_EQ(imp_collect_scores(db_path, project, &after), 0);+ double delta_score = imp_score_of(&after, "helper");+ printf(" after closure-delta helper score %.6f\n", delta_score);+ imp_scores_free(&after);++ th_rmtree(root);+ th_rmtree(dbdir);+ /* THE SYMPTOM, asserted before any mechanism guard: the graph is unchanged,+ * so the score must be unchanged. Scoring off the proxy buffer yields 0.0. */+ ASSERT_FLOAT_EQ(delta_score, full_score, 1e-6);+ /* Mechanism guard second, so a regression fails on the wrong score rather+ * than on bookkeeping. */+ ASSERT_GT((long long)sql_rows, 0);+ PASS();+}++/* EQUIVALENCE. A full index and an incremental index that converge on the same+ * tree must produce the same scores — for every symbol, not just the hot one.+ * Same directory and therefore the same project name and qualified names, so+ * the two score maps are directly comparable. */+TEST(importance_full_and_incremental_converge_on_same_scores) {+ enum { CALLERS = 12 };+ char *tmp = th_mktempdir("cbm_imp_equiv");+ if (!tmp) {+ FAIL("tmpdir");+ }+ char root[512];+ snprintf(root, sizeof(root), "%s", tmp);+ char *tmp2 = th_mktempdir("cbm_imp_equivdb");+ if (!tmp2) {+ th_rmtree(root);+ FAIL("tmpdir2");+ }+ char dbdir[512];+ snprintf(dbdir, sizeof(dbdir), "%s", tmp2);++ /* v1: every caller but c0 calls helper. c0 imports hot but does not. */+ ASSERT_EQ(imp_write_hot_fixture(root, CALLERS, ""), 0);+ ASSERT_EQ(th_write_file(TH_PATH(root, "c0.py"), "import hot\n\ndef use0():\n return 1\n"),+ 0);+ ASSERT_EQ(th_write_file(TH_PATH(root, "extra.py"),+ "import hot\n\ndef load_user_profile():\n return hot.helper()\n"),+ 0);++ char db_incr[600];+ snprintf(db_incr, sizeof(db_incr), "%s/incr.db", dbdir);+ cbm_pipeline_t *p1 = cbm_pipeline_new(root, db_incr, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p1);+ ASSERT_EQ(cbm_pipeline_run(p1), 0);+ char project[256];+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(p1));+ cbm_pipeline_free(p1);++ /* v2: c0's BODY starts calling helper. Body-only, so c0's surface is+ * unchanged and the closure planner accepts the delta — but the in-degree+ * of `helper`, which lives in the UNCHANGED hot.py, goes up by one. That+ * is the case a changed-files-only rescore gets wrong: the symbol whose+ * score moved is not in the changed set at all. */+ ASSERT_EQ(th_write_file(TH_PATH(root, "c0.py"),+ "import hot\n\ndef use0():\n return hot.helper()\n"),+ 0);++ uint64_t sql0 = atomic_load_explicit(&g_importance_store_rows, memory_order_relaxed);+ cbm_pipeline_t *p2 = cbm_pipeline_new(root, db_incr, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p2);+ ASSERT_EQ(cbm_pipeline_run(p2), 0);+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();+ cbm_pipeline_free(p2);+ uint64_t sql_rows = atomic_load_explicit(&g_importance_store_rows, memory_order_relaxed) - sql0;+ printf(" route=%d (closure_repair=%d) sql_rescored_rows=%llu\n", (int)route,+ (int)CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR, (unsigned long long)sql_rows);+ ASSERT_EQ((int)route, (int)CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);++ /* Same tree, indexed cold into a separate database. */+ char db_full[600];+ snprintf(db_full, sizeof(db_full), "%s/full.db", dbdir);+ cbm_pipeline_t *p3 = cbm_pipeline_new(root, db_full, CBM_MODE_FULL);+ ASSERT_NOT_NULL(p3);+ ASSERT_EQ(cbm_pipeline_run(p3), 0);+ cbm_pipeline_free(p3);++ ImpScoreSet incr = {0};+ ImpScoreSet full = {0};+ ASSERT_EQ(imp_collect_scores(db_incr, project, &incr), 0);+ ASSERT_EQ(imp_collect_scores(db_full, project, &full), 0);+ printf(" scored symbols: incremental=%d full=%d\n", incr.count, full.count);++ int mismatches = 0;+ for (int i = 0; i < full.count; i++) {+ double a = full.scores[i];+ double b = imp_score_of(&incr, full.qns[i]);+ if (!(fabs(a - b) < 1e-6)) {+ mismatches++;+ if (mismatches <= 5) {+ printf(" MISMATCH %s: full=%.6f incremental=%.6f\n", full.qns[i], a, b);+ }+ }+ }+ int count_full = full.count;+ int count_incr = incr.count;+ imp_scores_free(&incr);+ imp_scores_free(&full);+ th_rmtree(root);+ th_rmtree(dbdir);++ ASSERT_GT(count_full, 5); /* non-vacuous: there really are symbols to compare */+ ASSERT_EQ(count_incr, count_full);+ ASSERT_EQ(mismatches, 0); /* the symptom */+ ASSERT_GT((long long)sql_rows, 0); /* mechanism guard, asserted second */+ PASS();+}+/* ── Cost shape ───────────────────────────────────────────────────────── *//* The distinct-file count must be computed once per distinct NAME. Computing@@ -636,6 +902,10 @@ SUITE(importance) {RUN_TEST(importance_rehydrated_node_keeps_exactly_one_key);RUN_TEST(importance_second_index_run_keeps_exactly_one_key);+ /* Closure-delta route — the store-level recompute. */+ RUN_TEST(importance_closure_delta_keeps_referenced_symbol_sane);+ RUN_TEST(importance_full_and_incremental_converge_on_same_scores);+/* Cost shape. */RUN_TEST(importance_distinct_file_count_is_linear_in_group_size);}