Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(ask,map): ground path prefixes and list ax_* locators (#2124)

xerj-org89c05a7eda12
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 307e18dd6..105631795 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -44,6 +44,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`--plan` and `--yes` choose what to index; they do not agree to the
deletion.
+- `POST /_ask` (`xerj_plan`) grounds a slash-bearing path in the prompt as a
+ keyword `prefix` on `ax_path` (then `path`, `filepath`, `file`, `ax_file`).
+ A directory gets a trailing slash so `crates/app/src/` does not match
+ `crates/app/src2/`. An index with none of those keyword fields is a 422
+ that names the path, instead of dropping it as an ignored lowercase
+ modifier. `xerj_map` lists the `ax_*` locators stamped on every record,
+ and when the live mapping can be read its `field_count` is the catalog
+ fields union the top-level mapping fields — the same set the plan counts,
+ labeled on both sides. Cardinality of a locator the profiler never sampled
+ stays unmeasured
+ ([#2120](https://github.com/xerj-org/xerj/issues/2120)).
+
- A bare hub question that names a language or a technology
(`xerj "how do I use async let in Swift"`, `xerj "Swift Result type map"`)
routes from the catalogue entry — slug, topics, a language word in the
diff --git a/engine/crates/xerj-api/src/ask_api.rs b/engine/crates/xerj-api/src/ask_api.rs
index b8c8cfb32..cc2e00e21 100644
--- a/engine/crates/xerj-api/src/ask_api.rs
+++ b/engine/crates/xerj-api/src/ask_api.rs
@@ -61,8 +61,13 @@
//! `network` → `net`, `life expectancy` → `lifeExp`, `GDP per capita` →
//! `gdpPercap`, …) resolve field phrases by scored name matching against
//! the index's real fields; equality values resolve against the live value
-//! map built by the batched agg. It is NOT an LLM and not fuzzy retrieval:
-//! anything it cannot ground in the index is refused by name. `confidence`
+//! map built by the batched agg. A slash-bearing token (`crates/app/src`) is
+//! a path constraint: a keyword `prefix` on `ax_path` (then `path`,
+//! `filepath`, `file`, `ax_file`), with a trailing slash when the last
+//! segment is a directory so `src` does not also match `src2`. No such
+//! field is a 422 naming the path — it is not dropped as decoration. It is
+//! NOT an LLM and not fuzzy retrieval: anything it cannot ground in the
+//! index is refused by name. `confidence`
//! reports how much soft matching the plan needed — 0.9 for a fully exact
//! plan, lower per fallback, 0.5 for a bare `match_all`.
//!
@@ -237,10 +242,23 @@ pub async fn ask(State(state): State<AppState>, Json(body): Json<Value>) -> Resp
}
}
}
+ // `count` is every top-level mapping field (the set a filter can name).
+ // `xerj_map`'s `field_count` is that same set: catalog specs union the
+ // live mapping, which is what surfaces `ax_*` locators the profiler
+ // never sampled (#2120). `provenance_fields` names the `ax_*` ones so a
+ // caller can see them without a second request.
+ let mut provenance_fields: Vec<&str> = fields
+ .iter()
+ .filter(|f| f.name.starts_with("ax_"))
+ .map(|f| f.name.as_str())
+ .collect();
+ provenance_fields.sort_unstable();
plan_steps.push(json!({
"step": plan_steps.len() + 1,
"action": "fields",
"count": fields.len(),
+ "counted": "top-level mapping fields",
+ "provenance_fields": provenance_fields,
"source": if spec.is_some() { "catalog+mapping" } else { "mapping" },
}));
if fields.is_empty() {
@@ -799,6 +817,14 @@ fn range_clause_1(field: &str, op: &str, value: Value) -> Value {
Value::Object(outer)
}
+fn prefix_clause(field: &str, value: &str) -> Value {
+ let mut inner = Map::new();
+ inner.insert(field.to_string(), json!(value));
+ let mut outer = Map::new();
+ outer.insert("prefix".to_string(), Value::Object(inner));
+ Value::Object(outer)
+}
+
fn range_clause_2(field: &str, lo: Value, lo_op: &str, hi: Value, hi_op: &str) -> Value {
let mut bound = Map::new();
bound.insert(lo_op.to_string(), lo);
@@ -1526,6 +1552,11 @@ async fn plan_prompt(
numeric_pass(toks, fields, used, ctx)?;
// Pass A: date literals and bare years.
date_pass(toks, fields, time_field_hint, used, ctx)?;
+ // Pass P: a slash-bearing token is a path prefix, not a value. Claim it
+ // before the value pass so `norm_text` (which strips `/`) cannot fold it
+ // into an unrelated keyword, and before leftovers so it is not reported
+ // as a dropped lowercase modifier (#2120).
+ path_pass(toks, fields, used, ctx);
// Pass C: equality from the value map (field+value splits, then values).
let mut probes = 0usize;
let leftovers = value_pass(toks, fields, used, ctx, idx, &mut probes).await;
@@ -2250,6 +2281,110 @@ fn year_context(toks: &[Tok], used: &[bool], i: usize) -> bool {
(i > 0 && check(i - 1)) || (i + 1 < toks.len() && check(i + 1))
}
+/// Keyword fields a path constraint may filter, most-specific first.
+///
+/// `ax_path` is the full root-relative path autoindex stamps on every
+/// record. Code indexes also map `path`, but that value is the file name
+/// (`worktree.rs`), so a directory prefix has to land on `ax_path` when
+/// both exist.
+const PATH_FIELDS: &[&str] = &["ax_path", "path", "filepath", "file", "ax_file"];
+
+/// The keyword field a path prefix filters, or `None` when this index has
+/// none of [`PATH_FIELDS`].
+fn path_field(fields: &[FieldView]) -> Option<usize> {
+ PATH_FIELDS.iter().find_map(|name| {
+ fields
+ .iter()
+ .position(|f| f.name == *name && f.categorical())
+ })
+}
+
+/// A filesystem path named by one prompt token, as the `prefix` value to
+/// query, or `None` when `raw` is not a path.
+///
+/// Whitespace is the only token split, so `crates/herdr-gpui/src` arrives
+/// whole. `norm_text` then deletes the slashes, which is why the value pass
+/// cannot see it. A directory (last segment has no `.`) gets a trailing
+/// slash: prefix `crates/app/src/` matches `crates/app/src/lib.rs` and not
+/// `crates/app/src2/lib.rs`. A file (last segment contains `.`) is prefixed
+/// as written. `and/or` is grammar, not a path. `http://…` is left for the
+/// ordinary passes.
+fn path_prefix(raw: &str) -> Option<String> {
+ if !raw.contains('/') && !raw.contains('\\') {
+ return None;
+ }
+ let lower = raw.to_ascii_lowercase();
+ if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("file://")
+ {
+ return None;
+ }
+ let normalized = raw.replace('\\', "/");
+ let trimmed = normalized.trim_matches('/');
+ let trimmed = trimmed.strip_prefix("./").unwrap_or(trimmed);
+ if trimmed.is_empty() {
+ return None;
+ }
+ let segments: Vec<&str> = trimmed.split('/').filter(|s| !s.is_empty()).collect();
+ if segments.len() < 2 || !trimmed.chars().any(|c| c.is_ascii_alphabetic()) {
+ return None;
+ }
+ let contentful = segments.iter().any(|seg| {
+ let n = norm_text(seg);
+ !n.is_empty()
+ && !FUNCTION_WORDS.contains(&n.as_str())
+ && !GENERIC_WORDS.contains(&n.as_str())
+ });
+ if !contentful {
+ return None;
+ }
+ let last = segments[segments.len() - 1];
+ // Two bare words joined by a slash (`tcp/ip`, `client/server`,
+ // `north/south`) are prose, not a path. Only take a token as a path when
+ // it says so: three or more segments, a file extension on the last
+ // segment, or a leading `./` `/` `~/` or trailing slash.
+ let has_ext = last.rsplit_once('.').is_some_and(|(stem, ext)| {
+ !stem.is_empty() && !ext.is_empty() && ext.chars().all(|c| c.is_ascii_alphanumeric())
+ });
+ let anchored = normalized.starts_with("./")
+ || normalized.starts_with('/')
+ || normalized.starts_with("~/")
+ || normalized.ends_with('/');
+ if segments.len() < 3 && !has_ext && !anchored {
+ return None;
+ }
+ if last.contains('.') {
+ Some(trimmed.to_string())
+ } else {
+ Some(format!("{trimmed}/"))
+ }
+}
+
+/// Pass P: ground each path token as a keyword prefix. Tokens stay unused
+/// when the index has no path field, so [`settle_leftovers`] can refuse
+/// them by name instead of filing them as decoration.
+fn path_pass(toks: &[Tok], fields: &[FieldView], used: &mut [bool], ctx: &mut PlanCtx) {
+ let Some(fpos) = path_field(fields) else {
+ return;
+ };
+ let field = fields[fpos].name.clone();
+ for (i, t) in toks.iter().enumerate() {
+ if used[i] {
+ continue;
+ }
+ let Some(prefix) = path_prefix(&t.raw) else {
+ continue;
+ };
+ ctx.constraints.push(Constraint {
+ clause: prefix_clause(&field, &prefix),
+ phrase: t.raw.clone(),
+ via: "path-prefix",
+ is_range: false,
+ pos: i,
+ });
+ used[i] = true;
+ }
+}
+
/// Pass C: equality against the live value map. Returns the leftover runs
/// it could not ground, for the decoration/refusal decision.
async fn value_pass(
@@ -2387,6 +2522,23 @@ fn settle_leftovers(
return Ok(());
}
for run in unresolved {
+ // A path is a constraint the caller asked for. Dropping it as a
+ // lowercase modifier returns a different document set and says only
+ // that a modifier was ignored (#2120).
+ if let Some(path) = run
+ .iter()
+ .find_map(|&k| path_prefix(&toks[k].raw).map(|_| toks[k].raw.clone()))
+ {
+ return Err((
+ vec![path.clone()],
+ format!(
+ "phrase `{path}` looks like a file path, but this index has no keyword \
+ field named ax_path, path, filepath, file, or ax_file to filter on — \
+ refusing rather than dropping the path. Map one of those fields, or \
+ remove the path from the prompt"
+ ),
+ ));
+ }
let single = run.len() == 1;
let capitalized = toks[run[0]].capitalized;
if capitalized || !single || !grounded {
@@ -2483,6 +2635,58 @@ mod tests {
assert_eq!(concept_for("nothingknown"), None);
}
+ #[test]
+ fn path_prefix_is_a_directory_or_a_file() {
+ assert_eq!(
+ path_prefix("crates/herdr-gpui/src"),
+ Some("crates/herdr-gpui/src/".into())
+ );
+ // A trailing slash is the same directory. A sibling prefix is not.
+ assert_eq!(
+ path_prefix("crates/herdr-gpui/src/"),
+ Some("crates/herdr-gpui/src/".into())
+ );
+ assert_eq!(
+ path_prefix(r"crates\herdr-gpui\src"),
+ Some("crates/herdr-gpui/src/".into())
+ );
+ assert_eq!(
+ path_prefix("crates/herdr-gpui/src/worktree.rs"),
+ Some("crates/herdr-gpui/src/worktree.rs".into())
+ );
+ assert_eq!(path_prefix("./src/lib.rs"), Some("src/lib.rs".into()));
+ // Grammar, dates, and URLs are not paths.
+ assert_eq!(path_prefix("and/or"), None);
+ assert_eq!(path_prefix("2026/09/01"), None);
+ assert_eq!(path_prefix("https://example.com/a"), None);
+ assert_eq!(path_prefix("rust"), None);
+ // Two bare words joined by a slash are prose, not a path.
+ assert_eq!(path_prefix("tcp/ip"), None);
+ assert_eq!(path_prefix("client/server"), None);
+ assert_eq!(path_prefix("src/lib.rs"), Some("src/lib.rs".into()));
+ assert_eq!(path_prefix("app/src/"), Some("app/src/".into()));
+ }
+
+ #[test]
+ fn path_field_prefers_ax_path_over_the_filename_field() {
+ let fields = vec![
+ FieldView::new("path".into(), "keyword"),
+ FieldView::new("ax_path".into(), "keyword"),
+ FieldView::new("language".into(), "keyword"),
+ FieldView::new("body".into(), "text"),
+ ];
+ assert_eq!(fields[path_field(&fields).unwrap()].name, "ax_path");
+ let filename_only = vec![FieldView::new("path".into(), "keyword")];
+ assert_eq!(fields_name(&filename_only), "path");
+ assert!(path_field(&[FieldView::new("language".into(), "keyword")]).is_none());
+ // A text `path` is not a keyword prefix target.
+ assert!(path_field(&[FieldView::new("path".into(), "text")]).is_none());
+ }
+
+ fn fields_name(fields: &[FieldView]) -> &str {
+ &fields[path_field(fields).unwrap()].name
+ }
+
#[test]
fn value_agg_fields_orders_by_cardinality_then_name() {
let mut fields = vec![
diff --git a/engine/crates/xerj-api/tests/ask_endpoint.rs b/engine/crates/xerj-api/tests/ask_endpoint.rs
index c306577c4..75a447d7c 100644
--- a/engine/crates/xerj-api/tests/ask_endpoint.rs
+++ b/engine/crates/xerj-api/tests/ask_endpoint.rs
@@ -700,3 +700,152 @@ async fn native_router_serves_the_same_handler() {
assert_eq!(status, StatusCode::OK, "{body}");
assert_eq!(body["query"], json!({ "term": { "net": "ak" } }));
}
+
+/// #2120: "rust files in crates/herdr-gpui/src with more than 10 symbols"
+/// must keep the path. `ax_path` wins over the filename `path` field, a
+/// directory prefix does not match a sibling (`src` vs `src2`), and a path
+/// with no keyword path field is a 422 that names it — not an ignored
+/// lowercase modifier.
+#[tokio::test]
+async fn a_path_constraint_becomes_a_prefix_on_ax_path() {
+ let (app, _dir) = app().await;
+ let (status, body) = json_req(
+ &app,
+ "PUT",
+ "/ax-code",
+ json!({ "mappings": { "properties": {
+ "language": { "type": "keyword" },
+ "symbol_count": { "type": "long" },
+ "path": { "type": "keyword" },
+ "ax_path": { "type": "keyword" }
+ } } }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let docs = [
+ (
+ "in",
+ "rust",
+ 12,
+ "worktree.rs",
+ "crates/herdr-gpui/src/worktree.rs",
+ ),
+ ("out", "rust", 12, "lib.rs", "crates/other/src/lib.rs"),
+ (
+ "few",
+ "rust",
+ 3,
+ "small.rs",
+ "crates/herdr-gpui/src/small.rs",
+ ),
+ ("py", "python", 20, "py.rs", "crates/herdr-gpui/src/py.rs"),
+ ("sib", "rust", 11, "mod.rs", "crates/herdr-gpui/src2/mod.rs"),
+ ];
+ let mut ndjson = String::new();
+ for (id, language, symbols, path, ax_path) in docs {
+ ndjson.push_str(&format!(
+ "{{\"index\":{{\"_index\":\"ax-code\",\"_id\":\"{id}\"}}}}\n{}\n",
+ json!({
+ "language": language,
+ "symbol_count": symbols,
+ "path": path,
+ "ax_path": ax_path,
+ })
+ ));
+ }
+ let (status, body) = raw_req(&app, "POST", "/_bulk", ndjson).await;
+ assert_eq!(status, StatusCode::OK, "bulk failed: {body}");
+ assert_eq!(body["errors"], false, "{body}");
+ let (status, body) = json_req(&app, "POST", "/ax-code/_refresh", json!({})).await;
+ assert_eq!(status, StatusCode::OK, "refresh: {body}");
+
+ let prompt = "rust files in crates/herdr-gpui/src with more than 10 symbols";
+ let (status, body) = ask(&app, "ax-code", prompt).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(
+ body["query"],
+ json!({ "bool": { "filter": [
+ { "term": { "language": "rust" } },
+ { "prefix": { "ax_path": "crates/herdr-gpui/src/" } },
+ { "range": { "symbol_count": { "gt": 10 } } }
+ ] } }),
+ "{body}"
+ );
+ let plan = body["plan"].as_array().unwrap();
+ let fields = plan.iter().find(|s| s["action"] == "fields").unwrap();
+ assert_eq!(fields["counted"], "top-level mapping fields");
+ assert_eq!(fields["count"], 4);
+ assert!(
+ fields["provenance_fields"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|n| n == "ax_path"),
+ "{fields}"
+ );
+ assert!(
+ !plan.iter().any(|s| {
+ s["action"] == "ignored" && s["phrase"].as_str().unwrap_or("").contains("crates/")
+ }),
+ "the path must not be logged as an ignored modifier: {plan:?}"
+ );
+
+ let (status, found) = json_req(
+ &app,
+ "POST",
+ "/ax-code/_search",
+ json!({ "query": body["query"], "size": 10 }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{found}");
+ let ids: Vec<&str> = found["hits"]["hits"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter_map(|h| h["_id"].as_str())
+ .collect();
+ assert_eq!(
+ ids,
+ ["in"],
+ "directory prefix must miss src2, other crates, non-rust, and symbol_count <= 10: {found}"
+ );
+
+ // No path field: the path is named in a 422, not silently dropped while
+ // the language and symbol_count constraints succeed.
+ let (status, body) = json_req(
+ &app,
+ "PUT",
+ "/ax-plain",
+ json!({ "mappings": { "properties": {
+ "language": { "type": "keyword" },
+ "symbol_count": { "type": "long" }
+ } } }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let (status, body) = json_req(
+ &app,
+ "POST",
+ "/ax-plain/_doc/p1",
+ json!({ "language": "rust", "symbol_count": 12 }),
+ )
+ .await;
+ assert!(status.is_success(), "{body}");
+ let (status, body) = json_req(&app, "POST", "/ax-plain/_refresh", json!({})).await;
+ assert_eq!(status, StatusCode::OK, "refresh: {body}");
+ let (status, body) = ask(&app, "ax-plain", prompt).await;
+ assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
+ let reason = body["error"]["reason"].as_str().unwrap_or("");
+ assert!(
+ reason.contains("crates/herdr-gpui/src"),
+ "the refusal must name the path: {body}"
+ );
+ assert!(
+ reason.contains("ax_path"),
+ "the refusal must say which fields would have grounded it: {body}"
+ );
+ assert!(
+ !reason.contains("lowercase modifier"),
+ "a path is not decoration: {body}"
+ );
+}
diff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rs
index e748a331a..759653f48 100644
--- a/engine/crates/xerj-autoindex/src/catalog.rs
+++ b/engine/crates/xerj-autoindex/src/catalog.rs
@@ -198,9 +198,60 @@ pub struct DatasetDocInput<'a> {
pub run_id: &'a str,
}
+/// Field list stored on a dataset doc.
+///
+/// The profiler never observes the `ax_*` provenance locators — they are
+/// stamped after sampling — but the mapping builder maps every
+/// `PROVENANCE_FIELDS` entry as `keyword` and every record carries them.
+/// Leaving them out of
+/// `fields_json` is what made `xerj_map` omit `ax_path` while `xerj_plan`
+/// counted it (#2120). Appending here does not touch `pd.specs`: that vec
+/// is hashed into `schema_identity`, and a new spec there would abort every
+/// existing state dir.
+pub fn catalog_field_specs(specs: &[crate::infer::FieldSpec]) -> Vec<crate::infer::FieldSpec> {
+ let mut out = specs.to_vec();
+ for name in crate::PROVENANCE_FIELDS {
+ if out.iter().any(|s| s.name == *name) {
+ continue;
+ }
+ out.push(provenance_catalog_spec(name));
+ }
+ out
+}
+
+/// A locator the pipeline stamps on every record. Coverage is 1 because the
+/// stamp is unconditional. Cardinality is unmeasured (`0` plus the note) —
+/// `ax_path` is high and `ax_dataset` is not, and inventing either number
+/// would be a false claim.
+fn provenance_catalog_spec(name: &str) -> crate::infer::FieldSpec {
+ crate::infer::FieldSpec {
+ name: name.to_string(),
+ es_type: "keyword".into(),
+ date_enc: None,
+ semantic: None,
+ cardinality_est: 0,
+ cardinality_overflow: false,
+ null_ratio: 0.0,
+ avg_len: 0.0,
+ coverage: 1.0,
+ examples: Vec::new(),
+ notes: vec![
+ "autoindex provenance locator, mapped keyword and stamped on every record; \
+ not sampled, so cardinality_est 0 means unmeasured"
+ .into(),
+ ],
+ date_min: None,
+ date_max: None,
+ date_evidence: Vec::new(),
+ num_min: None,
+ num_max: None,
+ }
+}
+
pub fn dataset_doc(inp: &DatasetDocInput) -> (String, Value) {
let id = format!("ds:{}:{}", inp.prefix, inp.pd.slug);
- let fields_json = serde_json::to_string(&inp.pd.specs).unwrap_or_else(|_| "[]".into());
+ let fields_json =
+ serde_json::to_string(&catalog_field_specs(&inp.pd.specs)).unwrap_or_else(|_| "[]".into());
let doc = json!({
"doc_kind": "dataset",
"slug": inp.pd.slug,
@@ -861,7 +912,11 @@ pub fn render_map_page(
}
// fields table
if let Some(fj) = d.get("fields_json").and_then(|v| v.as_str()) {
- if let Ok(specs) = serde_json::from_str::<Vec<crate::infer::FieldSpec>>(fj) {
+ if let Ok(parsed) = serde_json::from_str::<Vec<crate::infer::FieldSpec>>(fj) {
+ // Old catalogs were written before locators were appended.
+ // Rendering them here is what an already-indexed corpus's
+ // `xerj autoindex map` shows, without a reindex (#2120).
+ let specs = catalog_field_specs(&parsed);
s.push_str("| field | type | semantic | cardinality | null% | examples |\n");
s.push_str("|---|---|---|---|---|---|\n");
let mut sorted: Vec<&crate::infer::FieldSpec> = specs.iter().collect();
@@ -872,7 +927,9 @@ pub fn render_map_page(
.then(a.name.cmp(&b.name))
});
for f in sorted.iter().take(40) {
- let card = if f.cardinality_overflow {
+ let card = if f.notes.iter().any(|n| n.contains("not sampled")) {
+ "—".to_string()
+ } else if f.cardinality_overflow {
format!("{}+", crate::infer::DISTINCT_CAP)
} else {
f.cardinality_est.to_string()
@@ -1168,6 +1225,48 @@ mod duplicate_tests {
/// A newline in an example used to end the markdown row. The next line
/// (`## Branded types…`) was then a heading in the middle of the table.
+ #[test]
+ fn catalog_fields_include_provenance_locators_the_profiler_never_saw() {
+ let specs = catalog_field_specs(&[one_field("language", "rust")]);
+ let names: Vec<&str> = specs.iter().map(|s| s.name.as_str()).collect();
+ for loc in crate::PROVENANCE_FIELDS {
+ assert!(names.contains(loc), "missing {loc}: {names:?}");
+ }
+ let again = catalog_field_specs(&specs);
+ assert_eq!(
+ again.len(),
+ specs.len(),
+ "a locator already stored is not duplicated"
+ );
+ let ax_path = specs.iter().find(|s| s.name == "ax_path").unwrap();
+ assert_eq!(ax_path.es_type, "keyword");
+ assert_eq!(ax_path.coverage, 1.0);
+ assert!(ax_path.notes.iter().any(|n| n.contains("not sampled")));
+ }
+
+ #[test]
+ fn an_old_catalog_map_still_lists_ax_path() {
+ let dataset = json!({
+ "index_name": "ax-code",
+ "slug": "code",
+ "record_count": 10,
+ "file_count": 1,
+ "formats": "rs",
+ "fields_json": serde_json::to_string(&vec![one_field("language", "rust")]).unwrap()
+ });
+ let rendered = render_map(None, &[dataset], &[], &[], &[], 0);
+ assert!(rendered.contains("`ax_path`"), "{rendered}");
+ assert!(rendered.contains("`ax_locator`"), "{rendered}");
+ let row = rendered
+ .lines()
+ .find(|l| l.contains("`ax_path`"))
+ .expect("ax_path row");
+ assert!(
+ row.contains("| — | 0%"),
+ "unmeasured cardinality is not a fake 0: {row}"
+ );
+ }
+
#[test]
fn an_example_newline_stays_inside_its_table_row() {
let dataset = json!({
diff --git a/engine/crates/xerj-mcp/src/map.rs b/engine/crates/xerj-mcp/src/map.rs
index 770f923c5..fd54321b6 100644
--- a/engine/crates/xerj-mcp/src/map.rs
+++ b/engine/crates/xerj-mcp/src/map.rs
@@ -500,10 +500,188 @@ fn summary_entry(entry: &Value) -> Value {
})
}
-/// `xerj_map` dispatch: read the catalog, render the map. A missing catalog
-/// (the node never ran autoindex) is an error with the fix named — the
-/// response an agent can act on — while an empty-but-present catalog is a
-/// normal empty result, not an error.
+/// Locator fields autoindex stamps on every record and maps as keyword
+/// (`xerj_autoindex::PROVENANCE_FIELDS`). Copied here so this proxy does not
+/// depend on that crate. The profiler never sees them, so a catalog written
+/// before #2120 omits them from `fields_json` even though they are queryable.
+const PROVENANCE_FIELDS: &[&str] = &[
+ "ax_path",
+ "ax_paths",
+ "ax_file",
+ "ax_locator",
+ "ax_dataset",
+ "ax_run",
+ "ax_format",
+];
+
+fn provenance_field(name: &str) -> Value {
+ json!({
+ "name": name,
+ "es_type": "keyword",
+ "coverage": 1.0,
+ "cardinality_est": 0,
+ "notes": [
+ "autoindex provenance locator, mapped keyword and stamped on every record; \
+ not sampled, so cardinality_est 0 means unmeasured"
+ ],
+ })
+}
+
+fn mapped_only_field(name: &str, spec: &Value) -> Value {
+ let es_type = spec.get("type").and_then(Value::as_str).unwrap_or("object");
+ if PROVENANCE_FIELDS.contains(&name) {
+ let mut field = provenance_field(name);
+ if let Some(obj) = field.as_object_mut() {
+ obj.insert("es_type".into(), json!(es_type));
+ }
+ field
+ } else {
+ json!({
+ "name": name,
+ "es_type": es_type,
+ "notes": ["mapped on the index but absent from the profiled catalog"],
+ })
+ }
+}
+
+/// Union each dataset's `fields_json` with the index mapping's top-level
+/// properties (or, when `mapping` is `None` because the mapping read failed,
+/// with [`PROVENANCE_FIELDS`]).
+///
+/// A corrupt `fields_json` is left alone: the renderer already turns that
+/// into an empty field list rather than an error, and inventing locators on
+/// top of a parse failure would hide the corruption.
+///
+/// Names are appended in sorted order. `render_response` re-sorts by
+/// coverage, so this order only matters for the bytes stored back into the
+/// hit, which nothing else reads.
+pub(crate) fn merge_mapped_fields(resp: &mut Value, mapping: Option<&Value>) {
+ let Some(hits) = resp.pointer_mut("/hits/hits").and_then(Value::as_array_mut) else {
+ return;
+ };
+ for hit in hits.iter_mut() {
+ let Some(src) = hit.get_mut("_source").and_then(Value::as_object_mut) else {
+ continue;
+ };
+ let index = src
+ .get("index_name")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let raw = src
+ .get("fields_json")
+ .and_then(Value::as_str)
+ .unwrap_or("[]");
+ let Ok(mut fields) = serde_json::from_str::<Vec<Value>>(raw) else {
+ continue;
+ };
+ if fields.iter().any(|f| !f.is_object()) {
+ continue;
+ }
+ let present: std::collections::HashSet<String> = fields
+ .iter()
+ .filter_map(|f| f.get("name").and_then(Value::as_str).map(str::to_string))
+ .collect();
+ let properties = mapping.and_then(|m| {
+ m.get(&index)
+ .and_then(|v| v.pointer("/mappings/properties"))
+ .and_then(Value::as_object)
+ });
+ if let Some(props) = properties {
+ let mut names: Vec<&String> = props.keys().collect();
+ names.sort();
+ for name in names {
+ if name.starts_with('_') || present.contains(name.as_str()) {
+ continue;
+ }
+ fields.push(mapped_only_field(name, &props[name]));
+ }
+ } else if mapping.is_none() {
+ for name in PROVENANCE_FIELDS {
+ if present.contains(*name) {
+ continue;
+ }
+ fields.push(provenance_field(name));
+ }
+ }
+ if let Ok(encoded) = serde_json::to_string(&fields) {
+ src.insert("fields_json".into(), Value::String(encoded));
+ }
+ }
+}
+
+fn field_count_means(mapping_read: bool) -> &'static str {
+ if mapping_read {
+ "each indexes[].field_count is the catalog's profiled fields union that index's \
+ top-level mapping fields, the same set xerj_plan counts as top-level mapping fields. \
+ ax_* locators the profiler did not sample are included"
+ } else {
+ "each indexes[].field_count is the catalog's profiled fields plus the ax_* provenance \
+ locators autoindex maps as keyword. The live mapping could not be read, so other \
+ mapped-but-unprofiled fields are not listed. xerj_plan's field count is top-level \
+ mapping fields"
+ }
+}
+
+fn annotate_field_count(rendered: &str, mapping_read: bool) -> String {
+ let Ok(mut value) = serde_json::from_str::<Value>(rendered) else {
+ return rendered.to_string();
+ };
+ if let Some(obj) = value.as_object_mut() {
+ obj.insert(
+ "field_count_means".into(),
+ json!(field_count_means(mapping_read)),
+ );
+ }
+ value.to_string()
+}
+
+async fn fetch_mappings(ctx: &Ctx, indexes: &[String]) -> Option<Value> {
+ if indexes.is_empty() {
+ return Some(json!({}));
+ }
+ let path = indexes
+ .iter()
+ .map(|name| super::enc(name))
+ .collect::<Vec<_>>()
+ .join(",");
+ let url = format!("{}/{path}/_mapping", ctx.base_url);
+ let mut req = ctx.client.get(&url);
+ if let Some(auth) = &ctx.auth {
+ req = req.header("Authorization", auth);
+ }
+ let resp = req.send().await.ok()?;
+ if !resp.status().is_success() {
+ return None;
+ }
+ let text = resp.text().await.ok()?;
+ serde_json::from_str(&text).ok()
+}
+
+fn index_names(resp: &Value) -> Vec<String> {
+ resp.pointer("/hits/hits")
+ .and_then(Value::as_array)
+ .map(|hits| {
+ let mut names: Vec<String> = hits
+ .iter()
+ .filter_map(|h| {
+ h.pointer("/_source/index_name")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ })
+ .collect();
+ names.sort();
+ names.dedup();
+ names
+ })
+ .unwrap_or_default()
+}
+
+/// `xerj_map` dispatch: read the catalog, union each index's live mapping so
+/// `ax_*` locators and any other mapped-but-unprofiled field are listed, then
+/// render. A missing catalog (the node never ran autoindex) is an error with
+/// the fix named — the response an agent can act on — while an empty-but-present
+/// catalog is a normal empty result, not an error.
pub(crate) async fn run(ctx: &Ctx, args: &Value) -> Value {
let parsed = match parse_args(args) {
Ok(a) => a,
@@ -521,7 +699,15 @@ pub(crate) async fn run(ctx: &Ctx, args: &Value) -> Value {
let text = resp.text().await.unwrap_or_default();
if status.is_success() {
match serde_json::from_str::<Value>(&text) {
- Ok(v) => tool_text(render_response(&v, &parsed), false),
+ Ok(mut v) => {
+ let mapping = fetch_mappings(ctx, &index_names(&v)).await;
+ let mapping_read = mapping.is_some();
+ merge_mapped_fields(&mut v, mapping.as_ref());
+ tool_text(
+ annotate_field_count(&render_response(&v, &parsed), mapping_read),
+ false,
+ )
+ }
Err(e) => tool_text(
format!("xerj_map: catalog reply was not JSON ({e}): {text}"),
true,
@@ -917,6 +1103,101 @@ mod tests {
assert_eq!(out["indexes_omitted"], 250 - 1);
}
+ #[test]
+ fn mapped_fields_the_catalog_omitted_are_unioned_in() {
+ let fields =
+ r#"[{"name":"language","es_type":"keyword","cardinality_est":2,"coverage":1.0}]"#;
+ let mut resp = catalog_response(vec![dataset_doc("ax-code", 28, fields)]);
+ let mapping = json!({
+ "ax-code": { "mappings": { "properties": {
+ "language": {"type": "keyword"},
+ "ax_path": {"type": "keyword"},
+ "ax_file": {"type": "keyword"},
+ "symbols": {"type": "object"},
+ "_internal": {"type": "keyword"}
+ }}}
+ });
+ merge_mapped_fields(&mut resp, Some(&mapping));
+ let out: Value = serde_json::from_str(&render_response(&resp, &args(None))).unwrap();
+ let idx = &out["indexes"][0];
+ // language (catalog) + ax_path + ax_file + symbols. `_internal` is not
+ // a user field, matching the planner's skip of `_`-prefixed names.
+ assert_eq!(idx["field_count"], 4, "{idx}");
+ let names: Vec<&str> = idx["fields"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter_map(|f| f["name"].as_str())
+ .collect();
+ assert!(names.contains(&"ax_path"), "{names:?}");
+ assert!(names.contains(&"ax_file"), "{names:?}");
+ assert!(names.contains(&"symbols"), "{names:?}");
+ assert!(!names.iter().any(|n| n.starts_with('_')), "{names:?}");
+ let ax = idx["fields"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|f| f["name"] == "ax_path")
+ .unwrap();
+ assert_eq!(ax["es_type"], "keyword");
+ assert_eq!(ax["coverage"], 1.0);
+ let language = idx["fields"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|f| f["name"] == "language")
+ .unwrap();
+ assert_eq!(
+ language["cardinality_est"], 2,
+ "a profiled field keeps its catalog stats"
+ );
+ }
+
+ #[test]
+ fn a_failed_mapping_read_still_lists_the_provenance_locators() {
+ let fields =
+ r#"[{"name":"language","es_type":"keyword","cardinality_est":1,"coverage":1.0}]"#;
+ let mut resp = catalog_response(vec![dataset_doc("ax-code", 1, fields)]);
+ merge_mapped_fields(&mut resp, None);
+ let out: Value = serde_json::from_str(&render_response(&resp, &args(None))).unwrap();
+ assert_eq!(
+ out["indexes"][0]["field_count"],
+ 1 + PROVENANCE_FIELDS.len()
+ );
+ let names: Vec<&str> = out["indexes"][0]["fields"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter_map(|f| f["name"].as_str())
+ .collect();
+ for loc in PROVENANCE_FIELDS {
+ assert!(names.contains(loc), "missing {loc} in {names:?}");
+ }
+ }
+
+ #[test]
+ fn a_mapping_that_omits_an_index_does_not_invent_locators() {
+ let fields =
+ r#"[{"name":"language","es_type":"keyword","cardinality_est":1,"coverage":1.0}]"#;
+ let mut resp = catalog_response(vec![dataset_doc("ax-code", 1, fields)]);
+ merge_mapped_fields(
+ &mut resp,
+ Some(&json!({"other": {"mappings": {"properties": {}}}})),
+ );
+ let out: Value = serde_json::from_str(&render_response(&resp, &args(None))).unwrap();
+ assert_eq!(out["indexes"][0]["field_count"], 1, "{out}");
+ }
+
+ #[test]
+ fn corrupt_fields_json_is_not_rewritten_by_the_mapping_merge() {
+ let mut resp = catalog_response(vec![dataset_doc("ax-bad", 5, "not json")]);
+ merge_mapped_fields(&mut resp, None);
+ assert_eq!(
+ resp["hits"]["hits"][0]["_source"]["fields_json"],
+ "not json"
+ );
+ }
+
#[test]
fn a_corrupt_fields_json_renders_an_empty_field_list_not_an_error() {
let resp = catalog_response(vec![dataset_doc("ax-bad", 5, "not json")]);