Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(engine): idle-age flush — a small memtable reaches a segment (#873) (#878)

xerj-org6936d8268578
diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rs
index 4158ecbd1..1ab2996b8 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: **116 settings** versus
+//! Configuration is intentionally minimal: **117 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.
//!
@@ -97,7 +97,7 @@ pub struct Config {
pub wal_tap: WalTapConfig,
}
-// 21 sub-configs, 116 leaf settings in total. Do not maintain that sum by hand
+// 21 sub-configs, 117 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
@@ -436,7 +436,7 @@ impl Config {
}
// ═════════════════════════════════════════════════════════════════════════════
-// Sub-configs (116 user-facing settings total; counted by
+// Sub-configs (117 user-facing settings total; counted by
// `journey_zero_config`, not by hand)
// ═════════════════════════════════════════════════════════════════════════════
@@ -725,7 +725,7 @@ pub struct TlsConfig {
/// Write-ahead log, flush, and object-store settings.
///
-/// **10 settings** (5 WAL/flush + 5 object-store).
+/// **11 settings** (6 WAL/flush + 5 object-store).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct StorageConfig {
@@ -761,6 +761,18 @@ pub struct StorageConfig {
pub flush_size_mb: u64,
/// Maximum time between flushes regardless of buffer size (default: `30` s).
pub flush_interval_secs: u64,
+ /// #873: flush a NON-EMPTY memtable whose contents have not changed for
+ /// this many seconds, regardless of size (default: `300` s; `0` disables).
+ /// Without it a dataset below the size thresholds never reached a
+ /// segment: its documents stayed memtable-resident for the process
+ /// lifetime, pinned their WAL generations, and replayed on every boot —
+ /// measured at 100,001 docs held in RAM 30+ minutes after ingest on an
+ /// idle node. 300 s matches Elasticsearch's
+ /// `indices.memory.shard_inactive_time` default. Detection is a probe on
+ /// the periodic flusher (`flush_interval_secs`), so worst-case latency is
+ /// `flush_idle_secs + flush_interval_secs` and the write path pays
+ /// nothing.
+ pub flush_idle_secs: u64,
// ── Object-store backend (compute-storage separation) ─────────────────────
/// Storage backend: `"local"` or `"s3"` (default: `"local"`).
@@ -790,6 +802,7 @@ impl Default for StorageConfig {
wal_max_size_mb: 1024,
flush_size_mb: 512,
flush_interval_secs: 30,
+ flush_idle_secs: 300,
backend: StorageBackendType::Local,
s3_bucket: String::new(),
s3_prefix: "xerj/".into(),
@@ -2358,7 +2371,7 @@ mod tests {
drift.join("\n ")
);
- // …and the file's own header quotes how many of the 116 it sets. That
+ // …and the file's own header quotes how many of the 117 it sets. That
// number was 38, then 56, and never once the truth (#207), so count the
// assignments instead of trusting the sentence.
let set_here = toml_src
@@ -2795,7 +2808,7 @@ mod tests {
("auth", 3),
("cors", 2),
("tls", 4),
- ("storage", 10),
+ ("storage", 11),
("merge", 8),
("compression", 3),
("fts", 1),
@@ -2854,7 +2867,7 @@ mod tests {
"the section table must sum to the whole config"
);
assert_eq!(
- total, 116,
+ total, 117,
"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-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index ac22ff770..5a2eaa733 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -3430,6 +3430,104 @@ mod merge_publication_transaction_tests {
hand_driven_index_with_config(config(dir), name, schema)
}
+ /// #873: a non-empty memtable BELOW the size thresholds flushes once its
+ /// contents have sat unchanged for `flush_idle_secs`. Idleness is
+ /// crossed via the test rewind hook, never a sleep. Also proves the two
+ /// negative arms: a fingerprint change re-arms the timer, and
+ /// `flush_idle_secs = 0` disables the path entirely.
+ #[tokio::test]
+ async fn small_idle_memtable_flushes_by_age_not_size() {
+ let dir = TempDir::new().unwrap();
+ let mut cfg = config(&dir);
+ cfg.storage.flush_idle_secs = 5;
+ let (_engine, index) = hand_driven_index_with_config(cfg, "idle-age", Schema::empty());
+ index
+ .index_document(Some("d1".into()), serde_json::json!({"m": "tiny"}))
+ .await
+ .unwrap();
+ // Probe 1 records the fingerprint; probe 2 is unchanged but unaged.
+ assert!(!index.needs_flush().await, "first probe must only arm");
+ assert!(
+ !index.needs_flush().await,
+ "unaged idle memtable must not flush"
+ );
+ // Cross the idle threshold without sleeping.
+ index.rewind_idle_probe_for_test(6_000);
+ assert!(index.needs_flush().await, "aged idle memtable must flush");
+ // A write re-arms: fingerprint changes, timer restarts.
+ index
+ .index_document(Some("d2".into()), serde_json::json!({"m": "tiny2"}))
+ .await
+ .unwrap();
+ assert!(
+ !index.needs_flush().await,
+ "activity must re-arm the idle timer"
+ );
+ index.rewind_idle_probe_for_test(6_000);
+ assert!(index.needs_flush().await);
+ // The flush the periodic sweeper would now run empties the memtable.
+ index.flush().await.unwrap();
+ assert_eq!(index.memtable_bytes(), 0, "flush must drain the memtable");
+ assert!(
+ !index.needs_flush().await,
+ "empty memtable never idle-flushes"
+ );
+
+ // The reviewer's trace on PR #878, reproduced exactly. It needs its
+ // OWN index: the collision requires the post-flush memtable to
+ // reproduce the SAME (doc_count, bytes) pair the pre-flush one had,
+ // which cannot happen above where the memtable held two docs at
+ // flush time. One doc in, aged, flushed; then one identically-shaped
+ // doc — the ordinary uniform-trickle workload (heartbeats,
+ // fixed-shape audit records, a periodic re-sync of the same batch).
+ let dir3 = TempDir::new().unwrap();
+ let mut cfg3 = config(&dir3);
+ cfg3.storage.flush_idle_secs = 5;
+ let (_e3, idx3) = hand_driven_index_with_config(cfg3, "idle-recur", Schema::empty());
+ idx3.index_document(Some("aa".into()), serde_json::json!({"m": "tiny"}))
+ .await
+ .unwrap();
+ assert!(!idx3.needs_flush().await, "arm");
+ idx3.rewind_idle_probe_for_test(6_000);
+ assert!(idx3.needs_flush().await, "ages and flushes once");
+ idx3.flush().await.unwrap();
+ assert_eq!(idx3.memtable_bytes(), 0);
+ // Same doc id, same body => same (doc_count, bytes) as before the
+ // flush. Without the drained-arm reset this matches the STALE
+ // fingerprint, skips the re-arm, and is compared against the
+ // pre-flush stamp that is already older than flush_idle_secs — so
+ // needs_flush returns true immediately and would do so on every
+ // probe forever, a flush every flush_interval_secs on an idle node.
+ idx3.index_document(Some("aa".into()), serde_json::json!({"m": "tiny"}))
+ .await
+ .unwrap();
+ assert!(
+ !idx3.needs_flush().await,
+ "a recurring fingerprint after a flush must arm a FRESH timer, not \
+ inherit the pre-flush stamp and flush on the very next probe"
+ );
+ idx3.rewind_idle_probe_for_test(6_000);
+ assert!(
+ idx3.needs_flush().await,
+ "and then ages normally from that fresh stamp"
+ );
+
+ // Disabled: 0 means the old threshold-only behaviour.
+ let dir2 = TempDir::new().unwrap();
+ let mut cfg2 = config(&dir2);
+ cfg2.storage.flush_idle_secs = 0;
+ let (_e2, idx2) = hand_driven_index_with_config(cfg2, "idle-off", Schema::empty());
+ idx2.index_document(Some("d1".into()), serde_json::json!({"m": "tiny"}))
+ .await
+ .unwrap();
+ assert!(!idx2.needs_flush().await);
+ idx2.rewind_idle_probe_for_test(600_000);
+ assert!(
+ !idx2.needs_flush().await,
+ "flush_idle_secs=0 must disable idle flush"
+ );
+ }
+
/// `hand_driven_index` for the fixture that needs a knob `config()` does
/// not set.
///
@@ -6969,6 +7067,24 @@ pub struct Index {
flush_doc_threshold: usize,
/// Byte threshold for auto-flush (from config flush_size_mb).
flush_byte_threshold: usize,
+ /// #873: seconds a non-empty memtable may sit unchanged before it is
+ /// flushed regardless of size (`storage.flush_idle_secs`; 0 = disabled).
+ /// Below the thresholds a small dataset otherwise NEVER flushed: its
+ /// documents stayed memtable-resident for the whole process lifetime and
+ /// its WAL generations replayed on every boot. Elasticsearch flushes a
+ /// shard idle past `indices.memory.shard_inactive_time` (default 5m) via
+ /// a periodic controller (IndexingMemoryController.java:76-78 →
+ /// IndexShard.flushOnIdle, IndexShard.java:2787-2790; AGPL — approach
+ /// only, implementation ours): idleness is detected by a probe, not by
+ /// stamping the write path.
+ flush_idle_secs: u64,
+ /// #873: last memtable fingerprint `needs_flush` observed (doc_count ^
+ /// rotated size). A changed fingerprint = write activity since the last
+ /// probe; an unchanged one ages toward the idle flush.
+ idle_probe_fingerprint: std::sync::atomic::AtomicU64,
+ /// #873: coarse ms timestamp (process-monotonic) of the probe that last
+ /// saw the fingerprint change.
+ idle_probe_at_ms: std::sync::atomic::AtomicU64,
/// Index-level settings (e.g. number_of_shards, number_of_replicas).
settings: Arc<RwLock<Value>>,
/// Cached schema hash for skipping schema evolution on unchanged docs.
@@ -7635,6 +7751,7 @@ impl Index {
// log workloads. Both are env-overridable — see resolve_flush_thresholds.
let (flush_doc_threshold, flush_byte_threshold) =
Self::resolve_flush_thresholds(config.storage.flush_size_mb);
+ let flush_idle_secs = config.storage.flush_idle_secs;
// Warn if >1 shard requested (we only support single-shard).
if let Some(n) = settings
@@ -7720,6 +7837,9 @@ impl Index {
data_dir: index_dir,
flush_doc_threshold,
flush_byte_threshold,
+ flush_idle_secs,
+ idle_probe_fingerprint: std::sync::atomic::AtomicU64::new(0),
+ idle_probe_at_ms: std::sync::atomic::AtomicU64::new(0),
settings: Arc::new(RwLock::new(settings)),
schema_hash_cache: Arc::new(std::sync::atomic::AtomicU64::new(0)),
schema_hash_epoch: Arc::new(AtomicU64::new(0)),
@@ -7987,6 +8107,7 @@ impl Index {
// See create_with_settings — doc count is a sanity cap, byte threshold drives flushes.
let (flush_doc_threshold, flush_byte_threshold) =
Self::resolve_flush_thresholds(config.storage.flush_size_mb);
+ let flush_idle_secs = config.storage.flush_idle_secs;
// Try to reload a previously-persisted HNSW snapshot. If both
// graph.bin and ids.json exist, validate, and the pinned field is
@@ -8139,6 +8260,9 @@ impl Index {
data_dir: index_dir,
flush_doc_threshold,
flush_byte_threshold,
+ flush_idle_secs,
+ idle_probe_fingerprint: std::sync::atomic::AtomicU64::new(0),
+ idle_probe_at_ms: std::sync::atomic::AtomicU64::new(0),
settings: Arc::new(RwLock::new(settings)),
schema_hash_cache: Arc::new(std::sync::atomic::AtomicU64::new(0)),
schema_hash_epoch: Arc::new(AtomicU64::new(0)),
@@ -20582,6 +20706,22 @@ impl Index {
/// Flush the memtable to a new segment on disk, then build the FTS index.
pub async fn flush(self: &Arc<Self>) -> Result<()> {
+ // #873: this flush is about to take whatever the memtable holds, so
+ // every idle-probe observation about it is stale from here on. Clear
+ // the pair at the ONE coordinator every flush path runs through
+ // (user `_flush`, the periodic sweep, a threshold-driven flush,
+ // shutdown) rather than lazily in `needs_flush`: a lazy reset only
+ // fires if a probe happens to land while the memtable is empty, and
+ // nothing schedules a probe between a flush and the next write. A
+ // write arriving first would then match the pre-flush fingerprint,
+ // skip the re-arm, and be judged against a stamp already older than
+ // `flush_idle_secs` — flushing on the very next probe, every probe,
+ // forever. The regression test walks exactly that sequence.
+ {
+ use std::sync::atomic::Ordering;
+ self.idle_probe_fingerprint.store(0, Ordering::Relaxed);
+ self.idle_probe_at_ms.store(0, Ordering::Relaxed);
+ }
let (field_configs, excluded_fts_fields, dv_skip) = {
let schema = self.schema.read().await;
(
@@ -20709,8 +20849,81 @@ impl Index {
/// Check if the memtable exceeds the configured thresholds.
pub async fn needs_flush(&self) -> bool {
+ use std::sync::atomic::Ordering;
let mem = &*self.memtable;
- mem.doc_count() >= self.flush_doc_threshold || mem.size_bytes() >= self.flush_byte_threshold
+ let docs = mem.doc_count();
+ let bytes = mem.size_bytes();
+ if docs >= self.flush_doc_threshold || bytes >= self.flush_byte_threshold {
+ return true;
+ }
+ // #873: idle-age flush. The periodic flusher probes every index on
+ // `flush_interval_secs`; a non-empty memtable whose fingerprint has
+ // not changed for `flush_idle_secs` flushes regardless of size, so a
+ // small dataset reaches a segment, releases its WAL generations, and
+ // stops replaying on every boot. Observing change here keeps the
+ // write hot path untouched — the ES-controller shape, not per-write
+ // stamping. A fingerprint collision (delete+insert of identical
+ // sizes inside one probe interval) at worst flushes an active index
+ // once, which is always safe.
+ if self.flush_idle_secs == 0 {
+ return false;
+ }
+ if docs == 0 {
+ // An empty memtable is not idle, it is done — and leaving the
+ // previous fingerprint standing here is a live defect, not a
+ // cosmetic one. After a flush drains the memtable, a later write
+ // that happens to reproduce the same (doc_count, bytes) pair —
+ // a uniform trickle of fixed-shape records is the ordinary case,
+ // not a contrived one — would match the stale `seen`, skip the
+ // re-arm, and be compared against a timestamp already older than
+ // `flush_idle_secs`. The very next probe would then flush, and
+ // the state would return here unchanged: a stable 10x-cadence
+ // loop (a flush every `flush_interval_secs`) on a node the
+ // operator believes is idle, which is precisely the background
+ // churn this change exists to remove. Clearing the pair makes
+ // the next write arm fresh.
+ self.idle_probe_fingerprint.store(0, Ordering::Relaxed);
+ self.idle_probe_at_ms.store(0, Ordering::Relaxed);
+ return false;
+ }
+ let fp = (docs as u64) ^ (bytes as u64).rotate_left(32);
+ let now = Self::coarse_now_ms();
+ let seen = self.idle_probe_fingerprint.load(Ordering::Relaxed);
+ let seen_at = self.idle_probe_at_ms.load(Ordering::Relaxed);
+ // `fp` is never 0 for a non-empty memtable (its low 32 bits are the
+ // doc count), so a cleared pair — initial state, or reset by the
+ // drained arm above — always mismatches and arms with a current
+ // stamp. That is what makes the reset above sufficient.
+ if fp != seen {
+ self.idle_probe_fingerprint.store(fp, Ordering::Relaxed);
+ self.idle_probe_at_ms.store(now, Ordering::Relaxed);
+ return false;
+ }
+ now.saturating_sub(seen_at) >= self.flush_idle_secs.saturating_mul(1000)
+ }
+
+ /// Milliseconds since the first call — a process-monotonic coarse clock
+ /// for the idle probe (wall-clock jumps cannot move it backwards).
+ fn coarse_now_ms() -> u64 {
+ static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
+ // Based a day up so early-process probes have room below them — the
+ // test rewind hook subtracts, and a floor at 0 near process start
+ // would silently pin the stamp instead of aging it.
+ 86_400_000
+ + START
+ .get_or_init(std::time::Instant::now)
+ .elapsed()
+ .as_millis() as u64
+ }
+
+ /// #873 test hook: rewind the idle probe so a test can cross
+ /// `flush_idle_secs` without sleeping.
+ #[cfg(test)]
+ pub(crate) fn rewind_idle_probe_for_test(&self, ms: u64) {
+ use std::sync::atomic::Ordering;
+ let at = self.idle_probe_at_ms.load(Ordering::Relaxed);
+ self.idle_probe_at_ms
+ .store(at.saturating_sub(ms), Ordering::Relaxed);
}
pub fn memtable_bytes(&self) -> usize {
diff --git a/engine/crates/xerj-engine/tests/product_experience.rs b/engine/crates/xerj-engine/tests/product_experience.rs
index 2f7c7ebe9..295ca8c4e 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 = 116;
+const EXPECTED_SETTINGS: usize = 117;
#[tokio::test]
async fn journey_zero_config() {
diff --git a/engine/xerj.default.toml b/engine/xerj.default.toml
index 2a2b2528c..2a8923ac5 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 116 user-facing settings to their
+# This file sets 55 of XERJ's 117 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
@@ -154,7 +154,7 @@ key_path = ""
# opt-out. Ignored entirely when enabled = false.
allow_insecure_grpc_h2c = false
-# ── Storage & WAL (5 of 10 settings) ──────────────────────────────────────────
+# ── Storage & WAL (6 of 11 settings) ──────────────────────────────────────────
[storage]
@@ -194,6 +194,16 @@ flush_size_mb = 512
# Ensures data is durable even during low-write periods.
flush_interval_secs = 30
+# Flush a NON-EMPTY memtable whose contents have not changed for this many
+# seconds, regardless of how small it is (0 disables). Without this, a dataset
+# that never reaches flush_size_mb stays in memory for the life of the process,
+# pins its WAL generations on disk, and replays them on every start — the cost
+# is largest when one node holds many small indices, which is exactly what
+# `xerj autoindex` produces. Detection rides the flush_interval_secs sweep, so
+# worst-case latency is flush_idle_secs + flush_interval_secs and writes pay
+# nothing.
+flush_idle_secs = 300
+
# ── Segment Merging (8 settings) ──────────────────────────────────────────────
#
# Three of these are DORMANT: accepted and validated, but no code path in this