Skip to main content

hermes_core/index/
mod.rs

1//! Index - multi-segment async search index
2//!
3//! The `Index` is the central concept that provides:
4//! - `Index::create()` / `Index::open()` - create or open an index
5//! - `index.writer()` - get an IndexWriter for adding documents
6//! - `index.reader()` - get an IndexReader for searching (with reload policy)
7//!
8//! The Index owns the SegmentManager which handles segment lifecycle and tracking.
9
10#[cfg(feature = "native")]
11use crate::dsl::Schema;
12#[cfg(feature = "native")]
13use crate::error::Result;
14#[cfg(feature = "sync")]
15use std::collections::HashMap;
16#[cfg(feature = "native")]
17use std::sync::Arc;
18#[cfg(feature = "native")]
19use std::sync::{OnceLock, Weak};
20
21mod searcher;
22pub use searcher::Searcher;
23
24#[cfg(feature = "native")]
25mod primary_key;
26#[cfg(feature = "native")]
27mod reader;
28#[cfg(feature = "native")]
29mod vector_builder;
30#[cfg(all(feature = "wasm", not(feature = "native")))]
31mod wasm_writer;
32#[cfg(feature = "native")]
33mod writer;
34#[cfg(feature = "native")]
35pub use primary_key::PrimaryKeyIndex;
36#[cfg(feature = "native")]
37pub use reader::IndexReader;
38#[cfg(feature = "native")]
39pub use vector_builder::{AlterVectorIndexOutcome, AlterVectorIndexState};
40#[cfg(all(feature = "wasm", not(feature = "native")))]
41pub use wasm_writer::IndexWriter as WasmIndexWriter;
42#[cfg(feature = "native")]
43pub use writer::{IndexWriter, PreparedCommit, WRITER_LOCK_FILENAME};
44
45mod metadata;
46pub use metadata::{
47    FieldVectorMeta, INDEX_META_FILENAME, IndexMetadata, SegmentMetaInfo, VectorIndexState,
48};
49
50#[cfg(feature = "native")]
51mod helpers;
52#[cfg(feature = "native")]
53pub use helpers::{
54    IndexingStats, SchemaConfig, SchemaFieldConfig, create_index_at_path, create_index_from_sdl,
55    index_documents_from_reader, index_json_document, parse_schema,
56};
57
58/// Default file name for the slice cache
59pub const SLICE_CACHE_FILENAME: &str = "index.slicecache";
60
61/// A BP pass can consume every background CPU worker and the complete
62/// per-pass memory allowance. More than two simultaneous passes only
63/// oversubscribe the same pool and multiply memory-bandwidth pressure.
64#[cfg(feature = "native")]
65pub const MAX_CONCURRENT_REORDER_PASSES: usize = 2;
66
67#[cfg(feature = "native")]
68#[derive(Clone, Copy, Debug, Eq, PartialEq)]
69pub(crate) enum ReorderPriority {
70    /// Periodic optimizer and explicit standalone reorder work. This class
71    /// must retain capacity while automatic merges continuously arrive,
72    /// otherwise fresh segments stay unordered for minutes behind giant BP
73    /// passes and query pruning recovers slowly after ingestion.
74    Optimizer,
75    /// BP performed while producing an automatic merge output.
76    AutomaticMerge,
77    Foreground,
78}
79
80/// Application-wide gate shared by optimizer, merge-time, and manual BP.
81///
82/// Besides enforcing the hard two-pass ceiling, the gate lets an explicit
83/// force merge reserve all but one slot. Background passes already running
84/// finish normally; new ones wait until the force merge releases its guard.
85#[cfg(feature = "native")]
86#[derive(Debug)]
87pub struct ReorderConcurrencyGate {
88    permits: Arc<tokio::sync::Semaphore>,
89    /// Standalone optimizer passes rewrite complete sparse blobs and can each
90    /// consume the full per-pass memory budget. Serializing this class avoids
91    /// multiplying disk traffic and retained source/output pages when a scan
92    /// discovers candidates in multiple indexes at once.
93    optimizer_permits: Arc<tokio::sync::Semaphore>,
94    /// Automatic merges may consume all but one whole-pass slot. The reserved
95    /// slot lets short optimizer passes continuously retire fresh segments.
96    /// With a one-pass configuration both classes share the only slot.
97    automatic_merge_permits: Arc<tokio::sync::Semaphore>,
98    limit: usize,
99    foreground_lock: Arc<tokio::sync::Mutex<()>>,
100    foreground_active: std::sync::atomic::AtomicBool,
101    foreground_finished: tokio::sync::Notify,
102}
103
104/// Process-wide cap on simultaneously active BMP segment scorers.
105///
106/// Each scorer performs random mmap reads. Letting every segment of every
107/// concurrent query run at once multiplies page faults without increasing
108/// useful NVMe throughput, so this gate is independent from the CPU pool.
109#[cfg(feature = "native")]
110#[derive(Debug)]
111pub(crate) struct BmpIoGate {
112    limit: usize,
113    active: parking_lot::Mutex<usize>,
114    available: parking_lot::Condvar,
115    async_available: tokio::sync::Notify,
116}
117
118#[cfg(feature = "native")]
119impl BmpIoGate {
120    fn new(limit: usize) -> Self {
121        Self {
122            limit,
123            active: parking_lot::Mutex::new(0),
124            available: parking_lot::Condvar::new(),
125            async_available: tokio::sync::Notify::new(),
126        }
127    }
128
129    #[cfg(feature = "sync")]
130    fn acquire(&self) -> BmpIoPermit<'_> {
131        let mut active = self.active.lock();
132        while *active >= self.limit {
133            self.available.wait(&mut active);
134        }
135        *active += 1;
136        BmpIoPermit { gate: self }
137    }
138
139    async fn acquire_async(&self) -> BmpIoPermit<'_> {
140        loop {
141            // Register before checking the counter, so a release between the
142            // check and await cannot be lost.
143            let notified = self.async_available.notified();
144            {
145                let mut active = self.active.lock();
146                if *active < self.limit {
147                    *active += 1;
148                    return BmpIoPermit { gate: self };
149                }
150            }
151            notified.await;
152        }
153    }
154}
155
156#[cfg(feature = "native")]
157struct BmpIoPermit<'a> {
158    gate: &'a BmpIoGate,
159}
160
161#[cfg(feature = "native")]
162impl Drop for BmpIoPermit<'_> {
163    fn drop(&mut self) {
164        let mut active = self.gate.active.lock();
165        *active -= 1;
166        self.gate.available.notify_one();
167        self.gate.async_available.notify_one();
168    }
169}
170
171#[cfg(feature = "native")]
172impl ReorderConcurrencyGate {
173    pub fn new(requested_limit: usize) -> Self {
174        let limit = requested_limit.clamp(1, MAX_CONCURRENT_REORDER_PASSES);
175        let automatic_merge_limit = limit.saturating_sub(1).max(1);
176        Self {
177            permits: Arc::new(tokio::sync::Semaphore::new(limit)),
178            optimizer_permits: Arc::new(tokio::sync::Semaphore::new(1)),
179            automatic_merge_permits: Arc::new(tokio::sync::Semaphore::new(automatic_merge_limit)),
180            limit,
181            foreground_lock: Arc::new(tokio::sync::Mutex::new(())),
182            foreground_active: std::sync::atomic::AtomicBool::new(false),
183            foreground_finished: tokio::sync::Notify::new(),
184        }
185    }
186
187    pub fn limit(&self) -> usize {
188        self.limit
189    }
190
191    pub(crate) async fn acquire(
192        self: &Arc<Self>,
193        priority: ReorderPriority,
194    ) -> std::result::Result<ReorderPermit, tokio::sync::AcquireError> {
195        match priority {
196            ReorderPriority::Optimizer => {
197                let optimizer_permit = Arc::clone(&self.optimizer_permits).acquire_owned().await?;
198                self.acquire_background(Some(optimizer_permit), None).await
199            }
200            ReorderPriority::AutomaticMerge => {
201                let merge_permit = Arc::clone(&self.automatic_merge_permits)
202                    .acquire_owned()
203                    .await?;
204                self.acquire_background(None, Some(merge_permit)).await
205            }
206            ReorderPriority::Foreground => self.acquire_foreground().await,
207        }
208    }
209
210    /// Acquire capacity for periodic optimizer or automatic merge work.
211    async fn acquire_background(
212        self: &Arc<Self>,
213        optimizer: Option<tokio::sync::OwnedSemaphorePermit>,
214        automatic_merge: Option<tokio::sync::OwnedSemaphorePermit>,
215    ) -> std::result::Result<ReorderPermit, tokio::sync::AcquireError> {
216        loop {
217            if self
218                .foreground_active
219                .load(std::sync::atomic::Ordering::Acquire)
220            {
221                let notified = self.foreground_finished.notified();
222                if self
223                    .foreground_active
224                    .load(std::sync::atomic::Ordering::Acquire)
225                {
226                    notified.await;
227                    continue;
228                }
229            }
230
231            let permit = Arc::clone(&self.permits).acquire_owned().await?;
232            if !self
233                .foreground_active
234                .load(std::sync::atomic::Ordering::Acquire)
235            {
236                return Ok(ReorderPermit {
237                    _permit: permit,
238                    _optimizer: optimizer,
239                    _automatic_merge: automatic_merge,
240                });
241            }
242            // A foreground operation started between the check and permit
243            // acquisition. Yield the slot instead of extending its queue.
244            drop(permit);
245        }
246    }
247
248    /// Acquire the one BP slot left available to a foreground force merge.
249    async fn acquire_foreground(
250        self: &Arc<Self>,
251    ) -> std::result::Result<ReorderPermit, tokio::sync::AcquireError> {
252        let permit = Arc::clone(&self.permits).acquire_owned().await?;
253        Ok(ReorderPermit {
254            _permit: permit,
255            _optimizer: None,
256            _automatic_merge: None,
257        })
258    }
259
260    /// Prioritize one explicit force merge across all indexes using this gate.
261    ///
262    /// Foreground operations are serialized to avoid two force merges each
263    /// reserving one slot and then waiting for the other. The guard is
264    /// cancellation-safe and releases reservations on drop.
265    pub(crate) async fn begin_foreground(
266        self: &Arc<Self>,
267    ) -> std::result::Result<ForegroundReorderGuard, tokio::sync::AcquireError> {
268        let exclusive = Arc::clone(&self.foreground_lock).lock_owned().await;
269        self.foreground_active
270            .store(true, std::sync::atomic::Ordering::Release);
271
272        // Construct the guard before awaiting capacity. If this future is
273        // cancelled while existing background work drains, Drop clears the
274        // active flag and releases the foreground mutex.
275        let mut guard = ForegroundReorderGuard {
276            gate: Arc::clone(self),
277            reserved: None,
278            _exclusive: exclusive,
279        };
280        if self.limit > 1 {
281            guard.reserved = Some(
282                Arc::clone(&self.permits)
283                    .acquire_many_owned((self.limit - 1) as u32)
284                    .await?,
285            );
286        }
287        Ok(guard)
288    }
289}
290
291#[cfg(feature = "native")]
292pub(crate) struct ReorderPermit {
293    _permit: tokio::sync::OwnedSemaphorePermit,
294    _optimizer: Option<tokio::sync::OwnedSemaphorePermit>,
295    _automatic_merge: Option<tokio::sync::OwnedSemaphorePermit>,
296}
297
298#[cfg(feature = "native")]
299pub(crate) struct ForegroundReorderGuard {
300    gate: Arc<ReorderConcurrencyGate>,
301    reserved: Option<tokio::sync::OwnedSemaphorePermit>,
302    _exclusive: tokio::sync::OwnedMutexGuard<()>,
303}
304
305#[cfg(feature = "native")]
306impl Drop for ForegroundReorderGuard {
307    fn drop(&mut self) {
308        // Make capacity visible before waking background waiters.
309        drop(self.reserved.take());
310        self.gate
311            .foreground_active
312            .store(false, std::sync::atomic::Ordering::Release);
313        self.gate.foreground_finished.notify_waiters();
314    }
315}
316
317/// Index configuration
318#[derive(Debug, Clone)]
319pub struct IndexConfig {
320    /// Number of threads shared by CPU-intensive search work.
321    ///
322    /// Indexes in the same process that request the same width reuse one Rayon
323    /// pool. A value of zero is invalid and is rejected by `Index::create` and
324    /// `Index::open`.
325    pub num_threads: usize,
326    /// Maximum BMP segment scorers issuing random mmap reads concurrently
327    /// across the process. CPU parallelism remains controlled by
328    /// `num_threads`; this separate cap protects the page cache and storage
329    /// queue from segment/query fan-out.
330    pub bmp_io_concurrency: usize,
331    /// Number of parallel segment builders (documents distributed round-robin)
332    pub num_indexing_threads: usize,
333    /// Width of the document-store compression pool. Concurrent segment
334    /// builders requesting the same width share one process-wide pool, so
335    /// indexing-worker fan-out does not multiply this thread count.
336    pub num_compression_threads: usize,
337    /// Block cache size for term dictionary per segment
338    pub term_cache_blocks: usize,
339    /// Process-wide byte budget for decompressed document-store blocks.
340    ///
341    /// Indexes opened with the same budget share one read-concurrent,
342    /// byte-bounded cache. This is a byte limit rather than a block count
343    /// because a stored document can legitimately make one decompressed block
344    /// tens of MiB.
345    pub store_cache_budget_bytes: usize,
346    /// Max memory (bytes) across all builders before auto-commit (global limit)
347    pub max_indexing_memory_bytes: usize,
348    /// Maximum vectors retained for one field's global ANN training sample.
349    /// The byte budget below is applied at the same time; the smaller bound
350    /// wins. Fields are sampled and trained serially.
351    pub vector_training_max_samples: usize,
352    /// Maximum raw vector bytes retained for one field's ANN training sample.
353    pub vector_training_memory_bytes: usize,
354    /// Merge policy for background segment merging
355    pub merge_policy: Box<dyn crate::merge::MergePolicy>,
356    /// Index optimization mode (adaptive, size-optimized, performance-optimized)
357    pub optimization: crate::structures::IndexOptimization,
358    /// Reload interval in milliseconds for IndexReader (how often to check for new segments)
359    pub reload_interval_ms: u64,
360    /// Maximum number of concurrent background merges per index (default: 4)
361    pub max_concurrent_merges: usize,
362    /// Application-wide background merge gate shared by clones of this
363    /// config. The per-index limit alone multiplied large merge working sets
364    /// by the number of active indexes.
365    #[cfg(feature = "native")]
366    pub background_merge_permits: Arc<tokio::sync::Semaphore>,
367    /// Wall-clock budget for merge-time BP reorder per field (only applies
368    /// when the index has `reorder_on_merge`). A truncated pass still writes
369    /// a valid, better-ordered segment; it is marked `bp_converged = false`
370    /// and the background optimizer deepens it later (warm-started).
371    /// `None` = unbudgeted (BP runs to full depth inside the merge, which can
372    /// hold a merge slot for 10-30+ minutes on 10M+ doc outputs).
373    pub merge_bp_time_budget: Option<std::time::Duration>,
374    /// Memory budget (bytes) for the BP forward index during reorder passes
375    /// (merge-time and background). When a large segment's forward index
376    /// would exceed this, the highest-df dims are dropped from BP's input
377    /// (logged loudly) — clustering quality degrades gracefully. Production
378    /// evidence: 18M-doc merges exceeded the former 2 GB default and dropped
379    /// ~10% of eligible dims; hosts with less headroom may lower this.
380    pub bp_memory_budget_bytes: usize,
381    /// Hard limit on simultaneous whole-segment BP rewrites. This is shared
382    /// by all indexes opened from clones of this config and applies to
383    /// optimizer, merge-time, and manual reorder passes. It is deliberately
384    /// separate from the Rayon pool width: one pass can already use every
385    /// background CPU thread and consume the full BP memory budget.
386    #[cfg(feature = "native")]
387    pub background_reorder_permits: Arc<ReorderConcurrencyGate>,
388    /// Optional process/application-owned Rayon pool for BP work. Supplying
389    /// one lets every index and the optimizer share the same worker threads;
390    /// `None` lazily uses one process-wide cores/2 fallback pool.
391    #[cfg(feature = "native")]
392    pub background_reorder_pool: Option<Arc<rayon::ThreadPool>>,
393}
394
395/// Search pools are shared process-wide by width. This avoids multiplying OS
396/// threads by the number of open indexes while still allowing applications to
397/// deliberately isolate indexes that need different CPU budgets.
398#[cfg(feature = "sync")]
399static SEARCH_CPU_POOLS: OnceLock<parking_lot::Mutex<HashMap<usize, Weak<rayon::ThreadPool>>>> =
400    OnceLock::new();
401
402/// Store caches are shared process-wide by configured byte budget, just like
403/// search CPU pools are shared by width. `IndexRegistry` clones one config for
404/// every index, but standalone callers with the same policy also converge on
405/// the same bounded cache.
406#[cfg(feature = "native")]
407static STORE_CACHE_POOLS: OnceLock<
408    parking_lot::Mutex<std::collections::HashMap<usize, Weak<crate::segment::SharedStoreCache>>>,
409> = OnceLock::new();
410
411#[cfg(feature = "native")]
412static BMP_IO_GATES: OnceLock<
413    parking_lot::Mutex<std::collections::HashMap<usize, Weak<BmpIoGate>>>,
414> = OnceLock::new();
415
416#[cfg(feature = "native")]
417pub(crate) fn shared_bmp_io_gate(limit: usize) -> Arc<BmpIoGate> {
418    let mut gates = BMP_IO_GATES
419        .get_or_init(|| parking_lot::Mutex::new(std::collections::HashMap::new()))
420        .lock();
421    if let Some(gate) = gates.get(&limit).and_then(Weak::upgrade) {
422        return gate;
423    }
424    let gate = Arc::new(BmpIoGate::new(limit));
425    gates.retain(|_, gate| gate.strong_count() > 0);
426    gates.insert(limit, Arc::downgrade(&gate));
427    log::info!("[bmp] process-wide random-I/O concurrency={limit}");
428    gate
429}
430
431#[cfg(feature = "native")]
432pub(crate) fn shared_store_cache(budget_bytes: usize) -> Arc<crate::segment::SharedStoreCache> {
433    let mut caches = STORE_CACHE_POOLS
434        .get_or_init(|| parking_lot::Mutex::new(std::collections::HashMap::new()))
435        .lock();
436    if let Some(cache) = caches.get(&budget_bytes).and_then(Weak::upgrade) {
437        return cache;
438    }
439    let cache = Arc::new(crate::segment::SharedStoreCache::new(budget_bytes));
440    caches.retain(|_, cache| cache.strong_count() > 0);
441    caches.insert(budget_bytes, Arc::downgrade(&cache));
442    log::info!(
443        "[store_cache] process-wide budget={}",
444        crate::format_bytes(budget_bytes as u64)
445    );
446    cache
447}
448
449#[cfg(feature = "sync")]
450fn shared_search_pool(num_threads: usize) -> Result<Arc<rayon::ThreadPool>> {
451    if num_threads == 0 {
452        return Err(crate::Error::Internal(
453            "IndexConfig.num_threads must be greater than zero".into(),
454        ));
455    }
456
457    let mut pools = SEARCH_CPU_POOLS
458        .get_or_init(|| parking_lot::Mutex::new(HashMap::new()))
459        .lock();
460    if let Some(pool) = pools.get(&num_threads).and_then(Weak::upgrade) {
461        return Ok(pool);
462    }
463
464    // Build while holding the registry lock. Index construction is cold-path
465    // work, and serialization here prevents two concurrent opens from creating
466    // duplicate pools for the same width.
467    let pool = Arc::new(
468        rayon::ThreadPoolBuilder::new()
469            .num_threads(num_threads)
470            .thread_name(move |idx| format!("hermes-search-{}-{}", num_threads, idx))
471            .build()
472            .map_err(|error| {
473                crate::Error::Internal(format!(
474                    "failed to create {num_threads}-thread search pool: {error}"
475                ))
476            })?,
477    );
478    pools.retain(|_, pool| pool.strong_count() > 0);
479    pools.insert(num_threads, Arc::downgrade(&pool));
480    log::info!("[search] process-wide CPU pool: {} thread(s)", num_threads);
481    Ok(pool)
482}
483
484impl Default for IndexConfig {
485    fn default() -> Self {
486        #[cfg(feature = "native")]
487        let compression_threads = crate::default_compression_threads();
488        #[cfg(not(feature = "native"))]
489        let compression_threads = 1;
490
491        #[cfg(feature = "native")]
492        let search_threads = crate::default_search_threads();
493        #[cfg(not(feature = "native"))]
494        let search_threads = 1;
495
496        Self {
497            num_threads: search_threads,
498            bmp_io_concurrency: 4,
499            num_indexing_threads: 1, // Increase to 2+ for production to avoid stalls during segment build
500            num_compression_threads: compression_threads,
501            term_cache_blocks: 256,
502            // Stored bodies can be much larger than the writer's nominal
503            // 16-KiB block target. Keep this process-wide and byte bounded so
504            // segment fan-out cannot multiply it into tens of GiB.
505            #[cfg(target_pointer_width = "64")]
506            store_cache_budget_bytes: 2 * 1024 * 1024 * 1024,
507            #[cfg(not(target_pointer_width = "64"))]
508            store_cache_budget_bytes: 32 * 1024 * 1024,
509            max_indexing_memory_bytes: 256 * 1024 * 1024, // 256 MB default
510            vector_training_max_samples: 10_000_000,
511            #[cfg(target_pointer_width = "64")]
512            vector_training_memory_bytes: 4 * 1024 * 1024 * 1024,
513            #[cfg(not(target_pointer_width = "64"))]
514            vector_training_memory_bytes: usize::MAX,
515            // large_scale: wide fan-in + budget/scored selection. Safe for
516            // small indexes too (tier floors only shape *when* segments
517            // merge); merge-time BP is wall-clock budgeted, so giant merges
518            // cannot hold slots indefinitely.
519            merge_policy: Box::new(crate::merge::TieredMergePolicy::large_scale()),
520            optimization: crate::structures::IndexOptimization::default(),
521            reload_interval_ms: 1000, // 1 second default
522            max_concurrent_merges: 4,
523            #[cfg(feature = "native")]
524            background_merge_permits: Arc::new(tokio::sync::Semaphore::new(4)),
525            merge_bp_time_budget: Some(std::time::Duration::from_secs(600)),
526            // 24 GB — mirrors segment::reorder::DEFAULT_MEMORY_BUDGET (that
527            // module is native-only; IndexConfig also compiles for wasm).
528            // A cap, not an allocation: usage is proportional to the segment
529            // being reordered (~4 B/posting + ~32 B/doc). Sized from prod
530            // evidence: a 58M-doc/5B-posting pass estimated 20.1 GB, which
531            // 8/16 GB budgets trimmed by dropping highest-df dims.
532            // 24 GB overflows 32-bit usize (wasm32) — reorder never runs
533            // there, so any large value works; use usize::MAX.
534            #[cfg(target_pointer_width = "64")]
535            bp_memory_budget_bytes: 24 * 1024 * 1024 * 1024,
536            #[cfg(not(target_pointer_width = "64"))]
537            bp_memory_budget_bytes: usize::MAX,
538            #[cfg(feature = "native")]
539            background_reorder_permits: Arc::new(ReorderConcurrencyGate::new(2)),
540            #[cfg(feature = "native")]
541            background_reorder_pool: None,
542        }
543    }
544}
545
546/// Build the segment-lifecycle owner from the corresponding index policy.
547///
548/// `Index` and `IndexWriter` both support create/open entry points. Routing
549/// their shared configuration through this helper prevents a new
550/// `SegmentManager` option from being wired into only some constructors.
551#[cfg(feature = "native")]
552fn segment_manager_from_config<D: crate::directories::DirectoryWriter + 'static>(
553    directory: &Arc<D>,
554    schema: &Arc<Schema>,
555    metadata: IndexMetadata,
556    config: &IndexConfig,
557) -> Arc<crate::merge::SegmentManager<D>> {
558    Arc::new(crate::merge::SegmentManager::new(
559        Arc::clone(directory),
560        Arc::clone(schema),
561        metadata,
562        config.merge_policy.clone_box(),
563        config.term_cache_blocks,
564        config.max_concurrent_merges,
565        Arc::clone(&config.background_merge_permits),
566        config.merge_bp_time_budget,
567        config.bp_memory_budget_bytes,
568        Arc::clone(&config.background_reorder_permits),
569        config.background_reorder_pool.clone(),
570    ))
571}
572
573/// Multi-segment async Index
574///
575/// The central concept for search. Owns segment lifecycle and provides:
576/// - `Index::create()` / `Index::open()` - create or open an index
577/// - `index.writer()` - get an IndexWriter for adding documents
578/// - `index.reader()` - get an IndexReader for searching with reload policy
579///
580/// All segment management is delegated to SegmentManager.
581#[cfg(feature = "native")]
582pub struct Index<D: crate::directories::DirectoryWriter + 'static> {
583    directory: Arc<D>,
584    config: IndexConfig,
585    /// Cache and CPU policy used by every searcher reload.
586    search_resources: searcher::SearcherResources,
587    /// Segment manager - owns segments, tracker, metadata, and trained structures
588    segment_manager: Arc<crate::merge::SegmentManager<D>>,
589    /// Cached reader (created lazily, reused across calls)
590    cached_reader: tokio::sync::OnceCell<IndexReader<D>>,
591}
592
593#[cfg(feature = "native")]
594impl<D: crate::directories::DirectoryWriter + 'static> Index<D> {
595    /// Create a new index in the directory
596    pub async fn create(directory: D, schema: Schema, config: IndexConfig) -> Result<Self> {
597        let search_resources = searcher::SearcherResources::new(
598            config.term_cache_blocks,
599            config.store_cache_budget_bytes,
600            config.num_threads,
601            config.bmp_io_concurrency,
602        )?;
603        let directory = Arc::new(directory);
604        let schema = Arc::new(schema);
605        // Directory-layer metrics (cold writes, lazy reads) carry the index label
606        directory.set_index_label(schema.index_label());
607
608        // Refuse to clobber an existing index: persisting a fresh empty
609        // metadata.json would orphan every committed segment, and the next
610        // writer open's orphan sweep would permanently delete them.
611        if directory
612            .exists(std::path::Path::new(INDEX_META_FILENAME))
613            .await?
614        {
615            return Err(crate::Error::Internal(format!(
616                "refusing to create index: {} already exists in this directory; \
617                 use Index::open to open the existing index, or delete the \
618                 directory first if you really want to start over",
619                INDEX_META_FILENAME
620            )));
621        }
622
623        let metadata = IndexMetadata::new((*schema).clone());
624
625        let segment_manager = segment_manager_from_config(&directory, &schema, metadata, &config);
626
627        // Save initial metadata
628        segment_manager.update_metadata(|_| {}).await?;
629
630        Ok(Self {
631            directory,
632            config,
633            search_resources,
634            segment_manager,
635            cached_reader: tokio::sync::OnceCell::new(),
636        })
637    }
638
639    /// Open an existing index from a directory
640    pub async fn open(directory: D, config: IndexConfig) -> Result<Self> {
641        let search_resources = searcher::SearcherResources::new(
642            config.term_cache_blocks,
643            config.store_cache_budget_bytes,
644            config.num_threads,
645            config.bmp_io_concurrency,
646        )?;
647        let directory = Arc::new(directory);
648
649        // Load metadata (includes schema)
650        let metadata = IndexMetadata::load(directory.as_ref()).await?;
651        let schema = Arc::new(metadata.schema.clone());
652        // Directory-layer metrics (cold writes, lazy reads) carry the index label
653        directory.set_index_label(schema.index_label());
654
655        let segment_manager = segment_manager_from_config(&directory, &schema, metadata, &config);
656
657        // Load trained structures into SegmentManager's ArcSwap
658        segment_manager.try_load_and_publish_trained().await?;
659
660        Ok(Self {
661            directory,
662            config,
663            search_resources,
664            segment_manager,
665            cached_reader: tokio::sync::OnceCell::new(),
666        })
667    }
668
669    /// Get the schema
670    pub fn schema(&self) -> Arc<Schema> {
671        self.schema_arc()
672    }
673
674    /// Clone the schema handle from the currently published generation.
675    pub fn schema_arc(&self) -> Arc<Schema> {
676        self.segment_manager.published_generation().schema.clone()
677    }
678
679    /// Get a reference to the underlying directory
680    pub fn directory(&self) -> &D {
681        &self.directory
682    }
683
684    /// Get the segment manager
685    pub fn segment_manager(&self) -> &Arc<crate::merge::SegmentManager<D>> {
686        &self.segment_manager
687    }
688
689    /// Get an IndexReader for searching (with reload policy)
690    ///
691    /// The reader is cached and reused across calls. The reader's internal
692    /// searcher will reload segments based on its reload interval (configurable via IndexConfig).
693    pub async fn reader(&self) -> Result<&IndexReader<D>> {
694        self.cached_reader
695            .get_or_try_init(|| async {
696                IndexReader::from_segment_manager_with_resources(
697                    self.schema_arc(),
698                    Arc::clone(&self.segment_manager),
699                    self.config.reload_interval_ms,
700                    self.search_resources.clone(),
701                )
702                .await
703            })
704            .await
705    }
706
707    /// Get the config
708    pub fn config(&self) -> &IndexConfig {
709        &self.config
710    }
711
712    /// Get segment readers for query execution (convenience method)
713    pub async fn segment_readers(&self) -> Result<Vec<Arc<crate::segment::SegmentReader>>> {
714        let reader = self.reader().await?;
715        let searcher = reader.searcher().await?;
716        Ok(searcher.segment_readers().to_vec())
717    }
718
719    /// Total number of documents across all segments
720    pub async fn num_docs(&self) -> Result<u32> {
721        let reader = self.reader().await?;
722        let searcher = reader.searcher().await?;
723        Ok(searcher.num_docs())
724    }
725
726    /// Get default fields for search
727    pub fn default_fields(&self) -> Vec<crate::Field> {
728        let schema = self.schema_arc();
729        if !schema.default_fields().is_empty() {
730            schema.default_fields().to_vec()
731        } else {
732            schema
733                .fields()
734                .filter(|(_, entry)| {
735                    entry.indexed && entry.field_type == crate::dsl::FieldType::Text
736                })
737                .map(|(field, _)| field)
738                .collect()
739        }
740    }
741
742    /// Get tokenizer registry
743    pub fn tokenizers(&self) -> Arc<crate::tokenizer::TokenizerRegistry> {
744        Arc::new(crate::tokenizer::TokenizerRegistry::default())
745    }
746
747    /// Create a query parser for this index
748    pub fn query_parser(&self) -> crate::dsl::QueryLanguageParser {
749        let default_fields = self.default_fields();
750        let tokenizers = self.tokenizers();
751        let schema = self.schema_arc();
752
753        let query_routers = schema.query_routers();
754        if !query_routers.is_empty()
755            && let Ok(router) = crate::dsl::QueryFieldRouter::from_rules(query_routers)
756        {
757            return crate::dsl::QueryLanguageParser::with_router(
758                Arc::clone(&schema),
759                default_fields,
760                tokenizers,
761                router,
762            );
763        }
764
765        crate::dsl::QueryLanguageParser::new(schema, default_fields, tokenizers)
766    }
767
768    /// Parse and search using a query string
769    pub async fn query(
770        &self,
771        query_str: &str,
772        limit: usize,
773    ) -> Result<crate::query::SearchResponse> {
774        self.query_offset(query_str, limit, 0).await
775    }
776
777    /// Query with offset for pagination
778    pub async fn query_offset(
779        &self,
780        query_str: &str,
781        limit: usize,
782        offset: usize,
783    ) -> Result<crate::query::SearchResponse> {
784        let parser = self.query_parser();
785        let query = parser
786            .parse(query_str)
787            .map_err(crate::error::Error::Query)?;
788        self.search_offset(query.as_ref(), limit, offset).await
789    }
790
791    /// Search and return results
792    pub async fn search(
793        &self,
794        query: &dyn crate::query::Query,
795        limit: usize,
796    ) -> Result<crate::query::SearchResponse> {
797        self.search_offset(query, limit, 0).await
798    }
799
800    /// Search with offset for pagination
801    pub async fn search_offset(
802        &self,
803        query: &dyn crate::query::Query,
804        limit: usize,
805        offset: usize,
806    ) -> Result<crate::query::SearchResponse> {
807        let reader = self.reader().await?;
808        let searcher = reader.searcher().await?;
809
810        #[cfg(feature = "sync")]
811        let (results, total_seen) = {
812            // Sync search: rayon handles segment parallelism internally.
813            // On multi-threaded tokio, use block_in_place to yield the worker;
814            // on single-threaded (tests), call directly.
815            let runtime_flavor = tokio::runtime::Handle::current().runtime_flavor();
816            if runtime_flavor == tokio::runtime::RuntimeFlavor::MultiThread {
817                tokio::task::block_in_place(|| {
818                    searcher.search_with_offset_and_count_sync(query, limit, offset)
819                })?
820            } else {
821                searcher.search_with_offset_and_count_sync(query, limit, offset)?
822            }
823        };
824
825        #[cfg(not(feature = "sync"))]
826        let (results, total_seen) = {
827            searcher
828                .search_with_offset_and_count(query, limit, offset)
829                .await?
830        };
831
832        let total_hits = total_seen;
833        let hits: Vec<crate::query::SearchHit> = results
834            .into_iter()
835            .map(|result| crate::query::SearchHit {
836                address: crate::query::DocAddress::new(result.segment_id, result.doc_id),
837                score: result.score,
838                matched_fields: result.extract_ordinals(),
839            })
840            .collect();
841
842        Ok(crate::query::SearchResponse { hits, total_hits })
843    }
844
845    /// Get a document by its unique address
846    pub async fn get_document(
847        &self,
848        address: &crate::query::DocAddress,
849    ) -> Result<Option<crate::dsl::Document>> {
850        let reader = self.reader().await?;
851        let searcher = reader.searcher().await?;
852        searcher.get_document(address).await
853    }
854
855    /// Get posting lists for a term across all segments
856    pub async fn get_postings(
857        &self,
858        field: crate::Field,
859        term: &[u8],
860    ) -> Result<
861        Vec<(
862            Arc<crate::segment::SegmentReader>,
863            crate::structures::BlockPostingList,
864        )>,
865    > {
866        let segments = self.segment_readers().await?;
867        let mut results = Vec::new();
868
869        for segment in segments {
870            if let Some(postings) = segment.get_postings(field, term).await? {
871                results.push((segment, postings));
872            }
873        }
874
875        Ok(results)
876    }
877}
878
879/// Native-only methods for Index
880#[cfg(feature = "native")]
881impl<D: crate::directories::DirectoryWriter + 'static> Index<D> {
882    /// Get an IndexWriter for adding documents
883    pub fn writer(&self) -> writer::IndexWriter<D> {
884        writer::IndexWriter::from_index(self)
885    }
886}
887
888#[cfg(test)]
889mod tests;
890
891// (tests moved to index/tests/ module)