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
perf(store): index-friendly plans for architecture, schema counts and anchored name search
Martin Vogel312fb368445f
diff --git a/src/store/store.c b/src/store/store.cindex ca9efe46e..d98c07e84 100644--- a/src/store/store.c+++ b/src/store/store.c@@ -9,6 +9,7 @@// for ISO timestamp#include <limits.h>+#include <stdarg.h>#include <stdint.h>#include "foundation/constants.h"#include "foundation/arena.h"@@ -54,9 +55,13 @@ enum {ST_GLOB_MIN_LEN = 3,ST_GLOB_SKIP = 2,ST_MAX_LANG = 10,- ST_SEARCH_MAX_BINDS = 32, /* increased: LIKE pre-filter adds binds per pattern */- ST_LIKE_POOL_MAX = 12, /* max malloc'd LIKE strings alive during one search */- ST_LIKE_HINT_MAX = 2, /* max LIKE hints extracted per regex pattern */+ ST_SEARCH_MAX_BINDS = 48, /* LIKE pre-filters + anchored-name range bounds add binds */+ ST_LIKE_POOL_MAX = 12, /* max malloc'd LIKE strings alive during one search */+ ST_LIKE_HINT_MAX = 2, /* max LIKE hints extracted per regex pattern */+ ST_NAME_RANGE_PREFIX = 64, /* longest anchored name prefix seeked on */+ ST_NAME_RANGE_LETTERS = 3, /* case-insensitive: letters expanded into case variants */+ ST_NAME_RANGE_MAX = 8, /* 2^ST_NAME_RANGE_LETTERS name ranges (UNION ALL arms) */+ ST_NAME_RANGE_ARM_SQL = 96, /* per-arm SQL beyond the select list and WHERE */ST_MAX_PKGS = 64,ST_INIT_CAP_4 = 4,ST_HEADER_PREFIX = 3,@@ -6732,6 +6737,36 @@ int cbm_extract_like_hints(const char *pattern, char **out, int max_out) {return count;}+/* Patterns run as POSIX ERE without REG_NEWLINE, so '^' anchors at the start of+ * the name only, and a pattern without '|' is one concatenation: every match+ * begins with the literal run after the '^'. A following '*', '?', '{' may+ * repeat the run's last character zero times and '+' may be combined with them+ * (glibc reads "a+?" as "(a+)?"), so that character is dropped; so is the one+ * before a backslash, which no rule here needs to interpret. */+int cbm_regex_anchored_prefix(const char *pattern, char *out, int out_sz) {+ if (!pattern || !out || out_sz <= 1 || pattern[0] != '^' || strchr(pattern, '|')) {+ if (out && out_sz > 0) {+ out[0] = '\0';+ }+ return 0;+ }+ int len = 0;+ const char *p = pattern + SKIP_ONE;+ while (*p && len < out_sz - SKIP_ONE) {+ unsigned char c = (unsigned char)*p;+ if (c < ' ' || c > '~' || strchr(".[]()*+?{}|^$\\", c)) {+ break;+ }+ out[len++] = (char)c;+ p++;+ }+ if (len > 0 && *p && strchr("*+?{\\", *p)) {+ len--;+ }+ out[len] = '\0';+ return len;+}+/* ── ensureCaseInsensitive / stripCaseFlag ────────────────────── */const char *cbm_ensure_case_insensitive(const char *pattern) {@@ -7028,6 +7063,151 @@ static int search_build_where(const cbm_search_params_t *params, char *where, inreturn nparams;}+/* Anchored name patterns ("^schedule$", "^kmalloc"): every matching name begins+ * with the pattern's literal prefix (cbm_regex_anchored_prefix), so it lies in a+ * half-open idx_nodes_name range [prefix, prefix with its last byte + 1). Under+ * iregexp the prefix matches in any letter case: the process never calls+ * setlocale, so the regex runs in the C locale and folds ASCII letters only, and+ * each of the first ST_NAME_RANGE_LETTERS letters doubles the ranges. The ranges+ * are ADDED to the full WHERE (LIKE hints and regex stay), so the rows are those+ * of the plain query — which instead scans every name of the project. */+typedef struct {+ char lo[ST_NAME_RANGE_MAX][ST_NAME_RANGE_PREFIX];+ char hi[ST_NAME_RANGE_MAX][ST_NAME_RANGE_PREFIX];+ int count;+} search_name_ranges_t;++static bool name_range_letter(char c) {+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');+}++static char name_range_case(char c, bool lower) {+ if (lower && c >= 'A' && c <= 'Z') {+ return (char)(c - 'A' + 'a');+ }+ if (!lower && c >= 'a' && c <= 'z') {+ return (char)(c - 'a' + 'A');+ }+ return c;+}++static int search_name_ranges(const cbm_search_params_t *p, search_name_ranges_t *r) {+ r->count = 0;+ /* Without the project the index cannot seek the name; degree filters wrap+ * the query in a subselect this rewrite leaves alone. */+ if (!p->project || !p->name_pattern || p->min_degree >= 0 || p->max_degree >= 0) {+ return 0;+ }+ char prefix[ST_NAME_RANGE_PREFIX];+ int len = cbm_regex_anchored_prefix(p->name_pattern, prefix, (int)sizeof(prefix));+ if (len == 0) {+ return 0;+ }+ /* A pattern the regex function rejects fails the plain query once a row+ * reaches the regex; fewer rows reach it here, so it keeps the plain query. */+ int flags = CBM_REG_EXTENDED | CBM_REG_NOSUB | (p->case_sensitive ? 0 : CBM_REG_ICASE);+ cbm_regex_t re;+ if (cbm_regcomp(&re, p->name_pattern, flags) != 0) {+ return 0;+ }+ cbm_regfree(&re);+ int letters = 0;+ if (!p->case_sensitive) {+ int k = 0;+ for (; k < len; k++) {+ if (name_range_letter(prefix[k])) {+ if (letters == ST_NAME_RANGE_LETTERS) {+ break;+ }+ letters++;+ }+ }+ len = k;+ }+ int variants = SKIP_ONE << letters;+ for (int v = 0; v < variants; v++) {+ int bit = letters - SKIP_ONE;+ for (int i = 0; i < len; i++) {+ char c = prefix[i];+ if (!p->case_sensitive && name_range_letter(c)) {+ /* Variant 0 is all upper case: ranges in ascending byte order. */+ c = name_range_case(c, ((v >> bit) & SKIP_ONE) != 0);+ bit--;+ }+ r->lo[v][i] = c;+ r->hi[v][i] = c;+ }+ r->lo[v][len] = '\0';+ r->hi[v][len] = '\0';+ r->hi[v][len - SKIP_ONE]++; /* printable ASCII: never wraps */+ }+ r->count = variants;+ return variants;+}++/* Main and count SQL over the name ranges: one UNION ALL arm per range, each+ * the plain WHERE plus its range, so every arm seeks idx_nodes_name. The arms+ * are disjoint and each yields (name, id) order, so ORDER BY 4, 1 (n.name,+ * n.id) merges them without a sort and the per-row degree subqueries run only+ * for rows the page emits; the count sums the per-range counts. On false+ * (allocation, bind slots) nothing is bound and the plain query runs. */+/* Append to buf[0..cap) at *len; false (nothing written past cap) when it+ * does not fit. */+static bool search_sql_append(char *buf, size_t cap, size_t *len, const char *fmt, ...) {+ if (*len >= cap) {+ return false;+ }+ va_list args;+ va_start(args, fmt);+ int wrote = vsnprintf(buf + *len, cap - *len, fmt, args);+ va_end(args);+ if (wrote < 0 || (size_t)wrote >= cap - *len) {+ return false;+ }+ *len += (size_t)wrote;+ return true;+}++static bool search_build_ranged_sql(const char *select_cols, const char *where,+ const search_name_ranges_t *r, int limit, int offset,+ search_bind_t *binds, int *bind_idx, char **out_sql,+ char **out_count_sql) {+ if (*bind_idx + (r->count * ST_COL_2) > ST_SEARCH_MAX_BINDS) {+ return false;+ }+ size_t cap = (strlen(select_cols) + strlen(where) + ST_NAME_RANGE_ARM_SQL) * (size_t)r->count ++ ST_NAME_RANGE_ARM_SQL;+ char *sql = cbm_alloc(CBM_MEM_CLASS_STORE, cap);+ char *cnt = cbm_alloc(CBM_MEM_CLASS_STORE, cap);+ int first_bind = *bind_idx;+ size_t sl = 0;+ size_t cl = 0;+ bool ok = sql && cnt && search_sql_append(cnt, cap, &cl, "SELECT ");+ for (int i = 0; ok && i < r->count; i++) {+ int lo = *bind_idx + SKIP_ONE;+ where_bind_text(binds, bind_idx, r->lo[i]);+ where_bind_text(binds, bind_idx, r->hi[i]);+ ok = search_sql_append(sql, cap, &sl,+ "%s%s FROM nodes n WHERE (%s) AND n.name >= ?%d AND n.name < ?%d",+ i > 0 ? " UNION ALL " : "", select_cols, where, lo, lo + SKIP_ONE) &&+ search_sql_append(cnt, cap, &cl,+ "%s(SELECT COUNT(*) FROM nodes n WHERE (%s) AND n.name >= ?%d AND "+ "n.name < ?%d)",+ i > 0 ? " + " : "", where, lo, lo + SKIP_ONE);+ }+ ok = ok && search_sql_append(sql, cap, &sl, " ORDER BY 4, 1 LIMIT %d OFFSET %d", limit, offset);+ if (!ok) {+ /* Nothing is bound: the caller runs the plain query. */+ *bind_idx = first_bind;+ cbm_free(CBM_MEM_CLASS_STORE, sql);+ cbm_free(CBM_MEM_CLASS_STORE, cnt);+ return false;+ }+ *out_sql = sql;+ *out_count_sql = cnt;+ return true;+}+int cbm_store_search(cbm_store_t *s, const cbm_search_params_t *params, cbm_search_output_t *out) {memset(out, 0, sizeof(*out));if (!s || !s->db) {@@ -7088,9 +7268,21 @@ int cbm_store_search(cbm_store_t *s, const cbm_search_params_t *params, cbm_searid_col, limit, offset);strncat(sql, order_limit, sizeof(sql) - strlen(sql) - 1);+ /* Anchored name pattern: the same rows through idx_nodes_name seeks. */+ search_name_ranges_t name_ranges;+ char *ranged_sql = NULL;+ char *ranged_count_sql = NULL;+ if (nparams > 0 && search_name_ranges(params, &name_ranges) > 0) {+ (void)search_build_ranged_sql(select_cols, where, &name_ranges, limit, offset, binds,+ &bind_idx, &ranged_sql, &ranged_count_sql);+ }+ const char *main_sql = ranged_sql ? ranged_sql : sql;+ const char *total_sql = ranged_count_sql ? ranged_count_sql : count_sql;+/* Execute count query */sqlite3_stmt *cnt_stmt = NULL;- int rc = sqlite3_prepare_v2(s->db, count_sql, CBM_NOT_FOUND, &cnt_stmt, NULL);+ int rc = sqlite3_prepare_v2(s->db, total_sql, CBM_NOT_FOUND, &cnt_stmt, NULL);+ cbm_free(CBM_MEM_CLASS_STORE, ranged_count_sql); /* prepare_v2 copies the text */if (rc == SQLITE_OK) {for (int i = 0; i < bind_idx; i++) {bind_text(cnt_stmt, i + SKIP_ONE, binds[i].text);@@ -7103,7 +7295,8 @@ int cbm_store_search(cbm_store_t *s, const cbm_search_params_t *params, cbm_sear/* Execute main query */sqlite3_stmt *main_stmt = NULL;- rc = sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &main_stmt, NULL);+ rc = sqlite3_prepare_v2(s->db, main_sql, CBM_NOT_FOUND, &main_stmt, NULL);+ cbm_free(CBM_MEM_CLASS_STORE, ranged_sql);if (rc != SQLITE_OK) {store_set_error_sqlite(s, "search prepare");like_pool_free(&like_pool);@@ -7956,6 +8149,25 @@ int cbm_store_count_edges_scoped(cbm_store_t *s, const char *project, const charreturn n;}+/* Per-label and per-type counts. GROUP BY over the (project, label) index+ * decodes every entry to compare its group key; stepping through the distinct+ * values with MIN(col) > previous seeks and counting each value's index range+ * is ~1.6x faster (kernel, 8.5M nodes: 0.26 -> 0.16 s; 16.9M edges: 0.54 ->+ * 0.32 s). The values reach ORDER BY in the ascending order GROUP BY emitted+ * them in, so tied counts keep their order. label and type are NOT NULL. */+static const char ST_LABEL_COUNTS_SQL[] =+ "WITH RECURSIVE v(x) AS (SELECT MIN(label) FROM nodes WHERE project = ?1 UNION ALL "+ "SELECT (SELECT MIN(label) FROM nodes WHERE project = ?1 AND label > v.x) FROM v "+ "WHERE v.x IS NOT NULL) "+ "SELECT x, (SELECT COUNT(*) FROM nodes WHERE project = ?1 AND label = v.x) AS c "+ "FROM v WHERE x IS NOT NULL ORDER BY c DESC;";+static const char ST_TYPE_COUNTS_SQL[] =+ "WITH RECURSIVE v(x) AS (SELECT MIN(type) FROM edges WHERE project = ?1 UNION ALL "+ "SELECT (SELECT MIN(type) FROM edges WHERE project = ?1 AND type > v.x) FROM v "+ "WHERE v.x IS NOT NULL) "+ "SELECT x, (SELECT COUNT(*) FROM edges WHERE project = ?1 AND type = v.x) AS c "+ "FROM v WHERE x IS NOT NULL ORDER BY c DESC;";+/* with_props=false skips the per-label/per-type JSON property-key discovery:* those json_each() scans walk EVERY row of each label/type (minutes-scale on* multi-million-node graphs) and get_architecture only needs the counts. */@@ -7968,8 +8180,7 @@ static int get_schema_impl(cbm_store_t *s, const char *project, cbm_schema_info_/* Node labels */{- const char *sql = "SELECT label, COUNT(*) FROM nodes WHERE project = ?1 GROUP BY label "- "ORDER BY COUNT(*) DESC;";+ const char *sql = ST_LABEL_COUNTS_SQL;sqlite3_stmt *stmt = NULL;if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK || !stmt) {if (stmt) {@@ -8041,8 +8252,7 @@ static int get_schema_impl(cbm_store_t *s, const char *project, cbm_schema_info_/* Edge types */{- const char *sql = "SELECT type, COUNT(*) FROM edges WHERE project = ?1 GROUP BY type ORDER "- "BY COUNT(*) DESC;";+ const char *sql = ST_TYPE_COUNTS_SQL;sqlite3_stmt *stmt = NULL;if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK || !stmt) {if (stmt) {@@ -9013,15 +9223,24 @@ static int arch_packages(cbm_store_t *s, const char *project, const char *path,char like[CBM_SZ_512];bool scoped = arch_path_prepare(path, norm, sizeof(norm), like, sizeof(like));char sqlbuf[ST_SQL_BUF];+ /* GROUP BY +n.name, not n.name: with a bare column the planner walks+ * idx_nodes_name over EVERY node of the project to get groups in name order,+ * with a table lookup per node to test the label (6.3 s on the 8.5M-node+ * kernel graph, for 5 Package nodes). The unary plus keeps the value and its+ * BINARY collation but not the index, so the rows come from the+ * idx_nodes_label seek. The ORDER BY sorter keeps tied counts in group+ * emission order, which was name order from the index; a sorted GROUP BY+ * follows the ORDER BY direction instead, so the name tie-break is explicit. */const char *base = "SELECT n.name, COUNT(*) as cnt FROM nodes n ""WHERE n.project=?1 AND n.label='Package'";if (scoped) {snprintf(sqlbuf, sizeof(sqlbuf),"%s AND (n.file_path = ?2 OR n.file_path LIKE ?3) "- "GROUP BY n.name ORDER BY cnt DESC LIMIT 15",+ "GROUP BY +n.name ORDER BY cnt DESC, +n.name LIMIT 15",base);} else {- snprintf(sqlbuf, sizeof(sqlbuf), "%s GROUP BY n.name ORDER BY cnt DESC LIMIT 15", base);+ snprintf(sqlbuf, sizeof(sqlbuf), "%s GROUP BY +n.name ORDER BY cnt DESC, +n.name LIMIT 15",+ base);}sqlite3_stmt *stmt = NULL;if (sqlite3_prepare_v2(s->db, sqlbuf, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {diff --git a/src/store/store.h b/src/store/store.hindex 364a3eaf4..123e7645e 100644--- a/src/store/store.h+++ b/src/store/store.h@@ -1243,6 +1243,13 @@ char *cbm_glob_to_like(const char *pattern);* Each out[i] is malloc'd — caller must free each string. */int cbm_extract_like_hints(const char *pattern, char **out, int max_out);+/* Literal prefix every match of an anchored POSIX ERE must begin with: the+ * plain printable-ASCII run after a leading '^', minus its last character when+ * a quantifier or escape follows it. Returns its length (written NUL-terminated+ * to out); 0 when the pattern is not anchored, contains '|', or starts with an+ * operator. Case is kept as written. */+int cbm_regex_anchored_prefix(const char *pattern, char *out, int out_sz);+/* Prepend (?i) to a regex pattern if not already present.* Returns a static buffer — do NOT free. */const char *cbm_ensure_case_insensitive(const char *pattern);diff --git a/tests/test_store_arch.c b/tests/test_store_arch.cindex 4a6d7eb66..8ed3f4636 100644--- a/tests/test_store_arch.c+++ b/tests/test_store_arch.c@@ -298,6 +298,45 @@ TEST(arch_path_scoping) {PASS();}+/* packages: count DESC, tied counts in name (BINARY) order. The aggregation+ * runs off the label index now; a sorted GROUP BY follows the ORDER BY+ * direction, which reversed the ties until the name tie-break was explicit. */+TEST(arch_packages_tied_counts_in_name_order) {+ cbm_store_t *s = cbm_store_open_memory();+ ASSERT_NOT_NULL(s);+ ASSERT_EQ(cbm_store_upsert_project(s, "test", "/tmp/test"), CBM_STORE_OK);+ static const char *const pkg_names[] = {"gamma", "alpha", "Zeta", "beta",+ "Alpha", "gamma", "beta"};+ enum { PKG_NODES = 7, PKG_GROUPS = 5 };+ for (int i = 0; i < PKG_NODES; i++) {+ char qn[64];+ snprintf(qn, sizeof(qn), "test.pkg%d.%s", i, pkg_names[i]);+ cbm_node_t n = {.project = "test",+ .label = "Package",+ .name = pkg_names[i],+ .qualified_name = qn,+ .file_path = "pkg/manifest.toml"};+ ASSERT_TRUE(cbm_store_upsert_node(s, &n) > 0);+ }+ static const char *const want_names[] = {"beta", "gamma", "Alpha", "Zeta", "alpha"};+ static const int want_counts[] = {2, 2, 1, 1, 1};+ const char *aspects[] = {"packages"};+ const char *paths[] = {NULL, "pkg"}; /* unscoped and path-scoped SQL */+ for (int p = 0; p < 2; p++) {+ cbm_architecture_info_t info;+ ASSERT_EQ(cbm_store_get_architecture(s, "test", paths[p], aspects, 1, &info),+ CBM_STORE_OK);+ ASSERT_EQ(info.package_count, PKG_GROUPS);+ for (int i = 0; i < PKG_GROUPS; i++) {+ ASSERT_STR_EQ(info.packages[i].name, want_names[i]);+ ASSERT_EQ(info.packages[i].node_count, want_counts[i]);+ }+ cbm_store_architecture_free(&info);+ }+ cbm_store_close(s);+ PASS();+}+TEST(arch_empty_project) {cbm_store_t *s = cbm_store_open_memory();ASSERT_NOT_NULL(s);@@ -1859,6 +1898,7 @@ SUITE(store_arch) {RUN_TEST(arch_hotspots_exclude_tests);RUN_TEST(arch_specific_aspects);RUN_TEST(arch_path_scoping);+ RUN_TEST(arch_packages_tied_counts_in_name_order);RUN_TEST(arch_empty_project);RUN_TEST(arch_languages);RUN_TEST(arch_routes);diff --git a/tests/test_store_search.c b/tests/test_store_search.cindex 4c1063bcc..cc0fbf1af 100644--- a/tests/test_store_search.c+++ b/tests/test_store_search.c@@ -621,6 +621,56 @@ TEST(store_schema_info) {PASS();}+/* Label and edge-type counts: count DESC, tied counts in BINARY name order —+ * the order the GROUP BY scan produced and the distinct-value walk keeps.+ * Another project's rows must not be counted. */+TEST(store_schema_counts_ties_in_name_order) {+ cbm_store_t *s = cbm_store_open_memory();+ ASSERT_NOT_NULL(s);+ cbm_store_upsert_project(s, "test", "/tmp/test");+ cbm_store_upsert_project(s, "other", "/tmp/other");+ static const char *const labels[] = {"gamma", "Delta", "alpha", "Zeta", "Beta",+ "Delta", "Zeta", "Alpha", "gamma", "Delta"};+ enum { NODE_COUNT = 10, LABEL_GROUPS = 6, TYPE_GROUPS = 4, EDGE_COUNT = 8 };+ int64_t ids[NODE_COUNT];+ for (int i = 0; i < NODE_COUNT; i++) {+ char qn[32];+ snprintf(qn, sizeof(qn), "test.n%d", i);+ cbm_node_t n = {.project = "test", .label = labels[i], .name = qn, .qualified_name = qn};+ ids[i] = cbm_store_upsert_node(s, &n);+ ASSERT_TRUE(ids[i] > 0);+ snprintf(qn, sizeof(qn), "other.n%d", i);+ cbm_node_t o = {.project = "other", .label = "Alpha", .name = qn, .qualified_name = qn};+ ASSERT_TRUE(cbm_store_upsert_node(s, &o) > 0);+ }+ static const char *const types[] = {"USAGE", "DEFINES", "CALLS", "IMPORTS",+ "CALLS", "DEFINES", "USAGE", "DEFINES"};+ for (int i = 0; i < EDGE_COUNT; i++) {+ cbm_edge_t e = {+ .project = "test", .source_id = ids[i], .target_id = ids[i + 1], .type = types[i]};+ ASSERT_TRUE(cbm_store_insert_edge(s, &e) > 0);+ }+ cbm_schema_info_t schema = {0};+ ASSERT_EQ(cbm_store_get_schema_counts(s, "test", &schema), CBM_STORE_OK);+ static const char *const want_labels[] = {"Delta", "Zeta", "gamma", "Alpha", "Beta", "alpha"};+ static const int want_label_counts[] = {3, 2, 2, 1, 1, 1};+ ASSERT_EQ(schema.node_label_count, LABEL_GROUPS);+ for (int i = 0; i < LABEL_GROUPS; i++) {+ ASSERT_STR_EQ(schema.node_labels[i].label, want_labels[i]);+ ASSERT_EQ(schema.node_labels[i].count, want_label_counts[i]);+ }+ static const char *const want_types[] = {"DEFINES", "CALLS", "USAGE", "IMPORTS"};+ static const int want_type_counts[] = {3, 2, 2, 1};+ ASSERT_EQ(schema.edge_type_count, TYPE_GROUPS);+ for (int i = 0; i < TYPE_GROUPS; i++) {+ ASSERT_STR_EQ(schema.edge_types[i].type, want_types[i]);+ ASSERT_EQ(schema.edge_types[i].count, want_type_counts[i]);+ }+ cbm_store_schema_free(&schema);+ cbm_store_close(s);+ PASS();+}+/* ── Search with exclude_labels ─────────────────────────────────── */TEST(store_search_exclude_labels) {@@ -859,6 +909,173 @@ TEST(store_search_case_insensitive) {PASS();}+/* ── Anchored name patterns: the idx_nodes_name range path ─────── */++TEST(store_regex_anchored_prefix) {+ char out[64];+ ASSERT_EQ(cbm_regex_anchored_prefix("^schedule$", out, sizeof(out)), 8);+ ASSERT_STR_EQ(out, "schedule");+ ASSERT_EQ(cbm_regex_anchored_prefix("^kmalloc", out, sizeof(out)), 7);+ ASSERT_STR_EQ(out, "kmalloc");+ ASSERT_EQ(cbm_regex_anchored_prefix("^get_", out, sizeof(out)), 4);+ ASSERT_STR_EQ(out, "get_");+ ASSERT_EQ(cbm_regex_anchored_prefix("^o'neil", out, sizeof(out)), 6);+ ASSERT_STR_EQ(out, "o'neil");+ /* The run stops at the first operator; the prefix before it holds. */+ ASSERT_EQ(cbm_regex_anchored_prefix("^foo.bar", out, sizeof(out)), 3);+ ASSERT_STR_EQ(out, "foo");+ ASSERT_EQ(cbm_regex_anchored_prefix("^foo[0-9]", out, sizeof(out)), 3);+ ASSERT_EQ(cbm_regex_anchored_prefix("^foo(bar)?", out, sizeof(out)), 3);+ ASSERT_EQ(cbm_regex_anchored_prefix("^foo$", out, sizeof(out)), 3);+ /* A quantifier or escape after the run drops its last character. */+ ASSERT_EQ(cbm_regex_anchored_prefix("^abc*", out, sizeof(out)), 2);+ ASSERT_STR_EQ(out, "ab");+ ASSERT_EQ(cbm_regex_anchored_prefix("^abc?", out, sizeof(out)), 2);+ ASSERT_EQ(cbm_regex_anchored_prefix("^abc+?", out, sizeof(out)), 2);+ ASSERT_EQ(cbm_regex_anchored_prefix("^abc{0,1}", out, sizeof(out)), 2);+ ASSERT_EQ(cbm_regex_anchored_prefix("^abc\\.d", out, sizeof(out)), 2);+ ASSERT_EQ(cbm_regex_anchored_prefix("^a*", out, sizeof(out)), 0);+ /* No provable prefix: unanchored, alternation, leading operator,+ * non-ASCII. */+ ASSERT_EQ(cbm_regex_anchored_prefix("schedule", out, sizeof(out)), 0);+ ASSERT_EQ(cbm_regex_anchored_prefix(".*schedule", out, sizeof(out)), 0);+ ASSERT_EQ(cbm_regex_anchored_prefix("^foo|bar", out, sizeof(out)), 0);+ ASSERT_EQ(cbm_regex_anchored_prefix("^(foo|bar)x", out, sizeof(out)), 0);+ ASSERT_EQ(cbm_regex_anchored_prefix("^(foo)", out, sizeof(out)), 0);+ ASSERT_EQ(cbm_regex_anchored_prefix("^[Ff]oo", out, sizeof(out)), 0);+ ASSERT_EQ(cbm_regex_anchored_prefix("^.foo", out, sizeof(out)), 0);+ ASSERT_EQ(cbm_regex_anchored_prefix("^\\x", out, sizeof(out)), 0);+ ASSERT_EQ(cbm_regex_anchored_prefix("^\xc3\xbc"+ "ber",+ out, sizeof(out)),+ 0);+ ASSERT_EQ(cbm_regex_anchored_prefix("^ab\xc3\xbc", out, sizeof(out)), 2);+ ASSERT_EQ(cbm_regex_anchored_prefix("(?i)^foo", out, sizeof(out)), 0);+ ASSERT_EQ(cbm_regex_anchored_prefix(NULL, out, sizeof(out)), 0);+ /* Bounded by the buffer; a quantifier right after the cut still drops. */+ ASSERT_EQ(cbm_regex_anchored_prefix("^abcdef", out, 4), 3);+ ASSERT_STR_EQ(out, "abc");+ ASSERT_EQ(cbm_regex_anchored_prefix("^abc*", out, 4), 2);+ PASS();+}++/* Statements a search ran with the name-range predicate (SQLITE_TRACE_STMT). */+static int anchored_trace_cb(unsigned type, void *ctx, void *stmt, void *sql) {+ (void)stmt;+ if (type == SQLITE_TRACE_STMT && sql && strstr((const char *)sql, "n.name >= ?")) {+ (*(int *)ctx)++;+ }+ return 0;+}++/* "name#label;" per row plus the total, for comparing two searches. */+static void anchored_search_rows(cbm_store_t *s, const cbm_search_params_t *p, int *rc,+ char *buf, size_t buf_sz) {+ cbm_search_output_t out = {0};+ *rc = cbm_store_search(s, p, &out);+ int len = snprintf(buf, buf_sz, "total=%d:", out.total);+ for (int i = 0; i < out.count && len > 0 && (size_t)len < buf_sz; i++) {+ len += snprintf(buf + len, buf_sz - (size_t)len, "%s#%s#%lld;", out.results[i].node.name,+ out.results[i].node.label, (long long)out.results[i].node.id);+ }+ cbm_store_search_free(&out);+}++/* An anchored literal pattern must return exactly what the same regex returns+ * without the range path. Wrapping it in a group, "(^schedule$)", keeps the+ * regex semantics but has no provable prefix, so it runs the plain scan. The+ * names cover every letter case of the prefix, prefix-vs-substring, and the+ * byte order the UNION ALL arms are merged in. */+TEST(store_search_anchored_name_matches_plain_scan) {+ cbm_store_t *s = cbm_store_open_memory();+ ASSERT_NOT_NULL(s);+ cbm_store_upsert_project(s, "p", "/tmp/p");+ static const char *const names[] = {+ "schedule", "Schedule", "SCHEDULE", "sCHEDULE", "scheduler", "schedule_work",+ "reschedule", "sched", "Sched_x", "get_name", "Get_Name", "getname",+ "o'neil", "ScHeDuLe", "schedule", "zabc"};+ enum { NAME_COUNT = 16 };+ for (int i = 0; i < NAME_COUNT; i++) {+ char qn[64];+ snprintf(qn, sizeof(qn), "p.m%d.%s", i, names[i]);+ cbm_node_t n = {.project = "p",+ .label = (i % 3 == 1) ? "Class" : "Function",+ .name = names[i],+ .qualified_name = qn,+ .file_path = "m.c"};+ ASSERT_TRUE(cbm_store_upsert_node(s, &n) > 0);+ }+ int ranged = 0;+ sqlite3_trace_v2(cbm_store_get_db(s), SQLITE_TRACE_STMT, anchored_trace_cb, &ranged);++ struct {+ const char *pattern;+ const char *label;+ bool case_sensitive;+ int limit;+ int offset;+ int want_total;+ } cases[] = {+ {"^schedule$", NULL, false, 0, 0, 6}, {"^sched", NULL, false, 0, 0, 10},+ {"^sched", "Function", false, 0, 0, 6}, {"^SCHED", NULL, true, 0, 0, 1},+ {"^Sched", NULL, true, 0, 0, 2}, {"^sche+dule$", NULL, false, 0, 0, 6},+ {"^s.hedule$", NULL, false, 0, 0, 6}, {"^get_", NULL, false, 0, 0, 2},+ {"^o'n", NULL, false, 0, 0, 1}, {"^zzz", NULL, false, 0, 0, 0},+ {"^sched", NULL, false, 3, 2, 10}, {"^sched", NULL, false, 4, 8, 10},+ };+ char fast[4096];+ char plain[4096];+ char twin[64];+ for (size_t c = 0; c < sizeof(cases) / sizeof(cases[0]); c++) {+ cbm_search_params_t p = {.project = "p",+ .label = cases[c].label,+ .name_pattern = cases[c].pattern,+ .case_sensitive = cases[c].case_sensitive,+ .limit = cases[c].limit,+ .offset = cases[c].offset,+ .min_degree = -1,+ .max_degree = -1};+ int rc_fast = 0;+ int rc_plain = 0;+ int before = ranged;+ anchored_search_rows(s, &p, &rc_fast, fast, sizeof(fast));+ ASSERT_EQ(ranged - before, 2); /* count + page both took the range path */+ snprintf(twin, sizeof(twin), "(%s)", cases[c].pattern);+ p.name_pattern = twin;+ before = ranged;+ anchored_search_rows(s, &p, &rc_plain, plain, sizeof(plain));+ ASSERT_EQ(ranged - before, 0);+ ASSERT_EQ(rc_fast, CBM_STORE_OK);+ ASSERT_EQ(rc_plain, CBM_STORE_OK);+ ASSERT_STR_EQ(fast, plain);+ char want_total[32];+ snprintf(want_total, sizeof(want_total), "total=%d:", cases[c].want_total);+ ASSERT_EQ(strncmp(fast, want_total, strlen(want_total)), 0);+ }+ sqlite3_trace_v2(cbm_store_get_db(s), 0, NULL, NULL);+ cbm_store_close(s);+ PASS();+}++/* A regex the engine rejects fails the plain query as soon as one row reaches+ * it ("zabc" passes the LIKE '%abc%' hint). The range path would never reach+ * the regex (no name starts with "abc") and answer an empty page instead, so a+ * pattern that does not compile keeps the plain query and its error. */+TEST(store_search_anchored_invalid_regex_keeps_error) {+ cbm_store_t *s = cbm_store_open_memory();+ ASSERT_NOT_NULL(s);+ cbm_store_upsert_project(s, "p", "/tmp/p");+ cbm_node_t n = {.project = "p", .label = "Function", .name = "zabc", .qualified_name = "p.zabc"};+ ASSERT_TRUE(cbm_store_upsert_node(s, &n) > 0);+ cbm_search_params_t p = {+ .project = "p", .name_pattern = "^abc(", .min_degree = -1, .max_degree = -1};+ cbm_search_output_t out = {0};+ ASSERT_EQ(cbm_store_search(s, &p, &out), CBM_STORE_ERR);+ cbm_store_search_free(&out);+ cbm_store_close(s);+ PASS();+}+/* ── Impact: HopToRisk ─────────────────────────────────────────── */TEST(store_hop_to_risk) {@@ -1873,6 +2090,9 @@ SUITE(store_search) {RUN_TEST(store_search_all);RUN_TEST(store_search_exclude_labels);RUN_TEST(store_search_case_insensitive);+ RUN_TEST(store_regex_anchored_prefix);+ RUN_TEST(store_search_anchored_name_matches_plain_scan);+ RUN_TEST(store_search_anchored_invalid_regex_keeps_error);RUN_TEST(store_bfs_outbound);RUN_TEST(store_bfs_inbound);RUN_TEST(store_bfs_cross_service);@@ -1881,6 +2101,7 @@ SUITE(store_search) {RUN_TEST(store_transaction_rollback);RUN_TEST(store_bulk_write_mode);RUN_TEST(store_schema_info);+ RUN_TEST(store_schema_counts_ties_in_name_order);RUN_TEST(store_dump_to_file);RUN_TEST(store_hop_to_risk);RUN_TEST(store_build_impact_summary);