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-init-qn

Martin Vogel776f6f589ad5
diff --cc tests/test_extraction.c
index edecba47d,211f7cda6..30e542003
--- a/tests/test_extraction.c
+++ b/tests/test_extraction.c
@@@ -4899,68 -7854,48 +7854,110 @@@ TEST(extract_go_method_receiver_qualifi
PASS();
}
- TEST(extract_go_multiple_init_disambiguated) {
- /* Go allows several init() per package (even per file); each gets a
- * file+ordinal-suffixed QN (#495 cfg-twin pattern) so none is lost to the
- * same-QN upsert. The ordinal — unlike a line number — must not move when
- * code is inserted above the function: the QN is node identity, and a
- * line-based suffix would churn nodes on every unrelated edit. */
- CBMFileResult *r = extract("package m\n"
- "func init() { a() }\n"
- "func init() { b() }\n"
- "func a() {}\n"
- "func b() {}\n",
- CBM_LANG_GO, "t", "x.go");
+ /* Templ shares Go's method grammar (method_declaration with a receiver), but
+ * only Go method QNs are receiver-qualified (#1913); templ's call-scope QN
+ * stays flat. The method's def QN and the enclosing-function QN of a call
+ * inside it must agree, or the call has no source node and degrades to the
+ * File node. */
+ TEST(extract_templ_method_qn_matches_call_scope) {
+ CBMFileResult *r = extract("package views\n"
+ "\n"
+ "type Page struct{}\n"
+ "\n"
+ "func (p Page) Title() string {\n"
+ "\treturn helper()\n"
+ "}\n"
+ "\n"
+ "func helper() string { return \"x\" }\n"
+ "\n"
+ "templ hello(name string) {\n"
+ "\t<div>{ name }</div>\n"
+ "}\n",
+ CBM_LANG_TEMPL, "t", "x.templ");
+ ASSERT_NOT_NULL(r);
+ const char *title_qn = NULL;
+ for (int i = 0; i < r->defs.count; i++) {
+ const CBMDefinition *d = &r->defs.items[i];
+ if (d->name && d->qualified_name && strcmp(d->name, "Title") == 0) {
+ title_qn = d->qualified_name;
+ }
+ }
+ const char *scope = NULL;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *c = &r->calls.items[i];
+ if (c->callee_name && strcmp(c->callee_name, "helper") == 0) {
+ scope = c->enclosing_func_qn;
+ }
+ }
+ ASSERT_NOT_NULL(title_qn);
+ ASSERT_NOT_NULL(scope);
+ ASSERT_STR_EQ(scope, title_qn);
+ cbm_free_result(r);
+ PASS();
+ }
+
++TEST(extract_go_multiple_init_disambiguated) {
++ /* Go allows several init() per package (even per file); each gets a
++ * file+ordinal-suffixed QN (#495 cfg-twin pattern) so none is lost to the
++ * same-QN upsert. The ordinal — unlike a line number — must not move when
++ * code is inserted above the function: the QN is node identity, and a
++ * line-based suffix would churn nodes on every unrelated edit. */
++ CBMFileResult *r = extract("package m\n"
++ "func init() { a() }\n"
++ "func init() { b() }\n"
++ "func a() {}\n"
++ "func b() {}\n",
++ CBM_LANG_GO, "t", "x.go");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ const char *first = NULL;
+ const char *second = NULL;
+ for (int i = 0; i < r->defs.count; i++) {
+ const CBMDefinition *d = &r->defs.items[i];
+ if (!d->name || strcmp(d->name, "init") != 0) {
+ continue;
+ }
+ if (!first) {
+ first = d->qualified_name;
+ } else {
+ second = d->qualified_name;
+ }
+ }
+ ASSERT_NOT_NULL(first);
+ ASSERT_NOT_NULL(second);
+ ASSERT_STR_EQ(first, "t.init#x.go:1");
+ ASSERT_STR_EQ(second, "t.init#x.go:2");
+
+ /* Stability: an insertion ABOVE both inits must not change either QN. */
+ CBMFileResult *r2 = extract("package m\n"
+ "import \"fmt\"\n"
+ "var shifted = fmt.Sprint(\"pad\")\n"
+ "func init() { a() }\n"
+ "func init() { b() }\n"
+ "func a() {}\n"
+ "func b() {}\n",
+ CBM_LANG_GO, "t", "x.go");
+ ASSERT_NOT_NULL(r2);
+ ASSERT_FALSE(r2->has_error);
+ int seen = 0;
+ for (int i = 0; i < r2->defs.count; i++) {
+ const CBMDefinition *d = &r2->defs.items[i];
+ if (!d->name || strcmp(d->name, "init") != 0) {
+ continue;
+ }
+ seen++;
+ if (seen == 1) {
+ ASSERT_STR_EQ(d->qualified_name, "t.init#x.go:1");
+ } else {
+ ASSERT_STR_EQ(d->qualified_name, "t.init#x.go:2");
+ }
+ }
+ ASSERT_EQ(seen, 2);
+ cbm_free_result(r2);
+ cbm_free_result(r);
+ PASS();
+}
+
/* TS/JS/TSX receiver-aware flag (#592/#606; same intent as the Perl flag above).
* A member call x.foo() with a non-this/super receiver is flagged is_method so
* the resolver can suppress a weak short-name match (`re.test()` must not bind a
@@@ -6638,11 -13202,14 +13264,15 @@@ SUITE(extraction)
RUN_TEST(extract_perl_config_string_not_a_callee);
RUN_TEST(extract_perl_builtin_call_is_function_not_method);
RUN_TEST(extract_perl_method_call_flags_is_method);
+ RUN_TEST(extract_rust_generic_impl_call_scope_matches_def);
RUN_TEST(extract_flag_exempt_method_call_not_flagged_is_method);
RUN_TEST(extract_python_member_call_flags_is_method);
+ RUN_TEST(extract_python_bare_call_flags_locally_bound_callee);
+ RUN_TEST(extract_python_bare_call_flag_is_depth_independent);
RUN_TEST(extract_go_selector_call_flags_is_method);
RUN_TEST(extract_go_method_receiver_qualified_qn);
+ RUN_TEST(extract_templ_method_qn_matches_call_scope);
+ RUN_TEST(extract_go_multiple_init_disambiguated);
RUN_TEST(extract_ts_member_call_flags_is_method);
RUN_TEST(extract_ts_this_super_receiver_not_flagged);
RUN_TEST(extract_js_member_call_flags_is_method);
diff --cc tests/test_pipeline.c
index a5d5b545f,ce80d1f42..8b413066d
--- a/tests/test_pipeline.c
+++ b/tests/test_pipeline.c
@@@ -2937,111 -5455,7109 +5455,7158 @@@ TEST(incremental_second_build_declarer_
PASS();
}
+ TEST(incremental_deleted_dockerfile_drops_its_image) {
+ cbm_incremental_route_t route = CBM_INCREMENTAL_ROUTE_NONE;
+ int left = incremental_dockerfile_delete(false, &route);
+ ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+ ASSERT_EQ(left, 1);
#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
- static void observe_named_generation(const char *db_path, const char *project,
- const char *before_name, const char *after_name,
- int *before_count, int *after_count) {
- *before_count = -1;
- *after_count = -1;
- cbm_store_t *store = cbm_store_open_path(db_path);
- if (!store) {
- return;
- }
- *before_count = named_node_count(store, project, before_name);
- *after_count = named_node_count(store, project, after_name);
- cbm_store_close(store);
+ left = incremental_dockerfile_delete(true, &route);
+ ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_LEGACY_PARTIAL);
+ ASSERT_EQ(left, 1);
+ #endif
+ PASS();
}
- static int count_generation_stage_artifacts(const char *dir_path, const char *db_basename) {
- cbm_dir_t *dir = cbm_opendir(dir_path);
- if (!dir) {
- return -1;
- }
- char prefix[256];
- snprintf(prefix, sizeof(prefix), "%s.stage.", db_basename);
- size_t prefix_len = strlen(prefix);
- int count = 0;
+ /* SQL DDL becomes first-class Table/View nodes wired into FROM/JOIN lineage,
+ * while the shared name registry must NOT leak those relations into other
+ * languages' textual resolution: a Python call or identifier sharing the
+ * table's name (`users`) would otherwise unique-name-bind a false CALLS/USAGE
+ * edge into the lineage layer. Pins the resolve-time relation veto
+ * (cbm_registry_resolve) together with the lineage opt-in
+ * (cbm_registry_resolve_lineage). */
+ TEST(pipeline_sql_lineage_and_relation_isolation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_sql_lineage_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "schema.sql",
+ "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);\n"
+ "CREATE VIEW active_users AS SELECT * FROM users;\n");
+ /* `users` exists project-wide ONLY as the SQL table, so without the
+ * relation veto the cross-file unique-name fallback would bind both the
+ * call and the bare reference below straight to the Table node. */
+ write_temp_file(tmp, "app.py",
+ "def load_users():\n"
+ " return users()\n"
+ "\n"
+ "def show_users():\n"
+ " return users\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/sql_lineage.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 view's FROM emits real lineage. */
+ ASSERT_EQ(named_edge_count(s, project, "USAGE", "active_users", "users"), 1);
+ /* Isolation: no Python edge of any kind reaches the Table. */
+ ASSERT_EQ(named_edge_count(s, project, "CALLS", "load_users", "users"), 0);
+ ASSERT_EQ(named_edge_count(s, project, "USAGE", "load_users", "users"), 0);
+ ASSERT_EQ(named_edge_count(s, project, "USAGE", "show_users", "users"), 0);
+ ASSERT_EQ(named_edge_count(s, project, "READS", "show_users", "users"), 0);
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* dbt lineage end-to-end. A dbt project's dependency structure lives entirely
+ * in Jinja ({{ ref('x') }}), which the SQL grammar cannot read, so this is the
+ * whole value: model -> model edges across files, plus the join onto a Table
+ * declared in ordinary DDL — Model and Table are both relation labels, so one
+ * lineage layer spans both. The Python file is the isolation control: `stg_orders`
+ * exists project-wide only as a dbt model, and the registry's relation veto must
+ * keep a same-named call out of the lineage layer. */
+ TEST(pipeline_dbt_jinja_lineage) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_dbt_lineage_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "raw_schema.sql", "CREATE TABLE customers (id INTEGER, name TEXT);\n");
+ write_temp_file(tmp, "stg_orders.sql",
+ "SELECT id, customer_id FROM {{ source('raw', 'customers') }}\n");
+ write_temp_file(tmp, "orders_enriched.sql",
+ "SELECT o.id, c.name\n"
+ "FROM {{ ref('stg_orders') }} o\n"
+ "JOIN {{ ref('stg_orders') }} c ON c.id = o.customer_id\n");
+ write_temp_file(tmp, "app.py", "def load():\n return stg_orders()\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/dbt.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);
+ /* model -> model: the ref() lineage the SQL grammar cannot see */
+ ASSERT_TRUE(named_edge_count(s, project, "USAGE", "orders_enriched", "stg_orders") >= 1);
+ /* model -> table: source() joining dbt onto plain DDL in the same repo */
+ ASSERT_EQ(named_edge_count(s, project, "USAGE", "stg_orders", "customers"), 1);
+ /* isolation: the Python call must not reach the model */
+ ASSERT_EQ(named_edge_count(s, project, "CALLS", "load", "stg_orders"), 0);
+ ASSERT_EQ(named_edge_count(s, project, "USAGE", "load", "stg_orders"), 0);
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Renaming a table must drop lineage from DEPENDENT (unchanged) SQL files on
+ * the incremental path. Table/View participate in the per-file LSP surface
+ * hash as registry-only labels (lsp_surface.c), so tables.sql's def change
+ * invalidates views.sql's resolution instead of slipping the early cutoff and
+ * leaving a stale view -> old-table USAGE edge. */
+ TEST(pipeline_incremental_sql_table_rename_drops_stale_lineage) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_sql_rename_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ write_temp_file(tmp, "tables.sql", "CREATE TABLE users (id INTEGER PRIMARY KEY);\n");
+ write_temp_file(tmp, "views.sql", "CREATE VIEW active AS SELECT * FROM users;\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/sql_rename.db", tmp);
+ cbm_pipeline_t *first = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(first);
+ ASSERT_EQ(cbm_pipeline_run(first), 0);
+ const char *first_project = cbm_pipeline_project_name(first);
+ cbm_store_t *first_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(first_store);
+ ASSERT_EQ(named_edge_count(first_store, first_project, "USAGE", "active", "users"), 1);
+ cbm_store_close(first_store);
+ cbm_pipeline_free(first);
+
+ write_temp_file(tmp, "tables.sql", "CREATE TABLE people (id INTEGER PRIMARY KEY);\n");
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *second = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(second);
+ ASSERT_EQ(cbm_pipeline_run(second), 0);
+ const char *second_project = cbm_pipeline_project_name(second);
+ cbm_store_t *second_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(second_store);
+ /* The view's FROM still says `users`, which no longer exists: the old
+ * edge must be gone (no stale lineage), and the unchanged dependent must
+ * not have been rebound to the renamed table either. */
+ ASSERT_EQ(named_edge_count(second_store, second_project, "USAGE", "active", "users"), 0);
+ ASSERT_EQ(named_edge_count(second_store, second_project, "USAGE", "active", "people"), 0);
+ cbm_store_close(second_store);
+ cbm_pipeline_free(second);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ /* Re-indexing only the caller must retain cross-file semantic proof for a
+ * callable value whose definition lives in an unchanged file. A fresh full
+ * index of the edited sources is the convergence oracle: incremental output
+ * must not downgrade the exact CALL_REFERENCE to a generic USAGE. */
+ TEST(pipeline_incremental_cross_file_call_reference_matches_fresh_full) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ref_cross_incr_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ static const char target_source[] = "export function importedIncrementalHandler(): void {}\n";
+ static const char initial_caller_source[] =
+ "import { importedIncrementalHandler } from './plugin';\n"
+ "function acceptIncrementalReference(callback: () => void): void {}\n"
+ "export function incrementalImportedArgument(): void {\n"
+ " acceptIncrementalReference(importedIncrementalHandler);\n"
+ "}\n";
+ static const char edited_caller_source[] =
+ "import { importedIncrementalHandler } from './plugin';\n"
+ "function acceptIncrementalReference(callback: () => void): void {}\n"
+ "export function incrementalImportedArgument(): void {\n"
+ " acceptIncrementalReference(importedIncrementalHandler);\n"
+ "}\n"
+ "// caller-only size-changing edit\n";
+
+ write_temp_file(tmp, "plugin.ts", target_source);
+ write_temp_file(tmp, "main.ts", initial_caller_source);
+
+ char incremental_db[512];
+ snprintf(incremental_db, sizeof(incremental_db), "%s/cross-reference-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",
+ "incrementalImportedArgument", "importedIncrementalHandler"),
+ 1);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "USAGE",
+ "incrementalImportedArgument", "importedIncrementalHandler"),
+ 0);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "CALLS",
+ "incrementalImportedArgument", "importedIncrementalHandler"),
+ 0);
+ cbm_store_close(baseline_store);
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "main.ts", edited_caller_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",
+ "incrementalImportedArgument", "importedIncrementalHandler");
+ int incremental_usage =
+ named_edge_count(incremental_store, incremental_project, "USAGE",
+ "incrementalImportedArgument", "importedIncrementalHandler");
+ int incremental_calls =
+ named_edge_count(incremental_store, incremental_project, "CALLS",
+ "incrementalImportedArgument", "importedIncrementalHandler");
+ cbm_store_close(incremental_store);
+ cbm_pipeline_free(incremental);
+
+ char full_db[512];
+ snprintf(full_db, sizeof(full_db), "%s/cross-reference-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", "incrementalImportedArgument",
+ "importedIncrementalHandler");
+ int full_usage = named_edge_count(full_store, full_project, "USAGE",
+ "incrementalImportedArgument", "importedIncrementalHandler");
+ int full_calls = named_edge_count(full_store, full_project, "CALLS",
+ "incrementalImportedArgument", "importedIncrementalHandler");
+ cbm_store_close(full_store);
+ cbm_pipeline_free(full);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(full_reference, 1);
+ ASSERT_EQ(full_usage, 0);
+ ASSERT_EQ(full_calls, 0);
+ ASSERT_EQ(incremental_reference, full_reference);
+ ASSERT_EQ(incremental_usage, full_usage);
+ ASSERT_EQ(incremental_calls, full_calls);
+ PASS();
+ }
+
+ /* A semantic control file can change an unchanged source file's exact target.
+ * Both target modules deliberately export the same short name: without the
+ * tsconfig path mapping, project-wide unique-name fallback is ambiguous and
+ * cannot make this test pass. The clean full index after the config-only edit
+ * is therefore an exact oracle for which module owns the CALL_REFERENCE.
+ *
+ * RED: incremental hashing tracks source inputs but not the semantic influence
+ * of tsconfig.json. Changing only the alias mapping leaves the same-DB graph
+ * pointed at target_a.ts while a fresh full index points at target_b.ts. */
+ /* ── Closure-repair routing matrix + convergence ─────────────────
+ *
+ * Every test asserts BOTH the route taken and equality with a fresh full
+ * index. Route equality matters because full-rebuild would satisfy any
+ * convergence assertion vacuously; graph equality matters because a wrong
+ * closure that still routes as CLOSURE_REPAIR is precisely the bug class
+ * this feature must never ship. */
+
+ static void closure_probe_repo(const char *tmp) {
+ write_temp_file(tmp, "lib.ts",
+ "export function closureProbeHelper(x: number): string {\n"
+ " return String(x);\n"
+ "}\n");
+ /* The callback-pass shape produces the exact-value CALL_REFERENCE edge
+ * (same idiom as the tsconfig alias convergence test). */
+ write_temp_file(tmp, "caller.ts",
+ "import { closureProbeHelper } from './lib';\n"
+ "function acceptClosureProbe(callback: (x: number) => string): void {\n"
+ " void callback;\n"
+ "}\n"
+ "export function closureProbeCaller(): void {\n"
+ " acceptClosureProbe(closureProbeHelper);\n"
+ "}\n");
+ write_temp_file(tmp, "bystander.ts",
+ "export function closureBystander(): number {\n"
+ " return 7;\n"
+ "}\n");
+ }
+
+ /* Fresh full reference build of the same tree into its own DB. */
+ static void closure_fresh_full(const char *tmp, const char *db_path, int *out_nodes, int *out_edges,
+ int *out_ref_edges, const char *project_hint) {
+ *out_nodes = -1;
+ *out_edges = -2;
+ *out_ref_edges = -3;
+ cbm_unlink(db_path);
+ cbm_remove_db_sidecars(db_path);
+ cbm_pipeline_t *full = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ if (!full) {
+ return;
+ }
+ int rc = cbm_pipeline_run(full);
+ const char *project = cbm_pipeline_project_name(full);
+ if (rc == 0) {
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ if (store) {
+ *out_nodes = cbm_store_count_nodes(store, project);
+ *out_edges = cbm_store_count_edges(store, project);
+ *out_ref_edges =
+ named_edge_to_file_count(store, project, "CALL_REFERENCE", "closureProbeCaller",
+ "closureProbeHelper", "lib.ts");
+ cbm_store_close(store);
+ }
+ }
+ (void)project_hint;
+ cbm_pipeline_free(full);
+ }
+
+ /* The manifest hash fans out across workers above a file-count threshold;
+ * below it the serial path runs. Byte-identity of the parallel build is
+ * what the exact no-op route stands on, so pin it with a repo big enough
+ * to take the parallel path on BOTH builds: unchanged bytes must route
+ * NOOP, and one changed file must still classify exactly. */
+ TEST(pipeline_parallel_manifest_is_byte_stable_above_threshold) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_par_manifest_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ for (int i = 0; i < 72; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "mod_%02d.py", i);
+ snprintf(body, sizeof(body), "def par_manifest_%02d():\n return %d\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ char db[512];
+ snprintf(db, sizeof(db), "%s/manifest.db", tmp);
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ cbm_pipeline_free(baseline);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *unchanged = cbm_pipeline_new(tmp, db, CBM_MODE_FULL);
+ 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);
+
+ write_temp_file(tmp, "mod_07.py", "def par_manifest_07():\n return 700\n");
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *edited = cbm_pipeline_new(tmp, db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(edited);
+ ASSERT_EQ(cbm_pipeline_run(edited), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+ cbm_pipeline_free(edited);
+ th_rmtree(tmp);
+ PASS();
+ }
+
+ TEST(pipeline_closure_repair_body_edit_converges_with_fresh_full) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_closure_body_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ closure_probe_repo(tmp);
+ char db[512];
+ snprintf(db, sizeof(db), "%s/closure.db", tmp);
+
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db, 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);
+
+ /* Body edit only: same exported surface, different body. */
+ write_temp_file(tmp, "lib.ts",
+ "export function closureProbeHelper(x: number): string {\n"
+ " const doubled = x + x;\n"
+ " return String(doubled);\n"
+ "}\n");
+
+ cbm_pipeline_t *incr = cbm_pipeline_new(tmp, db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incr);
+ ASSERT_EQ(cbm_pipeline_run(incr), 0);
+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(incr);
+ ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+
+ int repaired_nodes = -1;
+ int repaired_edges = -1;
+ int repaired_refs = -1;
+ cbm_store_t *store = cbm_store_open_path(db);
+ ASSERT_NOT_NULL(store);
+ repaired_nodes = cbm_store_count_nodes(store, project);
+ repaired_edges = cbm_store_count_edges(store, project);
+ repaired_refs = named_edge_to_file_count(store, project, "CALL_REFERENCE", "closureProbeCaller",
+ "closureProbeHelper", "lib.ts");
+ cbm_store_close(store);
+
+ char full_db[512];
+ snprintf(full_db, sizeof(full_db), "%s/reference-full.db", tmp);
+ int full_nodes;
+ int full_edges;
+ int full_refs;
+ closure_fresh_full(tmp, full_db, &full_nodes, &full_edges, &full_refs, project);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(repaired_refs, 1);
+ ASSERT_EQ(repaired_nodes, full_nodes);
+ ASSERT_EQ(repaired_edges, full_edges);
+ ASSERT_EQ(repaired_refs, full_refs);
+ PASS();
+ }
+
+ /* Removing a definition (no additions) keeps the closure route AND must drop
+ * the dependent's stale CALL_REFERENCE. This is the assertion legacy partial
+ * could never pass: its QN-keyed re-link resurrected yesterday's edge. */
+ TEST(pipeline_closure_repair_removed_def_drops_dependent_edge) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_closure_removed_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ closure_probe_repo(tmp);
+ char db[512];
+ snprintf(db, sizeof(db), "%s/closure.db", tmp);
+
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db, 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);
+
+ cbm_store_t *pre = cbm_store_open_path(db);
+ ASSERT_NOT_NULL(pre);
+ ASSERT_EQ(named_edge_to_file_count(pre, project, "CALL_REFERENCE", "closureProbeCaller",
+ "closureProbeHelper", "lib.ts"),
+ 1);
+ cbm_store_close(pre);
+
+ /* The helper vanishes; nothing is added. The caller keeps calling a name
+ * that no longer resolves anywhere. */
+ write_temp_file(tmp, "lib.ts", "export const closureProbeHelper = undefined;\n");
+
+ cbm_pipeline_t *incr = cbm_pipeline_new(tmp, db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incr);
+ ASSERT_EQ(cbm_pipeline_run(incr), 0);
+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(incr);
+
+ int repaired_refs = -1;
+ cbm_store_t *store = cbm_store_open_path(db);
+ ASSERT_NOT_NULL(store);
+ repaired_refs = named_edge_to_file_count(store, project, "CALL_REFERENCE", "closureProbeCaller",
+ "closureProbeHelper", "lib.ts");
+ int repaired_nodes = cbm_store_count_nodes(store, project);
+ int repaired_edges = cbm_store_count_edges(store, project);
+ cbm_store_close(store);
+
+ char full_db[512];
+ snprintf(full_db, sizeof(full_db), "%s/reference-full.db", tmp);
+ int full_nodes;
+ int full_edges;
+ int full_refs;
+ closure_fresh_full(tmp, full_db, &full_nodes, &full_edges, &full_refs, project);
+ th_rmtree(tmp);
+
+ /* Function def -> const def is a label/type change, not an added NAME, so
+ * the closure route must hold — and the stale edge must be gone. */
+ ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+ ASSERT_EQ(repaired_refs, full_refs);
+ ASSERT_EQ(repaired_nodes, full_nodes);
+ ASSERT_EQ(repaired_edges, full_edges);
+ PASS();
+ }
+
+ TEST(pipeline_closure_repair_added_name_declines_to_full) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_closure_added_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ closure_probe_repo(tmp);
+ char db[512];
+ snprintf(db, sizeof(db), "%s/closure.db", tmp);
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ cbm_pipeline_free(baseline);
+
+ /* A NEW name: yesterday's graph cannot know who would now resolve to
+ * it, so the planner must decline. */
+ write_temp_file(tmp, "lib.ts",
+ "export function closureProbeHelper(x: number): string {\n"
+ " return String(x);\n"
+ "}\n"
+ "export function closureProbeExtra(): number {\n"
+ " return 1;\n"
+ "}\n");
+ cbm_pipeline_t *incr = cbm_pipeline_new(tmp, db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incr);
+ ASSERT_EQ(cbm_pipeline_run(incr), 0);
+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(incr);
+ th_rmtree(tmp);
+ ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ PASS();
+ }
+
+ TEST(pipeline_closure_repair_new_file_declines_to_full) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_closure_newfile_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ closure_probe_repo(tmp);
+ char db[512];
+ snprintf(db, sizeof(db), "%s/closure.db", tmp);
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "newcomer.ts", "export function closureNewcomer(): void {}\n");
+ cbm_pipeline_t *incr = cbm_pipeline_new(tmp, db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incr);
+ ASSERT_EQ(cbm_pipeline_run(incr), 0);
+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(incr);
+ th_rmtree(tmp);
+ ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ PASS();
+ }
+
+ static int stem_index(const char *repo, const char *db) {
+ cbm_pipeline_t *p = cbm_pipeline_new(repo, db, CBM_MODE_FULL);
+ if (!p) {
+ return -1;
+ }
+ (void)cbm_pipeline_set_project_name(p, "stem");
+ cbm_pipeline_set_persistence(p, false);
+ int rc = cbm_pipeline_run(p);
+ cbm_pipeline_free(p);
+ return rc;
+ }
+
+ static void stem_unlink(const char *tmp, const char *rel) {
+ char path[512];
+ snprintf(path, sizeof(path), "%s/%s", tmp, rel);
+ (void)cbm_unlink(path);
+ }
+
+ /* Every collision shape of cbm_stem_marks_t, plus `fillers` plain scripts. */
+ static void stem_repo(const char *tmp, int fillers) {
+ write_temp_file(tmp, "genproto.sh", "#!/bin/sh\ngen_all() {\n echo all\n}\n");
+ write_temp_file(tmp, "genproto/one.sh", "#!/bin/sh\ngen_one() {\n echo one\n}\n");
+ write_temp_file(tmp, "rs/foo.rs", "pub mod bar;\npub fn top() {}\n");
+ write_temp_file(tmp, "rs/foo/bar.rs", "pub fn inner() {}\n");
+ write_temp_file(tmp, "c/foo.h", "int foo_add(int a, int b);\n");
+ write_temp_file(tmp, "c/foo.c", "#include \"foo.h\"\nint foo_add(int a, int b) { return a + b; }\n");
+ write_temp_file(tmp, "c/foo/x.c", "int foo_x(void) { return 1; }\n");
+ write_temp_file(tmp, "ts/foo.test.ts", "export function stemProbeA(): number { return 1; }\n");
+ write_temp_file(tmp, "ts/foo/test/a.ts", "export function stemProbeB(): number { return 2; }\n");
+ write_temp_file(tmp, "go.mod", "module example.com/stem\n\ngo 1.21\n");
+ write_temp_file(tmp, "goapi/api.sh", "#!/bin/sh\nrun_api() {\n echo api\n}\n");
+ write_temp_file(tmp, "goapi/api/server.go", "package api\n\nfunc Serve() {}\n");
+ write_temp_file(tmp, "goapi/main/main.go",
+ "package main\n\nimport \"example.com/stem/goapi/api\"\n\n"
+ "func main() { api.Serve() }\n");
+ for (int i = 0; i < fillers; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "fill/f%02d.sh", i);
+ snprintf(body, sizeof(body), "#!/bin/sh\nfill_%02d() {\n echo %d\n}\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ }
+
+ /* A file and the directory beside it with one stem (genproto.sh, genproto/)
+ * shared a QN, and the graph buffer kept only the Folder: the file's Module
+ * was lost. Now one side yields (cbm_stem_marks_t). The Folder is spelled
+ * `stem.genproto/` -- unless the directory is a Go package: it IS that
+ * package's module and Go imports land on it, so the file's Module yields as
+ * `stem.goapi.api#sh`. Rust's foo.rs beside foo/ and C's foo.h/foo.c stem pair
+ * keep their Module QNs; a dotted stem (foo.test.ts, foo/test/) collides by QN
+ * too. Run small (sequential extraction) and past MIN_FILES_FOR_PARALLEL
+ * (parallel workers), which insert Modules on separate paths. */
+ TEST(pipeline_stem_folder_collision_keeps_both_nodes) {
+ static const char *const checks[][2] = {
+ {"SELECT COUNT(*) FROM nodes WHERE label='Module' AND qualified_name='stem.genproto' AND "
+ "file_path='genproto.sh'",
+ "genproto.sh Module"},
+ {"SELECT COUNT(*) FROM nodes WHERE label='Folder' AND qualified_name='stem.genproto/' AND "
+ "file_path='genproto'",
+ "genproto/ Folder marked"},
+ {"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.type='CONTAINS_FILE' AND s.qualified_name='stem.genproto/' AND "
+ "t.file_path='genproto/one.sh'",
+ "marked Folder contains its file"},
+ {"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.type='DEFINES' AND s.label='File' AND "
+ "s.file_path='genproto.sh' AND t.label='Module' AND t.qualified_name='stem.genproto'",
+ "genproto.sh defines its Module"},
+ {"SELECT COUNT(*) FROM nodes WHERE label='Module' AND qualified_name='stem.rs.foo' AND "
+ "file_path='rs/foo.rs'",
+ "Rust foo.rs Module"},
+ {"SELECT COUNT(*) FROM nodes WHERE label='Module' AND qualified_name='stem.rs.foo.bar' AND "
+ "file_path='rs/foo/bar.rs'",
+ "Rust foo/bar.rs Module"},
+ {"SELECT COUNT(*) FROM nodes WHERE label='Folder' AND qualified_name='stem.rs.foo/'",
+ "rs/foo/ Folder marked"},
+ {"SELECT COUNT(*) FROM nodes WHERE label='Module' AND qualified_name='stem.c.foo'",
+ "C stem pair Module"},
+ {"SELECT COUNT(*) FROM nodes WHERE label='Folder' AND qualified_name='stem.c.foo/'",
+ "c/foo/ Folder marked"},
+ {"SELECT COUNT(*) FROM nodes WHERE label='Module' AND qualified_name='stem.ts.foo.test' AND "
+ "file_path='ts/foo.test.ts'",
+ "dotted foo.test.ts Module"},
+ {"SELECT COUNT(*) FROM nodes WHERE label='Folder' AND qualified_name='stem.ts.foo.test/'",
+ "ts/foo/test/ Folder marked"},
+ {"SELECT COUNT(*) FROM nodes WHERE label='Folder' AND qualified_name='stem.goapi.api'",
+ "Go package Folder keeps its QN"},
+ {"SELECT COUNT(*) FROM nodes WHERE label='Module' AND qualified_name='stem.goapi.api#sh' "
+ "AND file_path='goapi/api.sh'",
+ "api.sh Module beside the Go package"},
+ {"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.type='DEFINES' AND s.label='File' AND "
+ "s.file_path='goapi/api.sh' AND t.qualified_name='stem.goapi.api#sh'",
+ "api.sh defines its Module"},
+ {"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.type='IMPORTS' AND s.file_path='goapi/main/main.go' AND "
+ "t.label='Folder' AND t.qualified_name='stem.goapi.api'",
+ "Go import lands on the package Folder"},
+ };
+ enum { STEM_CHECKS = sizeof(checks) / sizeof(checks[0]) };
+ static const int fillers[] = {0, 60};
+ int got[2][STEM_CHECKS];
+ int rcs[2];
+ for (int run = 0; run < 2; run++) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_stemdir_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ stem_repo(tmp, fillers[run]);
+ char db[512];
+ snprintf(db, sizeof(db), "%s/stem.db", tmp);
+ rcs[run] = stem_index(tmp, db);
+ for (int c = 0; c < STEM_CHECKS; c++) {
+ got[run][c] = k8s_inc_count(db, checks[c][0]);
+ }
+ th_rmtree(tmp);
+ }
+ int wrong = 0;
+ for (int run = 0; run < 2; run++) {
+ ASSERT_EQ(rcs[run], 0);
+ for (int c = 0; c < STEM_CHECKS; c++) {
+ if (got[run][c] != 1) {
+ printf(" fillers=%d: %s: %d\n", fillers[run], checks[c][1], got[run][c]);
+ wrong++;
+ }
+ }
+ }
+ ASSERT_EQ(wrong, 0);
+ PASS();
+ }
+
+ /* A kustomization names a directory (`dashboards`) and the manifest beside it
+ * with the same stem (`dashboards.yaml`), as kubernetes/k8s.io does. The
+ * file's Module, once swallowed by the Folder, is a node now: the directory
+ * entry must still land on the (marked) Folder, the file entry on the file. */
+ TEST(pipeline_kustomize_entry_beside_same_stem_file) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_stemkust_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "monitoring/kustomization.yaml",
+ "apiVersion: kustomize.config.k8s.io/v1beta1\n"
+ "kind: Kustomization\n"
+ "resources:\n"
+ " - dashboards\n"
+ " - dashboards.yaml\n");
+ write_temp_file(tmp, "monitoring/dashboards.yaml",
+ "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: board\n");
+ write_temp_file(tmp, "monitoring/dashboards/kustomization.yaml",
+ "apiVersion: kustomize.config.k8s.io/v1beta1\n"
+ "kind: Kustomization\n"
+ "resources:\n"
+ " - cm.yaml\n");
+ write_temp_file(tmp, "monitoring/dashboards/cm.yaml",
+ "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: inner\n");
+ char db[512];
+ snprintf(db, sizeof(db), "%s/stemkust.db", tmp);
+ int rc = stem_index(tmp, db);
+ int to_dir = k8s_inc_count(
+ db, "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.type='IMPORTS' AND "
+ "s.file_path='monitoring/kustomization.yaml' AND t.label='Folder' AND "
+ "t.qualified_name='stem.monitoring.dashboards/'");
+ int to_file = k8s_inc_count(
+ db, "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.type='IMPORTS' AND "
+ "s.file_path='monitoring/kustomization.yaml' AND t.label='Module' AND "
+ "t.file_path='monitoring/dashboards.yaml'");
+ th_rmtree(tmp);
+ ASSERT_EQ(rc, 0);
+ ASSERT_EQ(to_dir, 1);
+ ASSERT_EQ(to_file, 1);
+ PASS();
+ }
+
+ /* Deleting a file that takes part in a stem collision changes which side
+ * carries the mark, and only a full rebuild re-spells the survivors, so the
+ * planner declines the closure repair: deleting genproto.sh frees the
+ * Folder's plain QN; deleting a Go package's only Go file leaves a plain
+ * directory, whose Folder then yields to api.sh's Module. A deletion away
+ * from every collision stays a closure repair. */
+ TEST(incremental_stem_mark_deletion_rebuilds) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_stemdel_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ closure_probe_repo(tmp);
+ write_temp_file(tmp, "genproto.sh", "#!/bin/sh\ngen_all() {\n echo all\n}\n");
+ write_temp_file(tmp, "genproto/one.sh", "#!/bin/sh\ngen_one() {\n echo one\n}\n");
+ write_temp_file(tmp, "goapi/api.sh", "#!/bin/sh\nrun_api() {\n echo api\n}\n");
+ write_temp_file(tmp, "goapi/api/server.go", "package api\n\nfunc Serve() {}\n");
+ write_temp_file(tmp, "goapi/api/run.sh", "#!/bin/sh\nrun_it() {\n echo run\n}\n");
+ write_temp_file(tmp, "misc/other.sh", "#!/bin/sh\nother() {\n echo other\n}\n");
+ char db[512];
+ snprintf(db, sizeof(db), "%s/stemdel.db", tmp);
+ static const char marked_dir[] =
+ "SELECT COUNT(*) FROM nodes WHERE label='Folder' AND qualified_name='stem.genproto/'";
+ static const char plain_dir[] =
+ "SELECT COUNT(*) FROM nodes WHERE label='Folder' AND qualified_name='stem.genproto'";
+ static const char go_side[] =
+ "SELECT COUNT(*) FROM nodes WHERE label='Module' AND qualified_name='stem.goapi.api#sh'";
+ static const char api_dir[] =
+ "SELECT COUNT(*) FROM nodes WHERE label='Folder' AND qualified_name='stem.goapi.api/'";
+ static const char api_mod[] = "SELECT COUNT(*) FROM nodes WHERE label='Module' AND "
+ "qualified_name='stem.goapi.api' AND file_path='goapi/api.sh'";
+
+ int full_rc = stem_index(tmp, db);
+ int full_marked = k8s_inc_count(db, marked_dir);
+ int full_go_side = k8s_inc_count(db, go_side);
+
+ stem_unlink(tmp, "misc/other.sh");
+ int other_rc = stem_index(tmp, db);
+ cbm_incremental_route_t other_route = cbm_pipeline_incremental_test_last_route();
+
+ stem_unlink(tmp, "genproto.sh");
+ int gen_rc = stem_index(tmp, db);
+ cbm_incremental_route_t gen_route = cbm_pipeline_incremental_test_last_route();
+ int gen_marked = k8s_inc_count(db, marked_dir);
+ int gen_plain = k8s_inc_count(db, plain_dir);
+
+ stem_unlink(tmp, "goapi/api/server.go");
+ int go_rc = stem_index(tmp, db);
+ cbm_incremental_route_t go_route = cbm_pipeline_incremental_test_last_route();
+ int go_side_after = k8s_inc_count(db, go_side);
+ int api_dir_after = k8s_inc_count(db, api_dir);
+ int api_mod_after = k8s_inc_count(db, api_mod);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(full_rc, 0);
+ ASSERT_EQ(full_marked, 1);
+ ASSERT_EQ(full_go_side, 1);
+ ASSERT_EQ(other_rc, 0);
+ ASSERT_EQ(other_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+ ASSERT_EQ(gen_rc, 0);
+ ASSERT_EQ(gen_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(gen_marked, 0);
+ ASSERT_EQ(gen_plain, 1);
+ ASSERT_EQ(go_rc, 0);
+ ASSERT_EQ(go_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(go_side_after, 0);
+ ASSERT_EQ(api_dir_after, 1);
+ ASSERT_EQ(api_mod_after, 1);
+ PASS();
+ }
+
+ /* The env join on a closure repair: a reader file edited, the join edges of
+ * the files the repair leaves alone come back from the store (their setters,
+ * image references and readers are proxies there), the edited file's are
+ * recomputed -- the same set a full build gives. */
+ TEST(incremental_env_join_repair_keeps_unchanged_pairs) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_envjoin_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ closure_probe_repo(tmp);
+ write_temp_file(tmp, "k8s/shop.yaml",
+ "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: shop\nspec:\n"
+ " template:\n spec:\n containers:\n - name: web\n"
+ " image: acme/web:1\n env:\n - name: PORT\n"
+ " value: \"8080\"\n - name: MODE\n"
+ " value: prod\n");
+ write_temp_file(tmp, "compose.yaml",
+ "services:\n web:\n image: acme/web:1\n build: ./web\n");
+ write_temp_file(tmp, "web/Dockerfile",
+ "FROM node:20\nCOPY src ./src\nCOPY lib ./lib\nCMD [\"node\", \"src/server.js\"]\n");
+ write_temp_file(tmp, "web/src/server.js",
+ "const port = process.env.PORT;\nconst mode = process.env.MODE;\n");
+ write_temp_file(tmp, "web/lib/conf.js", "module.exports = process.env.MODE;\n");
+ write_temp_file(tmp, "web/lib/more.js", "module.exports = process.env.PORT;\n");
+ write_temp_file(tmp, "misc/other.sh", "#!/bin/sh\nother() {\n echo other\n}\n");
+ char db[512];
+ snprintf(db, sizeof(db), "%s/envjoin.db", tmp);
+ static const char joins[] = "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id "
+ "WHERE e.type='CONFIGURES' AND s.label='EnvVar'";
+ #define ENVJOIN_PAIR(key, file) \
+ "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.type='CONFIGURES' AND s.label='EnvVar' AND s.qualified_name LIKE " \
+ "'%#env/web/" key "' AND t.file_path='" file "'"
+ static const char mode_server[] = ENVJOIN_PAIR("MODE", "web/src/server.js");
+ static const char mode_conf[] = ENVJOIN_PAIR("MODE", "web/lib/conf.js");
+ static const char port_server[] = ENVJOIN_PAIR("PORT", "web/src/server.js");
+ static const char port_more[] = ENVJOIN_PAIR("PORT", "web/lib/more.js");
+ #undef ENVJOIN_PAIR
+
+ int full_rc = stem_index(tmp, db);
+ int full_joins = k8s_inc_count(db, joins);
+ int full_mode_server = k8s_inc_count(db, mode_server);
+
+ write_temp_file(tmp, "web/src/server.js", "const port = process.env.PORT;\n");
+ int inc_rc = stem_index(tmp, db);
+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
+ int inc_joins = k8s_inc_count(db, joins);
+ int inc_mode_server = k8s_inc_count(db, mode_server);
+ int inc_mode_conf = k8s_inc_count(db, mode_conf);
+ int inc_port_server = k8s_inc_count(db, port_server);
+ int inc_port_more = k8s_inc_count(db, port_more);
+
+ /* a repair far from every image: each join edge joins two files the
+ * repair leaves alone, and is written again although both ends are
+ * pre-existing rows */
+ write_temp_file(tmp, "misc/other.sh", "#!/bin/sh\nother() {\n echo changed\n}\n");
+ int far_rc = stem_index(tmp, db);
+ cbm_incremental_route_t far_route = cbm_pipeline_incremental_test_last_route();
+ int far_joins = k8s_inc_count(db, joins);
+ int far_mode_conf = k8s_inc_count(db, mode_conf);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(full_rc, 0);
+ ASSERT_EQ(full_joins, 4);
+ ASSERT_EQ(full_mode_server, 1);
+ ASSERT_EQ(inc_rc, 0);
+ ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+ ASSERT_EQ(inc_joins, 3);
+ ASSERT_EQ(inc_mode_server, 0);
+ ASSERT_EQ(inc_mode_conf, 1);
+ ASSERT_EQ(inc_port_server, 1);
+ ASSERT_EQ(inc_port_more, 1);
+ ASSERT_EQ(far_rc, 0);
+ ASSERT_EQ(far_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+ ASSERT_EQ(far_joins, 3);
+ ASSERT_EQ(far_mode_conf, 1);
+ PASS();
+ }
+
+ /* A script's request to a compose service keeps the host in its Route on a
+ * repair as in a full run: the repair holds the compose services already
+ * (a full run makes them after the scripts), yet only a Kubernetes Service
+ * of the repository makes a Route path-only. */
+ TEST(incremental_script_request_to_compose_service_keeps_host) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_composeurl_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ closure_probe_repo(tmp);
+ write_temp_file(tmp, "compose.yaml", "services:\n web:\n image: acme/web:1\n");
+ write_temp_file(tmp, "hack/ping.sh", "#!/bin/sh\ncurl http://web:3000/x\n");
+ char db[512];
+ snprintf(db, sizeof(db), "%s/composeurl.db", tmp);
+ static const char kept[] = "SELECT COUNT(*) FROM nodes WHERE label='Route' AND "
+ "qualified_name='__route__GET__http://web:3000/y'";
+ static const char bare[] = "SELECT COUNT(*) FROM nodes WHERE label='Route' AND "
+ "qualified_name LIKE '__route__GET__/%'";
+ int full_rc = stem_index(tmp, db);
+ write_temp_file(tmp, "hack/ping.sh", "#!/bin/sh\ncurl http://web:3000/y\n");
+ int inc_rc = stem_index(tmp, db);
+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
+ int inc_kept = k8s_inc_count(db, kept);
+ int inc_bare = k8s_inc_count(db, bare);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(full_rc, 0);
+ ASSERT_EQ(inc_rc, 0);
+ ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+ ASSERT_EQ(inc_kept, 1);
+ ASSERT_EQ(inc_bare, 0);
+ PASS();
+ }
+
+ TEST(pipeline_closure_repair_budget_declines_to_full) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_closure_budget_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ closure_probe_repo(tmp);
+ for (int i = 0; i < 12; i++) {
+ char name[64];
+ char body[256];
+ snprintf(name, sizeof(name), "budget_%02d.ts", i);
+ snprintf(body, sizeof(body),
+ "export function closureBudget%02d(): number {\n return %d;\n}\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ for (int i = 0; i < 18; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "filler_%02d.ts", i);
+ snprintf(body, sizeof(body), "export const closureFiller%02d = %d;\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ char db[512];
+ snprintf(db, sizeof(db), "%s/closure.db", tmp);
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ cbm_pipeline_free(baseline);
+
+ /* Body-edit enough files to clear the absolute floor AND the percentage:
+ * 12 of 33 files is 36%% with 12 > CLOSURE_BUDGET_FLOOR_FILES, so the
+ * planner concedes to a full rebuild. */
+ for (int i = 0; i < 12; i++) {
+ char name[64];
+ char body[256];
+ snprintf(name, sizeof(name), "budget_%02d.ts", i);
+ snprintf(body, sizeof(body),
+ "export function closureBudget%02d(): number {\n return %d + 1;\n}\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+ cbm_pipeline_t *incr = cbm_pipeline_new(tmp, db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incr);
+ ASSERT_EQ(cbm_pipeline_run(incr), 0);
+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(incr);
+ th_rmtree(tmp);
+ ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ PASS();
+ }
+
+ TEST(pipeline_incremental_tsconfig_alias_change_matches_fresh_full) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ref_tsconfig_incr_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ static const char target_a_source[] = "export function semanticControlHandler(): void {\n"
+ " const selected = 'a';\n"
+ " void selected;\n"
+ "}\n";
+ static const char target_b_source[] = "export function semanticControlHandler(): void {\n"
+ " const selected = 'b';\n"
+ " void selected;\n"
+ "}\n";
+ static const char caller_source[] =
+ "import { semanticControlHandler } from '@semantic-target';\n"
+ "function acceptSemanticControl(callback: () => void): void {\n"
+ " void callback;\n"
+ "}\n"
+ "export function semanticControlCaller(): void {\n"
+ " acceptSemanticControl(semanticControlHandler);\n"
+ "}\n";
+ static const char initial_tsconfig[] =
+ "{\n"
+ " \"compilerOptions\": {\n"
+ " \"baseUrl\": \".\",\n"
+ " \"paths\": {\"@semantic-target\": [\"./target_a\"]}\n"
+ " }\n"
+ "}\n";
+ static const char replacement_tsconfig[] =
+ "{\n"
+ " \"compilerOptions\": {\n"
+ " \"baseUrl\": \".\",\n"
+ " \"paths\": {\"@semantic-target\": [\"./target_b\"]}\n"
+ " }\n"
+ "}\n";
+ static const char initial_jsconfig[] = "{\"compilerOptions\":{\"baseUrl\":\"./one\"}}\n";
+ static const char replacement_jsconfig[] = "{\"compilerOptions\":{\"baseUrl\":\"./two\"}}\n";
+ ASSERT_EQ(sizeof(initial_tsconfig), sizeof(replacement_tsconfig));
+ ASSERT_EQ(sizeof(initial_jsconfig), sizeof(replacement_jsconfig));
+
+ write_temp_file(tmp, "target_a.ts", target_a_source);
+ write_temp_file(tmp, "target_b.ts", target_b_source);
+ write_temp_file(tmp, "caller.ts", caller_source);
+ write_temp_file(tmp, "tsconfig.json", initial_tsconfig);
+ write_temp_file(tmp, "jsconfig.json", initial_jsconfig);
+ char tsconfig_path[512];
+ char jsconfig_path[512];
+ snprintf(tsconfig_path, sizeof(tsconfig_path), "%s/tsconfig.json", tmp);
+ snprintf(jsconfig_path, sizeof(jsconfig_path), "%s/jsconfig.json", tmp);
+ const time_t fixed_config_mtime = 1700000100;
+ ASSERT_EQ(pipeline_test_set_mtime(tsconfig_path, fixed_config_mtime, 222222222L), 0);
+ ASSERT_EQ(pipeline_test_set_mtime(jsconfig_path, fixed_config_mtime, 333333333L), 0);
+
+ char incremental_db[512];
+ snprintf(incremental_db, sizeof(incremental_db), "%s/tsconfig-reference-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_node_count(baseline_store, baseline_project, "semanticControlHandler"), 2);
+ ASSERT_EQ(named_edge_to_file_count(baseline_store, baseline_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler",
+ "target_a.ts"),
+ 1);
+ ASSERT_EQ(named_edge_to_file_count(baseline_store, baseline_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler",
+ "target_b.ts"),
+ 0);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "USAGE", "semanticControlCaller",
+ "semanticControlHandler"),
+ 0);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "CALLS", "semanticControlCaller",
+ "semanticControlHandler"),
+ 0);
+ cbm_file_hash_t selected_config_hash = {0};
+ ASSERT_EQ(cbm_store_get_file_hash(baseline_store, baseline_project, "tsconfig.json",
+ &selected_config_hash),
+ CBM_STORE_OK);
+ char expected_config_hash[CBM_SHA256_HEX_LEN + 1];
+ cbm_sha256_hex(initial_tsconfig, strlen(initial_tsconfig), expected_config_hash);
+ ASSERT_NOT_NULL(selected_config_hash.sha256);
+ ASSERT_STR_EQ(selected_config_hash.sha256, expected_config_hash);
+ cbm_store_clear_file_hash(&selected_config_hash);
+ cbm_file_hash_t unselected_config_hash = {0};
+ ASSERT_EQ(cbm_store_get_file_hash(baseline_store, baseline_project, "jsconfig.json",
+ &unselected_config_hash),
+ CBM_STORE_NOT_FOUND);
+ cbm_store_close(baseline_store);
+ cbm_pipeline_free(baseline);
+
+ /* The lower-priority jsconfig is not a semantic input while tsconfig is
+ * present in the same directory. Its byte change must remain a no-op. */
+ write_temp_file(tmp, "jsconfig.json", replacement_jsconfig);
+ ASSERT_EQ(pipeline_test_set_mtime(jsconfig_path, fixed_config_mtime, 333333333L), 0);
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *unselected = cbm_pipeline_new(tmp, incremental_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(unselected);
+ ASSERT_EQ(cbm_pipeline_run(unselected), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_NOOP);
+ cbm_pipeline_free(unselected);
+
+ /* The source files remain byte-for-byte unchanged; selected control bytes
+ * change at the same length and mtime. */
+ write_temp_file(tmp, "tsconfig.json", replacement_tsconfig);
+ ASSERT_EQ(pipeline_test_set_mtime(tsconfig_path, fixed_config_mtime, 222222222L), 0);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *incremental = cbm_pipeline_new(tmp, incremental_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incremental);
+ ASSERT_EQ(cbm_pipeline_run(incremental), 0);
+ /* Config-mediated retargeting is the closure route's hardest case: no
+ * source file changed, yet the caller's CALL_REFERENCE must move from
+ * target_a.ts to target_b.ts. Since alias-config governance landed this
+ * runs as a closure repair, and the convergence assertions below now
+ * prove that route rather than being satisfied by a full rebuild. */
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+ 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_a =
+ named_edge_to_file_count(incremental_store, incremental_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler", "target_a.ts");
+ int incremental_reference_b =
+ named_edge_to_file_count(incremental_store, incremental_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler", "target_b.ts");
+ int incremental_usage = named_edge_count(incremental_store, incremental_project, "USAGE",
+ "semanticControlCaller", "semanticControlHandler");
+ int incremental_calls = named_edge_count(incremental_store, incremental_project, "CALLS",
+ "semanticControlCaller", "semanticControlHandler");
+ cbm_store_close(incremental_store);
+ cbm_pipeline_free(incremental);
+
+ char full_db[512];
+ snprintf(full_db, sizeof(full_db), "%s/tsconfig-reference-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_a =
+ named_edge_to_file_count(full_store, full_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler", "target_a.ts");
+ int full_reference_b =
+ named_edge_to_file_count(full_store, full_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler", "target_b.ts");
+ int full_usage = named_edge_count(full_store, full_project, "USAGE", "semanticControlCaller",
+ "semanticControlHandler");
+ int full_calls = named_edge_count(full_store, full_project, "CALLS", "semanticControlCaller",
+ "semanticControlHandler");
+ cbm_store_close(full_store);
+ cbm_pipeline_free(full);
+ th_rmtree(tmp);
+
+ /* Prove the fresh oracle changed only because the alias now selects B. */
+ ASSERT_EQ(full_reference_a, 0);
+ ASSERT_EQ(full_reference_b, 1);
+ ASSERT_EQ(full_usage, 0);
+ ASSERT_EQ(full_calls, 0);
+
+ /* Incremental output must converge exactly on the fresh target and kind. */
+ ASSERT_EQ(incremental_reference_a, full_reference_a);
+ ASSERT_EQ(incremental_reference_b, full_reference_b);
+ ASSERT_EQ(incremental_usage, full_usage);
+ ASSERT_EQ(incremental_calls, full_calls);
+ PASS();
+ }
+
+ #if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ static int read_published_generation(const char *db_path, char *out, size_t out_size) {
+ cbm_store_t *store = cbm_store_open_path_query(db_path);
+ if (!store) {
+ return CBM_STORE_ERR;
+ }
+ int rc = cbm_store_generation(store, out, out_size);
+ cbm_store_close(store);
+ return rc;
+ }
+
+ static bool split_published_generation(const char *generation, char uid[18],
+ unsigned long long *mutation) {
+ if (!generation || strlen(generation) < 19 || generation[0] != 'u' || generation[17] != 'g') {
+ return false;
+ }
+ memcpy(uid, generation, 17);
+ uid[17] = '\0';
+ char *end = NULL;
+ unsigned long long parsed = strtoull(generation + 18, &end, 10);
+ if (!end || end == generation + 18 || *end != '\0') {
+ return false;
+ }
+ *mutation = parsed;
+ return true;
+ }
+
+ /* Every published database must carry cursor-generation metadata. A complete
+ * replacement gets a fresh database identity; an isolated delta clones the
+ * live database and advances only its mutation counter. */
+ TEST(pipeline_publication_stamps_full_and_delta_generations) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_cursor_generation_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def PublishedGeneration():\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_FAST);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ cbm_pipeline_free(baseline);
+ char first[128];
+ ASSERT_EQ(read_published_generation(db_path, first, sizeof(first)), CBM_STORE_OK);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *replacement = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(replacement);
+ ASSERT_EQ(cbm_pipeline_run(replacement), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ cbm_pipeline_free(replacement);
+ char second[128];
+ ASSERT_EQ(read_published_generation(db_path, second, sizeof(second)), CBM_STORE_OK);
+
+ write_temp_file(tmp, "generation.py", "def PublishedGeneration():\n return 2\n");
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *delta = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(delta);
+ ASSERT_EQ(cbm_pipeline_run(delta), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
+ cbm_pipeline_free(delta);
+ char third[128];
+ ASSERT_EQ(read_published_generation(db_path, third, sizeof(third)), CBM_STORE_OK);
+
+ char first_uid[18];
+ char second_uid[18];
+ char third_uid[18];
+ unsigned long long first_mutation = 0;
+ unsigned long long second_mutation = 0;
+ unsigned long long third_mutation = 0;
+ ASSERT_TRUE(split_published_generation(first, first_uid, &first_mutation));
+ ASSERT_TRUE(split_published_generation(second, second_uid, &second_mutation));
+ ASSERT_TRUE(split_published_generation(third, third_uid, &third_mutation));
+ ASSERT_TRUE(strcmp(first_uid, second_uid) != 0);
+ ASSERT_STR_EQ(second_uid, third_uid);
+ ASSERT_TRUE(third_mutation > second_mutation);
+ th_rmtree(tmp);
+ cbm_pipeline_incremental_test_reset_faults();
+ PASS();
+ }
+
+ static void observe_named_generation(const char *db_path, const char *project,
+ const char *before_name, const char *after_name,
+ int *before_count, int *after_count) {
+ *before_count = -1;
+ *after_count = -1;
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ if (!store) {
+ return;
+ }
+ *before_count = named_node_count(store, project, before_name);
+ *after_count = named_node_count(store, project, after_name);
+ cbm_store_close(store);
+ }
+
+ static int count_generation_stage_artifacts(const char *dir_path, const char *db_basename) {
+ cbm_dir_t *dir = cbm_opendir(dir_path);
+ if (!dir) {
+ return -1;
+ }
+ char prefix[256];
+ snprintf(prefix, sizeof(prefix), "%s.stage.", db_basename);
+ size_t prefix_len = strlen(prefix);
+ int count = 0;
+ cbm_dirent_t *entry;
+ while ((entry = cbm_readdir(dir)) != NULL) {
+ if (strncmp(entry->name, prefix, prefix_len) == 0) {
+ count++;
+ }
+ }
+ cbm_closedir(dir);
+ return count;
+ }
+
+ typedef struct {
+ const char *path;
+ const char *replacement;
+ int write_rc;
+ } manifest_race_mutation_t;
+
+ static void mutate_semantic_input_before_final_manifest(void *userdata) {
+ manifest_race_mutation_t *mutation = (manifest_race_mutation_t *)userdata;
+ mutation->write_rc = th_write_file(mutation->path, mutation->replacement);
+ }
+
+ TEST(pipeline_late_source_limit_preserves_previous_generation) {
+ char *repo = th_mktempdir("cbm_pipeline_late_limit");
+ ASSERT_NOT_NULL(repo);
+ ASSERT_EQ(th_write_file(TH_PATH(repo, "first.c"), "int first;\n"), 0);
+ char db_path[512];
+ char late_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/index.db", repo);
+ snprintf(late_path, sizeof(late_path), "%s/late.py", repo);
+
+ manifest_race_mutation_t mutation = {
+ .path = late_path,
+ .replacement = "late = 2\n",
+ .write_rc = -1,
+ };
+ cbm_pipeline_incremental_test_before_final_manifest_once(
+ mutate_semantic_input_before_final_manifest, &mutation);
+ cbm_pipeline_t *pipeline = cbm_pipeline_new(repo, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(pipeline);
+ cbm_index_resource_policy_t policy;
+ cbm_index_policy_init(&policy);
+ policy.max_files = (cbm_index_limit_u64_t){.enabled = true, .value = 1};
+ cbm_pipeline_set_resource_policy(pipeline, &policy);
+ int rc = cbm_pipeline_run(pipeline);
+ cbm_index_resource_violation_t violation = {0};
+ cbm_pipeline_get_resource_violation(pipeline, &violation);
+ cbm_pipeline_free(pipeline);
+ cbm_pipeline_incremental_test_reset_faults();
+
+ ASSERT_EQ(mutation.write_rc, 0);
+ ASSERT_EQ(rc, CBM_PIPELINE_RESOURCE_LIMIT);
+ ASSERT_EQ(violation.resource, CBM_INDEX_RESOURCE_FILES);
+ ASSERT_EQ(violation.observed, 2);
+ ASSERT_EQ(violation.limit, 1);
+ ASSERT_FALSE(cbm_file_exists(db_path));
+ th_cleanup(repo);
+ PASS();
+ }
+
+ /* A graph and its exact manifest are one generation. If source bytes change
+ * after extraction but before publication, the mixed generation must be
+ * rejected and the previous live DB preserved. */
+ TEST(pipeline_source_mutation_before_publication_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_generation_race_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ char source_path[512];
+ char db_path[512];
+ snprintf(source_path, sizeof(source_path), "%s/generation.py", tmp);
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ ASSERT_EQ(th_write_file(source_path, "def StableGeneration():\n return 1\n"), 0);
+
+ 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);
+
+ ASSERT_EQ(th_write_file(source_path, "def ExtractedGeneration():\n return 2\n"), 0);
+ manifest_race_mutation_t mutation = {
+ .path = source_path,
+ .replacement = "def FinalGeneration():\n return 3\n",
+ .write_rc = -1,
+ };
+ cbm_pipeline_incremental_test_before_final_manifest_once(
+ mutate_semantic_input_before_final_manifest, &mutation);
+ cbm_pipeline_t *raced = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(raced);
+ int raced_rc = cbm_pipeline_run(raced);
+ cbm_pipeline_free(raced);
+ int raced_stable = -1;
+ int raced_extracted = -1;
+ observe_named_generation(db_path, project, "StableGeneration", "ExtractedGeneration",
+ &raced_stable, &raced_extracted);
+ int raced_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+
+ 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_stable = -1;
+ int retry_final = -1;
+ observe_named_generation(db_path, project, "StableGeneration", "FinalGeneration", &retry_stable,
+ &retry_final);
+ int retry_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(mutation.write_rc, 0);
+ ASSERT_EQ(raced_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(raced_stable, 1);
+ ASSERT_EQ(raced_extracted, 0);
+ ASSERT_EQ(raced_stage_count, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_stable, 0);
+ ASSERT_EQ(retry_final, 1);
+ ASSERT_EQ(retry_stage_count, 0);
+ PASS();
+ }
+
+ /* Publication must never write through a name another local process can
+ * predict. The staging database used to be "<db>.stage.<pid>.<counter>",
+ * which anyone can compute in advance; publication then unlinked that name
+ * and wrote it, so a symlink planted in the gap redirects the write to a
+ * target of the attacker's choosing.
+ *
+ * Winning that timing window is not something a test should attempt -- a
+ * test that has to win a race is a coin flip, not a gate. The property that
+ * REMOVES the window is deterministic: publication must not touch any
+ * predictable name at all. Canaries occupy every name the old scheme could
+ * have picked, and all must survive. Against the old code exactly one is
+ * consumed, whichever serial the counter had reached.
+ *
+ * This calls cbm_pipeline_publish_generation directly. The only in-tree
+ * caller sits behind CBM_INCREMENTAL_TEST_API, so going through the pipeline
+ * would never reach the code under test. */
+ TEST(pipeline_publication_never_uses_a_predictable_staging_path) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_predictable_stage_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ enum { PREDICTABLE_CANARIES = 32 };
+ static const char canary[] = "canary-must-survive\n";
+ char canary_path[PREDICTABLE_CANARIES][640];
+ for (int i = 0; i < PREDICTABLE_CANARIES; i++) {
+ snprintf(canary_path[i], sizeof(canary_path[i]), "%s.stage.%ld.%d", db_path, (long)getpid(),
+ i + 1);
+ ASSERT_EQ(th_write_file(canary_path[i], canary), 0);
+ }
+
+ cbm_gbuf_t *gb = cbm_gbuf_new("predictable-stage-proj", tmp);
+ ASSERT_NOT_NULL(gb);
+ cbm_pipeline_generation_t generation = {
+ .gbuf = gb,
+ .final_db_path = db_path,
+ .project = "predictable-stage-proj",
+ .cancelled = NULL,
+ .manifest = NULL,
+ .manifest_count = 0,
+ .adr_content = NULL,
+ .coverage = NULL,
+ .coverage_count = 0,
+ };
+ int publish_rc = cbm_pipeline_publish_generation(&generation);
+ cbm_gbuf_free(gb);
+
+ int survived = 0;
+ int intact = 0;
+ for (int i = 0; i < PREDICTABLE_CANARIES; i++) {
+ FILE *f = cbm_fopen(canary_path[i], "rb");
+ if (!f) {
+ continue;
+ }
+ survived++;
+ char buf[64] = {0};
+ size_t n = fread(buf, 1, sizeof(buf) - 1, f);
+ (void)fclose(f);
+ if (n == strlen(canary) && memcmp(buf, canary, n) == 0) {
+ intact++;
+ }
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(publish_rc, 0);
+ /* Not one may be unlinked, truncated, or written through. */
+ ASSERT_EQ(survived, PREDICTABLE_CANARIES);
+ ASSERT_EQ(intact, PREDICTABLE_CANARIES);
+ PASS();
+ }
+
+ static int count_substring(const char *haystack, const char *needle) {
+ int count = 0;
+ size_t needle_len = strlen(needle);
+ for (const char *at = strstr(haystack, needle); at; at = strstr(at + needle_len, needle)) {
+ count++;
+ }
+ return count;
+ }
+
+ static int count_nested_stage_entries(const char *dir_path, const char *db_basename) {
+ cbm_dir_t *dir = cbm_opendir(dir_path);
+ if (!dir) {
+ return -1;
+ }
+ size_t base_len = strlen(db_basename);
+ int count = 0;
+ cbm_dirent_t *entry;
+ while ((entry = cbm_readdir(dir)) != NULL) {
+ if (strncmp(entry->name, db_basename, base_len) == 0 &&
+ count_substring(entry->name + base_len, ".stage.") >= 2) {
+ count++;
+ }
+ }
+ cbm_closedir(dir);
+ return count;
+ }
+
+ /* #1839: the outer run rewrites the pipeline's db_path to its stage, so the
+ * inner publication (dump or delta clone) minted ITS stage from a stage:
+ * <db>.stage.A.stage.B, plus -wal/-shm under WAL. A generation's stage is a
+ * sibling of the live database, whichever path it is minted from; a database
+ * whose own basename merely contains ".stage." is not a stage and keeps its
+ * full name. */
+ TEST(pipeline_stage_names_never_nest) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_stage_nesting_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ char odd_db[512];
+ snprintf(odd_db, sizeof(odd_db), "%s/x.stage.y.db", tmp);
+
+ char *outer = cbm_pipeline_create_staging_path(db_path);
+ ASSERT_NOT_NULL(outer);
+ char *inner = cbm_pipeline_create_staging_path(outer);
+ ASSERT_NOT_NULL(inner);
+ char *odd_stage = cbm_pipeline_create_staging_path(odd_db);
+ ASSERT_NOT_NULL(odd_stage);
+
+ size_t db_len = strlen(db_path);
+ size_t odd_len = strlen(odd_db);
+ int outer_tokens = count_substring(outer, ".stage.");
+ int inner_tokens = count_substring(inner, ".stage.");
+ bool inner_is_sibling =
+ strncmp(inner, db_path, db_len) == 0 && strncmp(inner + db_len, ".stage.", 7) == 0;
+ bool inner_distinct = strcmp(inner, outer) != 0;
+ bool odd_keeps_basename =
+ strncmp(odd_stage, odd_db, odd_len) == 0 && strncmp(odd_stage + odd_len, ".stage.", 7) == 0;
+ int nested_entries = count_nested_stage_entries(tmp, "generation.db");
+
+ cbm_pipeline_discard_stage(inner);
+ cbm_pipeline_discard_stage(outer);
+ cbm_pipeline_discard_stage(odd_stage);
+ int leftover_entries = count_generation_stage_artifacts(tmp, "generation.db") +
+ count_generation_stage_artifacts(tmp, "x.stage.y.db");
+ free(inner);
+ free(outer);
+ free(odd_stage);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(outer_tokens, 1);
+ ASSERT_EQ(inner_tokens, 1);
+ ASSERT_TRUE(inner_is_sibling);
+ ASSERT_TRUE(inner_distinct);
+ ASSERT_TRUE(odd_keeps_basename);
+ ASSERT_EQ(nested_entries, 0);
+ ASSERT_EQ(leftover_entries, 0);
+ PASS();
+ }
+
+ static bool path_exists(const char *path) {
+ cbm_path_info_t info;
+ return cbm_path_info_utf8(path, &info) == CBM_PATH_INFO_OK;
+ }
+
+ /* #1839: a minted stage is OWNED through an exclusive kernel lock on its
+ * "<stage>.lock" sidecar for exactly as long as the stage exists. A second
+ * holder cannot take it while the writer is live; discarding the stage frees
+ * the name and removes the sidecar, so nothing stays behind. */
+ TEST(pipeline_minted_stage_is_owned_until_released) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_stage_owner_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ char *stage = cbm_pipeline_create_staging_path(db_path);
+ ASSERT_NOT_NULL(stage);
+ char lock_path[600];
+ snprintf(lock_path, sizeof(lock_path), "%s.lock", stage);
+ bool lock_present_while_live = path_exists(lock_path);
+ int hold_while_live = cbm_pipeline_stage_lock_hold(stage);
+ if (hold_while_live >= 0) {
+ cbm_pipeline_stage_lock_drop(stage, hold_while_live);
+ }
+
+ cbm_pipeline_discard_stage(stage);
+ bool stage_gone = !path_exists(stage);
+ bool lock_gone = !path_exists(lock_path);
+
+ int hold_after_discard = cbm_pipeline_stage_lock_hold(stage);
+ int second_holder = cbm_pipeline_stage_lock_hold(stage);
+ if (second_holder >= 0) {
+ cbm_pipeline_stage_lock_drop(stage, second_holder);
+ }
+ cbm_pipeline_stage_lock_drop(stage, hold_after_discard);
+ int hold_after_drop = cbm_pipeline_stage_lock_hold(stage);
+ cbm_pipeline_stage_lock_drop(stage, hold_after_drop);
+ int leftovers = count_generation_stage_artifacts(tmp, "generation.db");
+ free(stage);
+ th_rmtree(tmp);
+
+ ASSERT_TRUE(lock_present_while_live);
+ ASSERT_EQ(hold_while_live, -1);
+ ASSERT_TRUE(stage_gone);
+ ASSERT_TRUE(lock_gone);
+ ASSERT_TRUE(hold_after_discard >= 0);
+ ASSERT_EQ(second_holder, -1);
+ ASSERT_TRUE(hold_after_drop >= 0);
+ ASSERT_EQ(leftovers, 0);
+ PASS();
+ }
+
+ static bool file_has_content(const char *path, const char *expected) {
+ FILE *f = cbm_fopen(path, "rb");
+ if (!f) {
+ return false;
+ }
+ char buf[256] = {0};
+ size_t n = fread(buf, 1, sizeof(buf) - 1, f);
+ (void)fclose(f);
+ return n == strlen(expected) && memcmp(buf, expected, n) == 0;
+ }
+
+ /* #1839 / #1864: a stage a dead writer left beside a VALID database is swept
+ * by the next run and never influences its route. The 0-byte shape is what a
+ * worker killed before its backup wrote a page leaves behind; a stale -shm
+ * beside it is swept with it. */
+ TEST(pipeline_stale_zero_byte_stage_beside_valid_db_routes_incremental_and_is_swept) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_stale_stage_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def StableGeneration():\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);
+
+ char stale_stage[600];
+ char stale_shm[600];
+ snprintf(stale_stage, sizeof(stale_stage), "%s.stage.deadbe", db_path);
+ snprintf(stale_shm, sizeof(stale_shm), "%s.stage.deadbe-shm", db_path);
+ ASSERT_EQ(th_write_file(stale_stage, ""), 0);
+ ASSERT_EQ(th_write_file(stale_shm, "stale-shm"), 0);
+
+ /* A body-only change: no added names, so the planner may repair. */
+ write_temp_file(tmp, "generation.py", "def StableGeneration():\n return 2\n");
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *incr = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incr);
+ int incr_rc = cbm_pipeline_run(incr);
+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(incr);
+
+ bool stale_stage_gone = !path_exists(stale_stage);
+ bool stale_shm_gone = !path_exists(stale_shm);
+ int stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ int stable_count = -1;
+ int absent_count = -1;
+ observe_named_generation(db_path, project, "StableGeneration", "NeverDefined", &stable_count,
+ &absent_count);
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(incr_rc, 0);
+ ASSERT_TRUE(route != CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_TRUE(route != CBM_INCREMENTAL_ROUTE_NONE);
+ ASSERT_TRUE(stale_stage_gone);
+ ASSERT_TRUE(stale_shm_gone);
+ ASSERT_EQ(stage_count, 0);
+ ASSERT_EQ(stable_count, 1);
+ ASSERT_EQ(absent_count, 0);
+ PASS();
+ }
+
+ /* A killed run cleans up nothing, and until 2026-09-18 its staging database was
+ * reclaimed only when THAT project was indexed again: a kernel index killed by
+ * the OOM killer left ~15 GB parked until someone re-indexed the kernel, and
+ * indefinitely if nobody ever did. Indexing ANY project now reclaims the
+ * orphans of every project sharing that cache directory -- while the lock probe
+ * still keeps a LIVE writer's stage, whichever project owns it. */
+ TEST(pipeline_sweep_reclaims_orphans_of_other_projects_and_keeps_their_live_stages) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_stage_sweep_other_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def StableGeneration():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/mine.db", tmp);
+
+ /* Two stages of a DIFFERENT project sharing the cache directory: one whose
+ * writer died (nothing holds its lock) and one whose writer is alive. */
+ char other_dead[600];
+ char other_dead_wal[600];
+ char other_live[600];
+ snprintf(other_dead, sizeof(other_dead), "%s/other.db.stage.cccccc", tmp);
+ snprintf(other_dead_wal, sizeof(other_dead_wal), "%s/other.db.stage.cccccc-wal", tmp);
+ snprintf(other_live, sizeof(other_live), "%s/other.db.stage.dddddd", tmp);
+ static const char other_live_bytes[] = "other-project-live-bytes";
+ ASSERT_EQ(th_write_file(other_dead, "other-project-dead-bytes"), 0);
+ ASSERT_EQ(th_write_file(other_dead_wal, "other-project-dead-wal"), 0);
+ ASSERT_EQ(th_write_file(other_live, other_live_bytes), 0);
+ int other_live_fd = cbm_pipeline_stage_lock_hold(other_live);
+ ASSERT_TRUE(other_live_fd >= 0);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *mine = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(mine);
+ ASSERT_EQ(cbm_pipeline_run(mine), 0);
+ cbm_pipeline_free(mine);
+
+ bool dead_gone = !path_exists(other_dead);
+ bool dead_wal_gone = !path_exists(other_dead_wal);
+ bool live_kept = file_has_content(other_live, other_live_bytes);
+ cbm_pipeline_stage_lock_drop(other_live, other_live_fd);
+
+ ASSERT_TRUE(dead_gone); /* reclaimed even though it belongs to "other" */
+ ASSERT_TRUE(dead_wal_gone); /* sidecars go with their stage */
+ ASSERT_TRUE(live_kept); /* another project's LIVE stage is untouched */
+ PASS();
+ }
+
+ /* #1839: the sweep removes exactly the stages nobody owns. A dead writer's
+ * stage (main, -wal, and the unlocked .lock sidecar its death left) goes; a
+ * stage whose writer is LIVE -- here the test, holding its lock -- is kept
+ * byte for byte, and goes only once that lock is dropped. No timing: liveness
+ * is the kernel lock, nothing else. */
+ TEST(pipeline_sweep_removes_dead_writer_stage_keeps_locked_stage) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_stage_sweep_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def StableGeneration():\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);
+
+ char dead_stage[600];
+ char dead_wal[600];
+ char dead_lock[600];
+ char live_stage[600];
+ char live_lock[600];
+ snprintf(dead_stage, sizeof(dead_stage), "%s.stage.aaaaaa", db_path);
+ snprintf(dead_wal, sizeof(dead_wal), "%s.stage.aaaaaa-wal", db_path);
+ snprintf(dead_lock, sizeof(dead_lock), "%s.stage.aaaaaa.lock", db_path);
+ snprintf(live_stage, sizeof(live_stage), "%s.stage.bbbbbb", db_path);
+ snprintf(live_lock, sizeof(live_lock), "%s.stage.bbbbbb.lock", db_path);
+ static const char live_bytes[] = "live-stage-bytes";
+ ASSERT_EQ(th_write_file(dead_stage, "dead-stage-bytes"), 0);
+ ASSERT_EQ(th_write_file(dead_wal, "dead-wal"), 0);
+ ASSERT_EQ(th_write_file(dead_lock, ""), 0);
+ ASSERT_EQ(th_write_file(live_stage, live_bytes), 0);
+ int live_fd = cbm_pipeline_stage_lock_hold(live_stage);
+ ASSERT_TRUE(live_fd >= 0);
+
+ write_temp_file(tmp, "generation.py", "def StableGeneration():\n return 2\n");
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *first = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(first);
+ int first_rc = cbm_pipeline_run(first);
+ cbm_pipeline_free(first);
+
+ bool dead_stage_gone = !path_exists(dead_stage);
+ bool dead_wal_gone = !path_exists(dead_wal);
+ bool dead_lock_gone = !path_exists(dead_lock);
+ bool live_kept = file_has_content(live_stage, live_bytes);
+ bool live_lock_kept = path_exists(live_lock);
+ int stable_after_first = -1;
+ int absent_after_first = -1;
+ observe_named_generation(db_path, project, "StableGeneration", "NeverDefined",
+ &stable_after_first, &absent_after_first);
+
+ cbm_pipeline_stage_lock_drop(live_stage, live_fd);
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *second = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(second);
+ int second_rc = cbm_pipeline_run(second);
+ cbm_pipeline_free(second);
+
+ bool live_gone = !path_exists(live_stage);
+ bool live_lock_gone = !path_exists(live_lock);
+ int stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ int stable_after_second = -1;
+ int absent_after_second = -1;
+ observe_named_generation(db_path, project, "StableGeneration", "NeverDefined",
+ &stable_after_second, &absent_after_second);
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(first_rc, 0);
+ ASSERT_TRUE(dead_stage_gone);
+ ASSERT_TRUE(dead_wal_gone);
+ ASSERT_TRUE(dead_lock_gone);
+ ASSERT_TRUE(live_kept);
+ ASSERT_TRUE(live_lock_kept);
+ ASSERT_EQ(stable_after_first, 1);
+ ASSERT_EQ(absent_after_first, 0);
+ ASSERT_EQ(second_rc, 0);
+ ASSERT_TRUE(live_gone);
+ ASSERT_TRUE(live_lock_gone);
+ ASSERT_EQ(stage_count, 0);
+ ASSERT_EQ(stable_after_second, 1);
+ ASSERT_EQ(absent_after_second, 0);
+ PASS();
+ }
+
+ /* #2111 create->register TOCTOU guard. The bug this pins: create_staging_path()
+ * used to make the stage's main file visible (via mkstemp) BEFORE taking its
+ * sidecar lock, and sweep_orphan_stages() treats an absent lock sidecar
+ * (ENOENT) as a confirmed-dead writer (kernel released the lock on death). So a
+ * second, concurrent cbm_pipeline_run() against the SAME final_path, landing
+ * its own sweep in that narrow unlocked window, removed the first run's
+ * in-flight stage out from under it: every extraction pass still completed
+ * (none touch the stage file on disk), but the publish that followed found its
+ * own stage gone. Two writers racing the same project is a real scenario this
+ * PR's own sweep exists to clean up after (auto_index; the recently-fixed
+ * stale-rendezvous-recovery retry path) -- not hypothetical, and exactly the
+ * shape of #2111's windows-guards red (every pass logged success, nothing was
+ * ever committed, "Pipeline failed" surfaced generic; on Windows the sidecar
+ * collision surfaced as EACCES/errno=13).
+ *
+ * The fix takes the sidecar lock BEFORE the main file becomes visible, so this
+ * hook -- fired the instant the main file exists -- finds the stage already
+ * lock-protected and the racing sweep keeps it. The hook fires at the same
+ * point under the old ordering, where the lock was NOT yet held, so this test
+ * goes RED if that ordering ever regresses.
+ *
+ * The racing run is cancelled immediately so it never reaches ITS OWN
+ * publish -- isolating the sweep's effect on the first run's stage from the
+ * separate question of two full runs both completing for the same project. */
+ typedef struct {
+ const char *tmp_dir;
+ const char *db_path;
+ bool stage_survived;
+ } racing_sweep_arg_t;
+
+ static bool find_sole_stage_path(const char *dir, const char *db_basename, char *out,
+ size_t out_sz) {
+ cbm_dir_t *d = cbm_opendir(dir);
+ if (!d) {
+ return false;
+ }
+ char prefix[256];
+ snprintf(prefix, sizeof(prefix), "%s.stage.", db_basename);
+ size_t prefix_len = strlen(prefix);
+ bool found = false;
cbm_dirent_t *entry;
- while ((entry = cbm_readdir(dir)) != NULL) {
- if (strncmp(entry->name, prefix, prefix_len) == 0) {
- count++;
+ while ((entry = cbm_readdir(d)) != NULL) {
+ size_t name_len = strlen(entry->name);
+ enum { STAGE_SUFFIX_RANDOM_CHARS = 6 }; /* mirrors CBM_STAGE_SUFFIX_RANDOM_CHARS */
+ if (strncmp(entry->name, prefix, prefix_len) == 0 &&
+ name_len == prefix_len + STAGE_SUFFIX_RANDOM_CHARS) {
+ snprintf(out, out_sz, "%s/%s", dir, entry->name);
+ found = true;
+ break;
+ }
+ }
+ cbm_closedir(d);
+ return found;
+ }
+
+ static void *racing_sweep_thread(void *arg) {
+ racing_sweep_arg_t *a = (racing_sweep_arg_t *)arg;
+ cbm_pipeline_t *p = cbm_pipeline_new(a->tmp_dir, a->db_path, CBM_MODE_FULL);
+ if (p) {
+ /* Its own sweep_orphan_stages() runs at the very start, before this
+ * run mints its own stage -- exactly like the first run's. Cancel
+ * immediately: this run must reach the sweep and nothing past it. */
+ cbm_pipeline_cancel(p);
+ (void)cbm_pipeline_run(p);
+ cbm_pipeline_free(p);
+ }
+ return NULL;
+ }
+
+ /* Fired from inside the FIRST run's create_staging_path(), the instant its
+ * stage main file exists (under the fix, with its sidecar lock already held;
+ * under the old create-then-lock ordering, before the lock was taken): run a
+ * second, cancelled cbm_pipeline_run() for the same project synchronously on
+ * another thread, so its sweep has every chance to reach the stage before
+ * control returns to the first run. */
+ static void racing_sweep_hook(void *userdata) {
+ racing_sweep_arg_t *a = (racing_sweep_arg_t *)userdata;
+ char stage_path[600] = {0};
+ bool had_stage =
+ find_sole_stage_path(a->tmp_dir, "generation.db", stage_path, sizeof(stage_path));
+ cbm_thread_t tid;
+ if (cbm_thread_create(&tid, 0, racing_sweep_thread, a) == 0) {
+ cbm_thread_join(&tid);
+ }
+ a->stage_survived = had_stage && path_exists(stage_path);
+ }
+
+ TEST(pipeline_concurrent_sweep_must_not_remove_inflight_stage) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_stage_race_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def StableGeneration():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ racing_sweep_arg_t race_arg = {.tmp_dir = tmp, .db_path = db_path, .stage_survived = false};
+ cbm_pipeline_incremental_test_after_stage_created_once(racing_sweep_hook, &race_arg);
+
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(p));
+ int rc = cbm_pipeline_run(p);
+ cbm_pipeline_free(p);
+
+ bool db_exists = path_exists(db_path);
+ int defined_count = -1;
+ int absent_count = -1;
+ observe_named_generation(db_path, project, "StableGeneration", "NeverDefined", &defined_count,
+ &absent_count);
+ int stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_TRUE(race_arg.stage_survived);
+ ASSERT_EQ(rc, 0);
+ ASSERT_TRUE(db_exists);
+ ASSERT_EQ(defined_count, 1);
+ ASSERT_EQ(absent_count, 0);
+ ASSERT_EQ(stage_count, 0);
+ PASS();
+ }
+
+ static int live_noop_run(const char *repo, const char *db_path, cbm_incremental_route_t *route) {
+ cbm_pipeline_incremental_test_reset_faults();
+ *route = CBM_INCREMENTAL_ROUTE_NONE;
+ cbm_pipeline_t *p = cbm_pipeline_new(repo, db_path, CBM_MODE_FULL);
+ if (!p) {
+ return CBM_NOT_FOUND;
+ }
+ int rc = cbm_pipeline_run(p);
+ *route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(p);
+ return rc;
+ }
+
+ /* An unchanged re-index proves the exact no-op on the LIVE generation. It
+ * never copies the database into a stage, seals the copy and renames it back
+ * (on a kernel-scale index that copy alone was a 19 GB write per call): the
+ * live file keeps its identity, size and mtime, no stage artifact remains,
+ * and the graph still serves. */
+ TEST(pipeline_unchanged_reindex_leaves_live_generation_untouched) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_live_noop_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def StableGeneration():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ char *project = cbm_project_name_from_path(tmp);
+ ASSERT_NOT_NULL(project);
+
+ cbm_incremental_route_t first_route;
+ int first_rc = live_noop_run(tmp, db_path, &first_route);
+ cbm_path_info_t before = {0};
+ struct stat before_st;
+ bool before_ok =
+ cbm_path_info_utf8(db_path, &before) == CBM_PATH_INFO_OK && stat(db_path, &before_st) == 0;
+
+ cbm_incremental_route_t noop_route;
+ int noop_rc = live_noop_run(tmp, db_path, &noop_route);
+ cbm_path_info_t after = {0};
+ struct stat after_st;
+ bool after_ok =
+ cbm_path_info_utf8(db_path, &after) == CBM_PATH_INFO_OK && stat(db_path, &after_st) == 0;
+ int defined_count = -1;
+ int absent_count = -1;
+ observe_named_generation(db_path, project, "StableGeneration", "NeverDefined", &defined_count,
+ &absent_count);
+ int stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ free(project);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(first_rc, 0);
+ ASSERT_TRUE(before_ok);
+ ASSERT_EQ(noop_rc, 0);
+ ASSERT_EQ(noop_route, CBM_INCREMENTAL_ROUTE_NOOP);
+ ASSERT_TRUE(after_ok);
+ ASSERT_TRUE(after_st.st_ino == before_st.st_ino);
+ ASSERT_TRUE(after.mtime_ns == before.mtime_ns);
+ ASSERT_TRUE(after.size == before.size);
+ ASSERT_EQ(stage_count, 0);
+ ASSERT_EQ(defined_count, 1);
+ ASSERT_EQ(absent_count, 0);
+ PASS();
+ }
+
+ /* The live proof answers only for an exact manifest. Every real change -- a
+ * same-size edit that keeps the original mtime, an addition, a deletion and
+ * a rename -- still routes past it into a rebuild that the graph shows, and
+ * only the unchanged re-index after them takes the no-op. */
+ TEST(pipeline_live_noop_proof_never_hides_a_change) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_live_noop_change_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "alpha.py", "def AlphaDefined():\n return 1\n");
+ write_temp_file(tmp, "beta.py", "def BetaDefined():\n return 2\n");
+ char db_path[512];
+ char alpha_path[512];
+ char beta_path[512];
+ char gamma_path[512];
+ char delta_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ snprintf(alpha_path, sizeof(alpha_path), "%s/alpha.py", tmp);
+ snprintf(beta_path, sizeof(beta_path), "%s/beta.py", tmp);
+ snprintf(gamma_path, sizeof(gamma_path), "%s/gamma.py", tmp);
+ snprintf(delta_path, sizeof(delta_path), "%s/delta.py", tmp);
+ char *project = cbm_project_name_from_path(tmp);
+ ASSERT_NOT_NULL(project);
+
+ cbm_incremental_route_t initial_route;
+ int initial_rc = live_noop_run(tmp, db_path, &initial_route);
+
+ /* Same size, original mtime restored: only the bytes differ. */
+ cbm_path_info_t alpha_info = {0};
+ bool alpha_stat_ok = cbm_path_info_utf8(alpha_path, &alpha_info) == CBM_PATH_INFO_OK;
+ write_temp_file(tmp, "alpha.py", "def AlphbDefined():\n return 1\n");
+ int mtime_rc = pipeline_test_set_mtime(alpha_path, (time_t)(alpha_info.mtime_ns / 1000000000),
+ (long)(alpha_info.mtime_ns % 1000000000));
+ cbm_path_info_t edited_info = {0};
+ bool edited_same_stat = cbm_path_info_utf8(alpha_path, &edited_info) == CBM_PATH_INFO_OK &&
+ edited_info.size == alpha_info.size &&
+ edited_info.mtime_ns == alpha_info.mtime_ns;
+ cbm_incremental_route_t modify_route;
+ int modify_rc = live_noop_run(tmp, db_path, &modify_route);
+ int old_alpha = -1;
+ int new_alpha = -1;
+ observe_named_generation(db_path, project, "AlphaDefined", "AlphbDefined", &old_alpha,
+ &new_alpha);
+
+ write_temp_file(tmp, "gamma.py", "def GammaDefined():\n return 3\n");
+ cbm_incremental_route_t add_route;
+ int add_rc = live_noop_run(tmp, db_path, &add_route);
+ int gamma_added = -1;
+ int unused = -1;
+ observe_named_generation(db_path, project, "GammaDefined", "NeverDefined", &gamma_added,
+ &unused);
+
+ int unlink_rc = cbm_unlink(beta_path);
+ cbm_incremental_route_t delete_route;
+ int delete_rc = live_noop_run(tmp, db_path, &delete_route);
+ int beta_left = -1;
+ observe_named_generation(db_path, project, "BetaDefined", "NeverDefined", &beta_left, &unused);
+
+ int rename_rc = cbm_rename_replace(gamma_path, delta_path);
+ cbm_incremental_route_t rename_route;
+ int renamed_rc = live_noop_run(tmp, db_path, &rename_route);
+ int gamma_renamed = -1;
+ observe_named_generation(db_path, project, "GammaDefined", "NeverDefined", &gamma_renamed,
+ &unused);
+ int old_path_hash = CBM_STORE_OK;
+ int new_path_hash = CBM_STORE_NOT_FOUND;
+ cbm_store_t *store = cbm_store_open_path_query(db_path);
+ if (store) {
+ cbm_file_hash_t hash = {0};
+ old_path_hash = cbm_store_get_file_hash(store, project, "gamma.py", &hash);
+ cbm_store_clear_file_hash(&hash);
+ new_path_hash = cbm_store_get_file_hash(store, project, "delta.py", &hash);
+ cbm_store_clear_file_hash(&hash);
+ cbm_store_close(store);
+ }
+
+ cbm_incremental_route_t final_route;
+ int final_rc = live_noop_run(tmp, db_path, &final_route);
+ cbm_pipeline_incremental_test_reset_faults();
+ free(project);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(initial_rc, 0);
+ ASSERT_TRUE(alpha_stat_ok);
+ ASSERT_EQ(mtime_rc, 0);
+ ASSERT_TRUE(edited_same_stat);
+ ASSERT_EQ(modify_rc, 0);
+ ASSERT_TRUE(modify_route != CBM_INCREMENTAL_ROUTE_NOOP);
+ ASSERT_EQ(old_alpha, 0);
+ ASSERT_EQ(new_alpha, 1);
+ ASSERT_EQ(add_rc, 0);
+ ASSERT_TRUE(add_route != CBM_INCREMENTAL_ROUTE_NOOP);
+ ASSERT_EQ(gamma_added, 1);
+ ASSERT_EQ(unlink_rc, 0);
+ ASSERT_EQ(delete_rc, 0);
+ ASSERT_TRUE(delete_route != CBM_INCREMENTAL_ROUTE_NOOP);
+ ASSERT_EQ(beta_left, 0);
+ ASSERT_EQ(rename_rc, 0);
+ ASSERT_EQ(renamed_rc, 0);
+ ASSERT_TRUE(rename_route != CBM_INCREMENTAL_ROUTE_NOOP);
+ ASSERT_EQ(gamma_renamed, 1);
+ ASSERT_EQ(old_path_hash, CBM_STORE_NOT_FOUND);
+ ASSERT_EQ(new_path_hash, CBM_STORE_OK);
+ ASSERT_EQ(final_rc, 0);
+ ASSERT_EQ(final_route, CBM_INCREMENTAL_ROUTE_NOOP);
+ PASS();
+ }
+
+ static char g_route_log_capture[8192];
+ static atomic_flag g_route_log_spin = ATOMIC_FLAG_INIT;
+
+ /* Keeps only the route decisions; worker threads log too, and only the
+ * appends need serialising. */
+ static void capture_route_log_sink(const char *line) {
+ if (!line || !strstr(line, "pipeline.route")) {
+ return;
+ }
+ while (atomic_flag_test_and_set_explicit(&g_route_log_spin, memory_order_acquire)) {}
+ size_t used = strlen(g_route_log_capture);
+ size_t avail = sizeof(g_route_log_capture) - used;
+ if (avail > 1) {
+ int n = snprintf(g_route_log_capture + used, avail, "%s\n", line);
+ if (n < 0 || (size_t)n >= avail) {
+ g_route_log_capture[sizeof(g_route_log_capture) - 1] = '\0';
+ }
+ }
+ atomic_flag_clear_explicit(&g_route_log_spin, memory_order_release);
+ }
+
+ /* #1864: a first index has no previous generation. The route probe used to
+ * open the run's own EMPTY stage placeholder, fail its integrity check, and
+ * warn "reason=invalid_existing_db" on every first index of every project,
+ * which the report read as a corrupted database and a crash loop. A fresh
+ * index says what it is. */
+ TEST(pipeline_fresh_index_never_reports_invalid_existing_db) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_fresh_route_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def StableGeneration():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ g_route_log_capture[0] = '\0';
+ CBMLogLevel previous_level = cbm_log_get_level();
+ cbm_log_set_level(CBM_LOG_DEBUG);
+ cbm_log_set_sink(capture_route_log_sink);
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *fresh = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ int fresh_rc = fresh ? cbm_pipeline_run(fresh) : -1;
+ cbm_pipeline_free(fresh);
+ cbm_log_set_sink(NULL);
+ cbm_log_set_level(previous_level);
+
+ bool invalid_reported = strstr(g_route_log_capture, "invalid_existing_db") != NULL;
+ bool fresh_reported = strstr(g_route_log_capture, "reason=no_existing_db") != NULL;
+ bool db_present = path_exists(db_path);
+ int stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(fresh_rc, 0);
+ ASSERT_TRUE(!invalid_reported);
+ ASSERT_TRUE(fresh_reported);
+ ASSERT_TRUE(db_present);
+ ASSERT_EQ(stage_count, 0);
+ PASS();
+ }
+
+ /* Discovery and extraction must describe the same immutable generation. A
+ * source file created after extraction is not present in the original file
+ * list, so merely re-hashing that list cannot detect the race. Publication
+ * must abort, leave the old DB intact, and let a clean retry discover both
+ * files. */
+ TEST(pipeline_source_addition_before_publication_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_addition_race_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ char source_path[512];
+ char late_path[512];
+ char db_path[512];
+ snprintf(source_path, sizeof(source_path), "%s/generation.py", tmp);
+ snprintf(late_path, sizeof(late_path), "%s/late.py", tmp);
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ ASSERT_EQ(th_write_file(source_path, "def StableAdditionGeneration():\n return 1\n"), 0);
+
+ 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);
+
+ ASSERT_EQ(th_write_file(source_path, "def ExtractedAdditionGeneration():\n return 2\n"), 0);
+ manifest_race_mutation_t mutation = {
+ .path = late_path,
+ .replacement = "def LateDiscoveredGeneration():\n return 3\n",
+ .write_rc = -1,
+ };
+ cbm_pipeline_incremental_test_before_final_manifest_once(
+ mutate_semantic_input_before_final_manifest, &mutation);
+ cbm_pipeline_t *raced = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(raced);
+ int raced_rc = cbm_pipeline_run(raced);
+ cbm_pipeline_free(raced);
+
+ int raced_stable = -1;
+ int raced_extracted = -1;
+ int raced_late = -1;
+ cbm_store_t *raced_store = cbm_store_open_path(db_path);
+ if (raced_store) {
+ raced_stable = named_node_count(raced_store, project, "StableAdditionGeneration");
+ raced_extracted = named_node_count(raced_store, project, "ExtractedAdditionGeneration");
+ raced_late = named_node_count(raced_store, project, "LateDiscoveredGeneration");
+ cbm_store_close(raced_store);
+ }
+ int raced_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_stable = -1;
+ int retry_extracted = -1;
+ int retry_late = -1;
+ cbm_store_t *retry_store = cbm_store_open_path(db_path);
+ if (retry_store) {
+ retry_stable = named_node_count(retry_store, project, "StableAdditionGeneration");
+ retry_extracted = named_node_count(retry_store, project, "ExtractedAdditionGeneration");
+ retry_late = named_node_count(retry_store, project, "LateDiscoveredGeneration");
+ cbm_store_close(retry_store);
+ }
+ int retry_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(mutation.write_rc, 0);
+ ASSERT_EQ(raced_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(raced_stable, 1);
+ ASSERT_EQ(raced_extracted, 0);
+ ASSERT_EQ(raced_late, 0);
+ ASSERT_EQ(raced_stage_count, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(retry_stable, 0);
+ ASSERT_EQ(retry_extracted, 1);
+ ASSERT_EQ(retry_late, 1);
+ ASSERT_EQ(retry_stage_count, 0);
+ PASS();
+ }
+
+ /* A selected path-alias config is an extraction input, not just manifest
+ * metadata. Rewriting it after extraction must not publish an A-resolved graph
+ * beside a B-hashed manifest; that combination would make the next run a
+ * false no-op and permanently retain the stale target. */
+ TEST(pipeline_tsconfig_mutation_before_publication_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_tsconfig_race_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+
+ static const char target_a_source[] = "export function publicationRaceHandler(): void {\n"
+ " const selected = 'a';\n"
+ " void selected;\n"
+ "}\n";
+ static const char target_b_source[] = "export function publicationRaceHandler(): void {\n"
+ " const selected = 'b';\n"
+ " void selected;\n"
+ "}\n";
+ static const char stable_caller_source[] =
+ "import { publicationRaceHandler } from '@publication-race';\n"
+ "function acceptPublicationRace(callback: () => void): void {\n"
+ " void callback;\n"
+ "}\n"
+ "export function PublicationRaceStableCaller(): void {\n"
+ " acceptPublicationRace(publicationRaceHandler);\n"
+ "}\n";
+ static const char extracted_caller_source[] =
+ "import { publicationRaceHandler } from '@publication-race';\n"
+ "function acceptPublicationRace(callback: () => void): void {\n"
+ " void callback;\n"
+ "}\n"
+ "export function PublicationRaceExtractedCaller(): void {\n"
+ " acceptPublicationRace(publicationRaceHandler);\n"
+ "}\n";
+ static const char tsconfig_a[] = "{\n"
+ " \"compilerOptions\": {\n"
+ " \"baseUrl\": \".\",\n"
+ " \"paths\": {\"@publication-race\": [\"./target_a\"]}\n"
+ " }\n"
+ "}\n";
+ static const char tsconfig_b[] = "{\n"
+ " \"compilerOptions\": {\n"
+ " \"baseUrl\": \".\",\n"
+ " \"paths\": {\"@publication-race\": [\"./target_b\"]}\n"
+ " }\n"
+ "}\n";
+
+ write_temp_file(tmp, "target_a.ts", target_a_source);
+ write_temp_file(tmp, "target_b.ts", target_b_source);
+ write_temp_file(tmp, "caller.ts", stable_caller_source);
+ write_temp_file(tmp, "tsconfig.json", tsconfig_a);
+ char caller_path[512];
+ char tsconfig_path[512];
+ char db_path[512];
+ snprintf(caller_path, sizeof(caller_path), "%s/caller.ts", tmp);
+ snprintf(tsconfig_path, sizeof(tsconfig_path), "%s/tsconfig.json", tmp);
+ 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);
+
+ ASSERT_EQ(th_write_file(caller_path, extracted_caller_source), 0);
+ manifest_race_mutation_t mutation = {
+ .path = tsconfig_path,
+ .replacement = tsconfig_b,
+ .write_rc = -1,
+ };
+ cbm_pipeline_incremental_test_before_final_manifest_once(
+ mutate_semantic_input_before_final_manifest, &mutation);
+ cbm_pipeline_t *raced = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(raced);
+ int raced_rc = cbm_pipeline_run(raced);
+ cbm_pipeline_free(raced);
+
+ int raced_stable_a = -1;
+ int raced_stable_b = -1;
+ int raced_extracted_nodes = -1;
+ cbm_store_t *raced_store = cbm_store_open_path(db_path);
+ if (raced_store) {
+ raced_stable_a = named_edge_to_file_count(raced_store, project, "CALL_REFERENCE",
+ "PublicationRaceStableCaller",
+ "publicationRaceHandler", "target_a.ts");
+ raced_stable_b = named_edge_to_file_count(raced_store, project, "CALL_REFERENCE",
+ "PublicationRaceStableCaller",
+ "publicationRaceHandler", "target_b.ts");
+ raced_extracted_nodes =
+ named_node_count(raced_store, project, "PublicationRaceExtractedCaller");
+ cbm_store_close(raced_store);
+ }
+ int raced_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_stable_nodes = -1;
+ int retry_extracted_a = -1;
+ int retry_extracted_b = -1;
+ int retry_extracted_usage = -1;
+ int retry_extracted_calls = -1;
+ cbm_store_t *retry_store = cbm_store_open_path(db_path);
+ if (retry_store) {
+ retry_stable_nodes = named_node_count(retry_store, project, "PublicationRaceStableCaller");
+ retry_extracted_a = named_edge_to_file_count(retry_store, project, "CALL_REFERENCE",
+ "PublicationRaceExtractedCaller",
+ "publicationRaceHandler", "target_a.ts");
+ retry_extracted_b = named_edge_to_file_count(retry_store, project, "CALL_REFERENCE",
+ "PublicationRaceExtractedCaller",
+ "publicationRaceHandler", "target_b.ts");
+ retry_extracted_usage =
+ named_edge_count(retry_store, project, "USAGE", "PublicationRaceExtractedCaller",
+ "publicationRaceHandler");
+ retry_extracted_calls =
+ named_edge_count(retry_store, project, "CALLS", "PublicationRaceExtractedCaller",
+ "publicationRaceHandler");
+ cbm_store_close(retry_store);
+ }
+ int retry_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(mutation.write_rc, 0);
+ ASSERT_EQ(raced_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(raced_stable_a, 1);
+ ASSERT_EQ(raced_stable_b, 0);
+ ASSERT_EQ(raced_extracted_nodes, 0);
+ ASSERT_EQ(raced_stage_count, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(retry_stable_nodes, 0);
+ ASSERT_EQ(retry_extracted_a, 0);
+ ASSERT_EQ(retry_extracted_b, 1);
+ ASSERT_EQ(retry_extracted_usage, 0);
+ ASSERT_EQ(retry_extracted_calls, 0);
+ ASSERT_EQ(retry_stage_count, 0);
+ PASS();
+ }
+
+ /* 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. */
+ TEST(pipeline_exact_inputs_migrate_coverage_metadata_and_index_mode) {
+ 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();
+ 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);
+
+ 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);
+
+ 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 = 1;
+ 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);
+
+ 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);
+
+ 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);
+
+ 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);
+
+ 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_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();
+ }
+
+ typedef struct {
+ bool published;
+ int rename_calls;
+ int export_count;
+ int exports_before_publish;
+ } artifact_publish_observer_t;
+
+ static artifact_publish_observer_t *g_artifact_publish_observer;
+
+ 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_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();
+ }
+
+ /* 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();
++}
++
+ /* 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);
+ }
+
+ 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();
+ }
+
+ /* 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);
}
- cbm_closedir(dir);
- return count;
+ /* 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();
}
- typedef struct {
- const char *path;
- const char *replacement;
- int write_rc;
- } manifest_race_mutation_t;
+ TEST(pipeline_capitalized_axios_import_is_http_client) {
+ return capitalized_axios_case(52);
+ }
- static void mutate_semantic_input_before_final_manifest(void *userdata) {
- manifest_race_mutation_t *mutation = (manifest_race_mutation_t *)userdata;
- mutation->write_rc = th_write_file(mutation->path, mutation->replacement);
+ TEST(pipeline_capitalized_axios_import_is_http_client_sequential) {
+ return capitalized_axios_case(0);
}
- /* A graph and its exact manifest are one generation. If source bytes change
- * after extraction but before publication, the mixed generation must be
- * rejected and the previous live DB preserved. */
- TEST(pipeline_source_mutation_before_publication_preserves_previous_generation) {
+ /* 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_publish_generation_race_XXXXXX");
- ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
- char source_path[512];
+ 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(source_path, sizeof(source_path), "%s/generation.py", tmp);
- snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
- ASSERT_EQ(th_write_file(source_path, "def StableGeneration():\n return 1\n"), 0);
+ 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_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);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s);
- ASSERT_EQ(th_write_file(source_path, "def ExtractedGeneration():\n return 2\n"), 0);
- manifest_race_mutation_t mutation = {
- .path = source_path,
- .replacement = "def FinalGeneration():\n return 3\n",
- .write_rc = -1,
- };
- cbm_pipeline_incremental_test_before_final_manifest_once(
- mutate_semantic_input_before_final_manifest, &mutation);
- cbm_pipeline_t *raced = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
- ASSERT_NOT_NULL(raced);
- int raced_rc = cbm_pipeline_run(raced);
- cbm_pipeline_free(raced);
- int raced_stable = -1;
- int raced_extracted = -1;
- observe_named_generation(db_path, project, "StableGeneration", "ExtractedGeneration",
- &raced_stable, &raced_extracted);
- int raced_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ /* 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_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_stable = -1;
- int retry_final = -1;
- observe_named_generation(db_path, project, "StableGeneration", "FinalGeneration", &retry_stable,
- &retry_final);
- int retry_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
- cbm_pipeline_incremental_test_reset_faults();
+ cbm_store_close(s);
+ cbm_pipeline_free(p);
th_rmtree(tmp);
-
- ASSERT_EQ(mutation.write_rc, 0);
- ASSERT_EQ(raced_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
- ASSERT_EQ(raced_stable, 1);
- ASSERT_EQ(raced_extracted, 0);
- ASSERT_EQ(raced_stage_count, 0);
- ASSERT_EQ(retry_rc, 0);
- ASSERT_EQ(retry_stable, 0);
- ASSERT_EQ(retry_final, 1);
- ASSERT_EQ(retry_stage_count, 0);
PASS();
}
@@@ -13307,16 -28228,50 +28277,51 @@@ 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_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_multi_init_nodes_survive);
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_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);