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.

feat(mcp): add lossless semantic pagination

Martin Vogel14c229b158ba
diff --git a/README.md b/README.md
index fb7906108..e7964ff01 100644
--- a/README.md
+++ b/README.md
@@ -673,7 +673,7 @@ JSON arguments can also be piped on stdin, for tools that take arguments. A tool
| Tool | Description |
|------|-------------|
-| `search_graph` | Structured search by label, name pattern, file pattern, degree filters. Pagination via limit/offset. |
+| `search_graph` | Structural, BM25, and semantic search. Page structural rows with `offset`/`limit` and ranked semantic rows independently with `semantic_offset`/`semantic_limit`. |
| `trace_path` | BFS traversal — who calls a function and what it calls (alias: `trace_call_path`). Depth 1-5. |
| `detect_changes` | Map git diff to affected symbols + blast radius with risk classification. |
| `query_graph` | Execute Cypher-like graph queries (read-only). |
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index b9e04bb2b..6bb0f5e37 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -481,10 +481,8 @@ static const tool_def_t TOOLS[] = {
"},\"required\":[\"repo_path\"]}"},
{"search_graph", "Search graph",
- "Search: BM25 query, regex name/qn, or vector semantic_query. Regex rows keep "
- "qn/file/lines and in/out over CALLS, USAGE, CALL_REFERENCE, INHERITS, IMPLEMENTS. "
- "Defaults: the smaller lossless direct/grouped tree, limit 50, ~3200 tokens (4x byte cap). "
- "Page with offset; detail=ids is qn-only.",
+ "Regex rows keep qn/file/lines and in/out over CALLS/USAGE/CALL_REFERENCE/INHERITS/"
+ "IMPLEMENTS. Pages: offset/limit structural; semantic_offset/semantic_limit semantic.",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},"
"\"query\":{\"type\":\"string\"},"
"\"label\":{\"type\":\"string\"},\"name_pattern\":{\"type\":\"string\"},\"qn_pattern\":{"
@@ -492,7 +490,12 @@ static const tool_def_t TOOLS[] = {
"\"relationship\":{\"type\":\"string\"},\"min_degree\":{\"type\":\"integer\"},"
"\"max_degree\":{\"type\":\"integer\"},\"exclude_entry_points\":{\"type\":\"boolean\"},"
"\"include_connected\":{\"type\":\"boolean\"},\"semantic_query\":{"
- "\"type\":\"array\",\"items\":{\"type\":\"string\"}},\"limit\":{\"type\":"
+ "\"type\":\"array\",\"items\":{\"type\":\"string\"}},"
+ "\"semantic_limit\":{\"type\":\"integer\",\"default\":50,\"minimum\":0,"
+ "\"maximum\":500},"
+ "\"semantic_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0,"
+ "\"maximum\":99998},"
+ "\"limit\":{\"type\":"
"\"integer\",\"default\":50,\"minimum\":1,\"maximum\":500},"
"\"offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0},"
"\"max_output_tokens\":{\"type\":\"integer\",\"default\":3200,\"minimum\":128,"
@@ -4255,8 +4258,8 @@ static void emit_semantic_results(yyjson_mut_doc *doc, yyjson_mut_val *root,
* Returns true if semantic_query was provided as a non-array (type error —
* caller should surface to the user). */
static bool run_semantic_query_core(const char *args, cbm_store_t *store, const char *project,
- int limit, cbm_vector_result_t **out_vresults, int *out_vcount,
- bool *out_present) {
+ int materialize_limit, cbm_vector_result_t **out_vresults,
+ int *out_vcount, bool *out_present) {
enum { MAX_KW_SEARCH = 32 };
*out_vresults = NULL;
*out_vcount = 0;
@@ -4277,9 +4280,8 @@ static bool run_semantic_query_core(const char *args, cbm_store_t *store, const
int ki = extract_semantic_keywords(sq_val, keywords, MAX_KW_SEARCH);
cbm_vector_result_t *vresults = NULL;
int vcount = 0;
- int sem_limit = limit > 0 ? limit : CBM_SZ_16;
- if (cbm_store_vector_search(store, project, keywords, ki, sem_limit, &vresults, &vcount) ==
- CBM_STORE_OK &&
+ if (cbm_store_vector_search(store, project, keywords, ki, materialize_limit, &vresults,
+ &vcount) == CBM_STORE_OK &&
vcount > 0) {
*out_vresults = vresults;
*out_vcount = vcount;
@@ -4418,13 +4420,23 @@ typedef struct {
bool floor_exceeded;
} sg_render_plan_t;
+typedef struct {
+ const cbm_vector_result_t *results;
+ int total;
+ int offset;
+ int limit;
+ bool total_exact;
+ bool present;
+} sg_semantic_page_t;
+
static bool sg_page_has_more(int total, int offset, int returned) {
- return total > offset + returned;
+ return (long long)total > (long long)offset + returned;
}
static void sg_emit_paging_tree(cbm_sb_t *sb, int total, int offset, const sg_render_plan_t *plan,
int requested_fields, bool connected_requested,
- size_t max_output_bytes, bool continuation_supported) {
+ size_t max_output_bytes, bool continuation_supported,
+ bool continuation_requires_positive_limit) {
bool has_more = continuation_supported && sg_page_has_more(total, offset, plan->returned);
cbm_tree_scalar_int(sb, "total", total);
cbm_tree_scalar_int(sb, "returned", plan->returned);
@@ -4432,7 +4444,11 @@ static void sg_emit_paging_tree(cbm_sb_t *sb, int total, int offset, const sg_re
if (has_more && plan->returned > 0) {
cbm_tree_scalar_int(sb, "next_offset", offset + plan->returned);
} else if (has_more) {
- cbm_tree_scalar_bool(sb, "continuation_requires_higher_budget", true);
+ cbm_tree_scalar_bool(sb,
+ continuation_requires_positive_limit
+ ? "continuation_requires_positive_limit"
+ : "continuation_requires_higher_budget",
+ true);
}
bool truncated = has_more || plan->budget_hit;
cbm_tree_scalar_bool(sb, "truncated", truncated);
@@ -4460,7 +4476,8 @@ static void sg_emit_paging_tree(cbm_sb_t *sb, int total, int offset, const sg_re
static void sg_emit_paging_json(yyjson_mut_doc *doc, yyjson_mut_val *root, int total, int offset,
const sg_render_plan_t *plan, int requested_fields,
bool connected_requested, size_t max_output_bytes,
- bool continuation_supported) {
+ bool continuation_supported,
+ bool continuation_requires_positive_limit) {
bool has_more = continuation_supported && sg_page_has_more(total, offset, plan->returned);
yyjson_mut_obj_add_int(doc, root, "total", total);
yyjson_mut_obj_add_int(doc, root, "returned", plan->returned);
@@ -4469,7 +4486,11 @@ static void sg_emit_paging_json(yyjson_mut_doc *doc, yyjson_mut_val *root, int t
if (has_more && plan->returned > 0) {
yyjson_mut_obj_add_int(doc, root, "next_offset", offset + plan->returned);
} else if (has_more) {
- yyjson_mut_obj_add_bool(doc, root, "continuation_requires_higher_budget", true);
+ yyjson_mut_obj_add_bool(doc, root,
+ continuation_requires_positive_limit
+ ? "continuation_requires_positive_limit"
+ : "continuation_requires_higher_budget",
+ true);
}
bool truncated = has_more || plan->budget_hit;
yyjson_mut_obj_add_bool(doc, root, "truncated", truncated);
@@ -4495,6 +4516,46 @@ static void sg_emit_paging_json(yyjson_mut_doc *doc, yyjson_mut_val *root, int t
}
}
+static bool sg_semantic_has_more(const sg_semantic_page_t *semantic, int returned) {
+ return semantic && sg_page_has_more(semantic->total, semantic->offset, returned);
+}
+
+static void sg_emit_semantic_paging_tree(cbm_sb_t *sb, const sg_semantic_page_t *semantic,
+ int returned) {
+ bool has_more = sg_semantic_has_more(semantic, returned);
+ cbm_tree_scalar_int(sb, "semantic_total", semantic->total);
+ cbm_tree_scalar_str(sb, "semantic_total_relation", semantic->total_exact ? "eq" : "gte");
+ cbm_tree_scalar_int(sb, "semantic_returned", returned);
+ cbm_tree_scalar_bool(sb, "semantic_has_more", has_more);
+ if (has_more && returned > 0) {
+ cbm_tree_scalar_int(sb, "semantic_next_offset", semantic->offset + returned);
+ } else if (has_more) {
+ cbm_tree_scalar_bool(sb,
+ semantic->limit == 0 ? "semantic_continuation_requires_positive_limit"
+ : "semantic_continuation_requires_higher_budget",
+ true);
+ }
+}
+
+static void sg_emit_semantic_paging_json(yyjson_mut_doc *doc, yyjson_mut_val *root,
+ const sg_semantic_page_t *semantic, int returned) {
+ bool has_more = sg_semantic_has_more(semantic, returned);
+ yyjson_mut_obj_add_int(doc, root, "semantic_total", semantic->total);
+ yyjson_mut_obj_add_str(doc, root, "semantic_total_relation",
+ semantic->total_exact ? "eq" : "gte");
+ yyjson_mut_obj_add_int(doc, root, "semantic_returned", returned);
+ yyjson_mut_obj_add_bool(doc, root, "semantic_has_more", has_more);
+ if (has_more && returned > 0) {
+ yyjson_mut_obj_add_int(doc, root, "semantic_next_offset", semantic->offset + returned);
+ } else if (has_more) {
+ yyjson_mut_obj_add_bool(doc, root,
+ semantic->limit == 0
+ ? "semantic_continuation_requires_positive_limit"
+ : "semantic_continuation_requires_higher_budget",
+ true);
+ }
+}
+
static void emit_search_results_ids_tree(cbm_sb_t *sb, const cbm_search_output_t *out,
int returned) {
static const char *const id_cols[] = {"qn"};
@@ -4775,12 +4836,12 @@ static void emit_semantic_results_toon(cbm_sb_t *sb, const cbm_vector_result_t *
static char *sg_render_payload(bool json_format, const cbm_search_output_t *out, int offset,
const char *const *fields, int requested_fields, cbm_store_t *store,
const char *relationship, bool connected_requested, bool detail_ids,
- const cbm_vector_result_t *vresults, int semantic_total,
- bool semantic_only, const char *diagnostic_hint,
- const sg_render_plan_t *plan, size_t max_output_bytes) {
+ const sg_semantic_page_t *semantic, bool semantic_only,
+ const char *diagnostic_hint, const sg_render_plan_t *plan,
+ size_t max_output_bytes) {
sg_render_plan_t meta_plan = *plan;
- int page_total = semantic_only ? semantic_total : out->total;
- int page_offset = semantic_only ? 0 : offset;
+ int page_total = semantic_only ? semantic->total : out->total;
+ int page_offset = semantic_only ? semantic->offset : offset;
if (semantic_only) {
meta_plan.returned = plan->semantic_returned;
}
@@ -4796,16 +4857,16 @@ static char *sg_render_payload(bool json_format, const cbm_search_output_t *out,
relationship, plan->connected_returned, plan->returned);
}
}
- if (semantic_total > 0 || semantic_only) {
- cbm_tree_scalar_int(&sb, "semantic_total", semantic_total);
- cbm_tree_scalar_int(&sb, "semantic_returned", plan->semantic_returned);
- emit_semantic_results_toon(&sb, vresults, plan->semantic_returned);
+ if (semantic->present) {
+ sg_emit_semantic_paging_tree(&sb, semantic, plan->semantic_returned);
+ emit_semantic_results_toon(&sb, semantic->results, plan->semantic_returned);
}
if (plan->core_hint_returned && diagnostic_hint) {
cbm_tree_scalar_str(&sb, "hint", diagnostic_hint);
}
sg_emit_paging_tree(&sb, page_total, page_offset, &meta_plan, requested_fields,
- connected_requested, max_output_bytes, !semantic_only);
+ connected_requested, max_output_bytes, true,
+ semantic_only && semantic->limit == 0);
return cbm_sb_finish(&sb);
}
@@ -4820,23 +4881,24 @@ static char *sg_render_payload(bool json_format, const cbm_search_output_t *out,
relationship, plan->connected_returned, plan->returned);
}
}
- if (semantic_total > 0 || semantic_only) {
- yyjson_mut_obj_add_int(doc, root, "semantic_total", semantic_total);
- yyjson_mut_obj_add_int(doc, root, "semantic_returned", plan->semantic_returned);
- emit_semantic_results(doc, root, vresults, plan->semantic_returned);
+ if (semantic->present) {
+ sg_emit_semantic_paging_json(doc, root, semantic, plan->semantic_returned);
+ emit_semantic_results(doc, root, semantic->results, plan->semantic_returned);
}
if (plan->core_hint_returned && diagnostic_hint) {
yyjson_mut_obj_add_strcpy(doc, root, "hint", diagnostic_hint);
}
sg_emit_paging_json(doc, root, page_total, page_offset, &meta_plan, requested_fields,
- connected_requested, max_output_bytes, !semantic_only);
+ connected_requested, max_output_bytes, true,
+ semantic_only && semantic->limit == 0);
char *json = yy_doc_to_str(doc);
yyjson_mut_doc_free(doc);
return json;
}
-static char *sg_budget_floor(bool json_format, int total, int offset, int semantic_total,
- size_t max_output_bytes, bool semantic_only) {
+static char *sg_budget_floor(bool json_format, int total, int offset,
+ const sg_semantic_page_t *semantic, size_t max_output_bytes,
+ bool semantic_only) {
sg_render_plan_t floor = {
.returned = 0,
.fields_returned = 0,
@@ -4846,20 +4908,26 @@ static char *sg_budget_floor(bool json_format, int total, int offset, int semant
.budget_hit = true,
.floor_exceeded = true,
};
- int page_total = total > 0 ? total : semantic_total;
- int page_offset = total > 0 ? offset : 0;
+ int page_total = semantic_only ? semantic->total : total;
+ int page_offset = semantic_only ? semantic->offset : offset;
if (!json_format) {
cbm_sb_t sb;
cbm_sb_init(&sb);
- sg_emit_paging_tree(&sb, page_total, page_offset, &floor, 0, false, max_output_bytes,
- !semantic_only);
+ if (semantic->present) {
+ sg_emit_semantic_paging_tree(&sb, semantic, 0);
+ }
+ sg_emit_paging_tree(&sb, page_total, page_offset, &floor, 0, false, max_output_bytes, true,
+ semantic_only && semantic->limit == 0);
return cbm_sb_finish(&sb);
}
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, root);
+ if (semantic->present) {
+ sg_emit_semantic_paging_json(doc, root, semantic, 0);
+ }
sg_emit_paging_json(doc, root, page_total, page_offset, &floor, 0, false, max_output_bytes,
- !semantic_only);
+ true, semantic_only && semantic->limit == 0);
char *json = yy_doc_to_str(doc);
yyjson_mut_doc_free(doc);
return json;
@@ -4898,6 +4966,22 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {
if (offset < 0) {
offset = 0;
}
+ int semantic_limit = cbm_mcp_get_int_arg(args, "semantic_limit", CBM_DEFAULT_SEARCH_LIMIT);
+ if (semantic_limit < 0) {
+ semantic_limit = 0;
+ } else if (semantic_limit > 500) {
+ semantic_limit = 500;
+ }
+ int semantic_offset = cbm_mcp_get_int_arg(args, "semantic_offset", 0);
+ if (semantic_offset < 0) {
+ semantic_offset = 0;
+ } else if (semantic_offset > MCP_QUERY_MAX_VISIBLE_ROWS) {
+ semantic_offset = MCP_QUERY_MAX_VISIBLE_ROWS;
+ }
+ /* One ranked hit beyond the requested semantic page makes has_more
+ * deterministic. Keeping the prefix through that lookahead also lets a
+ * budget-trimmed page resume at offset + rows actually emitted. */
+ int semantic_materialize_limit = semantic_offset + semantic_limit + 1;
int max_output_tokens = cbm_mcp_get_int_arg(args, "max_output_tokens", 3200);
if (max_output_tokens < 128) {
max_output_tokens = 128;
@@ -4972,8 +5056,8 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {
cbm_vector_result_t *vresults = NULL;
int vcount = 0;
bool sq_present = false;
- bool sq_type_error =
- run_semantic_query_core(args, store, project, limit, &vresults, &vcount, &sq_present);
+ bool sq_type_error = run_semantic_query_core(args, store, project, semantic_materialize_limit,
+ &vresults, &vcount, &sq_present);
if (sq_type_error) {
if (fields_owner) {
yyjson_doc_free(fields_owner);
@@ -4992,6 +5076,18 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {
true);
}
+ int semantic_available = vcount > semantic_offset ? vcount - semantic_offset : 0;
+ int semantic_page_count =
+ semantic_available < semantic_limit ? semantic_available : semantic_limit;
+ sg_semantic_page_t semantic = {
+ .results = semantic_page_count > 0 ? vresults + semantic_offset : NULL,
+ .total = vcount,
+ .offset = semantic_offset,
+ .limit = semantic_limit,
+ .total_exact = vcount < semantic_materialize_limit,
+ .present = sq_present,
+ };
+
/* Semantic-only calls must not prepend an unrelated, unfiltered symbol
* page. Combined calls retain both independently ranked result sets. */
bool has_filters = label || name_pattern || qn_pattern || file_pattern || relationship ||
@@ -5022,7 +5118,7 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {
sg_render_plan_t plan = {
.returned = out.count,
.fields_returned = requested_fields,
- .semantic_returned = vcount,
+ .semantic_returned = semantic_page_count,
.connected_returned = !detail_ids && include_connected,
.core_hint_returned = diagnostic_hint != NULL,
.budget_hit = false,
@@ -5033,8 +5129,8 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {
for (;;) {
payload =
sg_render_payload(json_format, &out, offset, fields, requested_fields, store,
- relationship, !detail_ids && include_connected, detail_ids, vresults,
- vcount, semantic_only, diagnostic_hint, &plan, max_output_bytes);
+ relationship, !detail_ids && include_connected, detail_ids, &semantic,
+ semantic_only, diagnostic_hint, &plan, max_output_bytes);
if (!payload || strlen(payload) <= max_output_bytes) {
break;
}
@@ -5060,12 +5156,12 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {
}
}
- bool identity_available = out.count > 0 || vcount > 0;
+ bool identity_available = out.count > 0 || semantic_page_count > 0;
bool identity_returned = plan.returned > 0 || plan.semantic_returned > 0;
if (!payload || strlen(payload) > max_output_bytes ||
(identity_available && plan.budget_hit && !identity_returned)) {
free(payload);
- payload = sg_budget_floor(json_format, out.total, offset, vcount, max_output_bytes,
+ payload = sg_budget_floor(json_format, out.total, offset, &semantic, max_output_bytes,
semantic_only);
}
diff --git a/src/store/store.c b/src/store/store.c
index 7e3663c8d..43014eb1d 100644
--- a/src/store/store.c
+++ b/src/store/store.c
@@ -9876,6 +9876,18 @@ static cbm_vector_result_t *vs_append_result(cbm_vector_result_t *results, int *
return results;
}
+static int vs_ranked_result_cmp(const void *lhs, const void *rhs) {
+ const cbm_vector_result_t *a = lhs;
+ const cbm_vector_result_t *b = rhs;
+ if (a->score > b->score) {
+ return -1;
+ }
+ if (a->score < b->score) {
+ return 1;
+ }
+ return (a->node_id > b->node_id) - (a->node_id < b->node_id);
+}
+
int cbm_store_vector_search(cbm_store_t *s, const char *project, const char **keywords,
int keyword_count, int limit, cbm_vector_result_t **out,
int *out_count) {
@@ -9891,16 +9903,15 @@ int cbm_store_vector_search(cbm_store_t *s, const char *project, const char **ke
return CBM_STORE_OK;
}
- /* Scan all node vectors, compute per-keyword cosine, take min.
- * We use the FIRST keyword as the SQL sort (for top-K pre-filter),
- * then re-score with min across all keywords in the append helper. */
+ /* Use the first keyword for a cheap candidate ordering, then score each
+ * materialized candidate by min-cosine across every keyword. */
const char *sql = "SELECT n.id, n.name, n.qualified_name, n.file_path, n.label,"
" cbm_cosine_i8(v.vector, ?1) as score, v.vector"
" FROM node_vectors v"
" INNER JOIN nodes n ON n.id = v.node_id"
" WHERE v.project = ?2"
" AND n.label IN (" CBM_SQL_CALLABLE_OR_TYPE_LABELS ")"
- " ORDER BY score DESC"
+ " ORDER BY score DESC, n.id ASC"
" LIMIT ?3";
sqlite3_stmt *stmt = NULL;
@@ -9910,59 +9921,74 @@ int cbm_store_vector_search(cbm_store_t *s, const char *project, const char **ke
return CBM_STORE_ERR;
}
- /* Use first keyword for SQL pre-filter, fetch more candidates for re-ranking */
- int fetch_limit = (limit > 0 ? limit : CBM_SZ_16) * ST_COL_5;
+ /* A fixed 5x prefilter is normally ample, but it is not a proof: a later
+ * candidate can have a lower first-keyword score and a much higher
+ * all-keyword min-score. Expand until either the scan is exhausted or the
+ * Kth final score is strictly above the best possible omitted score. This
+ * makes top-K prefixes identical for every requested K, which semantic
+ * offset pagination requires. */
+ int requested_limit = limit > 0 ? limit : CBM_SZ_16;
+ int fetch_limit = requested_limit > INT_MAX / ST_COL_5 ? INT_MAX : requested_limit * ST_COL_5;
sqlite3_bind_blob(stmt, SKIP_ONE, kw_vecs[0], VS_VEC_DIM, SQLITE_STATIC);
sqlite3_bind_text(stmt, ST_COL_2, project, SQLITE_AUTO_LEN, SQLITE_STATIC);
- sqlite3_bind_int(stmt, ST_COL_3, fetch_limit);
-
- {
- char kw_buf[VS_STR_BUF];
- char fl_buf[VS_STR_BUF];
- snprintf(kw_buf, sizeof(kw_buf), "%d", actual_kw);
- snprintf(fl_buf, sizeof(fl_buf), "%d", fetch_limit);
- cbm_log_info("vector_search.exec", "kw_count", kw_buf, "fetch_limit", fl_buf, "project",
- project);
- }
cbm_vector_result_t *results = NULL;
int count = 0;
- int cap = 0;
- int step_rc = 0;
- while ((step_rc = sqlite3_step(stmt)) == SQLITE_ROW) {
- cbm_vector_result_t *grown =
- vs_append_result(results, &count, &cap, stmt, kw_vecs, actual_kw);
- if (!grown) {
+ for (;;) {
+ int cap = 0;
+ int step_rc;
+ double omitted_score_ceiling = 0.0;
+ sqlite3_bind_int(stmt, ST_COL_3, fetch_limit);
+ while ((step_rc = sqlite3_step(stmt)) == SQLITE_ROW) {
+ omitted_score_ceiling = sqlite3_column_double(stmt, ST_COL_5);
+ cbm_vector_result_t *grown =
+ vs_append_result(results, &count, &cap, stmt, kw_vecs, actual_kw);
+ if (!grown) {
+ step_rc = SQLITE_NOMEM;
+ break;
+ }
+ results = grown;
+ }
+ if (step_rc != SQLITE_DONE) {
+ char rc_buf[VS_STR_BUF];
+ snprintf(rc_buf, sizeof(rc_buf), "%d", step_rc);
+ cbm_log_warn("vector_search.step_error", "rc", rc_buf, "msg", sqlite3_errmsg(s->db));
+ cbm_store_free_vector_results(results, count);
+ sqlite3_finalize(stmt);
+ return CBM_STORE_ERR;
+ }
+
+ if (count > 1) {
+ qsort(results, (size_t)count, sizeof(*results), vs_ranked_result_cmp);
+ }
+ bool scan_exhausted = count < fetch_limit;
+ bool top_k_certified = scan_exhausted || count < requested_limit ||
+ results[requested_limit - 1].score > omitted_score_ceiling;
+ if (top_k_certified || fetch_limit == INT_MAX) {
break;
}
- results = grown;
- }
- if (step_rc != SQLITE_DONE) {
- char rc_buf[VS_STR_BUF];
- snprintf(rc_buf, sizeof(rc_buf), "%d", step_rc);
- cbm_log_warn("vector_search.step_error", "rc", rc_buf, "msg", sqlite3_errmsg(s->db));
+ cbm_store_free_vector_results(results, count);
+ results = NULL;
+ count = 0;
+ fetch_limit = fetch_limit > INT_MAX / ST_COL_2 ? INT_MAX : fetch_limit * ST_COL_2;
+ sqlite3_reset(stmt);
}
+
{
+ char kw_buf[VS_STR_BUF];
+ char fl_buf[VS_STR_BUF];
char cnt_buf[VS_STR_BUF];
+ snprintf(kw_buf, sizeof(kw_buf), "%d", actual_kw);
+ snprintf(fl_buf, sizeof(fl_buf), "%d", fetch_limit);
snprintf(cnt_buf, sizeof(cnt_buf), "%d", count);
- cbm_log_info("vector_search.done", "candidates", cnt_buf);
+ cbm_log_info("vector_search.done", "kw_count", kw_buf, "fetch_limit", fl_buf, "candidates",
+ cnt_buf);
}
sqlite3_finalize(stmt);
- /* Re-sort by min-score (SQL sorted by first keyword only) */
- for (int i = 0; i < count - SKIP_ONE; i++) {
- for (int j = i + SKIP_ONE; j < count; j++) {
- if (results[j].score > results[i].score) {
- cbm_vector_result_t tmp = results[i];
- results[i] = results[j];
- results[j] = tmp;
- }
- }
- }
-
/* Trim to requested limit */
- int final_limit = limit > 0 ? limit : CBM_SZ_16;
+ int final_limit = requested_limit;
if (count > final_limit) {
for (int i = final_limit; i < count; i++) {
free(results[i].name);
diff --git a/tests/test_mcp.c b/tests/test_mcp.c
index 907c8cae1..bfb597a3e 100644
--- a/tests/test_mcp.c
+++ b/tests/test_mcp.c
@@ -3662,6 +3662,355 @@ TEST(tool_search_graph_bm25_reports_candidate_saturation) {
PASS();
}
+enum { MCP_TEST_SEMANTIC_VECTOR_DIM = 768 };
+
+static int mcp_test_insert_semantic_vector(cbm_store_t *store, const char *table,
+ const char *project, int64_t node_id, const char *token,
+ unsigned char primary, unsigned char secondary) {
+ unsigned char vector[MCP_TEST_SEMANTIC_VECTOR_DIM] = {0};
+ char hex[MCP_TEST_SEMANTIC_VECTOR_DIM * 2 + 1];
+ static const char digits[] = "0123456789abcdef";
+ vector[0] = primary;
+ vector[1] = secondary;
+ for (int i = 0; i < MCP_TEST_SEMANTIC_VECTOR_DIM; i++) {
+ hex[i * 2] = digits[vector[i] >> 4];
+ hex[i * 2 + 1] = digits[vector[i] & 0x0f];
+ }
+ hex[sizeof(hex) - 1] = '\0';
+
+ char sql[CBM_SZ_4K];
+ if (strcmp(table, "token_vectors") == 0) {
+ snprintf(sql, sizeof(sql),
+ "INSERT INTO token_vectors(project,token,vector,idf) "
+ "VALUES('%s','%s',X'%s',1);",
+ project, token, hex);
+ } else {
+ snprintf(sql, sizeof(sql),
+ "INSERT INTO node_vectors(node_id,project,vector) VALUES(%lld,'%s',X'%s');",
+ (long long)node_id, project, hex);
+ }
+ return cbm_store_exec(store, sql);
+}
+
+static yyjson_doc *mcp_test_semantic_page(cbm_mcp_server_t *srv, const char *args,
+ char **out_response, char **out_inner) {
+ *out_response = cbm_mcp_handle_tool(srv, "search_graph", args);
+ *out_inner = extract_text_content(*out_response);
+ return *out_inner ? yyjson_read(*out_inner, strlen(*out_inner), 0) : NULL;
+}
+
+/* Semantic rows are their own ranked result set. Structural limit/offset must
+ * neither choose their page nor make a budget-trimmed tail unrecoverable. */
+TEST(tool_search_graph_semantic_pagination_is_lossless_and_independent) {
+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
+ ASSERT_NOT_NULL(srv);
+ cbm_store_t *store = cbm_mcp_server_store(srv);
+ ASSERT_NOT_NULL(store);
+ const char *project = "semantic-pagination";
+ const char *token = "semantic-page-token";
+ cbm_mcp_server_set_project(srv, project);
+ ASSERT_EQ(cbm_store_upsert_project(store, project, "/tmp/semantic-pagination"), CBM_STORE_OK);
+ ASSERT_EQ(cbm_store_exec(store,
+ "CREATE TABLE node_vectors(node_id INTEGER PRIMARY KEY,"
+ "project TEXT NOT NULL,vector BLOB NOT NULL);"
+ "CREATE TABLE token_vectors(id INTEGER PRIMARY KEY,"
+ "project TEXT NOT NULL,token TEXT NOT NULL,vector BLOB NOT NULL,"
+ "idf INTEGER NOT NULL);"),
+ CBM_STORE_OK);
+ ASSERT_EQ(mcp_test_insert_semantic_vector(store, "token_vectors", project, 0, token, 127, 0),
+ CBM_STORE_OK);
+
+ char long_qn[900];
+ memset(long_qn, 'q', sizeof(long_qn) - 1);
+ long_qn[sizeof(long_qn) - 1] = '\0';
+ const char *expected[] = {long_qn, "semantic.rank.2", "semantic.rank.3",
+ "semantic.rank.4", "semantic.rank.5", "semantic.rank.6"};
+ for (int i = 0; i < 6; i++) {
+ char name[32];
+ char path[64];
+ snprintf(name, sizeof(name), "semantic_rank_%d", i + 1);
+ snprintf(path, sizeof(path), "src/semantic_rank_%d.c", i + 1);
+ cbm_node_t node = {.project = project,
+ .label = "Function",
+ .name = name,
+ .qualified_name = expected[i],
+ .file_path = path,
+ .start_line = i + 1,
+ .end_line = i + 1};
+ int64_t id = cbm_store_upsert_node(store, &node);
+ ASSERT_GT(id, 0);
+ ASSERT_EQ(mcp_test_insert_semantic_vector(store, "node_vectors", project, id, NULL, 127,
+ (unsigned char)(i * 20)),
+ CBM_STORE_OK);
+ }
+
+ char args[512];
+ char *response = NULL;
+ char *inner = NULL;
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"semantic_query\":[\"%s\"],"
+ "\"semantic_limit\":6,\"limit\":1,\"offset\":99,\"format\":\"json\"}",
+ project, token);
+ yyjson_doc *full_doc = mcp_test_semantic_page(srv, args, &response, &inner);
+ ASSERT_NOT_NULL(full_doc);
+ yyjson_val *full_root = yyjson_doc_get_root(full_doc);
+ yyjson_val *full_semantic = yyjson_obj_get(full_root, "semantic");
+ yyjson_val *full_rows = full_semantic ? yyjson_obj_get(full_semantic, "rows") : NULL;
+ ASSERT_EQ(yyjson_arr_size(full_rows), 6);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(full_root, "semantic_total")), 6);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(full_root, "semantic_total_relation")), "eq");
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(full_root, "semantic_has_more")));
+
+ for (int page = 0; page < 3; page++) {
+ int semantic_offset = page * 2;
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"semantic_query\":[\"%s\"],"
+ "\"semantic_offset\":%d,\"semantic_limit\":2,"
+ "\"limit\":1,\"offset\":99,\"format\":\"json\"}",
+ project, token, semantic_offset);
+ char *page_response = NULL;
+ char *page_inner = NULL;
+ yyjson_doc *page_doc = mcp_test_semantic_page(srv, args, &page_response, &page_inner);
+ ASSERT_NOT_NULL(page_doc);
+ yyjson_val *page_root = yyjson_doc_get_root(page_doc);
+ yyjson_val *page_semantic = yyjson_obj_get(page_root, "semantic");
+ yyjson_val *page_rows = page_semantic ? yyjson_obj_get(page_semantic, "rows") : NULL;
+ ASSERT_EQ(yyjson_arr_size(page_rows), 2);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(page_root, "semantic_returned")), 2);
+ for (int row = 0; row < 2; row++) {
+ const char *actual = yyjson_get_str(yyjson_arr_get(yyjson_arr_get(page_rows, row), 0));
+ const char *from_full =
+ yyjson_get_str(yyjson_arr_get(yyjson_arr_get(full_rows, semantic_offset + row), 0));
+ ASSERT_STR_EQ(actual, from_full);
+ }
+ bool want_more = page < 2;
+ ASSERT_EQ(yyjson_get_bool(yyjson_obj_get(page_root, "semantic_has_more")), want_more);
+ if (want_more) {
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(page_root, "semantic_next_offset")),
+ semantic_offset + 2);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(page_root, "semantic_total_relation")),
+ "gte");
+ } else {
+ ASSERT_NULL(yyjson_obj_get(page_root, "semantic_next_offset"));
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(page_root, "semantic_total_relation")),
+ "eq");
+ }
+ yyjson_doc_free(page_doc);
+ free(page_inner);
+ free(page_response);
+ }
+
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"name_pattern\":\".*\","
+ "\"semantic_query\":[\"%s\"],\"semantic_offset\":1,"
+ "\"semantic_limit\":2,\"limit\":1,\"offset\":4,\"format\":\"json\"}",
+ project, token);
+ char *combined_response = NULL;
+ char *combined_inner = NULL;
+ yyjson_doc *combined_doc =
+ mcp_test_semantic_page(srv, args, &combined_response, &combined_inner);
+ ASSERT_NOT_NULL(combined_doc);
+ yyjson_val *combined_root = yyjson_doc_get_root(combined_doc);
+ yyjson_val *combined_semantic = yyjson_obj_get(combined_root, "semantic");
+ yyjson_val *combined_rows =
+ combined_semantic ? yyjson_obj_get(combined_semantic, "rows") : NULL;
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(combined_root, "returned")), 1);
+ ASSERT_EQ(yyjson_arr_size(combined_rows), 2);
+ for (int row = 0; row < 2; row++) {
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(yyjson_arr_get(combined_rows, row), 0)),
+ yyjson_get_str(yyjson_arr_get(yyjson_arr_get(full_rows, row + 1), 0)));
+ }
+ yyjson_doc_free(combined_doc);
+ free(combined_inner);
+ free(combined_response);
+
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"semantic_query\":[\"%s\"],"
+ "\"semantic_offset\":2,\"semantic_limit\":2,\"limit\":1,\"offset\":99}",
+ project, token);
+ char *tree_response = cbm_mcp_handle_tool(srv, "search_graph", args);
+ char *tree = extract_text_content(tree_response);
+ ASSERT_NOT_NULL(tree);
+ ASSERT_NOT_NULL(strstr(tree, "semantic_total: 5"));
+ ASSERT_NOT_NULL(strstr(tree, "semantic_total_relation: gte"));
+ ASSERT_NOT_NULL(strstr(tree, "semantic_returned: 2"));
+ ASSERT_NOT_NULL(strstr(tree, "semantic_has_more: true"));
+ ASSERT_NOT_NULL(strstr(tree, "semantic_next_offset: 4"));
+ ASSERT_NOT_NULL(strstr(tree, "semantic.rank.3"));
+ ASSERT_NULL(strstr(tree, "semantic.rank.2"));
+ free(tree);
+ free(tree_response);
+
+ /* A byte budget may shorten this page, but continuation advances only by
+ * identities actually emitted. The first roomy retry row must therefore
+ * be the next row from the stable full ranking, with no gap. */
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"semantic_query\":[\"%s\"],"
+ "\"semantic_offset\":1,\"semantic_limit\":5,"
+ "\"max_output_tokens\":128,\"format\":\"json\"}",
+ project, token);
+ char *budget_response = NULL;
+ char *budget_inner = NULL;
+ yyjson_doc *budget_doc = mcp_test_semantic_page(srv, args, &budget_response, &budget_inner);
+ ASSERT_NOT_NULL(budget_doc);
+ yyjson_val *budget_root = yyjson_doc_get_root(budget_doc);
+ int budget_returned = (int)yyjson_get_int(yyjson_obj_get(budget_root, "semantic_returned"));
+ ASSERT_GT(budget_returned, 0);
+ ASSERT_LT(budget_returned, 5);
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(budget_root, "semantic_has_more")));
+ int budget_next = (int)yyjson_get_int(yyjson_obj_get(budget_root, "semantic_next_offset"));
+ ASSERT_EQ(budget_next, 1 + budget_returned);
+ yyjson_doc_free(budget_doc);
+ free(budget_inner);
+ free(budget_response);
+
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"semantic_query\":[\"%s\"],"
+ "\"semantic_offset\":%d,\"semantic_limit\":1,\"format\":\"json\"}",
+ project, token, budget_next);
+ char *resume_response = NULL;
+ char *resume_inner = NULL;
+ yyjson_doc *resume_doc = mcp_test_semantic_page(srv, args, &resume_response, &resume_inner);
+ ASSERT_NOT_NULL(resume_doc);
+ yyjson_val *resume_semantic = yyjson_obj_get(yyjson_doc_get_root(resume_doc), "semantic");
+ yyjson_val *resume_rows = resume_semantic ? yyjson_obj_get(resume_semantic, "rows") : NULL;
+ ASSERT_EQ(yyjson_arr_size(resume_rows), 1);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(yyjson_arr_get(resume_rows, 0), 0)),
+ yyjson_get_str(yyjson_arr_get(yyjson_arr_get(full_rows, budget_next), 0)));
+ yyjson_doc_free(resume_doc);
+ free(resume_inner);
+ free(resume_response);
+
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"semantic_query\":[\"%s\"],"
+ "\"semantic_limit\":0,\"format\":\"json\"}",
+ project, token);
+ char *zero_response = NULL;
+ char *zero_inner = NULL;
+ yyjson_doc *zero_doc = mcp_test_semantic_page(srv, args, &zero_response, &zero_inner);
+ ASSERT_NOT_NULL(zero_doc);
+ yyjson_val *zero_root = yyjson_doc_get_root(zero_doc);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(zero_root, "semantic_returned")), 0);
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(zero_root, "semantic_has_more")));
+ ASSERT_TRUE(yyjson_get_bool(
+ yyjson_obj_get(zero_root, "semantic_continuation_requires_positive_limit")));
+ ASSERT_NULL(yyjson_obj_get(zero_root, "semantic_next_offset"));
+ yyjson_doc_free(zero_doc);
+ free(zero_inner);
+ free(zero_response);
+
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"semantic_query\":[\"%s\"],"
+ "\"semantic_limit\":1,\"max_output_tokens\":128,\"format\":\"json\"}",
+ project, token);
+ char *floor_response = NULL;
+ char *floor_inner = NULL;
+ yyjson_doc *floor_doc = mcp_test_semantic_page(srv, args, &floor_response, &floor_inner);
+ ASSERT_NOT_NULL(floor_doc);
+ ASSERT_TRUE(strlen(floor_inner) <= 512U);
+ yyjson_val *floor_root = yyjson_doc_get_root(floor_doc);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(floor_root, "semantic_returned")), 0);
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(floor_root, "semantic_has_more")));
+ ASSERT_TRUE(yyjson_get_bool(
+ yyjson_obj_get(floor_root, "semantic_continuation_requires_higher_budget")));
+ ASSERT_NULL(yyjson_obj_get(floor_root, "semantic_next_offset"));
+ yyjson_doc_free(floor_doc);
+ free(floor_inner);
+ free(floor_response);
+
+ /* Multi-keyword min-cosine ranking must not depend on how deep a page asks
+ * the first-keyword prefilter to materialize. Fifteen first-keyword-heavy
+ * decoys put the genuinely balanced result just beyond the initial 5x
+ * window; every small page must still equal the corresponding full ranks. */
+ const char *stable_project = "semantic-page-stability";
+ const char *first_token = "semantic-rank-first";
+ const char *second_token = "semantic-rank-second";
+ ASSERT_EQ(cbm_store_upsert_project(store, stable_project, "/tmp/semantic-page-stability"),
+ CBM_STORE_OK);
+ cbm_mcp_server_set_project(srv, stable_project);
+ ASSERT_EQ(mcp_test_insert_semantic_vector(store, "token_vectors", stable_project, 0,
+ first_token, 127, 0),
+ CBM_STORE_OK);
+ ASSERT_EQ(mcp_test_insert_semantic_vector(store, "token_vectors", stable_project, 0,
+ second_token, 0, 127),
+ CBM_STORE_OK);
+ for (int i = 0; i < 16; i++) {
+ char name[40];
+ char qn[64];
+ snprintf(name, sizeof(name), "stable_rank_%02d", i + 1);
+ snprintf(qn, sizeof(qn), "semantic.stable.%02d", i + 1);
+ cbm_node_t node = {.project = stable_project,
+ .label = "Function",
+ .name = name,
+ .qualified_name = qn,
+ .file_path = "src/semantic_stable.c",
+ .start_line = i + 1,
+ .end_line = i + 1};
+ int64_t id = cbm_store_upsert_node(store, &node);
+ ASSERT_GT(id, 0);
+ unsigned char primary = i == 15 ? 90 : 127;
+ unsigned char secondary = i == 15 ? 90 : (unsigned char)(i + 1);
+ ASSERT_EQ(mcp_test_insert_semantic_vector(store, "node_vectors", stable_project, id, NULL,
+ primary, secondary),
+ CBM_STORE_OK);
+ }
+
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"semantic_query\":[\"%s\",\"%s\"],"
+ "\"semantic_limit\":16,\"format\":\"json\"}",
+ stable_project, first_token, second_token);
+ char *stable_full_response = NULL;
+ char *stable_full_inner = NULL;
+ yyjson_doc *stable_full_doc =
+ mcp_test_semantic_page(srv, args, &stable_full_response, &stable_full_inner);
+ ASSERT_NOT_NULL(stable_full_doc);
+ yyjson_val *stable_full_semantic =
+ yyjson_obj_get(yyjson_doc_get_root(stable_full_doc), "semantic");
+ yyjson_val *stable_full_rows =
+ stable_full_semantic ? yyjson_obj_get(stable_full_semantic, "rows") : NULL;
+ ASSERT_EQ(yyjson_arr_size(stable_full_rows), 16);
+ for (int page = 0; page < 2; page++) {
+ int stable_offset = page * 2;
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"semantic_query\":[\"%s\",\"%s\"],"
+ "\"semantic_offset\":%d,\"semantic_limit\":2,\"format\":\"json\"}",
+ stable_project, first_token, second_token, stable_offset);
+ char *stable_page_response = NULL;
+ char *stable_page_inner = NULL;
+ yyjson_doc *stable_page_doc =
+ mcp_test_semantic_page(srv, args, &stable_page_response, &stable_page_inner);
+ ASSERT_NOT_NULL(stable_page_doc);
+ yyjson_val *stable_page_semantic =
+ yyjson_obj_get(yyjson_doc_get_root(stable_page_doc), "semantic");
+ yyjson_val *stable_page_rows =
+ stable_page_semantic ? yyjson_obj_get(stable_page_semantic, "rows") : NULL;
+ ASSERT_EQ(yyjson_arr_size(stable_page_rows), 2);
+ for (int row = 0; row < 2; row++) {
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(yyjson_arr_get(stable_page_rows, row), 0)),
+ yyjson_get_str(yyjson_arr_get(
+ yyjson_arr_get(stable_full_rows, stable_offset + row), 0)));
+ }
+ yyjson_doc_free(stable_page_doc);
+ free(stable_page_inner);
+ free(stable_page_response);
+ }
+ yyjson_doc_free(stable_full_doc);
+ free(stable_full_inner);
+ free(stable_full_response);
+
+ char *tools = cbm_mcp_tools_list();
+ ASSERT_NOT_NULL(tools);
+ ASSERT_NOT_NULL(strstr(tools, "semantic_offset"));
+ ASSERT_NOT_NULL(strstr(tools, "semantic_limit"));
+ free(tools);
+
+ yyjson_doc_free(full_doc);
+ free(inner);
+ free(response);
+ cbm_mcp_server_free(srv);
+ PASS();
+}
+
TEST(tool_search_graph_budget_preserves_long_values_and_continuation) {
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
ASSERT_NOT_NULL(srv);
@@ -18382,6 +18731,7 @@ SUITE(mcp) {
RUN_TEST(tool_output_byte_budgets);
RUN_TEST(tool_search_graph_query_honors_file_pattern_issue552);
RUN_TEST(tool_search_graph_bm25_reports_candidate_saturation);
+ RUN_TEST(tool_search_graph_semantic_pagination_is_lossless_and_independent);
RUN_TEST(tool_search_graph_budget_preserves_long_values_and_continuation);
RUN_TEST(mcp_resource_discovery_methods_return_empty_lists);
RUN_TEST(tool_query_graph_basic);