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 (5a4af9c4) into fix/1355-external-import-shadow

Martin Vogel6e3799b090fd
diff --cc src/pipeline/pass_calls.c
index 1163417b3,738e5b932..f80be332e
--- a/src/pipeline/pass_calls.c
+++ b/src/pipeline/pass_calls.c
@@@ -661,9 -1150,15 +1159,18 @@@ static int resolve_single_call(cbm_pipe
res.strategy)) ||
cbm_suppress_weak_local_binding_call(suppress_weak_local_binding,
call->callee_is_locally_bound, res.strategy) ||
- cbm_suppress_external_import_shadow(call->callee_name, res.strategy, file_imports, imp_keys,
+ cbm_go_suppress_weak_method_match(lang == CBM_LANG_GO, call->is_method, res.strategy,
+ res.confidence) ||
+ /* Import-binding suppression (#2127): an external `from m import f`
+ * binds `f` for the whole module, so a weak short-name match onto a
+ * project `X.f` outside m is fabricated. Python-only (the import
+ * paths are module chains) — MUST match pass_parallel.c exactly. */
+ (lang == CBM_LANG_PYTHON && cbm_suppress_weak_import_bound_call(true, true, res.strategy) &&
+ cbm_python_import_binding_contradicts(imports, call->callee_name, res.qualified_name,
- ctx->gbuf, ctx->project_name, rel));
++ ctx->gbuf, ctx->project_name, rel)) ||
++ cbm_suppress_external_import_shadow(call->callee_name, res.strategy, imports, imp_keys,
+ imp_count, cbm_pipeline_get_pkgmap(),
+ cbm_pipeline_get_nsmap());
/* Service-pattern HTTP/ASYNC calls to an EXTERNAL client library (e.g.
* `requests.get("/api/orders/{id}")`) resolve to a QN containing the library
diff --cc src/pipeline/pass_definitions.c
index e71843db6,ed60d3f9a..549b20a3a
--- a/src/pipeline/pass_definitions.c
+++ b/src/pipeline/pass_definitions.c
@@@ -909,11 -1181,10 +1181,12 @@@ int cbm_pipeline_pass_definitions(cbm_p
total_imports +=
create_import_edges_for_file(ctx, result, files[i].rel_path, namespace_map);
create_channel_edges_for_file(ctx, result, files[i].rel_path);
+ cbm_pipeline_diagram_arrows(ctx, result);
cbm_pipeline_create_env_configures_for_file(ctx, result, files[i].rel_path);
}
- cbm_pipeline_namespace_map_free(namespace_map);
+ /* Publish instead of free — see the twin in pass_parallel.c (#1355). */
+ cbm_pipeline_namespace_map_free(cbm_pipeline_get_nsmap());
+ cbm_pipeline_set_nsmap(namespace_map);
if (owns_local_cache) {
for (int i = 0; i < file_count; i++) {
if (local_cache[i]) {
diff --cc src/pipeline/pass_parallel.c
index df3805ffd,302e76faa..3aadeb4dc
--- a/src/pipeline/pass_parallel.c
+++ b/src/pipeline/pass_parallel.c
@@@ -2967,9 -3413,15 +3422,18 @@@ static void resolve_file_calls(resolve_
call->callee_name, res.strategy)) ||
cbm_suppress_weak_local_binding_call(suppress_weak_local_binding,
call->callee_is_locally_bound, res.strategy) ||
+ cbm_go_suppress_weak_method_match(lang == CBM_LANG_GO, call->is_method, res.strategy,
+ res.confidence) ||
+ /* Import-binding suppression (#2127) — see pass_calls.c; this gate
+ * MUST stay identical to the one there. */
+ (lang == CBM_LANG_PYTHON &&
+ cbm_suppress_weak_import_bound_call(true, true, res.strategy) &&
+ cbm_python_import_binding_contradicts(&result->imports, call->callee_name,
+ res.qualified_name, rc->main_gbuf,
- rc->project_name, rel));
++ rc->project_name, rel)) ||
+ cbm_suppress_external_import_shadow(call->callee_name, res.strategy, &result->imports,
+ imp_keys, imp_count, cbm_pipeline_get_pkgmap(),
+ cbm_pipeline_get_nsmap());
/* Service-pattern HTTP/ASYNC client call (`requests.get(url)`): the
* service signal lives in the callee_name. The registry can mis-resolve
diff --cc src/pipeline/pipeline.c
index 475ddd858,92e23de64..698d9dc7a
--- a/src/pipeline/pipeline.c
+++ b/src/pipeline/pipeline.c
@@@ -2882,10 -4095,13 +4107,15 @@@ static int cbm_pipeline_run_staged(cbm_
cleanup:
cbm_pkgmap_free(cbm_pipeline_get_pkgmap());
cbm_pipeline_set_pkgmap(NULL);
+ cbm_pipeline_namespace_map_free(cbm_pipeline_get_nsmap());
+ cbm_pipeline_set_nsmap(NULL);
cbm_discover_free(files, file_count);
- cbm_pipeline_free_semantic_manifest(baseline_manifest, baseline_count);
+ if (p->frozen) {
+ p->frozen->baseline = baseline_manifest;
+ p->frozen->baseline_count = baseline_count;
+ } else {
+ cbm_pipeline_free_semantic_manifest(baseline_manifest, baseline_count);
+ }
cbm_gbuf_free(p->gbuf);
p->gbuf = NULL;
cbm_registry_free(p->registry);
diff --cc src/pipeline/pipeline.h
index 3be56cce3,a04e0144a..0c41d8c3b
--- a/src/pipeline/pipeline.h
+++ b/src/pipeline/pipeline.h
@@@ -320,26 -411,26 +412,45 @@@ bool cbm_weak_member_unique_name_exempt
* Pure; unit-tested in test_registry.c. */
bool cbm_suppress_weak_local_binding_call(bool enabled, bool callee_is_locally_bound,
const char *strategy);
+/* #1355: drop a project-wide same-name guess (suffix_match / unique_name /
+ * field_type_hint / fuzzy) for a BARE call whose name the calling file binds to
+ * a NON-RELATIVE (package) import that resolved to nothing in the graph —
+ * `import { eq } from "drizzle-orm"` must not make `eq(...)` a CALLS edge to an
+ * unrelated project `eq`. A name the import map does bind, a relative
+ * specifier, a member/qualified callee, and every import-/receiver-aware
+ * strategy are all kept. `indexed_packages` is the pipeline package map: a
+ * specifier naming a package the tree itself declares (a workspace sibling)
+ * counts as in-tree and is kept too; NULL disables that check.
+ * `declared_packages` is the pipeline namespace map and does the same job for
+ * package-path specifiers, which have no in-tree/external shape of their own:
+ * `import org.example.util.assertThing` is kept when some indexed file
+ * declares `package org.example.util`; NULL disables that check.
+ * Pure; unit-tested in test_registry.c. */
+bool cbm_suppress_external_import_shadow(const char *callee_name, const char *strategy,
+ const CBMImportArray *file_imports,
+ const char **import_map_keys, int import_map_count,
+ const CBMHashTable *indexed_packages,
+ const CBMHashTable *declared_packages);
+ /* Go analog of the TS/JS guard, same failure class: a selector call whose
+ * receiver the Go LSP could not type must not be bound by a receiver-blind
+ * short-name strategy. Drops suffix_match / fuzzy always, and unique_name only
+ * when its confidence is import-unreachability-penalized (the stdlib/vendor
+ * hijack shape). field_type_hint is deliberately NOT dropped for Go — struct
+ * fields carry declared types, so the hint is receiver-aware there. */
+ bool cbm_go_suppress_weak_method_match(bool is_go, bool is_method, const char *strategy,
+ double confidence);
+
+ /* Import-binding counterpart (#2127). True when the callee's root identifier
+ * is bound by an import of this file whose module chain contradicts the
+ * resolved target (`from unittest.mock import patch; patch()` must not bind a
+ * project `PkgConfigView.patch`), and the match came from a weak short-name
+ * strategy. Same drop-list as the guards above; the language set lives at the
+ * call sites and must be identical in pass_calls.c and pass_parallel.c.
+ * Pure; unit-tested in test_registry.c. */
+ bool cbm_suppress_weak_import_bound_call(bool enabled, bool import_binding_contradicts,
+ const char *strategy);
+
/* #725: drop a suffix_match CALLS edge when the caller language and the
* target file's language disagree. unique_name (candidates == 1) is #1572
* and is left alone; same_module / import_map / lsp_* are kept. JS/TS/TSX
diff --cc src/pipeline/pipeline_incremental.c
index 63f28611a,a860b5e32..4182ca711
--- a/src/pipeline/pipeline_incremental.c
+++ b/src/pipeline/pipeline_incremental.c
@@@ -2198,10 -3498,18 +3500,20 @@@ static int run_closure_delta(cbm_pipeli
}
cbm_pkgmap_free(cbm_pipeline_get_pkgmap());
cbm_pipeline_set_pkgmap(NULL);
+ cbm_pipeline_namespace_map_free(cbm_pipeline_get_nsmap());
+ cbm_pipeline_set_nsmap(NULL);
if (phase_rc != 0) {
cbm_log_error("delta.err", "phase", "extract_resolve", "rc", itoa_buf(phase_rc));
+ if (phase_rc == CBM_PIPELINE_ABORT_PRESERVE_DB) {
+ result = phase_rc;
+ }
+ goto out;
+ }
+ /* A repository split differently (pass_docker.c P4.2b) leaves the
+ * references of files not repaired here on the old component Images:
+ * only a full rebuild re-points them. */
+ if (!incr_image_components_equal(gbuf, hub_images, hub_count, &decl_arena)) {
+ cbm_log_info("delta.fallback", "reason", "image_components_changed");
goto out;
}
cbm_log_info("delta.repair", "files", itoa_buf(ci), "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
diff --cc src/pipeline/pipeline_internal.h
index 0de8625b8,06722aca7..a1ab9c6e5
--- a/src/pipeline/pipeline_internal.h
+++ b/src/pipeline/pipeline_internal.h
@@@ -205,16 -705,45 +705,55 @@@ void cbm_pipeline_diagram_arrows(cbm_pi
CBMHashTable *cbm_pipeline_get_pkgmap(void);
void cbm_pipeline_set_pkgmap(CBMHashTable *map);
+ /* Resolve a route handler reference (the registry's answer for route passes).
+ * A class-qualified "Ns\\Class::method" reference — the extractor's form for
+ * Laravel `[Class::class, 'method']` and invokable `Class::class` handlers
+ * (#1146), with the class already qualified through the file's `use` imports
+ * and namespace — is placed on a method QN only by what places the class file:
+ * the composer.json PSR-4 class file in gbuf (cbm_pipeline_psr4_member_qn).
+ * When a PSR-4 prefix covers the class, that answer is final: a covered class
+ * whose file or member is absent stays unresolved, as its `use` import does
+ * (#1186). Only a class no prefix covers falls back to the one candidate whose
+ * directories end with the class's namespace. Never by short name alone, so a
+ * vendor controller that is not in the repo gets no handler. A reference
+ * without "::" resolves exactly as cbm_registry_resolve_lang does for the
+ * calling file's language. */
+ cbm_resolution_t cbm_registry_resolve_handler(const cbm_registry_t *r, const char *handler_ref,
+ const char *module_qn, const char **import_map_keys,
+ const char **import_map_vals, int import_map_count,
+ const cbm_gbuf_t *gbuf, CBMLanguage lang);
+
+ /* Where composer's PSR-4 autoloader places a PHP class member. Tri-state, so
+ * "no prefix covers the class" (another strategy may answer) is never
+ * confused with "a prefix covers it but places nothing" (final). */
+ typedef enum {
+ CBM_PSR4_MEMBER_NOT_COVERED = 0, /* no psr-4 prefix covers the class */
+ CBM_PSR4_MEMBER_RESOLVED, /* *out_qn is the member's QN */
+ CBM_PSR4_MEMBER_UNRESOLVED, /* covered, but no class file holds the
+ * class with this member: leave it
+ * unresolved, never guess elsewhere */
+ } cbm_psr4_member_t;
+
+ /* Place `member` on the PHP class `class_fqn` ("Ns\\Class", NUL-terminated)
+ * the way composer's PSR-4 autoloader places the class: the class file the
+ * import resolver picks for `use Ns\\Class;` (#1186), the class that file
+ * defines, then that class's member. *out_qn is set only on
+ * CBM_PSR4_MEMBER_RESOLVED (else NULL) and is owned by gbuf. Missing
+ * arguments or no package map give CBM_PSR4_MEMBER_NOT_COVERED. Read-only on
+ * gbuf. */
+ cbm_psr4_member_t cbm_pipeline_psr4_member_qn(const cbm_gbuf_t *gbuf, const char *class_fqn,
+ const char *member, const char **out_qn);
+
+/* Get the current pipeline's declared-package map (NULL if none): the
+ * namespace/package → File-QN map built by cbm_pipeline_namespace_map_build
+ * from every indexed file's own `package`/`namespace`/`using` declaration.
+ * The import passes build it to resolve namespace imports; it is published
+ * here so the call passes can ask whether a package-path specifier names a
+ * package the tree itself declares (#1355). Set before resolve starts, read
+ * only afterwards — same single-writer contract as the pkgmap above. */
+CBMHashTable *cbm_pipeline_get_nsmap(void);
+void cbm_pipeline_set_nsmap(CBMHashTable *map);
+
/* Unified module resolver: relative → pkgmap → fqn_module fallback.
* Handles bare specifiers via pkgmap lookup with prefix matching.
* Caller must free() the returned string. */
diff --cc src/pipeline/registry.c
index 976b84c31,7de52a262..a4ca4cece
--- a/src/pipeline/registry.c
+++ b/src/pipeline/registry.c
@@@ -30,8 -31,8 +31,9 @@@ enum { REG_MAX_CANDIDATES = 256 }
#include "foundation/hash_table.h"
#include "foundation/dyn_array.h"
#include "foundation/platform.h"
+ #include "callable_sig.h" /* cbm_qn_callable_base_len_named: overloads share the name key */
+#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
@@@ -696,241 -750,51 +751,286 @@@ bool cbm_suppress_weak_local_binding_ca
return weak_short_name_strategy(strategy);
}
+/* A module specifier that names a path inside the indexed tree ("./x", "../x",
+ * "/abs/x", and on Windows "C:\x", "C:/x", "\\server\share\x") rather than an
+ * external package. Package specifiers are everything else — "drizzle-orm",
+ * "rxjs/operators", "@scope/pkg". Windows paths must count as in-tree here:
+ * pr-smoke runs this pipeline on Windows, and misclassifying a drive-letter or
+ * UNC specifier as "external" is exactly the false-external edge this guard
+ * exists to prevent (#1355). */
+static bool specifier_is_relative(const char *module_path) {
+ if (!module_path || !module_path[0]) {
+ return false;
+ }
+ if (module_path[0] == '.' || module_path[0] == '/') {
+ return true;
+ }
+ /* UNC share: \\server\share\... */
+ if (module_path[0] == '\\' && module_path[1] == '\\') {
+ return true;
+ }
+ /* Drive-letter absolute path: C:\repo\... or C:/repo/... */
+ if (isalpha((unsigned char)module_path[0]) && module_path[1] == ':' &&
+ (module_path[2] == '\\' || module_path[2] == '/')) {
+ return true;
+ }
+ return false;
+}
+
+/* True when the specifier names a package that the indexed tree DECLARES —
+ * a workspace sibling, not a third-party dependency. `indexed_packages` is the
+ * pipeline's package map, keyed by the `name` of every manifest found in the
+ * tree (package.json, go.mod, Cargo.toml, ...), so a pnpm/npm/cargo workspace
+ * registers each of its own packages here.
+ *
+ * The key is the bare package name, so a subpath specifier is walked back one
+ * slash at a time: "drizzle-orm/pg-core" -> "drizzle-orm". Scoped names keep
+ * their leading segment ("@scope/pkg/sub" -> "@scope/pkg" -> "@scope").
+ *
+ * Deliberately a NAME test, not a resolution test. A workspace package usually
+ * points `main`/`module` at a build artifact ("./index.cjs") that is not
+ * checked in, so asking whether the entry file exists in the graph answers
+ * "no" for exactly the monorepos this has to protect. Whether the tree claims
+ * the name is decidable from the manifest alone. */
+static bool specifier_names_indexed_package(const CBMHashTable *indexed_packages,
+ const char *module_path) {
+ if (!indexed_packages || !module_path || !module_path[0]) {
+ return false;
+ }
+ if (cbm_ht_has(indexed_packages, module_path)) {
+ return true;
+ }
+ char buf[CBM_SZ_512];
+ if (strlen(module_path) >= sizeof(buf)) {
+ return false;
+ }
+ snprintf(buf, sizeof(buf), "%s", module_path);
+ for (char *slash = strrchr(buf, '/'); slash != NULL; slash = strrchr(buf, '/')) {
+ *slash = '\0';
+ if (cbm_ht_has(indexed_packages, buf)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/* True when the specifier is a package PATH the indexed tree itself DECLARES.
+ * `declared_packages` is the pipeline's namespace map, keyed by the
+ * dot-normalized `package` / `namespace` / `use` declaration of every indexed
+ * file (cbm_pipeline_namespace_map_build), so this is the JVM/CLR/PHP
+ * counterpart of the manifest-name test above: those languages have no
+ * specifier shape that separates in-tree from third-party, and their manifests
+ * (pom.xml, build.gradle) name artifacts, not packages.
+ *
+ * A package-path specifier names a member inside a package, so the trailing
+ * segment is walked off one at a time, exactly like the namespace-map lookup in
+ * cbm_pipeline_resolve_import_node: `org.jetbrains.exposed.v1.tests.shared
+ * .assertEquals` -> `org.jetbrains.exposed.v1.tests.shared`, which Exposed's
+ * own Assert.kt declares, so the call keeps its edge. `java.net.URL` walks to
+ * `java.net` then `java`, which no project file declares, so it stays external
+ * and the guard still cuts its bind to an in-tree `URL` class.
+ *
+ * Separator normalization mirrors the map builder's: PHP writes `\`, some
+ * grammars `::` or `/`. NULL disables the check. */
+static bool specifier_names_declared_package(const CBMHashTable *declared_packages,
+ const char *module_path) {
+ if (!declared_packages || !module_path || !module_path[0]) {
+ return false;
+ }
+ char buf[CBM_SZ_512];
+ if (strlen(module_path) >= sizeof(buf)) {
+ return false;
+ }
+ snprintf(buf, sizeof(buf), "%s", module_path);
+ char *brace = strchr(buf, '{');
+ if (brace) {
+ *brace = '\0'; /* grouped import — the prefix is the package */
+ }
+ char *alias = strstr(buf, " as ");
+ if (alias) {
+ *alias = '\0';
+ }
+ for (char *p = buf; *p; p++) {
+ if (*p == '\\' || *p == ':' || *p == '/') {
+ *p = '.';
+ }
+ }
+ /* Collapse the empty segments "::" just produced, then strip glob/
+ * separator noise off the tail. */
+ for (;;) {
+ char *dd = strstr(buf, "..");
+ if (!dd) {
+ break;
+ }
+ memmove(dd, dd + 1, strlen(dd + 1) + 1);
+ }
+ size_t len = strlen(buf);
+ while (len > 0 && (buf[len - 1] == '*' || buf[len - 1] == '.' || buf[len - 1] == ' ')) {
+ buf[--len] = '\0';
+ }
+ if (buf[0] == '\0') {
+ return false;
+ }
+ if (cbm_ht_has(declared_packages, buf)) {
+ return true;
+ }
+ /* The walk has no floor, and that is a deliberate false-NEGATIVE: once the
+ * tree declares `com.example`, EVERY specifier under `com.example.**` reads
+ * as in-tree, including a third-party library that happens to publish under
+ * a declared prefix. Such a call keeps the same-name fallback it has on
+ * main, so the cost is a fabricated edge this guard could have removed —
+ * never a real edge lost. Stopping earlier would need a rule for where a
+ * package path ends and a type begins, and getting that wrong fails the
+ * other way. Pinned by external_import_shadow_declared_prefix_is_permissive
+ * in test_registry.c. */
+ for (char *dot = strrchr(buf, '.'); dot != NULL; dot = strrchr(buf, '.')) {
+ *dot = '\0';
+ if (cbm_ht_has(declared_packages, buf)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool import_map_binds(const char **import_map_keys, int import_map_count,
+ const char *local_name) {
+ if (!import_map_keys || import_map_count <= 0) {
+ return false;
+ }
+ for (int i = 0; i < import_map_count; i++) {
+ if (import_map_keys[i] && strcmp(import_map_keys[i], local_name) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/* #1355: a bare call whose name the calling file binds to an EXTERNAL package
+ * import must not fall back to a project-wide same-name guess.
+ *
+ * `import { eq } from "drizzle-orm"` binds `eq` in this file's scope. When the
+ * package is not part of the indexed tree it materializes no IMPORTS edge, so
+ * the import map has no entry, strategies 1-2 miss, and strategy 3/4 attach
+ * `eq(users.id, id)` to whatever project symbol happens to share the simple
+ * name — a CALLS edge into an unrelated local helper. The explicit import
+ * statement is positive evidence, taken from the caller's own source, that the
+ * identifier does NOT denote that symbol.
+ *
+ * Fires only when ALL of:
+ * - the callee is a BARE identifier: member (`x.foo()`) and package/namespace
+ * qualified callees are the receiver-aware guards' business, not this one;
+ * - the match came from a project-wide guess (suffix_match / unique_name;
+ * field_type_hint / fuzzy listed for the same defensive reason as the TS/JS
+ * guard) — every import-, receiver- or module-aware strategy is KEPT;
+ * - the file imports that exact local name from a NON-RELATIVE specifier;
+ * - no import-map key binds the name, i.e. that import resolved to nothing in
+ * the graph. A name the map does bind already had its chance at strategy 1
+ * and is import-aware by construction.
+ *
+ * Relative specifiers are deliberately excluded: they name a path inside the
+ * indexed tree, so a missing IMPORTS edge is an in-project resolution gap and
+ * the same-name fallback can still be right. A name imported from both a
+ * relative and a package specifier keeps the edge — the relative binding wins
+ * the tie explicitly, so the outcome does not depend on import order.
+ *
+ * `indexed_packages` extends that same reasoning to workspace monorepos, where
+ * a BARE specifier also names in-tree code: `import { eq } from "drizzle-orm"`
+ * inside the drizzle-orm repository is a sibling package, not a dependency. A
+ * specifier the tree's own manifests claim is treated exactly like a relative
+ * one. NULL disables the check and restores the specifier-shape-only contract.
+ *
+ * `declared_packages` closes the same hole for the package-path languages,
+ * where NO specifier shape says in-tree: `import
+ * org.jetbrains.exposed.v1.tests.shared.assertEquals` is spelled exactly like
+ * `import kotlin.test.assertEquals`, and only the tree's own `package`
+ * declarations tell them apart. It is permissive by construction — any
+ * specifier UNDER a declared package prefix counts as in-tree, see the note on
+ * the walk — so it can leave a fabricated edge in place, never remove a real
+ * one. NULL disables the check.
+ *
+ * Pure + side-effect-free so the contract is unit-testable without a pipeline. */
+bool cbm_suppress_external_import_shadow(const char *callee_name, const char *strategy,
+ const CBMImportArray *file_imports,
+ const char **import_map_keys, int import_map_count,
+ const CBMHashTable *indexed_packages,
+ const CBMHashTable *declared_packages) {
+ if (!callee_name || !callee_name[0] || !strategy || !strategy[0]) {
+ return false;
+ }
+ if (strcmp(strategy, "suffix_match") != 0 && strcmp(strategy, "unique_name") != 0 &&
+ strcmp(strategy, "field_type_hint") != 0 && strcmp(strategy, "fuzzy") != 0) {
+ return false;
+ }
+ if (strchr(callee_name, '.') != NULL || strstr(callee_name, "::") != NULL) {
+ return false;
+ }
+ if (!file_imports || file_imports->count <= 0) {
+ return false;
+ }
+ if (import_map_binds(import_map_keys, import_map_count, callee_name)) {
+ return false;
+ }
+ bool external_binding = false;
+ for (int i = 0; i < file_imports->count; i++) {
+ const CBMImport *imp = &file_imports->items[i];
+ if (!imp->local_name || !imp->module_path || strcmp(imp->local_name, callee_name) != 0) {
+ continue;
+ }
+ if (specifier_is_relative(imp->module_path) ||
+ specifier_names_indexed_package(indexed_packages, imp->module_path) ||
+ specifier_names_declared_package(declared_packages, imp->module_path)) {
+ return false; /* an in-tree binding for this name — never suppress */
+ }
+ external_binding = true;
+ }
+ return external_binding;
+}
+
+ bool cbm_go_suppress_weak_method_match(bool is_go, bool is_method, const char *strategy,
+ double confidence) {
+ /* Go analog of the TS/JS guard above, same failure class: a selector call
+ * whose receiver the Go LSP could not type reaches the registry and a bare
+ * short-name strategy binds it to an arbitrary same-named project symbol
+ * (`f.Close()` on an os.File -> a project `Close`, suffix_match over 15
+ * candidates). Built on the shared drop-list so "weak" means one thing
+ * for every guard; Go narrows it in one place only (unique_name below).
+ * field_type_hint stays weak: it is a receiver-NAME substring match, not
+ * a declared-type lookup (the parallel resolver no longer produces it for
+ * Go; a typed field call such as lrp_go_s8's `s.repo.Find()` resolves
+ * through the Go LSP). */
+ if (!is_go || !is_method || !weak_short_name_strategy(strategy)) {
+ return false;
+ }
+ if (strcmp(strategy, "unique_name") != 0) {
+ return true; /* suffix_match, field_type_hint, fuzzy */
+ }
+ /* unique_name is dropped only when PENALIZED: resolve_name_lookup scales
+ * CONF_UNIQUE_NAME by DEFAULT_CONFIDENCE exactly when the lone candidate
+ * is not reachable through the caller's imports — the stdlib/vendor
+ * hijack shape (`io.Copy` -> a project `Copy`). An unpenalized
+ * unique_name target sits inside the caller's import closure (or the
+ * file has no imports, e.g. a same-package call) and must be kept —
+ * dropping it kills genuinely-typed lone-candidate calls that never
+ * enter the field-type-hint upgrade (candidate_count == 1). */
+ return confidence < CONF_UNIQUE_NAME;
+ }
+
+ /* Import-binding counterpart of the parameter guard above (#2127). An import
+ * binds the identifier for the whole module; when that import is external it
+ * never materializes, and the chain falls through to project-wide short-name
+ * strategies (`from unittest.mock import patch; patch()` -> a REST view's
+ * `PkgConfigView.patch`). The caller decides whether the binding contradicts
+ * the target (cbm_python_import_binding_contradicts: a SCOPE FACT about this
+ * file, not a spelling list); only weak strategies are dropped, so import_map /
+ * same_module / lsp_* edges are untouched. Pure; unit-tested in test_registry.c. */
+ bool cbm_suppress_weak_import_bound_call(bool enabled, bool import_binding_contradicts,
+ const char *strategy) {
+ if (!enabled || !import_binding_contradicts) {
+ return false;
+ }
+ return weak_short_name_strategy(strategy);
+ }
+
static bool js_ts_family(CBMLanguage lang) {
return lang == CBM_LANG_JAVASCRIPT || lang == CBM_LANG_TYPESCRIPT || lang == CBM_LANG_TSX ||
lang == CBM_LANG_ARKTS;
diff --cc tests/test_pipeline.c
index 998b9056c,5f7dabed9..111bdfa01
--- a/tests/test_pipeline.c
+++ b/tests/test_pipeline.c
@@@ -5068,364 -6756,3949 +6756,4429 @@@ TEST(pipeline_tsconfig_mutation_before_
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) {
+ /* 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_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();
- }
-
- /* 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");
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_manifest_metadata_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);
-
+ write_temp_file(tmp, "generation.py", "def ExactMetadataGeneration():\n return 1\n");
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);
+ 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(pipeline));
- cbm_pipeline_free(pipeline);
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
- 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);
- }
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *exact_before_migration = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(exact_before_migration);
+ ASSERT_EQ(cbm_pipeline_run(exact_before_migration), 0);
+ cbm_incremental_route_t exact_before_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(exact_before_migration);
- int 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);
+ 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);
- 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();
- }
+ 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);
- /* 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");
+ 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);
- 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_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);
- 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);
+ 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);
- 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;
+ 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(run_rc, 0);
- ASSERT_EQ(fresh_nodes, 1);
- ASSERT_EQ(generated_column_count, 1);
- ASSERT_FALSE(quarantined);
+ ASSERT_EQ(exact_before_route, CBM_INCREMENTAL_ROUTE_NOOP);
+ ASSERT_EQ(migration_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(migrated_version, CBM_SEMANTIC_INDEX_VERSION);
+ ASSERT_TRUE(migrated_hashes_complete);
+ ASSERT_STR_EQ(migrated_mode, "fast");
+ ASSERT_EQ(mode_change_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(full_version, CBM_SEMANTIC_INDEX_VERSION);
+ ASSERT_TRUE(full_hashes_complete);
+ ASSERT_STR_EQ(full_mode, "full");
+ ASSERT_EQ(exact_full_route, CBM_INCREMENTAL_ROUTE_NOOP);
PASS();
}
- #endif
- /* 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");
- }
+ typedef struct {
+ bool published;
+ int rename_calls;
+ int export_count;
+ int exports_before_publish;
+ } artifact_publish_observer_t;
- 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";
+ static artifact_publish_observer_t *g_artifact_publish_observer;
- write_temp_file(tmp, "target.ts", callable_target_source);
- write_temp_file(tmp, "caller.ts", caller_source);
+ 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++;
+ }
+ }
+ }
- 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);
+ 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);
- 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_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));
- write_temp_file(tmp, "target.ts", value_target_source);
+ 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);
- 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);
+ /* 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);
- 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);
+ 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();
+ }
+
+ /* 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();
+ }
+
+ /* 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();
+ }
+
+ /* 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(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);
++ ASSERT_EQ(sequential, 0);
++ ASSERT_EQ(parallel, 0);
+ 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) {
++/* #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_incr_ids_XXXXXX");
++ 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);
+
- 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");
++ const char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
- char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
++ 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");
+
- 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 (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 (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);
- }
++ 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");
}
- 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;
+ /* 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);
}
- 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);
- }
- }
+ 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 */
- if (saved_workers) {
- cbm_setenv("CBM_WORKERS", saved_workers, 1);
- free(saved_workers);
+ 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");
}
@@@ -15637,10 -26509,10 +26989,14 @@@ SUITE(pipeline)
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);
diff --cc tests/test_registry.c
index f1dbde5b5,391fd3b88..08b87783d
--- a/tests/test_registry.c
+++ b/tests/test_registry.c
@@@ -1147,307 -1688,46 +1688,347 @@@ TEST(weak_call_guards_share_one_drop_li
PASS();
}
+TEST(external_import_shadow_drops_package_bound_bare_call) {
+ /* #1355: `import { eq, sql } from "drizzle-orm"` binds both names to a
+ * package outside the indexed tree, so no import-map key exists for them and
+ * a project-wide same-name guess is a fabricated edge. */
+ CBMImport imports[] = {
+ {.local_name = "eq", .module_path = "drizzle-orm"},
+ {.local_name = "sql", .module_path = "drizzle-orm"},
+ {.local_name = "users", .module_path = "./schema"},
+ };
+ CBMImportArray arr = {.items = imports, .count = 3, .cap = 3};
+ /* Only the relative import materialized an IMPORTS edge. */
+ const char *keys[] = {"users"};
+
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("eq", "unique_name", &arr, keys, 1, NULL, NULL));
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("sql", "unique_name", &arr, keys, 1, NULL, NULL));
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("eq", "suffix_match", &arr, keys, 1, NULL, NULL));
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("eq", "field_type_hint", &arr, keys, 1, NULL, NULL));
+ ASSERT_TRUE(cbm_suppress_external_import_shadow("eq", "fuzzy", &arr, keys, 1, NULL, NULL));
+ /* A file whose imports all failed to materialize is still covered: the
+ * evidence is the import statement, not the map. */
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("eq", "unique_name", &arr, NULL, 0, NULL, NULL));
+ PASS();
+}
+
+TEST(external_import_shadow_keeps_everything_else) {
+ /* Negative space: every input that is NOT "bare call bound to a package
+ * import the graph could not resolve" must keep its edge. */
+ CBMImport imports[] = {
+ {.local_name = "eq", .module_path = "drizzle-orm"},
+ {.local_name = "normalize", .module_path = "./text-utils"},
+ {.local_name = "getRootContainer", .module_path = "@repo/shared"},
+ };
+ CBMImportArray arr = {.items = imports, .count = 3, .cap = 3};
+ /* The relative import and the workspace package both materialized. */
+ const char *keys[] = {"normalize", "getRootContainer"};
+ const int nkeys = 2;
+
+ /* Import-/receiver-/module-aware strategies are never this guard's business. */
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("eq", "import_map", &arr, keys, nkeys, NULL, NULL));
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("eq", "import_map_suffix", &arr, keys, nkeys,
+ NULL, NULL));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("eq", "same_module", &arr, keys, nkeys, NULL, NULL));
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("eq", "qualified_suffix", &arr, keys, nkeys,
+ NULL, NULL));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("eq", "lsp_ts_import", &arr, keys, nkeys, NULL, NULL));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("eq", "lsp_ts_method", &arr, keys, nkeys, NULL, NULL));
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("eq", "service_pattern", &arr, keys, nkeys,
+ NULL, NULL));
+ /* A relative specifier names a path inside the tree — a missing IMPORTS edge
+ * there is an in-project gap, not an external binding. */
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("normalize", "unique_name", &arr, keys, nkeys,
+ NULL, NULL));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("normalize", "unique_name", &arr, NULL, 0, NULL, NULL));
+ /* A package the import map DOES bind resolved in-graph (workspace package). */
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("getRootContainer", "unique_name", &arr, keys,
+ nkeys, NULL, NULL));
+ /* A name the file never imports (called with no import at all). */
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("helper", "unique_name", &arr, keys, nkeys,
+ NULL, NULL));
+ /* Member and package/namespace-qualified callees belong to the
+ * receiver-aware guards, not to this one. */
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("eq.apply", "unique_name", &arr, keys, nkeys,
+ NULL, NULL));
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("eq::apply", "unique_name", &arr, keys, nkeys,
+ NULL, NULL));
+ /* Empty / absent inputs. */
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("eq", NULL, &arr, keys, nkeys, NULL, NULL));
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("eq", "", &arr, keys, nkeys, NULL, NULL));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow(NULL, "unique_name", &arr, keys, nkeys, NULL, NULL));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("", "unique_name", &arr, keys, nkeys, NULL, NULL));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("eq", "unique_name", NULL, keys, nkeys, NULL, NULL));
+ PASS();
+}
+
+TEST(external_import_shadow_relative_binding_wins_the_tie) {
+ /* A name imported from BOTH a package and a relative path keeps its edge,
+ * and does so independently of the order the imports were extracted in —
+ * the relative binding is an explicit tie-break, not an emergent property
+ * of iteration order. */
+ CBMImport pkg_first[] = {
+ {.local_name = "eq", .module_path = "drizzle-orm"},
+ {.local_name = "eq", .module_path = "./text-utils"},
+ };
+ CBMImport rel_first[] = {
+ {.local_name = "eq", .module_path = "./text-utils"},
+ {.local_name = "eq", .module_path = "drizzle-orm"},
+ };
+ CBMImportArray a = {.items = pkg_first, .count = 2, .cap = 2};
+ CBMImportArray b = {.items = rel_first, .count = 2, .cap = 2};
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("eq", "unique_name", &a, NULL, 0, NULL, NULL));
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("eq", "unique_name", &b, NULL, 0, NULL, NULL));
+ PASS();
+}
+
+TEST(external_import_shadow_windows_relative_specifier_kept) {
+ /* #1355 follow-up: a Windows-style specifier —
+ * drive-letter absolute (`C:\...` / `C:/...`) or UNC share (`\\server\...`)
+ * — names a path inside the indexed tree exactly like a POSIX "./x" or
+ * "/x". pr-smoke runs this pipeline on Windows; before this fix these
+ * specifiers fell through to "external package" and the same-name guess
+ * they'd otherwise validate got suppressed on that platform only. */
+ CBMImport imports[] = {
+ {.local_name = "eq", .module_path = "C:\\repo\\src\\text-utils.ts"},
+ {.local_name = "sql", .module_path = "C:/repo/src/text-utils.ts"},
+ {.local_name = "normalize", .module_path = "\\\\server\\share\\text-utils.ts"},
+ };
+ CBMImportArray arr = {.items = imports, .count = 3, .cap = 3};
+
+ /* None of these materialized an import-map key (as if resolution missed
+ * them, mirroring the reported scenario) — the specifier alone must still
+ * keep the edge because it is in-tree, not external. RED before the fix
+ * (specifier_is_relative saw '.' / '/' only, so all three were classified
+ * external and suppressed); GREEN after. */
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("eq", "unique_name", &arr, NULL, 0, NULL, NULL));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("sql", "unique_name", &arr, NULL, 0, NULL, NULL));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("normalize", "unique_name", &arr, NULL, 0, NULL, NULL));
+ /* A bare package specifier without any drive letter or leading separator
+ * (e.g. "drizzle-orm") must still be external — this predicate must not
+ * become "anything with a colon or backslash". */
+ CBMImport pkg_only[] = {
+ {.local_name = "eq", .module_path = "drizzle-orm"},
+ };
+ CBMImportArray parr = {.items = pkg_only, .count = 1, .cap = 1};
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("eq", "unique_name", &parr, NULL, 0, NULL, NULL));
+ PASS();
+}
+
+TEST(external_import_shadow_workspace_sibling_kept) {
+ /* #1355 / #1732: inside a workspace monorepo a BARE specifier can still name
+ * in-tree code — `import { eq } from "drizzle-orm"` written inside the
+ * drizzle-orm repository is a sibling package, not a dependency. Measured on
+ * drizzle-team/drizzle-orm at b7862528: without this check the guard removed
+ * 2609 CALLS edges, 1377 of which pointed at exactly the file the specifier
+ * names. The package map is keyed by each in-tree manifest's `name`, so the
+ * tree's own claim decides. */
+ CBMImport imports[] = {
+ {.local_name = "eq", .module_path = "drizzle-orm"},
+ {.local_name = "pgTable", .module_path = "drizzle-orm/pg-core"},
+ {.local_name = "hoisted", .module_path = "@scope/kit/sub"},
+ {.local_name = "test", .module_path = "vitest"},
+ };
+ CBMImportArray arr = {.items = imports, .count = 4, .cap = 4};
+
+ CBMHashTable *pkgs = cbm_ht_create(8);
+ ASSERT_NOT_NULL(pkgs);
+ cbm_ht_set(pkgs, "drizzle-orm", (void *)"qn");
+ cbm_ht_set(pkgs, "@scope/kit", (void *)"qn");
+
+ /* Exact name, subpath, and scoped subpath all resolve to an in-tree
+ * package — the same-name fallback keeps its chance. */
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("eq", "unique_name", &arr, NULL, 0, pkgs, NULL));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("pgTable", "suffix_match", &arr, NULL, 0, pkgs, NULL));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("hoisted", "unique_name", &arr, NULL, 0, pkgs, NULL));
+ /* A genuine third-party dependency is untouched by the new check: the tree
+ * declares no package called "vitest", so the #1355 removal still happens. */
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("test", "suffix_match", &arr, NULL, 0, pkgs, NULL));
+
+ /* A tree with no manifests at all (pkgmap NULL) keeps the pre-existing
+ * specifier-shape-only contract — every one of these is external again. */
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("eq", "unique_name", &arr, NULL, 0, NULL, NULL));
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("pgTable", "suffix_match", &arr, NULL, 0, NULL, NULL));
+
+ /* An unrelated package map must not accidentally match by prefix: "drizzle"
+ * is not "drizzle-orm", and the walk is by path segment, not by substring. */
+ CBMHashTable *other = cbm_ht_create(8);
+ ASSERT_NOT_NULL(other);
+ cbm_ht_set(other, "drizzle", (void *)"qn");
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("eq", "unique_name", &arr, NULL, 0, other, NULL));
+
+ cbm_ht_free(other);
+ cbm_ht_free(pkgs);
+ PASS();
+}
+
+TEST(external_import_shadow_declared_package_kept) {
+ /* #1355: package-path specifiers (Java, Kotlin, C#, PHP) carry NO shape
+ * that separates in-tree from third-party — `import
+ * org.jetbrains.exposed.v1.tests.shared.assertEquals` is spelled exactly
+ * like `import kotlin.test.assertEquals`, and neither is "relative". Only
+ * the tree's own `package` declarations tell them apart; the manifests the
+ * package map reads (pom.xml, build.gradle) name artifacts, not packages.
+ * Measured on JetBrains/Exposed at 0e4d81a4: without this check the guard
+ * removed 426 CALLS edges, every one of them a real in-project call into
+ * the repository's own Assert.kt. */
+ CBMImport imports[] = {
+ {.local_name = "assertEquals", .module_path = "org.example.tests.shared.assertEquals"},
+ {.local_name = "assertEquals", .module_path = "kotlin.test.assertEquals"},
+ {.local_name = "Helper", .module_path = "org.example.util.Helper"},
+ {.local_name = "URL", .module_path = "java.net.URL"},
+ {.local_name = "Logger", .module_path = "App\\Support\\Logger"},
+ };
+ CBMImportArray arr = {.items = imports, .count = 5, .cap = 5};
+
+ CBMHashTable *nspkgs = cbm_ht_create(8);
+ ASSERT_NOT_NULL(nspkgs);
+ cbm_ht_set(nspkgs, "org.example.tests.shared", (void *)"qn");
+ cbm_ht_set(nspkgs, "org.example.util", (void *)"qn");
+ cbm_ht_set(nspkgs, "App.Support", (void *)"qn");
+
+ /* The specifier names a member of a package the tree declares, so the walk
+ * strips the member segment and finds it — the call keeps its edge. */
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("assertEquals", "suffix_match", &arr, NULL, 0,
+ NULL, nspkgs));
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("Helper", "unique_name", &arr, NULL, 0, NULL, nspkgs));
+ /* PHP writes its separator as a backslash; the key normalization has to
+ * match the namespace map's, which stores dots. */
+ ASSERT_FALSE(
+ cbm_suppress_external_import_shadow("Logger", "unique_name", &arr, NULL, 0, NULL, nspkgs));
+ /* Negative space, and the effect the census called valuable: `java.net.URL`
+ * walks to "java.net" then "java", neither declared by any project file, so
+ * a bare `URL` bound to an in-tree URL class is still cut. */
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("URL", "suffix_match", &arr, NULL, 0, NULL, nspkgs));
+ /* NULL restores the previous contract: without the declared-package set
+ * every one of these reads as external again. */
+ ASSERT_TRUE(cbm_suppress_external_import_shadow("assertEquals", "suffix_match", &arr, NULL, 0,
+ NULL, NULL));
+ ASSERT_TRUE(
+ cbm_suppress_external_import_shadow("Helper", "unique_name", &arr, NULL, 0, NULL, NULL));
+
+ /* The walk is by dotted segment, not by substring: a tree that declares
+ * "org.example.tests" must not claim "org.example.testsuite.helper". */
+ CBMImport near[] = {
+ {.local_name = "near", .module_path = "org.example.testsuite.helper.near"},
+ };
+ CBMImportArray narr = {.items = near, .count = 1, .cap = 1};
+ CBMHashTable *prefix_only = cbm_ht_create(8);
+ ASSERT_NOT_NULL(prefix_only);
+ cbm_ht_set(prefix_only, "org.example.tests", (void *)"qn");
+ ASSERT_TRUE(cbm_suppress_external_import_shadow("near", "unique_name", &narr, NULL, 0, NULL,
+ prefix_only));
+
+ cbm_ht_free(prefix_only);
+ cbm_ht_free(nspkgs);
+ PASS();
+}
+
+TEST(external_import_shadow_declared_prefix_is_permissive) {
+ /* #1355, known limitation pinned deliberately. The declared-package walk
+ * has no floor: once the tree declares `com.example`, a third-party
+ * library publishing under `com.example.vendor` reads as in-tree and the
+ * guard stands down. The call then keeps exactly the edge it has on main,
+ * so this direction costs a fabricated edge the guard could have removed —
+ * it never removes a real one, which is the side a call-resolution
+ * suppressor has to fail on.
+ *
+ * This test exists so the behaviour cannot change silently: tightening the
+ * walk (stopping at the first type-shaped segment, say) must flip these
+ * two assertions, not slip through unnoticed. */
+ CBMImport imports[] = {
+ {.local_name = "vendorCall", .module_path = "com.example.vendor.pkg.vendorCall"},
+ };
+ CBMImportArray arr = {.items = imports, .count = 1, .cap = 1};
+
+ CBMHashTable *declares_prefix = cbm_ht_create(8);
+ ASSERT_NOT_NULL(declares_prefix);
+ cbm_ht_set(declares_prefix, "com.example", (void *)"qn");
+ /* The tree declares only the prefix, yet the whole subtree is treated as
+ * in-tree — the permissive direction. */
+ ASSERT_FALSE(cbm_suppress_external_import_shadow("vendorCall", "unique_name", &arr, NULL, 0,
+ NULL, declares_prefix));
+
+ /* Change nothing but the declared package and the guard fires again, which
+ * is what proves the previous assertion came from the prefix walk and not
+ * from some other clause standing down. */
+ CBMHashTable *declares_other = cbm_ht_create(8);
+ ASSERT_NOT_NULL(declares_other);
+ cbm_ht_set(declares_other, "com.other", (void *)"qn");
+ ASSERT_TRUE(cbm_suppress_external_import_shadow("vendorCall", "unique_name", &arr, NULL, 0,
+ NULL, declares_other));
+
+ cbm_ht_free(declares_other);
+ cbm_ht_free(declares_prefix);
+ PASS();
+}
+
+ TEST(go_suppress_drops_weak_selector_matches) {
+ /* Go selector call with an untyped receiver, landed via a receiver-blind
+ * short-name strategy → drop (same failure class as #592/#606).
+ * suffix_match/fuzzy drop at any confidence; unique_name drops only when
+ * import-unreachability-penalized (CONF_UNIQUE_NAME 0.75 * 0.5 = 0.375 —
+ * the `io.Copy` -> project `Copy` stdlib-hijack shape). */
+ ASSERT_TRUE(cbm_go_suppress_weak_method_match(true, true, "suffix_match", 0.9));
+ ASSERT_TRUE(cbm_go_suppress_weak_method_match(true, true, "suffix_match", 0.11));
+ ASSERT_TRUE(cbm_go_suppress_weak_method_match(true, true, "fuzzy", 0.9));
+ ASSERT_TRUE(cbm_go_suppress_weak_method_match(true, true, "unique_name", 0.375));
+ /* field_type_hint is a receiver-NAME substring match, not type evidence
+ * (F-G9): weak for Go like the shared list. */
+ ASSERT_TRUE(cbm_go_suppress_weak_method_match(true, true, "field_type_hint", 0.85));
+ PASS();
+ }
+
+ TEST(go_suppress_keeps_typed_and_import_aware_matches) {
+ /* Unpenalized unique_name = lone candidate inside the caller's import
+ * closure (or an import-free file, e.g. same-package) — a genuinely-typed
+ * lone-candidate call never enters the field-type-hint upgrade, so it must
+ * survive (lrp_go_s8_field_type_hint). */
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, true, "unique_name", 0.75));
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, true, "same_module", 0.9));
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, true, "import_map", 0.95));
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, true, "import_map_suffix", 0.9));
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, true, "qualified_suffix", 0.9));
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, true, "callee_suffix", 0.5));
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, true, "service_pattern", 0.5));
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, true, "lsp_strategy_cross_file", 0.92));
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, true, "lsp_direct", 0.95));
+ /* A bare call (is_method=false) is a free-function call → never suppressed. */
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, false, "suffix_match", 0.11));
+ /* Non-Go languages are never affected by this gate. */
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(false, true, "suffix_match", 0.11));
+ /* No match (NULL/empty strategy) → nothing to suppress. */
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, true, NULL, 0.5));
+ ASSERT_FALSE(cbm_go_suppress_weak_method_match(true, true, "", 0.5));
+ PASS();
+ }
+
/* ── Suite ─────────────────────────────────────────────────────── */
/* Method call THROUGH an imported symbol that is itself an indexed node
@@@ -1551,12 -2282,14 +2583,21 @@@ SUITE(registry)
RUN_TEST(weak_member_unique_name_exempt_is_python_self_rooted_unique_and_specific_only);
RUN_TEST(local_binding_suppress_drops_weak_shadowed_bare_calls);
RUN_TEST(local_binding_suppress_keeps_unshadowed_and_strong_strategies);
+ RUN_TEST(import_binding_suppress_drops_only_weak_contradicted_calls);
+ RUN_TEST(python_import_binding_contradicts_only_foreign_chains);
+ RUN_TEST(python_external_base_contradicts_django_shapes);
RUN_TEST(weak_call_guards_share_one_drop_list);
+ RUN_TEST(external_import_shadow_drops_package_bound_bare_call);
+ RUN_TEST(external_import_shadow_keeps_everything_else);
+ RUN_TEST(external_import_shadow_relative_binding_wins_the_tie);
+ RUN_TEST(external_import_shadow_windows_relative_specifier_kept);
+ RUN_TEST(external_import_shadow_workspace_sibling_kept);
+ RUN_TEST(external_import_shadow_declared_package_kept);
+ RUN_TEST(external_import_shadow_declared_prefix_is_permissive);
+ RUN_TEST(go_suppress_drops_weak_selector_matches);
+ RUN_TEST(go_suppress_keeps_typed_and_import_aware_matches);
+ RUN_TEST(registry_python_function_local_is_exact_only_issue1548);
+ RUN_TEST(registry_resolve_lexical_walks_enclosing_defs_issue1548);
+ RUN_TEST(registry_python_local_bound_at_own_file_issue1548);
+ RUN_TEST(fqn_symbol_prefix_len_matches_fqn_compute);
}