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 =
711            super::segment_manager_from_config(&directory, &schema, metadata, &config);
712        segment_manager.update_metadata(|_| {}).await?;
713
714        Ok(Self::new_with_parts(
715            directory,
716            schema,
717            config,
718            builder_config,
719            segment_manager,
720            writer_lock,
721        ))
722    }
723
724    /// Open an existing index for exclusive writing.
725    ///
726    /// Multiple independent writers for the same directory are unsupported;
727    /// for filesystem-rooted directories this is enforced with an advisory
728    /// single-writer lock ([`WRITER_LOCK_FILENAME`]) held for the writer's
729    /// lifetime. This path removes crash-leftover outputs before starting its
730    /// workers. Use [`Index::writer`](super::Index::writer) to share lifecycle
731    /// state with an already-open search index.
732    pub async fn open(directory: D, config: IndexConfig) -> Result<Self> {
733        let builder_config = default_builder_config(&config);
734        Self::open_with_config(directory, config, builder_config).await
735    }
736
737    /// Open an existing index with custom builder config
738    pub async fn open_with_config(
739        directory: D,
740        config: IndexConfig,
741        builder_config: SegmentBuilderConfig,
742    ) -> Result<Self> {
743        let directory = Arc::new(directory);
744
745        // The lock must be held before the orphan sweep below: sweeping while
746        // another process's writer is live deletes its in-flight outputs.
747        let writer_lock = try_acquire_writer_lock(directory.as_ref())?;
748        if let WriterLock::Unavailable { reason } = &writer_lock {
749            return Err(Error::Internal(reason.clone()));
750        }
751
752        let metadata = super::IndexMetadata::load(directory.as_ref()).await?;
753        let schema = Arc::new(metadata.schema.clone());
754        // Directory-layer metrics (cold writes, lazy reads) carry the index label
755        directory.set_index_label(schema.index_label());
756
757        let segment_manager =
758            super::segment_manager_from_config(&directory, &schema, metadata, &config);
759        let swept = segment_manager.cleanup_orphan_segments().await?;
760        if swept > 0 {
761            log::warn!(
762                "[segment_cleanup] swept {} orphan segment(s) while opening writer",
763                swept
764            );
765        }
766        segment_manager.try_load_and_publish_trained().await?;
767
768        Ok(Self::new_with_parts(
769            directory,
770            schema,
771            config,
772            builder_config,
773            segment_manager,
774            writer_lock,
775        ))
776    }
777
778    /// Create an IndexWriter from an existing Index.
779    /// Shares the SegmentManager for consistent segment lifecycle management.
780    ///
781    /// This constructor is infallible, so a single-writer lock conflict is
782    /// deferred: the returned writer fails loudly on its first mutating
783    /// operation instead of silently double-writing next to another writer.
784    pub fn from_index(index: &super::Index<D>) -> Self {
785        let writer_lock = match try_acquire_writer_lock(index.directory.as_ref()) {
786            Ok(lock) => lock,
787            Err(error) => WriterLock::Unavailable {
788                reason: format!("failed to acquire the single-writer lock: {error}"),
789            },
790        };
791        if let WriterLock::Unavailable { reason } = &writer_lock {
792            log::error!("[writer_lock] {reason}");
793        }
794        let builder_config = default_builder_config(&index.config);
795        Self::new_with_parts(
796            Arc::clone(&index.directory),
797            Arc::clone(&index.schema),
798            index.config.clone(),
799            builder_config,
800            Arc::clone(&index.segment_manager),
801            writer_lock,
802        )
803    }
804
805    // ========================================================================
806    // Construction + pipeline management
807    // ========================================================================
808
809    /// Common construction: creates worker state, spawns workers, assembles `Self`.
810    fn new_with_parts(
811        directory: Arc<D>,
812        schema: Arc<Schema>,
813        config: IndexConfig,
814        builder_config: SegmentBuilderConfig,
815        segment_manager: Arc<crate::merge::SegmentManager<D>>,
816        writer_lock: WriterLock,
817    ) -> Self {
818        // Auto-configure tokenizers from schema for all text fields
819        let registry = crate::tokenizer::TokenizerRegistry::new();
820        let mut tokenizers = FxHashMap::default();
821        for (field, entry) in schema.fields() {
822            if matches!(entry.field_type, crate::dsl::FieldType::Text)
823                && let Some(ref tok_name) = entry.tokenizer
824                && let Some(tok) = registry.get(tok_name)
825            {
826                tokenizers.insert(field, tok);
827            }
828        }
829
830        let num_workers = config.num_indexing_threads.max(1);
831        let worker_state = Arc::new(WorkerState {
832            directory: Arc::clone(&directory),
833            schema: Arc::clone(&schema),
834            builder_config,
835            tokenizers: parking_lot::RwLock::new(tokenizers),
836            memory_budget_per_worker: config.max_indexing_memory_bytes / num_workers,
837            segment_build_limiter: SegmentBuildLimiter::new(num_workers),
838            segment_manager: Arc::clone(&segment_manager),
839            built_segments: parking_lot::Mutex::new(Vec::new()),
840            cycle_error: parking_lot::Mutex::new(None),
841            cycle_failed: AtomicBool::new(false),
842            flush_count: AtomicUsize::new(0),
843            flush_mutex: parking_lot::Mutex::new(()),
844            flush_cvar: parking_lot::Condvar::new(),
845            resume_receiver: parking_lot::Mutex::new(None),
846            resume_epoch: AtomicUsize::new(0),
847            resume_cvar: parking_lot::Condvar::new(),
848            shutdown: AtomicBool::new(false),
849            num_workers,
850        });
851        let (doc_sender, workers) = Self::spawn_workers(&worker_state, num_workers);
852        let primary_key_index = Arc::new(parking_lot::RwLock::new(None));
853        let primary_key_refresh_lock = Arc::new(tokio::sync::Mutex::new(()));
854
855        Self {
856            directory,
857            schema,
858            config,
859            doc_sender: Arc::new(parking_lot::RwLock::new(doc_sender)),
860            workers,
861            worker_state,
862            segment_manager,
863            flushed_segments: Arc::new(parking_lot::Mutex::new(Vec::new())),
864            primary_key_index,
865            primary_key_refresh_lock,
866            commit_finalization: Arc::new(CommitFinalizationState::default()),
867            pk_reservations_retained: Arc::new(AtomicBool::new(false)),
868            writer_lock: parking_lot::RwLock::new(writer_lock),
869        }
870    }
871
872    /// Fail loudly when another writer owns the single-writer lock.
873    ///
874    /// A deferred conflict (`from_index` during a writer handover, e.g. a
875    /// rolling pod restart) is not permanent: the holder exits and the kernel
876    /// releases its advisory lock. Re-attempt acquisition on every call in
877    /// the `Unavailable` state so the writer recovers as soon as the lock
878    /// frees, instead of rejecting all writes for its lifetime.
879    fn ensure_writer_lock(&self) -> Result<()> {
880        // Fast path: uncontended read on the healthy states.
881        if !matches!(&*self.writer_lock.read(), WriterLock::Unavailable { .. }) {
882            return Ok(());
883        }
884
885        let mut lock = self.writer_lock.write();
886        // Another thread may have recovered while we waited for the write lock.
887        if !matches!(&*lock, WriterLock::Unavailable { .. }) {
888            return Ok(());
889        }
890        match try_acquire_writer_lock(self.directory.as_ref())? {
891            acquired @ (WriterLock::Held { .. } | WriterLock::NotApplicable) => {
892                log::info!(
893                    "[writer_lock] index={} single-writer lock acquired after retry; \
894                     the previous holder has released it — resuming writes",
895                    self.schema.index_label()
896                );
897                *lock = acquired;
898                Ok(())
899            }
900            WriterLock::Unavailable { reason } => {
901                let err = Error::Internal(reason.clone());
902                *lock = WriterLock::Unavailable { reason };
903                Err(err)
904            }
905        }
906    }
907
908    /// Clear primary-key reservations after an aborted or failed generation.
909    ///
910    /// Skipped while a failed post-commit PK refresh has left the uncommitted
911    /// reservations as the ONLY record of already-committed keys (fail-closed,
912    /// see `finalize_prepared_commit`): wiping them would admit duplicate
913    /// primary keys. Retaining the aborted generation's keys as well is
914    /// deliberately conservative — they clear on the next successful commit's
915    /// refresh.
916    fn clear_uncommitted_pk_reservations(&self) {
917        if self.pk_reservations_retained.load(Ordering::Acquire) {
918            log::warn!(
919                "[primary_key] index={} keeping uncommitted reservations through abort: a \
920                 failed post-commit refresh left them as the only record of \
921                 committed keys; they are cleared by the next successful commit",
922                self.schema.index_label()
923            );
924            return;
925        }
926        if let Some(pk_index) = self.primary_key_index.write().as_mut() {
927            pk_index.clear_uncommitted();
928        }
929    }
930
931    fn spawn_workers(
932        worker_state: &Arc<WorkerState<D>>,
933        num_workers: usize,
934    ) -> (
935        async_channel::Sender<Document>,
936        Vec<std::thread::JoinHandle<()>>,
937    ) {
938        let (sender, receiver) = async_channel::bounded(PIPELINE_MAX_SIZE_IN_DOCS);
939        let handle = tokio::runtime::Handle::current();
940        let mut workers = Vec::with_capacity(num_workers);
941        for i in 0..num_workers {
942            let state = Arc::clone(worker_state);
943            let rx = receiver.clone();
944            let rt = handle.clone();
945            workers.push(
946                std::thread::Builder::new()
947                    .name(format!("index-worker-{}", i))
948                    .spawn(move || Self::worker_loop(state, rx, rt, i))
949                    .expect("failed to spawn index worker thread"),
950            );
951        }
952        (sender, workers)
953    }
954
955    /// Get the schema
956    pub fn schema(&self) -> &Schema {
957        &self.schema
958    }
959
960    /// Set tokenizer for a field.
961    /// Propagated to worker threads — takes effect for the next SegmentBuilder they create.
962    pub fn set_tokenizer<T: crate::tokenizer::Tokenizer>(&mut self, field: Field, tokenizer: T) {
963        self.worker_state
964            .tokenizers
965            .write()
966            .insert(field, Box::new(tokenizer));
967    }
968
969    /// Initialize primary key deduplication from committed segments.
970    ///
971    /// Tries to load a cached bloom filter from `pk_bloom.bin` first. If the
972    /// cache covers all current segments, the bloom is reused directly (fast
973    /// path). If new segments appeared since the cache was written, only their
974    /// keys are iterated (incremental). Falls back to a full rebuild when no
975    /// cache exists.
976    ///
977    /// Only loads fast-field data (text dictionaries) per segment — NOT full
978    /// `SegmentReader`s — to avoid duplicating dense/sparse index memory.
979    ///
980    /// The CPU-intensive bloom build is offloaded via `spawn_blocking` so it
981    /// does not block the tokio runtime.
982    ///
983    /// No-op if schema has no primary field.
984    pub async fn init_primary_key_dedup(&mut self) -> Result<()> {
985        use super::primary_key::{PK_BLOOM_FILE, deserialize_pk_bloom};
986
987        self.commit_finalization.wait_until_idle().await;
988        self.ensure_writer_lock()?;
989
990        let field = match self.schema.primary_field() {
991            Some(f) => f,
992            None => return Ok(()),
993        };
994
995        // A merge/reorder replacement can publish while this initialization
996        // performs async segment loads. Serialize both paths so an older
997        // initialization snapshot cannot overwrite the replacement refresh
998        // and keep retired source segments pinned indefinitely.
999        let _refresh_guard = self.primary_key_refresh_lock.lock().await;
1000        {
1001            let callback_directory = Arc::clone(&self.directory);
1002            let callback_schema = Arc::clone(&self.schema);
1003            let callback_manager = Arc::downgrade(&self.segment_manager);
1004            let callback_primary_key = Arc::downgrade(&self.primary_key_index);
1005            let callback_refresh_lock = Arc::downgrade(&self.primary_key_refresh_lock);
1006            self.segment_manager.set_replacement_refresh(move || {
1007                let directory = Arc::clone(&callback_directory);
1008                let schema = Arc::clone(&callback_schema);
1009                let manager = callback_manager.clone();
1010                let primary_key = callback_primary_key.clone();
1011                let refresh_lock = callback_refresh_lock.clone();
1012                async move {
1013                    let (Some(manager), Some(primary_key), Some(refresh_lock)) = (
1014                        manager.upgrade(),
1015                        primary_key.upgrade(),
1016                        refresh_lock.upgrade(),
1017                    ) else {
1018                        return Ok(());
1019                    };
1020                    refresh_primary_key_snapshot(
1021                        &directory,
1022                        &schema,
1023                        &manager,
1024                        &primary_key,
1025                        &refresh_lock,
1026                        PrimaryKeyRefresh::Replacement,
1027                    )
1028                    .await
1029                }
1030            });
1031        }
1032
1033        let snapshot = self.segment_manager.acquire_snapshot().await;
1034        let current_seg_ids: Vec<String> = snapshot.segment_ids().to_vec();
1035
1036        // Try to load persisted bloom filter.
1037        let cached = match self
1038            .directory
1039            .open_read(std::path::Path::new(PK_BLOOM_FILE))
1040            .await
1041        {
1042            Ok(handle) => {
1043                let data = handle.read_bytes_range(0..handle.len()).await;
1044                match data {
1045                    Ok(bytes) => deserialize_pk_bloom(bytes.as_slice()),
1046                    Err(_) => None,
1047                }
1048            }
1049            Err(_) => None,
1050        };
1051
1052        // Load lightweight fast-field data for all segments concurrently.
1053        let load_futures: Vec<_> = current_seg_ids
1054            .iter()
1055            .map(|seg_id_str| {
1056                let seg_id_str = seg_id_str.clone();
1057                let dir = self.directory.as_ref();
1058                let schema = Arc::clone(&self.schema);
1059                async move { load_pk_segment_data(dir, &seg_id_str, &schema).await }
1060            })
1061            .collect();
1062        let all_data = futures::future::try_join_all(load_futures).await?;
1063
1064        if let Some((persisted_seg_ids, bloom)) = cached {
1065            // Partition: old segments (covered by bloom) first, new segments at end.
1066            let mut pk_data = Vec::with_capacity(all_data.len());
1067            let mut new_data = Vec::new();
1068            for d in all_data {
1069                if persisted_seg_ids.contains(&d.segment_id) {
1070                    pk_data.push(d);
1071                } else {
1072                    new_data.push(d);
1073                }
1074            }
1075            let needs_persist = !new_data.is_empty();
1076            let new_start = pk_data.len();
1077            pk_data.extend(new_data);
1078
1079            let pk_index = if new_start == pk_data.len() {
1080                // Fast path: all segments covered by cache.
1081                super::primary_key::PrimaryKeyIndex::from_persisted(field, bloom, pk_data, snapshot)
1082            } else {
1083                // Incremental: only iterate new segments' keys.
1084                let index_label = self.schema.index_label().to_owned();
1085                tokio::task::spawn_blocking(move || {
1086                    // Insert new segments' keys into the bloom, then construct
1087                    // PrimaryKeyIndex with the pre-populated bloom.
1088                    let mut bloom = bloom;
1089                    let mut added = 0usize;
1090                    let num_new = pk_data.len() - new_start;
1091                    for data in &pk_data[new_start..] {
1092                        if let Some(ff) = data.fast_fields.get(&field.0)
1093                            && let Some(dict) = ff.text_dict()
1094                        {
1095                            for key in dict.iter() {
1096                                bloom.insert(key.as_bytes());
1097                                added += 1;
1098                            }
1099                        }
1100                    }
1101                    if added > 0 {
1102                        log::info!(
1103                            "[primary_key] index={index_label} bloom: added {} keys from {} new segment(s)",
1104                            added,
1105                            num_new,
1106                        );
1107                    }
1108                    super::primary_key::PrimaryKeyIndex::from_persisted(
1109                        field, bloom, pk_data, snapshot,
1110                    )
1111                })
1112                .await
1113                .map_err(|e| Error::Internal(format!("spawn_blocking failed: {}", e)))?
1114            };
1115
1116            if needs_persist {
1117                self.persist_pk_bloom(&pk_index, &current_seg_ids).await;
1118            }
1119
1120            *self.primary_key_index.write() = Some(pk_index);
1121        } else {
1122            // No cache — full rebuild, offloaded to blocking thread.
1123            let pk_index = tokio::task::spawn_blocking(move || {
1124                super::primary_key::PrimaryKeyIndex::new(field, all_data, snapshot)
1125            })
1126            .await
1127            .map_err(|e| Error::Internal(format!("spawn_blocking failed: {}", e)))?;
1128
1129            self.persist_pk_bloom(&pk_index, &current_seg_ids).await;
1130            *self.primary_key_index.write() = Some(pk_index);
1131        }
1132
1133        // The freshly built index covers every committed segment, so any
1134        // reservations retained after a failed post-commit refresh are
1135        // superseded by committed_data.
1136        self.pk_reservations_retained
1137            .store(false, Ordering::Release);
1138
1139        Ok(())
1140    }
1141
1142    /// Persist the primary-key bloom filter to `pk_bloom.bin`.
1143    /// Best-effort: errors are logged but not propagated.
1144    async fn persist_pk_bloom(
1145        &self,
1146        pk_index: &super::primary_key::PrimaryKeyIndex,
1147        segment_ids: &[String],
1148    ) {
1149        use super::primary_key::PK_BLOOM_FILE;
1150
1151        let writer = match self
1152            .directory
1153            .streaming_writer(std::path::Path::new(PK_BLOOM_FILE))
1154            .await
1155        {
1156            Ok(writer) => writer,
1157            Err(error) => {
1158                log::warn!(
1159                    "[primary_key] index={} failed to open bloom cache: {}",
1160                    self.schema.index_label(),
1161                    error
1162                );
1163                return;
1164            }
1165        };
1166        let result = crate::segment::block_in_place_if_multithread(|| {
1167            write_pk_bloom_stream(pk_index, segment_ids, writer)
1168        });
1169        if let Err(e) = result {
1170            log::warn!(
1171                "[primary_key] index={} failed to persist bloom cache: {}",
1172                self.schema.index_label(),
1173                e
1174            );
1175        }
1176    }
1177
1178    /// Add a document to the indexing queue (sync, O(1)).
1179    ///
1180    /// `Document` is moved into the channel (zero-copy). Workers compete to pull it.
1181    /// Returns an explicit backpressure error when the queue is at capacity or
1182    /// a prepared commit generation is not yet resolved.
1183    pub fn add_document(&self, doc: Document) -> Result<()> {
1184        self.ensure_writer_lock()?;
1185        if self.worker_state.shutdown.load(Ordering::Acquire) {
1186            return Err(Error::IndexClosed);
1187        }
1188        if self.commit_finalization.in_progress.load(Ordering::Acquire) {
1189            return Err(Error::CommitInProgress);
1190        }
1191        let sender = self.doc_sender.read().clone();
1192        // A publication error deliberately leaves the prepared generation and
1193        // its workers paused for a lossless retry. Report this as backpressure
1194        // instead of inserting/rolling back a PK key against a closed channel.
1195        if sender.is_closed() {
1196            return Err(Error::CommitInProgress);
1197        }
1198        let primary_key_index = self.primary_key_index.read();
1199        if let Some(ref pk_index) = *primary_key_index {
1200            pk_index.check_and_insert(&doc)?;
1201        }
1202        match sender.try_send(doc) {
1203            Ok(()) => Ok(()),
1204            Err(async_channel::TrySendError::Full(doc)) => {
1205                // Roll back PK registration so the caller can retry later
1206                if let Some(ref pk_index) = *primary_key_index {
1207                    pk_index.rollback_uncommitted_key(&doc);
1208                }
1209                Err(Error::QueueFull)
1210            }
1211            Err(async_channel::TrySendError::Closed(doc)) => {
1212                // Roll back PK registration for defense-in-depth
1213                if let Some(ref pk_index) = *primary_key_index {
1214                    pk_index.rollback_uncommitted_key(&doc);
1215                }
1216                Err(Error::CommitInProgress)
1217            }
1218        }
1219    }
1220
1221    /// Add multiple documents to the indexing queue.
1222    ///
1223    /// Returns the number of documents successfully queued. Stops at the first
1224    /// backpressure error and returns the count queued so far.
1225    pub fn add_documents(&self, documents: Vec<Document>) -> Result<usize> {
1226        let total = documents.len();
1227        for (i, doc) in documents.into_iter().enumerate() {
1228            match self.add_document(doc) {
1229                Ok(()) => {}
1230                Err(Error::QueueFull | Error::CommitInProgress) => return Ok(i),
1231                Err(e) => return Err(e),
1232            }
1233        }
1234        Ok(total)
1235    }
1236
1237    // ========================================================================
1238    // Worker loop
1239    // ========================================================================
1240
1241    /// Worker loop — runs on a dedicated OS thread, survives across commits.
1242    ///
1243    /// Outer loop: each iteration processes one commit cycle.
1244    ///   Inner loop: pull documents from MPMC queue, index them, build segments
1245    ///   when memory budget is exceeded.
1246    ///   On channel close (prepare_commit): flush current builder, signal
1247    ///   flush_count, wait for resume with new receiver.
1248    ///   On shutdown (Drop): exit permanently.
1249    fn worker_loop(
1250        state: Arc<WorkerState<D>>,
1251        initial_receiver: async_channel::Receiver<Document>,
1252        handle: tokio::runtime::Handle,
1253        worker_id: usize,
1254    ) {
1255        let mut receiver = initial_receiver;
1256        let mut my_epoch = 0usize;
1257        let soft_flush_threshold =
1258            soft_flush_threshold(state.memory_budget_per_worker, worker_id, state.num_workers);
1259        let hard_flush_threshold = hard_flush_threshold(state.memory_budget_per_worker);
1260
1261        loop {
1262            // Wrap the recv+build phase in catch_unwind so a panic doesn't
1263            // prevent flush_count from being signaled (which would hang
1264            // prepare_commit forever).
1265            let build_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1266                let mut builder: Option<SegmentBuilder> = None;
1267
1268                while let Ok(doc) = receiver.recv_blocking() {
1269                    if state.shutdown.load(Ordering::Acquire) {
1270                        break;
1271                    }
1272                    // Another worker already invalidated this generation.
1273                    // Drain the shared queue so prepare_commit can complete,
1274                    // but do not spend CPU/RAM building outputs that must be
1275                    // discarded transactionally.
1276                    if state.cycle_failed.load(Ordering::Acquire) {
1277                        continue;
1278                    }
1279                    // Initialize builder if needed
1280                    if builder.is_none() {
1281                        match SegmentBuilder::new(
1282                            Arc::clone(&state.schema),
1283                            state.builder_config.clone(),
1284                        ) {
1285                            Ok(mut b) => {
1286                                for (field, tokenizer) in state.tokenizers.read().iter() {
1287                                    b.set_tokenizer(*field, tokenizer.clone_box());
1288                                }
1289                                builder = Some(b);
1290                            }
1291                            Err(e) => {
1292                                log::error!("Failed to create segment builder: {:?}", e);
1293                                state.record_cycle_error(format!(
1294                                    "failed to create segment builder: {e}"
1295                                ));
1296                                continue;
1297                            }
1298                        }
1299                    }
1300
1301                    let b = builder.as_mut().unwrap();
1302                    if let Err(e) = b.add_document(doc) {
1303                        log::error!("Failed to index document: {:?}", e);
1304                        state.record_cycle_error(format!("failed to index document: {e}"));
1305                        continue;
1306                    }
1307
1308                    let builder_memory = b.estimated_memory_bytes();
1309
1310                    if b.num_docs() & 0x3FFF == 0 {
1311                        log::debug!(
1312                            "[indexing] index={} docs={}, memory={}, budget={}",
1313                            state.schema.index_label(),
1314                            b.num_docs(),
1315                            crate::format_bytes(builder_memory as u64),
1316                            crate::format_bytes(state.memory_budget_per_worker as u64)
1317                        );
1318                    }
1319
1320                    // Require minimum 100 docs before flushing to avoid tiny segments
1321                    const MIN_DOCS_BEFORE_FLUSH: u32 = 100;
1322
1323                    if b.num_docs() >= MIN_DOCS_BEFORE_FLUSH
1324                        && let Some(_build_permit) = state.segment_build_limiter.reserve_if_due(
1325                            builder_memory,
1326                            soft_flush_threshold,
1327                            hard_flush_threshold,
1328                        )
1329                    {
1330                        log::info!(
1331                            "[indexing] index={} memory budget reached, building segment: \
1332                             worker={}, docs={}, memory={}, soft_budget={}, hard_budget={}",
1333                            state.schema.index_label(),
1334                            worker_id,
1335                            b.num_docs(),
1336                            crate::format_bytes(builder_memory as u64),
1337                            crate::format_bytes(soft_flush_threshold as u64),
1338                            crate::format_bytes(hard_flush_threshold as u64),
1339                        );
1340                        let full_builder = builder.take().unwrap();
1341                        Self::build_segment_inline(&state, full_builder, &handle);
1342                    }
1343                }
1344
1345                // Channel closed — flush current builder
1346                if !state.cycle_failed.load(Ordering::Acquire)
1347                    && let Some(b) = builder.take()
1348                    && b.num_docs() > 0
1349                {
1350                    let _build_permit = state.segment_build_limiter.acquire_flush();
1351                    Self::build_segment_inline(&state, b, &handle);
1352                }
1353            }));
1354
1355            if build_result.is_err() {
1356                log::error!(
1357                    "[worker] index={} panic during indexing cycle — documents in this cycle may be lost",
1358                    state.schema.index_label()
1359                );
1360                state.record_cycle_error("indexing worker panicked while building the batch");
1361            }
1362
1363            // Signal flush completion (always, even after panic — prevents
1364            // prepare_commit from hanging)
1365            let prev = state.flush_count.fetch_add(1, Ordering::Release);
1366            if prev + 1 == state.num_workers {
1367                // Last worker — wake prepare_commit. notify_all, not
1368                // notify_one: a cancelled commit leaves its detached
1369                // spawn_blocking waiter parked on this condvar, and with a
1370                // single notification that dead waiter would consume the
1371                // only wakeup, stalling a retried prepare_commit for its
1372                // full deadline.
1373                let _lock = state.flush_mutex.lock();
1374                state.flush_cvar.notify_all();
1375            }
1376
1377            // Wait for resume (new channel) or shutdown.
1378            // Check resume_epoch to avoid re-cloning a stale receiver from
1379            // a previous cycle.
1380            {
1381                let mut lock = state.resume_receiver.lock();
1382                loop {
1383                    if state.shutdown.load(Ordering::Acquire) {
1384                        return;
1385                    }
1386                    let current_epoch = state.resume_epoch.load(Ordering::Acquire);
1387                    if current_epoch > my_epoch
1388                        && let Some(rx) = lock.as_ref()
1389                    {
1390                        receiver = rx.clone();
1391                        my_epoch = current_epoch;
1392                        break;
1393                    }
1394                    state.resume_cvar.wait(&mut lock);
1395                }
1396            }
1397        }
1398    }
1399
1400    /// Build a segment on the worker thread. Uses `Handle::block_on()` to bridge
1401    /// into async context for I/O (streaming writers). CPU work (rayon) stays on
1402    /// the worker thread / rayon pool.
1403    fn build_segment_inline(
1404        state: &WorkerState<D>,
1405        builder: SegmentBuilder,
1406        handle: &tokio::runtime::Handle,
1407    ) {
1408        let segment_id = SegmentId::new();
1409        let segment_hex = segment_id.to_hex();
1410        // Claim the ID before the first file write. The guard is moved into
1411        // `PreparedSegment` on success and otherwise releases automatically.
1412        let operation = match state
1413            .segment_manager
1414            .protect_new_segment(segment_hex.clone())
1415        {
1416            Ok(operation) => operation,
1417            Err(e) => {
1418                log::error!(
1419                    "[segment_build_failed] index={} segment_id={} lifecycle_error={}",
1420                    state.schema.index_label(),
1421                    segment_hex,
1422                    e,
1423                );
1424                state.record_cycle_error(format!(
1425                    "failed to claim segment {segment_hex} for building: {e}"
1426                ));
1427                return;
1428            }
1429        };
1430        let trained = state.segment_manager.trained_for_segment_build();
1431        let doc_count = builder.num_docs();
1432        let build_start = std::time::Instant::now();
1433
1434        log::info!(
1435            "[segment_build] index={} segment_id={} doc_count={} ann={}",
1436            state.schema.index_label(),
1437            segment_hex,
1438            doc_count,
1439            trained.is_some()
1440        );
1441
1442        // Construct the cleanup owner before building. It keeps lifecycle
1443        // ownership through async deletion on ordinary error, abort, and
1444        // panic unwind; crash recovery is the only path left to the sweeper.
1445        let mut prepared = PreparedSegment {
1446            id: segment_hex.clone(),
1447            segment_id,
1448            num_docs: doc_count,
1449            segment_manager: Arc::clone(&state.segment_manager),
1450            operation: Some(operation),
1451            runtime: handle.clone(),
1452            needs_vector_upgrade: trained.is_none(),
1453            published: false,
1454        };
1455
1456        match handle.block_on(builder.build(
1457            state.directory.as_ref(),
1458            segment_id,
1459            trained.as_deref(),
1460        )) {
1461            Ok(meta) if meta.num_docs == doc_count && meta.num_docs > 0 => {
1462                let duration_ms = build_start.elapsed().as_millis() as u64;
1463                log::info!(
1464                    "[segment_build_done] index={} segment_id={} doc_count={} duration_ms={}",
1465                    state.schema.index_label(),
1466                    segment_hex,
1467                    meta.num_docs,
1468                    duration_ms,
1469                );
1470                prepared.num_docs = meta.num_docs;
1471                state.built_segments.lock().push(prepared);
1472            }
1473            Ok(meta) => {
1474                let error = format!(
1475                    "segment {segment_hex} built {} docs from a {doc_count}-document builder",
1476                    meta.num_docs
1477                );
1478                log::error!(
1479                    "[segment_build_failed] index={} {error}",
1480                    state.schema.index_label()
1481                );
1482                state.record_cycle_error(error);
1483            }
1484            Err(e) => {
1485                log::error!(
1486                    "[segment_build_failed] index={} segment_id={} error={:?}",
1487                    state.schema.index_label(),
1488                    segment_hex,
1489                    e
1490                );
1491                // `prepared` owns the lifecycle claim and schedules one
1492                // tracked, idempotent cleanup pass when this scope ends.
1493                state.record_cycle_error(format!("failed to build segment {segment_hex}: {e}"));
1494            }
1495        }
1496    }
1497
1498    // ========================================================================
1499    // Public API — commit, merge, etc.
1500    // ========================================================================
1501
1502    /// Check merge policy and spawn a background merge if needed.
1503    pub async fn maybe_merge(&self) {
1504        self.segment_manager.maybe_merge().await;
1505    }
1506
1507    /// Drain all in-flight merge tasks.
1508    /// Blocking merge phases cannot be cancelled safely once started.
1509    pub async fn abort_merges(&self) {
1510        self.segment_manager.abort_merges().await;
1511    }
1512
1513    /// Stop accepting lifecycle work, stop and join indexing workers, and
1514    /// discard unpublished segments. Index deletion calls this while holding
1515    /// the registry writer lock so in-flight requests finish first and stale
1516    /// writer Arcs cannot restart work afterward.
1517    pub async fn shutdown(&mut self) -> Result<()> {
1518        self.segment_manager.begin_shutdown();
1519        self.signal_worker_shutdown();
1520
1521        // A cancelled commit request leaves its owned finalizer running. Do not
1522        // clear shared PK/prepared state while that task may still publish or
1523        // refresh it. Worker shutdown is signalled first, so a successful
1524        // finalizer cannot restart ingestion while deletion is waiting.
1525        self.commit_finalization.wait_until_idle().await;
1526
1527        let workers = std::mem::take(&mut self.workers);
1528        let panicked = tokio::task::spawn_blocking(move || {
1529            workers
1530                .into_iter()
1531                .map(|worker| worker.join().is_err())
1532                .filter(|panicked| *panicked)
1533                .count()
1534        })
1535        .await
1536        .map_err(|error| Error::Internal(format!("failed to join index workers: {}", error)))?;
1537        if panicked > 0 {
1538            log::error!(
1539                "[index_shutdown] index={} {} indexing worker(s) panicked",
1540                self.schema.index_label(),
1541                panicked
1542            );
1543        }
1544
1545        // No commit is possible after shutdown. Dropping these RAII values
1546        // releases their lifecycle ownership before directory deletion.
1547        self.flushed_segments.lock().clear();
1548        self.worker_state.built_segments.lock().clear();
1549        if let Some(pk_index) = self.primary_key_index.write().as_mut() {
1550            pk_index.clear_uncommitted();
1551        }
1552        Ok(())
1553    }
1554
1555    /// Wait for the in-flight background merge to complete (if any).
1556    pub async fn wait_for_merging_thread(&self) {
1557        self.segment_manager.wait_for_merging_thread().await;
1558    }
1559
1560    /// Wait for all eligible merges to complete, including cascading merges.
1561    pub async fn wait_for_all_merges(&self) {
1562        self.segment_manager.wait_for_all_merges().await;
1563    }
1564
1565    /// Wait until an owned commit finalizer has reconciled durable metadata,
1566    /// primary-key state, and worker availability. Normally callers need not
1567    /// use this: it exists for orderly shutdown and request supervisors that
1568    /// want to observe completion after cancelling their original waiter.
1569    pub async fn wait_for_commit_finalization(&self) {
1570        self.commit_finalization.wait_until_idle().await;
1571    }
1572
1573    /// Get the segment tracker for sharing with readers.
1574    pub fn tracker(&self) -> std::sync::Arc<crate::segment::SegmentTracker> {
1575        self.segment_manager.tracker()
1576    }
1577
1578    /// Acquire a snapshot of current segments for reading.
1579    pub async fn acquire_snapshot(&self) -> crate::segment::SegmentSnapshot {
1580        self.segment_manager.acquire_snapshot().await
1581    }
1582
1583    /// Clean up orphan segment files not registered in metadata.
1584    ///
1585    /// Requires the single-writer lock: sweeping while another process's
1586    /// writer is live would delete its in-flight segment outputs.
1587    pub async fn cleanup_orphan_segments(&self) -> Result<usize> {
1588        self.ensure_writer_lock()?;
1589        self.segment_manager.cleanup_orphan_segments().await
1590    }
1591
1592    /// Prepare commit — signal workers to flush, wait for completion, collect segments.
1593    ///
1594    /// All documents sent via `add_document` before this call are guaranteed
1595    /// to be written to segment files on disk. Segments are NOT yet registered
1596    /// in metadata — call `PreparedCommit::commit()` for that.
1597    ///
1598    /// Workers are NOT destroyed — they flush their builders and wait for
1599    /// `resume_workers()` to give them a new channel.
1600    ///
1601    /// `add_document` returns `CommitInProgress` until commit/abort resumes workers.
1602    pub async fn prepare_commit(&mut self) -> Result<PreparedCommit<'_, D>> {
1603        self.ensure_writer_lock()?;
1604        if self.worker_state.shutdown.load(Ordering::Acquire) {
1605            return Err(Error::IndexClosed);
1606        }
1607        if self.commit_finalization.in_progress.load(Ordering::Acquire) {
1608            return Err(Error::CommitInProgress);
1609        }
1610        // 1. Close channel → workers drain remaining docs and flush builders
1611        self.doc_sender.read().close();
1612        self.worker_state.segment_build_limiter.begin_flush();
1613
1614        // Wake any workers still waiting on resume_cvar from previous cycle.
1615        // They'll clone the stale receiver, enter recv_blocking, get Err
1616        // immediately (sender already closed), flush, and signal completion.
1617        self.worker_state.resume_cvar.notify_all();
1618
1619        // 2. Wait for all workers to complete their flush (via spawn_blocking
1620        //    to avoid blocking the tokio runtime)
1621        let state = Arc::clone(&self.worker_state);
1622        let index_label = self.schema.index_label().to_owned();
1623        let all_flushed = tokio::task::spawn_blocking(move || {
1624            let mut lock = state.flush_mutex.lock();
1625            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
1626            while state.flush_count.load(Ordering::Acquire) < state.num_workers {
1627                let remaining = deadline.saturating_duration_since(std::time::Instant::now());
1628                if remaining.is_zero() {
1629                    log::error!(
1630                        "[prepare_commit] index={index_label} timed out waiting for workers: {}/{} flushed",
1631                        state.flush_count.load(Ordering::Acquire),
1632                        state.num_workers
1633                    );
1634                    return false;
1635                }
1636                state.flush_cvar.wait_for(&mut lock, remaining);
1637            }
1638            true
1639        })
1640        .await
1641        .map_err(|e| Error::Internal(format!("Failed to wait for workers: {}", e)))?;
1642
1643        if !all_flushed {
1644            // Keep this commit cycle paused. Resetting flush_count and handing
1645            // out a new receiver while an old worker is still building lets
1646            // that late worker increment the *next* cycle's counter. A later
1647            // prepare can then return before all of its workers flushed and
1648            // publish an incomplete set of segments. The caller may retry
1649            // prepare_commit; it will observe the same generation and collect
1650            // every completed output once the lagging worker finishes.
1651            return Err(Error::Internal(format!(
1652                "prepare_commit timed out: {}/{} workers flushed; writer remains paused, retry commit",
1653                self.worker_state.flush_count.load(Ordering::Acquire),
1654                self.worker_state.num_workers
1655            )));
1656        }
1657
1658        let cycle_error = { self.worker_state.cycle_error.lock().take() };
1659        if let Some(error) = cycle_error {
1660            // No partial publication: some documents in this generation no
1661            // longer exist in a worker builder, so successful sibling outputs
1662            // cannot be committed without violating commit's all-prior-docs
1663            // guarantee. Their RAII drops retain ownership through deletion.
1664            self.flushed_segments.lock().clear();
1665            self.worker_state.built_segments.lock().clear();
1666            self.clear_uncommitted_pk_reservations();
1667            self.resume_workers();
1668            return Err(Error::Internal(format!(
1669                "indexing generation failed; no documents from this batch were committed: {error}"
1670            )));
1671        }
1672
1673        // 3. Collect built segments
1674        let built = std::mem::take(&mut *self.worker_state.built_segments.lock());
1675        self.flushed_segments.lock().extend(built);
1676
1677        Ok(PreparedCommit {
1678            writer: self,
1679            is_resolved: false,
1680        })
1681    }
1682
1683    /// Commit (convenience): prepare_commit + commit in one call.
1684    ///
1685    /// Guarantees all prior `add_document` calls are committed.
1686    /// Vector training is decoupled — call `build_vector_index()` manually.
1687    pub async fn commit(&mut self) -> Result<bool> {
1688        self.prepare_commit().await?.commit().await
1689    }
1690
1691    /// Force merge all segments into one.
1692    pub async fn force_merge(&mut self) -> Result<()> {
1693        self.force_merge_with_snapshot_refresh(|| std::future::ready(Ok(())))
1694            .await
1695    }
1696
1697    /// Force merge while refreshing an external segment consumer after the
1698    /// background-merge drain and every durable replacement.
1699    ///
1700    /// Segment publication refreshes the writer's primary-key topology through
1701    /// the manager's lifecycle-owned hook. Servers use this callback to reload
1702    /// their cached `IndexReader` as well.
1703    pub async fn force_merge_with_snapshot_refresh<F, Fut>(
1704        &mut self,
1705        refresh_external: F,
1706    ) -> Result<()>
1707    where
1708        F: FnMut() -> Fut,
1709        Fut: std::future::Future<Output = Result<()>>,
1710    {
1711        self.prepare_commit().await?.commit().await?;
1712
1713        self.segment_manager
1714            .force_merge_with_snapshot_refresh(refresh_external)
1715            .await?;
1716
1717        // Segment IDs in the on-disk bloom cache need only the final
1718        // generation. Persisting the unchanged bloom after every hierarchy
1719        // level adds avoidable I/O on large primary-key indexes.
1720        self.persist_replacement_snapshot().await
1721    }
1722
1723    /// Reorder all segments via Recursive Graph Bisection (BP) for better BMP pruning.
1724    ///
1725    /// Each segment is individually rebuilt with record-level BP reordering:
1726    /// ordinals are shuffled across blocks so that similar content clusters tightly.
1727    pub async fn reorder(&mut self) -> Result<()> {
1728        self.reorder_with_snapshot_refresh(|| std::future::ready(Ok(())))
1729            .await
1730    }
1731
1732    /// Reorder while refreshing an external reader after each durable segment
1733    /// replacement, so retired sources are released during a long pass.
1734    pub async fn reorder_with_snapshot_refresh<F, Fut>(&mut self, refresh_external: F) -> Result<()>
1735    where
1736        F: FnMut() -> Fut,
1737        Fut: std::future::Future<Output = Result<()>>,
1738    {
1739        self.prepare_commit().await?.commit().await?;
1740
1741        self.segment_manager
1742            .reorder_segments_with_snapshot_refresh(refresh_external)
1743            .await?;
1744        self.persist_replacement_snapshot().await
1745    }
1746
1747    /// Persist the final topology after a bounded series of replacements.
1748    async fn persist_replacement_snapshot(&self) -> Result<()> {
1749        refresh_primary_key_snapshot(
1750            &self.directory,
1751            &self.schema,
1752            &self.segment_manager,
1753            &self.primary_key_index,
1754            &self.primary_key_refresh_lock,
1755            PrimaryKeyRefresh::FinalReplacement,
1756        )
1757        .await
1758    }
1759
1760    /// Get the segment manager (for background optimizer access).
1761    pub fn segment_manager(&self) -> &Arc<crate::merge::SegmentManager<D>> {
1762        &self.segment_manager
1763    }
1764
1765    /// Resume workers with a fresh channel. Called after commit or abort.
1766    ///
1767    /// Workers are already alive — just give them a new channel and wake them.
1768    /// If the tokio runtime has shut down (e.g., program exit), this is a no-op.
1769    fn resume_workers(&mut self) {
1770        Self::resume_workers_shared(&self.worker_state, &self.doc_sender);
1771    }
1772
1773    fn resume_workers_shared(
1774        worker_state: &Arc<WorkerState<D>>,
1775        doc_sender: &Arc<parking_lot::RwLock<async_channel::Sender<Document>>>,
1776    ) {
1777        if worker_state.shutdown.load(Ordering::Acquire) {
1778            return;
1779        }
1780        if tokio::runtime::Handle::try_current().is_err() {
1781            // Runtime is gone — signal permanent shutdown so workers don't
1782            // hang forever on resume_cvar.
1783            worker_state.shutdown.store(true, Ordering::Release);
1784            worker_state.resume_cvar.notify_all();
1785            return;
1786        }
1787
1788        // Reset flush count for next cycle
1789        worker_state.segment_build_limiter.end_flush();
1790        worker_state.flush_count.store(0, Ordering::Release);
1791        *worker_state.cycle_error.lock() = None;
1792        worker_state.cycle_failed.store(false, Ordering::Release);
1793
1794        // Create new channel
1795        let (sender, receiver) = async_channel::bounded(PIPELINE_MAX_SIZE_IN_DOCS);
1796        *doc_sender.write() = sender;
1797
1798        // Set new receiver, bump epoch, and wake all workers
1799        {
1800            let mut lock = worker_state.resume_receiver.lock();
1801            *lock = Some(receiver);
1802        }
1803        worker_state.resume_epoch.fetch_add(1, Ordering::Release);
1804        worker_state.resume_cvar.notify_all();
1805    }
1806
1807    fn signal_worker_shutdown(&self) {
1808        self.worker_state.shutdown.store(true, Ordering::Release);
1809        self.doc_sender.read().close();
1810        self.worker_state.segment_build_limiter.begin_flush();
1811        self.worker_state.resume_cvar.notify_all();
1812    }
1813
1814    // Vector index methods (build_vector_index, etc.) are in vector_builder.rs
1815}
1816
1817impl<D: DirectoryWriter + 'static> Drop for IndexWriter<D> {
1818    fn drop(&mut self) {
1819        self.signal_worker_shutdown();
1820        for w in std::mem::take(&mut self.workers) {
1821            let _ = w.join();
1822        }
1823    }
1824}
1825
1826/// A prepared commit that can be finalized or aborted.
1827///
1828/// Two-phase commit guard. Between `prepare_commit()` and
1829/// `commit()`/`abort()`, segments are on disk but NOT in metadata.
1830/// Dropping without calling either will auto-abort (discard segments,
1831/// respawn workers).
1832pub struct PreparedCommit<'a, D: DirectoryWriter + 'static> {
1833    writer: &'a mut IndexWriter<D>,
1834    is_resolved: bool,
1835}
1836
1837/// Returns prepared segments to the writer if an owned commit finalizer fails
1838/// or unwinds before it can establish that metadata owns them. Retrying commit
1839/// is safe even when publication actually won the race: `SegmentManager::commit`
1840/// is idempotent and the operation guards keep the files protected meanwhile.
1841struct PreparedSegmentsGuard<D: DirectoryWriter + 'static> {
1842    segments: Option<Vec<PreparedSegment<D>>>,
1843    retry_slot: Arc<parking_lot::Mutex<Vec<PreparedSegment<D>>>>,
1844}
1845
1846impl<D: DirectoryWriter + 'static> PreparedSegmentsGuard<D> {
1847    fn metadata_entries(&self) -> Vec<(String, u32)> {
1848        self.segments
1849            .as_deref()
1850            .unwrap_or_default()
1851            .iter()
1852            .map(PreparedSegment::metadata_entry)
1853            .collect()
1854    }
1855
1856    fn take_published(&mut self) -> Vec<PreparedSegment<D>> {
1857        self.segments.take().unwrap_or_default()
1858    }
1859
1860    fn vector_upgrade_segment_ids(&self) -> Vec<String> {
1861        self.segments
1862            .as_deref()
1863            .unwrap_or_default()
1864            .iter()
1865            .filter(|segment| segment.needs_vector_upgrade)
1866            .map(|segment| segment.id.clone())
1867            .collect()
1868    }
1869}
1870
1871impl<D: DirectoryWriter + 'static> Drop for PreparedSegmentsGuard<D> {
1872    fn drop(&mut self) {
1873        if let Some(segments) = self.segments.take() {
1874            self.retry_slot.lock().extend(segments);
1875        }
1876    }
1877}
1878
1879/// Couples completion of the owned commit task to writer availability. The
1880/// default is deliberately fail-closed: a pre-publication error or panic keeps
1881/// workers paused so the retained prepared generation can be retried. Only the
1882/// normal published path arms resumption.
1883struct CommitFinalizationGuard<D: DirectoryWriter + 'static> {
1884    state: Arc<CommitFinalizationState>,
1885    worker_state: Arc<WorkerState<D>>,
1886    doc_sender: Arc<parking_lot::RwLock<async_channel::Sender<Document>>>,
1887    resume_workers: bool,
1888}
1889
1890impl<D: DirectoryWriter + 'static> CommitFinalizationGuard<D> {
1891    fn resume_on_drop(&mut self) {
1892        self.resume_workers = true;
1893    }
1894}
1895
1896impl<D: DirectoryWriter + 'static> Drop for CommitFinalizationGuard<D> {
1897    fn drop(&mut self) {
1898        if self.resume_workers {
1899            IndexWriter::<D>::resume_workers_shared(&self.worker_state, &self.doc_sender);
1900        }
1901        self.state.finish();
1902    }
1903}
1904
1905/// Everything needed to finish one prepared generation is moved into this
1906/// value before spawning. Its two guards therefore reconcile segment
1907/// ownership and writer availability even if Tokio drops the task before its
1908/// first poll.
1909struct OwnedCommitFinalization<D: DirectoryWriter + 'static> {
1910    directory: Arc<D>,
1911    schema: Arc<Schema>,
1912    segment_manager: Arc<crate::merge::SegmentManager<D>>,
1913    primary_key_index: Arc<parking_lot::RwLock<Option<super::primary_key::PrimaryKeyIndex>>>,
1914    primary_key_refresh_lock: Arc<tokio::sync::Mutex<()>>,
1915    prepared: PreparedSegmentsGuard<D>,
1916    finalization: Option<CommitFinalizationGuard<D>>,
1917    publication_observed: Arc<AtomicBool>,
1918    pk_reservations_retained: Arc<AtomicBool>,
1919}
1920
1921#[derive(Clone, Copy)]
1922enum PrimaryKeyRefresh {
1923    /// A commit may introduce genuinely new keys and persists the cache.
1924    Commit,
1925    /// A merge/reorder only changes segment topology; keys are already in the
1926    /// monotonic bloom and the intermediate segment IDs need not be persisted.
1927    Replacement,
1928    /// Final topology refresh: still no key hashing, but persist the new set of
1929    /// segment IDs alongside the unchanged bloom.
1930    FinalReplacement,
1931}
1932
1933async fn refresh_primary_key_snapshot<D: DirectoryWriter + 'static>(
1934    directory: &Arc<D>,
1935    schema: &Arc<Schema>,
1936    segment_manager: &Arc<crate::merge::SegmentManager<D>>,
1937    primary_key_index: &Arc<parking_lot::RwLock<Option<super::primary_key::PrimaryKeyIndex>>>,
1938    primary_key_refresh_lock: &Arc<tokio::sync::Mutex<()>>,
1939    refresh: PrimaryKeyRefresh,
1940) -> Result<()> {
1941    let _refresh_guard = primary_key_refresh_lock.lock().await;
1942    let existing_ids: std::collections::HashSet<String> = {
1943        let guard = primary_key_index.read();
1944        let Some(pk_index) = guard.as_ref() else {
1945            return Ok(());
1946        };
1947        pk_index
1948            .committed_segment_ids()
1949            .map(ToOwned::to_owned)
1950            .collect()
1951    };
1952
1953    let snapshot = segment_manager.acquire_snapshot().await;
1954    let load_futures: Vec<_> = snapshot
1955        .segment_ids()
1956        .iter()
1957        .filter(|id| !existing_ids.contains(id.as_str()))
1958        .map(|seg_id_str| {
1959            let seg_id_str = seg_id_str.clone();
1960            let dir = directory.as_ref();
1961            let schema = Arc::clone(schema);
1962            async move { load_pk_segment_data(dir, &seg_id_str, &schema).await }
1963        })
1964        .collect();
1965    let new_data = futures::future::try_join_all(load_futures).await?;
1966    let seg_ids: Vec<String> = snapshot.segment_ids().to_vec();
1967
1968    let persist_bloom = {
1969        let mut guard = primary_key_index.write();
1970        let Some(pk_index) = guard.as_mut() else {
1971            return Ok(());
1972        };
1973        match refresh {
1974            PrimaryKeyRefresh::Commit => pk_index.refresh_incremental(new_data, snapshot),
1975            PrimaryKeyRefresh::Replacement | PrimaryKeyRefresh::FinalReplacement => {
1976                pk_index.refresh_replacement(new_data, snapshot);
1977            }
1978        }
1979        matches!(
1980            refresh,
1981            PrimaryKeyRefresh::Commit | PrimaryKeyRefresh::FinalReplacement
1982        )
1983    };
1984
1985    if persist_bloom {
1986        let writer = match directory
1987            .streaming_writer(std::path::Path::new(super::primary_key::PK_BLOOM_FILE))
1988            .await
1989        {
1990            Ok(writer) => writer,
1991            Err(error) => {
1992                log::warn!(
1993                    "[primary_key] index={} failed to open bloom cache: {}",
1994                    schema.index_label(),
1995                    error
1996                );
1997                return Ok(());
1998            }
1999        };
2000        // The outer read guard prevents replacement of the PK index while the
2001        // inner state lock streams its bloom. No corpus-sized Vec is created.
2002        let guard = primary_key_index.read();
2003        if let Some(pk_index) = guard.as_ref()
2004            && let Err(error) = crate::segment::block_in_place_if_multithread(|| {
2005                write_pk_bloom_stream(pk_index, &seg_ids, writer)
2006            })
2007        {
2008            log::warn!(
2009                "[primary_key] index={} failed to persist bloom cache: {}",
2010                schema.index_label(),
2011                error
2012            );
2013        }
2014    }
2015    Ok(())
2016}
2017
2018fn write_pk_bloom_stream(
2019    pk_index: &super::primary_key::PrimaryKeyIndex,
2020    segment_ids: &[String],
2021    mut writer: Box<dyn crate::directories::StreamingWriter>,
2022) -> std::io::Result<()> {
2023    pk_index.write_bloom_cache(segment_ids, writer.as_mut())?;
2024    writer.finish()
2025}
2026
2027async fn finalize_prepared_commit<D: DirectoryWriter + 'static>(
2028    mut commit: OwnedCommitFinalization<D>,
2029) -> Result<bool> {
2030    let metadata_entries = commit.prepared.metadata_entries();
2031    let published_segment_ids = commit.prepared.vector_upgrade_segment_ids();
2032
2033    // This entire future is owned by a Tokio task. Cancelling the RPC only
2034    // drops its JoinHandle; it cannot split durable metadata publication from
2035    // PK reservations or worker resumption.
2036    commit.segment_manager.commit(&metadata_entries).await?;
2037    commit.publication_observed.store(true, Ordering::Release);
2038
2039    let mut published = commit.prepared.take_published();
2040    for segment in &mut published {
2041        segment.mark_published();
2042    }
2043    drop(published);
2044    commit
2045        .segment_manager
2046        .schedule_vector_segment_upgrades(published_segment_ids);
2047    // Publication is irreversible. From here onward every exit path, including
2048    // panic unwind, must make the writer available again while PK reservations
2049    // remain fail-closed until refresh succeeds.
2050    if let Some(finalization) = commit.finalization.as_mut() {
2051        finalization.resume_on_drop();
2052    } else {
2053        log::error!("owned commit finalization guard was already released after publication");
2054    }
2055
2056    // Metadata publication is the commit point. Cache refresh is fail-closed:
2057    // retaining the generation's uncommitted keys may cause conservative
2058    // duplicate rejections, but can never admit a duplicate or turn a durable
2059    // commit into an API error.
2060    match refresh_primary_key_snapshot(
2061        &commit.directory,
2062        &commit.schema,
2063        &commit.segment_manager,
2064        &commit.primary_key_index,
2065        &commit.primary_key_refresh_lock,
2066        PrimaryKeyRefresh::Commit,
2067    )
2068    .await
2069    {
2070        // A successful refresh folded every committed key into committed_data
2071        // and cleared the reservations — nothing retained anymore.
2072        Ok(()) => commit
2073            .pk_reservations_retained
2074            .store(false, Ordering::Release),
2075        Err(error) => {
2076            // The retained reservations are now the ONLY record of the
2077            // published segments' keys. Abort paths must not clear them
2078            // (see clear_uncommitted_pk_reservations) or duplicates would
2079            // be admitted.
2080            commit
2081                .pk_reservations_retained
2082                .store(true, Ordering::Release);
2083            log::error!(
2084                "[primary_key] committed metadata but failed to refresh dedup state; \
2085                 retaining reservations until a later successful commit: {}",
2086                error,
2087            );
2088        }
2089    }
2090
2091    // Merge scheduling is optional post-commit work and may briefly wait on
2092    // manager state. Reconcile worker availability first so it cannot extend
2093    // ingestion backpressure after metadata and PK state already agree.
2094    drop(commit.finalization.take());
2095    commit.segment_manager.maybe_merge().await;
2096    Ok(true)
2097}
2098
2099impl<'a, D: DirectoryWriter + 'static> PreparedCommit<'a, D> {
2100    /// Finalize: register segments in metadata, evaluate merge policy, resume workers.
2101    ///
2102    /// Returns `true` if new segments were committed, `false` if nothing changed.
2103    pub async fn commit(mut self) -> Result<bool> {
2104        let segments = std::mem::take(&mut *self.writer.flushed_segments.lock());
2105
2106        // Fast path: nothing to commit
2107        if segments.is_empty() {
2108            log::debug!(
2109                "[commit] index={} no segments to commit, skipping",
2110                self.writer.schema.index_label()
2111            );
2112            self.is_resolved = true;
2113            self.writer.resume_workers();
2114            return Ok(false);
2115        }
2116
2117        if !self.writer.commit_finalization.begin() {
2118            self.writer.flushed_segments.lock().extend(segments);
2119            // Keep the prepared generation paused. Letting `Drop` auto-abort
2120            // here would delete the retryable segments owned by another
2121            // finalization state transition.
2122            self.is_resolved = true;
2123            return Err(Error::CommitInProgress);
2124        }
2125
2126        let publication_observed = Arc::new(AtomicBool::new(false));
2127        let owned = OwnedCommitFinalization {
2128            directory: Arc::clone(&self.writer.directory),
2129            schema: Arc::clone(&self.writer.schema),
2130            segment_manager: Arc::clone(&self.writer.segment_manager),
2131            primary_key_index: Arc::clone(&self.writer.primary_key_index),
2132            primary_key_refresh_lock: Arc::clone(&self.writer.primary_key_refresh_lock),
2133            prepared: PreparedSegmentsGuard {
2134                segments: Some(segments),
2135                retry_slot: Arc::clone(&self.writer.flushed_segments),
2136            },
2137            finalization: Some(CommitFinalizationGuard {
2138                state: Arc::clone(&self.writer.commit_finalization),
2139                worker_state: Arc::clone(&self.writer.worker_state),
2140                doc_sender: Arc::clone(&self.writer.doc_sender),
2141                resume_workers: false,
2142            }),
2143            publication_observed: Arc::clone(&publication_observed),
2144            pk_reservations_retained: Arc::clone(&self.writer.pk_reservations_retained),
2145        };
2146
2147        // From this point the owned value, not this cancel-sensitive guard,
2148        // controls every segment and the paused worker generation. Resolve the
2149        // local guard before spawning so even a runtime-spawn panic cannot
2150        // auto-abort the retryable generation during unwind.
2151        self.is_resolved = true;
2152        let task_publication = Arc::clone(&publication_observed);
2153        let task = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2154            tokio::spawn(async move {
2155                match std::panic::AssertUnwindSafe(finalize_prepared_commit(owned))
2156                    .catch_unwind()
2157                    .await
2158                {
2159                    Ok(result) => result,
2160                    Err(_) if task_publication.load(Ordering::Acquire) => {
2161                        log::error!(
2162                            "owned commit finalizer panicked after metadata publication; \
2163                             treating the durable generation as committed"
2164                        );
2165                        Ok(true)
2166                    }
2167                    Err(_) => Err(Error::Internal(
2168                        "owned commit finalizer panicked before metadata publication".into(),
2169                    )),
2170                }
2171            })
2172        }))
2173        .map_err(|_| Error::Internal("runtime rejected owned commit finalizer".into()))?;
2174
2175        match task.await {
2176            Ok(result) => result,
2177            Err(error) if publication_observed.load(Ordering::Acquire) => {
2178                log::error!(
2179                    "owned commit finalizer terminated after metadata publication: {}; \
2180                     treating the durable generation as committed",
2181                    error,
2182                );
2183                Ok(true)
2184            }
2185            Err(error) => Err(Error::Internal(format!(
2186                "owned commit finalizer terminated unexpectedly: {error}"
2187            ))),
2188        }
2189    }
2190
2191    /// Abort: discard prepared segments, delete their files asynchronously,
2192    /// and resume workers. Lifecycle ownership is held until deletion ends.
2193    pub fn abort(mut self) {
2194        self.is_resolved = true;
2195        self.writer.flushed_segments.lock().clear();
2196        self.writer.clear_uncommitted_pk_reservations();
2197        self.writer.resume_workers();
2198    }
2199}
2200
2201impl<D: DirectoryWriter + 'static> Drop for PreparedCommit<'_, D> {
2202    fn drop(&mut self) {
2203        if !self.is_resolved {
2204            log::warn!("PreparedCommit dropped without commit/abort — auto-aborting");
2205            self.writer.flushed_segments.lock().clear();
2206            self.writer.clear_uncommitted_pk_reservations();
2207            self.writer.resume_workers();
2208        }
2209    }
2210}
2211
2212/// Load only fast-field data for a segment (lightweight alternative to full SegmentReader).
2213async fn load_pk_segment_data<D: crate::directories::Directory>(
2214    dir: &D,
2215    seg_id_str: &str,
2216    schema: &Arc<crate::dsl::Schema>,
2217) -> Result<super::primary_key::PkSegmentData> {
2218    let seg_id = crate::segment::SegmentId::from_hex(seg_id_str)
2219        .ok_or_else(|| Error::Internal(format!("Invalid segment id: {}", seg_id_str)))?;
2220    let files = crate::segment::SegmentFiles::new(seg_id.0);
2221    let fast_fields =
2222        crate::segment::reader::loader::load_fast_fields_file(dir, &files, schema).await?;
2223    Ok(super::primary_key::PkSegmentData {
2224        segment_id: seg_id_str.to_string(),
2225        fast_fields,
2226    })
2227}