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(index): keep semantic vectors out of full-text indexes

bugeraf55577747b9
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 12e6ccb0c..198ab1cb3 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -1984,13 +1984,19 @@ impl Index {
let analyzer = mem
.default_analyzer()
.expect("standard analyzer always present");
+ let excluded_fts_fields = crate::memtable::semantic_derived_vector_fields(schema);
let p_t = std::time::Instant::now();
let analyzed: Vec<Vec<(String, Vec<xerj_fts::analyzer::Token>)>> = crate::ingest_pool()
.install(|| {
sources
.par_iter()
.map(|source| {
- crate::memtable::analyze_doc(source.as_ref(), schema, &analyzer)
+ crate::memtable::analyze_doc_excluding(
+ source.as_ref(),
+ schema,
+ &analyzer,
+ &excluded_fts_fields,
+ )
})
.collect()
});
@@ -2251,6 +2257,9 @@ impl Index {
let registry = Arc::clone(&self.registry);
let data_dir = self.data_dir.clone();
let field_configs = self.flush_signal.field_configs(&self.schema);
+ let excluded_fts_fields = self
+ .flush_signal
+ .semantic_derived_vector_fields(&self.schema);
let dataset_version = Arc::clone(&self.dataset_version);
let query_cache = Arc::clone(&self.query_cache);
let warm_caches = self.publish_warm_caches();
@@ -2278,6 +2287,7 @@ impl Index {
registry,
data_dir,
field_configs,
+ excluded_fts_fields,
on_drained,
warm_caches,
)
@@ -2499,9 +2509,12 @@ impl Index {
// memtable, writes the segment file + FTS index, swaps the snapshot,
// and checkpoints the WAL. The drained memtable is dropped, freeing
// all RAM.
- let field_configs = {
+ let (field_configs, excluded_fts_fields) = {
let schema = self.schema.read().await;
- build_fts_field_configs(&schema.schema)
+ (
+ build_fts_field_configs(&schema.schema),
+ crate::memtable::semantic_derived_vector_fields(&schema.schema),
+ )
};
// Explicit refresh: wait behind any in-flight concurrent flushes
// (semaphore has 4 permits) so the user-visible flush sees a
@@ -2522,6 +2535,7 @@ impl Index {
Arc::clone(&self.registry),
self.data_dir.clone(),
field_configs.clone(),
+ excluded_fts_fields.clone(),
|| {}, // serial refresh path — no permit to drop early
self.publish_warm_caches(),
)
@@ -2627,6 +2641,10 @@ impl Index {
let _ = field_configs_once.set(cfg.clone());
cfg
};
+ let excluded_fts_fields = {
+ let schema = self.schema.read().await;
+ crate::memtable::semantic_derived_vector_fields(&schema.schema)
+ };
let flush_signal_cb = Arc::clone(&self.flush_signal);
tokio::spawn(async move {
@@ -2649,6 +2667,7 @@ impl Index {
registry,
data_dir,
field_configs,
+ excluded_fts_fields,
on_drained,
warm_caches,
)
@@ -2853,9 +2872,12 @@ impl Index {
// Resolve per-field analyzer configs once for FTS rebuild. See
// `build_fts_field_configs` — keyword/numeric fields must use the
// `keyword` analyzer or the FST drops their values to stop-words.
- let field_configs = {
+ let (field_configs, excluded_fts_fields) = {
let schema = self.schema.read().await;
- build_fts_field_configs(&schema.schema)
+ (
+ build_fts_field_configs(&schema.schema),
+ crate::memtable::semantic_derived_vector_fields(&schema.schema),
+ )
};
// Kept for the legacy "if !text_fields.is_empty()" branch — empty
// here because the merge path now indexes ALL source fields, not
@@ -2955,6 +2977,7 @@ impl Index {
let store_for_task = Arc::clone(&self.store);
let registry_for_task = Arc::clone(&self.registry);
let field_configs_for_task = field_configs.clone();
+ let excluded_fts_fields_for_task = excluded_fts_fields.clone();
let segments_dir_for_task = segments_dir.clone();
let batch_for_task = batch;
let metas_for_task = metas;
@@ -3271,15 +3294,8 @@ impl Index {
Err(_) => continue,
};
let source = doc_value.get("_source").cloned().unwrap_or(Value::Null);
- let mut fields: HashMap<String, String> = HashMap::new();
- if let Some(obj) = source.as_object() {
- for (key, val) in obj {
- let text = extract_field_text(val);
- if !text.is_empty() {
- fields.insert(key.clone(), text);
- }
- }
- }
+ let fields =
+ extract_fts_fields_excluding(&source, &excluded_fts_fields_for_task);
fts_input.push((id_str, fields, source));
}
@@ -9803,9 +9819,12 @@ impl Index {
/// Flush the memtable to a new segment on disk, then build the FTS index.
pub async fn flush(&self) -> Result<()> {
- let field_configs = {
+ let (field_configs, excluded_fts_fields) = {
let schema = self.schema.read().await;
- build_fts_field_configs(&schema.schema)
+ (
+ build_fts_field_configs(&schema.schema),
+ crate::memtable::semantic_derived_vector_fields(&schema.schema),
+ )
};
// M5.15 — PARALLEL final flush.
//
@@ -9830,6 +9849,7 @@ impl Index {
let registry = Arc::clone(&self.registry);
let data_dir = self.data_dir.clone();
let field_configs = field_configs.clone();
+ let excluded_fts_fields = excluded_fts_fields.clone();
let warm_caches = self.publish_warm_caches();
shard_futures.push(tokio::spawn(async move {
let permit = sema.acquire_owned().await.ok();
@@ -9847,6 +9867,7 @@ impl Index {
registry,
data_dir,
field_configs,
+ excluded_fts_fields,
on_drained,
warm_caches,
)
@@ -10537,7 +10558,11 @@ fn read_doc_values_sidecar(
fn build_fts_field_configs(schema: &Schema) -> HashMap<String, xerj_fts::index::FieldIndexConfig> {
use xerj_fts::index::FieldIndexConfig;
let mut out = HashMap::new();
+ let excluded = crate::memtable::semantic_derived_vector_fields(schema);
for f in &schema.fields {
+ if excluded.contains(&f.name) {
+ continue;
+ }
let analyzer = match f.field_type {
FieldType::Text => "standard",
// Everything else is exact-match. We use the registered
@@ -10576,6 +10601,25 @@ fn extract_field_text(val: &Value) -> String {
}
}
+fn extract_fts_fields_excluding(
+ source: &Value,
+ excluded: &std::collections::HashSet<String>,
+) -> HashMap<String, String> {
+ let mut fields = HashMap::new();
+ if let Some(obj) = source.as_object() {
+ for (key, val) in obj {
+ if excluded.contains(key) {
+ continue;
+ }
+ let text = extract_field_text(val);
+ if !text.is_empty() {
+ fields.insert(key.clone(), text);
+ }
+ }
+ }
+ fields
+}
+
// ── Short-circuit count helper ───────────────────────────────────────────────
impl Index {
@@ -14879,6 +14923,7 @@ async fn do_flush_shard(
registry: Arc<AnalyzerRegistry>,
data_dir: PathBuf,
field_configs: HashMap<String, xerj_fts::index::FieldIndexConfig>,
+ excluded_fts_fields: std::collections::HashSet<String>,
on_drained: impl FnOnce() + Send + 'static,
// Publish-time cache warm (see `warm_segment_at_publish`): the index's
// read-path caches, threaded through because this is a free fn without
@@ -14983,7 +15028,10 @@ async fn do_flush_shard(
} else {
std::sync::Arc::new(serde_json::Value::Null)
};
- let fields = crate::memtable::extract_text_fields_from(&val);
+ let fields = crate::memtable::extract_text_fields_from_excluding(
+ &val,
+ &excluded_fts_fields,
+ );
(doc_id.clone(), fields, val)
})
.collect()
@@ -15269,6 +15317,19 @@ impl SyncFlushCoord {
*self.field_configs_cache.write() = Some(cfg.clone());
cfg
}
+
+ fn semantic_derived_vector_fields(
+ &self,
+ schema: &Arc<RwLock<ManagedSchema>>,
+ ) -> std::collections::HashSet<String> {
+ let Some(rt) = self.rt.as_ref() else {
+ return std::collections::HashSet::new();
+ };
+ rt.block_on(async {
+ let guard = schema.read().await;
+ crate::memtable::semantic_derived_vector_fields(&guard.schema)
+ })
+ }
}
// ── Free helpers ──────────────────────────────────────────────────────────────
diff --git a/engine/crates/xerj-engine/src/memtable.rs b/engine/crates/xerj-engine/src/memtable.rs
index 4cde205c3..da8e2e6ec 100644
--- a/engine/crates/xerj-engine/src/memtable.rs
+++ b/engine/crates/xerj-engine/src/memtable.rs
@@ -84,9 +84,19 @@ struct MemEntry {
/// flush (`drain_with_sources`, `drain`) and by the rare
/// `get_source` query path — neither is on the hot ingest loop.
pub fn extract_text_fields_from(source: &Value) -> HashMap<String, String> {
+ extract_text_fields_from_excluding(source, &std::collections::HashSet::new())
+}
+
+pub fn extract_text_fields_from_excluding(
+ source: &Value,
+ excluded: &std::collections::HashSet<String>,
+) -> HashMap<String, String> {
let mut out = HashMap::new();
if let Some(obj) = source.as_object() {
for (key, val) in obj {
+ if excluded.contains(key) {
+ continue;
+ }
let text = extract_text_value(val);
if !text.is_empty() {
out.insert(key.clone(), text);
@@ -3139,9 +3149,17 @@ impl Default for FtsMemtable {
///
/// Hoisted out of `FtsMemtable::insert` so [`analyze_doc`] can run the
/// identical walk outside the shard write lock.
-fn collect_text_fields(v: &Value, prefix: &str, out: &mut HashMap<String, String>) {
+fn collect_text_fields(
+ v: &Value,
+ prefix: &str,
+ out: &mut HashMap<String, String>,
+ excluded: &std::collections::HashSet<String>,
+) {
if let Value::Object(obj) = v {
for (k, val) in obj {
+ if prefix.is_empty() && excluded.contains(k) {
+ continue;
+ }
let path = if prefix.is_empty() {
k.clone()
} else {
@@ -3157,7 +3175,7 @@ fn collect_text_fields(v: &Value, prefix: &str, out: &mut HashMap<String, String
out.insert(path.clone(), t);
}
}
- collect_text_fields(val, &path, out);
+ collect_text_fields(val, &path, out, excluded);
}
Value::Array(arr) => {
let joined: String = arr
@@ -3191,6 +3209,16 @@ pub fn analyze_doc(
source: &Value,
schema: &Schema,
analyzer: &AnalyzerPipeline,
+) -> Vec<(String, Vec<Token>)> {
+ let excluded = semantic_derived_vector_fields(schema);
+ analyze_doc_excluding(source, schema, analyzer, &excluded)
+}
+
+pub fn analyze_doc_excluding(
+ source: &Value,
+ schema: &Schema,
+ analyzer: &AnalyzerPipeline,
+ excluded: &std::collections::HashSet<String>,
) -> Vec<(String, Vec<Token>)> {
let mut text_fields: HashMap<String, String> = HashMap::new();
@@ -3209,7 +3237,7 @@ pub fn analyze_doc(
// Also index any string-valued field not in the schema (dynamic
// mapping) — see `collect_text_fields`.
if source.is_object() {
- collect_text_fields(source, "", &mut text_fields);
+ collect_text_fields(source, "", &mut text_fields, excluded);
}
text_fields
@@ -3221,6 +3249,94 @@ pub fn analyze_doc(
.collect()
}
+/// Exact internal fields generated from semantic embedding mappings.
+///
+/// This is schema-derived: similarly named user fields are unaffected unless
+/// an embedding config explicitly designates them as its target.
+pub fn semantic_derived_vector_fields(schema: &Schema) -> std::collections::HashSet<String> {
+ let mut excluded = std::collections::HashSet::new();
+ for field in &schema.fields {
+ let Some(embedding) = &field.embedding else {
+ continue;
+ };
+ let target = embedding
+ .target_field
+ .clone()
+ .unwrap_or_else(|| format!("{}_vector", field.name));
+ excluded.insert(target.clone());
+ excluded.insert(format!("{target}_chunks"));
+ }
+ excluded
+}
+
+#[cfg(test)]
+mod semantic_derived_vector_exclusion_tests {
+ use super::*;
+ use serde_json::json;
+ use xerj_common::types::{EmbeddingConfig, FieldConfig, FieldType};
+
+ #[test]
+ fn derives_default_and_custom_targets_without_suffix_guessing() {
+ let mut schema = Schema::empty();
+ schema
+ .add_field(
+ FieldConfig::new("body", FieldType::Text).with_embedding(EmbeddingConfig {
+ endpoint: None,
+ model: None,
+ target_field: None,
+ }),
+ )
+ .unwrap();
+ schema
+ .add_field(FieldConfig::new("summary", FieldType::Text).with_embedding(
+ EmbeddingConfig {
+ endpoint: None,
+ model: None,
+ target_field: Some("summary_model_output".to_string()),
+ },
+ ))
+ .unwrap();
+ schema
+ .add_field(FieldConfig::new("user_vector", FieldType::Text))
+ .unwrap();
+
+ let excluded = semantic_derived_vector_fields(&schema);
+ assert_eq!(
+ excluded,
+ std::collections::HashSet::from([
+ "body_vector".to_string(),
+ "body_vector_chunks".to_string(),
+ "summary_model_output".to_string(),
+ "summary_model_output_chunks".to_string(),
+ ])
+ );
+
+ let source = json!({
+ "body": "cash and equivalents",
+ "page": 7,
+ "user_vector": [1.0, 2.0],
+ "body_vector_backup": [3.0, 4.0],
+ "body_vector": [0.1, 0.2],
+ "body_vector_chunks": [[0.1, 0.2], [0.3, 0.4]],
+ "summary_model_output": [0.5, 0.6],
+ "summary_model_output_chunks": [[0.5, 0.6], [0.7, 0.8]]
+ });
+ let fields = extract_text_fields_from_excluding(&source, &excluded);
+ assert_eq!(fields.get("page").map(String::as_str), Some("7"));
+ assert_eq!(
+ fields.get("user_vector").map(String::as_str),
+ Some("1.0 2.0")
+ );
+ assert_eq!(
+ fields.get("body_vector_backup").map(String::as_str),
+ Some("3.0 4.0")
+ );
+ for derived in &excluded {
+ assert!(!fields.contains_key(derived));
+ }
+ }
+}
+
/// Extract a string value from a JSON value for text indexing.
fn extract_text_value(val: &Value) -> String {
match val {
diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rs
index ed8042035..16d958db7 100644
--- a/engine/crates/xerj-engine/tests/integration.rs
+++ b/engine/crates/xerj-engine/tests/integration.rs
@@ -19,6 +19,102 @@ fn make_engine(dir: &TempDir) -> Engine {
Engine::new(config).expect("engine::new")
}
+#[tokio::test]
+async fn test_semantic_vectors_stay_stored_but_not_fts_indexed_after_merge_and_reopen() {
+ fn collect_names(dir: &std::path::Path, out: &mut Vec<String>) {
+ for entry in std::fs::read_dir(dir).unwrap() {
+ let entry = entry.unwrap();
+ if entry.file_type().unwrap().is_dir() {
+ collect_names(&entry.path(), out);
+ } else {
+ out.push(entry.file_name().to_string_lossy().into_owned());
+ }
+ }
+ }
+
+ async fn assert_queries(idx: &xerj_engine::Index) {
+ let semantic = idx
+ .search(&make_search(json!({
+ "semantic": {"field": "content", "query": "quarterly liquidity", "k": 10}
+ })))
+ .await
+ .unwrap();
+ assert_eq!(semantic.total.value, 2);
+ assert!(semantic.hits.iter().all(|hit| {
+ hit.source.get("custom_embedding").is_some()
+ && hit.source.get("custom_embedding_chunks").is_some()
+ }));
+
+ let lexical = idx
+ .search(&make_search(json!({
+ "match": {"content": "working capital"}
+ })))
+ .await
+ .unwrap();
+ assert_eq!(lexical.total.value, 2);
+
+ let page = idx
+ .search(&make_search(json!({
+ "term": {"page": 7}
+ })))
+ .await
+ .unwrap();
+ assert_eq!(page.total.value, 1);
+ }
+
+ let dir = TempDir::new().unwrap();
+ let mut schema = Schema::empty();
+ let mut content = FieldConfig::new("content", FieldType::Text);
+ content.options.dimensions = Some(16);
+ content.options.similarity = Some("cosine".to_string());
+ content.embedding = Some(xerj_common::types::EmbeddingConfig {
+ endpoint: None,
+ model: None,
+ target_field: Some("custom_embedding".to_string()),
+ });
+ schema.fields.push(content);
+ schema
+ .fields
+ .push(FieldConfig::new("page", FieldType::Long));
+
+ {
+ let engine = make_engine(&dir);
+ engine.create_index("sem-fts-exclusion", schema).unwrap();
+ let idx = engine.get_index("sem-fts-exclusion").unwrap();
+ let long_body = format!(
+ "quarterly liquidity evidence {}",
+ "cash assets liabilities working capital ".repeat(80)
+ );
+
+ idx.index_document(Some("a".into()), json!({"content": long_body, "page": 7}))
+ .await
+ .unwrap();
+ idx.refresh().await.unwrap();
+ idx.index_document(Some("b".into()), json!({"content": long_body, "page": 8}))
+ .await
+ .unwrap();
+ idx.refresh().await.unwrap();
+ idx.force_merge(1).await.unwrap();
+
+ assert_queries(&idx).await;
+ }
+
+ let mut names = Vec::new();
+ collect_names(dir.path(), &mut names);
+ assert!(names.iter().any(|name| name.ends_with(".content.fst")));
+ assert!(names.iter().any(|name| name.ends_with(".page.fst")));
+ assert!(!names
+ .iter()
+ .any(|name| name.ends_with(".custom_embedding.fst")));
+ assert!(!names
+ .iter()
+ .any(|name| name.ends_with(".custom_embedding_chunks.fst")));
+
+ let reopened = make_engine(&dir);
+ let idx = reopened.get_index("sem-fts-exclusion").unwrap();
+ assert_queries(&idx).await;
+}
+
fn make_search(query_json: Value) -> SearchRequest {
parse_request(&json!({ "query": query_json, "size": 100 })).expect("parse_request")
}