Skip to content

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.

Merge origin/main into fix/go-field-type-hint-owner-segment

Martin Vogela2787346c02d
diff --cc tests/test_pipeline.c
index 666b4674d,303af90f7..49d59d064
--- a/tests/test_pipeline.c
+++ b/tests/test_pipeline.c
@@@ -4411,285 -8168,7925 +8168,8044 @@@ TEST(pipeline_tsconfig_mutation_before_
PASS();
}
- #if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
- static void observe_incremental_generation(const char *db_path, const char *project,
- int generation_size, int *before_count,
- int *after_count) {
- *before_count = -1;
- *after_count = -1;
- cbm_store_t *store = cbm_store_open_path(db_path);
- if (!store || !project) {
- if (store) {
- cbm_store_close(store);
- }
- return;
- }
+ static void fail_unresolved_capture_before_publication(void *userdata) {
+ cbm_pipeline_mark_unresolved_capture_failed(userdata);
+ cbm_pipeline_add_file_error(userdata, "generation.py", "1-1", "parse_partial");
+ }
- int before = 0;
- int after = 0;
- for (int i = 0; i < generation_size; i++) {
- char before_name[32];
- char after_name[32];
- snprintf(before_name, sizeof(before_name), "Before%02d", i);
- snprintf(after_name, sizeof(after_name), "After%02d", i);
- int before_nodes = named_node_count(store, project, before_name);
- int after_nodes = named_node_count(store, project, after_name);
- if (before_nodes < 0 || after_nodes < 0) {
- cbm_store_close(store);
- return;
- }
- before += before_nodes;
- after += after_nodes;
- }
+ TEST(pipeline_capture_failure_preserves_general_coverage_and_rebuilds) {
+ char tmp[256] = "/tmp/cbm_capture_metadata_XXXXXX";
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def GeneralCoverage():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *first = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(first);
+ cbm_pipeline_incremental_test_before_final_manifest_once(
+ fail_unresolved_capture_before_publication, first);
+ ASSERT_EQ(cbm_pipeline_run(first), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(first));
+ cbm_pipeline_free(first);
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(store);
+ cbm_coverage_meta_t meta = {0};
+ ASSERT_EQ(cbm_store_coverage_meta_get(store, project, &meta), CBM_STORE_OK);
+ ASSERT_STR_EQ(meta.recording_status, "complete");
+ ASSERT_FALSE(meta.unresolved_calls_complete);
+ cbm_coverage_row_t *rows = NULL;
+ int row_count = 0;
+ ASSERT_EQ(cbm_store_coverage_get_path(store, project, "generation.py", &rows, &row_count),
+ CBM_STORE_OK);
+ ASSERT_EQ(row_count, 1);
+ ASSERT_STR_EQ(rows[0].kind, "parse_partial");
+ cbm_store_free_coverage(rows, row_count);
+ cbm_store_coverage_meta_clear(&meta);
cbm_store_close(store);
- *before_count = before;
- *after_count = after;
+ /* A partial repair cannot fill an omitted signal for unchanged files. */
+ write_temp_file(tmp, "changed.py", "def NewCoverage():\n return 2\n");
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_incremental_test_force_legacy_partial_once();
+ cbm_pipeline_t *partial = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(partial);
+ ASSERT_EQ(cbm_pipeline_run(partial), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_LEGACY_PARTIAL);
+ cbm_pipeline_free(partial);
+ store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(store);
+ ASSERT_EQ(cbm_store_coverage_meta_get(store, project, &meta), CBM_STORE_OK);
+ ASSERT_STR_EQ(meta.recording_status, "complete");
+ ASSERT_FALSE(meta.unresolved_calls_complete);
+ cbm_store_coverage_meta_clear(&meta);
+ rows = NULL;
+ row_count = 0;
+ ASSERT_EQ(cbm_store_coverage_get_path(store, project, "generation.py", &rows, &row_count),
+ CBM_STORE_OK);
+ ASSERT_EQ(row_count, 1);
+ ASSERT_STR_EQ(rows[0].kind, "parse_partial");
+ cbm_store_free_coverage(rows, row_count);
+ cbm_store_close(store);
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *repair = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(repair);
+ ASSERT_EQ(cbm_pipeline_run(repair), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ cbm_pipeline_free(repair);
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *unchanged = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(unchanged);
+ ASSERT_EQ(cbm_pipeline_run(unchanged), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_NOOP);
+ cbm_pipeline_free(unchanged);
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+ PASS();
}
- /* A parallel incremental run must preserve its prior database when the
- * per-file result cache cannot be allocated. A clean retry must then converge
- * to the new generation.
- *
- * RED before fail-closed propagation: the injected allocation failure skips
- * extract/resolve, but the caller dumps the already-purged graph, advances all
- * file hashes, and returns 0. The second graph is empty and the third run is a
- * no-op instead of recovering the missing definitions. */
- TEST(pipeline_incremental_parallel_result_cache_alloc_failure_preserves_db_and_retries) {
- enum { GENERATION_SIZE = 51 };
- char tmp[256];
- snprintf(tmp, sizeof(tmp), "/tmp/cbm_incr_cache_XXXXXX");
- if (!cbm_mkdtemp(tmp)) {
- FAIL("tmpdir");
- }
+ /* Metadata participates in exact-input compatibility. Old coverage schema or
+ * an upgrade to a more comprehensive discovery/index mode must force a
+ * complete replacement even when every semantic-input byte is unchanged; the
+ * replacement must write current metadata so the next identical run is a
+ * true no-op. Cheaper requests retain fuller published coverage separately. */
+ static int pipeline_exact_inputs_migrate_metadata_and_mode(int legacy_version) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_manifest_metadata_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def ExactMetadataGeneration():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
cbm_pipeline_incremental_test_reset_faults();
- char *old_workers = getenv("CBM_WORKERS");
- char *saved_workers = old_workers ? strdup(old_workers) : NULL;
- char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
- char *saved_single = old_single ? strdup(old_single) : NULL;
- cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
- cbm_setenv("CBM_WORKERS", "4", 1);
-
- int setup_ok = 1;
- for (int i = 0; setup_ok && i < GENERATION_SIZE; i++) {
- char path[512];
- char source[128];
- snprintf(path, sizeof(path), "%s/generation_%02d.py", tmp, i);
- snprintf(source, sizeof(source), "def Before%02d():\n return %d\n", i, i);
- setup_ok = th_write_file(path, source) == 0;
- }
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
- char db_path[512];
- snprintf(db_path, sizeof(db_path), "%s/incremental-cache.db", tmp);
- int first_rc = -1;
- int baseline_before = -1;
- int baseline_after = -1;
- if (setup_ok) {
- cbm_pipeline_t *first = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
- if (first) {
- first_rc = cbm_pipeline_run(first);
- observe_incremental_generation(db_path, cbm_pipeline_project_name(first),
- GENERATION_SIZE, &baseline_before, &baseline_after);
- cbm_pipeline_free(first);
- }
- }
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *exact_before_migration = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(exact_before_migration);
+ ASSERT_EQ(cbm_pipeline_run(exact_before_migration), 0);
+ cbm_incremental_route_t exact_before_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(exact_before_migration);
- int edit_ok = setup_ok && first_rc == 0;
- for (int i = 0; edit_ok && i < GENERATION_SIZE; i++) {
- char path[512];
- char source[160];
- snprintf(path, sizeof(path), "%s/generation_%02d.py", tmp, i);
- snprintf(source, sizeof(source),
- "def After%02d():\n return %d\n# edited generation %02d\n", i, i, i);
- edit_ok = th_write_file(path, source) == 0;
- }
+ cbm_store_t *metadata_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(metadata_store);
+ cbm_coverage_row_t *coverage_rows = NULL;
+ int coverage_count = 0;
+ ASSERT_EQ(cbm_store_coverage_get(metadata_store, project, &coverage_rows, &coverage_count),
+ CBM_STORE_OK);
+ cbm_coverage_meta_t current_meta = {0};
+ ASSERT_EQ(cbm_store_coverage_meta_get(metadata_store, project, &current_meta), CBM_STORE_OK);
+ cbm_coverage_meta_t legacy_meta = current_meta;
+ legacy_meta.coverage_version = legacy_version;
+ ASSERT_EQ(cbm_store_coverage_replace_ex(metadata_store, project, coverage_rows, coverage_count,
+ &legacy_meta),
+ CBM_STORE_OK);
+ cbm_store_free_coverage(coverage_rows, coverage_count);
+ cbm_store_coverage_meta_clear(&current_meta);
+ cbm_store_close(metadata_store);
- int second_rc = -1;
- int second_before = -1;
- int second_after = -1;
- if (edit_ok) {
- cbm_pipeline_incremental_test_fail_result_cache_alloc_once();
- cbm_pipeline_incremental_test_force_legacy_partial_once();
- cbm_pipeline_t *second = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
- if (second) {
- second_rc = cbm_pipeline_run(second);
- observe_incremental_generation(db_path, cbm_pipeline_project_name(second),
- GENERATION_SIZE, &second_before, &second_after);
- cbm_pipeline_free(second);
- }
- }
cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *migration = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(migration);
+ ASSERT_EQ(cbm_pipeline_run(migration), 0);
+ cbm_incremental_route_t migration_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(migration);
+
+ metadata_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(metadata_store);
+ cbm_coverage_meta_t migrated_meta = {0};
+ ASSERT_EQ(cbm_store_coverage_meta_get(metadata_store, project, &migrated_meta), CBM_STORE_OK);
+ int migrated_version = migrated_meta.coverage_version;
+ bool migrated_hashes_complete = migrated_meta.hash_records_complete;
+ char migrated_mode[32];
+ snprintf(migrated_mode, sizeof(migrated_mode), "%s",
+ migrated_meta.index_mode ? migrated_meta.index_mode : "");
+ cbm_store_coverage_meta_clear(&migrated_meta);
+ cbm_store_close(metadata_store);
- int third_rc = -1;
- int retry_before = -1;
- int retry_after = -1;
- if (edit_ok) {
- cbm_pipeline_t *third = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
- if (third) {
- third_rc = cbm_pipeline_run(third);
- observe_incremental_generation(db_path, cbm_pipeline_project_name(third),
- GENERATION_SIZE, &retry_before, &retry_after);
- cbm_pipeline_free(third);
- }
- }
cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *mode_change = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(mode_change);
+ ASSERT_EQ(cbm_pipeline_run(mode_change), 0);
+ cbm_incremental_route_t mode_change_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(mode_change);
- if (saved_workers) {
- cbm_setenv("CBM_WORKERS", saved_workers, 1);
- free(saved_workers);
- } else {
- cbm_unsetenv("CBM_WORKERS");
- }
- if (saved_single) {
- cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
- free(saved_single);
- } else {
- cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
- }
- th_rmtree(tmp);
+ metadata_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(metadata_store);
+ cbm_coverage_meta_t full_meta = {0};
+ ASSERT_EQ(cbm_store_coverage_meta_get(metadata_store, project, &full_meta), CBM_STORE_OK);
+ int full_version = full_meta.coverage_version;
+ bool full_hashes_complete = full_meta.hash_records_complete;
+ char full_mode[32];
+ snprintf(full_mode, sizeof(full_mode), "%s", full_meta.index_mode ? full_meta.index_mode : "");
+ cbm_store_coverage_meta_clear(&full_meta);
+ cbm_store_close(metadata_store);
- bool second_is_preserved_failure = second_rc == CBM_PIPELINE_ABORT_PRESERVE_DB &&
- second_before == GENERATION_SIZE && second_after == 0;
- if (!second_is_preserved_failure) {
- printf(" incremental cache failure diagnostic: rc=%d before=%d after=%d\n", second_rc,
- second_before, second_after);
- }
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *exact_full = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(exact_full);
+ ASSERT_EQ(cbm_pipeline_run(exact_full), 0);
+ cbm_incremental_route_t exact_full_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(exact_full);
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
- ASSERT_TRUE(setup_ok);
- ASSERT_EQ(first_rc, 0);
- ASSERT_EQ(baseline_before, GENERATION_SIZE);
- ASSERT_EQ(baseline_after, 0);
- ASSERT_TRUE(edit_ok);
- ASSERT_TRUE(second_is_preserved_failure);
- ASSERT_EQ(third_rc, 0);
- ASSERT_EQ(retry_before, 0);
- ASSERT_EQ(retry_after, GENERATION_SIZE);
+ ASSERT_EQ(exact_before_route, CBM_INCREMENTAL_ROUTE_NOOP);
+ ASSERT_EQ(migration_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(migrated_version, CBM_SEMANTIC_INDEX_VERSION);
+ ASSERT_TRUE(migrated_hashes_complete);
+ ASSERT_STR_EQ(migrated_mode, "fast");
+ ASSERT_EQ(mode_change_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(full_version, CBM_SEMANTIC_INDEX_VERSION);
+ ASSERT_TRUE(full_hashes_complete);
+ ASSERT_STR_EQ(full_mode, "full");
+ ASSERT_EQ(exact_full_route, CBM_INCREMENTAL_ROUTE_NOOP);
PASS();
}
- #endif
-
- TEST(pipeline_tsjs_receiver_suppresses_weak_method_edge) {
- char tmp[256];
- snprintf(tmp, sizeof(tmp), "/tmp/cbm_tsjs_recv_XXXXXX");
- if (!cbm_mkdtemp(tmp)) {
- FAIL("tmpdir");
- }
- /* The lone project symbol named "test" — a real method. */
- write_temp_file(tmp, "src/client.ts",
- "export class SalesforceRestClient {\n"
- " test(): boolean {\n"
- " return true;\n"
- " }\n"
- "}\n");
- /* Regex receiver: `re.test(s)` calls RegExp.prototype.test, NOT the method.
- * The TS-LSP cannot bind it to a project symbol → the registry would guess
- * "test" by short name (weak). This is the false edge to suppress. */
- write_temp_file(tmp, "src/caller.ts",
- "const re = /^[a-z]+$/;\n"
- "export function checkFormat(s: string): boolean {\n"
- " return re.test(s);\n"
- "}\n");
- /* Typed receiver: `c` is annotated SalesforceRestClient, so the TS-LSP
- * resolves c.test() to the method (lsp_ts_method, conf 0.95) BEFORE the
- * registry runs — the guard's explicit drop-list keeps every lsp_* edge. */
- write_temp_file(tmp, "src/typed.ts",
- "import { SalesforceRestClient } from './client';\n"
- "export function runTyped(c: SalesforceRestClient): boolean {\n"
- " return c.test();\n"
- "}\n");
- /* Bare local call: same-module resolution, unaffected by the guard. */
- write_temp_file(tmp, "src/local.ts",
- "function localHelper(): number {\n"
- " return 1;\n"
- "}\n"
- "export function callsLocal(): number {\n"
- " return localHelper();\n"
- "}\n");
+ TEST(pipeline_exact_inputs_migrate_coverage_metadata_and_index_mode) {
+ return pipeline_exact_inputs_migrate_metadata_and_mode(1);
+ }
- char db_path[512];
- snprintf(db_path, sizeof(db_path), "%s/tsjs_recv.db", tmp);
- cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
- const char *project = cbm_pipeline_project_name(p);
+ /* Published branch version 8 predates language doc links and diagrams.
+ * Unchanged inputs still need a rebuild, followed by an exact no-op. */
+ TEST(pipeline_semantic_version_8_index_is_rebuilt_once) {
+ return pipeline_exact_inputs_migrate_metadata_and_mode(8);
+ }
- cbm_store_t *s = cbm_store_open_path(db_path);
- ASSERT_NOT_NULL(s);
+ /* Published version 10 predates Python lexical-scope call resolution. */
+ TEST(pipeline_semantic_version_10_index_is_rebuilt_once) {
+ return pipeline_exact_inputs_migrate_metadata_and_mode(10);
+ }
- /* (1) The false edge is suppressed (reproduce-first: RED before the fix). */
- ASSERT_FALSE(cross_file_call_exists(s, project, "checkFormat", "test"));
- /* (2) The type-resolved receiver call survives (LSP wins before the guard). */
- ASSERT_TRUE(cross_file_call_exists(s, project, "runTyped", "test"));
- /* (3) The bare local call survives (same-module / lsp_ts_local). */
- ASSERT_TRUE(cross_file_call_exists(s, project, "callsLocal", "localHelper"));
- /* (4) breadth insurance: the real edges are still emitted. */
- ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "CALLS"), 2);
+ typedef struct {
+ bool published;
+ int rename_calls;
+ int export_count;
+ int exports_before_publish;
+ } artifact_publish_observer_t;
- cbm_store_close(s);
- cbm_pipeline_free(p);
- th_rmtree(tmp);
- PASS();
- }
+ static artifact_publish_observer_t *g_artifact_publish_observer;
- /* Python counterpart to the TS/JS receiver guard (#1276), sequential path.
- * Pins BOTH directions. NEGATIVE: an attribute call on an unknown receiver
- * (a parameter) must not bind the lone same-named project method through
- * unique_name. POSITIVE: an import-bound receiver (helper.compute) and a bare
- * local call must still produce their CALLS edges.
- * Fewer than 50 files exercises pass_calls.c. */
- TEST(pipeline_python_receiver_suppresses_weak_method_edge) {
+ static void observe_artifact_publish_log(const char *line) {
+ if (g_artifact_publish_observer && line && strstr(line, "msg=artifact.export")) {
+ g_artifact_publish_observer->export_count++;
+ if (!g_artifact_publish_observer->published) {
+ g_artifact_publish_observer->exports_before_publish++;
+ }
+ }
+ }
+
+ static int observe_successful_publish_rename(const char *staging_path, const char *final_path,
+ void *arg) {
+ artifact_publish_observer_t *observer = (artifact_publish_observer_t *)arg;
+ observer->rename_calls++;
+ int rc = cbm_rename_replace(staging_path, final_path);
+ observer->published = rc == 0;
+ return rc;
+ }
+
+ static int run_observing_artifact_publish(cbm_pipeline_t *pipeline,
+ artifact_publish_observer_t *observer) {
+ cbm_pipeline_set_rename_hook_for_tests(pipeline, observe_successful_publish_rename, observer);
+ CBMLogLevel previous_level = cbm_log_get_level();
+ CBMLogFormat previous_format = cbm_log_get_format();
+ g_artifact_publish_observer = observer;
+ cbm_log_set_level(CBM_LOG_INFO);
+ cbm_log_set_format(CBM_LOG_FORMAT_TEXT);
+ cbm_log_set_sink_ex(observe_artifact_publish_log, CBM_LOG_SINK_REPLACE);
+ int rc = cbm_pipeline_run(pipeline);
+ cbm_log_set_sink(NULL);
+ cbm_log_set_format(previous_format);
+ cbm_log_set_level(previous_level);
+ g_artifact_publish_observer = NULL;
+ return rc;
+ }
+
+ static bool pipeline_reports_excluded_dir(cbm_pipeline_t *pipeline, const char *rel_path) {
+ char **excluded = NULL;
+ int excluded_count = 0;
+ cbm_pipeline_get_excluded(pipeline, &excluded, &excluded_count);
+ for (int i = 0; i < excluded_count; i++) {
+ if (excluded[i] && strcmp(excluded[i], rel_path) == 0) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ typedef struct {
+ int rc;
+ cbm_incremental_route_t route;
+ bool tools_excluded;
+ artifact_publish_observer_t publish;
+ } observed_fast_run_t;
+
+ static observed_fast_run_t run_observed_fast_pipeline(const char *repo_path, const char *db_path) {
+ observed_fast_run_t result = {.rc = CBM_NOT_FOUND};
+ cbm_pipeline_t *pipeline = cbm_pipeline_new(repo_path, db_path, CBM_MODE_FAST);
+ if (!pipeline) {
+ return result;
+ }
+ result.rc = run_observing_artifact_publish(pipeline, &result.publish);
+ result.route = cbm_pipeline_incremental_test_last_route();
+ result.tools_excluded = pipeline_reports_excluded_dir(pipeline, "tools");
+ cbm_pipeline_free(pipeline);
+ return result;
+ }
+
+ typedef struct {
+ int rc;
+ int before_nodes;
+ int after_nodes;
+ } imported_generation_t;
+
+ static imported_generation_t import_artifact_generation(const char *repo_path,
+ const char *import_path,
+ const char *project) {
+ imported_generation_t result = {
+ .rc = cbm_artifact_import(repo_path, import_path),
+ .before_nodes = -1,
+ .after_nodes = -1,
+ };
+ if (result.rc == 0) {
+ observe_named_generation(import_path, project, "StoredBefore", "StoredAfter",
+ &result.before_nodes, &result.after_nodes);
+ }
+ return result;
+ }
+
+ static bool stored_mode_is_full(const char *db_path, const char *project) {
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ if (!store) {
+ return false;
+ }
+ cbm_coverage_meta_t meta = {0};
+ bool full = cbm_store_coverage_meta_get(store, project, &meta) == CBM_STORE_OK &&
+ meta.index_mode && strcmp(meta.index_mode, "full") == 0;
+ cbm_store_coverage_meta_clear(&meta);
+ cbm_store_close(store);
+ return full;
+ }
+
+ /* Once a repository contains a shared artifact, every subsequently published
+ * full generation must refresh it, even when persistence was not explicitly
+ * requested on that invocation. Otherwise the live DB advances while a clean
+ * teammate import silently restores the previous graph. */
+ TEST(pipeline_existing_artifact_refreshes_after_default_forced_full_reindex) {
char tmp[256];
- snprintf(tmp, sizeof(tmp), "/tmp/cbm_python_recv_XXXXXX");
- if (!cbm_mkdtemp(tmp)) {
- FAIL("tmpdir");
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_artifact_refresh_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ char source_path[512];
+ char db_path[512];
+ char imported_path[512];
+ snprintf(source_path, sizeof(source_path), "%s/generation.py", tmp);
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ snprintf(imported_path, sizeof(imported_path), "%s/imported.db", tmp);
+ ASSERT_EQ(th_write_file(source_path, "def ArtifactGenerationBefore():\n return 1\n"), 0);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ artifact_publish_observer_t baseline_observer = {0};
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ cbm_pipeline_set_persistence(baseline, true);
+ int baseline_rc = run_observing_artifact_publish(baseline, &baseline_observer);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+ ASSERT_TRUE(cbm_artifact_exists(tmp));
+
+ ASSERT_EQ(th_write_file(source_path, "def ArtifactGenerationAfter():\n return 2\n"), 0);
+ cbm_pipeline_incremental_test_reset_faults();
+ artifact_publish_observer_t reindex_observer = {0};
+ cbm_pipeline_t *default_reindex = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(default_reindex);
+ int reindex_rc = run_observing_artifact_publish(default_reindex, &reindex_observer);
+ cbm_incremental_route_t reindex_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(default_reindex);
+
+ /* A derived artifact must not become an input that forces another rebuild,
+ * and refreshing it must not switch the authoritative DB back to WAL. */
+ cbm_pipeline_incremental_test_reset_faults();
+ artifact_publish_observer_t explicit_observer = {0};
+ cbm_pipeline_t *explicit_noop = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(explicit_noop);
+ cbm_pipeline_set_persistence(explicit_noop, true);
+ int explicit_rc = run_observing_artifact_publish(explicit_noop, &explicit_observer);
+ cbm_incremental_route_t explicit_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(explicit_noop);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ artifact_publish_observer_t observer = {0};
+ cbm_pipeline_t *unchanged = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(unchanged);
+ int unchanged_rc = run_observing_artifact_publish(unchanged, &observer);
+ cbm_incremental_route_t unchanged_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(unchanged);
+
+ char journal_mode[16] = {0};
+ sqlite3 *raw = NULL;
+ sqlite3_stmt *journal_stmt = NULL;
+ int journal_ok =
+ sqlite3_open_v2(db_path, &raw, SQLITE_OPEN_READONLY, NULL) == SQLITE_OK &&
+ sqlite3_prepare_v2(raw, "PRAGMA journal_mode;", -1, &journal_stmt, NULL) == SQLITE_OK &&
+ sqlite3_step(journal_stmt) == SQLITE_ROW;
+ if (journal_ok) {
+ const unsigned char *mode = sqlite3_column_text(journal_stmt, 0);
+ if (!mode || snprintf(journal_mode, sizeof(journal_mode), "%s", (const char *)mode) >=
+ (int)sizeof(journal_mode)) {
+ journal_ok = 0;
+ }
+ }
+ sqlite3_finalize(journal_stmt);
+ if (raw) {
+ sqlite3_close(raw);
+ }
+
+ int live_before = -1;
+ int live_after = -1;
+ cbm_store_t *live_store = cbm_store_open_path(db_path);
+ if (live_store) {
+ live_before = named_node_count(live_store, project, "ArtifactGenerationBefore");
+ live_after = named_node_count(live_store, project, "ArtifactGenerationAfter");
+ cbm_store_close(live_store);
+ }
+
+ int import_rc = cbm_artifact_import(tmp, imported_path);
+ int artifact_before = -1;
+ int artifact_after = -1;
+ cbm_store_t *artifact_store = import_rc == 0 ? cbm_store_open_path(imported_path) : NULL;
+ if (artifact_store) {
+ artifact_before = named_node_count(artifact_store, project, "ArtifactGenerationBefore");
+ artifact_after = named_node_count(artifact_store, project, "ArtifactGenerationAfter");
+ cbm_store_close(artifact_store);
+ }
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(baseline_rc, 0);
+ ASSERT_EQ(baseline_observer.rename_calls, 1);
+ ASSERT_EQ(baseline_observer.exports_before_publish, 0);
+ ASSERT_EQ(baseline_observer.export_count, 1);
+ ASSERT_EQ(reindex_rc, 0);
+ ASSERT_EQ(reindex_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(reindex_observer.rename_calls, 1);
+ ASSERT_EQ(reindex_observer.exports_before_publish, 0);
+ ASSERT_EQ(reindex_observer.export_count, 1);
+ /* The no-ops are proven on the live generation and publish nothing; the
+ * artifact is still refreshed, from that already published database. */
+ ASSERT_EQ(explicit_rc, 0);
+ ASSERT_EQ(explicit_route, CBM_INCREMENTAL_ROUTE_NOOP);
+ ASSERT_EQ(explicit_observer.rename_calls, 0);
+ ASSERT_EQ(explicit_observer.export_count, 1);
+ ASSERT_EQ(unchanged_rc, 0);
+ ASSERT_EQ(unchanged_route, CBM_INCREMENTAL_ROUTE_NOOP);
+ ASSERT_EQ(observer.rename_calls, 0);
+ ASSERT_EQ(observer.export_count, 1);
+ ASSERT_TRUE(journal_ok);
+ ASSERT_STR_EQ(journal_mode, "delete");
+ ASSERT_EQ(live_before, 0);
+ ASSERT_EQ(live_after, 1);
+ ASSERT_EQ(import_rc, 0);
+ ASSERT_EQ(artifact_before, 0);
+ ASSERT_EQ(artifact_after, 1);
+ PASS();
+ }
+
+ /* Cancellation observed after predump must be an explicit preserved abort,
+ * never a false success. The retry then publishes the edited generation. */
+ TEST(pipeline_full_cancel_after_predump_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_cancel_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ static const char before_source[] = "def BeforeCancel():\n return 1\n";
+ static const char after_source[] = "def AfterCancel():\n return 2\n# changed\n";
+ write_temp_file(tmp, "generation.py", before_source);
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "generation.py", after_source);
+ cbm_pipeline_incremental_test_cancel_after_predump_once();
+ cbm_pipeline_t *cancelled = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(cancelled);
+ int cancelled_rc = cbm_pipeline_run(cancelled);
+ cbm_incremental_route_t cancelled_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(cancelled);
+ int cancelled_before = -1;
+ int cancelled_after = -1;
+ observe_named_generation(db_path, project, "BeforeCancel", "AfterCancel", &cancelled_before,
+ &cancelled_after);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *retry = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(retry);
+ int retry_rc = cbm_pipeline_run(retry);
+ cbm_incremental_route_t retry_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(retry);
+ int retry_before = -1;
+ int retry_after = -1;
+ observe_named_generation(db_path, project, "BeforeCancel", "AfterCancel", &retry_before,
+ &retry_after);
+ int stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(cancelled_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(cancelled_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(cancelled_before, 1);
+ ASSERT_EQ(cancelled_after, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(retry_before, 0);
+ ASSERT_EQ(retry_after, 1);
+ ASSERT_EQ(stage_count, 0);
+ PASS();
+ }
+
+ /* Cancellation can arrive while the destination DB is being quiesced. It must
+ * still be observed at the final commit boundary, before the atomic rename. */
+ TEST(pipeline_full_cancel_after_destination_prepare_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_late_cancel_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def BeforeLateCancel():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "generation.py", "def AfterLateCancel():\n return 2\n# changed\n");
+ cbm_pipeline_incremental_test_cancel_after_destination_prepare_once();
+ cbm_pipeline_t *cancelled = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(cancelled);
+ int cancelled_rc = cbm_pipeline_run(cancelled);
+ cbm_pipeline_free(cancelled);
+
+ int before_count = -1;
+ int after_count = -1;
+ observe_named_generation(db_path, project, "BeforeLateCancel", "AfterLateCancel", &before_count,
+ &after_count);
+ int stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(cancelled_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(before_count, 1);
+ ASSERT_EQ(after_count, 0);
+ ASSERT_EQ(stage_count, 0);
+ PASS();
+ }
+
+ /* A failure after graph serialization but before metadata/publication must
+ * discard only the staged generation. The final path remains the complete old
+ * graph and a clean retry converges. */
+ TEST(pipeline_full_persist_failure_after_stage_dump_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_full_fail_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def BeforeFullPersist():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "generation.py",
+ "def AfterFullPersist():\n return 2\n# changed generation\n");
+ cbm_pipeline_incremental_test_fail_after_stage_dump_once();
+ cbm_pipeline_t *faulted = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(faulted);
+ int faulted_rc = cbm_pipeline_run(faulted);
+ cbm_pipeline_free(faulted);
+ int faulted_before = -1;
+ int faulted_after = -1;
+ observe_named_generation(db_path, project, "BeforeFullPersist", "AfterFullPersist",
+ &faulted_before, &faulted_after);
+ int faulted_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *retry = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(retry);
+ int retry_rc = cbm_pipeline_run(retry);
+ cbm_pipeline_free(retry);
+ int retry_before = -1;
+ int retry_after = -1;
+ observe_named_generation(db_path, project, "BeforeFullPersist", "AfterFullPersist",
+ &retry_before, &retry_after);
+ int retry_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(faulted_rc, CBM_PIPELINE_PERSIST_FAILED);
+ ASSERT_EQ(faulted_before, 1);
+ ASSERT_EQ(faulted_after, 0);
+ ASSERT_EQ(faulted_stage_count, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_before, 0);
+ ASSERT_EQ(retry_after, 1);
+ ASSERT_EQ(retry_stage_count, 0);
+ PASS();
+ }
+
+ /* Keep the legacy partial route test-only so its fail-closed behavior remains
+ * covered even though production semantic changes now force a full rebuild. */
+ TEST(pipeline_incremental_persist_failure_preserves_previous_generation_and_retries) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_incr_fail_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def BeforeIncrementalPersist():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "generation.py",
+ "def AfterIncrementalPersist():\n return 2\n# changed generation\n");
+ cbm_pipeline_incremental_test_force_legacy_partial_once();
+ cbm_pipeline_incremental_test_fail_after_stage_dump_once();
+ cbm_pipeline_t *faulted = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(faulted);
+ int faulted_rc = cbm_pipeline_run(faulted);
+ cbm_incremental_route_t faulted_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(faulted);
+ int faulted_before = -1;
+ int faulted_after = -1;
+ observe_named_generation(db_path, project, "BeforeIncrementalPersist",
+ "AfterIncrementalPersist", &faulted_before, &faulted_after);
+ int faulted_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *retry = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(retry);
+ int retry_rc = cbm_pipeline_run(retry);
+ cbm_incremental_route_t retry_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(retry);
+ int retry_before = -1;
+ int retry_after = -1;
+ observe_named_generation(db_path, project, "BeforeIncrementalPersist",
+ "AfterIncrementalPersist", &retry_before, &retry_after);
+ int retry_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(faulted_rc, CBM_PIPELINE_PERSIST_FAILED);
+ ASSERT_EQ(faulted_route, CBM_INCREMENTAL_ROUTE_LEGACY_PARTIAL);
+ ASSERT_EQ(faulted_before, 1);
+ ASSERT_EQ(faulted_after, 0);
+ ASSERT_EQ(faulted_stage_count, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(retry_before, 0);
+ ASSERT_EQ(retry_after, 1);
+ ASSERT_EQ(retry_stage_count, 0);
+ PASS();
+ }
+
+ TEST(pipeline_incremental_successful_publication_preserves_adr) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_incr_adr_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def BeforeAdrIncremental():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+ static const char adr_text[] = "# Decision\nPreserve across publication.";
+ cbm_store_t *adr_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(adr_store);
+ ASSERT_EQ(cbm_store_adr_store(adr_store, project, adr_text), CBM_STORE_OK);
+ cbm_store_close(adr_store);
+
+ write_temp_file(tmp, "generation.py",
+ "def AfterAdrIncremental():\n return 2\n# changed generation\n");
+ cbm_pipeline_incremental_test_force_legacy_partial_once();
+ cbm_pipeline_t *incremental = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incremental);
+ int run_rc = cbm_pipeline_run(incremental);
+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(incremental);
+ cbm_store_t *published = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(published);
+ cbm_adr_t adr = {0};
+ int adr_rc = cbm_store_adr_get(published, project, &adr);
+ bool adr_matches = adr_rc == CBM_STORE_OK && adr.content && strcmp(adr.content, adr_text) == 0;
+ cbm_store_adr_free(&adr);
+ cbm_store_close(published);
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_LEGACY_PARTIAL);
+ ASSERT_TRUE(adr_matches);
+ PASS();
+ }
+
+ /* A forced-full rebuild must never erase an ADR merely because the old
+ * generation could not be read completely. The capture is part of the
+ * publication transaction: failure preserves both graph and ADR. */
+ TEST(pipeline_full_adr_capture_failure_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_adr_capture_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def BeforeAdrCapture():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ static const char adr_text[] = "# Decision\nADR capture is fail-closed.";
+ cbm_store_t *adr_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(adr_store);
+ ASSERT_EQ(cbm_store_adr_store(adr_store, project, adr_text), CBM_STORE_OK);
+ cbm_store_close(adr_store);
+
+ write_temp_file(tmp, "generation.py", "def AfterAdrCapture():\n return 2\n");
+ cbm_pipeline_incremental_test_fail_adr_capture_once();
+ cbm_pipeline_t *faulted = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(faulted);
+ int faulted_rc = cbm_pipeline_run(faulted);
+ cbm_pipeline_free(faulted);
+
+ int faulted_before = -1;
+ int faulted_after = -1;
+ observe_named_generation(db_path, project, "BeforeAdrCapture", "AfterAdrCapture",
+ &faulted_before, &faulted_after);
+ cbm_store_t *preserved = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(preserved);
+ cbm_adr_t preserved_adr = {0};
+ int preserved_adr_rc = cbm_store_adr_get(preserved, project, &preserved_adr);
+ bool preserved_adr_matches = preserved_adr_rc == CBM_STORE_OK && preserved_adr.content &&
+ strcmp(preserved_adr.content, adr_text) == 0;
+ cbm_store_adr_free(&preserved_adr);
+ cbm_store_close(preserved);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *retry = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(retry);
+ int retry_rc = cbm_pipeline_run(retry);
+ cbm_pipeline_free(retry);
+ int retry_before = -1;
+ int retry_after = -1;
+ observe_named_generation(db_path, project, "BeforeAdrCapture", "AfterAdrCapture", &retry_before,
+ &retry_after);
+ cbm_store_t *published = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(published);
+ cbm_adr_t published_adr = {0};
+ int published_adr_rc = cbm_store_adr_get(published, project, &published_adr);
+ bool published_adr_matches = published_adr_rc == CBM_STORE_OK && published_adr.content &&
+ strcmp(published_adr.content, adr_text) == 0;
+ cbm_store_adr_free(&published_adr);
+ cbm_store_close(published);
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(faulted_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(faulted_before, 1);
+ ASSERT_EQ(faulted_after, 0);
+ ASSERT_TRUE(preserved_adr_matches);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_before, 0);
+ ASSERT_EQ(retry_after, 1);
+ ASSERT_TRUE(published_adr_matches);
+ PASS();
+ }
+
+ /* An exact semantic manifest must fail closed when its repository root cannot
+ * be traversed. A regular file is a deterministic cross-platform opendir
+ * failure that does not depend on process permissions. */
+ TEST(pipeline_semantic_manifest_rejects_non_directory_root) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_manifest_not_dir_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "not-a-directory", "manifest root sentinel\n");
+ char root_path[512];
+ snprintf(root_path, sizeof(root_path), "%s/not-a-directory", tmp);
+
+ cbm_file_hash_t *manifest = NULL;
+ int manifest_count = -1;
+ int rc = cbm_pipeline_build_semantic_manifest("manifest-fail-closed", root_path, NULL, 0, NULL,
+ 0, NULL, NULL, &manifest, &manifest_count);
+ cbm_pipeline_free_semantic_manifest(manifest, manifest_count > 0 ? manifest_count : 0);
+ th_rmtree(tmp);
+
+ ASSERT_TRUE(rc != 0);
+ ASSERT_EQ(manifest_count, 0);
+ PASS();
+ }
+
+ #ifndef _WIN32
+ /* A nested directory the process cannot open (permission-denied) must not
+ * abort the whole manifest walk: it has no control files to contribute, so
+ * it is skipped, and control files in sibling directories still get found.
+ * Root-not-a-directory (above) is a different, still fail-closed case. */
+ TEST(pipeline_semantic_manifest_skips_unreadable_subdirectory) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_manifest_locked_dir_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "readable.py", "def Readable():\n return 1\n");
+ write_temp_file(tmp, "locked/secret.txt", "should never be opened\n");
+ write_temp_file(tmp, "sibling/.gitignore", "*.log\n");
+
+ char locked_path[512];
+ snprintf(locked_path, sizeof(locked_path), "%s/locked", tmp);
+ ASSERT_EQ(chmod(locked_path, 0), 0);
+
+ cbm_file_hash_t *manifest = NULL;
+ int manifest_count = -1;
+ int rc = cbm_pipeline_build_semantic_manifest("manifest-skip-locked", tmp, NULL, 0, NULL, 0,
+ NULL, NULL, &manifest, &manifest_count);
+
+ bool found_sibling_gitignore = false;
+ for (int i = 0; i < manifest_count; i++) {
+ if (manifest[i].rel_path && strcmp(manifest[i].rel_path, "sibling/.gitignore") == 0) {
+ found_sibling_gitignore = true;
+ }
+ }
+
+ chmod(locked_path, 0755);
+ cbm_pipeline_free_semantic_manifest(manifest, manifest_count > 0 ? manifest_count : 0);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(rc, 0);
+ ASSERT_TRUE(found_sibling_gitignore);
+ PASS();
+ }
+ #endif /* !_WIN32 */
+
+ /* A fully validated staged graph must be able to recover from a definitely
+ * non-SQLite destination without deleting evidence or overwriting an earlier
+ * quarantine. The replacement happens only after the corrupt bytes are moved. */
+ TEST(pipeline_full_reindex_quarantines_corrupt_destination_without_overwrite) {
+ static const char corrupt_bytes[] = "not a sqlite database\n";
+ static const char previous_backup[] = "older quarantine\n";
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_corrupt_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "fresh.py", "def FreshAfterCorruption():\n return 1\n");
+ write_temp_file(tmp, "generation.db", corrupt_bytes);
+ write_temp_file(tmp, "generation.db.corrupt", previous_backup);
+
+ char db_path[512];
+ char old_backup_path[512];
+ char new_backup_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ snprintf(old_backup_path, sizeof(old_backup_path), "%s.corrupt", db_path);
+ snprintf(new_backup_path, sizeof(new_backup_path), "%s.corrupt.1", db_path);
+
+ cbm_pipeline_t *pipeline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(pipeline);
+ int run_rc = cbm_pipeline_run(pipeline);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(pipeline));
+ cbm_pipeline_free(pipeline);
+
+ char old_observed[64] = {0};
+ char new_observed[64] = {0};
+ FILE *old_backup_file = cbm_fopen(old_backup_path, "rb");
+ FILE *new_backup_file = cbm_fopen(new_backup_path, "rb");
+ size_t old_size =
+ old_backup_file ? fread(old_observed, 1, sizeof(old_observed) - 1, old_backup_file) : 0;
+ size_t new_size =
+ new_backup_file ? fread(new_observed, 1, sizeof(new_observed) - 1, new_backup_file) : 0;
+ if (old_backup_file) {
+ fclose(old_backup_file);
+ }
+ if (new_backup_file) {
+ fclose(new_backup_file);
+ }
+
+ int fresh_nodes = -1;
+ cbm_store_t *store = cbm_store_open_path_query(db_path);
+ if (store) {
+ fresh_nodes = named_node_count(store, project, "FreshAfterCorruption");
+ cbm_store_close(store);
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_EQ((int)old_size, (int)strlen(previous_backup));
+ ASSERT_STR_EQ(old_observed, previous_backup);
+ ASSERT_EQ((int)new_size, (int)strlen(corrupt_bytes));
+ ASSERT_STR_EQ(new_observed, corrupt_bytes);
+ ASSERT_EQ(fresh_nodes, 1);
+ PASS();
+ }
+
+ /* Readable legacy graphs are replaceable generations, not corruption. The
+ * publication boundary must neither run current-schema migration against the
+ * old edges table nor require an ADR table that did not exist yet. */
+ TEST(pipeline_full_reindex_replaces_legacy_schema_without_quarantine) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_legacy_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "fresh.py", "def FreshAfterLegacy():\n return 1\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ sqlite3 *legacy = NULL;
+ ASSERT_EQ(sqlite3_open_v2(db_path, &legacy, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL),
+ SQLITE_OK);
+ const char *legacy_schema =
+ "CREATE TABLE projects(name TEXT PRIMARY KEY,indexed_at TEXT NOT NULL,root_path TEXT NOT "
+ "NULL);"
+ "CREATE TABLE file_hashes(project TEXT NOT NULL,rel_path TEXT NOT NULL,sha256 TEXT NOT "
+ "NULL,mtime_ns INTEGER NOT NULL DEFAULT 0,size INTEGER NOT NULL DEFAULT 0,PRIMARY KEY "
+ "(project,rel_path));"
+ "CREATE TABLE nodes(id INTEGER PRIMARY KEY,project TEXT NOT NULL,label TEXT NOT NULL,name "
+ "TEXT NOT NULL,qualified_name TEXT NOT NULL,file_path TEXT,start_line INTEGER,end_line "
+ "INTEGER,properties TEXT DEFAULT '{}');"
+ "CREATE TABLE edges(id INTEGER PRIMARY KEY,project TEXT NOT NULL,source_id INTEGER NOT "
+ "NULL,target_id INTEGER NOT NULL,type TEXT NOT NULL,properties TEXT DEFAULT '{}',UNIQUE "
+ "(source_id,target_id,type));";
+ ASSERT_EQ(sqlite3_exec(legacy, legacy_schema, NULL, NULL, NULL), SQLITE_OK);
+ sqlite3_stmt *insert_project = NULL;
+ ASSERT_EQ(sqlite3_prepare_v2(
+ legacy, "INSERT INTO projects(name,indexed_at,root_path) VALUES(?1,'legacy',?2);",
+ -1, &insert_project, NULL),
+ SQLITE_OK);
+ const char *project_name = strrchr(tmp, '/');
+ project_name = project_name ? project_name + 1 : tmp;
+ ASSERT_EQ(sqlite3_bind_text(insert_project, 1, project_name, -1, SQLITE_TRANSIENT), SQLITE_OK);
+ ASSERT_EQ(sqlite3_bind_text(insert_project, 2, tmp, -1, SQLITE_TRANSIENT), SQLITE_OK);
+ ASSERT_EQ(sqlite3_step(insert_project), SQLITE_DONE);
+ sqlite3_finalize(insert_project);
+ sqlite3_close(legacy);
+
+ cbm_pipeline_t *pipeline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(pipeline);
+ int run_rc = cbm_pipeline_run(pipeline);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(pipeline));
+ cbm_pipeline_free(pipeline);
+
+ int fresh_nodes = -1;
+ cbm_store_t *store = cbm_store_open_path_query(db_path);
+ if (store) {
+ fresh_nodes = named_node_count(store, project, "FreshAfterLegacy");
+ cbm_store_close(store);
+ }
+ int generated_column_count = 0;
+ sqlite3 *current = NULL;
+ sqlite3_stmt *column_query = NULL;
+ if (sqlite3_open_v2(db_path, &current, SQLITE_OPEN_READONLY, NULL) == SQLITE_OK &&
+ sqlite3_prepare_v2(current,
+ "SELECT count(*) FROM pragma_table_xinfo('edges') "
+ "WHERE name='local_name_gen';",
+ -1, &column_query, NULL) == SQLITE_OK &&
+ sqlite3_step(column_query) == SQLITE_ROW) {
+ generated_column_count = sqlite3_column_int(column_query, 0);
+ }
+ sqlite3_finalize(column_query);
+ if (current) {
+ sqlite3_close(current);
+ }
+ char quarantine_path[512];
+ snprintf(quarantine_path, sizeof(quarantine_path), "%s.corrupt", db_path);
+ cbm_path_info_t quarantine_info;
+ bool quarantined = cbm_path_info_utf8(quarantine_path, &quarantine_info) == 0;
+ th_rmtree(tmp);
+
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_EQ(fresh_nodes, 1);
+ ASSERT_EQ(generated_column_count, 1);
+ ASSERT_FALSE(quarantined);
+ PASS();
+ }
+ #endif
+
+ /* Re-indexing only a target whose qualified name survives a callable-to-value
+ * edit must not restore the unchanged caller's stale inbound CALL_REFERENCE
+ * snapshot. A fresh full index of the edited sources is the convergence oracle:
+ * the now-non-callable identifier remains a USAGE, never a call relationship. */
+ TEST(pipeline_incremental_changed_target_invalidates_stale_inbound_call_reference) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ref_stale_inbound_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ static const char callable_target_source[] = "export function staleSemanticTarget(): void {}\n";
+ static const char value_target_source[] = "export const staleSemanticTarget = 42;\n";
+ static const char caller_source[] =
+ "import { staleSemanticTarget } from './target';\n"
+ "function acceptStaleSemanticReference(callback: () => void): void {}\n"
+ "export function staleSemanticCaller(): void {\n"
+ " acceptStaleSemanticReference(staleSemanticTarget);\n"
+ "}\n";
+
+ write_temp_file(tmp, "target.ts", callable_target_source);
+ write_temp_file(tmp, "caller.ts", caller_source);
+
+ char incremental_db[512];
+ snprintf(incremental_db, sizeof(incremental_db), "%s/stale-inbound-incremental.db", tmp);
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, incremental_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ const char *baseline_project = cbm_pipeline_project_name(baseline);
+ cbm_store_t *baseline_store = cbm_store_open_path(incremental_db);
+ ASSERT_NOT_NULL(baseline_store);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "CALL_REFERENCE",
+ "staleSemanticCaller", "staleSemanticTarget"),
+ 1);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "USAGE", "staleSemanticCaller",
+ "staleSemanticTarget"),
+ 0);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "CALLS", "staleSemanticCaller",
+ "staleSemanticTarget"),
+ 0);
+ cbm_store_close(baseline_store);
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "target.ts", value_target_source);
+
+ cbm_pipeline_t *incremental = cbm_pipeline_new(tmp, incremental_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incremental);
+ ASSERT_EQ(cbm_pipeline_run(incremental), 0);
+ const char *incremental_project = cbm_pipeline_project_name(incremental);
+ cbm_store_t *incremental_store = cbm_store_open_path(incremental_db);
+ ASSERT_NOT_NULL(incremental_store);
+ int incremental_reference =
+ named_edge_count(incremental_store, incremental_project, "CALL_REFERENCE",
+ "staleSemanticCaller", "staleSemanticTarget");
+ int incremental_usage = named_edge_count(incremental_store, incremental_project, "USAGE",
+ "staleSemanticCaller", "staleSemanticTarget");
+ int incremental_calls = named_edge_count(incremental_store, incremental_project, "CALLS",
+ "staleSemanticCaller", "staleSemanticTarget");
+ cbm_store_close(incremental_store);
+ cbm_pipeline_free(incremental);
+
+ char full_db[512];
+ snprintf(full_db, sizeof(full_db), "%s/stale-inbound-full.db", tmp);
+ cbm_pipeline_t *full = cbm_pipeline_new(tmp, full_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(full);
+ ASSERT_EQ(cbm_pipeline_run(full), 0);
+ const char *full_project = cbm_pipeline_project_name(full);
+ cbm_store_t *full_store = cbm_store_open_path(full_db);
+ ASSERT_NOT_NULL(full_store);
+ int full_reference = named_edge_count(full_store, full_project, "CALL_REFERENCE",
+ "staleSemanticCaller", "staleSemanticTarget");
+ int full_usage = named_edge_count(full_store, full_project, "USAGE", "staleSemanticCaller",
+ "staleSemanticTarget");
+ int full_calls = named_edge_count(full_store, full_project, "CALLS", "staleSemanticCaller",
+ "staleSemanticTarget");
+ cbm_store_close(full_store);
+ cbm_pipeline_free(full);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(full_reference, 0);
+ ASSERT_EQ(full_usage, 1);
+ ASSERT_EQ(full_calls, 0);
+ ASSERT_EQ(incremental_reference, full_reference);
+ ASSERT_EQ(incremental_usage, full_usage);
+ ASSERT_EQ(incremental_calls, full_calls);
+ PASS();
+ }
+
+ /* Registry construction in incremental-parallel mode can materialize serial
+ * resource nodes after extraction establishes the workers' shared-ID
+ * watermark. A subsequent worker-created synthetic node must not reuse that
+ * ID: duplicate temporary IDs make dump-time edge remapping point CONFIGURES
+ * or DECORATES at the wrong target. The second run changes all 51 files so the
+ * production incremental path crosses MIN_FILES_FOR_PARALLEL_INCR. */
+ TEST(pipeline_incremental_parallel_registry_nodes_advance_shared_ids) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_incr_ids_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ char collision_path[512];
+ snprintf(collision_path, sizeof(collision_path), "%s/00_collision.py", tmp);
+ int setup_ok =
+ th_write_file(collision_path, "import os\n"
+ "def incrementalCollisionTarget(): return 1\n"
+ "def incrementalCollisionAccept(callback): pass\n"
+ "@old_marker\n"
+ "def incrementalCollisionCarrier():\n"
+ " incrementalCollisionTarget()\n"
+ " incrementalCollisionAccept(incrementalCollisionTarget)\n"
+ " return os.getenv(\"OLD_TOKEN\")\n") == 0;
+ for (int i = 0; setup_ok && i < 50; i++) {
+ char path[512];
+ char source[128];
+ snprintf(path, sizeof(path), "%s/z_pad_%02d.ts", tmp, i);
+ snprintf(source, sizeof(source), "// initial incremental ID pad %02d\n", i);
+ setup_ok = th_write_file(path, source) == 0;
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/incremental-ids.db", tmp);
+ int first_rc = -1;
+ int second_rc = -1;
+ int env_edge_count = -1;
+ int decorator_edge_count = -1;
+ int misdirected_env_edge_count = -1;
+ int reference_edge_count = -1;
+ int env_node_count = -1;
+ int decorator_node_count = -1;
+
+ if (setup_ok) {
+ cbm_pipeline_t *first = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ if (first) {
+ first_rc = cbm_pipeline_run(first);
+ cbm_pipeline_free(first);
+ }
+ }
+
+ int update_ok =
+ setup_ok && first_rc == 0 &&
+ th_write_file(collision_path, "import os\n"
+ "def incrementalCollisionTarget(): return 1\n"
+ "def incrementalCollisionAccept(callback): pass\n"
+ "@new_marker\n"
+ "def incrementalCollisionCarrier():\n"
+ " incrementalCollisionTarget()\n"
+ " incrementalCollisionAccept(incrementalCollisionTarget)\n"
+ " return os.getenv(\"NEW_TOKEN\")\n"
+ "# incremental size marker\n") == 0;
+ for (int i = 0; update_ok && i < 50; i++) {
+ char path[512];
+ char source[160];
+ snprintf(path, sizeof(path), "%s/z_pad_%02d.ts", tmp, i);
+ snprintf(source, sizeof(source), "// changed incremental ID pad %02d with marker\n", i);
+ update_ok = th_write_file(path, source) == 0;
+ }
+
+ if (update_ok) {
+ cbm_pipeline_t *second = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ if (second) {
+ second_rc = cbm_pipeline_run(second);
+ const char *project = cbm_pipeline_project_name(second);
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ if (store && project) {
+ env_edge_count = named_edge_count(store, project, "CONFIGURES",
+ "incrementalCollisionCarrier", "NEW_TOKEN");
+ decorator_edge_count = named_edge_count(
+ store, project, "DECORATES", "incrementalCollisionCarrier", "new_marker");
+ misdirected_env_edge_count = named_edge_count(
+ store, project, "CONFIGURES", "incrementalCollisionCarrier", "new_marker");
+ reference_edge_count =
+ named_edge_count(store, project, "CALL_REFERENCE",
+ "incrementalCollisionCarrier", "incrementalCollisionTarget");
+ env_node_count = named_node_count(store, project, "NEW_TOKEN");
+ decorator_node_count = named_node_count(store, project, "new_marker");
+ }
+ if (store) {
+ cbm_store_close(store);
+ }
+ cbm_pipeline_free(second);
+ }
+ }
+
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ if (env_node_count != 1 || decorator_node_count != 1 || env_edge_count != 1 ||
+ decorator_edge_count != 1 || misdirected_env_edge_count != 0 || reference_edge_count != 1) {
+ printf(" incremental ID diagnostic: env_node=%d decorator_node=%d "
+ "configures_env=%d decorates=%d configures_decorator=%d call_reference=%d\n",
+ env_node_count, decorator_node_count, env_edge_count, decorator_edge_count,
+ misdirected_env_edge_count, reference_edge_count);
+ }
+
+ ASSERT_TRUE(setup_ok);
+ ASSERT_EQ(first_rc, 0);
+ ASSERT_TRUE(update_ok);
+ ASSERT_EQ(second_rc, 0);
+ ASSERT_EQ(env_node_count, 1);
+ ASSERT_EQ(decorator_node_count, 1);
+ ASSERT_EQ(env_edge_count, 1);
+ ASSERT_EQ(decorator_edge_count, 1);
+ ASSERT_EQ(misdirected_env_edge_count, 0);
+ ASSERT_EQ(reference_edge_count, 1);
+ PASS();
+ }
+
+ #if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ static void observe_incremental_generation(const char *db_path, const char *project,
+ int generation_size, int *before_count,
+ int *after_count) {
+ *before_count = -1;
+ *after_count = -1;
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ if (!store || !project) {
+ if (store) {
+ cbm_store_close(store);
+ }
+ return;
+ }
+
+ int before = 0;
+ int after = 0;
+ for (int i = 0; i < generation_size; i++) {
+ char before_name[32];
+ char after_name[32];
+ snprintf(before_name, sizeof(before_name), "Before%02d", i);
+ snprintf(after_name, sizeof(after_name), "After%02d", i);
+ int before_nodes = named_node_count(store, project, before_name);
+ int after_nodes = named_node_count(store, project, after_name);
+ if (before_nodes < 0 || after_nodes < 0) {
+ cbm_store_close(store);
+ return;
+ }
+ before += before_nodes;
+ after += after_nodes;
+ }
+ cbm_store_close(store);
+ *before_count = before;
+ *after_count = after;
+ }
+
+ /* A parallel incremental run must preserve its prior database when the
+ * per-file result cache cannot be allocated. A clean retry must then converge
+ * to the new generation.
+ *
+ * RED before fail-closed propagation: the injected allocation failure skips
+ * extract/resolve, but the caller dumps the already-purged graph, advances all
+ * file hashes, and returns 0. The second graph is empty and the third run is a
+ * no-op instead of recovering the missing definitions. */
+ TEST(pipeline_incremental_parallel_result_cache_alloc_failure_preserves_db_and_retries) {
+ enum { GENERATION_SIZE = 51 };
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_incr_cache_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ cbm_pipeline_incremental_test_reset_faults();
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ int setup_ok = 1;
+ for (int i = 0; setup_ok && i < GENERATION_SIZE; i++) {
+ char path[512];
+ char source[128];
+ snprintf(path, sizeof(path), "%s/generation_%02d.py", tmp, i);
+ snprintf(source, sizeof(source), "def Before%02d():\n return %d\n", i, i);
+ setup_ok = th_write_file(path, source) == 0;
+ }
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/incremental-cache.db", tmp);
+ int first_rc = -1;
+ int baseline_before = -1;
+ int baseline_after = -1;
+ if (setup_ok) {
+ cbm_pipeline_t *first = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ if (first) {
+ first_rc = cbm_pipeline_run(first);
+ observe_incremental_generation(db_path, cbm_pipeline_project_name(first),
+ GENERATION_SIZE, &baseline_before, &baseline_after);
+ cbm_pipeline_free(first);
+ }
+ }
+
+ int edit_ok = setup_ok && first_rc == 0;
+ for (int i = 0; edit_ok && i < GENERATION_SIZE; i++) {
+ char path[512];
+ char source[160];
+ snprintf(path, sizeof(path), "%s/generation_%02d.py", tmp, i);
+ snprintf(source, sizeof(source),
+ "def After%02d():\n return %d\n# edited generation %02d\n", i, i, i);
+ edit_ok = th_write_file(path, source) == 0;
+ }
+
+ int second_rc = -1;
+ int second_before = -1;
+ int second_after = -1;
+ if (edit_ok) {
+ cbm_pipeline_incremental_test_fail_result_cache_alloc_once();
+ cbm_pipeline_incremental_test_force_legacy_partial_once();
+ cbm_pipeline_t *second = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ if (second) {
+ second_rc = cbm_pipeline_run(second);
+ observe_incremental_generation(db_path, cbm_pipeline_project_name(second),
+ GENERATION_SIZE, &second_before, &second_after);
+ cbm_pipeline_free(second);
+ }
+ }
+ cbm_pipeline_incremental_test_reset_faults();
+
+ int third_rc = -1;
+ int retry_before = -1;
+ int retry_after = -1;
+ if (edit_ok) {
+ cbm_pipeline_t *third = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ if (third) {
+ third_rc = cbm_pipeline_run(third);
+ observe_incremental_generation(db_path, cbm_pipeline_project_name(third),
+ GENERATION_SIZE, &retry_before, &retry_after);
+ cbm_pipeline_free(third);
+ }
+ }
+ cbm_pipeline_incremental_test_reset_faults();
+
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ bool second_is_preserved_failure = second_rc == CBM_PIPELINE_ABORT_PRESERVE_DB &&
+ second_before == GENERATION_SIZE && second_after == 0;
+ if (!second_is_preserved_failure) {
+ printf(" incremental cache failure diagnostic: rc=%d before=%d after=%d\n", second_rc,
+ second_before, second_after);
+ }
+
+ ASSERT_TRUE(setup_ok);
+ ASSERT_EQ(first_rc, 0);
+ ASSERT_EQ(baseline_before, GENERATION_SIZE);
+ ASSERT_EQ(baseline_after, 0);
+ ASSERT_TRUE(edit_ok);
+ ASSERT_TRUE(second_is_preserved_failure);
+ ASSERT_EQ(third_rc, 0);
+ ASSERT_EQ(retry_before, 0);
+ ASSERT_EQ(retry_after, GENERATION_SIZE);
+ PASS();
+ }
+ #endif
+
+ /* #1916: one index of the axios-wrapper fixture, reduced to the edge counts
+ * the test asserts. */
+ typedef struct {
+ int run_rc;
+ int wrapper_http; /* loadWrapperOrders -HTTP_CALLS-> <base>/orders */
+ int wrapper_http_v3; /* same call after the wrapper's base moves to /v3 */
+ int wrapper_http_v3_inv; /* ... and then the caller's path moves to /invoices */
+ int wrapper_raw_http; /* loadWrapperOrders -HTTP_CALLS-> /orders (uncomposed) */
+ int wrapper_route_reg; /* loadWrapperOrders -CALLS-> /orders (phantom route reg) */
+ int named_http; /* named import, base with trailing '/' */
+ int local_http; /* same-file instance spelled axiosInstance */
+ int local_raw_http; /* ... uncomposed (the #523 spelling match) */
+ int dynamic_http; /* non-literal baseURL: path kept, never guessed */
+ int dynamic_route_reg; /* ... misread as a route registration */
+ int direct_http; /* control: axios.get('/direct') */
+ int fake_http; /* look-alike factory.create: never a client */
+ int provider_handles; /* control: Express app.get stays a registration */
+ } AxiosWrapperObs;
+
+ static AxiosWrapperObs observe_axios_wrapper(const char *repo, const char *db) {
+ AxiosWrapperObs o;
+ memset(&o, 0xff, sizeof(o)); /* -1 everywhere: "not observed" */
+ cbm_pipeline_t *p = cbm_pipeline_new(repo, db, CBM_MODE_FULL);
+ if (!p) {
+ return o;
+ }
+ o.run_rc = cbm_pipeline_run(p);
+ const char *proj = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db);
+ if (s && proj) {
+ o.wrapper_http =
+ named_edge_count(s, proj, "HTTP_CALLS", "loadWrapperOrders", "/api/orders");
+ o.wrapper_http_v3 =
+ named_edge_count(s, proj, "HTTP_CALLS", "loadWrapperOrders", "/v3/orders");
+ o.wrapper_http_v3_inv =
+ named_edge_count(s, proj, "HTTP_CALLS", "loadWrapperOrders", "/v3/invoices");
+ o.wrapper_raw_http =
+ named_edge_count(s, proj, "HTTP_CALLS", "loadWrapperOrders", "/orders");
+ o.wrapper_route_reg = named_edge_count(s, proj, "CALLS", "loadWrapperOrders", "/orders");
+ o.named_http = named_edge_count(s, proj, "HTTP_CALLS", "loadNamedItems", "/v2/items");
+ o.local_http = named_edge_count(s, proj, "HTTP_CALLS", "loadLocal", "/local/x");
+ o.local_raw_http = named_edge_count(s, proj, "HTTP_CALLS", "loadLocal", "/x");
+ o.dynamic_http = named_edge_count(s, proj, "HTTP_CALLS", "loadDynamic", "/dynamic");
+ o.dynamic_route_reg = named_edge_count(s, proj, "CALLS", "loadDynamic", "/dynamic");
+ o.direct_http = named_edge_count(s, proj, "HTTP_CALLS", "loadDirectOrders", "/direct");
+ o.fake_http = named_edge_count(s, proj, "HTTP_CALLS", "loadFake", "/api/fake");
+ o.provider_handles = named_edge_count(s, proj, "HANDLES", "provideOrders", "/api/orders");
+ }
+ if (s) {
+ cbm_store_close(s);
+ }
+ cbm_pipeline_free(p);
+ return o;
+ }
+
+ /* #1916: `const api = axios.create({ baseURL: '/api' }); export default api`
+ * in one module and `api.get('/orders')` in another is THE Vue-admin wrapper
+ * pattern. The call must become HTTP_CALLS to GET /api/orders — before the
+ * fix the `.get` suffix made it an Express route REGISTRATION (a CALLS edge
+ * to a phantom server route /orders) and cross-repo matching found nothing.
+ * 52 fillers put the default run on the parallel resolver; the
+ * single-thread run is the sequential oracle; a same-DB reindex after the
+ * wrapper's base changes must converge with the fresh index. */
+ TEST(pipeline_axios_wrapper_baseurl_composes_http_calls_issue1916) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_axios_wrapper_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "src/client.ts",
+ "import axios from 'axios';\n"
+ "const api = axios.create({ baseURL: '/api', timeout: 5000 });\n"
+ "export default api;\n");
+ write_temp_file(
+ tmp, "src/orders.ts",
+ "import api from './client';\n"
+ "import axios from 'axios';\n"
+ "export function loadWrapperOrders(): unknown { return api.get('/orders'); }\n"
+ "export function loadDirectOrders(): unknown { return axios.get('/direct'); }\n");
+ write_temp_file(tmp, "src/named-client.ts",
+ "import axios from 'axios';\n"
+ "export const http = axios.create({ baseURL: '/v2/' });\n");
+ write_temp_file(tmp, "src/named-caller.ts",
+ "import { http } from './named-client';\n"
+ "export function loadNamedItems(): unknown { return http.post('/items'); }\n");
+ write_temp_file(tmp, "src/local.ts",
+ "import axios from 'axios';\n"
+ "const axiosInstance = axios.create({ baseURL: '/local' });\n"
+ "export function loadLocal(): unknown { return axiosInstance.get('/x'); }\n");
+ write_temp_file(tmp, "src/dynamic-client.ts",
+ "import axios from 'axios';\n"
+ "const dynamicApi = axios.create({ baseURL: process.env.API_BASE });\n"
+ "export default dynamicApi;\n");
+ write_temp_file(
+ tmp, "src/dynamic-caller.ts",
+ "import dynamicApi from './dynamic-client';\n"
+ "export function loadDynamic(): unknown { return dynamicApi.get('/dynamic'); }\n");
+ write_temp_file(tmp, "src/fake-client.ts",
+ "const factory = { create: (config: unknown) => config };\n"
+ "const fakeApi = factory.create({ baseURL: '/api' });\n"
+ "export default fakeApi;\n");
+ write_temp_file(tmp, "src/fake-caller.ts",
+ "import fakeApi from './fake-client';\n"
+ "export function loadFake(): unknown { return fakeApi.get('/fake'); }\n");
+ write_temp_file(tmp, "src/provider.ts",
+ "import express from 'express';\n"
+ "const app = express();\n"
+ "function provideOrders(): void {}\n"
+ "app.get('/api/orders', provideOrders);\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/wrapper_pad_%02d.ts", i);
+ snprintf(body, sizeof(body), "export function wrapperPad%02d(): number { return %d; }\n", i,
+ i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+
+ char db_seq[512];
+ char db_par[512];
+ char db_fresh[512];
+ char db_fresh2[512];
+ snprintf(db_seq, sizeof(db_seq), "%s/seq.db", tmp);
+ snprintf(db_par, sizeof(db_par), "%s/par.db", tmp);
+ snprintf(db_fresh, sizeof(db_fresh), "%s/fresh.db", tmp);
+ snprintf(db_fresh2, sizeof(db_fresh2), "%s/fresh2.db", tmp);
+
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ AxiosWrapperObs seq = observe_axios_wrapper(tmp, db_seq);
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ AxiosWrapperObs par = observe_axios_wrapper(tmp, db_par);
+
+ /* Only the wrapper changes; the importing caller is untouched. */
+ write_temp_file(tmp, "src/client.ts",
+ "import axios from 'axios';\n"
+ "const api = axios.create({ baseURL: '/v3' });\n"
+ "export default api;\n");
+ AxiosWrapperObs incr = observe_axios_wrapper(tmp, db_par);
+ AxiosWrapperObs fresh = observe_axios_wrapper(tmp, db_fresh);
+ /* Then only the caller changes; the (unchanged) wrapper's base must
+ * still be found when the caller alone is re-resolved. */
+ write_temp_file(
+ tmp, "src/orders.ts",
+ "import api from './client';\n"
+ "import axios from 'axios';\n"
+ "export function loadWrapperOrders(): unknown { return api.get('/invoices'); }\n"
+ "export function loadDirectOrders(): unknown { return axios.get('/direct'); }\n");
+ AxiosWrapperObs incr2 = observe_axios_wrapper(tmp, db_par);
+ AxiosWrapperObs fresh2 = observe_axios_wrapper(tmp, db_fresh2);
+
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(seq.run_rc, 0);
+ ASSERT_EQ(par.run_rc, 0);
+ /* Controls: direct axios and an Express registration are unchanged, and
+ * a look-alike factory never becomes a client. */
+ ASSERT_EQ(seq.direct_http, 1);
+ ASSERT_EQ(seq.provider_handles, 1);
+ ASSERT_EQ(seq.fake_http, 0);
+
+ /* The issue: default-imported wrapper composes base + path. */
+ ASSERT_EQ(seq.wrapper_http, 1);
+ ASSERT_EQ(seq.wrapper_raw_http, 0);
+ ASSERT_EQ(seq.wrapper_route_reg, 0);
+ ASSERT_EQ(seq.named_http, 1);
+ ASSERT_EQ(seq.local_http, 1);
+ ASSERT_EQ(seq.local_raw_http, 0);
+ ASSERT_EQ(seq.dynamic_http, 1);
+ ASSERT_EQ(seq.dynamic_route_reg, 0);
+
+ /* Sequential and parallel resolvers agree edge for edge. */
+ ASSERT_MEM_EQ(&seq, &par, sizeof(seq));
+
+ /* Reindex after the base moved converges with a fresh index. */
+ ASSERT_EQ(fresh.run_rc, 0);
+ ASSERT_EQ(fresh.wrapper_http_v3, 1);
+ ASSERT_EQ(fresh.wrapper_http, 0);
+ ASSERT_EQ(incr.run_rc, 0);
+ ASSERT_MEM_EQ(&incr, &fresh, sizeof(fresh));
+ ASSERT_EQ(fresh2.run_rc, 0);
+ ASSERT_EQ(fresh2.wrapper_http_v3_inv, 1);
+ ASSERT_EQ(fresh2.wrapper_http_v3, 0);
+ ASSERT_MEM_EQ(&incr2, &fresh2, sizeof(fresh2));
+ PASS();
+ }
+
+ /* Issue #1354: a method call on an instance built with `new ImportedClass()`
+ * produced no CALLS edge (only the constructor edge), while the identical
+ * shape in the class's own file resolved via lsp_ts_method. End to end:
+ * both cross-file shapes must now carry the type-aware lsp_ts_method edge,
+ * and the same-file control must keep it. */
+ TEST(pipeline_ts_crossfile_new_instance_method_call_issue1354) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ts_1354_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ /* write_temp_file creates one directory level only. */
+ write_temp_file(tmp, "lib/toast.service.ts",
+ "export class ToastService {\n"
+ " openSuccessUniqueXyz(msg: string): void {\n"
+ " console.log(msg);\n"
+ " }\n"
+ "}\n"
+ "\n"
+ "export function sameFileControl(): void {\n"
+ " const t = new ToastService();\n"
+ " t.openSuccessUniqueXyz('same-file control');\n"
+ "}\n");
+ write_temp_file(tmp, "app/variants.ts",
+ "import { ToastService } from '../lib/toast.service';\n"
+ "\n"
+ "export function crossNewLocal(): void {\n"
+ " const t = new ToastService();\n"
+ " t.openSuccessUniqueXyz('cross-file');\n"
+ "}\n"
+ "\n"
+ "export function crossNewChain(): void {\n"
+ " new ToastService().openSuccessUniqueXyz('chained');\n"
+ "}\n");
+ /* File named after its class (`NotifierService.ts` exports
+ * `NotifierService`): the imported module QN already ends in the class
+ * name, which must not be mistaken for the class QN. */
+ write_temp_file(tmp, "lib/NotifierService.ts",
+ "export class NotifierService {\n"
+ " notifyUniqueAbc(): void {}\n"
+ "}\n");
+ write_temp_file(tmp, "app/notify.ts",
+ "import { NotifierService } from '../lib/NotifierService';\n"
+ "\n"
+ "export function crossSameNameNew(): void {\n"
+ " const n = new NotifierService();\n"
+ " n.notifyUniqueAbc();\n"
+ "}\n"
+ "\n"
+ "export function crossSameNameTyped(n: NotifierService): void {\n"
+ " n.notifyUniqueAbc();\n"
+ "}\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/ts_1354.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ bool same_file = cross_file_call_has_strategy(s, project, "sameFileControl",
+ "openSuccessUniqueXyz", "lsp_ts_method");
+ bool cross_local = cross_file_call_has_strategy(s, project, "crossNewLocal",
+ "openSuccessUniqueXyz", "lsp_ts_method");
+ bool cross_chain = cross_file_call_has_strategy(s, project, "crossNewChain",
+ "openSuccessUniqueXyz", "lsp_ts_method");
+ bool same_name_new = cross_file_call_has_strategy(s, project, "crossSameNameNew",
+ "notifyUniqueAbc", "lsp_ts_method");
+ bool same_name_typed = cross_file_call_has_strategy(s, project, "crossSameNameTyped",
+ "notifyUniqueAbc", "lsp_ts_method");
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+
+ ASSERT_TRUE(same_file);
+ ASSERT_TRUE(cross_local);
+ ASSERT_TRUE(cross_chain);
+ ASSERT_TRUE(same_name_new);
+ ASSERT_TRUE(same_name_typed);
+ PASS();
+ }
+
+ /* Issue #2297: a call through `import { foo as fooShared }` produced no CALLS
+ * edge, so trace_path(foo, inbound) missed the caller. End to end through the
+ * real pipeline: the renamed call, an app-local wrapper that shares the
+ * exported name, and a method on a renamed class import all reach the
+ * exported member, while the plain named import control keeps lsp_ts_import. */
+ TEST(pipeline_ts_renamed_import_call_issue2297) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ts_2297_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "src/lib.ts",
+ "export function fooUniqueQrs(x: number): number {\n"
+ " return x + 1;\n"
+ "}\n"
+ "export function buildHealthUniqueQrs(input: { a: number }): number {\n"
+ " return input.a;\n"
+ "}\n"
+ "export class ConnUniqueQrs {\n"
+ " pingUniqueQrs(): number {\n"
+ " return 1;\n"
+ " }\n"
+ "}\n");
+ write_temp_file(tmp, "src/plain.ts",
+ "import { fooUniqueQrs } from './lib';\n"
+ "export function callsPlain(): number {\n"
+ " return fooUniqueQrs(1);\n"
+ "}\n");
+ write_temp_file(tmp, "src/renamed.ts",
+ "import { fooUniqueQrs as fooShared } from './lib';\n"
+ "export function callsRenamed(): number {\n"
+ " return fooShared(1);\n"
+ "}\n");
+ write_temp_file(tmp, "src/wrapper.ts",
+ "import { buildHealthUniqueQrs as buildShared } from './lib';\n"
+ "export function buildHealthUniqueQrs(input: { a: number }): number {\n"
+ " return buildShared({ ...input });\n"
+ "}\n");
+ write_temp_file(tmp, "src/klass.ts",
+ "import { ConnUniqueQrs as Connection } from './lib';\n"
+ "export function viaRenamedClass(): number {\n"
+ " return new Connection().pingUniqueQrs();\n"
+ "}\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/ts_2297.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ bool plain =
+ cross_file_call_has_strategy(s, project, "callsPlain", "fooUniqueQrs", "lsp_ts_import");
+ bool renamed = cross_file_call_has_strategy(s, project, "callsRenamed", "fooUniqueQrs",
+ "lsp_import_alias");
+ char wrapper_qn[512];
+ char exported_qn[512];
+ snprintf(wrapper_qn, sizeof(wrapper_qn), "%s.src.wrapper.buildHealthUniqueQrs", project);
+ snprintf(exported_qn, sizeof(exported_qn), "%s.src.lib.buildHealthUniqueQrs", project);
+ cbm_node_t wrapper_node = {0};
+ cbm_node_t exported_node = {0};
+ bool wrapper = false;
+ bool recursive = false;
+ if (cbm_store_find_node_by_qn(s, project, wrapper_qn, &wrapper_node) == CBM_STORE_OK &&
+ cbm_store_find_node_by_qn(s, project, exported_qn, &exported_node) == CBM_STORE_OK) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ cbm_store_find_edges_by_source_type(s, wrapper_node.id, "CALLS", &edges, &edge_count);
+ for (int i = 0; i < edge_count; i++) {
+ if (edges[i].target_id == exported_node.id && edges[i].properties_json &&
+ strstr(edges[i].properties_json, "lsp_import_alias"))
+ wrapper = true;
+ if (edges[i].target_id == wrapper_node.id)
+ recursive = true;
+ }
+ cbm_store_free_edges(edges, edge_count);
+ }
+ cbm_node_free_fields(&wrapper_node);
+ cbm_node_free_fields(&exported_node);
+ bool renamed_class = cross_file_call_has_strategy(s, project, "viaRenamedClass",
+ "pingUniqueQrs", "lsp_ts_method");
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+
+ ASSERT_TRUE(plain);
+ ASSERT_TRUE(renamed);
+ ASSERT_TRUE(wrapper);
+ ASSERT_FALSE(recursive);
+ ASSERT_TRUE(renamed_class);
+ PASS();
+ }
+
+ /* A query failure is distinct from a valid zero-edge result. */
+ static int ts514_pipeline_count(cbm_store_t *store, const char *sql, const char **values,
+ int value_count) {
+ sqlite3_stmt *stmt = NULL;
+ sqlite3 *db = cbm_store_get_db(store);
+ if (!db || sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
+ sqlite3_finalize(stmt);
+ return -1;
+ }
+ bool bound = sqlite3_bind_parameter_count(stmt) == value_count;
+ for (int i = 0; bound && i < value_count; i++)
+ bound = values[i] &&
+ sqlite3_bind_text(stmt, i + 1, values[i], -1, SQLITE_TRANSIENT) == SQLITE_OK;
+ int count = -1;
+ if (bound && sqlite3_step(stmt) == SQLITE_ROW) {
+ count = sqlite3_column_int(stmt, 0);
+ if (sqlite3_step(stmt) != SQLITE_DONE)
+ count = -1;
+ }
+ if (sqlite3_finalize(stmt) != SQLITE_OK)
+ count = -1;
+ return count;
+ }
+
+ /* #514: constructor injection and new-initialized fields resolve through both
+ * drivers. Same-named methods make wrong-owner and self-loop claims meaningful.
+ * Every negative has a real extracted call, source and target, plus successful
+ * queries and typed positive controls in the same run. */
+ TEST(pipeline_ts_param_property_injection_issue514) {
+ static const char *paths[] = {"cats/service.ts", "cats/controller.ts", "cats/reporter.ts"};
+ static const char *sources[] = {
+ "export class BaseService { findAll(): string[] { return []; } }\n"
+ "export class CatService extends BaseService { findAll(): string[] { return ['cat']; } }\n",
+ "import { CatService } from './service';\n"
+ "export class CatController {\n"
+ " constructor(private readonly catService: CatService, plain: CatService) {}\n"
+ " findAll() { return this.catService.findAll(); }\n"
+ " direct(control: CatService) { return control.findAll(); }\n"
+ " viaPlain() { return this.plain.findAll(); }\n"
+ "}\n",
+ "import { CatService, BaseService } from './service';\n"
+ "function makeService(): CatService { return new CatService(); }\n"
+ "export class CatReporter {\n"
+ " private fresh = new CatService();\n"
+ " private annotated: BaseService = new CatService();\n"
+ " private factory = makeService();\n"
+ " constructor(protected cats: CatService) {}\n"
+ " reportInjected() { return this.cats.findAll(); }\n"
+ " reportLocal() { return this.fresh.findAll(); }\n"
+ " reportAnnotated() { return this.annotated.findAll(); }\n"
+ " reportFactory() { return this.factory.findAll(); }\n"
+ "}\n",
+ };
+ static const struct {
+ int file;
+ const char *symbol;
+ const char *expression;
+ const char *callee;
+ const char *target;
+ int want;
+ } cases[] = {
+ {1, "CatController.direct", "control.findAll()", "control.findAll", "CatService.findAll",
+ 1},
+ {1, "CatController.findAll", "this.catService.findAll()", "this.catService.findAll",
+ "CatService.findAll", 1},
+ {2, "CatReporter.reportInjected", "this.cats.findAll()", "this.cats.findAll",
+ "CatService.findAll", 1},
+ {2, "CatReporter.reportLocal", "this.fresh.findAll()", "this.fresh.findAll",
+ "CatService.findAll", 1},
+ {2, "CatReporter.reportAnnotated", "this.annotated.findAll()", "this.annotated.findAll",
+ "BaseService.findAll", 1},
+ {1, "CatController.viaPlain", "this.plain.findAll()", "this.plain.findAll",
+ "CatService.findAll", 0},
+ {2, "CatReporter.reportFactory", "this.factory.findAll()", "this.factory.findAll",
+ "CatService.findAll", 0},
+ };
+ enum { NCASES = (int)(sizeof(cases) / sizeof(cases[0])) };
+ static const char node_sql[] = "SELECT count(*) FROM nodes WHERE project=?1 AND "
+ "qualified_name=?2 AND file_path=?3 AND label='Method'";
+ static const char edge_sql[] =
+ "SELECT count(*) FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON "
+ "t.id=e.target_id "
+ "WHERE e.project=?1 AND e.type='CALLS' AND s.qualified_name=?2 AND s.file_path=?3 "
+ "AND t.qualified_name=?4 AND t.file_path=?5 "
+ "AND (?6='' OR json_extract(e.properties,'$.strategy')=?6)";
+
+ CBMFileResult *fr[3] = {0};
+ bool extraction_ok = true;
+ for (int i = 0; i < 3; i++) {
+ fr[i] = cbm_extract_file(sources[i], (int)strlen(sources[i]), CBM_LANG_TYPESCRIPT,
+ "ts514_probe", paths[i], 0, NULL, NULL);
+ extraction_ok = extraction_ok && fr[i] && !fr[i]->has_error;
+ }
+ int occurrences[NCASES] = {0};
+ if (extraction_ok) {
+ for (int i = 0; i < NCASES; i++) {
+ int file = cases[i].file;
+ const char *site = strstr(sources[file], cases[i].expression);
+ char *caller = cbm_pipeline_fqn_compute("ts514_probe", paths[file], cases[i].symbol);
+ for (int c = 0; site && caller && c < fr[file]->calls.count; c++) {
+ const CBMCall *call = &fr[file]->calls.items[c];
+ uint32_t start = (uint32_t)(site - sources[file]);
+ if (call->enclosing_func_qn && strcmp(call->enclosing_func_qn, caller) == 0 &&
+ call->callee_name && strcmp(call->callee_name, cases[i].callee) == 0 &&
+ call->site_start_byte == start &&
+ call->site_end_byte == start + strlen(cases[i].expression) &&
+ call->start_line > 0)
+ occurrences[i]++;
+ }
+ free(caller);
+ }
+ }
+ for (int i = 0; i < 3; i++)
+ cbm_free_result(fr[i]);
+
+ const char *old_workers = getenv("CBM_WORKERS");
+ const char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+ if ((old_workers && !saved_workers) || (old_single && !saved_single)) {
+ free(saved_workers);
+ free(saved_single);
+ FAIL("save environment");
+ }
+ char tmp[256] = "/tmp/cbm_ts_514_XXXXXX";
+ if (!cbm_mkdtemp(tmp)) {
+ free(saved_workers);
+ free(saved_single);
+ FAIL("tmpdir");
+ }
+ for (int i = 0; i < 3; i++)
+ write_temp_file(tmp, paths[i], sources[i]);
+ for (int i = 0; i < 52; i++) {
+ char name[64], body[128];
+ snprintf(name, sizeof(name), "cats/filler%d.ts", i);
+ snprintf(body, sizeof(body), "export function filler%d(): number { return %d; }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ int run_rc[2] = {-1, -1}, files[2] = {-1, -1};
+ int edges[2][NCASES], source_nodes[2][NCASES], target_nodes[2][NCASES];
+ int unresolved_calls[2][2] = {{-1, -1}, {-1, -1}};
+ int self_loop[2] = {-1, -1}, annotation_wrong[2] = {-1, -1};
+ bool configured[2] = {false, false}, opened[2] = {false, false};
+ for (int mode = 0; mode < 2; mode++) {
+ for (int i = 0; i < NCASES; i++)
+ edges[mode][i] = source_nodes[mode][i] = target_nodes[mode][i] = -1;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ if (mode == 0)
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ else
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ const char *workers = getenv("CBM_WORKERS");
+ const char *single = getenv("CBM_INDEX_SINGLE_THREAD");
+ configured[mode] = workers && strcmp(workers, "4") == 0 &&
+ (mode == 0 ? single && strcmp(single, "1") == 0 : !single);
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/ts514_%d.db", tmp, mode);
+ cbm_pipeline_t *pipeline =
+ configured[mode] ? cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL) : NULL;
+ run_rc[mode] = pipeline ? cbm_pipeline_run(pipeline) : -1;
+ cbm_store_t *store = run_rc[mode] == 0 ? cbm_store_open_path(db_path) : NULL;
+ opened[mode] = store != NULL;
+ if (store) {
+ const char *project = cbm_pipeline_project_name(pipeline);
+ const char *file_values[] = {project};
+ files[mode] = ts514_pipeline_count(
+ store, "SELECT count(*) FROM nodes WHERE project=?1 AND label='File'", file_values,
+ 1);
+ for (int i = 0; i < NCASES; i++) {
+ char *src =
+ cbm_pipeline_fqn_compute(project, paths[cases[i].file], cases[i].symbol);
+ char *tgt = cbm_pipeline_fqn_compute(project, paths[0], cases[i].target);
+ const char *src_values[] = {project, src, paths[cases[i].file]};
+ const char *tgt_values[] = {project, tgt, paths[0]};
+ source_nodes[mode][i] = ts514_pipeline_count(store, node_sql, src_values, 3);
+ target_nodes[mode][i] = ts514_pipeline_count(store, node_sql, tgt_values, 3);
+ const char *edge_values[] = {
+ project, src, paths[cases[i].file],
+ tgt, paths[0], cases[i].want ? "lsp_ts_method" : ""};
+ edges[mode][i] = ts514_pipeline_count(store, edge_sql, edge_values, 6);
+ if (!cases[i].want)
+ unresolved_calls[mode][i - 5] = ts514_pipeline_count(
+ store,
+ "SELECT count(*) FROM edges e JOIN nodes s ON s.id=e.source_id "
+ "WHERE e.project=?1 AND e.type='CALLS' "
+ "AND s.qualified_name=?2 AND s.file_path=?3",
+ src_values, 3);
+ if (i == 1) {
+ edge_values[3] = src;
+ edge_values[4] = paths[cases[i].file];
+ edge_values[5] = "";
+ self_loop[mode] = ts514_pipeline_count(store, edge_sql, edge_values, 6);
+ }
+ if (i == 4) {
+ char *wrong = cbm_pipeline_fqn_compute(project, paths[0], "CatService.findAll");
+ edge_values[3] = wrong;
+ edge_values[5] = "";
+ annotation_wrong[mode] = ts514_pipeline_count(store, edge_sql, edge_values, 6);
+ free(wrong);
+ }
+ free(src);
+ free(tgt);
+ }
+ cbm_store_close(store);
+ }
+ cbm_pipeline_free(pipeline);
+ }
+ if (saved_workers)
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ else
+ cbm_unsetenv("CBM_WORKERS");
+ if (saved_single)
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ else
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ const char *restored_workers = getenv("CBM_WORKERS");
+ const char *restored_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ bool restored =
+ (saved_workers ? restored_workers && strcmp(saved_workers, restored_workers) == 0
+ : !restored_workers) &&
+ (saved_single ? restored_single && strcmp(saved_single, restored_single) == 0
+ : !restored_single);
+ free(saved_workers);
+ free(saved_single);
+ th_rmtree(tmp);
+
+ ASSERT_TRUE(extraction_ok);
+ ASSERT_TRUE(restored);
+ for (int i = 0; i < NCASES; i++)
+ ASSERT_EQ(occurrences[i], 1);
+ for (int mode = 0; mode < 2; mode++) {
+ ASSERT_TRUE(configured[mode]);
+ ASSERT_EQ(run_rc[mode], 0);
+ ASSERT_TRUE(opened[mode]);
+ ASSERT_GTE(files[mode], 55);
+ for (int i = 0; i < NCASES; i++) {
+ ASSERT_EQ(source_nodes[mode][i], 1);
+ ASSERT_EQ(target_nodes[mode][i], 1);
+ ASSERT_EQ(edges[mode][i], cases[i].want);
+ }
+ ASSERT_EQ(unresolved_calls[mode][0], 0);
+ ASSERT_EQ(unresolved_calls[mode][1], 0);
+ ASSERT_EQ(self_loop[mode], 0);
+ ASSERT_EQ(annotation_wrong[mode], 0);
+ }
+ PASS();
+ }
+
+ TEST(pipeline_tsjs_receiver_suppresses_weak_method_edge) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_tsjs_recv_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ /* The lone project symbol named "test" — a real method. */
+ write_temp_file(tmp, "src/client.ts",
+ "export class SalesforceRestClient {\n"
+ " test(): boolean {\n"
+ " return true;\n"
+ " }\n"
+ "}\n");
+ /* Regex receiver: `re.test(s)` calls RegExp.prototype.test, NOT the method.
+ * The TS-LSP cannot bind it to a project symbol → the registry would guess
+ * "test" by short name (weak). This is the false edge to suppress. */
+ write_temp_file(tmp, "src/caller.ts",
+ "const re = /^[a-z]+$/;\n"
+ "export function checkFormat(s: string): boolean {\n"
+ " return re.test(s);\n"
+ "}\n");
+ /* Typed receiver: `c` is annotated SalesforceRestClient, so the TS-LSP
+ * resolves c.test() to the method (lsp_ts_method, conf 0.95) BEFORE the
+ * registry runs — the guard's explicit drop-list keeps every lsp_* edge. */
+ write_temp_file(tmp, "src/typed.ts",
+ "import { SalesforceRestClient } from './client';\n"
+ "export function runTyped(c: SalesforceRestClient): boolean {\n"
+ " return c.test();\n"
+ "}\n");
+ /* Bare local call: same-module resolution, unaffected by the guard. */
+ write_temp_file(tmp, "src/local.ts",
+ "function localHelper(): number {\n"
+ " return 1;\n"
+ "}\n"
+ "export function callsLocal(): number {\n"
+ " return localHelper();\n"
+ "}\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/tsjs_recv.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* (1) The false edge is suppressed (reproduce-first: RED before the fix). */
+ ASSERT_GTE(fixture_node_count(s, project, "src/caller.ts", "checkFormat", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "src/client.ts", "test", "Method"), 1);
+ ASSERT_FALSE(cross_file_call_exists(s, project, "checkFormat", "test"));
+ /* (2) The type-resolved receiver call survives (LSP wins before the guard). */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "runTyped", "test"));
+ /* (3) The bare local call survives (same-module / lsp_ts_local). */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "callsLocal", "localHelper"));
+ /* (4) breadth insurance: the real edges are still emitted. */
+ ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "CALLS"), 2);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Python counterpart to the TS/JS receiver guard (#1276), sequential path.
+ * Pins BOTH directions. NEGATIVE: an attribute call on an unknown receiver
+ * (a parameter) must not bind the lone same-named project method through
+ * unique_name. POSITIVE: an import-bound receiver (helper.compute) and a bare
+ * local call must still produce their CALLS edges.
+ * Fewer than 50 files exercises pass_calls.c. */
+ TEST(pipeline_python_receiver_suppresses_weak_method_edge) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_python_recv_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "worker.py",
+ "class Worker:\n"
+ " def backward(self):\n"
+ " return 1\n");
+ write_temp_file(tmp, "pkg/__init__.py", "from .helper import compute\n");
+ write_temp_file(tmp, "pkg/helper.py",
+ "def compute(value):\n"
+ " return value * 2\n");
+ write_temp_file(tmp, "caller.py",
+ "from pkg import helper\n"
+ "\n"
+ "def external_call(accelerator):\n"
+ " return accelerator.backward()\n"
+ "\n"
+ "def imported_call():\n"
+ " return helper.compute(42)\n"
+ "\n"
+ "def local_helper():\n"
+ " return 1\n"
+ "\n"
+ "def bare_call():\n"
+ " return local_helper()\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/python_recv.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* NEGATIVE: `accelerator` is a parameter — Worker.backward must not bind. */
+ ASSERT_GTE(fixture_node_count(s, project, "caller.py", "external_call", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "worker.py", "backward", "Method"), 1);
+ ASSERT_FALSE(cross_file_call_exists(s, project, "external_call", "backward"));
+ /* POSITIVE: import-bound receiver and bare local call both survive. */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "imported_call", "compute"));
+ ASSERT_TRUE(cross_file_call_exists(s, project, "bare_call", "local_helper"));
+ /* Tripwire: a run that emitted no edges at all would satisfy the negative
+ * assertion vacuously. */
+ ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "CALLS"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* #606: a receiver typed as an unindexed (vendor/) class must not weakly bind a
+ * same-named project method. */
+ static void write_php_receiver_fixture(const char *tmp) {
+ write_temp_file(tmp, "src/Item.php",
+ "<?php\n"
+ "namespace App;\n"
+ "\n"
+ "class Item\n"
+ "{\n"
+ " public function getUid(): int\n"
+ " {\n"
+ " return 1;\n"
+ " }\n"
+ "}\n");
+ write_temp_file(tmp, "src/Domain/Repository.php",
+ "<?php\n"
+ "namespace App\\Domain;\n"
+ "\n"
+ "use App\\Item;\n"
+ "use Vendor\\Storage\\File;\n"
+ "\n"
+ "class Repository\n"
+ "{\n"
+ " public function findItem(): Item\n"
+ " {\n"
+ " return new Item();\n"
+ " }\n"
+ "\n"
+ " public function findFile(): File\n"
+ " {\n"
+ " return new File();\n"
+ " }\n"
+ "}\n");
+ write_temp_file(tmp, "src/Listener.php",
+ "<?php\n"
+ "namespace App;\n"
+ "\n"
+ "use Vendor\\Storage\\File;\n"
+ "use function sprintf;\n"
+ "\n"
+ "class Listener\n"
+ "{\n"
+ " public function vendorCall(File $file): int\n"
+ " {\n"
+ " return $file->getUid();\n"
+ " }\n"
+ "\n"
+ " public function selfCall(): int\n"
+ " {\n"
+ " return $this->localHelper();\n"
+ " }\n"
+ "\n"
+ " private function localHelper(): int\n"
+ " {\n"
+ " return 1;\n"
+ " }\n"
+ "}\n");
+ write_temp_file(tmp, "src/ChainListener.php",
+ "<?php\n"
+ "namespace App;\n"
+ "\n"
+ "use App\\Domain\\Repository;\n"
+ "\n"
+ "class ChainListener\n"
+ "{\n"
+ " public function chainedVendorCall(Repository $repository): int\n"
+ " {\n"
+ " return $repository->findFile()->getUid();\n"
+ " }\n"
+ "\n"
+ " public function projectCall(Repository $repository): Item\n"
+ " {\n"
+ " return $repository->findItem();\n"
+ " }\n"
+ "}\n");
+ }
+
+ /* Fewer than 50 files exercises pass_calls.c. */
+ TEST(pipeline_php_receiver_suppresses_weak_method_edge) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_php_recv_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_php_receiver_fixture(tmp);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/php_recv.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_GTE(fixture_node_count(s, project, "src/Item.php", "getUid", "Method"), 1);
+ ASSERT_FALSE(cross_file_call_exists(s, project, "vendorCall", "getUid"));
+ ASSERT_FALSE(cross_file_call_exists(s, project, "chainedVendorCall", "getUid"));
+ ASSERT_TRUE(cross_file_call_exists(s, project, "projectCall", "findItem"));
+ ASSERT_GTE(named_edge_count(s, project, "CALLS", "selfCall", "localHelper"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* >= 50 files forces pass_parallel.c. */
+ TEST(pipeline_php_receiver_parallel_suppresses_weak_method_edge) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_php_par_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_php_receiver_fixture(tmp);
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/Filler%d.php", i);
+ snprintf(body, sizeof(body), "<?php\nfunction filler%d(): int\n{\n return %d;\n}\n", i,
+ i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/php_par.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_GTE(fixture_node_count(s, project, "src/Item.php", "getUid", "Method"), 1);
+ ASSERT_FALSE(cross_file_call_exists(s, project, "vendorCall", "getUid"));
+ ASSERT_FALSE(cross_file_call_exists(s, project, "chainedVendorCall", "getUid"));
+ ASSERT_TRUE(cross_file_call_exists(s, project, "projectCall", "findItem"));
+ ASSERT_GTE(named_edge_count(s, project, "CALLS", "selfCall", "localHelper"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* The member guard's one exemption (2026-09-16, v0.10.8 → v0.11.0 A/B on
+ * django/django): a member call whose receiver is an attribute chain rooted at
+ * self/cls, whose callee has exactly ONE definition in the project and is not a
+ * builtin type's own method keeps its unique_name edge —
+ * `self.compiler.apply_converters()` names the only apply_converters there is.
+ * A bare parameter receiver and the builtin-member class the guard was built
+ * for (`parts.extend()` -> a project ListMixin.extend) stay suppressed.
+ * Fewer than 50 files exercises pass_calls.c. */
+ TEST(pipeline_python_receiver_keeps_specific_unique_name_member_call) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_python_uniq_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "compiler.py",
+ "class SQLCompiler:\n"
+ " def apply_converters(self, rows):\n"
+ " return rows\n");
+ write_temp_file(tmp, "mixin.py",
+ "class ListMixin:\n"
+ " def extend(self, other):\n"
+ " return other\n");
+ write_temp_file(tmp, "caller.py",
+ "class RawIterable:\n"
+ " def __init__(self, compiler):\n"
+ " self.compiler = compiler\n"
+ "\n"
+ " def iterate(self):\n"
+ " return self.compiler.apply_converters([])\n"
+ "\n"
+ "\n"
+ "def collect(parts):\n"
+ " parts.extend([1])\n"
+ " return parts\n"
+ "\n"
+ "\n"
+ "def handed_in(compiler):\n"
+ " return compiler.apply_converters([])\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/python_uniq.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* POSITIVE: the only apply_converters in the project binds through
+ * self.compiler, an object the class owns. */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "iterate", "apply_converters"));
+ /* NEGATIVE: the same unique name through a bare parameter carries no
+ * ownership evidence and stays suppressed (#1276's own shape). */
+ ASSERT_FALSE(cross_file_call_exists(s, project, "handed_in", "apply_converters"));
+ /* NEGATIVE: list.extend on a parameter must not bind ListMixin.extend. */
+ ASSERT_FALSE(cross_file_call_exists(s, project, "collect", "extend"));
+ /* Tripwire against a vacuous run. */
+ ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "CALLS"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Embedded-script hosts (2026-09-16 probe on JetBrains/Exposed): a member call
+ * inside an HTML <script> body is extracted as JavaScript and carries the JS
+ * receiver flag, but the weak-member guard was gated on the FILE language, so
+ * 4,207 generated Dokka pages bound `localStorage.getItem` to a docs bundle
+ * function through unique_name. HTML (and Vue/Svelte/Astro) join the gate.
+ * POSITIVE tripwire: a bare project call in a plain .js file still resolves. */
+ TEST(pipeline_html_embedded_member_call_stays_unbound) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_html_member_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ /* One directory level each: write_temp_file creates a single parent. */
+ write_temp_file(tmp, "scripts/storage.js",
+ "function getItem(key) {\n"
+ " return key;\n"
+ "}\n");
+ write_temp_file(tmp, "scripts/theme.js",
+ "import { getItem } from './storage.js';\n"
+ "\n"
+ "function loadTheme() {\n"
+ " return getItem('theme');\n"
+ "}\n");
+ write_temp_file(tmp, "docs/index.html",
+ "<html><head><script>\n"
+ "var mode = localStorage.getItem('dokka-dark-mode');\n"
+ "</script></head><body></body></html>\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/html_member.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* NEGATIVE: localStorage's own method must not bind the docs bundle. */
+ ASSERT_FALSE(cross_file_call_exists(s, project, "index", "getItem"));
+ /* POSITIVE: the bare project call in storage.js resolves as before. */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "loadTheme", "getItem"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* CALLS edges whose source and target QNs end with the given suffixes and
+ * whose serialized properties contain `props_fragment` (NULL: any edge). QN
+ * suffixes pin the exact node, not just a same-named one. */
+ static int go_calls_between(cbm_store_t *s, const char *project, const char *caller_suffix,
+ const char *callee_suffix, const char *props_fragment) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ cbm_store_find_edges_by_type(s, project, "CALLS", &edges, &edge_count);
+ size_t cs = strlen(caller_suffix);
+ size_t ts = strlen(callee_suffix);
+ int hits = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t src = {0};
+ cbm_node_t tgt = {0};
+ if (cbm_store_find_node_by_id(s, edges[i].source_id, &src) == CBM_STORE_OK &&
+ cbm_store_find_node_by_id(s, edges[i].target_id, &tgt) == CBM_STORE_OK &&
+ src.qualified_name && tgt.qualified_name) {
+ size_t sl = strlen(src.qualified_name);
+ size_t tl = strlen(tgt.qualified_name);
+ if (sl >= cs && tl >= ts && strcmp(src.qualified_name + sl - cs, caller_suffix) == 0 &&
+ strcmp(tgt.qualified_name + tl - ts, callee_suffix) == 0 &&
+ (!props_fragment ||
+ (edges[i].properties_json && strstr(edges[i].properties_json, props_fragment)))) {
+ hits++;
+ }
+ }
+ cbm_node_free_fields(&src);
+ cbm_node_free_fields(&tgt);
+ }
+ if (edges) {
+ cbm_store_free_edges(edges, edge_count);
+ }
+ return hits;
+ }
+
+ TEST(pipeline_go_method_caller_keeps_lsp_join) {
+ /* #1909: receiver-qualifying method QNs moves the def/textual-call QN to
+ * package.Type.method — go_lsp's enclosing-function QN must move with it
+ * (the ONE-formula contract), or every LSP resolution sourced from inside
+ * a method body loses its caller join and the edge dies. The callee name
+ * collides across receivers so no short-name fallback can mask the loss. */
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_mcall_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "go.mod", "module example.com/fxmcall\n\ngo 1.22\n");
+ write_temp_file(tmp, "svc/repo.go",
+ "package svc\n"
+ "\n"
+ "type Repo struct {\n"
+ "\tn int\n"
+ "}\n"
+ "\n"
+ "func (r *Repo) Install() int {\n"
+ "\treturn r.helper()\n"
+ "}\n");
+ write_temp_file(tmp, "svc/helper.go",
+ "package svc\n"
+ "\n"
+ "func (r *Repo) helper() int {\n"
+ "\treturn r.n\n"
+ "}\n");
+ write_temp_file(tmp, "other/other.go",
+ "package other\n"
+ "\n"
+ "type Decoy struct{}\n"
+ "\n"
+ "func (d *Decoy) helper() int { return 2 }\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_mcall.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+ ASSERT_TRUE(cross_file_call_exists(s, project, "Install", "helper"));
+ /* Pinned to the receiver-qualified target in svc/helper.go and to an LSP
+ * strategy: a name-only binding, or one onto other.Decoy.helper, would
+ * still satisfy the by-name check above. */
+ ASSERT_GTE(go_calls_between(s, project, ".svc.Repo.Install", ".svc.Repo.helper",
+ "\"strategy\":\"lsp_"),
+ 1);
+ ASSERT_EQ(go_calls_between(s, project, ".svc.Repo.Install", ".other.Decoy.helper", NULL), 0);
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Fixture for the #1906 Go selector-guard probes (sequential and parallel
+ * twins). pad_files > 0 adds filler Go files to push the index over
+ * MIN_FILES_FOR_PARALLEL, because the guard is wired into both resolvers
+ * (pass_calls.c and pass_parallel.c) and each needs its own probe. */
+ static void write_go_receiver_fixture(const char *tmp, int pad_files) {
+ /* go.mod makes project imports resolvable — real Go repos always have one,
+ * and import reachability (the unique_name penalty) depends on it. */
+ write_temp_file(tmp, "go.mod", "module example.com/myapp\n\ngo 1.22\n");
+ /* The lone project symbol named "Close" — a real method. */
+ write_temp_file(tmp, "storage/storage.go",
+ "package storage\n"
+ "\n"
+ "type Storage struct{ open bool }\n"
+ "\n"
+ "func NewStorage() *Storage { return &Storage{open: true} }\n"
+ "\n"
+ "func (s *Storage) Close() {\n"
+ "\ts.open = false\n"
+ "}\n"
+ "\n"
+ "func Boot() {\n"
+ "\ts := NewStorage()\n"
+ "\ts.Close()\n"
+ "}\n");
+ /* Cross-package control target: imported by hash.go, so the caller file
+ * has a non-empty import map (like any real Go file) and unreachable
+ * unique_name candidates get the import penalty. */
+ write_temp_file(tmp, "util/util.go",
+ "package util\n"
+ "\n"
+ "func Tag() string { return \"t\" }\n");
+ /* Stdlib receiver: `f.Close()` closes an *os.File, NOT the project method.
+ * The Go LSP cannot bind it to a project symbol → the registry would guess
+ * Close by short name (weak). This is the false edge to suppress —
+ * the exact shape that attached every file/rows/gzip Close in a real Go
+ * repo to one unrelated project method. */
+ write_temp_file(tmp, "hash/hash.go",
+ "package hash\n"
+ "\n"
+ "import (\n"
+ "\t\"os\"\n"
+ "\n"
+ "\t\"example.com/myapp/util\"\n"
+ ")\n"
+ "\n"
+ "func FileLen(path string) int64 {\n"
+ "\tf, err := os.Open(path)\n"
+ "\tif err != nil {\n"
+ "\t\treturn 0\n"
+ "\t}\n"
+ "\tdefer f.Close()\n"
+ "\tst, err := f.Stat()\n"
+ "\tif err != nil {\n"
+ "\t\treturn 0\n"
+ "\t}\n"
+ "\treturn st.Size()\n"
+ "}\n"
+ "\n"
+ "func localHelper() int { return 1 }\n"
+ "\n"
+ "func CallsLocal() int { return localHelper() }\n"
+ "\n"
+ "func UsesUtil() string { return util.Tag() }\n");
+ /* F-G9: two project methods named Run, one under a directory whose QN
+ * carries an uppercase T. `t.Run` on a *testing.T must bind neither. The
+ * parallel resolver field-type hint matched the capitalized receiver
+ * variable ("T") as a QN substring and produced a par-only edge. */
+ write_temp_file(tmp, "TBench/bench.go",
+ "package tbench\n"
+ "\n"
+ "type Bench struct{}\n"
+ "\n"
+ "func (b *Bench) Run(name string) bool { return name != \"\" }\n");
+ write_temp_file(tmp, "worker/worker.go",
+ "package worker\n"
+ "\n"
+ "type Worker struct{}\n"
+ "\n"
+ "func (w *Worker) Run(name string) bool { return false }\n");
+ write_temp_file(tmp, "hash/hash_test.go",
+ "package hash\n"
+ "\n"
+ "import \"testing\"\n"
+ "\n"
+ "func TestSubRun(t *testing.T) {\n"
+ "\tt.Run(\"a\", func(t *testing.T) {})\n"
+ "}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "filler/filler%d.go", i);
+ snprintf(body, sizeof(body), "package filler\n\nfunc Filler%d() int { return %d }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ }
+
+ TEST(pipeline_go_receiver_suppresses_weak_method_edge) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_recv_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_go_receiver_fixture(tmp, 0);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_recv.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* (1) The false edge is suppressed (reproduce-first: RED before the fix). */
+ ASSERT_FALSE(cross_file_call_exists(s, project, "FileLen", "Close"));
+ /* (2) The same-package typed-receiver call survives (LSP / same_module —
+ * both outside the weak drop-list). */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "Boot", "Close"));
+ /* (3) The bare local call survives (is_method stays false for bare calls). */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "CallsLocal", "localHelper"));
+ /* (4) The import-qualified cross-package call survives (import-aware
+ * strategies are outside the drop-list). */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "UsesUtil", "Tag"));
+ /* (5) F-G9: the stdlib *testing.T Run binds no project Run. */
+ ASSERT_FALSE(cross_file_call_exists(s, project, "TestSubRun", "Run"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Parallel twin of the test above. The guard is wired into pass_parallel.c as
+ * well as pass_calls.c, but the four-file fixture only ever runs the
+ * sequential resolver, so the parallel hunk was bound by no test. Real
+ * repositories take the parallel path: >= MIN_FILES_FOR_PARALLEL (50) files
+ * plus CBM_WORKERS=4 force it, the shape of
+ * pipeline_python_receiver_parallel_suppresses_weak_method_edges. Same
+ * both-directions pin as the sequential test. */
+ TEST(pipeline_go_receiver_parallel_suppresses_weak_method_edge) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_recv_par_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_go_receiver_fixture(tmp, 52);
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_recv_par.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* NEGATIVE: the stdlib *os.File Close must not bind the project method. */
+ ASSERT_FALSE(cross_file_call_exists(s, project, "FileLen", "Close"));
+ /* POSITIVE: typed same-package, bare local and import-qualified calls
+ * survive the parallel resolver too. */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "Boot", "Close"));
+ ASSERT_TRUE(cross_file_call_exists(s, project, "CallsLocal", "localHelper"));
+ ASSERT_TRUE(cross_file_call_exists(s, project, "UsesUtil", "Tag"));
+ /* F-G9: the parallel-only field-type hint must not bind `t.Run` either. */
+ ASSERT_FALSE(cross_file_call_exists(s, project, "TestSubRun", "Run"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_go_multi_init_nodes_survive) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_init_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ /* Two files, one package, one init() each — Go runs both at start-up.
+ * Pre-fix both collapsed onto one QN and the upsert kept one node
+ * (reproduce-first: RED asserts node count == 2). */
+ write_temp_file(tmp, "go.mod", "module example.com/reg\n\ngo 1.22\n");
+ write_temp_file(tmp, "reg/a.go",
+ "package reg\n"
+ "\n"
+ "var handlers = map[string]func(){}\n"
+ "\n"
+ "func init() { handlers[\"a\"] = handleA }\n"
+ "\n"
+ "func handleA() {}\n");
+ write_temp_file(tmp, "reg/b.go",
+ "package reg\n"
+ "\n"
+ "func init() { handlers[\"b\"] = handleB }\n"
+ "\n"
+ "func handleB() {}\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_init.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* Both init functions survive as distinct nodes. */
+ cbm_node_t *inits = NULL;
+ int ic = 0;
+ cbm_store_find_nodes_by_name(s, project, "init", &inits, &ic);
+ ASSERT_EQ(ic, 2);
+ cbm_store_free_nodes(inits, ic);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Edges of `edge_type` whose source and target QNs end with the given
+ * suffixes (go_calls_between for any edge type, without the properties). */
+ static int go_edges_between(cbm_store_t *s, const char *project, const char *edge_type,
+ const char *caller_suffix, const char *callee_suffix) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ cbm_store_find_edges_by_type(s, project, edge_type, &edges, &edge_count);
+ size_t cs = strlen(caller_suffix);
+ size_t ts = strlen(callee_suffix);
+ int hits = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t src = {0};
+ cbm_node_t tgt = {0};
+ if (cbm_store_find_node_by_id(s, edges[i].source_id, &src) == CBM_STORE_OK &&
+ cbm_store_find_node_by_id(s, edges[i].target_id, &tgt) == CBM_STORE_OK &&
+ src.qualified_name && tgt.qualified_name) {
+ size_t sl = strlen(src.qualified_name);
+ size_t tl = strlen(tgt.qualified_name);
+ if (sl >= cs && tl >= ts && strcmp(src.qualified_name + sl - cs, caller_suffix) == 0 &&
+ strcmp(tgt.qualified_name + tl - ts, callee_suffix) == 0) {
+ hits++;
+ }
+ }
+ cbm_node_free_fields(&src);
+ cbm_node_free_fields(&tgt);
+ }
+ if (edges) {
+ cbm_store_free_edges(edges, edge_count);
+ }
+ return hits;
+ }
+
+ /* Fixture for the #1910 Go init() LSP-join probes (sequential and parallel
+ * twins). Three init() in two files of one package -- two in b.go, so the
+ * per-file ordinal is pinned too -- each calling a method that only the Go
+ * LSP can bind: the receiver's type comes from a constructor in another
+ * file, and the method name also exists on a second package type and on
+ * other.Decoy, so no short-name fallback lands on the right target. a.go's
+ * init also passes a handler by value (add("a", handleA): a CALL_REFERENCE,
+ * which exists only as an LSP row). pad_files > 0 adds filler Go files past
+ * MIN_FILES_FOR_PARALLEL. */
+ static void write_go_init_lsp_fixture(const char *tmp, int pad_files) {
+ write_temp_file(tmp, "go.mod", "module example.com/fxinit\n\ngo 1.22\n");
+ write_temp_file(tmp, "reg/codec.go",
+ "package reg\n"
+ "\n"
+ "type Codec struct{ n int }\n"
+ "\n"
+ "func NewCodec() *Codec { return &Codec{} }\n"
+ "\n"
+ "func (c *Codec) register() { c.n++ }\n");
+ write_temp_file(tmp, "reg/store.go",
+ "package reg\n"
+ "\n"
+ "type Store struct{ open bool }\n"
+ "\n"
+ "func NewStore() *Store { return &Store{} }\n"
+ "\n"
+ "func (s *Store) register() { s.open = true }\n"
+ "\n"
+ "func (s *Store) warm() {}\n");
+ write_temp_file(tmp, "reg/a.go",
+ "package reg\n"
+ "\n"
+ "var handlers = map[string]func(){}\n"
+ "\n"
+ "func handleA() {}\n"
+ "\n"
+ "func add(name string, fn func()) { handlers[name] = fn }\n"
+ "\n"
+ "func init() {\n"
+ "\tc := NewCodec()\n"
+ "\tc.register()\n"
+ "\tadd(\"a\", handleA)\n"
+ "}\n");
+ write_temp_file(tmp, "reg/b.go",
+ "package reg\n"
+ "\n"
+ "func init() {\n"
+ "\ts := NewStore()\n"
+ "\ts.register()\n"
+ "}\n"
+ "\n"
+ "func init() {\n"
+ "\ts := NewStore()\n"
+ "\ts.warm()\n"
+ "}\n");
+ write_temp_file(tmp, "other/other.go",
+ "package other\n"
+ "\n"
+ "type Decoy struct{}\n"
+ "\n"
+ "func (d *Decoy) register() {}\n"
+ "\n"
+ "func (d *Decoy) warm() {}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "pad/filler%d.go", i);
+ snprintf(body, sizeof(body), "package pad\n\nfunc filler%d() int { return %d }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ }
+
+ /* Each init's LSP-resolved edges start at that init's own node. */
+ static int assert_go_init_lsp_edges(cbm_store_t *s, const char *project) {
+ const char *lsp = "\"strategy\":\"lsp_";
+ ASSERT_GTE(go_calls_between(s, project, ".reg.init#a.go:1", ".reg.Codec.register", lsp), 1);
+ ASSERT_GTE(go_calls_between(s, project, ".reg.init#b.go:1", ".reg.Store.register", lsp), 1);
+ ASSERT_GTE(go_calls_between(s, project, ".reg.init#b.go:2", ".reg.Store.warm", lsp), 1);
+ ASSERT_GTE(go_edges_between(s, project, "CALL_REFERENCE", ".reg.init#a.go:1", ".reg.handleA"),
+ 1);
+ /* No cross-wiring between the inits, and nothing onto the decoy. */
+ ASSERT_EQ(go_calls_between(s, project, ".reg.init#a.go:1", ".reg.Store.register", NULL), 0);
+ ASSERT_EQ(go_calls_between(s, project, ".reg.init#b.go:1", ".reg.Codec.register", NULL), 0);
+ ASSERT_EQ(go_calls_between(s, project, ".reg.init#b.go:2", ".reg.Store.register", NULL), 0);
+ ASSERT_EQ(go_calls_between(s, project, ".reg.init#a.go:1", ".other.Decoy.register", NULL), 0);
+ ASSERT_EQ(go_calls_between(s, project, ".reg.init#b.go:1", ".other.Decoy.register", NULL), 0);
+ ASSERT_EQ(go_calls_between(s, project, ".reg.init#b.go:2", ".other.Decoy.warm", NULL), 0);
+ return 0;
+ }
+
+ /* #1910: the def extractor and compute_func_qn name each init
+ * pkg.init#<file>:<N>; the Go LSP must name its caller the same way
+ * (cbm_go_init_qn), or every LSP resolution inside an init body loses the
+ * exact caller-QN join and falls back to the registry resolver. */
+ TEST(pipeline_go_init_lsp_edges_per_file) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_init_lsp_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_go_init_lsp_fixture(tmp, 0);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_init_lsp.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+ ASSERT_EQ(assert_go_init_lsp_edges(s, project), 0);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Parallel twin: >= MIN_FILES_FOR_PARALLEL (50) files plus CBM_WORKERS=4
+ * take the parallel resolver (resolve_worker's Tier-2 dispatch). */
+ TEST(pipeline_go_init_lsp_edges_per_file_parallel) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_init_lsp_par_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_go_init_lsp_fixture(tmp, 52);
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_init_lsp_par.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+ ASSERT_EQ(assert_go_init_lsp_edges(s, project), 0);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
++TEST(pipeline_go_parallel_field_hint_requires_owner_segment) {
++ /* #1927: try_field_type_hint (parallel resolver only) matched the hinted
++ * type name as a raw SUBSTRING of the candidate QN. A single-letter
++ * receiver — `f.Close()` on an *os.File — hints "F", and "F" is a
++ * substring of "…FileStore.Close", so a stdlib call was rebound to an
++ * arbitrary project method at PP_FIELD_HINT_CONF and presented as
++ * field_type_hint (the one weak strategy the Go selector guard trusts).
++ * The hint must fire only when the candidate's OWNING segment — the
++ * dot-segment immediately before the method — EQUALS the hinted type;
++ * otherwise the resolution stays a weak short-name match and the Go
++ * guard (#1906) drops it. >= 50 files forces pass_parallel.c, the only
++ * path that runs try_field_type_hint(). */
++ char tmp[256];
++ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_fth_XXXXXX");
++ if (!cbm_mkdtemp(tmp)) {
++ FAIL("tmpdir");
++ }
++
++ write_temp_file(tmp, "go.mod", "module example.com/fxhint\n\ngo 1.22\n");
++ /* Two project methods named Close → the registry resolves f.Close() as an
++ * ambiguous short-name match (candidate_count 2), the shape the hint
++ * upgrades. FileStore's QN carries the capital F the buggy substring
++ * latches onto; Conn is the second candidate. */
++ write_temp_file(tmp, "filestore/filestore.go",
++ "package filestore\n"
++ "\n"
++ "type FileStore struct{ open bool }\n"
++ "\n"
++ "func (fs *FileStore) Close() {\n"
++ "\tfs.open = false\n"
++ "}\n");
++ write_temp_file(tmp, "conn/conn.go",
++ "package conn\n"
++ "\n"
++ "type Conn struct{ live bool }\n"
++ "\n"
++ "func (cn *Conn) Close() {\n"
++ "\tcn.live = false\n"
++ "}\n");
++ /* Two project methods named Find → same ambiguity, but here the receiver
++ * variable IS named after its type (`finder`), the case the hint exists
++ * for: the owning segment of Finder.Find equals the hinted "Finder". */
++ write_temp_file(tmp, "finder/finder.go",
++ "package finder\n"
++ "\n"
++ "type Finder struct{ n int }\n"
++ "\n"
++ "func NewFinder() *Finder { return &Finder{n: 1} }\n"
++ "\n"
++ "func (fi *Finder) Find(id int) int {\n"
++ "\treturn fi.n + id\n"
++ "}\n");
++ write_temp_file(tmp, "locator/locator.go",
++ "package locator\n"
++ "\n"
++ "type Locator struct{ n int }\n"
++ "\n"
++ "func (lo *Locator) Find(id int) int {\n"
++ "\treturn lo.n - id\n"
++ "}\n");
++ write_temp_file(tmp, "app/app.go",
++ "package app\n"
++ "\n"
++ "import (\n"
++ "\t\"os\"\n"
++ "\n"
++ "\txf \"example.com/fxhint/finder\"\n"
++ ")\n"
++ "\n"
++ "func Lookup(path string) int64 {\n"
++ "\tf, err := os.Open(path)\n"
++ "\tif err != nil {\n"
++ "\t\treturn 0\n"
++ "\t}\n"
++ "\tdefer f.Close()\n"
++ "\tst, err := f.Stat()\n"
++ "\tif err != nil {\n"
++ "\t\treturn 0\n"
++ "\t}\n"
++ "\treturn st.Size()\n"
++ "}\n"
++ "\n"
++ "func UseFinder(id int) int {\n"
++ "\tfinder := xf.NewFinder()\n"
++ "\treturn finder.Find(id)\n"
++ "}\n");
++ for (int i = 0; i < 52; i++) {
++ char name[64];
++ char body[128];
++ snprintf(name, sizeof(name), "pad/filler%d.go", i);
++ snprintf(body, sizeof(body), "package pad\n\nfunc filler%d() int { return %d }\n", i, i);
++ write_temp_file(tmp, name, body);
++ }
++
++ char db_path[512];
++ snprintf(db_path, sizeof(db_path), "%s/go_fth.db", tmp);
++ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
++ ASSERT_NOT_NULL(p);
++ ASSERT_EQ(cbm_pipeline_run(p), 0);
++ const char *project = cbm_pipeline_project_name(p);
++
++ cbm_store_t *s = cbm_store_open_path(db_path);
++ ASSERT_NOT_NULL(s);
++
++ /* (1) Reproduce-first: RED before the fix. The substring hint rebinds the
++ * stdlib f.Close() to FileStore.Close ("F" ⊂ QN) at high confidence and
++ * the Go guard keeps it. With segment equality the upgrade is refused,
++ * the match stays suffix_match, and the Go guard drops it. */
++ ASSERT_FALSE(cross_file_call_exists(s, project, "Lookup", "Close"));
++ /* (2) The intended hint case survives: `finder` names its type, so the
++ * owning segment of Finder.Find equals the hint. */
++ ASSERT_TRUE(cross_file_call_exists(s, project, "UseFinder", "Find"));
++
++ cbm_store_close(s);
++ cbm_pipeline_free(p);
++ th_rmtree(tmp);
++ PASS();
++}
++
+ /* Fixture for the #1928 cross-language reference-guard probes (sequential and
+ * parallel twins). pad_files > 0 adds filler files to push the index over the
+ * parallel-pipeline threshold, since USAGE/WRITES/READS have one resolver per
+ * path and both must consult the guard. */
+ static void write_go_c_ref_guard_fixture(const char *tmp, int pad_files) {
+ write_temp_file(tmp, "go.mod", "module example.com/fxguard\n\ngo 1.22\n");
+ /* C targets must be indexed: block-local C variables are not emitted,
+ * so keep event at file scope for the cross-language reference guard. */
+ write_temp_file(tmp, "probe/probe.c",
+ "static int total_events = 0;\n"
+ "static int event = 0;\n"
+ "\n"
+ "static int handle(void) {\n"
+ " event = 0;\n"
+ " total_events += event;\n"
+ " return event;\n"
+ "}\n");
+ /* Go local writes and value uses must not bind to the C variables or
+ * functions in this fixture. */
+ write_temp_file(tmp, "app/app.go",
+ "package app\n"
+ "\n"
+ "func TrackEvent() int {\n"
+ "\tevent := 1\n"
+ "\treturn event\n"
+ "}\n"
+ "\n"
+ "func UsesHandle() int {\n"
+ "\th := handle\n"
+ "\t_ = h\n"
+ "\treturn 4\n"
+ "}\n"
+ "\n"
+ "func WriteTotal() {\n"
+ "\ttotal_events := 5\n"
+ "\t_ = total_events\n"
+ "}\n");
+ /* Same-language control: a Go package-level var written from another
+ * file must keep its WRITES edge. */
+ write_temp_file(tmp, "state/vars.go",
+ "package state\n"
+ "\n"
+ "var Counter int\n");
+ write_temp_file(tmp, "state/state.go",
+ "package state\n"
+ "\n"
+ "func Bump() {\n"
+ "\tCounter = 2\n"
+ "}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "pad/filler%d.go", i);
+ snprintf(body, sizeof(body), "package pad\n\nfunc filler%d() int { return %d }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ }
+
+ /* F-G8 D1: a variable bound by a CROSS-file multi-value or named-result call
+ * is typed. The cross-file registrar received the raw result text
+ * `(*Encoder, error)`, which did not parse, so `e, err := enc.NewEncoder()`
+ * left e untyped and e.EncodeTuple() fell to a name guess. A single result
+ * keeps its raw text: `[]Sample` must stay a slice so that `xs[0].TS()` is
+ * typed (the extractor's cleaned return_types read it as `Sample`). Every
+ * target method has two same-named decoys, so a guess cannot pass.
+ * pad_files > 0 forces the parallel resolver. */
+ static void write_go_multi_return_fixture(const char *tmp, int pad_files) {
+ write_temp_file(tmp, "go.mod", "module example.com/fx\n\ngo 1.22\n");
+ write_temp_file(tmp, "enc/enc.go",
+ "package enc\n"
+ "\n"
+ "type Encoder struct{ n int }\n"
+ "\n"
+ "func NewEncoder() (*Encoder, error) { return &Encoder{}, nil }\n"
+ "\n"
+ "func NewNamed() (e *Encoder) { e = &Encoder{}; return }\n"
+ "\n"
+ "func NewPair() (a, b *Encoder) { return &Encoder{}, &Encoder{} }\n"
+ "\n"
+ "func (e *Encoder) EncodeTuple() int { return e.n }\n"
+ "\n"
+ "func (e *Encoder) EncodeNamed() int { return e.n }\n"
+ "\n"
+ "func (e *Encoder) EncodeGrouped() int { return e.n }\n");
+ write_temp_file(tmp, "samples/samples.go",
+ "package samples\n"
+ "\n"
+ "type Sample interface{ TS() int64 }\n"
+ "\n"
+ "type sample struct{}\n"
+ "\n"
+ "func (sample) TS() int64 { return 0 }\n"
+ "\n"
+ "func Generate() []Sample { return []Sample{sample{}} }\n"
+ "\n"
+ "func List() ([]Sample, error) { return []Sample{sample{}}, nil }\n");
+ write_temp_file(tmp, "diag/diag.go",
+ "package diag\n"
+ "\n"
+ "type Diagnostic struct{ msg string }\n"
+ "\n"
+ "type Diagnostics []Diagnostic\n"
+ "\n"
+ "func (d Diagnostics) HasErrorsSlice() bool { return len(d) > 0 }\n"
+ "\n"
+ "func Run() (int, Diagnostics) { return 0, nil }\n");
+ write_temp_file(tmp, "app/types.go",
+ "package app\n"
+ "\n"
+ "type isolation struct{}\n"
+ "\n"
+ "func (i *isolation) LowWatermarkField() int { return 0 }\n"
+ "\n"
+ "type Head struct{ iso *isolation }\n"
+ "\n"
+ "func newHead() (*Head, error) { return &Head{iso: &isolation{}}, nil }\n");
+ write_temp_file(tmp, "app/app.go",
+ "package app\n"
+ "\n"
+ "import (\n"
+ "\t\"example.com/fx/diag\"\n"
+ "\t\"example.com/fx/enc\"\n"
+ "\t\"example.com/fx/samples\"\n"
+ ")\n"
+ "\n"
+ "func UseIndex() int64 {\n"
+ "\txs := samples.Generate()\n"
+ "\treturn xs[0].TS()\n"
+ "}\n"
+ "\n"
+ "func UseTupleSlice() int64 {\n"
+ "\tys, _ := samples.List()\n"
+ "\treturn ys[0].TS()\n"
+ "}\n"
+ "\n"
+ "func UseGrouped() int {\n"
+ "\tx, _ := enc.NewPair()\n"
+ "\treturn x.EncodeGrouped()\n"
+ "}\n"
+ "\n"
+ "func UseTuple() int {\n"
+ "\te, err := enc.NewEncoder()\n"
+ "\t_ = err\n"
+ "\treturn e.EncodeTuple()\n"
+ "}\n"
+ "\n"
+ "func UseNamed() int {\n"
+ "\te := enc.NewNamed()\n"
+ "\treturn e.EncodeNamed()\n"
+ "}\n"
+ "\n"
+ "func UseField() int {\n"
+ "\th, _ := newHead()\n"
+ "\treturn h.iso.LowWatermarkField()\n"
+ "}\n"
+ "\n"
+ "func UseSlice() bool {\n"
+ "\t_, d := diag.Run()\n"
+ "\treturn d.HasErrorsSlice()\n"
+ "}\n");
+ write_temp_file(tmp, "decoy/decoy.go",
+ "package decoy\n"
+ "\n"
+ "type D1 struct{}\n"
+ "\n"
+ "type D2 struct{}\n"
+ "\n"
+ "func (D1) EncodeTuple() int { return 0 }\n"
+ "func (D2) EncodeTuple() int { return 0 }\n"
+ "func (D1) EncodeNamed() int { return 0 }\n"
+ "func (D2) EncodeNamed() int { return 0 }\n"
+ "func (D1) LowWatermarkField() int { return 0 }\n"
+ "func (D2) LowWatermarkField() int { return 0 }\n"
+ "func (D1) HasErrorsSlice() bool { return false }\n"
+ "func (D2) HasErrorsSlice() bool { return false }\n"
+ "func (D1) EncodeGrouped() int { return 0 }\n"
+ "func (D2) EncodeGrouped() int { return 0 }\n"
+ "func (D1) TS() int64 { return 0 }\n"
+ "func (D2) TS() int64 { return 0 }\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "filler/filler%d.go", i);
+ snprintf(body, sizeof(body), "package filler\n\nfunc Filler%d() int { return %d }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ }
+
+ static int go_multi_return_case(int pad_files) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_multiret_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_go_multi_return_fixture(tmp, pad_files);
+ char *saved = NULL;
+ if (pad_files > 0) {
+ char *old_workers = getenv("CBM_WORKERS");
+ saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ }
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_multiret.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ int rc = p ? cbm_pipeline_run(p) : -1;
+ if (pad_files > 0) {
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ }
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(rc, 0);
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ static const struct {
+ const char *caller;
+ const char *method;
+ const char *file;
+ } want[] = {
+ {"UseTuple", "EncodeTuple", "enc/enc.go"}, /* e, err := enc.NewEncoder() */
+ {"UseNamed", "EncodeNamed", "enc/enc.go"}, /* named result (e *Encoder) */
+ {"UseField", "LowWatermarkField", "app/types.go"}, /* h, _ := newHead(); h.iso.X() */
+ {"UseSlice", "HasErrorsSlice", "diag/diag.go"}, /* _, d := diag.Run() */
+ {"UseGrouped", "EncodeGrouped", "enc/enc.go"}, /* (a, b *Encoder) */
+ {"UseIndex", "TS", "samples/samples.go"}, /* single []Sample, xs[0] */
+ {"UseTupleSlice", "TS", "samples/samples.go"}, /* ([]Sample, error) */
+ };
+ for (size_t i = 0; i < sizeof(want) / sizeof(want[0]); i++) {
+ int right = named_edge_to_file_count(s, project, "CALLS", want[i].caller, want[i].method,
+ want[i].file);
+ int decoy = named_edge_to_file_count(s, project, "CALLS", want[i].caller, want[i].method,
+ "decoy/decoy.go");
+ bool typed = cross_file_call_has_strategy(s, project, want[i].caller, want[i].method,
+ "\"strategy\":\"lsp_");
+ if (right < 1 || decoy != 0 || !typed) {
+ printf(" %s -> %s: right=%d decoy=%d lsp=%d\n", want[i].caller, want[i].method, right,
+ decoy, typed);
+ FAIL("multi-value / named-result receiver not typed");
+ }
+ }
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_go_multi_return_receiver_is_typed) {
+ return go_multi_return_case(0);
+ }
+
+ TEST(pipeline_go_multi_return_receiver_is_typed_parallel) {
+ return go_multi_return_case(52);
+ }
+
+ /* #2033: an identity alias declared in one file is followed from another file
+ * of the same package. `type FeatureSet = bitmap` (featureset.go), the method
+ * `bitmap.Set` (bitmap.go) and the call `reqs.Set(3)` (framework.go) are three
+ * files, so the alias reaches the call only through the cross-file defs. The
+ * same-package decoy `other.Set` means the call cannot bind by name. Before the
+ * fix the call had no CALLS edge at all. pad_files > 0 forces the parallel
+ * resolver and its prebuilt registry. */
+ static int go_crossfile_type_alias_case(int pad_files) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_alias_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "go.mod", "module example.com/fx\n\ngo 1.22\n");
+ write_temp_file(tmp, "fs/bitmap.go",
+ "package fs\n"
+ "\n"
+ "type bitmap []uint64\n"
+ "\n"
+ "func (b bitmap) Set(i int) { b[i/64] |= 1 << (i % 64) }\n");
+ write_temp_file(tmp, "fs/featureset.go",
+ "package fs\n"
+ "\n"
+ "type FeatureSet = bitmap\n");
+ write_temp_file(
+ tmp, "fs/framework.go",
+ "package fs\n"
+ "\n"
+ "type Framework struct{}\n"
+ "\n"
+ "func (f *Framework) NewFeatureSet() FeatureSet { return make(FeatureSet, 1) }\n"
+ "\n"
+ "func Use(f *Framework) {\n"
+ "\treqs := f.NewFeatureSet()\n"
+ "\treqs.Set(3)\n"
+ "}\n");
+ write_temp_file(tmp, "fs/other.go",
+ "package fs\n"
+ "\n"
+ "type other struct{}\n"
+ "\n"
+ "func (o other) Set(i int) {}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "filler/filler%d.go", i);
+ snprintf(body, sizeof(body), "package filler\n\nfunc Filler%d() int { return %d }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ char *saved = NULL;
+ if (pad_files > 0) {
+ char *old_workers = getenv("CBM_WORKERS");
+ saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ }
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_alias.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ int rc = p ? cbm_pipeline_run(p) : -1;
+ if (pad_files > 0) {
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ }
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(rc, 0);
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ int right = named_edge_to_file_count(s, project, "CALLS", "Use", "Set", "fs/bitmap.go");
+ int decoy = named_edge_to_file_count(s, project, "CALLS", "Use", "Set", "fs/other.go");
+ bool typed = cross_file_call_has_strategy(s, project, "Use", "Set", "\"strategy\":\"lsp_");
+ if (right != 1 || decoy != 0 || !typed) {
+ printf(" Use -> Set: right=%d decoy=%d lsp=%d\n", right, decoy, typed);
+ FAIL("call through a cross-file type alias not bound to the aliased type's method");
+ }
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_go_crossfile_type_alias_method) {
+ return go_crossfile_type_alias_case(0);
+ }
+
+ TEST(pipeline_go_crossfile_type_alias_method_parallel) {
+ return go_crossfile_type_alias_case(52);
+ }
+
+ TEST(pipeline_go_rw_usage_never_cross_into_c) {
+ /* #1928: USAGE and WRITES/READS resolve through the same short-name
+ * registry as CALLS but never consulted the #725 cross-language guard.
+ * On a Go tree with eBPF C probes every Go identifier spelled like a C
+ * one produced an edge into the C file — 31.5% of all WRITES on the
+ * measured repo crossed the Go/C boundary. Go code cannot write a C
+ * automatic variable, so every edge in that class is false. This is the
+ * SEQUENTIAL-path twin; the parallel twin follows. */
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_rw_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_go_c_ref_guard_fixture(tmp, 0);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_rw.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* Reproduce-first: RED before the fix — the Go local write binds the C
+ * probe's global, and the Go value use binds the C `handle`. */
+ ASSERT_GTE(fixture_node_count(s, project, "app/app.go", "TrackEvent", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "app/app.go", "UsesHandle", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "app/app.go", "WriteTotal", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "probe/probe.c", "handle", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "probe/probe.c", "event", "Variable"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "probe/probe.c", "total_events", "Variable"), 1);
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "TrackEvent", "event", "WRITES"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "TrackEvent", "event", "READS"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "UsesHandle", "handle", "WRITES"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "UsesHandle", "handle", "READS"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "UsesHandle", "handle", "USAGE"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "WriteTotal", "total_events", "WRITES"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "WriteTotal", "total_events", "USAGE"));
+ /* Same-language reference edges survive the guard. */
+ ASSERT_TRUE(cross_file_edge_exists(s, project, "Bump", "Counter", "WRITES"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* The Rust registries were built from the mixed-language def set: a Perl
+ * `sub new` became a Rust free function, and the project-wide
+ * lsp_short_name_unique fallback bound `Store::new()` to it at 0.90 (found by
+ * the generic-engine lane on its 12-language fixture). A Rust call never
+ * targets another language's definition. pad_files > 0 forces the parallel
+ * resolver, whose Rust registry is the shared all-defs build. */
+ /* Pads a Rust fixture with pad_files filler modules (pad_files > 0 forces the
+ * parallel resolver: CBM_WORKERS=4 for the run), runs the full pipeline into
+ * <tmp>/<db_name> and opens the store. NULL store = the run failed. */
+ static cbm_store_t *rust_fixture_run(const char *tmp, int pad_files, const char *db_name,
+ cbm_pipeline_t **out_p) {
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/filler%d.rs", i);
+ snprintf(body, sizeof(body), "pub fn filler%d() -> u32 {\n %d\n}\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ char *saved = NULL;
+ if (pad_files > 0) {
+ char *old_workers = getenv("CBM_WORKERS");
+ saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ }
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/%s", tmp, db_name);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ int rc = p ? cbm_pipeline_run(p) : -1;
+ if (pad_files > 0) {
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ }
+ *out_p = p;
+ return rc == 0 ? cbm_store_open_path(db_path) : NULL;
+ }
+
+ static int rust_registry_rust_only_case(int pad_files) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_rust_only_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "Cargo.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n");
+ write_temp_file(tmp, "src/store.rs",
+ "pub struct Store {\n"
+ " n: u32,\n"
+ "}\n"
+ "\n"
+ "impl Store {\n"
+ " pub fn new() -> Store {\n"
+ " Store { n: 0 }\n"
+ " }\n"
+ "\n"
+ " pub fn get(&self, k: u32) -> u32 {\n"
+ " self.n + k\n"
+ " }\n"
+ "}\n");
+ write_temp_file(tmp, "src/main.rs",
+ "mod store;\n"
+ "\n"
+ "use crate::store::Store;\n"
+ "\n"
+ "fn run() -> u32 {\n"
+ " let s = Store::new();\n"
+ " s.get(1)\n"
+ "}\n"
+ "\n"
+ "fn main() {\n"
+ " run();\n"
+ "}\n");
+ write_temp_file(tmp, "perlsrc/Lib.pm",
+ "package Lib;\n"
+ "\n"
+ "sub new {\n"
+ " my ($class) = @_;\n"
+ " return bless {}, $class;\n"
+ "}\n"
+ "\n"
+ "1;\n");
+ cbm_pipeline_t *p = NULL;
+ cbm_store_t *s = rust_fixture_run(tmp, pad_files, "rust_only.db", &p);
+ ASSERT_NOT_NULL(s);
+ const char *project = cbm_pipeline_project_name(p);
+
+ /* Never onto the Perl constructor ... */
+ ASSERT_EQ(named_edge_to_file_count(s, project, "CALLS", "run", "new", "perlsrc/Lib.pm"), 0);
+ /* ... and the Rust call still binds the Rust associated function. */
+ ASSERT_GTE(named_edge_to_file_count(s, project, "CALLS", "run", "new", "src/store.rs"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_rust_call_never_binds_another_language) {
+ return rust_registry_rust_only_case(0);
+ }
+
+ TEST(pipeline_rust_call_never_binds_another_language_parallel) {
+ return rust_registry_rust_only_case(52);
+ }
+
+ /* `Opts::write(true)` is an associated function. The LSP leaves it to the
+ * registry (import_map -> fsx.Opts.write), but its free-function short-name
+ * fallback bound it to the project's only free `write` (cache.write) first, and
+ * that LSP row pre-empted the right answer. With the cross-language namesakes
+ * gone (above), this hijack replaced 600+ correct qualified_suffix/import_map
+ * edges on the Rust corpus. A type-qualified call never takes that fallback. */
+ static int rust_assoc_call_free_namesake_case(int pad_files) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_rust_assoc_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "Cargo.toml", "[package]\nname = \"app\"\nversion = \"0.1.0\"\n");
+ write_temp_file(tmp, "src/fsx.rs",
+ "pub struct Opts {\n"
+ " pub w: bool,\n"
+ "}\n"
+ "\n"
+ "impl Opts {\n"
+ " pub fn write(w: bool) -> Opts {\n"
+ " Opts { w }\n"
+ " }\n"
+ "}\n");
+ write_temp_file(tmp, "src/cache.rs",
+ "pub fn write(p: &str) -> usize {\n"
+ " p.len()\n"
+ "}\n");
+ write_temp_file(tmp, "src/main.rs",
+ "mod cache;\n"
+ "mod fsx;\n"
+ "\n"
+ "use crate::fsx::Opts;\n"
+ "\n"
+ "fn run() -> bool {\n"
+ " let o = Opts::write(true);\n"
+ " o.w\n"
+ "}\n"
+ "\n"
+ "fn main() {\n"
+ " run();\n"
+ " cache::write(\"x\");\n"
+ "}\n");
+ cbm_pipeline_t *p = NULL;
+ cbm_store_t *s = rust_fixture_run(tmp, pad_files, "rust_assoc.db", &p);
+ ASSERT_NOT_NULL(s);
+ const char *project = cbm_pipeline_project_name(p);
+
+ /* The associated function, never the free namesake ... */
+ ASSERT_GTE(named_edge_to_file_count(s, project, "CALLS", "run", "write", "src/fsx.rs"), 1);
+ ASSERT_EQ(named_edge_to_file_count(s, project, "CALLS", "run", "write", "src/cache.rs"), 0);
+ /* ... while the module-qualified free call keeps its target. */
+ ASSERT_GTE(named_edge_to_file_count(s, project, "CALLS", "main", "write", "src/cache.rs"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_rust_assoc_call_never_binds_free_namesake) {
+ return rust_assoc_call_free_namesake_case(0);
+ }
+
+ TEST(pipeline_rust_assoc_call_never_binds_free_namesake_parallel) {
+ return rust_assoc_call_free_namesake_case(52);
+ }
+
+ /* F-R4 (#763, Rust): calls inside a method of a generic impl (`impl<T> Gen<T>`,
+ * `impl<'a> Life<'a>`) were sourced from the File node: the call scope kept the
+ * generic arguments the def side strips. Each method must be the source of its
+ * own call. pad_files > 0 forces the parallel resolver. */
+ static int rust_generic_impl_attribution_case(int pad_files) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_rust_gimpl_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "Cargo.toml", "[package]\nname = \"fx\"\nversion = \"0.1.0\"\n");
+ write_temp_file(
+ tmp, "src/lib.rs",
+ "pub struct Gen<T> { v: T }\n"
+ "impl<T> Gen<T> {\n"
+ " pub fn in_generic(&self) -> u32 { helper_a() + self.other_g() + Self::assoc_g() }\n"
+ " pub fn other_g(&self) -> u32 { 3 }\n"
+ " pub fn assoc_g() -> u32 { 4 }\n"
+ "}\n"
+ "pub struct Life<'a> { s: &'a str }\n"
+ "impl<'a> Life<'a> {\n"
+ " pub fn in_lifetime(&self) -> u32 { helper_b() + self.other_l() }\n"
+ " pub fn other_l(&self) -> u32 { 5 }\n"
+ "}\n"
+ "pub fn helper_a() -> u32 { 1 }\n"
+ "pub fn helper_b() -> u32 { 2 }\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/filler%d.rs", i);
+ snprintf(body, sizeof(body), "pub fn filler%d() -> u32 {\n %d\n}\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *saved = NULL;
+ if (pad_files > 0) {
+ char *old_workers = getenv("CBM_WORKERS");
+ saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ }
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/rust_gimpl.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_TRUE(cross_file_call_exists(s, project, "in_generic", "helper_a"));
+ ASSERT_TRUE(cross_file_call_exists(s, project, "in_lifetime", "helper_b"));
+ /* ... and not from the file. */
+ ASSERT_FALSE(cross_file_call_exists(s, project, "lib.rs", "helper_a"));
+ ASSERT_FALSE(cross_file_call_exists(s, project, "lib.rs", "helper_b"));
+ /* The LSP side names the impl's self type without its arguments too: its
+ * rows join these callers (lsp_*, not a registry fallback), and `self.` /
+ * `Self::` dispatch inside a generic impl resolves (Self::assoc_g had no
+ * edge at all). */
+ ASSERT_TRUE(
+ cross_file_call_has_strategy(s, project, "in_generic", "helper_a", "\"strategy\":\"lsp_"));
+ ASSERT_TRUE(
+ cross_file_call_has_strategy(s, project, "in_generic", "other_g", "\"strategy\":\"lsp_"));
+ ASSERT_TRUE(cross_file_call_exists(s, project, "in_generic", "assoc_g"));
+ ASSERT_TRUE(
+ cross_file_call_has_strategy(s, project, "in_lifetime", "other_l", "\"strategy\":\"lsp_"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (pad_files > 0) {
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_rust_generic_impl_method_sources_its_calls) {
+ return rust_generic_impl_attribution_case(0);
+ }
+
+ TEST(pipeline_rust_generic_impl_method_sources_its_calls_parallel) {
+ return rust_generic_impl_attribution_case(52);
+ }
+
+ TEST(pipeline_go_rw_usage_never_cross_into_c_parallel) {
+ /* Parallel twin of the test above: USAGE and WRITES/READS each have a
+ * second, independent resolver in pass_parallel.c (resolve_file_usages /
+ * resolve_file_rw) that must consult the same guard — the field census
+ * that motivated this caught the sequential-only fix leaving 344 Go→C
+ * WRITES alive on a ~1150-file repo. >= 50 files forces the parallel
+ * pipeline. */
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_rwp_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_go_c_ref_guard_fixture(tmp, 52);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_rwp.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_GTE(fixture_node_count(s, project, "app/app.go", "TrackEvent", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "app/app.go", "UsesHandle", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "app/app.go", "WriteTotal", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "probe/probe.c", "handle", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "probe/probe.c", "event", "Variable"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "probe/probe.c", "total_events", "Variable"), 1);
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "TrackEvent", "event", "WRITES"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "TrackEvent", "event", "READS"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "UsesHandle", "handle", "WRITES"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "UsesHandle", "handle", "READS"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "UsesHandle", "handle", "USAGE"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "WriteTotal", "total_events", "WRITES"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "WriteTotal", "total_events", "USAGE"));
+ ASSERT_TRUE(cross_file_edge_exists(s, project, "Bump", "Counter", "WRITES"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Fixture for the #2053 Rust std-receiver probes (sequential and parallel
+ * twins). The Rust LSP types `root: &Path` and dispatches `root.join(..)` to
+ * std's Path::join — a symbol with no graph node. Before the fix the pipeline
+ * then fell back to the textual registry, which bound the call to the only
+ * project method named `join` (EvidenceTier::join, unique_name). The
+ * call-expression receiver (`root.to_path_buf().join(..)`) is the same class
+ * one hop later: it needs to_path_buf's return type and PathBuf's Deref to
+ * Path. POSITIVE tripwires: the typed project call keeps its LSP edge, and a
+ * closure-parameter receiver the LSP cannot type still reaches the registry,
+ * so the fix removes only calls the LSP positively placed outside the
+ * project. `m.get(k)` on a std HashMap guards the parallel route fallback,
+ * which must not turn the skipped call into a self-call. pad_files > 0
+ * crosses the parallel-pipeline threshold. */
+ static void write_rust_std_receiver_fixture(const char *tmp, int pad_files) {
+ write_temp_file(tmp, "Cargo.toml",
+ "[package]\nname = \"stdrecv\"\nversion = \"0.1.0\"\nedition = \"2021\"\n");
+ write_temp_file(tmp, "src/lib.rs",
+ "use std::collections::HashMap;\n"
+ "use std::path::{Path, PathBuf};\n"
+ "\n"
+ "pub struct EvidenceTier(pub u8);\n"
+ "impl EvidenceTier {\n"
+ " pub fn join(&self, other: &EvidenceTier) -> EvidenceTier {\n"
+ " EvidenceTier(self.0.max(other.0))\n"
+ " }\n"
+ "}\n"
+ "\n"
+ "pub struct Gauge(pub u8);\n"
+ "impl Gauge {\n"
+ " pub fn recalibrate_gauge(&self) -> u8 {\n"
+ " self.0\n"
+ " }\n"
+ "}\n"
+ "\n"
+ "pub fn real_caller() -> EvidenceTier {\n"
+ " EvidenceTier(1).join(&EvidenceTier(2))\n"
+ "}\n"
+ "\n"
+ "pub fn stdlib_receiver(root: &Path) -> PathBuf {\n"
+ " root.join(\"subdir\")\n"
+ "}\n"
+ "\n"
+ "pub fn call_expr_receiver(root: &Path) -> PathBuf {\n"
+ " root.to_path_buf().join(\"nested\")\n"
+ "}\n"
+ "\n"
+ "pub fn untyped_receiver(gauges: &[Gauge]) -> u8 {\n"
+ " gauges.iter().map(|g| g.recalibrate_gauge()).sum()\n"
+ "}\n"
+ "\n"
+ "pub fn std_map_lookup(m: &HashMap<String, u8>, k: &str) -> Option<u8> {\n"
+ " m.get(k).copied()\n"
+ "}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/filler%d.rs", i);
+ snprintf(body, sizeof(body), "pub fn filler%d() -> i32 {\n %d\n}\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ }
+
+ static int run_rust_std_receiver_probe(int pad_files, const char *tag) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_rs_%s_XXXXXX", tag);
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_rust_std_receiver_fixture(tmp, pad_files);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/rs_std_recv.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* NEGATIVE: std's Path::join / PathBuf::join are not project symbols. */
+ ASSERT_EQ(named_edge_count(s, project, "CALLS", "stdlib_receiver", "join"), 0);
+ ASSERT_EQ(named_edge_count(s, project, "CALLS", "call_expr_receiver", "join"), 0);
+ /* NEGATIVE: a std `map.get(k)` with no route path is no self-call (the
+ * parallel empty-resolution route fallback must not bind source->source). */
+ ASSERT_EQ(named_edge_count(s, project, "CALLS", "std_map_lookup", "std_map_lookup"), 0);
+ /* POSITIVE: the typed project call keeps its edge. */
+ ASSERT_EQ(named_edge_count(s, project, "CALLS", "real_caller", "join"), 1);
+ /* POSITIVE: an untyped receiver still reaches the registry fallback. */
+ ASSERT_EQ(named_edge_count(s, project, "CALLS", "untyped_receiver", "recalibrate_gauge"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_rust_std_receiver_never_binds_project_method) {
+ return run_rust_std_receiver_probe(0, "seq");
+ }
+
+ TEST(pipeline_rust_std_receiver_never_binds_project_method_parallel) {
+ return run_rust_std_receiver_probe(52, "par");
+ }
+
+ static int count_nodes_named(cbm_store_t *s, const char *project, const char *name);
+
+ /* Fixture for the #1942 bare-reference-vs-Field probes: a Go struct field
+ * named like the commonest local (`err`), and a function whose local of the
+ * same name must NOT bind it — in Go a field is only reachable through a
+ * selector expression, never a bare identifier. Needs Go Field extraction
+ * (#1935) to have anything to falsely bind. */
+ static void write_go_bare_field_fixture(const char *tmp, int pad_files) {
+ write_temp_file(tmp, "go.mod", "module example.com/fxbare\n\ngo 1.22\n");
+ write_temp_file(tmp, "state/state.go",
+ "package state\n"
+ "\n"
+ "type Tracker struct {\n"
+ "\terr error\n"
+ "\tn int\n"
+ "}\n");
+ write_temp_file(tmp, "app/app.go",
+ "package app\n"
+ "\n"
+ "import \"errors\"\n"
+ "\n"
+ "func Run() error {\n"
+ "\terr := errors.New(\"x\")\n"
+ "\treturn err\n"
+ "}\n");
+ /* #1962: genuine selector references from a sibling file of the same
+ * package. `t.err = nil` writes the field through a selector; `t.n` reads
+ * it. The extractor strips the receiver on both paths, so only the
+ * is_member_access signal can distinguish these from Run's bare local. */
+ write_temp_file(tmp, "state/reset.go",
+ "package state\n"
+ "\n"
+ "func (t *Tracker) Reset() int {\n"
+ "\tt.err = nil\n"
+ "\treturn t.n\n"
+ "}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "pad/filler%d.go", i);
+ snprintf(body, sizeof(body), "package pad\n\nfunc filler%d() int { return %d }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ }
+
+ TEST(pipeline_go_bare_ref_never_binds_field) {
+ /* #1942: the READS/WRITES resolvers and the USAGE registry fallback hand
+ * bare reference text to the short-name registry, which contains Field
+ * nodes — so every Go local `err := …` bound whichever struct field was
+ * named err (21308 USAGE / 5191 WRITES onto Go fields on the measured
+ * repo, top target a test struct's field collecting 3013 edges).
+ * Sequential-path twin; the parallel twin follows. */
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_bare_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_go_bare_field_fixture(tmp, 0);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_bare.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* The field must exist for the probe to mean anything (#1935's fix). */
+ ASSERT_GTE(fixture_node_count(s, project, "app/app.go", "Run", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "state/state.go", "err", "Field"), 1);
+ /* Reproduce-first: RED before the fix — the bare local binds the field. */
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "Run", "err", "WRITES"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "Run", "err", "READS"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "Run", "err", "USAGE"));
+ /* #1962, reproduce-first: RED while the guard is a blanket veto — genuine
+ * selector references must reach the field (write via `t.err = nil`,
+ * value use via `t.n`). */
+ ASSERT_TRUE(cross_file_edge_exists(s, project, "Reset", "err", "WRITES"));
+ ASSERT_TRUE(cross_file_edge_exists(s, project, "Reset", "n", "USAGE"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_go_bare_ref_never_binds_field_parallel) {
+ /* Parallel twin: resolve_file_rw / resolve_file_usages are independent
+ * resolvers and must consult the same predicate (#1928's lesson). */
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_go_barep_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_go_bare_field_fixture(tmp, 52);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/go_barep.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_GTE(fixture_node_count(s, project, "app/app.go", "Run", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "state/state.go", "err", "Field"), 1);
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "Run", "err", "WRITES"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "Run", "err", "READS"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "Run", "err", "USAGE"));
+ /* #1962 parallel twin: resolve_file_rw / resolve_file_usages must honour
+ * the member-access signal exactly like the sequential resolvers. */
+ ASSERT_TRUE(cross_file_edge_exists(s, project, "Reset", "err", "WRITES"));
+ ASSERT_TRUE(cross_file_edge_exists(s, project, "Reset", "n", "USAGE"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* #2666: tests/test_main.c runs every suite through a macro,
+ * RUN_SELECTED_SUITE(mcp); the argument is a bare C identifier that names no
+ * declaration, and the registry fallback bound it to whichever struct member
+ * was called `mcp`. toggle() writes a bare name the extractor cannot see
+ * declared (a macro-made global, say) that a struct member also carries.
+ * state.c holds the genuine member uses that must keep their edges.
+ * pad_files pushes the run past MIN_FILES_FOR_PARALLEL for the parallel twin. */
+ static void write_c_bare_field_fixture(const char *tmp, int pad_files) {
+ write_temp_file(tmp, "include/suite.h",
+ "typedef struct suite_state {\n"
+ " char mcp[64];\n"
+ " int count;\n"
+ " int enabled;\n"
+ "} suite_state_t;\n");
+ write_temp_file(tmp, "tests/main.c",
+ "#include \"suite.h\"\n"
+ "#define RUN_SELECTED_SUITE(name) run_suite(#name)\n"
+ "int run_suite(const char *name);\n"
+ "int main(void) {\n"
+ " RUN_SELECTED_SUITE(mcp);\n"
+ " RUN_SELECTED_SUITE(count);\n"
+ " return 0;\n"
+ "}\n"
+ "void toggle(void) {\n"
+ " enabled = 1;\n"
+ "}\n");
+ write_temp_file(tmp, "src/state.c",
+ "#include \"suite.h\"\n"
+ "int state_count(const suite_state_t *s) { return s->count; }\n"
+ "void state_reset(suite_state_t *s) { s->enabled = 0; }\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "pad/filler%d.c", i);
+ snprintf(body, sizeof(body), "int filler%d(void) { return %d; }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ }
+
+ static int run_c_bare_field_case(const char *tmpl, int pad_files) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "%s", tmpl);
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_c_bare_field_fixture(tmp, pad_files);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/c_bare.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* The fields must exist for the probes to mean anything. */
+ ASSERT_GTE(fixture_node_count(s, project, "include/suite.h", "mcp", "Field"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "include/suite.h", "count", "Field"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "include/suite.h", "enabled", "Field"), 1);
+ /* Reproduce-first: RED before the fix — the macro arguments bind the
+ * same-named struct members, and the bare write binds `enabled`. */
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "main", "mcp", "USAGE"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "main", "count", "USAGE"));
+ ASSERT_FALSE(cross_file_edge_exists(s, project, "toggle", "enabled", "WRITES"));
+ /* The member half of `s->count` / `s->enabled = 0` still binds the field. */
+ ASSERT_TRUE(cross_file_edge_exists(s, project, "state_count", "count", "USAGE"));
+ ASSERT_TRUE(cross_file_edge_exists(s, project, "state_reset", "enabled", "WRITES"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_c_bare_ref_never_binds_field) {
+ /* Sequential path: resolve_usage_edges / resolve_rw_edges. */
+ return run_c_bare_field_case("/tmp/cbm_c_bare_XXXXXX", 0);
+ }
+
+ TEST(pipeline_c_bare_ref_never_binds_field_parallel) {
+ /* Parallel twin: resolve_file_usages / resolve_file_rw must consult the
+ * same predicate (#1928's lesson). */
+ return run_c_bare_field_case("/tmp/cbm_c_barep_XXXXXX", 52);
+ }
+
+ /* A C caller of a header function that shares its name with a struct member
+ * elsewhere (kernel: include/linux/mm.h put_page beside the arm64
+ * kvm_pgtable_mm_ops.put_page member). pad_files pushes the run past
+ * MIN_FILES_FOR_PARALLEL for the parallel twin. */
+ static void write_c_header_namesake_fixture(const char *tmp, int pad_files) {
+ write_temp_file(tmp, "include/linux/mm.h",
+ "struct page;\n"
+ "static inline void put_page(struct page *page)\n"
+ "{\n"
+ "\t(void)page;\n"
+ "}\n");
+ write_temp_file(tmp, "arch/arm64/include/asm/kvm_pgtable.h",
+ "struct kvm_pgtable_mm_ops {\n"
+ "\tvoid (*put_page)(void *addr);\n"
+ "};\n");
+ write_temp_file(tmp, "arch/arm64/kernel/elfcore.c",
+ "#include <linux/mm.h>\n"
+ "#include <asm/kvm_pgtable.h>\n"
+ "int mte_dump_tag_range(struct page *page)\n"
+ "{\n"
+ "\tput_page(page);\n"
+ "\treturn 0;\n"
+ "}\n");
+ write_temp_file(tmp, "drivers/net/rx.c",
+ "#include <linux/mm.h>\n"
+ "void recv_buffer_free(struct page *page)\n"
+ "{\n"
+ "\tput_page(page);\n"
+ "}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "pad/filler%d.c", i);
+ snprintf(body, sizeof(body), "int filler%d(void) { return %d; }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ }
+
+ /* CALLS edges from the nodes named src_name into nodes named tgt_name that
+ * carry tgt_label: the name-only probes cannot tell the header Function from
+ * its struct-member namesake. */
+ static int labelled_call_count(cbm_store_t *s, const char *project, const char *src_name,
+ const char *tgt_name, const char *tgt_label) {
+ cbm_node_t *srcs = NULL;
+ cbm_node_t *tgts = NULL;
+ int sc = 0;
+ int tc = 0;
+ int n = 0;
+ cbm_store_find_nodes_by_name(s, project, src_name, &srcs, &sc);
+ cbm_store_find_nodes_by_name(s, project, tgt_name, &tgts, &tc);
+ for (int i = 0; i < sc; i++) {
+ cbm_edge_t *edges = NULL;
+ int ec = 0;
+ cbm_store_find_edges_by_source_type(s, srcs[i].id, "CALLS", &edges, &ec);
+ for (int j = 0; j < ec; j++) {
+ for (int k = 0; k < tc; k++) {
+ if (edges[j].target_id == tgts[k].id && tgts[k].label &&
+ strcmp(tgts[k].label, tgt_label) == 0) {
+ n++;
+ }
+ }
+ }
+ if (edges) {
+ cbm_store_free_edges(edges, ec);
+ }
+ }
+ if (srcs) {
+ cbm_store_free_nodes(srcs, sc);
+ }
+ if (tgts) {
+ cbm_store_free_nodes(tgts, tc);
+ }
+ return n;
+ }
+
+ TEST(pipeline_c_call_reaches_header_function_beside_field) {
+ /* 2026-10-13 kernel audit: `put_page(page)` 345 -> 9 callers. The struct
+ * member in the short-name registry makes the bare name two candidates,
+ * so the lookup answers by suffix_match; .h is C++ in the extension table
+ * and the #725 guard dropped the C caller's edge as cross-language.
+ * Reproduce-first: RED before the fix. Sequential-path twin. */
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_c_hdr_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_c_header_namesake_fixture(tmp, 0);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/c_hdr.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* Both namesakes must exist for the probe to mean anything. */
+ ASSERT_GTE(fixture_node_count(s, project, "include/linux/mm.h", "put_page", "Function"), 1);
+ ASSERT_GTE(
+ fixture_node_count(s, project, "arch/arm64/include/asm/kvm_pgtable.h", "put_page", "Field"),
+ 1);
+ ASSERT_EQ(labelled_call_count(s, project, "mte_dump_tag_range", "put_page", "Function"), 1);
+ ASSERT_EQ(labelled_call_count(s, project, "recv_buffer_free", "put_page", "Function"), 1);
+ /* A bare C call never names the struct member. */
+ ASSERT_EQ(labelled_call_count(s, project, "mte_dump_tag_range", "put_page", "Field"), 0);
+ ASSERT_EQ(labelled_call_count(s, project, "recv_buffer_free", "put_page", "Field"), 0);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_c_call_reaches_header_function_beside_field_parallel) {
+ /* Parallel twin: the kernel resolves through pass_parallel.c, which asks
+ * the same #725 guard. */
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_c_hdrp_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_c_header_namesake_fixture(tmp, 52);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/c_hdrp.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_GTE(fixture_node_count(s, project, "include/linux/mm.h", "put_page", "Function"), 1);
+ ASSERT_GTE(
+ fixture_node_count(s, project, "arch/arm64/include/asm/kvm_pgtable.h", "put_page", "Field"),
+ 1);
+ ASSERT_EQ(labelled_call_count(s, project, "mte_dump_tag_range", "put_page", "Function"), 1);
+ ASSERT_EQ(labelled_call_count(s, project, "recv_buffer_free", "put_page", "Function"), 1);
+ ASSERT_EQ(labelled_call_count(s, project, "mte_dump_tag_range", "put_page", "Field"), 0);
+ ASSERT_EQ(labelled_call_count(s, project, "recv_buffer_free", "put_page", "Field"), 0);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* True when a node named src_name has an edge of edge_type to the Field
+ * `field` OWNED BY `owner` (qualified name ends in ".owner.field"). The
+ * name-only cross_file_edge_exists cannot tell two same-named fields apart,
+ * which is exactly what the C member-access probes below must do. */
+ static bool field_edge_exists(cbm_store_t *s, const char *project, const char *src_name,
+ const char *owner, const char *field, const char *edge_type) {
+ char suffix[256];
+ snprintf(suffix, sizeof(suffix), ".%s.%s", owner, field);
+ size_t suffix_len = strlen(suffix);
+ cbm_node_t *srcs = NULL;
+ cbm_node_t *tgts = NULL;
+ int sc = 0;
+ int tc = 0;
+ cbm_store_find_nodes_by_name(s, project, src_name, &srcs, &sc);
+ cbm_store_find_nodes_by_name(s, project, field, &tgts, &tc);
+ bool found = false;
+ for (int i = 0; i < sc && !found; i++) {
+ cbm_edge_t *edges = NULL;
+ int ec = 0;
+ cbm_store_find_edges_by_source_type(s, srcs[i].id, edge_type, &edges, &ec);
+ for (int j = 0; j < ec && !found; j++) {
+ for (int k = 0; k < tc && !found; k++) {
+ const char *qn = tgts[k].qualified_name;
+ size_t qn_len = qn ? strlen(qn) : 0;
+ found = edges[j].target_id == tgts[k].id && tgts[k].label &&
+ strcmp(tgts[k].label, "Field") == 0 && qn_len >= suffix_len &&
+ strcmp(qn + qn_len - suffix_len, suffix) == 0;
+ }
+ }
+ if (edges) {
+ cbm_store_free_edges(edges, ec);
+ }
+ }
+ if (srcs) {
+ cbm_store_free_nodes(srcs, sc);
+ }
+ if (tgts) {
+ cbm_store_free_nodes(tgts, tc);
+ }
+ return found;
+ }
+
+ /* Number of edges of edge_type that END on the Field `field` owned by `owner`,
+ * whatever their source: the call probes below must hold for a caller in any
+ * language, including a shell script whose source node has no stable name. */
+ static int field_inbound_edge_count(cbm_store_t *s, const char *project, const char *owner,
+ const char *field, const char *edge_type) {
+ char suffix[256];
+ snprintf(suffix, sizeof(suffix), ".%s.%s", owner, field);
+ size_t suffix_len = strlen(suffix);
+ cbm_node_t *tgts = NULL;
+ int tc = 0;
+ cbm_store_find_nodes_by_name(s, project, field, &tgts, &tc);
+ int total = 0;
+ for (int k = 0; k < tc; k++) {
+ const char *qn = tgts[k].qualified_name;
+ size_t qn_len = qn ? strlen(qn) : 0;
+ if (!tgts[k].label || strcmp(tgts[k].label, "Field") != 0 || qn_len < suffix_len ||
+ strcmp(qn + qn_len - suffix_len, suffix) != 0) {
+ continue;
+ }
+ cbm_edge_t *edges = NULL;
+ int ec = 0;
+ cbm_store_find_edges_by_target_type(s, tgts[k].id, edge_type, &edges, &ec);
+ total += ec;
+ if (edges) {
+ cbm_store_free_edges(edges, ec);
+ }
+ }
+ if (tgts) {
+ cbm_store_free_nodes(tgts, tc);
+ }
+ return total;
+ }
+
+ /* Fixture for the C member-access probes: two structs share the field name
+ * `count`, and each function touches exactly one of them. A bare-name lookup
+ * of `count` can only pick one Field for both functions; only the type of the
+ * object expression says which struct is meant. `use_opaque` reaches `count`
+ * through a type the project never defines, so no Field may be bound at all;
+ * `beta_only` through that same untyped object is the one Field of that name
+ * in the project, so nothing has to be picked and it binds.
+ *
+ * Calls follow the same rule. The structs carry a function-pointer member
+ * `notify` (declared through a typedef: a member spelled `void (*notify)(int)`
+ * has no Field node today, a separate extraction gap). `use_remote` calls
+ * Beta's `notify` from a file that declares its own struct with a `notify`
+ * member -- the candidate a bare-name lookup prefers, being in the same
+ * module. `call_param` calls a PARAMETER named like the field `alpha_only`,
+ * and `tool.sh` runs a command of that name: neither calls a struct member. */
+ static void write_c_member_field_fixture(const char *tmp, int pad_files) {
+ write_temp_file(tmp, "alpha.h",
+ "#ifndef ALPHA_H\n"
+ "#define ALPHA_H\n"
+ "typedef void (*alpha_notify_fn)(int);\n"
+ "struct Alpha {\n"
+ " int count;\n"
+ " int alpha_only;\n"
+ " alpha_notify_fn notify;\n"
+ "};\n"
+ "#endif\n");
+ write_temp_file(tmp, "beta.h",
+ "#ifndef BETA_H\n"
+ "#define BETA_H\n"
+ "typedef void (*beta_notify_fn)(int);\n"
+ "typedef struct {\n"
+ " int count;\n"
+ " int beta_only;\n"
+ " beta_notify_fn notify;\n"
+ "} Beta;\n"
+ "#endif\n");
+ write_temp_file(tmp, "use_alpha.c",
+ "#include \"alpha.h\"\n"
+ "\n"
+ "int use_alpha(struct Alpha *a) {\n"
+ " a->count = 1;\n"
+ " return a->count + a->alpha_only;\n"
+ "}\n"
+ "\n"
+ "int call_param(int (*alpha_only)(void)) {\n"
+ " return alpha_only();\n"
+ "}\n");
+ write_temp_file(tmp, "mix.c",
+ "#include \"beta.h\"\n"
+ "\n"
+ "typedef void (*local_notify_fn)(int);\n"
+ "struct Local {\n"
+ " local_notify_fn notify;\n"
+ "};\n"
+ "\n"
+ "void use_remote(Beta b) {\n"
+ " b.notify(3);\n"
+ "}\n");
+ write_temp_file(tmp, "tool.sh",
+ "#!/bin/sh\n"
+ "alpha_only --check\n");
+ write_temp_file(tmp, "use_beta.c",
+ "#include \"beta.h\"\n"
+ "\n"
+ "int use_beta(Beta b) {\n"
+ " b.count = 2;\n"
+ " return b.count + b.beta_only;\n"
+ "}\n");
+ write_temp_file(tmp, "use_opaque.c",
+ "struct Opaque;\n"
+ "\n"
+ "int use_opaque(struct Opaque *o) {\n"
+ " return o->count + o->beta_only;\n"
+ "}\n");
+ /* Inline functions in a header. A `.h` is parsed as C++, and its member
+ * accesses mean what they mean in the .c files that include it. */
+ write_temp_file(tmp, "inline.h",
+ "#ifndef INLINE_H\n"
+ "#define INLINE_H\n"
+ "#include \"alpha.h\"\n"
+ "#include \"beta.h\"\n"
+ "static inline int hdr_alpha(struct Alpha *a) {\n"
+ " return a->count;\n"
+ "}\n"
+ "static inline int hdr_beta(Beta *b) {\n"
+ " b->count = 1;\n"
+ " return b->count;\n"
+ "}\n"
+ "/* A struct the header itself declares, through a typedef. */\n"
+ "typedef struct {\n"
+ " int count;\n"
+ " char *buf;\n"
+ "} HdrBuf;\n"
+ "struct HdrNode {\n"
+ " int count;\n"
+ "};\n"
+ "static inline int hdr_own_typedef(HdrBuf *s) {\n"
+ " return s->count;\n"
+ "}\n"
+ "static inline int hdr_own_struct(struct HdrNode *n) {\n"
+ " return n->count;\n"
+ "}\n"
+ "#endif\n");
+ /* Functions inside preprocessor branches of a .c file are functions like
+ * any other. */
+ write_temp_file(tmp, "guarded.c",
+ "#include \"alpha.h\"\n"
+ "#include \"beta.h\"\n"
+ "\n"
+ "#ifdef SOME_CONFIG\n"
+ "int guarded_alpha(struct Alpha *a) {\n"
+ " return a->count;\n"
+ "}\n"
+ "#else\n"
+ "int guarded_beta(Beta *b) {\n"
+ " return b->count;\n"
+ "}\n"
+ "#endif\n");
+ /* A member call on an object nothing types. In C the one member of that
+ * name in the project may still bind; in a C++ source such a call is a
+ * method of some type the project does not hold, and binds nothing. */
+ write_temp_file(tmp, "cb.h",
+ "#ifndef CB_H\n"
+ "#define CB_H\n"
+ "struct CbTable {\n"
+ " int (*only_cb)(int);\n"
+ "};\n"
+ "#endif\n");
+ write_temp_file(tmp, "untyped_c.c",
+ "struct Hidden;\n"
+ "\n"
+ "int c_untyped_call(struct Hidden *h) {\n"
+ " return h->only_cb(1);\n"
+ "}\n");
+ write_temp_file(tmp, "untyped_cpp.cpp",
+ "template <class T> int cpp_untyped_call(T *h) {\n"
+ " return h->only_cb(1);\n"
+ "}\n");
+ /* A global variable declared behind an `#ifndef` types the accesses made
+ * through it, whether its type is spelled with `struct` or a typedef. */
+ write_temp_file(tmp, "globals.c",
+ "#include \"alpha.h\"\n"
+ "#include \"beta.h\"\n"
+ "\n"
+ "#ifndef NO_GLOBALS\n"
+ "static struct Alpha g_alpha;\n"
+ "static Beta g_beta;\n"
+ "#endif\n"
+ "\n"
+ "int read_alpha_global(void) {\n"
+ " return g_alpha.count;\n"
+ "}\n"
+ "\n"
+ "int read_beta_global(void) {\n"
+ " return g_beta.count;\n"
+ "}\n");
+ /* Ops tables: pointer-to-function members written inline, called through
+ * `->`. Two tables share both member names, so only the object's type
+ * says which is called; `arrow_chain` reaches its table through a member
+ * whose type is spelled `struct Ops *`. */
+ write_temp_file(tmp, "ops.h",
+ "#ifndef OPS_H\n"
+ "#define OPS_H\n"
+ "struct Dev;\n"
+ "struct Ops {\n"
+ " void (*open)(int fd);\n"
+ " int (*shut)(int fd);\n"
+ " struct Dev *(*owner)(int fd);\n"
+ "};\n"
+ "struct Dev {\n"
+ " struct Ops *ops;\n"
+ " int id;\n"
+ "};\n"
+ "struct Bank {\n"
+ " struct Dev *devs, *spare;\n"
+ " struct Dev fixed[2];\n"
+ " int id;\n"
+ "};\n"
+ "#endif\n");
+ write_temp_file(tmp, "other_ops.h",
+ "#ifndef OTHER_OPS_H\n"
+ "#define OTHER_OPS_H\n"
+ "struct OtherOps {\n"
+ " void (*open)(int fd);\n"
+ " int (*shut)(int fd);\n"
+ " int id;\n"
+ "};\n"
+ "#endif\n");
+ write_temp_file(tmp, "use_ops.c",
+ "#include \"ops.h\"\n"
+ "#include \"other_ops.h\"\n"
+ "\n"
+ "void arrow_ops(struct Ops *o) {\n"
+ " o->open(1);\n"
+ "}\n"
+ "\n"
+ "void arrow_other(struct OtherOps *x) {\n"
+ " x->open(2);\n"
+ "}\n"
+ "\n"
+ "int arrow_chain(struct Dev *d) {\n"
+ " return d->ops->shut(3);\n"
+ "}\n"
+ "\n"
+ "int arrow_ret(struct Ops *o) {\n"
+ " return o->owner(4)->id;\n"
+ "}\n"
+ "\n"
+ "int index_ptr(struct Bank *b) {\n"
+ " return b->devs[1].id;\n"
+ "}\n"
+ "\n"
+ "int index_arr(struct Bank *b) {\n"
+ " return b->fixed[0].id;\n"
+ "}\n"
+ "\n"
+ "int second_decl(struct Bank *b) {\n"
+ " return b->spare->id;\n"
+ "}\n");
+ /* Designated initializers name members with no object expression at all:
+ * the type being initialized says whose member `.open` is. At file scope
+ * (the usual ops table), nested, through an array, in a block and in a
+ * compound literal. Each table file initializes ONE of the two tables. */
+ write_temp_file(tmp, "table_ops.c",
+ "#include \"ops.h\"\n"
+ "\n"
+ "static void my_open(int fd) { (void)fd; }\n"
+ "static int my_shut(int fd) { return fd; }\n"
+ "\n"
+ "static struct Ops table_ops = {\n"
+ " .open = my_open,\n"
+ " .shut = my_shut,\n"
+ "};\n"
+ "\n"
+ "static struct Bank bank_init = {\n"
+ " .fixed = { [0] = { .ops = &table_ops } },\n"
+ " .id = 3,\n"
+ "};\n");
+ write_temp_file(tmp, "table_other.c",
+ "#include \"other_ops.h\"\n"
+ "\n"
+ "static void their_open(int fd) { (void)fd; }\n"
+ "\n"
+ "static struct OtherOps other_table = {\n"
+ " .open = their_open,\n"
+ "};\n");
+ write_temp_file(tmp, "init_local.c",
+ "#include \"ops.h\"\n"
+ "#include \"other_ops.h\"\n"
+ "\n"
+ "int init_block(void) {\n"
+ " struct Dev d = { .id = 1 };\n"
+ " return d.id;\n"
+ "}\n"
+ "\n"
+ "void init_literal(struct Bank *b) {\n"
+ " *b->devs = (struct Dev){ .id = 2 };\n"
+ "}\n"
+ "\n"
+ "void init_array(void) {\n"
+ " struct OtherOps pair[2] = { { .id = 1 }, { .id = 2 } };\n"
+ " (void)pair;\n"
+ "}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "pad/filler%d.c", i);
+ snprintf(body, sizeof(body), "int filler%d(void) { return %d; }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ }
+
+ /* Shared assertions for the sequential and the parallel twin. */
+ static int assert_c_member_fields_bind_by_type(cbm_store_t *s, const char *project) {
+ /* The probe means nothing unless both same-named fields exist. */
+ ASSERT_GTE(fixture_node_count(s, project, "alpha.h", "count", "Field"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "beta.h", "count", "Field"), 1);
+ /* Reproduce-first: RED while `count` resolves by bare name — both
+ * functions then bind the SAME Field, so one of each pair is wrong. */
+ ASSERT_TRUE(field_edge_exists(s, project, "use_alpha", "Alpha", "count", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "use_alpha", "Beta", "count", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "use_beta", "Beta", "count", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "use_beta", "Alpha", "count", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "use_alpha", "Alpha", "count", "WRITES"));
+ ASSERT_FALSE(field_edge_exists(s, project, "use_alpha", "Beta", "count", "WRITES"));
+ ASSERT_TRUE(field_edge_exists(s, project, "use_beta", "Beta", "count", "WRITES"));
+ ASSERT_FALSE(field_edge_exists(s, project, "use_beta", "Alpha", "count", "WRITES"));
+ /* A field whose name is unique keeps its edge. */
+ ASSERT_TRUE(field_edge_exists(s, project, "use_alpha", "Alpha", "alpha_only", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "use_beta", "Beta", "beta_only", "USAGE"));
+ /* An object whose type the project never defines binds no Field by a
+ * name several structs share... */
+ ASSERT_FALSE(field_edge_exists(s, project, "use_opaque", "Alpha", "count", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "use_opaque", "Beta", "count", "USAGE"));
+ /* ...and still binds a member name the project holds exactly once. */
+ ASSERT_TRUE(field_edge_exists(s, project, "use_opaque", "Beta", "beta_only", "USAGE"));
+ /* A call through a function-pointer member lands on the member of its
+ * object's type, not on the same-named member its own file declares. */
+ ASSERT_GTE(fixture_node_count(s, project, "mix.c", "notify", "Field"), 1);
+ ASSERT_TRUE(field_edge_exists(s, project, "use_remote", "Beta", "notify", "CALLS"));
+ ASSERT_FALSE(field_edge_exists(s, project, "use_remote", "Local", "notify", "CALLS"));
+ /* A bare C call of a parameter named `alpha_only` and a shell command of
+ * that name are not calls of the struct member, however unique the name. */
+ ASSERT_EQ(field_inbound_edge_count(s, project, "Alpha", "alpha_only", "CALLS"), 0);
+ /* `p->f(...)` through an inline pointer-to-function member: the call lands
+ * on the member of the pointed-to struct, never on the same-named member
+ * of the other table. */
+ ASSERT_GTE(fixture_node_count(s, project, "ops.h", "open", "Field"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "other_ops.h", "open", "Field"), 1);
+ ASSERT_TRUE(field_edge_exists(s, project, "arrow_ops", "Ops", "open", "CALLS"));
+ ASSERT_FALSE(field_edge_exists(s, project, "arrow_ops", "OtherOps", "open", "CALLS"));
+ ASSERT_TRUE(field_edge_exists(s, project, "arrow_other", "OtherOps", "open", "CALLS"));
+ ASSERT_FALSE(field_edge_exists(s, project, "arrow_other", "Ops", "open", "CALLS"));
+ /* The object of the call is itself a member access whose member is typed
+ * `struct Ops *`: both steps of the chain are typed. */
+ ASSERT_TRUE(field_edge_exists(s, project, "arrow_chain", "Dev", "ops", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "arrow_chain", "Ops", "shut", "CALLS"));
+ ASSERT_FALSE(field_edge_exists(s, project, "arrow_chain", "OtherOps", "shut", "CALLS"));
+ /* A call through a pointer-to-function member has that member's return
+ * type: `o->owner(4)->id` is the `id` of struct Dev. */
+ ASSERT_TRUE(field_edge_exists(s, project, "arrow_ret", "Ops", "owner", "CALLS"));
+ ASSERT_TRUE(field_edge_exists(s, project, "arrow_ret", "Dev", "id", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "arrow_ret", "OtherOps", "id", "USAGE"));
+ /* A pointer member and an array member have an element type, and the
+ * second declarator of `struct Dev *devs, *spare;` is a member too. `id`
+ * is a name three structs share, so each of these needs the full chain. */
+ ASSERT_TRUE(field_edge_exists(s, project, "index_ptr", "Bank", "devs", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "index_ptr", "Dev", "id", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "index_ptr", "Bank", "id", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "index_arr", "Bank", "fixed", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "index_arr", "Dev", "id", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "second_decl", "Bank", "spare", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "second_decl", "Dev", "id", "USAGE"));
+ /* The same rule inside a header's inline functions. */
+ ASSERT_TRUE(field_edge_exists(s, project, "hdr_alpha", "Alpha", "count", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "hdr_alpha", "Beta", "count", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "hdr_beta", "Beta", "count", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "hdr_beta", "Alpha", "count", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "hdr_beta", "Beta", "count", "WRITES"));
+ ASSERT_FALSE(field_edge_exists(s, project, "hdr_beta", "Alpha", "count", "WRITES"));
+ /* A struct the header declares itself, by typedef or by tag. */
+ ASSERT_TRUE(field_edge_exists(s, project, "hdr_own_typedef", "HdrBuf", "count", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "hdr_own_typedef", "Alpha", "count", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "hdr_own_struct", "HdrNode", "count", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "hdr_own_struct", "Beta", "count", "USAGE"));
+ /* ...and inside `#ifdef` / `#else` branches. */
+ ASSERT_TRUE(field_edge_exists(s, project, "guarded_alpha", "Alpha", "count", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "guarded_alpha", "Beta", "count", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "guarded_beta", "Beta", "count", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "guarded_beta", "Alpha", "count", "USAGE"));
+ /* An untyped member call binds the project's one member of that name in
+ * C, and nothing in a C++ source. */
+ ASSERT_GTE(fixture_node_count(s, project, "cb.h", "only_cb", "Field"), 1);
+ ASSERT_TRUE(field_edge_exists(s, project, "c_untyped_call", "CbTable", "only_cb", "CALLS"));
+ ASSERT_FALSE(field_edge_exists(s, project, "cpp_untyped_call", "CbTable", "only_cb", "CALLS"));
+ /* A global behind `#ifndef` types the accesses through it. */
+ ASSERT_TRUE(field_edge_exists(s, project, "read_alpha_global", "Alpha", "count", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "read_alpha_global", "Beta", "count", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "read_beta_global", "Beta", "count", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "read_beta_global", "Alpha", "count", "USAGE"));
+ /* Designated initializers at file scope: the source is the file. */
+ ASSERT_TRUE(field_edge_exists(s, project, "table_ops.c", "Ops", "open", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "table_ops.c", "Ops", "shut", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "table_ops.c", "OtherOps", "open", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "table_other.c", "OtherOps", "open", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "table_other.c", "Ops", "open", "USAGE"));
+ /* Nested: `.fixed = { [0] = { .ops = ... } }` initializes a Dev. */
+ ASSERT_TRUE(field_edge_exists(s, project, "table_ops.c", "Bank", "fixed", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "table_ops.c", "Dev", "ops", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "table_ops.c", "Bank", "id", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "table_ops.c", "Dev", "id", "USAGE"));
+ /* In a block, in a compound literal, and per element of an array. */
+ ASSERT_TRUE(field_edge_exists(s, project, "init_block", "Dev", "id", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "init_block", "Bank", "id", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "init_literal", "Dev", "id", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "init_literal", "OtherOps", "id", "USAGE"));
+ ASSERT_TRUE(field_edge_exists(s, project, "init_array", "OtherOps", "id", "USAGE"));
+ ASSERT_FALSE(field_edge_exists(s, project, "init_array", "Dev", "id", "USAGE"));
+ return 0;
+ }
+
+ TEST(pipeline_c_member_access_binds_field_by_object_type) {
+ /* `x.f` / `x->f` handed only the member name `f` to the short-name
+ * registry, which returned whichever Field was called `f`: 9,150 USAGE
+ * and 2,810 WRITES edges onto Fields on this repository, 3,976 of the
+ * USAGE edges onto a name several structs share. Sequential-path twin. */
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_c_field_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_c_member_field_fixture(tmp, 0);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/c_field.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+ int rc = assert_c_member_fields_bind_by_type(s, project);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ if (rc != 0) {
+ return rc;
+ }
+ PASS();
+ }
+
+ TEST(pipeline_c_member_access_binds_field_by_object_type_parallel) {
+ /* Parallel twin: resolve_file_usages / resolve_file_rw are independent
+ * resolvers and must take the same typed join (#1928's lesson). */
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_c_fieldp_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_c_member_field_fixture(tmp, 52);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/c_fieldp.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+ int rc = assert_c_member_fields_bind_by_type(s, project);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ if (rc != 0) {
+ return rc;
+ }
+ PASS();
+ }
+
+ /* Count nodes with the given exact name in the project (e.g. a Route path). */
+ static int count_nodes_named(cbm_store_t *s, const char *project, const char *name) {
+ cbm_node_t *ns = NULL;
+ int n = 0;
+ cbm_store_find_nodes_by_name(s, project, name, &ns, &n);
+ if (ns) {
+ cbm_store_free_nodes(ns, n);
+ }
+ return n;
+ }
+
+ /* Parallel-resolver regression for the TS/JS receiver guard (>= 50 files forces
+ * pass_parallel.c's resolve_file_calls). The guard must not drop a weak member
+ * match before the service classification runs — it suppresses ONLY the plain
+ * CALLS fall-through, so every service edge (HTTP_CALLS via the #523 callee
+ * bypass or emit_service_edge's unconditional detect_url_in_args, Route via the
+ * ROUTE_REG fall-through, …) is emitted exactly as on main. These callees are
+ * classified by main's verb-suffix + URL-arg heuristic, NOT by an HTTP library
+ * name in the callee — a duplicated predicate keyed on the resolved QN lost them
+ * (axios.get, api.patch on a renamed-axios instance, supertest request(app).get).
+ * The regex false edge must stay suppressed in parallel too. CBM_WORKERS forces
+ * >1 worker so the parallel path is taken regardless of the host core count. */
+ /* #1355: padding count for write_external_import_shadow_fixture, deliberately
+ * well past MIN_FILES_FOR_PARALLEL (=50, a private #define in
+ * src/pipeline/pipeline.c — not exposed to tests, so this cannot be a
+ * static_assert against it) rather than sitting right at the threshold. The
+ * margin, not the exact value, is what the test depends on: a modest bump to
+ * the real threshold must not silently drop this fixture back onto the
+ * sequential-only path and leave the parallel resolver unexercised. Same
+ * pattern as ET_PARALLEL_PAD / CP_PARALLEL_PAD in test_edge_types_probe.c /
+ * test_convergence_probe.c. */
+ enum { EXTERNAL_IMPORT_SHADOW_PARALLEL_PAD = 64 };
+
+ /* #1355: write the shared external-import-shadow fixture into `dir`.
+ * `pad_files` filler modules push the run over MIN_FILES_FOR_PARALLEL so the
+ * same tree can be indexed by both resolvers. */
+ static void write_external_import_shadow_fixture(const char *dir, int pad_files) {
+ /* The lone project symbols named eq/sql — ordinary local helpers. */
+ write_temp_file(dir, "src/text-utils.ts",
+ "export function eq(a: string, b: string): boolean {\n"
+ " return a.trim() === b.trim();\n"
+ "}\n"
+ "export function sql(chunk: string): string {\n"
+ " return chunk.replace(/\\s+/g, ' ');\n"
+ "}\n"
+ "export function normalize(s: string): string {\n"
+ " return s.trim().toLowerCase();\n"
+ "}\n");
+ /* `eq` and `sql` come from an external package that is not in the tree, so
+ * the registry falls through to a project-wide same-name guess. These are
+ * the fabricated edges. `normalize` is imported relatively from the SAME
+ * file the guess would have picked — it must survive. */
+ write_temp_file(dir, "src/queries.ts",
+ "import { eq, sql } from 'drizzle-orm';\n"
+ "import { normalize } from './text-utils';\n"
+ "export function buildQuery(id: string): unknown {\n"
+ " return [eq({ id }, id), sql('select 1'), normalize(id)];\n"
+ "}\n");
+ /* No import of `eq` at all: nothing in the caller's source contradicts the
+ * guess, so the pre-existing fallback keeps its edge. */
+ write_temp_file(dir, "src/no-import.ts",
+ "export function callsWithoutImport(a: string, b: string): boolean {\n"
+ " return eq(a, b);\n"
+ "}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/pad_%02d.ts", i);
+ snprintf(body, sizeof(body), "export function shadowPad%02d(): number { return %d; }\n", i,
+ i);
+ write_temp_file(dir, name, body);
+ }
+ }
+
+ /* #1355: assert the guard's whole contract against one indexed store. */
+ static int assert_external_import_shadow_contract(const char *dir, const char *db_name) {
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/%s", dir, db_name);
+ cbm_pipeline_t *p = cbm_pipeline_new(dir, db_path, CBM_MODE_FULL);
+ if (!p) {
+ return 1;
+ }
+ if (cbm_pipeline_run(p) != 0) {
+ cbm_pipeline_free(p);
+ return 2;
+ }
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ if (!s) {
+ cbm_pipeline_free(p);
+ return 3;
+ }
+ int rc = 0;
+ /* (1) the reported bug: an externally-imported name must not bind to the
+ * local homonym (RED before the fix, on both resolvers). */
+ if (cross_file_call_exists(s, project, "buildQuery", "eq")) {
+ rc = 4;
+ }
+ if (rc == 0 && cross_file_call_exists(s, project, "buildQuery", "sql")) {
+ rc = 5;
+ }
+ /* (2) the relative import to the very same file still resolves. */
+ if (rc == 0 && !cross_file_call_exists(s, project, "buildQuery", "normalize")) {
+ rc = 6;
+ }
+ /* (3) a bare call the caller never imports keeps its pre-existing edge. */
+ if (rc == 0 && !cross_file_call_exists(s, project, "callsWithoutImport", "eq")) {
+ rc = 7;
+ }
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ return rc;
+ }
+
+ TEST(pipeline_external_import_shadow_not_bound_to_local_homonym_issue1355) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ext_import_shadow_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ /* Enough files that CBM_WORKERS can take the fused-parallel path; the same
+ * tree is then indexed by each resolver in turn, because the guard lives at
+ * two independent emit sites (pass_calls.c and pass_parallel.c). */
+ write_external_import_shadow_fixture(tmp, EXTERNAL_IMPORT_SHADOW_PARALLEL_PAD);
+
+ /* getenv() returns a pointer into the process environment that must be
+ * treated as read-only; strdup() below only ever reads through it. */
+ const char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ const char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ int sequential = assert_external_import_shadow_contract(tmp, "shadow-sequential.db");
+
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ int parallel = assert_external_import_shadow_contract(tmp, "shadow-parallel.db");
+
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(sequential, 0);
+ ASSERT_EQ(parallel, 0);
+ PASS();
+ }
+
+ /* #1355 / #1732: the same tree, but the bare specifier now names a WORKSPACE
+ * package that the repository itself ships. `main` deliberately points at a
+ * build artifact that is not checked in — the shape every real monorepo has,
+ * and the reason an entry-file lookup cannot answer this question. */
+ static void write_workspace_shadow_fixture(const char *dir, int pad_files) {
+ /* One directory level only: write_temp_file's mkdir is documented as
+ * "simple version, one level", and a deeper path fails silently — which
+ * makes the fixture look healthy while the file never lands. */
+ write_temp_file(dir, "lib/package.json",
+ "{\n \"name\": \"@fixture/lib\",\n \"main\": \"./dist/index.js\"\n}\n");
+ write_temp_file(dir, "lib/index.ts",
+ "export function wsEq(a: string, b: string): boolean {\n"
+ " return a === b;\n"
+ "}\n");
+ write_temp_file(dir, "app/package.json", "{\n \"name\": \"@fixture/app\"\n}\n");
+ /* The lone project symbol named wsSpec — an ordinary local helper that a
+ * project-wide guess would happily bind an external `wsSpec` to. */
+ write_temp_file(dir, "app/spec-helpers.ts",
+ "export function wsSpec(label: string): string {\n"
+ " return label;\n"
+ "}\n");
+ write_temp_file(dir, "app/query.ts",
+ "import { wsEq } from '@fixture/lib';\n"
+ "import { wsSpec } from 'vitest';\n"
+ "export function wsBuild(id: string): unknown {\n"
+ " return [wsEq(id, id), wsSpec('case')];\n"
+ "}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "app/pad_%02d.ts", i);
+ snprintf(body, sizeof(body), "export function wsPad%02d(): number { return %d; }\n", i, i);
+ write_temp_file(dir, name, body);
+ }
+ }
+
+ static int assert_workspace_shadow_contract(const char *dir, const char *db_name) {
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/%s", dir, db_name);
+ cbm_pipeline_t *p = cbm_pipeline_new(dir, db_path, CBM_MODE_FULL);
+ if (!p) {
+ return 1;
+ }
+ if (cbm_pipeline_run(p) != 0) {
+ cbm_pipeline_free(p);
+ return 2;
+ }
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ if (!s) {
+ cbm_pipeline_free(p);
+ return 3;
+ }
+ int rc = 0;
+ /* (1) the workspace sibling: the tree declares @fixture/lib, so the bare
+ * specifier is in-project and the fallback keeps its chance. RED without
+ * the package-map check — this is the 1377-edge class measured on
+ * drizzle-team/drizzle-orm. */
+ if (!cross_file_call_exists(s, project, "wsBuild", "wsEq")) {
+ rc = 4;
+ }
+ /* (2) a genuine third-party package in the very same file is still cut:
+ * the check must not disarm the guard wholesale. */
+ if (rc == 0 && cross_file_call_exists(s, project, "wsBuild", "wsSpec")) {
+ rc = 5;
+ }
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ return rc;
+ }
+
+ TEST(pipeline_external_import_shadow_keeps_workspace_sibling_issue1355) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ws_import_shadow_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_workspace_shadow_fixture(tmp, EXTERNAL_IMPORT_SHADOW_PARALLEL_PAD);
+
+ const char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ const char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ int sequential = assert_workspace_shadow_contract(tmp, "ws-sequential.db");
+
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ int parallel = assert_workspace_shadow_contract(tmp, "ws-parallel.db");
+
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(sequential, 0);
+ ASSERT_EQ(parallel, 0);
+ PASS();
+ }
+
+ /* #1355: the same tree once more, in a package-path language. A Kotlin/Java
+ * specifier is a dotted package path whether the package is the project's own
+ * or a dependency, so specifier shape decides nothing and the package map only
+ * knows manifest artifact names. The tree's own `package` declarations are the
+ * evidence, and the pipeline already collects them (the namespace map the
+ * import passes build). `assertEquals` is imported twice — from the project's
+ * package and from kotlin.test — exactly as JetBrains/Exposed writes it, which
+ * is what leaves the import map without a key and hands the call to the
+ * project-wide guess. */
+ static void write_declared_package_shadow_fixture(const char *dir, int pad_files) {
+ /* One directory level only — write_temp_file's mkdir does not recurse, and
+ * a deeper path fails silently. The package path lives in the `package`
+ * declaration, not in the directory layout, which is the whole point. */
+ write_temp_file(dir, "util/Assert.kt",
+ "package com.example.util\n"
+ "\n"
+ "fun pkgEq(a: String, b: String): Boolean {\n"
+ " return a == b\n"
+ "}\n");
+ /* The lone project symbol named pkgSpec, in a third package so the guess
+ * that reaches it is a project-wide one and not a same-module hit. */
+ write_temp_file(dir, "spec/SpecHelpers.kt",
+ "package com.example.spec\n"
+ "\n"
+ "fun pkgSpec(label: String): Boolean {\n"
+ " return label.isNotEmpty()\n"
+ "}\n");
+ write_temp_file(dir, "app/Query.kt",
+ "package com.example.app\n"
+ "\n"
+ "import com.example.util.pkgEq\n"
+ "import kotlin.test.pkgEq\n"
+ "import kotlin.test.pkgSpec\n"
+ "import org.junit.pkgSpec\n"
+ "\n"
+ "fun pkgBuild(id: String): Boolean {\n"
+ " return pkgEq(id, id) && pkgSpec(id)\n"
+ "}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "app/Pad%02d.kt", i);
+ snprintf(body, sizeof(body),
+ "package com.example.app\n\nfun pkgPad%02d(): Int {\n return %d\n}\n", i, i);
+ write_temp_file(dir, name, body);
+ }
+ }
+
+ static int assert_declared_package_shadow_contract(const char *dir, const char *db_name) {
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/%s", dir, db_name);
+ cbm_pipeline_t *p = cbm_pipeline_new(dir, db_path, CBM_MODE_FULL);
+ if (!p) {
+ return 1;
+ }
+ if (cbm_pipeline_run(p) != 0) {
+ cbm_pipeline_free(p);
+ return 2;
+ }
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ if (!s) {
+ cbm_pipeline_free(p);
+ return 3;
+ }
+ int rc = 0;
+ /* The package the tree declares: `com.example.util` is in-project, so the
+ * call keeps its edge. RED without the declared-package check — this is the
+ * 426-edge class measured on JetBrains/Exposed.
+ *
+ * The matching negative — an undeclared package is still cut — is asserted
+ * where it can be reached on BOTH resolvers: directly on the predicate in
+ * test_registry.c (external_import_shadow_declared_package_kept, including
+ * `java.net.URL`), and end-to-end in the route fixture below. The
+ * sequential resolver builds its own import map straight from the
+ * extraction records, without the ambiguity check its parallel twin
+ * applies, so a doubly-imported Kotlin name resolves by `import_map` there
+ * and never reaches this guard at all — asserting the negative here would
+ * assert that quirk, not this contract. */
+ if (!cross_file_call_exists(s, project, "pkgBuild", "pkgEq")) {
+ rc = 4;
+ }
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ return rc;
+ }
+
+ TEST(pipeline_external_import_shadow_keeps_declared_package_issue1355) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_pkg_import_shadow_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_declared_package_shadow_fixture(tmp, EXTERNAL_IMPORT_SHADOW_PARALLEL_PAD);
+
+ const char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ const char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ int sequential = assert_declared_package_shadow_contract(tmp, "pkg-sequential.db");
+
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ int parallel = assert_declared_package_shadow_contract(tmp, "pkg-parallel.db");
+
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(sequential, 0);
+ ASSERT_EQ(parallel, 0);
+ PASS();
+ }
+
+ /* #1355: the guard must suppress ONLY the plain-CALLS fall-through, never the
+ * route/HTTP/CONFIG classification that runs inside the emitters. A bare call
+ * bound by a package import is exactly the shape a route registration takes
+ * when the router is a dependency, and dropping it before classification costs
+ * the Route node and every HANDLES edge downstream of it. Same reasoning, and
+ * the same drop_plain_call seam, as the #592/#606 member guard. */
+ static void write_route_shadow_fixture(const char *dir, int pad_files) {
+ /* The project symbols the guess would bind to. The file name puts "express"
+ * in their qualified names, which is what makes the resolved QN classify as
+ * a route registration — the same substring match main uses on real trees. */
+ write_temp_file(dir, "app/express-routes.ts",
+ "export function regGet(path: string, handler: unknown): string {\n"
+ " return path;\n"
+ "}\n"
+ "export function regSpec(label: string): string {\n"
+ " return label;\n"
+ "}\n");
+ /* Both names come from a package outside the tree. `regGet` carries a
+ * path-shaped first argument, so it is a route registration; `regSpec` is
+ * an ordinary fabricated edge and must still go. */
+ write_temp_file(dir, "app/server.ts",
+ "import { regGet, regSpec } from 'vendor-router';\n"
+ "export function boot(): string {\n"
+ " return regGet('/orders', () => 'ok') + regSpec('case');\n"
+ "}\n");
+ for (int i = 0; i < pad_files; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "app/pad_%02d.ts", i);
+ snprintf(body, sizeof(body), "export function routePad%02d(): number { return %d; }\n", i,
+ i);
+ write_temp_file(dir, name, body);
+ }
+ }
+
+ static int assert_route_shadow_contract(const char *dir, const char *db_name) {
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/%s", dir, db_name);
+ cbm_pipeline_t *p = cbm_pipeline_new(dir, db_path, CBM_MODE_FULL);
+ if (!p) {
+ return 1;
+ }
+ if (cbm_pipeline_run(p) != 0) {
+ cbm_pipeline_free(p);
+ return 2;
+ }
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ if (!s) {
+ cbm_pipeline_free(p);
+ return 3;
+ }
+ int rc = 0;
+ /* (1) the Route node survives the guard. RED when the guard returns before
+ * the emitter: main mints __route__ANY__/orders here and the published
+ * guard lost it, together with every HANDLES edge that hangs off it. */
+ if (count_nodes_named(s, project, "/orders") < 1) {
+ rc = 4;
+ }
+ /* (2) the fabricated plain-CALLS edge in the same file is still removed, so
+ * (1) cannot pass by the guard having been disarmed. */
+ if (rc == 0 && cross_file_call_exists(s, project, "boot", "regSpec")) {
+ rc = 5;
+ }
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ return rc;
+ }
+
+ TEST(pipeline_external_import_shadow_keeps_route_registration_issue1355) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_route_import_shadow_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_route_shadow_fixture(tmp, EXTERNAL_IMPORT_SHADOW_PARALLEL_PAD);
+
+ const char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ const char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ int sequential = assert_route_shadow_contract(tmp, "route-sequential.db");
+
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ int parallel = assert_route_shadow_contract(tmp, "route-parallel.db");
+
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(sequential, 0);
+ ASSERT_EQ(parallel, 0);
+ PASS();
+ }
+
+ TEST(pipeline_tsjs_receiver_parallel_keeps_service_edges) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_tsjs_par_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ /* The lone project symbols named get()/patch()/test() — weak short-name
+ * targets the registry mis-binds the member calls below to. */
+ write_temp_file(tmp, "src/thing.ts",
+ "export class ApiThing {\n"
+ " get(): number {\n"
+ " return 1;\n"
+ " }\n"
+ " patch(): number {\n"
+ " return 2;\n"
+ " }\n"
+ " load(): number {\n"
+ " return 3;\n"
+ " }\n"
+ "}\n"
+ "export class Other {\n"
+ " test(): boolean {\n"
+ " return true;\n"
+ " }\n"
+ "}\n");
+ /* Untyped axios: the HTTP signal is in the callee name, not the resolved QN
+ * (the registry mis-binds "get" to ApiThing.get). Must yield HTTP_CALLS. */
+ write_temp_file(tmp, "src/http.ts",
+ "export function callApi() {\n"
+ " return axios.get('/api/orders');\n"
+ "}\n");
+ /* Renamed axios instance `api`: no HTTP lib id in the callee — classified by
+ * the .patch verb suffix + URL arg. Must yield HTTP_CALLS (was lost when the
+ * exemption keyed on the resolved QN only). */
+ write_temp_file(tmp, "src/http2.ts",
+ "export function callPatch(): unknown {\n"
+ " return api.patch('/plans/:id', {});\n"
+ "}\n");
+ /* Supertest-style chained receiver `request(app).get('/y')` — untyped, verb
+ * suffix + URL arg. */
+ write_temp_file(tmp, "src/supertest.ts",
+ "export function callSup(app: unknown): unknown {\n"
+ " return request(app).get('/y');\n"
+ "}\n");
+ /* `dev.load('/data')`: `.load` is NOT a route suffix and `dev` is not an HTTP
+ * lib, so main classifies it via the unconditional detect_url_in_args (URL
+ * arg) -> HTTP_CALLS, while the weak plain match to ApiThing.load is the false
+ * edge that must be suppressed. This is exactly the detect_url_in_args path
+ * the previous (predicate-duplicating) guard skipped by dropping the call
+ * before emit_service_edge ran — the class of ~399 HTTP_CALLS it lost. */
+ write_temp_file(tmp, "src/load.ts",
+ "export function callLoad(dev: unknown): unknown {\n"
+ " return dev.load('/api/data');\n"
+ "}\n");
+ /* Route registration by callee suffix + a '/'-path arg. Must yield a Route. */
+ write_temp_file(tmp, "src/routes.ts",
+ "function handler() {}\n"
+ "export function reg(router: any) {\n"
+ " router.get('/users', handler);\n"
+ "}\n");
+ /* Regex receiver: the false edge that must stay suppressed in parallel too. */
+ write_temp_file(tmp, "src/re.ts",
+ "const re = /^[a-z]+$/;\n"
+ "export function checkFormat(s: string): boolean {\n"
+ " return re.test(s);\n"
+ "}\n");
+ /* Pad past MIN_FILES_FOR_PARALLEL (50) so the parallel resolver runs. */
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/filler%d.ts", i);
+ snprintf(body, sizeof(body), "export function filler%d(): number {\n return %d;\n}\n", i,
+ i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1); /* force parallel regardless of host cores */
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/tsjs_par.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* (1) Genuine HTTP_CALLS survive under the guard:
+ * - axios.get('/api/orders') -> 1 edge, typed GET (recognized lib #523
+ * callee bypass; no method-less arg-URL twin), and
+ * - dev.load('/api/data') -> 1 edge via detect_url_in_args, which runs
+ * after emit_service_edge's branch even when the plain fall-through is
+ * suppressed.
+ * dev.load is the class the predicate-duplicating guard lost: `.load` is not
+ * a route suffix and `dev` is not an HTTP lib, so it was dropped before
+ * emit_service_edge ran (RED on that guard: only axios's edge). */
+ ASSERT_EQ(http_calls_to_route(s, project, "callApi", "__route__GET__"), 1);
+ ASSERT_EQ(http_calls_to_route(s, project, "callApi", "__route__"), 1);
+ ASSERT_EQ(http_calls_to_route(s, project, "callLoad", "__route__ANY__"), 1);
+ ASSERT_EQ(cbm_store_count_edges_by_type(s, project, "HTTP_CALLS"), 2);
+ /* (2) The verb-suffix + route-path member calls keep their route
+ * registrations (edge type CALLS -> a Route node named by the path). These
+ * classify as route_registration on main, NOT HTTP_CALLS — Option A preserves
+ * that by construction. Assert the three Route paths survive:
+ * api.patch('/plans/:id'), request(app).get('/y'), router.get('/users'). */
+ ASSERT_GTE(count_nodes_named(s, project, "/plans/:id"), 1);
+ ASSERT_GTE(count_nodes_named(s, project, "/y"), 1);
+ ASSERT_GTE(count_nodes_named(s, project, "/users"), 1);
+ /* (3) The false plain-CALLS edges are suppressed in parallel: the regex
+ * receiver and the dev.load weak match to ApiThing.load. */
+ ASSERT_GTE(fixture_node_count(s, project, "src/re.ts", "checkFormat", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "src/thing.ts", "test", "Method"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "src/load.ts", "callLoad", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "src/thing.ts", "load", "Method"), 1);
+ ASSERT_FALSE(cross_file_call_exists(s, project, "checkFormat", "test"));
+ ASSERT_FALSE(cross_file_call_exists(s, project, "callLoad", "load"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Route-registration CALLS edges (via=route_registration) out of the function
+ * `source_name`. */
+ static int route_registrations_from(cbm_store_t *s, const char *project, const char *source_name) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_type(s, project, "CALLS", &edges, &edge_count) != CBM_STORE_OK) {
+ return -1;
+ }
+ int matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t source = {0};
+ int source_ok = cbm_store_find_node_by_id(s, edges[i].source_id, &source) == CBM_STORE_OK;
+ if (source_ok && source.name && strcmp(source.name, source_name) == 0 &&
+ edges[i].properties_json &&
+ strstr(edges[i].properties_json, "\"via\":\"route_registration\"")) {
+ matches++;
+ }
+ cbm_node_free_fields(&source);
+ }
+ if (edges) {
+ cbm_store_free_edges(edges, edge_count);
+ }
+ return matches;
+ }
+
+ /* `import Axios from "axios"` -- the default-import binding capitalized, a
+ * common convention -- must classify `Axios.get/post/delete(url)` as HTTP
+ * client calls exactly like `axios.*`. The library table matched only the
+ * lowercase id, so the calls fell through to the `.get`/`.post` route-suffix
+ * fallback and became route REGISTRATIONS: on
+ * microsoft/Game-Control-Puzzle-Event-Administration-Tools all 69 client
+ * calls masqueraded as server Routes. A real Express registration in the same
+ * project stays a registration. `fillers` > 0 forces the parallel resolver,
+ * 0 keeps the sequential one; both classify through the same table. */
+ static int capitalized_axios_case(int fillers) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_axios_cap_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "src/service.ts",
+ "import Axios from \"axios\";\n"
+ "export function getSettings(eventId: string) {\n"
+ " return Axios.get(`/api/admin/events/${eventId}/settings`);\n"
+ "}\n"
+ "export function addUser(eventId: string, participant: unknown) {\n"
+ " return Axios.post(`/api/admin/users/${eventId}`, participant);\n"
+ "}\n"
+ "export function removeUser(id: string) {\n"
+ " return Axios.delete(`/api/admin/users/${id}`);\n"
+ "}\n");
+ write_temp_file(tmp, "src/server.ts",
+ "function listUsers(req: unknown, res: unknown) {}\n"
+ "export function mount(router: any) {\n"
+ " router.get('/api/admin/users', listUsers);\n"
+ "}\n");
+ for (int i = 0; i < fillers; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/filler%d.ts", i);
+ snprintf(body, sizeof(body), "export function filler%d(): number {\n return %d;\n}\n", i,
+ i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/axios_cap.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ static const struct {
+ const char *caller;
+ const char *typed_route;
+ } client[] = {{"getSettings", "__route__GET__"},
+ {"addUser", "__route__POST__"},
+ {"removeUser", "__route__DELETE__"}};
+ for (size_t i = 0; i < sizeof(client) / sizeof(client[0]); i++) {
+ ASSERT_EQ(route_registrations_from(s, project, client[i].caller), 0);
+ ASSERT_EQ(http_calls_to_route(s, project, client[i].caller, client[i].typed_route), 1);
+ }
+ /* Control: the server-side registration is untouched. */
+ ASSERT_EQ(route_registrations_from(s, project, "mount"), 1);
+ ASSERT_EQ(http_calls_to_route(s, project, "mount", "__route__"), 0);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_capitalized_axios_import_is_http_client) {
+ return capitalized_axios_case(52);
+ }
+
+ TEST(pipeline_capitalized_axios_import_is_http_client_sequential) {
+ return capitalized_axios_case(0);
+ }
+
+ /* FastAPI/Starlette WebSocket route registration (distilled from #1245). The
+ * route-registration suffix table knew `.add_api_websocket_route` but not the
+ * decorator forms `.websocket` / `.websocket_route`, so a WebSocket endpoint
+ * registered via `@router.websocket('/ws')` produced no Route node at all —
+ * the endpoint was invisible to the graph. `@app.get('/health')` is the
+ * positive control (already a route suffix). Fewer than 50 files exercises
+ * pass_calls.c; the same suffix table drives the parallel resolver. */
+ TEST(pipeline_python_websocket_decorators_register_routes) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_py_ws_routes_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "app.py",
+ "from fastapi import APIRouter, FastAPI, WebSocket\n\n"
+ "app = FastAPI()\n"
+ "router = APIRouter()\n\n"
+ "@app.get('/health')\n"
+ "def health():\n"
+ " return {'ok': True}\n\n"
+ "@router.websocket('/ws')\n"
+ "async def ws_endpoint(websocket: WebSocket):\n"
+ " await websocket.accept()\n\n"
+ "@app.websocket_route('/events')\n"
+ "async def events_endpoint(websocket: WebSocket):\n"
+ " await websocket.accept()\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/py_ws.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* Positive control: the HTTP decorator mints its Route node. */
+ ASSERT_GTE(count_nodes_named(s, project, "/health"), 1);
+ /* The two WebSocket decorator forms must mint Route nodes too. */
+ ASSERT_GTE(count_nodes_named(s, project, "/ws"), 1);
+ ASSERT_GTE(count_nodes_named(s, project, "/events"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Python bare-call local-binding suppression, sequential path. The bare-call
+ * counterpart of the receiver guard above: `run` is a PARAMETER, so `run()`
+ * cannot be the module-level `run` and must not bind SatoriLive.run.
+ *
+ * The positive control is deliberately a CROSS-FILE bare call with no import,
+ * so it resolves by a weak short-name strategy — one this guard could have
+ * killed. Asserting a same-file (same_module) edge instead would prove nothing,
+ * because no guard in this codebase touches same_module for any input.
+ * Fewer than 50 files exercises pass_calls.c. */
+ TEST(pipeline_python_bare_local_binding_suppresses_weak_edge) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_py_bare_seq_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "live.py",
+ "class SatoriLive:\n"
+ " def run(self):\n"
+ " return 1\n");
+ write_temp_file(tmp, "helpers.py",
+ "def compute_widget_total():\n"
+ " return 7\n");
+ write_temp_file(tmp, "gate.py",
+ "def _run_with_heavy_slot(run):\n"
+ " return run()\n"
+ "\n"
+ "def uses_free_function():\n"
+ " return compute_widget_total()\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/py_bare.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* NEGATIVE: the callee is shadowed by a parameter. */
+ ASSERT_FALSE(cross_file_call_exists(s, project, "_run_with_heavy_slot", "run"));
+ /* POSITIVE: an unshadowed cross-file bare call survives. */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "uses_free_function", "compute_widget_total"));
+ /* Tripwire: a run that emitted no edges at all would satisfy the negative
+ * assertion vacuously. */
+ ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "CALLS"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Parallel Python regression for #1276. The field-type heuristic capitalizes
+ * the receiver token and previously promoted accelerator.print() to
+ * MockAccelerator.print at 0.85; ordinary suffix matching also selected one
+ * arbitrary backward()/step() implementation. All are unresolved-receiver
+ * calls and must remain absent, while the import-bound call and the bare local
+ * call remain — the same both-directions pin as the sequential test above.
+ * >= 50 files forces pass_parallel.c and try_field_type_hint(), so this is also
+ * the guard against a sequential/parallel divergence. */
+ TEST(pipeline_python_receiver_parallel_suppresses_weak_method_edges) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_python_par_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "targets.py",
+ "class MockAccelerator:\n"
+ " def print(self, value):\n"
+ " return value\n"
+ "\n"
+ "class OtherPrinter:\n"
+ " def print(self, value):\n"
+ " return value\n"
+ "\n"
+ "class FlashAttentionFunction:\n"
+ " def backward(self, loss):\n"
+ " return loss\n"
+ "\n"
+ "class OtherBackward:\n"
+ " def backward(self, loss):\n"
+ " return loss\n"
+ "\n"
+ "class EulerScheduler:\n"
+ " def step(self):\n"
+ " return 1\n"
+ "\n"
+ "class OtherScheduler:\n"
+ " def step(self):\n"
+ " return 1\n");
+ write_temp_file(tmp, "pkg/__init__.py", "from .helper import compute\n");
+ write_temp_file(tmp, "pkg/helper.py",
+ "def compute(value):\n"
+ " return value * 2\n");
+ write_temp_file(tmp, "caller.py",
+ "from pkg import helper\n"
+ "\n"
+ "def local_helper():\n"
+ " return 1\n"
+ "\n"
+ "def train(accelerator, trainer):\n"
+ " accelerator.print('hello')\n"
+ " accelerator.backward(1)\n"
+ " trainer.lr_scheduler.step()\n"
+ " helper.compute(42)\n"
+ " return local_helper()\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "filler%d.py", i);
+ snprintf(body, sizeof(body), "def filler%d():\n return %d\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/python_par.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* NEGATIVE: every receiver here is a parameter or an attribute of one. */
+ ASSERT_GTE(fixture_node_count(s, project, "caller.py", "train", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "targets.py", "print", "Method"), 2);
+ ASSERT_GTE(fixture_node_count(s, project, "targets.py", "backward", "Method"), 2);
+ ASSERT_GTE(fixture_node_count(s, project, "targets.py", "step", "Method"), 2);
+ ASSERT_FALSE(cross_file_call_exists(s, project, "train", "print"));
+ ASSERT_FALSE(cross_file_call_exists(s, project, "train", "backward"));
+ ASSERT_FALSE(cross_file_call_exists(s, project, "train", "step"));
+ /* POSITIVE: import-bound and bare local calls survive the parallel path too. */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "train", "compute"));
+ ASSERT_TRUE(cross_file_call_exists(s, project, "train", "local_helper"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Parallel counterpart. >= 50 files forces pass_parallel.c, which is wired with
+ * the same gate: a guard wired on only one resolver produces an edge on the
+ * sequential path and not the parallel one, breaking MT determinism. #1386
+ * wired both and tested only the sequential path, and the `parallel` suite is
+ * exactly what catches that. Same both-directions pin as the sequential test. */
+ TEST(pipeline_python_bare_local_binding_parallel_suppresses_weak_edge) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_py_bare_par_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "live.py",
+ "class SatoriLive:\n"
+ " def run(self):\n"
+ " return 1\n"
+ "\n"
+ "class BatchJob:\n"
+ " def execute(self):\n"
+ " return 2\n");
+ write_temp_file(tmp, "helpers.py",
+ "def compute_widget_total():\n"
+ " return 7\n");
+ write_temp_file(tmp, "gate.py",
+ "def _run_with_heavy_slot(run, execute):\n"
+ " run()\n"
+ " return execute()\n"
+ "\n"
+ "def uses_free_function():\n"
+ " return compute_widget_total()\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "filler%d.py", i);
+ snprintf(body, sizeof(body), "def filler%d():\n return %d\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/py_bare_par.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* NEGATIVE: both callees are shadowed by parameters. */
+ ASSERT_FALSE(cross_file_call_exists(s, project, "_run_with_heavy_slot", "run"));
+ ASSERT_FALSE(cross_file_call_exists(s, project, "_run_with_heavy_slot", "execute"));
+ /* POSITIVE: the unshadowed cross-file bare call survives the parallel path. */
+ ASSERT_TRUE(cross_file_call_exists(s, project, "uses_free_function", "compute_widget_total"));
+ /* Tripwire against a vacuous pass. */
+ ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "CALLS"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* CALLS edges from a caller to a callee, both matched by QN suffix (start each
+ * suffix with '.' to anchor it at a segment boundary), any strategy. *guessed
+ * is set when a matching edge came from a name guess rather than an import
+ * binding or the LSP. */
+ static int py_calls_between(cbm_store_t *s, const char *project, const char *caller_suffix,
+ const char *callee_suffix, bool *guessed) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ cbm_store_find_edges_by_type(s, project, "CALLS", &edges, &edge_count);
+ int hits = 0;
+ size_t cs = strlen(caller_suffix);
+ size_t ts = strlen(callee_suffix);
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t src = {0};
+ cbm_node_t tgt = {0};
+ if (cbm_store_find_node_by_id(s, edges[i].source_id, &src) == CBM_STORE_OK &&
+ cbm_store_find_node_by_id(s, edges[i].target_id, &tgt) == CBM_STORE_OK) {
+ size_t sl = strlen(src.qualified_name);
+ size_t tl = strlen(tgt.qualified_name);
+ if (sl >= cs && tl >= ts && strcmp(src.qualified_name + sl - cs, caller_suffix) == 0 &&
+ strcmp(tgt.qualified_name + tl - ts, callee_suffix) == 0) {
+ hits++;
+ const char *pj = edges[i].properties_json ? edges[i].properties_json : "";
+ if (guessed && !strstr(pj, "\"import_map\"") && !strstr(pj, "\"lsp")) {
+ *guessed = true;
+ }
+ }
+ }
+ cbm_node_free_fields(&src);
+ cbm_node_free_fields(&tgt);
+ }
+ if (edges)
+ cbm_store_free_edges(edges, edge_count);
+ return hits;
+ }
+
+ /* Pin CBM_WORKERS=4 for a padded (> 50 files) parallel run; restore after. */
+ typedef struct {
+ char *saved;
+ bool had;
+ int rc;
+ } py_workers_pin_t;
+
+ static py_workers_pin_t py_pin_workers(bool parallel) {
+ py_workers_pin_t pin = {0};
+ if (!parallel) {
+ return pin;
+ }
+ const char *old = getenv("CBM_WORKERS");
+ pin.had = old != NULL;
+ pin.saved = old ? strdup(old) : NULL;
+ pin.rc = (old && !pin.saved) ? -1 : cbm_setenv("CBM_WORKERS", "4", 1);
+ return pin;
+ }
+
+ static int py_unpin_workers(bool parallel, py_workers_pin_t *pin) {
+ if (!parallel) {
+ return 0;
+ }
+ int rc = pin->had ? cbm_setenv("CBM_WORKERS", pin->saved, 1) : cbm_unsetenv("CBM_WORKERS");
+ free(pin->saved);
+ pin->saved = NULL;
+ return rc;
+ }
+
+ static void py_write_padding(const char *tmp, const char *stem, bool parallel) {
+ for (int i = 0; parallel && i < 52; i++) {
+ char name[64];
+ char body[96];
+ snprintf(name, sizeof(name), "%s%d.py", stem, i);
+ snprintf(body, sizeof(body), "def %s%d():\n return %d\n", stem, i, i);
+ write_temp_file(tmp, name, body);
+ }
+ }
+
+ /* `from . import x`, `from .. import x` and `from . import x as y` name the
+ * importing file's own (or parent) package. The extractor recorded them one
+ * package too high ("..x"), so the import fell to pass_pkgmap's symbol-name
+ * guess -- the lexicographically first same-named project definition -- and
+ * every call became a confident edge into comp.aaa, through the import map and
+ * the Python LSP's alias binding alike (home-assistant: 7,175 call pairs).
+ * Both resolvers: <= 50 files sequential, padded > 50 parallel. */
+ static int check_python_package_relative_imports(bool parallel) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_py_relpkg_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "comp/__init__.py", "");
+ write_temp_file(tmp, "comp/aaa/__init__.py",
+ "def async_register(hass):\n"
+ " return 1\n\n"
+ "def local_fn():\n"
+ " return 2\n");
+ write_temp_file(tmp, "comp/web/__init__.py",
+ "def async_register(hass):\n"
+ " return 3\n");
+ write_temp_file(tmp, "comp/web/trigger.py",
+ "from . import async_register\n\n"
+ "def attach(hass):\n"
+ " return async_register(hass)\n");
+ write_temp_file(tmp, "comp/web/sub/__init__.py",
+ "def local_fn():\n"
+ " return 4\n");
+ write_temp_file(tmp, "comp/web/sub/mod.py",
+ "from .. import async_register\n"
+ "from . import local_fn as lf\n\n"
+ "def deep(hass):\n"
+ " async_register(hass)\n"
+ " return lf()\n");
+ py_write_padding(tmp, "relpad", parallel);
+
+ py_workers_pin_t pin = py_pin_workers(parallel);
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/relpkg.db", tmp);
+ cbm_pipeline_t *p = pin.rc == 0 ? cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL) : NULL;
+ int run_rc = p ? cbm_pipeline_run(p) : -1;
+ cbm_store_t *s = run_rc == 0 ? cbm_store_open_path(db_path) : NULL;
+ bool opened = s != NULL;
+ bool guessed = false;
+ int own = -1, own_decoy = -1, parent = -1, parent_decoy = -1, alias = -1, alias_decoy = -1;
+ if (s) {
+ const char *project = cbm_pipeline_project_name(p);
+ own = py_calls_between(s, project, ".comp.web.trigger.attach", ".comp.web.async_register",
+ &guessed);
+ own_decoy = py_calls_between(s, project, ".comp.web.trigger.attach",
+ ".comp.aaa.async_register", NULL);
+ parent = py_calls_between(s, project, ".comp.web.sub.mod.deep", ".comp.web.async_register",
+ &guessed);
+ parent_decoy = py_calls_between(s, project, ".comp.web.sub.mod.deep",
+ ".comp.aaa.async_register", NULL);
+ alias = py_calls_between(s, project, ".comp.web.sub.mod.deep", ".comp.web.sub.local_fn",
+ &guessed);
+ alias_decoy =
+ py_calls_between(s, project, ".comp.web.sub.mod.deep", ".comp.aaa.local_fn", NULL);
+ cbm_store_close(s);
+ }
+ cbm_pipeline_free(p);
+ int unpin_rc = py_unpin_workers(parallel, &pin);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(pin.rc, 0);
+ ASSERT_EQ(unpin_rc, 0);
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_TRUE(opened);
+ ASSERT_EQ(own, 1); /* from . import x: the file's own package */
+ ASSERT_EQ(own_decoy, 0); /* never the lexicographically first namesake */
+ ASSERT_EQ(parent, 1); /* from .. import x: the parent package */
+ ASSERT_EQ(parent_decoy, 0);
+ ASSERT_EQ(alias, 1); /* from . import x as y */
+ ASSERT_EQ(alias_decoy, 0);
+ ASSERT_FALSE(guessed); /* bound by the import, not by a name guess */
+ PASS();
+ }
+
+ TEST(pipeline_python_package_relative_imports) {
+ return check_python_package_relative_imports(false);
+ }
+
+ TEST(pipeline_python_package_relative_imports_parallel) {
+ return check_python_package_relative_imports(true);
+ }
+
+ /* #1237: a plain `from pkg.db import get_row_or_none` and bare calls resolve to
+ * the imported module-level def (function and method callers, plus the
+ * same-file caller), never to a same-named def elsewhere that a name guess
+ * would rank first (legacy.compat), and a re-index that only ADDS an unrelated
+ * file (the reporter's watcher re-index after writing benchmark scripts into the
+ * indexed tree) keeps exactly the same CALLS. Main already resolved this shape
+ * when the guard landed: it pins the shape and has no RED on revert. */
+ static int check_python_from_import_bare_call_issue1237(bool parallel) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_py_1237_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "pkg/__init__.py", "");
+ write_temp_file(tmp, "pkg/db.py",
+ "def get_row_or_none(model, **filters):\n"
+ " return None\n\n"
+ "def other_helper():\n"
+ " return get_row_or_none(1, id=2)\n");
+ write_temp_file(tmp, "pkg/views.py",
+ "from pkg.db import get_row_or_none\n\n"
+ "def show(pk):\n"
+ " return get_row_or_none(object, id=pk)\n\n"
+ "class Detail:\n"
+ " def get(self, pk):\n"
+ " return get_row_or_none(object, pk=pk)\n");
+ write_temp_file(tmp, "legacy/__init__.py", "");
+ write_temp_file(tmp, "legacy/compat.py",
+ "def get_row_or_none(model):\n"
+ " return model\n");
+ py_write_padding(tmp, "rowpad", parallel);
+
+ py_workers_pin_t pin = py_pin_workers(parallel);
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/rows.db", tmp);
+ int run_rc[2] = {-1, -1};
+ int show[2] = {-1, -1};
+ int method[2] = {-1, -1};
+ int same[2] = {-1, -1};
+ int decoy[2] = {-1, -1};
+ int calls[2] = {-1, -1};
+ bool guessed = false;
+ for (int run = 0; run < 2 && pin.rc == 0; run++) {
+ if (run == 1) {
+ /* Second run on the same db: routes to the incremental re-index. */
+ write_temp_file(tmp, "bench_rows.py", "def bench():\n return 0\n");
+ }
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ run_rc[run] = p ? cbm_pipeline_run(p) : -1;
+ cbm_store_t *s = run_rc[run] == 0 ? cbm_store_open_path(db_path) : NULL;
+ if (s) {
+ const char *project = cbm_pipeline_project_name(p);
+ const char *target = ".pkg.db.get_row_or_none";
+ const char *namesake = ".legacy.compat.get_row_or_none";
+ show[run] = py_calls_between(s, project, ".pkg.views.show", target, &guessed);
+ method[run] = py_calls_between(s, project, ".pkg.views.Detail.get", target, &guessed);
+ same[run] = py_calls_between(s, project, ".pkg.db.other_helper", target, &guessed);
+ decoy[run] = py_calls_between(s, project, ".pkg.views.show", namesake, NULL) +
+ py_calls_between(s, project, ".pkg.views.Detail.get", namesake, NULL);
+ calls[run] = cbm_store_count_edges_by_type(s, project, "CALLS");
+ cbm_store_close(s);
+ }
+ cbm_pipeline_free(p);
+ }
+ int unpin_rc = py_unpin_workers(parallel, &pin);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(pin.rc, 0);
+ ASSERT_EQ(unpin_rc, 0);
+ for (int run = 0; run < 2; run++) {
+ ASSERT_EQ(run_rc[run], 0);
+ ASSERT_EQ(show[run], 1); /* cross-file bare call through a plain from-import */
+ ASSERT_EQ(method[run], 1); /* the same from a method */
+ ASSERT_EQ(same[run], 1); /* same-file bare call */
+ ASSERT_EQ(decoy[run], 0); /* never the namesake a name guess would pick */
+ }
+ ASSERT_EQ(calls[1], calls[0]); /* adding a call-free file moves no CALLS edge */
+ ASSERT_FALSE(guessed);
+ PASS();
+ }
+
+ TEST(pipeline_python_from_import_bare_call_issue1237) {
+ return check_python_from_import_bare_call_issue1237(false);
+ }
+
+ TEST(pipeline_python_from_import_bare_call_issue1237_parallel) {
+ return check_python_from_import_bare_call_issue1237(true);
+ }
+
+ /* Reproduce-first: pass_parallel's fused cross-LSP eligibility currently counts
+ * only parser-backed calls/call references. A Python binary operator has no
+ * parser CBMCall; its __add__ semantic record and carrier are created together
+ * only by the cross resolver. Consequently combine.py looks like it has zero
+ * semantic sites and the fused pass skips it before that carrier can exist.
+ *
+ * `visible()` is deliberately in a different file. Its ordinary method-call
+ * carrier makes THAT file cross-LSP eligible and its lsp_* edge proves that the
+ * Alpha definition, import map, shared registry, and cross resolver are all
+ * healthy. Putting the control call in combine.py would hide the bug by making
+ * the broken file eligible. The 52 fillers plus three fixture files exceed
+ * MIN_FILES_FOR_PARALLEL (50), and CBM_WORKERS=4 forces the production fused
+ * path independent of host core count. */
+ TEST(pipeline_parallel_python_cross_only_dunder_gets_synthetic_carrier) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_py_syn_par_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "alpha.py",
+ "class Alpha:\n"
+ " def __add__(self, other):\n"
+ " return self\n");
+ write_temp_file(tmp, "visible.py",
+ "from .alpha import Alpha\n\n"
+ "def visible(left: Alpha, right: Alpha):\n"
+ " return left.__add__(right)\n");
+ write_temp_file(tmp, "combine.py",
+ "from .alpha import Alpha\n\n"
+ "def combine(left: Alpha, right: Alpha):\n"
+ " return left + right\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "py_pad_%02d.py", i);
+ snprintf(body, sizeof(body), "def py_pad_%02d():\n return %d\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/python_parallel.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ int run_rc = cbm_pipeline_run(p);
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ bool store_opened = s != NULL;
+ bool control_lsp = false;
+ bool combine_to_add = false;
+ if (s) {
+ control_lsp =
+ cross_file_call_has_strategy(s, project, "visible", "__add__", "\"strategy\":\"lsp_");
+ combine_to_add = cross_file_call_exists(s, project, "combine", "__add__");
+ cbm_store_close(s);
+ }
+
+ cbm_pipeline_free(p);
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_TRUE(store_opened);
+ ASSERT_TRUE(control_lsp); /* non-vacuity: cross LSP + target are healthy */
+ ASSERT_TRUE(combine_to_add); /* RED: fused eligibility skips combine.py */
+ PASS();
+ }
+
+ /* Same fused-eligibility hole for Rust built-in macro arguments. The parser
+ * exposes format! but not render() inside its token tree. Per-file LSP already
+ * qualifies every parser-backed site in hidden.rs, so the fused heuristic sees
+ * no remaining work and never runs the cross pass that would discover both the
+ * semantic render target and its exact synthetic carrier.
+ *
+ * The exact same 55-file fixture is indexed once through the sequential path
+ * first. A hidden() -> render CALLS edge there is a strong non-vacuity control:
+ * only the sequential cross-LSP pass can discover both the macro-hidden call
+ * and its synthetic carrier. The parallel run must preserve that result. */
+ TEST(pipeline_parallel_rust_cross_only_macro_hidden_gets_synthetic_carrier) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_rs_syn_par_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "lib.rs", "pub fn render() -> &'static str { \"ok\" }\n");
+ write_temp_file(tmp, "main.rs",
+ "mod lib;\n\n"
+ "pub fn hidden() -> String { format!(\"{}\", lib::render()) }\n");
+ for (int i = 0; i < 53; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "rust_pad_%02d.rs", i);
+ snprintf(body, sizeof(body), "pub fn rust_pad_%02d() -> i32 { %d }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ char seq_db_path[512];
+ snprintf(seq_db_path, sizeof(seq_db_path), "%s/rust_sequential.db", tmp);
+ cbm_pipeline_t *seq = cbm_pipeline_new(tmp, seq_db_path, CBM_MODE_FULL);
+ int seq_run_rc = seq ? cbm_pipeline_run(seq) : -1;
+ const char *seq_project = seq ? cbm_pipeline_project_name(seq) : NULL;
+ cbm_store_t *seq_store = cbm_store_open_path(seq_db_path);
+ bool seq_store_opened = seq_store != NULL;
+ bool seq_hidden_to_render = false;
+ if (seq_store && seq_project) {
+ seq_hidden_to_render = cross_file_call_exists(seq_store, seq_project, "hidden", "render");
+ cbm_store_close(seq_store);
+ }
+ cbm_pipeline_free(seq);
+
+ /* The parallel half must not inherit a caller-level single-thread override,
+ * even when the surrounding test process was launched with one. Restore it
+ * after both halves complete. */
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/rust_parallel.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ int run_rc = cbm_pipeline_run(p);
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ bool store_opened = s != NULL;
+ bool render_target_present = false;
+ bool hidden_to_render = false;
+ if (s) {
+ render_target_present = count_nodes_named(s, project, "render") > 0;
+ hidden_to_render = cross_file_call_exists(s, project, "hidden", "render");
+ cbm_store_close(s);
+ }
+
+ cbm_pipeline_free(p);
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(seq_run_rc, 0);
+ ASSERT_TRUE(seq_store_opened);
+ ASSERT_TRUE(seq_hidden_to_render); /* same fixture is semantically resolvable */
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_TRUE(store_opened);
+ ASSERT_TRUE(render_target_present); /* target is present in the parallel graph */
+ ASSERT_TRUE(hidden_to_render); /* RED: fused eligibility skips hidden.rs */
+ PASS();
+ }
+
+ /* Slash-prefixed call arguments are not necessarily HTTP routes. Keep the
+ * parallel arg-url heuristic from minting Route nodes for filesystem paths or
+ * regex-replacement operands, while preserving a genuine API path. */
+ TEST(pipeline_arg_url_rejects_non_http_slash_arguments) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_arg_url_guard_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "src/args.py",
+ "import requests\n"
+ "TMP = '/tmp/pgv_fuzz.bin'\n"
+ "def run_copy(path):\n"
+ " return path\n"
+ "def write_fixture():\n"
+ " return run_copy(TMP)\n"
+ "def load_api():\n"
+ " return requests.get('/api/data')\n");
+ write_temp_file(tmp, "src/regex.js",
+ "function sink(value) { return value; }\n"
+ "export function sanitize(template) {\n"
+ " sink(/<table/i);\n"
+ " return template.replace('/html/g', '');\n"
+ "}\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/filler%d.ts", i);
+ snprintf(body, sizeof(body), "export function filler%d(): number { return %d; }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/arg_url_guard.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_GTE(fixture_node_count(s, project, "src/args.py", "write_fixture", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "src/args.py", "load_api", "Function"), 1);
+ ASSERT_GTE(fixture_node_count(s, project, "src/regex.js", "sanitize", "Function"), 1);
+ ASSERT_EQ(count_nodes_named(s, project, "/html/g"), 0);
+ ASSERT_EQ(count_nodes_named(s, project, "/<table/i"), 0);
+ ASSERT_EQ(count_nodes_named(s, project, "/tmp/pgv_fuzz.bin"), 0);
+ ASSERT_GTE(count_nodes_named(s, project, "/api/data"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* #2235: an Orval-style generated client passes its URL inside a request
+ * config object to a LOCAL helper -- `http({url: `/api/customers/${id}`,
+ * method: 'GET'})`. The template literal itself already canonicalizes to
+ * "/api/customers/{}"; what was lost is the object wrapper: the arg-url
+ * heuristic only read bare string/template arguments, so the call produced
+ * no HTTP_CALLS edge and cross-repo matching had nothing to join. Parallel
+ * resolver (> 50 files), where the arg-url heuristic lives. A config object
+ * without a `url` key must not mint a route. */
+ TEST(pipeline_ts_config_object_url_http_calls_issue2235) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_i2235_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "src/http.ts",
+ "export const http = <T,>(config: { url: string; method: string }): "
+ "Promise<T> => {\n"
+ " return fetch(config.url, { method: config.method }).then((r) => r.json());\n"
+ "};\n");
+ write_temp_file(
+ tmp, "src/gen/customer-controller.ts",
+ "import { http } from '../http';\n"
+ "export const get1 = (id: string, signal?: AbortSignal) => {\n"
+ " return http<unknown>({url: `/api/customers/${id}`, method: 'GET', signal});\n"
+ "};\n"
+ "export const noUrl = () => {\n"
+ " return http<unknown>({path: '/api/ignored/x', method: 'GET'});\n"
+ "};\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/filler%d.ts", i);
+ snprintf(body, sizeof(body), "export function filler%d(): number { return %d; }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/i2235.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* RED before the fix: the url inside the config object was never read. */
+ ASSERT_EQ(named_edge_count(s, project, "HTTP_CALLS", "get1", "/api/customers/{}"), 1);
+ /* Only the `url` key names the request URL. */
+ ASSERT_EQ(count_nodes_named(s, project, "/api/ignored/x"), 0);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Count HTTP_CALLS-style edges whose url_path property contains `keyword`. */
+ static int count_edges_with_url_path(cbm_store_t *s, const char *project, const char *keyword) {
+ cbm_edge_t *es = NULL;
+ int n = 0;
+ cbm_store_find_edges_by_url_path(s, project, keyword, &es, &n);
+ if (es) {
+ cbm_store_free_edges(es, n);
+ }
+ return n;
+ }
+
+ /* Distilled from PR #1245: detect_url_in_args (parallel resolver, >= 50 files)
+ * runs for EVERY resolved call with no callee gating, so a filesystem path
+ * with a document/log extension passed to a project-defined open/read/write
+ * helper passed normalize_url_arg (second slash, no space) and the route
+ * literal guard, minting a Route node + an HTTP_CALLS edge for a file. The
+ * callees are project functions on purpose: a bare builtin `open(...)` never
+ * resolves to a target and so never reaches emit_service_edge at all. The
+ * first path segments avoid the filesystem-root list (etc/var/tmp/...) so
+ * only the extension guard can reject them. requests.get('/api/items') is
+ * the positive control that must keep its Route + HTTP_CALLS. */
+ TEST(pipeline_arg_url_rejects_document_file_paths) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_arg_url_docs_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "src/files.py",
+ "import requests\n"
+ "def open_file(path):\n"
+ " return path\n"
+ "def read_file(path):\n"
+ " return path\n"
+ "def write_file(path):\n"
+ " return path\n"
+ "def load_docs():\n"
+ " open_file('/new/file.txt')\n"
+ " read_file('/docs/guide.md')\n"
+ " write_file('/data/app.log')\n"
+ " read_file('/reports/summary.pdf')\n"
+ " open_file('/docs/index.rst')\n"
+ "def fetch_items():\n"
+ " return requests.get('/api/items')\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/filler%d.ts", i);
+ snprintf(body, sizeof(body), "export function filler%d(): number { return %d; }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/arg_url_docs.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* Positive control first: the genuine HTTP call still mints its route. */
+ ASSERT_GTE(count_nodes_named(s, project, "/api/items"), 1);
+ ASSERT_GTE(count_edges_with_url_path(s, project, "/api/items"), 1);
+ /* No Route node for any filesystem document path... */
+ ASSERT_EQ(count_nodes_named(s, project, "/new/file.txt"), 0);
+ ASSERT_EQ(count_nodes_named(s, project, "/docs/guide.md"), 0);
+ ASSERT_EQ(count_nodes_named(s, project, "/data/app.log"), 0);
+ ASSERT_EQ(count_nodes_named(s, project, "/reports/summary.pdf"), 0);
+ ASSERT_EQ(count_nodes_named(s, project, "/docs/index.rst"), 0);
+ /* ...and no HTTP_CALLS edge carrying one as its url_path either. */
+ ASSERT_EQ(count_edges_with_url_path(s, project, "/new/file.txt"), 0);
+ ASSERT_EQ(count_edges_with_url_path(s, project, "/docs/guide.md"), 0);
+ ASSERT_EQ(count_edges_with_url_path(s, project, "/data/app.log"), 0);
+ ASSERT_EQ(count_edges_with_url_path(s, project, "/reports/summary.pdf"), 0);
+ ASSERT_EQ(count_edges_with_url_path(s, project, "/docs/index.rst"), 0);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* A failed SQL query must never look like an absent false edge. */
+ static int navigation_probe_count(cbm_store_t *store, const char *sql, const char *project,
+ const char *value, const char *source_name) {
+ sqlite3_stmt *st = NULL;
+ sqlite3 *db = cbm_store_get_db(store);
+ if (!db || sqlite3_prepare_v2(db, sql, -1, &st, NULL) != SQLITE_OK) {
+ sqlite3_finalize(st);
+ return -1;
+ }
+ int count = -1;
+ bool bound = sqlite3_bind_text(st, 1, project, -1, SQLITE_TRANSIENT) == SQLITE_OK &&
+ sqlite3_bind_text(st, 2, value, -1, SQLITE_TRANSIENT) == SQLITE_OK;
+ if (bound && source_name) {
+ bound = sqlite3_bind_text(st, 3, source_name, -1, SQLITE_TRANSIENT) == SQLITE_OK;
+ }
+ if (bound && sqlite3_step(st) == SQLITE_ROW) {
+ count = sqlite3_column_int(st, 0);
+ if (sqlite3_step(st) != SQLITE_DONE) {
+ count = -1;
+ }
+ }
+ if (sqlite3_finalize(st) != SQLITE_OK) {
+ count = -1;
+ }
+ return count;
+ }
+
+ /* #1250: exercise the generic URL heuristic with real extracted occurrences
+ * and real source nodes. More than 50 files selects the parallel resolver.
+ * HTTP clients, custom navigateApi wrappers, Python and ASYNC keep their edges. */
+ TEST(pipeline_arg_url_skips_client_navigation) {
+ static const char page[] =
+ "import axios from 'axios';\n"
+ "import { get as navigate } from 'axios';\n"
+ "import { navigateTo, http, navigateApi } from './nav';\n"
+ "export class PaymentsPage {\n"
+ " constructor(private router: any, private navCtrl: any, private location: any,\n"
+ " private $router: any, private history: any) {}\n"
+ " goPayments(): void { this.router.navigateByUrl('/payments/list'); }\n"
+ " goBenefits(): void { this.navCtrl.navigateForward('/benefits/detail'); }\n"
+ " goBack(): void { this.location.go('/orders/back'); }\n"
+ " goVue(): void { this.$router.push('/dashboard/settings'); }\n"
+ " goHist(): void { this.history.pushState(null, '', '/account/history'); }\n"
+ " goWidget(id: string): void { navigateTo(`/widgetTypes/view/${id}`); }\n"
+ " load(): unknown { return http('/api/customers'); }\n"
+ " orders(): unknown { return axios.get('/api/orders'); }\n"
+ " items(): unknown { return fetch('/api/items'); }\n"
+ " custom(): unknown { return navigateApi('/api/navigation'); }\n"
+ " explicitAlias(): unknown { return navigate('/api/alias'); }\n"
+ " publish(): void { mqtt.publish('/tenant/events', 'payload'); }\n"
+ "}\n";
+ static const struct {
+ const char *callee;
+ const char *source;
+ const char *path;
+ } navigation[] = {
+ {"this.router.navigateByUrl", "goPayments", "/payments/list"},
+ {"this.navCtrl.navigateForward", "goBenefits", "/benefits/detail"},
+ {"this.location.go", "goBack", "/orders/back"},
+ {"this.$router.push", "goVue", "/dashboard/settings"},
+ {"this.history.pushState", "goHist", "/account/history"},
+ {"navigateTo", "goWidget", "/widgetTypes/view/{}"},
+ };
+ static const char edge_sql[] = "SELECT count(*) FROM edges e JOIN nodes s ON s.id=e.source_id "
+ "WHERE e.project=?1 AND e.type='HTTP_CALLS' "
+ "AND json_extract(e.properties,'$.url_path')=?2 AND s.name=?3";
+ static const char route_sql[] =
+ "SELECT count(*) FROM nodes WHERE project=?1 AND label='Route' AND name=?2";
+ static const char source_sql[] =
+ "SELECT count(*) FROM nodes WHERE project=?1 AND name=?2 AND file_path=?3";
+ static const struct {
+ const char *source;
+ const char *path;
+ } positive[] = {{"load", "/api/customers"},
+ {"orders", "/api/orders"},
+ {"items", "/api/items"},
+ {"custom", "/api/navigation"},
+ {"load_items", "/api/python/items"},
+ {"explicitAlias", "/api/alias"}};
+
+ int extracted[6] = {0};
+ CBMFileResult *fr = cbm_extract_file(page, (int)strlen(page), CBM_LANG_TYPESCRIPT,
+ "navigation_probe", "src/page.ts", 0, NULL, NULL);
+ bool extraction_ok = fr && !fr->has_error;
+ if (extraction_ok) {
+ for (int c = 0; c < fr->calls.count; c++) {
+ const CBMCall *call = &fr->calls.items[c];
+ for (size_t i = 0; i < sizeof(navigation) / sizeof(navigation[0]); i++) {
+ if (call->callee_name && strcmp(call->callee_name, navigation[i].callee) == 0 &&
+ call->enclosing_func_qn && call->start_line > 0 &&
+ call->site_end_byte > call->site_start_byte && call->arg_count > 0) {
+ extracted[i]++;
+ }
+ }
+ }
+ }
+ cbm_free_result(fr);
+
+ const char *old_workers = getenv("CBM_WORKERS");
+ const char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+ if ((old_workers && !saved_workers) || (old_single && !saved_single)) {
+ free(saved_workers);
+ free(saved_single);
+ FAIL("save environment");
+ }
+ char tmp[256] = "/tmp/cbm_arg_url_nav_XXXXXX";
+ if (!cbm_mkdtemp(tmp)) {
+ free(saved_workers);
+ free(saved_single);
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "src/nav.ts",
+ "export class AppRouter {\n"
+ " navigateByUrl(url: string): void {}\n"
+ " push(url: string): void {}\n"
+ "}\n"
+ "export class NavController {\n"
+ " navigateForward(url: string): void {}\n"
+ "}\n"
+ "export class AppLocation { go(url: string): void {} }\n"
+ "export class AppHistory {\n"
+ " pushState(state: unknown, title: string, url: string): void {}\n"
+ "}\n"
+ "export function navigateTo(url: string): void {}\n"
+ "export function http(url: string): unknown { return url; }\n"
+ "export function navigateApi(url: string): unknown { return url; }\n");
+ write_temp_file(tmp, "src/page.ts", page);
+ write_temp_file(tmp, "src/py_client.py",
+ "def navigate(url):\n return url\n"
+ "def load_items():\n return navigate('/api/python/items')\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/filler%d.ts", i);
+ snprintf(body, sizeof(body), "export function filler%d(): number { return %d; }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ const char *workers = getenv("CBM_WORKERS");
+ bool configured =
+ workers && strcmp(workers, "4") == 0 && getenv("CBM_INDEX_SINGLE_THREAD") == NULL;
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/arg_url_nav.db", tmp);
+ cbm_pipeline_t *p = configured ? cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL) : NULL;
+ int run_rc = p ? cbm_pipeline_run(p) : -1;
+ cbm_store_t *store = run_rc == 0 ? cbm_store_open_path(db_path) : NULL;
+ bool observed = store != NULL;
+ int nav_edges[6], nav_routes[6], sources[6], good_edges[6];
+ int files = -1, async_edges = -1, async_http = -1;
+ for (size_t i = 0; i < 6; i++) {
+ nav_edges[i] = nav_routes[i] = sources[i] = -1;
+ }
+ for (size_t i = 0; i < 6; i++) {
+ good_edges[i] = -1;
+ }
+ if (store) {
+ const char *project = cbm_pipeline_project_name(p);
+ files = navigation_probe_count(store,
+ "SELECT count(*) FROM nodes WHERE project=?1 AND label=?2",
+ project, "File", NULL);
+ for (size_t i = 0; i < 6; i++) {
+ nav_edges[i] = navigation_probe_count(store, edge_sql, project, navigation[i].path,
+ navigation[i].source);
+ nav_routes[i] =
+ navigation_probe_count(store, route_sql, project, navigation[i].path, NULL);
+ sources[i] = navigation_probe_count(store, source_sql, project, navigation[i].source,
+ "src/page.ts");
+ }
+ for (size_t i = 0; i < 6; i++) {
+ good_edges[i] = navigation_probe_count(store, edge_sql, project, positive[i].path,
+ positive[i].source);
+ }
+ async_edges = navigation_probe_count(
+ store,
+ "SELECT count(*) FROM edges e JOIN nodes s ON s.id=e.source_id "
+ "JOIN nodes t ON t.id=e.target_id WHERE e.project=?1 AND e.type='ASYNC_CALLS' "
+ "AND t.name=?2 AND s.name=?3",
+ project, "/tenant/events", "publish");
+ async_http = navigation_probe_count(store, edge_sql, project, "/tenant/events", "publish");
+ cbm_store_close(store);
+ }
+ cbm_pipeline_free(p);
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ const char *restored_workers = getenv("CBM_WORKERS");
+ const char *restored_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ bool restored =
+ (saved_workers ? restored_workers && strcmp(saved_workers, restored_workers) == 0
+ : !restored_workers) &&
+ (saved_single ? restored_single && strcmp(saved_single, restored_single) == 0
+ : !restored_single);
+ free(saved_workers);
+ free(saved_single);
+ th_rmtree(tmp);
+
+ ASSERT_TRUE(extraction_ok);
+ ASSERT_TRUE(configured);
+ ASSERT_TRUE(restored);
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_TRUE(observed);
+ ASSERT_GTE(files, 55);
+ for (size_t i = 0; i < 6; i++) {
+ ASSERT_EQ(extracted[i], 1);
+ ASSERT_EQ(sources[i], 1);
+ ASSERT_EQ(nav_edges[i], 0);
+ ASSERT_EQ(nav_routes[i], 0);
+ }
+ for (size_t i = 0; i < 6; i++) {
+ ASSERT_GTE(good_edges[i], 1);
+ }
+ ASSERT_GTE(async_edges, 1);
+ ASSERT_EQ(async_http, 0);
+ PASS();
+ }
+
+ /* Native `fetch()` (#856), sequential path (< 50 files → pass_calls.c). A bare
+ * unqualified call to the global fetch API has no import and no local
+ * definition anywhere in this project, so registry resolution comes back
+ * empty; classify it as HTTP_CALLS via the same #523-style empty-resolution
+ * fallback used for axios/requests. A member call on an unrelated receiver
+ * (`repo.fetch()`) must NOT be swept in — its callee_name is "repo.fetch",
+ * not the bare "fetch" this check matches exactly. */
+ TEST(pipeline_native_fetch_classified_as_http_calls) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_fetch_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "src/api.ts",
+ "export function loadData(): unknown {\n"
+ " return fetch('/api/data');\n"
+ "}\n");
+ /* `repo.fetch()` — a method call, not the global. Must not over-match. */
+ write_temp_file(tmp, "src/repo.ts",
+ "export function useRepo(repo: { fetch: () => unknown }): unknown {\n"
+ " return repo.fetch();\n"
+ "}\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/fetch.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "HTTP_CALLS"), 1);
+ /* Exactly the bare call, not the method call too. */
+ ASSERT_EQ(cbm_store_count_edges_by_type(s, project, "HTTP_CALLS"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_native_fetch_template_base_url_makes_route) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_fetch_template_base_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "src/api.ts",
+ "const BASE_URL = \"http://payments:8080\";\n"
+ "export async function createPayment(body: unknown) {\n"
+ " return fetch(`${BASE_URL}/v1/payments`, { method: 'POST', body });\n"
+ "}\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/fetch_template_base.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+ int http_call_count = cbm_store_count_edges_by_type(s, project, "HTTP_CALLS");
+ int matching_route_count =
+ http_calls_to_route(s, project, "createPayment", "/v1/payments");
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ ASSERT_EQ(http_call_count, 1);
+ ASSERT_EQ(matching_route_count, 1);
+ PASS();
+ }
+
+ /* #1892: Swift produced no Route node and no HTTP_CALLS edge, because the
+ * Swift grammar has no "arguments" field and the generic lookup therefore read
+ * no call arguments at all. Alamofire/URLSession were already in the service
+ * pattern table; the URL simply never reached it. This is the Swift twin of
+ * the TypeScript fetch case above. */
+ /* The shape real Swift actually writes: the URL is built by a constructor and
+ * force-unwrapped, so the literal is two levels below the argument list. This
+ * is what issue #1892 reported from a real project. */
+ TEST(pipeline_swift_nested_url_makes_route_issue1892) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_swiftnested_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "Sources/Client.swift",
+ "import Foundation\n"
+ "final class Client {\n"
+ " func listWidgets() {\n"
+ " URLSession.shared.dataTask(with: "
+ "URL(string: \"/api/v1/widgets\")!)\n"
+ " }\n"
+ "}\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/swiftnested.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "HTTP_CALLS"), 1);
+
+ cbm_node_t *routes = NULL;
+ int route_count = 0;
+ cbm_store_find_nodes_by_label(s, project, "Route", &routes, &route_count);
+ int widget_routes = 0;
+ for (int i = 0; i < route_count; i++) {
+ if (routes[i].qualified_name && strstr(routes[i].qualified_name, "/api/v1/widgets")) {
+ widget_routes++;
+ }
+ }
+ cbm_store_free_nodes(routes, route_count);
+ ASSERT_GTE(widget_routes, 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* HANDLES edges from the function named `source_name` to Routes whose
+ * qualified name equals `route_qn`. */
+ static int handles_to_route(cbm_store_t *s, const char *project, const char *source_name,
+ const char *route_qn) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_type(s, project, "HANDLES", &edges, &edge_count) != CBM_STORE_OK) {
+ return -1;
+ }
+ int matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t source = {0};
+ cbm_node_t target = {0};
+ int source_ok = cbm_store_find_node_by_id(s, edges[i].source_id, &source) == CBM_STORE_OK;
+ int target_ok = cbm_store_find_node_by_id(s, edges[i].target_id, &target) == CBM_STORE_OK;
+ if (source_ok && target_ok && source.name && target.qualified_name &&
+ (!source_name || strcmp(source.name, source_name) == 0) &&
+ strcmp(target.qualified_name, route_qn) == 0) {
+ matches++;
+ }
+ cbm_node_free_fields(&source);
+ cbm_node_free_fields(&target);
+ }
+ if (edges) {
+ cbm_store_free_edges(edges, edge_count);
+ }
+ return matches;
+ }
+
+ /* fastapi (2026-10-05): one binary indexed the same tree to 3,253 or to
+ * 1,119,241 HANDLES edges. A prefix Route took the directory of whichever
+ * registrar's CALLS edge came first (worker order) and linked every decorated
+ * handler under it, with no filter for the root prefix `/`; every infra URL
+ * then copied the handlers of the root route. Now: every registrar counts, a
+ * root mount bridges nothing, and an infra URL matches a root route only of
+ * its own service. */
+ TEST(pipeline_route_prefix_bridge_is_order_free_and_root_bridges_nothing) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_routebridge_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ /* two apps mounted at the root and under /api, from two directories */
+ write_temp_file(tmp, "svc/a/main.py",
+ "from fastapi import FastAPI\n"
+ "app = FastAPI()\n"
+ "app.mount(\"/\", None)\n"
+ "app.mount(\"/api\", None)\n"
+ "\n"
+ "@app.get(\"/items\")\n"
+ "def read_items():\n"
+ " return []\n");
+ write_temp_file(tmp, "svc/a/api/routes.py",
+ "from fastapi import APIRouter\n"
+ "router = APIRouter()\n"
+ "\n"
+ "@router.get(\"/ax\")\n"
+ "def api_a():\n"
+ " return 1\n");
+ write_temp_file(tmp, "svc/b/main.py",
+ "from fastapi import FastAPI\n"
+ "app = FastAPI()\n"
+ "app.mount(\"/\", None)\n"
+ "app.mount(\"/api\", None)\n"
+ "app.mount(\"/c\", None)\n"
+ "\n"
+ "@app.get(\"/users\")\n"
+ "def read_users():\n"
+ " return []\n");
+ write_temp_file(tmp, "svc/b/api/routes.py",
+ "from fastapi import APIRouter\n"
+ "router = APIRouter()\n"
+ "\n"
+ "@router.get(\"/by\")\n"
+ "def api_b():\n"
+ " return 2\n");
+ /* a real root handler, and a documentation site's link to a chat server */
+ write_temp_file(tmp, "web/site.py",
+ "from flask import Flask\n"
+ "app = Flask(__name__)\n"
+ "\n"
+ "@app.route(\"/\")\n"
+ "def index():\n"
+ " return \"ok\"\n"
+ "\n"
+ "@app.route(\"/c\")\n"
+ "def contact():\n"
+ " return \"c\"\n");
+ write_temp_file(tmp, "mkdocs.yml",
+ "site_name: demo\n"
+ "extra:\n"
+ " social:\n"
+ " - icon: fontawesome/brands/discord\n"
+ " link: https://discord.com/invite/abc123\n"
+ " - icon: fontawesome/brands/github\n"
+ " link: https://github.com/carol\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/routebridge.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* decorator routes are untouched */
+ ASSERT_EQ(handles_to_route(s, project, "read_items", "__route__GET__/items"), 1);
+ ASSERT_EQ(handles_to_route(s, project, "index", "__route__ANY__/"), 1);
+ /* a root mount names no part of a handler's path: nothing is bridged */
+ ASSERT_EQ(handles_to_route(s, project, "read_items", "__route__ANY__/"), 0);
+ ASSERT_EQ(handles_to_route(s, project, "read_users", "__route__ANY__/"), 0);
+ /* /api is registered from both directories: both api handlers, whatever
+ * order the registrations' CALLS edges landed in */
+ ASSERT_EQ(handles_to_route(s, project, "api_a", "__route__ANY__/api"), 1);
+ ASSERT_EQ(handles_to_route(s, project, "api_b", "__route__ANY__/api"), 1);
+ /* a prefix and a URL path match on whole segments only: `c` is no segment
+ * of svc/b/main.py, and `/c` is no route of github.com/carol */
+ ASSERT_EQ(handles_to_route(s, project, "read_users", "__route__ANY__/c"), 0);
+ ASSERT_EQ(handles_to_route(s, project, "contact", "__route__ANY__/c"), 1);
+ ASSERT_EQ(handles_to_route(s, project, NULL, "__route__infra__https://github.com/carol"), 0);
+ /* the chat link is no route of this repository's root handler */
+ ASSERT_EQ(
+ handles_to_route(s, project, NULL, "__route__infra__https://discord.com/invite/abc123"), 0);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_swift_http_call_makes_route_issue1892) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_swifthttp_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ /* URLSession, not Alamofire's `AF` shorthand: the service pattern table
+ * matches the library name in the callee text, and "AF.request" contains
+ * no such name. */
+ write_temp_file(tmp, "Sources/Client.swift",
+ "import Foundation\n"
+ "final class Client {\n"
+ " func listWidgets() {\n"
+ " URLSession.shared.dataTask(with: \"/api/v1/widgets\")\n"
+ " }\n"
+ "}\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/swifthttp.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "HTTP_CALLS"), 1);
+
+ /* The edge carries the URL, so pass_route_nodes can mint the Route the
+ * cross-repo matcher joins a server route against. */
+ cbm_node_t *routes = NULL;
+ int route_count = 0;
+ cbm_store_find_nodes_by_label(s, project, "Route", &routes, &route_count);
+ int widget_routes = 0;
+ for (int i = 0; i < route_count; i++) {
+ if (routes[i].qualified_name && strstr(routes[i].qualified_name, "/api/v1/widgets")) {
+ widget_routes++;
+ }
+ }
+ cbm_store_free_nodes(routes, route_count);
+ ASSERT_GTE(widget_routes, 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Native `fetch()` (#856), parallel path (>= 50 files -> pass_parallel.c's
+ * resolve_file_calls). Mirrors pipeline_native_fetch_classified_as_http_calls
+ * but forces the parallel resolver, since the empty-resolution fallback is a
+ * separate implementation there (resolve_file_calls calls
+ * emit_http_async_service_edge directly rather than through emit_service_edge,
+ * which would otherwise re-derive CBM_SVC_NONE for "fetch" and silently fall
+ * through to a plain CALLS edge). */
+ TEST(pipeline_native_fetch_parallel_classified_as_http_calls) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_fetch_par_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "src/api.ts",
+ "export function loadData(): unknown {\n"
+ " return fetch('/api/data');\n"
+ "}\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/filler%d.ts", i);
+ snprintf(body, sizeof(body), "export function filler%d(): number {\n return %d;\n}\n", i,
+ i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1); /* force parallel regardless of host cores */
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/fetch_par.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "HTTP_CALLS"), 1);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Native `fetch()` (#856): a LOCAL `fetch` definition must win over the
+ * global-API guess. Registry resolution finds this project's own top-level
+ * `fetch` function, so the call is a plain CALLS edge to it — never
+ * HTTP_CALLS. Isolated in its own project: the registry's project-wide
+ * unique-name fallback means a local `fetch` anywhere in a project can
+ * legitimately capture bare `fetch()` calls project-wide, so this must not
+ * share a project with the genuine-native-fetch test above. */
+ TEST(pipeline_local_fetch_shadow_not_classified_as_http) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_fetch_shadow_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "src/local_fetch.ts",
+ "function fetch(url: string): string {\n"
+ " return 'mock:' + url;\n"
+ "}\n"
+ "export function useLocalFetch(): string {\n"
+ " return fetch('/api/data');\n"
+ "}\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/fetch_shadow.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ ASSERT_EQ(cbm_store_count_edges_by_type(s, project, "HTTP_CALLS"), 0);
+ ASSERT_TRUE(cross_file_call_exists(s, project, "useLocalFetch", "fetch"));
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* A call the HTTP service patterns classify (axios, an axios.create instance)
+ * gets exactly ONE HTTP_CALLS edge, typed with the verb its callee names. The
+ * arg-URL heuristic (detect_url_in_args, via=arg_url) exists for calls the
+ * patterns do not know -- a local fetch wrapper such as callApi('/api/orders')
+ * -- and must not add a second, method-less __route__ANY__ edge for the same
+ * call site. On microsoft/healthcare-ai-model-evaluator 59 of 129 HTTP_CALLS
+ * were such twins, and the cross-repo matcher bound them to server handlers of
+ * any method. `fillers` > 0 forces the parallel resolver (the RED case); 0
+ * keeps the sequential one, which must agree. */
+ static int typed_http_no_url_twin_case(int fillers) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_http_twin_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "src/api.ts",
+ "import axios from 'axios';\n"
+ "const axiosInstance = axios.create({ baseURL: 'http://localhost:5000' });\n"
+ "export function getModel(id: string) {\n"
+ " return axiosInstance.get(`/api/models/${id}`);\n"
+ "}\n"
+ "export function addModel(body: unknown) {\n"
+ " return axiosInstance.post('/api/models', body);\n"
+ "}\n"
+ "export function removeModel(id: string) {\n"
+ " return axios.delete(`/api/models/${id}`);\n"
+ "}\n");
+ write_temp_file(tmp, "src/wrapper.ts",
+ "function callApi(path: string): Promise<Response> {\n"
+ " return fetch(path);\n"
+ "}\n"
+ "export function listOrders() {\n"
+ " return callApi('/api/orders');\n"
+ "}\n");
+ for (int i = 0; i < fillers; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/filler%d.ts", i);
+ snprintf(body, sizeof(body), "export function filler%d(): number {\n return %d;\n}\n", i,
+ i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/http_twin.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ static const struct {
+ const char *caller;
+ const char *typed_route;
+ } typed[] = {{"getModel", "__route__GET__"},
+ {"addModel", "__route__POST__"},
+ {"removeModel", "__route__DELETE__"}};
+ for (size_t i = 0; i < sizeof(typed) / sizeof(typed[0]); i++) {
+ /* The typed edge stays ... */
+ ASSERT_EQ(http_calls_to_route(s, project, typed[i].caller, typed[i].typed_route), 1);
+ /* ... and it is the only HTTP_CALLS edge of that call site. */
+ ASSERT_EQ(http_calls_to_route(s, project, typed[i].caller, "__route__ANY__"), 0);
+ ASSERT_EQ(http_calls_to_route(s, project, typed[i].caller, "__route__"), 1);
+ }
+ if (fillers > 0) {
+ /* Control: the heuristic still covers the call no pattern knows. The
+ * sequential resolver has no arg-URL heuristic yet (#2235). */
+ ASSERT_EQ(http_calls_to_route(s, project, "listOrders", "__route__ANY__"), 1);
+ }
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ if (saved) {
+ cbm_setenv("CBM_WORKERS", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_typed_http_call_has_no_arg_url_twin) {
+ return typed_http_no_url_twin_case(52);
+ }
+
+ TEST(pipeline_typed_http_call_has_no_arg_url_twin_sequential) {
+ return typed_http_no_url_twin_case(0);
+ }
+
+ /* #706 / #1147 end to end: a URL composed from module constants reaches the
+ * HTTP classifier, so the client call forms an HTTP_CALLS edge. Python
+ * `API_URL = API_BASE_URL + "/orders/create"` (env-derived base, literal path
+ * kept) and a TS object-literal endpoint map over a base constant. The
+ * unresolvable control (`requests.get(u)` on a computed value) adds none. */
+ TEST(pipeline_url_constant_folding_http_calls_issue706_1147) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_urlfold_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "svc/client.py",
+ "import os\n"
+ "import requests\n"
+ "API_BASE_URL = os.environ[\"API_BASE_URL\"]\n"
+ "API_URL = API_BASE_URL + \"/orders/create\"\n"
+ "def send(payload):\n"
+ " return requests.post(API_URL, json=payload)\n"
+ "def dyn():\n"
+ " u = os.environ.get(\"X\")\n"
+ " return requests.get(u)\n");
+ write_temp_file(tmp, "web/api.ts",
+ "const BASE = '/api'\n"
+ "export const API_ENDPOINTS = {\n"
+ " USER: `${BASE}/users/me`,\n"
+ "}\n"
+ "export function loadUser(): unknown {\n"
+ " return fetch(API_ENDPOINTS.USER);\n"
+ "}\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/urlfold.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
+ const char *project = cbm_pipeline_project_name(p);
+
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
+
+ /* Asserted per edge, not by count: a client call may also carry a second,
+ * arg_url-sourced HTTP_CALLS edge for the same path. */
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ ASSERT_EQ(cbm_store_find_edges_by_type(s, project, "HTTP_CALLS", &edges, &edge_count),
+ CBM_STORE_OK);
+ int py_edges = 0;
+ int ts_edges = 0;
+ int control_edges = 0;
+ for (int i = 0; i < edge_count; i++) {
+ const char *props = edges[i].properties_json ? edges[i].properties_json : "";
+ cbm_node_t src = {0};
+ cbm_store_find_node_by_id(s, edges[i].source_id, &src);
+ if (src.name && strcmp(src.name, "dyn") == 0) {
+ control_edges++;
+ } else if (src.name && strcmp(src.name, "send") == 0 &&
+ strstr(props, "\"url_path\":\"/orders/create\"")) {
+ py_edges++;
+ } else if (src.name && strcmp(src.name, "loadUser") == 0 &&
+ strstr(props, "\"url_path\":\"/api/users/me\"")) {
+ ts_edges++;
+ }
+ cbm_node_free_fields(&src);
+ }
+ cbm_store_free_edges(edges, edge_count);
+ ASSERT_GTE(py_edges, 1);
+ ASSERT_GTE(ts_edges, 1);
+ ASSERT_EQ(control_edges, 0);
+
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Run the same identities through both service resolvers. An import alias is
+ * deliberately absent from the callee-name pattern table until resolution. */
+ TEST(pipeline_folded_topics_preserve_identity_sequential_parallel) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_topicfold_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "src/topics.ts",
+ "const TENANT = 'tenant';\n"
+ "const TOPIC = `${TENANT}/events`;\n"
+ "const TOPICS = { EVENTS: `${TENANT}/events` };\n"
+ "const PREFIX = 'tenant/';\n"
+ "const DOUBLE = `${PREFIX}/events`;\n"
+ "const UNKNOWN = `${tenant}/events`;\n"
+ "export function literal() { mqtt.publish('tenant/events', 'payload'); }\n"
+ "export function direct() { mqtt.publish(`${TENANT}/events`, 'payload'); }\n"
+ "export function constant() { mqtt.publish(TOPIC, 'payload'); }\n"
+ "export function member() { mqtt.publish(TOPICS.EVENTS, 'payload'); }\n"
+ "export function doubled() { mqtt.publish(DOUBLE, 'payload'); }\n"
+ "export function unknown() { mqtt.publish(UNKNOWN, 'payload'); }\n");
+ write_temp_file(tmp, "src/aliases.py",
+ "from paho.mqtt import publish as send\n"
+ "TENANT = 'tenant'\n"
+ "TOPIC = f'{TENANT}/events'\n"
+ "ABS = f'/{TENANT}/events'\n"
+ "def alias():\n send(TOPIC, 'payload')\n"
+ "def keyword():\n send(topic=TOPIC, payload='x')\n"
+ "def slash_topic():\n send(ABS, 'payload')\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/padding%d.ts", i);
+ snprintf(body, sizeof(body), "export function padding%d() { return %d; }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ const char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+ const char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ int run_rc[2] = {-1, -1};
+ bool opened[2] = {false, false};
+ int matches[2][9] = {{0}};
+ int http_edges[2] = {-1, -1};
+ int invented[2] = {-1, -1};
+ const char *functions[] = {"literal", "direct", "constant", "member", "doubled",
+ "unknown", "alias", "keyword", "slash_topic"};
+ const char *topics[] = {"tenant/events", "tenant/events", "tenant/events",
+ "tenant/events", "tenant//events", "{}/events",
+ "tenant/events", "tenant/events", "/tenant/events"};
+ for (int mode = 0; mode < 2; mode++) {
+ if (mode == 0) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ }
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/topics_%d.db", tmp, mode);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ run_rc[mode] = p ? cbm_pipeline_run(p) : -1;
+ const char *project = p ? cbm_pipeline_project_name(p) : NULL;
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ opened[mode] = s != NULL;
+ if (s && project) {
+ for (size_t i = 0; i < sizeof(functions) / sizeof(functions[0]); i++) {
+ matches[mode][i] =
+ named_edge_count(s, project, "ASYNC_CALLS", functions[i], topics[i]);
+ }
+ http_edges[mode] = cbm_store_count_edges_by_type(s, project, "HTTP_CALLS");
+ invented[mode] = count_nodes_named(s, project, "/events");
+ /* Only slash_topic really contains a leading slash. */
+ for (size_t i = 0; i < 8; i++) {
+ invented[mode] +=
+ named_edge_count(s, project, "ASYNC_CALLS", functions[i], "/tenant/events");
+ }
+ }
+ if (s) {
+ cbm_store_close(s);
+ }
+ cbm_pipeline_free(p);
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ for (int mode = 0; mode < 2; mode++) {
+ ASSERT_EQ(run_rc[mode], 0);
+ ASSERT_TRUE(opened[mode]);
+ for (size_t i = 0; i < sizeof(functions) / sizeof(functions[0]); i++) {
+ ASSERT_GTE(matches[mode][i], 1);
+ }
+ ASSERT_EQ(http_edges[mode], 0);
+ ASSERT_EQ(invented[mode], 0);
+ }
+ PASS();
+ }
+
+ /* Relative endpoint maps still supply the parallel wrapper-client heuristic
+ * through their URL candidate, including the request-config slot from #2235. */
+ TEST(pipeline_relative_folded_wrapper_url_candidates) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_relativefold_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(
+ tmp, "src/wrapper.ts",
+ "const REL = 'api';\n"
+ "const API_ENDPOINTS = { GAME_LAUNCH_URL: `${REL}/games/launch` };\n"
+ "function client(url: string) { return url; }\n"
+ "function http(config: {url: string}) { return config; }\n"
+ "export function launch() { return client(API_ENDPOINTS.GAME_LAUNCH_URL); }\n"
+ "export function config() { return http({url: API_ENDPOINTS.GAME_LAUNCH_URL}); }\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/padding%d.ts", i);
+ snprintf(body, sizeof(body), "export function padding%d() { return %d; }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ const char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+ const char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/wrappers.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ int run_rc = p ? cbm_pipeline_run(p) : -1;
+ const char *project = p ? cbm_pipeline_project_name(p) : NULL;
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ bool opened = s != NULL;
+ int launch_edges = 0;
+ int config_edges = 0;
+ if (s && project) {
+ launch_edges = named_edge_count(s, project, "HTTP_CALLS", "launch", "/api/games/launch");
+ config_edges = named_edge_count(s, project, "HTTP_CALLS", "config", "/api/games/launch");
+ }
+ if (s) {
+ cbm_store_close(s);
+ }
+ cbm_pipeline_free(p);
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_TRUE(opened);
+ ASSERT_GTE(launch_edges, 1);
+ ASSERT_GTE(config_edges, 1);
+ PASS();
+ }
+
+ /* HTTP_CALLS + ASYNC_CALLS edges out of the function `source_name`. */
+ static int service_edges_from(cbm_store_t *s, const char *project, const char *source_name) {
+ static const char *const types[] = {"HTTP_CALLS", "ASYNC_CALLS"};
+ int matches = 0;
+ for (size_t t = 0; t < sizeof(types) / sizeof(types[0]); t++) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_type(s, project, types[t], &edges, &edge_count) !=
+ CBM_STORE_OK) {
+ return -1;
+ }
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t source = {0};
+ if (cbm_store_find_node_by_id(s, edges[i].source_id, &source) == CBM_STORE_OK &&
+ source.name && strcmp(source.name, source_name) == 0) {
+ matches++;
+ }
+ cbm_node_free_fields(&source);
+ }
+ cbm_store_free_edges(edges, edge_count);
+ }
+ return matches;
+ }
+
+ /* IMPORTS edges out of `file_path` that bind `local_name`; -1 on a failed query. */
+ static int imports_binding_count(cbm_store_t *s, const char *project, const char *file_path,
+ const char *local_name) {
+ static const char sql[] =
+ "SELECT count(*) FROM edges e JOIN nodes f ON f.id=e.source_id WHERE e.project=?1 "
+ "AND e.type='IMPORTS' AND f.file_path=?2 AND json_extract(e.properties,'$.local_name')=?3";
+ sqlite3 *db = cbm_store_get_db(s);
+ sqlite3_stmt *st = NULL;
+ if (!db || sqlite3_prepare_v2(db, sql, -1, &st, NULL) != SQLITE_OK) {
+ sqlite3_finalize(st);
+ return -1;
+ }
+ int count = -1;
+ if (sqlite3_bind_text(st, 1, project, -1, SQLITE_TRANSIENT) == SQLITE_OK &&
+ sqlite3_bind_text(st, 2, file_path, -1, SQLITE_TRANSIENT) == SQLITE_OK &&
+ sqlite3_bind_text(st, 3, local_name, -1, SQLITE_TRANSIENT) == SQLITE_OK &&
+ sqlite3_step(st) == SQLITE_ROW) {
+ count = sqlite3_column_int(st, 0);
+ }
+ sqlite3_finalize(st);
+ return count;
+ }
+
+ /* A call through an import of an EXTERNAL client library is that library's
+ * call: `fetchIt` from `{ get as fetchIt } from 'axios'` is a typed GET,
+ * `http_post` from `from requests import post as http_post` a typed POST,
+ * `emitIt` from `{ publish as emitIt } from 'mqtt'` a publish. Precision
+ * controls, each with no HTTP_CALLS/ASYNC_CALLS edge:
+ * - urljoin from urllib.parse: an HTTP library's helper, not a request;
+ * - lodash's `get`, json's `dumps`: libraries no service pattern knows;
+ * - `send` defined in the importing module shadows
+ * `from paho.mqtt import publish as send`; `relay` rebound as a parameter
+ * shadows `... as relay` (a name no project function has, so only the
+ * parameter binding stands between the call and the import);
+ * - `httpx` is a PROJECT package here: its import is materialized (the
+ * precondition is asserted), so a call it cannot resolve stays unresolved
+ * instead of becoming the external httpx.post.
+ * Both resolvers: sequential and parallel (> 50 files). */
+ TEST(pipeline_external_import_binding_controls_sequential_parallel) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_extimport_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(
+ tmp, "src/ext_http.ts",
+ "import { get as fetchIt } from 'axios';\n"
+ "import { get as lodashGet } from 'lodash';\n"
+ "import { publish as emitIt } from 'mqtt';\n"
+ "export function viaAxiosAlias(): unknown { return fetchIt('/api/alias-get'); }\n"
+ "export function viaLodashAlias(o: object): unknown {\n"
+ " return lodashGet(o, '/api/lodash');\n"
+ "}\n"
+ "export function viaMqtt(): void { emitIt('tenant/ts', 'payload'); }\n");
+ write_temp_file(tmp, "src/ext_py.py",
+ "from requests import post as http_post\n"
+ "from urllib.parse import urljoin\n"
+ "from json import dumps as publish_json\n"
+ "from paho.mqtt import publish as send\n"
+ "def py_post():\n return http_post('/api/py-post')\n"
+ "def join_url(base):\n return urljoin(base, '/static/asset.css')\n"
+ "def join_abs(name):\n return urljoin('https://example.com/assets/', name)\n"
+ "def to_json():\n return publish_json('/tenant/json')\n"
+ "def send(topic, payload):\n return topic\n"
+ "def shadowed():\n return send('tenant/shadow', 'payload')\n");
+ write_temp_file(tmp, "src/ext_param.py",
+ "from paho.mqtt import publish as relay\n"
+ "def param_shadow(relay):\n return relay('tenant/param', 'payload')\n");
+ write_temp_file(tmp, "httpx/__init__.py", "def get(url):\n return url\n");
+ write_temp_file(tmp, "src/proj_client.py",
+ "from httpx import post as hx_post\n"
+ "def proj_post():\n return hx_post('/api/project')\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "src/padding%d.ts", i);
+ snprintf(body, sizeof(body), "export function padding%d() { return %d; }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ static const char *const silent[] = {"viaLodashAlias", "join_url", "join_abs", "to_json",
+ "shadowed", "param_shadow", "proj_post"};
+ enum { SILENT = sizeof(silent) / sizeof(silent[0]) };
+ const char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+ const char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ int run_rc[2] = {-1, -1};
+ bool opened[2] = {false, false};
+ int typed_get[2] = {-1, -1};
+ int typed_post[2] = {-1, -1};
+ int published[2] = {-1, -1};
+ int shadow_calls[2] = {-1, -1};
+ int project_import[2] = {-1, -1};
+ int silent_edges[2][SILENT];
+ for (int mode = 0; mode < 2; mode++) {
+ for (int i = 0; i < SILENT; i++) {
+ silent_edges[mode][i] = -1;
+ }
+ if (mode == 0) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ }
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/extimport_%d.db", tmp, mode);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ run_rc[mode] = p ? cbm_pipeline_run(p) : -1;
+ const char *project = p ? cbm_pipeline_project_name(p) : NULL;
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ opened[mode] = s != NULL;
+ if (s && project) {
+ typed_get[mode] = http_calls_to_route(s, project, "viaAxiosAlias", "__route__GET__");
+ typed_post[mode] = http_calls_to_route(s, project, "py_post", "__route__POST__");
+ published[mode] = named_edge_count(s, project, "ASYNC_CALLS", "viaMqtt", "tenant/ts");
+ shadow_calls[mode] = named_edge_count(s, project, "CALLS", "shadowed", "send");
+ project_import[mode] =
+ imports_binding_count(s, project, "src/proj_client.py", "hx_post");
+ for (int i = 0; i < SILENT; i++) {
+ silent_edges[mode][i] = service_edges_from(s, project, silent[i]);
+ }
+ }
+ if (s) {
+ cbm_store_close(s);
+ }
+ cbm_pipeline_free(p);
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+ for (int mode = 0; mode < 2; mode++) {
+ ASSERT_EQ(run_rc[mode], 0);
+ ASSERT_TRUE(opened[mode]);
+ ASSERT_EQ(typed_get[mode], 1);
+ ASSERT_EQ(typed_post[mode], 1);
+ ASSERT_EQ(published[mode], 1);
+ ASSERT_GTE(shadow_calls[mode], 1);
+ ASSERT_GTE(project_import[mode], 1);
+ for (int i = 0; i < SILENT; i++) {
+ ASSERT_EQ(silent_edges[mode][i], 0);
+ }
+ }
+ PASS();
+ }
+
+ /* ── Git history pass tests ─────────────────────────────────────── */
+
+ TEST(githistory_is_trackable) {
+ /* Source files → trackable */
+ ASSERT_TRUE(cbm_is_trackable_file("main.go"));
+ ASSERT_TRUE(cbm_is_trackable_file("src/app.py"));
+ ASSERT_TRUE(cbm_is_trackable_file("README.md"));
+
+ /* Non-trackable: skip prefixes */
+ ASSERT_FALSE(cbm_is_trackable_file("node_modules/foo/bar.js"));
+ ASSERT_FALSE(cbm_is_trackable_file("vendor/lib/dep.go"));
+ ASSERT_FALSE(cbm_is_trackable_file(".git/config"));
+ ASSERT_FALSE(cbm_is_trackable_file("__pycache__/mod.pyc"));
+
+ /* Non-trackable: lock files */
+ ASSERT_FALSE(cbm_is_trackable_file("package-lock.json"));
+ ASSERT_FALSE(cbm_is_trackable_file("go.sum"));
+
+ /* Non-trackable: binary/minified extensions */
+ ASSERT_FALSE(cbm_is_trackable_file("image.png"));
+ ASSERT_FALSE(cbm_is_trackable_file("src/style.min.css"));
+
+ PASS();
+ }
+
+ TEST(githistory_compute_coupling) {
+ /* 5 commits with overlapping files */
+ char *files_0[] = {"a.go", "b.go", "c.go"};
+ char *files_1[] = {"a.go", "b.go"};
+ char *files_2[] = {"a.go", "b.go"};
+ char *files_3[] = {"a.go", "c.go"};
+ char *files_4[] = {"d.go", "e.go"};
+
+ cbm_commit_files_t commits[] = {
+ {files_0, 3, 0}, {files_1, 2, 0}, {files_2, 2, 0}, {files_3, 2, 0}, {files_4, 2, 0},
+ };
+
+ cbm_change_coupling_t results[100];
+ int n = cbm_compute_change_coupling(commits, 5, results, 100);
+
+ /* a.go + b.go co-change 3 times → should appear */
+ bool found_ab = false;
+ for (int i = 0; i < n; i++) {
+ if ((strcmp(results[i].file_a, "a.go") == 0 && strcmp(results[i].file_b, "b.go") == 0) ||
+ (strcmp(results[i].file_a, "b.go") == 0 && strcmp(results[i].file_b, "a.go") == 0)) {
+ found_ab = true;
+ ASSERT_EQ(results[i].co_change_count, 3);
+ ASSERT_TRUE(results[i].coupling_score >= 0.7);
+ }
+ }
+ ASSERT_TRUE(found_ab);
+
+ /* d.go + e.go co-change only 1 time → below threshold, should NOT appear */
+ for (int i = 0; i < n; i++) {
+ ASSERT_FALSE(strcmp(results[i].file_a, "d.go") == 0 ||
+ strcmp(results[i].file_b, "d.go") == 0);
+ }
+
+ PASS();
+ }
+
+ TEST(githistory_coupling_carries_last_co_change) {
+ /* Coupling output must surface the most recent commit timestamp at which
+ * a pair co-changed, so callers can score recency in addition to
+ * frequency. The pair (a.go, b.go) co-changes at three timestamps; the
+ * resulting last_co_change must be the maximum (newest) of those. */
+ char *files_old[] = {"a.go", "b.go"};
+ char *files_mid[] = {"a.go", "b.go"};
+ char *files_new[] = {"a.go", "b.go"};
+ /* Unrelated co-change in the middle to make sure we don't accidentally
+ * pick up that pair's timestamp by index. */
+ char *files_other[] = {"c.go", "d.go"};
+
+ cbm_commit_files_t commits[] = {
+ {files_old, 2, 1700000000LL}, /* oldest a.go/b.go co-change */
+ {files_other, 2, 1750000000LL}, /* unrelated pair */
+ {files_mid, 2, 1720000000LL},
+ {files_new, 2, 1800000000LL}, /* newest a.go/b.go co-change */
+ };
+
+ cbm_change_coupling_t results[16];
+ int n = cbm_compute_change_coupling(commits, 4, results, 16);
+ ASSERT_GTE(n, 1);
+
+ bool found_ab = false;
+ for (int i = 0; i < n; i++) {
+ bool is_ab =
+ (strcmp(results[i].file_a, "a.go") == 0 && strcmp(results[i].file_b, "b.go") == 0) ||
+ (strcmp(results[i].file_a, "b.go") == 0 && strcmp(results[i].file_b, "a.go") == 0);
+ if (!is_ab) {
+ continue;
+ }
+ ASSERT_EQ(results[i].co_change_count, 3);
+ /* last_co_change must be the max of the three a.go/b.go timestamps. */
+ ASSERT_EQ(results[i].last_co_change, 1800000000LL);
+ found_ab = true;
+ }
+ ASSERT_TRUE(found_ab);
+ PASS();
+ }
+
+ TEST(githistory_skip_large_commits) {
+ /* A single commit with 25 files → should be skipped (>20) */
+ char *files[25];
+ char bufs[25][32];
+ for (int i = 0; i < 25; i++) {
+ snprintf(bufs[i], sizeof(bufs[i]), "file%d.go", i);
+ files[i] = bufs[i];
+ }
+
+ cbm_commit_files_t commits[] = {{files, 25, 0}};
+
+ cbm_change_coupling_t results[100];
+ int n = cbm_compute_change_coupling(commits, 1, results, 100);
+ ASSERT_EQ(n, 0);
+
+ PASS();
+ }
+
+ TEST(githistory_limits_to_max) {
+ /* Create many commits to generate >100 couplings */
+ /* 50 files, each pair has 3 commits → C(50,2)=1225 pairs, but only
+ * pairs with ≥3 co-changes and score≥0.3 pass the threshold */
+ int nfiles = 50;
+ int npairs = nfiles * (nfiles - 1) / 2;
+ int ncommits = npairs * 3;
+
+ cbm_commit_files_t *commits = calloc(ncommits, sizeof(cbm_commit_files_t));
+ char **file_strs = calloc(nfiles, sizeof(char *));
+ for (int i = 0; i < nfiles; i++) {
+ file_strs[i] = malloc(32);
+ snprintf(file_strs[i], 32, "f%d.go", i);
+ }
+
+ int ci = 0;
+ for (int i = 0; i < nfiles; i++) {
+ for (int j = i + 1; j < nfiles; j++) {
+ for (int k = 0; k < 3; k++) {
+ commits[ci].files = malloc(2 * sizeof(char *));
+ commits[ci].files[0] = file_strs[i];
+ commits[ci].files[1] = file_strs[j];
+ commits[ci].count = 2;
+ ci++;
+ }
+ }
+ }
+
+ /* max_out = 100 → should cap at 100 */
+ cbm_change_coupling_t results[100];
+ int n = cbm_compute_change_coupling(commits, ncommits, results, 100);
+ ASSERT_TRUE(n <= 100);
+
+ /* Cleanup */
+ for (int i = 0; i < ncommits; i++) {
+ free(commits[i].files);
+ }
+ for (int i = 0; i < nfiles; i++) {
+ free(file_strs[i]);
+ }
+ free(file_strs);
+ free(commits);
+
+ PASS();
+ }
+
+ /* ── Test detection tests ──────────────────────────────────────── */
+
+ TEST(testdetect_is_test_file) {
+ /* Test file patterns (all languages) */
+ ASSERT_TRUE(cbm_is_test_path("foo_test.go"));
+ ASSERT_TRUE(cbm_is_test_path("test_handler.py"));
+ ASSERT_TRUE(cbm_is_test_path("handler.test.js"));
+ ASSERT_TRUE(cbm_is_test_path("handler.spec.ts"));
+ ASSERT_TRUE(cbm_is_test_path("Component.test.tsx"));
+ ASSERT_TRUE(cbm_is_test_path("OrderTest.java"));
+ ASSERT_TRUE(cbm_is_test_path("handler_test.rs"));
+ ASSERT_TRUE(cbm_is_test_path("handler_test.cpp"));
+ ASSERT_TRUE(cbm_is_test_path("OrderTest.cs"));
+ ASSERT_TRUE(cbm_is_test_path("OrderTest.php"));
+ ASSERT_TRUE(cbm_is_test_path("OrderSpec.scala"));
+ ASSERT_TRUE(cbm_is_test_path("OrderTest.kt"));
+ ASSERT_TRUE(cbm_is_test_path("handler_test.lua"));
+
+ /* Non-test file patterns */
+ ASSERT_FALSE(cbm_is_test_path("foo.go"));
+ ASSERT_FALSE(cbm_is_test_path("handler.py"));
+ ASSERT_FALSE(cbm_is_test_path("handler.js"));
+ ASSERT_FALSE(cbm_is_test_path("handler.ts"));
+ ASSERT_FALSE(cbm_is_test_path("Component.tsx"));
+ ASSERT_FALSE(cbm_is_test_path("Order.java"));
+ ASSERT_FALSE(cbm_is_test_path("handler.rs"));
+ ASSERT_FALSE(cbm_is_test_path("handler.cpp"));
+ ASSERT_FALSE(cbm_is_test_path("Order.cs"));
+ ASSERT_FALSE(cbm_is_test_path("Order.php"));
+ ASSERT_FALSE(cbm_is_test_path("Order.scala"));
+ ASSERT_FALSE(cbm_is_test_path("Order.kt"));
+ ASSERT_FALSE(cbm_is_test_path("handler.lua"));
+
+ PASS();
+ }
+
+ TEST(testdetect_is_test_function) {
+ /* Test function patterns */
+ ASSERT_TRUE(cbm_is_test_func_name("TestCreate")); /* Go */
+ ASSERT_TRUE(cbm_is_test_func_name("test_create")); /* Python/Rust/Lua */
+ ASSERT_TRUE(cbm_is_test_func_name("test")); /* JS/TS */
+ ASSERT_TRUE(cbm_is_test_func_name("describe")); /* JS/TS */
+ ASSERT_TRUE(cbm_is_test_func_name("it")); /* JS/TS */
+ ASSERT_TRUE(cbm_is_test_func_name("testCreate")); /* Java/PHP/Scala/Kotlin */
+ ASSERT_TRUE(cbm_is_test_func_name("TestCreate")); /* C++/C# */
+
+ /* Non-test function patterns */
+ ASSERT_FALSE(cbm_is_test_func_name("create"));
+ ASSERT_FALSE(cbm_is_test_func_name("handleRequest"));
+ ASSERT_FALSE(cbm_is_test_func_name("process"));
+
+ PASS();
+ }
+
+ /* ── Implements pass tests (graph buffer based) ────────────────── */
+
+ TEST(implements_creates_override) {
+ /* Port of TestPassImplementsCreatesOverrideEdges.
+ * Set up Interface+methods, Class+methods, verify IMPLEMENTS+OVERRIDE. */
+ cbm_gbuf_t *gb = cbm_gbuf_new("test-proj", "/tmp/test");
+ ASSERT_NOT_NULL(gb);
+
+ /* Interface "Reader" with methods "Read" and "Close" */
+ int64_t iface_id =
+ cbm_gbuf_upsert_node(gb, "Interface", "Reader", "pkg.Reader", "pkg/reader.go", 1, 5, "{}");
+ ASSERT_GT(iface_id, 0);
+
+ int64_t read_method_id =
+ cbm_gbuf_upsert_node(gb, "Method", "Read", "pkg.Reader.Read", "pkg/reader.go", 2, 2, "{}");
+ int64_t close_method_id = cbm_gbuf_upsert_node(gb, "Method", "Close", "pkg.Reader.Close",
+ "pkg/reader.go", 3, 3, "{}");
+ ASSERT_GT(read_method_id, 0);
+ ASSERT_GT(close_method_id, 0);
+
+ /* DEFINES_METHOD edges */
+ cbm_gbuf_insert_edge(gb, iface_id, read_method_id, "DEFINES_METHOD", "{}");
+ cbm_gbuf_insert_edge(gb, iface_id, close_method_id, "DEFINES_METHOD", "{}");
+
+ /* Class "FileReader" with matching methods */
+ int64_t class_id = cbm_gbuf_upsert_node(gb, "Class", "FileReader", "pkg.FileReader",
+ "pkg/filereader.go", 1, 10, "{}");
+ ASSERT_GT(class_id, 0);
+
+ int64_t fr_read_id =
+ cbm_gbuf_upsert_node(gb, "Method", "Read", "pkg.FileReader.Read", "pkg/filereader.go", 2, 4,
+ "{\"receiver\":\"(f *FileReader)\"}");
+ int64_t fr_close_id =
+ cbm_gbuf_upsert_node(gb, "Method", "Close", "pkg.FileReader.Close", "pkg/filereader.go", 5,
+ 7, "{\"receiver\":\"(f *FileReader)\"}");
+ ASSERT_GT(fr_read_id, 0);
+ ASSERT_GT(fr_close_id, 0);
+
+ /* Run Go-style implements detection */
+ atomic_int cancelled = 0;
+ cbm_pipeline_ctx_t ctx = {
+ .project_name = "test-proj",
+ .repo_path = "/tmp/test",
+ .gbuf = gb,
+ .registry = NULL,
+ .cancelled = &cancelled,
+ };
+ int edges_created = cbm_pipeline_implements_go(&ctx);
+ ASSERT_GT(edges_created, 0);
+
+ /* Verify IMPLEMENTS edge: FileReader → Reader */
+ const cbm_gbuf_edge_t **impl_edges = NULL;
+ int impl_count = 0;
+ int rc =
+ cbm_gbuf_find_edges_by_source_type(gb, class_id, "IMPLEMENTS", &impl_edges, &impl_count);
+ ASSERT_EQ(rc, 0);
+ ASSERT_EQ(impl_count, 1);
+ ASSERT_EQ(impl_edges[0]->target_id, iface_id);
+
+ /* Verify OVERRIDE edges: FileReader.Read → Reader.Read */
+ const cbm_gbuf_edge_t **read_overrides = NULL;
+ int read_override_count = 0;
+ rc = cbm_gbuf_find_edges_by_source_type(gb, fr_read_id, "OVERRIDE", &read_overrides,
+ &read_override_count);
+ ASSERT_EQ(rc, 0);
+ ASSERT_EQ(read_override_count, 1);
+ ASSERT_EQ(read_overrides[0]->target_id, read_method_id);
+
+ /* Verify OVERRIDE edge: FileReader.Close → Reader.Close */
+ const cbm_gbuf_edge_t **close_overrides = NULL;
+ int close_override_count = 0;
+ rc = cbm_gbuf_find_edges_by_source_type(gb, fr_close_id, "OVERRIDE", &close_overrides,
+ &close_override_count);
+ ASSERT_EQ(rc, 0);
+ ASSERT_EQ(close_override_count, 1);
+ ASSERT_EQ(close_overrides[0]->target_id, close_method_id);
+
+ cbm_gbuf_free(gb);
+ PASS();
+ }
+
+ TEST(implements_no_match) {
+ /* Port of TestPassImplementsNoOverrideWithoutMatch.
+ * Interface requires Read+Write, struct only has Read → no edges. */
+ cbm_gbuf_t *gb = cbm_gbuf_new("test-proj", "/tmp/test");
+ ASSERT_NOT_NULL(gb);
+
+ /* Interface "ReadWriter" with methods "Read" and "Write" */
+ int64_t iface_id = cbm_gbuf_upsert_node(gb, "Interface", "ReadWriter", "pkg.ReadWriter",
+ "pkg/rw.go", 1, 5, "{}");
+ int64_t read_id =
+ cbm_gbuf_upsert_node(gb, "Method", "Read", "pkg.ReadWriter.Read", "pkg/rw.go", 2, 2, "{}");
+ int64_t write_id = cbm_gbuf_upsert_node(gb, "Method", "Write", "pkg.ReadWriter.Write",
+ "pkg/rw.go", 3, 3, "{}");
+ cbm_gbuf_insert_edge(gb, iface_id, read_id, "DEFINES_METHOD", "{}");
+ cbm_gbuf_insert_edge(gb, iface_id, write_id, "DEFINES_METHOD", "{}");
+
+ /* Struct "OnlyReader" with only "Read" (missing "Write") */
+ int64_t class_id = cbm_gbuf_upsert_node(gb, "Class", "OnlyReader", "pkg.OnlyReader",
+ "pkg/onlyreader.go", 1, 10, "{}");
+ int64_t or_read_id =
+ cbm_gbuf_upsert_node(gb, "Method", "Read", "pkg.OnlyReader.Read", "pkg/onlyreader.go", 2, 4,
+ "{\"receiver\":\"(o *OnlyReader)\"}");
+
+ /* Run Go-style implements detection */
+ atomic_int cancelled = 0;
+ cbm_pipeline_ctx_t ctx = {
+ .project_name = "test-proj",
+ .repo_path = "/tmp/test",
+ .gbuf = gb,
+ .registry = NULL,
+ .cancelled = &cancelled,
+ };
+ int edges_created = cbm_pipeline_implements_go(&ctx);
+ ASSERT_EQ(edges_created, 0);
+
+ /* Verify NO IMPLEMENTS edge */
+ const cbm_gbuf_edge_t **impl_edges = NULL;
+ int impl_count = 0;
+ cbm_gbuf_find_edges_by_source_type(gb, class_id, "IMPLEMENTS", &impl_edges, &impl_count);
+ ASSERT_EQ(impl_count, 0);
+
+ /* Verify NO OVERRIDE edge */
+ const cbm_gbuf_edge_t **override_edges = NULL;
+ int override_count = 0;
+ cbm_gbuf_find_edges_by_source_type(gb, or_read_id, "OVERRIDE", &override_edges,
+ &override_count);
+ ASSERT_EQ(override_count, 0);
+
+ /* Suppress unused warnings */
+ (void)iface_id;
+ (void)read_id;
+ (void)write_id;
+
+ cbm_gbuf_free(gb);
+ PASS();
+ }
+
+ /* ── Usages pass tests (full pipeline integration) ──────────────── */
+
+ /* Helper to create a temp dir with a single source file */
+ static char g_usages_tmpdir[256];
+
+ static int setup_usages_repo(const char *filename, const char *content, const char *extra_file,
+ const char *extra_content) {
+ snprintf(g_usages_tmpdir, sizeof(g_usages_tmpdir), "/tmp/cbm_usage_XXXXXX");
+ if (!cbm_mkdtemp(g_usages_tmpdir))
+ return -1;
+
+ /* Check if filename has subdirectory */
+ char path[512];
+ snprintf(path, sizeof(path), "%s/%s", g_usages_tmpdir, filename);
+
+ /* Create subdirectories if needed */
+ char dir_path[512];
+ snprintf(dir_path, sizeof(dir_path), "%s", path);
+ char *last_slash = strrchr(dir_path, '/');
+ if (last_slash) {
+ *last_slash = '\0';
+ th_mkdir_p(dir_path);
}
- write_temp_file(tmp, "worker.py",
- "class Worker:\n"
- " def backward(self):\n"
- " return 1\n");
- write_temp_file(tmp, "pkg/__init__.py", "from .helper import compute\n");
- write_temp_file(tmp, "pkg/helper.py",
- "def compute(value):\n"
- " return value * 2\n");
- write_temp_file(tmp, "caller.py",
- "from pkg import helper\n"
- "\n"
- "def external_call(accelerator):\n"
- " return accelerator.backward()\n"
- "\n"
- "def imported_call():\n"
- " return helper.compute(42)\n"
- "\n"
- "def local_helper():\n"
- " return 1\n"
- "\n"
- "def bare_call():\n"
- " return local_helper()\n");
+ FILE *f = fopen(path, "w");
+ if (!f)
+ return -1;
+ fprintf(f, "%s", content);
+ fclose(f);
- char db_path[512];
- snprintf(db_path, sizeof(db_path), "%s/python_recv.db", tmp);
- cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p);
- ASSERT_EQ(cbm_pipeline_run(p), 0);
- const char *project = cbm_pipeline_project_name(p);
+ if (extra_file && extra_content) {
+ snprintf(path, sizeof(path), "%s/%s", g_usages_tmpdir, extra_file);
+ f = fopen(path, "w");
+ if (!f)
+ return -1;
+ fprintf(f, "%s", extra_content);
+ fclose(f);
+ }
- cbm_store_t *s = cbm_store_open_path(db_path);
- ASSERT_NOT_NULL(s);
+ return 0;
+ }
- /* NEGATIVE: `accelerator` is a parameter — Worker.backward must not bind. */
- ASSERT_FALSE(cross_file_call_exists(s, project, "external_call", "backward"));
- /* POSITIVE: import-bound receiver and bare local call both survive. */
- ASSERT_TRUE(cross_file_call_exists(s, project, "imported_call", "compute"));
- ASSERT_TRUE(cross_file_call_exists(s, project, "bare_call", "local_helper"));
- /* Tripwire: a run that emitted no edges at all would satisfy the negative
- * assertion vacuously. */
- ASSERT_GTE(cbm_store_count_edges_by_type(s, project, "CALLS"), 1);
+ static void teardown_usages_repo(void) {
+ if (g_usages_tmpdir[0])
+ rm_rf(g_usages_tmpdir);
+ g_usages_tmpdir[0] = '\0';
+ }
- cbm_store_close(s);
+ /* Real cross-file memo failure, after successful extraction. The failure
+ * must reach the public per-file error list on both production drivers. */
+ static int pipeline_lsp_failure_case(bool parallel, const char *stage, bool python, bool depth) {
+ const char *src = "struct S { int m() { return 1; } };\n"
+ "void run() { S s; s.m(); }\n";
+ if (python)
+ src = "class S:\n def m(self):\n return 1\ndef run():\n s = S()\n s.m()\n";
+ const char *filename = python ? "memo.py" : "memo.cpp";
+ const char *extra_name = NULL;
+ const char *extra_src = NULL;
+ /* The cross stage needs a call the per-file LSP cannot resolve: the parallel
+ * driver skips the cross walk for a file whose sites are all resolved. */
+ if (strcmp(stage, "cross") == 0) {
+ src = python ? "from memo_def import S\ndef run():\n s = S()\n s.m()\n"
+ : "void run() { S s; s.m(); }\n";
+ extra_name = python ? "memo_def.py" : "memo_def.cpp";
+ extra_src = python ? "class S:\n def m(self):\n return 1\n"
+ : "struct S { int m() { return 1; } };\n";
+ }
+ if (setup_usages_repo(filename, src, extra_name, extra_src) != 0)
+ FAIL("failed to create memo fixture");
+ char path[512];
+ if (parallel) {
+ for (int i = 0; i < 51; i++) {
+ snprintf(path, sizeof(path), "%s/memo_pad_%02d.%s", g_usages_tmpdir, i,
+ python ? "py" : "cpp");
+ if (th_write_file(path, python ? "# inert parallel routing fixture\n"
+ : "// inert parallel routing fixture\n") != 0) {
+ teardown_usages_repo();
+ FAIL("failed to create parallel routing fixture");
+ }
+ }
+ }
+ const char *keys[] = {
+ "CBM_WORKERS", "CBM_INDEX_SINGLE_THREAD",
+ depth ? (python ? "CBM_TEST_PY_LSP_DEPTH_FAIL_STAGE" : "CBM_TEST_C_LSP_DEPTH_FAIL_STAGE")
+ : (python ? "CBM_TEST_PY_LSP_MEMO_FAIL_STAGE" : "CBM_TEST_C_LSP_MEMO_FAIL_STAGE")};
+ char *saved[3] = {0};
+ bool env_saved = true;
+ for (int i = 0; i < 3; i++) {
+ const char *old = getenv(keys[i]);
+ saved[i] = old ? strdup(old) : NULL;
+ env_saved = env_saved && (!old || saved[i]);
+ }
+ if (!env_saved) {
+ for (int i = 0; i < 3; i++)
+ free(saved[i]);
+ teardown_usages_repo();
+ FAIL("failed to save memo fixture environment");
+ }
+ int set_rc = cbm_setenv(keys[0], parallel ? "4" : "1", 1);
+ set_rc |= parallel ? cbm_unsetenv(keys[1]) : cbm_setenv(keys[1], "1", 1);
+ set_rc |= cbm_setenv(keys[2], stage, 1);
+ snprintf(path, sizeof(path), "%s/memo.db", g_usages_tmpdir);
+ cbm_pipeline_t *p = set_rc == 0 ? cbm_pipeline_new(g_usages_tmpdir, path, CBM_MODE_FULL) : NULL;
+ int run_rc = p ? cbm_pipeline_run(p) : -1;
+ cbm_file_error_t *errors = NULL;
+ int error_count = 0;
+ cbm_pipeline_get_file_errors(p, &errors, &error_count);
+ int memo_errors = 0;
+ const char *expected_phase = strcmp(stage, "cross") == 0 ? "lsp_skipped" : "extract";
+ bool precise = true;
+ for (int i = 0; i < error_count; i++) {
+ if (errors[i].path && strcmp(errors[i].path, filename) == 0) {
+ memo_errors++;
+ precise = precise && errors[i].phase && strcmp(errors[i].phase, expected_phase) == 0 &&
+ errors[i].reason &&
+ strcmp(errors[i].reason,
+ depth ? (python ? CBM_PY_LSP_DEPTH_ERROR : CBM_C_LSP_DEPTH_ERROR)
+ : (python ? CBM_PY_LSP_MEMO_ERROR : CBM_C_LSP_MEMO_ERROR)) == 0;
+ }
+ }
cbm_pipeline_free(p);
- th_rmtree(tmp);
+ int restore_rc = 0;
+ for (int i = 0; i < 3; i++) {
+ restore_rc |= saved[i] ? cbm_setenv(keys[i], saved[i], 1) : cbm_unsetenv(keys[i]);
+ free(saved[i]);
+ }
+ teardown_usages_repo();
+ ASSERT_EQ(set_rc, 0);
+ ASSERT_EQ(restore_rc, 0);
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_EQ(memo_errors, 1);
+ ASSERT_TRUE(precise);
PASS();
}
@@@ -13426,17 -29604,58 +29723,59 @@@ SUITE(pipeline)
RUN_TEST(pipeline_incremental_parallel_result_cache_alloc_failure_preserves_db_and_retries);
#endif
RUN_TEST(pipeline_tsjs_receiver_suppresses_weak_method_edge);
+ RUN_TEST(pipeline_axios_wrapper_baseurl_composes_http_calls_issue1916);
+ RUN_TEST(pipeline_ts_crossfile_new_instance_method_call_issue1354);
+ RUN_TEST(pipeline_ts_renamed_import_call_issue2297);
+ RUN_TEST(pipeline_ts_param_property_injection_issue514);
RUN_TEST(pipeline_python_receiver_suppresses_weak_method_edge);
+ RUN_TEST(pipeline_php_receiver_suppresses_weak_method_edge);
+ RUN_TEST(pipeline_php_receiver_parallel_suppresses_weak_method_edge);
+ RUN_TEST(pipeline_python_receiver_keeps_specific_unique_name_member_call);
+ RUN_TEST(pipeline_html_embedded_member_call_stays_unbound);
RUN_TEST(pipeline_go_method_caller_keeps_lsp_join);
RUN_TEST(pipeline_go_receiver_suppresses_weak_method_edge);
+ RUN_TEST(pipeline_go_receiver_parallel_suppresses_weak_method_edge);
+ RUN_TEST(pipeline_go_multi_return_receiver_is_typed);
+ RUN_TEST(pipeline_go_multi_return_receiver_is_typed_parallel);
+ RUN_TEST(pipeline_go_parallel_field_hint_requires_owner_segment);
RUN_TEST(pipeline_go_multi_init_nodes_survive);
+ RUN_TEST(pipeline_go_init_lsp_edges_per_file);
+ RUN_TEST(pipeline_go_init_lsp_edges_per_file_parallel);
+ RUN_TEST(pipeline_go_crossfile_type_alias_method);
+ RUN_TEST(pipeline_go_crossfile_type_alias_method_parallel);
RUN_TEST(pipeline_go_rw_usage_never_cross_into_c);
RUN_TEST(pipeline_go_rw_usage_never_cross_into_c_parallel);
+ RUN_TEST(pipeline_rust_call_never_binds_another_language);
+ RUN_TEST(pipeline_rust_call_never_binds_another_language_parallel);
+ RUN_TEST(pipeline_rust_assoc_call_never_binds_free_namesake);
+ RUN_TEST(pipeline_rust_assoc_call_never_binds_free_namesake_parallel);
+ RUN_TEST(pipeline_rust_generic_impl_method_sources_its_calls);
+ RUN_TEST(pipeline_rust_generic_impl_method_sources_its_calls_parallel);
+ RUN_TEST(pipeline_rust_std_receiver_never_binds_project_method);
+ RUN_TEST(pipeline_rust_std_receiver_never_binds_project_method_parallel);
RUN_TEST(pipeline_go_bare_ref_never_binds_field);
RUN_TEST(pipeline_go_bare_ref_never_binds_field_parallel);
+ RUN_TEST(pipeline_c_bare_ref_never_binds_field);
+ RUN_TEST(pipeline_c_bare_ref_never_binds_field_parallel);
+ RUN_TEST(pipeline_c_call_reaches_header_function_beside_field);
+ RUN_TEST(pipeline_c_call_reaches_header_function_beside_field_parallel);
+ RUN_TEST(pipeline_c_member_access_binds_field_by_object_type);
+ RUN_TEST(pipeline_c_member_access_binds_field_by_object_type_parallel);
RUN_TEST(pipeline_tsjs_receiver_parallel_keeps_service_edges);
+ RUN_TEST(pipeline_capitalized_axios_import_is_http_client);
+ RUN_TEST(pipeline_capitalized_axios_import_is_http_client_sequential);
+ RUN_TEST(pipeline_python_websocket_decorators_register_routes);
RUN_TEST(pipeline_python_receiver_parallel_suppresses_weak_method_edges);
+ RUN_TEST(pipeline_python_bare_local_binding_suppresses_weak_edge);
+ RUN_TEST(pipeline_python_bare_local_binding_parallel_suppresses_weak_edge);
+ RUN_TEST(pipeline_external_import_shadow_not_bound_to_local_homonym_issue1355);
+ RUN_TEST(pipeline_external_import_shadow_keeps_workspace_sibling_issue1355);
+ RUN_TEST(pipeline_external_import_shadow_keeps_declared_package_issue1355);
+ RUN_TEST(pipeline_external_import_shadow_keeps_route_registration_issue1355);
+ RUN_TEST(pipeline_python_package_relative_imports);
+ RUN_TEST(pipeline_python_package_relative_imports_parallel);
+ RUN_TEST(pipeline_python_from_import_bare_call_issue1237);
+ RUN_TEST(pipeline_python_from_import_bare_call_issue1237_parallel);
RUN_TEST(pipeline_parallel_python_cross_only_dunder_gets_synthetic_carrier);
RUN_TEST(pipeline_parallel_rust_cross_only_macro_hidden_gets_synthetic_carrier);
RUN_TEST(pipeline_arg_url_rejects_non_http_slash_arguments);