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.

storage: don't persist derived semantic_text vectors in stored _source (#1122, #2433) (#2471)

xerj-org0eaa8af9bdb5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a128ee403..59afe4aa9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Upgrade notes
+
+- **Stored `semantic_text` vectors** (PR
+ [#2471](https://github.com/xerj-org/xerj/pull/2471)). Segments written by
+ this build no longer store the vectors the built-in lexical embedder
+ derives for a `semantic_text` field (`<target>` and `<target>_chunks`) in
+ the stored `_source`; readers rebuild them from the text. Older segments
+ open unchanged and lose their stored copy when a merge rewrites them.
+ There is no format-marker change, so an older binary still opens the
+ index, but it reads those rows without vectors: `_source` lacks them and
+ semantic and kNN recall on them drops until the index is reindexed.
+ Before downgrading, restart this build with
+ `XERJ_STORE_SEMANTIC_VECTORS=1` and run `POST /{index}/_forcemerge?max_num_segments=1`
+ on each index with a `semantic_text` field: with the variable set, flushes
+ store full vectors and a merge writes them back for rows stored without
+ them. Vectors from neural, ONNX or proxy embedders, and vectors supplied
+ by the caller, were always kept and are not affected.
+
### Added
- `xerj sessions import --format claude-code --input FILE --output NEW.jsonl`
@@ -77,6 +95,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[#1170](https://github.com/xerj-org/xerj/issues/1170); the issue stays
open).
+### Changed
+
+- A `semantic_text` field with the built-in lexical embedder no longer
+ stores its embedding twice. The pooled and per-passage vectors were kept
+ in the stored `_source` as well as in the vector index; the columnar
+ stored encoder now drops them when they rebuild bit-exactly from the
+ text, and every reader (`_source`, `GET`, kNN, reindex, snapshot)
+ rebuilds them, so responses are unchanged. On a 6,000-document test the
+ segment file went from 20.1 MB to 1.8 MB and the index from 3.67x to
+ 1.63x its source size. The saving is on disk; the HNSW graph in memory is
+ unchanged. Sections under 128 documents keep their vectors.
+ `XERJ_STORE_SEMANTIC_VECTORS=1` turns this off; see the upgrade note
+ (part of [#1122](https://github.com/xerj-org/xerj/issues/1122) and
+ [#2433](https://github.com/xerj-org/xerj/issues/2433)).
+
### Fixed
- A segment merge's output-write step (doc-values build, stored encode, FTS
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index 874b41fc3..20c6a4b15 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -7807,6 +7807,7 @@ dependencies = [
"dashmap",
"fst",
"lz4_flex",
+ "memchr",
"memmap2",
"rayon",
"roaring",
@@ -7818,6 +7819,7 @@ dependencies = [
"tokio",
"tracing",
"uuid",
+ "xerj-ai",
"xerj-common",
"xxhash-rust",
"zstd",
diff --git a/engine/crates/xerj-ai/src/lib.rs b/engine/crates/xerj-ai/src/lib.rs
index 812b74a71..3cb4ff0cd 100644
--- a/engine/crates/xerj-ai/src/lib.rs
+++ b/engine/crates/xerj-ai/src/lib.rs
@@ -38,6 +38,7 @@ pub mod microbatch;
pub mod neural;
#[cfg(feature = "onnx-experimental")]
pub mod onnx;
+pub mod semantic_lexical;
pub use chunker::{Chunk, TextChunker};
pub use embed::{EmbeddingProxy, EmbeddingProxyConfig};
diff --git a/engine/crates/xerj-ai/src/semantic_lexical.rs b/engine/crates/xerj-ai/src/semantic_lexical.rs
new file mode 100644
index 000000000..9948a8b38
--- /dev/null
+++ b/engine/crates/xerj-ai/src/semantic_lexical.rs
@@ -0,0 +1,205 @@
+//! The exact chunk + embed + pool recipe `semantic_text` uses with the
+//! built-in lexical embedder.
+//!
+//! It lives here, not in the engine, so the stored-section codec can rebuild
+//! the derived vectors from the text instead of persisting them in every
+//! stored `_source` (#1122, #2433). Ingest and regeneration both call these
+//! functions, so a regenerated vector is bit-identical to the ingested one.
+//! The codec only drops a vector after re-deriving it and comparing bits.
+//! Changing anything here changes what old stripped segments rehydrate to,
+//! so bump `stored_codec::derived_vectors::MARKER_LEXICAL_V1` if you do.
+
+use crate::chunker::TextChunker;
+use crate::local::local_embed;
+
+/// Default chunk size (characters) for auto-embed-on-ingest chunking.
+/// `EmbeddingConfig` has no per-field chunk parameter yet, so this is a
+/// sensible fixed default (roughly a paragraph).
+pub const SEMANTIC_CHUNK_SIZE: usize = 512;
+/// Default overlap (characters) between consecutive chunks.
+pub const SEMANTIC_CHUNK_OVERLAP: usize = 64;
+
+/// The chunker used by the auto-embed-on-ingest path.
+pub fn semantic_chunker() -> TextChunker {
+ TextChunker::new(SEMANTIC_CHUNK_SIZE, SEMANTIC_CHUNK_OVERLAP)
+}
+
+/// L2-normalize each input vector, mean-pool across all of them, then
+/// re-normalize the pooled result. Produces a unit-norm vector of the same
+/// dimensionality as the inputs (empty input => empty vec). Vectors whose
+/// length differs from the first are skipped.
+pub fn mean_pool_normalize(vectors: &[Vec<f32>]) -> Vec<f32> {
+ let dims = match vectors.first() {
+ Some(v) => v.len(),
+ None => return Vec::new(),
+ };
+ let mut acc = vec![0.0f32; dims];
+ let mut used = 0usize;
+ for v in vectors {
+ if v.len() != dims {
+ continue;
+ }
+ let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
+ if norm > 0.0 {
+ for (a, x) in acc.iter_mut().zip(v.iter()) {
+ *a += x / norm;
+ }
+ used += 1;
+ }
+ }
+ if used > 0 {
+ let inv = 1.0 / used as f32;
+ for a in acc.iter_mut() {
+ *a *= inv;
+ }
+ }
+ // Re-normalize the pooled vector to unit length.
+ let norm = acc.iter().map(|x| x * x).sum::<f32>().sqrt();
+ if norm > 0.0 {
+ for a in acc.iter_mut() {
+ *a /= norm;
+ }
+ }
+ acc
+}
+
+/// Chunk `text` and embed each overlapping chunk with the built-in *local*
+/// embedder, returning one unit-norm vector per passage. Short text
+/// (<= chunk_size) produces a single chunk, so the result is
+/// `vec![local_embed(text, dims)]`.
+pub fn local_chunk_vectors(text: &str, dims: usize) -> Vec<Vec<f32>> {
+ let chunks = semantic_chunker().chunk(text, None);
+ if chunks.len() <= 1 {
+ return vec![local_embed(text, dims)];
+ }
+ chunks.iter().map(|c| local_embed(&c.text, dims)).collect()
+}
+
+/// A pooled vector plus, for multi-passage text, the per-passage vectors.
+pub type LexicalSemanticVectors = (Vec<f32>, Option<Vec<Vec<f32>>>);
+
+/// The vectors ingest persists for one lexical `semantic_text` value: the
+/// pooled vector, plus the per-passage vectors when there is more than one
+/// passage. Mirrors `apply_semantic_embeddings_batch`: one passage is used
+/// as-is, several are mean-pooled and re-normalized. `None` for `dims == 0`.
+pub fn lexical_semantic_vectors(text: &str, dims: usize) -> Option<LexicalSemanticVectors> {
+ if dims == 0 {
+ return None;
+ }
+ let mut chunks: Vec<Vec<f32>> = local_chunk_vectors(text, dims)
+ .into_iter()
+ .filter(|v| !v.is_empty())
+ .collect();
+ match chunks.len() {
+ 0 => None,
+ 1 => chunks.pop().map(|pooled| (pooled, None)),
+ _ => {
+ let pooled = mean_pool_normalize(&chunks);
+ Some((pooled, Some(chunks)))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn short_text_is_one_unpooled_passage() {
+ let (pooled, chunks) = lexical_semantic_vectors("a short passage", 16).unwrap();
+ assert!(chunks.is_none());
+ assert_eq!(pooled, local_embed("a short passage", 16));
+ }
+
+ #[test]
+ fn long_text_pools_its_passages() {
+ let text = "lorem ipsum dolor sit amet ".repeat(60);
+ let (pooled, chunks) = lexical_semantic_vectors(&text, 32).unwrap();
+ let chunks = chunks.expect("long text has several passages");
+ assert!(chunks.len() > 1);
+ assert_eq!(pooled, mean_pool_normalize(&chunks));
+ assert!(lexical_semantic_vectors(&text, 0).is_none());
+ }
+
+ /// FNV-1a 64 over the f32 bit patterns of the pooled vector, then each
+ /// passage vector (none for single-passage text).
+ fn fingerprint((pooled, chunks): &LexicalSemanticVectors) -> u64 {
+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;
+ let mut feed = |v: &[f32]| {
+ for f in v {
+ for b in f.to_bits().to_le_bytes() {
+ h ^= u64::from(b);
+ h = h.wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ }
+ // Separator so passage boundaries are part of the hash.
+ h ^= 0xff;
+ h = h.wrapping_mul(0x0000_0100_0000_01b3);
+ };
+ feed(pooled);
+ for c in chunks.iter().flatten() {
+ feed(c);
+ }
+ h
+ }
+
+ /// Stored segments drop these vectors and rebuild them on read, tagged
+ /// `lexical-v1` (#1122/#2433). If tokenization, case folding, Unicode
+ /// tables (a toolchain bump), hashing or chunking change their output,
+ /// already-written segments would read back different vectors than the
+ /// HNSW index holds. A change here needs a new marker version, not a
+ /// re-pinned hash.
+ #[test]
+ fn lexical_v1_vectors_are_pinned() {
+ let long_mixed = "Grüße aus Köln. Ünïcödé façade naïve café. Ελληνικά κείμενα. \
+ Кириллица текст. 日本語のテキスト。中文文本。한국어 텍스트. \
+ עברית العربية हिन्दी ไทย. İstanbul ß Dž fi Ⅻ 𝔘𝔫𝔦𝔠𝔬𝔡𝔢 🚀🎉 "
+ .repeat(12);
+ let corpus: Vec<(&str, String, usize)> = vec![
+ (
+ "ascii",
+ "Quarterly revenue grew in the storage ledger".into(),
+ 32,
+ ),
+ (
+ "latin1",
+ "Grüße aus Köln — façade, naïve café, ÆØÅ æøå".into(),
+ 32,
+ ),
+ ("turkic", "İstanbul ISTANBUL istanbul ıi Iİ".into(), 16),
+ ("sharp_s", "STRASSE straße Straße ß ẞ".into(), 16),
+ (
+ "greek_cyrillic",
+ "ΣΊΣΥΦΟΣ σίσυφος Ελληνικά — Москва МОСКВА ёЁ".into(),
+ 64,
+ ),
+ ("cjk", "日本語のテキスト 中文文本 한국어 텍스트".into(), 64),
+ ("rtl_indic_thai", "עברית العربية हिन्दी ไทย".into(), 32),
+ ("compat_marks", "Dž fi Ⅻ e\u{301} é Å Å 𝔘𝔫𝔦𝔠𝔬𝔡𝔢".into(), 32),
+ ("emoji_digits", "🚀🎉 👩‍👩‍👧 ١٢٣ 456 123".into(), 16),
+ ("multi_passage_mixed", long_mixed, 32),
+ ];
+ let got: Vec<(&str, u64)> = corpus
+ .iter()
+ .map(|(name, text, dims)| {
+ let v = lexical_semantic_vectors(text, *dims).unwrap();
+ (*name, fingerprint(&v))
+ })
+ .collect();
+ let multi = lexical_semantic_vectors(&corpus[9].1, 32).unwrap();
+ assert!(multi.1.as_ref().is_some_and(|c| c.len() > 1));
+ let want: &[(&str, u64)] = &[
+ ("ascii", 0xb18dc7157381c097),
+ ("latin1", 0x5c3d6b7e97441622),
+ ("turkic", 0xdbd5eb2aec430f62),
+ ("sharp_s", 0x2ddf8010c6cf313d),
+ ("greek_cyrillic", 0x67d0ea0cf16331cc),
+ ("cjk", 0xf2f4de163e1b3b89),
+ ("rtl_indic_thai", 0x08493924a0bb30aa),
+ ("compat_marks", 0x36bc49586424f6e8),
+ ("emoji_digits", 0x40d6b03c9056dd2b),
+ ("multi_passage_mixed", 0x2337850d5df9865d),
+ ];
+ assert_eq!(got, want, "lexical-v1 embeddings drifted");
+ }
+}
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index c5838d838..23aa05e92 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -2306,9 +2306,10 @@ mod flush_publication_recovery_tests {
}
}
- /// #2427: a query the segment FTS declines (here a clause on a field no
- /// document has, the shape the multi-index code-search CLI sends) walks
- /// every cold segment through the brute stored scan. That scan decoded
+ /// #2427: a query the segment FTS declines (here a `range` should-clause
+ /// on a field no document has; #2467 lets the FTS skip unmapped
+ /// term/phrase leaves, but not `range`/`exists`) walks every cold
+ /// segment through the brute stored scan. That scan decoded
/// every column — on a semantic_text corpus ~85% embedding companions —
/// although the page can only observe the `_source` includes plus the
/// fields the query reads. With an include list the cold decode must
@@ -2369,7 +2370,7 @@ mod flush_publication_recovery_tests {
"query": {"bool": {
"should": [
{"match": {"body": "needle"}},
- {"match_phrase": {"defs": "no such field"}}
+ {"range": {"defs": {"gte": "a"}}}
],
"minimum_should_match": 1
}},
@@ -14095,6 +14096,29 @@ impl Index {
.map(|chunk| chunk.into_iter().map(|i| ids[i].clone()).collect())
.collect()
}
+ // #1122/#2433: at the target count, a forcemerge under
+ // XERJ_STORE_SEMANTIC_VECTORS still rewrites each segment that
+ // holds rows stored without their derived semantic vectors, so
+ // the documented pre-downgrade `_forcemerge` restores them on an
+ // index that is already one segment.
+ Some(_) if xerj_storage::stored_codec::derived_vectors::store_vectors_opt_out() => {
+ let segments_dir = self.data_dir.join("segments");
+ segments_snapshot_init
+ .iter()
+ .filter(|meta| {
+ let Ok(reader) = SegmentReader::open(segments_dir.join(&meta.seg_path))
+ else {
+ return false;
+ };
+ matches!(
+ reader.section(SectionType::Stored),
+ Ok(Some(raw)) if xerj_storage::stored_codec::stored_has_derived_rows(raw)
+ .unwrap_or(false)
+ )
+ })
+ .map(|meta| vec![meta.id.clone()])
+ .collect()
+ }
Some(_) => Vec::new(),
None => policy.select_merges(&segments_snapshot_init),
};
@@ -14755,7 +14779,13 @@ impl Index {
}
};
let stored_bytes =
- match xerj_storage::stored_codec::decode_stored(stored_bytes_raw) {
+ // #1122/#2433: keep stripped semantic vectors
+ // stripped (the merged encode would only
+ // re-derive and drop them again), unless
+ // XERJ_STORE_SEMANTIC_VECTORS restores them.
+ match xerj_storage::stored_codec::decode_stored_for_rewrite(
+ stored_bytes_raw,
+ ) {
Ok(b) => b,
Err(e) => {
tracing::error!(
@@ -58313,12 +58343,12 @@ fn scored_fast_plan(
}
}
-/// Default chunk size (characters) for auto-embed-on-ingest chunking.
-/// `EmbeddingConfig` has no per-field chunk parameter yet, so this is a
-/// sensible fixed default (roughly a paragraph).
-const SEMANTIC_CHUNK_SIZE: usize = 512;
-/// Default overlap (characters) between consecutive chunks.
-const SEMANTIC_CHUNK_OVERLAP: usize = 64;
+// #1122/#2433: the lexical chunk/embed/pool recipe lives in xerj-ai so the
+// stored-section codec can regenerate the derived vectors bit-identically
+// instead of persisting them in every stored `_source`.
+#[cfg(test)]
+use xerj_ai::semantic_lexical::SEMANTIC_CHUNK_SIZE;
+use xerj_ai::semantic_lexical::{local_chunk_vectors, mean_pool_normalize, semantic_chunker};
/// Select one order-preserving caller-side embedding window. One oversized
/// document-field job remains whole so the planner always makes progress.
@@ -58658,67 +58688,6 @@ mod semantic_embedding_window_tests {
}
}
-/// The chunker used by the auto-embed-on-ingest path.
-fn semantic_chunker() -> xerj_ai::TextChunker {
- xerj_ai::TextChunker::new(SEMANTIC_CHUNK_SIZE, SEMANTIC_CHUNK_OVERLAP)
-}
-
-/// L2-normalize each input vector, mean-pool across all of them, then
-/// re-normalize the pooled result. Produces a unit-norm vector of the same
-/// dimensionality as the inputs (empty input => empty vec). Vectors whose
-/// length differs from the first are skipped.
-fn mean_pool_normalize(vectors: &[Vec<f32>]) -> Vec<f32> {
- let dims = match vectors.first() {
- Some(v) => v.len(),
- None => return Vec::new(),
- };
- let mut acc = vec![0.0f32; dims];
- let mut used = 0usize;
- for v in vectors {
- if v.len() != dims {
- continue;
- }
- let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
- if norm > 0.0 {
- for (a, x) in acc.iter_mut().zip(v.iter()) {
- *a += x / norm;
- }
- used += 1;
- }
- }
- if used > 0 {
- let inv = 1.0 / used as f32;
- for a in acc.iter_mut() {
- *a *= inv;
- }
- }
- // Re-normalize the pooled vector to unit length.
- let norm = acc.iter().map(|x| x * x).sum::<f32>().sqrt();
- if norm > 0.0 {
- for a in acc.iter_mut() {
- *a /= norm;
- }
- }
- acc
-}
-
-/// Chunk `text` and embed each overlapping chunk with the built-in *local*
-/// embedder, returning one unit-norm vector per passage. Short text
-/// (<= chunk_size) produces a single chunk, so the result is
-/// `vec![local_embed(text, dims)]`. This is the per-chunk primitive used by
-/// the auto-embed-on-ingest path to persist passage vectors for max-sim
-/// semantic scoring.
-fn local_chunk_vectors(text: &str, dims: usize) -> Vec<Vec<f32>> {
- let chunks = semantic_chunker().chunk(text, None);
- if chunks.len() <= 1 {
- return vec![xerj_ai::local::local_embed(text, dims)];
- }
- chunks
- .iter()
- .map(|c| xerj_ai::local::local_embed(&c.text, dims))
- .collect()
-}
-
/// Chunk `text` and mean-pool the per-chunk *local* embeddings into a single
/// unit-norm vector of length `dims`. Short text (<= chunk_size) produces a
/// single chunk, so the result is exactly `local_embed(text, dims)` — a no-op
diff --git a/engine/crates/xerj-engine/tests/semantic_vectors_not_stored.rs b/engine/crates/xerj-engine/tests/semantic_vectors_not_stored.rs
new file mode 100644
index 000000000..14aeabd94
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/semantic_vectors_not_stored.rs
@@ -0,0 +1,246 @@
+//! #1122 / #2433: the vectors the built-in lexical embedder derives for a
+//! `semantic_text` field are not persisted in the stored `_source`. The
+//! segment keeps the text and passage metadata; every reader gets the
+//! vectors rebuilt bit-identically, before and after flush, merge and
+//! reopen.
+
+use serde_json::{json, Value};
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_common::types::{FieldConfig, FieldType, Schema};
+use xerj_engine::Engine;
+use xerj_query::parse_request;
+use xerj_storage::{SectionType, SegmentReader};
+
+const INDEX: &str = "sem-derived";
+const WORDS: &[&str] = &[
+ "liquidity",
+ "quarterly",
+ "revenue",
+ "storage",
+ "vector",
+ "merge",
+ "segment",
+ "harbor",
+ "orchard",
+ "glacier",
+ "copper",
+ "lantern",
+ "meadow",
+ "compiler",
+ "kernel",
+ "ledger",
+];
+
+fn make_engine(dir: &TempDir) -> Engine {
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ Engine::new(config).expect("engine::new")
+}
+
+fn schema() -> Schema {
+ let mut schema = Schema::empty();
+ let mut content = FieldConfig::new("content", FieldType::Text);
+ content.options.dimensions = Some(32);
+ content.options.similarity = Some("cosine".to_string());
+ content.embedding = Some(xerj_common::types::EmbeddingConfig {
+ endpoint: None,
+ model: None,
+ target_field: Some("content_vector".to_string()),
+ });
+ schema.fields.push(content);
+ schema.fields.push(FieldConfig::new("n", FieldType::Long));
+ schema
+}
+
+fn text(i: usize) -> String {
+ let base: Vec<&str> = (0..12)
+ .map(|k| WORDS[(i * 7 + k * 3) % WORDS.len()])
+ .collect();
+ let base = base.join(" ");
+ if i.is_multiple_of(10) {
+ // Several passages: exercises `<target>_chunks`.
+ format!("doc {i} {}", format!("{base} ").repeat(20))
+ } else {
+ format!("doc {i} {base}")
+ }
+}
+
+async fn bulk(engine: &Engine, range: std::ops::Range<usize>) {
+ let mut body = String::new();
+ for i in range {
+ body.push_str(&format!(
+ "{{\"index\":{{\"_index\":\"{INDEX}\",\"_id\":\"{i}\"}}}}\n"
+ ));
+ body.push_str(&serde_json::to_string(&json!({"content": text(i), "n": i})).unwrap());
+ body.push('\n');
+ }
+ let result = xerj_engine::bulk::process_bulk(engine, None, &body).await;
+ assert!(
+ !result.errors,
+ "{:?}",
+ result.items.iter().find(|i| i.error.is_some())
+ );
+}
+
+fn seg_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
+ for entry in std::fs::read_dir(dir).unwrap() {
+ let path = entry.unwrap().path();
+ if path.is_dir() {
+ seg_files(&path, out);
+ } else if path.extension().is_some_and(|ext| ext == "seg") {
+ out.push(path);
+ }
+ }
+}
+
+/// Every columnar stored section on disk: vectors absent, marker present.
+fn assert_segments_stripped(dir: &TempDir) {
+ let mut files = Vec::new();
+ seg_files(dir.path(), &mut files);
+ assert!(!files.is_empty(), "no segment written");
+ let mut columnar = 0;
+ for path in files {
+ let reader = SegmentReader::open(&path).unwrap();
+ let Some(raw) = reader.section(SectionType::Stored).unwrap() else {
+ continue;
+ };
+ // Small sections stay row-oriented LZ4 and keep their vectors.
+ let Some(names) = xerj_storage::stored_codec::stored_v2_source_column_names(raw).unwrap()
+ else {
+ continue;
+ };
+ columnar += 1;
+ assert!(
+ names.iter().any(|n| n == "content_vector"),
+ "virtual column listed"
+ );
+ let preserved = xerj_storage::stored_codec::decode_stored_preserving_derived(raw).unwrap();
+ let preserved = String::from_utf8(preserved).unwrap();
+ assert!(
+ !preserved.contains("\"content_vector\":"),
+ "{path:?} stores vectors"
+ );
+ assert!(!preserved.contains("\"content_vector_chunks\":"));
+ assert!(preserved.contains(r#""derived":"lexical-v1""#));
+ let full = xerj_storage::stored_codec::decode_stored(raw).unwrap();
+ let full = String::from_utf8(full).unwrap();
+ assert!(
+ full.contains("\"content_vector\":"),
+ "decode rebuilds vectors"
+ );
+ assert!(full.contains("\"content_vector_chunks\":"));
+ assert!(
+ !full.contains(r#""derived""#),
+ "marker never reaches readers"
+ );
+ }
+ assert!(columnar > 0, "no columnar stored section to check");
+}
+
+async fn snapshot(idx: &xerj_engine::Index, ids: &[usize]) -> Vec<Value> {
+ let mut out = Vec::new();
+ for id in ids {
+ out.push(idx.get_document(&id.to_string()).await.unwrap().unwrap());
+ }
+ out
+}
+
+async fn semantic_hits(idx: &xerj_engine::Index) -> Vec<(String, f32, Value)> {
+ let request = parse_request(&json!({
+ "query": {"semantic": {"field": "content", "query": "quarterly liquidity ledger", "k": 10}},
+ "size": 10,
+ "_source": true
+ }))
+ .unwrap();
+ let response = idx.search(&request).await.unwrap();
+ response
+ .hits
+ .iter()
+ .map(|hit| (hit.id.clone(), hit.score, hit.source.clone()))
+ .collect()
+}
+
+async fn knn_top(idx: &xerj_engine::Index, vector: &Value) -> String {
+ let request = parse_request(&json!({
+ "query": {"knn": {"field": "content_vector", "query_vector": vector, "k": 3, "num_candidates": 50}},
+ "size": 3
+ }))
+ .unwrap();
+ idx.search(&request).await.unwrap().hits[0].id.clone()
+}
+
+fn assert_same_hits(got: &[(String, f32, Value)], want: &[(String, f32, Value)], step: &str) {
+ let ids = |hits: &[(String, f32, Value)]| hits.iter().map(|h| h.0.clone()).collect::<Vec<_>>();
+ assert_eq!(ids(got), ids(want), "{step} changed semantic ranking");
+ for (g, w) in got.iter().zip(want) {
+ assert!(
+ (g.1 - w.1).abs() < 1e-4,
+ "{step} changed a score: {g:?} vs {w:?}"
+ );
+ assert_eq!(g.2, w.2, "{step} changed a hit source");
+ }
+}
+
+#[tokio::test]
+async fn lexical_semantic_vectors_are_rebuilt_not_stored() {
+ let dir = TempDir::new().unwrap();
+ let probe = [0usize, 1, 10, 137, 250, 1999];
+ let engine = make_engine(&dir);
+ engine.create_index(INDEX, schema()).unwrap();
+ let idx = engine.get_index(INDEX).unwrap();
+
+ bulk(&engine, 0..1000).await;
+ bulk(&engine, 1000..2000).await;
+ let before_docs = snapshot(&idx, &probe).await;
+ for doc in &before_docs {
+ assert_eq!(doc["content_vector"].as_array().unwrap().len(), 32);
+ }
+ assert!(before_docs[0]["content_vector_chunks"].is_array());
+ let before_hits = semantic_hits(&idx).await;
+ assert!(!before_hits.is_empty());
+
+ idx.flush().await.unwrap();
+ assert_segments_stripped(&dir);
+ assert_eq!(
+ snapshot(&idx, &probe).await,
+ before_docs,
+ "flush changed a document"
+ );
+ assert_same_hits(&semantic_hits(&idx).await, &before_hits, "flush");
+ assert_eq!(
+ knn_top(&idx, &before_docs[3]["content_vector"]).await,
+ "137"
+ );
+
+ bulk(&engine, 2000..2600).await;
+ idx.flush().await.unwrap();
+ idx.force_merge(1).await.unwrap();
+ assert_segments_stripped(&dir);
+ assert_eq!(
+ snapshot(&idx, &probe).await,
+ before_docs,
+ "merge changed a document"
+ );
+ let merged_hits = semantic_hits(&idx).await;
+ drop(idx);
+ drop(engine);
+
+ let reopened = make_engine(&dir);
+ let idx = reopened.get_index(INDEX).unwrap();
+ assert_eq!(
+ snapshot(&idx, &probe).await,
+ before_docs,
+ "reopen changed a document"
+ );
+ assert_same_hits(&semantic_hits(&idx).await, &merged_hits, "reopen");
+ assert_eq!(knn_top(&idx, &before_docs[1]["content_vector"]).await, "1");
+}
+
+#[test]
+fn storage_and_query_agree_on_the_passage_metadata_prefix() {
+ assert_eq!(
+ xerj_storage::stored_codec::derived_vectors::PASSAGE_METADATA_PREFIX,
+ xerj_query::executor::PASSAGE_METADATA_PREFIX
+ );
+}
diff --git a/engine/crates/xerj-engine/tests/semantic_vectors_opt_out_restores.rs b/engine/crates/xerj-engine/tests/semantic_vectors_opt_out_restores.rs
new file mode 100644
index 000000000..34641492a
--- /dev/null
+++ b/engine/crates/xerj-engine/tests/semantic_vectors_opt_out_restores.rs
@@ -0,0 +1,248 @@
+//! #1122 / #2433 review: the documented downgrade path. Rows written with
+//! the default (derived vectors stripped from the stored `_source`) must get
+//! their vectors back on disk when the process runs with
+//! `XERJ_STORE_SEMANTIC_VECTORS=1` and the index is force-merged, so a binary
+//! that cannot rebuild them still finds them.
+//!
+//! Its own test binary: the opt-out is process-wide.
+
+use serde_json::{json, Value};
+use tempfile::TempDir;
+use xerj_common::config::Config;
+use xerj_common::types::{FieldConfig, FieldType, Schema};
+use xerj_engine::Engine;
+use xerj_query::parse_request;
+use xerj_storage::{SectionType, SegmentReader};
+
+const INDEX: &str = "sem-optout";
+const WORDS: &[&str] = &[
+ "liquidity",
+ "quarterly",
+ "revenue",
+ "storage",
+ "vector",
+ "merge",
+ "segment",
+ "harbor",
+ "orchard",
+ "glacier",
+ "copper",
+ "lantern",
+ "meadow",
+ "compiler",
+ "kernel",
+ "ledger",
+];
+
+fn make_engine(dir: &TempDir) -> Engine {
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_str().unwrap().to_string();
+ Engine::new(config).expect("engine::new")
+}
+
+fn schema() -> Schema {
+ let mut schema = Schema::empty();
+ let mut content = FieldConfig::new("content", FieldType::Text);
+ content.options.dimensions = Some(32);
+ content.options.similarity = Some("cosine".to_string());
+ content.embedding = Some(xerj_common::types::EmbeddingConfig {
+ endpoint: None,
+ model: None,
+ target_field: Some("content_vector".to_string()),
+ });
+ schema.fields.push(content);
+ schema.fields.push(FieldConfig::new("n", FieldType::Long));
+ schema
+}
+
+fn text(i: usize) -> String {
+ let base: Vec<&str> = (0..12)
+ .map(|k| WORDS[(i * 7 + k * 3) % WORDS.len()])
+ .collect();
+ let base = base.join(" ");
+ if i.is_multiple_of(10) {
+ // Several passages: exercises `<target>_chunks`.
+ format!("doc {i} {}", format!("{base} ").repeat(20))
+ } else {
+ format!("doc {i} {base}")
+ }
+}
+
+async fn bulk(engine: &Engine, range: std::ops::Range<usize>) {
+ let mut body = String::new();
+ for i in range {
+ body.push_str(&format!(
+ "{{\"index\":{{\"_index\":\"{INDEX}\",\"_id\":\"{i}\"}}}}\n"
+ ));
+ body.push_str(&serde_json::to_string(&json!({"content": text(i), "n": i})).unwrap());
+ body.push('\n');
+ }
+ let result = xerj_engine::bulk::process_bulk(engine, None, &body).await;
+ assert!(
+ !result.errors,
+ "{:?}",
+ result.items.iter().find(|i| i.error.is_some())
+ );
+}
+
+fn seg_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
+ for entry in std::fs::read_dir(dir).unwrap() {
+ let path = entry.unwrap().path();
+ if path.is_dir() {
+ seg_files(&path, out);
+ } else if path.extension().is_some_and(|ext| ext == "seg") {
+ out.push(path);
+ }
+ }
+}
+
+/// Count columnar stored sections; assert every one is stripped (`want_stripped`)
+/// or stores full vectors, as seen by the non-rehydrating decoder.
+fn check_segments(dir: &TempDir, want_stripped: bool) -> usize {
+ let mut files = Vec::new();
+ seg_files(dir.path(), &mut files);
+ let mut columnar = 0;
+ for path in files {
+ let reader = SegmentReader::open(&path).unwrap();
+ let Some(raw) = reader.section(SectionType::Stored).unwrap() else {
+ continue;
+ };
+ let raw_text = String::from_utf8(
+ xerj_storage::stored_codec::decode_stored_preserving_derived(raw).unwrap(),
+ )
+ .unwrap();
+ if xerj_storage::stored_codec::stored_v2_source_column_names(raw)
+ .unwrap()
+ .is_some()
+ {
+ columnar += 1;
+ }
+ if want_stripped {
+ if xerj_storage::stored_codec::stored_v2_source_column_names(raw)
+ .unwrap()
+ .is_some()
+ {
+ assert!(
+ !raw_text.contains("\"content_vector\":"),
+ "{path:?} stores vectors"
+ );
+ assert!(raw_text.contains(r#""derived":"lexical-v1""#));
+ }
+ } else {
+ assert!(
+ !raw_text.contains(r#""derived""#),
+ "{path:?} still has stripped rows after the opt-out merge"
+ );
+ let docs: Vec<Value> = serde_json::from_str(&raw_text).unwrap();
+ for doc in &docs {
+ let source = &doc["_source"];
+ assert!(
+ source.get("content_vector").is_some(),
+ "{path:?}: doc {} has no stored vector",
+ doc["_id"]
+ );
+ }
+ assert!(raw_text.contains("\"content_vector_chunks\":"));
+ }
+ }
+ columnar
+}
+
+async fn snapshot(idx: &xerj_engine::Index, ids: &[usize]) -> Vec<Value> {
+ let mut out = Vec::new();
+ for id in ids {
+ out.push(idx.get_document(&id.to_string()).await.unwrap().unwrap());
+ }
+ out
+}
+
+async fn semantic_hits(idx: &xerj_engine::Index) -> Vec<(String, f32, Value)> {
+ let request = parse_request(&json!({
+ "query": {"semantic": {"field": "content", "query": "quarterly liquidity ledger", "k": 10}},
+ "size": 10,
+ "_source": true
+ }))
+ .unwrap();
+ let response = idx.search(&request).await.unwrap();
+ response
+ .hits
+ .iter()
+ .map(|hit| (hit.id.clone(), hit.score, hit.source.clone()))
+ .collect()
+}
+
+#[tokio::test]
+async fn opt_out_force_merge_restores_stripped_vectors_on_disk() {
+ xerj_storage::stored_codec::derived_vectors::set_store_vectors_opt_out(false);
+ let dir = TempDir::new().unwrap();
+ let probe = [0usize, 1, 10, 137, 999, 1500];
+ let engine = make_engine(&dir);
+ engine.create_index(INDEX, schema()).unwrap();
+ let idx = engine.get_index(INDEX).unwrap();
+
+ bulk(&engine, 0..1000).await;
+ idx.flush().await.unwrap();
+ idx.force_merge(1).await.unwrap();
+ assert_eq!(idx.store_snapshot().segments.len(), 1);
+ assert!(
+ check_segments(&dir, true) > 0,
+ "default write is not columnar"
+ );
+ let before_docs = snapshot(&idx, &probe[..5]).await;
+ let before_hits = semantic_hits(&idx).await;
+ assert!(!before_hits.is_empty());
+
+ // "Restart with XERJ_STORE_SEMANTIC_VECTORS=1", then the documented
+ // `_forcemerge?max_num_segments=1` on an index that is already one
+ // segment: the stripped segment must still be rewritten.
+ xerj_storage::stored_codec::derived_vectors::set_store_vectors_opt_out(true);
+ assert!(
+ idx.force_merge(1).await.unwrap() > 0,
+ "single segment not rewritten"
+ );
+ assert_eq!(idx.store_snapshot().segments.len(), 1);
+ assert!(
+ check_segments(&dir, false) > 0,
+ "rewritten section is not columnar"
+ );
+ assert_eq!(
+ snapshot(&idx, &probe[..5]).await,
+ before_docs,
+ "rewrite changed a document"
+ );
+ let hits = |h: &[(String, f32, Value)]| {
+ h.iter()
+ .map(|h| (h.0.clone(), h.2.clone()))
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(hits(&semantic_hits(&idx).await), hits(&before_hits));
+ // Nothing left to restore: a second forcemerge is a no-op.
+ assert_eq!(idx.force_merge(1).await.unwrap(), 0);
+
+ // New docs under the opt-out, merged with the restored segment.
+ bulk(&engine, 1000..1600).await;
+ idx.flush().await.unwrap();
+ let before_docs = snapshot(&idx, &probe).await;
+ idx.force_merge(1).await.unwrap();
+ assert!(
+ check_segments(&dir, false) > 0,
+ "merged section is not columnar"
+ );
+ assert_eq!(
+ snapshot(&idx, &probe).await,
+ before_docs,
+ "merge changed a document"
+ );
+ drop(idx);
+ drop(engine);
+
+ // Reopened (still opted out): the restored vectors are what is read.
+ let reopened = make_engine(&dir);
+ let idx = reopened.get_index(INDEX).unwrap();
+ assert_eq!(
+ snapshot(&idx, &probe).await,
+ before_docs,
+ "reopen changed a document"
+ );
+ check_segments(&dir, false);
+}
diff --git a/engine/crates/xerj-storage/Cargo.toml b/engine/crates/xerj-storage/Cargo.toml
index 2f1169323..49e38a5c9 100644
--- a/engine/crates/xerj-storage/Cargo.toml
+++ b/engine/crates/xerj-storage/Cargo.toml
@@ -12,6 +12,9 @@ test-hooks = []
[dependencies]
xerj-common = { path = "../xerj-common" }
+# Default features only (no candle/ort): the lexical semantic_text recipe the
+# stored codec uses to regenerate derived vectors (#1122, #2433).
+xerj-ai = { path = "../xerj-ai", default-features = false }
# Async runtime
tokio = { workspace = true }
@@ -20,6 +23,7 @@ tokio = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
rayon = { workspace = true }
+memchr = { workspace = true }
# Binary I/O
bytes = { workspace = true }
diff --git a/engine/crates/xerj-storage/src/index_store.rs b/engine/crates/xerj-storage/src/index_store.rs
index a1bed0451..6aff9b6ef 100644
--- a/engine/crates/xerj-storage/src/index_store.rs
+++ b/engine/crates/xerj-storage/src/index_store.rs
@@ -4631,13 +4631,16 @@ impl IndexStore {
Ok(Some(b)) => b,
_ => continue,
};
- let stored_bytes = match crate::stored_codec::decode_stored(stored_bytes_raw) {
- Ok(b) => b,
- Err(e) => {
- warn!(segment = %meta.id, error = %e, "cannot decode stored section");
- continue;
- }
- };
+ // Only (id, seq_no) are read and nothing is re-encoded, so the
+ // opt-out does not apply: skip rebuilding derived vectors.
+ let stored_bytes =
+ match crate::stored_codec::decode_stored_preserving_derived(stored_bytes_raw) {
+ Ok(b) => b,
+ Err(e) => {
+ warn!(segment = %meta.id, error = %e, "cannot decode stored section");
+ continue;
+ }
+ };
let docs: Vec<serde_json::Value> = match serde_json::from_slice(&stored_bytes) {
Ok(d) => d,
diff --git a/engine/crates/xerj-storage/src/merge.rs b/engine/crates/xerj-storage/src/merge.rs
index 3b12be451..3ef49ef6a 100644
--- a/engine/crates/xerj-storage/src/merge.rs
+++ b/engine/crates/xerj-storage/src/merge.rs
@@ -340,7 +340,10 @@ impl MergeExecutor {
if let Some(stored_bytes_raw) = reader.section(SectionType::Stored)? {
rate_limiter.consume(stored_bytes_raw.len() as u64);
- let stored_bytes = crate::stored_codec::decode_stored(stored_bytes_raw)?;
+ // #1122/#2433: re-encoded below; stripped rows stay stripped
+ // unless XERJ_STORE_SEMANTIC_VECTORS asks for full vectors.
+ let stored_bytes =
+ crate::stored_codec::decode_stored_for_rewrite(stored_bytes_raw)?;
let docs: Vec<Json> = serde_json::from_slice(&stored_bytes)?;
for doc in docs {
let doc_id = doc.get("_id").and_then(|v| v.as_str()).unwrap_or("");
diff --git a/engine/crates/xerj-storage/src/stored_codec.rs b/engine/crates/xerj-storage/src/stored_codec.rs
index bb8ce02f3..3aed3c5a8 100644
--- a/engine/crates/xerj-storage/src/stored_codec.rs
+++ b/engine/crates/xerj-storage/src/stored_codec.rs
@@ -84,6 +84,7 @@ use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::collections::HashMap;
use std::io::{Cursor, Read, Write};
+pub mod derived_vectors;
mod row_hydration;
pub use row_hydration::{
decode_stored_v2_ids, decode_stored_v2_rows, decode_stored_v2_rows_controlled,
@@ -348,13 +349,24 @@ fn encode_stored_v2_at_level_inner(
long_effort_level: Option<i32>,
) -> Vec<u8> {
// Parse the JSON array of documents. Failure → v1 fallback.
- let docs: Vec<serde_json::Value> = match serde_json::from_slice(stored_docs_json) {
+ let mut docs: Vec<serde_json::Value> = match serde_json::from_slice(stored_docs_json) {
Ok(v) => v,
Err(_) => return encode_stored_lz4(stored_docs_json),
};
if docs.len() < V2_MIN_DOCS {
return encode_stored_lz4(stored_docs_json);
}
+ // #1122/#2433: drop regenerable semantic_text vectors (see
+ // `derived_vectors`). Must match `encode_stored_v2_from_values_inner`.
+ {
+ use rayon::prelude::*;
+ docs.par_iter_mut().for_each(|doc| {
+ let stripped = doc.get("_source").and_then(derived_vectors::strip_source);
+ if let (Some(stripped), Some(obj)) = (stripped, doc.as_object_mut()) {
+ obj.insert("_source".into(), stripped);
+ }
+ });
+ }
// Flatten each doc into (id, seq_no, source-fields). Anything non-JSON
// at the top level degrades to the RAW column codec. Keys are
@@ -492,6 +504,21 @@ fn encode_stored_v2_from_values_inner(
let prof = std::env::var_os("XERJ_PROF").is_some();
let t_build = std::time::Instant::now();
+ // #1122/#2433: drop regenerable semantic_text vectors (see
+ // `derived_vectors`); identical to the JSON entry point's pass.
+ let stripped: Vec<Option<serde_json::Value>> = {
+ use rayon::prelude::*;
+ docs.par_iter()
+ .map(|(_, _, src)| derived_vectors::strip_source(src))
+ .collect()
+ };
+ let stripped_docs: Vec<(&str, u64, &serde_json::Value)> = docs
+ .iter()
+ .zip(&stripped)
+ .map(|((id, seq, src), stripped)| (*id, *seq, stripped.as_ref().unwrap_or(src)))
+ .collect();
+ let docs: &[(&str, u64, &serde_json::Value)] = &stripped_docs;
+
// Synthetic __id / __seq_no columns need owned Values to borrow from.
let ids: Vec<serde_json::Value> = docs
.iter()
@@ -915,18 +942,58 @@ fn split_stored_v3(bytes: &[u8]) -> Result<StoredV3Parts<'_>> {
/// Returns the canonical JSON-array payload that every upstream caller
/// expects (`[{"_id", "_seq_no", "_source": {...}}, ...]`).
pub fn decode_stored(bytes: &[u8]) -> Result<Vec<u8>> {
+ decode_stored_inner(bytes, true)
+}
+
+/// [`decode_stored`] without rebuilding derived `semantic_text` vectors
+/// (#1122/#2433): stripped rows keep their marker and stay vector-less.
+/// For a rewrite that re-encodes the documents (merge), so a stripped row
+/// is not regenerated only to be verified and dropped again. Never hand
+/// this output to a reader.
+pub fn decode_stored_preserving_derived(bytes: &[u8]) -> Result<Vec<u8>> {
+ decode_stored_inner(bytes, false)
+}
+
+/// Decode for a merge that re-encodes the documents (#1122/#2433).
+///
+/// By default stripped rows stay stripped ([`decode_stored_preserving_derived`]).
+/// With `XERJ_STORE_SEMANTIC_VECTORS` set the rows are rehydrated instead, so
+/// the merged segment stores full vectors: that is how `force_merge` restores
+/// vectors written before the opt-out was turned on.
+pub fn decode_stored_for_rewrite(bytes: &[u8]) -> Result<Vec<u8>> {
+ decode_stored_inner(bytes, derived_vectors::store_vectors_opt_out())
+}
+
+/// Whether a stored section holds rows whose derived `semantic_text`
+/// vectors were stripped (#1122/#2433). `force_merge` under
+/// `XERJ_STORE_SEMANTIC_VECTORS` rewrites such a segment even when the
+/// index is already at its target segment count.
+pub fn stored_has_derived_rows(bytes: &[u8]) -> Result<bool> {
+ Ok(derived_vectors::contains_marker(
+ &decode_stored_preserving_derived(bytes)?,
+ ))
+}
+
+fn decode_stored_inner(bytes: &[u8], rehydrate: bool) -> Result<Vec<u8>> {
if bytes.len() >= 4 && &bytes[..4] == STORED_V3_MAGIC {
let (present_nulls, inner) = split_stored_v3(bytes)?;
- return decode_stored_v2(&inner[4..], &present_nulls);
+ return decode_stored_v2_filtered(&inner[4..], &present_nulls, None, rehydrate);
}
if is_columnar_stored_magic(bytes) {
- return decode_stored_v2(&bytes[4..], &[]);
+ return decode_stored_v2_filtered(&bytes[4..], &[], None, rehydrate);
}
- if bytes.len() >= 4 && &bytes[..4] == STORED_LZ4_MAGIC {
- return lz4_flex::decompress_size_prepended(&bytes[4..])
- .map_err(|e| StorageError::Other(anyhow::anyhow!("LZ4 decompress failed: {e}")));
+ let raw = if bytes.len() >= 4 && &bytes[..4] == STORED_LZ4_MAGIC {
+ lz4_flex::decompress_size_prepended(&bytes[4..])
+ .map_err(|e| StorageError::Other(anyhow::anyhow!("LZ4 decompress failed: {e}")))?
+ } else {
+ bytes.to_vec()
+ };
+ // A merge can write marker-bearing rows through the LZ4 fallback.
+ if rehydrate {
+ derived_vectors::rehydrate_canonical(raw)
+ } else {
+ Ok(raw)
}
- Ok(bytes.to_vec())
}
/// Column-projected decode over any supported stored payload (#950).
@@ -1401,14 +1468,28 @@ pub fn stored_v2_source_column_names(bytes: &[u8]) -> Result<Option<Vec<String>>
return Ok(None);
}
let directory = parse_v2_directory(&bytes[4..])?;
- Ok(Some(
- directory
- .columns
- .iter()
- .filter(|column| column.name != "__id" && column.name != "__seq_no")
- .map(|column| column.name.to_string())
- .collect(),
- ))
+ let mut names: Vec<String> = directory
+ .columns
+ .iter()
+ .filter(|column| column.name != "__id" && column.name != "__seq_no")
+ .map(|column| column.name.to_string())
+ .collect();
+ // #1122/#2433: derived semantic vectors may be stripped from every row
+ // and so have no column; they are still `_source` fields a projection
+ // can ask for (the row decoders rebuild them).
+ let targets: Vec<String> = names
+ .iter()
+ .filter_map(|name| derived_vectors::metadata_target(name))
+ .map(str::to_string)
+ .collect();
+ for target in targets {
+ for name in [derived_vectors::chunks_name(&target), target] {
+ if !names.contains(&name) {
+ names.push(name);
+ }
+ }
+ }
+ Ok(Some(names))
}
/// Decode only named columns from a V2 stored section.
@@ -1933,14 +2014,39 @@ where
));
}
let directory = parse_v2_directory(&bytes[4..])?;
+ // #1122/#2433: stripped rows rebuild their vectors from the text.
+ let metadata_column = format!("{}{vector_field}", derived_vectors::PASSAGE_METADATA_PREFIX);
+ let has_metadata = directory
+ .columns
+ .iter()
+ .any(|column| column.name == metadata_column);
let Some(vector_column) = directory
.columns
.iter()
.find(|column| column.name == vector_field)
else {
- return Ok(StoredDecodeRun::Complete(
- StoredV2KnnProjectionResult::MissingVectorColumn,
- ));
+ if !has_metadata {
+ return Ok(StoredDecodeRun::Complete(
+ StoredV2KnnProjectionResult::MissingVectorColumn,
+ ));
+ }
+ if decode_cancelled(&mut checkpoint, StoredDecodePhase::BeforeColumn, 0, 0) {
+ return Ok(StoredDecodeRun::Cancelled);
+ }
+ let mut vectors: StoredVectorRows = vec![None; directory.num_docs];
+ let mut vector_chunks: Option<StoredVectorChunkRows> = None;
+ if !fill_derived_knn_rows(
+ bytes,
+ &metadata_column,
+ vector_chunks_field.is_some(),
+ &mut vectors,
+ &mut vector_chunks,
+ )? {
+ return Ok(StoredDecodeRun::Complete(
+ StoredV2KnnProjectionResult::UnsupportedVectorShape,
+ ));
+ }
+ return knn_projection_with_identity(bytes, vectors, vector_chunks, &mut checkpoint);
};
let vector_index = directory
.columns
@@ -2014,8 +2120,109 @@ where
},
None => None,
};
+ let mut vectors = vectors;
+ let mut vector_chunks = vector_chunks;
+ if has_metadata
+ && vectors.iter().any(Option::is_none)
+ && !fill_derived_knn_rows(
+ bytes,
+ &metadata_column,
+ vector_chunks_field.is_some(),
+ &mut vectors,
+ &mut vector_chunks,
+ )?
+ {
+ return Ok(StoredDecodeRun::Complete(
+ StoredV2KnnProjectionResult::UnsupportedVectorShape,
+ ));
+ }
+ knn_projection_with_identity(bytes, vectors, vector_chunks, &mut checkpoint)
+}
+
+/// Rebuild the typed vectors of every stripped row (`vectors[row] == None`
+/// with a lexical marker in its passage metadata) from its text.
+/// `Ok(false)` when the rows cannot be read selectively.
+fn fill_derived_knn_rows(
+ bytes: &[u8],
+ metadata_column: &str,
+ want_chunks: bool,
+ vectors: &mut StoredVectorRows,
+ vector_chunks: &mut Option<StoredVectorChunkRows>,
+) -> Result<bool> {
+ let ordinals: Vec<usize> = (0..vectors.len())
+ .filter(|&row| vectors[row].is_none())
+ .collect();
+ if ordinals.is_empty() {
+ return Ok(true);
+ }
+ let StoredV2RowHydrationResult::Hydrated {
+ rows: meta_rows, ..
+ } = decode_stored_v2_rows_projected(bytes, &ordinals, &[metadata_column])?
+ else {
+ return Ok(false);
+ };
+ let mut fields: Vec<String> = Vec::new();
+ for row in &meta_rows {
+ if let Some(field) = row
+ .source
+ .get(metadata_column)
+ .filter(|meta| derived_vectors::is_stripped(meta))
+ .and_then(derived_vectors::metadata_field)
+ {
+ if !fields.iter().any(|known| known == field) {
+ fields.push(field.to_string());
+ }
+ }
+ }
+ if fields.is_empty() {
+ return Ok(true);
+ }
+ let field_refs: Vec<&str> = fields.iter().map(String::as_str).collect();
+ let StoredV2RowHydrationResult::Hydrated {
+ rows: text_rows, ..
+ } = decode_stored_v2_rows_projected(bytes, &ordinals, &field_refs)?
+ else {
+ return Ok(false);
+ };
+ let texts: HashMap<usize, serde_json::Map<String, serde_json::Value>> = text_rows
+ .into_iter()
+ .map(|row| (row.ordinal, row.source))
+ .collect();
+ let rebuilt: Vec<(usize, Option<derived_vectors::LexicalSemanticVectors>)> = {
+ use rayon::prelude::*;
+ meta_rows
+ .par_iter()
+ .map(|row| {
+ let rebuilt = row.source.get(metadata_column).and_then(|meta| {
+ let text = derived_vectors::metadata_field(meta)
+ .and_then(|field| texts.get(&row.ordinal)?.get(field))
+ .and_then(serde_json::Value::as_str);
+ derived_vectors::regenerate(meta, text)
+ });
+ (row.ordinal, rebuilt)
+ })
+ .collect()
+ };
+ for (ordinal, rebuilt) in rebuilt {
+ let Some((pooled, chunks)) = rebuilt else {
+ continue;
+ };
+ vectors[ordinal] = Some(pooled);
+ if let (true, Some(chunks)) = (want_chunks, chunks) {
+ vector_chunks.get_or_insert_with(|| vec![None; vectors.len()])[ordinal] = Some(chunks);
+ }
+ }
+ Ok(true)
+}
+
+fn knn_projection_with_identity(
+ bytes: &[u8],
+ vectors: StoredVectorRows,
+ vector_chunks: Option<StoredVectorChunkRows>,
+ checkpoint: &mut dyn FnMut(StoredDecodeCheckpoint) -> std::ops::ControlFlow<()>,
+) -> Result<StoredDecodeRun<StoredV2KnnProjectionResult>> {
let (identity_num_docs, id_values, seq_values) =
- match row_hydration::decode_v2_identity_columns_controlled(bytes, &mut checkpoint)? {
+ match row_hydration::decode_v2_identity_columns_controlled(bytes, checkpoint)? {
StoredDecodeRun::Complete(Some(values)) => values,
StoredDecodeRun::Complete(None) => {
return Ok(StoredDecodeRun::Complete(
@@ -2040,10 +2247,6 @@ where
))
}
-fn decode_stored_v2(body: &[u8], present_nulls: &[(u32, u32)]) -> Result<Vec<u8>> {
- decode_stored_v2_filtered(body, present_nulls, None)
-}
-
/// Decode a stored section like [`decode_stored`], but emit only the
/// `_source` columns `keep` accepts (`_id` and `_seq_no` are always
/// emitted). Same canonical `[{"_id","_seq_no","_source":{…}}, …]` framing,
@@ -2065,10 +2268,10 @@ fn decode_stored_v2(body: &[u8], present_nulls: &[(u32, u32)]) -> Result<Vec<u8>
pub fn decode_stored_keeping(bytes: &[u8], keep: &dyn Fn(&str) -> bool) -> Result<Option<Vec<u8>>> {
if bytes.len() >= 4 && &bytes[..4] == STORED_V3_MAGIC {
let (present_nulls, inner) = split_stored_v3(bytes)?;
- return decode_stored_v2_filtered(&inner[4..], &present_nulls, Some(keep)).map(Some);
+ return decode_stored_v2_filtered(&inner[4..], &present_nulls, Some(keep), true).map(Some);
}
if is_columnar_stored_magic(bytes) {
- return decode_stored_v2_filtered(&bytes[4..], &[], Some(keep)).map(Some);
+ return decode_stored_v2_filtered(&bytes[4..], &[], Some(keep), true).map(Some);
}
Ok(None)
}
@@ -2077,6 +2280,7 @@ fn decode_stored_v2_filtered(
body: &[u8],
present_nulls: &[(u32, u32)],
keep: Option<&dyn Fn(&str) -> bool>,
+ rehydrate: bool,
) -> Result<Vec<u8>> {
// Positions that were a *present* explicit `_source` null (issue #415).
// Empty for plain ZBS2 segments; populated by `split_stored_v3` for ZBS3.
@@ -2134,6 +2338,40 @@ fn decode_stored_v2_filtered(
// column order, as the serial loop reported them.
// #2427: which columns are emitted, and which must be decoded (the
// emitted ones plus whatever a kept COPY_OF / CROSS_DEP derives from).
+ // #1122/#2433: rows whose derived semantic vectors were stripped get
+ // them rebuilt from the text. A reader that keeps those vectors needs
+ // every column decoded (the text and metadata they derive from); the
+ // `allowed` set then trims the rebuilt row back to what `keep` asked.
+ let has_metadata = rehydrate
+ && entries
+ .iter()
+ .any(|(name, _, _)| derived_vectors::metadata_target(name).is_some());
+ let wants_derived = has_metadata
+ && keep.is_none_or(|keep| {
+ derived_vectors::keep_wants_derived(entries.iter().map(|(n, _, _)| n.as_str()), keep)
+ });
+ let allowed: Option<std::collections::HashSet<String>> = match keep {
+ Some(keep) if wants_derived => {
+ let mut names: std::collections::HashSet<String> = entries
+ .iter()
+ .map(|(name, _, _)| name.clone())
+ .filter(|name| keep(name))
+ .collect();
+ for target in entries
+ .iter()
+ .filter_map(|(name, _, _)| derived_vectors::metadata_target(name))
+ {
+ for name in [target.to_string(), derived_vectors::chunks_name(target)] {
+ if keep(&name) {
+ names.insert(name);
+ }
+ }
+ }
+ Some(names)
+ }
+ _ => None,
+ };
+ let keep = if wants_derived { None } else { keep };
let emit: Vec<bool> = entries
.iter()
.map(|(name, _, _)| {
@@ -2397,6 +2635,12 @@ fn decode_stored_v2_filtered(
source_map.insert(name.clone(), serde_json::Value::Null);
}
}
+ if wants_derived {
+ derived_vectors::rehydrate_source_map(&mut source_map);
+ }
+ if let Some(allowed) = allowed.as_ref() {
+ source_map.retain(|name, _| allowed.contains(name));
+ }
let mut doc = serde_json::Map::new();
doc.insert("_id".into(), cell(id_col_ix));
doc.insert("_seq_no".into(), cell(seq_col_ix));
@@ -3423,6 +3667,170 @@ mod tests {
use super::*;
use serde_json::json;
+ // ── #1122/#2433: derived semantic vectors are not persisted ──────────
+
+ fn semantic_docs(n: usize) -> Vec<serde_json::Value> {
+ (0..n)
+ .map(|i| {
+ let text = if i.is_multiple_of(9) {
+ format!("doc {i} {}", "storage vectors merge segment ".repeat(40))
+ } else {
+ format!("doc {i} quarterly liquidity ledger {}", i * 31)
+ };
+ let mut source = derived_vectors::tests::ingested(&text, 16);
+ source["n"] = json!(i);
+ json!({"_id": i.to_string(), "_seq_no": i, "_source": source})
+ })
+ .collect()
+ }
+
+ fn sources(json_bytes: &[u8]) -> Vec<serde_json::Value> {
+ let docs: Vec<serde_json::Value> = serde_json::from_slice(json_bytes).unwrap();
+ docs.into_iter().map(|d| d["_source"].clone()).collect()
+ }
+
+ #[test]
+ fn derived_vectors_round_trip_through_both_encoders() {
+ let docs = semantic_docs(300);
+ let raw = serde_json::to_vec(&docs).unwrap();
+ let refs: Vec<(String, u64)> = (0..docs.len()).map(|i| (i.to_string(), i as u64)).collect();
+ let tuples: Vec<(&str, u64, &serde_json::Value)> = docs
+ .iter()
+ .zip(&refs)
+ .map(|(d, (id, seq))| (id.as_str(), *seq, &d["_source"]))
+ .collect();
+ let from_json = encode_stored_v2(&raw);
+ let from_values = encode_stored_v2_from_values_nojson(&tuples);
+ let unstripped_len = raw.len();
+ for encoded in [&from_json, &from_values] {
+ assert!(is_columnar_stored_magic(encoded));
+ let names = stored_v2_source_column_names(encoded).unwrap().unwrap();
+ assert!(names.iter().any(|n| n == "body_vector"));
+ assert!(names.iter().any(|n| n == "body_vector_chunks"));
+ assert_eq!(sources(&decode_stored(encoded).unwrap()), sources(&raw));
+ let preserved = decode_stored_preserving_derived(encoded).unwrap();
+ assert!(preserved.len() < unstripped_len);
+ for source in sources(&preserved) {
+ assert!(source.get("body_vector").is_none());
+ assert!(source.get("body_vector_chunks").is_none());
+ assert!(derived_vectors::is_stripped(
+ &source[&format!("{}body_vector", derived_vectors::PASSAGE_METADATA_PREFIX)]
+ ));
+ }
+ }
+ assert_eq!(
+ decode_stored(&from_json).unwrap(),
+ decode_stored(&from_values).unwrap()
+ );
+ }
+
+ #[test]
+ fn derived_vectors_keep_projection_rows_and_knn() {
+ let docs = semantic_docs(200);
+ let raw = serde_json::to_vec(&docs).unwrap();
+ let encoded = encode_stored_v2(&raw);
+ let originals = sources(&raw);
+
+ let with_vec = decode_stored_keeping(&encoded, &|n| n == "body_vector" || n == "n")
+ .unwrap()
+ .unwrap();
+ for (got, want) in sources(&with_vec).iter().zip(&originals) {
+ assert_eq!(got.as_object().unwrap().len(), 2, "{got}");
+ assert_eq!(got["body_vector"], want["body_vector"]);
+ }
+ let without = decode_stored_keeping(&encoded, &|n| n == "n")
+ .unwrap()
+ .unwrap();
+ for got in sources(&without) {
+ assert_eq!(got.as_object().unwrap().len(), 1, "{got}");
+ }
+
+ let ordinals = [0usize, 5, 9, 199];
+ match row_hydration::decode_stored_v2_rows(&encoded, &ordinals).unwrap() {
+ row_hydration::StoredV2RowHydrationResult::Hydrated { rows, .. } => {
+ for row in rows {
+ assert_eq!(
+ serde_json::Value::Object(row.source),
+ originals[row.ordinal]
+ );
+ }
+ }
+ other => panic!("unexpected {other:?}"),
+ }
+ match row_hydration::decode_stored_v2_rows_projected(
+ &encoded,
+ &ordinals,
+ &["body_vector_chunks"],
+ )
+ .unwrap()
+ {
+ row_hydration::StoredV2RowHydrationResult::Hydrated { rows, .. } => {
+ for row in rows {
+ let want = originals[row.ordinal].get("body_vector_chunks");
+ assert_eq!(row.source.get("body_vector_chunks"), want);
+ assert!(row.source.len() <= 1, "{:?}", row.source);
+ }
+ }
+ other => panic!("unexpected {other:?}"),
+ }
+
+ match decode_stored_v2_knn_projection(&encoded, "body_vector", Some("body_vector_chunks"))
+ .unwrap()
+ {
+ StoredV2KnnProjectionResult::Projected(projection) => {
+ assert_eq!(projection.num_docs, 200);
+ let chunks = projection.vector_chunks.unwrap();
+ for (i, want) in originals.iter().enumerate() {
+ assert_eq!(projection.ids[i].as_deref(), Some(i.to_string().as_str()));
+ assert_eq!(
+ projection.vectors[i],
+ derived_vectors::vector_f32(&want["body_vector"])
+ );
+ let want_chunks = want.get("body_vector_chunks").map(|c| {
+ c.as_array()
+ .unwrap()
+ .iter()
+ .map(|v| derived_vectors::vector_f32(v).unwrap())
+ .collect::<Vec<_>>()
+ });
+ assert_eq!(chunks[i], want_chunks);
+ }
+ }
+ other => panic!("unexpected {other:?}"),
+ }
+ }
+
+ #[test]
+ fn derived_vectors_legacy_and_foreign_rows_are_untouched() {
+ // A segment written before the strip (or with the opt-out) has the
+ // vectors as ordinary columns and decodes unchanged.
+ let mut docs = semantic_docs(150);
+ // Foreign vector: not what the lexical embedder derives.
+ docs[3]["_source"]["body_vector"] = json!([0.5, 0.5]);
+ let raw = serde_json::to_vec(&docs).unwrap();
+ let encoded = encode_stored_v2(&raw);
+ let preserved = sources(&decode_stored_preserving_derived(&encoded).unwrap());
+ assert_eq!(preserved[3]["body_vector"], json!([0.5, 0.5]));
+ assert!(preserved[4].get("body_vector").is_none());
+ assert_eq!(sources(&decode_stored(&encoded).unwrap()), sources(&raw));
+
+ // Small (LZ4) sections keep vectors and pass through unchanged.
+ let small = serde_json::to_vec(&semantic_docs(3)).unwrap();
+ let lz4 = encode_stored_v2(&small);
+ assert_eq!(decode_stored(&lz4).unwrap(), small);
+ // A marked LZ4 section (merge output of stripped rows) rehydrates.
+ let marked: Vec<serde_json::Value> =
+ sources(&decode_stored_preserving_derived(&encoded).unwrap())
+ .into_iter()
+ .take(3)
+ .enumerate()
+ .map(|(i, s)| json!({"_id": i.to_string(), "_seq_no": i, "_source": s}))
+ .collect();
+ let marked_lz4 = encode_stored_lz4(&serde_json::to_vec(&marked).unwrap());
+ let want: Vec<serde_json::Value> = sources(&raw).into_iter().take(3).collect();
+ assert_eq!(sources(&decode_stored(&marked_lz4).unwrap()), want);
+ }
+
#[test]
fn lz4_roundtrip() {
let raw = br#"[{"_id":"a","_source":{"msg":"hello world"}}]"#;
diff --git a/engine/crates/xerj-storage/src/stored_codec/derived_vectors.rs b/engine/crates/xerj-storage/src/stored_codec/derived_vectors.rs
new file mode 100644
index 000000000..350c246e1
--- /dev/null
+++ b/engine/crates/xerj-storage/src/stored_codec/derived_vectors.rs
@@ -0,0 +1,381 @@
+//! Derived `semantic_text` vectors are not persisted in stored `_source`
+//! (#1122, #2433).
+//!
+//! With the built-in lexical embedder, ingest writes three companions next to
+//! each `semantic_text` field: the pooled vector (`<target>`), the passage
+//! metadata (`__xerj_passage_meta__<target>`) and, for multi-passage text,
+//! the per-passage vectors (`<target>_chunks`). The vectors are a pure
+//! function of the text ([`xerj_ai::semantic_lexical`]), and the HNSW index
+//! holds the pooled vector again, so persisting them in every stored row made
+//! a semantic index ~2.2x its source.
+//!
+//! Like Elasticsearch, which keeps inference results out of the stored
+//! `_source` by default, the columnar encoder drops them and the decoders
+//! rebuild them:
+//!
+//! * **Encode** ([`strip_source`]): a target is dropped only after the vectors
+//! re-derived from the text compare bit-equal to the stored ones. Vectors
+//! from an external/neural/ONNX backend, or supplied by the caller, never
+//! match and are kept verbatim. The passage metadata gains a marker
+//! (`"derived":"lexical-v1"`, `"dims":N`) so readers know to rebuild them.
+//! * **Decode** ([`rehydrate_source_map`]): every reader that can return the
+//! vectors puts them back from the text, so `_source`, kNN, reindex and
+//! snapshot readers see exactly the documents that were ingested.
+//! * Merges read with the marker preserved and stay stripped; old segments
+//! (no marker) still carry their vectors and decode unchanged, and are
+//! stripped when a merge rewrites them.
+//!
+//! `XERJ_STORE_SEMANTIC_VECTORS=true` keeps the vectors in newly written
+//! segments, and merges then rebuild the vectors of already-stripped rows
+//! ([`super::decode_stored_for_rewrite`]), so a `force_merge` under the
+//! opt-out leaves every segment with full vectors before a downgrade to a
+//! binary without this code.
+
+use serde_json::{Map, Value};
+pub use xerj_ai::semantic_lexical::LexicalSemanticVectors;
+
+/// Must equal `xerj_query::executor::PASSAGE_METADATA_PREFIX` (asserted by an
+/// engine test; storage cannot depend on the query crate).
+pub const PASSAGE_METADATA_PREFIX: &str = "__xerj_passage_meta__";
+/// Marker value: vectors rebuilt by [`xerj_ai::semantic_lexical`] v1.
+pub const MARKER_LEXICAL_V1: &str = "lexical-v1";
+const MARKER_KEY: &str = "derived";
+const DIMS_KEY: &str = "dims";
+const CHUNKS_SUFFIX: &str = "_chunks";
+
+/// Byte pattern a canonical serialisation contains iff some row is stripped.
+pub(super) const MARKER_BYTES: &[u8] = br#""derived":"lexical-v1""#;
+
+/// 0 = read `XERJ_STORE_SEMANTIC_VECTORS` on first use, 1 = strip, 2 = store.
+static STORE_VECTORS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
+
+/// `XERJ_STORE_SEMANTIC_VECTORS` is set: write full vectors, and have merges
+/// put back the vectors of rows an earlier write stripped.
+pub fn store_vectors_opt_out() -> bool {
+ use std::sync::atomic::Ordering;
+ match STORE_VECTORS.load(Ordering::Relaxed) {
+ 1 => false,
+ 2 => true,
+ _ => {
+ let on = std::env::var("XERJ_STORE_SEMANTIC_VECTORS")
+ .map(|v| {
+ matches!(
+ v.trim().to_ascii_lowercase().as_str(),
+ "1" | "true" | "yes" | "on"
+ )
+ })
+ .unwrap_or(false);
+ let _ = STORE_VECTORS.compare_exchange(
+ 0,
+ if on { 2 } else { 1 },
+ Ordering::Relaxed,
+ Ordering::Relaxed,
+ );
+ STORE_VECTORS.load(Ordering::Relaxed) == 2
+ }
+ }
+}
+
+/// Override `XERJ_STORE_SEMANTIC_VECTORS` for the rest of the process.
+/// For tests that model "restart with the opt-out set" in one process.
+#[doc(hidden)]
+pub fn set_store_vectors_opt_out(on: bool) {
+ STORE_VECTORS.store(if on { 2 } else { 1 }, std::sync::atomic::Ordering::Relaxed);
+}
+
+pub(super) fn chunks_name(target: &str) -> String {
+ format!("{target}{CHUNKS_SUFFIX}")
+}
+
+/// The target a passage-metadata column/key describes.
+pub(super) fn metadata_target(name: &str) -> Option<&str> {
+ name.strip_prefix(PASSAGE_METADATA_PREFIX)
+ .filter(|target| !target.is_empty())
+}
+
+pub(super) fn vector_f32(value: &Value) -> Option<Vec<f32>> {
+ match value {
+ Value::String(s) => xerj_common::packed_f32::unpack_f32_vector(s),
+ Value::Array(items) if !items.is_empty() => {
+ items.iter().map(|v| v.as_f64().map(|f| f as f32)).collect()
+ }
+ _ => None,
+ }
+}
+
+fn same_bits(a: &[f32], b: &[f32]) -> bool {
+ a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
+}
+
+/// The JSON form ingest writes for one vector (packed `xerj:f32:` string,
+/// or a number array when the vector cannot be packed).
+fn vector_value(vector: &[f32]) -> Value {
+ match xerj_common::packed_f32::pack_f32_vector(vector) {
+ Some(packed) => Value::String(packed),
+ None => Value::Array(vector.iter().map(|f| Value::from(*f as f64)).collect()),
+ }
+}
+
+/// Typed vectors for a stripped row: `(pooled, chunks)`. `None` when the
+/// metadata carries no marker or the text is missing.
+pub(super) fn regenerate(meta: &Value, text: Option<&str>) -> Option<LexicalSemanticVectors> {
+ let meta = meta.as_object()?;
+ if meta.get(MARKER_KEY).and_then(Value::as_str) != Some(MARKER_LEXICAL_V1) {
+ return None;
+ }
+ let dims = meta.get(DIMS_KEY).and_then(Value::as_u64)? as usize;
+ xerj_ai::semantic_lexical::lexical_semantic_vectors(text?, dims)
+}
+
+/// The text field a passage metadata value names.
+pub(super) fn metadata_field(meta: &Value) -> Option<&str> {
+ meta.get("field").and_then(Value::as_str)
+}
+
+pub(super) fn is_stripped(meta: &Value) -> bool {
+ meta.get(MARKER_KEY).and_then(Value::as_str) == Some(MARKER_LEXICAL_V1)
+}
+
+/// Encode side: a copy of `source` without the derived vectors it can prove
+/// are regenerable, or `None` when nothing is dropped (no semantic field,
+/// non-lexical or caller-supplied vectors, already stripped, or opt-out).
+pub fn strip_source(source: &Value) -> Option<Value> {
+ if store_vectors_opt_out() {
+ return None;
+ }
+ let obj = source.as_object()?;
+ let mut stripped: Vec<(&str, String)> = Vec::new();
+ for (key, meta) in obj {
+ let Some(target) = metadata_target(key) else {
+ continue;
+ };
+ if is_stripped(meta) {
+ continue;
+ }
+ let Some(text) = metadata_field(meta)
+ .and_then(|f| obj.get(f))
+ .and_then(Value::as_str)
+ else {
+ continue;
+ };
+ let Some(stored) = obj.get(target).and_then(vector_f32) else {
+ continue;
+ };
+ let Some((pooled, chunks)) =
+ xerj_ai::semantic_lexical::lexical_semantic_vectors(text, stored.len())
+ else {
+ continue;
+ };
+ if !same_bits(&pooled, &stored) {
+ continue;
+ }
+ let chunks_key = chunks_name(target);
+ let stored_chunks = obj.get(&chunks_key).filter(|v| !v.is_null());
+ let chunks_match = match (&chunks, stored_chunks) {
+ (None, None) => true,
+ (Some(expected), Some(Value::Array(items))) => {
+ items.len() == expected.len()
+ && items.iter().zip(expected).all(|(item, want)| {
+ vector_f32(item).is_some_and(|got| same_bits(&got, want))
+ })
+ }
+ _ => false,
+ };
+ if chunks_match {
+ stripped.push((target, chunks_key));
+ }
+ }
+ if stripped.is_empty() {
+ return None;
+ }
+ // Rebuild in order (no `swap_remove` reordering of the visible fields).
+ let mut out = Map::new();
+ for (key, value) in obj {
+ if stripped
+ .iter()
+ .any(|(target, chunks)| key == target || key == chunks)
+ {
+ continue;
+ }
+ let mut value = value.clone();
+ if let Some(target) = metadata_target(key) {
+ if stripped.iter().any(|(t, _)| *t == target) {
+ let dims = obj.get(target).and_then(vector_f32).map_or(0, |v| v.len());
+ if let Some(meta) = value.as_object_mut() {
+ meta.insert(MARKER_KEY.into(), Value::from(MARKER_LEXICAL_V1));
+ meta.insert(DIMS_KEY.into(), Value::from(dims as u64));
+ }
+ }
+ }
+ out.insert(key.clone(), value);
+ }
+ Some(Value::Object(out))
+}
+
+/// Decode side: put the vectors back for every stripped target in `map`, and
+/// remove the marker, so the document is the one ingest produced. Returns
+/// whether anything changed. Order matches ingest: `<target>`, metadata,
+/// `<target>_chunks`.
+pub fn rehydrate_source_map(map: &mut Map<String, Value>) -> bool {
+ let mut regenerated: Vec<(String, LexicalSemanticVectors)> = Vec::new();
+ for (key, meta) in map.iter() {
+ let Some(target) = metadata_target(key) else {
+ continue;
+ };
+ if !is_stripped(meta) {
+ continue;
+ }
+ let text = metadata_field(meta)
+ .and_then(|f| map.get(f))
+ .and_then(Value::as_str);
+ if let Some((pooled, chunks)) = regenerate(meta, text) {
+ regenerated.push((target.to_string(), (pooled, chunks)));
+ }
+ }
+ // A marker whose text is gone (cannot happen for an ingested doc) is
+ // still removed so the metadata reads as written.
+ let any_marker = map
+ .iter()
+ .any(|(key, meta)| metadata_target(key).is_some() && is_stripped(meta));
+ if !any_marker {
+ return false;
+ }
+ let old = std::mem::take(map);
+ for (key, mut value) in old {
+ if let Some(target) = metadata_target(&key) {
+ if is_stripped(&value) {
+ if let Some(meta) = value.as_object_mut() {
+ meta.remove(MARKER_KEY);
+ meta.remove(DIMS_KEY);
+ }
+ if let Some(ix) = regenerated.iter().position(|(t, _)| t == target) {
+ let (target, (pooled, chunks)) = regenerated.swap_remove(ix);
+ map.insert(target.clone(), vector_value(&pooled));
+ map.insert(key, value);
+ if let Some(chunks) = chunks {
+ map.insert(
+ chunks_name(&target),
+ Value::Array(chunks.iter().map(|c| vector_value(c)).collect()),
+ );
+ }
+ continue;
+ }
+ }
+ }
+ map.insert(key, value);
+ }
+ true
+}
+
+/// [`rehydrate_source_map`] over a canonical `[{"_id","_seq_no","_source"}]`
+/// byte array (the legacy LZ4/raw decode). Returns the input unchanged when
+/// no row is stripped.
+pub(super) fn rehydrate_canonical(bytes: Vec<u8>) -> crate::Result<Vec<u8>> {
+ if !contains_marker(&bytes) {
+ return Ok(bytes);
+ }
+ let mut docs: Vec<Value> = serde_json::from_slice(&bytes)
+ .map_err(|e| crate::StorageError::Other(anyhow::anyhow!("rehydrate parse: {e}")))?;
+ for doc in &mut docs {
+ if let Some(source) = doc.get_mut("_source").and_then(Value::as_object_mut) {
+ rehydrate_source_map(source);
+ }
+ }
+ serde_json::to_vec(&docs)
+ .map_err(|e| crate::StorageError::Other(anyhow::anyhow!("rehydrate serialize: {e}")))
+}
+
+pub(super) fn contains_marker(bytes: &[u8]) -> bool {
+ memchr::memmem::find(bytes, MARKER_BYTES).is_some()
+}
+
+/// Whether a reader that keeps the columns `keep` accepts must rebuild
+/// vectors: some passage-metadata column exists and `keep` asks for its
+/// target or the target's chunks.
+pub(super) fn keep_wants_derived<'a>(
+ names: impl Iterator<Item = &'a str>,
+ keep: &dyn Fn(&str) -> bool,
+) -> bool {
+ names
+ .filter_map(metadata_target)
+ .any(|target| keep(target) || keep(&chunks_name(target)))
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+ use serde_json::json;
+
+ pub(crate) fn ingested(text: &str, dims: usize) -> Value {
+ let (pooled, chunks) =
+ xerj_ai::semantic_lexical::lexical_semantic_vectors(text, dims).unwrap();
+ let mut src = Map::new();
+ src.insert("title".into(), json!("t"));
+ src.insert("body".into(), json!(text));
+ src.insert("body_vector".into(), vector_value(&pooled));
+ src.insert(
+ format!("{PASSAGE_METADATA_PREFIX}body_vector"),
+ json!({"field": "body", "chunks": [[0, text.len()]]}),
+ );
+ if let Some(chunks) = chunks {
+ src.insert(
+ "body_vector_chunks".into(),
+ Value::Array(chunks.iter().map(|c| vector_value(c)).collect()),
+ );
+ }
+ Value::Object(src)
+ }
+
+ #[test]
+ fn strip_then_rehydrate_round_trips_short_and_long_text() {
+ for text in [
+ "a short note about rust",
+ &"lorem ipsum dolor sit amet ".repeat(60),
+ ] {
+ let original = ingested(text, 24);
+ let stripped = strip_source(&original).expect("lexical vectors are stripped");
+ let obj = stripped.as_object().unwrap();
+ assert!(!obj.contains_key("body_vector"));
+ assert!(!obj.contains_key("body_vector_chunks"));
+ assert!(is_stripped(
+ &obj[&format!("{PASSAGE_METADATA_PREFIX}body_vector")]
+ ));
+ let mut back = obj.clone();
+ assert!(rehydrate_source_map(&mut back));
+ assert_eq!(Value::Object(back), original);
+ }
+ }
+
+ #[test]
+ fn foreign_vectors_are_kept() {
+ let mut original = ingested("a short note about rust", 8);
+ original["body_vector"] = vector_value(&[0.5; 8]);
+ assert!(strip_source(&original).is_none());
+ let mut long = ingested(&"lorem ipsum dolor sit amet ".repeat(60), 8);
+ long["body_vector_chunks"][0] = vector_value(&[0.5; 8]);
+ assert!(strip_source(&long).is_none());
+ // Edited text no longer derives the stored vector.
+ let mut edited = ingested("a short note about rust", 8);
+ edited["body"] = json!("something else");
+ assert!(strip_source(&edited).is_none());
+ }
+
+ #[test]
+ fn number_array_vectors_are_stripped_and_rebuilt_packed() {
+ let mut original = ingested("a short note about rust", 8);
+ let vector = vector_f32(&original["body_vector"]).unwrap();
+ original["body_vector"] = json!(vector.iter().map(|f| *f as f64).collect::<Vec<_>>());
+ let stripped = strip_source(&original).unwrap();
+ let mut back = stripped.as_object().unwrap().clone();
+ rehydrate_source_map(&mut back);
+ assert_eq!(vector_f32(&back["body_vector"]).unwrap(), vector);
+ }
+
+ #[test]
+ fn documents_without_semantic_fields_are_untouched() {
+ assert!(strip_source(&json!({"a": 1, "b": "x"})).is_none());
+ let mut map = json!({"a": 1}).as_object().unwrap().clone();
+ assert!(!rehydrate_source_map(&mut map));
+ assert!(contains_marker(br#"{"derived":"lexical-v1","dims":8}"#));
+ }
+}
diff --git a/engine/crates/xerj-storage/src/stored_codec/row_hydration.rs b/engine/crates/xerj-storage/src/stored_codec/row_hydration.rs
index 1118d3c4e..6dc37c729 100644
--- a/engine/crates/xerj-storage/src/stored_codec/row_hydration.rs
+++ b/engine/crates/xerj-storage/src/stored_codec/row_hydration.rs
@@ -862,6 +862,32 @@ where
let mut stats = StoredV2RowHydrationStats::default();
let requested: Option<HashSet<&str>> =
source_fields.map(|fields| fields.iter().copied().collect());
+ // #1122/#2433: a row whose derived semantic vectors were stripped gets
+ // them rebuilt from its text when the projection wants them, so decode
+ // every column for it and trim back to the projection afterwards.
+ let wants_derived = {
+ let mut targets = directory
+ .columns
+ .iter()
+ .filter_map(|column| derived_vectors::metadata_target(column.name))
+ .peekable();
+ targets.peek().is_some()
+ && match requested.as_ref() {
+ None => true,
+ Some(fields) => targets.any(|target| {
+ fields.contains(target)
+ || fields.contains(derived_vectors::chunks_name(target).as_str())
+ }),
+ }
+ };
+ let allowed: Option<HashSet<String>> = if wants_derived {
+ requested
+ .as_ref()
+ .map(|fields| fields.iter().map(|field| field.to_string()).collect())
+ } else {
+ None
+ };
+ let requested = if wants_derived { None } else { requested };
let mut columns: Vec<Option<Vec<serde_json::Value>>> =
(0..directory.columns.len()).map(|_| None).collect();
let mut dict_ids = HashMap::new();
@@ -967,6 +993,12 @@ where
stats.output_values_cloned += 1;
}
}
+ if wants_derived {
+ derived_vectors::rehydrate_source_map(&mut source);
+ if let Some(allowed) = allowed.as_ref() {
+ source.retain(|name, _| allowed.contains(name));
+ }
+ }
stats.output_values_cloned += 2;
rows.push(StoredV2HydratedRow {
ordinal,
diff --git a/landing/docs/upgrades.html b/landing/docs/upgrades.html
index 11602f8ee..cedd3bb29 100644
--- a/landing/docs/upgrades.html
+++ b/landing/docs/upgrades.html
@@ -298,6 +298,13 @@ understands format 2.</pre>
<h2>Rolling back</h2>
<p>Roll back by reinstalling the previous binary. That works for every index whose marker is still at a version the previous binary reads; check the <code class="inline">xerj_meta.json</code> files first. An index whose marker has moved past it will not open under the old binary, and rolling it back means restoring the backup you took before the upgrade.</p>
+ <h3>Rolling back past stored <code class="inline">semantic_text</code> vectors</h3>
+ <p>Builds that include PR <a href="https://github.com/xerj-org/xerj/pull/2471">#2471</a> do not store the vectors the built-in lexical embedder derives for a <code class="inline">semantic_text</code> field (<code class="inline">&lt;target&gt;</code> and <code class="inline">&lt;target&gt;_chunks</code>) in a segment's stored <code class="inline">_source</code>; they rebuild them from the text when a document is read. The format marker does not change, so an older binary opens those indices, but it reads the affected documents without vectors: <code class="inline">_source</code> lacks them and semantic and kNN recall drops until the index is reindexed. To roll back without a reindex, first restart the newer binary with <code class="inline">XERJ_STORE_SEMANTIC_VECTORS=1</code> and force-merge each index that has a <code class="inline">semantic_text</code> field. With the variable set, flushes store full vectors and a forcemerge rewrites every segment that holds documents stored without them, including an index that is already one segment:</p>
+<pre class="code">$ sudo systemctl edit xerj # Environment=XERJ_STORE_SEMANTIC_VECTORS=1
+$ sudo systemctl restart xerj
+$ curl -XPOST 'localhost:9200/&lt;index&gt;/_forcemerge?max_num_segments=1'</pre>
+ <p>Vectors from neural, ONNX or proxy embedders, and vectors the caller supplied, are always stored and need no step.</p>
+
<p class="source-note">Source · engine/crates/xerj-server/src/main.rs · engine/crates/xerj-storage/src/index_store.rs (check_data_dir_version) · engine/crates/xerj-fts/src/index.rs (field_file_component)</p>