Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

Merge origin/main into pr/windows-setenv-utf8

Martin Vogel19c6fd9cc075
diff --cc internal/cbm/cbm.c
index f17d54757,23b871dbc..1156a6a73
--- a/internal/cbm/cbm.c
+++ b/internal/cbm/cbm.c
@@@ -24,8 -28,8 +28,9 @@@
#include "foundation/compat.h"
#include "foundation/compat_fs.h" // cbm_fopen — crash-supervisor per-file marker write
#include "foundation/hash_table.h" // CBMHashTable — crash-supervisor quarantine set
+ #include "foundation/str_util.h" // cbm_json_escape — variants file_path
#include "tree_sitter/api.h" // TSParser, TSNode, TSTree, TSInput, TSLanguage, TSPoint, TSParseOptions, TSParseState
+#include "foundation/platform.h"
#include "foundation/constants.h"
#include "mimalloc.h" // mi_malloc/mi_calloc/mi_realloc/mi_free/mi_usable_size — bind 3rd-party allocators (#424)
#if defined(CBM_BIND_TS_ALLOCATOR) && CBM_BIND_TS_ALLOCATOR
diff --cc tests/test_extraction.c
index 806433b0b,7bfda63fc..05203a150
--- a/tests/test_extraction.c
+++ b/tests/test_extraction.c
@@@ -8158,42 -11939,1077 +11940,1112 @@@ TEST(extract_walk_truncated_when_a_node
PASS();
}
+ /* ═══════════════════════════════════════════════════════════════════
+ * Deep nesting: the syntax-tree walkers must not spend stack per level
+ *
+ * Extraction runs on pipeline worker threads whose stack is
+ * CBM_WORKER_STACK_SIZE (src/pipeline/worker_pool.h), not on the test runner's
+ * main thread, whose size depends on the platform and its rlimit. Each probe
+ * below therefore runs cbm_extract_file on a thread of exactly that size, so
+ * a walker that recurses once per nesting level runs out of stack at the
+ * depth it would in the pipeline. On POSIX the thread lives in a forked child
+ * and an overflow surfaces as the child's killing signal instead of taking
+ * the runner with it (the pattern of tests/test_stack_overflow.c); Windows
+ * runs it in-process, where a real overflow is a visible runner abort. A
+ * probe returns 0 when every expectation held and prints what did not.
+ *
+ * DEEP_NEST_LEVELS: a walker frame holds at least its saved frame pointer and
+ * return address plus the 32-byte TSNode it passes down (on arm64 a TSNode is
+ * passed by reference to a copy in the caller's frame), 48 bytes, so 200,000
+ * frames need 9.6 MB — past the 8 MB worker stack even at that floor;
+ * measured frames are larger and the sanitizer build adds red zones. The
+ * parser is not the limit: tree-sitter keeps the nesting on its heap parse
+ * stack and its node and cursor helpers are iterative, so the depth is the
+ * walker's problem alone. The fixtures nest parentheses, which copy no text
+ * per level (a nested call copies its argument text at every level, which is
+ * what makes the stack_overflow_b suite slow).
+ * ═══════════════════════════════════════════════════════════════════ */
+
+ enum { DEEP_NEST_LEVELS = 200000 };
+
+ typedef int (*deep_probe_fn)(void);
+
+ typedef struct {
+ deep_probe_fn fn;
+ int rc;
+ } deep_probe_job_t;
+
+ static void *deep_probe_thread_main(void *arg) {
+ deep_probe_job_t *job = (deep_probe_job_t *)arg;
+ job->rc = job->fn();
+ return NULL;
+ }
+
+ /* 0 when the probe passed, its own code otherwise, 2 if no thread came up. */
+ static int deep_probe_on_worker_stack(deep_probe_fn fn) {
+ deep_probe_job_t job = {fn, 3};
+ cbm_thread_t thread;
+ if (cbm_thread_create(&thread, CBM_WORKER_STACK_SIZE, deep_probe_thread_main, &job) != 0) {
+ return 2;
+ }
+ (void)cbm_thread_join(&thread);
+ return job.rc;
+ }
+
+ /* 1 when the probe passed; otherwise `why` says what happened. */
+ static int deep_probe_passed(deep_probe_fn fn, char *why, size_t why_len) {
+ #if defined(_WIN32)
+ int rc = deep_probe_on_worker_stack(fn);
+ if (rc != 0) {
+ snprintf(why, why_len, "probe returned %d", rc);
+ }
+ return rc == 0;
+ #else
+ fflush(NULL);
+ pid_t pid = fork();
+ if (pid < 0) {
+ snprintf(why, why_len, "fork failed");
+ return 0;
+ }
+ if (pid == 0) {
+ int rc = deep_probe_on_worker_stack(fn);
+ fflush(NULL);
+ _exit(rc);
+ }
+ int status = 0;
+ (void)waitpid(pid, &status, 0);
+ if (WIFSIGNALED(status)) {
+ snprintf(why, why_len,
+ "extraction killed by signal %d on a worker-sized stack: a walker recursed once "
+ "per nesting level",
+ WTERMSIG(status));
+ return 0;
+ }
+ if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
+ snprintf(why, why_len, "probe returned %d", WIFEXITED(status) ? WEXITSTATUS(status) : -1);
+ return 0;
+ }
+ return 1;
+ #endif
+ }
+
+ /* head, `levels` times '(', core, `levels` times ')', tail. *core_at receives
+ * the byte offset of core. */
+ static char *build_nested_source(const char *head, const char *core, const char *tail, int levels,
+ uint32_t *core_at) {
+ size_t head_len = strlen(head);
+ size_t core_len = strlen(core);
+ size_t tail_len = strlen(tail);
+ char *src = malloc(head_len + core_len + tail_len + 2 * (size_t)levels + 1);
+ if (!src) {
+ return NULL;
+ }
+ char *w = src;
+ memcpy(w, head, head_len);
+ w += head_len;
+ memset(w, '(', (size_t)levels);
+ w += levels;
+ *core_at = (uint32_t)(w - src);
+ memcpy(w, core, core_len);
+ w += core_len;
+ memset(w, ')', (size_t)levels);
+ w += levels;
+ memcpy(w, tail, tail_len + 1);
+ return src;
+ }
+
+ /* `$x = ((...((f))...))(...);` — a first-class callable whose callee sits under
+ * DEEP_NEST_LEVELS parentheses. PHP, because its first-class callable syntax
+ * is the path that hands a parenthesised callee to terminal_callee_leaf
+ * (extract_calls.c): the leaf finder steps into one named child per wrapper
+ * node that has no terminal field, while every ordinary call path first needs
+ * a textual callee name, which the field resolver only yields for identifier
+ * and member shapes whose leaf sits one or two levels down (a member chain
+ * `a.b.c()` stops at its `property`; nested calls `f(f(f()))` are arguments,
+ * visited by the explicit-stack walker). Expected: the exact occurrence the
+ * leaf finder names — one CALL_REFERENCE usage of `f` at the byte of the `f`
+ * token — in a cleanly parsed file. */
+ static int deep_callee_chain_probe(void) {
+ uint32_t f_at = 0;
+ char *src = build_nested_source("<?php\n$x = ", "f", "(...);\n", DEEP_NEST_LEVELS, &f_at);
+ if (!src) {
+ return 4;
+ }
+ CBMFileResult *r = extract(src, CBM_LANG_PHP, "t", "deep_callee.php");
+ int rc = 0;
+ if (!r || r->has_error || r->parse_incomplete) {
+ printf(" deep callee: extraction failed or the parse was not clean\n");
+ rc = 1;
+ } else {
+ int references = 0;
+ for (int i = 0; i < r->usages.count; i++) {
+ const CBMUsage *u = &r->usages.items[i];
+ if (u->kind != CBM_USAGE_CALL_REFERENCE || !u->ref_name ||
+ strcmp(u->ref_name, "f") != 0) {
+ continue;
+ }
+ references++;
+ if (u->site_start_byte != f_at || u->site_end_byte != f_at + 1) {
+ printf(" deep callee: reference site %u-%u, expected %u-%u\n",
+ u->site_start_byte, u->site_end_byte, f_at, f_at + 1);
+ rc = 1;
+ }
+ }
+ if (references != 1) {
+ printf(" deep callee: %d CALL_REFERENCE usages of f, expected 1\n", references);
+ rc = 1;
+ }
+ }
+ if (r) {
+ cbm_free_result(r);
+ }
+ free(src);
+ return rc;
+ }
+
+ TEST(extract_deep_callee_chain_completes) {
+ char why[160];
+ if (!deep_probe_passed(deep_callee_chain_probe, why, sizeof(why))) {
+ FAIL(why);
+ }
+ PASS();
+ }
+
+ /* One invalid token at the bottom of DEEP_NEST_LEVELS parentheses. Every
+ * enclosing parenthesized_expression then carries ts_node_has_error without
+ * being an ERROR node, which is the chain cbm_collect_error_regions (cbm.c)
+ * descends: it steps into a child that contains an error and stops at the
+ * top-most ERROR or MISSING node. Nested ERROR nodes would not do — the walk
+ * never enters an ERROR subtree, so they cost it one level. Expected: one
+ * region, on the line of the nest only, with the neighbouring definition
+ * intact and the file still usable. */
+ static int deep_error_regions_probe(void) {
+ uint32_t core_at = 0;
+ char *src = build_nested_source("def ok():\n return 1\nx = ", "1 2", "\ny = ok()\n",
+ DEEP_NEST_LEVELS, &core_at);
+ if (!src) {
+ return 4;
+ }
+ CBMFileResult *r = extract(src, CBM_LANG_PYTHON, "t", "deep_error.py");
+ int rc = 0;
+ if (!r) {
+ printf(" deep error regions: extraction failed\n");
+ rc = 1;
+ } else {
+ if (!r->parse_incomplete || r->error_region_count != 1 || !r->error_ranges ||
+ strcmp(r->error_ranges, "3-3") != 0) {
+ printf(" deep error regions: incomplete=%d count=%d ranges=%s, expected one "
+ "region 3-3\n",
+ r->parse_incomplete ? 1 : 0, r->error_region_count,
+ r->error_ranges ? r->error_ranges : "(none)");
+ rc = 1;
+ }
+ if (r->parse_unusable) {
+ printf(" deep error regions: one line of five must not make the file unusable\n");
+ rc = 1;
+ }
+ if (!has_def(r, "Function", "ok")) {
+ printf(" deep error regions: the definition next to the nest was lost\n");
+ rc = 1;
+ }
+ cbm_free_result(r);
+ }
+ free(src);
+ return rc;
+ }
+
+ TEST(extract_deep_error_regions_complete) {
+ char why[160];
+ if (!deep_probe_passed(deep_error_regions_probe, why, sizeof(why))) {
+ FAIL(why);
+ }
+ PASS();
+ }
+
+ /* `f(cb=((...(obj.handler)...)))`: a labeled argument whose value is a bound
+ * method under LABELED_WRAPPERS parentheses. The usage pass classifies
+ * `handler` by climbing the wrappers (python_direct_callable_attribute_site, a
+ * loop) and then asking is_direct_argument_value, whose one recursive step
+ * moved from the value to the labeled argument holding it. The grammar never
+ * nests a labeled argument inside another's value, so that step is bounded
+ * and no stack depth is at stake; what the test pins is the answer across the
+ * conversion of that step to a loop: the usage is a callable-value candidate
+ * whose site is the outermost wrapper, and the keyword `cb` is no usage. The
+ * bare form pins the site on the attribute itself. */
+ enum { LABELED_WRAPPERS = 2000 };
+
+ static int handler_candidate_site(const CBMFileResult *r, uint32_t expect_start,
+ uint32_t expect_end, const char *form) {
+ int seen = 0;
+ int rc = 0;
+ for (int i = 0; i < r->usages.count; i++) {
+ const CBMUsage *u = &r->usages.items[i];
+ if (!u->ref_name) {
+ continue;
+ }
+ if (strcmp(u->ref_name, "cb") == 0) {
+ printf(" %s argument: the keyword label became a usage\n", form);
+ rc = 1;
+ }
+ if (strcmp(u->ref_name, "handler") != 0) {
+ continue;
+ }
+ seen++;
+ if (!u->may_be_call_reference || u->site_start_byte != expect_start ||
+ u->site_end_byte != expect_end) {
+ printf(" %s argument: handler candidate=%d site %u-%u, expected candidate site "
+ "%u-%u\n",
+ form, u->may_be_call_reference ? 1 : 0, u->site_start_byte, u->site_end_byte,
+ expect_start, expect_end);
+ rc = 1;
+ }
+ }
+ if (seen != 1) {
+ printf(" %s argument: %d usages of handler, expected 1\n", form, seen);
+ rc = 1;
+ }
+ return rc;
+ }
+
+ static int deep_argument_nesting_probe(void) {
+ const uint32_t attribute_len = (uint32_t)strlen("obj.handler");
+ uint32_t core_at = 0;
+ char *src = build_nested_source("f(cb=", "obj.handler", ")\n", LABELED_WRAPPERS, &core_at);
+ if (!src) {
+ return 4;
+ }
+ int rc = 0;
+ CBMFileResult *wrapped = extract(src, CBM_LANG_PYTHON, "t", "deep_arg.py");
+ if (!wrapped || wrapped->has_error || wrapped->parse_incomplete) {
+ printf(" wrapped argument: extraction failed or the parse was not clean\n");
+ rc = 1;
+ } else {
+ rc |= handler_candidate_site(wrapped, core_at - LABELED_WRAPPERS,
+ core_at + attribute_len + LABELED_WRAPPERS, "wrapped");
+ }
+ if (wrapped) {
+ cbm_free_result(wrapped);
+ }
+ free(src);
+
+ CBMFileResult *bare = extract("f(cb=obj.handler)\n", CBM_LANG_PYTHON, "t", "bare_arg.py");
+ if (!bare || bare->has_error || bare->parse_incomplete) {
+ printf(" bare argument: extraction failed or the parse was not clean\n");
+ rc = 1;
+ } else {
+ rc |= handler_candidate_site(bare, 5, 5 + attribute_len, "bare");
+ }
+ if (bare) {
+ cbm_free_result(bare);
+ }
+ return rc;
+ }
+
+ TEST(extract_deep_argument_nesting_completes) {
+ char why[160];
+ if (!deep_probe_passed(deep_argument_nesting_probe, why, sizeof(why))) {
+ FAIL(why);
+ }
+ PASS();
+ }
+
+ /* #1527: the call-context metrics find each call's innermost enclosing
+ * Function/Method with a line sweep instead of scanning every def per call.
+ * The sweep must give the scan's exact answer -- smallest span, ties to the
+ * lowest def index -- on nested, overlapping, same-line, malformed
+ * (end < start) and unnamed/non-callable ranges. Fixed-seed generator:
+ * deterministic, many shapes. */
+ static uint32_t enc_rand(uint32_t *state) {
+ *state = (*state * 1103515245u) + 12345u;
+ return (*state >> 16) & 0x7fffu;
+ }
+
+ TEST(extract_enclosing_sweep_matches_scan_issue1527) {
+ static const char *const labels[] = {"Function", "Method", "Class", "Variable"};
+ uint32_t seed = 1527;
+ for (int round = 0; round < 40; round++) {
+ CBMArena a;
+ cbm_arena_init(&a);
+ CBMFileResult r;
+ memset(&r, 0, sizeof(r));
+ int ndefs = round == 0 ? 0 : (int)(enc_rand(&seed) % 300);
+ int ncalls = (int)(enc_rand(&seed) % 1500) + 1;
+ int max_line = (int)(enc_rand(&seed) % 400) + 5;
+ for (int i = 0; i < ndefs; i++) {
+ CBMDefinition d;
+ memset(&d, 0, sizeof(d));
+ d.name = (enc_rand(&seed) % 10) == 0 ? NULL : "f";
+ d.label = labels[enc_rand(&seed) % 4];
+ d.start_line = 1 + (enc_rand(&seed) % (uint32_t)max_line);
+ int len = (int)(enc_rand(&seed) % 60) - 3; /* a few malformed end < start */
+ d.end_line = (uint32_t)((int)d.start_line + len > 0 ? (int)d.start_line + len : 0);
+ cbm_defs_push(&r.defs, &a, d);
+ }
+ for (int i = 0; i < ncalls; i++) {
+ CBMCall c;
+ memset(&c, 0, sizeof(c));
+ c.callee_name = "g";
+ c.start_line = (int)(enc_rand(&seed) % (uint32_t)(max_line + 10)) - 2;
+ cbm_calls_push(&r.calls, &a, c);
+ }
+ ASSERT_EQ(cbm_test_enclosing_sweep_mismatches(&r), 0);
+ cbm_arena_destroy(&a);
+ }
+ PASS();
+ }
+
+ /* Python namespace facts: provenance is ordered, content-only and independently
+ * owned. These tests do not enable any reexport resolution. */
+ static bool py_facts_equal(const CBMPyNamespaceFacts *a, const CBMPyNamespaceFacts *b) {
+ if (!cbm_py_namespace_facts_valid(a) || !cbm_py_namespace_facts_valid(b) ||
+ a->version != b->version || a->language != b->language || a->status != b->status ||
+ a->failure != b->failure || a->count != b->count)
+ return false;
+ for (int i = 0; i < a->count; i++) {
+ const CBMPyNamespaceFact *x = &a->items[i], *y = &b->items[i];
+ if (x->kind != y->kind || x->def_kind != y->def_kind ||
+ x->sequence_kind != y->sequence_kind || x->reason != y->reason ||
+ x->flags != y->flags || x->relative_level != y->relative_level ||
+ x->name_count != y->name_count || !cmp_str_eq(x->local_name, y->local_name) ||
+ !cmp_str_eq(x->module_name, y->module_name) ||
+ !cmp_str_eq(x->member_name, y->member_name))
+ return false;
+ for (int j = 0; j < x->name_count; j++) {
+ if (!cmp_str_eq(x->names[j], y->names[j]))
+ return false;
+ }
+ }
+ return true;
+ }
+
+ static bool py_facts_owned_range(const CBMArena *arena, const void *ptr, size_t bytes) {
+ if (!ptr)
+ return bytes == 0;
+ uintptr_t address = (uintptr_t)ptr;
+ for (int i = 0; i < arena->nblocks; i++) {
+ uintptr_t start = (uintptr_t)arena->blocks[i];
+ size_t size = arena->block_sizes[i];
+ if (address >= start && bytes <= size && address - start <= size - bytes)
+ return true;
+ }
+ return false;
+ }
+
+ static bool py_facts_owned_string(const CBMArena *arena, const char *str) {
+ return !str || (py_facts_owned_range(arena, str, 1) &&
+ py_facts_owned_range(arena, str, strlen(str) + 1));
+ }
+
+ static bool py_facts_owned(const CBMArena *arena, const CBMPyNamespaceFacts *facts) {
+ if (!py_facts_owned_range(arena, facts->items, (size_t)facts->count * sizeof(*facts->items)))
+ return false;
+ for (int i = 0; i < facts->count; i++) {
+ const CBMPyNamespaceFact *f = &facts->items[i];
+ if (!py_facts_owned_string(arena, f->local_name) ||
+ !py_facts_owned_string(arena, f->module_name) ||
+ !py_facts_owned_string(arena, f->member_name) ||
+ !py_facts_owned_range(arena, f->names, (size_t)f->name_count * sizeof(*f->names)))
+ return false;
+ for (int j = 0; j < f->name_count; j++) {
+ if (!py_facts_owned_string(arena, f->names[j]))
+ return false;
+ }
+ }
+ return true;
+ }
+
+ static const char PY_FACTS_ORDERED[] = "def item():\n return 1\n"
+ "from first import item\n"
+ "from second import item as item\n"
+ "item = unknown\n"
+ "del item\n"
+ "import pkg.mod\n"
+ "import pkg.mod as alias\n"
+ "from . import child as local\n"
+ "from ..outer import member\n"
+ "from one.shared import *\n"
+ "from two.shared import *\n"
+ "class Local:\n pass\n";
+
+ TEST(python_namespace_facts_preserve_order_and_import_provenance) {
+ CBMFileResult *r = extract(PY_FACTS_ORDERED, CBM_LANG_PYTHON, "t", "pkg/__init__.py");
+ bool ok = r && !r->has_error && !r->parse_incomplete &&
+ r->py_namespace.status == CBM_PY_NS_COMPLETE && r->py_namespace.count == 12 &&
+ cbm_py_namespace_facts_valid(&r->py_namespace) && has_def(r, "Function", "item") &&
+ has_def(r, "Class", "Local") && r->module_qn &&
+ strcmp(r->module_qn, "t.pkg.__init__") == 0;
+ if (ok) {
+ const CBMPyNamespaceFact *f = r->py_namespace.items;
+ ok = f[0].kind == CBM_PY_NS_OWN_DEF && f[0].def_kind == CBM_PY_NS_DEF_FUNCTION &&
+ strcmp(f[0].local_name, "item") == 0 && f[1].kind == CBM_PY_NS_IMPORT_NAME &&
+ strcmp(f[1].module_name, "first") == 0 && strcmp(f[1].member_name, "item") == 0 &&
+ strcmp(f[1].local_name, "item") == 0 && f[2].kind == CBM_PY_NS_IMPORT_NAME &&
+ strcmp(f[2].module_name, "second") == 0 && strcmp(f[2].local_name, "item") == 0 &&
+ f[3].kind == CBM_PY_NS_SHADOW && strcmp(f[3].local_name, "item") == 0 &&
+ f[4].kind == CBM_PY_NS_DELETE && strcmp(f[4].local_name, "item") == 0 &&
+ f[5].kind == CBM_PY_NS_IMPORT_MODULE && strcmp(f[5].module_name, "pkg.mod") == 0 &&
+ strcmp(f[5].local_name, "pkg") == 0 && f[5].flags == CBM_PY_NS_IMPORT_BINDS_ROOT &&
+ f[6].kind == CBM_PY_NS_IMPORT_MODULE && strcmp(f[6].module_name, "pkg.mod") == 0 &&
+ strcmp(f[6].local_name, "alias") == 0 && f[6].flags == 0 && f[7].relative_level == 1 &&
+ strcmp(f[7].module_name, "") == 0 && strcmp(f[7].member_name, "child") == 0 &&
+ strcmp(f[7].local_name, "local") == 0 && f[8].relative_level == 2 &&
+ strcmp(f[8].module_name, "outer") == 0 && strcmp(f[8].member_name, "member") == 0 &&
+ f[9].kind == CBM_PY_NS_IMPORT_STAR && strcmp(f[9].module_name, "one.shared") == 0 &&
+ f[10].kind == CBM_PY_NS_IMPORT_STAR && strcmp(f[10].module_name, "two.shared") == 0 &&
+ f[11].kind == CBM_PY_NS_OWN_DEF && f[11].def_kind == CBM_PY_NS_DEF_CLASS &&
+ strcmp(f[11].local_name, "Local") == 0 && py_facts_owned(&r->arena, &r->py_namespace);
+ }
+ if (r)
+ cbm_free_result(r);
+ ASSERT_TRUE(ok);
+ PASS();
+ }
+
+ /* The type checker view of `if TYPE_CHECKING:` publishes its consequence (a
+ * lazy-module package: the else branch only installs the module). A name an
+ * elif/else import binds again is withdrawn by a SHADOW: its runtime source is
+ * the alternative. Both streams stay COMPLETE and valid. */
+ TEST(python_namespace_facts_type_checking_alternatives) {
+ CBMFileResult *lazy = extract("from typing import TYPE_CHECKING\n"
+ "if TYPE_CHECKING:\n from .lazy_mod import Lazy\n"
+ "else:\n import sys\n",
+ CBM_LANG_PYTHON, "t", "lz/__init__.py");
+ CBMFileResult *compat = extract("from typing import TYPE_CHECKING\n"
+ "if TYPE_CHECKING:\n from .types_only import Shim\n"
+ "else:\n try:\n from .runtime_impl import Shim\n"
+ " except ImportError:\n Shim = None\n",
+ CBM_LANG_PYTHON, "t", "cmp/__init__.py");
+ bool ok = lazy && compat && lazy->py_namespace.status == CBM_PY_NS_COMPLETE &&
+ compat->py_namespace.status == CBM_PY_NS_COMPLETE &&
+ cbm_py_namespace_facts_valid(&lazy->py_namespace) &&
+ cbm_py_namespace_facts_valid(&compat->py_namespace) &&
+ lazy->py_namespace.count == 3 && compat->py_namespace.count == 3;
+ if (ok) {
+ const CBMPyNamespaceFact *l = lazy->py_namespace.items;
+ const CBMPyNamespaceFact *c = compat->py_namespace.items;
+ ok = l[1].kind == CBM_PY_NS_IMPORT_NAME && strcmp(l[1].local_name, "Lazy") == 0 &&
+ l[2].kind == CBM_PY_NS_SHADOW && strcmp(l[2].local_name, "sys") == 0 &&
+ c[1].kind == CBM_PY_NS_IMPORT_NAME && strcmp(c[1].local_name, "Shim") == 0 &&
+ c[2].kind == CBM_PY_NS_SHADOW && strcmp(c[2].local_name, "Shim") == 0;
+ }
+ if (lazy)
+ cbm_free_result(lazy);
+ if (compat)
+ cbm_free_result(compat);
+ ASSERT_TRUE(ok);
+ PASS();
+ }
+
+ /* A string-literal statement (a module, class or attribute docstring) has no
+ * effect, and `from __future__ import x` binds x like any from-import. Neither
+ * may withdraw the names bound before it: sqlalchemy's sql/expression.py lost
+ * its 149 re-exports to `nullsfirst = nulls_first` followed by a triple-quoted
+ * docstring. An f-string with a replacement field can run code
+ * (__format__ / __str__) and stays an effect. */
+ static bool py_facts_any_unknown(const CBMFileResult *r, CBMPyNamespaceUnknownReason reason) {
+ for (int i = 0; r && i < r->py_namespace.count; i++) {
+ if (r->py_namespace.items[i].kind == CBM_PY_NS_UNKNOWN &&
+ r->py_namespace.items[i].reason == reason)
+ return true;
+ }
+ return false;
+ }
+
+ TEST(python_namespace_facts_string_statements_and_future_imports) {
+ static const char source[] = "\"\"\"Module docstring.\"\"\"\n"
+ "from __future__ import annotations\n"
+ "from __future__ import (division as div, generator_stop)\n"
+ "from .impl import a\n"
+ "\"\"\"A triple-quoted string after an import.\"\"\"\n"
+ "'''Single-quoted triple.'''\n"
+ "r\"raw \\d\"\n"
+ "b\"bytes\"\n"
+ "rb'raw bytes'\n"
+ "u\"unicode\"\n"
+ "\"implicit\" 'concatenation'\n"
+ "f\"no replacement field {{escaped}}\"\n"
+ "from .impl import b\n"
+ "class Documented:\n"
+ " \"\"\"Class docstring.\"\"\"\n"
+ " def method(self):\n"
+ " pass\n"
+ "x = a\n"
+ "\"\"\"Attribute docstring.\"\"\"\n";
+ CBMFileResult *r = extract(source, CBM_LANG_PYTHON, "t", "pkg/__init__.py");
+ bool ok = r && !r->has_error && r->py_namespace.status == CBM_PY_NS_COMPLETE &&
+ cbm_py_namespace_facts_valid(&r->py_namespace) && r->py_namespace.count == 7;
+ if (ok) {
+ const CBMPyNamespaceFact *f = r->py_namespace.items;
+ ok = f[0].kind == CBM_PY_NS_IMPORT_NAME && strcmp(f[0].module_name, "__future__") == 0 &&
+ f[0].relative_level == 0 && strcmp(f[0].member_name, "annotations") == 0 &&
+ strcmp(f[0].local_name, "annotations") == 0 && f[1].kind == CBM_PY_NS_IMPORT_NAME &&
+ strcmp(f[1].member_name, "division") == 0 && strcmp(f[1].local_name, "div") == 0 &&
+ f[2].kind == CBM_PY_NS_IMPORT_NAME && strcmp(f[2].local_name, "generator_stop") == 0 &&
+ f[3].kind == CBM_PY_NS_IMPORT_NAME && strcmp(f[3].local_name, "a") == 0 &&
+ f[4].kind == CBM_PY_NS_IMPORT_NAME && strcmp(f[4].local_name, "b") == 0 &&
+ f[5].kind == CBM_PY_NS_OWN_DEF && f[5].def_kind == CBM_PY_NS_DEF_CLASS &&
+ strcmp(f[5].local_name, "Documented") == 0 && f[6].kind == CBM_PY_NS_SHADOW &&
+ strcmp(f[6].local_name, "x") == 0;
+ }
+ if (!ok && r) {
+ for (int i = 0; i < r->py_namespace.count; i++) {
+ const CBMPyNamespaceFact *f = &r->py_namespace.items[i];
+ printf(" string/future fact %d: kind %d reason %d name %s\n", i, (int)f->kind,
+ (int)f->reason, f->local_name ? f->local_name : "-");
+ }
+ }
+ if (r)
+ cbm_free_result(r);
+ ASSERT_TRUE(ok); /* RED while a docstring is an effect and __future__ is unsupported */
+
+ /* Controls: each stays a namespace barrier. */
+ static const struct {
+ const char *name;
+ const char *source;
+ CBMPyNamespaceUnknownReason reason;
+ } barriers[] = {
+ {"f-string field", "from .impl import a\nf\"{a}\"\n", CBM_PY_NS_REASON_EFFECT},
+ {"concatenated f-string field", "from .impl import a\n\"x\" f\"{a!r}\"\n",
+ CBM_PY_NS_REASON_EFFECT},
+ {"call", "from .impl import a\nprint(a)\n", CBM_PY_NS_REASON_EFFECT},
+ /* Python rejects it, and so does the grammar: the whole file is unknown */
+ {"star from __future__", "from .impl import a\nfrom __future__ import *\n",
+ CBM_PY_NS_REASON_PARSE},
+ };
+ for (size_t i = 0; i < sizeof(barriers) / sizeof(barriers[0]); i++) {
+ r = extract(barriers[i].source, CBM_LANG_PYTHON, "t", "pkg/__init__.py");
+ ok = r && r->py_namespace.status == CBM_PY_NS_COMPLETE &&
+ cbm_py_namespace_facts_valid(&r->py_namespace) &&
+ py_facts_any_unknown(r, barriers[i].reason);
+ if (!ok)
+ printf(" control '%s' is no namespace barrier\n", barriers[i].name);
+ if (r)
+ cbm_free_result(r);
+ ASSERT_TRUE(ok);
+ }
+ PASS();
+ }
+
+ /* A top-level call of a same-module function is a namespace effect, unless the
+ * callee provably cannot rebind the caller's names: sqlalchemy's
+ * `sql/__init__.py` ends with `__go(locals())`. Every submodule its body
+ * imports becomes a package attribute, so those names are shadowed at the
+ * call; everything else of the namespace survives. */
+ static bool py_facts_has_effect(const CBMFileResult *r) {
+ for (int i = 0; r && i < r->py_namespace.count; i++) {
+ if (r->py_namespace.items[i].kind == CBM_PY_NS_UNKNOWN &&
+ r->py_namespace.items[i].reason == CBM_PY_NS_REASON_EFFECT)
+ return true;
+ }
+ return false;
+ }
+
+ static int py_facts_count_kind(const CBMFileResult *r, CBMPyNamespaceFactKind kind) {
+ int n = 0;
+ for (int i = 0; r && i < r->py_namespace.count; i++)
+ n += r->py_namespace.items[i].kind == kind;
+ return n;
+ }
+
+ static bool py_facts_valid_complete(const CBMFileResult *r) {
+ return r && !r->has_error && r->py_namespace.status == CBM_PY_NS_COMPLETE &&
+ cbm_py_namespace_facts_valid(&r->py_namespace);
+ }
+
+ TEST(python_namespace_facts_init_call_allowlist) {
+ static const char go[] = "from typing import TYPE_CHECKING, Any\n"
+ "from .impl import base\n"
+ "from .elements import cast\n"
+ "def __go(lcls: Any) -> None:\n"
+ " from .. import util as _sa_util\n"
+ " from . import base\n"
+ " from . import coercions, elements as _el\n"
+ " if not TYPE_CHECKING:\n"
+ " base.coercions = _el.coercions = coercions\n"
+ " from .annotation import _prepare_annotations\n"
+ " _prepare_annotations(cast, cast)\n"
+ " _sa_util.preloaded.import_prefix(\"sqlalchemy.sql\")\n"
+ "\n"
+ "__go(locals())\n";
+ CBMFileResult *r = extract(go, CBM_LANG_PYTHON, "t", "sql/__init__.py");
+ bool ok = py_facts_valid_complete(r) && !py_facts_has_effect(r) && r->py_namespace.count == 9;
+ if (ok) {
+ const CBMPyNamespaceFact *f = r->py_namespace.items;
+ static const char *const shadowed[] = {"base", "coercions", "elements", "annotation"};
+ ok = f[2].kind == CBM_PY_NS_IMPORT_NAME && strcmp(f[2].local_name, "base") == 0 &&
+ f[4].kind == CBM_PY_NS_OWN_DEF && strcmp(f[4].local_name, "__go") == 0;
+ for (int i = 0; ok && i < 4; i++) {
+ ok = f[5 + i].kind == CBM_PY_NS_SHADOW && f[5 + i].local_name &&
+ strcmp(f[5 + i].local_name, shadowed[i]) == 0;
+ }
+ }
+ if (!ok && r) {
+ for (int i = 0; i < r->py_namespace.count; i++) {
+ const CBMPyNamespaceFact *f = &r->py_namespace.items[i];
+ printf(" __go fact %d: kind %d reason %d name %s\n", i, (int)f->kind, (int)f->reason,
+ f->local_name ? f->local_name : "-");
+ }
+ }
+ if (r)
+ cbm_free_result(r);
+ ASSERT_TRUE(ok); /* RED while every top-level call withdraws the namespace */
+
+ /* A plain module is no package: the body's imports set attributes of its
+ * parent package, never of the module itself. */
+ r = extract("def __go(lcls):\n from . import base\n\n__go(locals())\n", CBM_LANG_PYTHON, "t",
+ "sql/mod.py");
+ ok = py_facts_valid_complete(r) && !py_facts_has_effect(r) &&
+ py_facts_count_kind(r, CBM_PY_NS_SHADOW) == 0;
+ if (r)
+ cbm_free_result(r);
+ ASSERT_TRUE(ok);
+
+ /* Each of these can rebind a name of the caller's namespace (or is not
+ * provably a same-module function): the call stays a whole-namespace
+ * effect. */
+ static const char *const effects[][2] = {
+ {"param", "def __go(lcls):\n lcls['base'] = 1\n\n__go(locals())\n"},
+ {"global", "def __go(lcls):\n global base\n base = 1\n\n__go(locals())\n"},
+ {"nested global", "def __go(lcls):\n def inner():\n global base\n"
+ " base = 1\n inner()\n\n__go(locals())\n"},
+ {"globals()", "def __go(lcls):\n globals()['base'] = 1\n\n__go(locals())\n"},
+ {"sys.modules", "def __go(lcls):\n import sys\n sys.modules[__name__].base = 1\n"
+ "\n__go(locals())\n"},
+ {"imported callee", "from .setup import __go\n__go(locals())\n"},
+ {"own package name", "def __go(lcls):\n from .. import sql\n sql.base = 1\n"
+ "\n__go(locals())\n"},
+ {"same-module helper", "def helper():\n pass\n\ndef __go(lcls):\n helper()\n"
+ "\n__go(locals())\n"},
+ {"rebound callee", "def __go(lcls):\n pass\n\n__go = other\n__go(locals())\n"},
+ {"call before def", "__go(locals())\n\ndef __go(lcls):\n pass\n"},
+ {"argument effect", "def __go(lcls):\n pass\n\n__go(make())\n"},
+ {"rebound locals", "def locals():\n return {}\n\ndef __go(lcls):\n pass\n"
+ "\n__go(locals())\n"},
+ };
+ for (size_t i = 0; i < sizeof(effects) / sizeof(effects[0]); i++) {
+ char src[512];
+ snprintf(src, sizeof(src), "from .impl import base\n%s", effects[i][1]);
+ r = extract(src, CBM_LANG_PYTHON, "t", "sql/__init__.py");
+ ok = py_facts_valid_complete(r) && py_facts_has_effect(r);
+ if (!ok)
+ printf(" control '%s' is no namespace effect\n", effects[i][0]);
+ if (r)
+ cbm_free_result(r);
+ ASSERT_TRUE(ok);
+ }
+ PASS();
+ }
+
+ TEST(python_namespace_facts_distinguish_all_operations_and_unknowns) {
+ static const char source[] = "__all__ = ['old']; __all__ = []\n"
+ "__all__ = dynamic\n"
+ "__all__ = ('new', '_private', 'a,b', '')\n"
+ "__all__ += ('new',)\n"
+ "__all__ -= []\n"
+ "del __all__\n";
+ CBMFileResult *r = extract(source, CBM_LANG_PYTHON, "t", "main.py");
+ CBMFileResult *empty = extract("# no bindings\n", CBM_LANG_PYTHON, "t", "empty.py");
+ bool ok = r && empty && !r->has_error && !r->parse_incomplete && !empty->has_error &&
+ r->py_namespace.status == CBM_PY_NS_COMPLETE && r->py_namespace.count == 7 &&
+ empty->py_namespace.status == CBM_PY_NS_COMPLETE && empty->py_namespace.count == 0 &&
+ cbm_py_namespace_facts_valid(&r->py_namespace);
+ if (ok) {
+ const CBMPyNamespaceFact *f = r->py_namespace.items;
+ ok = f[0].kind == CBM_PY_NS_ALL_SET && f[0].name_count == 1 &&
+ strcmp(f[0].names[0], "old") == 0 && f[1].kind == CBM_PY_NS_ALL_SET &&
+ f[1].name_count == 0 && f[1].names == NULL &&
+ f[1].sequence_kind == CBM_PY_NS_SEQUENCE_LIST && f[2].kind == CBM_PY_NS_ALL_UNKNOWN &&
+ f[3].kind == CBM_PY_NS_ALL_SET && f[3].sequence_kind == CBM_PY_NS_SEQUENCE_TUPLE &&
+ f[3].name_count == 4 && strcmp(f[3].names[0], "new") == 0 &&
+ strcmp(f[3].names[1], "_private") == 0 && strcmp(f[3].names[2], "a,b") == 0 &&
+ strcmp(f[3].names[3], "") == 0 && f[4].kind == CBM_PY_NS_ALL_APPEND &&
+ f[4].name_count == 1 && strcmp(f[4].names[0], "new") == 0 &&
+ f[5].kind == CBM_PY_NS_ALL_UNKNOWN && f[6].kind == CBM_PY_NS_ALL_DELETE;
+ }
+ if (r)
+ cbm_free_result(r);
+ if (empty)
+ cbm_free_result(empty);
+ ASSERT_TRUE(ok);
+ PASS();
+ }
+
+ TEST(python_namespace_facts_unknown_effects_and_body_stability) {
+ static const char one[] = "from pkg import Item\ndef f():\n return 1\n";
+ static const char two[] =
+ "from pkg import Item\ndef f():\n from elsewhere import Other\n return Other()\n";
+ CBMFileResult *a = extract(one, CBM_LANG_PYTHON, "t", "main.py");
+ CBMFileResult *b = extract(two, CBM_LANG_PYTHON, "t", "main.py");
+ bool ok = a && b && !a->has_error && !b->has_error && !a->parse_incomplete &&
+ !b->parse_incomplete && a->py_namespace.count == 2 &&
+ py_facts_equal(&a->py_namespace, &b->py_namespace);
+ if (a)
+ cbm_free_result(a);
+ if (b)
+ cbm_free_result(b);
+ static const char unknown[] = "from pkg import Item\n"
+ "if enabled:\n from other import Item\n"
+ "@deco\ndef wrapped():\n pass\n"
+ "class Derived(Base):\n pass\n"
+ "Item = factory()\n";
+ a = extract(unknown, CBM_LANG_PYTHON, "t", "main.py");
+ ok = a && !a->has_error && !a->parse_incomplete && a->py_namespace.count == 8 && ok;
+ if (a && a->py_namespace.count == 8) {
+ const CBMPyNamespaceFact *f = a->py_namespace.items;
+ ok = f[0].kind == CBM_PY_NS_IMPORT_NAME && f[1].kind == CBM_PY_NS_UNKNOWN &&
+ f[1].reason == CBM_PY_NS_REASON_COMPOUND && f[2].kind == CBM_PY_NS_UNKNOWN &&
+ f[3].kind == CBM_PY_NS_SHADOW && f[3].reason == CBM_PY_NS_REASON_DECORATED &&
+ strcmp(f[3].local_name, "wrapped") == 0 && f[4].kind == CBM_PY_NS_UNKNOWN &&
+ f[5].kind == CBM_PY_NS_SHADOW && f[5].reason == CBM_PY_NS_REASON_UNPROVEN_CLASS &&
+ f[6].kind == CBM_PY_NS_UNKNOWN && f[7].kind == CBM_PY_NS_SHADOW && ok;
+ }
+ if (a)
+ cbm_free_result(a);
+ ASSERT_TRUE(ok);
+ PASS();
+ }
+
+ TEST(python_namespace_facts_parse_errors_are_complete_unknown) {
+ const char *source = "from pkg import Before\ndef broken(:\n";
+ CBMFileResult *r = extract(source, CBM_LANG_PYTHON, "t", "main.py");
+ bool ok = r && r->parse_incomplete && r->py_namespace.status == CBM_PY_NS_COMPLETE &&
+ r->py_namespace.count == 1 && r->py_namespace.items[0].kind == CBM_PY_NS_UNKNOWN &&
+ r->py_namespace.items[0].reason == CBM_PY_NS_REASON_PARSE &&
+ cbm_py_namespace_facts_valid(&r->py_namespace);
+ if (r)
+ cbm_free_result(r);
+ CBMFileResult fallback = {0};
+ cbm_arena_init(&fallback.arena);
+ CBMExtractCtx ctx = {.arena = &fallback.arena,
+ .result = &fallback,
+ .source = "",
+ .source_len = 0,
+ .language = CBM_LANG_PYTHON};
+ ok = cbm_extract_python_namespace_facts(&ctx) == CBM_PY_NS_COMPLETE &&
+ fallback.py_namespace.count == 1 &&
+ fallback.py_namespace.items[0].reason == CBM_PY_NS_REASON_PARSE && ok;
+ cbm_arena_destroy(&fallback.arena);
+ r = extract("const x = 1;\n", CBM_LANG_JAVASCRIPT, "t", "__init__.js");
+ ok = r && !r->has_error && r->py_namespace.status == CBM_PY_NS_NOT_APPLICABLE &&
+ r->py_namespace.language == CBM_LANG_JAVASCRIPT && r->py_namespace.count == 0 && ok;
+ if (r)
+ cbm_free_result(r);
+ ASSERT_TRUE(ok);
+ PASS();
+ }
+
+ TEST(python_namespace_facts_capture_and_copy_fail_atomically) {
+ static const char source[] = "from .pkg import Item as Local\n__all__ = ['Local', '']\n";
+ bool ok = true, capture_complete = false, copy_complete = false;
+ int capture_failures = 0, copy_failures = 0;
+ for (int limit = 0; limit < 64 && !capture_complete; limit++) {
+ cbm_py_namespace_test_capture_fail_after(limit);
+ CBMFileResult *r = extract(source, CBM_LANG_PYTHON, "t", "pkg/__init__.py");
+ cbm_py_namespace_test_capture_fail_after(-1);
+ if (!r) {
+ ok = false;
+ break;
+ }
+ const CBMPyNamespaceFacts *f = &r->py_namespace;
+ capture_complete = f->status == CBM_PY_NS_COMPLETE;
+ if (capture_complete) {
+ ok = f->count == 2 && cbm_py_namespace_facts_valid(f) && ok;
+ } else {
+ capture_failures++;
+ ok = f->status == CBM_PY_NS_INCOMPLETE && f->failure == CBM_PY_NS_FAILURE_ALLOCATION &&
+ !f->items && f->count == 0 && f->cap == 0 && cbm_py_namespace_facts_valid(f) && ok;
+ }
+ cbm_free_result(r);
+ }
+ CBMFileResult *r = extract(source, CBM_LANG_PYTHON, "t", "pkg/__init__.py");
+ CBMArena reference_arena;
+ cbm_arena_init(&reference_arena);
+ CBMPyNamespaceFacts original = {0};
+ ok = r && cbm_py_namespace_facts_copy(&reference_arena, &r->py_namespace, &original) && ok;
+ for (int limit = 0; r && limit < 64 && !copy_complete; limit++) {
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMPyNamespaceFacts copy = {0};
+ cbm_py_namespace_test_copy_fail_after(limit);
+ copy_complete = cbm_py_namespace_facts_copy(&arena, &r->py_namespace, &copy);
+ cbm_py_namespace_test_copy_fail_after(-1);
+ if (copy_complete) {
+ ok = py_facts_equal(&copy, &r->py_namespace) && py_facts_owned(&arena, &copy) && ok;
+ } else {
+ copy_failures++;
+ ok = copy.status == CBM_PY_NS_INCOMPLETE &&
+ copy.failure == CBM_PY_NS_FAILURE_ALLOCATION && !copy.items && copy.count == 0 &&
+ copy.cap == 0 && ok;
+ }
+ ok = py_facts_equal(&r->py_namespace, &original) && ok;
+ cbm_arena_destroy(&arena);
+ }
+ /* Rebuilding into an existing result must replace old complete facts on
+ * failure; do not leave a stale successful manifest attached. */
+ if (r) {
+ CBMExtractCtx ctx = {.arena = &r->arena,
+ .result = r,
+ .source = source,
+ .source_len = (int)strlen(source),
+ .language = CBM_LANG_PYTHON};
+ cbm_py_namespace_test_capture_fail_after(0);
+ CBMPyNamespaceStatus status = cbm_extract_python_namespace_facts(&ctx);
+ cbm_py_namespace_test_capture_fail_after(-1);
+ ok = status == CBM_PY_NS_INCOMPLETE && !r->py_namespace.items &&
+ r->py_namespace.count == 0 && ok;
+ cbm_free_result(r);
+ }
+ cbm_arena_destroy(&reference_arena);
+ ASSERT_TRUE(ok);
+ ASSERT_TRUE(capture_complete);
+ ASSERT_TRUE(copy_complete);
+ ASSERT_GT(capture_failures, 2);
+ ASSERT_GT(copy_failures, 2);
+ PASS();
+ }
+
+ TEST(python_namespace_facts_validation_rejects_partial_and_unknown_schema) {
+ CBMPyNamespaceFacts zero = {0};
+ bool ok = cbm_py_namespace_facts_valid(&zero) && zero.status == CBM_PY_NS_NOT_CAPTURED;
+ CBMPyNamespaceFact event = {.kind = CBM_PY_NS_ALL_SET,
+ .sequence_kind = CBM_PY_NS_SEQUENCE_LIST};
+ CBMPyNamespaceFacts facts = {.version = CBM_PY_NAMESPACE_FACTS_VERSION,
+ .language = CBM_LANG_PYTHON,
+ .status = CBM_PY_NS_COMPLETE,
+ .items = &event,
+ .count = 1,
+ .cap = 1};
+ ok = cbm_py_namespace_facts_valid(&facts) && ok;
+ for (int variant = 0; variant < 8; variant++) {
+ CBMPyNamespaceFact bad_event = event;
+ CBMPyNamespaceFacts bad = facts;
+ bad.items = &bad_event;
+ if (variant == 0)
+ bad.version++;
+ if (variant == 1)
+ bad.cap = 0;
+ if (variant == 2)
+ bad.count = -1;
+ if (variant == 3)
+ bad_event.kind = (CBMPyNamespaceFactKind)999;
+ if (variant == 4)
+ bad_event.name_count = 1;
+ if (variant == 5)
+ bad_event.flags = UINT32_MAX;
+ if (variant == 6)
+ bad.language = CBM_LANG_JAVA;
+ if (variant == 7)
+ bad.status = CBM_PY_NS_INCOMPLETE;
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMPyNamespaceFacts copy = {0};
+ ok = !cbm_py_namespace_facts_valid(&bad) &&
+ !cbm_py_namespace_facts_copy(&arena, &bad, &copy) &&
+ copy.status == CBM_PY_NS_INCOMPLETE && copy.count == 0 && !copy.items && ok;
+ cbm_arena_destroy(&arena);
+ }
+ ASSERT_TRUE(ok);
+ PASS();
+ }
+
+ TEST(python_namespace_facts_compact_spill_and_copy_keep_owned_payload) {
+ char source[] = "from . import Thing as Local\n"
+ "__all__ = ['Local', '', 'a,b', '_private']\n"
+ "if enabled:\n Local = dynamic\n"
+ "__all__ = []\n";
+ CBMFileResult *r = extract(source, CBM_LANG_PYTHON, "t", "pkg/__init__.py");
+ CBMArena retained;
+ cbm_arena_init(&retained);
+ CBMPyNamespaceFacts expected = {0};
+ bool ok = r && !r->has_error && !r->parse_incomplete && r->py_namespace.count == 4 &&
+ cbm_py_namespace_facts_copy(&retained, &r->py_namespace, &expected);
+ memset(source, 'x', strlen(source)); /* facts cannot borrow the caller's input */
+ char dir[512];
+ int n = snprintf(dir, sizeof(dir), "%s/cbm_py_facts_XXXXXX", cbm_tmpdir());
+ bool made = n > 0 && (size_t)n < sizeof(dir) && cbm_mkdtemp(dir);
+ size_t saved = cbm_result_spill_pin_free_bytes_for_tests(SIZE_MAX);
+ cbm_result_spill_t *spill = made ? cbm_result_spill_open(dir, 1, 1) : NULL;
+ cbm_result_spill_pin_free_bytes_for_tests(saved);
+ ok = spill && ok;
+ if (r && spill && ok) {
+ cbm_result_compact(r);
+ cbm_result_compact(r);
+ ok = r->arena.nblocks == 1 && r->py_namespace.cap == r->py_namespace.count &&
+ py_facts_equal(&r->py_namespace, &expected) &&
+ py_facts_owned(&r->arena, &r->py_namespace);
+ if (ok && cbm_result_spill_park(spill, 0, 0, r)) {
+ r = NULL;
+ CBMFileResult header = {0};
+ ok = cbm_result_spill_peek_header(spill, 0, &header) &&
+ header.py_namespace.status == CBM_PY_NS_COMPLETE && header.py_namespace.count == 4;
+ for (int round = 0; round < 2; round++) {
+ CBMFileResult *loaded = cbm_result_spill_load(spill, 0);
+ ok = loaded && loaded->cached_tree == NULL &&
+ py_facts_owned(&loaded->arena, &loaded->py_namespace) &&
+ py_facts_equal(&loaded->py_namespace, &expected) && ok;
+ if (loaded)
+ cbm_free_result(loaded);
+ }
+ } else {
+ ok = false;
+ }
+ }
+ if (r)
+ cbm_free_result(r);
+ cbm_result_spill_close(spill);
+ if (made) {
+ char subdir[1024];
+ snprintf(subdir, sizeof(subdir), "%s/spill", dir);
+ cbm_rmdir(subdir);
+ cbm_rmdir(dir);
+ }
+ /* Original result/source tree and both reloads are gone; the independent
+ * copied payload still owns the relative empty module and literal strings. */
+ ok = py_facts_owned(&retained, &expected) && cbm_py_namespace_facts_valid(&expected) &&
+ expected.count == 4 && expected.items[0].relative_level == 1 &&
+ strcmp(expected.items[0].module_name, "") == 0 && expected.items[1].name_count == 4 &&
+ strcmp(expected.items[1].names[2], "a,b") == 0 && ok;
+ cbm_arena_destroy(&retained);
+ ASSERT_TRUE(ok);
+ PASS();
+ }
+
+ TEST(python_namespace_facts_unavailable_and_empty_survive_spill) {
+ CBMPyNamespaceFacts states[] = {
+ {0},
+ {.version = CBM_PY_NAMESPACE_FACTS_VERSION,
+ .language = CBM_LANG_PYTHON,
+ .status = CBM_PY_NS_COMPLETE},
+ {.version = CBM_PY_NAMESPACE_FACTS_VERSION,
+ .language = CBM_LANG_PYTHON,
+ .status = CBM_PY_NS_INCOMPLETE,
+ .failure = CBM_PY_NS_FAILURE_ALLOCATION},
+ {.version = CBM_PY_NAMESPACE_FACTS_VERSION,
+ .language = CBM_LANG_JAVASCRIPT,
+ .status = CBM_PY_NS_NOT_APPLICABLE},
+ };
+ char dir[512];
+ int n = snprintf(dir, sizeof(dir), "%s/cbm_py_fact_states_XXXXXX", cbm_tmpdir());
+ bool made = n > 0 && (size_t)n < sizeof(dir) && cbm_mkdtemp(dir);
+ size_t saved = cbm_result_spill_pin_free_bytes_for_tests(SIZE_MAX);
+ cbm_result_spill_t *spill = made ? cbm_result_spill_open(dir, 1, 4) : NULL;
+ cbm_result_spill_pin_free_bytes_for_tests(saved);
+ bool ok = spill != NULL;
+ for (int i = 0; spill && i < 4; i++) {
+ CBMFileResult *r = cbm_result_alloc();
+ if (!r) {
+ ok = false;
+ break;
+ }
+ cbm_arena_init(&r->arena);
+ r->module_qn = cbm_arena_strdup(&r->arena, "t.metadata");
+ r->py_namespace = states[i];
+ cbm_result_compact(r);
+ cbm_result_compact(r);
+ bool ready =
+ r->module_qn && r->arena.nblocks == 1 && py_facts_equal(&r->py_namespace, &states[i]);
+ if (!ready || !cbm_result_spill_park(spill, 0, i, r)) {
+ ok = false;
+ cbm_free_result(r);
+ continue;
+ }
+ CBMFileResult header = {0};
+ ok = cbm_result_spill_peek_header(spill, i, &header) &&
+ header.py_namespace.status == states[i].status && header.py_namespace.count == 0 && ok;
+ for (int round = 0; round < 2; round++) {
+ CBMFileResult *loaded = cbm_result_spill_load(spill, i);
+ ok = loaded && py_facts_equal(&loaded->py_namespace, &states[i]) &&
+ py_facts_owned(&loaded->arena, &loaded->py_namespace) && ok;
+ if (loaded)
+ cbm_free_result(loaded);
+ }
+ }
+ cbm_result_spill_close(spill);
+ if (made) {
+ char subdir[1024];
+ snprintf(subdir, sizeof(subdir), "%s/spill", dir);
+ cbm_rmdir(subdir);
+ cbm_rmdir(dir);
+ }
+ ASSERT_TRUE(ok);
+ PASS();
+ }
+
+ TEST(python_namespace_facts_multiple_bindings_and_unsupported_effects) {
+ static const char source[] = "import alpha, beta.mod as Beta\n"
+ "from pkg import (One, Two as Local)\n"
+ "from pkg import later\n"
+ "def later():\n pass\n"
+ "from pkg import __all__\n"
+ "def __all__():\n pass\n"
+ "values = {obj: 1}\n"
+ "class HasDescriptor:\n field = descriptor\n"
+ "__all__ = ['escaped\\n']\n";
+ CBMFileResult *r = extract(source, CBM_LANG_PYTHON, "t", "main.py");
+ bool ok = r && !r->has_error && !r->parse_incomplete &&
+ r->py_namespace.status == CBM_PY_NS_COMPLETE && r->py_namespace.count == 13 &&
+ cbm_py_namespace_facts_valid(&r->py_namespace) && has_def(r, "Function", "later") &&
+ has_def(r, "Class", "HasDescriptor");
+ if (ok) {
+ const CBMPyNamespaceFact *f = r->py_namespace.items;
+ ok = f[0].kind == CBM_PY_NS_IMPORT_MODULE && strcmp(f[0].local_name, "alpha") == 0 &&
+ f[1].kind == CBM_PY_NS_IMPORT_MODULE && strcmp(f[1].local_name, "Beta") == 0 &&
+ strcmp(f[1].module_name, "beta.mod") == 0 && f[2].kind == CBM_PY_NS_IMPORT_NAME &&
+ strcmp(f[2].member_name, "One") == 0 && f[3].kind == CBM_PY_NS_IMPORT_NAME &&
+ strcmp(f[3].member_name, "Two") == 0 && strcmp(f[3].local_name, "Local") == 0 &&
+ f[4].kind == CBM_PY_NS_IMPORT_NAME && f[5].kind == CBM_PY_NS_OWN_DEF &&
+ strcmp(f[5].local_name, "later") == 0 && f[6].kind == CBM_PY_NS_IMPORT_NAME &&
+ strcmp(f[6].local_name, "__all__") == 0 && f[7].kind == CBM_PY_NS_OWN_DEF &&
+ strcmp(f[7].local_name, "__all__") == 0 && f[8].kind == CBM_PY_NS_UNKNOWN &&
+ f[9].kind == CBM_PY_NS_SHADOW && strcmp(f[9].local_name, "values") == 0 &&
+ f[10].kind == CBM_PY_NS_UNKNOWN && f[11].kind == CBM_PY_NS_SHADOW &&
+ f[11].reason == CBM_PY_NS_REASON_UNPROVEN_CLASS &&
+ /* a string with an escape evaluates nothing: no effect, but no
+ * literal export name either */
+ f[12].kind == CBM_PY_NS_ALL_UNKNOWN;
+ }
+ if (r)
+ cbm_free_result(r);
+ ASSERT_TRUE(ok);
+ PASS();
+ }
+
+#ifdef _WIN32
+/* The supervisor sets this path through cbm_setenv. Exercise the actual
+ * journal writer, which must read it as UTF-8 before calling cbm_fopen. */
+TEST(extraction_marker_round_trips_non_ascii_environment_path) {
+ char dir[512] = "/tmp/cbm-marker-XXXXXX";
+ ASSERT_NOT_NULL(cbm_mkdtemp(dir));
+ char marker[640];
+ snprintf(marker, sizeof(marker), "%s/marker-\xce\x94-\xe4\xb8\x81.log", dir);
+ char saved[4096];
+ const char *previous = cbm_safe_getenv("CBM_INDEX_MARKER_FILE", saved, sizeof(saved), NULL);
+ ASSERT_EQ(cbm_setenv("CBM_INDEX_MARKER_FILE", marker, 1), 0);
+ cbm_index_mark_start("synthetic.cpp");
+ cbm_index_mark_done("synthetic.cpp");
+ if (previous) {
+ (void)cbm_setenv("CBM_INDEX_MARKER_FILE", saved, 1);
+ } else {
+ (void)cbm_unsetenv("CBM_INDEX_MARKER_FILE");
+ }
+ FILE *file = cbm_fopen(marker, "rb");
+ char contents[128] = {0};
+ if (file) {
+ (void)fread(contents, 1, sizeof(contents) - 1, file);
+ (void)fclose(file);
+ }
+ (void)cbm_unlink(marker);
+ (void)cbm_rmdir(dir);
+ ASSERT_NOT_NULL(file);
+ ASSERT_STR_EQ(contents, "S synthetic.cpp\nD synthetic.cpp\n");
+ PASS();
+}
+#endif
+
SUITE(extraction) {
+#ifdef _WIN32
+ RUN_TEST(extraction_marker_round_trips_non_ascii_environment_path);
+#endif
RUN_TEST(extract_compact_keeps_every_field_and_shrinks_the_arena);
RUN_TEST(extract_compact_is_idempotent_and_survives_empty_results);
RUN_TEST(extract_spill_round_trip_keeps_every_field);