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
engine: reserve the memtable flush build working set against the memory watermark, and purge freed pages after a build (#2427) (#2826)
xerj-org38f4d5c0f84c
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex e5dcae4ee..148e4105a 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -302,7 +302,7 @@ mod pressure_cache_release_gate_tests {/// Run the installed allocator purge, if any. Never panics: a broken hook/// must not take the drain (or the process) down — purging is an/// optimisation for RSS return, not a correctness step.-fn purge_allocator_pages() {+pub(crate) fn purge_allocator_pages() {let hook = ALLOCATOR_PURGE_HOOK.read().unwrap_or_else(|e| e.into_inner());diff --git a/engine/crates/xerj-engine/src/governor.rs b/engine/crates/xerj-engine/src/governor.rsindex 2c4c2a36c..f0ffe6808 100644--- a/engine/crates/xerj-engine/src/governor.rs+++ b/engine/crates/xerj-engine/src/governor.rs@@ -442,6 +442,9 @@ pub struct ResourceGovernor {/// Process-wide ledger of in-flight segment merges and their estimated/// working set (#2427). See [`ResourceGovernor::try_reserve_merge`].merge_ledger: Arc<Mutex<MergeLedger>>,+ /// In-flight memtable flush builds and their estimated working set+ /// (#2427). See [`ResourceGovernor::reserve_flush_build`].+ flush_ledger: Arc<FlushLedger>,// ── item 1: per-query memory guard (`max_query_memory_mb`) ──────────/// Maximum bytes a single query may be estimated to allocate. `0` = off.@@ -608,6 +611,90 @@ impl ResourceGovernor {Err(self.analyze_reservation_refused(bytes))}+ /// Admit one memtable flush build whose working set is estimated at+ /// `bytes`, or `None` to wait (#2427).+ ///+ /// A flush build (JSON re-parse, full-text postings, doc-value columns,+ /// stored-section encode) allocates several times the frozen memtable+ /// bytes for 1-2 s, and none of that was charged anywhere: the gate's+ /// ingest-memory trace never showed `flush_drained` above 50 MB while+ /// untracked memory jumped by ~550 MB and RSS crossed the cap on each+ /// flush burst. Admission is now against the same committed total the+ /// analyze reservations use (live RSS, or the reservations' baseline+ /// plus every held reservation), so:+ ///+ /// - a second build that would carry the process past the watermark+ /// waits for the first one to finish instead of stacking on it, and+ /// - the reservation is added to the analyze pool, so ingest admission+ /// sees the build's bytes before they are allocated and answers 429+ /// instead of letting RSS trip the breaker.+ ///+ /// A build is always admitted when no other build is in flight, so+ /// flushing (which is what frees memtable memory) always progresses.+ pub(crate) fn try_reserve_flush_build(&self, bytes: u64) -> Option<FlushBuildReservation> {+ let mut state = self+ .flush_ledger+ .state+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ let watermark = self.memory_watermark_bytes.load(Ordering::Relaxed);+ let observed = self.observed_process_memory();+ if state.in_flight > 0 && watermark > 0 && bytes > 0 {+ let already = self.analyze_reserved.load(Ordering::Acquire);+ if !self.analyze_fits(watermark, observed, already, bytes) {+ return None;+ }+ }+ state.in_flight += 1;+ state.reserved = state.reserved.saturating_add(bytes);+ drop(state);+ let counted = watermark > 0 && bytes > 0;+ let baseline = counted.then(|| {+ self.analyze_reserved.fetch_add(bytes, Ordering::AcqRel);+ let id = self.lock_analyze_baselines().insert(observed);+ (Arc::clone(&self.analyze_baselines), id)+ });+ Some(FlushBuildReservation {+ ledger: Arc::clone(&self.flush_ledger),+ analyze: AnalyzeReservation {+ slot: counted.then(|| Arc::clone(&self.analyze_reserved)),+ baseline,+ bytes: if counted { bytes } else { 0 },+ },+ bytes,+ })+ }++ /// [`Self::try_reserve_flush_build`], waiting until the build fits or+ /// no other build is in flight. Unbounded: the caller puts its flush+ /// admission deadline around it and fails the flush before the freeze.+ pub(crate) async fn reserve_flush_build(&self, bytes: u64) -> FlushBuildReservation {+ loop {+ let released = self.flush_ledger.released.notified();+ tokio::pin!(released);+ released.as_mut().enable();+ if let Some(reservation) = self.try_reserve_flush_build(bytes) {+ return reservation;+ }+ // A finishing build wakes us; RSS can also fall without one+ // (cache release, allocator purge), so poll as well.+ tokio::select! {+ _ = &mut released => {}+ _ = tokio::time::sleep(FLUSH_BUILD_POLL) => {}+ }+ }+ }++ /// Estimated working set held by in-flight flush builds, and how many.+ pub fn flush_build_reserved(&self) -> (u64, u64) {+ let state = self+ .flush_ledger+ .state+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ (state.reserved, state.in_flight)+ }+/// Admit one `_bulk` request before its body is split and parsed (#2427).////// Every write path checks the breaker, but only after the bulk parse@@ -2240,6 +2327,7 @@ fn build(config: &Config) -> ResourceGovernor {memory_engaged_since: Mutex::new(None),memory_band_anchor: AtomicU64::new(0),merge_ledger: Arc::new(Mutex::new(MergeLedger::default())),+ flush_ledger: Arc::new(FlushLedger::default()),max_query_memory_bytes,search_pool: Arc::new(Semaphore::new(max_concurrent_searches)),max_concurrent_searches,@@ -2720,6 +2808,58 @@ impl Drop for MergeReservation {}}+/// How often a flush build waiting for headroom rechecks RSS (#2427).+const FLUSH_BUILD_POLL: Duration = Duration::from_millis(100);++/// Process-wide accounting behind [`FlushBuildReservation`] (#2427).+#[derive(Debug, Default)]+pub(crate) struct FlushLedger {+ state: Mutex<FlushLedgerState>,+ released: tokio::sync::Notify,+}++#[derive(Debug, Default)]+struct FlushLedgerState {+ reserved: u64,+ in_flight: u64,+}++/// One memtable flush build's estimated working set, held from before the+/// freeze until the segment is published (#2427). Counted in the analyze+/// pool so ingest admission sees it; dropping it releases the bytes and wakes+/// a build waiting for headroom.+#[derive(Debug)]+#[must_use = "dropping the reservation releases the flush budget at once"]+pub(crate) struct FlushBuildReservation {+ ledger: Arc<FlushLedger>,+ analyze: AnalyzeReservation,+ bytes: u64,+}++impl FlushBuildReservation {+ /// Bytes this reservation holds.+ pub(crate) fn bytes(&self) -> u64 {+ self.bytes+ }+}++impl Drop for FlushBuildReservation {+ fn drop(&mut self) {+ // Release the admission bytes first, then the ledger slot, so a woken+ // waiter sees both.+ drop(std::mem::replace(+ &mut self.analyze,+ AnalyzeReservation::none(),+ ));+ {+ let mut state = self.ledger.state.lock().unwrap_or_else(|e| e.into_inner());+ state.reserved = state.reserved.saturating_sub(self.bytes);+ state.in_flight = state.in_flight.saturating_sub(1);+ }+ self.ledger.released.notify_waiters();+ }+}+/// Releases an analyze reservation when the batch's tokens exist (#1122).#[derive(Debug)]pub(crate) struct AnalyzeReservation {@@ -5348,4 +5488,89 @@ mod tests {g.refresh(0, raised * 98 / 100, 0);assert!(g.check_ingest_admission().is_err());}++ // ── #2427: flush build reservation ────────────────────────────────────++ const MB: u64 = 1 << 20;++ #[test]+ fn lone_flush_build_is_admitted_even_past_the_watermark() {+ let g = ResourceGovernor::with_analyze_headroom_for_test(64 * MB);+ let r = g+ .try_reserve_flush_build(1024 * MB)+ .expect("lone build admitted");+ assert_eq!(r.bytes(), 1024 * MB);+ assert_eq!(g.flush_build_reserved(), (1024 * MB, 1));+ drop(r);+ assert_eq!(g.flush_build_reserved(), (0, 0));+ assert_eq!(g.analyze_reserved_for_test(), 0);+ }++ #[test]+ fn second_flush_build_waits_when_it_does_not_fit() {+ let g = ResourceGovernor::with_analyze_headroom_for_test(1024 * MB);+ let first = g.try_reserve_flush_build(800 * MB).expect("first build");+ assert!(+ g.try_reserve_flush_build(400 * MB).is_none(),+ "800 + 400 MB over 1 GB of headroom must wait"+ );+ let small = g+ .try_reserve_flush_build(64 * MB)+ .expect("a build that fits is admitted");+ drop(small);+ drop(first);+ let second = g+ .try_reserve_flush_build(400 * MB)+ .expect("fits once the first is done");+ assert_eq!(g.flush_build_reserved(), (400 * MB, 1));+ drop(second);+ }++ #[test]+ fn flush_build_reservation_counts_against_ingest_admission() {+ let g = ResourceGovernor::with_analyze_headroom_for_test(1024 * MB);+ let build = g.try_reserve_flush_build(900 * MB).expect("build");+ assert_eq!(g.analyze_reserved_for_test(), 900 * MB);+ assert!(+ g.reserve_analyze(300 * MB).is_err(),+ "ingest must see the flush working set before it is allocated"+ );+ drop(build);+ assert_eq!(g.analyze_reserved_for_test(), 0);+ let analyze = g.reserve_analyze(300 * MB).expect("fits after the build");+ drop(analyze);+ }++ #[test]+ fn unlimited_watermark_tracks_builds_without_charging_admission() {+ let g = ResourceGovernor::with_analyze_headroom_for_test(MB);+ g.memory_watermark_bytes.store(0, Ordering::Relaxed);+ let a = g.try_reserve_flush_build(500 * MB).expect("a");+ let b = g+ .try_reserve_flush_build(500 * MB)+ .expect("no watermark, no wait");+ assert_eq!(g.flush_build_reserved(), (1000 * MB, 2));+ assert_eq!(g.analyze_reserved_for_test(), 0);+ drop((a, b));+ assert_eq!(g.flush_build_reserved(), (0, 0));+ }++ #[tokio::test]+ async fn waiting_flush_build_is_woken_by_the_release() {+ let g = ResourceGovernor::with_analyze_headroom_for_test(1024 * MB);+ let first = g.try_reserve_flush_build(800 * MB).expect("first build");+ let waiter = {+ let g = Arc::clone(&g);+ tokio::spawn(async move { g.reserve_flush_build(400 * MB).await })+ };+ tokio::time::sleep(Duration::from_millis(250)).await;+ assert!(!waiter.is_finished(), "second build must wait for headroom");+ drop(first);+ let second = tokio::time::timeout(Duration::from_secs(5), waiter)+ .await+ .expect("woken after the release")+ .expect("task");+ assert_eq!(second.bytes(), 400 * MB);+ assert_eq!(g.flush_build_reserved(), (400 * MB, 1));+ }}diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex cf77d6ffa..3c3adae9c 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -38352,6 +38352,79 @@ async fn await_flush_task(}}+/// Working set of one memtable flush build, in percent of the frozen+/// memtable bytes it starts from (#2427). `XERJ_FLUSH_WORKING_SET_PCT`+/// overrides it; `0` turns the flush reservation off.+const FLUSH_WORKING_SET_PCT_DEFAULT: u64 = 200;++/// RSS, in percent of the watermark, above which a finished flush build+/// returns its freed pages to the OS at once (#2427).+const FLUSH_PURGE_RSS_PCT: u64 = 70;++fn flush_working_set_pct() -> u64 {+ static PCT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();+ *PCT.get_or_init(|| {+ std::env::var("XERJ_FLUSH_WORKING_SET_PCT")+ .ok()+ .and_then(|v| v.trim().parse::<u64>().ok())+ .unwrap_or(FLUSH_WORKING_SET_PCT_DEFAULT)+ })+}++/// Estimated working set of a flush build over `memtable_bytes` of frozen+/// memtable (#2427). The build re-parses every source into a `Value`, builds+/// postings and doc-value columns, and encodes the stored section from a+/// JSON copy of the sources, all at once; see [`FLUSH_WORKING_SET_PCT_DEFAULT`].+fn flush_working_set_bytes(memtable_bytes: usize) -> u64 {+ (memtable_bytes as u64).saturating_mul(flush_working_set_pct()) / 100+}++/// Release a finished build's reservation, then return its freed pages to+/// the OS when the process is close to the watermark (#2427).+///+/// jemalloc keeps freed pages resident for `dirty_decay_ms` (1 s). A build+/// frees several hundred MB at once, and on the gate those pages were still+/// resident when the next burst allocated: 454 MB of the 3,364 MB peak was+/// free pages. Purging right away hands them back before the next build+/// starts; under the threshold the decay alone is enough.+fn release_flush_build(reservation: crate::governor::FlushBuildReservation) {+ drop(reservation);+ let Some(governor) = crate::governor::global() else {+ return;+ };+ let watermark = governor.memory_watermark_bytes();+ if flush_build_should_purge(governor.observed_rss_bytes(), watermark) {+ crate::engine::purge_allocator_pages();+ }+}++fn flush_build_should_purge(rss: u64, watermark: u64) -> bool {+ watermark > 0 && rss.saturating_mul(100) >= watermark.saturating_mul(FLUSH_PURGE_RSS_PCT)+}++#[cfg(test)]+mod flush_working_set_tests {+ use super::*;++ #[test]+ fn purge_only_near_the_watermark() {+ assert!(!flush_build_should_purge(1 << 30, 0));+ assert!(!flush_build_should_purge(69, 100));+ assert!(flush_build_should_purge(70, 100));+ assert!(flush_build_should_purge(150, 100));+ }++ #[test]+ fn working_set_scales_with_the_frozen_bytes() {+ let pct = flush_working_set_pct();+ assert_eq!(flush_working_set_bytes(0), 0);+ assert_eq!(+ flush_working_set_bytes(100 << 20),+ (100u64 << 20) * pct / 100+ );+ }+}+#[allow(clippy::too_many_arguments)]async fn do_flush_shard(shard_idx: usize,@@ -38441,6 +38514,57 @@ async fn do_flush_shard(} else {None};+ // #2427 — reserve this build's working set before the freeze. The build+ // (JSON re-parse, postings, doc-value columns, stored encode) allocates a+ // multiple of the frozen memtable bytes, and nothing charged it: each+ // flush burst on the gate was ~550 MB of untracked memory that pushed RSS+ // past the cap. A build that does not fit next to the ones in flight+ // waits for them here; the reservation also counts against ingest+ // admission until the segment is published. Same deadline and same+ // before-the-freeze failure as the gates above.+ let flush_reservation = match crate::governor::global() {+ Some(governor) if !bypass_finalize_gate && flush_working_set_pct() > 0 => {+ let shard_bytes = memtable.shard_load(shard_idx).1;+ let bytes = flush_working_set_bytes(shard_bytes);+ let wait_started = std::time::Instant::now();+ match within_wall_clock(admit_timeout, governor.reserve_flush_build(bytes)).await {+ Some(reservation) => {+ tracing::debug!(+ index = %index_name,+ shard = shard_idx,+ shard_bytes,+ reserved = bytes,+ wait_ms = wait_started.elapsed().as_millis() as u64,+ "flush build working set reserved"+ );+ if std::env::var_os("XERJ_PROF").is_some() {+ eprintln!(+ "XERJ_PROF flush-reserve shard={shard_idx} shard_bytes={shard_bytes} reserved={bytes} wait_us={}",+ wait_started.elapsed().as_micros()+ );+ }+ Some(reservation)+ }+ None => {+ drop(pressure_permit);+ drop(fin_permit);+ on_drained();+ return Err(flush_admit_timeout_error(+ &index_name,+ "the flush memory budget",+ admit_timeout,+ ));+ }+ }+ }+ _ => None,+ };+ let flush_build_trace = flush_reservation.as_ref().map(|reservation| {+ crate::ingest_memory::Retained::new(+ crate::ingest_memory::Category::FlushBuild,+ reservation.bytes() as usize,+ )+ });// #1015 — NO collection-publication guard here. The drain below is a// FREEZE, not a removal: the claimed docs stay reader-visible in the// shard's frozen generations for the whole segment build, so there is@@ -38649,7 +38773,9 @@ async fn do_flush_shard(let segments_dir = data_dir.join("segments");let registry_for_build = Arc::clone(®istry);let fts_doc_count = drained_fts.len();- let drained_fts_for_build = Arc::clone(&drained_fts);+ // Moved, not cloned: the build closure is the last owner, so the parsed+ // payload is freed as soon as the side-cars are written (#2427).+ let drained_fts_for_build = drained_fts;let segments_dir_for_dv = segments_dir.clone();let store_for_warm = Arc::clone(&store);// POV battery (B-3) caught that gating FTS+DV on the raw-bytes path@@ -38819,7 +38945,7 @@ async fn do_flush_shard(// dispatch.let t_finalize = std::time::Instant::now();let store_for_finalize = Arc::clone(&store);- let storage_drained_for_finalize = Arc::clone(&storage_drained);+ let storage_drained_for_finalize = storage_drained;// #1015 — the claim rides the coordinator into the worker: the build// holds it (frozen generations stay reader-visible), publish RETIRES it// inside the bracket, and every failure path releases it.@@ -38836,114 +38962,132 @@ async fn do_flush_shard(let joined = tokio::task::spawn_blocking(move || {let _fin_permit = fin_permit;let _pressure_permit = pressure_permit;- // This lease lives in the blocking worker, not either async waiter.- // It spans build→publish exactly as before: it tracks the caches- // `build_fts` warms so a failed publication can evict them.- let lease =- PrePublicationLease::tracked(failed_warm_caches, Arc::clone(&warmed_segment_id));- // ── BUILD — NO publication bracket (#1015). The frozen- // generations keep the drained docs fully reader-visible- // (postings, doc-values, sources) while the segment and its- // side-cars are written; a search racing the build sees the- // exact same doc set as before the flush started. ──- let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- crate::background_pool().install(|| {- store_for_finalize.build_flush_segment(&storage_drained_for_finalize, build_fts)- })- }));- let meta = match built {- Ok(Ok(meta)) => meta,- Ok(Err(error)) => {- // Build failed before anything reader-visible happened:- // release the claim — the frozen generations stay- // readable and unclaimed, so the next flush of this- // shard recycles them. This pointer-flag flip replaces- // the old `restore_failed_flush` re-insert entirely- // (the docs never left the view, so there is nothing to- // re-insert and no version-map resurrection guard to- // re-check).- claim_for_finalize.release();- return Ok(Err(error));- }- Err(payload) => {- claim_for_finalize.release();- std::panic::resume_unwind(payload);- }- };- // ── PUBLISH — the ONLY reader-visible instant (#1015). The- // bracket opened here spans: version-map repoint, the snapshot- // rcu, the frozen-generation retire, and the guard commit —- // millisecond-scale. A capture that straddles any part of it- // fails the #1014 evenness check and retries on the next- // instant, instead of retrying against the full drain+build- // (~600 ms) window the old pre-drain bracket held. ──- let mut collection_publication_guard = match collection_publication.begin() {- Ok(guard) => guard,- Err(_) => {- claim_for_finalize.release();- return Err(collection_publication_interrupted());- }- };- let published = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- crate::background_pool().install(|| {- store_for_finalize.publish_flush_segment(&storage_drained_for_finalize, &meta)- })- }));- let outcome = match published {- Ok(Ok(- outcome @ xerj_storage::index_store::FlushFinalizeOutcome::Published { .. },- )) => {- // Retire INSIDE the bracket, immediately after the- // snapshot swap: "the segment is in the snapshot" and- // "the frozen docs left the memtable" are one atomic- // instant for capturing readers. The freed bytes leave- // the memtable aggregate here (they were resident — and- // charged — for the whole build).- let _retained = claim_for_finalize.retire();- collection_publication_guard.commit();- // finalize published the snapshot before it returned;- // commit the lease while still in the worker, no await.- lease.commit();- outcome- }- Ok(Ok(xerj_storage::index_store::FlushFinalizeOutcome::Empty)) => {- // publish_flush_segment never returns Empty on a- // non-empty drain set (build_flush_segment errors- // first); handle it defensively as a failure.- claim_for_finalize.release();- collection_publication_guard.cancel();- xerj_storage::index_store::FlushFinalizeOutcome::Empty- }- Ok(Err(error)) => {- // Publication failed and was rolled back (failpoints- // included): the segment is abandoned, the version map- // is restored, and the docs must stay visible — release- // the claim so the next flush retries them.- claim_for_finalize.release();- collection_publication_guard.cancel();- return Ok(Err(error));- }- Err(payload) => {- claim_for_finalize.release();- collection_publication_guard.cancel();- std::panic::resume_unwind(payload);- }- };- // ── POST-publish maintenance — OUTSIDE the bracket (#1015):- // the bucket catalog PUT is network I/O and the WAL- // checkpoint/prune takes locks; neither belongs between- // `begin()` and `commit()`. Deferred failures are warn-only —- // the segment is already published. ──- if let Err(error) =- store_for_finalize.after_flush_publish(&storage_drained_for_finalize, &meta)- {- tracing::warn!(- error = %error,- segment_id = %meta.id,- "flush maintenance deferred after publication"+ let flush_reservation = flush_reservation;+ let flush_build_trace = flush_build_trace;+ // The build, publish and maintenance run in this inner closure so+ // every payload it owns (drained docs, segment buffers) is freed+ // before the reservation is released below (#2427).+ let result = (move || {+ // This lease lives in the blocking worker, not either async waiter.+ // It spans build→publish exactly as before: it tracks the caches+ // `build_fts` warms so a failed publication can evict them.+ let lease = PrePublicationLease::tracked(+ failed_warm_caches,+ Arc::clone(&warmed_segment_id),);+ // ── BUILD — NO publication bracket (#1015). The frozen+ // generations keep the drained docs fully reader-visible+ // (postings, doc-values, sources) while the segment and its+ // side-cars are written; a search racing the build sees the+ // exact same doc set as before the flush started. ──+ let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ crate::background_pool().install(|| {+ store_for_finalize+ .build_flush_segment(&storage_drained_for_finalize, build_fts)+ })+ }));+ let meta = match built {+ Ok(Ok(meta)) => meta,+ Ok(Err(error)) => {+ // Build failed before anything reader-visible happened:+ // release the claim — the frozen generations stay+ // readable and unclaimed, so the next flush of this+ // shard recycles them. This pointer-flag flip replaces+ // the old `restore_failed_flush` re-insert entirely+ // (the docs never left the view, so there is nothing to+ // re-insert and no version-map resurrection guard to+ // re-check).+ claim_for_finalize.release();+ return Ok(Err(error));+ }+ Err(payload) => {+ claim_for_finalize.release();+ std::panic::resume_unwind(payload);+ }+ };+ // ── PUBLISH — the ONLY reader-visible instant (#1015). The+ // bracket opened here spans: version-map repoint, the snapshot+ // rcu, the frozen-generation retire, and the guard commit —+ // millisecond-scale. A capture that straddles any part of it+ // fails the #1014 evenness check and retries on the next+ // instant, instead of retrying against the full drain+build+ // (~600 ms) window the old pre-drain bracket held. ──+ let mut collection_publication_guard = match collection_publication.begin() {+ Ok(guard) => guard,+ Err(_) => {+ claim_for_finalize.release();+ return Err(collection_publication_interrupted());+ }+ };+ let published = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ crate::background_pool().install(|| {+ store_for_finalize+ .publish_flush_segment(&storage_drained_for_finalize, &meta)+ })+ }));+ let outcome = match published {+ Ok(Ok(+ outcome @ xerj_storage::index_store::FlushFinalizeOutcome::Published {+ ..+ },+ )) => {+ // Retire INSIDE the bracket, immediately after the+ // snapshot swap: "the segment is in the snapshot" and+ // "the frozen docs left the memtable" are one atomic+ // instant for capturing readers. The freed bytes leave+ // the memtable aggregate here (they were resident — and+ // charged — for the whole build).+ let _retained = claim_for_finalize.retire();+ collection_publication_guard.commit();+ // finalize published the snapshot before it returned;+ // commit the lease while still in the worker, no await.+ lease.commit();+ outcome+ }+ Ok(Ok(xerj_storage::index_store::FlushFinalizeOutcome::Empty)) => {+ // publish_flush_segment never returns Empty on a+ // non-empty drain set (build_flush_segment errors+ // first); handle it defensively as a failure.+ claim_for_finalize.release();+ collection_publication_guard.cancel();+ xerj_storage::index_store::FlushFinalizeOutcome::Empty+ }+ Ok(Err(error)) => {+ // Publication failed and was rolled back (failpoints+ // included): the segment is abandoned, the version map+ // is restored, and the docs must stay visible — release+ // the claim so the next flush retries them.+ claim_for_finalize.release();+ collection_publication_guard.cancel();+ return Ok(Err(error));+ }+ Err(payload) => {+ claim_for_finalize.release();+ collection_publication_guard.cancel();+ std::panic::resume_unwind(payload);+ }+ };+ // ── POST-publish maintenance — OUTSIDE the bracket (#1015):+ // the bucket catalog PUT is network I/O and the WAL+ // checkpoint/prune takes locks; neither belongs between+ // `begin()` and `commit()`. Deferred failures are warn-only —+ // the segment is already published. ──+ if let Err(error) =+ store_for_finalize.after_flush_publish(&storage_drained_for_finalize, &meta)+ {+ tracing::warn!(+ error = %error,+ segment_id = %meta.id,+ "flush maintenance deferred after publication"+ );+ }+ Ok(Ok(outcome))+ })();+ drop(flush_build_trace);+ if let Some(reservation) = flush_reservation {+ release_flush_build(reservation);}- Ok(Ok(outcome))+ result}).await;match joined {diff --git a/engine/crates/xerj-engine/src/ingest_memory.rs b/engine/crates/xerj-engine/src/ingest_memory.rsindex d0865c0e9..a1c8a13c5 100644--- a/engine/crates/xerj-engine/src/ingest_memory.rs+++ b/engine/crates/xerj-engine/src/ingest_memory.rs@@ -133,10 +133,14 @@ pub enum Category {/// from every open index (#2427). Lives as long as the index is open/// and grows with every distinct doc id.VersionMap,+ /// Estimated working set of in-flight memtable flush builds (#2427):+ /// the governor's flush reservation, held from before the freeze until+ /// the segment is published.+ FlushBuild,}impl Category {- pub const ALL: [Self; 25] = [+ pub const ALL: [Self; 26] = [Self::HttpBody,Self::HttpRewriteBuffer,Self::RawSource,@@ -162,6 +166,7 @@ impl Category {Self::CacheVectorColumn,Self::VectorGraph,Self::VersionMap,+ Self::FlushBuild,];const COUNT: usize = Self::ALL.len();@@ -518,6 +523,7 @@ fn measurement(category: Category) -> Measurement {| Category::CacheVectorColumn| Category::VectorGraph| Category::VersionMap+ | Category::FlushBuild| Category::MergeDecoded| Category::MergeSurvivor| Category::MergeParsed => Measurement::Estimated,