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(index): make parallel indexing deterministic (byte-identical runs)
Martin Vogeld9ea73f9e4b0
diff --git a/src/graph_buffer/graph_buffer.c b/src/graph_buffer/graph_buffer.cindex f1e190d61..2504bd26c 100644--- a/src/graph_buffer/graph_buffer.c+++ b/src/graph_buffer/graph_buffer.c@@ -652,13 +652,72 @@ int64_t cbm_gbuf_upsert_node(cbm_gbuf_t *gb, const char *label, const char *name(strcmp(existing->label, "Project") == 0 || strcmp(existing->label, "Folder") == 0)) {return existing->id;}+ /* Same-QN arrival. Two distinct cases:+ *+ * 1) The SAME source entity re-upserted (identity fields match) —+ * refresh in place, exactly as before.+ *+ * 2) A DIFFERENT source entity sharing the QN. In C a struct, a+ * function and a macro can all carry one name and the QN scheme+ * does not encode the entity kind, so they collide here. The old+ * code let the LAST arrival overwrite — under parallel extraction+ * the merge order varies run to run, so WHICH entity survived+ * (label/name/lines/props) flickered (xfs: Function-node count+ * 4998 vs 5015 across two runs), and every order-sensitive+ * consumer downstream (semantic vectors, LSH, near-threshold+ * scores) inherited the flicker. Pick the survivor by a canonical+ * CONTENT rule instead — lexicographically smallest+ * (label, file_path, start_line, name) — so the outcome is a pure+ * function of the colliding entities, not of scheduling. Exactly+ * one entity is dropped, as one always was; kind-disambiguated+ * QNs (the real cure) are tracked as a follow-up. */+ bool same_entity =+ existing->label && label && strcmp(existing->label, label) == 0 &&+ existing->file_path && file_path && strcmp(existing->file_path, file_path) == 0 &&+ existing->start_line == start_line && existing->name && name &&+ strcmp(existing->name, name) == 0;+ if (!same_entity) {+ int c = strcmp(label ? label : "", existing->label ? existing->label : "");+ if (c == 0) {+ c = strcmp(file_path ? file_path : "",+ existing->file_path ? existing->file_path : "");+ }+ if (c == 0) {+ c = start_line - existing->start_line;+ }+ if (c == 0) {+ c = strcmp(name ? name : "", existing->name ? existing->name : "");+ }+ if (c >= 0) {+ return existing->id; /* existing entity is the canonical winner */+ }+ }/* Update in-place. name/properties are strdup'd BEFORE freeing old ones* (callers may pass existing->name as an argument). label/file_path are* interned: gb_intern returns a stable pool pointer (idempotent even when- * label == existing->label), so the old value is replaced, never freed. */+ * label == existing->label), so the old value is replaced, never freed.+ * When the surviving label/name changes, keep the secondary indexes+ * consistent (the old code left the node listed under its ORIGINAL+ * label/name — cbm_gbuf_find_by_label/name then missed or mis-listed it,+ * which is how the flickering Function set reached the semantic pass). */char *new_name = heap_strdup(name);char *new_props = properties_json ? heap_strdup(properties_json) : NULL;- existing->label = (char *)gb_intern(gb, label);+ const char *new_label_interned = gb_intern(gb, label);+ bool label_changed = !existing->label || !new_label_interned ||+ strcmp(existing->label, new_label_interned) != 0;+ bool name_changed =+ !existing->name || !new_name || strcmp(existing->name, new_name) != 0;+ if (label_changed) {+ remove_node_from_ptr_array(+ cbm_ht_get(gb->nodes_by_label, existing->label ? existing->label : ""),+ existing->id);+ }+ if (name_changed) {+ remove_node_from_ptr_array(+ cbm_ht_get(gb->nodes_by_name, existing->name ? existing->name : ""),+ existing->id);+ }+ existing->label = (char *)new_label_interned;free(existing->name);existing->name = new_name;existing->file_path = (char *)gb_intern(gb, file_path);@@ -668,6 +727,16 @@ int64_t cbm_gbuf_upsert_node(cbm_gbuf_t *gb, const char *label, const char *namefree(existing->properties_json);existing->properties_json = new_props;}+ if (label_changed) {+ node_ptr_array_t *by_label =+ get_or_create_node_array(gb->nodes_by_label, existing->label ? existing->label : "");+ cbm_da_push(by_label, (const cbm_gbuf_node_t *)existing);+ }+ if (name_changed) {+ node_ptr_array_t *by_name =+ get_or_create_node_array(gb->nodes_by_name, existing->name ? existing->name : "");+ cbm_da_push(by_name, (const cbm_gbuf_node_t *)existing);+ }return existing->id;}@@ -1131,15 +1200,73 @@ static void merge_update_existing(cbm_gbuf_t *dst, cbm_gbuf_node_t *existing,existing->label && sn->label && strcmp(sn->label, "Module") == 0 &&(strcmp(existing->label, "Project") == 0 || strcmp(existing->label, "Folder") == 0);if (!module_on_container) {- existing->label = (char *)gb_intern(dst, sn->label);- free(existing->name);- existing->name = heap_strdup(sn->name);- existing->file_path = (char *)gb_intern(dst, sn->file_path);- existing->start_line = sn->start_line;- existing->end_line = sn->end_line;- if (sn->properties_json) {- free(existing->properties_json);- existing->properties_json = heap_strdup(sn->properties_json);+ /* Canonical collision winner (determinism) — mirrors+ * cbm_gbuf_upsert_node. Distinct source entities can share a QN (C:+ * struct/function/macro with one name); unconditional "src wins" made+ * the survivor depend on worker merge order, flickering the node set+ * (and every downstream consumer) run to run. Same entity → refresh;+ * different entity → keep the lexicographically smallest+ * (label, file_path, start_line, name). */+ bool same_entity =+ existing->label && sn->label && strcmp(existing->label, sn->label) == 0 &&+ existing->file_path && sn->file_path &&+ strcmp(existing->file_path, sn->file_path) == 0 &&+ existing->start_line == sn->start_line && existing->name && sn->name &&+ strcmp(existing->name, sn->name) == 0;+ bool sn_wins = true;+ if (!same_entity) {+ int c = strcmp(sn->label ? sn->label : "", existing->label ? existing->label : "");+ if (c == 0) {+ c = strcmp(sn->file_path ? sn->file_path : "",+ existing->file_path ? existing->file_path : "");+ }+ if (c == 0) {+ c = sn->start_line - existing->start_line;+ }+ if (c == 0) {+ c = strcmp(sn->name ? sn->name : "", existing->name ? existing->name : "");+ }+ sn_wins = c < 0;+ }+ if (sn_wins) {+ /* Keep the secondary indexes consistent when the surviving+ * label/name changes (the old code left the node listed under its+ * original label/name, so find_by_label/name mis-listed it). */+ const char *new_label = gb_intern(dst, sn->label);+ bool label_changed = !existing->label || !new_label ||+ strcmp(existing->label, new_label) != 0;+ bool name_changed = !existing->name || !sn->name ||+ strcmp(existing->name, sn->name) != 0;+ if (label_changed) {+ remove_node_from_ptr_array(+ cbm_ht_get(dst->nodes_by_label, existing->label ? existing->label : ""),+ existing->id);+ }+ if (name_changed) {+ remove_node_from_ptr_array(+ cbm_ht_get(dst->nodes_by_name, existing->name ? existing->name : ""),+ existing->id);+ }+ existing->label = (char *)new_label;+ free(existing->name);+ existing->name = heap_strdup(sn->name);+ existing->file_path = (char *)gb_intern(dst, sn->file_path);+ existing->start_line = sn->start_line;+ existing->end_line = sn->end_line;+ if (sn->properties_json) {+ free(existing->properties_json);+ existing->properties_json = heap_strdup(sn->properties_json);+ }+ if (label_changed) {+ node_ptr_array_t *by_label = get_or_create_node_array(+ dst->nodes_by_label, existing->label ? existing->label : "");+ cbm_da_push(by_label, (const cbm_gbuf_node_t *)existing);+ }+ if (name_changed) {+ node_ptr_array_t *by_name = get_or_create_node_array(+ dst->nodes_by_name, existing->name ? existing->name : "");+ cbm_da_push(by_name, (const cbm_gbuf_node_t *)existing);+ }}}diff --git a/src/pipeline/pass_pkgmap.c b/src/pipeline/pass_pkgmap.cindex 96b6a78b6..61803254b 100644--- a/src/pipeline/pass_pkgmap.c+++ b/src/pipeline/pass_pkgmap.c@@ -1515,6 +1515,14 @@ const cbm_gbuf_node_t *cbm_pipeline_resolve_import_node(const cbm_pipeline_ctx_tconst cbm_gbuf_node_t **hits = NULL;int n = 0;if (cbm_gbuf_find_by_name(ctx->gbuf, cands[ci], &hits, &n) == 0 && hits) {+ /* Deterministic winner: hits[] is in node-registration order,+ * which under parallel extraction varies run to run — taking+ * the FIRST targetable hit made the same import resolve to+ * different same-named nodes across runs (xfs: 360 flickering+ * IMPORTS diff lines between two MT runs). Pick the candidate+ * with the lexicographically smallest qualified name instead:+ * stable, content-derived, identical for ST and MT. */+ const cbm_gbuf_node_t *best = NULL;for (int i = 0; i < n; i++) {const cbm_gbuf_node_t *cand = hits[i];if (!cand || !import_targetable_label(cand->label)) {@@ -1524,7 +1532,13 @@ const cbm_gbuf_node_t *cbm_pipeline_resolve_import_node(const cbm_pipeline_ctx_tstrcmp(cand->qualified_name, source_file_qn) == 0) {continue; /* self */}- return cand;+ if (!best || (cand->qualified_name && best->qualified_name &&+ strcmp(cand->qualified_name, best->qualified_name) < 0)) {+ best = cand;+ }+ }+ if (best) {+ return best;}}}diff --git a/src/pipeline/pass_semantic_edges.c b/src/pipeline/pass_semantic_edges.cindex ad86d647b..188fdc1c7 100644--- a/src/pipeline/pass_semantic_edges.c+++ b/src/pipeline/pass_semantic_edges.c@@ -67,6 +67,13 @@ typedef struct {int64_t target_id;float score;bool same_file;+ /* Canonical admission keys (determinism): func index of the discovering+ * side, its candidate rank, and the partner's func index. The sequential+ * admission pass replays pairs in (i, c) order so which pairs win the+ * per-node max_edges budget no longer depends on worker scheduling. */+ int i;+ int j;+ int c;} deferred_edge_t;typedef struct {@@ -82,7 +89,7 @@ static void deferred_buf_init(deferred_edge_buf_t *buf) {}static void deferred_buf_push(deferred_edge_buf_t *buf, int64_t src, int64_t tgt, float score,- bool same_file) {+ bool same_file, int i, int j, int c) {if (buf->count >= buf->cap) {int nc = buf->cap < CBM_SZ_256 ? CBM_SZ_256 : buf->cap * GROW;deferred_edge_t *grown = realloc(buf->edges, (size_t)nc * sizeof(deferred_edge_t));@@ -92,8 +99,13 @@ static void deferred_buf_push(deferred_edge_buf_t *buf, int64_t src, int64_t tgtbuf->edges = grown;buf->cap = nc;}- buf->edges[buf->count++] = (deferred_edge_t){- .source_id = src, .target_id = tgt, .score = score, .same_file = same_file};+ buf->edges[buf->count++] = (deferred_edge_t){.source_id = src,+ .target_id = tgt,+ .score = score,+ .same_file = same_file,+ .i = i,+ .j = j,+ .c = c};}static void deferred_buf_free(deferred_edge_buf_t *buf) {@@ -393,25 +405,59 @@ static int tokenize_json_array_field(const char *json, const char *key, char **t/* Walk the CALLS edges rooted at n (either outbound or inbound depending on* `outbound`) and tokenize the names of the target/source nodes. Caller-side* caps via max_tokens and MAX_CALLEES. */-static int tokenize_call_neighbors(const cbm_gbuf_node_t *n, const cbm_gbuf_t *gbuf, bool outbound,- char **tokens, int count, int max_tokens) {- if (!gbuf || count >= max_tokens) {- return count;- }+static int cmp_name_ptr(const void *pa, const void *pb) {+ const char *a = *(const char *const *)pa;+ const char *b = *(const char *const *)pb;+ return strcmp(a, b);+}++/* Collect the CALLS-neighbor names of `node_id`, SORTED by name. The edge+ * arrays are in insertion order — which under parallel extraction varies run+ * to run — and both consumers truncate (MAX_CALLEES / max_tokens), so an+ * unstable order changed WHICH neighbors contribute to the semantic vectors+ * and flickered near-threshold SEMANTICALLY_RELATED edges (determinism).+ * Returns a malloc'd array of borrowed name pointers; caller frees the array. */+static const char **collect_sorted_call_neighbors(const cbm_gbuf_t *gbuf, int64_t node_id,+ bool outbound, int *out_n) {+ *out_n = 0;const cbm_gbuf_edge_t **edges = NULL;int ec = 0;- int rc = outbound ? cbm_gbuf_find_edges_by_source_type(gbuf, n->id, "CALLS", &edges, &ec)- : cbm_gbuf_find_edges_by_target_type(gbuf, n->id, "CALLS", &edges, &ec);- if (rc != 0) {- return count;+ int rc = outbound ? cbm_gbuf_find_edges_by_source_type(gbuf, node_id, "CALLS", &edges, &ec)+ : cbm_gbuf_find_edges_by_target_type(gbuf, node_id, "CALLS", &edges, &ec);+ if (rc != 0 || ec <= 0) {+ return NULL;}- for (int e = 0; e < ec && e < MAX_CALLEES && count < max_tokens; e++) {+ const char **names = malloc((size_t)ec * sizeof(char *));+ if (!names) {+ return NULL;+ }+ int n = 0;+ for (int e = 0; e < ec; e++) {int64_t id = outbound ? edges[e]->target_id : edges[e]->source_id;const cbm_gbuf_node_t *neighbor = cbm_gbuf_find_by_id(gbuf, id);if (neighbor && neighbor->name) {- count += cbm_sem_tokenize(neighbor->name, tokens + count, max_tokens - count);+ names[n++] = neighbor->name;}}+ qsort(names, (size_t)n, sizeof(char *), cmp_name_ptr);+ *out_n = n;+ return names;+}++static int tokenize_call_neighbors(const cbm_gbuf_node_t *n, const cbm_gbuf_t *gbuf, bool outbound,+ char **tokens, int count, int max_tokens) {+ if (!gbuf || count >= max_tokens) {+ return count;+ }+ int nn = 0;+ const char **names = collect_sorted_call_neighbors(gbuf, n->id, outbound, &nn);+ if (!names) {+ return count;+ }+ for (int e = 0; e < nn && e < MAX_CALLEES && count < max_tokens; e++) {+ count += cbm_sem_tokenize(names[e], tokens + count, max_tokens - count);+ }+ free((void *)names);return count;}@@ -452,21 +498,19 @@ static int tokenize_node(const cbm_gbuf_node_t *n, const cbm_gbuf_t *gbuf, charstatic void build_api_vec(const cbm_gbuf_t *gbuf, int64_t node_id, cbm_sem_vec_t *out) {memset(out, 0, sizeof(*out));- const cbm_gbuf_edge_t **edges = NULL;- int edge_count = 0;- if (cbm_gbuf_find_edges_by_source_type(gbuf, node_id, "CALLS", &edges, &edge_count) != 0) {+ /* Sorted neighbors: stable MAX_CALLEES subset + stable float-accumulation+ * order (see collect_sorted_call_neighbors). */+ int n = 0;+ const char **names = collect_sorted_call_neighbors(gbuf, node_id, /*outbound=*/true, &n);+ if (!names) {return;}- int added = 0;- for (int i = 0; i < edge_count && added < MAX_CALLEES; i++) {- const cbm_gbuf_node_t *target = cbm_gbuf_find_by_id(gbuf, edges[i]->target_id);- if (target && target->name) {- cbm_sem_vec_t callee_ri;- cbm_sem_random_index(target->name, &callee_ri);- cbm_sem_vec_add_scaled(out, &callee_ri, PSE_UNIT_POS);- added++;- }+ for (int i = 0; i < n && i < MAX_CALLEES; i++) {+ cbm_sem_vec_t callee_ri;+ cbm_sem_random_index(names[i], &callee_ri);+ cbm_sem_vec_add_scaled(out, &callee_ri, PSE_UNIT_POS);}+ free((void *)names);cbm_sem_normalize(out);}@@ -696,7 +740,7 @@ static void sig_build_worker(int worker_id, void *ctx_ptr) {typedef struct {cbm_sem_func_t *funcs;uint64_t *signatures;- int *edge_counts; /* shared, atomically updated */+ int *edge_counts; /* budget applied sequentially in phase6b (determinism) */cbm_sem_config_t cfg;int func_count;@@ -767,14 +811,15 @@ static int score_collect_candidates(score_ctx_t *sc, int i, int *seen, int *candreturn cand_count;}-/* Score one candidate pair (i, j) and push a deferred edge if the score- * passes the threshold and both endpoints still have edge budget. */-static void score_try_emit(score_ctx_t *sc, int i, int j, deferred_edge_buf_t *my_buf) {- int ei = atomic_load_explicit((_Atomic int *)&sc->edge_counts[i], memory_order_relaxed);- int ej = atomic_load_explicit((_Atomic int *)&sc->edge_counts[j], memory_order_relaxed);- if (ei >= sc->cfg.max_edges || ej >= sc->cfg.max_edges) {- return;- }+/* Score one candidate pair (i, j) and push a deferred candidate edge if the+ * score passes the threshold. ADMISSION (the per-node max_edges budget) is+ * deliberately NOT decided here: the old check-then-increment on shared+ * atomic counts made the admitted edge SET depend on worker scheduling —+ * multi-threaded runs lost edges vs single-threaded and differed run-to-run+ * (repro_parallel_edge_determinism). Scoring is pure math and stays parallel;+ * the budget is applied afterwards in one sequential pass over the pairs in+ * canonical (i, candidate-rank) order. */+static void score_try_emit(score_ctx_t *sc, int i, int j, int c, deferred_edge_buf_t *my_buf) {if (strcmp(sc->funcs[i].file_ext, sc->funcs[j].file_ext) != 0) {return;}@@ -784,9 +829,8 @@ static void score_try_emit(score_ctx_t *sc, int i, int j, deferred_edge_buf_t *m}bool same_file = sc->funcs[i].file_path && sc->funcs[j].file_path &&strcmp(sc->funcs[i].file_path, sc->funcs[j].file_path) == 0;- deferred_buf_push(my_buf, sc->funcs[i].node_id, sc->funcs[j].node_id, score, same_file);- atomic_fetch_add_explicit((_Atomic int *)&sc->edge_counts[i], SKIP_ONE, memory_order_relaxed);- atomic_fetch_add_explicit((_Atomic int *)&sc->edge_counts[j], SKIP_ONE, memory_order_relaxed);+ deferred_buf_push(my_buf, sc->funcs[i].node_id, sc->funcs[j].node_id, score, same_file, i, j,+ c);}static void score_worker(int worker_id, void *ctx_ptr) {@@ -798,11 +842,6 @@ static void score_worker(int worker_id, void *ctx_ptr) {if (i >= sc->func_count) {break;}- int my_edges =- atomic_load_explicit((_Atomic int *)&sc->edge_counts[i], memory_order_relaxed);- if (my_edges >= sc->cfg.max_edges) {- continue;- }int seen[SCORE_SEEN_CAP];for (int s = 0; s < SCORE_SEEN_CAP; s++) {seen[s] = SCORE_SEEN_EMPTY;@@ -810,7 +849,7 @@ static void score_worker(int worker_id, void *ctx_ptr) {int candidates[SEM_MAX_CANDIDATES];int cand_count = score_collect_candidates(sc, i, seen, candidates, SEM_MAX_CANDIDATES);for (int c = 0; c < cand_count; c++) {- score_try_emit(sc, i, candidates[c], my_buf);+ score_try_emit(sc, i, candidates[c], c, my_buf);}}}@@ -856,6 +895,24 @@ typedef struct {int cap;} sem_bucket_t;+/* Canonical node order: by qualified name (unique per node), id tie-break+ * for defensiveness. Gives the semantic pass a stable, content-derived input+ * order regardless of how parallel extraction merged the graph buffer. */+static int cmp_node_ptr_by_qn(const void *pa, const void *pb) {+ const cbm_gbuf_node_t *a = *(const cbm_gbuf_node_t *const *)pa;+ const cbm_gbuf_node_t *b = *(const cbm_gbuf_node_t *const *)pb;+ const char *qa = a->qualified_name ? a->qualified_name : "";+ const char *qb = b->qualified_name ? b->qualified_name : "";+ int r = strcmp(qa, qb);+ if (r != 0) {+ return r;+ }+ if (a->id != b->id) {+ return a->id < b->id ? -1 : 1;+ }+ return 0;+}+/* Phase 1a: seed the funcs[] / node_ptrs[] arrays from all Function and* Method nodes in the graph buffer. Returns the number of functions collected* (0 on OOM), and fills *out_funcs / *out_nodes with newly malloc'd arrays. */@@ -898,6 +955,20 @@ static int phase1_scan_functions(cbm_gbuf_t *gbuf, cbm_sem_func_t **out_funcs,func_count++;}}+ /* Canonicalize the func order (determinism): the label-index order above+ * is gbuf insertion order = parallel-extraction merge order, which varies+ * run to run. Everything downstream is order-sensitive — LSH bucket chain+ * order, the SEM_MAX_CANDIDATES truncation, seen[] and the admission+ * sequence — so an unstable order changes WHICH semantic edges are+ * emitted. Sort the cheap pointer array by qualified name (unique) and+ * re-derive the three fields set so far; the heavy per-func payloads are+ * filled in later phases, so no 12.7 KB structs are moved. */+ qsort(node_ptrs, (size_t)func_count, sizeof(node_ptrs[0]), cmp_node_ptr_by_qn);+ for (int k = 0; k < func_count; k++) {+ funcs[k].node_id = node_ptrs[k]->id;+ funcs[k].file_path = node_ptrs[k]->file_path;+ funcs[k].file_ext = file_ext(node_ptrs[k]->file_path);+ }*out_funcs = funcs;*out_nodes = node_ptrs;return func_count;@@ -932,20 +1003,66 @@ static void phase5c_build_lsh_buckets(const uint64_t *signatures, int func_count/* Phase 6b: serialize deferred edges from all worker buffers into the graph* buffer (sequential because gbuf isn't thread-safe). */+/* Canonical order for candidate pairs: ascending discovering-func index,+ * then ascending candidate rank — the order a sequential scoring loop over+ * canonically-sorted funcs would have produced. */+static int cmp_deferred_edge_canonical(const void *pa, const void *pb) {+ const deferred_edge_t *a = pa;+ const deferred_edge_t *b = pb;+ if (a->i != b->i) {+ return a->i < b->i ? -1 : 1;+ }+ if (a->c != b->c) {+ return a->c < b->c ? -1 : 1;+ }+ return 0;+}++/* Sequential, deterministic admission + merge: gather every above-threshold+ * pair from the worker buffers, replay them in canonical (i, rank) order,+ * and apply the per-node max_edges budget HERE — single-threaded — so the+ * admitted edge set is a pure function of the (canonically sorted) inputs,+ * independent of worker count and scheduling. */static int phase6b_merge_edges(cbm_gbuf_t *gbuf, deferred_edge_buf_t *worker_bufs,- int worker_count) {- int total_edges = 0;+ int worker_count, int *edge_counts, int max_edges) {+ int total_pairs = 0;for (int w = 0; w < worker_count; w++) {- for (int e = 0; e < worker_bufs[w].count; e++) {- deferred_edge_t *de = &worker_bufs[w].edges[e];- char props[PROPS_BUF];- snprintf(props, sizeof(props), "{\"score\":%.3f,\"same_file\":%s}", de->score,- de->same_file ? "true" : "false");- cbm_gbuf_insert_edge(gbuf, de->source_id, de->target_id, "SEMANTICALLY_RELATED", props);- total_edges++;+ total_pairs += worker_bufs[w].count;+ }+ deferred_edge_t *pairs = NULL;+ if (total_pairs > 0) {+ pairs = malloc((size_t)total_pairs * sizeof(deferred_edge_t));+ }+ if (!pairs) {+ for (int w = 0; w < worker_count; w++) {+ deferred_buf_free(&worker_bufs[w]);}+ return 0;+ }+ int n = 0;+ for (int w = 0; w < worker_count; w++) {+ memcpy(&pairs[n], worker_bufs[w].edges,+ (size_t)worker_bufs[w].count * sizeof(deferred_edge_t));+ n += worker_bufs[w].count;deferred_buf_free(&worker_bufs[w]);}+ qsort(pairs, (size_t)n, sizeof(deferred_edge_t), cmp_deferred_edge_canonical);++ int total_edges = 0;+ for (int e = 0; e < n; e++) {+ deferred_edge_t *de = &pairs[e];+ if (edge_counts[de->i] >= max_edges || edge_counts[de->j] >= max_edges) {+ continue;+ }+ char props[PROPS_BUF];+ snprintf(props, sizeof(props), "{\"score\":%.3f,\"same_file\":%s}", de->score,+ de->same_file ? "true" : "false");+ cbm_gbuf_insert_edge(gbuf, de->source_id, de->target_id, "SEMANTICALLY_RELATED", props);+ edge_counts[de->i]++;+ edge_counts[de->j]++;+ total_edges++;+ }+ free(pairs);return total_edges;}@@ -1168,7 +1285,7 @@ static int run_scoring_phase(cbm_gbuf_t *gbuf, cbm_sem_func_t *funcs, uint64_t *CBM_PROF_END_N("semantic_edges", "6a_score_parallel", t_phase6a, func_count);CBM_PROF_START(t_phase6b);- int total = phase6b_merge_edges(gbuf, worker_bufs, worker_count);+ int total = phase6b_merge_edges(gbuf, worker_bufs, worker_count, edge_counts, cfg.max_edges);CBM_PROF_END_N("semantic_edges", "6b_edge_merge_seq", t_phase6b, total);free(worker_bufs);@@ -1239,6 +1356,7 @@ int cbm_pipeline_pass_semantic_edges(cbm_pipeline_ctx_t *ctx) {worker_count);CBM_PROF_END_N("semantic_edges", "4_build_and_store_vec", t_phase4, func_count);+cbm_log_info("pass.semantic.vectors_stored", "count", itoa_log(func_count));/* Phase 5: LSH hyperplanes → signatures → buckets. */diff --git a/src/pipeline/pass_similarity.c b/src/pipeline/pass_similarity.cindex f0c22ba70..f01e55f79 100644--- a/src/pipeline/pass_similarity.c+++ b/src/pipeline/pass_similarity.c@@ -89,8 +89,28 @@ typedef struct {cbm_minhash_t fp;const char *file_path;const char *ext;+ const char *qn; /* canonical ordering + pair-ownership (determinism) */} fp_entry_t;+/* Canonical entry order: by qualified name (unique). The label-index order+ * from collect_fp_entries is gbuf insertion order = parallel-extraction merge+ * order, which varies run to run; LSH bucket chains and the per-node edge-cap+ * truncation both inherit it, flickering WHICH SIMILAR_TO edges are emitted. */+static int cmp_fp_entry_by_qn(const void *pa, const void *pb) {+ const fp_entry_t *a = pa;+ const fp_entry_t *b = pb;+ const char *qa = a->qn ? a->qn : "";+ const char *qb = b->qn ? b->qn : "";+ int r = strcmp(qa, qb);+ if (r != 0) {+ return r;+ }+ if (a->node_id != b->node_id) {+ return a->node_id < b->node_id ? -1 : 1;+ }+ return 0;+}+/* Collect all Function/Method nodes with fingerprints from graph buffer. */static int collect_fp_entries(cbm_gbuf_t *gbuf, fp_entry_t **out_entries) {fp_entry_t *entries = NULL;@@ -124,9 +144,12 @@ static int collect_fp_entries(cbm_gbuf_t *gbuf, fp_entry_t **out_entries) {.fp = fp,.file_path = n->file_path,.ext = file_ext(n->file_path),+ .qn = n->qualified_name,};}}+ /* Canonicalize (determinism) — see cmp_fp_entry_by_qn. */+ qsort(entries, (size_t)count, sizeof(fp_entry_t), cmp_fp_entry_by_qn);*out_entries = entries;return count;}@@ -203,7 +226,12 @@ static void sim_query_worker(int worker_id, void *ctx_ptr) {if (strcmp(src->ext, cand->file_ext) != 0) {continue;}- if (src->node_id >= cand->node_id) {+ /* Pair ownership by canonical QN order, not node id: ids are+ * assigned in parallel-merge order and vary run to run, which+ * flipped which side owned a pair and (with the per-source edge+ * cap) flickered the emitted set (determinism). */+ if (!src->qn || !cand->qualified_name ||+ strcmp(src->qn, cand->qualified_name) >= 0) {continue;}@@ -283,6 +311,7 @@ int cbm_pipeline_pass_similarity(cbm_pipeline_ctx_t *ctx) {.fingerprint = &entries[i].fp,.file_path = entries[i].file_path,.file_ext = entries[i].ext,+ .qualified_name = entries[i].qn,};cbm_lsh_insert(lsh, &lsh_entries[i]);}diff --git a/src/simhash/minhash.h b/src/simhash/minhash.hindex 9bfe9445a..cd7a7151a 100644--- a/src/simhash/minhash.h+++ b/src/simhash/minhash.h@@ -88,8 +88,11 @@ typedef struct cbm_lsh_index cbm_lsh_index_t;typedef struct {int64_t node_id;const cbm_minhash_t *fingerprint;- const char *file_path; /* for same-file tagging */- const char *file_ext; /* for same-language filtering */+ const char *file_path; /* for same-file tagging */+ const char *file_ext; /* for same-language filtering */+ const char *qualified_name; /* canonical pair-ownership tie-break: node ids+ vary run-to-run under parallel extraction,+ qualified names do not (determinism) */} cbm_lsh_entry_t;/* Create a new LSH index. */diff --git a/tests/repro/repro_parallel_determinism.c b/tests/repro/repro_parallel_determinism.cindex 6733e8d72..42253d5d1 100644--- a/tests/repro/repro_parallel_determinism.c+++ b/tests/repro/repro_parallel_determinism.c@@ -130,6 +130,13 @@ static char *rpd_index_and_fingerprint(const char *repo, const char *dbpath) {return fp;}+/* GUARD (green <=> the parallel-indexing races are fixed): repeated+ * multi-threaded runs over a fixed corpus must produce the IDENTICAL sorted+ * node+edge set. Root causes fixed (all order/scheduling dependence):+ * semantic-pass admission + canonical funcs order, import target first-match,+ * similarity ordering + id-based pair ownership, call-neighbor truncation+ * subsets, and the QN-collision last-wins overwrite in gbuf upsert AND merge+ * (a C struct/function/macro sharing one name flipped label by merge order). */TEST(repro_parallel_edge_determinism) {struct stat st;if (stat(RPD_CORPUS, &st) != 0 || !S_ISDIR(st.st_mode)) {@@ -140,32 +147,60 @@ TEST(repro_parallel_edge_determinism) {char dbpath[512];snprintf(dbpath, sizeof(dbpath), "%s/cbm_rpd_par_det.db", cbm_tmpdir());- /* Single-threaded reference graph. */- setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);- char *fp_st = rpd_index_and_fingerprint(RPD_CORPUS, dbpath);- unsetenv("CBM_INDEX_SINGLE_THREAD");- ASSERT_NOT_NULL(fp_st);- ASSERT_TRUE(strlen(fp_st) > 0);+ /* First multi-threaded run = reference; every further MT run must match. */+ char *fp_ref = rpd_index_and_fingerprint(RPD_CORPUS, dbpath);+ ASSERT_NOT_NULL(fp_ref);+ ASSERT_TRUE(strlen(fp_ref) > 0);- /* Every multi-threaded run must reproduce the single-threaded graph exactly. */int diverged = 0;- for (int k = 0; k < RPD_MT_RUNS && !diverged; k++) {+ for (int k = 1; k < RPD_MT_RUNS && !diverged; k++) {char *fp_mt = rpd_index_and_fingerprint(RPD_CORPUS, dbpath);ASSERT_NOT_NULL(fp_mt);- if (strcmp(fp_mt, fp_st) != 0)+ if (strcmp(fp_mt, fp_ref) != 0)diverged = 1;free(fp_mt);}unlink(dbpath);- free(fp_st);+ free(fp_ref);- /* RED today: parallel indexing diverges from the single-threaded graph.- * GREEN once the edge-production/merge race is fixed (MT == ST, every run). */ASSERT_EQ(diverged, 0);PASS();}+/* RED (open bug, fix deferred): the SEQUENTIAL pipeline and the PARALLEL+ * pipeline are different code paths that produce SYSTEMATICALLY different+ * graphs — on the xfs corpus they disagree on ~3459 USAGE, ~1666 WRITES and+ * ~60 CALLS sorted-edge lines, consistently (each mode is internally+ * deterministic after the race fixes above; the modes just don't agree).+ * GREEN when both pipelines emit the same graph for the same corpus. */+TEST(repro_seq_parallel_equivalence) {+ struct stat st;+ if (stat(RPD_CORPUS, &st) != 0 || !S_ISDIR(st.st_mode)) {+ SKIP("real-repo tier: corpus " RPD_CORPUS " absent");+ }++ char dbpath[512];+ snprintf(dbpath, sizeof(dbpath), "%s/cbm_rpd_seq_par.db", cbm_tmpdir());++ setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);+ char *fp_st = rpd_index_and_fingerprint(RPD_CORPUS, dbpath);+ unsetenv("CBM_INDEX_SINGLE_THREAD");+ ASSERT_NOT_NULL(fp_st);++ char *fp_mt = rpd_index_and_fingerprint(RPD_CORPUS, dbpath);+ ASSERT_NOT_NULL(fp_mt);++ int equal = strcmp(fp_st, fp_mt) == 0;+ unlink(dbpath);+ free(fp_st);+ free(fp_mt);++ ASSERT_EQ(equal, 1);+ PASS();+}+void suite_repro_parallel_determinism(void) {RUN_TEST(repro_parallel_edge_determinism);+ RUN_TEST(repro_seq_parallel_equivalence);}diff --git a/tests/test_simhash.c b/tests/test_simhash.cindex ef651e31f..f22df753d 100644--- a/tests/test_simhash.c+++ b/tests/test_simhash.c@@ -635,8 +635,9 @@ TEST(pass_similarity_same_file_tagged) {make_fp_props(props, sizeof(props), &fp);cbm_gbuf_t *gb = cbm_gbuf_new("test", "/tmp");- int64_t id_a = cbm_gbuf_upsert_node(gb, "Function", "foo", "test.a.foo", "same.go", 1, 10, props);- cbm_gbuf_upsert_node(gb, "Function", "bar", "test.a.bar", "same.go", 11, 20, props);+ cbm_gbuf_upsert_node(gb, "Function", "foo", "test.a.foo", "same.go", 1, 10, props);+ int64_t id_b =+ cbm_gbuf_upsert_node(gb, "Function", "bar", "test.a.bar", "same.go", 11, 20, props);atomic_int cancelled = 0;cbm_pipeline_ctx_t ctx = {@@ -649,9 +650,11 @@ TEST(pass_similarity_same_file_tagged) {cbm_pipeline_pass_similarity(&ctx);+ /* Pair ownership is canonical by qualified name (determinism fix):+ * "test.a.bar" < "test.a.foo", so bar owns the pair and is the source. */const cbm_gbuf_edge_t **edges = NULL;int edge_count = 0;- cbm_gbuf_find_edges_by_source_type(gb, id_a, "SIMILAR_TO", &edges, &edge_count);+ cbm_gbuf_find_edges_by_source_type(gb, id_b, "SIMILAR_TO", &edges, &edge_count);ASSERT_EQ(edge_count, 1);/* Edge should have same_file property */ASSERT_NOT_NULL(strstr(edges[0]->properties_json, "\"same_file\":true"));