Skip to main content

hermes_core/index/
writer.rs

1//! IndexWriter — async document indexing with parallel segment building.
2//!
3//! This module is only compiled with the "native" feature.
4//!
5//! # Architecture
6//!
7//! ```text
8//! add_document() ──try_send──► [shared bounded MPMC] ◄──recv── worker 0
9//!                                                     ◄──recv── worker 1
10//!                                                     ◄──recv── worker N
11//! ```
12//!
13//! - **Shared MPMC queue** (`async_channel`): all workers compete for documents.
14//!   Busy workers (building segments) naturally stop pulling; free workers pick up slack.
15//! - **Zero-copy pipeline**: `Document` is moved (never cloned) through every stage:
16//!   `add_document()` → channel → `recv_blocking()` → `SegmentBuilder::add_document()`.
17//! - `add_document` returns `QueueFull` when the queue is at capacity.
18//! - **Workers are OS threads**: CPU-intensive work (tokenization, posting list building)
19//!   runs on dedicated threads, never blocking the tokio async runtime.
20//!   Async I/O (segment file writes) is bridged via `Handle::block_on()`.
21//! - **Fixed per-worker memory budget**: `max_indexing_memory_bytes / num_workers`.
22//!   Workers use deterministic, staggered soft flush thresholds within that
23//!   budget so equal-size builders do not all stop draining at once.
24//! - **Build concurrency reserve**: while input is open, at most `N - 1`
25//!   workers build segments concurrently. A worker that cannot get a slot
26//!   keeps draining up to the former 80% flush boundary. Once input closes,
27//!   all `N` tail builds may finish concurrently because no drainer is needed.
28//! - **Two-phase commit**:
29//!   1. `prepare_commit()` — closes queue, workers flush builders to disk.
30//!      Returns a `PreparedCommit` guard. No new documents accepted until resolved.
31//!   2. `PreparedCommit::commit()` — registers segments in metadata, resumes workers.
32//!   3. `PreparedCommit::abort()` — discards prepared segments, resumes workers.
33//!   4. `commit()` — convenience: `prepare_commit().await?.commit().await`.
34//!
35//! Since `prepare_commit`/`commit` take `&mut self`, Rust’s borrow checker
36//! guarantees no concurrent `add_document` calls during the commit window.
37
38use std::sync::Arc;
39use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
40
41use futures::FutureExt;
42use rustc_hash::FxHashMap;
43
44use crate::directories::DirectoryWriter;
45use crate::dsl::{Document, Field, Schema};
46use crate::error::{Error, Result};
47use crate::segment::{SegmentBuilder, SegmentBuilderConfig, SegmentId};
48use crate::tokenizer::BoxedTokenizer;
49
50use super::IndexConfig;
51
52/// Total pipeline capacity (in documents).
53const PIPELINE_MAX_SIZE_IN_DOCS: usize = 10_000;
54
55/// Builder memory percentage at which the first worker starts trying to flush.
56///
57/// The last worker starts at [`SOFT_FLUSH_MAX_PERCENT`], preserving the former
58/// 20% segment-build headroom. Intermediate workers are evenly staggered
59/// between the two bounds.
60const SOFT_FLUSH_MIN_PERCENT: usize = 70;
61const SOFT_FLUSH_MAX_PERCENT: usize = 80;
62
63/// File name of the advisory single-writer lock inside the index directory.
64pub const WRITER_LOCK_FILENAME: &str = ".hermes_writer.lock";
65
66/// Return a deterministic per-worker soft flush threshold.
67///
68/// All thresholds remain at or below the former uniform 80% trigger, so their
69/// sum cannot increase builder memory. The 70–80% spread prevents identical
70/// workers consuming the shared queue at the same rate from entering segment
71/// builds in lockstep.
72fn soft_flush_threshold(memory_budget: usize, worker_id: usize, num_workers: usize) -> usize {
73    if num_workers <= 1 {
74        return hard_flush_threshold(memory_budget);
75    }
76
77    let worker_id = worker_id.min(num_workers - 1);
78    let span = SOFT_FLUSH_MAX_PERCENT - SOFT_FLUSH_MIN_PERCENT;
79    let denominator = 100u128 * (num_workers - 1) as u128;
80    let numerator = (SOFT_FLUSH_MIN_PERCENT * (num_workers - 1) + span * worker_id) as u128;
81    ((memory_budget as u128 * numerator) / denominator) as usize
82}
83
84/// Preserve the historical 20% allowance for allocations created while a
85/// segment is finalized. Workers may stagger below this boundary, but no
86/// queued builder consumes the scratch reserve while waiting for a build slot.
87fn hard_flush_threshold(memory_budget: usize) -> usize {
88    memory_budget.saturating_mul(SOFT_FLUSH_MAX_PERCENT) / 100
89}
90
91/// Derive the builder defaults used by the standard writer constructors.
92///
93/// `IndexConfig::num_compression_threads` is the public per-index setting; it
94/// must reach segment builders instead of being replaced by the machine-wide
95/// `SegmentBuilderConfig` default. Explicit `*_with_config` constructors bypass
96/// this helper and continue honoring every supplied builder option.
97fn default_builder_config(index_config: &IndexConfig) -> SegmentBuilderConfig {
98    SegmentBuilderConfig {
99        num_compression_threads: index_config.num_compression_threads,
100        ..SegmentBuilderConfig::default()
101    }
102}
103
104/// Bounds simultaneous segment finalization while reserving an indexing
105/// worker to drain the shared document queue.
106///
107/// A soft-threshold worker first tries to acquire without waiting. If every
108/// slot is occupied it may continue indexing until its hard per-worker memory
109/// flush boundary. At that hard limit it waits, preserving the remaining 20%
110/// of every worker share for finalization scratch.
111struct SegmentBuildLimiter {
112    live_max_active: usize,
113    flush_max_active: usize,
114    active: AtomicUsize,
115    flushing: AtomicBool,
116    wait_mutex: parking_lot::Mutex<()>,
117    available: parking_lot::Condvar,
118}
119
120impl SegmentBuildLimiter {
121    fn new(num_workers: usize) -> Self {
122        Self {
123            // A single-worker writer must still be able to build. With two or
124            // more workers, reserve one worker from concurrent finalization.
125            live_max_active: num_workers.saturating_sub(1).max(1),
126            // Once the input queue closes there is no ingestion to reserve;
127            // flush every tail concurrently as the old writer did.
128            flush_max_active: num_workers.max(1),
129            active: AtomicUsize::new(0),
130            flushing: AtomicBool::new(false),
131            wait_mutex: parking_lot::Mutex::new(()),
132            available: parking_lot::Condvar::new(),
133        }
134    }
135
136    fn try_acquire(&self) -> Option<SegmentBuildPermit<'_>> {
137        self.try_acquire_up_to(self.live_max_active)
138    }
139
140    fn try_acquire_up_to(&self, limit: usize) -> Option<SegmentBuildPermit<'_>> {
141        let mut active = self.active.load(Ordering::Acquire);
142        loop {
143            if active >= limit {
144                return None;
145            }
146            match self.active.compare_exchange_weak(
147                active,
148                active + 1,
149                Ordering::AcqRel,
150                Ordering::Acquire,
151            ) {
152                Ok(_) => return Some(SegmentBuildPermit { limiter: self }),
153                Err(observed) => active = observed,
154            }
155        }
156    }
157
158    fn acquire(&self) -> SegmentBuildPermit<'_> {
159        let mut wait = self.wait_mutex.lock();
160        loop {
161            let limit = if self.flushing.load(Ordering::Acquire) {
162                self.flush_max_active
163            } else {
164                self.live_max_active
165            };
166            if let Some(permit) = self.try_acquire_up_to(limit) {
167                return permit;
168            }
169            self.available.wait(&mut wait);
170        }
171    }
172
173    fn acquire_flush(&self) -> SegmentBuildPermit<'_> {
174        self.acquire_up_to(self.flush_max_active)
175    }
176
177    fn acquire_up_to(&self, limit: usize) -> SegmentBuildPermit<'_> {
178        let mut wait = self.wait_mutex.lock();
179        loop {
180            if let Some(permit) = self.try_acquire_up_to(limit) {
181                return permit;
182            }
183            self.available.wait(&mut wait);
184        }
185    }
186
187    /// Promote existing live waiters when input closes. Store the phase before
188    /// taking the condvar mutex; a waiter either observes it directly or
189    /// releases the mutex in `wait`, after which this notification reaches it.
190    fn begin_flush(&self) {
191        self.flushing.store(true, Ordering::Release);
192        let _wait = self.wait_mutex.lock();
193        self.available.notify_all();
194    }
195
196    fn end_flush(&self) {
197        self.flushing.store(false, Ordering::Release);
198    }
199
200    /// Reserve a build slot once `builder_memory` reaches its soft threshold.
201    ///
202    /// When all slots are busy, `None` below `hard_budget` means "keep
203    /// draining". At the hard budget this waits for a slot rather than
204    /// exceeding the configured per-worker memory share.
205    fn reserve_if_due(
206        &self,
207        builder_memory: usize,
208        soft_threshold: usize,
209        hard_budget: usize,
210    ) -> Option<SegmentBuildPermit<'_>> {
211        if builder_memory < soft_threshold {
212            return None;
213        }
214        if let Some(permit) = self.try_acquire() {
215            return Some(permit);
216        }
217        if builder_memory < hard_budget {
218            return None;
219        }
220        Some(self.acquire())
221    }
222}
223
224struct SegmentBuildPermit<'a> {
225    limiter: &'a SegmentBuildLimiter,
226}
227
228impl Drop for SegmentBuildPermit<'_> {
229    fn drop(&mut self) {
230        let previous = self.limiter.active.fetch_sub(1, Ordering::AcqRel);
231        debug_assert!(previous > 0);
232        // Synchronize notification with acquire's condvar wait so a permit
233        // becoming free cannot be missed between its check and sleeping.
234        let _wait = self.limiter.wait_mutex.lock();
235        // Live-ingestion and closed-queue flush waiters have different limits;
236        // wake both classes so the reserved flush slot cannot be stranded.
237        self.limiter.available.notify_all();
238    }
239}
240
241#[cfg(test)]
242mod indexing_pipeline_tests {
243    use std::sync::Arc;
244    use std::time::Duration;
245
246    use super::{
247        SOFT_FLUSH_MAX_PERCENT, SOFT_FLUSH_MIN_PERCENT, SegmentBuildLimiter,
248        default_builder_config, hard_flush_threshold, soft_flush_threshold,
249    };
250
251    #[test]
252    fn standard_builder_config_honors_index_compression_width() {
253        let index_config = crate::index::IndexConfig {
254            num_compression_threads: 7,
255            ..Default::default()
256        };
257
258        let builder_config = default_builder_config(&index_config);
259
260        assert_eq!(builder_config.num_compression_threads, 7);
261    }
262
263    #[test]
264    fn flush_thresholds_are_staggered_without_increasing_memory_budget() {
265        const WORKERS: usize = 12;
266        const PER_WORKER_BUDGET: usize = 1024 * 1024 * 1024;
267
268        let thresholds: Vec<_> = (0..WORKERS)
269            .map(|worker| soft_flush_threshold(PER_WORKER_BUDGET, worker, WORKERS))
270            .collect();
271
272        assert_eq!(
273            thresholds[0],
274            PER_WORKER_BUDGET * SOFT_FLUSH_MIN_PERCENT / 100
275        );
276        assert_eq!(
277            thresholds[WORKERS - 1],
278            PER_WORKER_BUDGET * SOFT_FLUSH_MAX_PERCENT / 100
279        );
280        assert!(
281            thresholds.windows(2).all(|pair| pair[0] < pair[1]),
282            "production-width workers must not reach identical flush thresholds: {thresholds:?}"
283        );
284
285        let staggered_total: usize = thresholds.iter().sum();
286        let former_uniform_total = WORKERS * (PER_WORKER_BUDGET * SOFT_FLUSH_MAX_PERCENT / 100);
287        assert!(
288            staggered_total <= former_uniform_total,
289            "staggering must not increase aggregate builder memory"
290        );
291
292        assert_eq!(
293            soft_flush_threshold(PER_WORKER_BUDGET, 0, 1),
294            PER_WORKER_BUDGET * SOFT_FLUSH_MAX_PERCENT / 100,
295            "single-worker behavior retains the former 80% build headroom"
296        );
297
298        let hard_threshold = hard_flush_threshold(PER_WORKER_BUDGET);
299        let build_scratch = PER_WORKER_BUDGET - hard_threshold;
300        let steady_state_peak = (WORKERS - 1) * (hard_threshold + build_scratch) + hard_threshold;
301        assert!(
302            steady_state_peak <= WORKERS * PER_WORKER_BUDGET,
303            "rotated hard-threshold builds must retain aggregate scratch headroom"
304        );
305    }
306
307    #[test]
308    fn full_build_gate_leaves_soft_threshold_worker_draining() {
309        const WORKERS: usize = 12;
310        let limiter = SegmentBuildLimiter::new(WORKERS);
311        let mut active_builds: Vec<_> = (0..WORKERS - 1)
312            .map(|_| {
313                limiter
314                    .try_acquire()
315                    .expect("N - 1 builds should be admitted")
316            })
317            .collect();
318
319        assert!(
320            limiter.try_acquire().is_none(),
321            "the final worker must be reserved from concurrent segment builds"
322        );
323        assert!(
324            limiter.reserve_if_due(750, 700, 800).is_none(),
325            "a worker below its hard budget must keep draining when builds are saturated"
326        );
327
328        drop(active_builds.pop());
329        let replacement = limiter
330            .reserve_if_due(750, 700, 800)
331            .expect("a completed build must immediately rotate draining capacity");
332        assert!(limiter.try_acquire().is_none());
333        drop(replacement);
334        drop(active_builds);
335    }
336
337    #[test]
338    fn closed_queue_flush_uses_the_reserved_build_slot() {
339        let limiter = SegmentBuildLimiter::new(2);
340        let live_build = limiter
341            .try_acquire()
342            .expect("one live build should be admitted");
343        assert!(limiter.try_acquire().is_none());
344
345        let tail_build = limiter.acquire_flush();
346        assert!(
347            limiter
348                .try_acquire_up_to(limiter.flush_max_active)
349                .is_none(),
350            "closed-queue flushes must remain bounded by the worker count"
351        );
352
353        drop(tail_build);
354        drop(live_build);
355    }
356
357    #[test]
358    fn closing_input_promotes_an_existing_live_waiter() {
359        let limiter = Arc::new(SegmentBuildLimiter::new(2));
360        let live_build = limiter.try_acquire().unwrap();
361        let waiter_limiter = Arc::clone(&limiter);
362        let (started_tx, started_rx) = std::sync::mpsc::channel();
363        let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
364
365        let waiter = std::thread::spawn(move || {
366            started_tx.send(()).unwrap();
367            let _permit = waiter_limiter
368                .reserve_if_due(800, 700, 800)
369                .expect("closed input must promote a hard-boundary waiter");
370            acquired_tx.send(()).unwrap();
371        });
372
373        started_rx.recv_timeout(Duration::from_secs(1)).unwrap();
374        assert!(acquired_rx.recv_timeout(Duration::from_millis(50)).is_err());
375
376        limiter.begin_flush();
377        acquired_rx
378            .recv_timeout(Duration::from_secs(1))
379            .expect("live waiter did not adopt the closed-queue build limit");
380        waiter.join().unwrap();
381        limiter.end_flush();
382        drop(live_build);
383    }
384
385    #[test]
386    fn hard_budget_waiter_resumes_when_a_build_finishes() {
387        let limiter = Arc::new(SegmentBuildLimiter::new(3));
388        let first = limiter.try_acquire().unwrap();
389        let second = limiter.try_acquire().unwrap();
390        let waiter_limiter = Arc::clone(&limiter);
391        let (started_tx, started_rx) = std::sync::mpsc::channel();
392        let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
393
394        let waiter = std::thread::spawn(move || {
395            started_tx.send(()).unwrap();
396            let _permit = waiter_limiter
397                .reserve_if_due(800, 700, 800)
398                .expect("hard-budget worker must eventually acquire a build slot");
399            acquired_tx.send(()).unwrap();
400        });
401
402        started_rx.recv_timeout(Duration::from_secs(1)).unwrap();
403        assert!(
404            acquired_rx.recv_timeout(Duration::from_millis(50)).is_err(),
405            "hard-budget worker must not over-subscribe segment builds"
406        );
407        drop(first);
408        acquired_rx
409            .recv_timeout(Duration::from_secs(1))
410            .expect("hard-budget worker did not wake after a build completed");
411        waiter.join().unwrap();
412        drop(second);
413    }
414}
415
416/// Advisory single-writer lock state.
417///
418/// Two independent writers on one index directory silently destroy each
419/// other's data: the orphan sweep at writer open deletes the other process's
420/// unpublished segment files, and metadata saves are last-writer-wins. For
421/// directories rooted on a local filesystem the writer therefore holds an OS
422/// advisory lock for its whole lifetime; the kernel releases it automatically
423/// when the process dies.
424enum WriterLock {
425    /// Lock acquired. Closing the file (writer drop) releases it.
426    Held { _file: std::fs::File },
427    /// The directory has no lockable local filesystem root (e.g. RAM or
428    /// remote directories) — cross-process locking is not applicable.
429    NotApplicable,
430    /// Another writer holds the lock. Every mutating operation fails loudly
431    /// with this message instead of silently double-writing.
432    Unavailable { reason: String },
433}
434
435/// Local filesystem root of the index directory, when the directory type
436/// exposes one.
437fn writer_lock_root<D: DirectoryWriter + 'static>(directory: &D) -> Option<std::path::PathBuf> {
438    let any: &dyn std::any::Any = directory;
439    if let Some(mmap) = any.downcast_ref::<crate::directories::MmapDirectory>() {
440        return Some(mmap.root().to_path_buf());
441    }
442    // FsDirectory does not expose its root path, so the single-writer lock
443    // cannot be enforced for it yet. Say so loudly instead of silently
444    // skipping protection for a filesystem-backed writer.
445    if any
446        .downcast_ref::<crate::directories::FsDirectory>()
447        .is_some()
448    {
449        log::warn!(
450            "[writer_lock] FsDirectory exposes no root path; single-writer locking \
451             is not enforced for this writer — do not open a second writer for the \
452             same index directory"
453        );
454    }
455    None
456}
457
458/// Try to take the exclusive single-writer lock for `directory`.
459///
460/// Returns `WriterLock::Unavailable` (not `Err`) on conflict so infallible
461/// constructors can defer the failure to their first mutating operation.
462fn try_acquire_writer_lock<D: DirectoryWriter + 'static>(directory: &D) -> Result<WriterLock> {
463    let Some(root) = writer_lock_root(directory) else {
464        return Ok(WriterLock::NotApplicable);
465    };
466    std::fs::create_dir_all(&root)?;
467    let lock_path = root.join(WRITER_LOCK_FILENAME);
468    let file = std::fs::OpenOptions::new()
469        .create(true)
470        .truncate(false)
471        .write(true)
472        .open(&lock_path)?;
473    match file.try_lock() {
474        Ok(()) => Ok(WriterLock::Held { _file: file }),
475        Err(std::fs::TryLockError::WouldBlock) => Ok(WriterLock::Unavailable {
476            reason: format!(
477                "another IndexWriter already holds the single-writer lock for this \
478                 index ({}); Hermes supports one writer per index directory — stop \
479                 the other writer (e.g. a running hermes-server or hermes-tool) \
480                 before opening this one",
481                lock_path.display()
482            ),
483        }),
484        Err(std::fs::TryLockError::Error(error)) => Err(Error::Io(error)),
485    }
486}
487
488/// Async IndexWriter for adding documents and committing segments.
489///
490/// **Backpressure:** `add_document()` is sync and O(1). It returns
491/// `Error::QueueFull` when the shared queue is full and
492/// `Error::CommitInProgress` while a generation is publishing or awaiting
493/// retry; callers must back off.
494///
495/// **Two-phase commit:**
496/// - `prepare_commit()` → `PreparedCommit::commit()` or `PreparedCommit::abort()`
497/// - `commit()` is a convenience that does both phases.
498/// - Between prepare and commit, the caller can do external work (WAL, sync, etc.)
499///   knowing that abort is possible if something fails.
500/// - Dropping `PreparedCommit` without calling commit/abort auto-aborts.
501pub struct IndexWriter<D: DirectoryWriter + 'static> {
502    pub(super) directory: Arc<D>,
503    pub(super) schema: Arc<Schema>,
504    pub(super) config: IndexConfig,
505    /// MPMC sender, replaced under a brief lock on each commit cycle (workers
506    /// get the corresponding new receiver via resume).
507    doc_sender: Arc<parking_lot::RwLock<async_channel::Sender<Document>>>,
508    /// Worker OS thread handles — long-lived, survive across commits.
509    workers: Vec<std::thread::JoinHandle<()>>,
510    /// Shared worker state (immutable config + mutable segment output + sync)
511    worker_state: Arc<WorkerState<D>>,
512    /// Segment manager — owns metadata.json, handles segments and background merging
513    pub(super) segment_manager: Arc<crate::merge::SegmentManager<D>>,
514    /// Segments flushed to disk but not yet registered in metadata. Each item
515    /// owns an active-operation guard, so orphan sweeping cannot delete it.
516    flushed_segments: Arc<parking_lot::Mutex<Vec<PreparedSegment<D>>>>,
517    /// Primary key dedup index (None if schema has no primary field)
518    primary_key_index: Arc<parking_lot::RwLock<Option<super::primary_key::PrimaryKeyIndex>>>,
519    /// Serializes async snapshot acquisition/loading across commits and
520    /// lifecycle-owned merge/reorder topology refreshes.
521    primary_key_refresh_lock: Arc<tokio::sync::Mutex<()>>,
522    /// Tracks the owned finalizer spawned by `PreparedCommit::commit`. The
523    /// requesting future may disappear, but a second commit generation must
524    /// not start until this one has made publication and worker state agree.
525    commit_finalization: Arc<CommitFinalizationState>,
526    /// True while a failed post-commit PK refresh has left the uncommitted
527    /// reservations as the ONLY record of already-committed keys (fail-closed,
528    /// see `finalize_prepared_commit`). While set, abort paths must NOT clear
529    /// the reservations or duplicate primary keys could be admitted.
530    pk_reservations_retained: Arc<AtomicBool>,
531    /// Advisory single-writer lock, held for the writer's lifetime.
532    /// `Unavailable` is retryable: the conflicting holder may exit at any
533    /// time (the kernel then releases its lock), so `ensure_writer_lock`
534    /// re-attempts acquisition instead of caching the conflict forever.
535    writer_lock: parking_lot::RwLock<WriterLock>,
536}
537
538#[derive(Default)]
539struct CommitFinalizationState {
540    in_progress: AtomicBool,
541    idle: tokio::sync::Notify,
542}
543
544impl CommitFinalizationState {
545    fn begin(&self) -> bool {
546        self.in_progress
547            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
548            .is_ok()
549    }
550
551    fn finish(&self) {
552        self.in_progress.store(false, Ordering::Release);
553        self.idle.notify_waiters();
554    }
555
556    async fn wait_until_idle(&self) {
557        while self.in_progress.load(Ordering::Acquire) {
558            let notified = self.idle.notified();
559            if !self.in_progress.load(Ordering::Acquire) {
560                break;
561            }
562            notified.await;
563        }
564    }
565}
566
567/// Shared state for worker threads.
568struct WorkerState<D: DirectoryWriter + 'static> {
569    directory: Arc<D>,
570    schema: Arc<Schema>,
571    builder_config: SegmentBuilderConfig,
572    tokenizers: parking_lot::RwLock<FxHashMap<Field, BoxedTokenizer>>,
573    /// Fixed per-worker memory budget (bytes). When a builder exceeds this, segment is built.
574    memory_budget_per_worker: usize,
575    /// Limits live segment finalization to N - 1 workers, reserving
576    /// queue-draining capacity; closed-queue tail flushes may use all N.
577    segment_build_limiter: SegmentBuildLimiter,
578    /// Segment manager — workers read trained structures from its ArcSwap (lock-free).
579    segment_manager: Arc<crate::merge::SegmentManager<D>>,
580    /// Segments built by workers, collected by `prepare_commit()`. Their RAII
581    /// guards protect both in-progress and completed-uncommitted files.
582    built_segments: parking_lot::Mutex<Vec<PreparedSegment<D>>>,
583    /// First failure in the current flush generation. Worker-side indexing is
584    /// asynchronous, so `prepare_commit` is the only sound place to surface
585    /// it to the caller. A failed generation is aborted as a unit; publishing
586    /// only its successful segments would silently lose documents.
587    cycle_error: parking_lot::Mutex<Option<String>>,
588    cycle_failed: AtomicBool,
589
590    // === Worker lifecycle synchronization ===
591    // Workers survive across commits. On prepare_commit the channel is closed;
592    // workers flush their builders, increment flush_count, then wait on
593    // resume_cvar for a new receiver. commit/abort creates a fresh channel
594    // and wakes them.
595    /// Number of workers that have completed their flush.
596    flush_count: AtomicUsize,
597    /// Mutex + condvar for prepare_commit to wait on all workers flushed.
598    flush_mutex: parking_lot::Mutex<()>,
599    flush_cvar: parking_lot::Condvar,
600    /// Holds the new channel receiver after commit/abort. Workers clone from this.
601    resume_receiver: parking_lot::Mutex<Option<async_channel::Receiver<Document>>>,
602    /// Monotonically increasing epoch, bumped by each resume_workers call.
603    /// Workers compare against their local epoch to avoid re-cloning a stale receiver.
604    resume_epoch: AtomicUsize,
605    /// Condvar for workers to wait for resume (new channel) or shutdown.
606    resume_cvar: parking_lot::Condvar,
607    /// When true, workers should exit permanently (IndexWriter dropped).
608    shutdown: AtomicBool,
609    /// Total number of worker threads.
610    num_workers: usize,
611}
612
613/// A completed indexing segment that has not been published in metadata yet.
614///
615/// `operation` is intentionally data, not a side-channel set update: moving
616/// this value through worker → prepared commit → commit/abort moves lifecycle
617/// ownership with it, and every unwind/drop path releases ownership safely.
618struct PreparedSegment<D: DirectoryWriter + 'static> {
619    id: String,
620    segment_id: SegmentId,
621    num_docs: u32,
622    segment_manager: Arc<crate::merge::SegmentManager<D>>,
623    operation: Option<crate::merge::SegmentOperationGuard>,
624    runtime: tokio::runtime::Handle,
625    needs_vector_upgrade: bool,
626    published: bool,
627}
628
629impl<D: DirectoryWriter + 'static> PreparedSegment<D> {
630    fn metadata_entry(&self) -> (String, u32) {
631        (self.id.clone(), self.num_docs)
632    }
633
634    fn mark_published(&mut self) {
635        self.published = true;
636        // Metadata + SegmentTracker are now the durable lifecycle owners.
637        drop(self.operation.take());
638    }
639}
640
641impl<D: DirectoryWriter + 'static> WorkerState<D> {
642    fn record_cycle_error(&self, error: impl Into<String>) {
643        let mut first_error = self.cycle_error.lock();
644        if first_error.is_none() {
645            *first_error = Some(error.into());
646        }
647        drop(first_error);
648        self.cycle_failed.store(true, Ordering::Release);
649    }
650}
651
652impl<D: DirectoryWriter + 'static> Drop for PreparedSegment<D> {
653    fn drop(&mut self) {
654        if self.published {
655            return;
656        }
657        let Some(operation) = self.operation.take() else {
658            return;
659        };
660        self.segment_manager.schedule_unpublished_segment_cleanup(
661            self.segment_id,
662            operation,
663            self.runtime.clone(),
664        );
665    }
666}
667
668impl<D: DirectoryWriter + 'static> IndexWriter<D> {
669    /// Create a new index in the directory
670    pub async fn create(directory: D, schema: Schema, config: IndexConfig) -> Result<Self> {
671        let builder_config = default_builder_config(&config);
672        Self::create_with_config(directory, schema, config, builder_config).await
673    }
674
675    /// Create a new index with custom builder config
676    pub async fn create_with_config(
677        directory: D,
678        schema: Schema,
679        config: IndexConfig,
680        builder_config: SegmentBuilderConfig,
681    ) -> Result<Self> {
682        crate::dsl::reject_removed_vector_index_types(&schema).map_err(Error::Schema)?;
683        let directory = Arc::new(directory);
684        let schema = Arc::new(schema);
685        // Directory-layer metrics (cold writes, lazy reads) carry the index label
686        directory.set_index_label(schema.index_label());
687
688        // Refuse a second writer before touching any index state.
689        let writer_lock = try_acquire_writer_lock(directory.as_ref())?;
690        if let WriterLock::Unavailable { reason } = &writer_lock {
691            return Err(Error::Internal(reason.clone()));
692        }
693        // Refuse to clobber an existing index: persisting a fresh empty
694        // metadata.json would orphan every committed segment, and the next
695        // writer open's orphan sweep would permanently delete them.
696        if directory
697            .exists(std::path::Path::new(super::INDEX_META_FILENAME))
698            .await?
699        {
700            return Err(Error::Internal(format!(
701                "refusing to create index: {} already exists in this directory; \
702                 use IndexWriter::open to open the existing index, or delete the \
703                 directory first if you really want to start over",
704                super::INDEX_META_FILENAME
705            )));
706        }
707
708        let metadata = super::IndexMetadata::new((*schema).clone());
709
710        let segment_manager = Arc::new(crate::merge::SegmentManager::new(
711            Arc::clone(&directory),
712            Arc::clone(&schema),
713            metadata,
714            config.merge_policy.clone_box(),
715            config.term_cache_blocks,
716            config.max_concurrent_merges,
717            Arc::clone(&config.background_merge_permits),
718            config.merge_bp_time_budget,
719            config.bp_memory_budget_bytes,
720            Arc::clone(&config.background_reorder_permits),
721            config.background_reorder_pool.clone(),
722        ));
723        segment_manager.update_metadata(|_| {}).await?;
724
725        Ok(Self::new_with_parts(
726            directory,
727            schema,
728            config,
729            builder_config,
730            segment_manager,
731            writer_lock,
732        ))
733    }
734
735    /// Open an existing index for exclusive writing.
736    ///
737    /// Multiple independent writers for the same directory are unsupported;
738    /// for filesystem-rooted directories this is enforced with an advisory
739    /// single-writer lock ([`WRITER_LOCK_FILENAME`]) held for the writer's
740    /// lifetime. This path removes crash-leftover outputs before starting its
741    /// workers. Use [`Index::writer`](super::Index::writer) to share lifecycle
742    /// state with an already-open search index.
743    pub async fn open(directory: D, config: IndexConfig) -> Result<Self> {
744        let builder_config = default_builder_config(&config);
745        Self::open_with_config(directory, config, builder_config).await
746    }
747
748    /// Open an existing index with custom builder config
749    pub async fn open_with_config(
750        directory: D,
751        config: IndexConfig,
752        builder_config: SegmentBuilderConfig,
753    ) -> Result<Self> {
754        let directory = Arc::new(directory);
755
756        // The lock must be held before the orphan sweep below: sweeping while
757        // another process's writer is live deletes its in-flight outputs.
758        let writer_lock = try_acquire_writer_lock(directory.as_ref())?;
759        if let WriterLock::Unavailable { reason } = &writer_lock {
760            return Err(Error::Internal(reason.clone()));
761        }
762
763        let metadata = super::IndexMetadata::load(directory.as_ref()).await?;
764        let schema = Arc::new(metadata.schema.clone());
765        // Directory-layer metrics (cold writes, lazy reads) carry the index label
766        directory.set_index_label(schema.index_label());
767
768        let segment_manager = Arc::new(crate::merge::SegmentManager::new(
769            Arc::clone(&directory),
770            Arc::clone(&schema),
771            metadata,
772            config.merge_policy.clone_box(),
773            config.term_cache_blocks,
774            config.max_concurrent_merges,
775            Arc::clone(&config.background_merge_permits),
776            config.merge_bp_time_budget,
777            config.bp_memory_budget_bytes,
778            Arc::clone(&config.background_reorder_permits),
779            config.background_reorder_pool.clone(),
780        ));
781        let swept = segment_manager.cleanup_orphan_segments().await?;
782        if swept > 0 {
783            log::warn!(
784                "[segment_cleanup] swept {} orphan segment(s) while opening writer",
785                swept
786            );
787        }
788        segment_manager.try_load_and_publish_trained().await?;
789
790        Ok(Self::new_with_parts(
791            directory,
792            schema,
793            config,
794            builder_config,
795            segment_manager,
796            writer_lock,
797        ))
798    }
799
800    /// Create an IndexWriter from an existing Index.
801    /// Shares the SegmentManager for consistent segment lifecycle management.
802    ///
803    /// This constructor is infallible, so a single-writer lock conflict is
804    /// deferred: the returned writer fails loudly on its first mutating
805    /// operation instead of silently double-writing next to another writer.
806    pub fn from_index(index: &super::Index<D>) -> Self {
807        let writer_lock = match try_acquire_writer_lock(index.directory.as_ref()) {
808            Ok(lock) => lock,
809            Err(error) => WriterLock::Unavailable {
810                reason: format!("failed to acquire the single-writer lock: {error}"),
811            },
812        };
813        if let WriterLock::Unavailable { reason } = &writer_lock {
814            log::error!("[writer_lock] {reason}");
815        }
816        let builder_config = default_builder_config(&index.config);
817        Self::new_with_parts(
818            Arc::clone(&index.directory),
819            Arc::clone(&index.schema),
820            index.config.clone(),
821            builder_config,
822            Arc::clone(&index.segment_manager),
823            writer_lock,
824        )
825    }
826
827    // ========================================================================
828    // Construction + pipeline management
829    // ========================================================================
830
831    /// Common construction: creates worker state, spawns workers, assembles `Self`.
832    fn new_with_parts(
833        directory: Arc<D>,
834        schema: Arc<Schema>,
835        config: IndexConfig,
836        builder_config: SegmentBuilderConfig,
837        segment_manager: Arc<crate::merge::SegmentManager<D>>,
838        writer_lock: WriterLock,
839    ) -> Self {
840        // Auto-configure tokenizers from schema for all text fields
841        let registry = crate::tokenizer::TokenizerRegistry::new();
842        let mut tokenizers = FxHashMap::default();
843        for (field, entry) in schema.fields() {
844            if matches!(entry.field_type, crate::dsl::FieldType::Text)
845                && let Some(ref tok_name) = entry.tokenizer
846                && let Some(tok) = registry.get(tok_name)
847            {
848                tokenizers.insert(field, tok);
849            }
850        }
851
852        let num_workers = config.num_indexing_threads.max(1);
853        let worker_state = Arc::new(WorkerState {
854            directory: Arc::clone(&directory),
855            schema: Arc::clone(&schema),
856            builder_config,
857            tokenizers: parking_lot::RwLock::new(tokenizers),
858            memory_budget_per_worker: config.max_indexing_memory_bytes / num_workers,
859            segment_build_limiter: SegmentBuildLimiter::new(num_workers),
860            segment_manager: Arc::clone(&segment_manager),
861            built_segments: parking_lot::Mutex::new(Vec::new()),
862            cycle_error: parking_lot::Mutex::new(None),
863            cycle_failed: AtomicBool::new(false),
864            flush_count: AtomicUsize::new(0),
865            flush_mutex: parking_lot::Mutex::new(()),
866            flush_cvar: parking_lot::Condvar::new(),
867            resume_receiver: parking_lot::Mutex::new(None),
868            resume_epoch: AtomicUsize::new(0),
869            resume_cvar: parking_lot::Condvar::new(),
870            shutdown: AtomicBool::new(false),
871            num_workers,
872        });
873        let (doc_sender, workers) = Self::spawn_workers(&worker_state, num_workers);
874        let primary_key_index = Arc::new(parking_lot::RwLock::new(None));
875        let primary_key_refresh_lock = Arc::new(tokio::sync::Mutex::new(()));
876
877        Self {
878            directory,
879            schema,
880            config,
881            doc_sender: Arc::new(parking_lot::RwLock::new(doc_sender)),
882            workers,
883            worker_state,
884            segment_manager,
885            flushed_segments: Arc::new(parking_lot::Mutex::new(Vec::new())),
886            primary_key_index,
887            primary_key_refresh_lock,
888            commit_finalization: Arc::new(CommitFinalizationState::default()),
889            pk_reservations_retained: Arc::new(AtomicBool::new(false)),
890            writer_lock: parking_lot::RwLock::new(writer_lock),
891        }
892    }
893
894    /// Fail loudly when another writer owns the single-writer lock.
895    ///
896    /// A deferred conflict (`from_index` during a writer handover, e.g. a
897    /// rolling pod restart) is not permanent: the holder exits and the kernel
898    /// releases its advisory lock. Re-attempt acquisition on every call in
899    /// the `Unavailable` state so the writer recovers as soon as the lock
900    /// frees, instead of rejecting all writes for its lifetime.
901    fn ensure_writer_lock(&self) -> Result<()> {
902        // Fast path: uncontended read on the healthy states.
903        if !matches!(&*self.writer_lock.read(), WriterLock::Unavailable { .. }) {
904            return Ok(());
905        }
906
907        let mut lock = self.writer_lock.write();
908        // Another thread may have recovered while we waited for the write lock.
909        if !matches!(&*lock, WriterLock::Unavailable { .. }) {
910            return Ok(());
911        }
912        match try_acquire_writer_lock(self.directory.as_ref())? {
913            acquired @ (WriterLock::Held { .. } | WriterLock::NotApplicable) => {
914                log::info!(
915                    "[writer_lock] single-writer lock acquired after retry; \
916                     the previous holder has released it — resuming writes"
917                );
918                *lock = acquired;
919                Ok(())
920            }
921            WriterLock::Unavailable { reason } => {
922                let err = Error::Internal(reason.clone());
923                *lock = WriterLock::Unavailable { reason };
924                Err(err)
925            }
926        }
927    }
928
929    /// Clear primary-key reservations after an aborted or failed generation.
930    ///
931    /// Skipped while a failed post-commit PK refresh has left the uncommitted
932    /// reservations as the ONLY record of already-committed keys (fail-closed,
933    /// see `finalize_prepared_commit`): wiping them would admit duplicate
934    /// primary keys. Retaining the aborted generation's keys as well is
935    /// deliberately conservative — they clear on the next successful commit's
936    /// refresh.
937    fn clear_uncommitted_pk_reservations(&self) {
938        if self.pk_reservations_retained.load(Ordering::Acquire) {
939            log::warn!(
940                "[primary_key] keeping uncommitted reservations through abort: a \
941                 failed post-commit refresh left them as the only record of \
942                 committed keys; they are cleared by the next successful commit"
943            );
944            return;
945        }
946        if let Some(pk_index) = self.primary_key_index.write().as_mut() {
947            pk_index.clear_uncommitted();
948        }
949    }
950
951    fn spawn_workers(
952        worker_state: &Arc<WorkerState<D>>,
953        num_workers: usize,
954    ) -> (
955        async_channel::Sender<Document>,
956        Vec<std::thread::JoinHandle<()>>,
957    ) {
958        let (sender, receiver) = async_channel::bounded(PIPELINE_MAX_SIZE_IN_DOCS);
959        let handle = tokio::runtime::Handle::current();
960        let mut workers = Vec::with_capacity(num_workers);
961        for i in 0..num_workers {
962            let state = Arc::clone(worker_state);
963            let rx = receiver.clone();
964            let rt = handle.clone();
965            workers.push(
966                std::thread::Builder::new()
967                    .name(format!("index-worker-{}", i))
968                    .spawn(move || Self::worker_loop(state, rx, rt, i))
969                    .expect("failed to spawn index worker thread"),
970            );
971        }
972        (sender, workers)
973    }
974
975    /// Get the schema
976    pub fn schema(&self) -> &Schema {
977        &self.schema
978    }
979
980    /// Set tokenizer for a field.
981    /// Propagated to worker threads — takes effect for the next SegmentBuilder they create.
982    pub fn set_tokenizer<T: crate::tokenizer::Tokenizer>(&mut self, field: Field, tokenizer: T) {
983        self.worker_state
984            .tokenizers
985            .write()
986            .insert(field, Box::new(tokenizer));
987    }
988
989    /// Initialize primary key deduplication from committed segments.
990    ///
991    /// Tries to load a cached bloom filter from `pk_bloom.bin` first. If the
992    /// cache covers all current segments, the bloom is reused directly (fast
993    /// path). If new segments appeared since the cache was written, only their
994    /// keys are iterated (incremental). Falls back to a full rebuild when no
995    /// cache exists.
996    ///
997    /// Only loads fast-field data (text dictionaries) per segment — NOT full
998    /// `SegmentReader`s — to avoid duplicating dense/sparse index memory.
999    ///
1000    /// The CPU-intensive bloom build is offloaded via `spawn_blocking` so it
1001    /// does not block the tokio runtime.
1002    ///
1003    /// No-op if schema has no primary field.
1004    pub async fn init_primary_key_dedup(&mut self) -> Result<()> {
1005        use super::primary_key::{PK_BLOOM_FILE, deserialize_pk_bloom};
1006
1007        self.commit_finalization.wait_until_idle().await;
1008        self.ensure_writer_lock()?;
1009
1010        let field = match self.schema.primary_field() {
1011            Some(f) => f,
1012            None => return Ok(()),
1013        };
1014
1015        // A merge/reorder replacement can publish while this initialization
1016        // performs async segment loads. Serialize both paths so an older
1017        // initialization snapshot cannot overwrite the replacement refresh
1018        // and keep retired source segments pinned indefinitely.
1019        let _refresh_guard = self.primary_key_refresh_lock.lock().await;
1020        {
1021            let callback_directory = Arc::clone(&self.directory);
1022            let callback_schema = Arc::clone(&self.schema);
1023            let callback_manager = Arc::downgrade(&self.segment_manager);
1024            let callback_primary_key = Arc::downgrade(&self.primary_key_index);
1025            let callback_refresh_lock = Arc::downgrade(&self.primary_key_refresh_lock);
1026            self.segment_manager.set_replacement_refresh(move || {
1027                let directory = Arc::clone(&callback_directory);
1028                let schema = Arc::clone(&callback_schema);
1029                let manager = callback_manager.clone();
1030                let primary_key = callback_primary_key.clone();
1031                let refresh_lock = callback_refresh_lock.clone();
1032                async move {
1033                    let (Some(manager), Some(primary_key), Some(refresh_lock)) = (
1034                        manager.upgrade(),
1035                        primary_key.upgrade(),
1036                        refresh_lock.upgrade(),
1037                    ) else {
1038                        return Ok(());
1039                    };
1040                    refresh_primary_key_snapshot(
1041                        &directory,
1042                        &schema,
1043                        &manager,
1044                        &primary_key,
1045                        &refresh_lock,
1046                        PrimaryKeyRefresh::Replacement,
1047                    )
1048                    .await
1049                }
1050            });
1051        }
1052
1053        let snapshot = self.segment_manager.acquire_snapshot().await;
1054        let current_seg_ids: Vec<String> = snapshot.segment_ids().to_vec();
1055
1056        // Try to load persisted bloom filter.
1057        let cached = match self
1058            .directory
1059            .open_read(std::path::Path::new(PK_BLOOM_FILE))
1060            .await
1061        {
1062            Ok(handle) => {
1063                let data = handle.read_bytes_range(0..handle.len()).await;
1064                match data {
1065                    Ok(bytes) => deserialize_pk_bloom(bytes.as_slice()),
1066                    Err(_) => None,
1067                }
1068            }
1069            Err(_) => None,
1070        };
1071
1072        // Load lightweight fast-field data for all segments concurrently.
1073        let load_futures: Vec<_> = current_seg_ids
1074            .iter()
1075            .map(|seg_id_str| {
1076                let seg_id_str = seg_id_str.clone();
1077                let dir = self.directory.as_ref();
1078                let schema = Arc::clone(&self.schema);
1079                async move { load_pk_segment_data(dir, &seg_id_str, &schema).await }
1080            })
1081            .collect();
1082        let all_data = futures::future::try_join_all(load_futures).await?;
1083
1084        if let Some((persisted_seg_ids, bloom)) = cached {
1085            // Partition: old segments (covered by bloom) first, new segments at end.
1086            let mut pk_data = Vec::with_capacity(all_data.len());
1087            let mut new_data = Vec::new();
1088            for d in all_data {
1089                if persisted_seg_ids.contains(&d.segment_id) {
1090                    pk_data.push(d);
1091                } else {
1092                    new_data.push(d);
1093                }
1094            }
1095            let needs_persist = !new_data.is_empty();
1096            let new_start = pk_data.len();
1097            pk_data.extend(new_data);
1098
1099            let pk_index = if new_start == pk_data.len() {
1100                // Fast path: all segments covered by cache.
1101                super::primary_key::PrimaryKeyIndex::from_persisted(field, bloom, pk_data, snapshot)
1102            } else {
1103                // Incremental: only iterate new segments' keys.
1104                tokio::task::spawn_blocking(move || {
1105                    // Insert new segments' keys into the bloom, then construct
1106                    // PrimaryKeyIndex with the pre-populated bloom.
1107                    let mut bloom = bloom;
1108                    let mut added = 0usize;
1109                    let num_new = pk_data.len() - new_start;
1110                    for data in &pk_data[new_start..] {
1111                        if let Some(ff) = data.fast_fields.get(&field.0)
1112                            && let Some(dict) = ff.text_dict()
1113                        {
1114                            for key in dict.iter() {
1115                                bloom.insert(key.as_bytes());
1116                                added += 1;
1117                            }
1118                        }
1119                    }
1120                    if added > 0 {
1121                        log::info!(
1122                            "[primary_key] bloom: added {} keys from {} new segment(s)",
1123                            added,
1124                            num_new,
1125                        );
1126                    }
1127                    super::primary_key::PrimaryKeyIndex::from_persisted(
1128                        field, bloom, pk_data, snapshot,
1129                    )
1130                })
1131                .await
1132                .map_err(|e| Error::Internal(format!("spawn_blocking failed: {}", e)))?
1133            };
1134
1135            if needs_persist {
1136                self.persist_pk_bloom(&pk_index, &current_seg_ids).await;
1137            }
1138
1139            *self.primary_key_index.write() = Some(pk_index);
1140        } else {
1141            // No cache — full rebuild, offloaded to blocking thread.
1142            let pk_index = tokio::task::spawn_blocking(move || {
1143                super::primary_key::PrimaryKeyIndex::new(field, all_data, snapshot)
1144            })
1145            .await
1146            .map_err(|e| Error::Internal(format!("spawn_blocking failed: {}", e)))?;
1147
1148            self.persist_pk_bloom(&pk_index, &current_seg_ids).await;
1149            *self.primary_key_index.write() = Some(pk_index);
1150        }
1151
1152        // The freshly built index covers every committed segment, so any
1153        // reservations retained after a failed post-commit refresh are
1154        // superseded by committed_data.
1155        self.pk_reservations_retained
1156            .store(false, Ordering::Release);
1157
1158        Ok(())
1159    }
1160
1161    /// Persist the primary-key bloom filter to `pk_bloom.bin`.
1162    /// Best-effort: errors are logged but not propagated.
1163    async fn persist_pk_bloom(
1164        &self,
1165        pk_index: &super::primary_key::PrimaryKeyIndex,
1166        segment_ids: &[String],
1167    ) {
1168        use super::primary_key::PK_BLOOM_FILE;
1169
1170        let writer = match self
1171            .directory
1172            .streaming_writer(std::path::Path::new(PK_BLOOM_FILE))
1173            .await
1174        {
1175            Ok(writer) => writer,
1176            Err(error) => {
1177                log::warn!("[primary_key] failed to open bloom cache: {}", error);
1178                return;
1179            }
1180        };
1181        let result = crate::segment::block_in_place_if_multithread(|| {
1182            write_pk_bloom_stream(pk_index, segment_ids, writer)
1183        });
1184        if let Err(e) = result {
1185            log::warn!("[primary_key] failed to persist bloom cache: {}", e);
1186        }
1187    }
1188
1189    /// Add a document to the indexing queue (sync, O(1)).
1190    ///
1191    /// `Document` is moved into the channel (zero-copy). Workers compete to pull it.
1192    /// Returns an explicit backpressure error when the queue is at capacity or
1193    /// a prepared commit generation is not yet resolved.
1194    pub fn add_document(&self, doc: Document) -> Result<()> {
1195        self.ensure_writer_lock()?;
1196        if self.worker_state.shutdown.load(Ordering::Acquire) {
1197            return Err(Error::IndexClosed);
1198        }
1199        if self.commit_finalization.in_progress.load(Ordering::Acquire) {
1200            return Err(Error::CommitInProgress);
1201        }
1202        let sender = self.doc_sender.read().clone();
1203        // A publication error deliberately leaves the prepared generation and
1204        // its workers paused for a lossless retry. Report this as backpressure
1205        // instead of inserting/rolling back a PK key against a closed channel.
1206        if sender.is_closed() {
1207            return Err(Error::CommitInProgress);
1208        }
1209        let primary_key_index = self.primary_key_index.read();
1210        if let Some(ref pk_index) = *primary_key_index {
1211            pk_index.check_and_insert(&doc)?;
1212        }
1213        match sender.try_send(doc) {
1214            Ok(()) => Ok(()),
1215            Err(async_channel::TrySendError::Full(doc)) => {
1216                // Roll back PK registration so the caller can retry later
1217                if let Some(ref pk_index) = *primary_key_index {
1218                    pk_index.rollback_uncommitted_key(&doc);
1219                }
1220                Err(Error::QueueFull)
1221            }
1222            Err(async_channel::TrySendError::Closed(doc)) => {
1223                // Roll back PK registration for defense-in-depth
1224                if let Some(ref pk_index) = *primary_key_index {
1225                    pk_index.rollback_uncommitted_key(&doc);
1226                }
1227                Err(Error::CommitInProgress)
1228            }
1229        }
1230    }
1231
1232    /// Add multiple documents to the indexing queue.
1233    ///
1234    /// Returns the number of documents successfully queued. Stops at the first
1235    /// backpressure error and returns the count queued so far.
1236    pub fn add_documents(&self, documents: Vec<Document>) -> Result<usize> {
1237        let total = documents.len();
1238        for (i, doc) in documents.into_iter().enumerate() {
1239            match self.add_document(doc) {
1240                Ok(()) => {}
1241                Err(Error::QueueFull | Error::CommitInProgress) => return Ok(i),
1242                Err(e) => return Err(e),
1243            }
1244        }
1245        Ok(total)
1246    }
1247
1248    // ========================================================================
1249    // Worker loop
1250    // ========================================================================
1251
1252    /// Worker loop — runs on a dedicated OS thread, survives across commits.
1253    ///
1254    /// Outer loop: each iteration processes one commit cycle.
1255    ///   Inner loop: pull documents from MPMC queue, index them, build segments
1256    ///   when memory budget is exceeded.
1257    ///   On channel close (prepare_commit): flush current builder, signal
1258    ///   flush_count, wait for resume with new receiver.
1259    ///   On shutdown (Drop): exit permanently.
1260    fn worker_loop(
1261        state: Arc<WorkerState<D>>,
1262        initial_receiver: async_channel::Receiver<Document>,
1263        handle: tokio::runtime::Handle,
1264        worker_id: usize,
1265    ) {
1266        let mut receiver = initial_receiver;
1267        let mut my_epoch = 0usize;
1268        let soft_flush_threshold =
1269            soft_flush_threshold(state.memory_budget_per_worker, worker_id, state.num_workers);
1270        let hard_flush_threshold = hard_flush_threshold(state.memory_budget_per_worker);
1271
1272        loop {
1273            // Wrap the recv+build phase in catch_unwind so a panic doesn't
1274            // prevent flush_count from being signaled (which would hang
1275            // prepare_commit forever).
1276            let build_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1277                let mut builder: Option<SegmentBuilder> = None;
1278
1279                while let Ok(doc) = receiver.recv_blocking() {
1280                    if state.shutdown.load(Ordering::Acquire) {
1281                        break;
1282                    }
1283                    // Another worker already invalidated this generation.
1284                    // Drain the shared queue so prepare_commit can complete,
1285                    // but do not spend CPU/RAM building outputs that must be
1286                    // discarded transactionally.
1287                    if state.cycle_failed.load(Ordering::Acquire) {
1288                        continue;
1289                    }
1290                    // Initialize builder if needed
1291                    if builder.is_none() {
1292                        match SegmentBuilder::new(
1293                            Arc::clone(&state.schema),
1294                            state.builder_config.clone(),
1295                        ) {
1296                            Ok(mut b) => {
1297                                for (field, tokenizer) in state.tokenizers.read().iter() {
1298                                    b.set_tokenizer(*field, tokenizer.clone_box());
1299                                }
1300                                builder = Some(b);
1301                            }
1302                            Err(e) => {
1303                                log::error!("Failed to create segment builder: {:?}", e);
1304                                state.record_cycle_error(format!(
1305                                    "failed to create segment builder: {e}"
1306                                ));
1307                                continue;
1308                            }
1309                        }
1310                    }
1311
1312                    let b = builder.as_mut().unwrap();
1313                    if let Err(e) = b.add_document(doc) {
1314                        log::error!("Failed to index document: {:?}", e);
1315                        state.record_cycle_error(format!("failed to index document: {e}"));
1316                        continue;
1317                    }
1318
1319                    let builder_memory = b.estimated_memory_bytes();
1320
1321                    if b.num_docs() & 0x3FFF == 0 {
1322                        log::debug!(
1323                            "[indexing] docs={}, memory={}, budget={}",
1324                            b.num_docs(),
1325                            crate::format_bytes(builder_memory as u64),
1326                            crate::format_bytes(state.memory_budget_per_worker as u64)
1327                        );
1328                    }
1329
1330                    // Require minimum 100 docs before flushing to avoid tiny segments
1331                    const MIN_DOCS_BEFORE_FLUSH: u32 = 100;
1332
1333                    if b.num_docs() >= MIN_DOCS_BEFORE_FLUSH
1334                        && let Some(_build_permit) = state.segment_build_limiter.reserve_if_due(
1335                            builder_memory,
1336                            soft_flush_threshold,
1337                            hard_flush_threshold,
1338                        )
1339                    {
1340                        log::info!(
1341                            "[indexing] memory budget reached, building segment: \
1342                             worker={}, docs={}, memory={}, soft_budget={}, hard_budget={}",
1343                            worker_id,
1344                            b.num_docs(),
1345                            crate::format_bytes(builder_memory as u64),
1346                            crate::format_bytes(soft_flush_threshold as u64),
1347                            crate::format_bytes(hard_flush_threshold as u64),
1348                        );
1349                        let full_builder = builder.take().unwrap();
1350                        Self::build_segment_inline(&state, full_builder, &handle);
1351                    }
1352                }
1353
1354                // Channel closed — flush current builder
1355                if !state.cycle_failed.load(Ordering::Acquire)
1356                    && let Some(b) = builder.take()
1357                    && b.num_docs() > 0
1358                {
1359                    let _build_permit = state.segment_build_limiter.acquire_flush();
1360                    Self::build_segment_inline(&state, b, &handle);
1361                }
1362            }));
1363
1364            if build_result.is_err() {
1365                log::error!(
1366                    "[worker] panic during indexing cycle — documents in this cycle may be lost"
1367                );
1368                state.record_cycle_error("indexing worker panicked while building the batch");
1369            }
1370
1371            // Signal flush completion (always, even after panic — prevents
1372            // prepare_commit from hanging)
1373            let prev = state.flush_count.fetch_add(1, Ordering::Release);
1374            if prev + 1 == state.num_workers {
1375                // Last worker — wake prepare_commit. notify_all, not
1376                // notify_one: a cancelled commit leaves its detached
1377                // spawn_blocking waiter parked on this condvar, and with a
1378                // single notification that dead waiter would consume the
1379                // only wakeup, stalling a retried prepare_commit for its
1380                // full deadline.
1381                let _lock = state.flush_mutex.lock();
1382                state.flush_cvar.notify_all();
1383            }
1384
1385            // Wait for resume (new channel) or shutdown.
1386            // Check resume_epoch to avoid re-cloning a stale receiver from
1387            // a previous cycle.
1388            {
1389                let mut lock = state.resume_receiver.lock();
1390                loop {
1391                    if state.shutdown.load(Ordering::Acquire) {
1392                        return;
1393                    }
1394                    let current_epoch = state.resume_epoch.load(Ordering::Acquire);
1395                    if current_epoch > my_epoch
1396                        && let Some(rx) = lock.as_ref()
1397                    {
1398                        receiver = rx.clone();
1399                        my_epoch = current_epoch;
1400                        break;
1401                    }
1402                    state.resume_cvar.wait(&mut lock);
1403                }
1404            }
1405        }
1406    }
1407
1408    /// Build a segment on the worker thread. Uses `Handle::block_on()` to bridge
1409    /// into async context for I/O (streaming writers). CPU work (rayon) stays on
1410    /// the worker thread / rayon pool.
1411    fn build_segment_inline(
1412        state: &WorkerState<D>,
1413        builder: SegmentBuilder,
1414        handle: &tokio::runtime::Handle,
1415    ) {
1416        let segment_id = SegmentId::new();
1417        let segment_hex = segment_id.to_hex();
1418        // Claim the ID before the first file write. The guard is moved into
1419        // `PreparedSegment` on success and otherwise releases automatically.
1420        let operation = match state
1421            .segment_manager
1422            .protect_new_segment(segment_hex.clone())
1423        {
1424            Ok(operation) => operation,
1425            Err(e) => {
1426                log::error!(
1427                    "[segment_build_failed] segment_id={} lifecycle_error={}",
1428                    segment_hex,
1429                    e,
1430                );
1431                state.record_cycle_error(format!(
1432                    "failed to claim segment {segment_hex} for building: {e}"
1433                ));
1434                return;
1435            }
1436        };
1437        let trained = state.segment_manager.trained_for_segment_build();
1438        let doc_count = builder.num_docs();
1439        let build_start = std::time::Instant::now();
1440
1441        log::info!(
1442            "[segment_build] segment_id={} doc_count={} ann={}",
1443            segment_hex,
1444            doc_count,
1445            trained.is_some()
1446        );
1447
1448        // Construct the cleanup owner before building. It keeps lifecycle
1449        // ownership through async deletion on ordinary error, abort, and
1450        // panic unwind; crash recovery is the only path left to the sweeper.
1451        let mut prepared = PreparedSegment {
1452            id: segment_hex.clone(),
1453            segment_id,
1454            num_docs: doc_count,
1455            segment_manager: Arc::clone(&state.segment_manager),
1456            operation: Some(operation),
1457            runtime: handle.clone(),
1458            needs_vector_upgrade: trained.is_none(),
1459            published: false,
1460        };
1461
1462        match handle.block_on(builder.build(
1463            state.directory.as_ref(),
1464            segment_id,
1465            trained.as_deref(),
1466        )) {
1467            Ok(meta) if meta.num_docs == doc_count && meta.num_docs > 0 => {
1468                let duration_ms = build_start.elapsed().as_millis() as u64;
1469                log::info!(
1470                    "[segment_build_done] segment_id={} doc_count={} duration_ms={}",
1471                    segment_hex,
1472                    meta.num_docs,
1473                    duration_ms,
1474                );
1475                prepared.num_docs = meta.num_docs;
1476                state.built_segments.lock().push(prepared);
1477            }
1478            Ok(meta) => {
1479                let error = format!(
1480                    "segment {segment_hex} built {} docs from a {doc_count}-document builder",
1481                    meta.num_docs
1482                );
1483                log::error!("[segment_build_failed] {error}");
1484                state.record_cycle_error(error);
1485            }
1486            Err(e) => {
1487                log::error!(
1488                    "[segment_build_failed] segment_id={} error={:?}",
1489                    segment_hex,
1490                    e
1491                );
1492                // `prepared` owns the lifecycle claim and schedules one
1493                // tracked, idempotent cleanup pass when this scope ends.
1494                state.record_cycle_error(format!("failed to build segment {segment_hex}: {e}"));
1495            }
1496        }
1497    }
1498
1499    // ========================================================================
1500    // Public API — commit, merge, etc.
1501    // ========================================================================
1502
1503    /// Check merge policy and spawn a background merge if needed.
1504    pub async fn maybe_merge(&self) {
1505        self.segment_manager.maybe_merge().await;
1506    }
1507
1508    /// Drain all in-flight merge tasks.
1509    /// Blocking merge phases cannot be cancelled safely once started.
1510    pub async fn abort_merges(&self) {
1511        self.segment_manager.abort_merges().await;
1512    }
1513
1514    /// Stop accepting lifecycle work, stop and join indexing workers, and
1515    /// discard unpublished segments. Index deletion calls this while holding
1516    /// the registry writer lock so in-flight requests finish first and stale
1517    /// writer Arcs cannot restart work afterward.
1518    pub async fn shutdown(&mut self) -> Result<()> {
1519        self.segment_manager.begin_shutdown();
1520        self.signal_worker_shutdown();
1521
1522        // A cancelled commit request leaves its owned finalizer running. Do not
1523        // clear shared PK/prepared state while that task may still publish or
1524        // refresh it. Worker shutdown is signalled first, so a successful
1525        // finalizer cannot restart ingestion while deletion is waiting.
1526        self.commit_finalization.wait_until_idle().await;
1527
1528        let workers = std::mem::take(&mut self.workers);
1529        let panicked = tokio::task::spawn_blocking(move || {
1530            workers
1531                .into_iter()
1532                .map(|worker| worker.join().is_err())
1533                .filter(|panicked| *panicked)
1534                .count()
1535        })
1536        .await
1537        .map_err(|error| Error::Internal(format!("failed to join index workers: {}", error)))?;
1538        if panicked > 0 {
1539            log::error!("[index_shutdown] {} indexing worker(s) panicked", panicked);
1540        }
1541
1542        // No commit is possible after shutdown. Dropping these RAII values
1543        // releases their lifecycle ownership before directory deletion.
1544        self.flushed_segments.lock().clear();
1545        self.worker_state.built_segments.lock().clear();
1546        if let Some(pk_index) = self.primary_key_index.write().as_mut() {
1547            pk_index.clear_uncommitted();
1548        }
1549        Ok(())
1550    }
1551
1552    /// Wait for the in-flight background merge to complete (if any).
1553    pub async fn wait_for_merging_thread(&self) {
1554        self.segment_manager.wait_for_merging_thread().await;
1555    }
1556
1557    /// Wait for all eligible merges to complete, including cascading merges.
1558    pub async fn wait_for_all_merges(&self) {
1559        self.segment_manager.wait_for_all_merges().await;
1560    }
1561
1562    /// Wait until an owned commit finalizer has reconciled durable metadata,
1563    /// primary-key state, and worker availability. Normally callers need not
1564    /// use this: it exists for orderly shutdown and request supervisors that
1565    /// want to observe completion after cancelling their original waiter.
1566    pub async fn wait_for_commit_finalization(&self) {
1567        self.commit_finalization.wait_until_idle().await;
1568    }
1569
1570    /// Get the segment tracker for sharing with readers.
1571    pub fn tracker(&self) -> std::sync::Arc<crate::segment::SegmentTracker> {
1572        self.segment_manager.tracker()
1573    }
1574
1575    /// Acquire a snapshot of current segments for reading.
1576    pub async fn acquire_snapshot(&self) -> crate::segment::SegmentSnapshot {
1577        self.segment_manager.acquire_snapshot().await
1578    }
1579
1580    /// Clean up orphan segment files not registered in metadata.
1581    ///
1582    /// Requires the single-writer lock: sweeping while another process's
1583    /// writer is live would delete its in-flight segment outputs.
1584    pub async fn cleanup_orphan_segments(&self) -> Result<usize> {
1585        self.ensure_writer_lock()?;
1586        self.segment_manager.cleanup_orphan_segments().await
1587    }
1588
1589    /// Prepare commit — signal workers to flush, wait for completion, collect segments.
1590    ///
1591    /// All documents sent via `add_document` before this call are guaranteed
1592    /// to be written to segment files on disk. Segments are NOT yet registered
1593    /// in metadata — call `PreparedCommit::commit()` for that.
1594    ///
1595    /// Workers are NOT destroyed — they flush their builders and wait for
1596    /// `resume_workers()` to give them a new channel.
1597    ///
1598    /// `add_document` returns `CommitInProgress` until commit/abort resumes workers.
1599    pub async fn prepare_commit(&mut self) -> Result<PreparedCommit<'_, D>> {
1600        self.ensure_writer_lock()?;
1601        if self.worker_state.shutdown.load(Ordering::Acquire) {
1602            return Err(Error::IndexClosed);
1603        }
1604        if self.commit_finalization.in_progress.load(Ordering::Acquire) {
1605            return Err(Error::CommitInProgress);
1606        }
1607        // 1. Close channel → workers drain remaining docs and flush builders
1608        self.doc_sender.read().close();
1609        self.worker_state.segment_build_limiter.begin_flush();
1610
1611        // Wake any workers still waiting on resume_cvar from previous cycle.
1612        // They'll clone the stale receiver, enter recv_blocking, get Err
1613        // immediately (sender already closed), flush, and signal completion.
1614        self.worker_state.resume_cvar.notify_all();
1615
1616        // 2. Wait for all workers to complete their flush (via spawn_blocking
1617        //    to avoid blocking the tokio runtime)
1618        let state = Arc::clone(&self.worker_state);
1619        let all_flushed = tokio::task::spawn_blocking(move || {
1620            let mut lock = state.flush_mutex.lock();
1621            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
1622            while state.flush_count.load(Ordering::Acquire) < state.num_workers {
1623                let remaining = deadline.saturating_duration_since(std::time::Instant::now());
1624                if remaining.is_zero() {
1625                    log::error!(
1626                        "[prepare_commit] timed out waiting for workers: {}/{} flushed",
1627                        state.flush_count.load(Ordering::Acquire),
1628                        state.num_workers
1629                    );
1630                    return false;
1631                }
1632                state.flush_cvar.wait_for(&mut lock, remaining);
1633            }
1634            true
1635        })
1636        .await
1637        .map_err(|e| Error::Internal(format!("Failed to wait for workers: {}", e)))?;
1638
1639        if !all_flushed {
1640            // Keep this commit cycle paused. Resetting flush_count and handing
1641            // out a new receiver while an old worker is still building lets
1642            // that late worker increment the *next* cycle's counter. A later
1643            // prepare can then return before all of its workers flushed and
1644            // publish an incomplete set of segments. The caller may retry
1645            // prepare_commit; it will observe the same generation and collect
1646            // every completed output once the lagging worker finishes.
1647            return Err(Error::Internal(format!(
1648                "prepare_commit timed out: {}/{} workers flushed; writer remains paused, retry commit",
1649                self.worker_state.flush_count.load(Ordering::Acquire),
1650                self.worker_state.num_workers
1651            )));
1652        }
1653
1654        let cycle_error = { self.worker_state.cycle_error.lock().take() };
1655        if let Some(error) = cycle_error {
1656            // No partial publication: some documents in this generation no
1657            // longer exist in a worker builder, so successful sibling outputs
1658            // cannot be committed without violating commit's all-prior-docs
1659            // guarantee. Their RAII drops retain ownership through deletion.
1660            self.flushed_segments.lock().clear();
1661            self.worker_state.built_segments.lock().clear();
1662            self.clear_uncommitted_pk_reservations();
1663            self.resume_workers();
1664            return Err(Error::Internal(format!(
1665                "indexing generation failed; no documents from this batch were committed: {error}"
1666            )));
1667        }
1668
1669        // 3. Collect built segments
1670        let built = std::mem::take(&mut *self.worker_state.built_segments.lock());
1671        self.flushed_segments.lock().extend(built);
1672
1673        Ok(PreparedCommit {
1674            writer: self,
1675            is_resolved: false,
1676        })
1677    }
1678
1679    /// Commit (convenience): prepare_commit + commit in one call.
1680    ///
1681    /// Guarantees all prior `add_document` calls are committed.
1682    /// Vector training is decoupled — call `build_vector_index()` manually.
1683    pub async fn commit(&mut self) -> Result<bool> {
1684        self.prepare_commit().await?.commit().await
1685    }
1686
1687    /// Force merge all segments into one.
1688    pub async fn force_merge(&mut self) -> Result<()> {
1689        self.force_merge_with_snapshot_refresh(|| std::future::ready(Ok(())))
1690            .await
1691    }
1692
1693    /// Force merge while refreshing an external segment consumer after the
1694    /// background-merge drain and every durable replacement.
1695    ///
1696    /// Segment publication refreshes the writer's primary-key topology through
1697    /// the manager's lifecycle-owned hook. Servers use this callback to reload
1698    /// their cached `IndexReader` as well.
1699    pub async fn force_merge_with_snapshot_refresh<F, Fut>(
1700        &mut self,
1701        refresh_external: F,
1702    ) -> Result<()>
1703    where
1704        F: FnMut() -> Fut,
1705        Fut: std::future::Future<Output = Result<()>>,
1706    {
1707        self.prepare_commit().await?.commit().await?;
1708
1709        self.segment_manager
1710            .force_merge_with_snapshot_refresh(refresh_external)
1711            .await?;
1712
1713        // Segment IDs in the on-disk bloom cache need only the final
1714        // generation. Persisting the unchanged bloom after every hierarchy
1715        // level adds avoidable I/O on large primary-key indexes.
1716        self.persist_replacement_snapshot().await
1717    }
1718
1719    /// Reorder all segments via Recursive Graph Bisection (BP) for better BMP pruning.
1720    ///
1721    /// Each segment is individually rebuilt with record-level BP reordering:
1722    /// ordinals are shuffled across blocks so that similar content clusters tightly.
1723    pub async fn reorder(&mut self) -> Result<()> {
1724        self.reorder_with_snapshot_refresh(|| std::future::ready(Ok(())))
1725            .await
1726    }
1727
1728    /// Reorder while refreshing an external reader after each durable segment
1729    /// replacement, so retired sources are released during a long pass.
1730    pub async fn reorder_with_snapshot_refresh<F, Fut>(&mut self, refresh_external: F) -> Result<()>
1731    where
1732        F: FnMut() -> Fut,
1733        Fut: std::future::Future<Output = Result<()>>,
1734    {
1735        self.prepare_commit().await?.commit().await?;
1736
1737        self.segment_manager
1738            .reorder_segments_with_snapshot_refresh(refresh_external)
1739            .await?;
1740        self.persist_replacement_snapshot().await
1741    }
1742
1743    /// Persist the final topology after a bounded series of replacements.
1744    async fn persist_replacement_snapshot(&self) -> Result<()> {
1745        refresh_primary_key_snapshot(
1746            &self.directory,
1747            &self.schema,
1748            &self.segment_manager,
1749            &self.primary_key_index,
1750            &self.primary_key_refresh_lock,
1751            PrimaryKeyRefresh::FinalReplacement,
1752        )
1753        .await
1754    }
1755
1756    /// Get the segment manager (for background optimizer access).
1757    pub fn segment_manager(&self) -> &Arc<crate::merge::SegmentManager<D>> {
1758        &self.segment_manager
1759    }
1760
1761    /// Resume workers with a fresh channel. Called after commit or abort.
1762    ///
1763    /// Workers are already alive — just give them a new channel and wake them.
1764    /// If the tokio runtime has shut down (e.g., program exit), this is a no-op.
1765    fn resume_workers(&mut self) {
1766        Self::resume_workers_shared(&self.worker_state, &self.doc_sender);
1767    }
1768
1769    fn resume_workers_shared(
1770        worker_state: &Arc<WorkerState<D>>,
1771        doc_sender: &Arc<parking_lot::RwLock<async_channel::Sender<Document>>>,
1772    ) {
1773        if worker_state.shutdown.load(Ordering::Acquire) {
1774            return;
1775        }
1776        if tokio::runtime::Handle::try_current().is_err() {
1777            // Runtime is gone — signal permanent shutdown so workers don't
1778            // hang forever on resume_cvar.
1779            worker_state.shutdown.store(true, Ordering::Release);
1780            worker_state.resume_cvar.notify_all();
1781            return;
1782        }
1783
1784        // Reset flush count for next cycle
1785        worker_state.segment_build_limiter.end_flush();
1786        worker_state.flush_count.store(0, Ordering::Release);
1787        *worker_state.cycle_error.lock() = None;
1788        worker_state.cycle_failed.store(false, Ordering::Release);
1789
1790        // Create new channel
1791        let (sender, receiver) = async_channel::bounded(PIPELINE_MAX_SIZE_IN_DOCS);
1792        *doc_sender.write() = sender;
1793
1794        // Set new receiver, bump epoch, and wake all workers
1795        {
1796            let mut lock = worker_state.resume_receiver.lock();
1797            *lock = Some(receiver);
1798        }
1799        worker_state.resume_epoch.fetch_add(1, Ordering::Release);
1800        worker_state.resume_cvar.notify_all();
1801    }
1802
1803    fn signal_worker_shutdown(&self) {
1804        self.worker_state.shutdown.store(true, Ordering::Release);
1805        self.doc_sender.read().close();
1806        self.worker_state.segment_build_limiter.begin_flush();
1807        self.worker_state.resume_cvar.notify_all();
1808    }
1809
1810    // Vector index methods (build_vector_index, etc.) are in vector_builder.rs
1811}
1812
1813impl<D: DirectoryWriter + 'static> Drop for IndexWriter<D> {
1814    fn drop(&mut self) {
1815        self.signal_worker_shutdown();
1816        for w in std::mem::take(&mut self.workers) {
1817            let _ = w.join();
1818        }
1819    }
1820}
1821
1822/// A prepared commit that can be finalized or aborted.
1823///
1824/// Two-phase commit guard. Between `prepare_commit()` and
1825/// `commit()`/`abort()`, segments are on disk but NOT in metadata.
1826/// Dropping without calling either will auto-abort (discard segments,
1827/// respawn workers).
1828pub struct PreparedCommit<'a, D: DirectoryWriter + 'static> {
1829    writer: &'a mut IndexWriter<D>,
1830    is_resolved: bool,
1831}
1832
1833/// Returns prepared segments to the writer if an owned commit finalizer fails
1834/// or unwinds before it can establish that metadata owns them. Retrying commit
1835/// is safe even when publication actually won the race: `SegmentManager::commit`
1836/// is idempotent and the operation guards keep the files protected meanwhile.
1837struct PreparedSegmentsGuard<D: DirectoryWriter + 'static> {
1838    segments: Option<Vec<PreparedSegment<D>>>,
1839    retry_slot: Arc<parking_lot::Mutex<Vec<PreparedSegment<D>>>>,
1840}
1841
1842impl<D: DirectoryWriter + 'static> PreparedSegmentsGuard<D> {
1843    fn metadata_entries(&self) -> Vec<(String, u32)> {
1844        self.segments
1845            .as_deref()
1846            .unwrap_or_default()
1847            .iter()
1848            .map(PreparedSegment::metadata_entry)
1849            .collect()
1850    }
1851
1852    fn take_published(&mut self) -> Vec<PreparedSegment<D>> {
1853        self.segments.take().unwrap_or_default()
1854    }
1855
1856    fn vector_upgrade_segment_ids(&self) -> Vec<String> {
1857        self.segments
1858            .as_deref()
1859            .unwrap_or_default()
1860            .iter()
1861            .filter(|segment| segment.needs_vector_upgrade)
1862            .map(|segment| segment.id.clone())
1863            .collect()
1864    }
1865}
1866
1867impl<D: DirectoryWriter + 'static> Drop for PreparedSegmentsGuard<D> {
1868    fn drop(&mut self) {
1869        if let Some(segments) = self.segments.take() {
1870            self.retry_slot.lock().extend(segments);
1871        }
1872    }
1873}
1874
1875/// Couples completion of the owned commit task to writer availability. The
1876/// default is deliberately fail-closed: a pre-publication error or panic keeps
1877/// workers paused so the retained prepared generation can be retried. Only the
1878/// normal published path arms resumption.
1879struct CommitFinalizationGuard<D: DirectoryWriter + 'static> {
1880    state: Arc<CommitFinalizationState>,
1881    worker_state: Arc<WorkerState<D>>,
1882    doc_sender: Arc<parking_lot::RwLock<async_channel::Sender<Document>>>,
1883    resume_workers: bool,
1884}
1885
1886impl<D: DirectoryWriter + 'static> CommitFinalizationGuard<D> {
1887    fn resume_on_drop(&mut self) {
1888        self.resume_workers = true;
1889    }
1890}
1891
1892impl<D: DirectoryWriter + 'static> Drop for CommitFinalizationGuard<D> {
1893    fn drop(&mut self) {
1894        if self.resume_workers {
1895            IndexWriter::<D>::resume_workers_shared(&self.worker_state, &self.doc_sender);
1896        }
1897        self.state.finish();
1898    }
1899}
1900
1901/// Everything needed to finish one prepared generation is moved into this
1902/// value before spawning. Its two guards therefore reconcile segment
1903/// ownership and writer availability even if Tokio drops the task before its
1904/// first poll.
1905struct OwnedCommitFinalization<D: DirectoryWriter + 'static> {
1906    directory: Arc<D>,
1907    schema: Arc<Schema>,
1908    segment_manager: Arc<crate::merge::SegmentManager<D>>,
1909    primary_key_index: Arc<parking_lot::RwLock<Option<super::primary_key::PrimaryKeyIndex>>>,
1910    primary_key_refresh_lock: Arc<tokio::sync::Mutex<()>>,
1911    prepared: PreparedSegmentsGuard<D>,
1912    finalization: Option<CommitFinalizationGuard<D>>,
1913    publication_observed: Arc<AtomicBool>,
1914    pk_reservations_retained: Arc<AtomicBool>,
1915}
1916
1917#[derive(Clone, Copy)]
1918enum PrimaryKeyRefresh {
1919    /// A commit may introduce genuinely new keys and persists the cache.
1920    Commit,
1921    /// A merge/reorder only changes segment topology; keys are already in the
1922    /// monotonic bloom and the intermediate segment IDs need not be persisted.
1923    Replacement,
1924    /// Final topology refresh: still no key hashing, but persist the new set of
1925    /// segment IDs alongside the unchanged bloom.
1926    FinalReplacement,
1927}
1928
1929async fn refresh_primary_key_snapshot<D: DirectoryWriter + 'static>(
1930    directory: &Arc<D>,
1931    schema: &Arc<Schema>,
1932    segment_manager: &Arc<crate::merge::SegmentManager<D>>,
1933    primary_key_index: &Arc<parking_lot::RwLock<Option<super::primary_key::PrimaryKeyIndex>>>,
1934    primary_key_refresh_lock: &Arc<tokio::sync::Mutex<()>>,
1935    refresh: PrimaryKeyRefresh,
1936) -> Result<()> {
1937    let _refresh_guard = primary_key_refresh_lock.lock().await;
1938    let existing_ids: std::collections::HashSet<String> = {
1939        let guard = primary_key_index.read();
1940        let Some(pk_index) = guard.as_ref() else {
1941            return Ok(());
1942        };
1943        pk_index
1944            .committed_segment_ids()
1945            .map(ToOwned::to_owned)
1946            .collect()
1947    };
1948
1949    let snapshot = segment_manager.acquire_snapshot().await;
1950    let load_futures: Vec<_> = snapshot
1951        .segment_ids()
1952        .iter()
1953        .filter(|id| !existing_ids.contains(id.as_str()))
1954        .map(|seg_id_str| {
1955            let seg_id_str = seg_id_str.clone();
1956            let dir = directory.as_ref();
1957            let schema = Arc::clone(schema);
1958            async move { load_pk_segment_data(dir, &seg_id_str, &schema).await }
1959        })
1960        .collect();
1961    let new_data = futures::future::try_join_all(load_futures).await?;
1962    let seg_ids: Vec<String> = snapshot.segment_ids().to_vec();
1963
1964    let persist_bloom = {
1965        let mut guard = primary_key_index.write();
1966        let Some(pk_index) = guard.as_mut() else {
1967            return Ok(());
1968        };
1969        match refresh {
1970            PrimaryKeyRefresh::Commit => pk_index.refresh_incremental(new_data, snapshot),
1971            PrimaryKeyRefresh::Replacement | PrimaryKeyRefresh::FinalReplacement => {
1972                pk_index.refresh_replacement(new_data, snapshot);
1973            }
1974        }
1975        matches!(
1976            refresh,
1977            PrimaryKeyRefresh::Commit | PrimaryKeyRefresh::FinalReplacement
1978        )
1979    };
1980
1981    if persist_bloom {
1982        let writer = match directory
1983            .streaming_writer(std::path::Path::new(super::primary_key::PK_BLOOM_FILE))
1984            .await
1985        {
1986            Ok(writer) => writer,
1987            Err(error) => {
1988                log::warn!("[primary_key] failed to open bloom cache: {}", error);
1989                return Ok(());
1990            }
1991        };
1992        // The outer read guard prevents replacement of the PK index while the
1993        // inner state lock streams its bloom. No corpus-sized Vec is created.
1994        let guard = primary_key_index.read();
1995        if let Some(pk_index) = guard.as_ref()
1996            && let Err(error) = crate::segment::block_in_place_if_multithread(|| {
1997                write_pk_bloom_stream(pk_index, &seg_ids, writer)
1998            })
1999        {
2000            log::warn!("[primary_key] failed to persist bloom cache: {}", error);
2001        }
2002    }
2003    Ok(())
2004}
2005
2006fn write_pk_bloom_stream(
2007    pk_index: &super::primary_key::PrimaryKeyIndex,
2008    segment_ids: &[String],
2009    mut writer: Box<dyn crate::directories::StreamingWriter>,
2010) -> std::io::Result<()> {
2011    pk_index.write_bloom_cache(segment_ids, writer.as_mut())?;
2012    writer.finish()
2013}
2014
2015async fn finalize_prepared_commit<D: DirectoryWriter + 'static>(
2016    mut commit: OwnedCommitFinalization<D>,
2017) -> Result<bool> {
2018    let metadata_entries = commit.prepared.metadata_entries();
2019    let published_segment_ids = commit.prepared.vector_upgrade_segment_ids();
2020
2021    // This entire future is owned by a Tokio task. Cancelling the RPC only
2022    // drops its JoinHandle; it cannot split durable metadata publication from
2023    // PK reservations or worker resumption.
2024    commit.segment_manager.commit(&metadata_entries).await?;
2025    commit.publication_observed.store(true, Ordering::Release);
2026
2027    let mut published = commit.prepared.take_published();
2028    for segment in &mut published {
2029        segment.mark_published();
2030    }
2031    drop(published);
2032    commit
2033        .segment_manager
2034        .schedule_vector_segment_upgrades(published_segment_ids);
2035    // Publication is irreversible. From here onward every exit path, including
2036    // panic unwind, must make the writer available again while PK reservations
2037    // remain fail-closed until refresh succeeds.
2038    if let Some(finalization) = commit.finalization.as_mut() {
2039        finalization.resume_on_drop();
2040    } else {
2041        log::error!("owned commit finalization guard was already released after publication");
2042    }
2043
2044    // Metadata publication is the commit point. Cache refresh is fail-closed:
2045    // retaining the generation's uncommitted keys may cause conservative
2046    // duplicate rejections, but can never admit a duplicate or turn a durable
2047    // commit into an API error.
2048    match refresh_primary_key_snapshot(
2049        &commit.directory,
2050        &commit.schema,
2051        &commit.segment_manager,
2052        &commit.primary_key_index,
2053        &commit.primary_key_refresh_lock,
2054        PrimaryKeyRefresh::Commit,
2055    )
2056    .await
2057    {
2058        // A successful refresh folded every committed key into committed_data
2059        // and cleared the reservations — nothing retained anymore.
2060        Ok(()) => commit
2061            .pk_reservations_retained
2062            .store(false, Ordering::Release),
2063        Err(error) => {
2064            // The retained reservations are now the ONLY record of the
2065            // published segments' keys. Abort paths must not clear them
2066            // (see clear_uncommitted_pk_reservations) or duplicates would
2067            // be admitted.
2068            commit
2069                .pk_reservations_retained
2070                .store(true, Ordering::Release);
2071            log::error!(
2072                "[primary_key] committed metadata but failed to refresh dedup state; \
2073                 retaining reservations until a later successful commit: {}",
2074                error,
2075            );
2076        }
2077    }
2078
2079    // Merge scheduling is optional post-commit work and may briefly wait on
2080    // manager state. Reconcile worker availability first so it cannot extend
2081    // ingestion backpressure after metadata and PK state already agree.
2082    drop(commit.finalization.take());
2083    commit.segment_manager.maybe_merge().await;
2084    Ok(true)
2085}
2086
2087impl<'a, D: DirectoryWriter + 'static> PreparedCommit<'a, D> {
2088    /// Finalize: register segments in metadata, evaluate merge policy, resume workers.
2089    ///
2090    /// Returns `true` if new segments were committed, `false` if nothing changed.
2091    pub async fn commit(mut self) -> Result<bool> {
2092        let segments = std::mem::take(&mut *self.writer.flushed_segments.lock());
2093
2094        // Fast path: nothing to commit
2095        if segments.is_empty() {
2096            log::debug!("[commit] no segments to commit, skipping");
2097            self.is_resolved = true;
2098            self.writer.resume_workers();
2099            return Ok(false);
2100        }
2101
2102        if !self.writer.commit_finalization.begin() {
2103            self.writer.flushed_segments.lock().extend(segments);
2104            // Keep the prepared generation paused. Letting `Drop` auto-abort
2105            // here would delete the retryable segments owned by another
2106            // finalization state transition.
2107            self.is_resolved = true;
2108            return Err(Error::CommitInProgress);
2109        }
2110
2111        let publication_observed = Arc::new(AtomicBool::new(false));
2112        let owned = OwnedCommitFinalization {
2113            directory: Arc::clone(&self.writer.directory),
2114            schema: Arc::clone(&self.writer.schema),
2115            segment_manager: Arc::clone(&self.writer.segment_manager),
2116            primary_key_index: Arc::clone(&self.writer.primary_key_index),
2117            primary_key_refresh_lock: Arc::clone(&self.writer.primary_key_refresh_lock),
2118            prepared: PreparedSegmentsGuard {
2119                segments: Some(segments),
2120                retry_slot: Arc::clone(&self.writer.flushed_segments),
2121            },
2122            finalization: Some(CommitFinalizationGuard {
2123                state: Arc::clone(&self.writer.commit_finalization),
2124                worker_state: Arc::clone(&self.writer.worker_state),
2125                doc_sender: Arc::clone(&self.writer.doc_sender),
2126                resume_workers: false,
2127            }),
2128            publication_observed: Arc::clone(&publication_observed),
2129            pk_reservations_retained: Arc::clone(&self.writer.pk_reservations_retained),
2130        };
2131
2132        // From this point the owned value, not this cancel-sensitive guard,
2133        // controls every segment and the paused worker generation. Resolve the
2134        // local guard before spawning so even a runtime-spawn panic cannot
2135        // auto-abort the retryable generation during unwind.
2136        self.is_resolved = true;
2137        let task_publication = Arc::clone(&publication_observed);
2138        let task = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2139            tokio::spawn(async move {
2140                match std::panic::AssertUnwindSafe(finalize_prepared_commit(owned))
2141                    .catch_unwind()
2142                    .await
2143                {
2144                    Ok(result) => result,
2145                    Err(_) if task_publication.load(Ordering::Acquire) => {
2146                        log::error!(
2147                            "owned commit finalizer panicked after metadata publication; \
2148                             treating the durable generation as committed"
2149                        );
2150                        Ok(true)
2151                    }
2152                    Err(_) => Err(Error::Internal(
2153                        "owned commit finalizer panicked before metadata publication".into(),
2154                    )),
2155                }
2156            })
2157        }))
2158        .map_err(|_| Error::Internal("runtime rejected owned commit finalizer".into()))?;
2159
2160        match task.await {
2161            Ok(result) => result,
2162            Err(error) if publication_observed.load(Ordering::Acquire) => {
2163                log::error!(
2164                    "owned commit finalizer terminated after metadata publication: {}; \
2165                     treating the durable generation as committed",
2166                    error,
2167                );
2168                Ok(true)
2169            }
2170            Err(error) => Err(Error::Internal(format!(
2171                "owned commit finalizer terminated unexpectedly: {error}"
2172            ))),
2173        }
2174    }
2175
2176    /// Abort: discard prepared segments, delete their files asynchronously,
2177    /// and resume workers. Lifecycle ownership is held until deletion ends.
2178    pub fn abort(mut self) {
2179        self.is_resolved = true;
2180        self.writer.flushed_segments.lock().clear();
2181        self.writer.clear_uncommitted_pk_reservations();
2182        self.writer.resume_workers();
2183    }
2184}
2185
2186impl<D: DirectoryWriter + 'static> Drop for PreparedCommit<'_, D> {
2187    fn drop(&mut self) {
2188        if !self.is_resolved {
2189            log::warn!("PreparedCommit dropped without commit/abort — auto-aborting");
2190            self.writer.flushed_segments.lock().clear();
2191            self.writer.clear_uncommitted_pk_reservations();
2192            self.writer.resume_workers();
2193        }
2194    }
2195}
2196
2197/// Load only fast-field data for a segment (lightweight alternative to full SegmentReader).
2198async fn load_pk_segment_data<D: crate::directories::Directory>(
2199    dir: &D,
2200    seg_id_str: &str,
2201    schema: &Arc<crate::dsl::Schema>,
2202) -> Result<super::primary_key::PkSegmentData> {
2203    let seg_id = crate::segment::SegmentId::from_hex(seg_id_str)
2204        .ok_or_else(|| Error::Internal(format!("Invalid segment id: {}", seg_id_str)))?;
2205    let files = crate::segment::SegmentFiles::new(seg_id.0);
2206    let fast_fields =
2207        crate::segment::reader::loader::load_fast_fields_file(dir, &files, schema).await?;
2208    Ok(super::primary_key::PkSegmentData {
2209        segment_id: seg_id_str.to_string(),
2210        fast_fields,
2211    })
2212}