Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
fix(python): separate package symbol scope from file identity
Martin Vogel132ded8c602a
diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.hindex 9b2f07bf0..f9d42ec36 100644--- a/internal/cbm/cbm.h+++ b/internal/cbm/cbm.h@@ -543,6 +543,7 @@ typedef enum {CBM_LSP_COMPLETE = 0,CBM_LSP_MEMO_FAILED,CBM_LSP_DEPTH_EXCEEDED,+ CBM_LSP_SCOPE_FAILED,} CBMLSPStatus;// Growable arrays used during extraction.@@ -1286,4 +1287,9 @@ bool cbm_label_is_relation(const char *label);// `label` may be NULL (returns false). Defined in helpers.c.bool cbm_label_is_registry_symbol(const char *label);+/* Python symbol scope only: callers must establish the language explicitly.+ * A trailing .__init__ is omitted when a nonempty prefix precedes it; raw+ * Module/file identity is unchanged. NULL returns zero. */+size_t cbm_fqn_symbol_scope_len(const char *module_qn);+#endif // CBM_Hdiff --git a/internal/cbm/helpers.c b/internal/cbm/helpers.cindex c5b81000b..b793524b3 100644--- a/internal/cbm/helpers.c+++ b/internal/cbm/helpers.c@@ -1816,6 +1816,17 @@ char *cbm_fqn_compute(CBMArena *a, const char *project, const char *rel_path, coreturn buf;}+size_t cbm_fqn_symbol_scope_len(const char *module_qn) {+ if (!module_qn)+ return 0;+ size_t len = strlen(module_qn);+ static const char suffix[] = ".__init__";+ size_t suffix_len = sizeof(suffix) - 1;+ if (len > suffix_len && memcmp(module_qn + len - suffix_len, suffix, suffix_len) == 0)+ return len - suffix_len;+ return len;+}+char *cbm_fqn_module(CBMArena *a, const char *project, const char *rel_path) {return cbm_fqn_compute(a, project, rel_path, NULL);}diff --git a/internal/cbm/lsp/py_lsp.c b/internal/cbm/lsp/py_lsp.cindex 836e6557c..8f64dfb2b 100644--- a/internal/cbm/lsp/py_lsp.c+++ b/internal/cbm/lsp/py_lsp.c@@ -43,6 +43,10 @@#ifdef CBM_ENABLE_TEST_SEAMSstatic _Thread_local int py_test_memo_allocations_left = -1;static _Thread_local bool py_test_depth_failure;+static _Thread_local int py_test_scope_allocations_left = -1;+void cbm_py_lsp_test_scope_fail_after(int successful_allocations) {+ py_test_scope_allocations_left = successful_allocations;+}void cbm_py_lsp_test_depth_fail(bool enabled) {py_test_depth_failure = enabled;}@@ -69,8 +73,9 @@ void cbm_py_lsp_record_failure(CBMFileResult *result, CBMLSPStatus status) {result->has_error = true;result->lsp_skipped = true;/* Static lifetime also works when the result arena cannot allocate. */- result->error_msg =- status == CBM_LSP_DEPTH_EXCEEDED ? CBM_PY_LSP_DEPTH_ERROR : CBM_PY_LSP_MEMO_ERROR;+ result->error_msg = status == CBM_LSP_SCOPE_FAILED ? CBM_PY_LSP_SCOPE_ERROR+ : status == CBM_LSP_DEPTH_EXCEEDED ? CBM_PY_LSP_DEPTH_ERROR+ : CBM_PY_LSP_MEMO_ERROR;}// Forward decls@@ -294,9 +299,34 @@ static void py_scope_restore(PyLSPContext *ctx, CBMScope *saved) {ctx->current_scope = saved;}-void py_lsp_init(PyLSPContext *ctx, CBMArena *arena, const char *source, int source_len,- const CBMTypeRegistry *registry, const char *module_qn,- CBMResolvedCallArray *out) {+/* Only a changed Python scope needs storage. Failure is explicit: never+ * register or walk a package using the raw file scope as an OOM fallback. */+static bool py_symbol_scope(CBMArena *arena, const char *module_qn, const char *stage,+ const char **out) {+ *out = module_qn;+ size_t len = cbm_fqn_symbol_scope_len(module_qn);+ if (!module_qn || module_qn[len] == '\0')+ return true;+#ifdef CBM_ENABLE_TEST_SEAMS+ const char *fail_stage = getenv("CBM_TEST_PY_LSP_SCOPE_FAIL_STAGE");+ if ((fail_stage && strcmp(fail_stage, stage) == 0) || py_test_scope_allocations_left == 0)+ return false;+ if (py_test_scope_allocations_left > 0)+ py_test_scope_allocations_left--;+#else+ (void)stage;+#endif+ char *scope = cbm_arena_strndup(arena, module_qn, len);+ if (!scope)+ return false;+ *out = scope;+ return true;+}++static void py_lsp_init_for_stage(PyLSPContext *ctx, CBMArena *arena, const char *source,+ int source_len, const CBMTypeRegistry *registry,+ const char *module_qn, CBMResolvedCallArray *out,+ const char *stage) {if (!ctx)return;memset(ctx, 0, sizeof(PyLSPContext));@@ -310,13 +340,23 @@ void py_lsp_init(PyLSPContext *ctx, CBMArena *arena, const char *source, int souctx->source_len = source_len;ctx->registry = registry;ctx->registry_head = (CBMTypeRegistry *)registry;- ctx->module_qn = module_qn;+ ctx->file_module_qn = module_qn;ctx->resolved_calls = out;+ if (!py_symbol_scope(arena, module_qn, stage, &ctx->module_qn)) {+ ctx->eval_failure = CBM_LSP_SCOPE_FAILED;+ return;+ }ctx->current_scope = py_scope_push_checked(ctx);const char *dbg = getenv("CBM_LSP_DEBUG");ctx->debug = dbg && dbg[0] && dbg[0] != '0';}+void py_lsp_init(PyLSPContext *ctx, CBMArena *arena, const char *source, int source_len,+ const CBMTypeRegistry *registry, const char *module_qn,+ CBMResolvedCallArray *out) {+ py_lsp_init_for_stage(ctx, arena, source, source_len, registry, module_qn, out, "context");+}+void py_lsp_add_import(PyLSPContext *ctx, const char *local_name, const char *module_qn) {if (!ctx || !local_name || !module_qn)return;@@ -2952,17 +2992,18 @@ static void py_emit_call_for(PyLSPContext *ctx, TSNode call_node) {// segment) and look up "<root>.<mod>". A genuinely-external module// (requests, os) has no such project def, so it correctly stays// lsp_module_attr_unresolved.- if (mod && ctx->module_qn) {- const char *last_dot = strrchr(ctx->module_qn, '.');- if (last_dot && last_dot > ctx->module_qn) {- size_t root_len = (size_t)(last_dot - ctx->module_qn);+ if (mod && ctx->file_module_qn) {+ const char *last_dot = strrchr(ctx->file_module_qn, '.');+ if (last_dot && last_dot > ctx->file_module_qn) {+ size_t root_len = (size_t)(last_dot - ctx->file_module_qn);// Skip if mod is already rooted under the project to avoid// "<root>.<root>.mod".- if (!(strncmp(mod, ctx->module_qn, root_len) == 0 && mod[root_len] == '.')) {+ if (!(strncmp(mod, ctx->file_module_qn, root_len) == 0 &&+ mod[root_len] == '.')) {char *qual_mod =(char *)cbm_arena_alloc(ctx->arena, root_len + 1 + strlen(mod) + 1);if (qual_mod) {- memcpy(qual_mod, ctx->module_qn, root_len);+ memcpy(qual_mod, ctx->file_module_qn, root_len);qual_mod[root_len] = '.';strcpy(qual_mod + root_len + 1, mod);const CBMRegisteredFunc *qf =@@ -4421,6 +4462,7 @@ static void py_bind_external_module_classes(PyLSPContext *ctx, const PyKids *rk)return;}size_t prefix_len = strlen(ctx->module_qn);+ bool package_scope = ctx->file_module_qn && strcmp(ctx->file_module_qn, ctx->module_qn) != 0;CBMTypeShortIter all_types;cbm_registry_all_types_chain(ctx->registry, &all_types);for (int i = -1; (i = cbm_type_short_iter_next(&all_types)) >= 0;) {@@ -4431,6 +4473,8 @@ static void py_bind_external_module_classes(PyLSPContext *ctx, const PyKids *rk)cbm_scope_lookup_local(defined, name)) {continue;}+ if (package_scope && strchr(qn + prefix_len + 1, '.'))+ continue; /* submodule/nested classes are not package globals */py_scope_bind(ctx, name, cbm_type_named(ctx->arena, qn));}}@@ -4935,7 +4979,7 @@ void py_lsp_process_file(PyLSPContext *ctx, TSNode root) {const char *prev_func = ctx->enclosing_func_qn;/* Extraction uses the file's Module QN at top level. Keep the caller* arena-owned for cross-file APIs whose module_qn input may be temporary. */- ctx->enclosing_func_qn = cbm_arena_sprintf(ctx->arena, "%s", ctx->module_qn);+ ctx->enclosing_func_qn = cbm_arena_sprintf(ctx->arena, "%s", ctx->file_module_qn);// Pass 1: execute top-level binding effects in source order. Function// bodies remain deferred until the final module scope has been assembled.for (uint32_t i = 0; i < nc && !ctx->eval_failure; i++) {@@ -5169,6 +5213,16 @@ void cbm_run_py_lsp(CBMArena *arena, CBMFileResult *result, const char *source,if (!arena || !result || result->lsp_skipped)return;+ CBMTypeRegistry reg;+ cbm_registry_init(®, arena);+ PyLSPContext ctx;+ py_lsp_init_for_stage(&ctx, arena, source, source_len, ®, result->module_qn,+ &result->resolved_calls, "raw");+ if (ctx.eval_failure) {+ cbm_py_lsp_record_failure(result, ctx.eval_failure);+ return;+ }+/* Inject minimal builtin definitions as real graph nodes (builtins.len,* builtins.str, builtins.str.upper, ...). The typeshed registry already* RESOLVES builtin calls (emitting the strategy + a "builtins.*" callee_qn),@@ -5178,12 +5232,9 @@ void cbm_run_py_lsp(CBMArena *arena, CBMFileResult *result, const char *source,* builtin/constructor/method edges point at. Upsert dedups by QN. */py_builtins_inject_defs(result, arena);- CBMTypeRegistry reg;- cbm_registry_init(®, arena);-cbm_python_stdlib_register(®, arena);- const char *module_qn = result->module_qn;+ const char *module_qn = ctx.module_qn;// Register the file's own definitions so calls inside this file can// resolve via the registry.@@ -5204,8 +5255,6 @@ void cbm_run_py_lsp(CBMArena *arena, CBMFileResult *result, const char *source,reg.index_first_registered = true;cbm_registry_finalize_into(®, &idx_arena);- PyLSPContext ctx;- py_lsp_init(&ctx, arena, source, source_len, ®, module_qn, &result->resolved_calls);/* Let the resolver inject synthetic syntactic calls for operator/subscript* dunder desugaring so those recovered calls reach the CALLS-edge pipeline. */ctx.syn_calls = &result->calls;@@ -5303,7 +5352,7 @@ static void py_split_field_defs(CBMArena *arena, const char *field_defs, const c/* Build a registry from CBMLSPDef[] supplied by the caller — covers both* the source file's own defs and cross-file referenced defs. */-static void py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRegistry *reg,+static bool py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRegistry *reg,CBMLSPDef *defs, int def_count) {/* Pass 1: types only — the method pass probes the registry per Method def* (receiver auto-registration), which is a LINEAR scan pre-finalize:@@ -5367,7 +5416,13 @@ static void py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeReret_types[n] = NULL;}}- PySignatureParamParserContext parser_ctx = {.module_qn = d->def_module_qn};+ const char *symbol_scope = d->def_module_qn;+ /* Fallback definitions can be mixed-language. Only authoritative+ * Python metadata opts into package scope normalization. */+ if (d->lang == CBM_LANG_PYTHON &&+ !py_symbol_scope(arena, d->def_module_qn, "register", &symbol_scope))+ return false;+ PySignatureParamParserContext parser_ctx = {.module_qn = symbol_scope};const CBMType **param_types = cbm_type_materialize_signature_params(arena, d->signature_param_types, d->signature_param_count,py_signature_param_type_adapter, &parser_ctx);@@ -5387,8 +5442,16 @@ static void py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRecbm_registry_add_func(reg, rf);}}+ return true;}+#ifdef CBM_ENABLE_TEST_SEAMS+bool cbm_py_lsp_test_register_defs(CBMArena *arena, CBMTypeRegistry *reg, CBMLSPDef *defs,+ int def_count) {+ return py_register_lsp_defs(arena, NULL, reg, defs, def_count);+}+#endif+bool cbm_run_py_lsp_cross(CBMArena *arena, const char *source, int source_len,const char *module_qn, CBMLSPDef *defs, int def_count,const char **import_names, const char **import_qns, int import_count,@@ -5431,15 +5494,20 @@ CBMLSPStatus cbm_run_py_lsp_cross_status(CBMArena *arena, const char *source, in/* Index allocations go to a per-call scratch arena (see php_lsp_cross). */CBMArena idx_arena;cbm_arena_init(&idx_arena);- py_register_lsp_defs(arena, &idx_arena, ®, defs, def_count);+ PyLSPContext ctx;+ py_lsp_init_for_stage(&ctx, arena, source, source_len, ®, module_qn, out, "cross");+ if (ctx.eval_failure)+ goto cross_cleanup;+ if (!py_register_lsp_defs(arena, &idx_arena, ®, defs, def_count)) {+ ctx.eval_failure = CBM_LSP_SCOPE_FAILED;+ goto cross_cleanup;+ }py_mark_ambiguous_callable_bindings(®);/* Finalize registry — O(1) lookups. See go_lsp.c "3c. Finalize"* comment for the rationale. */cbm_registry_finalize_into(®, &idx_arena);- PyLSPContext ctx;- py_lsp_init(&ctx, arena, source, source_len, ®, module_qn, out);ctx.syn_calls = synthetic_calls;for (int i = 0; i < import_count; i++) {if (import_names && import_qns && import_names[i] && import_qns[i]) {@@ -5448,6 +5516,7 @@ CBMLSPStatus cbm_run_py_lsp_cross_status(CBMArena *arena, const char *source, in}py_memo_test_stage(&ctx, "cross");py_lsp_process_file(&ctx, root);+cross_cleanup:cbm_arena_destroy(&idx_arena);if (owns_tree && tree)@@ -5473,7 +5542,8 @@ CBMTypeRegistry *cbm_py_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, iif (d->lang != CBM_LANG_PYTHON)continue;/* Reuse the existing register fn on a single-def slice (n=1 inline). */- py_register_lsp_defs(arena, NULL, reg, d, 1);+ if (!py_register_lsp_defs(arena, NULL, reg, d, 1))+ return NULL; /* caller owns the shared arena and other registries */}py_mark_ambiguous_callable_bindings(reg);@@ -5517,7 +5587,9 @@ CBMLSPStatus cbm_run_py_lsp_cross_with_registry_status(TSNode root = ts_tree_root_node(tree);PyLSPContext ctx;- py_lsp_init(&ctx, arena, source, source_len, reg, module_qn, out);+ py_lsp_init_for_stage(&ctx, arena, source, source_len, reg, module_qn, out, "cross");+ if (ctx.eval_failure)+ goto prebuilt_cleanup;ctx.syn_calls = synthetic_calls;for (int i = 0; i < import_count; i++) {if (import_names && import_qns && import_names[i] && import_qns[i]) {@@ -5526,7 +5598,7 @@ CBMLSPStatus cbm_run_py_lsp_cross_with_registry_status(}py_memo_test_stage(&ctx, "cross");py_lsp_process_file(&ctx, root);-+prebuilt_cleanup:if (owns_tree && tree)ts_tree_delete(tree);if (parser)diff --git a/internal/cbm/lsp/py_lsp.h b/internal/cbm/lsp/py_lsp.hindex 908406ca8..85f06587a 100644--- a/internal/cbm/lsp/py_lsp.h+++ b/internal/cbm/lsp/py_lsp.h@@ -61,7 +61,8 @@ typedef struct {// caller QNs.const char *enclosing_func_qn;const char *enclosing_class_qn;- const char *module_qn;+ const char *module_qn; // Python symbol scope (package __init__ omitted)+ const char *file_module_qn; // raw file identity; borrowed for this API call// Output: resolved calls accumulate here.CBMResolvedCallArray *resolved_calls;@@ -102,7 +103,7 @@ typedef struct {uint32_t type_cache_gen; // bumped on every scope mutation (O(1) flush)int eval_depth; // evaluator recursion depth (PY_LSP_MAX_EVAL_DEPTH)uint32_t eval_truncations; // depth-cap cutoff count — gates memo inserts- CBMLSPStatus eval_failure; // sticky: memo/depth failure makes this walk incomplete+ CBMLSPStatus eval_failure; // sticky: explicit failure makes this walk incomplete// Pending links of the left-associative chains being evaluated// iteratively (operator, receiver, subscript, conditional and// parenthesis chains): one stack shared by nested evaluations.@@ -173,10 +174,14 @@ void cbm_python_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena);#define CBM_PY_LSP_DEPTH_ERROR "Python expression recursion depth limit exceeded"#define CBM_PY_LSP_MEMO_ERROR "Python expression memo allocation or capacity failure"+#define CBM_PY_LSP_SCOPE_ERROR "Python symbol scope allocation failure"void cbm_py_lsp_record_failure(CBMFileResult *result, CBMLSPStatus status);#ifdef CBM_ENABLE_TEST_SEAMSvoid cbm_py_lsp_test_memo_fail_after(int successful_allocations);void cbm_py_lsp_test_depth_fail(bool enabled);+void cbm_py_lsp_test_scope_fail_after(int successful_allocations);+bool cbm_py_lsp_test_register_defs(CBMArena *arena, CBMTypeRegistry *reg, CBMLSPDef *defs,+ int def_count);const CBMType *cbm_py_lsp_test_eval(PyLSPContext *ctx, TSNode node);void cbm_py_lsp_test_bind_external_classes(PyLSPContext *ctx, TSNode root);#endifdiff --git a/src/pipeline/pass_calls.c b/src/pipeline/pass_calls.cindex 7be198ee7..4057b3128 100644--- a/src/pipeline/pass_calls.c+++ b/src/pipeline/pass_calls.c@@ -385,7 +385,7 @@ bool cbm_pipeline_http_client_call_url(const cbm_gbuf_t *gbuf, const char *projestatic void handle_route_registration(cbm_pipeline_ctx_t *ctx, const CBMCall *call,const cbm_gbuf_node_t *source_node, const char *module_qn,const char **imp_keys, const char **imp_vals, int imp_count,- const char *route_mount) {+ const char *route_mount, CBMLanguage lang) {const char *method = cbm_service_pattern_route_method(call->callee_name);char mounted[CBM_SZ_256];const char *path =@@ -410,7 +410,7 @@ static void handle_route_registration(cbm_pipeline_ctx_t *ctx, const CBMCall *caif (call->second_arg_name != NULL && call->second_arg_name[0] != '\0') {cbm_resolution_t hres =cbm_registry_resolve_handler(ctx->registry, call->second_arg_name, module_qn, imp_keys,- imp_vals, imp_count, ctx->gbuf);+ imp_vals, imp_count, ctx->gbuf, lang);if (hres.qualified_name != NULL && hres.qualified_name[0] != '\0') {const cbm_gbuf_node_t *handler = cbm_gbuf_find_by_qn(ctx->gbuf, hres.qualified_name);if (handler != NULL) {@@ -611,11 +611,12 @@ static void emit_classified_edge(cbm_pipeline_ctx_t *ctx, const CBMCall *call,const cbm_gbuf_node_t *source, const cbm_gbuf_node_t *target,const cbm_resolution_t *res, const char *module_qn,const char **imp_keys, const char **imp_vals, int imp_count,- bool suppress_plain_calls, const char *route_mount) {+ bool suppress_plain_calls, const char *route_mount,+ CBMLanguage lang) {cbm_svc_kind_t svc = cbm_service_pattern_match(res->qualified_name);if (svc == CBM_SVC_ROUTE_REG && call->first_string_arg && call->first_string_arg[0] == '/') {handle_route_registration(ctx, call, source, module_qn, imp_keys, imp_vals, imp_count,- route_mount);+ route_mount, lang);return;}if (svc == CBM_SVC_HTTP || svc == CBM_SVC_ASYNC) {@@ -708,7 +709,7 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBMreturn SKIP_ONE;}emit_classified_edge(ctx, call, source_node, target_node, &res, module_qn, imp_keys,- imp_vals, imp_count, false, route_mount);+ imp_vals, imp_count, false, route_mount, lang);return SKIP_ONE;}}@@ -774,8 +775,8 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBMlang, lsp->strategy, lsp->callee_qn, ctx->project_name);cbm_resolution_t res = {0};if (!rust_external) {- res = cbm_registry_resolve(ctx->registry, call->callee_name, module_qn, imp_keys, imp_vals,- imp_count);+ res = cbm_registry_resolve_lang(ctx->registry, call->callee_name, module_qn, imp_keys,+ imp_vals, imp_count, lang);/* Cross-language veto: a name-only guess never binds another* language's symbol (a JS app.get must not become Python's* builtins.dict.get). The vetoed answer becomes EMPTY here, before@@ -828,7 +829,7 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBMif (cbm_service_pattern_route_method(call->callee_name) != NULL && call->first_string_arg &&call->first_string_arg[0] == '/') {handle_route_registration(ctx, call, source_node, module_qn, imp_keys, imp_vals,- imp_count, route_mount);+ imp_count, route_mount, lang);return SKIP_ONE;}cbm_svc_kind_t esvc = cbm_service_pattern_match(call->callee_name);@@ -978,13 +979,13 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBMif (cbm_service_pattern_route_method(call->callee_name) != NULL && call->first_string_arg &&call->first_string_arg[0] == '/') {handle_route_registration(ctx, call, source_node, module_qn, imp_keys, imp_vals,- imp_count, route_mount);+ imp_count, route_mount, lang);return SKIP_ONE;}return 0;}emit_classified_edge(ctx, call, source_node, target_node, &res, module_qn, imp_keys, imp_vals,- imp_count, drop_plain_call, route_mount);+ imp_count, drop_plain_call, route_mount, lang);return SKIP_ONE;}@@ -1243,7 +1244,8 @@ static int scan_depends_in_sig(cbm_pipeline_ctx_t *ctx, const cbm_regex_t *re, c}memcpy(func_ref, scan + match[SKIP_ONE].rm_so, (size_t)ref_len);func_ref[ref_len] = '\0';- cbm_resolution_t res = cbm_registry_resolve(ctx->registry, func_ref, module_qn, ik, iv, ic);+ cbm_resolution_t res = cbm_registry_resolve_lang(ctx->registry, func_ref, module_qn, ik, iv,+ ic, CBM_LANG_PYTHON);if (res.qualified_name && res.qualified_name[0] != '\0') {const cbm_gbuf_node_t *sn = cbm_gbuf_find_by_qn(ctx->gbuf, def->qualified_name);const cbm_gbuf_node_t *tn = cbm_gbuf_find_by_qn(ctx->gbuf, res.qualified_name);diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.cindex 3e10e73d2..c72a2a5d0 100644--- a/src/pipeline/pass_lsp_cross.c+++ b/src/pipeline/pass_lsp_cross.c@@ -248,8 +248,8 @@ static const char *pxc_resolve_base_qn(const pxc_base_scope_t *bs, const char *rif (!bs || !bs->reg || !raw || !raw[0]) {return NULL;}- cbm_resolution_t res =- cbm_registry_resolve(bs->reg, raw, module_qn, bs->imp_keys, bs->imp_vals, bs->imp_count);+ cbm_resolution_t res = cbm_registry_resolve_lang(bs->reg, raw, module_qn, bs->imp_keys,+ bs->imp_vals, bs->imp_count, bs->lang);if (!res.qualified_name || !res.qualified_name[0]) {return NULL;}@@ -2187,16 +2187,33 @@ static void pxc_mark_module_defs(const CBMModuleDefIndex *idx, bool *selected,* (`project.module`). Select the nearest materialized module prefix; the* language registry still has to prove the full target QN before an edge is* emitted, so this broadens the candidate set without weakening precision. */-static void pxc_mark_import_defs(const CBMModuleDefIndex *idx, bool *selected,+#ifdef CBM_ENABLE_TEST_SEAMS+static _Thread_local int pxc_import_probe_allocations_left = -1;+void cbm_pxc_test_import_probe_fail_after(int successful_allocations) {+ pxc_import_probe_allocations_left = successful_allocations;+}+#endif++static bool pxc_mark_import_defs(const CBMModuleDefIndex *idx, bool *selected,const CBMLSPDef *all_defs, CBMLanguage caller_lang,const char *import_qn, int *total) {if (!idx || !idx->ht || !import_qn || !import_qn[0]) {- return;- }- char *candidate = strdup(import_qn);- if (!candidate) {- return;+ return true;}+ static const char init_seg[] = ".__init__";+ size_t import_len = strlen(import_qn);+ if (import_len > SIZE_MAX - sizeof(init_seg))+ return false;+#ifdef CBM_ENABLE_TEST_SEAMS+ if (pxc_import_probe_allocations_left == 0)+ return false;+ if (pxc_import_probe_allocations_left > 0)+ pxc_import_probe_allocations_left--;+#endif+ char *candidate = (char *)malloc(import_len + sizeof(init_seg));+ if (!candidate)+ return false;+ memcpy(candidate, import_qn, import_len + 1);bool matched = false;for (;;) {pxc_module_entry_t *entry = (pxc_module_entry_t *)cbm_ht_get(idx->ht, candidate);@@ -2208,6 +2225,31 @@ static void pxc_mark_import_defs(const CBMModuleDefIndex *idx, bool *selected,matched = true;break;}+ if (caller_lang == CBM_LANG_PYTHON) {+ size_t cand_len = strlen(candidate);+ memcpy(candidate + cand_len, init_seg, sizeof(init_seg));+ entry = (pxc_module_entry_t *)cbm_ht_get(idx->ht, candidate);+ candidate[cand_len] = '\0';+ /* A suffixed module may be a non-Python directory named __init__.+ * Only this new probe filters strictly; normal-entry precedence+ * above remains unchanged. Eligibility is independent of dedup. */+ bool eligible = false;+ for (int j = 0; entry && j < entry->count; j++) {+ int di = entry->indices[j];+ if (all_defs[di].lang != CBM_LANG_PYTHON)+ continue;+ eligible = true;+ if (!selected[di]) {+ selected[di] = true;+ if (total)+ (*total)++;+ }+ }+ if (eligible) {+ matched = true;+ break;+ }+ }char *dot = strrchr(candidate, '.');if (!dot) {break;@@ -2238,6 +2280,7 @@ static void pxc_mark_import_defs(const CBMModuleDefIndex *idx, bool *selected,}}free(candidate);+ return true;}CBMModuleDefIndex *cbm_pxc_build_module_def_index(CBMLSPDef *all_defs, int def_count) {@@ -2317,7 +2360,10 @@ CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDefint total = 0;pxc_mark_module_defs(idx, selected, all_defs, caller_lang, own_module, &total);for (int i = 0; i < imp_count; i++) {- pxc_mark_import_defs(idx, selected, all_defs, caller_lang, imp_qns[i], &total);+ if (!pxc_mark_import_defs(idx, selected, all_defs, caller_lang, imp_qns[i], &total)) {+ free(selected);+ return NULL; /* out_success remains false: dispatcher uses all_defs */+ }}if (pxc_is_jvm_lang(caller_lang) && idx->namespace_ht) {const char *namespace_key = pxc_namespace_index_key(caller_namespace);diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.cindex 96747ef8b..8d77cf7f8 100644--- a/src/pipeline/pass_parallel.c+++ b/src/pipeline/pass_parallel.c@@ -604,9 +604,9 @@ static bool is_checked_exception(const char *name) {static const char *resolve_as_class(const cbm_registry_t *reg, const char *name,const char *module_qn, const char **imp_keys,- const char **imp_vals, int imp_count) {+ const char **imp_vals, int imp_count, CBMLanguage lang) {cbm_resolution_t res =- cbm_registry_resolve(reg, name, module_qn, imp_keys, imp_vals, imp_count);+ cbm_registry_resolve_lang(reg, name, module_qn, imp_keys, imp_vals, imp_count, lang);if (!res.qualified_name || res.qualified_name[0] == '\0') {return NULL;}@@ -2363,7 +2363,7 @@ static void emit_route_registration(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *souconst char *handler_ref, const char *module_qn,const cbm_registry_t *registry, const cbm_gbuf_t *main_gbuf,const char **ik, const char **iv, int ic,- const char *route_mount) {+ const char *route_mount, CBMLanguage lang) {const char *method = cbm_service_pattern_route_method(call->callee_name);char mounted[CBM_SZ_256];route_path = cbm_laravel_mount_route(route_mount, route_path, mounted, sizeof(mounted));@@ -2384,8 +2384,8 @@ static void emit_route_registration(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *souesc_rp);cbm_gbuf_insert_edge(gbuf, source->id, rid, "CALLS", props);if (handler_ref && handler_ref[0] != '\0') {- cbm_resolution_t hres =- cbm_registry_resolve_handler(registry, handler_ref, module_qn, ik, iv, ic, main_gbuf);+ cbm_resolution_t hres = cbm_registry_resolve_handler(registry, handler_ref, module_qn, ik,+ iv, ic, main_gbuf, lang);if (hres.qualified_name && hres.qualified_name[0] != '\0') {const cbm_gbuf_node_t *h = cbm_gbuf_find_by_qn(main_gbuf, hres.qualified_name);if (h) {@@ -2681,7 +2681,8 @@ static void emit_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,const cbm_resolution_t *res, const char *module_qn,const cbm_registry_t *registry, const cbm_gbuf_t *main_gbuf,const char **imp_keys, const char **imp_vals, int imp_count,- bool suppress_plain_calls, const char *route_mount) {+ bool suppress_plain_calls, const char *route_mount,+ CBMLanguage lang) {cbm_svc_kind_t svc = cbm_service_pattern_match(res->qualified_name);const char *arg = call->first_string_arg;@@ -2709,7 +2710,7 @@ static void emit_service_edge(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,if (route_path) {emit_route_registration(gbuf, source, call, route_path, handler_ref, module_qn,registry, main_gbuf, imp_keys, imp_vals, imp_count,- route_mount);+ route_mount, lang);return;}/* No path found — fall through to normal CALLS edge */@@ -2759,7 +2760,7 @@ static void emit_xlang_refused_route(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *soconst CBMCall *call, const char *module_qn,const cbm_registry_t *registry, const cbm_gbuf_t *main_gbuf,const char **imp_keys, const char **imp_vals, int imp_count,- const char *route_mount) {+ const char *route_mount, CBMLanguage lang) {if (cbm_service_pattern_route_method(call->callee_name) == NULL) {return;}@@ -2771,7 +2772,7 @@ static void emit_xlang_refused_route(cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *soconst char *route_path = find_route_path_in_args(call, &handler_ref);if (route_path) {emit_route_registration(gbuf, source, call, route_path, handler_ref, module_qn, registry,- main_gbuf, imp_keys, imp_vals, imp_count, route_mount);+ main_gbuf, imp_keys, imp_vals, imp_count, route_mount, lang);}}@@ -3201,8 +3202,8 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CBlang, lsp->strategy, lsp->callee_qn, rc->project_name);if ((!res.qualified_name || !res.qualified_name[0]) && !call->requires_lsp_resolution &&!rust_external) {- res = cbm_registry_resolve(rc->registry, call->callee_name, module_qn, imp_keys,- imp_vals, imp_count);+ res = cbm_registry_resolve_lang(rc->registry, call->callee_name, module_qn, imp_keys,+ imp_vals, imp_count, lang);}/* `p->open(fd)`: the registry does not split a callee on the arrow.* The object's type decides, as for the dot call handled further@@ -3330,7 +3331,7 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB.strategy = "service_pattern"};emit_service_edge(ws->local_edge_buf, source_node, source_node, call, &svc_res,module_qn, rc->registry, rc->main_gbuf, imp_keys, imp_vals,- imp_count, false, route_mount);+ imp_count, false, route_mount, lang);continue;}}@@ -3357,7 +3358,7 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB* route/HTTP/service classification is unchanged. */emit_service_edge(ws->local_edge_buf, source_node, source_node, call, &fake_res,module_qn, rc->registry, rc->main_gbuf, imp_keys, imp_vals,- imp_count, true, route_mount);+ imp_count, true, route_mount, lang);} else if (cbm_service_pattern_is_global_fetch(call->callee_name)) {/* Native `fetch()` (#856): only the global API once resolution* has failed to find a local/imported `fetch`. Call the low-level@@ -3418,7 +3419,8 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB* CALLS edge across a language boundary. A route registration* behind the refused binding still gets its Route. */emit_xlang_refused_route(ws->local_edge_buf, source_node, call, module_qn, rc->registry,- rc->main_gbuf, imp_keys, imp_vals, imp_count, route_mount);+ rc->main_gbuf, imp_keys, imp_vals, imp_count, route_mount,+ lang);continue;}if (!target_node || source_node->id == target_node->id) {@@ -3436,7 +3438,7 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CBif (url_or_topic) {emit_service_edge(ws->local_edge_buf, source_node, NULL, call, &res, module_qn,rc->registry, rc->main_gbuf, imp_keys, imp_vals, imp_count,- false, route_mount);+ false, route_mount, lang);ws->calls_resolved++;}}@@ -3445,7 +3447,7 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB_rc_t0 = extract_now_ns();emit_service_edge(ws->local_edge_buf, source_node, target_node, call, &res, module_qn,rc->registry, rc->main_gbuf, imp_keys, imp_vals, imp_count,- drop_plain_call, route_mount);+ drop_plain_call, route_mount, lang);atomic_fetch_add_explicit(&rc->time_ns_rc_emit, extract_now_ns() - _rc_t0,memory_order_relaxed);ws->calls_resolved++;@@ -3555,8 +3557,8 @@ static void resolve_file_usages(resolve_ctx_t *rc, resolve_worker_state_t *ws,(lang == CBM_LANG_SQL)? cbm_registry_resolve_lineage(rc->registry, usage->ref_name, module_qn,imp_keys, imp_vals, imp_count)- : cbm_registry_resolve(rc->registry, usage->ref_name, module_qn, imp_keys,- imp_vals, imp_count);+ : cbm_registry_resolve_lang(rc->registry, usage->ref_name, module_qn, imp_keys,+ imp_vals, imp_count, lang);if (!res.qualified_name || res.qualified_name[0] == '\0') {continue;}@@ -3612,7 +3614,8 @@ static void resolve_file_usages(resolve_ctx_t *rc, resolve_worker_state_t *ws,/* Resolve throws/raises for one file. */static void resolve_file_throws(resolve_ctx_t *rc, resolve_worker_state_t *ws,CBMFileResult *result, const char *rel, const char *module_qn,- const char **imp_keys, const char **imp_vals, int imp_count) {+ const char **imp_keys, const char **imp_vals, int imp_count,+ CBMLanguage lang) {for (int t = 0; t < result->throws.count; t++) {CBMThrow *thr = &result->throws.items[t];if (!thr->exception_name || !thr->enclosing_func_qn) {@@ -3627,8 +3630,8 @@ static void resolve_file_throws(resolve_ctx_t *rc, resolve_worker_state_t *ws,continue;}const char *edge_type = is_checked_exception(thr->exception_name) ? "THROWS" : "RAISES";- cbm_resolution_t res = cbm_registry_resolve(rc->registry, thr->exception_name, module_qn,- imp_keys, imp_vals, imp_count);+ cbm_resolution_t res = cbm_registry_resolve_lang(+ rc->registry, thr->exception_name, module_qn, imp_keys, imp_vals, imp_count, lang);if (!res.qualified_name || res.qualified_name[0] == '\0') {continue;}@@ -3686,8 +3689,8 @@ static void resolve_file_rw(resolve_ctx_t *rc, resolve_worker_state_t *ws, CBMFi}continue;}- cbm_resolution_t res = cbm_registry_resolve(rc->registry, rw->var_name, module_qn, imp_keys,- imp_vals, imp_count);+ cbm_resolution_t res = cbm_registry_resolve_lang(rc->registry, rw->var_name, module_qn,+ imp_keys, imp_vals, imp_count, lang);if (!res.qualified_name || res.qualified_name[0] == '\0') {continue;}@@ -3729,7 +3732,8 @@ static void resolve_def_inherits(resolve_ctx_t *rc, resolve_worker_state_t *ws,return;}for (int b = 0; def->base_classes[b]; b++) {- const char *bqn = resolve_as_class(rc->registry, def->base_classes[b], mq, ik, iv, ic);+ const char *bqn =+ resolve_as_class(rc->registry, def->base_classes[b], mq, ik, iv, ic, fs->lang);/* Same external-base gate as the sequential semantic pass. */if (!bqn ||cbm_python_external_base_contradicts(fs->lang, fs->imports, def->base_classes[b], bqn,@@ -3751,7 +3755,8 @@ static void resolve_def_inherits(resolve_ctx_t *rc, resolve_worker_state_t *ws,/* Resolve decorators → DECORATES edges for one definition. */static void resolve_def_decorators(resolve_ctx_t *rc, resolve_worker_state_t *ws,const CBMDefinition *def, const cbm_gbuf_node_t *node,- const char *mq, const char **ik, const char **iv, int ic) {+ const char *mq, const char **ik, const char **iv, int ic,+ CBMLanguage lang) {if (!def->decorators) {return;}@@ -3761,14 +3766,14 @@ static void resolve_def_decorators(resolve_ctx_t *rc, resolve_worker_state_t *wsif (fn[0] == '\0') {continue;}- cbm_resolution_t res = cbm_registry_resolve(rc->registry, fn, mq, ik, iv, ic);+ cbm_resolution_t res = cbm_registry_resolve_lang(rc->registry, fn, mq, ik, iv, ic, lang);if ((!res.qualified_name || res.qualified_name[0] == '\0') && !strchr(fn, '.')) {/* C# attributes are referenced by their short name (`[Log]`) but* declared with an `Attribute` suffix (`class LogAttribute`). */char with_suffix[CBM_SZ_256];int wn = snprintf(with_suffix, sizeof(with_suffix), "%sAttribute", fn);if (wn > 0 && (size_t)wn < sizeof(with_suffix)) {- res = cbm_registry_resolve(rc->registry, with_suffix, mq, ik, iv, ic);+ res = cbm_registry_resolve_lang(rc->registry, with_suffix, mq, ik, iv, ic, lang);}}const cbm_gbuf_node_t *dn = NULL;@@ -3834,7 +3839,7 @@ static void resolve_file_semantic(resolve_ctx_t *rc, resolve_worker_state_t *ws,continue;}resolve_def_inherits(rc, ws, def, node, &fs, module_qn, imp_keys, imp_vals, imp_count);- resolve_def_decorators(rc, ws, def, node, module_qn, imp_keys, imp_vals, imp_count);+ resolve_def_decorators(rc, ws, def, node, module_qn, imp_keys, imp_vals, imp_count, lang);}for (int t = 0; t < result->impl_traits.count; t++) {CBMImplTrait *it = &result->impl_traits.items[t];@@ -3842,9 +3847,9 @@ static void resolve_file_semantic(resolve_ctx_t *rc, resolve_worker_state_t *ws,continue;}const char *tqn = resolve_as_class(rc->registry, it->trait_name, module_qn, imp_keys,- imp_vals, imp_count);+ imp_vals, imp_count, lang);const char *sqn = resolve_as_class(rc->registry, it->struct_name, module_qn, imp_keys,- imp_vals, imp_count);+ imp_vals, imp_count, lang);if (!tqn || !sqn) {continue;}@@ -4191,7 +4196,8 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {(strcmp(result->error_msg, CBM_C_LSP_MEMO_ERROR) == 0 ||strcmp(result->error_msg, CBM_PY_LSP_MEMO_ERROR) == 0 ||strcmp(result->error_msg, CBM_C_LSP_DEPTH_ERROR) == 0 ||- strcmp(result->error_msg, CBM_PY_LSP_DEPTH_ERROR) == 0)) {+ strcmp(result->error_msg, CBM_PY_LSP_DEPTH_ERROR) == 0 ||+ strcmp(result->error_msg, CBM_PY_LSP_SCOPE_ERROR) == 0)) {rc->lsp_failures[file_idx] = result->error_msg;ws->errors++;}@@ -4253,7 +4259,7 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {/* ── THROWS / RAISES ───────────────────────────────────── */_ph_t0 = extract_now_ns();- resolve_file_throws(rc, ws, result, rel, module_qn, imp_keys, imp_vals, imp_count);+ resolve_file_throws(rc, ws, result, rel, module_qn, imp_keys, imp_vals, imp_count, lang);atomic_fetch_add_explicit(&rc->time_ns_throws, extract_now_ns() - _ph_t0,memory_order_relaxed);diff --git a/src/pipeline/pass_semantic.c b/src/pipeline/pass_semantic.cindex 3ef84b9dc..7894fbcf7 100644--- a/src/pipeline/pass_semantic.c+++ b/src/pipeline/pass_semantic.c@@ -182,9 +182,9 @@ static void free_import_map(const char **keys, const char **vals, int count) {/* Resolve a class/type name through the registry. Returns borrowed QN or NULL. */static const char *resolve_as_class(const cbm_registry_t *reg, const char *name,const char *module_qn, const char **imp_keys,- const char **imp_vals, int imp_count) {+ const char **imp_vals, int imp_count, CBMLanguage lang) {cbm_resolution_t res =- cbm_registry_resolve(reg, name, module_qn, imp_keys, imp_vals, imp_count);+ cbm_registry_resolve_lang(reg, name, module_qn, imp_keys, imp_vals, imp_count, lang);if (!res.qualified_name || res.qualified_name[0] == '\0') {return NULL;}@@ -558,14 +558,14 @@ static void synth_decorator_qn(const char *func_name, char *out, size_t outsz) {/* Resolve one decorator and create DECORATES edge. */static void resolve_decorator(cbm_pipeline_ctx_t *ctx, const cbm_gbuf_node_t *node,const char *decorator, const char *module_qn, const char **imp_keys,- const char **imp_vals, int imp_count, int *count) {+ const char **imp_vals, int imp_count, int *count, CBMLanguage lang) {char func_name[CBM_SZ_256];extract_decorator_func(decorator, func_name, sizeof(func_name));if (func_name[0] == '\0') {return;}- cbm_resolution_t res =- cbm_registry_resolve(ctx->registry, func_name, module_qn, imp_keys, imp_vals, imp_count);+ cbm_resolution_t res = cbm_registry_resolve_lang(ctx->registry, func_name, module_qn, imp_keys,+ imp_vals, imp_count, lang);if ((!res.qualified_name || res.qualified_name[0] == '\0') && !strchr(func_name, '.')) {/* C# attributes are referenced by their short name (`[Log]`) but declared* with the conventional `Attribute` suffix (`class LogAttribute`). Retry@@ -573,8 +573,8 @@ static void resolve_decorator(cbm_pipeline_ctx_t *ctx, const cbm_gbuf_node_t *nochar with_suffix[CBM_SZ_256];int wn = snprintf(with_suffix, sizeof(with_suffix), "%sAttribute", func_name);if (wn > 0 && (size_t)wn < sizeof(with_suffix)) {- res = cbm_registry_resolve(ctx->registry, with_suffix, module_qn, imp_keys, imp_vals,- imp_count);+ res = cbm_registry_resolve_lang(ctx->registry, with_suffix, module_qn, imp_keys,+ imp_vals, imp_count, lang);}}const cbm_gbuf_node_t *dec = NULL;@@ -626,7 +626,7 @@ static void sem_process_def_edges(cbm_pipeline_ctx_t *ctx, const CBMDefinition *const cbm_file_info_t *fi, const CBMFileResult *result,const char *module_qn, const char **imp_keys,const char **imp_vals, int imp_count, int *inherits_count,- int *decorates_count) {+ int *decorates_count, CBMLanguage lang) {if (!def->qualified_name) {return;}@@ -637,7 +637,7 @@ static void sem_process_def_edges(cbm_pipeline_ctx_t *ctx, const CBMDefinition *if (def->base_classes) {for (int b = 0; def->base_classes[b]; b++) {const char *base_qn = resolve_as_class(ctx->registry, def->base_classes[b], module_qn,- imp_keys, imp_vals, imp_count);+ imp_keys, imp_vals, imp_count, lang);if (!base_qn || cbm_python_external_base_contradicts(fi->language, &result->imports, def->base_classes[b], base_qn,ctx->gbuf, ctx->project_name, fi->rel_path)) {@@ -661,7 +661,7 @@ static void sem_process_def_edges(cbm_pipeline_ctx_t *ctx, const CBMDefinition *if (def->decorators) {for (int dc = 0; def->decorators[dc]; dc++) {resolve_decorator(ctx, node, def->decorators[dc], module_qn, imp_keys, imp_vals,- imp_count, decorates_count);+ imp_count, decorates_count, lang);}}}@@ -706,12 +706,12 @@ static int resolve_impl_traits(cbm_pipeline_ctx_t *ctx, const CBMFileResult *rescontinue;}const char *trait_qn = resolve_as_class(ctx->registry, it->trait_name, module_qn, imp_keys,- imp_vals, imp_count);+ imp_vals, imp_count, CBM_LANG_RUST);if (!trait_qn) {continue;}const char *struct_qn = resolve_as_class(ctx->registry, it->struct_name, module_qn,- imp_keys, imp_vals, imp_count);+ imp_keys, imp_vals, imp_count, CBM_LANG_RUST);if (!struct_qn) {continue;}@@ -770,7 +770,8 @@ int cbm_pipeline_pass_semantic(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *f/* ── INHERITS + DECORATES from definitions ──────────────── */for (int d = 0; d < result->defs.count; d++) {sem_process_def_edges(ctx, &result->defs.items[d], &files[i], result, module_qn,- imp_keys, imp_vals, imp_count, &inherits_count, &decorates_count);+ imp_keys, imp_vals, imp_count, &inherits_count, &decorates_count,+ files[i].language);}/* ── IMPLEMENTS from impl_traits (Rust) ─────────────────── */diff --git a/src/pipeline/pass_usages.c b/src/pipeline/pass_usages.cindex 1ce353c02..c3988a7de 100644--- a/src/pipeline/pass_usages.c+++ b/src/pipeline/pass_usages.c@@ -246,8 +246,8 @@ static int resolve_usage_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *res(lang == CBM_LANG_SQL)? cbm_registry_resolve_lineage(ctx->registry, usage->ref_name, module_qn,imp_keys, imp_vals, imp_count)- : cbm_registry_resolve(ctx->registry, usage->ref_name, module_qn, imp_keys,- imp_vals, imp_count);+ : cbm_registry_resolve_lang(ctx->registry, usage->ref_name, module_qn, imp_keys,+ imp_vals, imp_count, lang);if (!res.qualified_name || res.qualified_name[0] == '\0') {continue;}@@ -300,7 +300,7 @@ static int resolve_usage_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *res/* Resolve THROWS/RAISES edges for one file's extracted throws. */static int resolve_throw_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *result,const char *rel, const char *module_qn, const char **imp_keys,- const char **imp_vals, int imp_count) {+ const char **imp_vals, int imp_count, CBMLanguage lang) {int resolved = 0;for (int t = 0; t < result->throws.count; t++) {CBMThrow *thr = &result->throws.items[t];@@ -314,8 +314,8 @@ static int resolve_throw_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *res}const char *edge_type = is_checked_exception(thr->exception_name) ? "THROWS" : "RAISES";- cbm_resolution_t res = cbm_registry_resolve(ctx->registry, thr->exception_name, module_qn,- imp_keys, imp_vals, imp_count);+ cbm_resolution_t res = cbm_registry_resolve_lang(+ ctx->registry, thr->exception_name, module_qn, imp_keys, imp_vals, imp_count, lang);const cbm_gbuf_node_t *tgt = NULL;if (res.qualified_name && res.qualified_name[0]) {@@ -380,8 +380,8 @@ static int resolve_rw_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *resultcontinue;}- cbm_resolution_t res = cbm_registry_resolve(ctx->registry, rw->var_name, module_qn,- imp_keys, imp_vals, imp_count);+ cbm_resolution_t res = cbm_registry_resolve_lang(ctx->registry, rw->var_name, module_qn,+ imp_keys, imp_vals, imp_count, lang);if (!res.qualified_name || res.qualified_name[0] == '\0') {continue;}@@ -484,8 +484,8 @@ int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *filusage_resolved += resolve_usage_edges(ctx, result, rel, module_qn, imp_keys, imp_vals,imp_count, files[i].language);- throw_resolved +=- resolve_throw_edges(ctx, result, rel, module_qn, imp_keys, imp_vals, imp_count);+ throw_resolved += resolve_throw_edges(ctx, result, rel, module_qn, imp_keys, imp_vals,+ imp_count, files[i].language);rw_resolved += resolve_rw_edges(ctx, result, rel, module_qn, imp_keys, imp_vals, imp_count,files[i].language);diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.hindex 17ce77164..5fb746b07 100644--- a/src/pipeline/pipeline_internal.h+++ b/src/pipeline/pipeline_internal.h@@ -246,6 +246,15 @@ bool cbm_pipeline_frozen_manifests_equal(cbm_pipeline_t *p, const cbm_file_hash_int left_count, const cbm_file_hash_t *right,int right_count);+/* Internal explicit-language resolution; public raw/lineage APIs stay raw. */+cbm_resolution_t cbm_registry_resolve_lang(const cbm_registry_t *r, const char *callee_name,+ const char *module_qn, const char **import_map_keys,+ const char **import_map_vals, int import_map_count,+ CBMLanguage lang);+#ifdef CBM_ENABLE_TEST_SEAMS+void cbm_pxc_test_import_probe_fail_after(int successful_allocations);+#endif+/* ── Shared pipeline constants ─────────────────────────────────── *//* Per-file tree-sitter parse budget, in MICROSECONDS of this thread's CPU time@@ -604,11 +613,12 @@ void cbm_pipeline_set_pkgmap(CBMHashTable *map);* (#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 does. */+ * 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);+ 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 neverdiff --git a/src/pipeline/registry.c b/src/pipeline/registry.cindex 644b42b7c..ce5c4f8a7 100644--- a/src/pipeline/registry.c+++ b/src/pipeline/registry.c@@ -438,6 +438,7 @@ void cbm_registry_import_map_cache_end(void) {* eliminated. */typedef struct {cbm_resolution_t res;+ size_t scope_len; /* raw and Python-scoped requests may share one file cache */} resolve_cache_entry_t;static CBM_TLS CBMHashTable *_resolve_cache = NULL;@@ -1432,22 +1433,45 @@ static cbm_resolution_t resolve_import_map(const cbm_registry_t *r, const char *return empty_result();}-/* Strategy 2: Same-module match */-static cbm_resolution_t resolve_same_module(const cbm_registry_t *r, const char *callee_name,- const char *suffix, const char *module_qn) {+/* Exact same-module lookup without ever hashing a truncated candidate. The+ * long path uses the canonical short-name bucket, not heuristic name limits. */+static const char *same_module_candidate(const cbm_registry_t *r, const char *module_qn,+ size_t scope_len, const char *name) {+ if (!module_qn || !name)+ return NULL;+ size_t name_len = strlen(name);char candidate[CBM_SZ_512];- snprintf(candidate, sizeof(candidate), "%s.%s", module_qn, callee_name);- const char *stored_key = cbm_ht_get_key(r->exact, candidate);- if (stored_key) {- return (cbm_resolution_t){stored_key, "same_module", CONF_SAME_MODULE, REG_RESOLVED};- }- if (suffix && suffix[0]) {- snprintf(candidate, sizeof(candidate), "%s.%s", module_qn, suffix);- stored_key = cbm_ht_get_key(r->exact, candidate);- if (stored_key) {- return (cbm_resolution_t){stored_key, "same_module", CONF_SAME_MODULE, REG_RESOLVED};- }+ if (scope_len < sizeof(candidate) && name_len < sizeof(candidate) - scope_len - 1) {+ memcpy(candidate, module_qn, scope_len);+ candidate[scope_len] = '.';+ memcpy(candidate + scope_len + 1, name, name_len + 1);+ return cbm_ht_get_key(r->exact, candidate);+ }+ qn_array_t *arr = (qn_array_t *)cbm_ht_get(r->by_name, simple_name(name));+ if (!arr)+ return NULL;+ for (int i = 0; i < arr->count; i++) {+ const char *qn = arr->items[i];+ if (!qn)+ continue;+ size_t qn_len = strlen(qn);+ if (qn_len > scope_len && qn_len - scope_len - 1 == name_len &&+ memcmp(qn, module_qn, scope_len) == 0 && qn[scope_len] == '.' &&+ memcmp(qn + scope_len + 1, name, name_len) == 0)+ return qn;}+ return NULL;+}++/* Strategy 2: Same-module match. Scoring elsewhere retains the raw file QN. */+static cbm_resolution_t resolve_same_module(const cbm_registry_t *r, const char *callee_name,+ const char *suffix, const char *module_qn,+ size_t scope_len) {+ const char *stored_key = same_module_candidate(r, module_qn, scope_len, callee_name);+ if (!stored_key && suffix && suffix[0])+ stored_key = same_module_candidate(r, module_qn, scope_len, suffix);+ if (stored_key)+ return (cbm_resolution_t){stored_key, "same_module", CONF_SAME_MODULE, REG_RESOLVED};return empty_result();}@@ -1699,7 +1723,8 @@ static cbm_resolution_t resolve_name_lookup(const cbm_registry_t *r, const char* cbm_registry_resolve owns the per-file cache). */static cbm_resolution_t registry_resolve_chain(const cbm_registry_t *r, const char *callee_name,const char *module_qn, const char **import_map_keys,- const char **import_map_vals, int import_map_count) {+ const char **import_map_vals, int import_map_count,+ size_t scope_len) {/* Split callee at the first path separator: "pkg.Func" → prefix="pkg",* suffix="Func". Rust/C++ use "::" rather than ".", so honor whichever* separator appears first ("lib::square" → prefix="lib", suffix="square").@@ -1732,7 +1757,7 @@ static cbm_resolution_t registry_resolve_chain(const cbm_registry_t *r, const chresolve_import_map(r, prefix, suffix, import_map_keys, import_map_vals, import_map_count);if (!(res.qualified_name && res.qualified_name[0])) {/* Strategy 2: same module */- res = resolve_same_module(r, callee_name, suffix, module_qn);+ res = resolve_same_module(r, callee_name, suffix, module_qn, scope_len);}if (!(res.qualified_name && res.qualified_name[0])) {/* Strategy 3+4: name lookup */@@ -1784,9 +1809,10 @@ bool cbm_registry_name_guess_vetoed(const cbm_registry_t *r, CBMLanguage caller_registry_entry_language(r, res->qualified_name));}-cbm_resolution_t cbm_registry_resolve(const cbm_registry_t *r, const char *callee_name,- const char *module_qn, const char **import_map_keys,- const char **import_map_vals, int import_map_count) {+static cbm_resolution_t registry_resolve_scoped(const cbm_registry_t *r, const char *callee_name,+ const char *module_qn, const char **import_map_keys,+ const char **import_map_vals, int import_map_count,+ size_t scope_len) {if (!r || !callee_name) {return empty_result();}@@ -1794,16 +1820,13 @@ cbm_resolution_t cbm_registry_resolve(const cbm_registry_t *r, const char *calle/* Per-file cache: same callee_name in N call sites → 1 chain walk* + N-1 O(1) hash hits. module_qn is constant per file so the* cache key only needs callee_name. */- if (_resolve_cache) {- resolve_cache_entry_t *cached =- (resolve_cache_entry_t *)cbm_ht_get(_resolve_cache, callee_name);- if (cached) {- return cached->res;- }- }+ resolve_cache_entry_t *cached =+ _resolve_cache ? (resolve_cache_entry_t *)cbm_ht_get(_resolve_cache, callee_name) : NULL;+ if (cached && cached->scope_len == scope_len)+ return cached->res;cbm_resolution_t res = registry_resolve_chain(r, callee_name, module_qn, import_map_keys,- import_map_vals, import_map_count);+ import_map_vals, import_map_count, scope_len);/* Data relations (Table/View) are lineage-only registry members: common* table names (users, orders, config) collide with code identifiers across@@ -1819,10 +1842,15 @@ cbm_resolution_t cbm_registry_resolve(const cbm_registry_t *r, const char *calle/* Cache the result (including empty — caching the negative answer* is just as valuable; same name asks the same question). */- if (_resolve_cache) {+ if (cached) {+ /* Same key, different effective scope: reuse its owned entry/key. */+ cached->res = res;+ cached->scope_len = scope_len;+ } else if (_resolve_cache) {resolve_cache_entry_t *e = (resolve_cache_entry_t *)malloc(sizeof(*e));if (e) {e->res = res;+ e->scope_len = scope_len;char *kdup = strdup(callee_name);if (kdup) {cbm_ht_set(_resolve_cache, kdup, e);@@ -1834,6 +1862,23 @@ cbm_resolution_t cbm_registry_resolve(const cbm_registry_t *r, const char *callereturn res;}+cbm_resolution_t cbm_registry_resolve(const cbm_registry_t *r, const char *callee_name,+ const char *module_qn, const char **import_map_keys,+ const char **import_map_vals, int import_map_count) {+ return registry_resolve_scoped(r, callee_name, module_qn, import_map_keys, import_map_vals,+ import_map_count, module_qn ? strlen(module_qn) : 0);+}++cbm_resolution_t cbm_registry_resolve_lang(const cbm_registry_t *r, const char *callee_name,+ const char *module_qn, const char **import_map_keys,+ const char **import_map_vals, int import_map_count,+ CBMLanguage lang) {+ size_t scope_len = lang == CBM_LANG_PYTHON ? cbm_fqn_symbol_scope_len(module_qn)+ : (module_qn ? strlen(module_qn) : 0);+ return registry_resolve_scoped(r, callee_name, module_qn, import_map_keys, import_map_vals,+ import_map_count, scope_len);+}+/* ── Class-qualified route handlers (PHP, #1146) ─────────────────── *//* Method QNs are path-based: <project>.<dirs>.<file stem>.<Class>.<method>.@@ -1950,11 +1995,11 @@ static const char *aligned_member_qn(const cbm_registry_t *r, const char *fqn, scbm_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) {+ const cbm_gbuf_t *gbuf, CBMLanguage lang) {const char *sep = handler_ref ? strstr(handler_ref, "::") : NULL;if (!r || !sep) {- return cbm_registry_resolve(r, handler_ref, module_qn, import_map_keys, import_map_vals,- import_map_count);+ return cbm_registry_resolve_lang(r, handler_ref, module_qn, import_map_keys,+ import_map_vals, import_map_count, lang);}const char *member = sep + PAIR_LEN;size_t fqn_len = (size_t)(sep - handler_ref);@@ -1999,7 +2044,7 @@ cbm_resolution_t cbm_registry_resolve_lineage(const cbm_registry_t *r, const cha* it would poison one variant with the other's semantics. SQL files hold* few distinct relation refs, so the chain walk stays cheap. */return registry_resolve_chain(r, callee_name, module_qn, import_map_keys, import_map_vals,- import_map_count);+ import_map_count, module_qn ? strlen(module_qn) : 0);}/* ── Fuzzy Resolve ──────────────────────────────────────────────── */diff --git a/tests/test_pipeline.c b/tests/test_pipeline.cindex b106c46d6..280bf61bf 100644--- a/tests/test_pipeline.c+++ b/tests/test_pipeline.c@@ -10892,6 +10892,352 @@ TEST(pipeline_python_module_callers_parallel) {return python_module_callers_pipeline_case(true);}+/* Python file identity keeps .__init__; its exported symbols do not. */+static bool python_init_local_inheritance(cbm_store_t *store, const char *project,+ const char *module) {+ char child_qn[768], parent_qn[768], wrong_qn[768];+ int cn = snprintf(child_qn, sizeof(child_qn), "%s.%s.BooleanField", project, module);+ int pn = snprintf(parent_qn, sizeof(parent_qn), "%s.%s.Field", project, module);+ int wn = snprintf(wrong_qn, sizeof(wrong_qn), "%s.other.Field", project);+ if (cn <= 0 || (size_t)cn >= sizeof(child_qn) || pn <= 0 || (size_t)pn >= sizeof(parent_qn) ||+ wn <= 0 || (size_t)wn >= sizeof(wrong_qn))+ return false;+ cbm_node_t child = {0}, parent = {0}, wrong = {0};+ bool ok = cbm_store_find_node_by_qn(store, project, child_qn, &child) == CBM_STORE_OK &&+ cbm_store_find_node_by_qn(store, project, parent_qn, &parent) == CBM_STORE_OK &&+ cbm_store_find_node_by_qn(store, project, wrong_qn, &wrong) == CBM_STORE_OK &&+ child.id > 0 && parent.id > 0 && wrong.id > 0 && parent.id != wrong.id &&+ child.label && parent.label && wrong.label && strcmp(child.label, "Class") == 0 &&+ strcmp(parent.label, "Class") == 0 && strcmp(wrong.label, "Class") == 0;+ cbm_edge_t *edges = NULL;+ int count = 0, local = 0, foreign = 0;+ if (ok) {+ ok = cbm_store_find_edges_by_source_type(store, child.id, "INHERITS", &edges, &count) ==+ CBM_STORE_OK;+ for (int i = 0; ok && i < count; i++) {+ local += edges[i].target_id == parent.id;+ foreign += edges[i].target_id == wrong.id;+ }+ }+ cbm_store_free_edges(edges, count);+ cbm_node_free_fields(&child);+ cbm_node_free_fields(&parent);+ cbm_node_free_fields(&wrong);+ return ok && local == 1 && foreign == 0;+}++static int python_init_scope_pipeline_case(bool parallel, const char *failure_stage) {+ static const char body[] = "from util import normalize\n"+ "from other import Field as OtherField\n"+ "def helper(value):\n return normalize(value)\n"+ "class Field:\n"+ " def clean(self, value):\n return helper(value)\n"+ " def validate(self, value):\n return self.clean(value)\n"+ "class BooleanField(Field):\n"+ " def to_python(self, value):\n"+ " self.validate(value)\n return helper(value)\n"+ "def build(value):\n"+ " field = BooleanField()\n"+ " field.to_python(value)\n return helper(value)\n";+ static const char consumer[] = "from pkg import BooleanField, helper\n"+ "def consume(value):\n"+ " field = BooleanField()\n"+ " field.to_python(value)\n return helper(value)\n";+ static const struct {+ const char *caller;+ const char *caller_label;+ const char *target;+ const char *target_label;+ } local_edges[] = {+ {"Field.clean", "Method", "helper", "Function"},+ {"Field.validate", "Method", "Field.clean", "Method"},+ {"BooleanField.to_python", "Method", "Field.validate", "Method"},+ {"BooleanField.to_python", "Method", "helper", "Function"},+ {"build", "Function", "BooleanField.to_python", "Method"},+ {"build", "Function", "helper", "Function"},+ };+ char root[512], path[768];+ int n = snprintf(root, sizeof(root), "%s/cbm-python-init-XXXXXX", cbm_tmpdir());+ if (n <= 0 || (size_t)n >= sizeof(root) || !cbm_mkdtemp(root))+ FAIL("failed to create Python package fixture");+ n = snprintf(path, sizeof(path), "%s/pkg", root);+ bool written = n > 0 && (size_t)n < sizeof(path);+ if (written) {+ cbm_mkdir_p(path, 0755);+ written = python_module_write_fixture_file(+ root, "pkg/__init__.py",+ failure_stage ? "class S:\n def m(self):\n return 1\n"+ "def run():\n s = S()\n return s.m()\n"+ : body);+ }+ if (written && !failure_stage) {+ written = python_module_write_fixture_file(root, "plain.py", body) &&+ python_module_write_fixture_file(root, "consumer.py", consumer) &&+ python_module_write_fixture_file(root, "util.py",+ "def normalize(value):\n return value\n") &&+ python_module_write_fixture_file(root, "other.py", "class Field:\n pass\n");+ }+ for (int i = 0; written && parallel && i < 52; i++) {+ char name[64];+ snprintf(name, sizeof(name), "init_pad_%02d.py", i);+ written = python_module_write_fixture_file(root, name, "# inert parallel routing file\n");+ }+ if (!written) {+ th_rmtree(root);+ FAIL("failed to write Python package fixture");+ }+ const char *keys[] = {"CBM_WORKERS", "CBM_INDEX_SINGLE_THREAD",+ "CBM_TEST_PY_LSP_SCOPE_FAIL_STAGE"};+ char *saved[3] = {0};+ bool saved_ok = true;+ for (int i = 0; i < 3; i++) {+ const char *old = getenv(keys[i]);+ saved[i] = old ? strdup(old) : NULL;+ saved_ok = saved_ok && (!old || saved[i]);+ }+ if (!saved_ok) {+ for (int i = 0; i < 3; i++)+ free(saved[i]);+ th_rmtree(root);+ FAIL("failed to save Python package fixture environment");+ }+ int set_rc = cbm_setenv(keys[0], parallel ? "4" : "1", 1);+ set_rc |= parallel ? cbm_unsetenv(keys[1]) : cbm_setenv(keys[1], "1", 1);+ set_rc |= failure_stage ? cbm_setenv(keys[2], failure_stage, 1) : cbm_unsetenv(keys[2]);+ n = snprintf(path, sizeof(path), "%s/package.db", root);+ cbm_pipeline_t *pipeline = set_rc == 0 && n > 0 && (size_t)n < sizeof(path)+ ? cbm_pipeline_new(root, path, CBM_MODE_FULL)+ : NULL;+ int run_rc = pipeline ? cbm_pipeline_run(pipeline) : -1;+ cbm_file_error_t *errors = NULL;+ int error_count = 0, scope_errors = 0;+ bool precise = true;+ cbm_pipeline_get_file_errors(pipeline, &errors, &error_count);+ for (int i = 0; i < error_count; i++) {+ bool is_package = errors[i].path && strcmp(errors[i].path, "pkg/__init__.py") == 0;+ if (failure_stage && is_package) {+ scope_errors++;+ const char *phase = strcmp(failure_stage, "raw") == 0 ? "extract" : "lsp_skipped";+ precise = precise && errors[i].phase && strcmp(errors[i].phase, phase) == 0 &&+ errors[i].reason && strcmp(errors[i].reason, CBM_PY_LSP_SCOPE_ERROR) == 0;+ } else {+ precise = false;+ }+ }+ cbm_store_t *store = run_rc == 0 ? cbm_store_open_path(path) : NULL;+ bool correct = store != NULL;+ if (store) {+ const char *project = cbm_pipeline_project_name(pipeline);+ cbm_node_t *files = NULL;+ int file_count = 0;+ correct = project &&+ cbm_store_find_nodes_by_label(store, project, "File", &files, &file_count) ==+ CBM_STORE_OK &&+ file_count == (failure_stage ? 1 : 5) + (parallel ? 52 : 0);+ cbm_store_free_nodes(files, file_count);+ if (project && !failure_stage) {+ const char *modules[] = {"plain", "pkg"};+ for (int m = 0; m < 2; m++) {+ for (size_t i = 0; i < sizeof(local_edges) / sizeof(local_edges[0]); i++) {+ char caller[128], target[128];+ snprintf(caller, sizeof(caller), "%s.%s", modules[m], local_edges[i].caller);+ snprintf(target, sizeof(target), "%s.%s", modules[m], local_edges[i].target);+ bool edge = python_module_exact_lsp_edge(store, project, caller,+ local_edges[i].caller_label, target,+ local_edges[i].target_label);+ correct = correct && edge;+ }+ char caller[128];+ snprintf(caller, sizeof(caller), "%s.helper", modules[m]);+ bool imported = python_module_exact_lsp_edge(store, project, caller, "Function",+ "util.normalize", "Function");+ bool inherits = python_init_local_inheritance(store, project, modules[m]);+ correct = correct && imported && inherits;+ }+ bool method =+ python_module_exact_lsp_edge(store, project, "consumer.consume", "Function",+ "pkg.BooleanField.to_python", "Method");+ bool function = python_module_exact_lsp_edge(store, project, "consumer.consume",+ "Function", "pkg.helper", "Function");+ correct = correct && method && function;+ }+ cbm_store_close(store);+ }+ cbm_pipeline_free(pipeline);+ int restore_rc = 0;+ for (int i = 0; i < 3; i++) {+ restore_rc |= saved[i] ? cbm_setenv(keys[i], saved[i], 1) : cbm_unsetenv(keys[i]);+ free(saved[i]);+ }+ int cleanup_rc = th_rmtree(root);+ ASSERT_EQ(set_rc, 0);+ ASSERT_EQ(restore_rc, 0);+ ASSERT_EQ(cleanup_rc, 0);+ ASSERT_EQ(run_rc, 0);+ ASSERT_EQ(error_count, failure_stage ? 1 : 0);+ ASSERT_EQ(scope_errors, failure_stage ? 1 : 0);+ ASSERT_TRUE(precise && correct);+ PASS();+}++TEST(pipeline_python_init_scope_sequential) {+ return python_init_scope_pipeline_case(false, NULL);+}+TEST(pipeline_python_init_scope_parallel) {+ return python_init_scope_pipeline_case(true, NULL);+}+TEST(pipeline_python_init_raw_scope_failure_sequential) {+ return python_init_scope_pipeline_case(false, "raw");+}+TEST(pipeline_python_init_raw_scope_failure_parallel) {+ return python_init_scope_pipeline_case(true, "raw");+}+TEST(pipeline_python_init_cross_scope_failure_sequential) {+ return python_init_scope_pipeline_case(false, "cross");+}+TEST(pipeline_python_init_cross_scope_failure_parallel) {+ return python_init_scope_pipeline_case(true, "cross");+}+TEST(pipeline_python_init_register_scope_failure_sequential) {+ return python_init_scope_pipeline_case(false, "register");+}+TEST(pipeline_python_init_register_scope_failure_parallel) {+ return python_init_scope_pipeline_case(true, "register");+}++/* Compare identities, not just counts; a duplicate import must stop at the+ * same nearest eligible entry even when it contributes no new selections. */+static bool python_init_filter_is(CBMLSPDef *defs, int def_count, const char *const *imports,+ int import_count, const char *const *expected, int count) {+ CBMModuleDefIndex *index = cbm_pxc_build_module_def_index(defs, def_count);+ int got_count = -1;+ bool succeeded = false;+ CBMLSPDef *got =+ cbm_pxc_filter_defs_for_file(index, defs, CBM_LANG_PYTHON, NULL, "test.consumer", imports,+ import_count, &got_count, &succeeded);+ bool correct = index && succeeded && got_count == count && (count == 0 || got);+ for (int i = 0; correct && i < count; i++) {+ int hits = 0;+ for (int j = 0; j < got_count; j++)+ hits += got[j].qualified_name && strcmp(got[j].qualified_name, expected[i]) == 0;+ correct = hits == 1;+ }+ free(got);+ cbm_pxc_free_module_def_index(index);+ return correct;+}++TEST(pipeline_python_init_import_filter_precedence) {+ CBMLSPDef defs[] = {+ {.qualified_name = "test.consumer.use",+ .def_module_qn = "test.consumer",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.pkg.Store",+ .def_module_qn = "test.pkg.__init__",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.pkg.Foreign",+ .def_module_qn = "test.pkg.__init__",+ .lang = CBM_LANG_GO},+ {.qualified_name = "test.Parent",+ .def_module_qn = "test.__init__",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.foreign.Only",+ .def_module_qn = "test.foreign.__init__",+ .lang = CBM_LANG_GO},+ {.qualified_name = "test.unknown.Only",+ .def_module_qn = "test.unknown.__init__",+ .lang = (CBMLanguage)-1},+ {.qualified_name = "test.plain.Exact",+ .def_module_qn = "test.plain",+ .lang = CBM_LANG_JAVA},+ {.qualified_name = "test.plain.Package",+ .def_module_qn = "test.plain.__init__",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.pkg.nested.Item",+ .def_module_qn = "test.pkg.nested.__init__",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.pkg.sub.Item",+ .def_module_qn = "test.pkg.sub",+ .lang = CBM_LANG_PYTHON},+ };+ const char *pkg[] = {"test.pkg", "test.pkg.Store", "test.pkg.Store"};+ const char *want_pkg[] = {"test.consumer.use", "test.pkg.Store"};+ const char *foreign[] = {"test.foreign.Only", "test.unknown.Only"};+ const char *want_parent[] = {"test.consumer.use", "test.Parent"};+ const char *normal[] = {"test.plain.Exact", "test.plain.Exact"};+ const char *want_normal[] = {"test.consumer.use", "test.plain.Exact"};+ const char *nested[] = {"test.pkg.nested.Item", "test.pkg.nested.Item"};+ const char *want_nested[] = {"test.consumer.use", "test.pkg.nested.Item"};+ const char *submodule[] = {"test.pkg.sub.Item"};+ const char *want_submodule[] = {"test.consumer.use", "test.pkg.sub.Item"};+ int n = (int)(sizeof(defs) / sizeof(defs[0]));+ bool pkg_ok = python_init_filter_is(defs, n, pkg, 3, want_pkg, 2);+ bool foreign_ok = python_init_filter_is(defs, n, foreign, 2, want_parent, 2);+ bool normal_ok = python_init_filter_is(defs, n, normal, 2, want_normal, 2);+ bool nested_ok = python_init_filter_is(defs, n, nested, 2, want_nested, 2);+ bool submodule_ok = python_init_filter_is(defs, n, submodule, 1, want_submodule, 2);+ ASSERT_TRUE(pkg_ok && foreign_ok && normal_ok && nested_ok && submodule_ok);+ PASS();+}++TEST(pipeline_python_init_import_probe_failure_falls_back) {+ const char *source = "from pkg import Store\n"+ "def use():\n store = Store()\n return store.get()\n";+ CBMLSPDef defs[] = {+ {.qualified_name = "test.consumer.use",+ .short_name = "use",+ .label = "Function",+ .def_module_qn = "test.consumer",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.pkg.Store",+ .short_name = "Store",+ .label = "Class",+ .def_module_qn = "test.pkg.__init__",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.pkg.Store.get",+ .short_name = "get",+ .label = "Method",+ .def_module_qn = "test.pkg.__init__",+ .receiver_type = "test.pkg.Store",+ .return_types = "int",+ .lang = CBM_LANG_PYTHON},+ };+ const char *keys[] = {"Store"};+ const char *values[] = {"test.pkg.Store"};+ CBMModuleDefIndex *index = cbm_pxc_build_module_def_index(defs, 3);+ int count = -1;+ bool succeeded = true;+ cbm_pxc_test_import_probe_fail_after(0);+ CBMLSPDef *filtered = cbm_pxc_filter_defs_for_file(+ index, defs, CBM_LANG_PYTHON, NULL, "test.consumer", values, 1, &count, &succeeded);+ cbm_pxc_test_import_probe_fail_after(-1);+ bool failed_precisely = index && !filtered && count == 0 && !succeeded;+ free(filtered);+ CBMFileResult result = {0};+ cbm_arena_init(&result.arena);+ cbm_pxc_test_import_probe_fail_after(0);+ cbm_pxc_dispatch_file(CBM_LANG_PYTHON, &result, source, (int)strlen(source), "consumer.py",+ "test.consumer", NULL, index, defs, 3, keys, values, 1, NULL, NULL);+ cbm_pxc_test_import_probe_fail_after(-1);+ const char *site = strstr(source, "store.get()");+ int exact = 0;+ for (int i = 0; i < result.resolved_calls.count; i++) {+ const CBMResolvedCall *call = &result.resolved_calls.items[i];+ if (call->caller_qn && strcmp(call->caller_qn, "test.consumer.use") == 0 &&+ call->callee_qn && strcmp(call->callee_qn, "test.pkg.Store.get") == 0 &&+ call->kind == CBM_RESOLVED_INVOCATION && call->strategy &&+ strncmp(call->strategy, "lsp_", 4) == 0 && site &&+ call->site_start_byte == (uint32_t)(site - source) &&+ call->site_end_byte == (uint32_t)(site - source + strlen("store.get()")))+ exact++;+ }+ bool resolved = !result.has_error && !result.lsp_skipped && exact == 1;+ cbm_arena_destroy(&result.arena);+ cbm_pxc_free_module_def_index(index);+ ASSERT_TRUE(failed_precisely && resolved);+ PASS();+}+/* #1277: typed instance fields of a Python class imported from another file.* Counts CALLS edges caller -> callee (QN suffixes) whose properties name an* LSP strategy. */@@ -20582,6 +20928,16 @@ TEST(pipeline_calls_args_overlong_argument_stops_cleanly) {SUITE(pipeline) {RUN_TEST(pipeline_python_module_callers_sequential);RUN_TEST(pipeline_python_module_callers_parallel);+ RUN_TEST(pipeline_python_init_scope_sequential);+ RUN_TEST(pipeline_python_init_scope_parallel);+ RUN_TEST(pipeline_python_init_raw_scope_failure_sequential);+ RUN_TEST(pipeline_python_init_raw_scope_failure_parallel);+ RUN_TEST(pipeline_python_init_cross_scope_failure_sequential);+ RUN_TEST(pipeline_python_init_cross_scope_failure_parallel);+ RUN_TEST(pipeline_python_init_register_scope_failure_sequential);+ RUN_TEST(pipeline_python_init_register_scope_failure_parallel);+ RUN_TEST(pipeline_python_init_import_filter_precedence);+ RUN_TEST(pipeline_python_init_import_probe_failure_falls_back);RUN_TEST(pipeline_issue1527_python_raw_memo_failure_sequential);RUN_TEST(pipeline_issue1527_python_raw_memo_failure_parallel);RUN_TEST(pipeline_issue1527_python_cross_memo_failure_sequential);diff --git a/tests/test_py_lsp.c b/tests/test_py_lsp.cindex 6a7bfa114..3ac5e742f 100644--- a/tests/test_py_lsp.c+++ b/tests/test_py_lsp.c@@ -3040,7 +3040,403 @@ TEST(pylsp_module_cross_callers_own_input_and_join_exact_sites) {PASS();}+/* Package symbols use their parent scope while Module callers retain the file. */+TEST(pylsp_init_scope_context_and_helper) {+ static const struct {+ const char *raw;+ const char *scope;+ } cases[] = {+ {"test.__init__", "test"},+ {"test.pkg.__init__", "test.pkg"},+ {"test.pkg.nested.__init__", "test.pkg.nested"},+ {"test.plain", "test.plain"},+ {"test.x__init__", "test.x__init__"},+ {"__init__", "__init__"},+ {"test.index", "test.index"},+ {NULL, NULL},+ };+ bool correct = true;+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {+ CBMArena arena;+ cbm_arena_init(&arena);+ CBMTypeRegistry registry;+ cbm_registry_init(®istry, &arena);+ CBMResolvedCallArray out = {0};+ PyLSPContext ctx;+ py_lsp_init(&ctx, &arena, "pass\n", 5, ®istry, cases[i].raw, &out);+ correct =+ correct && ctx.eval_failure == CBM_LSP_COMPLETE && ctx.current_scope &&+ ctx.file_module_qn == cases[i].raw &&+ cbm_fqn_symbol_scope_len(cases[i].raw) == (cases[i].scope ? strlen(cases[i].scope) : 0);+ correct =+ correct && (cases[i].scope ? ctx.module_qn && strcmp(ctx.module_qn, cases[i].scope) == 0+ : ctx.module_qn == NULL);+ cbm_arena_destroy(&arena);+ }+ ASSERT_TRUE(correct);+ PASS();+}++TEST(pylsp_init_scope_raw_exact_occurrences_and_annotations) {+ static const char source[] =+ "class Store:\n def get(self):\n return 1\n"+ "def identity(value: Store) -> Store:\n return value\n"+ "def quoted(value: 'Store') -> 'Store':\n return value\n"+ "def wrapped(values: list[Store]) -> Store:\n return values[0]\n"+ "def run(first: Store, second: 'Store', values: list[Store]):\n"+ " first.get()\n second.get()\n values[0].get()\n"+ " identity(first).get()\n quoted(second).get()\n"+ " wrapped(values).get()\n"+ "class User:\n def use(self, item: Store):\n return item.get()\n"+ "top = Store()\ntop.get()\n";+ static const char *paths[] = {"plain.py", "__init__.py", "pkg/nested/__init__.py"};+ static const char *scopes[] = {"test.plain", "test", "test.pkg.nested"};+ static const char *modules[] = {"test.plain", "test.__init__", "test.pkg.nested.__init__"};+ static const char *sites[] = {"first.get()", "second.get()",+ "values[0].get()", "identity(first).get()",+ "quoted(second).get()", "wrapped(values).get()"};+ bool correct = true;+ for (int mode = 0; mode < 3; mode++) {+ CBMFileResult *r = cbm_extract_file(source, (int)strlen(source), CBM_LANG_PYTHON, "test",+ paths[mode], 0, NULL, NULL);+ bool extracted = r && !r->has_error && !r->parse_incomplete && !r->lsp_skipped &&+ r->module_qn && strcmp(r->module_qn, modules[mode]) == 0;+ correct = correct && extracted;+ if (extracted) {+ char caller[128], target[128], method[128];+ snprintf(caller, sizeof(caller), "%s.run", scopes[mode]);+ snprintf(target, sizeof(target), "%s.Store.get", scopes[mode]);+ snprintf(method, sizeof(method), "%s.User.use", scopes[mode]);+ correct = correct && pylsp_module_has_def(r, caller) &&+ pylsp_module_has_def(r, target) && pylsp_module_has_def(r, method);+ for (size_t j = 0; j < sizeof(sites) / sizeof(sites[0]); j++) {+ bool joined = pylsp_module_site_joins(&r->calls, &r->resolved_calls, source,+ sites[j], caller, target);+ correct = correct && joined;+ }+ bool method_join = pylsp_module_site_joins(&r->calls, &r->resolved_calls, source,+ "item.get()", method, target);+ bool module_join = pylsp_module_site_joins(&r->calls, &r->resolved_calls, source,+ "top.get()", modules[mode], target);+ correct = correct && method_join && module_join;+ }+ if (r)+ cbm_free_result(r);+ }+ ASSERT_TRUE(correct);+ PASS();+}++static bool pylsp_init_named_type(const CBMType *type, const char *qn) {+ return type && type->kind == CBM_TYPE_NAMED && type->data.named.qualified_name &&+ strcmp(type->data.named.qualified_name, qn) == 0;+}++static bool pylsp_init_signature(const CBMTypeRegistry *registry, const char *function,+ const char *expected_type) {+ const CBMRegisteredFunc *f = cbm_registry_lookup_func(registry, function);+ const CBMType *sig = f ? f->signature : NULL;+ if (!sig || sig->kind != CBM_TYPE_FUNC || !sig->data.func.param_types)+ return false;+ const CBMType **params = sig->data.func.param_types;+ if (!pylsp_init_named_type(params[0], expected_type) ||+ !pylsp_init_named_type(params[1], expected_type) || !params[2] || params[3])+ return false;+ const CBMType *container = params[2];+ return container->kind == CBM_TYPE_TEMPLATE && container->data.template_type.template_name &&+ strcmp(container->data.template_type.template_name, "list") == 0 &&+ container->data.template_type.arg_count == 1 &&+ container->data.template_type.template_args &&+ pylsp_init_named_type(container->data.template_type.template_args[0], expected_type);+}++TEST(pylsp_init_scope_cross_signatures_keep_definition_language) {+ const char *params[] = {"Token", "'Token'", "list[Token]"};+ CBMLSPDef defs[] = {+ {.qualified_name = "test.pkg.call",+ .short_name = "call",+ .label = "Function",+ .def_module_qn = "test.pkg.__init__",+ .lang = CBM_LANG_PYTHON,+ .signature_param_types = params,+ .signature_param_count = 3},+ {.qualified_name = "test.foreign.__init__.call",+ .short_name = "call",+ .label = "Function",+ .def_module_qn = "test.foreign.__init__",+ .lang = CBM_LANG_GO,+ .signature_param_types = params,+ .signature_param_count = 3},+ {.qualified_name = "test.unknown.__init__.call",+ .short_name = "call",+ .label = "Function",+ .def_module_qn = "test.unknown.__init__",+ .lang = (CBMLanguage)-1,+ .signature_param_types = params,+ .signature_param_count = 3},+ };+ CBMArena arena, shared;+ cbm_arena_init(&arena);+ cbm_arena_init(&shared);+ CBMTypeRegistry fallback;+ cbm_registry_init(&fallback, &arena);+ bool registered = cbm_py_lsp_test_register_defs(&arena, &fallback, defs, 3);+ bool correct = registered &&+ pylsp_init_signature(&fallback, "test.pkg.call", "test.pkg.Token") &&+ pylsp_init_signature(&fallback, "test.foreign.__init__.call",+ "test.foreign.__init__.Token") &&+ pylsp_init_signature(&fallback, "test.unknown.__init__.call",+ "test.unknown.__init__.Token");+ CBMTypeRegistry *base = cbm_py_build_cross_registry(&shared, defs, 3);+ correct = correct && base && base->read_only &&+ pylsp_init_signature(base, "test.pkg.call", "test.pkg.Token") &&+ !cbm_registry_lookup_func(base, "test.foreign.__init__.call") &&+ !cbm_registry_lookup_func(base, "test.unknown.__init__.call");+ cbm_arena_destroy(&arena);+ cbm_arena_destroy(&shared);+ ASSERT_TRUE(correct);+ PASS();+}++TEST(pylsp_init_scope_external_classes_and_cross_exact_joins) {+ const char *source = "from pkg.sub import Widget as Imported\n"+ "def use():\n store = Store()\n store.get()\n"+ " imported = Imported()\n imported.get()\n";+ CBMLSPDef defs[] = {+ {.qualified_name = "test.pkg.Store",+ .short_name = "Store",+ .label = "Class",+ .def_module_qn = "test.pkg.__init__",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.pkg.Store.get",+ .short_name = "get",+ .label = "Method",+ .def_module_qn = "test.pkg.__init__",+ .receiver_type = "test.pkg.Store",+ .return_types = "int",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.pkg.sub.Widget",+ .short_name = "Widget",+ .label = "Class",+ .def_module_qn = "test.pkg.sub",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.pkg.sub.Widget.get",+ .short_name = "get",+ .label = "Method",+ .def_module_qn = "test.pkg.sub",+ .receiver_type = "test.pkg.sub.Widget",+ .return_types = "int",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.pkg.Outer.Nested",+ .short_name = "Nested",+ .label = "Class",+ .def_module_qn = "test.pkg.__init__",+ .lang = CBM_LANG_PYTHON},+ };+ const char *names[] = {"Imported"};+ const char *qns[] = {"test.pkg.sub.Widget"};+ CBMFileResult *r = cbm_extract_file(source, (int)strlen(source), CBM_LANG_PYTHON, "test",+ "pkg/__init__.py", 0, NULL, NULL);+ TSParser *parser = ts_parser_new();+ if (parser)+ ts_parser_set_language(parser, tree_sitter_python());+ TSTree *tree =+ parser ? ts_parser_parse_string(parser, NULL, source, (uint32_t)strlen(source)) : NULL;+ bool correct = r && !r->has_error && !r->parse_incomplete && !r->lsp_skipped && tree &&+ pylsp_module_has_def(r, "test.pkg.use");+ for (int prebuilt = 0; correct && prebuilt < 2; prebuilt++) {+ CBMArena arena, shared;+ cbm_arena_init(&arena);+ cbm_arena_init(&shared);+ CBMTypeRegistry *base = cbm_py_build_cross_registry(&shared, defs, 5);+ CBMTypeRegistry overlay;+ cbm_registry_init(&overlay, &arena);+ overlay.fallback = base;+ CBMResolvedCallArray out = {0};+ PyLSPContext ctx;+ py_lsp_init(&ctx, &arena, source, (int)strlen(source), &overlay, "test.pkg.__init__", &out);+ cbm_py_lsp_test_bind_external_classes(&ctx, ts_tree_root_node(tree));+ bool globals = base && ctx.eval_failure == CBM_LSP_COMPLETE &&+ pylsp_init_named_type(cbm_scope_lookup_local(ctx.current_scope, "Store"),+ "test.pkg.Store") &&+ !cbm_scope_lookup_local(ctx.current_scope, "Widget") &&+ !cbm_scope_lookup_local(ctx.current_scope, "Nested");+ char module_input[] = "test.pkg.__init__";+ CBMLSPStatus status =+ prebuilt+ ? cbm_run_py_lsp_cross_with_registry_status(&arena, source, (int)strlen(source),+ module_input, &overlay, names, qns, 1,+ tree, &out, NULL)+ : cbm_run_py_lsp_cross_status(&arena, source, (int)strlen(source), module_input,+ defs, 5, names, qns, 1, tree, &out, NULL);+ memset(module_input, 'x', sizeof(module_input) - 1);+ bool store = pylsp_module_site_joins(&r->calls, &out, source, "store.get()", "test.pkg.use",+ "test.pkg.Store.get");+ bool imported = pylsp_module_site_joins(&r->calls, &out, source, "imported.get()",+ "test.pkg.use", "test.pkg.sub.Widget.get");+ correct = correct && globals && status == CBM_LSP_COMPLETE && store && imported;+ cbm_arena_destroy(&arena);+ cbm_arena_destroy(&shared);+ }+ if (tree)+ ts_tree_delete(tree);+ if (parser)+ ts_parser_delete(parser);+ if (r)+ cbm_free_result(r);+ ASSERT_TRUE(correct);+ PASS();+}++TEST(pylsp_init_scope_failure_preserves_outputs_and_wrappers) {+ const char *source = "def run():\n value = Store()\n return value.get()\n";+ CBMLSPDef defs[] = {+ {.qualified_name = "test.pkg.Store",+ .short_name = "Store",+ .label = "Class",+ .def_module_qn = "test.pkg.__init__",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.pkg.Store.get",+ .short_name = "get",+ .label = "Method",+ .def_module_qn = "test.pkg.__init__",+ .receiver_type = "test.pkg.Store",+ .return_types = "int",+ .lang = CBM_LANG_PYTHON},+ };+ bool correct = true;+ cbm_py_lsp_test_scope_fail_after(0);+ CBMFileResult *raw = cbm_extract_file(source, (int)strlen(source), CBM_LANG_PYTHON, "test",+ "pkg/__init__.py", 0, NULL, NULL);+ cbm_py_lsp_test_scope_fail_after(-1);+ correct = raw && raw->has_error && raw->lsp_skipped && raw->error_msg &&+ strcmp(raw->error_msg, CBM_PY_LSP_SCOPE_ERROR) == 0 &&+ raw->resolved_calls.count == 0 && pylsp_module_has_def(raw, "test.pkg.run");+ if (raw)+ cbm_free_result(raw);+ for (int mode = 0; mode < 3; mode++) {+ CBMArena arena, shared;+ cbm_arena_init(&arena);+ cbm_arena_init(&shared);+ CBMTypeRegistry *base = cbm_py_build_cross_registry(&shared, defs, 2);+ CBMTypeRegistry overlay;+ cbm_registry_init(&overlay, &arena);+ overlay.fallback = base;+ CBMResolvedCall prior = {.caller_qn = "completed.caller",+ .callee_qn = "completed.target",+ .strategy = "prior.strategy",+ .reason = "prior.reason",+ .confidence = 0.125f,+ .kind = CBM_RESOLVED_INVOCATION,+ .site_start_byte = 7,+ .site_end_byte = 14};+ unsigned char saved[sizeof(prior)];+ memcpy(saved, &prior, sizeof(prior));+ CBMCall previous_synthetic = {.callee_name = "completed.synthetic"};+ CBMCallArray synthetic = {.items = &previous_synthetic, .count = 1, .cap = 1};+ CBMResolvedCallArray out = {.items = &prior, .count = 1, .cap = 1};+ cbm_py_lsp_test_scope_fail_after(mode == 2 ? 1 : 0);+ /* mode 2 gets past context normalization, then fails signature scope. */+ CBMLSPStatus status = mode == 1+ ? cbm_run_py_lsp_cross_with_registry_status(+ &arena, source, (int)strlen(source), "test.pkg.__init__",+ &overlay, NULL, NULL, 0, NULL, &out, &synthetic)+ : cbm_run_py_lsp_cross_status(&arena, source, (int)strlen(source),+ "test.pkg.__init__", defs, 2, NULL,+ NULL, 0, NULL, &out, &synthetic);+ cbm_py_lsp_test_scope_fail_after(-1);+ correct = correct && base && status == CBM_LSP_SCOPE_FAILED && out.count == 1 &&+ out.items == &prior && memcmp(saved, &prior, sizeof(prior)) == 0 &&+ synthetic.count == 1 && synthetic.items == &previous_synthetic &&+ strcmp(previous_synthetic.callee_name, "completed.synthetic") == 0;+ cbm_py_lsp_test_scope_fail_after(0);+ bool complete =+ mode == 1+ ? cbm_run_py_lsp_cross_with_registry(&arena, source, (int)strlen(source),+ "test.pkg.__init__", &overlay, NULL, NULL, 0,+ NULL, &out, &synthetic)+ : cbm_run_py_lsp_cross(&arena, source, (int)strlen(source), "test.pkg.__init__",+ defs, 2, NULL, NULL, 0, NULL, &out, &synthetic);+ cbm_py_lsp_test_scope_fail_after(-1);+ correct =+ correct && !complete && out.count == 1 && memcmp(saved, &prior, sizeof(prior)) == 0;+ CBMBatchPyLSPFile file = {.source = source,+ .source_len = (int)strlen(source),+ .module_qn = "test.pkg.__init__",+ .defs = defs,+ .def_count = 2};+ CBMResolvedCallArray batch = {0};+ cbm_py_lsp_test_scope_fail_after(0);+ bool batch_complete = cbm_batch_py_lsp_cross(&arena, &file, 1, &batch);+ cbm_py_lsp_test_scope_fail_after(-1);+ correct = correct && !batch_complete && batch.count == 0;+ cbm_arena_destroy(&arena);+ cbm_arena_destroy(&shared);+ }+ ASSERT_TRUE(correct);+ PASS();+}++TEST(pylsp_init_scope_shared_failure_keeps_arena_and_needed_fallback) {+ const char *source = "def use():\n obj = Item()\n return obj.get()\n";+ CBMLSPDef defs[] = {+ {.qualified_name = "test.plain.Item",+ .short_name = "Item",+ .label = "Class",+ .def_module_qn = "test.plain",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.plain.Item.get",+ .short_name = "get",+ .label = "Method",+ .def_module_qn = "test.plain",+ .receiver_type = "test.plain.Item",+ .return_types = "int",+ .lang = CBM_LANG_PYTHON},+ {.qualified_name = "test.unused.work",+ .short_name = "work",+ .label = "Function",+ .def_module_qn = "test.unused.__init__",+ .lang = CBM_LANG_PYTHON},+ };+ CBMArena arena, shared;+ cbm_arena_init(&arena);+ cbm_arena_init(&shared);+ char *sentinel = cbm_arena_strdup(&shared, "caller-owned shared data");+ cbm_py_lsp_test_scope_fail_after(0);+ CBMTypeRegistry *failed = cbm_py_build_cross_registry(&shared, defs, 3);+ CBMResolvedCallArray out = {0};+ CBMLSPStatus fallback =+ cbm_run_py_lsp_cross_status(&arena, source, (int)strlen(source), "test.plain", defs, 2,+ NULL, NULL, 0, NULL, &out, NULL);+ cbm_py_lsp_test_scope_fail_after(-1);+ bool correct = !failed && sentinel && strcmp(sentinel, "caller-owned shared data") == 0 &&+ fallback == CBM_LSP_COMPLETE;+ CBMFileResult *extracted = cbm_extract_file(source, (int)strlen(source), CBM_LANG_PYTHON,+ "test", "plain.py", 0, NULL, NULL);+ correct = correct && extracted && !extracted->has_error && !extracted->parse_incomplete &&+ pylsp_module_has_def(extracted, "test.plain.use") &&+ pylsp_module_site_joins(&extracted->calls, &out, source, "obj.get()",+ "test.plain.use", "test.plain.Item.get");+ CBMTypeRegistry *fresh = cbm_py_build_cross_registry(&shared, defs, 3);+ correct = correct && fresh && fresh->read_only &&+ cbm_registry_lookup_func(fresh, "test.unused.work") &&+ strcmp(sentinel, "caller-owned shared data") == 0;+ if (extracted)+ cbm_free_result(extracted);+ cbm_arena_destroy(&arena);+ cbm_arena_destroy(&shared);+ ASSERT_TRUE(correct);+ PASS();+}+SUITE(py_lsp) {+ RUN_TEST(pylsp_init_scope_context_and_helper);+ RUN_TEST(pylsp_init_scope_raw_exact_occurrences_and_annotations);+ RUN_TEST(pylsp_init_scope_cross_signatures_keep_definition_language);+ RUN_TEST(pylsp_init_scope_external_classes_and_cross_exact_joins);+ RUN_TEST(pylsp_init_scope_failure_preserves_outputs_and_wrappers);+ RUN_TEST(pylsp_init_scope_shared_failure_keeps_arena_and_needed_fallback);+RUN_TEST(pylsp_module_callers_join_exact_raw_occurrences);RUN_TEST(pylsp_module_named_lambda_keeps_exact_dunder_pair);RUN_TEST(pylsp_module_cross_callers_own_input_and_join_exact_sites);diff --git a/tests/test_registry.c b/tests/test_registry.cindex d581464ec..564262f48 100644--- a/tests/test_registry.c+++ b/tests/test_registry.c@@ -1659,7 +1659,277 @@ TEST(resolve_import_map_alias_with_suffix_hits_method) {PASS();}+/* Python package scope is an explicit resolver input, not a property inferred+ * from a QN shared by other languages. Keep these fixtures separate from the+ * raw public-API tests above. */+static bool registry_scope_match(cbm_resolution_t result, const char *qn, const char *strategy) {+ return qn && strategy && result.qualified_name && result.strategy &&+ strcmp(result.qualified_name, qn) == 0 && strcmp(result.strategy, strategy) == 0 &&+ result.candidate_count == 1;+}++TEST(python_symbol_scope_len_preserves_file_identity) {+ const char *inputs[] = {"proj.pkg.__init__",+ "proj.__init__",+ "proj.pkg.__init__.__init__",+ "proj.pkg.mod",+ "proj.pkg.x__init__",+ "__init__",+ ".__init__",+ "proj.pkg.index",+ "",+ NULL};+ const char *scopes[] = {"proj.pkg",+ "proj",+ "proj.pkg.__init__",+ "proj.pkg.mod",+ "proj.pkg.x__init__",+ "__init__",+ ".__init__",+ "proj.pkg.index",+ "",+ ""};+ bool lengths = true;+ for (size_t i = 0; i < sizeof(inputs) / sizeof(inputs[0]); i++) {+ lengths = cbm_fqn_symbol_scope_len(inputs[i]) == strlen(scopes[i]) && lengths;+ }+ char *module = cbm_pipeline_fqn_module("proj", "pkg/__init__.py");+ char *symbol = cbm_pipeline_fqn_compute("proj", "pkg/__init__.py", "Field");+ bool identities = module && symbol && strcmp(module, "proj.pkg.__init__") == 0 &&+ strcmp(symbol, "proj.pkg.Field") == 0 &&+ cbm_fqn_symbol_scope_len(module) == strlen("proj.pkg");+ free(module);+ free(symbol);+ ASSERT_TRUE(lengths && identities);+ PASS();+}++TEST(registry_python_package_scope_is_explicit) {+ cbm_registry_t *r = cbm_registry_new();+ ASSERT_NOT_NULL(r);+ cbm_registry_add(r, "Field", "proj.forms.fields.Field", "Class");+ cbm_registry_add(r, "Field", "proj.db.fields.Field", "Class");+ cbm_registry_add(r, "Field", "proj.db.fields.__init__.Field", "Class");+ cbm_registry_add(r, "Field", "proj.db.plain.Field", "Class");+ cbm_registry_add(r, "Field", "proj.db.index.Field", "Class");+ const char *keys[] = {"forms"};+ const char *vals[] = {"proj.forms"};+ const char *module = "proj.db.fields.__init__";+ bool seeded = cbm_registry_size(r) == 5;+ cbm_resolution_t package =+ cbm_registry_resolve_lang(r, "Field", module, keys, vals, 1, CBM_LANG_PYTHON);+ bool python = registry_scope_match(package, "proj.db.fields.Field", "same_module");+ cbm_resolution_t plain =+ cbm_registry_resolve_lang(r, "Field", "proj.db.plain", keys, vals, 1, CBM_LANG_PYTHON);+ bool normal = registry_scope_match(plain, "proj.db.plain.Field", "same_module");+ cbm_resolution_t raw = cbm_registry_resolve(r, "Field", module, keys, vals, 1);+ bool preserved = registry_scope_match(raw, "proj.db.fields.__init__.Field", "same_module");+ const CBMLanguage raw_languages[] = {CBM_LANG_JAVA, CBM_LANG_GO, CBM_LANG_JAVASCRIPT,+ (CBMLanguage)-1, CBM_LANG_COUNT};+ for (size_t i = 0; i < sizeof(raw_languages) / sizeof(raw_languages[0]); i++) {+ cbm_resolution_t result =+ cbm_registry_resolve_lang(r, "Field", module, keys, vals, 1, raw_languages[i]);+ preserved = registry_scope_match(result, raw.qualified_name, "same_module") &&+ result.confidence == raw.confidence && preserved;+ }+ cbm_resolution_t index =+ cbm_registry_resolve_lang(r, "Field", "proj.db.index", keys, vals, 1, CBM_LANG_JAVASCRIPT);+ bool index_raw = registry_scope_match(index, "proj.db.index.Field", "same_module");+ cbm_registry_free(r);+ ASSERT_TRUE(seeded && python && normal && preserved && index_raw);+ PASS();+}++TEST(registry_python_scope_keeps_import_precedence_and_raw_scoring) {+ cbm_registry_t *r = cbm_registry_new();+ ASSERT_NOT_NULL(r);+ cbm_registry_add(r, "Field", "proj.vendor.Field", "Class");+ cbm_registry_add(r, "Field", "proj.pkg.Field", "Class");+ cbm_registry_add(r, "Field", "proj.pkg.__init__.Field", "Class");+ cbm_registry_add(r, "choose", "proj.pkg.__init__.child.choose", "Function");+ cbm_registry_add(r, "choose", "proj.pkg.peer.choose", "Function");+ const char *keys[] = {"Field"};+ const char *vals[] = {"proj.vendor.Field"};+ bool seeded = cbm_registry_size(r) == 5;+ cbm_resolution_t imported =+ cbm_registry_resolve_lang(r, "Field", "proj.pkg.__init__", keys, vals, 1, CBM_LANG_PYTHON);+ bool precedence = registry_scope_match(imported, "proj.vendor.Field", "import_map");+ cbm_resolution_t raw = cbm_registry_resolve(r, "choose", "proj.pkg.__init__", NULL, NULL, 0);+ cbm_resolution_t python =+ cbm_registry_resolve_lang(r, "choose", "proj.pkg.__init__", NULL, NULL, 0, CBM_LANG_PYTHON);+ bool scoring =+ raw.qualified_name && python.qualified_name && raw.strategy && python.strategy &&+ strcmp(raw.qualified_name, "proj.pkg.__init__.child.choose") == 0 &&+ strcmp(python.qualified_name, raw.qualified_name) == 0 &&+ strcmp(raw.strategy, "suffix_match") == 0 && strcmp(python.strategy, raw.strategy) == 0 &&+ python.confidence == raw.confidence && python.candidate_count == raw.candidate_count;+ cbm_registry_free(r);+ ASSERT_TRUE(seeded && precedence && scoring);+ PASS();+}++TEST(registry_python_scope_cache_modes_and_raw_lineage) {+ cbm_registry_t *r = cbm_registry_new();+ ASSERT_NOT_NULL(r);+ cbm_registry_add(r, "Entry", "proj.pkg.Entry", "Function");+ cbm_registry_add(r, "Entry", "proj.pkg.__init__.Entry", "Function");+ cbm_registry_add(r, "Reject", "proj.pkg.Reject", "Table");+ cbm_registry_add(r, "Reject", "proj.pkg.__init__.Reject", "Function");+ cbm_registry_add(r, "Accept", "proj.pkg.Accept", "Function");+ cbm_registry_add(r, "Accept", "proj.pkg.__init__.Accept", "Table");+ cbm_registry_add(r, "Relation", "proj.pkg.Relation", "View");+ cbm_registry_add(r, "Relation", "proj.pkg.__init__.Relation", "Table");+ bool seeded = cbm_registry_size(r) == 8;+ bool correct = true;+ /* Each cache lifetime has one fixed module/import map. Alternate modes in+ * both starting orders; repeated same-mode requests also exercise hits. */+ for (int first_python = 0; first_python < 2; first_python++) {+ cbm_registry_resolve_cache_begin(8);+ for (int turn = 0; turn < 16; turn++) {+ bool python = ((turn / 2 + first_python) % 2) != 0;+ const char *names[] = {"Entry", "Reject", "Accept", "Relation", "Missing"};+ for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) {+ cbm_resolution_t result =+ python ? cbm_registry_resolve_lang(r, names[i], "proj.pkg.__init__", NULL, NULL,+ 0, CBM_LANG_PYTHON)+ : cbm_registry_resolve(r, names[i], "proj.pkg.__init__", NULL, NULL, 0);+ const char *expected = NULL;+ if (i == 0) {+ expected = python ? "proj.pkg.Entry" : "proj.pkg.__init__.Entry";+ } else if (i == 1 && !python) {+ expected = "proj.pkg.__init__.Reject";+ } else if (i == 2 && python) {+ expected = "proj.pkg.Accept";+ }+ correct =+ (expected ? registry_scope_match(result, expected, "same_module")+ : result.qualified_name == NULL && result.candidate_count == 0) &&+ correct;+ }+ /* The cached relation veto must never poison the uncached SQL API,+ * nor may the SQL result bypass the next default cached veto. */+ cbm_resolution_t lineage =+ cbm_registry_resolve_lineage(r, "Relation", "proj.pkg.__init__", NULL, NULL, 0);+ correct = registry_scope_match(lineage, "proj.pkg.__init__.Relation", "same_module") &&+ correct;+ cbm_resolution_t veto = cbm_registry_resolve_lang(r, "Relation", "proj.pkg.__init__",+ NULL, NULL, 0, CBM_LANG_PYTHON);+ correct = veto.qualified_name == NULL && veto.candidate_count == 0 && correct;+ }+ cbm_registry_resolve_cache_end();+ }+ cbm_registry_free(r);+ ASSERT_TRUE(seeded && correct);+ PASS();+}++static const char *registry_scope_canonical(cbm_registry_t *r, const char *name, const char *qn) {+ const char **candidates = NULL;+ int count = 0;+ cbm_registry_find_by_name(r, name, &candidates, &count);+ for (int i = 0; i < count; i++) {+ if (strcmp(candidates[i], qn) == 0) {+ return candidates[i];+ }+ }+ return NULL;+}++TEST(registry_python_scope_complete_candidate_boundaries) {+ const size_t lengths[] = {511, 512, 513, 1536};+ bool complete = true;+ for (size_t i = 0; i < sizeof(lengths) / sizeof(lengths[0]); i++) {+ cbm_registry_t *r = cbm_registry_new();+ if (!r) {+ complete = false;+ break;+ }+ char scope[2048];+ char module[2048];+ char target[2048];+ const char *name = "LongTarget";+ size_t scope_len = lengths[i] - strlen(name) - 1;+ memcpy(scope, "proj.", 5);+ memset(scope + 5, 'a', scope_len - 5);+ scope[scope_len] = '\0';+ int mn = snprintf(module, sizeof(module), "%s.__init__", scope);+ int tn = snprintf(target, sizeof(target), "%s.%s", scope, name);+ bool shape = mn > 0 && (size_t)mn < sizeof(module) && tn > 0 && (size_t)tn == lengths[i] &&+ (size_t)tn < sizeof(target);+ cbm_registry_add(r, name, target, "Function");+ if (lengths[i] > 511) {+ char truncated[512];+ memcpy(truncated, target, sizeof(truncated) - 1);+ truncated[sizeof(truncated) - 1] = '\0';+ cbm_registry_add(r, "truncated_decoy", truncated, "Function");+ }+ const char *canonical = registry_scope_canonical(r, name, target);+ cbm_resolution_t python =+ cbm_registry_resolve_lang(r, name, module, NULL, NULL, 0, CBM_LANG_PYTHON);+ cbm_resolution_t normal = cbm_registry_resolve(r, name, scope, NULL, NULL, 0);+ complete = shape && canonical && python.qualified_name == canonical &&+ normal.qualified_name == canonical &&+ registry_scope_match(python, target, "same_module") &&+ registry_scope_match(normal, target, "same_module") && complete;+ cbm_registry_free(r);+ }+ ASSERT_TRUE(complete);+ PASS();+}++TEST(registry_python_scope_qualified_terminal_bucket_uncapped) {+ cbm_registry_t *r = cbm_registry_new();+ ASSERT_NOT_NULL(r);+ /* The exact targets are inserted after the heuristic limit. A long exact+ * comparison must use the canonical terminal bucket, not "Owner.perform"+ * as the bucket key, and must not stop at 256 candidates. */+ bool shape = true;+ for (int i = 0; i < 300; i++) {+ char qn[80];+ int n = snprintf(qn, sizeof(qn), "proj.noise%d.perform", i);+ shape = n > 0 && (size_t)n < sizeof(qn) && shape;+ cbm_registry_add(r, "perform", qn, "Method");+ }+ char scope[1024];+ memcpy(scope, "proj.", 5);+ memset(scope + 5, 'b', 900);+ scope[905] = '\0';+ char module[1024];+ int mn = snprintf(module, sizeof(module), "%s.__init__", scope);+ shape = mn > 0 && (size_t)mn < sizeof(module) && shape;+ const char *names[] = {"Owner.perform", "Owner::perform"};+ bool resolved = true;+ for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) {+ char target[1024];+ char prefixed[80];+ int tn = snprintf(target, sizeof(target), "%s.%s", scope, names[i]);+ int pn = snprintf(prefixed, sizeof(prefixed), "receiver.%s", names[i]);+ shape = tn > 0 && (size_t)tn < sizeof(target) && pn > 0 && (size_t)pn < sizeof(prefixed) &&+ shape;+ cbm_registry_add(r, "perform", target, "Method");+ const char *canonical = registry_scope_canonical(r, "perform", target);+ cbm_resolution_t direct =+ cbm_registry_resolve_lang(r, names[i], module, NULL, NULL, 0, CBM_LANG_PYTHON);+ cbm_resolution_t suffix =+ cbm_registry_resolve_lang(r, prefixed, module, NULL, NULL, 0, CBM_LANG_PYTHON);+ resolved = canonical && direct.qualified_name == canonical &&+ suffix.qualified_name == canonical &&+ registry_scope_match(direct, target, "same_module") &&+ registry_scope_match(suffix, target, "same_module") && resolved;+ }+ bool seeded = cbm_registry_size(r) == 302;+ cbm_registry_free(r);+ ASSERT_TRUE(shape && seeded && resolved);+ PASS();+}+SUITE(registry) {+ RUN_TEST(python_symbol_scope_len_preserves_file_identity);+ RUN_TEST(registry_python_package_scope_is_explicit);+ RUN_TEST(registry_python_scope_keeps_import_precedence_and_raw_scoring);+ RUN_TEST(registry_python_scope_cache_modes_and_raw_lineage);+ RUN_TEST(registry_python_scope_complete_candidate_boundaries);+ RUN_TEST(registry_python_scope_qualified_terminal_bucket_uncapped);/* FQN */RUN_TEST(fqn_simple);RUN_TEST(fqn_no_name);