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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
feat(ai): ingest-time chunk-embedding pipeline (per-passage vectors)
xerj-org661997712496
diff --git a/README.md b/README.mdindex 0f9e2d6bb..1205d196a 100644--- a/README.md+++ b/README.md@@ -249,10 +249,12 @@ If a test expects a response and XERJ returns something different, that's a bugXERJ ships full-text, aggregation, log-analytics, dense-vector kNN, and hybrid search. **rc-2** added three AI-adjacent capabilities (each conformance-gated and verified by real requests):- **Auto-embed on ingest + a built-in embedder** — `semantic_text` works with zero external config; the built-in embedder is lexical (a bundled *neural* model is still future work).+- **Ingest-time chunk-embedding** — long `semantic_text` values embed **per overlapping passage**, and `semantic` search scores by the best-matching passage (max-sim), so a long document is retrievable on any one of its sections.- **Agent-memory REST API** — `POST /_memory/{ns}` store, `/_recall` (kNN or BM25 + metadata filter), list/forget/drop; namespaced and offline.-- **Anomaly detection (`_ml`)** — real statistical detectors with baseline + deviation scoring (on-demand; continuous datafeeds and forecasting are future work).+- **Anomaly detection (`_ml`)** — real statistical detectors with baseline + deviation scoring, on-demand **and** via continuous `_ml/datafeeds` (a background job re-scores a live index on a timer; forecasting is still future work).+- **Vector quantization** — opt a `dense_vector` field into **scalar8** (`int8_hnsw`) for ~4× smaller vectors at recall@10 ≈ 0.99.-Still planned: a bundled neural embedding model, an ingest-time chunk-embedding pipeline, continuous anomaly datafeeds, and distributed-clustering hardening. See [ROADMAP.md](./ROADMAP.md) for the full status and honest limitations.+Still planned: a bundled neural embedding model and distributed-clustering hardening. See [ROADMAP.md](./ROADMAP.md) for the full status and honest limitations.---diff --git a/ROADMAP.md b/ROADMAP.mdindex bc0ff10db..50ee296ba 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -40,7 +40,29 @@ A namespaced agent-memory API, backed by regular XERJ indices (reusing documentA real statistical detector replaces the empty compat stubs:`PUT /_ml/anomaly_detectors/{id}` (create: source index, time field, function `count|mean|min|max|sum`, bucket span, threshold), `GET` (fetch/list — returns real jobs), `POST /_ml/anomaly_detectors/{id}/_score` (buckets the source over time, builds a moving mean/stddev baseline, flags buckets deviating beyond the threshold with a normalized anomaly score), `DELETE`. Live-verified: a 500-value spike among 24 baseline buckets of ~10 was correctly flagged (`is_anomaly:true`, `anomaly_score:100`), and `DELETE` removed the job from subsequent `GET`s.-- **Limitation:** on-demand scoring only (`POST _score`) — no continuous datafeed scheduler, no forecasting, no influencers/model-plot, single-node config registry. When the baseline std_dev is 0 the z-score is a placeholder (`1000000`). `_cat/ml/datafeeds` and `_cat/ml/trained_models` remain valid empty stubs.+- **Limitation:** on-demand scoring only (`POST _score`) — no continuous datafeed scheduler, no forecasting, no influencers/model-plot, single-node config registry. When the baseline std_dev is 0 the z-score is a placeholder (`1000000`). `_cat/ml/datafeeds` and `_cat/ml/trained_models` remain valid empty stubs. (The continuous datafeed scheduler has since landed — see below.)++## Landed since rc-2 (on `main`, unreleased)++These shipped after rc-2 during the RC3 gap-closure and AI-use-case pass. Each is conformance-gated (full ES-compat YAML suite green) and ships a runnable recipe + docs.++### 4. Real scalar8 vector quantization (serving path) ✅++A `dense_vector` field can opt into **scalar8** (int8) quantization via `index_options.type: int8_hnsw`. The kNN *serving* path scores against 1-byte-per-dimension codes (≈4× smaller vector working set) while `_source` still returns the original float32 vectors. Live-verified on a 128-dim corpus: **recall@10 ≈ 0.99** vs exact float32, footprint 512 → 128 B/vec. Recipe: `recipes/vector_quantization.py`; guide: `docs/recipes/vector-quantization.md`.++- **Limitation:** `binary` (1-bit) is still rejected at startup rather than faked; scalar4/offload remain future work.++### 5. Continuous anomaly datafeeds (`_ml/datafeeds`) ✅++The datafeed scheduler that rc-2 lacked: `PUT/GET/DELETE /_ml/datafeeds/{id}` + `_start`/`_stop`, and `GET /_ml/anomaly_detectors/{job}/results/records`. A background task re-buckets a live index on a timer and appends newly-flagged anomaly records you poll — a second spike is detected with no second call. Live-verified end-to-end. Recipe: `recipes/anomaly_datafeed.py`; guide: `docs/recipes/continuous-anomaly-datafeeds.md`.++- **Limitation:** single-node scheduler; no forecasting/influencers.++### 6. Ingest-time chunk-embedding pipeline (per-passage vectors) ✅++Long `semantic_text` values are split into overlapping passages, embedded **per passage**, and the per-passage vectors persisted (in `<field>_vector_chunks`, only when a value spans >1 passage). A `semantic` query scores each document by its **best-matching passage** (max-sim) instead of a single pooled vector, so a long document competes on any one of its sections. Live-verified: on 40 articles + a compendium of all 40, the compendium reached top-3 for **98%** of single-topic queries with per-passage scoring vs **32%** pooled. Short single-passage values are byte-identical to before. Recipe: `recipes/passage_search.py`; guide: `docs/recipes/passage-retrieval.md`.++- **Limitation:** the built-in embedder is still lexical (per-passage vectors are only as good as the embedder); a bundled neural model remains future work. A field that is *also* scalar8-quantized scores against the pooled vector (per-passage max-sim is exact-f32 only).## Partial / in progress@@ -82,8 +104,7 @@ Counting these toward "supported query types" overstates correctness — they re### Neural embeddings & richer ML- A bundled/local **neural** embedding model (the current built-in embedder is lexical).-- An ingest-time embedding pipeline with the existing text chunker (overlapping chunks → per-chunk vectors).-- Continuous anomaly datafeeds (real-time jobs) and forecasting for capacity/write-load signals.+- Forecasting for capacity/write-load signals (continuous `_ml` datafeeds have landed — see "Landed since rc-2"; the ingest-time per-passage chunk-embedding pipeline has also landed).### Correctness of stubbed surfacediff --git a/docs/examples/passage-retrieval/passage_demo.py b/docs/examples/passage-retrieval/passage_demo.pynew file mode 100644index 000000000..0866261ee--- /dev/null+++ b/docs/examples/passage-retrieval/passage_demo.py@@ -0,0 +1,149 @@+#!/usr/bin/env python3+"""passage_search.py — per-passage retrieval on long documents.++XERJ's ingest-time chunk-embedding pipeline: a ``semantic_text`` field+auto-embeds *each overlapping passage* of a long document, and a ``semantic``+query scores a document by its BEST-matching passage (max-sim) rather than a+single blurred whole-document vector. That is what lets a query about one topic+find a long document that only covers that topic in one section.++Real workload (deterministic, offline)+--------------------------------------+Index 40 real AI-engineering articles (``demo/data/ai_kb.ndjson``) as short+docs, PLUS one long "compendium" doc containing all 40 concatenated. Then run+each article's title as a query and ask: **can the long compendium — which+contains every topic as one passage — compete for the top ranks?**++* **per-passage** (``semantic_text`` + ``semantic``): the compendium's matching+ passage is scored undiluted, so it consistently lands near the top.+* **pooled** (``dense_vector`` + ``knn``): the compendium is a single vector+ averaging 40 topics, so any one query barely registers against it and it is+ buried below the 40 undiluted short docs.++Both arms use XERJ's own server-side embedder (the pooled baseline reuses+XERJ's ``<field>_vector`` read back out of ``_source``), so the only variable+is pooled-vs-per-passage. We report how often the compendium reaches the top-3.++Run: python3 recipes/passage_search.py (honors $XERJ_URL, default :9200)+"""+import json+import os+import sys+import urllib.error+import urllib.request++URL = os.environ.get("XERJ_URL", "http://localhost:9200").rstrip("/")+HERE = os.path.dirname(os.path.abspath(__file__))+KB = os.path.join(HERE, "..", "demo", "data", "ai_kb.ndjson")+TOPK = 3+++def req(method, path, body=None, quiet=False):+ data = json.dumps(body).encode() if body is not None else None+ r = urllib.request.Request(+ URL + path, data=data, headers={"Content-Type": "application/json"}, method=method+ )+ try:+ with urllib.request.urlopen(r) as resp:+ return json.load(resp)+ except urllib.error.HTTPError as e:+ if not quiet:+ sys.stderr.write(f"HTTP {e.code} {method} {path}\n{e.read().decode()[:500]}\n")+ raise+++def recreate(index, mappings):+ try:+ req("DELETE", "/" + index, quiet=True)+ except urllib.error.HTTPError:+ pass+ req("PUT", "/" + index, {"mappings": {"properties": mappings}})+++def rank_of(hits, doc_id):+ """1-based rank of doc_id in a hits list, or None if absent."""+ for i, h in enumerate(hits, 1):+ if h["_id"] == doc_id:+ return i+ return None+++def main():+ with open(KB, encoding="utf-8") as fh:+ articles = [json.loads(line) for line in fh if line.strip()]+ if len(articles) < 10:+ sys.exit("need at least 10 KB articles")++ print(f"XERJ at {URL}")+ print(f"{len(articles)} short article docs + 1 long compendium of all {len(articles)}\n")++ recreate("kb-passages", {"body": {"type": "semantic_text"}})+ recreate("kb-pooled", {"vec": {"type": "dense_vector", "dims": 384, "similarity": "cosine"}})+ # Probe index: index a short string, read back XERJ's own embedding of it so+ # the pooled `knn` baseline is driven by the same server-side embedder.+ recreate("kb-probe", {"body": {"type": "semantic_text"}})++ def embed(text):+ req("PUT", "/kb-probe/_doc/q?refresh=true", {"body": text})+ return req("GET", "/kb-probe/_doc/q")["_source"]["body_vector"]++ # Short article docs into both arms. For a short (single-chunk) doc the+ # pooled companion IS the article's embedding, so the baseline is exact.+ for i, art in enumerate(articles):+ body = f"{art['title']}. {art['content']}"+ req("PUT", f"/kb-passages/_doc/a{i}?refresh=true", {"body": body})+ vec = req("GET", f"/kb-passages/_doc/a{i}")["_source"]["body_vector"]+ req("PUT", f"/kb-pooled/_doc/a{i}?refresh=true", {"vec": vec})++ # One long compendium containing every article as a passage.+ compendium = "\n\n".join(f"{a['title']}. {a['content']}" for a in articles)+ req("PUT", "/kb-passages/_doc/compendium?refresh=true", {"body": compendium})+ comp_src = req("GET", "/kb-passages/_doc/compendium")["_source"]+ n_passages = len(comp_src.get("body_vector_chunks", []))+ print(f"compendium embedded into {n_passages} passage vectors "+ f"(pooled into 1 whole-doc vector of {len(comp_src['body_vector'])} dims)\n")+ if n_passages < 5:+ sys.exit("FAIL: compendium did not produce multiple passage vectors")+ req("PUT", "/kb-pooled/_doc/compendium?refresh=true", {"vec": comp_src["body_vector"]})++ pp_topk = 0+ po_topk = 0+ pp_ranks = []+ po_ranks = []+ for art in articles:+ title = art["title"]+ sem = req("POST", "/kb-passages/_search", {+ "size": TOPK,+ "query": {"semantic": {"field": "body", "query": title, "k": 50}},+ })+ # Server-embed the query via the probe index for the pooled arm.+ qv = embed(title)+ pool = req("POST", "/kb-pooled/_search", {+ "size": TOPK,+ "knn": {"field": "vec", "query_vector": qv, "k": 50},+ })+ pr = rank_of(sem["hits"]["hits"], "compendium")+ qr = rank_of(pool["hits"]["hits"], "compendium")+ pp_ranks.append(pr)+ po_ranks.append(qr)+ pp_topk += pr is not None+ po_topk += qr is not None++ n = len(articles)+ pp_rate = pp_topk / n+ po_rate = po_topk / n+ print(f"compendium reached the top-{TOPK}:")+ print(f" per-passage : {pp_topk}/{n} ({pp_rate:.0%})")+ print(f" pooled : {po_topk}/{n} ({po_rate:.0%})")++ if pp_rate < 0.75:+ sys.exit(f"FAIL: per-passage top-{TOPK} rate {pp_rate:.2f} < 0.75")+ if pp_rate <= po_rate:+ sys.exit(f"FAIL: per-passage ({pp_rate:.2f}) did not beat pooled ({po_rate:.2f})")+ print(f"\nOK: per-passage scoring let the long document compete on each of its "+ f"sections\n ({pp_topk}/{n} top-{TOPK}); a single pooled vector managed "+ f"only {po_topk}/{n}.")+++if __name__ == "__main__":+ main()diff --git a/docs/recipes/README.md b/docs/recipes/README.mdindex 186def22a..426091f32 100644--- a/docs/recipes/README.md+++ b/docs/recipes/README.md@@ -8,6 +8,7 @@ These are practical "how do I actually do X" recipes, not an API reference (that|---|---|---|| [Give an AI agent long-term memory](./agentic-memory.md) | A memory-backed agent using the `/_memory` API (store, semantic + keyword recall, metadata filters, forgetting, per-agent isolation) | [`agent_memory.py`](../examples/agentic-memory/agent_memory.py) || [Semantic search & RAG](./semantic-search-rag.md) | Retrieval by meaning with `semantic_text` (auto-embed on ingest, no separate vector DB) | [`rag_demo.py`](../examples/semantic-search-rag/rag_demo.py) |+| [Passage retrieval on long docs](./passage-retrieval.md) | `semantic_text` auto-embeds every overlapping passage; a long doc competes on any one of its sections via best-passage (max-sim) scoring — 98% top-3 vs 32% pooled | [`passage_demo.py`](../examples/passage-retrieval/passage_demo.py) || [Log analytics](./log-analytics.md) | From raw logs to dashboards — error rates, p95 latency, top services via aggregations | [`log_analytics.py`](../examples/log-analytics/log_analytics.py) || [Vector search (kNN)](./vector-search-knn.md) | Nearest-neighbor similarity search over `dense_vector` (HNSW), with filters | [`knn_demo.py`](../examples/vector-search-knn/knn_demo.py) || [Vector quantization](./vector-quantization.md) | Opt a `dense_vector` field into scalar8 (`int8_hnsw`) — 4× smaller vectors, recall@10 ≈ 0.99 | [`quant_demo.py`](../examples/vector-quantization/quant_demo.py) |diff --git a/docs/recipes/passage-retrieval.md b/docs/recipes/passage-retrieval.mdnew file mode 100644index 000000000..4b9de724b--- /dev/null+++ b/docs/recipes/passage-retrieval.md@@ -0,0 +1,112 @@+# Passage retrieval: long documents that compete on any section++## The problem++Embeddings describe *one* piece of text. But real documents — a manual, a+contract, a long article, a support-ticket thread — are *many* topics stitched+together. If you embed the whole document into a single vector, you get the+**average** of everything it says. A query about one section then has to match+that blurred average, and it loses to a short document that is *only* about+that section. The relevant long document is there; your retriever just can't+see it.++The fix the field settled on is **passage (chunk) embeddings**: split the+document into overlapping passages, embed each one, and score the document by+its *best-matching* passage. Most stacks make you build that pipeline+yourself — a separate chunker, a vector column per chunk, a nested query — and+keep it in sync with your data.++## Why XERJ++XERJ does it on ingest, with no configuration. A `semantic_text` field splits+each value into overlapping passages, embeds **every passage**, and persists+the per-passage vectors alongside the document. A `semantic` query then scores+each document by its **best-matching passage** (max-sim) instead of a single+pooled vector — so a long document competes on *any one* of its sections.++Short values (a single passage) are unchanged: one vector, exactly as before.+The pipeline only kicks in when a value is long enough to span more than one+passage, so you pay nothing for short fields.++## The solution++Nothing to configure — map the field as `semantic_text` and index normally:++```bash+curl -sX PUT "$XERJ_URL/docs" -H 'content-type: application/json' -d '{+ "mappings": { "properties": { "body": { "type": "semantic_text" } } }+}'++# A long, multi-topic document — embedded per passage automatically.+curl -sX PUT "$XERJ_URL/docs/_doc/handbook?refresh=true" \+ -H 'content-type: application/json' \+ -d '{ "body": "...many paragraphs across many topics..." }'+```++Query it with `semantic` — the question is embedded server-side and scored+against the best passage:++```bash+curl -sX POST "$XERJ_URL/docs/_search" -H 'content-type: application/json' -d '{+ "query": { "semantic": { "field": "body",+ "query": "how does chlorophyll drive photosynthesis",+ "k": 10 } }+}'+```++The document is retrieved on the strength of the one passage that matches —+even if the rest of it is about something else entirely.++## Try it++`docs/examples/passage-retrieval/passage_demo.py` (identical to+`recipes/passage_search.py`) indexes the 40 real KB articles as short docs+**plus** one long "compendium" that concatenates all 40, then runs each+article's title as a query and measures how often the long compendium reaches+the top 3. Both arms use XERJ's own embedder — the pooled baseline reads+XERJ's whole-document `<field>_vector` back out of `_source` — so the only+variable is pooled-vs-per-passage:++```+$ python3 recipes/passage_search.py+40 short article docs + 1 long compendium of all 40++compendium embedded into 21 passage vectors (pooled into 1 whole-doc vector of 384 dims)++compendium reached the top-3:+ per-passage : 39/40 (98%)+ pooled : 13/40 (32%)++OK: per-passage scoring let the long document compete on each of its sections+ (39/40 top-3); a single pooled vector managed only 13/40.+```++The compendium contains every topic, so with per-passage scoring it competes+for almost every query. Averaged into a single vector, it is a mediocre blur+that loses to the undiluted short docs two times out of three.++## How it works++- **Chunker.** The built-in overlapping chunker (512-char passages, 64-char+ overlap) splits the field value; each passage is embedded with the same+ embedder used for the whole field (built-in lexical by default, or your+ configured OpenAI-compatible endpoint).+- **Storage.** The pooled whole-document vector stays in `<field>_vector` for+ back-compat and plain kNN; the per-passage vectors are persisted in+ `<field>_vector_chunks` **only** when the document spans more than one+ passage.+- **Scoring.** A `semantic` query scores each candidate by the maximum+ similarity over its passage vectors, falling back to the single pooled+ vector for short documents.++## Notes and limits++- **Short fields are byte-identical to before.** A single-passage value stores+ one vector and scores exactly as it did pre-pipeline; no existing behavior+ changes.+- **The built-in embedder is lexical**, not neural — great for offline demos+ and CI. Point XERJ at an OpenAI-compatible `/v1/embeddings` endpoint+ (`[embedding]` in `xerj.toml`) for production semantics; the pipeline is+ identical, just higher-quality per-passage vectors.+- **Scoring is exact (brute-force max-sim)** over the passage vectors, which is+ what makes the ranking deterministic on the corpus sizes these recipes use.diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex a0b564b60..48e56e29e 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -3522,6 +3522,15 @@ impl Index {}}} else {+ // Per-chunk (passage) companion: multi-chunk `semantic_text` docs+ // persist their per-passage vectors under `<field>_chunks` at+ // ingest. When present we score by the BEST-matching passage+ // (max-sim) rather than the single pooled vector — a query that+ // matches one section of a long document ranks that document on+ // that section, not on the whole-doc average. Plain `dense_vector`+ // kNN and short single-chunk docs have no such companion, so they+ // fall through to the exact single-vector scan below (unchanged).+ let chunk_field = format!("{field}_chunks");for (id, src) in candidates {// Apply filter: if the filter doesn't match this doc, skip.if let Some(ref f) = filter {@@ -3533,21 +3542,45 @@ impl Index {continue;}}- let vec_val = match get_field_value(&src, field) {- Some(v) => v,- None => continue,- };- let doc_vec: Vec<f32> = match &vec_val {- Value::Array(arr) => arr- .iter()- .filter_map(|v| v.as_f64().map(|f| f as f32))- .collect(),- _ => continue,+ let score = if let Some(Value::Array(chunks)) = get_field_value(&src, &chunk_field)+ {+ // Best-matching passage over the stored chunk vectors.+ let mut best: Option<f32> = None;+ for cv in &chunks {+ let dv: Vec<f32> = match cv {+ Value::Array(a) => a+ .iter()+ .filter_map(|v| v.as_f64().map(|f| f as f32))+ .collect(),+ _ => continue,+ };+ if dv.len() != query_vec.len() {+ continue;+ }+ let s = compute_vector_similarity(similarity, query_vec, &dv);+ best = Some(best.map_or(s, |b| b.max(s)));+ }+ match best {+ Some(s) => s,+ None => continue,+ }+ } else {+ let vec_val = match get_field_value(&src, field) {+ Some(v) => v,+ None => continue,+ };+ let doc_vec: Vec<f32> = match &vec_val {+ Value::Array(arr) => arr+ .iter()+ .filter_map(|v| v.as_f64().map(|f| f as f32))+ .collect(),+ _ => continue,+ };+ if doc_vec.len() != query_vec.len() {+ continue;+ }+ compute_vector_similarity(similarity, query_vec, &doc_vec)};- if doc_vec.len() != query_vec.len() {- continue;- }- let score = compute_vector_similarity(similarity, query_vec, &doc_vec);scored.push((id, score, src));}}@@ -3748,11 +3781,10 @@ impl Index {continue;};let text = text.to_string();- let vec = if let Some(proxy) = &*self.embedding_proxy {- // Chunk long text before embedding so a single document maps to- // a chunk-aware vector instead of one embedding of the whole- // (possibly truncated) field. Short text (<= chunk_size) yields- // one chunk == the exact pre-chunking behavior.+ // Chunk once and embed EACH overlapping chunk. `chunk_vecs` is one+ // embedding per passage (>= 1). Short text (<= chunk_size) yields a+ // single chunk == the exact pre-chunking behavior.+ let chunk_vecs: Vec<Vec<f32>> = if let Some(proxy) = &*self.embedding_proxy {let chunks = semantic_chunker().chunk(&text, None);let chunk_texts: Vec<String> = if chunks.len() <= 1 {vec![text.clone()]@@ -3764,20 +3796,35 @@ impl Index {"semantic_text embed failed for field [{field}]: {e}")))})?;- let vs: Vec<Vec<f32>> = vs.into_iter().filter(|v| !v.is_empty()).collect();- match vs.len() {- 0 => continue,- // Single chunk: return the embedding as-is (pre-chunking- // behavior — no re-normalization).- 1 => vs.into_iter().next().unwrap(),- // Multiple chunks: L2-normalize each, mean-pool, re-normalize.- _ => mean_pool_normalize(&vs),- }+ vs.into_iter().filter(|v| !v.is_empty()).collect()} else {- local_chunk_embed(&text, dims)+ local_chunk_vectors(&text, dims)};- let arr: Vec<Value> = vec.into_iter().map(|f| Value::from(f as f64)).collect();- obj.insert(target, Value::Array(arr));+ // Pooled vector for `target`: single chunk is stored as-is (no+ // re-normalization, matching pre-chunking behavior); multiple+ // chunks are L2-normalized, mean-pooled, then re-normalized. This+ // keeps `target` back-compatible for plain kNN and for callers+ // that read the companion vector directly.+ let pooled = match chunk_vecs.len() {+ 0 => continue,+ 1 => chunk_vecs[0].clone(),+ _ => mean_pool_normalize(&chunk_vecs),+ };+ let arr: Vec<Value> = pooled.into_iter().map(|f| Value::from(f as f64)).collect();+ obj.insert(target.clone(), Value::Array(arr));+ // Per-chunk passage vectors — persisted ONLY when the document+ // actually spans more than one chunk, under `<target>_chunks` as an+ // array of vectors. Semantic search prefers these and scores by the+ // best-matching passage (max-sim) instead of the blurred pooled+ // average. Single-chunk docs store nothing extra, so their `_source`+ // and single-vector scoring are byte-identical to before.+ if chunk_vecs.len() > 1 {+ let chunks_json: Vec<Value> = chunk_vecs+ .iter()+ .map(|cv| Value::Array(cv.iter().map(|f| Value::from(*f as f64)).collect()))+ .collect();+ obj.insert(format!("{target}_chunks"), Value::Array(chunks_json));+ }}Ok(source)}@@ -16412,19 +16459,35 @@ fn mean_pool_normalize(vectors: &[Vec<f32>]) -> Vec<f32> {acc}-/// 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-/// relative to the pre-chunking behavior.-fn local_chunk_embed(text: &str, dims: usize) -> Vec<f32> {+/// 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 xerj_ai::local::local_embed(text, dims);+ return vec![xerj_ai::local::local_embed(text, dims)];}- let vecs: Vec<Vec<f32>> = chunks+ chunks.iter().map(|c| xerj_ai::local::local_embed(&c.text, dims))- .collect();+ .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+/// relative to the pre-chunking behavior. Retained as the reference pooled+/// path the per-chunk tests assert against (the ingest path now stores the+/// per-chunk vectors directly via [`local_chunk_vectors`]).+#[cfg(test)]+fn local_chunk_embed(text: &str, dims: usize) -> Vec<f32> {+ let vecs = local_chunk_vectors(text, dims);+ if vecs.len() <= 1 {+ return vecs.into_iter().next().unwrap_or_default();+ }mean_pool_normalize(&vecs)}@@ -17405,4 +17468,69 @@ mod chunk_embed_tests {assert_eq!(pooled.len(), DEFAULT_DIMS);assert!((l2_norm(&pooled) - 1.0).abs() < 1e-4);}++ /// `local_chunk_vectors` returns one unit-norm vector PER passage for a+ /// multi-chunk document, and pooling those equals `local_chunk_embed`.+ #[test]+ fn chunk_vectors_are_per_passage_and_pool_consistently() {+ let text =+ "The quick brown fox jumps over the lazy dog. Pack my box with five dozen liquor jugs. "+ .repeat(20);+ let n_chunks = semantic_chunker().chunk(&text, None).len();+ assert!(n_chunks > 1, "fixture must span multiple chunks");++ let vecs = local_chunk_vectors(&text, DEFAULT_DIMS);+ assert_eq!(vecs.len(), n_chunks, "one vector per chunk");+ for v in &vecs {+ assert_eq!(v.len(), DEFAULT_DIMS);+ assert!(+ (l2_norm(v) - 1.0).abs() < 1e-4,+ "each passage vector unit-norm"+ );+ }+ // Pooling the per-chunk vectors reproduces the pooled companion.+ assert_eq!(+ mean_pool_normalize(&vecs),+ local_chunk_embed(&text, DEFAULT_DIMS)+ );+ }++ /// The whole point of per-chunk storage: a query that matches ONE buried+ /// passage of a long document scores higher against the best chunk+ /// (max-sim) than against the blurred whole-document pooled vector. This+ /// is the vector-level invariant the ingest+query wiring relies on.+ #[test]+ fn max_sim_over_chunks_beats_pooled_for_a_buried_passage() {+ // A long document whose passages cover distinct topics; the topic of+ // interest ("photosynthesis chloroplast ...") is only ONE passage.+ let filler =+ "quarterly revenue guidance and operating margins for the fiscal year. ".repeat(12);+ let target_passage =+ "photosynthesis converts sunlight into chemical energy inside the chloroplast \+ of a plant cell using chlorophyll pigments. ";+ let doc = format!("{filler}{target_passage}{filler}");+ assert!(+ semantic_chunker().chunk(&doc, None).len() > 1,+ "doc must span multiple chunks"+ );++ let query = "how does chlorophyll drive photosynthesis in a chloroplast";+ let q = local_embed(query, DEFAULT_DIMS);++ // Pooled: the whole-doc average vector (what we stored before).+ let pooled = local_chunk_embed(&doc, DEFAULT_DIMS);+ let pooled_score = compute_vector_similarity("cosine", &q, &pooled);++ // Per-chunk: best-matching passage (what semantic search now uses).+ let chunk_vecs = local_chunk_vectors(&doc, DEFAULT_DIMS);+ let max_sim = chunk_vecs+ .iter()+ .map(|cv| compute_vector_similarity("cosine", &q, cv))+ .fold(f32::MIN, f32::max);++ assert!(+ max_sim > pooled_score,+ "best-passage max-sim ({max_sim}) should beat pooled ({pooled_score})"+ );+ }}diff --git a/engine/tests/es-compat-yaml/yaml/vectors/52_semantic_text_chunked.yml b/engine/tests/es-compat-yaml/yaml/vectors/52_semantic_text_chunked.ymlnew file mode 100644index 000000000..4c9df0694--- /dev/null+++ b/engine/tests/es-compat-yaml/yaml/vectors/52_semantic_text_chunked.yml@@ -0,0 +1,61 @@+# Per-passage (chunk) embeddings for `semantic_text` — regression lock.+#+# XERJ's ingest-time chunk-embedding pipeline splits a long `semantic_text`+# value into overlapping passages, embeds EACH passage, and persists the+# per-passage vectors. A `semantic` query then scores a document by its+# best-matching passage (max-sim) instead of a single pooled whole-document+# vector.+#+# This test buries one biology passage in a long, otherwise-finance document.+# A biology query must rank that long document ABOVE a short pure-finance+# document — which only holds because the buried passage is scored undiluted.+# Under the old pooled-vector behavior the long document's vector was+# finance-dominated. Short single-passage docs are unaffected (their `_source`+# and scoring are byte-identical to before), so the other vectors tests still+# pass unchanged.++setup:+ - do:+ indices.create:+ index: passages+ body:+ mappings:+ properties:+ body:+ type: semantic_text++ - do:+ bulk:+ refresh: true+ body:+ # A long document: finance boilerplate on both sides of ONE buried+ # biology passage. Long enough to span multiple overlapping chunks.+ - index:+ _index: passages+ _id: long+ - body: "Quarterly revenue guidance and operating margins improved this fiscal year. Quarterly revenue guidance and operating margins improved this fiscal year. Quarterly revenue guidance and operating margins improved this fiscal year. Quarterly revenue guidance and operating margins improved this fiscal year. Quarterly revenue guidance and operating margins improved this fiscal year. Quarterly revenue guidance and operating margins improved this fiscal year. Photosynthesis converts sunlight into chemical energy inside the chloroplast of a plant cell using chlorophyll pigments. Quarterly revenue guidance and operating margins improved this fiscal year. Quarterly revenue guidance and operating margins improved this fiscal year. Quarterly revenue guidance and operating margins improved this fiscal year. Quarterly revenue guidance and operating margins improved this fiscal year. Quarterly revenue guidance and operating margins improved this fiscal year. Quarterly revenue guidance and operating margins improved this fiscal year."+ # A short document that is purely finance.+ - index:+ _index: passages+ _id: fin+ - body: "Quarterly revenue guidance and operating margins improved this fiscal year outlook."++---+"semantic query ranks the long doc by its buried biology passage":+ - do:+ search:+ index: passages+ body:+ size: 2+ query:+ semantic:+ field: body+ query: "how does chlorophyll drive photosynthesis inside a chloroplast plant cell"+ k: 10++ # Both docs carry a vector → the kNN pool is 2.+ - match: { hits.total.value: 2 }+ - length: { hits.hits: 2 }+ # The long, mostly-finance document wins on its buried biology passage —+ # this is the per-passage (max-sim) behavior, not pooled scoring.+ - match: { hits.hits.0._id: "long" }diff --git a/recipes/README.md b/recipes/README.mdindex 051819957..0358ff085 100644--- a/recipes/README.md+++ b/recipes/README.md@@ -23,6 +23,7 @@ xerj --insecure --data-dir ./data &# 3. run any recipepython3 recipes/semantic_search.py+python3 recipes/passage_search.pypython3 recipes/rag_app.pypython3 recipes/memory_agent.py # run twice — memory persistspython3 recipes/log_anomaly.py@@ -37,6 +38,7 @@ Every recipe honors `XERJ_URL` (default `http://localhost:9200`).| File | What it shows | Real workload ||---|---|---|| [`semantic_search.py`](semantic_search.py) | BM25 vs semantic vs hybrid (RRF) retrieval on one `semantic_text` field | `demo/data/ai_kb.ndjson` — 40 hand-written AI-engineering articles |+| [`passage_search.py`](passage_search.py) | **Per-passage** retrieval on long docs: `semantic_text` auto-embeds every overlapping chunk, so a long document competes on any one of its sections (98% top-3 vs 32% for a single pooled vector) | Same 40 articles + a long "compendium" of all 40 || [`rag_app.py`](rag_app.py) | A full RAG pipeline: HTML→text→chunk→index→hybrid-retrieve→answer, with a retrieval eval and citations | XERJ's own docs (`landing/docs/*.html`) — ~96 chunks over 23 pages || [`memory_agent.py`](memory_agent.py) | A triage agent with **persistent** long-term memory via the `/_memory` API: recall similar past incidents, decide, remember | Real OpenSSH attack capture (`engine/demo-data/ssh_one.ndjson`, logpai/loghub) || [`log_anomaly.py`](log_anomaly.py) | Statistical anomaly detection (`_ml`) finding brute-force spikes over a moving baseline, then attributing the worst hour | Same real SSH capture (655k events) |@@ -46,6 +48,9 @@ Every recipe honors `XERJ_URL` (default `http://localhost:9200`).- **semantic_text auto-embedding** — documents embed at ingest with noconfig; `semantic` queries embed the question the same way.+- **ingest-time chunk-embedding** — long `semantic_text` values are split+ into overlapping passages and embedded per-passage; `semantic` scores a+ document by its best-matching passage (max-sim), not a pooled average.- **hybrid queries** — `bool`/`match` fused with `semantic`/`knn` viaReciprocal Rank Fusion in one query tree.- **Agent-Memory API** — `POST /_memory/{ns}`, `_recall`, backed by adiff --git a/recipes/passage_search.py b/recipes/passage_search.pynew file mode 100644index 000000000..0866261ee--- /dev/null+++ b/recipes/passage_search.py@@ -0,0 +1,149 @@+#!/usr/bin/env python3+"""passage_search.py — per-passage retrieval on long documents.++XERJ's ingest-time chunk-embedding pipeline: a ``semantic_text`` field+auto-embeds *each overlapping passage* of a long document, and a ``semantic``+query scores a document by its BEST-matching passage (max-sim) rather than a+single blurred whole-document vector. That is what lets a query about one topic+find a long document that only covers that topic in one section.++Real workload (deterministic, offline)+--------------------------------------+Index 40 real AI-engineering articles (``demo/data/ai_kb.ndjson``) as short+docs, PLUS one long "compendium" doc containing all 40 concatenated. Then run+each article's title as a query and ask: **can the long compendium — which+contains every topic as one passage — compete for the top ranks?**++* **per-passage** (``semantic_text`` + ``semantic``): the compendium's matching+ passage is scored undiluted, so it consistently lands near the top.+* **pooled** (``dense_vector`` + ``knn``): the compendium is a single vector+ averaging 40 topics, so any one query barely registers against it and it is+ buried below the 40 undiluted short docs.++Both arms use XERJ's own server-side embedder (the pooled baseline reuses+XERJ's ``<field>_vector`` read back out of ``_source``), so the only variable+is pooled-vs-per-passage. We report how often the compendium reaches the top-3.++Run: python3 recipes/passage_search.py (honors $XERJ_URL, default :9200)+"""+import json+import os+import sys+import urllib.error+import urllib.request++URL = os.environ.get("XERJ_URL", "http://localhost:9200").rstrip("/")+HERE = os.path.dirname(os.path.abspath(__file__))+KB = os.path.join(HERE, "..", "demo", "data", "ai_kb.ndjson")+TOPK = 3+++def req(method, path, body=None, quiet=False):+ data = json.dumps(body).encode() if body is not None else None+ r = urllib.request.Request(+ URL + path, data=data, headers={"Content-Type": "application/json"}, method=method+ )+ try:+ with urllib.request.urlopen(r) as resp:+ return json.load(resp)+ except urllib.error.HTTPError as e:+ if not quiet:+ sys.stderr.write(f"HTTP {e.code} {method} {path}\n{e.read().decode()[:500]}\n")+ raise+++def recreate(index, mappings):+ try:+ req("DELETE", "/" + index, quiet=True)+ except urllib.error.HTTPError:+ pass+ req("PUT", "/" + index, {"mappings": {"properties": mappings}})+++def rank_of(hits, doc_id):+ """1-based rank of doc_id in a hits list, or None if absent."""+ for i, h in enumerate(hits, 1):+ if h["_id"] == doc_id:+ return i+ return None+++def main():+ with open(KB, encoding="utf-8") as fh:+ articles = [json.loads(line) for line in fh if line.strip()]+ if len(articles) < 10:+ sys.exit("need at least 10 KB articles")++ print(f"XERJ at {URL}")+ print(f"{len(articles)} short article docs + 1 long compendium of all {len(articles)}\n")++ recreate("kb-passages", {"body": {"type": "semantic_text"}})+ recreate("kb-pooled", {"vec": {"type": "dense_vector", "dims": 384, "similarity": "cosine"}})+ # Probe index: index a short string, read back XERJ's own embedding of it so+ # the pooled `knn` baseline is driven by the same server-side embedder.+ recreate("kb-probe", {"body": {"type": "semantic_text"}})++ def embed(text):+ req("PUT", "/kb-probe/_doc/q?refresh=true", {"body": text})+ return req("GET", "/kb-probe/_doc/q")["_source"]["body_vector"]++ # Short article docs into both arms. For a short (single-chunk) doc the+ # pooled companion IS the article's embedding, so the baseline is exact.+ for i, art in enumerate(articles):+ body = f"{art['title']}. {art['content']}"+ req("PUT", f"/kb-passages/_doc/a{i}?refresh=true", {"body": body})+ vec = req("GET", f"/kb-passages/_doc/a{i}")["_source"]["body_vector"]+ req("PUT", f"/kb-pooled/_doc/a{i}?refresh=true", {"vec": vec})++ # One long compendium containing every article as a passage.+ compendium = "\n\n".join(f"{a['title']}. {a['content']}" for a in articles)+ req("PUT", "/kb-passages/_doc/compendium?refresh=true", {"body": compendium})+ comp_src = req("GET", "/kb-passages/_doc/compendium")["_source"]+ n_passages = len(comp_src.get("body_vector_chunks", []))+ print(f"compendium embedded into {n_passages} passage vectors "+ f"(pooled into 1 whole-doc vector of {len(comp_src['body_vector'])} dims)\n")+ if n_passages < 5:+ sys.exit("FAIL: compendium did not produce multiple passage vectors")+ req("PUT", "/kb-pooled/_doc/compendium?refresh=true", {"vec": comp_src["body_vector"]})++ pp_topk = 0+ po_topk = 0+ pp_ranks = []+ po_ranks = []+ for art in articles:+ title = art["title"]+ sem = req("POST", "/kb-passages/_search", {+ "size": TOPK,+ "query": {"semantic": {"field": "body", "query": title, "k": 50}},+ })+ # Server-embed the query via the probe index for the pooled arm.+ qv = embed(title)+ pool = req("POST", "/kb-pooled/_search", {+ "size": TOPK,+ "knn": {"field": "vec", "query_vector": qv, "k": 50},+ })+ pr = rank_of(sem["hits"]["hits"], "compendium")+ qr = rank_of(pool["hits"]["hits"], "compendium")+ pp_ranks.append(pr)+ po_ranks.append(qr)+ pp_topk += pr is not None+ po_topk += qr is not None++ n = len(articles)+ pp_rate = pp_topk / n+ po_rate = po_topk / n+ print(f"compendium reached the top-{TOPK}:")+ print(f" per-passage : {pp_topk}/{n} ({pp_rate:.0%})")+ print(f" pooled : {po_topk}/{n} ({po_rate:.0%})")++ if pp_rate < 0.75:+ sys.exit(f"FAIL: per-passage top-{TOPK} rate {pp_rate:.2f} < 0.75")+ if pp_rate <= po_rate:+ sys.exit(f"FAIL: per-passage ({pp_rate:.2f}) did not beat pooled ({po_rate:.2f})")+ print(f"\nOK: per-passage scoring let the long document compete on each of its "+ f"sections\n ({pp_topk}/{n} top-{TOPK}); a single pooled vector managed "+ f"only {po_topk}/{n}.")+++if __name__ == "__main__":+ main()diff --git a/recipes/run_all.sh b/recipes/run_all.shindex 154e51be5..242d0b644 100755--- a/recipes/run_all.sh+++ b/recipes/run_all.sh@@ -35,7 +35,7 @@ until curl -fsS "$XERJ_URL/" >/dev/null 2>&1; dodonerc=0-for r in semantic_search rag_app memory_agent log_anomaly anomaly_datafeed vector_quantization; do+for r in semantic_search passage_search rag_app memory_agent log_anomaly anomaly_datafeed vector_quantization; doprintf '\n═══ %s ═══\n' "$r"if python3 "$ROOT/recipes/$r.py"; then :; else echo "FAILED: $r"; rc=1; fidone