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(es-compat): real single-node transform & rollup execution (Batch E)
xerj-orgef99e6f3d308
diff --git a/demo/playbooks/ES_API_AUDIT.md b/demo/playbooks/ES_API_AUDIT.mdindex c1cfe539f..4d86b2a46 100644--- a/demo/playbooks/ES_API_AUDIT.md+++ b/demo/playbooks/ES_API_AUDIT.md@@ -6,9 +6,9 @@ Every route in `build_es_compat_router` was **tested live against a running bina| verdict | count | share ||---|--:|--:|-| ✅ REAL | 140 | 86% |-| 🟡 PARTIAL | 8 | 5% |-| ⚪ STUB | 14 | 9% |+| ✅ REAL | 147 | 91% |+| 🟡 PARTIAL | 6 | 4% |+| ⚪ STUB | 9 | 6% || ❌ BROKEN | 0 | 0% |**Read it as:** the entire core data plane — documents, bulk, the full query DSL, aggregations, vectors/kNN, mappings, settings, templates, aliases, scroll/PIT, reindex, update/delete-by-query, snapshot/restore, ingest pipelines, analyzers — is REAL. The STUBs are exactly the surfaces a single-node engine cannot meaningfully back: distributed-only features (CCR, transform/rollup execution, cluster reroute/allocation, tasks, ML) and Kibana handshake shims (X-Pack, security, license, watcher, monitoring) — routed so ES clients/Kibana negotiate cleanly rather than 404.@@ -30,7 +30,7 @@ Every route in `build_es_compat_router` was **tested live against a running bina| snapshot | 4 | 4 | 0 | 0 | 0 || tasks | 4 | 4 | 0 | 0 | 0 || templates | 4 | 4 | 0 | 0 | 0 |-| transform-rollup-ccr | 14 | 0 | 3 | 11 | 0 |+| transform-rollup-ccr | 14 | 7 | 1 | 6 | 0 || watcher-monitoring | 4 | 4 | 0 | 0 | 0 || xpack-security | 6 | 6 | 0 | 0 | 0 |@@ -40,25 +40,25 @@ Single node, `--insecure`, release binary. Generated by `demo/playbooks/bench.mj## Bulk ingest-- Docs ingested: **40,000** (real LLM-telemetry corpus, 10,000/batch)-- Wall time (bulk only): **1.5 s**-- Throughput: **26,521 docs/s**+- Docs ingested: **100,000** (real LLM-telemetry corpus, 10,000/batch)+- Wall time (bulk only): **3.8 s**+- Throughput: **26,618 docs/s**-## Read-path latency (ms) — 100 iters after warmup, over 40,000 docs+## Read-path latency (ms) — 100 iters after warmup, over 100,000 docs| operation | mean | p50 | p95 | p99 | max ||---|--:|--:|--:|--:|--:|-| match_all (size 10) | 1.57 | 1.55 | 2.01 | 2.22 | 2.22 |-| term filter | 1.66 | 1.62 | 2.21 | 2.33 | 2.33 |-| bool must+filter | 1.63 | 1.60 | 2.07 | 2.28 | 2.28 |-| range | 1.39 | 1.37 | 1.75 | 2.33 | 2.33 |-| agg: terms(model) | 1.43 | 1.41 | 1.80 | 2.32 | 2.32 |-| agg: stats(latency_ms) | 1.29 | 1.26 | 1.66 | 1.90 | 1.90 |-| agg: date_histogram | 1.38 | 1.34 | 2.26 | 2.94 | 2.94 |-| agg: terms+nested avg | 1.41 | 1.35 | 1.65 | 1.76 | 1.76 |-| cardinality | 1.33 | 1.31 | 1.61 | 2.47 | 2.47 |-| _count | 1.30 | 1.26 | 1.58 | 1.76 | 1.76 |-| kNN k=10 (20k×16d) | 1.44 | 1.40 | 1.71 | 2.43 | 2.43 |+| match_all (size 10) | 1.59 | 1.62 | 2.04 | 2.55 | 2.55 |+| term filter | 1.55 | 1.59 | 1.75 | 2.18 | 2.18 |+| bool must+filter | 1.51 | 1.52 | 1.76 | 1.94 | 1.94 |+| range | 5.05 | 1.41 | 1.99 | 362.35 | 362.35 |+| agg: terms(model) | 1.42 | 1.36 | 2.07 | 7.10 | 7.10 |+| agg: stats(latency_ms) | 1.27 | 1.23 | 1.38 | 2.75 | 2.75 |+| agg: date_histogram | 1.37 | 1.35 | 1.58 | 2.49 | 2.49 |+| agg: terms+nested avg | 1.38 | 1.36 | 1.72 | 1.96 | 1.96 |+| cardinality | 1.27 | 1.27 | 1.39 | 4.60 | 4.60 |+| _count | 1.18 | 1.17 | 1.45 | 3.09 | 3.09 |+| kNN k=10 (20k×16d) | 1.44 | 1.40 | 1.67 | 1.98 | 1.98 |_All latencies are end-to-end HTTP round-trip from localhost. kNN over a separate 20k×16-d HNSW index._@@ -306,13 +306,13 @@ _14/14 tested live: 3 PUT handlers (transform, rollup job, ccr auto_follow) genu| ⚪ | POST | `/:index/_ccr/unfollow` | `ccr_unfollow` | 501 | 501 'CCR... not on v1.0 roadmap'. Src 18761: not_implemented_yet() stub. || 🟡 | PUT | `/_ccr/auto_follow/:name` | `put_ccr_auto_follow` | 200 | 200 {"acknowledged":true}; re-GET returns pattern w/ injected name -> persists to engine.ccr_auto_follow. Src 18801: insert only; CCR engine is single-cluster, pattern never acts (follow=501). || ⚪ | GET | `/_ccr/stats` | `ccr_stats` | 200 | 200 all counters 0, follow_stats.indices=[]. Src 18768: State(_state) unused, returns fixed JSON literal -> static, never reflects engine state. |-| ⚪ | GET | `/_rollup/data/:index` | `get_rollup_data` | 200 | 200 hits.total.value=0, hits=[] for index 'bench'. Src 18698-18705: _state unused, returns hardcoded empty shards/hits regardless of index -> no real rollup data. |-| 🟡 | PUT | `/_rollup/job/:id` | `put_rollup_job` | 200 | 200 {"acknowledged":true}; re-GET returns stored job w/ id -> persists to engine.rollup_jobs. Src 18624: insert only, no validation; no rollup index built, _start 501. |-| ⚪ | POST | `/_rollup/job/:id/_start` | `start_rollup_job` | 501 | 501 'Rollup job execution... _start does not run the rollup'. Src 18680: not_implemented_yet() stub. |-| ⚪ | POST | `/_rollup/job/:id/_stop` | `stop_rollup_job` | 501 | 501 '..._stop has nothing to stop'. Src 18691: not_implemented_yet() stub, no job state. |-| 🟡 | PUT | `/_transform/:id` | `put_transform` | 200 | 200 {"acknowledged":true}; re-GET returns exact config w/ injected id -> persists to engine.transforms dashmap. Src 18509: insert only, no validation; _start is 501 so aggregator never runs. |-| ⚪ | POST | `/_transform/:id/_start` | `start_transform` | 501 | 501 not_implemented_exception 'Transform job execution... _start does not actually run the aggregator'. Src 18575: hardcoded not_implemented_yet(), no engine call. |-| ⚪ | POST | `/_transform/:id/_stop` | `stop_transform` | 501 | 501 '..._stop has nothing to stop'. Src 18586: not_implemented_yet() stub, no state touched. |+| ✅ | GET | `/_rollup/data/:index` | `get_rollup_data` | 200 | Live: GET /_rollup/data/bench_rollup -> real caps from stored job: fields={@timestamp:[date_histogram 1d UTC], model:[terms], latency_ms:[avg,max,min], completion_tokens:[sum]}, index_pattern bench, job_id daily. Derived from engine.rollup_jobs filtered by rollup_index. |+| ✅ | PUT | `/_rollup/job/:id` | `put_rollup_job` | 200 | 200 {acknowledged:true}; persists to engine.rollup_jobs. _start now runs a real rollup; GET /_rollup/data returns derived caps. |+| ✅ | POST | `/_rollup/job/:id/_start` | `start_rollup_job` | 200 | Live: PUT daily (date_histogram @timestamp 1d + terms model; metrics latency_ms[avg,max,min], completion_tokens[sum]) then _start -> {started:true}, 12 rolled-up docs in bench_rollup; sample {@timestamp:1777161600000,model,latency_ms.avg:310.77,max:436,min:228,completion_tokens.sum:5294,doc_count:13,_rollup.id:daily}. run_rollup_job builds composite (date_histogram+terms sources, per-metric sub-aggs), iterates pattern-matched indices, after_key paginated, writes to rollup_index. |+| ✅ | POST | `/_rollup/job/:id/_stop` | `stop_rollup_job` | 200 | Live: _stop -> {stopped:true}; state recorded on engine.rollup_jobs entry (_xerj.state=stopped). |+| ✅ | PUT | `/_transform/:id` | `put_transform` | 200 | 200 {acknowledged:true}; persists to engine.transforms. _start now runs a real pivot. config re-GET returns it w/ injected id. |+| ✅ | POST | `/_transform/:id/_start` | `start_transform` | 200 | Live: PUT by_model (group_by model+intent terms, aggs avg latency_ms + sum completion_tokens) then _start -> 47 grouped docs written to dest bench_by_model from 4008 source docs; sample {model,intent,avg_latency:341.33,total_completion:844,doc_count:3}. run_pivot_transform builds composite agg (group_by->sources, after_key paginated), flattens each bucket, index_document into dest, refresh; documents_processed recorded. |+| ✅ | POST | `/_transform/:id/_stop` | `stop_transform` | 200 | Live: _stop -> {acknowledged:true}; GET _transform/by_model shows _xerj={state:stopped,documents_processed:47}. Real state transition on engine.transforms entry. |### watcher-monitoringdiff --git a/demo/playbooks/PARITY_BACKLOG.md b/demo/playbooks/PARITY_BACKLOG.mdindex 2269d73e6..ff44c45b8 100644--- a/demo/playbooks/PARITY_BACKLOG.md+++ b/demo/playbooks/PARITY_BACKLOG.md@@ -9,8 +9,9 @@ real on one binary and are the loop's terminal set.- [x] **B — index management ops**: `_close`/`_open`, `_cache/clear`, `_disk_usage`, `_shrink`/`_split`, `_freeze`/`_unfreeze`, `_recovery`- [x] **C — cluster/node stats realness**: `_nodes`, `_nodes/stats`, `_nodes/:id/stats`, `_cluster/stats`, `_cluster/state`, `_cluster/pending_tasks`, `_internal/desired_balance`, `_index_template/_simulate_index`, `painless/_execute`, `_ilm/policy`- [x] **D — cat honest-derived**: `_cat/segments`, `_cat/fielddata`, `_cat/pending_tasks`, `_cat/plugins`, `_cat/nodeattrs`, `:index/_alias`, `_tasks/:id/_cancel`, `_update_by_query`-- [ ] **E — transform/rollup execution** (single-node feasible: scheduled aggregation jobs)-- [ ] **TERMINAL (cannot do single-node)**: all `_ccr/*`, `_cat/ml/*` — leave as honest stubs, document.+- [x] **E — transform/rollup execution**: `_transform/:id/_start`+`_stop` (real pivot via composite agg → dest), `_rollup/job/:id/_start`+`_stop` (real date_histogram+terms+metrics → rollup_index), `_rollup/data/:index` (real caps). Live: 4008→47 pivot docs, 12 rollup docs.+- [ ] **F — stragglers**: `cluster_allocation_explain`, `cluster_reroute`, `search` GET/POST (investigate the PARTIAL), `cat_thread_pool` (honest-real or document).+- [ ] **TERMINAL (cannot do single-node)**: all `_ccr/*` (needs ≥2 clusters), `_cat/ml/*` (needs ML engine) — leave as honest stubs, document.## Loop protocolEach iteration: pick next unchecked batch → implement (codegen workflow) → build →diff --git a/demo/playbooks/es_api_audit.json b/demo/playbooks/es_api_audit.jsonindex 4bc81cf9c..65260fb88 100644--- a/demo/playbooks/es_api_audit.json+++ b/demo/playbooks/es_api_audit.json@@ -1246,26 +1246,26 @@"path": "/_transform/:id","handler": "put_transform","http_status": 200,- "verdict": "PARTIAL",- "evidence": "200 {\"acknowledged\":true}; re-GET returns exact config w/ injected id -> persists to engine.transforms dashmap. Src 18509: insert only, no validation; _start is 501 so aggregator never runs.",+ "verdict": "REAL",+ "evidence": "200 {acknowledged:true}; persists to engine.transforms. _start now runs a real pivot. config re-GET returns it w/ injected id.","group": "transform-rollup-ccr"},{"method": "POST","path": "/_transform/:id/_start","handler": "start_transform",- "http_status": 501,- "verdict": "STUB",- "evidence": "501 not_implemented_exception 'Transform job execution... _start does not actually run the aggregator'. Src 18575: hardcoded not_implemented_yet(), no engine call.",+ "http_status": 200,+ "verdict": "REAL",+ "evidence": "Live: PUT by_model (group_by model+intent terms, aggs avg latency_ms + sum completion_tokens) then _start -> 47 grouped docs written to dest bench_by_model from 4008 source docs; sample {model,intent,avg_latency:341.33,total_completion:844,doc_count:3}. run_pivot_transform builds composite agg (group_by->sources, after_key paginated), flattens each bucket, index_document into dest, refresh; documents_processed recorded.","group": "transform-rollup-ccr"},{"method": "POST","path": "/_transform/:id/_stop","handler": "stop_transform",- "http_status": 501,- "verdict": "STUB",- "evidence": "501 '..._stop has nothing to stop'. Src 18586: not_implemented_yet() stub, no state touched.",+ "http_status": 200,+ "verdict": "REAL",+ "evidence": "Live: _stop -> {acknowledged:true}; GET _transform/by_model shows _xerj={state:stopped,documents_processed:47}. Real state transition on engine.transforms entry.","group": "transform-rollup-ccr"},{@@ -1273,26 +1273,26 @@"path": "/_rollup/job/:id","handler": "put_rollup_job","http_status": 200,- "verdict": "PARTIAL",- "evidence": "200 {\"acknowledged\":true}; re-GET returns stored job w/ id -> persists to engine.rollup_jobs. Src 18624: insert only, no validation; no rollup index built, _start 501.",+ "verdict": "REAL",+ "evidence": "200 {acknowledged:true}; persists to engine.rollup_jobs. _start now runs a real rollup; GET /_rollup/data returns derived caps.","group": "transform-rollup-ccr"},{"method": "POST","path": "/_rollup/job/:id/_start","handler": "start_rollup_job",- "http_status": 501,- "verdict": "STUB",- "evidence": "501 'Rollup job execution... _start does not run the rollup'. Src 18680: not_implemented_yet() stub.",+ "http_status": 200,+ "verdict": "REAL",+ "evidence": "Live: PUT daily (date_histogram @timestamp 1d + terms model; metrics latency_ms[avg,max,min], completion_tokens[sum]) then _start -> {started:true}, 12 rolled-up docs in bench_rollup; sample {@timestamp:1777161600000,model,latency_ms.avg:310.77,max:436,min:228,completion_tokens.sum:5294,doc_count:13,_rollup.id:daily}. run_rollup_job builds composite (date_histogram+terms sources, per-metric sub-aggs), iterates pattern-matched indices, after_key paginated, writes to rollup_index.","group": "transform-rollup-ccr"},{"method": "POST","path": "/_rollup/job/:id/_stop","handler": "stop_rollup_job",- "http_status": 501,- "verdict": "STUB",- "evidence": "501 '..._stop has nothing to stop'. Src 18691: not_implemented_yet() stub, no job state.",+ "http_status": 200,+ "verdict": "REAL",+ "evidence": "Live: _stop -> {stopped:true}; state recorded on engine.rollup_jobs entry (_xerj.state=stopped).","group": "transform-rollup-ccr"},{@@ -1300,8 +1300,8 @@"path": "/_rollup/data/:index","handler": "get_rollup_data","http_status": 200,- "verdict": "STUB",- "evidence": "200 hits.total.value=0, hits=[] for index 'bench'. Src 18698-18705: _state unused, returns hardcoded empty shards/hits regardless of index -> no real rollup data.",+ "verdict": "REAL",+ "evidence": "Live: GET /_rollup/data/bench_rollup -> real caps from stored job: fields={@timestamp:[date_histogram 1d UTC], model:[terms], latency_ms:[avg,max,min], completion_tokens:[sum]}, index_pattern bench, job_id daily. Derived from engine.rollup_jobs filtered by rollup_index.","group": "transform-rollup-ccr"},{diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 44f2d58f1..42c5b39db 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -19174,29 +19174,64 @@ pub async fn delete_transform(}pub async fn start_transform(- State(_state): State<AppState>,- Path(_id): Path<String>,+ State(state): State<AppState>,+ Path(id): Path<String>,) -> impl IntoResponse {- // v0.6.1 — transform DEFINITIONS are stored via PUT /_transform/{id},- // but no pivot/latest aggregator job actually runs. Replace the- // misleading 200-OK with 501 so clients know the transform won't- // produce any output.- crate::stub::not_implemented_yet(- "Transform job execution (pivot / latest)",- "v1.x",- "PUT/GET/DELETE on transforms still works (storage only); _start does not actually run the aggregator",- )+ // Real single-node pivot execution: pull the stored config, run the+ // composite aggregation derived from group_by + aggregations against the+ // source index, and write one document per bucket into dest. (Clone the+ // config out first — never hold the DashMap guard across an `.await`.)+ let config = match state.engine.transforms.get(&id) {+ Some(c) => c.clone(),+ None => {+ let e = xerj_common::XerjError::index_not_found(format!("transform [{id}] not found"));+ return ApiError::new(e).into_response();+ }+ };++ match run_pivot_transform(&state, &config).await {+ Ok(written) => {+ // Record run state on the stored config so GET reflects it.+ if let Some(mut e) = state.engine.transforms.get_mut(&id) {+ if let Some(o) = e.value_mut().as_object_mut() {+ o.insert(+ "_xerj".to_string(),+ json!({ "state": "started", "documents_processed": written }),+ );+ }+ }+ Json(json!({ "acknowledged": true })).into_response()+ }+ Err(msg) => {+ let e = xerj_common::XerjError::invalid_query(format!(+ "transform [{id}] execution failed: {msg}"+ ));+ ApiError::new(e).into_response()+ }+ }}pub async fn stop_transform(- State(_state): State<AppState>,- Path(_id): Path<String>,+ State(state): State<AppState>,+ Path(id): Path<String>,) -> impl IntoResponse {- crate::stub::not_implemented_yet(- "Transform job execution (pivot / latest)",- "v1.x",- "PUT/GET/DELETE on transforms still works (storage only); _stop has nothing to stop",- )+ if let Some(mut e) = state.engine.transforms.get_mut(&id) {+ if let Some(o) = e.value_mut().as_object_mut() {+ let processed = o+ .get("_xerj")+ .and_then(|x| x.get("documents_processed"))+ .cloned()+ .unwrap_or(json!(0));+ o.insert(+ "_xerj".to_string(),+ json!({ "state": "stopped", "documents_processed": processed }),+ );+ }+ Json(json!({ "acknowledged": true })).into_response()+ } else {+ let e = xerj_common::XerjError::index_not_found(format!("transform [{id}] not found"));+ ApiError::new(e).into_response()+ }}// ─────────────────────────────────────────────────────────────────────────────@@ -19281,37 +19316,441 @@ pub async fn delete_rollup_job(}pub async fn start_rollup_job(- State(_state): State<AppState>,- Path(_id): Path<String>,+ State(state): State<AppState>,+ Path(id): Path<String>,) -> impl IntoResponse {- // v0.6.1 — was returning `{"started": true}` for any registered- // rollup job, even though no rollup actually runs. Honest 501.- crate::stub::not_implemented_yet(- "Rollup job execution",- "v1.x",- "PUT/GET/DELETE on rollup jobs still works (storage); _start does not run the rollup",- )+ // Real single-node rollup execution: run the composite aggregation derived+ // from groups (date_histogram + terms/histogram) with one sub-agg per+ // metric over the source index(es), and write rolled-up docs into+ // rollup_index. Clone config out before the `.await`.+ let config = match state.engine.rollup_jobs.get(&id) {+ Some(c) => c.clone(),+ None => {+ let e = xerj_common::XerjError::index_not_found(format!("rollup job [{id}] not found"));+ return ApiError::new(e).into_response();+ }+ };++ match run_rollup_job(&state, &id, &config).await {+ Ok(written) => {+ if let Some(mut e) = state.engine.rollup_jobs.get_mut(&id) {+ if let Some(o) = e.value_mut().as_object_mut() {+ o.insert(+ "_xerj".to_string(),+ json!({ "state": "started", "documents_processed": written }),+ );+ }+ }+ Json(json!({ "started": true })).into_response()+ }+ Err(msg) => {+ let e = xerj_common::XerjError::invalid_query(format!(+ "rollup job [{id}] execution failed: {msg}"+ ));+ ApiError::new(e).into_response()+ }+ }}pub async fn stop_rollup_job(- State(_state): State<AppState>,- Path(_id): Path<String>,+ State(state): State<AppState>,+ Path(id): Path<String>,) -> impl IntoResponse {- crate::stub::not_implemented_yet(- "Rollup job execution",- "v1.x",- "PUT/GET/DELETE on rollup jobs still works (storage); _stop has nothing to stop",- )+ if let Some(mut e) = state.engine.rollup_jobs.get_mut(&id) {+ if let Some(o) = e.value_mut().as_object_mut() {+ let processed = o+ .get("_xerj")+ .and_then(|x| x.get("documents_processed"))+ .cloned()+ .unwrap_or(json!(0));+ o.insert(+ "_xerj".to_string(),+ json!({ "state": "stopped", "documents_processed": processed }),+ );+ }+ Json(json!({ "stopped": true })).into_response()+ } else {+ let e = xerj_common::XerjError::index_not_found(format!("rollup job [{id}] not found"));+ ApiError::new(e).into_response()+ }}pub async fn get_rollup_data(- State(_state): State<AppState>,- Path(_index): Path<String>,+ State(state): State<AppState>,+ Path(index): Path<String>,) -> impl IntoResponse {- Json(json!({- "_shards": { "total": 1, "successful": 1, "failed": 0 },- "hits": { "total": { "value": 0, "relation": "eq" }, "hits": [] }- }))+ // ES `GET /<rollup_index>/_rollup/data` returns the rollup capabilities of+ // an index: which jobs wrote into it and what fields/aggs they cover.+ // Derive that from the stored rollup-job configs whose rollup_index matches.+ let mut jobs: Vec<Value> = Vec::new();+ for e in state.engine.rollup_jobs.iter() {+ let cfg = e.value();+ let rollup_index = cfg.get("rollup_index").and_then(|v| v.as_str()).unwrap_or("");+ if rollup_index != index {+ continue;+ }+ let index_pattern = cfg.get("index_pattern").and_then(|v| v.as_str()).unwrap_or("");+ let mut fields = serde_json::Map::new();+ if let Some(groups) = cfg.get("groups").and_then(|g| g.as_object()) {+ if let Some(dh) = groups.get("date_histogram").and_then(|d| d.as_object()) {+ if let Some(field) = dh.get("field").and_then(|f| f.as_str()) {+ let mut agg = serde_json::Map::new();+ agg.insert("agg".to_string(), json!("date_histogram"));+ for k in ["fixed_interval", "calendar_interval", "interval", "delay", "time_zone"] {+ if let Some(v) = dh.get(k) {+ agg.insert(k.to_string(), v.clone());+ }+ }+ if !agg.contains_key("time_zone") {+ agg.insert("time_zone".to_string(), json!("UTC"));+ }+ fields.insert(field.to_string(), json!([Value::Object(agg)]));+ }+ }+ if let Some(terms) = groups.get("terms").and_then(|t| t.get("fields")).and_then(|f| f.as_array()) {+ for f in terms {+ if let Some(field) = f.as_str() {+ fields.entry(field.to_string()).or_insert_with(|| json!([]));+ if let Some(arr) = fields.get_mut(field).and_then(|v| v.as_array_mut()) {+ arr.push(json!({ "agg": "terms" }));+ }+ }+ }+ }+ if let Some(hist) = groups.get("histogram").and_then(|h| h.as_object()) {+ let interval = hist.get("interval").cloned().unwrap_or(json!(null));+ if let Some(hfields) = hist.get("fields").and_then(|f| f.as_array()) {+ for f in hfields {+ if let Some(field) = f.as_str() {+ fields.entry(field.to_string()).or_insert_with(|| json!([]));+ if let Some(arr) = fields.get_mut(field).and_then(|v| v.as_array_mut()) {+ arr.push(json!({ "agg": "histogram", "interval": interval }));+ }+ }+ }+ }+ }+ }+ if let Some(metrics) = cfg.get("metrics").and_then(|m| m.as_array()) {+ for m in metrics {+ let field = m.get("field").and_then(|f| f.as_str()).unwrap_or("");+ if field.is_empty() {+ continue;+ }+ fields.entry(field.to_string()).or_insert_with(|| json!([]));+ if let Some(arr) = fields.get_mut(field).and_then(|v| v.as_array_mut()) {+ if let Some(ms) = m.get("metrics").and_then(|x| x.as_array()) {+ for one in ms {+ if let Some(name) = one.as_str() {+ arr.push(json!({ "agg": name }));+ }+ }+ }+ }+ }+ }+ jobs.push(json!({+ "job_id": e.key().clone(),+ "rollup_index": rollup_index,+ "index_pattern": index_pattern,+ "fields": Value::Object(fields),+ }));+ }++ Json(json!({ index: { "rollup_jobs": jobs } })).into_response()+}++// ─────────────────────────────────────────────────────────────────────────────+// Transform / rollup execution helpers (real single-node aggregation jobs).+// ─────────────────────────────────────────────────────────────────────────────++/// Build a deterministic, idempotent doc id from a composite key's values+/// (in `order`), optionally namespaced by a prefix (e.g. the source index).+fn agg_key_doc_id(prefix: &str, key: &Value, order: &[String]) -> String {+ let mut parts: Vec<String> = Vec::new();+ if !prefix.is_empty() {+ parts.push(prefix.to_string());+ }+ if let Some(ko) = key.as_object() {+ for k in order {+ match ko.get(k) {+ Some(Value::String(s)) => parts.push(s.clone()),+ Some(Value::Null) | None => parts.push("_null".to_string()),+ Some(v) => parts.push(v.to_string()),+ }+ }+ }+ let joined = parts.join("__");+ if joined.is_empty() {+ "_empty".to_string()+ } else {+ joined+ }+}++/// Flatten a composite bucket's sub-aggregation results onto `doc`. Single-value+/// metrics (`{"value": x}`) flatten to the scalar under `name`; multi-value+/// metrics (stats/percentiles) are kept as the nested object.+fn flatten_bucket_metrics(doc: &mut serde_json::Map<String, Value>, bucket: &serde_json::Map<String, Value>) {+ for (k, v) in bucket {+ if k == "key" || k == "doc_count" {+ continue;+ }+ if let Some(val) = v.get("value") {+ doc.insert(k.clone(), val.clone());+ } else {+ doc.insert(k.clone(), v.clone());+ }+ }+}++/// Run a pivot transform end to end. Returns the number of docs written to dest.+async fn run_pivot_transform(state: &AppState, config: &Value) -> Result<usize, String> {+ let source_index = config+ .pointer("/source/index")+ .and_then(|v| {+ v.as_str()+ .map(|s| s.to_string())+ .or_else(|| v.as_array().and_then(|a| a.first()).and_then(|x| x.as_str()).map(|s| s.to_string()))+ })+ .ok_or_else(|| "transform has no source.index".to_string())?;+ let dest_index = config+ .pointer("/dest/index")+ .and_then(|v| v.as_str())+ .ok_or_else(|| "transform has no dest.index".to_string())?+ .to_string();+ let group_by = config+ .pointer("/pivot/group_by")+ .and_then(|v| v.as_object())+ .cloned()+ .ok_or_else(|| "transform has no pivot.group_by".to_string())?;+ let pivot_aggs = config+ .pointer("/pivot/aggregations")+ .or_else(|| config.pointer("/pivot/aggs"))+ .cloned()+ .unwrap_or_else(|| json!({}));+ let source_query = config.pointer("/source/query").cloned();++ // Each group_by entry is already a composite source spec: {name: {terms|date_histogram|histogram: {...}}}.+ let order: Vec<String> = group_by.keys().cloned().collect();+ let sources: Vec<Value> = order.iter().map(|name| json!({ name.clone(): group_by[name] })).collect();++ let src_idx = state.engine.get_index(&source_index).map_err(|e| e.to_string())?;+ let dest_idx = state.engine.get_or_create_index(&dest_index).map_err(|e| e.to_string())?;++ let mut after: Option<Value> = None;+ let mut written = 0usize;+ loop {+ let mut composite = json!({ "size": 1000, "sources": sources });+ if let Some(ref a) = after {+ composite["after"] = a.clone();+ }+ let mut body = json!({+ "size": 0,+ "aggs": { "_pivot": { "composite": composite, "aggregations": pivot_aggs } }+ });+ if let Some(ref q) = source_query {+ body["query"] = q.clone();+ }+ let req = xerj_query::parse_request(&body).map_err(|e| e.to_string())?;+ let res = src_idx.search(&req).await.map_err(|e| e.to_string())?;+ let aggs = match res.aggs {+ Some(a) => a,+ None => break,+ };+ let pivot = match aggs.get("_pivot") {+ Some(p) => p,+ None => break,+ };+ let buckets = pivot.get("buckets").and_then(|b| b.as_array()).cloned().unwrap_or_default();+ if buckets.is_empty() {+ break;+ }+ for b in &buckets {+ let key = b.get("key").cloned().unwrap_or_else(|| json!({}));+ let mut doc = serde_json::Map::new();+ if let Some(ko) = key.as_object() {+ for (k, v) in ko {+ doc.insert(k.clone(), v.clone());+ }+ }+ if let Some(bo) = b.as_object() {+ flatten_bucket_metrics(&mut doc, bo);+ }+ doc.insert("doc_count".to_string(), b.get("doc_count").cloned().unwrap_or(json!(0)));+ let id = agg_key_doc_id("", &key, &order);+ dest_idx+ .index_document(Some(id), Value::Object(doc))+ .await+ .map_err(|e| e.to_string())?;+ written += 1;+ }+ match pivot.get("after_key") {+ Some(ak) if !ak.is_null() => after = Some(ak.clone()),+ _ => break,+ }+ if buckets.len() < 1000 {+ break;+ }+ }+ dest_idx.refresh().await.ok();+ Ok(written)+}++/// Run a rollup job end to end across every index matching `index_pattern`.+/// Returns the total number of rolled-up docs written to rollup_index.+async fn run_rollup_job(state: &AppState, job_id: &str, config: &Value) -> Result<usize, String> {+ let index_pattern = config+ .get("index_pattern")+ .and_then(|v| v.as_str())+ .ok_or_else(|| "rollup job has no index_pattern".to_string())?+ .to_string();+ let rollup_index = config+ .get("rollup_index")+ .and_then(|v| v.as_str())+ .ok_or_else(|| "rollup job has no rollup_index".to_string())?+ .to_string();+ let groups = config+ .get("groups")+ .and_then(|v| v.as_object())+ .ok_or_else(|| "rollup job has no groups".to_string())?;+ let metrics = config.get("metrics").and_then(|v| v.as_array()).cloned().unwrap_or_default();++ // Composite sources from groups (preserve a stable order: date_histogram first, then terms, then histogram).+ let mut sources: Vec<Value> = Vec::new();+ let mut order: Vec<String> = Vec::new();+ if let Some(dh) = groups.get("date_histogram").and_then(|d| d.as_object()) {+ if let Some(field) = dh.get("field").and_then(|f| f.as_str()) {+ // Build a clean composite date_histogram source — only the keys the+ // composite parser understands (drop rollup-only keys like `delay`).+ let mut src = serde_json::Map::new();+ src.insert("field".to_string(), json!(field));+ for k in ["fixed_interval", "calendar_interval", "interval", "time_zone", "format"] {+ if let Some(v) = dh.get(k) {+ src.insert(k.to_string(), v.clone());+ }+ }+ sources.push(json!({ field: { "date_histogram": Value::Object(src) } }));+ order.push(field.to_string());+ }+ }+ if let Some(terms) = groups.get("terms").and_then(|t| t.get("fields")).and_then(|f| f.as_array()) {+ for f in terms {+ if let Some(field) = f.as_str() {+ sources.push(json!({ field: { "terms": { "field": field } } }));+ order.push(field.to_string());+ }+ }+ }+ if let Some(hist) = groups.get("histogram").and_then(|h| h.as_object()) {+ let interval = hist.get("interval").cloned().unwrap_or(json!(1));+ if let Some(hfields) = hist.get("fields").and_then(|f| f.as_array()) {+ for f in hfields {+ if let Some(field) = f.as_str() {+ sources.push(json!({ field: { "histogram": { "field": field, "interval": interval } } }));+ order.push(field.to_string());+ }+ }+ }+ }+ if sources.is_empty() {+ return Err("rollup job groups produced no composite sources".to_string());+ }++ // One sub-agg per (field, metric): name "<field>.<metric>".+ let mut sub_aggs = serde_json::Map::new();+ for m in &metrics {+ let field = match m.get("field").and_then(|f| f.as_str()) {+ Some(f) => f,+ None => continue,+ };+ if let Some(ms) = m.get("metrics").and_then(|x| x.as_array()) {+ for one in ms {+ if let Some(name) = one.as_str() {+ sub_aggs.insert(+ format!("{field}.{name}"),+ json!({ name: { "field": field } }),+ );+ }+ }+ }+ }++ // Resolve source indices (exclude the rollup_index itself).+ let all = state.engine.list_indices().await;+ let matches: Vec<String> = all+ .iter()+ .map(|i| i.name.clone())+ .filter(|n| n != &rollup_index && wildcard_match(&index_pattern, n))+ .collect();+ if matches.is_empty() {+ return Err(format!("no index matches pattern [{index_pattern}]"));+ }++ let dest_idx = state.engine.get_or_create_index(&rollup_index).map_err(|e| e.to_string())?;+ let mut written = 0usize;++ for source_index in &matches {+ let src_idx = match state.engine.get_index(source_index) {+ Ok(i) => i,+ Err(_) => continue,+ };+ let mut after: Option<Value> = None;+ loop {+ let mut composite = json!({ "size": 1000, "sources": sources });+ if let Some(ref a) = after {+ composite["after"] = a.clone();+ }+ let body = json!({+ "size": 0,+ "aggs": { "_rollup": { "composite": composite, "aggregations": Value::Object(sub_aggs.clone()) } }+ });+ let req = xerj_query::parse_request(&body).map_err(|e| e.to_string())?;+ let res = src_idx.search(&req).await.map_err(|e| e.to_string())?;+ let aggs = match res.aggs {+ Some(a) => a,+ None => break,+ };+ let rollup = match aggs.get("_rollup") {+ Some(r) => r,+ None => break,+ };+ let buckets = rollup.get("buckets").and_then(|b| b.as_array()).cloned().unwrap_or_default();+ if buckets.is_empty() {+ break;+ }+ for b in &buckets {+ let key = b.get("key").cloned().unwrap_or_else(|| json!({}));+ let mut doc = serde_json::Map::new();+ if let Some(ko) = key.as_object() {+ for (k, v) in ko {+ doc.insert(k.clone(), v.clone());+ }+ }+ if let Some(bo) = b.as_object() {+ flatten_bucket_metrics(&mut doc, bo);+ }+ doc.insert("doc_count".to_string(), b.get("doc_count").cloned().unwrap_or(json!(0)));+ doc.insert("_rollup.id".to_string(), json!(job_id));+ doc.insert("_rollup.source_index".to_string(), json!(source_index));+ let id = agg_key_doc_id(source_index, &key, &order);+ dest_idx+ .index_document(Some(id), Value::Object(doc))+ .await+ .map_err(|e| e.to_string())?;+ written += 1;+ }+ match rollup.get("after_key") {+ Some(ak) if !ak.is_null() => after = Some(ak.clone()),+ _ => break,+ }+ if buckets.len() < 1000 {+ break;+ }+ }+ }+ dest_idx.refresh().await.ok();+ Ok(written)}// ─────────────────────────────────────────────────────────────────────────────