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): size each record with the server's vectors before sealing (#2807) (#2860)

Jake Elbirt1930a477873b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 22edf2e2a..bcdc49c58 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -490,9 +490,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
refused record came from, and for a size refusal they say how to index the
rest: under a new `--prefix` and `--state-dir`, with the file left out
(`--exclude`) or with `--no-semantic`. That route fixes its file list before
- it sends anything, so it cannot set the file aside, and a rerun repeats the
- refusal. It used to say only "prepared bulk contained 1 rejected items"
- (#2807).
+ it sends anything, so it cannot set a refused file aside. It used to say
+ only "prepared bulk contained 1 rejected items" (#2807).
+- `xerj corpus index` and `xerj autoindex --no-graph` now size each record
+ with the vectors the server will add, before they fix the file list, and
+ set aside a record that would not fit as a junk record. The run completes
+ with exit 3, the file's other records are indexed, and reruns complete too.
+ The 2 MB generated `.d.ts` file from #2807 loses only its whole-file record;
+ its type records are still indexed. That route used to stop on the server's
+ refusal, and every rerun stopped on the same record. A run that an earlier
+ version already stopped this way replays the list it fixed and stops again;
+ index that folder under a new `--prefix` and `--state-dir` (#2807).
## [1.0.0-rc.100] - 2026-10-26
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index fba71d656..dcc557557 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -7468,6 +7468,7 @@ dependencies = [
"tree-sitter-zig",
"uuid",
"walkdir",
+ "xerj-ai",
"xerj-common",
"xerj-wasm",
"xxhash-rust",
diff --git a/engine/crates/xerj-ai/src/semantic_lexical.rs b/engine/crates/xerj-ai/src/semantic_lexical.rs
index 9948a8b38..3a0ec248c 100644
--- a/engine/crates/xerj-ai/src/semantic_lexical.rs
+++ b/engine/crates/xerj-ai/src/semantic_lexical.rs
@@ -24,6 +24,27 @@ pub fn semantic_chunker() -> TextChunker {
TextChunker::new(SEMANTIC_CHUNK_SIZE, SEMANTIC_CHUNK_OVERLAP)
}
+/// UTF-8 byte offsets of the passages ingest embeds for `text`: the chunker's
+/// passages, or the whole text when it cuts one or none. This is the offset
+/// list `xerj-engine` `apply_semantic_embeddings_batch` builds and stores in
+/// the passage metadata, so a client can size a document before it sends it
+/// (#2807, `xerj_common::document_limit::semantic_vector_bytes`).
+pub fn semantic_passage_offsets(text: &str) -> Vec<(usize, usize)> {
+ // A text of at most `SEMANTIC_CHUNK_SIZE` bytes has at most that many
+ // chars, so the chunker returns it whole; skip its per-char pass.
+ if text.len() <= SEMANTIC_CHUNK_SIZE {
+ return vec![(0, text.len())];
+ }
+ let chunks = semantic_chunker().chunk(text, None);
+ if chunks.len() <= 1 {
+ return vec![(0, text.len())];
+ }
+ chunks
+ .iter()
+ .map(|chunk| (chunk.start_offset, chunk.end_offset))
+ .collect()
+}
+
/// 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
@@ -104,6 +125,31 @@ pub fn lexical_semantic_vectors(text: &str, dims: usize) -> Option<LexicalSemant
mod tests {
use super::*;
+ #[test]
+ fn passage_offsets_match_the_chunker_on_both_sides_of_the_fast_path() {
+ // #2807: the short-text shortcut must give what the chunker gives.
+ let multibyte = "é".repeat(300); // 600 bytes, 300 chars: one passage
+ let long = "Word after word. ".repeat(100);
+ for text in ["", "short", multibyte.as_str(), long.as_str()] {
+ let chunks = semantic_chunker().chunk(text, None);
+ let expected: Vec<(usize, usize)> = if chunks.len() <= 1 {
+ vec![(0, text.len())]
+ } else {
+ chunks
+ .iter()
+ .map(|c| (c.start_offset, c.end_offset))
+ .collect()
+ };
+ assert_eq!(
+ semantic_passage_offsets(text),
+ expected,
+ "{} bytes",
+ text.len()
+ );
+ }
+ assert!(semantic_passage_offsets(&long).len() > 1);
+ }
+
#[test]
fn short_text_is_one_unpooled_passage() {
let (pooled, chunks) = lexical_semantic_vectors("a short passage", 16).unwrap();
diff --git a/engine/crates/xerj-autoindex/Cargo.toml b/engine/crates/xerj-autoindex/Cargo.toml
index f2a56aa3a..e8986b5a7 100644
--- a/engine/crates/xerj-autoindex/Cargo.toml
+++ b/engine/crates/xerj-autoindex/Cargo.toml
@@ -12,6 +12,9 @@ description = "xerj autoindex — point it at any folder and make the contents A
xerj-common = { path = "../xerj-common" }
# Session exports use the same native PII redactor as ingest pipelines.
xerj-wasm = { path = "../xerj-wasm" }
+# #2807: the server's own semantic chunker, so preparation can size a record
+# with the vectors the server will add. Default features only: no embedder.
+xerj-ai = { path = "../xerj-ai", default-features = false }
uuid.workspace = true
anyhow.workspace = true
serde.workspace = true
diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
index dcd9e7211..21912d80c 100644
--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
@@ -28,6 +28,9 @@ struct HttpState {
/// #2807: refuse the first `index` action of the next data bulk as over
/// the per-document byte limit, echoing its `_id` as the server does.
refuse_next_data_item_as_too_large: bool,
+ /// #2807: refuse any record longer than this many bytes, as the server
+ /// refuses a record that the vectors it adds push over its limit.
+ refuse_documents_over: Option<usize>,
/// Apply the first half of the next data bulk's items and *then* report
/// `errors: true`. This is the dangerous backend shape the legacy
/// replacement transaction was hardened against (visibility changed, but
@@ -613,6 +616,37 @@ fn bulk_http(body: &[u8], state: &Arc<Mutex<HttpState>>) -> (u16, Value) {
}),
);
}
+ if let Some(limit) = locked.refuse_documents_over {
+ // Pair each action with its source line; a `delete` has none.
+ let mut refused = None;
+ let mut rest = lines.iter();
+ while let Some(line) = rest.next() {
+ let action: Value = serde_json::from_slice(line).unwrap();
+ if action.get("delete").is_none()
+ && rest.next().is_some_and(|source| source.len() > limit)
+ {
+ refused = Some(action);
+ break;
+ }
+ }
+ if let Some(action) = refused {
+ return (
+ 200,
+ json!({
+ "errors": true,
+ "items": [{"index": {
+ "_id": action["index"]["_id"],
+ "status": 413,
+ "error": {
+ "type": "engine_exception",
+ "reason": "document is 16590136 bytes, over the 8388608 byte limit for one indexed JSON document; it was not indexed. Split it into smaller documents",
+ "status": 413
+ }
+ }}]
+ }),
+ );
+ }
+ }
if std::mem::take(&mut locked.fail_next_data_bulk) || numbered {
return (
200,
@@ -7736,3 +7770,64 @@ fn a_record_refused_for_size_on_the_generated_path_names_its_file() {
);
assert!(!error.contains("prepared bulk contained"), "{error}");
}
+
+/// #2807: the server adds the semantic vectors to a record before it checks
+/// the per-document limit, so a 2 MB generated `.d.ts` grows past it. The
+/// generated (`--no-graph`) path, which `xerj corpus index` uses, seals before
+/// it sends, so a refusal there stopped every rerun of the same generation.
+/// Preparation now sizes each record as the server will see it and sets the
+/// one that would not fit aside as a junk record: the run completes with
+/// junk, the file's other records are indexed, and reruns complete too.
+#[test]
+fn a_record_too_large_once_vectors_are_added_is_set_aside_before_sealing() {
+ let _guard = HTTP_E2E_LOCK.lock().unwrap_or_else(|p| p.into_inner());
+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK
+ .lock()
+ .unwrap_or_else(|p| p.into_inner());
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ fs::write(corpus.path().join("a.csv"), "id,value\n1,alpha\n").unwrap();
+ fs::create_dir(corpus.path().join("src")).unwrap();
+ let mut generated = String::from("declare namespace Generated {\n");
+ let mut n = 0;
+ while generated.len() < 2_000_000 {
+ generated.push_str(&format!(
+ " interface Shape{n} {{ id: number; label: string; parent?: Shape{}; tags: string[] }}\n",
+ n.max(1) - 1
+ ));
+ n += 1;
+ }
+ generated.push_str("}\n");
+ fs::write(corpus.path().join("src/generated.d.ts"), generated).unwrap();
+ let endpoint = HttpEndpoint::start();
+ // Stands in for the server: the whole-file record is about 2.6 MB as
+ // sent, and the vectors take it past 8 MiB. Every other record is small.
+ endpoint.state.lock().unwrap().refuse_documents_over = Some(1 << 20);
+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, true);
+
+ let (code, summary) =
+ run_index_report(config.clone()).unwrap_or_else(|error| panic!("{error:#}"));
+ let summary = summary.expect("the generation commits");
+ assert_eq!(code, 3, "completed-with-junk: {summary}");
+ assert_eq!(summary["junk_records_total"], 1, "{summary}");
+ let docs = serde_json::to_string(&endpoint.data_docs()).unwrap();
+ assert!(docs.contains("alpha"), "the other file is indexed");
+ assert!(
+ docs.contains("Shape1"),
+ "the file's symbol records are indexed"
+ );
+ let file_doc = endpoint
+ .catalog_docs()
+ .into_iter()
+ .find(|doc| doc["doc_kind"] == "file" && doc["path"] == "src/generated.d.ts")
+ .expect("the file keeps its catalog document");
+ assert_eq!(file_doc["junk"], 1, "{file_doc}");
+
+ // The rerun replays nothing stuck: it completes, and an edit lands.
+ fs::write(corpus.path().join("a.csv"), "id,value\n1,beta\n").unwrap();
+ let code = run_index(config).unwrap_or_else(|error| panic!("{error:#}"));
+ assert_eq!(code, 3);
+ let docs = serde_json::to_string(&endpoint.data_docs()).unwrap();
+ assert!(docs.contains("beta"), "the edit is indexed");
+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 2);
+}
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 42330c25d..cefa89979 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -2222,6 +2222,32 @@ fn begin_non_graph_generation(
.map(|_| sync_executor::open_committed_snapshot(state_dir, &base))
.transpose()?;
let chunker_identity = prepared_records_identity(cfg)?;
+ // #2807: read the embedding identity before sealing, so preparation can
+ // size each record with the vectors the server will add. The same
+ // identity is pinned after the seal.
+ let semantic = plan
+ .datasets
+ .iter()
+ .any(|dataset| dataset.semantic_field.is_some());
+ let embedding_identity = if semantic {
+ let identity = es
+ .embedding_execution_identity()
+ .context("generation cutover could not pin the server embedding execution identity")?;
+ anyhow::ensure!(
+ identity.resumable,
+ "generation cutover requires a resumable embedding execution identity: {}",
+ identity
+ .non_resumable_reason
+ .as_deref()
+ .unwrap_or("the server did not provide an immutable identity")
+ );
+ Some(identity)
+ } else {
+ None
+ };
+ let vector_dims = embedding_identity
+ .as_ref()
+ .and_then(|identity| identity.dimensions);
let (snapshot, mut groups) = {
let mut prepared = None;
let mut groups_out = None;
@@ -2290,6 +2316,7 @@ fn begin_non_graph_generation(
prior_snapshot.as_ref(),
&chunker_identity,
labeler,
+ vector_dims,
) {
Ok(snapshot) => {
prepared = Some(snapshot);
@@ -2338,22 +2365,7 @@ fn begin_non_graph_generation(
.filter_map(|f| plan.files.get(&f.content_id).map(|a| a.rel.clone()))
.collect();
note_truncated_files(pr, &truncated);
- let semantic = plan
- .datasets
- .iter()
- .any(|dataset| dataset.semantic_field.is_some());
- let identity = if semantic {
- let identity = es
- .embedding_execution_identity()
- .context("generation cutover could not pin the server embedding execution identity")?;
- anyhow::ensure!(
- identity.resumable,
- "generation cutover requires a resumable embedding execution identity: {}",
- identity
- .non_resumable_reason
- .as_deref()
- .unwrap_or("the server did not provide an immutable identity")
- );
+ let identity = if let Some(identity) = embedding_identity {
journal.pin_embedding_identity(
&identity.identity_sha256,
identity.resumable,
diff --git a/engine/crates/xerj-autoindex/src/sync_executor.rs b/engine/crates/xerj-autoindex/src/sync_executor.rs
index 75ac2c763..2bd311c12 100644
--- a/engine/crates/xerj-autoindex/src/sync_executor.rs
+++ b/engine/crates/xerj-autoindex/src/sync_executor.rs
@@ -3166,6 +3166,7 @@ pub fn create_snapshot(
// The source-snapshot wrapper has no plan and therefore never runs
// `prepare_artifact`; a labeler would have nothing to vote on.
None,
+ None,
)
}
@@ -3195,6 +3196,8 @@ pub fn create_prepared_snapshot(
"prepared-records-v1",
// Test-only wrapper: no `--label` in these snapshots' contracts.
None,
+ // Test-only wrapper: no server vectors to size records against.
+ None,
)
}
@@ -3212,6 +3215,13 @@ pub fn create_prepared_snapshot(
/// one-file change seals O(changed) new bytes. `chunker_identity` is the run's
/// `prepared_records_identity` and becomes part of each file's sealed
/// preparation identity.
+///
+/// #2807: `vector_dims` is the width of the vectors the server adds to each
+/// record's semantic field, from its embedding identity. A record that would
+/// pass [`xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES`] once they
+/// are added is set aside as a junk record instead of sealed. `None` sizes
+/// records without vectors. The width is pinned in the generation's execution
+/// identity, so a reused artifact was sized against the same width.
#[allow(clippy::too_many_arguments)]
pub fn create_prepared_snapshot_reporting(
state_dir: &Path,
@@ -3224,6 +3234,7 @@ pub fn create_prepared_snapshot_reporting(
reuse: Option<&SourceSnapshot>,
chunker_identity: &str,
labeler: Option<&crate::label::Labeler>,
+ vector_dims: Option<usize>,
) -> Result<SourceSnapshot> {
create_snapshot_inner(
state_dir,
@@ -3236,6 +3247,7 @@ pub fn create_prepared_snapshot_reporting(
reuse,
chunker_identity,
labeler,
+ vector_dims,
)
}
@@ -3251,6 +3263,7 @@ fn create_snapshot_inner(
reuse: Option<&SourceSnapshot>,
chunker_identity: &str,
labeler: Option<&crate::label::Labeler>,
+ vector_dims: Option<usize>,
) -> Result<SourceSnapshot> {
validate_tx_id(tx_id)?;
ensure_inventory_lengths(inventory)?;
@@ -3463,6 +3476,8 @@ fn create_snapshot_inner(
lookup.as_ref().expect("assignment implies a plan"),
&mut budget,
labeler,
+ vector_dims,
+ pr,
)?),
None => None,
},
@@ -3511,6 +3526,8 @@ fn create_snapshot_inner(
lookup.as_ref().expect("assignment implies a plan"),
&mut budget,
labeler,
+ vector_dims,
+ pr,
)?),
None => None,
};
@@ -3736,6 +3753,8 @@ fn prepare_artifact(
// differently-labelled) NDJSON. `None` — the default, and every caller
// without `--label` — seals unlabelled exactly as before.
labeler: Option<&crate::label::Labeler>,
+ vector_dims: Option<usize>,
+ pr: &crate::progress::Progress,
) -> Result<PreparedArtifact> {
let datasets = &lookup.datasets;
let coercions = &lookup.coercions;
@@ -3766,6 +3785,9 @@ fn prepare_artifact(
let mut records_by_dataset: BTreeMap<String, u64> = BTreeMap::new();
let mut passages = 0u64;
let mut vectors = 0u64;
+ // Records set aside for size, and the first one's locator and size.
+ let mut oversized = 0u64;
+ let mut first_oversized: Option<(String, usize, bool)> = None;
let mut sink_error: Option<anyhow::Error> = None;
let mut sink = |record: crate::extract::RawRecord| -> bool {
let Some(slug) = assignments
@@ -3833,10 +3855,39 @@ fn prepare_artifact(
}
}
}
+ let semantic = dataset
+ .semantic_field
+ .as_ref()
+ .is_some_and(|field| fields.get(field).is_some());
+ // #2807: the server adds the semantic vectors before it checks the
+ // per-document limit, so a record well under it can be refused, and a
+ // refusal after sealing stops every rerun of this generation. Size the
+ // record as the server will see it, and set it aside as a junk record
+ // when it would not fit. The file's other records are still indexed.
+ let vector_bytes = match (vector_dims, dataset.semantic_field.as_deref()) {
+ (Some(dims), Some(field)) => {
+ fields.get(field).and_then(Value::as_str).map_or(0, |text| {
+ xerj_common::document_limit::semantic_vector_bytes(
+ field,
+ &format!("{field}_vector"),
+ dims,
+ &xerj_ai::semantic_lexical::semantic_passage_offsets(text),
+ )
+ })
+ }
+ _ => 0,
+ };
+ let document = Value::Object(fields).to_string();
+ let indexed_bytes = document.len().saturating_add(vector_bytes);
+ if xerj_common::document_limit::indexed_document_too_large(indexed_bytes) {
+ oversized += 1;
+ first_oversized.get_or_insert((record.locator, indexed_bytes, vector_bytes > 0));
+ return true;
+ }
let id = crate::ids::doc_id(slug, content_id, &record.locator);
let action = serde_json::json!({"index": {"_index": dataset.index, "_id": id}});
- if let Err(error) = writeln!(writer, "{action}")
- .and_then(|_| writeln!(writer, "{}", Value::Object(fields.clone())))
+ if let Err(error) =
+ writeln!(writer, "{action}").and_then(|_| writeln!(writer, "{document}"))
{
sink_error = Some(anyhow::Error::new(error).context("write prepared NDJSON"));
return false;
@@ -3846,11 +3897,7 @@ fn prepare_artifact(
// under, so a file that fans out over several datasets stays reconcilable
// against each one separately.
*records_by_dataset.entry(slug.to_string()).or_default() += 1;
- if dataset
- .semantic_field
- .as_ref()
- .is_some_and(|field| fields.get(field).is_some())
- {
+ if semantic {
passages += 1;
vectors += 1;
}
@@ -3895,6 +3942,23 @@ fn prepare_artifact(
if let Some(error) = sink_error {
return Err(error);
}
+ if let Some((locator, indexed_bytes, with_vectors)) = first_oversized {
+ let (sized, remedy) = if with_vectors {
+ (
+ "with the vectors the server adds, ",
+ "; --no-semantic indexes it without vectors",
+ )
+ } else {
+ ("", "")
+ };
+ pr.note(&format!(
+ "warning: {} had {oversized} record(s) set aside as junk: {sized}record \
+ {locator} would be {indexed_bytes} bytes, over the {} byte limit for one \
+ document. The file's other records are indexed{remedy}",
+ source.rel,
+ xerj_common::document_limit::MAX_INDEXED_DOCUMENT_BYTES,
+ ));
+ }
writer.flush()?;
writer.inner.get_ref().sync_all()?;
drop(writer);
@@ -3904,7 +3968,7 @@ fn prepare_artifact(
records,
passages,
vectors,
- junk: stats.junk,
+ junk: stats.junk + oversized,
truncated: stats.truncated,
records_by_dataset,
bytes,
@@ -4438,6 +4502,7 @@ mod tests {
None,
"chunker-v1",
None,
+ None,
)
.unwrap();
assert_eq!(first.files.len(), 3);
@@ -4474,6 +4539,7 @@ mod tests {
Some(&first),
"chunker-v1",
None,
+ None,
)
.unwrap();
@@ -4649,6 +4715,7 @@ mod tests {
prior,
"chunker-v1",
None,
+ None,
)
.unwrap();
(snapshot, source)
@@ -4745,6 +4812,7 @@ mod tests {
None,
"chunker-v1",
None,
+ None,
)
.unwrap();
std::fs::write(corpus.path().join("b.md"), "bravo contents CHANGED\n").unwrap();
@@ -4761,6 +4829,7 @@ mod tests {
Some(&first),
"chunker-v1",
None,
+ None,
)
.unwrap();
@@ -4799,6 +4868,7 @@ mod tests {
None,
"chunker-v1",
None,
+ None,
)
.unwrap();
let second = create_prepared_snapshot_reporting(
@@ -4812,6 +4882,7 @@ mod tests {
Some(&first),
"chunker-v2",
None,
+ None,
)
.unwrap();
let key = &inventory.keys[0];
diff --git a/engine/crates/xerj-common/src/document_limit.rs b/engine/crates/xerj-common/src/document_limit.rs
index a536b19c6..b0ef44f5b 100644
--- a/engine/crates/xerj-common/src/document_limit.rs
+++ b/engine/crates/xerj-common/src/document_limit.rs
@@ -124,6 +124,62 @@ fn exceeds(value: &Value, accounted: &mut usize) -> bool {
}
}
+/// Name prefix of the passage metadata member the server writes beside each
+/// semantic vector. Equal to `xerj_query::executor::PASSAGE_METADATA_PREFIX`.
+const PASSAGE_METADATA_PREFIX: &str = "__xerj_passage_meta__";
+
+/// Bytes the server adds to a document's compact JSON when it embeds one
+/// `semantic_text` field (#2807).
+///
+/// The server checks [`MAX_INDEXED_DOCUMENT_BYTES`] after it has added the
+/// vectors, so a client that needs to know whether a record fits adds this to
+/// the record's own length. `passages` are the UTF-8 byte offsets ingest
+/// embeds (`xerj_ai::semantic_lexical::semantic_passage_offsets`), and `dims`
+/// is the vector width the server reports. The count follows what
+/// `xerj-engine` `apply_semantic_embeddings_batch` inserts: the pooled
+/// vector, the passage metadata, and one vector per passage when there is
+/// more than one. Every member is charged a separating comma, so the result is
+/// one byte high for a document that had no other member. It assumes every
+/// vector packs (`packed_f32`); the server writes a vector with a non-finite
+/// value as a longer number array, which this does not count.
+pub fn semantic_vector_bytes(
+ field: &str,
+ target: &str,
+ dims: usize,
+ passages: &[(usize, usize)],
+) -> usize {
+ if passages.is_empty() {
+ return 0;
+ }
+ // `,"key":value`
+ let member = |key: &str, value: usize| 2 + json_string_len(key) + value;
+ let packed = crate::packed_f32::PACKED_F32_PREFIX.len() + 8 * dims + 2;
+ // `[[start,end],...]`
+ let offsets = 1 + passages
+ .iter()
+ .map(|&(start, end)| 4 + decimal_len(start) + decimal_len(end))
+ .sum::<usize>();
+ // `{"field":"…","chunks":[…]}`: two braces, and no comma before the first member.
+ let metadata = 2 + member("field", json_string_len(field)) + member("chunks", offsets) - 1;
+ let mut bytes =
+ member(target, packed) + member(&format!("{PASSAGE_METADATA_PREFIX}{target}"), metadata);
+ if passages.len() > 1 {
+ bytes += member(
+ &format!("{target}_chunks"),
+ 1 + passages.len() * (packed + 1),
+ );
+ }
+ bytes
+}
+
+fn json_string_len(text: &str) -> usize {
+ serde_json::to_string(text).map_or(text.len() * 6 + 2, |json| json.len())
+}
+
+fn decimal_len(n: usize) -> usize {
+ n.checked_ilog10().map_or(1, |digits| digits as usize + 1)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -185,6 +241,43 @@ mod tests {
assert!(at_least.contains("not indexed"));
}
+ #[test]
+ fn semantic_vector_bytes_matches_what_the_server_inserts() {
+ // The members `apply_semantic_embeddings_batch` writes, built the
+ // same way. A change to that shape has to change this function too.
+ let vector = |seed: f32| vec![seed; 384];
+ for passages in [
+ vec![(0usize, 7usize)],
+ vec![(0, 512), (448, 960), (896, 10_042)],
+ ] {
+ let mut doc = json!({"title": "t", "body": "text"});
+ let object = doc.as_object_mut().unwrap();
+ let before = Value::Object(object.clone()).to_string().len();
+ let packed =
+ |seed| Value::String(crate::packed_f32::pack_f32_vector(&vector(seed)).unwrap());
+ object.insert("body_vector".into(), packed(0.5));
+ let offsets: Vec<Value> = passages
+ .iter()
+ .map(|&(start, end)| json!([start, end]))
+ .collect();
+ object.insert(
+ "__xerj_passage_meta__body_vector".into(),
+ json!({"field": "body", "chunks": offsets}),
+ );
+ if passages.len() > 1 {
+ let chunks: Vec<Value> = (0..passages.len()).map(|i| packed(i as f32)).collect();
+ object.insert("body_vector_chunks".into(), Value::Array(chunks));
+ }
+ let after = doc.to_string().len();
+ assert_eq!(
+ semantic_vector_bytes("body", "body_vector", 384, &passages),
+ after - before,
+ "{passages:?}"
+ );
+ }
+ assert_eq!(semantic_vector_bytes("body", "body_vector", 384, &[]), 0);
+ }
+
#[test]
fn a_small_value_is_under_the_limit_and_a_long_string_is_not() {
assert!(json_value_exceeds_indexed_document_limit(&json!({"id": 1})).is_none());
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 4432c2320..b22389ad7 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -8335,6 +8335,57 @@ mod semantic_deadline_regression_tests {
);
}
+ /// #2807: this server checks the per-document limit after it adds the
+ /// vectors, so autoindex sizes each record before it sends it with
+ /// `xerj_common::document_limit::semantic_vector_bytes`. A change to what
+ /// `apply_semantic_embeddings_batch` writes has to change that function.
+ #[tokio::test]
+ async fn semantic_vector_bytes_is_what_embedding_adds() {
+ let dir = TempDir::new().unwrap();
+ let engine_instance = engine(&dir);
+ let mut schema = Schema::empty();
+ let mut body = FieldConfig::new("body", FieldType::Text);
+ body.options.dimensions = Some(384);
+ body.options.similarity = Some("cosine".into());
+ body.embedding = Some(xerj_common::types::EmbeddingConfig {
+ endpoint: None,
+ model: None,
+ target_field: Some("body_vector".into()),
+ });
+ schema.add_field(body).unwrap();
+ let mut companion = FieldConfig::new("body_vector", FieldType::Vector);
+ companion.options.dimensions = Some(384);
+ companion.options.similarity = Some("cosine".into());
+ schema.add_field(companion).unwrap();
+ engine_instance
+ .create_index("sized-passages", schema)
+ .unwrap();
+ let idx = engine_instance.get_index("sized-passages").unwrap();
+
+ for text in [
+ "One short passage, caf\u{e9}.".to_string(),
+ "The quick brown fox jumps over the lazy dog. Pack my box with five dozen liquor jugs. "
+ .repeat(40),
+ ] {
+ let passages = xerj_ai::semantic_lexical::semantic_passage_offsets(&text);
+ let source = serde_json::json!({"title": "t", "body": text});
+ let before = serde_json::to_vec(&source).unwrap().len();
+ let embedded = idx.apply_semantic_embeddings(source).await.unwrap();
+ let after = serde_json::to_vec(&embedded).unwrap().len();
+ assert_eq!(
+ after - before,
+ xerj_common::document_limit::semantic_vector_bytes(
+ "body",
+ "body_vector",
+ 384,
+ &passages
+ ),
+ "{} passages",
+ passages.len()
+ );
+ }
+ }
+
#[tokio::test]
async fn mixed_short_and_chunked_semantic_docs_use_exact_passage_winner() {
let dir = TempDir::new().unwrap();