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(autoindex): estimate neural ingest time and say --embed-mode is fixed at ingest (#2250)

xerj-orgadd937a41b31
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6b6b97b52..13e54266a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -69,6 +69,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
does not retry a timed-out refresh
([#2234](https://github.com/xerj-org/xerj/issues/2234)).
+- Neural `xerj autoindex` prints an estimated embedding time before ingest,
+ from a probe measured when the neural model loads and the bytes of files
+ that feed a `semantic_text` dataset. The line names no duration when the
+ probe did not run, and it points at the faster lexical default.
+ `--embed-mode` help and the startup warning state that the mode is fixed
+ per index at ingest and that changing it requires a re-index. Creating or
+ updating a mapping warns when `inference_id`, `model_id`, or
+ `inference_endpoint` names a different embedder than the server is running;
+ those keys do not switch the embedder
+ ([#1612](https://github.com/xerj-org/xerj/issues/1612)).
+
- A matching index template's `semantic_text` properties and
`index.default_pipeline` are applied when an index is created, including
the body `xerj autoindex` sends and the first bulk or single-document
diff --git a/docs/recipes/autoindex-semantic-search.md b/docs/recipes/autoindex-semantic-search.md
index dda1601d0..7ebb86fdf 100644
--- a/docs/recipes/autoindex-semantic-search.md
+++ b/docs/recipes/autoindex-semantic-search.md
@@ -29,8 +29,16 @@ downloads once on first use, then runs from a local cache (air-gap friendly via
xerj --insecure --data-dir ./data --embed-mode neural
```
-Drop `--embed-mode neural` and everything below still works — it just uses the
-built-in lexical embedder instead. Nothing else in the recipe changes.
+`--embed-mode` is fixed per index at ingest. Documents keep the vectors written
+when they were indexed. Starting a later process without the flag does not
+re-embed this folder: the index keeps its neural vectors until you re-index
+into a new index (a new `--data-dir`, or `xerj autoindex remove` and a fresh
+run). Omitting the flag is the lexical embedder, which is much faster and is
+not neural. Before a neural `xerj autoindex` run the client prints an estimated
+embedding time from a probe this server measured at startup and the bytes of
+files that feed a `semantic_text` dataset. That line is embedding time only.
+If the probe did not run, the client says the rate was not measured and prints
+no duration.
## 2. Discover and index the folder — zero config
diff --git a/docs/recipes/semantic-search-rag.md b/docs/recipes/semantic-search-rag.md
index a911ac88e..c28c85d25 100644
--- a/docs/recipes/semantic-search-rag.md
+++ b/docs/recipes/semantic-search-rag.md
@@ -168,7 +168,7 @@ The doc is *titled* "Rotating an API key," but only its **body** is embedded, an
the body never uses the word "rotate" — so a pure "rotate" paraphrase misses in
lexical mode.
-### Upgrade to real neural semantics — still one binary, still in place
+### Upgrade to real neural semantics — still one binary
```bash
# Built-in neural embedder — ships in the binary; downloads all-MiniLM-L6-v2
@@ -177,9 +177,12 @@ lexical mode.
xerj --insecure --data-dir ./data --embed-mode neural
```
-With `--embed-mode neural`, the "rotate" paraphrase above lands on `kb-1` — the
-BERT encoder captures that *rotate ≈ regenerate ≈ replace* even with no shared
-term. Measured on the standard sentence-similarity pair, the built-in neural
+With `--embed-mode neural`, documents indexed after the switch are embedded by
+the BERT encoder, so the "rotate" paraphrase above lands on `kb-1` — it
+captures that *rotate ≈ regenerate ≈ replace* even with no shared term.
+Documents already in the index keep the vectors written at ingest: changing
+the flag does not re-embed them. Re-index the corpus after switching.
+Measured on the standard sentence-similarity pair, the built-in neural
embedder scores a paraphrase at cosine **0.72** vs an unrelated sentence at
**−0.04**; the lexical embedder cannot separate them that way.
diff --git a/engine/crates/xerj-ai/src/neural.rs b/engine/crates/xerj-ai/src/neural.rs
index c3c3d45af..3a262cef9 100644
--- a/engine/crates/xerj-ai/src/neural.rs
+++ b/engine/crates/xerj-ai/src/neural.rs
@@ -311,6 +311,56 @@ impl NeuralEmbedder {
}
}
+/// Passages in one ingest-rate probe. 32 rows of 512 ASCII characters fit one
+/// length-aware forward pass under [`PADDED_TOKEN_BUDGET`] for prose-like
+/// text, which is the shape `semantic_text` chunks are cut to.
+pub const INGEST_PROBE_PASSAGES: usize = 32;
+
+/// Characters (and bytes — the probe is ASCII) in each probe passage.
+pub const INGEST_PROBE_CHARS: usize = 512;
+
+/// Time one batch of ingest-shaped passages.
+///
+/// One untimed warmup passage runs first, so the timed call is not the
+/// process's first Candle forward. Returns `None` when the call fails or the
+/// clock reports 0 ms — that is "not measured", not a rate of infinity.
+/// The result is not part of [`asset_identity`]: batching and wall time do
+/// not change the vectors.
+pub fn measure_ingest_probe(
+ embedder: &NeuralEmbedder,
+) -> Option<xerj_common::config::NeuralIngestProbe> {
+ let passage = ingest_probe_passage();
+ debug_assert_eq!(passage.len(), INGEST_PROBE_CHARS);
+ let warmup = embedder
+ .embed_blocking(std::slice::from_ref(&passage))
+ .ok()?;
+ if warmup.len() != 1 {
+ return None;
+ }
+ let texts = vec![passage; INGEST_PROBE_PASSAGES];
+ let started = std::time::Instant::now();
+ let vectors = embedder.embed_blocking(&texts).ok()?;
+ let millis = u64::try_from(started.elapsed().as_millis()).ok()?;
+ if millis == 0 || vectors.len() != INGEST_PROBE_PASSAGES {
+ return None;
+ }
+ Some(xerj_common::config::NeuralIngestProbe {
+ bytes: (INGEST_PROBE_CHARS * INGEST_PROBE_PASSAGES) as u64,
+ passages: INGEST_PROBE_PASSAGES as u32,
+ millis,
+ })
+}
+
+fn ingest_probe_passage() -> String {
+ let unit = "fn embed_passage(text: &str) -> Vec<f32> { hash_tokens(text) } ";
+ let mut passage = String::with_capacity(INGEST_PROBE_CHARS);
+ while passage.len() < INGEST_PROBE_CHARS {
+ passage.push_str(unit);
+ }
+ passage.truncate(INGEST_PROBE_CHARS);
+ passage
+}
+
/// How [`NeuralEmbedder::embed_blocking`] turns per-token hidden states into
/// one vector. Part of the identity: the same weights pooled differently are a
/// different embedder.
diff --git a/engine/crates/xerj-api/src/embed_warning.rs b/engine/crates/xerj-api/src/embed_warning.rs
new file mode 100644
index 000000000..d89fc0336
--- /dev/null
+++ b/engine/crates/xerj-api/src/embed_warning.rs
@@ -0,0 +1,254 @@
+//! Warnings when a mapping asks for an embedder the server will not use.
+//!
+//! `semantic_text` accepts `inference_id`, `model_id`, and `inference_endpoint`
+//! because those keys exist on the Elasticsearch wire. Ingest does not read
+//! them: every document is embedded with the server's `--embed-mode`, which is
+//! fixed for the index at ingest time. Saying so on the create/mapping
+//! response is the warning; the hard refusal when a restarted process opens a
+//! populated index under a different embedder stays in the engine.
+
+use serde_json::{Map, Value};
+
+/// The embedder this process will actually run. Names are compared
+/// case-insensitively after trimming.
+#[derive(Debug, Clone)]
+pub struct ResolvedEmbedder {
+ pub backend: String,
+ pub neural_model: String,
+ pub proxy_model: String,
+ pub proxy_endpoint: String,
+}
+
+/// One warning per `semantic_text` field whose requested id or endpoint does
+/// not match [`ResolvedEmbedder`]. No request is not a mismatch.
+pub fn semantic_embedder_warnings(body: &Value, resolved: &ResolvedEmbedder) -> Vec<String> {
+ let Some(properties) = properties_of(body) else {
+ return Vec::new();
+ };
+ let mut fields = Vec::new();
+ collect(properties, "", &mut fields);
+ let mut warnings = Vec::new();
+ for (name, spec) in fields {
+ if let Some(warning) = field_warning(&name, spec, resolved) {
+ warnings.push(warning);
+ if warnings.len() == 8 {
+ warnings.push(
+ "further semantic_text embedder mismatches were omitted; the mapping does not \
+ switch the embedder"
+ .to_string(),
+ );
+ break;
+ }
+ }
+ }
+ warnings
+}
+
+fn properties_of(body: &Value) -> Option<&Map<String, Value>> {
+ body.get("mappings")
+ .and_then(|mappings| mappings.get("properties"))
+ .or_else(|| body.get("properties"))
+ .and_then(Value::as_object)
+}
+
+fn collect<'a>(
+ properties: &'a Map<String, Value>,
+ prefix: &str,
+ out: &mut Vec<(String, &'a Map<String, Value>)>,
+) {
+ for (name, spec) in properties {
+ let Some(spec) = spec.as_object() else {
+ continue;
+ };
+ let full = if prefix.is_empty() {
+ name.clone()
+ } else {
+ format!("{prefix}.{name}")
+ };
+ if spec.get("type").and_then(Value::as_str) == Some("semantic_text") {
+ out.push((full.clone(), spec));
+ }
+ if let Some(nested) = spec.get("properties").and_then(Value::as_object) {
+ collect(nested, &full, out);
+ }
+ }
+}
+
+fn field_warning(
+ field: &str,
+ spec: &Map<String, Value>,
+ resolved: &ResolvedEmbedder,
+) -> Option<String> {
+ let inference_id = spec
+ .get("inference_id")
+ .or_else(|| spec.get("model_id"))
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|id| !id.is_empty());
+ let endpoint = spec
+ .get("inference_endpoint")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|endpoint| !endpoint.is_empty());
+ if inference_id.is_none() && endpoint.is_none() {
+ return None;
+ }
+ let id_mismatch = inference_id.is_some_and(|id| !id_matches(id, resolved));
+ let endpoint_mismatch = endpoint.is_some_and(|endpoint| !endpoint_matches(endpoint, resolved));
+ if !id_mismatch && !endpoint_mismatch {
+ return None;
+ }
+ let mut asked = Vec::new();
+ if let Some(id) = inference_id {
+ if id_mismatch {
+ asked.push(format!("inference_id/model_id={id}"));
+ }
+ }
+ if let Some(endpoint) = endpoint {
+ if endpoint_mismatch {
+ asked.push(format!("inference_endpoint={endpoint}"));
+ }
+ }
+ Some(format!(
+ "field [{field}] sets {}, but that does not switch the embedder. This index embeds with \
+ the server's {} backend, fixed at ingest time. Changing --embed-mode or this mapping \
+ does not re-embed documents already written; re-index into a new index. The faster \
+ default is lexical (`xerj --embed-mode lexical`, or omit the flag).",
+ asked.join(" and "),
+ resolved.backend
+ ))
+}
+
+fn id_matches(id: &str, resolved: &ResolvedEmbedder) -> bool {
+ if id.eq_ignore_ascii_case(resolved.backend.trim()) {
+ return true;
+ }
+ match resolved.backend.trim() {
+ "neural" => {
+ let model = resolved.neural_model.trim();
+ !model.is_empty() && id.eq_ignore_ascii_case(model)
+ }
+ "proxy" => {
+ let model = resolved.proxy_model.trim();
+ !model.is_empty() && id.eq_ignore_ascii_case(model)
+ }
+ _ => false,
+ }
+}
+
+fn endpoint_matches(endpoint: &str, resolved: &ResolvedEmbedder) -> bool {
+ if resolved.backend.trim() != "proxy" {
+ return false;
+ }
+ let configured = resolved.proxy_endpoint.trim();
+ !configured.is_empty() && endpoint.eq_ignore_ascii_case(configured)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn lexical() -> ResolvedEmbedder {
+ ResolvedEmbedder {
+ backend: "lexical".into(),
+ neural_model: "sentence-transformers/all-MiniLM-L6-v2".into(),
+ proxy_model: String::new(),
+ proxy_endpoint: String::new(),
+ }
+ }
+
+ #[test]
+ fn an_empty_create_response_omits_warnings() {
+ let encoded =
+ serde_json::to_string(&crate::responses::EsIndexResponse::ok("docs")).unwrap();
+ assert!(!encoded.contains("warnings"), "{encoded}");
+ assert!(encoded.contains("\"acknowledged\":true"), "{encoded}");
+ assert!(encoded.contains("\"index\":\"docs\""), "{encoded}");
+ }
+
+ #[test]
+ fn a_matching_or_absent_request_is_silent() {
+ let body = json!({"mappings": {"properties": {
+ "body": {"type": "semantic_text"},
+ "title": {"type": "semantic_text", "inference_id": "lexical"}
+ }}});
+ assert!(semantic_embedder_warnings(&body, &lexical()).is_empty());
+ }
+
+ #[test]
+ fn a_different_inference_id_warns_and_names_reindex() {
+ let body = json!({"properties": {
+ "body": {"type": "semantic_text", "model_id": ".elser_model_2"}
+ }});
+ let warnings = semantic_embedder_warnings(&body, &lexical());
+ assert_eq!(warnings.len(), 1, "{warnings:?}");
+ let warning = &warnings[0];
+ assert!(warning.contains("body"), "{warning}");
+ assert!(warning.contains(".elser_model_2"), "{warning}");
+ assert!(
+ warning.contains("does not switch the embedder"),
+ "{warning}"
+ );
+ assert!(warning.contains("fixed at ingest"), "{warning}");
+ assert!(warning.contains("re-index"), "{warning}");
+ assert!(warning.contains("lexical"), "{warning}");
+ }
+
+ #[test]
+ fn an_endpoint_on_a_non_proxy_backend_warns() {
+ let body = json!({"mappings": {"properties": {
+ "body": {"type": "semantic_text", "inference_endpoint": "https://example.test/v1"}
+ }}});
+ let warnings = semantic_embedder_warnings(&body, &lexical());
+ assert_eq!(warnings.len(), 1, "{warnings:?}");
+ assert!(warnings[0].contains("inference_endpoint=https://example.test/v1"));
+ }
+
+ #[test]
+ fn neural_accepts_its_model_id_and_rejects_another() {
+ let resolved = ResolvedEmbedder {
+ backend: "neural".into(),
+ neural_model: "sentence-transformers/all-MiniLM-L6-v2".into(),
+ proxy_model: String::new(),
+ proxy_endpoint: String::new(),
+ };
+ let same = json!({"mappings": {"properties": {
+ "body": {"type": "semantic_text", "inference_id": "Sentence-Transformers/all-MiniLM-L6-v2"}
+ }}});
+ assert!(semantic_embedder_warnings(&same, &resolved).is_empty());
+ let other = json!({"mappings": {"properties": {
+ "body": {"type": "semantic_text", "inference_id": "lexical"}
+ }}});
+ assert_eq!(semantic_embedder_warnings(&other, &resolved).len(), 1);
+ }
+
+ #[test]
+ fn proxy_matches_its_endpoint_and_model_only() {
+ let resolved = ResolvedEmbedder {
+ backend: "proxy".into(),
+ neural_model: String::new(),
+ proxy_model: "text-embedding-3-small".into(),
+ proxy_endpoint: "https://embed.example/v1".into(),
+ };
+ let same = json!({"mappings": {"properties": {
+ "body": {
+ "type": "semantic_text",
+ "inference_id": "text-embedding-3-small",
+ "inference_endpoint": "https://embed.example/v1"
+ }
+ }}});
+ assert!(semantic_embedder_warnings(&same, &resolved).is_empty());
+ let other = json!({"mappings": {"properties": {
+ "body": {
+ "type": "semantic_text",
+ "inference_id": "text-embedding-3-small",
+ "inference_endpoint": "https://other.example/v1"
+ }
+ }}});
+ let warnings = semantic_embedder_warnings(&other, &resolved);
+ assert_eq!(warnings.len(), 1, "{warnings:?}");
+ assert!(warnings[0].contains("other.example"));
+ assert!(!warnings[0].contains("inference_id/model_id"));
+ }
+}
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 4969467b1..8f7ba1063 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -1634,7 +1634,8 @@ pub async fn create_index(
if let Some(Some(policy_name)) = ilm_lifecycle_directive_from_settings(&body) {
let _ = crate::ism_api::attach_policy(&state, &index, &policy_name).await;
}
- let resp = EsIndexResponse::ok(&index);
+ let mut resp = EsIndexResponse::ok(&index);
+ resp.warnings = embedder_warnings(&state, &body);
(StatusCode::OK, Json(resp)).into_response()
}
Err(e) => ApiError::new(xerj_common::XerjError::from(e)).into_response(),
@@ -1687,7 +1688,8 @@ pub async fn create_index(
let _ = crate::ism_api::attach_policy(&state, &index, &policy_name).await;
}
- let resp = EsIndexResponse::ok(&index);
+ let mut resp = EsIndexResponse::ok(&index);
+ resp.warnings = embedder_warnings(&state, &body);
(StatusCode::OK, Json(resp)).into_response()
}
Err(e) => ApiError::new(xerj_common::XerjError::from(e)).into_response(),
@@ -2372,6 +2374,83 @@ mod runtime_field_type_tests {
);
}
+ #[tokio::test]
+ async fn create_index_warns_when_semantic_text_asks_for_another_embedder() {
+ let router = crate::router::build_es_compat_router(test_state());
+ let response = router
+ .oneshot(
+ Request::put("/embed-warn")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ json!({"mappings": {"properties": {
+ "body": {"type": "semantic_text", "inference_id": ".elser_model_2"}
+ }}})
+ .to_string(),
+ ))
+ .expect("request"),
+ )
+ .await
+ .expect("create response");
+ let status = response.status();
+ let bytes = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response bytes");
+ let body: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
+ assert!(status.is_success(), "{status} {body}");
+ let warning = body["warnings"][0].as_str().unwrap_or("");
+ assert!(warning.contains("does not switch the embedder"), "{body}");
+ assert!(warning.contains("re-index"), "{body}");
+ assert!(warning.contains(".elser_model_2"), "{body}");
+ }
+
+ #[tokio::test]
+ async fn put_mapping_without_an_embedder_request_has_no_warnings_key() {
+ let state = test_state();
+ let router = crate::router::build_es_compat_router(state.clone());
+ let created = router
+ .clone()
+ .oneshot(
+ Request::put("/embed-quiet")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ json!({"mappings": {"properties": {"body": {"type": "text"}}}}).to_string(),
+ ))
+ .expect("request"),
+ )
+ .await
+ .expect("create");
+ assert!(created.status().is_success());
+ let created_bytes = to_bytes(created.into_body(), usize::MAX).await.unwrap();
+ let created_body: Value = serde_json::from_slice(&created_bytes).unwrap();
+ assert!(
+ created_body.get("warnings").is_none(),
+ "no mismatch must leave the create JSON unchanged: {created_body}"
+ );
+ let mapped = router
+ .oneshot(
+ Request::put("/embed-quiet/_mapping")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ json!({"properties": {
+ "note": {"type": "semantic_text", "inference_id": "lexical"}
+ }})
+ .to_string(),
+ ))
+ .expect("request"),
+ )
+ .await
+ .expect("mapping");
+ let status = mapped.status();
+ let bytes = to_bytes(mapped.into_body(), usize::MAX).await.unwrap();
+ let body: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
+ assert!(status.is_success(), "{status} {body}");
+ assert!(
+ body.get("warnings").is_none(),
+ "a matching inference_id must not add warnings: {body}"
+ );
+ assert_eq!(body["acknowledged"], true, "{body}");
+ }
+
#[tokio::test]
async fn create_index_accepts_a_lookup_runtime_field_over_http() {
let (status, body) = create_index_with_runtime_type("lookup").await;
@@ -3300,7 +3379,12 @@ pub async fn put_mapping(
return ApiError::new(xerj_common::XerjError::from(error)).into_response();
}
}
- return Json(json!({ "acknowledged": true })).into_response();
+ let warnings = embedder_warnings(&state, &body);
+ let mut payload = json!({ "acknowledged": true });
+ if !warnings.is_empty() {
+ payload["warnings"] = json!(warnings);
+ }
+ return Json(payload).into_response();
}
// Publication begins only after every deterministic candidate has passed.
@@ -3323,7 +3407,30 @@ pub async fn put_mapping(
}
}
- Json(json!({ "acknowledged": true })).into_response()
+ let warnings = embedder_warnings(&state, &body);
+ let mut payload = json!({ "acknowledged": true });
+ if !warnings.is_empty() {
+ payload["warnings"] = json!(warnings);
+ }
+ Json(payload).into_response()
+}
+
+/// The server embedder a mapping's `inference_id` is compared with. Identity
+/// failure yields no warning rather than a failed create: the mapping still
+/// does not switch the embedder, and the index-open guard remains the hard
+/// check.
+fn embedder_warnings(state: &AppState, body: &Value) -> Vec<String> {
+ let Ok(identity) = state.engine.embedding_execution_identity() else {
+ return Vec::new();
+ };
+ let embedding = &state.engine.config().embedding;
+ let resolved = crate::embed_warning::ResolvedEmbedder {
+ backend: identity.backend,
+ neural_model: embedding.neural_model.clone(),
+ proxy_model: embedding.default_model.clone(),
+ proxy_endpoint: embedding.default_endpoint.clone(),
+ };
+ crate::embed_warning::semantic_embedder_warnings(body, &resolved)
}
fn semantic_mapping_contract(
@@ -21100,9 +21207,10 @@ fn es_properties_to_fields(properties: &Value) -> Result<Vec<FieldConfig>, Strin
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("{field_name}_vector"));
- // Allow a mapping to point at an external inference endpoint/model
- // (`inference_id` mirrors ES 8.x semantic_text wiring); when absent
- // the engine falls back to the zero-config built-in embedder.
+ // `inference_id` / `model_id` / `inference_endpoint` are stored so a
+ // mapping round-trips. Ingest does not read them: the server's
+ // `--embed-mode` embeds every document, and create/put mapping
+ // warns when these keys name a different embedder (#1612).
let endpoint = field_def
.get("inference_endpoint")
.and_then(Value::as_str)
diff --git a/engine/crates/xerj-api/src/lib.rs b/engine/crates/xerj-api/src/lib.rs
index cff45e259..406b07eee 100644
--- a/engine/crates/xerj-api/src/lib.rs
+++ b/engine/crates/xerj-api/src/lib.rs
@@ -70,6 +70,7 @@ pub mod authz;
pub mod binary_protocol;
pub mod cat;
pub mod cluster_shard;
+pub mod embed_warning;
pub mod error;
pub mod es_compat;
pub mod extract;
diff --git a/engine/crates/xerj-api/src/responses.rs b/engine/crates/xerj-api/src/responses.rs
index 0c9aabbf8..88814092e 100644
--- a/engine/crates/xerj-api/src/responses.rs
+++ b/engine/crates/xerj-api/src/responses.rs
@@ -82,6 +82,10 @@ pub struct EsIndexResponse {
pub acknowledged: bool,
pub shards_acknowledged: bool,
pub index: String,
+ /// Present only when a mapping asked for an embedder this server will not
+ /// use. Empty stays off the wire so existing clients see the same JSON.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub warnings: Vec<String>,
}
impl EsIndexResponse {
@@ -90,6 +94,7 @@ impl EsIndexResponse {
acknowledged: true,
shards_acknowledged: true,
index: index.into(),
+ warnings: Vec::new(),
}
}
}
diff --git a/engine/crates/xerj-autoindex/src/catalog.rs b/engine/crates/xerj-autoindex/src/catalog.rs
index 2f75545a0..dab87cdf5 100644
--- a/engine/crates/xerj-autoindex/src/catalog.rs
+++ b/engine/crates/xerj-autoindex/src/catalog.rs
@@ -168,7 +168,7 @@ pub fn catalog_mapping() -> Value {
pub const GOTCHAS: &[&str] = &[
"hybrid search: use {\"query\":{\"hybrid\":{\"queries\":[…]}}} ONLY — retriever.rrf is a silent stub and rank.rrf is ignored on this engine",
"indexes CREATED by this build stem English text fields (Snowball, via a declared `analysis.analyzer.default`) whenever the profiler marked the dataset's prose semantic — plurals and inflections match (`databases` ↔ `database`) on `text`/`semantic_text` fields of THOSE indexes; keyword fields are never stemmed, and indexes an older build created keep the unstemmed `standard` analyzer (analysis settings are fixed at index creation — reindex into a fresh index to change them)",
- "semantic_text fields are embedded server-side: the DEFAULT is the built-in LEXICAL feature-hash embedder (384-dim hybrid lexical+vector, NOT neural) — start the server with `--embed-mode neural` (built-in Candle BERT), `--embed-mode proxy`, or an ONNX-enabled build with `--embed-mode onnx-experimental --onnx-model … --onnx-tokenizer …` for neural semantics; ONNX runs only when this map shows a semantic_field, and its first real inference is confirmed by the server activation log",
+ "semantic_text fields are embedded server-side: the DEFAULT is the built-in LEXICAL feature-hash embedder (384-dim hybrid lexical+vector, NOT neural) — start the server with `--embed-mode neural` (built-in Candle BERT), `--embed-mode proxy`, or an ONNX-enabled build with `--embed-mode onnx-experimental --onnx-model … --onnx-tokenizer …` for neural semantics; ONNX runs only when this map shows a semantic_field, and its first real inference is confirmed by the server activation log. `--embed-mode` is fixed per index at ingest: changing it does not re-embed documents already written; re-index into a new index. A mapping inference_id or inference_endpoint does not switch the embedder",
"semantic queries ignore _source filtering and return the ~8KB *_vector field in _source — strip client-side",
"exact filters use TOP-LEVEL keyword fields (term on .keyword subfields returns 0 hits on this engine)",
"all dates are normalized to RFC3339 UTC millis; mappings use strict_date_optional_time||epoch_millis",
diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rs
index 3f751adea..6983f9642 100644
--- a/engine/crates/xerj-autoindex/src/esclient.rs
+++ b/engine/crates/xerj-autoindex/src/esclient.rs
@@ -1151,6 +1151,15 @@ pub struct EmbeddingExecutionIdentity {
pub resumable: bool,
#[serde(default)]
pub non_resumable_reason: Option<String>,
+ /// Advisory neural-ingest sample from `GET /v1/embedding/identity`.
+ /// Absent on older servers and on every non-neural backend. Not part of
+ /// `identity_sha256`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ingest_probe_bytes: Option<u64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ingest_probe_passages: Option<u32>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ingest_probe_millis: Option<u64>,
}
/// Ensure an autoindex index-create body pins the index to a single WAL shard.
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index f79ee3d8d..17bbe24b9 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -33,6 +33,7 @@ pub mod init;
/// `--label`: ingest-time labelling through the node's `/_decide` (#1062).
pub mod label;
pub mod memory_cli;
+pub mod neural_cost;
pub mod objsource;
#[cfg(test)]
mod objsource_minio_tests;
@@ -1648,6 +1649,43 @@ fn finish_generated_progress(pr: &Progress, code: i32, summary: &Value, skipped_
);
}
+fn inventory_size_map(inventory: &content::Inventory) -> HashMap<&str, u64> {
+ inventory
+ .keys
+ .iter()
+ .zip(inventory.files.iter())
+ .map(|(key, file)| (key.as_str(), file.size))
+ .collect()
+}
+
+/// Print a neural embedding-time estimate when the server measured one.
+///
+/// Best-effort: a failed identity read does not fail the run (the later pin
+/// still does, on a real semantic ingest) and never invents a rate. Zero
+/// source bytes print nothing, including a lexical corpus.
+fn note_neural_ingest_cost(
+ es: &Es,
+ source_bytes: u64,
+ kind: neural_cost::SourceBytes,
+ pr: &Progress,
+) {
+ if source_bytes == 0 {
+ return;
+ }
+ let identity = match es.embedding_execution_identity() {
+ Ok(identity) => identity,
+ Err(error) => {
+ pr.note(&format!(
+ "embedding cost: could not read GET /v1/embedding/identity ({error}); no time estimate printed"
+ ));
+ return;
+ }
+ };
+ if let Some(message) = neural_cost::note(&identity, source_bytes, kind) {
+ pr.note(&message);
+ }
+}
+
#[allow(clippy::too_many_arguments)] // cutover threads the whole run context
fn begin_non_graph_generation(
es: &Es,
@@ -1775,6 +1813,9 @@ fn begin_non_graph_generation(
semantic_contract: "disabled-no-semantic-fields-v1".into(),
resumable: true,
non_resumable_reason: None,
+ ingest_probe_bytes: None,
+ ingest_probe_passages: None,
+ ingest_probe_millis: None,
}
};
@@ -7963,6 +8004,18 @@ fn run_index_report_inner(
tally,
)?;
let unchanged = serde_json::to_value(&plan)? == serde_json::to_value(&base.plan)?;
+ let sizes = inventory_size_map(&inventory);
+ let changed_bytes = if unchanged {
+ 0
+ } else {
+ neural_cost::changed_semantic_source_bytes(&base.plan.files, &plan, &sizes)
+ };
+ note_neural_ingest_cost(
+ &es,
+ changed_bytes,
+ neural_cost::SourceBytes::SemanticSource,
+ &pr,
+ );
println!("{}", serde_json::to_string_pretty(&plan)?);
// stdout is the RESULT, stderr is PROGRESS: the projection above is
// the result, this explanation is progress and goes out through the
@@ -8083,6 +8136,15 @@ fn run_index_report_inner(
finish_generated_progress(&pr, code, &summary, dataless_skipped);
return Ok((code, Some(summary)));
}
+ let sizes = inventory_size_map(&inventory);
+ let changed_bytes =
+ neural_cost::changed_semantic_source_bytes(&base.plan.files, &plan, &sizes);
+ note_neural_ingest_cost(
+ &es,
+ changed_bytes,
+ neural_cost::SourceBytes::SemanticSource,
+ &pr,
+ );
begin_non_graph_generation(
&es,
&mut journal,
@@ -8732,6 +8794,14 @@ fn run_index_report_inner(
return Ok((0, None));
}
+ let sizes = inventory_size_map(&inventory);
+ note_neural_ingest_cost(
+ &es,
+ neural_cost::semantic_source_bytes(&plan, &sizes),
+ neural_cost::SourceBytes::SemanticSource,
+ &pr,
+ );
+
if cfg.dry_run {
println!("{}", serde_json::to_string_pretty(&plan)?);
pr.note("(dry run — nothing indexed)");
@@ -12671,6 +12741,9 @@ mod duplicate_integration_tests {
semantic_contract: "semantic_text-derived-vector.v1".into(),
resumable: false,
non_resumable_reason: Some("identity is derived from the model name".into()),
+ ingest_probe_bytes: None,
+ ingest_probe_passages: None,
+ ingest_probe_millis: None,
};
// All comparable fields match → the identity did NOT change.
let err = ensure_embedding_execution_unchanged_and_resumable(
diff --git a/engine/crates/xerj-autoindex/src/neural_cost.rs b/engine/crates/xerj-autoindex/src/neural_cost.rs
new file mode 100644
index 000000000..8a621276f
--- /dev/null
+++ b/engine/crates/xerj-autoindex/src/neural_cost.rs
@@ -0,0 +1,358 @@
+//! Neural ingest time estimate.
+//!
+//! The number comes from a probe the server measured (`GET /v1/embedding/identity`)
+//! and the bytes of source that will be embedded. This module never substitutes
+//! a constant rate. No probe, a zero probe, a non-neural backend, or zero
+//! source bytes produces no estimate.
+
+use std::collections::{HashMap, HashSet};
+
+use crate::esclient::EmbeddingExecutionIdentity;
+use crate::estimate::{human_bytes, human_secs};
+use crate::state::{FileAssignment, Plan};
+
+/// What `source_bytes` counts, so the sentence does not call a whole NDJSON
+/// file "the embedded text".
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SourceBytes {
+ /// Files whose assignment feeds a dataset with a `semantic_text` field.
+ SemanticSource,
+ /// A `xerj index` NDJSON file. Embedded fields may be a subset of it.
+ NdjsonFileUpperBound,
+}
+
+/// The note to print before a neural ingest, or `None` when there is nothing
+/// honest to say (not neural, or no source bytes).
+pub fn note(
+ identity: &EmbeddingExecutionIdentity,
+ source_bytes: u64,
+ kind: SourceBytes,
+) -> Option<String> {
+ if identity.backend != "neural" || source_bytes == 0 {
+ return None;
+ }
+ let probe = match (
+ identity.ingest_probe_bytes,
+ identity.ingest_probe_passages,
+ identity.ingest_probe_millis,
+ ) {
+ (Some(bytes), Some(passages), Some(millis)) if bytes > 0 && passages > 0 && millis > 0 => {
+ Some((bytes, passages, millis))
+ }
+ _ => None,
+ };
+ let subject = match kind {
+ SourceBytes::SemanticSource => format!(
+ "{} of source that feeds a semantic_text dataset",
+ human_bytes(source_bytes)
+ ),
+ SourceBytes::NdjsonFileUpperBound => format!(
+ "{} of NDJSON (an upper bound on embedded text, not a count of semantic_text fields)",
+ human_bytes(source_bytes)
+ ),
+ };
+ let sticky = "The embedding mode is fixed per index at ingest: changing --embed-mode does not \
+ re-embed documents already written; re-index into a new index. The faster default \
+ is lexical (`xerj --embed-mode lexical`, or omit the flag).";
+ let body = match probe {
+ Some((bytes, passages, millis)) => {
+ let seconds = estimate_seconds(source_bytes, bytes, millis);
+ let per_passage = bytes / u64::from(passages);
+ let rate = (bytes as f64) * 1000.0 / (millis as f64);
+ format!(
+ "neural ingest: about {} to embed {subject}, from a measured probe of {passages} \
+ passages / {} ({per_passage} bytes each) in {millis} ms ({} of that probe text \
+ per second, timed after one untimed warmup passage). Embedding time only: chunk \
+ overlap is not included, and denser text such as source code can take longer. {sticky}",
+ human_secs(seconds),
+ human_bytes(bytes),
+ human_bytes(rate.round() as u64),
+ )
+ }
+ None => format!(
+ "neural ingest: {subject}. The embedding rate was not measured on this process, so \
+ no time estimate is printed. Neural embedding is CPU-bound and much slower than the \
+ default lexical embedder. {sticky}"
+ ),
+ };
+ Some(body)
+}
+
+/// `source_bytes / (probe_bytes / (probe_millis / 1000))`.
+///
+/// Both inputs are measurements. The division is floating point only so a
+/// sub-second estimate can be printed; it does not introduce a rate the probe
+/// did not supply.
+pub fn estimate_seconds(source_bytes: u64, probe_bytes: u64, probe_millis: u64) -> f64 {
+ if probe_bytes == 0 || probe_millis == 0 {
+ return f64::NAN;
+ }
+ (source_bytes as f64) * (probe_millis as f64) / ((probe_bytes as f64) * 1000.0)
+}
+
+/// Sum of file sizes that feed a dataset with `semantic_field` set.
+///
+/// A file is counted once. A missing size is skipped, not replaced with a guess.
+pub fn semantic_source_bytes(plan: &Plan, sizes: &HashMap<&str, u64>) -> u64 {
+ let semantic = semantic_slugs(plan);
+ let mut total = 0u64;
+ for (key, assignment) in &plan.files {
+ if !feeds(&semantic, assignment) {
+ continue;
+ }
+ if let Some(size) = sizes.get(key.as_str()) {
+ total = total.saturating_add(*size);
+ }
+ }
+ total
+}
+
+/// Bytes of semantic-feeding files a reconcile will embed again.
+///
+/// Unchanged content (equal digests, already feeding a semantic dataset) is
+/// excluded: the generated path reuses it. A missing digest cannot prove
+/// reuse, so that file is counted.
+pub fn changed_semantic_source_bytes(
+ previous: &HashMap<String, FileAssignment>,
+ plan: &Plan,
+ sizes: &HashMap<&str, u64>,
+) -> u64 {
+ let semantic = semantic_slugs(plan);
+ let mut total = 0u64;
+ for (key, assignment) in &plan.files {
+ if !feeds(&semantic, assignment) {
+ continue;
+ }
+ let changed = match previous.get(key) {
+ None => true,
+ Some(prior) => match (&prior.content_digest, &assignment.content_digest) {
+ (Some(before), Some(after)) => before != after || !feeds(&semantic, prior),
+ _ => true,
+ },
+ };
+ if !changed {
+ continue;
+ }
+ if let Some(size) = sizes.get(key.as_str()) {
+ total = total.saturating_add(*size);
+ }
+ }
+ total
+}
+
+fn semantic_slugs(plan: &Plan) -> HashSet<&str> {
+ plan.datasets
+ .iter()
+ .filter(|dataset| dataset.semantic_field.is_some())
+ .map(|dataset| dataset.slug.as_str())
+ .collect()
+}
+
+fn feeds(semantic: &HashSet<&str>, assignment: &FileAssignment) -> bool {
+ assignment
+ .assignments
+ .iter()
+ .any(|(_, slug)| semantic.contains(slug.as_str()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::state::PlanDataset;
+
+ fn identity(backend: &str, probe: Option<(u64, u32, u64)>) -> EmbeddingExecutionIdentity {
+ let (bytes, passages, millis) = match probe {
+ Some((bytes, passages, millis)) => (Some(bytes), Some(passages), Some(millis)),
+ None => (None, None, None),
+ };
+ EmbeddingExecutionIdentity {
+ version: 1,
+ backend: backend.into(),
+ identity_sha256: "ab".repeat(32),
+ dimensions: Some(384),
+ semantic_contract: "semantic_text-derived-vector.v1".into(),
+ resumable: true,
+ non_resumable_reason: None,
+ ingest_probe_bytes: bytes,
+ ingest_probe_passages: passages,
+ ingest_probe_millis: millis,
+ }
+ }
+
+ #[test]
+ fn estimate_is_source_bytes_over_the_measured_rate() {
+ // 16_384 probe bytes in 1_000 ms is 16_384 B/s. 32_768 source bytes
+ // is exactly 2 seconds. No other rate is in the formula.
+ let seconds = estimate_seconds(32_768, 16_384, 1_000);
+ assert!((seconds - 2.0).abs() < 1e-9, "{seconds}");
+ }
+
+ #[test]
+ fn a_zero_probe_is_not_a_number() {
+ assert!(estimate_seconds(1_000, 0, 1_000).is_nan());
+ assert!(estimate_seconds(1_000, 1_000, 0).is_nan());
+ }
+
+ #[test]
+ fn neural_note_quotes_the_probe_and_points_at_lexical() {
+ let note = note(
+ &identity("neural", Some((16_384, 32, 1_000))),
+ 32_768,
+ SourceBytes::SemanticSource,
+ )
+ .expect("neural with a probe and source bytes");
+ assert!(note.contains("about 2.0 s"), "{note}");
+ assert!(note.contains("32 passages"), "{note}");
+ assert!(note.contains("16.0 KB"), "{note}");
+ assert!(note.contains("re-index"), "{note}");
+ assert!(note.contains("xerj --embed-mode lexical"), "{note}");
+ assert!(note.contains("fixed per index"), "{note}");
+ assert!(note.contains("warmup"), "{note}");
+ }
+
+ #[test]
+ fn an_unmeasured_neural_probe_does_not_invent_a_duration() {
+ for probe in [
+ None,
+ Some((0, 32, 1_000)),
+ Some((16_384, 0, 1_000)),
+ Some((16_384, 32, 0)),
+ ] {
+ let note = note(
+ &identity("neural", probe),
+ 32_768,
+ SourceBytes::SemanticSource,
+ )
+ .expect("still say the rate is unknown");
+ assert!(note.contains("not measured"), "{note}");
+ assert!(!note.contains("about "), "{note}");
+ assert!(note.contains("xerj --embed-mode lexical"), "{note}");
+ }
+ }
+
+ #[test]
+ fn non_neural_and_empty_corpora_say_nothing() {
+ let neural = identity("neural", Some((16_384, 32, 1_000)));
+ assert!(note(&neural, 0, SourceBytes::SemanticSource).is_none());
+ assert!(note(
+ &identity("lexical", Some((16_384, 32, 1_000))),
+ 32_768,
+ SourceBytes::SemanticSource
+ )
+ .is_none());
+ assert!(note(
+ &identity("proxy", None),
+ 32_768,
+ SourceBytes::NdjsonFileUpperBound
+ )
+ .is_none());
+ }
+
+ #[test]
+ fn ndjson_upper_bound_is_labeled_as_a_file_not_embedded_text() {
+ let note = note(
+ &identity("neural", Some((16_384, 32, 2_000))),
+ 16_384,
+ SourceBytes::NdjsonFileUpperBound,
+ )
+ .unwrap();
+ assert!(note.contains("upper bound"), "{note}");
+ assert!(note.contains("about 2.0 s"), "{note}");
+ }
+
+ fn assignment(slug: &str, digest: Option<&str>) -> FileAssignment {
+ FileAssignment {
+ rel: format!("{slug}.txt"),
+ path_id: String::new(),
+ is_symlink: Some(false),
+ family: "txtprose".into(),
+ gzip: false,
+ content_digest: digest.map(str::to_string),
+ assignments: vec![(None, slug.into())],
+ as_document: false,
+ }
+ }
+
+ fn sample_plan(files: Vec<(&str, &str, Option<&str>)>, semantic: bool) -> Plan {
+ Plan {
+ datasets: vec![PlanDataset {
+ slug: "docs".into(),
+ index: "ax-docs".into(),
+ family: "txtprose".into(),
+ group: None,
+ specs: Vec::new(),
+ time_field: None,
+ semantic_field: semantic.then(|| "body".into()),
+ text_analyzer: None,
+ scope: None,
+ sampled_records: 0,
+ file_count: files.len(),
+ }],
+ files: files
+ .into_iter()
+ .map(|(key, slug, digest)| (key.to_string(), assignment(slug, digest)))
+ .collect(),
+ ..Plan::default()
+ }
+ }
+
+ #[test]
+ fn semantic_bytes_count_each_feeding_file_once_and_skip_missing_sizes() {
+ let plan = sample_plan(
+ vec![
+ ("a", "docs", Some("1")),
+ ("b", "other", Some("2")),
+ ("c", "docs", Some("3")),
+ ],
+ true,
+ );
+ let sizes = HashMap::from([("a", 100u64), ("b", 9_000u64)]);
+ assert_eq!(semantic_source_bytes(&plan, &sizes), 100);
+ let lexical = sample_plan(vec![("a", "docs", Some("1"))], false);
+ assert_eq!(semantic_source_bytes(&lexical, &sizes), 0);
+ }
+
+ #[test]
+ fn changed_bytes_skip_an_unchanged_digest() {
+ let previous_plan = sample_plan(
+ vec![("a", "docs", Some("same")), ("b", "docs", Some("old"))],
+ true,
+ );
+ let next = sample_plan(
+ vec![
+ ("a", "docs", Some("same")),
+ ("b", "docs", Some("new")),
+ ("c", "docs", Some("fresh")),
+ ],
+ true,
+ );
+ let sizes = HashMap::from([("a", 10u64), ("b", 20u64), ("c", 30u64)]);
+ assert_eq!(
+ changed_semantic_source_bytes(&previous_plan.files, &next, &sizes),
+ 50
+ );
+ }
+
+ #[test]
+ fn a_missing_digest_is_counted_because_reuse_is_unproven() {
+ let previous_plan = sample_plan(vec![("a", "docs", None)], true);
+ let next = sample_plan(vec![("a", "docs", None)], true);
+ let sizes = HashMap::from([("a", 40u64)]);
+ assert_eq!(
+ changed_semantic_source_bytes(&previous_plan.files, &next, &sizes),
+ 40
+ );
+ }
+
+ #[test]
+ fn identity_json_keeps_probe_fields_optional() {
+ let bare = r#"{"version":1,"backend":"neural","identity_sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","dimensions":384,"semantic_contract":"semantic_text-derived-vector.v1","resumable":true}"#;
+ let parsed: EmbeddingExecutionIdentity = serde_json::from_str(bare).unwrap();
+ assert!(parsed.ingest_probe_millis.is_none());
+ let with = r#"{"version":1,"backend":"neural","identity_sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","semantic_contract":"semantic_text-derived-vector.v1","resumable":true,"ingest_probe_bytes":16384,"ingest_probe_passages":32,"ingest_probe_millis":1000}"#;
+ let parsed: EmbeddingExecutionIdentity = serde_json::from_str(with).unwrap();
+ assert_eq!(parsed.ingest_probe_millis, Some(1000));
+ let encoded = serde_json::to_string(&identity("lexical", None)).unwrap();
+ assert!(!encoded.contains("ingest_probe"), "{encoded}");
+ }
+}
diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rs
index eed7477b6..d549314d3 100644
--- a/engine/crates/xerj-common/src/config.rs
+++ b/engine/crates/xerj-common/src/config.rs
@@ -1547,6 +1547,22 @@ impl LogsConfig {
// ─────────────────────────────────────────────────────────────────────────────
+/// One measured neural-ingest sample. Advisory: it is not configuration,
+/// it is not serialized, and it is not part of the embedding identity.
+///
+/// Recorded once after the neural model loads. Autoindex turns it into a
+/// time estimate (`corpus bytes / (probe bytes / probe seconds)`). A missing
+/// probe means "not measured" — callers must not invent a rate.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct NeuralIngestProbe {
+ /// UTF-8 bytes of the timed passages.
+ pub bytes: u64,
+ /// Passages in the timed call.
+ pub passages: u32,
+ /// Wall time of that call, in milliseconds. Zero is not a measurement.
+ pub millis: u64,
+}
+
/// Embedding backend settings.
///
/// XERJ can embed `semantic_text` fields four ways, chosen by
@@ -1655,6 +1671,11 @@ pub struct EmbeddingConfig {
#[serde(skip)]
pub runtime_onnx_assets:
std::sync::Arc<std::sync::OnceLock<Result<EmbeddingAssetSnapshot, String>>>,
+ /// Neural ingest probe, shared by cloned configs (the server preloads
+ /// from a clone). `None` inside the cell means the probe ran and did not
+ /// produce a rate; an empty cell means it has not run. Not a setting.
+ #[serde(skip)]
+ pub neural_ingest_probe: std::sync::Arc<std::sync::OnceLock<Option<NeuralIngestProbe>>>,
}
#[derive(Debug, Clone)]
@@ -1689,6 +1710,7 @@ impl Default for EmbeddingConfig {
onnx_max_input_bytes_per_call: 8 * 1024 * 1024,
onnx_max_inflight_input_bytes: 32 * 1024 * 1024,
runtime_onnx_assets: std::sync::Arc::new(std::sync::OnceLock::new()),
+ neural_ingest_probe: std::sync::Arc::new(std::sync::OnceLock::new()),
}
}
}
diff --git a/engine/crates/xerj-common/src/types.rs b/engine/crates/xerj-common/src/types.rs
index 3e6f57d79..8eef7c709 100644
--- a/engine/crates/xerj-common/src/types.rs
+++ b/engine/crates/xerj-common/src/types.rs
@@ -396,8 +396,10 @@ impl Default for FieldOptions {
/// Optional embedding configuration attached to a field.
///
-/// When present, the engine calls the configured embedding service to
-/// automatically vectorise this field's text on ingest.
+/// When present, ingest vectorises this field with the server's
+/// `--embed-mode`. `endpoint` and `model` are recorded from a mapping's
+/// `inference_endpoint` / `inference_id` and are not consulted at ingest;
+/// a mismatch is a warning on the mapping response, not a different embedder.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EmbeddingConfig {
/// Override the global `embedding.default_endpoint`.
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index aeff700d8..00a4884e6 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -184,6 +184,15 @@ pub struct EmbeddingExecutionIdentity {
pub resumable: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub non_resumable_reason: Option<String>,
+ /// Measured neural-ingest probe. Advisory and omitted when unset.
+ /// Not part of [`Self::identity_sha256`]: a different machine or a
+ /// warmer CPU must still resume the same index. Zero is never sent.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ingest_probe_bytes: Option<u64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ingest_probe_passages: Option<u32>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub ingest_probe_millis: Option<u64>,
}
// ── Clustering types ─────────────────────────────────────────────────────────
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 668f3b3e5..7ca0d1535 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -39334,6 +39334,12 @@ pub(crate) fn embedding_execution_identity(
_ => unreachable!(),
};
let canonical = format!("{CONTRACT};backend={backend};{material}");
+ // The probe is a rate sample, not an input to the digest above. Folding
+ // it in would make every boot look like a different embedder.
+ let probe = (backend == "neural")
+ .then(|| cfg.neural_ingest_probe.get().copied().flatten())
+ .flatten()
+ .filter(|probe| probe.bytes > 0 && probe.passages > 0 && probe.millis > 0);
Ok(crate::engine::EmbeddingExecutionIdentity {
// This is the WIRE/API version the autoindex client pins on
// (esclient.rs requires == 1); it is NOT the on-disk migration marker.
@@ -39348,6 +39354,9 @@ pub(crate) fn embedding_execution_identity(
semantic_contract: CONTRACT.to_string(),
resumable,
non_resumable_reason: reason,
+ ingest_probe_bytes: probe.map(|probe| probe.bytes),
+ ingest_probe_passages: probe.map(|probe| probe.passages),
+ ingest_probe_millis: probe.map(|probe| probe.millis),
})
}
@@ -39662,6 +39671,31 @@ mod embedding_identity_tests {
let encoded = serde_json::to_string(&identity).unwrap();
assert!(!encoded.contains("endpoint"));
assert!(!encoded.contains("path"));
+ assert!(
+ !encoded.contains("ingest_probe"),
+ "an unmeasured probe must stay off the wire: {encoded}"
+ );
+ assert!(identity.ingest_probe_millis.is_none());
+ }
+
+ /// A stored probe must not move `identity_sha256`. The digest is what
+ /// resume pins; a rate sample changes every boot.
+ #[test]
+ fn an_ingest_probe_does_not_change_the_identity_digest() {
+ let cfg = xerj_common::config::EmbeddingConfig::default();
+ let before = embedding_execution_identity(&cfg).unwrap();
+ cfg.neural_ingest_probe
+ .set(Some(xerj_common::config::NeuralIngestProbe {
+ bytes: 16_384,
+ passages: 32,
+ millis: 800,
+ }))
+ .unwrap();
+ let after = embedding_execution_identity(&cfg).unwrap();
+ assert_eq!(before.identity_sha256, after.identity_sha256);
+ assert!(after.ingest_probe_bytes.is_none());
+ let encoded = serde_json::to_string(&after).unwrap();
+ assert!(!encoded.contains("ingest_probe"), "{encoded}");
}
#[test]
@@ -40118,6 +40152,35 @@ mod embedding_identity_tests {
let encoded = serde_json::to_string(&identity).unwrap();
assert!(!encoded.contains(&first_dir.path().to_string_lossy().into_owned()));
assert!(!encoded.contains("MiniLM"), "{encoded}");
+ assert!(
+ !encoded.contains("ingest_probe"),
+ "a neural identity with no probe must omit the rate fields: {encoded}"
+ );
+
+ let probed = neural(&first_dir);
+ probed
+ .neural_ingest_probe
+ .set(Some(xerj_common::config::NeuralIngestProbe {
+ bytes: 16_384,
+ passages: 32,
+ millis: 800,
+ }))
+ .unwrap();
+ let with_probe = embedding_execution_identity(&probed).unwrap();
+ assert_eq!(
+ with_probe.identity_sha256, identity.identity_sha256,
+ "the probe is not an embedder input"
+ );
+ assert_eq!(with_probe.ingest_probe_bytes, Some(16_384));
+ assert_eq!(with_probe.ingest_probe_passages, Some(32));
+ assert_eq!(with_probe.ingest_probe_millis, Some(800));
+ let probed_json = serde_json::to_string(&with_probe).unwrap();
+ assert!(
+ probed_json.contains("\"ingest_probe_millis\":800"),
+ "{probed_json}"
+ );
+ assert!(!probed_json.contains("endpoint"), "{probed_json}");
+ assert!(!probed_json.contains(&first_dir.path().to_string_lossy().into_owned()));
// Same bytes in a DIFFERENT directory → same identity. This is the
// property the fix exists for: it is a different `NeuralConfig`, so it
@@ -40716,6 +40779,7 @@ pub fn ensure_neural_ready(cfg: &xerj_common::config::EmbeddingConfig) -> Result
xerj_ai::neural::startup_failure_message(&neural_cfg.model_id, &error),
)));
}
+ record_neural_ingest_probe(cfg);
Ok(())
}
#[cfg(not(feature = "neural"))]
@@ -40724,6 +40788,36 @@ pub fn ensure_neural_ready(cfg: &xerj_common::config::EmbeddingConfig) -> Result
}
}
+/// Time one ingest-shaped batch and store it on `cfg` for identity reporting.
+///
+/// A probe failure does not fail startup: the model loaded, and autoindex
+/// prints "not measured" rather than a made-up rate. The cell is filled
+/// either way so a later index open does not probe again.
+#[cfg(feature = "neural")]
+fn record_neural_ingest_probe(cfg: &xerj_common::config::EmbeddingConfig) {
+ if cfg.neural_ingest_probe.get().is_some() {
+ return;
+ }
+ let neural_cfg = configured_neural_config(cfg);
+ let Some(embedder) = xerj_ai::Embedder::preload_neural(&neural_cfg).ok() else {
+ let _ = cfg.neural_ingest_probe.set(None);
+ return;
+ };
+ let probe = xerj_ai::neural::measure_ingest_probe(&embedder);
+ match probe {
+ Some(probe) => info!(
+ bytes = probe.bytes,
+ passages = probe.passages,
+ millis = probe.millis,
+ "neural ingest probe (512-character passages, one untimed warmup excluded)"
+ ),
+ None => warn!(
+ "neural ingest probe did not produce a rate; autoindex will not print a time estimate"
+ ),
+ }
+ let _ = cfg.neural_ingest_probe.set(probe);
+}
+
/// Construct the built-in neural embedder when compiled in.
///
/// The model is loaded here (and at server startup via [`ensure_neural_ready`]).
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index 49f963be2..f58db54d3 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -383,6 +383,10 @@ fn help_text(feedback: bool) -> String {
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20running and fail every ingest, and it does not write\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20lexical vectors. Restart with: xerj --embed-mode lexical\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Or set HF_ENDPOINT to a Hub mirror and start again.\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20The mode is fixed per index at ingest time. Documents keep\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20the vectors written when they were indexed. Changing\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20--embed-mode does not re-embed an existing index; re-index.\n\
+ \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Lexical is the fast default.\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20proxy external OpenAI-compatible /v1/embeddings endpoint\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20auto proxy if embedding.default_endpoint is set, else lexical\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20onnx-experimental local all-MiniLM-L6-v2-compatible FP32\n\
@@ -1242,6 +1246,28 @@ fn warn_dormant_overrides(cfg: &Config) {
}
}
+/// `--embed-mode` (and `embedding.mode`) is an ingest-time property of every
+/// document. `auto` is the default and stays quiet; an explicit mode is the
+/// case that reads as a cheap switch.
+fn embed_mode_fixed_at_ingest_warning(mode: &str) -> Option<String> {
+ let trimmed = mode.trim();
+ if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("auto") {
+ return None;
+ }
+ Some(format!(
+ "embedding.mode={trimmed} is fixed per index at ingest time. Documents keep the vectors \
+ written when they were indexed. Changing --embed-mode does not re-embed an existing \
+ index; re-index into a new index. The fast default is lexical (`xerj --embed-mode lexical`, \
+ or omit the flag)."
+ ))
+}
+
+fn warn_embed_mode_is_fixed_at_ingest(cfg: &Config) {
+ if let Some(message) = embed_mode_fixed_at_ingest_warning(&cfg.embedding.mode) {
+ warn!("{message}");
+ }
+}
+
fn init_tracing(logging: &xerj_common::config::LoggingConfig) {
let mut filter = EnvFilter::try_from_env("XERJ_LOG")
.or_else(|_| EnvFilter::try_from_env("RUST_LOG"))
@@ -2043,6 +2069,53 @@ fn index_help_text(feedback: bool) -> String {
)
}
+/// `xerj index` on a neural node: say how long embedding this file might take,
+/// from the startup probe, before the ingest loop starts.
+async fn warn_neural_cli_index(engine: &Engine, index: &xerj_engine::Index, file_bytes: u64) {
+ let Ok(identity) = engine.embedding_execution_identity() else {
+ return;
+ };
+ if identity.backend != "neural" {
+ return;
+ }
+ let schema = index.schema().await;
+ let embeds = schema.fields.iter().any(|field| field.embedding.is_some());
+ if !embeds {
+ eprintln!(
+ "warning: embedding.mode=neural is fixed per index at ingest time. This index has no \
+ semantic_text field, so {} of NDJSON is not an embedding-time estimate. Changing \
+ --embed-mode does not re-embed documents already written; re-index. The faster \
+ default is `xerj --embed-mode lexical` (or omit the flag).",
+ xerj_autoindex::estimate::human_bytes(file_bytes)
+ );
+ return;
+ }
+ let wire = xerj_autoindex::esclient::EmbeddingExecutionIdentity {
+ version: identity.version,
+ backend: identity.backend,
+ identity_sha256: identity.identity_sha256,
+ dimensions: identity.dimensions,
+ semantic_contract: identity.semantic_contract,
+ resumable: identity.resumable,
+ non_resumable_reason: identity.non_resumable_reason,
+ ingest_probe_bytes: identity.ingest_probe_bytes,
+ ingest_probe_passages: identity.ingest_probe_passages,
+ ingest_probe_millis: identity.ingest_probe_millis,
+ };
+ match xerj_autoindex::neural_cost::note(
+ &wire,
+ file_bytes,
+ xerj_autoindex::neural_cost::SourceBytes::NdjsonFileUpperBound,
+ ) {
+ Some(message) => eprintln!("warning: {message}"),
+ None => eprintln!(
+ "warning: embedding.mode=neural is fixed per index at ingest time. Changing \
+ --embed-mode does not re-embed documents already written; re-index. The faster \
+ default is `xerj --embed-mode lexical` (or omit the flag)."
+ ),
+ }
+}
+
/// Run the `xerj index` subcommand — direct NDJSON → engine ingest.
///
/// Memory-maps the file, finds newline boundaries in parallel via rayon,
@@ -2091,6 +2164,7 @@ async fn run_cli_index(cmd: IndexCmdArgs) -> Result<()> {
// Tracing after config so the [logging] format applies (RC4-W4 item 6).
init_tracing(&cfg.logging);
warn_dormant_overrides(&cfg);
+ warn_embed_mode_is_fixed_at_ingest(&cfg);
cfg.tls.enabled = false;
cfg.auth.enabled = false;
cfg.cluster.enabled = false;
@@ -2131,6 +2205,7 @@ async fn run_cli_index(cmd: IndexCmdArgs) -> Result<()> {
let file =
std::fs::File::open(&cmd.file).with_context(|| format!("open {}", cmd.file.display()))?;
let file_size = file.metadata().map(|m| m.len()).unwrap_or(0);
+ warn_neural_cli_index(&engine, &index, file_size).await;
let mmap: memmap2::Mmap = unsafe { memmap2::Mmap::map(&file) }
.with_context(|| format!("mmap {}", cmd.file.display()))?;
// Advise the kernel that we'll read sequentially and that we plan
@@ -3031,7 +3106,7 @@ mod neural_startup_tests {
#[cfg(test)]
mod help_text_tests {
- use super::{auth_disabled_line, help_text};
+ use super::{auth_disabled_line, embed_mode_fixed_at_ingest_warning, help_text};
/// #1840: `--embed-mode neural` must say the model loads at startup and
/// that a failed download refuses to start, with the lexical command.
@@ -3070,6 +3145,38 @@ mod help_text_tests {
);
}
+ /// #1612: the flag is an ingest-time property. Help must say so next to
+ /// the mode list, including the re-index requirement.
+ #[test]
+ fn embed_mode_help_says_the_mode_is_fixed_at_ingest() {
+ let help = help_text(true);
+ assert!(
+ help.contains("fixed per index at ingest"),
+ "help must say the mode is fixed per index:\n{help}"
+ );
+ assert!(
+ help.contains("does not re-embed"),
+ "help must say changing the flag does not re-embed:\n{help}"
+ );
+ assert!(
+ help.contains("re-index"),
+ "help must say a change requires a re-index:\n{help}"
+ );
+ }
+
+ #[test]
+ fn explicit_embed_mode_warns_that_it_is_fixed_at_ingest() {
+ let neural = embed_mode_fixed_at_ingest_warning("neural").unwrap();
+ assert!(neural.contains("fixed per index"));
+ assert!(neural.contains("re-index"));
+ assert!(neural.contains("xerj --embed-mode lexical"));
+ assert!(embed_mode_fixed_at_ingest_warning("auto").is_none());
+ assert!(embed_mode_fixed_at_ingest_warning(" ").is_none());
+ assert!(embed_mode_fixed_at_ingest_warning("lexical")
+ .unwrap()
+ .contains("lexical"));
+ }
+
/// A loopback `--insecure` boot says nothing off this host can connect,
/// then used to say anyone on the network can write. Those two lines
/// cannot both be true.
@@ -3844,6 +3951,7 @@ async fn async_main() -> Result<()> {
info!("xerj v{} starting", env!("CARGO_PKG_VERSION"));
warn_dormant_overrides(&cfg);
+ warn_embed_mode_is_fixed_at_ingest(&cfg);
// 3a. `server.bind_address` must be an IP literal — and must be rejected
// *here*, ahead of the two exposure checks that follow.
diff --git a/landing/llms-full.txt b/landing/llms-full.txt
index 953be5a49..b6aa6c508 100644
--- a/landing/llms-full.txt
+++ b/landing/llms-full.txt
@@ -185,13 +185,20 @@ Content types:
with `--embed-mode neural` — a built-in in-process BERT encoder (all-MiniLM-L6-v2)
that ships in the binary and auto-downloads its model (~90 MB) on first use, no
external service — or `--embed-mode proxy` (any OpenAI-compatible `/v1/embeddings`).
- You can also declare `semantic_text` with an external `inference_id` /
- `inference_endpoint`, or index your own vectors into a `dense_vector` field and use
- `knn`. Only describe output as neural when one of those modes is actually running.
+ You can index your own vectors into a `dense_vector` field and use `knn`.
+ A `semantic_text` mapping may set `inference_id`, `model_id`, or
+ `inference_endpoint`; those keys do not switch the embedder. Ingest uses the
+ server's `--embed-mode`, and create/put mapping returns a warning when the
+ mapping names a different one. Only describe output as neural when
+ `--embed-mode neural` or `--embed-mode proxy` is actually running.
* `--embed-mode` is a server-start flag that applies AT INGEST: a document keeps
the embedding produced by the mode in force when it was indexed. Switching
lexical → neural does not re-embed anything already indexed — you must
re-index. Decide before indexing your first corpus.
+ * Before a neural `xerj autoindex` ingest, the client prints an estimated
+ embedding time from a probe this server measured when the model loaded and
+ the bytes of files that feed a `semantic_text` dataset. No duration is
+ printed when that probe did not run. The figure is embedding time only.
* `--embed-mode neural` fetches its model over HTTPS from the HuggingFace Hub
(`sentence-transformers/all-MiniLM-L6-v2`: config.json, tokenizer.json,
model.safetensors, ~90 MB) into `~/.cache/huggingface` on first use, then runs
@@ -1066,7 +1073,11 @@ semantic_text:
making it `semantic`-query searchable with zero external config (built-in embedder).
- `dimensions`/`dims` overrides the embedder width (default 384). Similarity is cosine
(built-in embeddings are L2-normalised).
- - Optional `inference_id` / `inference_endpoint` route embedding to an external model.
+ - `inference_id` / `model_id` / `inference_endpoint` are accepted on the mapping
+ and the create/put mapping response warns when they name a different embedder
+ than the server is running. They do not route embedding to an external model.
+ An external model is `--embed-mode proxy` plus `embedding.default_endpoint`,
+ and that choice is fixed at ingest: changing it requires a re-index.
dense_vector:
- `dims` (required for meaningful kNN), `similarity` (default "cosine").