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.

feat(engine): kNN + aggregations in a single request (rc.6) + calltree.ai case study

Xerj Squad Aae2b83417ea6
diff --git a/docs/case-studies/calltree-analytics/01_make_dataset.py b/docs/case-studies/calltree-analytics/01_make_dataset.py
new file mode 100644
index 000000000..e99e35515
--- /dev/null
+++ b/docs/case-studies/calltree-analytics/01_make_dataset.py
@@ -0,0 +1,53 @@
+# Realistic wifi support conversations. Structured fields + free-text body.
+# Deliberately mixes wifi and non-wifi (billing, TV) so retrieval has to discriminate.
+import json, random
+random.seed(7)
+WIFI = [
+ ("2.4GHz","range","Wifi drops in the back bedroom, far from the router. Fine in the living room.","resolved"),
+ ("2.4GHz","congestion","Slow wifi every evening around 7pm, neighbors all online, 2.4 band crowded.","resolved"),
+ ("2.4GHz","interference","Wifi cuts out when the microwave runs. Only the older laptop is affected.","resolved"),
+ ("2.4GHz","channel-overlap","Constant lag, wifi analyzer shows 6 networks on channel 6 overlapping.","workaround"),
+ ("2.4GHz","legacy-device","Old smart plug won't connect, only supports 2.4GHz, keeps dropping.","resolved"),
+ ("5GHz","range","5GHz signal weak two rooms away, drops to 2.4 automatically and slows down.","resolved"),
+ ("5GHz","dfs-radar","Wifi disconnects for a minute at random, near an airport, DFS channel radar events.","escalated"),
+ ("5GHz","band-steering","Phone keeps switching between 2.4 and 5, drops the video call each time.","workaround"),
+ ("5GHz","slow-speed","Paying for gigabit but only getting 300Mbps over 5GHz wifi on the laptop.","resolved"),
+ ("5GHz","disconnects","5GHz keeps dropping every few minutes on the new mesh node upstairs.","escalated"),
+ ("5GHz","channel-width","Speeds capped, 5GHz stuck at 20MHz channel width instead of 80.","resolved"),
+ ("2.4GHz","disconnects","Cameras on 2.4GHz drop offline overnight then reconnect in the morning.","open"),
+ ("5GHz","congestion","Apartment building, 5GHz also crowded now, streaming buffers at night.","workaround"),
+ ("2.4GHz","slow-speed","2.4GHz only reaching 40Mbps even right next to the router.","resolved"),
+ ("5GHz","range","New house, 5GHz doesn't reach the garage office at all.","escalated"),
+]
+OTHER = [
+ ("n/a","billing","Charged twice this month, want a refund on the duplicate charge.","resolved"),
+ ("n/a","billing","Bill went up after promo ended, asking for a better rate.","open"),
+ ("n/a","tv","Cable box keeps rebooting during live TV, picture freezes.","escalated"),
+ ("n/a","outage","Whole street internet is down since the storm last night.","resolved"),
+ ("n/a","email","Can't log into my ISP email account, password reset not arriving.","resolved"),
+ ("n/a","install","Rescheduling my install appointment to next week.","resolved"),
+]
+def expand(base, n):
+ out=[]
+ for i in range(n):
+ band,issue,body,res = random.choice(base)
+ out.append(dict(band=band,issue=issue,body=body,resolution=res,
+ device=random.choice(["laptop","phone","smart-tv","iot","tablet","desktop"]),
+ csat=random.choice([1,2,3,4,5,4,5,5,3]),
+ handle_time_s=random.randint(120,1800),
+ agent=random.choice(["A. Rivera","J. Chen","M. Okafor","S. Patel"]),
+ channel=random.choice(["voice","chat","email"]),
+ day=random.randint(1,28)))
+ return out
+docs = expand(WIFI, 90) + expand(OTHER, 40)
+random.shuffle(docs)
+# canonical KB articles (the "canonical records" to cluster against)
+KB = [
+ dict(kb_id="KB-2G-RANGE", title="Improving 2.4GHz range and coverage", body="2.4GHz travels farther through walls but is slower and more congested; place the router centrally, reduce interference from microwaves and cordless phones, choose channel 1/6/11."),
+ dict(kb_id="KB-5G-DFS", title="5GHz DFS radar disconnects", body="5GHz DFS channels must yield to radar; near airports/weather stations this causes periodic disconnects. Lock the router to a non-DFS 5GHz channel (36-48)."),
+ dict(kb_id="KB-BANDSTEER", title="Band steering and roaming drops", body="Band steering moves a device between 2.4 and 5GHz; on calls this can drop the connection. Split the SSIDs or disable band steering for sensitive devices."),
+ dict(kb_id="KB-CONGEST", title="Evening wifi congestion", body="Peak-hour slowdowns come from channel congestion in dense areas; use a wifi analyzer, move to a clear channel, prefer 5GHz which has more non-overlapping channels."),
+ dict(kb_id="KB-WIDTH", title="Channel width and throughput", body="5GHz throughput depends on channel width (20/40/80/160MHz); if stuck at 20MHz speeds are capped. Enable 80MHz where the spectrum is clean."),
+]
+json.dump(dict(docs=docs, kb=KB), open("/tmp/claude-1001/-home-claude-ai-xerj/09b4eaff-87bf-4097-b72f-3907d1ef6cd4/scratchpad/rob/dataset.json","w"))
+print(f"generated {len(docs)} conversations ({sum(1 for d in docs if d['band']!='n/a')} wifi), {len(KB)} KB articles")
diff --git a/docs/case-studies/calltree-analytics/02_embed_index.py b/docs/case-studies/calltree-analytics/02_embed_index.py
new file mode 100644
index 000000000..26521e45f
--- /dev/null
+++ b/docs/case-studies/calltree-analytics/02_embed_index.py
@@ -0,0 +1,42 @@
+import json, urllib.request, time
+X="http://127.0.0.1:9200"; OLL="http://127.0.0.1:11434/api/embeddings"
+d=json.load(open("/tmp/claude-1001/-home-claude-ai-xerj/09b4eaff-87bf-4097-b72f-3907d1ef6cd4/scratchpad/rob/dataset.json"))
+def embed(text):
+ req=urllib.request.Request(OLL,data=json.dumps({"model":"embeddinggemma","prompt":text}).encode(),
+ headers={"Content-Type":"application/json"})
+ return json.loads(urllib.request.urlopen(req).read())["embedding"]
+DIMS=len(embed("probe")); print("embedding dims:",DIMS)
+
+def put(path,body,method="PUT"):
+ r=urllib.request.Request(f"{X}/{path}",data=json.dumps(body).encode() if body else None,
+ headers={"Content-Type":"application/json"},method=method)
+ try: return urllib.request.urlopen(r).read()
+ except Exception as e: return str(e).encode()
+
+# --- conversations index: structured columns + dense_vector for retrieval ---
+put("conversations",None,"DELETE")
+put("conversations",{"mappings":{"properties":{
+ "band":{"type":"keyword"},"issue":{"type":"keyword"},"resolution":{"type":"keyword"},
+ "device":{"type":"keyword"},"agent":{"type":"keyword"},"channel":{"type":"keyword"},
+ "csat":{"type":"integer"},"handle_time_s":{"type":"integer"},"day":{"type":"integer"},
+ "body":{"type":"text"},
+ "vec":{"type":"dense_vector","dims":DIMS,"similarity":"cosine"}}}})
+# --- KB index (canonical records) ---
+put("kb",None,"DELETE")
+put("kb",{"mappings":{"properties":{"kb_id":{"type":"keyword"},"title":{"type":"text"},
+ "body":{"type":"text"},"vec":{"type":"dense_vector","dims":DIMS,"similarity":"cosine"}}}})
+
+def bulk(index, rows, textfn):
+ lines=[]
+ for i,r in enumerate(rows):
+ r=dict(r); r["vec"]=embed(textfn(r))
+ lines.append(json.dumps({"index":{"_id":str(i)}})); lines.append(json.dumps(r))
+ body=("\n".join(lines)+"\n").encode()
+ rq=urllib.request.Request(f"{X}/{index}/_bulk",data=body,
+ headers={"Content-Type":"application/x-ndjson"},method="POST")
+ return json.loads(urllib.request.urlopen(rq).read()).get("errors")
+t=time.time()
+e1=bulk("conversations", d["docs"], lambda r: r["body"])
+e2=bulk("kb", d["kb"], lambda r: r["title"]+". "+r["body"])
+put("conversations/_refresh",None,"POST"); put("kb/_refresh",None,"POST")
+print(f"indexed {len(d['docs'])} conversations (errors={e1}) + {len(d['kb'])} KB (errors={e2}) in {time.time()-t:.1f}s")
diff --git a/docs/case-studies/calltree-analytics/03_deep_research.py b/docs/case-studies/calltree-analytics/03_deep_research.py
new file mode 100644
index 000000000..314a4922c
--- /dev/null
+++ b/docs/case-studies/calltree-analytics/03_deep_research.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python3
+"""calltree.ai deep-research task, ONE request each — using the rc.6
+knn+aggregations feature. Needs XERJ :9200 + Ollama (embeddinggemma + an LLM)."""
+import json, urllib.request
+X="http://127.0.0.1:9200"; OLL="http://127.0.0.1:11434"
+def embed(t):
+ r=urllib.request.Request(f"{OLL}/api/embeddings",data=json.dumps({"model":"embeddinggemma","prompt":t}).encode(),headers={"Content-Type":"application/json"})
+ return json.loads(urllib.request.urlopen(r).read())["embedding"]
+def S(b,idx="conversations"):
+ r=urllib.request.Request(f"{X}/{idx}/_search",data=json.dumps(b).encode(),headers={"Content-Type":"application/json"})
+ return json.loads(urllib.request.urlopen(r).read())
+def gen(prompt):
+ r=urllib.request.Request(f"{OLL}/api/generate",data=json.dumps({"model":"qwen2.5:7b","prompt":prompt,"stream":False}).encode(),headers={"Content-Type":"application/json"})
+ return json.loads(urllib.request.urlopen(r).read())["response"].strip()
+
+qv=embed("wifi connectivity problems dropouts slow weak signal range")
+print('"of calls about wifi issues, how many 2.4 vs 5GHz, and what are the key issues?"\n')
+# ONE request: semantic retrieval + band split + key issues + csat + example hits
+r=S({"query":{"knn":{"field":"vec","query_vector":qv,"k":80,"num_candidates":130}},
+ "size":3,"_source":["band","issue","body"],
+ "aggs":{"by_band":{"terms":{"field":"band"},"aggs":{
+ "key_issues":{"terms":{"field":"issue","size":4}},
+ "csat":{"percentiles":{"field":"csat","percents":[50]}},
+ "aht":{"avg":{"field":"handle_time_s"}}}}}})
+buckets=[b for b in r["aggregations"]["by_band"]["buckets"] if b["key"]!="n/a"]
+tot=sum(b["doc_count"] for b in buckets)
+print(f"retrieved {r['hits']['total']['value']} nearest wifi calls; aggregated in the same request:\n")
+for b in buckets:
+ iss=", ".join(x["key"] for x in b["key_issues"]["buckets"])
+ print(f" {b['key']:7} {b['doc_count']:2} ({100*b['doc_count']/tot:.0f}%) csat_p50={b['csat']['values']['50.0']} aht={b['aht']['value']:.0f}s issues: {iss}")
+# LLM synthesis over the example hits returned in the SAME response
+ex="\n".join(f"- [{h['_source']['band']}/{h['_source']['issue']}] {h['_source']['body']}" for h in r["hits"]["hits"])
+print("\ndeep-research narrative (LLM over the retrieved examples):")
+print(" ", gen(f"Support calls about wifi:\n{ex}\n\nOne-sentence executive summary of the key issue.")[:300])
diff --git a/docs/case-studies/calltree-analytics/README.md b/docs/case-studies/calltree-analytics/README.md
new file mode 100644
index 000000000..a9bda8a10
--- /dev/null
+++ b/docs/case-studies/calltree-analytics/README.md
@@ -0,0 +1,217 @@
+# Case study: deep-research analytics over support conversations (calltree.ai)
+
+**Who:** [calltree.ai](https://calltree.ai) runs AI over customer support interactions.
+They have per-customer embedding models that cluster conversations by issue type and
+score them against canonical records (knowledgebase articles, team guidance), and
+they want **"deep research" style reports** over past interactions — e.g.
+*"of calls about wifi issues, how many are related to 2.4GHz vs 5GHz, and what are
+the key issues?"* That single question bundles **retrieval, aggregation, labeling,
+schema, and embedding** tasks.
+
+**The problem:** there was no good place to do **SQL-style columnar analytics +
+embedding retrieval together**. Shimming it onto DuckDB (OLAP) plus a separate
+vector store meant ETL between systems, no joins across them, and a poor developer
+experience.
+
+**What this case study shows:** XERJ does this in one store — tested live on a
+running engine with real 768-dim **EmbeddingGemma** embeddings over 130 support
+conversations — **including a new engine feature built for this use case:
+kNN + aggregations in a single request (rc.6).** Every number below is real output
+from the scripts in this directory.
+
+---
+
+## The answer, in one request (with the rc.6 feature)
+
+`03_deep_research.py`, real output:
+
+```
+"of calls about wifi issues, how many 2.4 vs 5GHz, and what are the key issues?"
+
+retrieved 80 nearest wifi calls; aggregated in the same request:
+ 2.4GHz 29 (54%) csat_p50=4.0 aht=897s issues: channel-overlap, congestion, disconnects, legacy-device
+ 5GHz 25 (46%) csat_p50=4.0 aht=924s issues: range, disconnects, congestion
+
+deep-research narrative (LLM over the retrieved examples):
+ The key issue is that the 5GHz signal is weak in a nearby room, dropping to 2.4GHz
+ and resulting in slower speeds.
+```
+
+One `POST /_search` did the **semantic retrieval** (kNN over "wifi issues"), the
+**band split** (2.4 vs 5GHz), **key issues** per band, **CSAT** percentile and
+**AHT** average, *and* returned example conversations — then one LLM call turned the
+retrieved examples into the narrative. That is the whole deep-research loop.
+
+---
+
+## Step-by-step guide (runnable)
+
+**Prereqs:** XERJ on `:9200`; Ollama serving an embedding model (`embeddinggemma`)
+and an LLM (`qwen2.5`). Swap in your per-customer embedding model in step 2.
+
+### 1. Data — conversations + canonical KB
+```bash
+python3 01_make_dataset.py # 130 support convos (structured cols + free text) + 5 KB articles
+```
+Each conversation carries structured columns (`band`, `issue`, `device`, `csat`,
+`handle_time_s`, `resolution`, `agent`, `channel`, `day`) and a `body`.
+
+### 2. Embed + index (one store: columns + text + vectors)
+```bash
+python3 02_embed_index.py # embed body -> dense_vector; index into `conversations` + `kb`
+```
+Mapping — the key point is **structured columns, full-text, and the vector live
+together**:
+```json
+{ "band":{"type":"keyword"}, "issue":{"type":"keyword"}, "csat":{"type":"integer"},
+ "handle_time_s":{"type":"integer"}, "body":{"type":"text"},
+ "vec":{"type":"dense_vector","dims":768,"similarity":"cosine"} }
+```
+
+### 3. The research task
+```bash
+python3 03_deep_research.py # the single-request kNN+aggs deep-research report
+```
+
+### The composable primitives (each is a real XERJ query)
+
+| task in the question | XERJ primitive | notes |
+|---|---|---|
+| "calls about wifi issues" | `knn` over the topic vector | discriminates wifi from billing/TV: 74/100 nearest are wifi |
+| "how many 2.4 vs 5GHz" | `terms`/`filters` agg **on the kNN slice** | rc.6 — one request |
+| "key issues" | `terms` (raw) or `significant_terms` (two-step, see below) | over-represented issue labels |
+| CSAT / AHT / trend | `percentiles`, `stats`, `avg`, `date_histogram` | compose in the same `aggs` |
+| "vs canonical records" | `knn` into the `kb` index | nearest KB + cosine = distance-to-canonical |
+| the narrative | `top_hits` / kNN hits → LLM | grounded evidence in the same response |
+
+---
+
+## The engine feature we built for this: kNN + aggregations (rc.6)
+
+**The gap (before):** aggregations did **not** run alongside a `knn`/semantic query.
+`knn`+`aggs`, `query.knn`+`aggs`, and `bool.filter:[knn]`+`aggs` all returned no
+buckets. You had to do it in two steps (kNN → collect ids → separate filtered
+aggregation) — the friction that made the DuckDB shim tempting.
+
+**The fix (rc.6):** aggregations now run over the **retrieved top-`k` neighbour
+set** (Elasticsearch top-level-knn semantics), independent of the `from`/`size` hit
+page. Implementation: the shared kNN result assembler (`knn_result_from_scored`,
+used by *all* three executors — HNSW, exact brute-force, multi-kNN) computes the
+aggregation over the top-k sources when `aggs` is present. An `aggs`-bearing kNN
+routes to the **exact brute-force** path, because ANN recall is <100% and aggregate
+counts must be exact, not approximate.
+
+**Validated:**
+- Integration test `test_knn_plus_aggregations_single_request` — asserts the agg
+ runs over the exact semantic slice (far docs excluded), passes; no kNN
+ regressions.
+- Live, above, with real embeddings.
+
+**Request shape:**
+```json
+POST /conversations/_search
+{ "query": { "knn": { "field": "vec", "query_vector": [...], "k": 200, "num_candidates": 400 } },
+ "size": 3,
+ "aggs": { "by_band": { "terms": { "field": "band" },
+ "aggs": { "csat": { "percentiles": { "field":"csat","percents":[50] } } } } } }
+```
+
+**Honest limitation:** `significant_terms` over a kNN slice returns empty today — it
+needs a background corpus the vector path doesn't yet supply. Use `terms` (raw
+counts) inside a kNN slice, or the two-step pattern when you need statistical
+significance against the whole index. (Filed as the rc.6 follow-up.)
+
+See [`../../../engine/CHANGELOG-rc6.md`](../../../engine/CHANGELOG-rc6.md).
+
+---
+
+## Recommended architecture (embed → label → materialize → analyze)
+
+The pattern that scales, and the mental-model shift away from "SQL+embedding in one
+query":
+
+```
+ your per-customer embedding model
+ │ (at ingest)
+ conversation ──► embed(body) ──► vector ─┐
+ ├─ cluster/issue label ─┤ materialize as
+ ├─ nearest_kb + kb_distance ─┤ COLUMNS on the doc
+ └─ band, device, csat, aht … ─┘
+ │
+ XERJ (one index · object-store backed · ES-wire)
+ │
+ recurring reports ─► columnar aggs on the label columns (no kNN needed)
+ ad-hoc "calls about X" ─► knn + aggs in one request (rc.6)
+ report body ─► top_hits / knn hits → LLM synthesis
+```
+
+The expensive semantic work (labeling, distance-to-canonical) happens **once at
+ingest by your model**; the recurring reports become plain, fast columnar
+aggregations sitting next to the vectors and labels. "Minimize loss against
+canonical records" becomes `avg(kb_distance)` by issue, with high-distance outliers
+= novel/uncovered issues — a straight aggregation.
+
+---
+
+## Scaling guide
+
+- **Object-store backend (your setup).** Segments live on object storage; hot
+ segments are cached. Aggregations read columnar doc-values, so an analytics query
+ scans columns, not `_source`. Because your time-to-answer is LLM-bound, the extra
+ latency of a cold-segment fetch is usually in the noise — and warm reports are
+ fast. Keep the columns you aggregate on (`band`, `issue`, `csat`, `kb_distance`,
+ `day`) as typed fields so they get doc-values.
+- **Sizing the semantic slice (`k` / `num_candidates`).** `k` is the neighbour pool
+ the aggregation runs over; set it to how many conversations you want in the slice
+ (e.g. `k: 500`). `num_candidates` is the ANN fan-out for the plain (non-agg) path;
+ agg queries run exact brute-force, so `num_candidates` is ignored there — cost
+ scales with corpus size × dims for the scan. For very large corpora, pre-filter
+ with a cheap keyword/date `bool` before the vector step, or use the
+ materialized-label path (no kNN) for recurring reports.
+- **Ingest / labeling pipeline.** Do embedding + labeling + nearest-KB in your model
+ at ingest and bulk-index the results; this is the same "index once, query cheaply"
+ economics that makes the reports scale. Re-embedding on a model change is a
+ reindex job, not a query-time cost.
+- **Sharding & multi-tenant.** One index per customer (clean per-customer embedding
+ space and deletion) or a shared index with a `customer` keyword filter; the vector
+ `similarity`/dims are per-field, so per-customer models fit naturally as separate
+ indices.
+- **Cost lever.** The analytics are columnar aggregations on object-store-backed
+ segments — you pay storage + occasional fetch, not a always-on OLAP cluster. The
+ vector index (HNSW) is built for the plain-retrieval path; exact agg scans don't
+ need it, so an analytics-heavy workload can even skip graph build to save memory.
+
+---
+
+## Comparison with other approaches
+
+| approach | analytics | embeddings | one store? | the friction |
+|---|---|---|---|---|
+| **DuckDB shim + vector store** (your current) | ✅ great SQL | ✅ (separate) | ❌ | ETL between OLAP and vectors; no cross-system join; two things to operate |
+| **Postgres + pgvector** | ✅ full SQL | ✅ | ✅ | vector search + large-scan analytics compete for the same OLTP engine; kNN+GROUP BY works but scales poorly on big corpora; no object-store columnar tier |
+| **Elasticsearch / OpenSearch** | ✅ aggregations | ✅ kNN | ✅ | closest analog; kNN+aggs supported; heavier ops, JVM memory, and hot-storage cost model |
+| **Warehouse (Snowflake/BigQuery/Databricks) + vector add-on** | ✅ best-in-class SQL | ⚠️ bolt-on | ⚠️ | great for the SQL half; embedding retrieval is a second-class citizen; latency + cost for interactive report loops |
+| **Dedicated vector DB (Pinecone/Weaviate/Qdrant)** | ⚠️ limited aggs | ✅ | ✅ vectors | strong retrieval, weak columnar analytics; you'd still need a warehouse for the SQL half |
+| **XERJ (this)** | ✅ ES-compatible aggs | ✅ kNN/semantic | ✅ | one store, object-store backed, **kNN+aggs in one request (rc.6)**; gaps: no fused RRF hybrid, thin SQL surface, `significant_terms`-over-kNN pending |
+
+**Where XERJ fits calltree.ai specifically:** you already own the embedding/labeling
+step; you want the *analytics + retrieval + evidence* in one place with an
+object-store cost model and an ES-compatible surface. XERJ gives exactly that, and
+the one real gap for your example task (aggregate a semantic slice in one call) is
+now closed in rc.6.
+
+## Honest limitations (what to weigh)
+
+1. **Hybrid RRF isn't exposed** — approximate lexical+vector fusion with
+ `bool.should[match, knn]` or re-rank client-side.
+2. **SQL is a thin convenience layer** (`SELECT/WHERE/GROUP BY→terms/COUNT`) — don't
+ port DuckDB SQL 1:1; drive the aggregation API (or generate its JSON).
+3. **`significant_terms` over a kNN slice** returns empty (background not wired) —
+ use `terms` in-slice or the two-step for significance.
+4. **kNN quality is your embedding model's job** — XERJ stores/searches vectors; the
+ clustering quality is your per-customer model, which is where you already invest.
+
+## Run it
+```bash
+python3 01_make_dataset.py && python3 02_embed_index.py && python3 03_deep_research.py
+```
diff --git a/engine/CHANGELOG-rc6.md b/engine/CHANGELOG-rc6.md
new file mode 100644
index 000000000..a8d61df16
--- /dev/null
+++ b/engine/CHANGELOG-rc6.md
@@ -0,0 +1,33 @@
+# XERJ 1.0.0-rc.6 — changelog
+
+## New: kNN + aggregations in a single request
+
+Aggregations may now accompany a `knn` / semantic query. The aggregations run over
+the **retrieved top-`k` neighbour set** (Elasticsearch top-level-knn semantics),
+independent of the `from`/`size` hit page. This makes "aggregate a semantic slice"
+a single round-trip:
+
+```json
+POST /conversations/_search
+{
+ "query": { "knn": { "field": "vec", "query_vector": [...], "k": 200, "num_candidates": 400 } },
+ "size": 0,
+ "aggs": {
+ "by_band": { "terms": { "field": "band" } },
+ "csat_p50": { "percentiles": { "field": "csat", "percents": [50] } }
+ }
+}
+```
+
+- Covers every kNN executor (HNSW, exact brute-force, multi-kNN) — they all funnel
+ through the shared result assembler.
+- An `aggs`-bearing kNN takes the **exact brute-force** path (ANN recall is <100%;
+ aggregate counts must be exact, not approximate).
+- Aggregation is computed over all top-k sources, before `from`/`size` windowing.
+
+**Known limitation:** `significant_terms` over a kNN set returns empty — it needs a
+background corpus which the vector path does not yet supply. Use `terms` (raw
+counts) within a kNN slice, or the two-step pattern (kNN → ids → agg with the full
+index as background) when statistical significance is required.
+
+Tests: `test_knn_plus_aggregations_single_request` (integration).
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index d4189f907..26edfa99a 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -8659,7 +8659,17 @@ impl Index {
// boost, no similarity cutoff. Boost/cutoff requests go exact
// brute force where both are applied in the right order
// (cutoff on the unboosted transformed score, then boost).
- if filter_opt.is_none() && boost.is_none() && min_similarity.is_none() {
+ //
+ // rc.6: an `aggs`-bearing knn also takes the exact brute-force
+ // path. ANN recall is <100%, so the retrieved top-k neighbour
+ // SET can differ slightly from exact; aggregations over that set
+ // must be exact (analytics counts, not ranked hits), so we do not
+ // let ANN approximation leak into agg buckets.
+ if filter_opt.is_none()
+ && boost.is_none()
+ && min_similarity.is_none()
+ && request.aggs.is_none()
+ {
if let Some(result) = self
.run_knn_hnsw(request, &field, &query_vec, k, num_candidates, &similarity)
.await
@@ -19833,6 +19843,21 @@ fn knn_result_from_scored(
// (Hybrid/RRF ignores this total and recomputes its own from the fused
// list, so bounding it here is safe for that path.)
let total_value = scored.len() as u64;
+
+ // ── kNN + aggregations (rc.6) ─────────────────────────────────────
+ // ES top-level-`knn` semantics: when `aggs` accompany a knn/semantic
+ // query, the aggregations run over the RETRIEVED NEIGHBOUR SET (the
+ // top-`k` after the `num_candidates` fan-out), independent of the
+ // `from`/`size` hit-page. This makes "aggregate a semantic slice" a
+ // single request — e.g. `knn(topic) + terms(band) + significant_terms`.
+ // Computed BEFORE `scored` is consumed into hits, over all top-k
+ // sources (not the paginated page). Every knn executor (HNSW,
+ // brute-force, multi-knn) funnels through here, so all of them gain it.
+ let aggs = request.aggs.as_ref().map(|aggs_def| {
+ let sources: Vec<Value> = scored.iter().map(|(_, _, s)| s.clone()).collect();
+ crate::aggs::run_aggs(aggs_def, &sources)
+ });
+
let hits: Vec<Hit> = if request.size == 0 {
Vec::new()
} else {
@@ -19861,7 +19886,7 @@ fn knn_result_from_scored(
relation: TotalHitsRelation::Eq,
},
took_ms: started.elapsed().as_millis() as u64,
- aggs: None,
+ aggs,
timed_out: false,
profile: None,
max_score: None,
diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rs
index bb8f46b1c..419f9d897 100644
--- a/engine/crates/xerj-engine/tests/integration.rs
+++ b/engine/crates/xerj-engine/tests/integration.rs
@@ -5802,6 +5802,7 @@ async fn test_highlight_survives_source_filtering() {
);
}
+<<<<<<< Updated upstream
// ── Reproduction: term/terms on a NON-FIRST array element (multi-valued keyword) ─
// A keyword ARRAY currently stores ONLY element [0] in the single-valued
// doc-values column (memtable `push_field`) AND the single-valued segment
@@ -5865,4 +5866,52 @@ async fn test_term_matches_non_first_array_element() {
rt.total.value, 1,
"terms must match a NON-FIRST array element"
);
+=======
+// ── kNN + aggregations in a single request (rc.5) ─────────────────────────────
+// The gap the calltree.ai analytics use-case hit: aggregate a SEMANTIC slice in
+// one call. Aggregations must run over the retrieved top-k neighbour set (ES
+// top-level-knn semantics), independent of the from/size hit page.
+#[tokio::test]
+async fn test_knn_plus_aggregations_single_request() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ let mut schema = Schema::empty();
+ let mut vf = FieldConfig::new("v", FieldType::Vector);
+ vf.options.dimensions = Some(3);
+ vf.options.similarity = Some("cosine".to_string());
+ schema.fields.push(vf);
+ schema.fields.push(FieldConfig::new("band", FieldType::Keyword));
+ engine.create_index("knnagg", schema).unwrap();
+ let idx = engine.get_index("knnagg").unwrap();
+
+ // Four docs near [1,0,0] (the "topic" cluster) split across two bands,
+ // plus one far-away doc that must NOT enter the top-k or the agg buckets.
+ idx.index_document(Some("1".into()), json!({"v":[1.0,0.0,0.0],"band":"2.4GHz"})).await.unwrap();
+ idx.index_document(Some("2".into()), json!({"v":[0.98,0.02,0.0],"band":"2.4GHz"})).await.unwrap();
+ idx.index_document(Some("3".into()), json!({"v":[0.95,0.05,0.0],"band":"5GHz"})).await.unwrap();
+ idx.index_document(Some("4".into()), json!({"v":[0.9,0.1,0.0],"band":"5GHz"})).await.unwrap();
+ idx.index_document(Some("far".into()), json!({"v":[0.0,0.0,1.0],"band":"other"})).await.unwrap();
+
+ // knn over the topic cluster (k=4 → the 4 near docs), size:0 (analytics),
+ // aggregate the retrieved set by band.
+ let req = parse_request(&json!({
+ "query": {"knn": {"field":"v","query_vector":[1.0,0.0,0.0],"k":4,"num_candidates":10}},
+ "size": 0,
+ "aggs": {"by_band": {"terms": {"field": "band"}}}
+ })).unwrap();
+ let res = idx.search(&req).await.unwrap();
+
+ // aggregations must be present and computed over the top-4 (not all 5).
+ let aggs = res.aggs.expect("knn query must carry aggregations");
+ let buckets = aggs["by_band"]["buckets"].as_array().expect("terms buckets");
+ let mut counts: std::collections::HashMap<String, i64> = std::collections::HashMap::new();
+ for b in buckets {
+ counts.insert(b["key"].as_str().unwrap().to_string(), b["doc_count"].as_i64().unwrap());
+ }
+ assert_eq!(counts.get("2.4GHz"), Some(&2), "2.4GHz count over the semantic slice");
+ assert_eq!(counts.get("5GHz"), Some(&2), "5GHz count over the semantic slice");
+ assert_eq!(counts.get("other"), None, "the far doc must NOT be in the agg (excluded from top-k)");
+ assert_eq!(res.total.value, 4, "hits.total is the retrieved neighbour pool");
+ assert!(res.hits.is_empty(), "size:0 returns aggs only, no hits");
+>>>>>>> Stashed changes
}