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): a lone background merge waits until its reservation fits (#2709)

xerj-org12d2d3b149a2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d84a9cd1f..7fe1dd7cf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -47,6 +47,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- A background merge no longer starts alone when its own memory reservation
+ would carry the node past the merge-pool ceiling. It waits (at most 30 s)
+ while the next batches are planned small enough to fit, so merging still
+ makes progress without the overshoot behind the 1 GB gate's 3.5 GB ingest
+ peak on a 3,072 MB cap (Refs #2427).
- Search under a memory cap: when the segment hydration cache is full, a query that has to build a segment's stored slices or FTS reader outside the cache now reserves that memory from a separate read budget (`XERJ_READ_TRANSIENT_MB`, default a tenth of `XERJ_MAX_PROCESS_MEMORY_MB`). It waits up to `XERJ_READ_TRANSIENT_WAIT_MS` (default 5 s) for room instead of stacking whole decompressed sections on top of each other. Background cache warms that the full cache would refuse are skipped. While the memory breaker is engaged, its drain still flushes and purges on every tick but releases the read caches at most once per `XERJ_BREAKER_CACHE_RELEASE_SECS` (default 30 s), so queries no longer re-hydrate cold every two seconds. `GET /_nodes/stats` reports the budget under `indices.read_transient_budget`. (Refs #2427, #1122)
- Opt-in lexical `judge` now matches CJK characters and adjacent pairs inside
uninterrupted Chinese/Japanese/Korean text instead of treating the whole
diff --git a/engine/crates/xerj-engine/src/governor.rs b/engine/crates/xerj-engine/src/governor.rs
index 46a8639b8..94962712d 100644
--- a/engine/crates/xerj-engine/src/governor.rs
+++ b/engine/crates/xerj-engine/src/governor.rs
@@ -737,24 +737,44 @@ impl ResourceGovernor {
let engaged = self.memory_breaker_engaged();
let mut ledger = self.merge_ledger.lock().unwrap_or_else(|e| e.into_inner());
// #2427 ingest overshoot: a lone background batch does not start
- // inside the read reserve; it waits (bounded) for the drain. See
- // `merge_budget::lone_merge_waits_for_headroom`.
- if !forced && ledger.in_flight == 0 && watermark > 0 && observed >= watermark {
+ // inside the read reserve, and does not start when its own
+ // reservation would carry RSS into it (the 1 GB gate's ingest node
+ // peaked at 3.5 GB against a 3,072 MB cap this way). It waits,
+ // bounded, for the drain; meanwhile the next batches are planned
+ // to fit the headroom. See `merge_budget::lone_merge_waits_for_headroom`
+ // and `merge_budget::pressure_cap_for_headroom`.
+ let lone_background = !forced && ledger.in_flight == 0 && watermark > 0 && observed > 0;
+ let mut headroom_wait_expired = false;
+ if lone_background && observed.saturating_add(bytes) >= watermark {
let since = *ledger
.headroom_wait_since
.get_or_insert_with(std::time::Instant::now);
if crate::merge_budget::lone_merge_waits_for_headroom(
observed,
watermark,
+ bytes,
ledger.in_flight,
forced,
since.elapsed(),
self.merge_headroom_max_wait,
) {
+ if observed < watermark {
+ ledger.pressure_cap = crate::merge_budget::pressure_cap_for_headroom(
+ ledger.pressure_cap,
+ input_bytes,
+ bytes,
+ watermark - observed,
+ );
+ }
return None;
}
+ // Waited the full bound: start it anyway so merging progresses.
+ headroom_wait_expired = true;
} else if observed < watermark {
- // Headroom came back: the next wait starts its own clock.
+ // Headroom came back: the next wait starts its own clock. Only
+ // when the batch fits, not merely when RSS is under the
+ // ceiling; otherwise a batch that never fits restarts the clock
+ // on every pass and never runs.
ledger.headroom_wait_since = None;
}
if !crate::merge_budget::decide_merge_admission(
@@ -765,6 +785,7 @@ impl ResourceGovernor {
engaged,
bytes,
forced,
+ headroom_wait_expired,
) {
return None;
}
@@ -4046,8 +4067,10 @@ mod tests {
);
// A big merge starts on a quiet node and reserves about half the
- // limit: the merge budget is held.
- let base = limit / 2;
+ // limit: the merge budget is held. The node is quiet enough that
+ // the reservation fits under the merge pool, which a lone merge
+ // now needs (or a full bounded wait).
+ let base = limit / 4;
g.refresh(0, base, 0);
let input = (limit / 2) / crate::merge_budget::MERGE_WORKING_SET_NUMERATOR;
let merge = g
@@ -4062,7 +4085,7 @@ mod tests {
// The merge allocates its working set: RSS goes past the hard limit.
// Its working set plus a little other growth takes RSS past the hard
// limit, while the non-merge part stays well under it.
- let other = limit / 16;
+ let other = limit / 4 + limit / 16;
g.refresh(0, base + held + other, 0);
assert!(base + held + other >= limit);
assert!(g.memory_breaker_engaged());
@@ -4558,6 +4581,57 @@ mod tests {
drop(late);
}
+ /// #2427 1 GB gate on `0eaa8af9`, ingest node (3.5 GB peak, 47 breaker
+ /// trips against a 3,072 MB cap): with nothing else merging, a batch
+ /// started whenever RSS was under the merge-pool ceiling, even when its
+ /// own reservation was larger than the room left. Now it waits while
+ /// it does not fit, the next batches are planned to the headroom, and
+ /// the wait clock is not restarted by RSS merely being under the
+ /// ceiling, so the bounded wait still guarantees it runs.
+ #[test]
+ fn a_lone_merge_whose_reservation_exceeds_the_headroom_waits_and_shrinks() {
+ let mut cfg = Config::default();
+ cfg.limits.max_total_memtable_mb = 0;
+ cfg.limits.memory_watermark_percent = 95;
+ let mut g = build(&cfg);
+ let ceiling = g.merge_pool_ceiling_bytes();
+ assert!(ceiling > 0, "this test needs a live RSS watermark");
+ let headroom = 64 * 1024 * 1024;
+ let rss = ceiling - headroom;
+ g.refresh(0, rss, 0);
+ assert!(!g.memory_breaker_engaged());
+
+ // Its reservation alone is more than the headroom: held back.
+ let big_input = headroom;
+ let big = crate::merge_budget::merge_reservation_bytes(big_input, 0);
+ assert!(big >= headroom);
+ assert!(g.try_reserve_merge(big_input, false).is_none());
+ let (cap, since) = {
+ let l = g.merge_ledger.lock().unwrap();
+ (l.pressure_cap, l.headroom_wait_since)
+ };
+ // The next batches are planned to fit what is left.
+ assert!(cap > 0 && cap < big_input);
+ assert!(crate::merge_budget::merge_reservation_bytes(cap, 0) < headroom);
+ assert!(since.is_some(), "the wait clock started");
+ // A retry under the ceiling keeps the same clock (it used to reset
+ // whenever RSS was under the ceiling).
+ assert!(g.try_reserve_merge(big_input, false).is_none());
+ assert_eq!(g.merge_ledger.lock().unwrap().headroom_wait_since, since);
+
+ // A batch planned under the narrowed cap fits and starts alone.
+ let small = g.try_reserve_merge(cap, false).expect("fits the headroom");
+ drop(small);
+ assert!(g.merge_ledger.lock().unwrap().headroom_wait_since.is_none());
+
+ // `_forcemerge` is never held back by this check.
+ drop(g.try_reserve_merge(big_input, true).expect("forced"));
+
+ // Progress: past the bound the oversized lone batch starts.
+ g.merge_headroom_max_wait = Duration::ZERO;
+ drop(g.try_reserve_merge(big_input, false).expect("bounded wait"));
+ }
+
/// #2427: the merge output-write step (doc-values build, stored encode,
/// FTS build) runs after the last yield checkpoint. It is charged to the
/// merge ledger before it starts. A step that would take RSS to the hard
diff --git a/engine/crates/xerj-engine/src/merge_budget.rs b/engine/crates/xerj-engine/src/merge_budget.rs
index 1b4306c95..901529447 100644
--- a/engine/crates/xerj-engine/src/merge_budget.rs
+++ b/engine/crates/xerj-engine/src/merge_budget.rs
@@ -167,15 +167,26 @@ pub fn merge_reservation_bytes(planned_input_bytes: u64, on_disk_bytes: u64) ->
///
/// * `watermark == 0` (breaker off) or `observed_rss == 0` (no probe):
/// start.
-/// * No merge in flight anywhere in the process: start one, so merging can
-/// always make progress, unless the breaker is engaged and the merge is a
-/// background one. A `forced` merge (`_forcemerge`) is still allowed as
-/// the single in-flight merge while engaged; it is a deliberate operator
-/// request and it waits on its own.
+/// * No merge in flight anywhere in the process:
+/// * a `forced` merge (`_forcemerge`) starts, engaged or not; it is a
+/// deliberate operator request and it waits on its own;
+/// * a background merge does not start while the breaker is engaged;
+/// * otherwise a background merge starts only if its reservation fits:
+/// `observed_rss + request` stays under the watermark. This is the
+/// headroom check the lone merge used to skip (#2427, 1 GB gate on
+/// `0eaa8af9`: the ingest node launched lone batches whose reservation
+/// was larger than the room left and peaked at 3.5 GB against a
+/// 3,072 MB cap). Progress is still guaranteed:
+/// `headroom_wait_expired` admits the batch once the governor has held
+/// lone merges back for [`MERGE_HEADROOM_MAX_WAIT`], and in the
+/// meantime the governor shrinks the next batches to the headroom
+/// ([`pressure_cap_for_headroom`]) so a smaller batch usually fits
+/// long before that.
/// * Breaker engaged: defer. Background merges are the one memory consumer
/// the node can postpone, so they wait for the drain.
/// * Otherwise start only if `observed_rss + reserved + request` stays under
/// the watermark.
+#[allow(clippy::too_many_arguments)]
pub fn decide_merge_admission(
watermark: u64,
observed_rss: u64,
@@ -184,12 +195,19 @@ pub fn decide_merge_admission(
breaker_engaged: bool,
request: u64,
forced: bool,
+ headroom_wait_expired: bool,
) -> bool {
if watermark == 0 || observed_rss == 0 {
return true;
}
if in_flight == 0 {
- return !breaker_engaged || forced;
+ if forced {
+ return true;
+ }
+ if breaker_engaged {
+ return false;
+ }
+ return headroom_wait_expired || observed_rss.saturating_add(request) < watermark;
}
if breaker_engaged {
return false;
@@ -200,6 +218,35 @@ pub fn decide_merge_admission(
< watermark
}
+/// The adaptive batch input cap after a lone background batch was held
+/// back because its reservation did not fit the headroom (#2427).
+///
+/// `input_bytes` is the batch's planned input and `request` the bytes it
+/// asked to reserve ([`merge_reservation_bytes`]); `headroom` is what is
+/// left under the merge-pool ceiling. The next batches are planned at the
+/// same input-to-reservation ratio scaled down to the headroom, so the
+/// planner splits the work into batches that fit instead of retrying the
+/// one that did not. `current == 0` means no adaptive cap yet. Never below
+/// 1; the planner still builds a minimum-count batch under any cap, and
+/// [`decide_merge_admission`]'s bounded wait lets that one through.
+pub fn pressure_cap_for_headroom(
+ current: u64,
+ input_bytes: u64,
+ request: u64,
+ headroom: u64,
+) -> u64 {
+ let scaled = (u128::from(input_bytes) * u128::from(headroom) / u128::from(request.max(1)))
+ .min(u128::from(u64::MAX)) as u64;
+ // Leave a little room: a batch planned exactly at the headroom would
+ // still be refused by the strict `<` check.
+ let target = (scaled - scaled / 8).max(1);
+ if current == 0 {
+ target
+ } else {
+ current.min(target)
+ }
+}
+
/// Whether an in-flight background merge batch must stop (#2427).
///
/// Admission checks a batch against `input * MERGE_WORKING_SET_NUMERATOR`
@@ -243,9 +290,12 @@ pub const MERGE_HEADROOM_MAX_WAIT: std::time::Duration = std::time::Duration::fr
/// grew RSS by 400-900 MB, and every one of the run's over-cap samples
/// (3,100-3,502 MB against 3,072 MB) is one of those batches.
///
-/// A lone background batch now waits while `observed_rss` is at or above
-/// `ceiling` (the merge-pool ceiling), so it starts after the drain, with
-/// the batch's growth room under the cap. The wait is bounded by `max_wait`
+/// A lone background batch now waits while `observed_rss + request` is at
+/// or above `ceiling` (the merge-pool ceiling), so it starts after the
+/// drain, with the batch's growth room under the cap. `request` is the
+/// batch's reservation; `0` checks RSS alone. Including it closes the gap
+/// where RSS sat just under the ceiling and a batch whose reservation was
+/// larger than the room left still started alone. The wait is bounded by `max_wait`
/// (`waited` is how long lone merges have been held back), so a node whose
/// live set sits above the ceiling still compacts. `_forcemerge`, a merge
/// beside others (already checked against the ledger), and an unknown RSS
@@ -253,6 +303,7 @@ pub const MERGE_HEADROOM_MAX_WAIT: std::time::Duration = std::time::Duration::fr
pub fn lone_merge_waits_for_headroom(
observed_rss: u64,
ceiling: u64,
+ request: u64,
in_flight: u64,
forced: bool,
waited: std::time::Duration,
@@ -262,7 +313,7 @@ pub fn lone_merge_waits_for_headroom(
&& in_flight == 0
&& ceiling > 0
&& observed_rss > 0
- && observed_rss >= ceiling
+ && observed_rss.saturating_add(request) >= ceiling
&& waited < max_wait
}
@@ -617,6 +668,7 @@ mod tests {
5,
true,
4_000 * MIB,
+ false,
false
));
assert!(decide_merge_admission(
@@ -626,6 +678,7 @@ mod tests {
5,
true,
4_000 * MIB,
+ false,
false
));
}
@@ -641,6 +694,7 @@ mod tests {
2_700 * MIB,
ceiling,
0,
+ 0,
false,
Duration::ZERO,
max
@@ -649,6 +703,7 @@ mod tests {
ceiling,
ceiling,
0,
+ 0,
false,
max - Duration::from_millis(1),
max
@@ -658,6 +713,7 @@ mod tests {
ceiling - 1,
ceiling,
0,
+ 0,
false,
Duration::ZERO,
max
@@ -668,6 +724,7 @@ mod tests {
2_700 * MIB,
ceiling,
0,
+ 0,
false,
max,
max
@@ -678,6 +735,7 @@ mod tests {
2_700 * MIB,
ceiling,
0,
+ 0,
true,
Duration::ZERO,
max
@@ -685,6 +743,7 @@ mod tests {
assert!(!lone_merge_waits_for_headroom(
2_700 * MIB,
ceiling,
+ 0,
1,
false,
Duration::ZERO,
@@ -694,6 +753,7 @@ mod tests {
0,
ceiling,
0,
+ 0,
false,
Duration::ZERO,
max
@@ -702,6 +762,7 @@ mod tests {
2_700 * MIB,
0,
0,
+ 0,
false,
Duration::ZERO,
max
@@ -709,18 +770,126 @@ mod tests {
}
#[test]
- fn merge_admission_always_lets_one_merge_run_when_not_engaged() {
- // Even an estimate that alone exceeds the watermark starts when no
- // other merge is in flight: merging must make progress.
+ fn a_lone_merge_needs_headroom_but_always_makes_progress() {
+ let wm = 2_850 * MIB;
+ // #2427 1 GB gate: a lone 400 MiB reservation at 2,700 MiB RSS
+ // would cross the watermark. It used to start because nothing
+ // else was merging; now it is held back while the wait runs.
+ assert!(!decide_merge_admission(
+ wm,
+ 2_700 * MIB,
+ 0,
+ 0,
+ false,
+ 400 * MIB,
+ false,
+ false
+ ));
+ // A batch that fits the headroom starts alone as before.
assert!(decide_merge_admission(
- 2_850 * MIB,
+ wm,
+ 2_700 * MIB,
+ 0,
+ 0,
+ false,
+ 100 * MIB,
+ false,
+ false
+ ));
+ // Progress: once the bounded wait has expired the lone batch
+ // starts even though it does not fit.
+ assert!(decide_merge_admission(
+ wm,
+ 2_700 * MIB,
+ 0,
+ 0,
+ false,
+ 400 * MIB,
+ false,
+ true
+ ));
+ // `_forcemerge` is never held back by the headroom check.
+ assert!(decide_merge_admission(
+ wm,
2_700 * MIB,
0,
0,
false,
400 * MIB,
+ true,
false
));
+ // The expired wait does not override an engaged breaker.
+ assert!(!decide_merge_admission(
+ wm,
+ 2_900 * MIB,
+ 0,
+ 0,
+ true,
+ 8 * MIB,
+ false,
+ true
+ ));
+ }
+
+ #[test]
+ fn a_held_back_lone_merge_shrinks_the_next_batches_to_the_headroom() {
+ // 50 MiB of planned input asked for 400 MiB; 150 MiB is left.
+ let cap = pressure_cap_for_headroom(0, 50 * MIB, 400 * MIB, 150 * MIB);
+ // Scaled to the headroom (18.75 MiB) less an eighth for the strict
+ // check: the next batch's reservation fits.
+ assert!(cap < 50 * MIB * 150 / 400);
+ assert!(cap * 400 / 50 < 150 * MIB);
+ assert!(cap > 0);
+ // An existing tighter cap is kept; a looser one is narrowed.
+ assert_eq!(
+ pressure_cap_for_headroom(MIB, 50 * MIB, 400 * MIB, 150 * MIB),
+ MIB
+ );
+ assert_eq!(
+ pressure_cap_for_headroom(512 * MIB, 50 * MIB, 400 * MIB, 150 * MIB),
+ cap
+ );
+ // No headroom or an unknown request never yields a zero cap.
+ assert_eq!(pressure_cap_for_headroom(0, 50 * MIB, 400 * MIB, 0), 1);
+ assert!(pressure_cap_for_headroom(0, 50 * MIB, 0, 150 * MIB) > 0);
+ }
+
+ #[test]
+ fn a_lone_merge_waits_when_its_reservation_does_not_fit_under_the_ceiling() {
+ use std::time::Duration;
+ let ceiling = 2_458 * MIB;
+ let max = MERGE_HEADROOM_MAX_WAIT;
+ // RSS just under the ceiling, but the batch would take it over.
+ assert!(lone_merge_waits_for_headroom(
+ 2_400 * MIB,
+ ceiling,
+ 400 * MIB,
+ 0,
+ false,
+ Duration::ZERO,
+ max
+ ));
+ // The same batch with room for it starts.
+ assert!(!lone_merge_waits_for_headroom(
+ 1_900 * MIB,
+ ceiling,
+ 400 * MIB,
+ 0,
+ false,
+ Duration::ZERO,
+ max
+ ));
+ // Bounded.
+ assert!(!lone_merge_waits_for_headroom(
+ 2_400 * MIB,
+ ceiling,
+ 400 * MIB,
+ 0,
+ false,
+ max,
+ max
+ ));
}
#[test]
@@ -735,6 +904,7 @@ mod tests {
1,
false,
reserved,
+ false,
false
));
// At 2,200 MiB RSS a second one would cross the watermark.
@@ -745,6 +915,7 @@ mod tests {
1,
false,
reserved,
+ false,
false
));
// And a third does not fit at all once two are reserved.
@@ -755,6 +926,7 @@ mod tests {
2,
false,
reserved,
+ false,
false
));
}
@@ -770,6 +942,7 @@ mod tests {
0,
true,
8 * MIB,
+ false,
false
));
assert!(!decide_merge_admission(
@@ -779,6 +952,7 @@ mod tests {
1,
true,
8 * MIB,
+ false,
false
));
// A forced merge may run alone while engaged, but not beside another.
@@ -789,7 +963,8 @@ mod tests {
0,
true,
8 * MIB,
- true
+ true,
+ false
));
assert!(!decide_merge_admission(
wm,
@@ -798,7 +973,8 @@ mod tests {
1,
true,
8 * MIB,
- true
+ true,
+ false
));
}