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): stop a flat RSS watermark from draining forever (#1981) (#2232)

xerj-org6c0c498758c4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index df42558c8..3c163e753 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -71,6 +71,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- An idle node whose resident set sits flat at or above the memory watermark
+ no longer drains every 2 seconds for the rest of the process. The breaker
+ releases once RSS has not fallen by more than 4 MiB for 2 seconds, and does
+ not re-arm inside that band (page-sized `ri_phys_footprint` noise is not a
+ new working set); a climb past it engages again. While the breaker stays
+ engaged, drain requests double their spacing up to 15 minutes when a drain
+ does not lower RSS by more than 4 MiB. `corpus index` / `autoindex` report
+ `eta_quality=stalled` when a phase with a known total completes nothing
+ (including 0/N), and when a phase with no total has been silent for 10
+ minutes (#1981).
+
- Semantic `xerj autoindex` against `--embed-mode proxy` resumes after a
mid-run failure and does not re-embed documents already indexed, when the
backend, configured model, endpoint, and confirmed vector width are
diff --git a/engine/crates/xerj-autoindex/src/progress.rs b/engine/crates/xerj-autoindex/src/progress.rs
index a47d628d4..76a116158 100644
--- a/engine/crates/xerj-autoindex/src/progress.rs
+++ b/engine/crates/xerj-autoindex/src/progress.rs
@@ -89,8 +89,19 @@ use std::time::{Duration, Instant};
const EWMA_ALPHA: f64 = 0.2;
/// No ETA until the phase has run at least this long.
const ETA_MIN_PHASE_SECS: f64 = 5.0;
-/// No ETA until this fraction of the phase is complete.
+/// No numeric ETA until this fraction of the phase is complete.
+///
+/// This gate used to also suppress [`Eta::Stalled`]. A phase sitting at 0/N
+/// (fraction 0, which is under 2%) therefore stayed `eta_quality=unknown` for
+/// as long as it hung — the 11-hour `corpus index` in #1981, journal not yet
+/// written, looked like "still starting". The fraction still blocks a numeric
+/// ETA. It does not block the stall label.
const ETA_MIN_FRACTION: f64 = 0.02;
+/// A phase with no denominator (`walk`, before the tree is counted) has
+/// nothing to increment, so the ordinary stall window would flag every walk
+/// longer than 15 s. Flag that shape only once the silence is far past a
+/// healthy walk. A phase that *has* a denominator uses [`Progress::stall_threshold`].
+const UNKNOWN_TOTAL_STALL: Duration = Duration::from_secs(10 * 60);
/// Below this fraction a computed ETA is labelled `rough`, not `good`.
const ETA_GOOD_FRACTION: f64 = 0.10;
/// A displayed ETA may not move by more than this fraction per tick.
@@ -762,14 +773,27 @@ impl Progress {
} else {
0.0
};
- let eta = if total == 0 || phase_elapsed < ETA_MIN_PHASE_SECS || fraction < ETA_MIN_FRACTION
- {
+ // A phase with no denominator can legitimately run with `done == 0`
+ // (the walk has not returned a count yet). One that published a
+ // denominator and then completes nothing is the hang: 0/N is still
+ // nothing completed, even though its fraction is under
+ // `ETA_MIN_FRACTION` (#1981).
+ let stall_after = if total == 0 {
+ self.stall_threshold()
+ .as_secs_f64()
+ .max(UNKNOWN_TOTAL_STALL.as_secs_f64())
+ } else {
+ self.stall_threshold().as_secs_f64()
+ };
+ let eta = if phase_elapsed < ETA_MIN_PHASE_SECS {
Eta::Unknown
- } else if since_progress > self.stall_threshold().as_secs_f64() {
+ } else if since_progress > stall_after {
// The last measurement is too old to extrapolate from. The named
// straggler below is the real answer to "what is it doing?" — an
// extrapolated number here would be pure invention.
Eta::Stalled
+ } else if total == 0 || fraction < ETA_MIN_FRACTION {
+ Eta::Unknown
} else {
match state.rate {
Some(rate) if rate > 0.0 => {
@@ -2336,6 +2360,101 @@ mod tests {
drop(big);
}
+ /// #1981: a phase that has a denominator and completes nothing — including
+ /// 0/N, whose fraction is under [`ETA_MIN_FRACTION`] — reports a stall.
+ /// The old gate forced `eta_quality=unknown` for the whole hang, which is
+ /// what an 11-hour `corpus index` (journal not yet written) looked like.
+ #[test]
+ fn a_phase_at_zero_reports_a_stall_once_nothing_completes() {
+ let (progress, buffer) = Progress::capture(Surface::Plain, Duration::from_secs(5));
+ progress.phase("index", 17448, 0);
+ {
+ let mut state = progress.state.lock().unwrap();
+ state.phase_started = Instant::now() - Duration::from_secs(120);
+ state.last_advance_at = Instant::now() - Duration::from_secs(120);
+ state.last_bar_at = Some(Instant::now() - Duration::from_secs(20));
+ }
+ progress.tick();
+ let line = captured(&buffer)
+ .lines()
+ .rev()
+ .find(|line| line.starts_with("xerj-progress "))
+ .expect("a machine line")
+ .to_string();
+ assert!(
+ line.contains("items=0/17448") && line.contains("eta_quality=stalled"),
+ "0/N past the stall window is a stall, not an unknown ETA: {line}"
+ );
+ assert!(
+ captured(&buffer).contains("no progress for"),
+ "the relayed bar must say the phase is stalled: {}",
+ captured(&buffer)
+ );
+
+ // The first seconds of a real phase are not a stall, and a phase
+ // with no denominator (the walk) is not a stall at the short window.
+ let (progress, buffer) = Progress::capture(Surface::Plain, Duration::from_secs(5));
+ progress.phase("index", 10, 0);
+ {
+ let mut state = progress.state.lock().unwrap();
+ state.phase_started = Instant::now() - Duration::from_secs(2);
+ state.last_advance_at = Instant::now() - Duration::from_secs(2);
+ }
+ progress.tick();
+ let line = captured(&buffer)
+ .lines()
+ .rev()
+ .find(|line| line.starts_with("xerj-progress "))
+ .unwrap()
+ .to_string();
+ assert!(
+ line.contains("eta_quality=unknown") && !line.contains("eta_quality=stalled"),
+ "two seconds at 0/N is still starting: {line}"
+ );
+
+ let (progress, buffer) = Progress::capture(Surface::Plain, Duration::from_secs(5));
+ progress.phase("walk", 0, 0);
+ {
+ let mut state = progress.state.lock().unwrap();
+ state.phase_started = Instant::now() - Duration::from_secs(30);
+ state.last_advance_at = Instant::now() - Duration::from_secs(30);
+ }
+ progress.tick();
+ let line = captured(&buffer)
+ .lines()
+ .rev()
+ .find(|line| line.starts_with("xerj-progress "))
+ .unwrap()
+ .to_string();
+ assert!(
+ line.contains("pct=unknown") && line.contains("eta_quality=unknown"),
+ "a 30s walk has no denominator yet and is not a stall: {line}"
+ );
+
+ // The same unknown-total phase, silent for far longer than a walk,
+ // does report the stall. That is the hang with no journal.
+ let (progress, buffer) = Progress::capture(Surface::Plain, Duration::from_secs(5));
+ progress.phase("walk", 0, 0);
+ {
+ let mut state = progress.state.lock().unwrap();
+ let silent = UNKNOWN_TOTAL_STALL + Duration::from_secs(1);
+ state.phase_started = Instant::now() - silent;
+ state.last_advance_at = Instant::now() - silent;
+ state.last_bar_at = Some(Instant::now() - Duration::from_secs(20));
+ }
+ progress.tick();
+ let line = captured(&buffer)
+ .lines()
+ .rev()
+ .find(|line| line.starts_with("xerj-progress "))
+ .unwrap()
+ .to_string();
+ assert!(
+ line.contains("eta_quality=stalled"),
+ "ten minutes with no denominator and no progress is a stall: {line}"
+ );
+ }
+
/// #2058: a hash read that has not returned for a few seconds is named even
/// when the pool still holds more files than the tail rule will list. A
/// scan or index phase with the same shape stays unnamed — that rule did
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index fb8694083..e1fd8f53f 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -30,7 +30,11 @@ use crate::{EngineError, Result};
// tier, dozens of indices under their own flush line but over the 2 GiB
// summed-memtable budget, indexed count stuck at 0). The sampler requests
// a DRAIN on either latch: flush every index, release rebuildable caches,
-// purge allocator pages.
+// purge allocator pages. The latches do not share a timer. RSS uses
+// [`crate::governor::MemoryDrainSchedule`], which doubles its spacing up to
+// 15 minutes when a drain does not lower RSS (#1981). The summed-memtable
+// latch keeps the fixed 2 s window (#2238): that flush is what lets corpus
+// index move, and a stable RSS must not stretch it.
/// Minimum spacing between automatic drains while the breaker stays engaged.
/// The engage edge always fires immediately; repeats are rate-limited so a
@@ -38,15 +42,20 @@ use crate::{EngineError, Result};
/// reads) without the drain worker competing with ingest for every tick.
const MEMORY_DRAIN_MIN_INTERVAL: std::time::Duration = std::time::Duration::from_secs(2);
-/// Whether this sampler tick should ask the drain worker to run (#948, #2238).
+/// Whether this sampler tick should ask the drain worker to run on the fixed
+/// window (#948, #2238).
///
-/// `needs_drain` is [`crate::governor::ResourceGovernor::ingest_pressure_needs_drain`]:
-/// the RSS latch or the summed-memtable latch. A memtable-only trip used to
-/// return false here, so a multi-index ingest that had filled the auto tier's
-/// 2 GiB memtable budget kept receiving HTTP 429 with nothing flushed and the
+/// The sampler passes the summed-memtable latch. A memtable-only trip used to
+/// be ignored, so a multi-index ingest that had filled the auto tier's 2 GiB
+/// memtable budget kept receiving HTTP 429 with nothing flushed and the
/// indexed count stayed at 0. The engage edge fires immediately; while the
/// latch stays up, repeats wait `min_interval`. Releasing the latch clears
/// the timer so the next engage drains at once.
+///
+/// The RSS latch does not use this function. A drain that cannot shrink RSS
+/// backs off ([`crate::governor::MemoryDrainSchedule`], #1981). Applying that
+/// backoff to the memtable latch would stall corpus index while RSS sits
+/// still, which is the normal shape of a memtable-only trip.
fn pressure_drain_due(
needs_drain: bool,
last_drain_at: &mut Option<std::time::Instant>,
@@ -67,6 +76,32 @@ fn pressure_drain_due(
due
}
+/// Whether this sample should request one drain for either parent latch.
+///
+/// RSS and the summed-memtable budget each keep their own clock. A flat RSS
+/// backs off ([`crate::governor::MemoryDrainSchedule`]); memtable pressure
+/// stays on [`MEMORY_DRAIN_MIN_INTERVAL`], including when the RSS clock is
+/// already stretched. One `true` is one request — the channel coalesces a
+/// second — so a staggered engage can ask slightly sooner than one window,
+/// and neither latch waits out the other's gap.
+fn sample_drain_due(
+ now: std::time::Instant,
+ rss: u64,
+ rss_engaged: bool,
+ memtable_engaged: bool,
+ rss_drains: &mut crate::governor::MemoryDrainSchedule,
+ last_memtable_drain_at: &mut Option<std::time::Instant>,
+) -> bool {
+ let rss_due = rss_drains.observe(now, rss, rss_engaged);
+ let memtable_due = pressure_drain_due(
+ memtable_engaged,
+ last_memtable_drain_at,
+ now,
+ MEMORY_DRAIN_MIN_INTERVAL,
+ );
+ rss_due || memtable_due
+}
+
/// Bounded request channel from the sampler thread to the drain worker.
/// Capacity 1 + try_send ⇒ requests coalesce: one arrives mid-drain is
/// dropped, and the next sampler tick re-requests if still engaged.
@@ -4381,10 +4416,16 @@ impl Engine {
period_ms = crate::governor::SAMPLE_INTERVAL_MS,
"memory/disk sampler thread started (parent circuit breaker)"
);
- // #948 drain bookkeeping: None while the breaker is
- // disengaged (so the next engage edge fires immediately),
- // Some(last-drain) while engaged (rate-limited repeats).
- let mut last_drain_at: Option<std::time::Instant> = None;
+ // Two clocks (#948). RSS backs off when a drain does not lower
+ // it (#1981). The summed-memtable latch stays on the 2 s window
+ // (#2238), including while that RSS clock is already stretched:
+ // a stable RSS is the normal shape of a memtable-only trip, and
+ // backing off there leaves corpus index at 429 with nothing
+ // flushed. try_send never blocks, so Thread A's no-lock contract
+ // still holds.
+ let mut rss_drains =
+ crate::governor::MemoryDrainSchedule::new(MEMORY_DRAIN_MIN_INTERVAL);
+ let mut last_memtable_drain_at: Option<std::time::Instant> = None;
loop {
std::thread::sleep(period);
if weak_a.strong_count() == 0 {
@@ -4402,19 +4443,17 @@ impl Engine {
let (disk_pct, disk_avail) = crate::governor::disk_used_pct_and_avail(&data_dir);
governor.refresh_memory_observing(observed, disk_pct, disk_avail, available_commit);
- // Issue #948 / #2238 — a breaker that only rejects never lets
- // a memory-pinned workload finish: caches hold gigabytes of
- // re-hydratable state and the memtable holds raw write
- // payloads, and 429s free none of it. Request a drain on the
- // engage edge of EITHER parent latch (RSS or summed memtable)
- // and at most once per window while it stays engaged.
- // try_send never blocks, so Thread A's no-lock/no-block
- // contract above still holds.
- if pressure_drain_due(
- governor.ingest_pressure_needs_drain(),
- &mut last_drain_at,
+ if sample_drain_due(
std::time::Instant::now(),
- MEMORY_DRAIN_MIN_INTERVAL,
+ // Same figure the breaker just compared: working set, or
+ // on Windows the max of working set and commit charge.
+ // Backing off on the working set alone would stretch
+ // drains while commit charge is the value still climbing.
+ observed,
+ governor.memory_breaker_engaged(),
+ governor.memtable_breaker_engaged(),
+ &mut rss_drains,
+ &mut last_memtable_drain_at,
) {
if let Some(tx) = MEMORY_DRAIN_TX.get() {
let _ = tx.try_send(());
@@ -6109,12 +6148,14 @@ mod index_template_merge_tests {
#[cfg(test)]
mod pressure_drain_tests {
- use super::pressure_drain_due;
+ use super::{pressure_drain_due, sample_drain_due, MEMORY_DRAIN_MIN_INTERVAL};
+ use crate::governor::MemoryDrainSchedule;
use std::time::{Duration, Instant};
/// #2238: the engage edge drains immediately, a still-engaged latch does
/// not drain again inside the window, and releasing the latch arms the
- /// next engage. `needs_drain` is the governor's memtable-or-RSS predicate.
+ /// next engage. The sampler passes the memtable latch; the RSS latch
+ /// has its own schedule.
#[test]
fn pressure_drain_fires_on_the_engage_edge_and_respects_the_window() {
let mut last = None;
@@ -6143,4 +6184,104 @@ mod pressure_drain_tests {
"the next engage drains immediately"
);
}
+
+ /// #1981 x #2238: a flat RSS backs off, and that backoff must not hide a
+ /// memtable trip. Corpus index hits the summed budget while RSS is
+ /// stable; the flush that frees it stays on the 2 s window. A memtable
+ /// engage that arrives during an RSS gap drains on that sample, not at
+ /// the end of the gap.
+ #[test]
+ fn memtable_pressure_is_not_stretched_by_the_rss_backoff() {
+ let min = MEMORY_DRAIN_MIN_INTERVAL;
+ let t0 = Instant::now();
+ let stuck = 64 * 1024 * 1024;
+ let mut rss_drains = MemoryDrainSchedule::new(min);
+ let mut last_memtable = None;
+
+ let mut rss_fires = 0u32;
+ let mut t = Duration::ZERO;
+ let warmup = Duration::from_secs(60);
+ while t < warmup {
+ if sample_drain_due(
+ t0 + t,
+ stuck,
+ true,
+ false,
+ &mut rss_drains,
+ &mut last_memtable,
+ ) {
+ rss_fires += 1;
+ }
+ t += min;
+ }
+ assert!(
+ rss_fires < 20,
+ "a flat RSS must back off across 60s, fired {rss_fires}"
+ );
+ assert!(
+ !sample_drain_due(
+ t0 + warmup,
+ stuck,
+ true,
+ false,
+ &mut rss_drains,
+ &mut last_memtable,
+ ),
+ "the RSS clock is still inside its backed-off gap"
+ );
+ assert!(
+ sample_drain_due(
+ t0 + warmup,
+ stuck,
+ true,
+ true,
+ &mut rss_drains,
+ &mut last_memtable,
+ ),
+ "a memtable engage drains immediately during that gap"
+ );
+ assert!(!sample_drain_due(
+ t0 + warmup + Duration::from_millis(500),
+ stuck,
+ true,
+ true,
+ &mut rss_drains,
+ &mut last_memtable,
+ ));
+ assert!(sample_drain_due(
+ t0 + warmup + min,
+ stuck,
+ true,
+ true,
+ &mut rss_drains,
+ &mut last_memtable,
+ ));
+
+ // Memtable only, RSS stable and disengaged: every 2 s step fires.
+ // Folding this latch into the RSS backoff would drop fires well
+ // below the step count.
+ let mut rss_drains = MemoryDrainSchedule::new(min);
+ let mut last_memtable = None;
+ let horizon = Duration::from_secs(120);
+ let mut mem_fires = 0u32;
+ let mut t = Duration::ZERO;
+ while t < horizon {
+ if sample_drain_due(
+ t0 + t,
+ stuck,
+ false,
+ true,
+ &mut rss_drains,
+ &mut last_memtable,
+ ) {
+ mem_fires += 1;
+ }
+ t += min;
+ }
+ let steps = (horizon.as_secs() / min.as_secs()) as u32;
+ assert_eq!(
+ mem_fires, steps,
+ "memtable pressure keeps the fixed window while RSS does not fall"
+ );
+ }
}
diff --git a/engine/crates/xerj-engine/src/governor.rs b/engine/crates/xerj-engine/src/governor.rs
index f96f63945..96430277f 100644
--- a/engine/crates/xerj-engine/src/governor.rs
+++ b/engine/crates/xerj-engine/src/governor.rs
@@ -28,7 +28,8 @@
//! admission checks are relaxed atomic loads — never syscalls.
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering};
-use std::sync::{Arc, OnceLock};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant};
use serde_json::Value;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
@@ -40,6 +41,66 @@ use crate::segment_cache_budget::{SegmentHydrationBudget, SegmentHydrationBudget
/// The process-wide governor singleton.
static GOVERNOR: OnceLock<Arc<ResourceGovernor>> = OnceLock::new();
+/// Decides when the sampler may request another memory-pressure drain.
+///
+/// The engage edge fires immediately. While the breaker stays engaged, the
+/// next request waits `interval`, which starts at the 2 s floor and doubles
+/// up to [`MEMORY_DRAIN_MAX_INTERVAL`] whenever a request did not lower RSS.
+/// A drop resets the spacing. Disengaging resets everything, so the next
+/// real engage is immediate again.
+#[derive(Debug)]
+pub(crate) struct MemoryDrainSchedule {
+ interval: Duration,
+ last_request: Option<Instant>,
+ rss_at_request: Option<u64>,
+ min: Duration,
+}
+
+impl MemoryDrainSchedule {
+ pub(crate) fn new(min: Duration) -> Self {
+ Self {
+ interval: min,
+ last_request: None,
+ rss_at_request: None,
+ min,
+ }
+ }
+
+ /// `true` when this sample should request a drain.
+ pub(crate) fn observe(&mut self, now: Instant, rss: u64, engaged: bool) -> bool {
+ if !engaged {
+ self.interval = self.min;
+ self.last_request = None;
+ self.rss_at_request = None;
+ return false;
+ }
+ let due = match self.last_request {
+ None => true,
+ Some(at) => now.saturating_duration_since(at) >= self.interval,
+ };
+ if !due {
+ return false;
+ }
+ if let Some(prev) = self.rss_at_request {
+ // A one-page dip is compressor noise, not a drain that worked.
+ // Resetting on it would pin the spacing at 2 s for a footprint
+ // that never actually shrinks (#1981).
+ if prev.saturating_sub(rss) > MEMORY_RSS_NOISE_BYTES {
+ self.interval = self.min;
+ } else {
+ self.interval = self
+ .interval
+ .checked_mul(2)
+ .unwrap_or(MEMORY_DRAIN_MAX_INTERVAL)
+ .min(MEMORY_DRAIN_MAX_INTERVAL);
+ }
+ }
+ self.rss_at_request = Some(rss);
+ self.last_request = Some(now);
+ true
+ }
+}
+
/// Interval at which the background sampler refreshes the RSS / memtable /
/// disk atomics. Kept short so the RSS admission has a tight overshoot margin
/// under a runaway ingest — the sampler runs on a dedicated OS thread (see
@@ -47,6 +108,36 @@ static GOVERNOR: OnceLock<Arc<ResourceGovernor>> = OnceLock::new();
/// tokio pool is saturated.
pub const SAMPLE_INTERVAL_MS: u64 = 100;
+/// How long RSS may sit flat at or above the watermark before the breaker
+/// releases (#1981).
+///
+/// One memory-pressure drain is 2 s apart from the next. That is enough time
+/// for the drain to reclaim caches and purge arenas. If RSS still has not
+/// fallen, another drain will not either — on macOS jemalloc has no
+/// background thread, so a footprint the purge cannot shrink (compressed
+/// pages in `ri_phys_footprint`, or a live set the caches are not) used to
+/// keep the sampler requesting a drain every 2 s for the rest of the
+/// process. Each request flushes every index and walks the caches. That is
+/// the idle-CPU climb: the node is quiet until RSS crosses the watermark,
+/// then one core stays busy with drains that change nothing, and a restart
+/// (RSS back under the watermark) looks like a cure.
+pub const MEMORY_FLAT_RELEASE: Duration = Duration::from_secs(2);
+
+/// Ceiling on the automatic drain spacing once a drain stops lowering RSS.
+/// The floor is the sampler's 2 s minimum; doubling from there reaches this
+/// in a few minutes instead of staying at 2 s for an 18-hour uptime.
+pub const MEMORY_DRAIN_MAX_INTERVAL: Duration = Duration::from_secs(15 * 60);
+
+/// RSS movement at or below this is not a falling drain and not new
+/// pressure (#1981).
+///
+/// macOS reports `ri_phys_footprint`, which moves by pages while the
+/// compressor runs even when the process is idle. An exact-byte clock never
+/// stays flat for [`MEMORY_FLAT_RELEASE`] on that signal, and a one-byte dip
+/// would also reset the drain backoff, so the 2 s flush loop would survive
+/// the latch fix. A climb past this band is a real working-set change.
+pub const MEMORY_RSS_NOISE_BYTES: u64 = 4 * 1024 * 1024;
+
/// Bytes of analyze-time reservation charged per raw JSON input byte (#1122).
///
/// `document_limit` measured about 56 bytes of RSS per token for a
@@ -134,6 +225,15 @@ pub struct ResourceGovernor {
/// against the new value without the band, so a live raise releases at
/// once instead of waiting for RSS to fall 5% below the NEW watermark.
memory_trip_watermark: AtomicU64,
+ /// When RSS first stopped falling while the breaker was engaged at or
+ /// above the watermark. `None` while RSS is falling or the breaker is
+ /// disengaged. Aged by tests; the sampler's wall clock fills it in
+ /// production (#1981).
+ memory_flat_since: Mutex<Option<Instant>>,
+ /// RSS at which a flat footprint was released. Later samples at or below
+ /// this stay disengaged, so the latch cannot flap back on at the same
+ /// reading one sample later. `0` means no floor.
+ memory_stall_floor: AtomicU64,
// ── item 1: per-query memory guard (`max_query_memory_mb`) ──────────
/// Maximum bytes a single query may be estimated to allocate. `0` = off.
@@ -323,6 +423,44 @@ impl ResourceGovernor {
self.memory_tripped.load(Ordering::Relaxed)
}
+ /// Start or read the flat-footprint clock. The first sample inside the
+ /// noise band records `now` and returns zero; later samples return how
+ /// long RSS has stayed there. Cleared when RSS leaves that band, the
+ /// breaker releases, or the watermark is retuned.
+ fn note_memory_flat(&self) -> Duration {
+ let mut slot = self
+ .memory_flat_since
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ match *slot {
+ Some(at) => at.elapsed(),
+ None => {
+ *slot = Some(Instant::now());
+ Duration::ZERO
+ }
+ }
+ }
+
+ fn clear_memory_flat(&self) {
+ *self
+ .memory_flat_since
+ .lock()
+ .unwrap_or_else(|e| e.into_inner()) = None;
+ }
+
+ /// #1981 test hook: age the flat-footprint clock without sleeping, so a
+ /// test can cross [`MEMORY_FLAT_RELEASE`] on a paused schedule.
+ #[cfg(test)]
+ fn age_memory_flat_for_test(&self, by: Duration) {
+ let mut slot = self
+ .memory_flat_since
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ if let Some(at) = *slot {
+ *slot = Some(at.checked_sub(by).unwrap_or(at));
+ }
+ }
+
/// Whether the summed-memtable budget breaker is currently engaged.
pub fn memtable_breaker_engaged(&self) -> bool {
self.memtable_tripped.load(Ordering::Relaxed)
@@ -339,6 +477,11 @@ impl ResourceGovernor {
/// with every index still under its own flush line. Writes then stay
/// 429 and the indexed count stays 0 unless this latch requests the
/// same drain.
+ ///
+ /// The two latches do not share a timer. The RSS latch backs off when a
+ /// drain does not lower RSS (#1981). The memtable latch stays on the
+ /// fixed window, because that flush is what frees this budget and a
+ /// stable RSS is the normal shape of a memtable-only trip.
pub fn ingest_pressure_needs_drain(&self) -> bool {
self.memory_breaker_engaged() || self.memtable_breaker_engaged()
}
@@ -566,7 +709,10 @@ impl ResourceGovernor {
/// [`Self::refresh_memory_disk`] plus an optional Windows available-commit
/// sample. `None` leaves the commit latch as it was (Linux, and tests
/// that only move RSS). A `Some` below the commit reserve engages the
- /// breaker even when `rss` is under the watermark.
+ /// breaker even when `rss` is under the watermark (#1122). That hold is
+ /// independent of the flat-footprint release (#1981): a footprint that
+ /// does not fall still releases once commit is back above the reserve,
+ /// and commit starvation does not clear the flat clock.
pub fn refresh_memory_observing(
&self,
rss: u64,
@@ -585,17 +731,36 @@ impl ResourceGovernor {
// has nothing more to free: holding would only reject writes the node
// can take and keep the sampler re-draining every
// `MEMORY_DRAIN_MIN_INTERVAL` forever, so the latch releases exactly
- // as it did before the band existed. A live watermark change (#1323)
- // drops the band for that sample: the operator's new value decides.
+ // as it did before the band existed.
+ //
+ // The same "stopped falling" rule applies AT or ABOVE the watermark
+ // (#1981), after [`MEMORY_FLAT_RELEASE`], with a
+ // [`MEMORY_RSS_NOISE_BYTES`] band so page-sized footprint noise is
+ // not a climb or a recovery. A footprint that does not fall past
+ // that band is not a drain the sampler should repeat for the life
+ // of the process. The release records `memory_stall_floor` so a
+ // later sample inside the band does not engage again — without that
+ // floor `rss >= watermark` would re-trip one sample later and the
+ // drain edge would fire forever. A climb past the band is new
+ // pressure and engages. A live watermark change (#1323) drops the
+ // band and the floor for that sample: the operator's new value
+ // decides.
let prev_rss = self.rss_bytes.swap(rss, Ordering::Relaxed);
let watermark = self.memory_watermark_bytes.load(Ordering::Relaxed);
let cur_mem = self.memory_tripped.load(Ordering::Relaxed);
let retuned = self.memory_trip_watermark.load(Ordering::Relaxed) != watermark;
let release_bytes = watermark - (watermark / 20);
+ let stall_floor = self.memory_stall_floor.load(Ordering::Relaxed);
+ // In-band hysteresis (#1250) still uses an exact comparison: one
+ // sample that does not fall releases. Above the watermark the same
+ // comparison would treat compressor noise as a climb or a recovery.
+ let falling = rss < prev_rss;
+ let dropped = prev_rss.saturating_sub(rss) > MEMORY_RSS_NOISE_BYTES;
+ let climbed = rss.saturating_sub(prev_rss) > MEMORY_RSS_NOISE_BYTES;
// `None` keeps the previous latch so an RSS-only refresh (Linux, and
// the test helper) does not clear a commit trip it did not sample.
// Reserve 0 means this platform has no commit probe: starved stays
- // false and the formula below is the pre-#1122 RSS check.
+ // false and the RSS formula below is the pre-#1122 check.
let starved = if self.commit_reserve_bytes == 0 {
false
} else if let Some(available) = available_commit {
@@ -606,15 +771,56 @@ impl ResourceGovernor {
self.commit_starved.load(Ordering::Relaxed)
};
self.commit_starved.store(starved, Ordering::Relaxed);
- let mem_next = if watermark == 0 {
- starved
- } else if rss >= watermark || starved {
- true
- } else if cur_mem && !retuned {
- rss >= release_bytes && rss < prev_rss
- } else {
- false
- };
+ // RSS latch (#1250, #1981). Commit starvation is applied after this
+ // so a flat footprint can release, and a pagefileless box still
+ // stays engaged while available commit is under the reserve.
+ let rss_next = watermark != 0
+ && if rss >= watermark {
+ let within_floor =
+ stall_floor != 0 && rss <= stall_floor.saturating_add(MEMORY_RSS_NOISE_BYTES);
+ if !cur_mem && within_floor && !retuned {
+ false
+ } else if cur_mem && !retuned && !dropped {
+ if climbed {
+ // Still climbing past noise: the drain has not
+ // caught the working set. Forget the flat clock.
+ self.clear_memory_flat();
+ self.memory_stall_floor.store(0, Ordering::Relaxed);
+ true
+ } else {
+ let flat_for = self.note_memory_flat();
+ // Starvation must not record a stall floor: that
+ // floor means "released at this footprint", and the
+ // breaker has not released. The clock keeps running
+ // so the release happens on the first sample after
+ // commit recovers, once the window has elapsed.
+ if !starved && flat_for >= MEMORY_FLAT_RELEASE {
+ self.memory_stall_floor.store(rss, Ordering::Relaxed);
+ self.clear_memory_flat();
+ false
+ } else {
+ true
+ }
+ }
+ } else {
+ // Dropped past the noise band, a live retune, or the
+ // engage edge. Reaching this arm means one of those is
+ // true, so the flat clock and the floor are stale.
+ self.clear_memory_flat();
+ self.memory_stall_floor.store(0, Ordering::Relaxed);
+ true
+ }
+ } else if cur_mem && !retuned {
+ self.clear_memory_flat();
+ rss >= release_bytes && falling
+ } else {
+ self.clear_memory_flat();
+ if !cur_mem || retuned {
+ self.memory_stall_floor.store(0, Ordering::Relaxed);
+ }
+ false
+ };
+ let mem_next = starved || rss_next;
if mem_next {
self.memory_trip_watermark
.store(watermark, Ordering::Relaxed);
@@ -1263,6 +1469,8 @@ fn build(config: &Config) -> ResourceGovernor {
} else {
0
}),
+ memory_flat_since: Mutex::new(None),
+ memory_stall_floor: AtomicU64::new(0),
max_query_memory_bytes,
search_pool: Arc::new(Semaphore::new(max_concurrent_searches)),
max_concurrent_searches,
@@ -2614,6 +2822,59 @@ mod tests {
assert!(g.thread_spawn_safe());
}
+ /// #1122 x #1981: commit starvation and a flat footprint are different
+ /// holds. A footprint that sits on the watermark must not release the
+ /// breaker while available commit is still under the reserve — that
+ /// release is what lets the next allocation abort. The flat clock keeps
+ /// running, so the first sample after commit recovers releases instead
+ /// of starting the 2 s window over, and that footprint does not re-arm.
+ #[test]
+ fn commit_starvation_holds_a_flat_footprint_until_commit_returns() {
+ const MIB: u64 = 1024 * 1024;
+ const GIB: u64 = 1024 * MIB;
+ let mut cfg = Config::default();
+ cfg.limits.max_total_memtable_mb = 0;
+ cfg.limits.memory_watermark_percent = 95;
+ let mut g = build(&cfg);
+ g.commit_limit_bytes = 16 * GIB;
+ g.commit_reserve_bytes = 512 * MIB;
+ g.commit_capped = true;
+ g.available_commit_bytes.store(4 * GIB, Ordering::Relaxed);
+ g.commit_starved.store(false, Ordering::Relaxed);
+ g.memory_tripped.store(false, Ordering::Relaxed);
+
+ let wm = g.memory_watermark_bytes.load(Ordering::Relaxed);
+ assert!(wm > 0, "this test needs a live RSS watermark");
+ let stuck = wm + 100;
+ g.refresh_memory_observing(stuck, 0, 0, Some(128 * MIB));
+ assert!(g.memory_breaker_engaged(), "crossing the watermark engages");
+ g.refresh_memory_observing(stuck, 0, 0, Some(128 * MIB));
+ g.age_memory_flat_for_test(MEMORY_FLAT_RELEASE + Duration::from_millis(1));
+ g.refresh_memory_observing(stuck, 0, 0, Some(128 * MIB));
+ assert!(
+ g.memory_breaker_engaged(),
+ "a flat footprint must not release a breaker commit starvation is holding"
+ );
+ let msg = format!("{}", g.check_ingest_admission().unwrap_err());
+ assert!(msg.contains("pagefile"), "{msg}");
+
+ g.refresh_memory_observing(stuck, 0, 0, Some(2 * GIB));
+ assert!(
+ !g.memory_breaker_engaged(),
+ "once commit is back, a footprint that already sat flat releases"
+ );
+ g.refresh_memory_observing(stuck, 0, 0, Some(2 * GIB));
+ assert!(
+ !g.memory_breaker_engaged(),
+ "the same footprint must not re-arm"
+ );
+ g.refresh_memory_observing(stuck + MEMORY_RSS_NOISE_BYTES + 1, 0, 0, Some(2 * GIB));
+ assert!(
+ g.memory_breaker_engaged(),
+ "a climb past the noise band is new pressure"
+ );
+ }
+
/// Off Windows there is no commit charge, so the breaker probe is the RSS
/// sample it just took. Both probes read the kernel counter, and that
/// read allocates, as do other tests in this process, so one pair can
@@ -2972,6 +3233,145 @@ mod tests {
assert!(g.check_ingest_admission().is_ok());
}
+ /// #1981: a footprint that sits flat at or above the watermark is not a
+ /// drain the sampler should repeat until restart. After
+ /// [`MEMORY_FLAT_RELEASE`] the latch releases, and the same RSS does not
+ /// re-engage (that flap would request a drain on every engage edge). A
+ /// higher RSS is new pressure and engages again. One flat sample is not
+ /// enough — the in-flight drain has not had its window.
+ #[test]
+ fn flat_rss_above_the_watermark_releases_and_does_not_rearm() {
+ let mut cfg = Config::default();
+ cfg.limits.max_total_memtable_mb = 0;
+ cfg.limits.memory_watermark_percent = 95;
+ let g = build(&cfg);
+ let wm = g.memory_watermark_bytes.load(Ordering::Relaxed);
+ assert!(wm > 0, "this test needs a live RSS watermark");
+ let stuck = wm + 100;
+
+ g.refresh(0, stuck, 0);
+ assert!(g.memory_breaker_engaged(), "crossing the watermark engages");
+ g.refresh(0, stuck, 0);
+ assert!(
+ g.memory_breaker_engaged(),
+ "one flat sample must stay engaged so a drain can run"
+ );
+ g.age_memory_flat_for_test(MEMORY_FLAT_RELEASE + Duration::from_millis(1));
+ g.refresh(0, stuck, 0);
+ assert!(
+ !g.memory_breaker_engaged(),
+ "RSS that does not fall must release instead of draining forever"
+ );
+ assert!(g.check_ingest_admission().is_ok());
+
+ // The old latch re-tripped here: rss >= watermark on a disengaged
+ // governor is an engage edge, and the sampler would drain again.
+ g.refresh(0, stuck, 0);
+ assert!(
+ !g.memory_breaker_engaged(),
+ "the same footprint must not re-arm the drain"
+ );
+ // Page-sized noise around the floor is the macOS signal, not a new
+ // working set. Re-arming on it would engage, drain, and release on
+ // every sample.
+ g.refresh(0, stuck + 1, 0);
+ assert!(
+ !g.memory_breaker_engaged(),
+ "a one-byte bump around the floor must not re-arm the drain"
+ );
+
+ g.refresh(0, stuck + MEMORY_RSS_NOISE_BYTES + 1, 0);
+ assert!(
+ g.memory_breaker_engaged(),
+ "a climb past the noise band is new pressure"
+ );
+ }
+
+ /// #1981: `ri_phys_footprint` does not sit on one byte. A quiet node
+ /// whose samples wander inside [`MEMORY_RSS_NOISE_BYTES`] must still
+ /// release once that wander has lasted [`MEMORY_FLAT_RELEASE`].
+ #[test]
+ fn rss_noise_around_a_flat_footprint_still_releases() {
+ let mut cfg = Config::default();
+ cfg.limits.max_total_memtable_mb = 0;
+ cfg.limits.memory_watermark_percent = 95;
+ let g = build(&cfg);
+ let wm = g.memory_watermark_bytes.load(Ordering::Relaxed);
+ assert!(wm > MEMORY_RSS_NOISE_BYTES);
+ let stuck = wm + MEMORY_RSS_NOISE_BYTES;
+
+ g.refresh(0, stuck, 0);
+ assert!(g.memory_breaker_engaged());
+ g.refresh(0, stuck + 4096, 0);
+ assert!(g.memory_breaker_engaged(), "noise must not release early");
+ g.refresh(0, stuck - 4096, 0);
+ assert!(g.memory_breaker_engaged());
+ g.age_memory_flat_for_test(MEMORY_FLAT_RELEASE + Duration::from_millis(1));
+ g.refresh(0, stuck + 8192, 0);
+ assert!(
+ !g.memory_breaker_engaged(),
+ "page-sized wander is a flat footprint"
+ );
+ g.refresh(0, stuck - 8192, 0);
+ assert!(!g.memory_breaker_engaged(), "the same band must not re-arm");
+ }
+
+ /// #1981: while the breaker stays engaged and RSS does not fall, drain
+ /// requests must back off. An 18-hour stuck footprint sampled on the old
+ /// 2 s cadence is 32_400 requests; the doubled schedule stays in the
+ /// dozens. Falling RSS returns to the 2 s floor.
+ #[test]
+ fn drain_requests_back_off_when_rss_does_not_fall() {
+ let min = Duration::from_secs(2);
+ let mut schedule = MemoryDrainSchedule::new(min);
+ let t0 = Instant::now();
+ let horizon = Duration::from_secs(18 * 60 * 60);
+ let stuck = 64 * MEMORY_RSS_NOISE_BYTES;
+ let mut fires = 0u64;
+ let mut t = Duration::ZERO;
+ let mut step = 0u64;
+ while t < horizon {
+ // Alternate a page either side of the stuck footprint. The old
+ // schedule treated every downward byte as a successful drain
+ // and snapped back to 2 s.
+ let rss = if step.is_multiple_of(2) {
+ stuck
+ } else {
+ stuck + 4096
+ };
+ if schedule.observe(t0 + t, rss, true) {
+ fires += 1;
+ }
+ t += min;
+ step += 1;
+ }
+ let unbounded = horizon.as_secs() / min.as_secs();
+ assert!(
+ fires < unbounded / 50,
+ "stuck RSS requested {fires} drains over 18h; the 2s loop would be {unbounded}"
+ );
+ assert!(fires > 10, "backoff must still retry, got {fires}");
+
+ // A drop resets the spacing: the next request is one floor later,
+ // not a doubled gap. Step a full cap ahead so this request is due
+ // no matter where in the capped window the 18 h loop stopped.
+ let now = t0 + horizon + MEMORY_DRAIN_MAX_INTERVAL;
+ let dropped = stuck - MEMORY_RSS_NOISE_BYTES - 1;
+ assert!(
+ schedule.observe(now, dropped, true),
+ "a lower RSS is due work"
+ );
+ assert!(
+ !schedule.observe(now + min - Duration::from_millis(1), dropped, true),
+ "the reset spacing is still the floor, not immediate"
+ );
+ assert!(schedule.observe(now + min, dropped - MEMORY_RSS_NOISE_BYTES - 1, true));
+
+ // Disengage forgets the episode; the next engage fires at once.
+ assert!(!schedule.observe(now + min + min, dropped, false));
+ assert!(schedule.observe(now + min + min, dropped, true));
+ }
+
/// #1250 x #1323: the watermark is live-tunable. Raising it while the
/// breaker is engaged must release at once whenever RSS is under the NEW
/// watermark — not wait for RSS to fall 5% below it — or the live fix
diff --git a/landing/llms-full.txt b/landing/llms-full.txt
index b6aa6c508..01b695e76 100644
--- a/landing/llms-full.txt
+++ b/landing/llms-full.txt
@@ -1593,9 +1593,11 @@ apply; if it does not, YOU are the gate — estimate, ask, and only then run.
see it on an older binary, check `_count` before you conclude the run is hung.
* `pct` AND `eta_s` ARE HONEST OR ABSENT. Both can be the literal string `unknown` (JSON
`null`) — before a denominator exists, before the estimate has settled, or when nothing
- has completed recently (`eta_quality=stalled`, meaning one big file is still
- streaming). Never invent a number to fill the gap; report `waiting_on` instead, which
- names the file it is actually on.
+ has completed recently (`eta_quality=stalled`). That includes a phase sitting at
+ 0/N — under 2% used to stay `eta_quality=unknown` for the whole hang — and a phase
+ with no denominator that has been silent for 10 minutes. A short walk at
+ `pct=unknown` is not a stall. Never invent a number to fill the gap; report
+ `waiting_on` instead, which names the file it is actually on.
* PERCENT IS BYTES-BASED, NOT FILE-BASED. `items=250/251` with `pct=1.9` is normal and
correct: in that measured corpus one 34.6 MB file held 98% of the bytes. A file-count
percent would have claimed 99.6% and then sat there.