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(replication): push a filtered subset of indices to an external ES-compatible target (#320)
xerj-org3b19c768d62c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b44006384..b0a748fcd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,7 +7,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]-_Nothing yet._+### Added++- **Push a filtered subset of indices to an external ES-compatible target —+ the single-node WAL tap** ([#320](https://github.com/xerj-org/xerj/issues/320)).+ Nothing pushed data out of the engine before this: `_ccr/*` answered `501`,+ reindex-from-remote was refused up front, and snapshot/restore — scheduled and+ whole-index — was the only export path. A XERJ node used as a lightweight edge+ collector had no way to stream a curated slice of its data up to a central+ cluster.+ - New `[wal_tap]` config section (9 settings, off by default) and a runtime+ REST surface: `GET`/`PUT /_xerj/wal_tap` and `GET /_xerj/wal_tap/_stats`.+ The allowlist is glob-based and adjustable without a restart.+ - The wire format is `_bulk` and nothing else, so the target can be+ Elasticsearch, OpenSearch, or another XERJ node with nothing installed.+ - **This is not CCR.** It is one-directional, single-node, and independent of+ the post-GA sharding/replication track. `_ccr/*` still answers `501`.+ - The tap adds nothing to the write path: it tails WAL files from disk on a+ timer and takes no lock the writer wants.+ - Delivery is at-least-once, with `version_type: external` carrying the WAL+ `seq_no` on every action so a redelivery converges on the same document the+ source holds.+ - WAL retention is deliberately *not* coupled to the tap — a slow remote must+ not be able to fill the local disk. A tap that falls far enough behind loses+ entries and says so: `gaps` in `_stats`, plus a warning per occurrence.+ - XERJ's own `.xerj*` system indices are never shipped, whatever the allowlist+ says, and a wildcard never expands to a hidden index.+ - There is no backfill. A new index is shipped whole; an established one ships+ from the moment it is allowlisted. Seed the target with snapshot/restore+ first if it needs the existing documents.## [1.0.0-rc.16] - 2026-08-13diff --git a/engine/Cargo.lock b/engine/Cargo.lockindex 809d3b005..39c26c8f1 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -6843,6 +6843,7 @@ dependencies = ["parking_lot","rayon","regex",+ "reqwest","rustc-hash","serde","serde_json",diff --git a/engine/README.md b/engine/README.mdindex d37c3d83c..7404ee2ff 100644--- a/engine/README.md+++ b/engine/README.md@@ -53,7 +53,7 @@ HTTP wire payloads, single-node, tmpfs data dir, both freshly started| Per-batch (5K) bulk p99 | **34.8 ms** | 80.3 ms | ES 2.3× || Data loss on restart | 0% | 0% | tied || GC pauses | 20–40 ms (JVM) | **0** (no GC) | **xerj** |-| Config surface | 3,000+ knobs | **105**, all optional | **xerj** |+| Config surface | 3,000+ knobs | **114**, all optional | **xerj** |xerj wins on every operational and read-path metric. ES still winsbulk-ingest throughput on warm Lucene `IndexWriter` (perf-backlog item@@ -86,7 +86,7 @@ The resulting binary is at `target/release/xerj`.## ConfigurationSee [`xerj.default.toml`](xerj.default.toml) for the commonly-tuned settings, and-[`crates/xerj-common/src/config.rs`](crates/xerj-common/src/config.rs) for all 105+[`crates/xerj-common/src/config.rs`](crates/xerj-common/src/config.rs) for all 114— every one of them optional.The minimal config to get started:diff --git a/engine/crates/xerj-api/src/lib.rs b/engine/crates/xerj-api/src/lib.rsindex 0e63816d3..a239b780e 100644--- a/engine/crates/xerj-api/src/lib.rs+++ b/engine/crates/xerj-api/src/lib.rs@@ -70,6 +70,7 @@ pub mod responses;pub mod router;pub mod state;pub mod stub;+pub mod wal_tap_api;// ── Convenience re-exports ────────────────────────────────────────────────────diff --git a/engine/crates/xerj-api/src/router.rs b/engine/crates/xerj-api/src/router.rsindex 4ddf827c1..94d979b73 100644--- a/engine/crates/xerj-api/src/router.rs+++ b/engine/crates/xerj-api/src/router.rs@@ -29,7 +29,7 @@ use xerj_common::config::CorsConfig;use crate::{auth::auth_middleware, authz, es_compat, graph_api, ism_api, memory_api, native,- state::AppState,+ state::AppState, wal_tap_api,};// ─────────────────────────────────────────────────────────────────────────────@@ -837,6 +837,15 @@ pub fn build_es_compat_router(state: AppState) -> Router {).route("/:index/_ccr/unfollow", post(es_compat::ccr_unfollow)).route("/:index/_ccr/info", get(es_compat::ccr_info))+ // ── WAL tap (issue #320) ───────────────────────────────────────────────────+ // Native surface, not an ES one: pushing this node's WAL to another+ // cluster has no Elasticsearch endpoint, and hanging it off `_ccr/*`+ // would make those honest 501s a lie.+ .route(+ "/_xerj/wal_tap",+ get(wal_tap_api::get_wal_tap).put(wal_tap_api::put_wal_tap),+ )+ .route("/_xerj/wal_tap/_stats", get(wal_tap_api::wal_tap_stats))// ── Legacy index templates (v1) ────────────────────────────────────────────.route("/_template/:name",diff --git a/engine/crates/xerj-api/src/wal_tap_api.rs b/engine/crates/xerj-api/src/wal_tap_api.rsnew file mode 100644index 000000000..82e3315a3--- /dev/null+++ b/engine/crates/xerj-api/src/wal_tap_api.rs@@ -0,0 +1,214 @@+//! REST surface for the single-node WAL tap (issue #320).+//!+//! ```text+//! GET /_xerj/wal_tap current configuration (never the credential)+//! PUT /_xerj/wal_tap merge-patch it, no restart+//! GET /_xerj/wal_tap/_stats per-index cursors, lag, counters, last error+//! ```+//!+//! This is a native (`_xerj`-namespaced) surface, not an Elasticsearch one:+//! there is no ES endpoint that means "push my WAL somewhere", and pretending+//! `_ccr/*` did would be exactly the silent-stub behaviour those handlers were+//! made to `501` to avoid.+//!+//! Everything here is cluster-scoped, so it authorises like any other+//! `/_*` route (`authz::classify` → `Target::Cluster`).++use axum::{+ extract::State,+ response::{IntoResponse, Response},+ Json,+};+use serde::Deserialize;+use serde_json::{json, Value};++use xerj_common::config::WalTapConfig;+use xerj_engine::wal_tap::WalTap;++use crate::{extract::OptionalJson, state::AppState};++/// The configuration as the API reports it.+///+/// `target_auth` is deliberately absent: it is a bearer credential for another+/// cluster, and an endpoint that reads it back turns "can call the admin API"+/// into "holds the target's credential". `target_auth_configured` is the+/// operator-visible part.+fn config_body(config: &WalTapConfig) -> Value {+ json!({+ "enabled": config.enabled,+ "target_url": config.target_url,+ "target_auth_configured": !config.target_auth.is_empty(),+ "indices": config.indices,+ "poll_interval_ms": config.poll_interval_ms,+ "max_batch_docs": config.max_batch_docs,+ "max_batch_bytes": config.max_batch_bytes,+ "request_timeout_secs": config.request_timeout_secs,+ "max_retry_backoff_secs": config.max_retry_backoff_secs,+ })+}++/// `GET /_xerj/wal_tap`+pub async fn get_wal_tap(State(state): State<AppState>) -> Response {+ Json(config_body(&state.engine.wal_tap.config())).into_response()+}++/// The mutable half. Every field optional — an absent field keeps its current+/// value, so an operator can flip `enabled` without restating the allowlist.+#[derive(Debug, Default, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct WalTapPatch {+ pub enabled: Option<bool>,+ pub target_url: Option<String>,+ /// Write-only. `""` clears the stored credential.+ pub target_auth: Option<String>,+ pub indices: Option<Vec<String>>,+ pub poll_interval_ms: Option<u64>,+ pub max_batch_docs: Option<usize>,+ pub max_batch_bytes: Option<usize>,+ pub request_timeout_secs: Option<u64>,+ pub max_retry_backoff_secs: Option<u64>,+}++fn bad_request(reason: &str) -> Response {+ (+ axum::http::StatusCode::BAD_REQUEST,+ Json(json!({+ "error": {"type": "illegal_argument_exception", "reason": reason},+ "status": 400,+ })),+ )+ .into_response()+}++/// `PUT /_xerj/wal_tap`+///+/// Takes effect on the next poll. Cursors are keyed by index name and are+/// untouched here, so adding an index to the allowlist starts it "from now"+/// while an index that was already running resumes exactly where it was —+/// removing and re-adding one does not re-ship what it already shipped.+pub async fn put_wal_tap(+ State(state): State<AppState>,+ OptionalJson(body): OptionalJson<WalTapPatch>,+) -> Response {+ let patch = body.unwrap_or_default();+ let mut config = state.engine.wal_tap.config();++ if let Some(v) = patch.enabled {+ config.enabled = v;+ }+ if let Some(v) = patch.target_url {+ let trimmed = v.trim().to_string();+ if !trimmed.is_empty()+ && !(trimmed.starts_with("http://") || trimmed.starts_with("https://"))+ {+ return bad_request(+ "wal_tap.target_url must be an absolute http:// or https:// URL, e.g. \+ \"https://central:9200\"",+ );+ }+ config.target_url = trimmed;+ }+ if let Some(v) = patch.target_auth {+ config.target_auth = v;+ }+ if let Some(v) = patch.indices {+ // A pattern that can only ever match system indices is a mistake worth+ // reporting rather than silently dropping: the tap refuses `.xerj-*`+ // unconditionally, so such a pattern would ship nothing forever and+ // look like a broken tap.+ if let Some(bad) = v.iter().find(|p| p.starts_with(".xerj")) {+ return bad_request(&format!(+ "wal_tap.indices pattern {bad:?} only matches system indices, which are \+ never shipped"+ ));+ }+ config.indices = v;+ }+ if let Some(v) = patch.poll_interval_ms {+ if !(50..=60_000).contains(&v) {+ return bad_request("wal_tap.poll_interval_ms must be between 50 and 60000");+ }+ config.poll_interval_ms = v;+ }+ if let Some(v) = patch.max_batch_docs {+ if v == 0 {+ return bad_request("wal_tap.max_batch_docs must be at least 1");+ }+ config.max_batch_docs = v;+ }+ if let Some(v) = patch.max_batch_bytes {+ if v == 0 {+ return bad_request("wal_tap.max_batch_bytes must be at least 1");+ }+ config.max_batch_bytes = v;+ }+ if let Some(v) = patch.request_timeout_secs {+ if v == 0 {+ return bad_request("wal_tap.request_timeout_secs must be at least 1");+ }+ config.request_timeout_secs = v;+ }+ if let Some(v) = patch.max_retry_backoff_secs {+ if v == 0 {+ return bad_request("wal_tap.max_retry_backoff_secs must be at least 1");+ }+ config.max_retry_backoff_secs = v;+ }++ if config.enabled && config.target_url.is_empty() {+ return bad_request("wal_tap.enabled requires a target_url");+ }++ let body = config_body(&config);+ state.engine.wal_tap.set_config(config);+ Json(json!({"acknowledged": true, "wal_tap": body})).into_response()+}++/// `GET /_xerj/wal_tap/_stats`+///+/// The honesty surface. `gaps > 0` means entries were pruned out of the WAL+/// before the tap could ship them and are gone; `lag_seq` is how far behind+/// the index's own sequence counter the tap is; `last_error` is why it stopped+/// advancing.+pub async fn wal_tap_stats(State(state): State<AppState>) -> Response {+ let tap = &state.engine.wal_tap;+ let config = tap.config();+ let stats = tap.stats();+ let cursors = tap.cursors();++ let mut indices = serde_json::Map::new();+ for name in state.engine.index_name_list() {+ if !WalTap::ships(&config, &name) {+ continue;+ }+ let stat = stats.get(&name).cloned().unwrap_or_default();+ // `current_seq_no` is the NEXT seq to be handed out, so the highest+ // reserved one is that minus 1.+ let head = state+ .engine+ .get_index(&name)+ .map(|i| i.current_seq_no().saturating_sub(1))+ .unwrap_or(0);+ let mut body = serde_json::to_value(&stat).unwrap_or_else(|_| json!({}));+ if let Some(obj) = body.as_object_mut() {+ obj.insert(+ "lag_seq".into(),+ json!(head.saturating_sub(stat.last_shipped_seq)),+ );+ obj.insert(+ "cursors".into(),+ serde_json::to_value(cursors.get(&name).cloned().unwrap_or_default())+ .unwrap_or_else(|_| json!({})),+ );+ }+ indices.insert(name, body);+ }++ Json(json!({+ "enabled": config.enabled,+ "target_url": config.target_url,+ "ticks": tap.ticks(),+ "indices": indices,+ }))+ .into_response()+}diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rsindex 3c49c6b34..e4d68ebbd 100644--- a/engine/crates/xerj-common/src/config.rs+++ b/engine/crates/xerj-common/src/config.rs@@ -1,6 +1,6 @@//! xerj configuration system.//!-//! Configuration is intentionally minimal: **105 settings** versus+//! Configuration is intentionally minimal: **114 settings** versus//! Elasticsearch's 3000+. Every option is named, documented, and has a sensible//! production-ready default. The format is TOML, loaded from a single file.//!@@ -92,9 +92,12 @@ pub struct Config {pub compat: CompatConfig,/// ISM/ILM index-lifecycle-management background execution — 1 setting.pub lifecycle: LifecycleConfig,+ /// Single-node WAL tap: push a filtered index subset to an external+ /// ES-compatible target — 9 settings. Off by default.+ pub wal_tap: WalTapConfig,}-// 20 sub-configs, 105 leaf settings in total. Do not maintain that sum by hand+// 21 sub-configs, 114 leaf settings in total. Do not maintain that sum by hand// — `journey_zero_config` in xerj-engine/tests/product_experience.rs counts a// serialised `Config::default()` and fails if this comment and the module// header stop matching. `Default` is derived: every field is a sub-config that@@ -1737,6 +1740,80 @@ impl Default for LifecycleConfig {// ─────────────────────────────────────────────────────────────────────────────+/// Single-node WAL tap — push a filtered subset of indices to an external+/// ES-compatible target (issue #320). **9 settings.**+///+/// This is deliberately *not* cross-cluster replication. It is one+/// directional, single node, and target-agnostic because the wire format is+/// just `_bulk`: an Elasticsearch cluster, an OpenSearch cluster, or another+/// xerj node all work.+///+/// Semantics that matter before you turn it on:+///+/// - **No backfill.** An index whose WAL has never been pruned (a new one) is+/// shipped whole. An index that has been running long enough to prune+/// starts from the moment it is allowlisted: it ships what happens next,+/// not what is already in segments. Use snapshot/restore to seed the target+/// first if you need the existing data.+/// - **At-least-once.** A batch is re-sent if the cursor could not be+/// advanced, so the target may see a document twice. `doc_id` is the+/// `_bulk` `_id` and each action carries `version_type: external` with the+/// entry's `seq_no`, so a redelivery (and an out-of-order one) is a no-op+/// on any target that honours external versioning.+/// - **Retention never waits for the target.** WAL generations are pruned as+/// soon as their entries are durable in a segment, whether or not the tap+/// has shipped them — coupling the two would let a slow remote fill the+/// local disk. A tap that falls that far behind loses entries and *says+/// so*: `gaps` in `GET /_xerj/wal_tap/_stats`, plus a warning per gap.+/// - **System indices are never shipped**, whatever the allowlist says.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(default, deny_unknown_fields)]+pub struct WalTapConfig {+ /// Master switch (default: `false` — off).+ pub enabled: bool,+ /// Base URL of the target cluster, e.g. `"https://central:9200"`. The+ /// tap POSTs to `{target_url}/_bulk`. Empty disables the tap even when+ /// `enabled = true`.+ pub target_url: String,+ /// Verbatim `Authorization` header value for the target, e.g.+ /// `"ApiKey abc123"` or `"Basic dXNlcjpwdw=="`. Empty sends none.+ /// Never echoed back by the REST surface.+ pub target_auth: String,+ /// Index allowlist. Glob patterns (`*` only, as in `_cat` expressions);+ /// empty ships nothing. `["*"]` ships every non-system index.+ pub indices: Vec<String>,+ /// How often each index's WAL is polled, in milliseconds (default:+ /// `500`). This is the floor on end-to-end latency.+ pub poll_interval_ms: u64,+ /// Maximum WAL entries in one `_bulk` request (default: `1000`).+ pub max_batch_docs: usize,+ /// Maximum `_bulk` body size in bytes (default: 5 MiB). A single+ /// document larger than this is still sent, alone.+ pub max_batch_bytes: usize,+ /// Per-request timeout against the target, in seconds (default: `30`).+ pub request_timeout_secs: u64,+ /// Ceiling on the exponential retry backoff, in seconds (default: `60`).+ pub max_retry_backoff_secs: u64,+}++impl Default for WalTapConfig {+ fn default() -> Self {+ Self {+ enabled: false,+ target_url: String::new(),+ target_auth: String::new(),+ indices: Vec::new(),+ poll_interval_ms: 500,+ max_batch_docs: 1000,+ max_batch_bytes: 5 * 1024 * 1024,+ request_timeout_secs: 30,+ max_retry_backoff_secs: 60,+ }+ }+}++// ─────────────────────────────────────────────────────────────────────────────+/// Scroll + async-search context lifecycle settings (RC4 blocker 11).////// **7 settings.**@@ -2445,6 +2522,7 @@ mod tests {("logging", 2),("compat", 2),("lifecycle", 1),+ ("wal_tap", 9),];/// Count the settings by *counting them*.@@ -2487,7 +2565,7 @@ mod tests {"the section table must sum to the whole config");assert_eq!(- total, 105,+ total, 114,"the total settings count changed. It is quoted in this module's \header, in xerj-common/src/lib.rs, in engine/README.md, in \xerj.default.toml and in EXPECTED_SETTINGS in \diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rsindex 0e2a5d523..836cc8498 100644--- a/engine/crates/xerj-common/src/lib.rs+++ b/engine/crates/xerj-common/src/lib.rs@@ -7,13 +7,13 @@//! ## Design philosophy//!//! Unlike Elasticsearch's 3000+ configuration knobs, xerj deliberately exposes-//! **105 settings**, each meaningful and production-tested. Every default+//! **114 settings**, each meaningful and production-tested. Every default//! is chosen so that a fresh deployment with zero configuration changes performs//! well for the majority of workloads.//!//! ## Modules//!-//! - [`config`] — TOML-based configuration (105 settings)+//! - [`config`] — TOML-based configuration (114 settings)//! - [`feedback`] — the bug/UX-report invitation shared by every `--help`//! - [`error`] — Unified error type ([`XerjError`])//! - [`types`] — Core domain types (documents, fields, IDs)diff --git a/engine/crates/xerj-engine/Cargo.toml b/engine/crates/xerj-engine/Cargo.tomlindex 9a3e205e2..826245fe7 100644--- a/engine/crates/xerj-engine/Cargo.toml+++ b/engine/crates/xerj-engine/Cargo.toml@@ -29,6 +29,9 @@ anyhow = { workspace = true }dashmap = { workspace = true }arc-swap = { workspace = true }parking_lot = "0.12"+# WAL tap (#320): the outbound `_bulk` sender. Already in the tree via+# xerj-ai, so this adds no new external dependency.+reqwest = { workspace = true }rayon = { workspace = true }libc = "0.2"uuid = { workspace = true }diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex e81f6e742..33e4511cb 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -527,6 +527,12 @@ pub struct Engine {pub rollup_jobs: Arc<DashMap<String, Value>>,/// CCR auto-follow pattern name → pattern JSONpub ccr_auto_follow: Arc<DashMap<String, Value>>,+ /// Single-node WAL tap (issue #320): live config, durable cursors and+ /// counters for the one-directional push of allowlisted indices to an+ /// external ES-compatible target. Always present; inert until+ /// `wal_tap.enabled` and a target URL are set. Not CCR — see+ /// [`crate::wal_tap`] for why the two are different features.+ pub wal_tap: Arc<crate::wal_tap::WalTap>,/// API key id → record. Populated by `POST /_security/api_key` so the/// auth middleware can re-authenticate `Authorization: ApiKey <encoded>`./// In-memory only (lost on restart).@@ -688,6 +694,11 @@ impl Engine {} = crate::cluster_state::preflight(&data_dir);let storage_available = cluster_state_status.is_writable();+ // Cloned before `config` is moved into the Arc below — the WAL tap+ // owns a live, runtime-editable copy (PUT /_xerj/wal_tap) rather than+ // reading the frozen boot config.+ let wal_tap_config = config.wal_tap.clone();+// Apply operator-tunable aggregation bucket cap. Stored in a static// AtomicUsize inside aggs.rs so all per-bucket-allocator hot loops// can read it with no plumbing through every agg signature.@@ -741,6 +752,7 @@ impl Engine {frozen_indices: Arc::new(DashMap::new()),rollup_jobs: Arc::new(DashMap::new()),ccr_auto_follow: Arc::new(DashMap::new()),+ wal_tap: Arc::new(crate::wal_tap::WalTap::new(&data_dir, wal_tap_config)),api_keys: Arc::new(DashMap::new()),application_privileges: Arc::new(DashMap::new()),legacy_templates: Arc::new(DashMap::new()),@@ -3762,7 +3774,7 @@ fn copy_dir_recursive(}/// Simple glob pattern matching (supports `*` and `?`).-fn glob_match(pattern: &str, text: &str) -> bool {+pub(crate) fn glob_match(pattern: &str, text: &str) -> bool {let pat: Vec<char> = pattern.chars().collect();let txt: Vec<char> = text.chars().collect();let (m, n) = (pat.len(), txt.len());diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 1936e2435..ff69297bc 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -18479,6 +18479,17 @@ impl Index {&self.data_dir}+ /// Root of this index's write-ahead log — the directory holding either+ /// `*.wal` files (legacy single-WAL layout) or `s0`, `s1`, … shard+ /// subdirectories.+ ///+ /// Read-only consumers live here: the WAL tap (`crate::wal_tap`) tails+ /// these files on a timer so it never has to take a lock the write path+ /// wants.+ pub fn wal_dir(&self) -> PathBuf {+ self.store.wal_dir()+ }+// ── Delete index ──────────────────────────────────────────────────────────/// Remove all data files for this index.diff --git a/engine/crates/xerj-engine/src/lib.rs b/engine/crates/xerj-engine/src/lib.rsindex 05f01711a..61a80b1ad 100644--- a/engine/crates/xerj-engine/src/lib.rs+++ b/engine/crates/xerj-engine/src/lib.rs@@ -38,6 +38,7 @@ pub mod segment_cache_estimates;pub mod slow_query;pub mod sql;pub mod turbo_ingest;+pub mod wal_tap;mod write_publication;#[cfg(test)]diff --git a/engine/crates/xerj-engine/src/wal_tap.rs b/engine/crates/xerj-engine/src/wal_tap.rsnew file mode 100644index 000000000..a400148d3--- /dev/null+++ b/engine/crates/xerj-engine/src/wal_tap.rs@@ -0,0 +1,941 @@+//! Single-node WAL tap — push a filtered subset of indices to an external+//! ES-compatible target (issue #320).+//!+//! ## What this is+//!+//! A background loop that tails each allowlisted index's write-ahead log and+//! replays the entries it finds into `{target}/_bulk`. The target can be an+//! Elasticsearch cluster, an OpenSearch cluster, or another xerj node — the+//! wire format is `_bulk` and nothing else, so there is nothing to install on+//! the far side.+//!+//! ## What this is not+//!+//! It is not cross-cluster replication. Nothing flows back, there is no+//! follower state machine, no leader election, no retention leases, and it+//! does not depend on the post-GA multi-node track. `_ccr/*` still answers+//! `501`, honestly, because none of that exists.+//!+//! ## The four decisions+//!+//! **1. Where it hooks.** Nowhere on the write path. The tap reads WAL files+//! from disk on a timer; it takes no lock the writer wants and adds not one+//! instruction to `append` / `append_index_raw_batch`. That is affordable+//! because every append already drains its `BufWriter` to the page cache+//! (`WalWriter::write_one_frame_inner`), so a reader in the same process sees+//! whole frames the moment they are acked. The price is that end-to-end+//! latency has `poll_interval_ms` as its floor.+//!+//! **2. Ordering and dedup.** The cursor is a **byte offset**, never a+//! sequence number: the lock-free writer reserves seq_nos outside the shard+//! mutex, so a file can hold frames out of seq order and a seq-filtered resume+//! would skip entries (see [`xerj_storage::wal::WalTailCursor`]). Delivery is+//! at-least-once — a batch that could not be confirmed is re-sent from the+//! un-advanced cursor. Every action carries `_id = doc_id` plus+//! `version_type: external` with the entry's `seq_no`, which is the same+//! "highest seq wins" rule this engine's own version map uses+//! (`VersionMap::set_if_latest`), so a redelivery or an out-of-order delivery+//! resolves to the same document the source holds. A target that ignores+//! external versioning — which currently includes xerj's own `_bulk` — falls+//! back to last-write-wins by arrival instead.+//!+//! **3. Backpressure.** Bounded by construction: one in-flight request per+//! index, batches capped by `max_batch_docs` and `max_batch_bytes`, and+//! nothing buffered between polls. When the target is down the cursor simply+//! does not advance and the retry backs off exponentially (capped, jittered)+//! — memory does not grow, and neither does anything else on this node.+//!+//! **4a. Where a tap starts.** At the beginning of an index's WAL when+//! nothing in it has ever been pruned (generation 0 still on disk) — so an+//! index created while the tap is running is shipped whole, first document+//! included. On an index that has been running long enough to prune, at the+//! end: the surviving generations are an arbitrary recent slice, and shipping+//! them would look like a backfill without being one. **There is no backfill.**+//! Seed the target with snapshot/restore if it needs the existing documents.+//!+//! **4b. What falling behind costs.** WAL retention is *not* coupled to the+//! tap, deliberately: `prune_verified` deletes a rotated generation as soon as+//! its entries are durable in a segment, and making that wait on a remote+//! target is how a slow consumer turns into a disk-full incident. So a tap+//! that falls far enough behind loses entries — and always finds out. The+//! cursor carries the generation it sits in, a pruned-out-from-under-us+//! generation is detected exactly ([`WalShardTail::gap`]), and each occurrence+//! logs at `warn` and increments `gaps` in `GET /_xerj/wal_tap/_stats`. The+//! degradation is visible, not silent.+//!+//! Prior art consulted before writing this (per the repository's+//! reference-coding mandate):+//!+//! - **quickwit** `quickwit-metastore/src/checkpoint.rs:170` (`SourceCheckpoint`)+//! and `:280-345` (`check_compatibility` / `try_apply_delta`), Apache-2.0.+//! Its model is one position per partition, a delta that moves *backwards*+//! is refused, and a delta that leaves a *hole* is accepted with a warning+//! because "gaps may happen … if the indexing pipeline is down for more than+//! the retention period". That is the same shape adopted here: one cursor+//! per WAL shard, and a pruned generation surfaces as a counted, logged gap+//! rather than either a stall or silence. Adapted, not copied.+//! - **elasticsearch** `x-pack/plugin/ccr/.../ShardFollowNodeTask.java:270-330`+//! and `:586-640` — **approach only, AGPL/SSPL/Elastic-2.0, no code taken.**+//! Confirms the two primitives: an explicitly bounded write buffer (count+//! *and* bytes) as the whole of backpressure, and capped exponential backoff+//! with jitter separating retryable transport failures from fatal ones.++use std::collections::BTreeMap;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Arc;+use std::time::Duration;++use parking_lot::RwLock;+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use tracing::{debug, info, warn};++use xerj_common::config::WalTapConfig;+use xerj_common::types::is_reserved_index;+use xerj_storage::wal::{tail_shard, wal_shard_dirs, WalEntry, WalTailCursor};++use crate::engine::Engine;++/// Filename of the durable cursor state, under the engine data directory.+const STATE_FILE: &str = "wal_tap_state.json";++/// Prefix of every index xerj creates for itself.+///+/// Broader than [`is_reserved_index`] on purpose. That predicate's constant is+/// `.xerj-memory-` (the brain namespace, which the authz layer guards); the+/// console bootstraps `.xerj_users`, `.xerj_api_tokens`, `.xerj_sessions`,+/// `.xerj_magic_links` and friends, which hold hashed credentials and live+/// sessions. Nothing under either shape may leave this node.+const XERJ_SYSTEM_INDEX_PREFIX: &str = ".xerj";++/// Is `index` one of xerj's own?+fn is_xerj_system_index(index: &str) -> bool {+ index.starts_with(XERJ_SYSTEM_INDEX_PREFIX) || is_reserved_index(index)+}++/// Persisted format version. Bump on any incompatible change to+/// [`PersistedState`]; an unrecognised version is refused rather than+/// reinterpreted, because misreading a cursor means silently re-shipping or+/// silently skipping.+const STATE_VERSION: u32 = 1;++// ─────────────────────────────────────────────────────────────────────────────+// Durable cursor state+// ─────────────────────────────────────────────────────────────────────────────++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+struct IndexCursors {+ /// WAL shard name (`"s0"`, or `""` for the legacy single-WAL layout) →+ /// position.+ shards: BTreeMap<String, WalTailCursor>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+struct PersistedState {+ version: u32,+ indices: BTreeMap<String, IndexCursors>,+}++impl Default for PersistedState {+ fn default() -> Self {+ Self {+ version: STATE_VERSION,+ indices: BTreeMap::new(),+ }+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// Stats+// ─────────────────────────────────────────────────────────────────────────────++/// Per-index counters, all monotonic within a process lifetime.+#[derive(Debug, Clone, Default, Serialize)]+pub struct IndexTapStats {+ /// `index` actions accepted into a `_bulk` body.+ pub docs_shipped: u64,+ /// `delete` actions accepted into a `_bulk` body.+ pub deletes_shipped: u64,+ /// `_bulk` requests the target answered 2xx to.+ pub batches_sent: u64,+ /// Requests that failed outright (transport error or non-2xx). The cursor+ /// does not advance for these — they are retried.+ pub bulk_failures: u64,+ /// Items the target rejected inside an otherwise-successful `_bulk`+ /// response. The cursor DOES advance past these; see [`WalTap::send_bulk`].+ pub item_failures: u64,+ /// Version conflicts inside a `_bulk` response. Expected and benign: they+ /// are how external versioning absorbs a redelivery. Counted separately so+ /// they never look like data loss.+ pub version_conflicts: u64,+ /// Times a WAL generation was pruned before the tap read it. Each one is+ /// unrecoverable data loss for the target.+ pub gaps: u64,+ /// `UpdateMapping` WAL entries seen. No current xerj code path writes one+ /// (only read sites exist), so this is expected to stay 0; if it ever+ /// moves, the target's dynamic mapping is what handled the change.+ pub mapping_updates_skipped: u64,+ /// Frames skipped because their payload did not decode.+ pub corrupt_skipped: u64,+ /// Consecutive failed sends; drives the backoff.+ pub consecutive_failures: u32,+ /// Last failure, as a short string. `None` once a send succeeds.+ pub last_error: Option<String>,+ /// Highest `seq_no` shipped so far, for the lag estimate.+ pub last_shipped_seq: u64,+}++// ─────────────────────────────────────────────────────────────────────────────+// The tap+// ─────────────────────────────────────────────────────────────────────────────++/// Shared, runtime-mutable tap state. Held by the [`Engine`] so the REST+/// surface can read stats and edit the allowlist without a restart.+pub struct WalTap {+ config: RwLock<WalTapConfig>,+ state: RwLock<PersistedState>,+ stats: RwLock<BTreeMap<String, IndexTapStats>>,+ state_path: PathBuf,+ client: reqwest::Client,+ /// Monotonic tick counter, so tests can observe that the loop ran.+ ticks: AtomicU64,+ /// Milliseconds-since-start before which the next send must not be tried.+ retry_not_before_ms: AtomicU64,+ started: std::time::Instant,+}++impl WalTap {+ /// Build a tap and load any persisted cursors from `data_dir`.+ ///+ /// A state file that cannot be parsed is refused loudly and treated as+ /// absent — which means every allowlisted index restarts "from now"+ /// instead of re-shipping from a position that may be nonsense.+ pub fn new(data_dir: &Path, config: WalTapConfig) -> Self {+ let state_path = data_dir.join(STATE_FILE);+ let state = match std::fs::read(&state_path) {+ Ok(bytes) => match serde_json::from_slice::<PersistedState>(&bytes) {+ Ok(s) if s.version == STATE_VERSION => s,+ Ok(s) => {+ warn!(+ found = s.version,+ expected = STATE_VERSION,+ "WAL tap state file has an unknown version — starting from now"+ );+ PersistedState::default()+ }+ Err(e) => {+ warn!(error = %e, path = ?state_path,+ "WAL tap state file is unreadable — starting from now");+ PersistedState::default()+ }+ },+ Err(_) => PersistedState::default(),+ };++ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(config.request_timeout_secs.max(1)))+ .build()+ .unwrap_or_default();++ Self {+ config: RwLock::new(config),+ state: RwLock::new(state),+ stats: RwLock::new(BTreeMap::new()),+ state_path,+ client,+ ticks: AtomicU64::new(0),+ retry_not_before_ms: AtomicU64::new(0),+ started: std::time::Instant::now(),+ }+ }++ /// Snapshot of the live configuration.+ pub fn config(&self) -> WalTapConfig {+ self.config.read().clone()+ }++ /// Replace the live configuration. Takes effect on the next poll; no+ /// restart, and cursors are preserved so an index that stays in the+ /// allowlist does not re-ship or skip.+ pub fn set_config(&self, config: WalTapConfig) {+ *self.config.write() = config;+ }++ /// Number of completed poll cycles — the "it is actually running" signal+ /// for tests and for `_stats`.+ pub fn ticks(&self) -> u64 {+ self.ticks.load(Ordering::Relaxed)+ }++ /// Per-index counters.+ pub fn stats(&self) -> BTreeMap<String, IndexTapStats> {+ self.stats.read().clone()+ }++ /// Per-index, per-shard cursors, for `_stats`.+ pub fn cursors(&self) -> BTreeMap<String, BTreeMap<String, WalTailCursor>> {+ self.state+ .read()+ .indices+ .iter()+ .map(|(k, v)| (k.clone(), v.shards.clone()))+ .collect()+ }++ /// Does `index` match the allowlist, and is it allowed to be shipped at+ /// all?+ ///+ /// Two rules sit above the patterns:+ ///+ /// 1. **xerj's own system indices are never shipped**, whatever the+ /// allowlist says. That means every `.xerj*` name, not just the+ /// [`is_reserved_index`] namespace: that constant is `.xerj-memory-`,+ /// which covers the brain indices but not `.xerj_users`,+ /// `.xerj_api_tokens` or `.xerj_sessions` — where hashed credentials,+ /// tokens and console sessions live. An `indices = ["*"]` tap that+ /// shipped those to another cluster would be a credential leak, and it+ /// is what the regression test+ /// `system_indices_are_never_pushed_even_with_a_star_allowlist` exists+ /// to catch.+ /// 2. **A wildcard does not expand to a hidden index.** `["*"]` means+ /// "every ordinary index", not "also `.kibana`" — the same rule+ /// Elasticsearch's `expand_wildcards` uses, where a pattern reaches a+ /// dotted index only when the pattern is itself dotted. Naming one+ /// outright (`indices = [".kibana"]`) still works.+ pub fn ships(config: &WalTapConfig, index: &str) -> bool {+ if is_xerj_system_index(index) {+ return false;+ }+ config.indices.iter().any(|pat| {+ if index.starts_with('.') && !pat.starts_with('.') {+ return false;+ }+ crate::engine::glob_match(pat, index)+ })+ }++ fn stat<R>(&self, index: &str, f: impl FnOnce(&mut IndexTapStats) -> R) -> R {+ let mut guard = self.stats.write();+ f(guard.entry(index.to_string()).or_default())+ }++ fn persist(&self) {+ let snapshot = self.state.read().clone();+ let bytes = match serde_json::to_vec_pretty(&snapshot) {+ Ok(b) => b,+ Err(e) => {+ warn!(error = %e, "WAL tap: cannot serialise cursor state");+ return;+ }+ };+ // Durable replace: a torn cursor file is a silent re-ship or a silent+ // skip on the next boot, which is exactly the class of bug this+ // feature must not introduce.+ if let Err(e) = xerj_common::fsio::write_file_durable(&self.state_path, &bytes) {+ warn!(error = %e, path = ?self.state_path, "WAL tap: cannot persist cursor state");+ }+ }++ fn now_ms(&self) -> u64 {+ self.started.elapsed().as_millis() as u64+ }++ fn in_backoff(&self) -> bool {+ self.now_ms() < self.retry_not_before_ms.load(Ordering::Relaxed)+ }++ /// Capped exponential backoff with jitter, keyed off the worst+ /// consecutive-failure count across indices.+ ///+ /// Approach (not code) from Elasticsearch's `ShardFollowNodeTask.computeDelay`.+ fn arm_backoff(&self, config: &WalTapConfig, failures: u32) {+ let base = config.poll_interval_ms.max(50);+ let shift = failures.saturating_sub(1).min(20);+ let uncapped = base.saturating_mul(1u64 << shift);+ let cap = config.max_retry_backoff_secs.max(1) * 1000;+ let delay = uncapped.min(cap);+ // Deterministic, dependency-free jitter in [50%, 100%] of the delay:+ // enough to stop N indices from re-hammering a recovering target in+ // lockstep, without pulling in an RNG.+ let jitter = self.now_ms() % 50 + 50;+ let delay = delay * jitter / 100;+ self.retry_not_before_ms+ .store(self.now_ms() + delay, Ordering::Relaxed);+ }++ fn clear_backoff(&self) {+ self.retry_not_before_ms.store(0, Ordering::Relaxed);+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// Bulk payload+// ─────────────────────────────────────────────────────────────────────────────++/// One WAL entry rendered as its two (or one) `_bulk` NDJSON lines.+///+/// `version_type: external` with the WAL `seq_no` as the version is what makes+/// at-least-once safe: the target keeps the highest-seq version of each+/// `_id`, which is the same winner [`xerj_storage::version_map::VersionMap`]+/// picks locally.+fn render_action(index: &str, seq_no: u64, entry: &WalEntry, out: &mut String) -> Option<bool> {+ match entry {+ WalEntry::Index { doc_id, source } => {+ let meta = json!({"index": {+ "_index": index,+ "_id": doc_id,+ "version": seq_no,+ "version_type": "external",+ }});+ out.push_str(&meta.to_string());+ out.push('\n');+ out.push_str(&compact_source(source));+ out.push('\n');+ Some(false)+ }+ WalEntry::Delete { doc_id } => {+ let meta = json!({"delete": {+ "_index": index,+ "_id": doc_id,+ "version": seq_no,+ "version_type": "external",+ }});+ out.push_str(&meta.to_string());+ out.push('\n');+ Some(true)+ }+ // Never written by any current code path (grep: only read sites+ // exist). If one ever appears, the target's dynamic mapping is what+ // absorbs the change — forwarding xerj's internal schema would mean+ // translating it into an ES mapping, a second translation surface with+ // its own failure modes, for an entry that does not occur.+ WalEntry::UpdateMapping { .. } => None,+ }+}++/// A document source as one NDJSON line. A WAL source is always a JSON value+/// with no interior newlines once re-serialised compactly, which is what+/// `_bulk` requires.+fn compact_source(source: &Value) -> String {+ source.to_string()+}++/// One `_bulk` request's worth of rendered actions.+struct Chunk {+ body: String,+ docs: u64,+ deletes: u64,+ max_seq: u64,+}++/// Split a batch into `_bulk` bodies no larger than `max_bytes`.+///+/// A single action larger than `max_bytes` gets a chunk of its own rather than+/// being dropped: the cap is there to respect the target's+/// `http.max_content_length`, and silently discarding an oversized document+/// would be data loss dressed up as a limit.+fn render_chunks(index: &str, batch: &[(u64, WalEntry)], max_bytes: usize) -> Vec<Chunk> {+ let max_bytes = max_bytes.max(1);+ let mut chunks: Vec<Chunk> = Vec::new();+ let mut cur = Chunk {+ body: String::new(),+ docs: 0,+ deletes: 0,+ max_seq: 0,+ };++ for (seq, entry) in batch {+ let mut rendered = String::new();+ let Some(is_delete) = render_action(index, *seq, entry, &mut rendered) else {+ continue;+ };+ if !cur.body.is_empty() && cur.body.len() + rendered.len() > max_bytes {+ chunks.push(std::mem::replace(+ &mut cur,+ Chunk {+ body: String::new(),+ docs: 0,+ deletes: 0,+ max_seq: 0,+ },+ ));+ }+ cur.body.push_str(&rendered);+ if is_delete {+ cur.deletes += 1;+ } else {+ cur.docs += 1;+ }+ cur.max_seq = cur.max_seq.max(*seq);+ }+ if !cur.body.is_empty() {+ chunks.push(cur);+ }+ chunks+}++// ─────────────────────────────────────────────────────────────────────────────+// The poll loop+// ─────────────────────────────────────────────────────────────────────────────++/// Outcome of shipping one `_bulk` request.+enum SendOutcome {+ /// The target accepted the request. Per-item failures may still have+ /// occurred; the cursor advances either way.+ Accepted {+ item_failures: u64,+ version_conflicts: u64,+ },+ /// The request did not land. The cursor must not advance.+ Failed(String),+}++impl WalTap {+ /// POST one NDJSON body to `{target}/_bulk`.+ ///+ /// Whole-request failures (transport error, any non-2xx) leave the cursor+ /// where it is, so nothing is dropped and the batch is retried. Per-item+ /// failures inside a 2xx response are counted, logged, and *passed over*:+ /// a document the target will reject deterministically — a mapping+ /// conflict, say — would otherwise wedge the tap forever, and a wedged tap+ /// loses everything behind it to WAL pruning rather than just the one bad+ /// document. That trade is deliberate and is why `item_failures` is in+ /// `_stats`.+ async fn send_bulk(&self, config: &WalTapConfig, body: String) -> SendOutcome {+ let url = format!("{}/_bulk", config.target_url.trim_end_matches('/'));+ let mut req = self+ .client+ .post(&url)+ .header("Content-Type", "application/x-ndjson")+ .timeout(Duration::from_secs(config.request_timeout_secs.max(1)))+ .body(body);+ if !config.target_auth.is_empty() {+ req = req.header("Authorization", config.target_auth.clone());+ }++ let resp = match req.send().await {+ Ok(r) => r,+ Err(e) => return SendOutcome::Failed(format!("transport: {e}")),+ };+ let status = resp.status();+ if !status.is_success() {+ let snippet = resp+ .text()+ .await+ .unwrap_or_default()+ .chars()+ .take(300)+ .collect::<String>();+ return SendOutcome::Failed(format!("HTTP {status}: {snippet}"));+ }++ let parsed: Value = match resp.json().await {+ Ok(v) => v,+ // A 2xx the target could not describe. Treat as landed — resending+ // would double-deliver for no new information.+ Err(e) => {+ debug!(error = %e, "WAL tap: unparseable _bulk response body");+ return SendOutcome::Accepted {+ item_failures: 0,+ version_conflicts: 0,+ };+ }+ };++ let mut item_failures = 0u64;+ let mut version_conflicts = 0u64;+ if parsed.get("errors").and_then(Value::as_bool) == Some(true) {+ for item in parsed+ .get("items")+ .and_then(Value::as_array)+ .map(Vec::as_slice)+ .unwrap_or_default()+ {+ let Some(action) = item.as_object().and_then(|o| o.values().next()) else {+ continue;+ };+ let Some(error) = action.get("error") else {+ continue;+ };+ let kind = error.get("type").and_then(Value::as_str).unwrap_or("");+ if kind == "version_conflict_engine_exception" {+ version_conflicts += 1;+ } else {+ if item_failures == 0 {+ warn!(error = %error, "WAL tap: target rejected a document — \+ skipped (see item_failures in _stats)");+ }+ item_failures += 1;+ }+ }+ }+ SendOutcome::Accepted {+ item_failures,+ version_conflicts,+ }+ }++ /// Poll one index once: read its WAL tail, ship it, advance its cursors.+ ///+ /// Returns `true` when there is more to read immediately (the batch was+ /// truncated), so the caller can keep going without waiting a full poll+ /// interval.+ async fn poll_index(&self, config: &WalTapConfig, name: &str, wal_root: PathBuf) -> bool {+ let known: BTreeMap<String, WalTailCursor> = self+ .state+ .read()+ .indices+ .get(name)+ .map(|c| c.shards.clone())+ .unwrap_or_default();++ let budget = config.max_batch_docs.max(1);+ let read = {+ let known = known.clone();+ // WAL reads are blocking file I/O; keep them off the async+ // runtime's worker threads.+ match tokio::task::spawn_blocking(move || {+ let mut shards = Vec::new();+ for (shard, dir) in wal_shard_dirs(&wal_root) {+ let cursor = known.get(&shard).copied();+ let tail = tail_shard(&dir, cursor, budget);+ shards.push((shard, tail));+ }+ shards+ })+ .await+ {+ Ok(v) => v,+ Err(e) => {+ warn!(index = %name, error = %e, "WAL tap: WAL read task failed");+ return false;+ }+ }+ };++ // Merge the shard streams. Every entry read this poll is shipped:+ // the per-shard cursors advance together with the one request, so a+ // partial-batch horizon is unnecessary — each shard either ships all+ // of what it read or none of it.+ let mut batch: Vec<(u64, WalEntry)> = Vec::new();+ let mut new_cursors: BTreeMap<String, WalTailCursor> = known.clone();+ let mut more = false;+ let mut gaps = 0u64;+ let mut corrupt = 0u64;+ let mut mapping_updates = 0u64;++ for (shard, tail) in read {+ if tail.gap {+ gaps += 1;+ warn!(+ index = %name, shard = %shard,+ "WAL tap: a WAL generation was pruned before it could be shipped — \+ entries are missing at the target and cannot be recovered from the \+ WAL. The tap is behind; raise poll throughput or check the target."+ );+ }+ corrupt += tail.corrupt_skipped as u64;+ more |= tail.truncated;+ for entry in tail.entries {+ if matches!(entry.entry, WalEntry::UpdateMapping { .. }) {+ mapping_updates += 1;+ }+ batch.push((entry.seq_no, entry.entry));+ }+ new_cursors.insert(shard, tail.cursor);+ }++ if gaps > 0 || corrupt > 0 || mapping_updates > 0 {+ self.stat(name, |s| {+ s.gaps += gaps;+ s.corrupt_skipped += corrupt;+ s.mapping_updates_skipped += mapping_updates;+ });+ }++ if batch.is_empty() {+ // Nothing to send, but the cursors may still have moved (a fresh+ // "start from now" position, or frames that decoded to nothing).+ if new_cursors != known {+ self.state+ .write()+ .indices+ .entry(name.to_string())+ .or_default()+ .shards = new_cursors;+ self.persist();+ }+ return more;+ }++ // Ship in seq order. Byte order is what the cursor resumes from, but+ // seq order is what decides which write wins — both here inside one+ // batch, and at any target that honours external versioning.+ batch.sort_by_key(|(seq, _)| *seq);++ let chunks = render_chunks(name, &batch, config.max_batch_bytes);+ if chunks.is_empty() {+ // Everything read was an entry kind that renders to nothing.+ self.state+ .write()+ .indices+ .entry(name.to_string())+ .or_default()+ .shards = new_cursors;+ self.persist();+ return more;+ }++ // `max_batch_bytes` bounds one HTTP request, not one poll: a target's+ // `http.max_content_length` is what it exists for. Every chunk of the+ // read has to land before the cursors move, so a failure part-way+ // through redelivers the earlier chunks on the next poll — which is+ // exactly what external versioning makes free.+ let mut docs = 0u64;+ let mut deletes = 0u64;+ let mut max_seq = 0u64;+ let mut item_failures = 0u64;+ let mut version_conflicts = 0u64;+ let mut batches = 0u64;++ for chunk in chunks {+ match self.send_bulk(config, chunk.body).await {+ SendOutcome::Accepted {+ item_failures: items,+ version_conflicts: conflicts,+ } => {+ docs += chunk.docs;+ deletes += chunk.deletes;+ max_seq = max_seq.max(chunk.max_seq);+ item_failures += items;+ version_conflicts += conflicts;+ batches += 1;+ }+ SendOutcome::Failed(err) => {+ let failures = self.stat(name, |s| {+ s.docs_shipped += docs;+ s.deletes_shipped += deletes;+ s.batches_sent += batches;+ s.item_failures += item_failures;+ s.version_conflicts += version_conflicts;+ s.bulk_failures += 1;+ s.consecutive_failures = s.consecutive_failures.saturating_add(1);+ s.last_error = Some(err.clone());+ s.consecutive_failures+ });+ warn!(index = %name, error = %err, failures,+ "WAL tap: _bulk failed — cursor held, will retry");+ self.arm_backoff(config, failures);+ return false;+ }+ }+ }++ self.state+ .write()+ .indices+ .entry(name.to_string())+ .or_default()+ .shards = new_cursors;+ self.persist();+ self.stat(name, |s| {+ s.docs_shipped += docs;+ s.deletes_shipped += deletes;+ s.batches_sent += batches;+ s.item_failures += item_failures;+ s.version_conflicts += version_conflicts;+ s.last_shipped_seq = s.last_shipped_seq.max(max_seq);+ s.consecutive_failures = 0;+ s.last_error = None;+ });+ self.clear_backoff();+ debug!(index = %name, docs, deletes, batches, "WAL tap: batch shipped");+ more+ }++ /// Drop cursors for indices that no longer exist.+ ///+ /// Hygiene, and one correctness case: an index deleted and recreated under+ /// the same name gets a brand-new WAL starting at generation 0, which the+ /// old cursor points far past. `tail_shard` self-heals that as a gap, but+ /// forgetting the cursor is both cheaper and more honest — the new index+ /// genuinely has no shipped history.+ fn forget_deleted(&self, live: &[String]) {+ let mut state = self.state.write();+ if state.indices.keys().all(|k| live.iter().any(|l| l == k)) {+ return;+ }+ state.indices.retain(|name, _| {+ let kept = live.iter().any(|l| l == name);+ if !kept {+ debug!(index = %name, "WAL tap: forgetting the cursor of a deleted index");+ }+ kept+ });+ drop(state);+ self.persist();+ }++ /// One full pass over the allowlisted indices. Exposed for tests; the+ /// server drives [`run`] instead.+ pub async fn tick(&self, engine: &Engine) {+ let config = self.config();+ self.ticks.fetch_add(1, Ordering::Relaxed);+ if !config.enabled || config.target_url.trim().is_empty() || config.indices.is_empty() {+ return;+ }+ if self.in_backoff() {+ return;+ }++ let live = engine.index_name_list();+ self.forget_deleted(&live);++ for name in live {+ if !Self::ships(&config, &name) {+ continue;+ }+ let Ok(index) = engine.get_index(&name) else {+ continue;+ };+ let wal_root = index.wal_dir();+ // Keep draining an index that is behind, but bounded: at most a+ // few batches per tick so one busy index cannot starve the others.+ for _ in 0..4 {+ if !self.poll_index(&config, &name, wal_root.clone()).await {+ break;+ }+ }+ if self.in_backoff() {+ break;+ }+ }+ }+}++/// Drive the tap until the process exits.+pub async fn run(tap: Arc<WalTap>, engine: Arc<Engine>) {+ info!("WAL tap loop started (disabled until wal_tap.enabled and a target are set)");+ loop {+ let interval = Duration::from_millis(tap.config().poll_interval_ms.clamp(50, 60_000));+ tokio::time::sleep(interval).await;+ tap.tick(&engine).await;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn cfg(indices: &[&str]) -> WalTapConfig {+ WalTapConfig {+ enabled: true,+ target_url: "http://localhost:1".into(),+ indices: indices.iter().map(|s| s.to_string()).collect(),+ ..Default::default()+ }+ }++ #[test]+ fn allowlist_matches_globs() {+ let c = cfg(&["edge-*", "metrics"]);+ assert!(WalTap::ships(&c, "edge-logs"));+ assert!(WalTap::ships(&c, "metrics"));+ assert!(!WalTap::ships(&c, "orders"));+ }++ #[test]+ fn system_indices_are_never_shipped_even_by_a_star_allowlist() {+ let c = cfg(&["*"]);+ assert!(WalTap::ships(&c, "edge-logs"));+ assert!(!WalTap::ships(&c, ".xerj-memory-alice"));+ assert!(!WalTap::ships(&c, ".xerj_users"));+ assert!(!WalTap::ships(&c, ".xerj_api_tokens"));+ // …and naming one outright does not get round it either.+ assert!(!WalTap::ships(&cfg(&[".xerj_users"]), ".xerj_users"));+ assert!(!WalTap::ships(&cfg(&[".xerj*"]), ".xerj_sessions"));+ }++ /// A wildcard means "every ordinary index", not "also the hidden ones" —+ /// the same rule ES's `expand_wildcards` uses. An explicitly dotted+ /// pattern still reaches them.+ #[test]+ fn a_wildcard_does_not_expand_to_hidden_indices() {+ assert!(!WalTap::ships(&cfg(&["*"]), ".kibana"));+ assert!(WalTap::ships(&cfg(&[".kibana"]), ".kibana"));+ assert!(WalTap::ships(&cfg(&[".kib*"]), ".kibana"));+ }++ #[test]+ fn an_empty_allowlist_ships_nothing() {+ let c = cfg(&[]);+ assert!(!WalTap::ships(&c, "edge-logs"));+ }++ #[test]+ fn actions_carry_external_versioning_so_redelivery_is_idempotent() {+ let mut out = String::new();+ let entry = WalEntry::Index {+ doc_id: "d1".into(),+ source: json!({"a": 1}),+ };+ assert_eq!(+ render_action("edge-logs", 42, &entry, &mut out),+ Some(false)+ );+ let meta: Value = serde_json::from_str(out.lines().next().unwrap()).unwrap();+ assert_eq!(meta["index"]["_id"], "d1");+ assert_eq!(meta["index"]["_index"], "edge-logs");+ assert_eq!(meta["index"]["version"], 42);+ assert_eq!(meta["index"]["version_type"], "external");+ assert_eq!(out.lines().nth(1).unwrap(), r#"{"a":1}"#);++ let mut out = String::new();+ let del = WalEntry::Delete {+ doc_id: "d1".into(),+ };+ assert_eq!(render_action("edge-logs", 43, &del, &mut out), Some(true));+ let meta: Value = serde_json::from_str(out.lines().next().unwrap()).unwrap();+ assert_eq!(meta["delete"]["version"], 43);+ assert_eq!(out.lines().count(), 1);+ }++ #[test]+ fn mapping_updates_render_nothing() {+ let mut out = String::new();+ let entry = WalEntry::UpdateMapping { schema: json!({}) };+ assert_eq!(render_action("i", 1, &entry, &mut out), None);+ assert!(out.is_empty());+ }++ #[test]+ fn unreadable_state_file_starts_from_now_rather_than_from_garbage() {+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(dir.path().join(STATE_FILE), b"{not json").unwrap();+ let tap = WalTap::new(dir.path(), WalTapConfig::default());+ assert!(tap.cursors().is_empty());+ }++ #[test]+ fn backoff_is_capped_and_jittered() {+ let dir = tempfile::tempdir().unwrap();+ let config = WalTapConfig {+ poll_interval_ms: 500,+ max_retry_backoff_secs: 10,+ ..Default::default()+ };+ let tap = WalTap::new(dir.path(), config.clone());+ tap.arm_backoff(&config, 30);+ let armed = tap.retry_not_before_ms.load(Ordering::Relaxed);+ let delay = armed.saturating_sub(tap.now_ms());+ assert!(+ delay <= 10_000,+ "backoff must respect the cap, got {delay}ms"+ );+ assert!(+ delay >= 4_000,+ "backoff must still be substantial, got {delay}ms"+ );+ }+}diff --git a/engine/crates/xerj-engine/tests/product_experience.rs b/engine/crates/xerj-engine/tests/product_experience.rsindex 04e3c27d1..e62e7cb39 100644--- a/engine/crates/xerj-engine/tests/product_experience.rs+++ b/engine/crates/xerj-engine/tests/product_experience.rs@@ -753,7 +753,7 @@ fn count_settings(value: &serde_json::Value) -> usize {/// Settings in a default `Config`, measured by `count_settings`. Quoted in/// `xerj-common/src/config.rs`; keep the two in step.-const EXPECTED_SETTINGS: usize = 105;+const EXPECTED_SETTINGS: usize = 114;#[tokio::test]async fn journey_zero_config() {diff --git a/engine/crates/xerj-engine/tests/wal_tap_push.rs b/engine/crates/xerj-engine/tests/wal_tap_push.rsnew file mode 100644index 000000000..29c0460fe--- /dev/null+++ b/engine/crates/xerj-engine/tests/wal_tap_push.rs@@ -0,0 +1,542 @@+//! Issue #320 — push a filtered subset of indices to an external+//! ES-compatible target (single-node WAL tap).+//!+//! Every test here fails on the pre-#320 tree for the same reason: nothing+//! pushed data out of the engine at all. `_ccr/*` answered `501`,+//! reindex-from-remote was refused up front, and snapshot/restore was the only+//! export path — scheduled, whole-index, not near-real-time.+//!+//! The target is a stub HTTP server that speaks just enough `_bulk` to record+//! what it was sent, which is also the point of the feature: the wire format+//! is `_bulk` and nothing else, so an Elasticsearch cluster, an OpenSearch+//! cluster or another xerj node are all the same to the tap.++use std::collections::HashMap;+use std::sync::{Arc, Mutex};++use serde_json::{json, Value};+use tempfile::TempDir;+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::{TcpListener, TcpStream};++use xerj_common::config::{Config, WalTapConfig};+use xerj_common::types::Schema;+use xerj_engine::Engine;++// ─────────────────────────────────────────────────────────────────────────────+// A stub `_bulk` target+// ─────────────────────────────────────────────────────────────────────────────++#[derive(Default)]+struct Received {+ /// Every NDJSON body the target was POSTed, in order.+ bodies: Vec<String>,+ /// `Authorization` header of the last request, if any.+ last_auth: Option<String>,+}++struct StubTarget {+ url: String,+ received: Arc<Mutex<Received>>,+ _task: tokio::task::JoinHandle<()>,+}++impl StubTarget {+ async fn start() -> Self {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ let received = Arc::new(Mutex::new(Received::default()));+ let sink = received.clone();+ let task = tokio::spawn(async move {+ loop {+ let Ok((stream, _)) = listener.accept().await else {+ return;+ };+ let sink = sink.clone();+ tokio::spawn(async move {+ let _ = serve_one(stream, sink).await;+ });+ }+ });+ Self {+ url,+ received,+ _task: task,+ }+ }++ /// Every `_bulk` action line the target has seen, paired with the source+ /// line that followed it (`None` for a delete).+ fn actions(&self) -> Vec<(Value, Option<Value>)> {+ let bodies = self.received.lock().unwrap().bodies.clone();+ let mut out = Vec::new();+ for body in bodies {+ let mut lines = body.lines();+ while let Some(meta) = lines.next() {+ if meta.trim().is_empty() {+ continue;+ }+ let meta: Value = serde_json::from_str(meta)+ .unwrap_or_else(|e| panic!("bad action line {meta:?}: {e}"));+ let is_delete = meta.get("delete").is_some();+ let source = if is_delete {+ None+ } else {+ Some(serde_json::from_str(lines.next().expect("source line")).unwrap())+ };+ out.push((meta, source));+ }+ }+ out+ }++ fn indexed_ids(&self, index: &str) -> Vec<String> {+ self.actions()+ .iter()+ .filter_map(|(meta, _)| meta.get("index"))+ .filter(|a| a["_index"] == index)+ .map(|a| a["_id"].as_str().unwrap_or_default().to_string())+ .collect()+ }++ fn request_count(&self) -> usize {+ self.received.lock().unwrap().bodies.len()+ }+}++/// Read one HTTP request, record the body, answer with an ES-shaped `_bulk`+/// response.+async fn serve_one(mut stream: TcpStream, sink: Arc<Mutex<Received>>) -> std::io::Result<()> {+ let mut raw = Vec::new();+ let mut buf = [0u8; 8192];+ loop {+ let n = stream.read(&mut buf).await?;+ if n == 0 {+ break;+ }+ raw.extend_from_slice(&buf[..n]);+ let text = String::from_utf8_lossy(&raw).into_owned();+ let Some(head_end) = text.find("\r\n\r\n") else {+ continue;+ };+ let head = &text[..head_end];+ let len: usize = head+ .lines()+ .find_map(|l| {+ let (k, v) = l.split_once(':')?;+ k.eq_ignore_ascii_case("content-length")+ .then(|| v.trim().parse().ok())?+ })+ .unwrap_or(0);+ if raw.len() < head_end + 4 + len {+ continue;+ }+ let body = text[head_end + 4..head_end + 4 + len].to_string();+ let auth = head.lines().find_map(|l| {+ let (k, v) = l.split_once(':')?;+ k.eq_ignore_ascii_case("authorization")+ .then(|| v.trim().to_string())+ });+ {+ let mut guard = sink.lock().unwrap();+ guard.bodies.push(body);+ guard.last_auth = auth;+ }+ let payload = br#"{"took":1,"errors":false,"items":[]}"#;+ let resp = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",+ payload.len()+ );+ stream.write_all(resp.as_bytes()).await?;+ stream.write_all(payload).await?;+ stream.flush().await?;+ break;+ }+ Ok(())+}++// ─────────────────────────────────────────────────────────────────────────────+// Harness+// ─────────────────────────────────────────────────────────────────────────────++fn engine_with_tap(dir: &TempDir, tap: WalTapConfig) -> Engine {+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_str().unwrap().to_string();+ config.wal_tap = tap;+ Engine::new(config).expect("engine::new")+}++fn tap_config(url: &str, indices: &[&str]) -> WalTapConfig {+ WalTapConfig {+ enabled: true,+ target_url: url.to_string(),+ indices: indices.iter().map(|s| s.to_string()).collect(),+ ..Default::default()+ }+}++async fn write_docs(engine: &Engine, index: &str, ids: &[&str]) {+ if engine.get_index(index).is_err() {+ engine.create_index(index, Schema::empty()).unwrap();+ }+ let idx = engine.get_index(index).unwrap();+ for id in ids {+ idx.index_document(+ Some((*id).to_string()),+ json!({"msg": format!("hello {id}")}),+ )+ .await+ .unwrap();+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// Tests+// ─────────────────────────────────────────────────────────────────────────────++/// The headline. Before #320 there was no push path of any kind: this asserts+/// that documents written to an allowlisted index land at an external+/// `_bulk` target, and that documents written to an index outside the+/// allowlist do not.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn an_allowlisted_index_is_pushed_to_an_external_bulk_target() {+ let target = StubTarget::start().await;+ let dir = TempDir::new().unwrap();+ let engine = engine_with_tap(&dir, tap_config(&target.url, &["edge-*"]));++ write_docs(&engine, "edge-logs", &["1", "2", "3"]).await;+ write_docs(&engine, "orders", &["o1"]).await;++ engine.wal_tap.tick(&engine).await;++ let mut shipped = target.indexed_ids("edge-logs");+ shipped.sort();+ assert_eq!(+ shipped,+ vec!["1", "2", "3"],+ "every document of an allowlisted index must reach the target"+ );+ assert!(+ target.indexed_ids("orders").is_empty(),+ "the allowlist is a filter, not a suggestion: {:?}",+ target.actions()+ );++ let stats = engine.wal_tap.stats();+ let edge = stats.get("edge-logs").expect("stats for edge-logs");+ assert_eq!(edge.docs_shipped, 3);+ assert_eq!(edge.bulk_failures, 0);+ assert_eq!(edge.gaps, 0);+ assert!(edge.last_error.is_none());+}++/// At-least-once delivery is only safe because every action carries the WAL+/// `seq_no` as an external version — the same "highest seq wins" rule the+/// engine's own version map uses. Without it a redelivered or reordered batch+/// could resurrect an older document at the target.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn every_action_carries_external_versioning_and_the_document_id() {+ let target = StubTarget::start().await;+ let dir = TempDir::new().unwrap();+ let engine = engine_with_tap(&dir, tap_config(&target.url, &["edge-logs"]));++ write_docs(&engine, "edge-logs", &["a"]).await;+ engine.wal_tap.tick(&engine).await;++ let actions = target.actions();+ let (meta, source) = actions.first().expect("one action");+ let action = &meta["index"];+ assert_eq!(action["_index"], "edge-logs");+ assert_eq!(action["_id"], "a");+ assert_eq!(action["version_type"], "external");+ assert!(+ action["version"].as_u64().unwrap_or(0) > 0,+ "the WAL seq_no must be the external version, got {action}"+ );+ assert_eq!(source.as_ref().unwrap()["msg"], "hello a");+}++/// A delete has to travel too, or the target diverges permanently on every+/// removed document.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn deletes_are_pushed_as_bulk_delete_actions() {+ let target = StubTarget::start().await;+ let dir = TempDir::new().unwrap();+ let engine = engine_with_tap(&dir, tap_config(&target.url, &["edge-logs"]));++ write_docs(&engine, "edge-logs", &["a", "b"]).await;+ engine+ .get_index("edge-logs")+ .unwrap()+ .delete_document("a")+ .await+ .unwrap();++ engine.wal_tap.tick(&engine).await;++ let deletes: Vec<String> = target+ .actions()+ .iter()+ .filter_map(|(meta, _)| meta.get("delete").cloned())+ .map(|a| a["_id"].as_str().unwrap_or_default().to_string())+ .collect();+ assert_eq!(deletes, vec!["a"], "the delete must reach the target");+ assert_eq!(engine.wal_tap.stats()["edge-logs"].deletes_shipped, 1);+}++/// The one rule the allowlist cannot override. `.xerj-*` holds API keys,+/// sessions and console state; `indices = ["*"]` must not ship it anywhere.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn system_indices_are_never_pushed_even_with_a_star_allowlist() {+ let target = StubTarget::start().await;+ let dir = TempDir::new().unwrap();+ let engine = engine_with_tap(&dir, tap_config(&target.url, &["*"]));++ write_docs(&engine, "edge-logs", &["1"]).await;+ write_docs(&engine, ".xerj-secrets", &["k1"]).await;++ engine.wal_tap.tick(&engine).await;++ assert_eq!(target.indexed_ids("edge-logs"), vec!["1"]);+ let shipped_indices: Vec<String> = target+ .actions()+ .iter()+ .filter_map(|(meta, _)| meta.as_object()?.values().next()?.get("_index").cloned())+ .map(|v| v.as_str().unwrap_or_default().to_string())+ .collect();+ assert!(+ !shipped_indices.iter().any(|i| i.starts_with(".xerj")),+ "a system index escaped to an external cluster: {shipped_indices:?}"+ );+}++/// Backpressure and durability: an unreachable target must not lose data and+/// must not grow anything locally. The cursor stays put, the failure is+/// visible, and the documents arrive once the target comes back.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn an_unreachable_target_holds_the_cursor_and_reports_why() {+ let dir = TempDir::new().unwrap();+ // Bind and immediately drop a listener to get a port nothing is serving.+ let dead = {+ let l = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = l.local_addr().unwrap();+ drop(l);+ format!("http://{addr}")+ };+ let engine = engine_with_tap(&dir, tap_config(&dead, &["edge-logs"]));++ write_docs(&engine, "edge-logs", &["1", "2"]).await;+ engine.wal_tap.tick(&engine).await;++ let stats = engine.wal_tap.stats();+ let edge = stats.get("edge-logs").expect("stats for edge-logs");+ assert!(edge.bulk_failures >= 1, "the failure must be counted");+ assert_eq!(edge.docs_shipped, 0, "nothing was actually delivered");+ assert!(+ edge.last_error.is_some(),+ "an operator must be able to see why the tap stopped advancing"+ );+ assert!(+ engine+ .wal_tap+ .cursors()+ .get("edge-logs")+ .map(|shards| shards.is_empty())+ .unwrap_or(true),+ "the cursor must not advance past entries the target never received"+ );++ // Point it at a live target: the held-back documents go now.+ let target = StubTarget::start().await;+ let mut config = engine.wal_tap.config();+ config.target_url = target.url.clone();+ config.max_retry_backoff_secs = 1;+ engine.wal_tap.set_config(config);+ tokio::time::sleep(std::time::Duration::from_millis(1200)).await;+ engine.wal_tap.tick(&engine).await;++ let mut shipped = target.indexed_ids("edge-logs");+ shipped.sort();+ assert_eq!(+ shipped,+ vec!["1", "2"],+ "documents held during the outage must ship once the target returns"+ );+}++/// A cursor that has already shipped an entry must not ship it again on the+/// next poll, and a restart must resume from the persisted position rather+/// than replaying the whole retained WAL.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn cursors_are_durable_so_a_restart_does_not_re_ship_everything() {+ let target = StubTarget::start().await;+ let dir = TempDir::new().unwrap();+ let tap = tap_config(&target.url, &["edge-logs"]);++ {+ let engine = engine_with_tap(&dir, tap.clone());+ write_docs(&engine, "edge-logs", &["1", "2"]).await;+ engine.wal_tap.tick(&engine).await;+ assert_eq!(target.indexed_ids("edge-logs").len(), 2);++ // An idle poll ships nothing.+ engine.wal_tap.tick(&engine).await;+ assert_eq!(+ target.request_count(),+ 1,+ "an idle poll must not re-send an already-shipped batch"+ );+ }++ // Restart against the same data directory.+ let engine = engine_with_tap(&dir, tap);+ write_docs(&engine, "edge-logs", &["3"]).await;+ engine.wal_tap.tick(&engine).await;++ let shipped = target.indexed_ids("edge-logs");+ assert_eq!(+ shipped,+ vec!["1", "2", "3"],+ "a restart must resume, not replay: {shipped:?}"+ );+}++/// The credential travels to the target and nowhere else.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_configured_credential_is_sent_to_the_target() {+ let target = StubTarget::start().await;+ let dir = TempDir::new().unwrap();+ let mut tap = tap_config(&target.url, &["edge-logs"]);+ tap.target_auth = "ApiKey s3cr3t".to_string();+ let engine = engine_with_tap(&dir, tap);++ write_docs(&engine, "edge-logs", &["1"]).await;+ engine.wal_tap.tick(&engine).await;++ assert_eq!(+ target.received.lock().unwrap().last_auth.as_deref(),+ Some("ApiKey s3cr3t")+ );+}++/// The allowlist is runtime-adjustable without a restart — that is half the+/// point of the feature for an edge node whose curation changes.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_allowlist_can_be_changed_at_runtime() {+ let target = StubTarget::start().await;+ let dir = TempDir::new().unwrap();+ let engine = engine_with_tap(&dir, tap_config(&target.url, &["edge-logs"]));++ write_docs(&engine, "edge-logs", &["1"]).await;+ write_docs(&engine, "metrics", &["m1"]).await;+ engine.wal_tap.tick(&engine).await;+ assert!(target.indexed_ids("metrics").is_empty());++ let mut config = engine.wal_tap.config();+ config.indices.push("metrics".to_string());+ engine.wal_tap.set_config(config);++ write_docs(&engine, "metrics", &["m2"]).await;+ engine.wal_tap.tick(&engine).await;++ assert!(+ target.indexed_ids("metrics").contains(&"m2".to_string()),+ "an index added to the allowlist must start shipping: {:?}",+ target.actions()+ );+}++/// Off by default, and inert when on but unconfigured. A feature that pushes+/// documents to another cluster must never do so because someone upgraded.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_tap_is_off_by_default_and_inert_without_a_target() {+ assert!(!WalTapConfig::default().enabled);+ assert!(WalTapConfig::default().indices.is_empty());++ let target = StubTarget::start().await;+ let dir = TempDir::new().unwrap();+ // Enabled, allowlisted — but no target URL.+ let engine = engine_with_tap(+ &dir,+ WalTapConfig {+ enabled: true,+ target_url: String::new(),+ indices: vec!["*".into()],+ ..Default::default()+ },+ );+ write_docs(&engine, "edge-logs", &["1"]).await;+ engine.wal_tap.tick(&engine).await;+ assert_eq!(target.request_count(), 0);+ assert!(engine.wal_tap.stats().is_empty());+}++/// `max_batch_docs` and `max_batch_bytes` bound each request rather than+/// silently truncating the stream: everything still arrives, in more requests.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn batch_limits_split_the_stream_instead_of_dropping_it() {+ let target = StubTarget::start().await;+ let dir = TempDir::new().unwrap();+ let mut tap = tap_config(&target.url, &["edge-logs"]);+ tap.max_batch_docs = 3;+ tap.max_batch_bytes = 200;+ let engine = engine_with_tap(&dir, tap);++ let ids: Vec<String> = (1..=9).map(|i| i.to_string()).collect();+ let refs: Vec<&str> = ids.iter().map(String::as_str).collect();+ write_docs(&engine, "edge-logs", &refs).await;++ engine.wal_tap.tick(&engine).await;++ let mut shipped = target.indexed_ids("edge-logs");+ shipped.sort();+ let mut expected = ids.clone();+ expected.sort();+ assert_eq!(shipped, expected, "a bounded batch must not drop documents");+ assert!(+ target.request_count() > 1,+ "the byte/doc caps must actually split the stream"+ );++ // And every document arrived exactly once — the caps must not double-send.+ let mut counts: HashMap<String, usize> = HashMap::new();+ for id in target.indexed_ids("edge-logs") {+ *counts.entry(id).or_default() += 1;+ }+ assert!(+ counts.values().all(|&c| c == 1),+ "documents were delivered more than once: {counts:?}"+ );+}++/// An index deleted and recreated under the same name gets a brand-new WAL+/// starting at generation 0, which the old cursor points far past. Left alone+/// that stalls the shard silently and forever — the worst failure mode a WAL+/// consumer can have, because `_stats` would show a healthy tap shipping+/// nothing.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn recreating_an_index_under_the_same_name_does_not_stall_the_tap() {+ let target = StubTarget::start().await;+ let dir = TempDir::new().unwrap();+ let engine = engine_with_tap(&dir, tap_config(&target.url, &["edge-logs"]));++ write_docs(&engine, "edge-logs", &["1"]).await;+ engine.wal_tap.tick(&engine).await;+ assert_eq!(target.indexed_ids("edge-logs"), vec!["1"]);++ engine.delete_index("edge-logs").await.unwrap();+ // The tick that observes the deletion forgets the stale cursor.+ engine.wal_tap.tick(&engine).await;+ assert!(+ !engine.wal_tap.cursors().contains_key("edge-logs"),+ "the cursor of a deleted index must not outlive it"+ );++ write_docs(&engine, "edge-logs", &["2"]).await;+ engine.wal_tap.tick(&engine).await;+ assert!(+ target.indexed_ids("edge-logs").contains(&"2".to_string()),+ "a recreated index must keep shipping: {:?}",+ target.actions()+ );+}diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 3043cb782..80a49f197 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -2231,6 +2231,27 @@ async fn async_main() -> Result<()> {tokio::spawn(xerj_api::es_compat::run_metrics_gauge_loop(state.clone()));}+ // 9b-2. WAL tap (issue #320) — one-directional push of an allowlisted+ // index subset to an external ES-compatible target. The loop always+ // runs; it is inert (one sleep per poll interval, no I/O) until+ // `wal_tap.enabled` and a `target_url` are set, either in the config+ // file or at runtime via `PUT /_xerj/wal_tap`.+ {+ let tap = state.engine.wal_tap.clone();+ let engine = state.engine.clone();+ if tap.config().enabled {+ let cfg = tap.config();+ info!(+ target = %cfg.target_url,+ indices = ?cfg.indices,+ poll_interval_ms = cfg.poll_interval_ms,+ "WAL tap enabled — pushing to an external ES-compatible target \+ (one-directional, no backfill; see GET /_xerj/wal_tap/_stats)"+ );+ }+ tokio::spawn(xerj_engine::wal_tap::run(tap, engine));+ }+// 9c. Routers — engine and Xerj Console are *peer* surfaces. Each crate// builds a complete Router (routes + its own auth + its own// middleware) and `xerj-server` merges them onto the same TCPdiff --git a/engine/crates/xerj-storage/src/wal.rs b/engine/crates/xerj-storage/src/wal.rsindex 0101b4083..87091eea2 100644--- a/engine/crates/xerj-storage/src/wal.rs+++ b/engine/crates/xerj-storage/src/wal.rs@@ -1527,71 +1527,18 @@ fn read_wal_file(path: PathBuf) -> Vec<Result<ReplayEntry>> {let this_offset = off as u64;off = end;- // Check and strip the compression flag from op_code.- let is_compressed = (op_code & OP_COMPRESSED_FLAG) != 0;- let raw_op_code = op_code & !OP_COMPRESSED_FLAG;-- let op = match WalOpCode::from_u8(raw_op_code) {- Some(o) => o,- None => {- warn!(- op_code = raw_op_code,- "unknown WAL op code — skipping entry"- );- continue;- }- };-- // Decompress payload if compressed.- let payload_owned: Vec<u8>;- let payload_bytes: &[u8] = if is_compressed {- match decompress_size_prepended(payload) {- Ok(dec) => {- payload_owned = dec;- &payload_owned- }- Err(e) => {- results.push(Err(StorageError::WalCorrupt(- this_offset,- format!("gen={generation} lz4 decompression failed: {e}"),- )));- continue;- }- }- } else {- payload- };-- let entry: WalEntry = match serde_json::from_slice(payload_bytes) {- Ok(e) => e,- Err(e) => {- results.push(Err(StorageError::WalCorrupt(- this_offset,- format!("gen={generation} json error op={op:?}: {e}"),- )));+ match decode_frame_payload(op_code, payload, generation, this_offset) {+ FrameDecode::Entry(entry) => results.push(Ok(ReplayEntry {+ seq_no,+ entry,+ file_offset: this_offset,+ })),+ FrameDecode::UnknownOp => continue,+ FrameDecode::Bad(e) => {+ results.push(Err(e));continue;}- };-- // Sanity-check op code matches enum variant- let expected_op = match &entry {- WalEntry::Index { .. } => WalOpCode::Index,- WalEntry::Delete { .. } => WalOpCode::Delete,- WalEntry::UpdateMapping { .. } => WalOpCode::UpdateMapping,- };- if op != expected_op {- results.push(Err(StorageError::WalCorrupt(- this_offset,- format!("op code mismatch: header={op:?}, payload={expected_op:?}"),- )));- continue;}-- results.push(Ok(ReplayEntry {- seq_no,- entry,- file_offset: this_offset,- }));}}}@@ -1608,6 +1555,445 @@ fn read_wal_file(path: PathBuf) -> Vec<Result<ReplayEntry>> {results}+/// What one CRC-valid frame's payload turned out to hold.+enum FrameDecode {+ /// A decoded entry.+ Entry(WalEntry),+ /// The op byte is not one this build knows — warn and skip WITHOUT+ /// recording an error, so a file written by a future version stays+ /// prunable rather than being retained forever.+ UnknownOp,+ /// Framing was intact but the payload did not decode (lz4, JSON, or an+ /// op-code/variant mismatch).+ Bad(StorageError),+}++/// Decode one CRC-valid frame's payload: strip the compression flag,+/// decompress, parse the JSON, and check the op byte against the decoded+/// variant.+///+/// Shared by [`read_wal_file`] (full replay) and [`tail_wal_file`] (the+/// WAL-tap reader) so the two can never drift on what a frame means.+fn decode_frame_payload(+ op_code: u8,+ payload: &[u8],+ generation: u64,+ this_offset: u64,+) -> FrameDecode {+ let is_compressed = (op_code & OP_COMPRESSED_FLAG) != 0;+ let raw_op_code = op_code & !OP_COMPRESSED_FLAG;++ let op = match WalOpCode::from_u8(raw_op_code) {+ Some(o) => o,+ None => {+ warn!(+ op_code = raw_op_code,+ "unknown WAL op code — skipping entry"+ );+ return FrameDecode::UnknownOp;+ }+ };++ let payload_owned: Vec<u8>;+ let payload_bytes: &[u8] = if is_compressed {+ match decompress_size_prepended(payload) {+ Ok(dec) => {+ payload_owned = dec;+ &payload_owned+ }+ Err(e) => {+ return FrameDecode::Bad(StorageError::WalCorrupt(+ this_offset,+ format!("gen={generation} lz4 decompression failed: {e}"),+ ))+ }+ }+ } else {+ payload+ };++ let entry: WalEntry = match serde_json::from_slice(payload_bytes) {+ Ok(e) => e,+ Err(e) => {+ return FrameDecode::Bad(StorageError::WalCorrupt(+ this_offset,+ format!("gen={generation} json error op={op:?}: {e}"),+ ))+ }+ };++ let expected_op = match &entry {+ WalEntry::Index { .. } => WalOpCode::Index,+ WalEntry::Delete { .. } => WalOpCode::Delete,+ WalEntry::UpdateMapping { .. } => WalOpCode::UpdateMapping,+ };+ if op != expected_op {+ return FrameDecode::Bad(StorageError::WalCorrupt(+ this_offset,+ format!("op code mismatch: header={op:?}, payload={expected_op:?}"),+ ));+ }++ FrameDecode::Entry(entry)+}++// ── WAL tail reader (issue #320) ─────────────────────────────────────────────++/// A consumer's durable position inside ONE WAL shard stream.+///+/// The position is a **byte offset**, not a sequence number, and that is not+/// an accident: the M5.8 lock-free writer reserves its seq_nos with a+/// `fetch_add` *outside* the shard mutex and only then appends under it, so+/// frames can land in a file out of seq order (see the sort in+/// [`read_wal_file`]). Append order is the only order a file position can be+/// resumed from without risking a skipped frame, so that is what a cursor is.+///+/// `generation` and `drained` exist to answer one question the offset alone+/// cannot: *was anything pruned out from under us?* Rotated generations are+/// deleted once every entry in them is durable in a segment+/// ([`WalWriter::prune_verified`]) — retention never waits for a consumer, by+/// design, because a slow remote target must not be able to fill the disk. A+/// consumer that falls far enough behind therefore loses source data, and the+/// contract here is that it always **finds out** ([`WalShardTail::gap`]).+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub struct WalTailCursor {+ /// Generation the cursor sits in.+ pub generation: u64,+ /// Byte offset just past the last consumed frame.+ pub offset: u64,+ /// The last read reached a clean end-of-file for `generation`. Lets the+ /// gap check tell "we finished this generation and it was then pruned"+ /// (fine) from "this generation was pruned before we read it" (a gap).+ pub drained: bool,+}++impl WalTailCursor {+ /// A cursor positioned at the very start of `generation`.+ pub fn start_of(generation: u64) -> Self {+ Self {+ generation,+ offset: WAL_HEADER_LEN,+ drained: false,+ }+ }+}++/// The result of one tail poll over a single shard stream.+#[derive(Debug)]+pub struct WalShardTail {+ /// Entries read, in **append order** — the order the source engine+ /// applied them under the shard mutex.+ pub entries: Vec<ReplayEntry>,+ /// Where to resume. Persist this only after the entries have been+ /// consumed successfully; re-reading from an un-advanced cursor is how+ /// at-least-once delivery is achieved.+ pub cursor: WalTailCursor,+ /// Whole generations were pruned before this consumer read them: entries+ /// are missing and are not recoverable from the WAL. Never silent.+ pub gap: bool,+ /// `max_entries` cut the batch short — poll again immediately.+ pub truncated: bool,+ /// Frames skipped because their payload did not decode.+ pub corrupt_skipped: usize,+}++/// Every WAL shard stream under `wal_root`, as `(shard_name, dir)`.+///+/// Mirrors what [`IndexStore`](crate::index_store::IndexStore) writes: the+/// legacy single-WAL layout puts `*.wal` straight in the root (shard name+/// `""`), the sharded layout uses `s0`, `s1`, … subdirectories.+pub fn wal_shard_dirs(wal_root: &Path) -> Vec<(String, PathBuf)> {+ let mut dirs: Vec<(String, PathBuf)> = Vec::new();+ let Ok(rd) = fs::read_dir(wal_root) else {+ return dirs;+ };+ let mut has_root_wal = false;+ for entry in rd.filter_map(|e| e.ok()) {+ let path = entry.path();+ let name = entry.file_name().to_string_lossy().into_owned();+ if path.extension().map(|x| x == "wal").unwrap_or(false) {+ has_root_wal = true;+ } else if path.is_dir() && name.starts_with('s') && name[1..].parse::<usize>().is_ok() {+ dirs.push((name, path));+ }+ }+ if has_root_wal {+ dirs.push((String::new(), wal_root.to_path_buf()));+ }+ dirs.sort_by(|a, b| a.0.cmp(&b.0));+ dirs+}++/// Sorted list of the generations present in one shard directory.+fn generations_in(dir: &Path) -> Vec<u64> {+ let mut gens: Vec<u64> = fs::read_dir(dir)+ .into_iter()+ .flatten()+ .flatten()+ .filter_map(|e| parse_wal_generation(&e.file_name().to_string_lossy()))+ .collect();+ gens.sort_unstable();+ gens+}++/// Read the tail of one WAL shard stream.+///+/// `cursor == None` is a first look at this stream, and where it starts+/// depends on one question: has anything ever been pruned here?+///+/// - **Generation 0 is still on disk** — nothing has been reclaimed, so the+/// file set *is* the whole history. Start at the beginning and read it. This+/// is what makes an index created after the consumer starts get all of its+/// documents, including the ones written in the first poll interval.+/// - **Generation 0 is gone** — the stream has been pruned before, so its+/// surviving files are an arbitrary recent slice. Start at the end instead+/// and ship only what happens next. Shipping the slice would look like a+/// backfill while being nothing of the sort; snapshot/restore is the tool+/// for a real copy.+///+/// `max_entries == 0` reads nothing and leaves the cursor where it was.+pub fn tail_shard(dir: &Path, cursor: Option<WalTailCursor>, max_entries: usize) -> WalShardTail {+ let gens = generations_in(dir);+ let Some(&newest) = gens.last() else {+ // No generations at all (fresh index): stay where we are.+ return WalShardTail {+ entries: Vec::new(),+ cursor: cursor.unwrap_or(WalTailCursor::start_of(0)),+ gap: false,+ truncated: false,+ corrupt_skipped: 0,+ };+ };+ let first = gens[0];++ let cursor = match cursor {+ Some(c) => c,+ // Never pruned: the files on disk are the entire history, so read it.+ None if first == 0 => WalTailCursor::start_of(0),+ // Pruned before: start at the end rather than ship an arbitrary slice.+ // Walk the newest generation to find its last frame boundary and throw+ // the entries away — paid once, when a tap first sees the stream.+ None => {+ let scan = tail_wal_file(&wal_path(dir, newest), WAL_HEADER_LEN, false, usize::MAX);+ return WalShardTail {+ entries: Vec::new(),+ cursor: WalTailCursor {+ generation: newest,+ offset: scan.end_offset,+ drained: scan.drained,+ },+ gap: false,+ truncated: false,+ corrupt_skipped: 0,+ };+ }+ };++ // Did the pruner delete generations we had not finished reading?+ // `drained` on generation g means g is done, so g+1 appearing as the+ // oldest file on disk is normal progress, not a gap.+ let (start_gen, start_off, gap) = if cursor.generation > newest {+ // The cursor points past every generation that exists. A stream only+ // goes backwards when it is not the same stream: the index was deleted+ // and recreated under the same name, or the data directory was rolled+ // back. Restart from the beginning and flag it — holding position here+ // would stall this shard silently and forever, which is precisely the+ // failure a WAL consumer must never have.+ (first, WAL_HEADER_LEN, true)+ } else if cursor.generation < first {+ let expected_next = cursor.generation + if cursor.drained { 1 } else { 0 };+ (first, WAL_HEADER_LEN, first > expected_next)+ } else {+ (cursor.generation, cursor.offset, false)+ };++ let mut entries: Vec<ReplayEntry> = Vec::new();+ let mut corrupt_skipped = 0usize;+ let mut truncated = false;+ let mut out_cursor = WalTailCursor {+ generation: start_gen,+ offset: start_off,+ drained: false,+ };++ for &gen in gens.iter().filter(|&&g| g >= start_gen) {+ let from = if gen == start_gen {+ start_off+ } else {+ WAL_HEADER_LEN+ };+ // A rotated generation will never grow again, so a corrupt region in+ // it is permanent: resync past it exactly like replay does. The+ // newest generation is still being appended to, so a bad frame at its+ // tail is almost certainly a half-written one — stop and re-read it+ // on the next poll instead of resyncing over a frame that is about to+ // become valid.+ let allow_resync = gen != newest;+ let budget = max_entries.saturating_sub(entries.len());+ let scan = tail_wal_file(&wal_path(dir, gen), from, allow_resync, budget);++ corrupt_skipped += scan.corrupt;+ entries.extend(scan.entries);+ out_cursor = WalTailCursor {+ generation: gen,+ offset: scan.end_offset,+ drained: scan.drained,+ };+ if scan.truncated {+ truncated = true;+ break;+ }+ }++ WalShardTail {+ entries,+ cursor: out_cursor,+ gap,+ truncated,+ corrupt_skipped,+ }+}++/// One file's contribution to a tail poll.+struct FileTail {+ entries: Vec<ReplayEntry>,+ /// Offset to resume from: the start of the first frame NOT consumed.+ end_offset: u64,+ /// Reached a clean end-of-file.+ drained: bool,+ /// Stopped because the entry budget ran out.+ truncated: bool,+ corrupt: usize,+}++/// Read frames from `path` starting at `from_offset`, at most `budget` of them.+///+/// Frames are returned in append order. `end_offset` always lands on a frame+/// boundary, so the caller can persist it and resume from exactly there.+fn tail_wal_file(path: &Path, from_offset: u64, allow_resync: bool, budget: usize) -> FileTail {+ let buf = match fs::read(path) {+ Ok(b) => b,+ Err(e) if e.kind() == io::ErrorKind::NotFound => {+ // Pruned between listing and reading. Treat as finished so the+ // caller moves on to the next generation.+ return FileTail {+ entries: Vec::new(),+ end_offset: from_offset,+ drained: true,+ truncated: false,+ corrupt: 0,+ };+ }+ Err(e) => {+ warn!(?path, error = %e, "WAL tap: cannot read generation");+ return FileTail {+ entries: Vec::new(),+ end_offset: from_offset,+ drained: false,+ truncated: false,+ corrupt: 0,+ };+ }+ };++ if buf.len() < WAL_HEADER_LEN as usize || &buf[..4] != WAL_MAGIC {+ return FileTail {+ entries: Vec::new(),+ end_offset: from_offset.max(WAL_HEADER_LEN),+ drained: false,+ truncated: false,+ corrupt: 0,+ };+ }+ let generation = u64::from_le_bytes(buf[4..12].try_into().unwrap());++ let mut off = (from_offset.max(WAL_HEADER_LEN) as usize).min(buf.len());+ let mut entries = Vec::new();+ let mut corrupt = 0usize;++ loop {+ if entries.len() >= budget {+ return FileTail {+ entries,+ end_offset: off as u64,+ drained: false,+ truncated: true,+ corrupt,+ };+ }+ match parse_raw_frame(&buf, off) {+ RawFrame::End => {+ return FileTail {+ entries,+ end_offset: off as u64,+ drained: true,+ truncated: false,+ corrupt,+ }+ }+ RawFrame::Corrupt => {+ if !allow_resync {+ // Active generation: a half-written frame completes on+ // the writer's next flush. Hold the boundary.+ return FileTail {+ entries,+ end_offset: off as u64,+ drained: false,+ truncated: false,+ corrupt,+ };+ }+ match scan_next_valid_frame(&buf, off + 1) {+ Some(next) => {+ warn!(+ generation,+ offset = off,+ resync_at = next,+ "WAL tap: corrupt region in a rotated generation — entries in \+ the gap cannot be shipped"+ );+ corrupt += 1;+ off = next;+ }+ None => {+ // Torn tail on a file that will never grow again.+ corrupt += 1;+ return FileTail {+ entries,+ end_offset: off as u64,+ drained: true,+ truncated: false,+ corrupt,+ };+ }+ }+ }+ RawFrame::Frame {+ seq_no,+ op_code,+ payload,+ end,+ } => {+ let this_offset = off as u64;+ off = end;+ match decode_frame_payload(op_code, payload, generation, this_offset) {+ FrameDecode::Entry(entry) => entries.push(ReplayEntry {+ seq_no,+ entry,+ file_offset: this_offset,+ }),+ FrameDecode::UnknownOp => {}+ FrameDecode::Bad(e) => {+ warn!(generation, offset = this_offset, error = %e,+ "WAL tap: undecodable frame — skipped");+ corrupt += 1;+ }+ }+ }+ }+ }+}+// ── Helpers ───────────────────────────────────────────────────────────────────fn wal_path(dir: &Path, generation: u64) -> PathBuf {@@ -2348,4 +2734,266 @@ mod tests {}assert_eq!(total, 200);}++ // ── WAL tail reader (issue #320) ─────────────────────────────────────────++ fn doc(id: &str) -> WalEntry {+ WalEntry::Index {+ doc_id: id.to_string(),+ source: serde_json::json!({"v": id}),+ }+ }++ fn doc_ids(tail: &WalShardTail) -> Vec<String> {+ tail.entries+ .iter()+ .map(|e| match &e.entry {+ WalEntry::Index { doc_id, .. } => format!("+{doc_id}"),+ WalEntry::Delete { doc_id } => format!("-{doc_id}"),+ WalEntry::UpdateMapping { .. } => "~".to_string(),+ })+ .collect()+ }++ /// A never-pruned stream is read from the beginning, so an index created+ /// while a tap is running is shipped whole — including the documents+ /// written before its first poll.+ #[test]+ fn a_fresh_stream_is_tailed_from_the_beginning() {+ let dir = tempfile::tempdir().unwrap();+ let mut w = make_writer(dir.path());+ w.append(&doc("a")).unwrap();+ w.append(&doc("b")).unwrap();+ drop(w);++ let tail = tail_shard(dir.path(), None, 100);+ assert_eq!(doc_ids(&tail), vec!["+a", "+b"]);+ assert!(!tail.gap);+ assert!(tail.cursor.drained);+ }++ /// The resume contract: a cursor read back returns only what arrived+ /// after it, exactly once.+ #[test]+ fn a_cursor_resumes_without_re_reading_or_skipping() {+ let dir = tempfile::tempdir().unwrap();+ let mut w = make_writer(dir.path());+ w.append(&doc("a")).unwrap();++ let first = tail_shard(dir.path(), None, 100);+ assert_eq!(doc_ids(&first), vec!["+a"]);++ // Nothing new yet.+ let idle = tail_shard(dir.path(), Some(first.cursor), 100);+ assert!(idle.entries.is_empty());+ assert!(!idle.gap);++ w.append(&doc("b")).unwrap();+ w.append(&WalEntry::Delete {+ doc_id: "a".to_string(),+ })+ .unwrap();+ let next = tail_shard(dir.path(), Some(idle.cursor), 100);+ assert_eq!(doc_ids(&next), vec!["+b", "-a"]);+ }++ /// `max_entries` bounds one read; the cursor lands on a frame boundary so+ /// the next read continues from exactly there.+ #[test]+ fn a_truncated_read_resumes_at_the_frame_boundary() {+ let dir = tempfile::tempdir().unwrap();+ let mut w = make_writer(dir.path());+ for id in ["a", "b", "c", "d"] {+ w.append(&doc(id)).unwrap();+ }+ drop(w);++ let first = tail_shard(dir.path(), None, 2);+ assert_eq!(doc_ids(&first), vec!["+a", "+b"]);+ assert!(first.truncated);+ assert!(!first.cursor.drained);++ let second = tail_shard(dir.path(), Some(first.cursor), 100);+ assert_eq!(doc_ids(&second), vec!["+c", "+d"]);+ assert!(!second.truncated);+ }++ /// Rotation is not a gap: a consumer that keeps up walks from one+ /// generation into the next without noticing.+ #[test]+ fn rotation_is_not_a_gap() {+ let dir = tempfile::tempdir().unwrap();+ let mut w = make_writer(dir.path());+ w.append(&doc("a")).unwrap();+ let caught_up = tail_shard(dir.path(), None, 100);+ assert_eq!(doc_ids(&caught_up), vec!["+a"]);++ w.force_rotate().unwrap();+ w.append(&doc("b")).unwrap();+ drop(w);++ let after = tail_shard(dir.path(), Some(caught_up.cursor), 100);+ assert_eq!(doc_ids(&after), vec!["+b"]);+ assert!(+ !after.gap,+ "rotating past a drained generation is not a gap"+ );+ }++ /// Draining a generation that is THEN pruned is still not a gap — the+ /// consumer had already read every entry in it.+ #[test]+ fn pruning_a_generation_we_already_drained_is_not_a_gap() {+ let dir = tempfile::tempdir().unwrap();+ let mut w = make_writer(dir.path());+ w.append(&doc("a")).unwrap();+ let caught_up = tail_shard(dir.path(), None, 100);+ assert_eq!(doc_ids(&caught_up), vec!["+a"]);+ assert_eq!(caught_up.cursor.generation, 0);+ assert!(caught_up.cursor.drained);++ w.force_rotate().unwrap();+ w.append(&doc("b")).unwrap();+ drop(w);+ // The flush path reclaims generation 0 once its entries are durable.+ std::fs::remove_file(wal_path(dir.path(), 0)).unwrap();++ let after = tail_shard(dir.path(), Some(caught_up.cursor), 100);+ assert_eq!(doc_ids(&after), vec!["+b"]);+ assert!(!after.gap);+ }++ /// The honesty contract. Retention never waits for a consumer, so a+ /// consumer that falls far enough behind loses entries — and MUST be told.+ /// This is the case the whole cursor design exists to detect.+ #[test]+ fn a_generation_pruned_before_it_was_read_is_reported_as_a_gap() {+ let dir = tempfile::tempdir().unwrap();+ let mut w = make_writer(dir.path());+ w.append(&doc("a")).unwrap();+ let behind = tail_shard(dir.path(), None, 100);+ assert_eq!(behind.cursor.generation, 0);++ // Two more generations come and go while the consumer is stalled.+ w.force_rotate().unwrap();+ w.append(&doc("b")).unwrap();+ w.force_rotate().unwrap();+ w.append(&doc("c")).unwrap();+ drop(w);+ std::fs::remove_file(wal_path(dir.path(), 0)).unwrap();+ std::fs::remove_file(wal_path(dir.path(), 1)).unwrap();++ let after = tail_shard(dir.path(), Some(behind.cursor), 100);+ assert!(+ after.gap,+ "generation 1 was pruned unread — that is data the target will \+ never receive and it must not be silent"+ );+ assert_eq!(doc_ids(&after), vec!["+c"]);+ }++ /// A stream that has been pruned before starts at the END: its surviving+ /// files are an arbitrary recent slice, and shipping them would look like+ /// a backfill without being one.+ #[test]+ fn a_previously_pruned_stream_starts_at_the_end() {+ let dir = tempfile::tempdir().unwrap();+ let mut w = make_writer(dir.path());+ w.append(&doc("old")).unwrap();+ w.force_rotate().unwrap();+ w.append(&doc("recent")).unwrap();+ drop(w);+ std::fs::remove_file(wal_path(dir.path(), 0)).unwrap();++ let first = tail_shard(dir.path(), None, 100);+ assert!(+ first.entries.is_empty(),+ "an established index must not half-backfill; got {:?}",+ doc_ids(&first)+ );+ assert!(!first.gap);++ // …and it picks up everything from there on.+ let mut w = make_writer(dir.path());+ w.append(&doc("new")).unwrap();+ drop(w);+ let next = tail_shard(dir.path(), Some(first.cursor), 100);+ assert_eq!(doc_ids(&next), vec!["+new"]);+ }++ /// A half-written frame at the tail of the ACTIVE generation is not+ /// corruption — the writer is mid-append. Hold the boundary and pick the+ /// frame up once it is complete, rather than resyncing over it.+ #[test]+ fn a_half_written_tail_frame_is_waited_for_not_skipped() {+ let dir = tempfile::tempdir().unwrap();+ let mut w = make_writer(dir.path());+ w.append(&doc("a")).unwrap();+ drop(w);++ let path = wal_path(dir.path(), 0);+ let good = std::fs::read(&path).unwrap();+ // Append a plausible but incomplete frame header.+ let mut torn = good.clone();+ torn.extend_from_slice(&[0u8; 8]);+ std::fs::write(&path, &torn).unwrap();++ let tail = tail_shard(dir.path(), None, 100);+ assert_eq!(doc_ids(&tail), vec!["+a"]);+ assert!(!tail.cursor.drained);+ assert_eq!(tail.corrupt_skipped, 0, "a torn tail is not corruption");+ assert_eq!(tail.cursor.offset as usize, good.len());+ }++ /// A cursor from a stream that no longer exists — an index deleted and+ /// recreated under the same name — must not stall the consumer forever.+ /// Restart from the beginning and flag it.+ #[test]+ fn a_cursor_past_every_generation_restarts_instead_of_stalling() {+ let dir = tempfile::tempdir().unwrap();+ let mut w = make_writer(dir.path());+ w.append(&doc("fresh")).unwrap();+ drop(w);++ let stale = WalTailCursor {+ generation: 42,+ offset: 9_000,+ drained: false,+ };+ let tail = tail_shard(dir.path(), Some(stale), 100);+ assert_eq!(doc_ids(&tail), vec!["+fresh"]);+ assert!(+ tail.gap,+ "a rolled-back stream is a reportable discontinuity"+ );+ assert_eq!(tail.cursor.generation, 0);+ }++ /// Both WAL layouts are discovered: legacy `*.wal` in the root, and the+ /// sharded `s0`/`s1`/… subdirectories.+ #[test]+ fn shard_dirs_cover_both_layouts() {+ let root = tempfile::tempdir().unwrap();+ let legacy = root.path().join("legacy");+ make_writer(&legacy).append(&doc("a")).unwrap();+ assert_eq!(+ wal_shard_dirs(&legacy)+ .into_iter()+ .map(|(n, _)| n)+ .collect::<Vec<_>>(),+ vec![""]+ );++ let sharded = root.path().join("sharded");+ for shard in ["s0", "s1"] {+ make_writer(&sharded.join(shard)).append(&doc("a")).unwrap();+ }+ assert_eq!(+ wal_shard_dirs(&sharded)+ .into_iter()+ .map(|(n, _)| n)+ .collect::<Vec<_>>(),+ vec!["s0", "s1"]+ );+ }}diff --git a/engine/xerj.default.toml b/engine/xerj.default.tomlindex 357d61b68..0d118b0a2 100644--- a/engine/xerj.default.toml+++ b/engine/xerj.default.toml@@ -1,6 +1,6 @@# xerj Default Configuration# ============================================================-# This file sets 54 of XERJ's 105 user-facing settings to their+# This file sets 54 of XERJ's 114 user-facing settings to their# production-ready defaults, and describes the rest in comments.# Every value here IS the default, so copying this file changes# nothing until you edit it (a test enforces that). The complete@@ -501,3 +501,39 @@ format = "text"# default `info` filter). Turn on for request-level observability without# dropping the global log filter down to debug.access_log = false++# ── WAL tap: push a filtered subset of indices to an external target ──────────+# (9 settings, issue #320)+#+# One-directional, single-node, near-real-time push of selected indices to any+# ES-compatible cluster (Elasticsearch, OpenSearch, or another XERJ node). The+# wire format is `_bulk`, so the target needs nothing installed. This is NOT+# cross-cluster replication: nothing flows back, and there is no follower state+# machine.+#+# Before turning it on, three behaviours you are agreeing to:+#+# * No backfill. A new index (nothing pruned from its WAL yet) is shipped+# whole; an established one starts from the moment it is allowlisted. Seed+# the target with snapshot/restore first if it needs the existing documents.+# * At-least-once. Each action carries `version_type=external` with the WAL+# seq_no, so redelivery is a no-op on a target that honours it.+# * Retention never waits for the target. WAL generations are pruned once they+# are durable in a segment, whether or not the tap has shipped them — a slow+# remote must not be able to fill this node's disk. A tap that falls that far+# behind loses entries and reports `gaps` in GET /_xerj/wal_tap/_stats.+#+# System indices (.xerj-*) are never shipped, whatever `indices` says.+# Everything here is also settable at runtime, without a restart, via+# PUT /_xerj/wal_tap.+#+# [wal_tap]+# enabled = true # not a default (false)+# target_url = "https://central:9200" # not a default ("")+# target_auth = "ApiKey abc123" # not a default ("")+# indices = ["edge-*", "metrics"] # not a default ([])+# poll_interval_ms = 500+# max_batch_docs = 1000+# max_batch_bytes = 5242880+# request_timeout_secs = 30+# max_retry_backoff_secs = 60diff --git a/landing/docs/config.html b/landing/docs/config.htmlindex 0eeea0bd8..dfe564276 100644--- a/landing/docs/config.html+++ b/landing/docs/config.html@@ -124,7 +124,7 @@<p>Paths for the config are, in precedence order: <code class="inline">--config /path/to/xerj.toml</code> on the command line, then <code class="inline">/etc/xerj/xerj.toml</code>, then <code class="inline">./xerj.toml</code> in the working directory. If none exist, the full default is used.</p><h2>Full key table</h2>- <div class="cfg"><div class="head">KEY</div><div class="head">TYPE</div><div class="head">DEFAULT</div><div class="head">DESCRIPTION</div><div class="group" id="server">[server]</div><div class="cell k">rest_port</div><div class="cell t">u16</div><div class="cell d">8080</div><div class="cell dsc">Native REST API listener port. All native endpoints (/v1/*) live here.</div><div class="cell k">grpc_port</div><div class="cell t">u16</div><div class="cell d">8081</div><div class="cell dsc">Reserved for a future gRPC API. Not wired in v0.1 — leave at default.</div><div class="cell k">es_compat_port</div><div class="cell t">u16</div><div class="cell d">9200</div><div class="cell dsc">Elasticsearch-compatible wire port. Point Kibana, Logstash, or the ES client here. Set to 0 to disable.</div><div class="cell k">bind_address</div><div class="cell t">string</div><div class="cell d">"127.0.0.1"</div><div class="cell dsc">Interface to bind every listener to. Loopback by default, so an unconfigured node is unreachable from the network. Set "0.0.0.0" or a private address to expose it (also --bind / XERJ_BIND_ADDRESS). Must be an IPv4 or IPv6 literal — host names are not resolved, and a node given one refuses to start.</div><div class="cell k">allow_insecure_network_bind</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Permit a non-loopback bind_address while tls.enabled = false. Startup refuses that combination otherwise: every listener would serve plain HTTP, so the API key in every Authorization header crosses the network in cleartext. Set true only when a proxy, sidecar, mesh or container boundary terminates TLS in front of the node. Env: XERJ_ALLOW_INSECURE_NETWORK_BIND.</div><div class="cell k">data_dir</div><div class="cell t">path</div><div class="cell d">"./data"</div><div class="cell dsc">Root for indices, WAL files, and segments. Needs fast I/O and enough free space.</div><div class="group" id="auth">[auth]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Require an API key on every request. Set to false only on a trusted network.</div><div class="cell k">admin_api_key</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Static admin key. Left empty, a 256-bit key is generated on first run and written to <data_dir>/admin.key.</div><div class="group" id="tls">[tls]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Terminate TLS at the server. Requires cert_path + key_path. If you terminate at a proxy, leave false.</div><div class="cell k">cert_path</div><div class="cell t">path</div><div class="cell d">""</div><div class="cell dsc">PEM X.509 certificate. Use a CA-signed cert in production.</div><div class="cell k">key_path</div><div class="cell t">path</div><div class="cell d">""</div><div class="cell dsc">PEM private key. Permissions should be 0600.</div><div class="group" id="storage">[storage]</div><div class="cell k">wal_sync</div><div class="cell t">enum</div><div class="cell d">"batched"</div><div class="cell dsc">"sync" · "batched" · "async". Durability vs throughput. Batched is the recommended default.</div><div class="cell k">wal_batch_ms</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Fsync cadence when wal_sync="batched" (ms). Range 1–10000. Lower = smaller loss window.</div><div class="cell k">wal_max_size_mb</div><div class="cell t">u32</div><div class="cell d">1024</div><div class="cell dsc">WAL rollover threshold (MiB). Larger means fewer rollovers, longer crash recovery.</div><div class="cell k">flush_size_mb</div><div class="cell t">u32</div><div class="cell d">512</div><div class="cell dsc">Memtable buffer size that triggers a segment flush (MiB).</div><div class="cell k">flush_interval_secs</div><div class="cell t">u32</div><div class="cell d">30</div><div class="cell dsc">Maximum wall-clock interval between flushes even if the buffer is not full.</div><div class="group" id="merge">[merge]</div><div class="cell k">strategy</div><div class="cell t">enum</div><div class="cell d">"size_tiered"</div><div class="cell dsc">Only "size_tiered" is implemented; "log_structured" is refused at startup rather than silently running the other policy.</div><div class="cell k">min_segments</div><div class="cell t">u32</div><div class="cell d">10</div><div class="cell dsc">Accepted and validated (must be ≥ 2) but <strong>not wired</strong>: the merge trigger is per-tier and comes from min_merge_count. Setting it away from the default logs a warning at startup.</div><div class="cell k">max_segment_mb</div><div class="cell t">u32</div><div class="cell d">8192</div><div class="cell dsc">Upper bound on a mergeable segment (MiB). Segments at or above this size are never merged again.</div><div class="cell k">io_rate_mb_per_sec</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Accepted but <strong>not wired</strong>: merge I/O is not throttled in this build — the rate limiter that honours it sits in an unused storage-crate merge executor. Setting it away from the default logs a warning at startup.</div><div class="cell k">max_concurrent</div><div class="cell t">u8</div><div class="cell d">1</div><div class="cell dsc">Accepted but <strong>not wired</strong>: merge parallelism comes from the XERJ_MERGE_PARALLELISM environment variable, which also defaults to 1. Setting it away from the default logs a warning at startup.</div><div class="group" id="compression">[compression]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Accepted but <strong>not wired</strong>: every durable artifact is a compressed envelope with no uncompressed write path, so false changes nothing on disk. Setting it away from the default logs a warning at startup.</div><div class="cell k">level</div><div class="cell t">enum</div><div class="cell d">"balanced"</div><div class="cell dsc">"fast" (Zstd L1), "balanced" (Zstd L3, default), "best" (Zstd L6, cold storage). Applied when segments are re-encoded <strong>at merge</strong>; flush always writes L3, because raising the flush level collapses sustained ingest. Force-merge to apply a change to data already on disk.</div><div class="cell k">block_size_docs</div><div class="cell t">u32</div><div class="cell d">128</div><div class="cell dsc">Accepted but <strong>not wired</strong>: the stored codec is columnar over the whole segment section, not blocked by document count. Range 16–4096 is enforced at startup, and a non-default value logs a warning.</div><div class="group" id="fts">[fts]</div><div class="cell k">default_analyzer</div><div class="cell t">enum</div><div class="cell d">"standard"</div><div class="cell dsc">"standard" · "whitespace" · "simple" · "english". Override per-field in the mapping.</div><div class="group" id="vector">[vector]</div><div class="cell k">default_metric</div><div class="cell t">enum</div><div class="cell d">"cosine"</div><div class="cell dsc">"cosine" · "dot_product" · "euclidean". Cosine for text embeddings is the usual choice.</div><div class="cell k">hnsw_m</div><div class="cell t">u32</div><div class="cell d">16</div><div class="cell dsc">Accepted and validated; the built-in HNSW graph currently builds with fixed M=16 — this key is not yet wired to the build.</div><div class="cell k">hnsw_ef_construction</div><div class="cell t">u32</div><div class="cell d">200</div><div class="cell dsc">Accepted; must be ≥ hnsw_m. The graph currently builds with fixed ef_construction=200 — this key is not yet wired to the build.</div><div class="cell k">hnsw_ef_search</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Accepted but not read by the serving path — the ANN beam width comes from the request's num_candidates (floored at 800).</div><div class="cell k">default_quantization</div><div class="cell t">enum</div><div class="cell d">"none"</div><div class="cell dsc">"none" (the default) or "scalar8" = 4× RAM saving, 1–2% recall loss. "binary" has no quantizer behind it and is refused at startup rather than silently stored at full precision; "scalar4" is not a value this key accepts at all (the 4-bit quantizer in the vector crate is unreachable from config or mapping).</div><div class="cell k">max_dimensions</div><div class="cell t">u32</div><div class="cell d">16384</div><div class="cell dsc">Upper bound on vector dimensionality. 4× the Elasticsearch limit of 4096.</div><div class="group" id="logs">[logs]</div><div class="cell k">retention_days</div><div class="cell t">u32</div><div class="cell d">90</div><div class="cell dsc">Auto-delete log docs older than N days. 0 disables.</div><div class="cell k">time_partition</div><div class="cell t">enum</div><div class="cell d">"1h"</div><div class="cell dsc">"1m" · "5m" · "15m" · "1h" · "6h" · "1d". Time-slice granularity for retention pruning.</div><div class="group" id="embedding">[embedding]</div><div class="cell k">default_endpoint</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">OpenAI-compatible embeddings URL. Empty disables auto-embedding on ingest. Example: "https://api.openai.com/v1/embeddings".</div><div class="cell k">default_model</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Model name passed to the endpoint. Example: "text-embedding-3-small" or "nomic-embed-text".</div><div class="cell k">batch_size</div><div class="cell t">u32</div><div class="cell d">64</div><div class="cell dsc">Docs per embedding API call. Range 1–2048. Bigger batches amortise round-trip cost.</div><div class="cell k">timeout_ms</div><div class="cell t">u32</div><div class="cell d">5000</div><div class="cell dsc">HTTP timeout for embedding calls (ms). Ingest fails with a timeout error if exceeded.</div><div class="group" id="limits">[limits]</div><div class="cell k">max_query_memory_mb</div><div class="cell t">u32</div><div class="cell d">512</div><div class="cell dsc">Per-query memory cap (MiB). Queries that exceed it are cancelled.</div><div class="cell k">max_concurrent_searches</div><div class="cell t">u32</div><div class="cell d">64</div><div class="cell dsc">Global in-flight search ceiling. Extras are queued.</div><div class="cell k">max_fields_per_index</div><div class="cell t">u32</div><div class="cell d">500</div><div class="cell dsc">Field-explosion protection. ES default is 1000; 500 is intentionally stricter.</div><div class="group" id="indexing">[indexing]</div><div class="cell k">turbo_batch_size</div><div class="cell t">u32</div><div class="cell d">1000</div><div class="cell dsc">Docs per batch in turbo mode. Range 500–5000. Larger = higher throughput, slightly higher latency.</div><div class="cell k">turbo_parallel</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Parallel tokenisation on Rayon threads. Disable only for debugging.</div><div class="cell k">turbo_fast_analyzer</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Skip stemming and stop-word removal in turbo mode. Trades recall for speed.</div><div class="group" id="cluster">[cluster]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Enable multi-node cluster mode. When true, the Raft state machine and cluster transport are started on port.</div><div class="cell k">port</div><div class="cell t">u16</div><div class="cell d">9300</div><div class="cell dsc">TCP port for intra-cluster Raft and search messages. Must be reachable from every peer.</div><div class="cell k">peers</div><div class="cell t">array</div><div class="cell d">[]</div><div class="cell dsc">Peer list in "node_id=host:port" format. The local node identifies itself from the entry matching bind_address:port. Example: ["a=10.0.0.1:9300","b=10.0.0.2:9300","c=10.0.0.3:9300"].</div><div class="cell k">tick_ms</div><div class="cell t">u64</div><div class="cell d">50</div><div class="cell dsc">Raft tick interval (ms). Lower = faster leader election at the cost of CPU.</div><div class="cell k">auth_secret</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Cluster-wide shared secret authenticating every control frame on port (HMAC-SHA256 over a per-connection challenge). Mandatory when enabled = true — with cluster mode on and no secret here or in XERJ_CLUSTER_AUTH_SECRET the node refuses to start. Same value on every node; minimum 16 chars; generate with `openssl rand -hex 32`. Authenticates, does not encrypt.</div></div>+ <div class="cfg"><div class="head">KEY</div><div class="head">TYPE</div><div class="head">DEFAULT</div><div class="head">DESCRIPTION</div><div class="group" id="server">[server]</div><div class="cell k">rest_port</div><div class="cell t">u16</div><div class="cell d">8080</div><div class="cell dsc">Native REST API listener port. All native endpoints (/v1/*) live here.</div><div class="cell k">grpc_port</div><div class="cell t">u16</div><div class="cell d">8081</div><div class="cell dsc">Reserved for a future gRPC API. Not wired in v0.1 — leave at default.</div><div class="cell k">es_compat_port</div><div class="cell t">u16</div><div class="cell d">9200</div><div class="cell dsc">Elasticsearch-compatible wire port. Point Kibana, Logstash, or the ES client here. Set to 0 to disable.</div><div class="cell k">bind_address</div><div class="cell t">string</div><div class="cell d">"127.0.0.1"</div><div class="cell dsc">Interface to bind every listener to. Loopback by default, so an unconfigured node is unreachable from the network. Set "0.0.0.0" or a private address to expose it (also --bind / XERJ_BIND_ADDRESS). Must be an IPv4 or IPv6 literal — host names are not resolved, and a node given one refuses to start.</div><div class="cell k">allow_insecure_network_bind</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Permit a non-loopback bind_address while tls.enabled = false. Startup refuses that combination otherwise: every listener would serve plain HTTP, so the API key in every Authorization header crosses the network in cleartext. Set true only when a proxy, sidecar, mesh or container boundary terminates TLS in front of the node. Env: XERJ_ALLOW_INSECURE_NETWORK_BIND.</div><div class="cell k">data_dir</div><div class="cell t">path</div><div class="cell d">"./data"</div><div class="cell dsc">Root for indices, WAL files, and segments. Needs fast I/O and enough free space.</div><div class="group" id="auth">[auth]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Require an API key on every request. Set to false only on a trusted network.</div><div class="cell k">admin_api_key</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Static admin key. Left empty, a 256-bit key is generated on first run and written to <data_dir>/admin.key.</div><div class="group" id="tls">[tls]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Terminate TLS at the server. Requires cert_path + key_path. If you terminate at a proxy, leave false.</div><div class="cell k">cert_path</div><div class="cell t">path</div><div class="cell d">""</div><div class="cell dsc">PEM X.509 certificate. Use a CA-signed cert in production.</div><div class="cell k">key_path</div><div class="cell t">path</div><div class="cell d">""</div><div class="cell dsc">PEM private key. Permissions should be 0600.</div><div class="group" id="storage">[storage]</div><div class="cell k">wal_sync</div><div class="cell t">enum</div><div class="cell d">"batched"</div><div class="cell dsc">"sync" · "batched" · "async". Durability vs throughput. Batched is the recommended default.</div><div class="cell k">wal_batch_ms</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Fsync cadence when wal_sync="batched" (ms). Range 1–10000. Lower = smaller loss window.</div><div class="cell k">wal_max_size_mb</div><div class="cell t">u32</div><div class="cell d">1024</div><div class="cell dsc">WAL rollover threshold (MiB). Larger means fewer rollovers, longer crash recovery.</div><div class="cell k">flush_size_mb</div><div class="cell t">u32</div><div class="cell d">512</div><div class="cell dsc">Memtable buffer size that triggers a segment flush (MiB).</div><div class="cell k">flush_interval_secs</div><div class="cell t">u32</div><div class="cell d">30</div><div class="cell dsc">Maximum wall-clock interval between flushes even if the buffer is not full.</div><div class="group" id="merge">[merge]</div><div class="cell k">strategy</div><div class="cell t">enum</div><div class="cell d">"size_tiered"</div><div class="cell dsc">Only "size_tiered" is implemented; "log_structured" is refused at startup rather than silently running the other policy.</div><div class="cell k">min_segments</div><div class="cell t">u32</div><div class="cell d">10</div><div class="cell dsc">Accepted and validated (must be ≥ 2) but <strong>not wired</strong>: the merge trigger is per-tier and comes from min_merge_count. Setting it away from the default logs a warning at startup.</div><div class="cell k">max_segment_mb</div><div class="cell t">u32</div><div class="cell d">8192</div><div class="cell dsc">Upper bound on a mergeable segment (MiB). Segments at or above this size are never merged again.</div><div class="cell k">io_rate_mb_per_sec</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Accepted but <strong>not wired</strong>: merge I/O is not throttled in this build — the rate limiter that honours it sits in an unused storage-crate merge executor. Setting it away from the default logs a warning at startup.</div><div class="cell k">max_concurrent</div><div class="cell t">u8</div><div class="cell d">1</div><div class="cell dsc">Accepted but <strong>not wired</strong>: merge parallelism comes from the XERJ_MERGE_PARALLELISM environment variable, which also defaults to 1. Setting it away from the default logs a warning at startup.</div><div class="group" id="compression">[compression]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Accepted but <strong>not wired</strong>: every durable artifact is a compressed envelope with no uncompressed write path, so false changes nothing on disk. Setting it away from the default logs a warning at startup.</div><div class="cell k">level</div><div class="cell t">enum</div><div class="cell d">"balanced"</div><div class="cell dsc">"fast" (Zstd L1), "balanced" (Zstd L3, default), "best" (Zstd L6, cold storage). Applied when segments are re-encoded <strong>at merge</strong>; flush always writes L3, because raising the flush level collapses sustained ingest. Force-merge to apply a change to data already on disk.</div><div class="cell k">block_size_docs</div><div class="cell t">u32</div><div class="cell d">128</div><div class="cell dsc">Accepted but <strong>not wired</strong>: the stored codec is columnar over the whole segment section, not blocked by document count. Range 16–4096 is enforced at startup, and a non-default value logs a warning.</div><div class="group" id="fts">[fts]</div><div class="cell k">default_analyzer</div><div class="cell t">enum</div><div class="cell d">"standard"</div><div class="cell dsc">"standard" · "whitespace" · "simple" · "english". Override per-field in the mapping.</div><div class="group" id="vector">[vector]</div><div class="cell k">default_metric</div><div class="cell t">enum</div><div class="cell d">"cosine"</div><div class="cell dsc">"cosine" · "dot_product" · "euclidean". Cosine for text embeddings is the usual choice.</div><div class="cell k">hnsw_m</div><div class="cell t">u32</div><div class="cell d">16</div><div class="cell dsc">Accepted and validated; the built-in HNSW graph currently builds with fixed M=16 — this key is not yet wired to the build.</div><div class="cell k">hnsw_ef_construction</div><div class="cell t">u32</div><div class="cell d">200</div><div class="cell dsc">Accepted; must be ≥ hnsw_m. The graph currently builds with fixed ef_construction=200 — this key is not yet wired to the build.</div><div class="cell k">hnsw_ef_search</div><div class="cell t">u32</div><div class="cell d">100</div><div class="cell dsc">Accepted but not read by the serving path — the ANN beam width comes from the request's num_candidates (floored at 800).</div><div class="cell k">default_quantization</div><div class="cell t">enum</div><div class="cell d">"none"</div><div class="cell dsc">"none" (the default) or "scalar8" = 4× RAM saving, 1–2% recall loss. "binary" has no quantizer behind it and is refused at startup rather than silently stored at full precision; "scalar4" is not a value this key accepts at all (the 4-bit quantizer in the vector crate is unreachable from config or mapping).</div><div class="cell k">max_dimensions</div><div class="cell t">u32</div><div class="cell d">16384</div><div class="cell dsc">Upper bound on vector dimensionality. 4× the Elasticsearch limit of 4096.</div><div class="group" id="logs">[logs]</div><div class="cell k">retention_days</div><div class="cell t">u32</div><div class="cell d">90</div><div class="cell dsc">Auto-delete log docs older than N days. 0 disables.</div><div class="cell k">time_partition</div><div class="cell t">enum</div><div class="cell d">"1h"</div><div class="cell dsc">"1m" · "5m" · "15m" · "1h" · "6h" · "1d". Time-slice granularity for retention pruning.</div><div class="group" id="embedding">[embedding]</div><div class="cell k">default_endpoint</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">OpenAI-compatible embeddings URL. Empty disables auto-embedding on ingest. Example: "https://api.openai.com/v1/embeddings".</div><div class="cell k">default_model</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Model name passed to the endpoint. Example: "text-embedding-3-small" or "nomic-embed-text".</div><div class="cell k">batch_size</div><div class="cell t">u32</div><div class="cell d">64</div><div class="cell dsc">Docs per embedding API call. Range 1–2048. Bigger batches amortise round-trip cost.</div><div class="cell k">timeout_ms</div><div class="cell t">u32</div><div class="cell d">5000</div><div class="cell dsc">HTTP timeout for embedding calls (ms). Ingest fails with a timeout error if exceeded.</div><div class="group" id="limits">[limits]</div><div class="cell k">max_query_memory_mb</div><div class="cell t">u32</div><div class="cell d">512</div><div class="cell dsc">Per-query memory cap (MiB). Queries that exceed it are cancelled.</div><div class="cell k">max_concurrent_searches</div><div class="cell t">u32</div><div class="cell d">64</div><div class="cell dsc">Global in-flight search ceiling. Extras are queued.</div><div class="cell k">max_fields_per_index</div><div class="cell t">u32</div><div class="cell d">500</div><div class="cell dsc">Field-explosion protection. ES default is 1000; 500 is intentionally stricter.</div><div class="group" id="indexing">[indexing]</div><div class="cell k">turbo_batch_size</div><div class="cell t">u32</div><div class="cell d">1000</div><div class="cell dsc">Docs per batch in turbo mode. Range 500–5000. Larger = higher throughput, slightly higher latency.</div><div class="cell k">turbo_parallel</div><div class="cell t">bool</div><div class="cell d">true</div><div class="cell dsc">Parallel tokenisation on Rayon threads. Disable only for debugging.</div><div class="cell k">turbo_fast_analyzer</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Skip stemming and stop-word removal in turbo mode. Trades recall for speed.</div><div class="group" id="cluster">[cluster]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Enable multi-node cluster mode. When true, the Raft state machine and cluster transport are started on port.</div><div class="cell k">port</div><div class="cell t">u16</div><div class="cell d">9300</div><div class="cell dsc">TCP port for intra-cluster Raft and search messages. Must be reachable from every peer.</div><div class="cell k">peers</div><div class="cell t">array</div><div class="cell d">[]</div><div class="cell dsc">Peer list in "node_id=host:port" format. The local node identifies itself from the entry matching bind_address:port. Example: ["a=10.0.0.1:9300","b=10.0.0.2:9300","c=10.0.0.3:9300"].</div><div class="cell k">tick_ms</div><div class="cell t">u64</div><div class="cell d">50</div><div class="cell dsc">Raft tick interval (ms). Lower = faster leader election at the cost of CPU.</div><div class="cell k">auth_secret</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Cluster-wide shared secret authenticating every control frame on port (HMAC-SHA256 over a per-connection challenge). Mandatory when enabled = true — with cluster mode on and no secret here or in XERJ_CLUSTER_AUTH_SECRET the node refuses to start. Same value on every node; minimum 16 chars; generate with `openssl rand -hex 32`. Authenticates, does not encrypt.</div><div class="group" id="wal_tap">[wal_tap]</div><div class="cell k">enabled</div><div class="cell t">bool</div><div class="cell d">false</div><div class="cell dsc">Push a filtered subset of indices to an external ES-compatible target (Elasticsearch, OpenSearch, or another XERJ node) in near-real-time. One-directional and single-node — this is not cross-cluster replication. Off by default.</div><div class="cell k">target_url</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Base URL of the target cluster; the tap POSTs to {target_url}/_bulk. Example: "https://central:9200". Empty disables the tap even with enabled = true.</div><div class="cell k">target_auth</div><div class="cell t">string</div><div class="cell d">""</div><div class="cell dsc">Verbatim Authorization header for the target, e.g. "ApiKey abc123". Write-only: GET /_xerj/wal_tap reports whether one is set, never its value.</div><div class="cell k">indices</div><div class="cell t">array</div><div class="cell d">[]</div><div class="cell dsc">Index allowlist, glob patterns. Empty ships nothing; ["edge-*","metrics"] ships those. A wildcard never expands to a hidden index, and XERJ's own .xerj* system indices are never shipped whatever this says.</div><div class="cell k">poll_interval_ms</div><div class="cell t">u64</div><div class="cell d">500</div><div class="cell dsc">How often each allowlisted index's WAL is polled (ms). Range 50–60000. This is the floor on end-to-end latency; the tap adds nothing to the write path.</div><div class="cell k">max_batch_docs</div><div class="cell t">usize</div><div class="cell d">1000</div><div class="cell dsc">Maximum WAL entries read and shipped per poll, per index.</div><div class="cell k">max_batch_bytes</div><div class="cell t">usize</div><div class="cell d">5242880</div><div class="cell dsc">Maximum _bulk body size (bytes). Bounds one HTTP request against the target's http.max_content_length — a larger batch is split across requests, never truncated.</div><div class="cell k">request_timeout_secs</div><div class="cell t">u64</div><div class="cell d">30</div><div class="cell dsc">Per-request timeout against the target. A timed-out batch is retried; the cursor does not advance, so nothing is dropped.</div><div class="cell k">max_retry_backoff_secs</div><div class="cell t">u64</div><div class="cell d">60</div><div class="cell dsc">Ceiling on the exponential, jittered retry backoff when the target is down. WAL retention never waits for the target, so a tap that falls far enough behind loses entries and reports them as gaps in GET /_xerj/wal_tap/_stats.</div></div><h2 id="server-section">[server]</h2>diff --git a/scripts/verify-wal-tap.sh b/scripts/verify-wal-tap.shnew file mode 100755index 000000000..ed7004ed4--- /dev/null+++ b/scripts/verify-wal-tap.sh@@ -0,0 +1,138 @@+#!/usr/bin/env bash+# End-to-end proof of the single-node WAL tap (issue #320), with two real xerj+# nodes rather than a stub: documents written to the source must appear on the+# target within a poll interval, filtered by the allowlist, with deletes+# propagating and system indices never leaving the node.+#+# The unit and integration coverage lives in+# engine/crates/xerj-storage/src/wal.rs (tail/cursor/gap) and+# engine/crates/xerj-engine/tests/wal_tap_push.rs (push semantics). This script+# is the one that proves the whole path over real HTTP.+#+# cargo build --release -p xerj-server+# scripts/verify-wal-tap.sh engine/target/release/xerj+set -uo pipefail++BIN="${1:?usage: verify-wal-tap.sh <path-to-xerj-binary>}"+ROOT="$(mktemp -d /tmp/i320-verify.XXXXXX)"+SRC=9350+DST=9360+FAIL=0++cleanup() {+ [[ -n "${SRC_PID:-}" ]] && kill "$SRC_PID" 2>/dev/null+ [[ -n "${DST_PID:-}" ]] && kill "$DST_PID" 2>/dev/null+ wait 2>/dev/null+}+trap cleanup EXIT++check() { # check <label> <expected> <actual>+ if [[ "$2" == "$3" ]]; then echo " PASS $1"; else+ echo " FAIL $1: expected [$2], got [$3]"; FAIL=1+ fi+}++mkdir -p "$ROOT/source/data" "$ROOT/target/data"+cat > "$ROOT/target/xerj.toml" <<EOF+[server]+es_compat_port = $DST+rest_port = 9361+grpc_port = 9362+data_dir = "$ROOT/target/data"+bind_address = "127.0.0.1"+[auth]+enabled = false+EOF+cat > "$ROOT/source/xerj.toml" <<EOF+[server]+es_compat_port = $SRC+rest_port = 9351+grpc_port = 9352+data_dir = "$ROOT/source/data"+bind_address = "127.0.0.1"+[auth]+enabled = false++[wal_tap]+enabled = true+target_url = "http://127.0.0.1:$DST"+indices = ["edge-*"]+poll_interval_ms = 200+EOF++"$BIN" --config "$ROOT/target/xerj.toml" > "$ROOT/target.log" 2>&1 &+DST_PID=$!+"$BIN" --config "$ROOT/source/xerj.toml" > "$ROOT/source.log" 2>&1 &+SRC_PID=$!+for port in $SRC $DST; do+ for _ in $(seq 1 60); do+ curl -sf -m 2 "http://127.0.0.1:$port/_cluster/health" >/dev/null && break+ sleep 1+ done+done+echo "== source :$SRC (tap on, allowlist edge-*) -> target :$DST | logs in $ROOT"++count() { curl -s "http://127.0.0.1:$1/$2/_count" | sed -n 's/.*"count":\([0-9]*\).*/\1/p'; }++# ── 1. an allowlisted index flows ───────────────────────────────────────────+for i in 1 2 3; do+ curl -s -XPUT "http://127.0.0.1:$SRC/edge-logs/_doc/$i" \+ -H 'Content-Type: application/json' -d "{\"msg\":\"hello $i\"}" >/dev/null+done+# ── 2. a non-allowlisted index must not ─────────────────────────────────────+curl -s -XPUT "http://127.0.0.1:$SRC/orders/_doc/o1" \+ -H 'Content-Type: application/json' -d '{"total":42}' >/dev/null++sleep 3+curl -s -XPOST "http://127.0.0.1:$DST/edge-logs/_refresh" >/dev/null+echo+echo "-- push"+check "3 docs reached the target" "3" "$(count $DST edge-logs)"+check "a non-allowlisted index did not" "" "$(count $DST orders)"++# ── 3. deletes travel ───────────────────────────────────────────────────────+curl -s -XDELETE "http://127.0.0.1:$SRC/edge-logs/_doc/2" >/dev/null+sleep 3+curl -s -XPOST "http://127.0.0.1:$DST/edge-logs/_refresh" >/dev/null+check "a delete propagated" "2" "$(count $DST edge-logs)"++# ── 4. system indices never leave ───────────────────────────────────────────+echo+echo "-- system indices"+sys_on_target=$(curl -s "http://127.0.0.1:$DST/_cat/indices?h=index" | grep -c '^\.xerj' || true)+sys_bootstrapped=$(curl -s "http://127.0.0.1:$DST/_cat/indices?h=index" | grep '^\.xerj' | wc -l)+echo " (the target bootstraps its own $sys_bootstrapped system indices; the test is \+whether the SOURCE's docs are in them)"+check "no source doc landed in a target system index" "0" \+ "$(curl -s "http://127.0.0.1:$DST/.xerj_users/_count" | sed -n 's/.*"count":\([0-9]*\).*/\1/p')"++# ── 5. the runtime REST surface ─────────────────────────────────────────────+echo+echo "-- REST surface"+cfg=$(curl -s "http://127.0.0.1:$SRC/_xerj/wal_tap")+echo " GET /_xerj/wal_tap -> $cfg"+check "the credential is never echoed back" "0" "$(grep -c 'target_auth"' <<<"$cfg")"++curl -s -XPUT "http://127.0.0.1:$SRC/_xerj/wal_tap" -H 'Content-Type: application/json' \+ -d '{"indices":["edge-*","metrics"]}' >/dev/null+curl -s -XPUT "http://127.0.0.1:$SRC/metrics/_doc/m1" \+ -H 'Content-Type: application/json' -d '{"cpu":0.5}' >/dev/null+sleep 3+curl -s -XPOST "http://127.0.0.1:$DST/metrics/_refresh" >/dev/null+check "an index added at runtime starts shipping" "1" "$(count $DST metrics)"++bad=$(curl -s -o /dev/null -w "%{http_code}" -XPUT "http://127.0.0.1:$SRC/_xerj/wal_tap" \+ -H 'Content-Type: application/json' -d '{"indices":[".xerj_users"]}')+check "a system-index pattern is refused" "400" "$bad"++echo+echo "-- stats"+curl -s "http://127.0.0.1:$SRC/_xerj/wal_tap/_stats" | head -c 900; echo++gaps=$(curl -s "http://127.0.0.1:$SRC/_xerj/wal_tap/_stats" | grep -o '"gaps":[0-9]*' | \+ awk -F: '{s+=$2} END {print s+0}')+check "no gaps under a keeping-up tap" "0" "$gaps"++echo+[[ $FAIL -eq 0 ]] && echo "== ALL CHECKS PASSED" || echo "== FAILURES PRESENT"+exit $FAIL