Skip to main content

itzma_core/
namespace.rs

1//! The [`Namespace`] handle: the public entry point for reading and writing.
2//!
3//! A namespace is an isolated collection of documents that share one schema.
4//! On object storage it is just a key prefix, `<id>/`, holding a manifest and a
5//! WAL (see [`manifest`] and [`wal`]). A handle itself holds nothing but the
6//! schema and a sequence hint, so any number of handles, in any number of
7//! processes, can point at the same namespace — the exception is
8//! [`Namespace::with_cache`], which opts the query path into reusing a
9//! caller-supplied [`CacheStore`](crate::CacheStore) across calls; the
10//! manifest is never cached, so this changes nothing about write-then-query
11//! visibility.
12
13use std::sync::Arc;
14use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
15use std::time::Duration;
16
17use object_store::ObjectStore;
18
19use crate::budget::{DEFAULT_READ_BUDGET, ReadBudget};
20use crate::columns::DocColumns;
21use crate::compaction::{self, Compaction, CompactionOptions};
22use crate::decoded::{DecodedCache, DecodedRef};
23use crate::document;
24use crate::document::{Document, Schema, SparseVector, WalOp};
25use crate::error::{ItzmaError, Result};
26use crate::fetch::FetchPolicy;
27use crate::filter::{self, FilterOptions, FilterPage};
28use crate::gc::{self, GcOptions, GcReport};
29use crate::index;
30use crate::indexer::{self, IndexOptions, IndexReport, MIN_SEGMENT_FORMAT, Outcome};
31use crate::lease::{LeaseOptions, MaintenanceLease};
32use crate::maintain::{self, MaintenanceOptions, MaintenanceReport};
33use crate::manifest::{self, Manifest};
34use crate::predicate::Predicate;
35use crate::query::{self, Builtin, QueryOptions};
36use crate::recover::{self, RecoverReport};
37use crate::schema_object;
38use crate::search::Hit;
39use crate::segment;
40use crate::sparse_index;
41use crate::sparse_indexer::{self, IndexSparseOptions, IndexSparseReport};
42use crate::sparse_query::{self, SparseQueryOptions};
43use crate::stream::{self, StreamError, StreamOptions, StreamReport};
44use crate::view;
45use crate::wal::{self, WriteKey};
46use crate::wal_codec;
47
48/// A handle to one namespace on an object store.
49///
50/// Get one with [`Namespace::create`] (new namespace) or [`Namespace::open`]
51/// (existing). Handles are cheap: they hold the store, the id, the schema and
52/// a sequence hint. Methods take `&self`, so a handle can be shared across
53/// tasks, and separate handles on the same namespace are safe to use
54/// concurrently. Writers are sequenced by the object store, not by the
55/// handle.
56///
57/// # Consistency
58///
59/// - A write is durable once `upsert` or `delete` returns.
60/// - A `query` that starts after a write returned sees that write, even from a
61///   different handle or process (read-your-writes).
62/// - Readers see a consistent prefix of the log: all of a batch or none of it,
63///   and never a later batch without an earlier one.
64/// - Two writers racing get distinct seqs and are ordered by seq. If both
65///   touch the same id, the higher seq wins.
66///
67/// # Examples
68///
69/// ```
70/// # #[tokio::main]
71/// # async fn main() -> itzma_core::Result<()> {
72/// use std::sync::Arc;
73///
74/// use itzma_core::{Document, Metric, Namespace, Schema};
75/// use object_store::memory::InMemory;
76///
77/// let store = Arc::new(InMemory::new());
78/// let ns = Namespace::create(store, "docs", Schema::new(2, Metric::L2)).await?;
79///
80/// ns.upsert(vec![
81///     Document { id: "near".into(), vector: vec![1.0, 0.0], attrs: None, sparse: None },
82///     Document { id: "far".into(), vector: vec![9.0, 9.0], attrs: None, sparse: None },
83/// ])
84/// .await?;
85///
86/// let hits = ns.query(&[0.0, 0.0], 1).await?;
87/// assert_eq!(hits[0].id, "near");
88/// # Ok(())
89/// # }
90/// ```
91pub struct Namespace {
92    store: Arc<dyn ObjectStore>,
93    /// The store the query path reads segment, index, and WAL-tail bytes
94    /// through. Defaults to the same value as `store` — set it with
95    /// [`with_cache`](Self::with_cache) to let repeated queries reuse a
96    /// [`CacheStore`](crate::CacheStore). The manifest is never read through
97    /// this field; every manifest load always uses `store`, so write-then-
98    /// query visibility is unaffected either way (see `with_cache`'s doc).
99    query_store: Arc<dyn ObjectStore>,
100    id: String,
101    schema: Schema,
102    /// Where the next append starts probing. A stale hint costs one extra
103    /// listing on collision, never correctness.
104    next_seq: AtomicU64,
105    /// The namespace's `wal_format` as this handle last saw it. Only keyed
106    /// writes look at it, and it only ever goes up.
107    wal_level: AtomicU32,
108    /// The most bytes one query or one compaction run may read.
109    read_budget: u64,
110    /// How ranged reads turn "these pieces of this object" into requests.
111    /// Defaults to [`FetchPolicy::object_store`]; set it with
112    /// [`with_fetch_policy`](Self::with_fetch_policy).
113    fetch_policy: FetchPolicy,
114    /// Parsed structures kept between queries, set with
115    /// [`with_decoded_cache`](Self::with_decoded_cache).
116    decoded_cache: Option<Arc<DecodedCache>>,
117    /// The last manifest and folded WAL tail the query path read.
118    views: view::Views,
119}
120
121/// Ids become key prefixes, so they are restricted to characters that cannot
122/// introduce a `/` or otherwise collide with another namespace's keys.
123pub(crate) fn validate_id(id: &str) -> Result<()> {
124    let ok = (1..=64).contains(&id.len())
125        && id
126            .bytes()
127            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-');
128    if ok {
129        Ok(())
130    } else {
131        Err(ItzmaError::InvalidNamespaceId(id.to_string()))
132    }
133}
134
135/// How many times `query` reads against a manifest before it gives up, when
136/// the segments it needs keep vanishing because the manifest keeps moving.
137const MAX_READ_ATTEMPTS: u32 = 3;
138
139impl Namespace {
140    /// Create a new, empty namespace and return a handle to it.
141    ///
142    /// Writes the manifest with put-if-absent. If several callers race to
143    /// create the same id, exactly one succeeds. The schema is fixed from this
144    /// point on, and is written a second time to `schema.json`, an object that
145    /// is never changed, so losing the manifest does not lose it.
146    ///
147    /// The manifest is written first and decides whether the namespace exists.
148    /// If the call fails after that, before the schema object is written, the
149    /// namespace exists: `open` it, which writes the object. A create that
150    /// finds a schema object for the id holding a different schema is refused
151    /// with [`ItzmaError::NamespaceExists`] and writes nothing.
152    ///
153    /// Creation is explicit, unlike the implicit create-on-first-write,
154    /// because the dimension and metric have to be declared up front.
155    ///
156    /// # Errors
157    ///
158    /// - [`ItzmaError::InvalidNamespaceId`] unless `id` matches
159    ///   `[a-z0-9_-]{1,64}`.
160    /// - [`ItzmaError::InvalidSchema`] if `schema.dim == 0`, or the attribute
161    ///   schema has more than 256 fields, a field name outside
162    ///   `[A-Za-z0-9_]{1,64}`, or is free-form.
163    /// - [`ItzmaError::NamespaceExists`] if the id is taken.
164    /// - [`ItzmaError::UnsupportedFormat`] or [`ItzmaError::Serde`] if the id
165    ///   has a schema object this build cannot read.
166    /// - [`ItzmaError::Storage`] for any backend failure.
167    pub async fn create(store: Arc<dyn ObjectStore>, id: &str, schema: Schema) -> Result<Self> {
168        validate_id(id)?;
169        if schema.dim == 0 {
170            return Err(ItzmaError::InvalidSchema("dim must be at least 1"));
171        }
172        schema.attrs.check_declaration()?;
173        if let Some(existing) = schema_object::read(&*store, id).await? {
174            if existing != schema {
175                return Err(ItzmaError::NamespaceExists(id.to_string()));
176            }
177        }
178        let manifest = Manifest::new(schema.clone());
179        manifest::create(&*store, id, &manifest).await?;
180        schema_object::write(&*store, id, &schema).await?;
181        Ok(Self::from_manifest(store, id, &manifest))
182    }
183
184    /// Open an existing namespace and return a handle to it.
185    ///
186    /// Reads the manifest to learn the schema and where the WAL resumes. The
187    /// handle keeps no other state from this read: each later `query` loads
188    /// the manifest again.
189    ///
190    /// Then it reads `schema.json` and checks it holds the manifest's schema.
191    /// If the object is missing, `open` writes it from the manifest, which
192    /// finishes a create that stopped between its two writes and covers a
193    /// namespace made before the object existed. That makes `open`
194    /// a write, once, for such a namespace, so it needs write access then.
195    ///
196    /// # Errors
197    ///
198    /// - [`ItzmaError::InvalidNamespaceId`] for a malformed id.
199    /// - [`ItzmaError::NamespaceNotFound`] if no such namespace exists.
200    /// - [`ItzmaError::CorruptManifest`] if `schema.json` holds a different
201    ///   schema from the manifest. Nothing is changed.
202    /// - [`ItzmaError::UnsupportedFormat`] if the manifest was written by an
203    ///   incompatible version.
204    /// - [`ItzmaError::WalFormatTooNew`] if a newer build raised the
205    ///   namespace's WAL format past what this build reads. Every
206    ///   method that loads the manifest returns it too.
207    /// - [`ItzmaError::Serde`] / [`ItzmaError::Storage`] on a corrupt object
208    ///   or backend failure.
209    pub async fn open(store: Arc<dyn ObjectStore>, id: &str) -> Result<Self> {
210        validate_id(id)?;
211        let (manifest, _version) = manifest::load(&*store, id).await?;
212        // A namespace with no attribute schema comes from a format this
213        // build does not read.
214        if manifest.schema.attrs.is_free_form() {
215            return Err(ItzmaError::UnsupportedFormat { version: 1 });
216        }
217        schema_object::ensure(&*store, id, &manifest.schema).await?;
218        Ok(Self::from_manifest(store, id, &manifest))
219    }
220
221    /// Write a new manifest for a namespace that has lost its own, and return a
222    /// handle to it.
223    ///
224    /// The schema comes from `schema.json`. The live segments are a chain from
225    /// seq 1 built from the segment names, taking at each step the segment that
226    /// reaches furthest and decodes, and the WAL past its end is left as the
227    /// tail. A segment that is missing or does not decode only shortens the
228    /// chain: the WAL from there on is read instead, and the next
229    /// [`compact`](Self::compact) rebuilds the segment. The new manifest carries
230    /// the newest WAL format level this build writes, and as segment level the
231    /// newest version any segment object of the namespace was written in, or
232    /// [`segment::DEFAULT_FORMAT`] if that is higher (a raise with no segment
233    /// written since leaves no trace, so it comes back at the default). A build
234    /// that reads less refuses the namespace. Recovering asserts that every
235    /// build that touches it reads what this one does. Writers are not held up,
236    /// since they never read the manifest.
237    ///
238    /// Only the manifest is written, and only with put-if-absent. WAL objects,
239    /// segments and `schema.json` are read and left as they are, and a segment
240    /// the chain does not use is not deleted (that is [`gc`](Self::gc)'s job).
241    /// Segments are checked by decoding them one at a time, under the default
242    /// read budget, so a run reads every live segment once.
243    ///
244    /// # Errors
245    ///
246    /// - [`ItzmaError::InvalidNamespaceId`] for a malformed id.
247    /// - [`ItzmaError::ManifestExists`] if the namespace has a manifest, or
248    ///   another recovery wrote one first. Nothing is changed.
249    /// - [`ItzmaError::Unrecoverable`] if `schema.json` is missing, or a range
250    ///   of seqs has no readable copy (no segment that decodes covers it, and
251    ///   its WAL objects are missing or fenced). The error names what to restore
252    ///   from a replica, a versioned bucket or a backup, and a rerun can
253    ///   succeed once it is back. Nothing is written.
254    /// - [`ItzmaError::UnsupportedFormat`] if a segment is of a format this
255    ///   build does not read. That is a newer build's data, not damage, so the
256    ///   run stops and does not skip it.
257    /// - [`ItzmaError::ReadBudgetExceeded`] if a single segment is over the
258    ///   default read budget.
259    /// - [`ItzmaError::Storage`] for any backend failure.
260    pub async fn recover(store: Arc<dyn ObjectStore>, id: &str) -> Result<(Self, RecoverReport)> {
261        validate_id(id)?;
262        let (manifest, report) = recover::rebuild(&*store, id).await?;
263        Ok((Self::from_manifest(store, id, &manifest), report))
264    }
265
266    /// Everything `upsert` and `upsert_keyed` check about one document before
267    /// any storage call: the id, the vector, the sparse vector and the
268    /// attributes.
269    fn validate_doc(&self, doc: &Document) -> Result<()> {
270        doc.validate_id()?;
271        self.schema.validate(&doc.vector)?;
272        doc.validate_sparse()?;
273        self.schema.attrs.validate(doc.attrs.as_ref())
274    }
275
276    /// Build a handle from a loaded manifest, seeding the sequence hint just
277    /// past the folded prefix.
278    fn from_manifest(store: Arc<dyn ObjectStore>, id: &str, manifest: &Manifest) -> Self {
279        Self {
280            query_store: store.clone(),
281            store,
282            id: id.to_string(),
283            schema: manifest.schema.clone(),
284            next_seq: AtomicU64::new(manifest.wal_folded_through + 1),
285            wal_level: AtomicU32::new(manifest.wal_format),
286            read_budget: DEFAULT_READ_BUDGET,
287            fetch_policy: FetchPolicy::object_store(),
288            decoded_cache: None,
289            views: view::Views::new(),
290        }
291    }
292
293    /// Set the most bytes one [`query`](Self::query) or one
294    /// [`compact`](Self::compact) run may read, and return the handle. The
295    /// default is [`DEFAULT_READ_BUDGET`], 1 GiB. The budget belongs to this
296    /// handle: it is not stored, and another handle on the same namespace
297    /// keeps its own.
298    ///
299    /// Every segment and WAL object a run reads is counted before its body
300    /// is, and a run that would go over stops with
301    /// [`ItzmaError::ReadBudgetExceeded`] and writes nothing. The count is
302    /// stored bytes (a compressed WAL object counts as its uncompressed
303    /// size), a proxy for memory that does not see the extra weight of
304    /// attributes once decoded. Since a query or a merge holds every live
305    /// document in memory, this is also the largest namespace either can
306    /// handle.
307    pub fn with_read_budget(mut self, bytes: u64) -> Self {
308        self.read_budget = bytes;
309        self
310    }
311
312    /// Let the query path (`query`, `query_with`) read segment, index, and WAL-
313    /// tail bytes through `cached` instead of the store this handle was opened
314    /// with, and return the handle. Pass a [`CacheStore`](crate::CacheStore)
315    /// wrapping the same backing store to let repeated queries reuse warm
316    /// RAM/NVMe bytes instead of re-fetching from the object store every time.
317    ///
318    /// The manifest is never affected: every query still loads it fresh from
319    /// the store this handle was opened with, on every call, so a write is
320    /// visible to the very next query exactly as it is without this method —
321    /// `cached` only ever serves segment, index, and WAL-tail reads. Compaction,
322    /// GC, index builds, and `inspect` are also unaffected; they always use the
323    /// store this handle was opened with, never `cached`. The manifest is
324    /// excluded so a write is always visible to the next query.
325    ///
326    /// # Examples
327    ///
328    /// ```
329    /// use std::sync::Arc;
330    /// use itzma_core::{CacheOptions, CacheStore, Namespace, Schema, Metric};
331    /// use object_store::memory::InMemory;
332    ///
333    /// # #[tokio::main]
334    /// # async fn main() {
335    /// let store: Arc<dyn object_store::ObjectStore> = Arc::new(InMemory::new());
336    /// let ns = Namespace::create(store.clone(), "docs", Schema::new(4, Metric::L2))
337    ///     .await
338    ///     .unwrap();
339    /// let cache = CacheStore::new(store, CacheOptions::default()).unwrap();
340    /// let ns = ns.with_cache(Arc::new(cache));
341    /// # let _ = ns;
342    /// # }
343    /// ```
344    pub fn with_cache(mut self, cached: Arc<dyn ObjectStore>) -> Self {
345        self.query_store = cached;
346        self
347    }
348
349    /// Keep what the query path parses (index heads and partitions, segment
350    /// directories, Bloom filters, id, attribute and tombstone blocks, sparse
351    /// term directories, and whole segments the flat path decodes) in `cache`
352    /// between queries, and return the handle.
353    ///
354    /// A structure found in the cache is neither fetched nor charged to the
355    /// read budget, so a warm query can read nothing from the store but the
356    /// manifest and the WAL listing (the handle keeps its folded tail itself).
357    /// One cache can be
358    /// shared by many handles, on one store or several. Compaction, GC, index
359    /// builds, `inspect` and `recover` never use it.
360    ///
361    /// # Examples
362    ///
363    /// ```
364    /// use std::sync::Arc;
365    /// use itzma_core::{DecodedCache, DecodedCacheOptions, Metric, Namespace, Schema};
366    /// use object_store::memory::InMemory;
367    ///
368    /// # #[tokio::main]
369    /// # async fn main() -> itzma_core::Result<()> {
370    /// let cache = DecodedCache::new(DecodedCacheOptions::default());
371    /// let ns = Namespace::create(Arc::new(InMemory::new()), "docs", Schema::new(4, Metric::L2))
372    ///     .await?
373    ///     .with_decoded_cache(cache);
374    /// let hits = ns.query(&[0.0; 4], 10).await?;
375    /// assert!(hits.is_empty());
376    /// # Ok(())
377    /// # }
378    /// ```
379    #[must_use]
380    pub fn with_decoded_cache(mut self, cache: Arc<DecodedCache>) -> Self {
381        self.decoded_cache = Some(cache);
382        self
383    }
384
385    /// Let queries on this handle use a manifest and a WAL tail up to
386    /// `max_age` old, and return the handle.
387    ///
388    /// Within `max_age` of the last refresh a query sends no request for
389    /// either; with a [`DecodedCache`] warm too, it can run with no store call
390    /// at all. The first query after `max_age` refreshes both (one manifest
391    /// GET, then a listing of the WAL past what the handle already folded),
392    /// and queries that arrive meanwhile wait for that one refresh.
393    ///
394    /// What a query sees: every write this handle made, whatever `max_age` is
395    /// (upserts, deletes and keyed writes alike), and every write another
396    /// writer made before the last refresh, which is at most `max_age` before
397    /// the query began. Without this call a handle is strict: every query
398    /// loads the manifest and lists the WAL, and sees every write that landed
399    /// before it did. A `max_age` of zero is the same as strict. A very small
400    /// one makes queries take turns on the refresh, which is slower than
401    /// strict, so pick one well above a manifest round trip.
402    ///
403    /// Keep `max_age` far below the `min_age` of any [`gc`](Self::gc) run on
404    /// this namespace (24 hours by default). A longer bound is still correct,
405    /// since a query that meets a segment `gc` removed reloads the manifest
406    /// and tries again, but it pays for that miss. The handle cannot check
407    /// this, since `min_age` belongs to each `gc` call.
408    ///
409    /// Only [`query`](Self::query), [`query_with`](Self::query_with),
410    /// [`query_sparse`](Self::query_sparse) and [`filter`](Self::filter) use
411    /// the cached view. Writes, [`compact`](Self::compact), the index builds,
412    /// `gc` and [`maintain`](Self::maintain) always load the manifest.
413    ///
414    /// # Examples
415    ///
416    /// ```
417    /// use std::sync::Arc;
418    /// use std::time::Duration;
419    /// use itzma_core::{Document, Metric, Namespace, Schema};
420    /// use object_store::memory::InMemory;
421    ///
422    /// # #[tokio::main]
423    /// # async fn main() -> itzma_core::Result<()> {
424    /// let ns = Namespace::create(Arc::new(InMemory::new()), "docs", Schema::new(1, Metric::L2))
425    ///     .await?
426    ///     .with_staleness(Duration::from_secs(1));
427    /// ns.upsert(vec![Document { id: "a".into(), vector: vec![0.0], attrs: None, sparse: None }])
428    ///     .await?;
429    /// // The handle's own write is visible at once.
430    /// assert_eq!(ns.query(&[0.0], 1).await?[0].id, "a");
431    /// # Ok(())
432    /// # }
433    /// ```
434    #[must_use]
435    pub fn with_staleness(mut self, max_age: Duration) -> Self {
436        self.views.set_staleness(Some(max_age));
437        self
438    }
439
440    /// The decoded cache bound to the query store, if the handle has one.
441    fn decoded(&self) -> Option<DecodedRef> {
442        self.decoded_cache
443            .as_ref()
444            .map(|cache| cache.handle(&self.query_store))
445    }
446
447    /// Set how ranged reads turn wanted byte ranges into requests,
448    /// and return the handle. The default, [`FetchPolicy::object_store`], is
449    /// tuned for S3 and similar stores; pass [`FetchPolicy::local`] for an
450    /// `InMemory` or `LocalFileSystem` store, where a request costs about as
451    /// much as the bytes it reads.
452    pub fn with_fetch_policy(mut self, policy: FetchPolicy) -> Self {
453        self.fetch_policy = policy;
454        self
455    }
456
457    /// The namespace id this handle was created or opened with.
458    pub fn id(&self) -> &str {
459        &self.id
460    }
461
462    /// The schema this namespace was created with. Read from the manifest at
463    /// `create` or `open` time; it never changes afterwards.
464    pub fn schema(&self) -> &Schema {
465        &self.schema
466    }
467
468    /// Insert documents, replacing any that already have the same id.
469    ///
470    /// The whole slice is committed as one WAL entry, so it becomes visible
471    /// atomically: readers see all of it or none of it. Every vector is
472    /// checked against the schema first, and one bad document rejects the
473    /// entire call with nothing written.
474    ///
475    /// If the same id appears twice in `docs`, the later one wins. Returns the
476    /// WAL sequence number the batch was committed at.
477    ///
478    /// # Errors
479    ///
480    /// - [`ItzmaError::EmptyBatch`] if `docs` is empty.
481    /// - [`ItzmaError::InvalidId`] if a document's `id` is empty or longer than
482    ///   [`document::MAX_ID_BYTES`].
483    /// - [`ItzmaError::DimensionMismatch`] / [`ItzmaError::InvalidVector`] for
484    ///   a bad vector (see [`Schema::validate`]).
485    /// - [`ItzmaError::UnknownAttr`], [`ItzmaError::AttrTypeMismatch`] and
486    ///   [`ItzmaError::InvalidAttrs`] if a document's `attrs` break the
487    ///   namespace's attribute schema. One bad document rejects the
488    ///   whole batch. A namespace made before typed attributes checks nothing.
489    /// - [`ItzmaError::WriteContention`] if 32 sequence numbers in a row were
490    ///   taken by other writers. Nothing was written; retrying is safe.
491    /// - [`ItzmaError::Storage`] for any backend failure.
492    ///
493    /// # Examples
494    ///
495    /// ```
496    /// # #[tokio::main]
497    /// # async fn main() -> itzma_core::Result<()> {
498    /// use std::sync::Arc;
499    ///
500    /// use itzma_core::{Document, Metric, Namespace, Schema};
501    /// use object_store::memory::InMemory;
502    ///
503    /// let store = Arc::new(InMemory::new());
504    /// let ns = Namespace::create(store, "docs", Schema::new(1, Metric::L2)).await?;
505    ///
506    /// let doc = |v: f32| Document { id: "a".into(), vector: vec![v], attrs: None, sparse: None };
507    /// assert_eq!(ns.upsert(vec![doc(1.0)]).await?, 1);
508    /// assert_eq!(ns.upsert(vec![doc(5.0)]).await?, 2); // replaces "a"
509    ///
510    /// let hits = ns.query(&[5.0], 10).await?;
511    /// assert_eq!(hits.len(), 1);
512    /// assert_eq!(hits[0].distance, 0.0);
513    /// # Ok(())
514    /// # }
515    /// ```
516    pub async fn upsert(&self, docs: Vec<Document>) -> Result<u64> {
517        for doc in &docs {
518            self.validate_doc(doc)?;
519        }
520        self.append(docs.into_iter().map(WalOp::Upsert).collect())
521            .await
522    }
523
524    /// Remove documents by id.
525    ///
526    /// Like `upsert`, the whole call is one atomic WAL entry. Ids that do not
527    /// exist are ignored, so deleting is idempotent. Returns the WAL sequence
528    /// number the batch was committed at.
529    ///
530    /// The documents are hidden from queries immediately, but their bytes are
531    /// not erased. They stay in the WAL until [`gc`](Self::gc) fences its
532    /// objects, which is off unless asked for, and in any segment that
533    /// holds them until that segment is superseded and collected.
534    ///
535    /// # Errors
536    ///
537    /// - [`ItzmaError::EmptyBatch`] if `ids` is empty.
538    /// - [`ItzmaError::InvalidId`] if an id is empty or longer than
539    ///   [`document::MAX_ID_BYTES`].
540    /// - [`ItzmaError::WriteContention`] / [`ItzmaError::Storage`] as for
541    ///   [`upsert`](Self::upsert).
542    ///
543    /// # Examples
544    ///
545    /// ```
546    /// # #[tokio::main]
547    /// # async fn main() -> itzma_core::Result<()> {
548    /// use std::sync::Arc;
549    ///
550    /// use itzma_core::{Document, Metric, Namespace, Schema};
551    /// use object_store::memory::InMemory;
552    ///
553    /// let store = Arc::new(InMemory::new());
554    /// let ns = Namespace::create(store, "docs", Schema::new(1, Metric::L2)).await?;
555    /// ns.upsert(vec![Document { id: "a".into(), vector: vec![1.0], attrs: None, sparse: None }]).await?;
556    ///
557    /// ns.delete(vec!["a".into()]).await?;
558    /// assert!(ns.query(&[1.0], 10).await?.is_empty());
559    /// # Ok(())
560    /// # }
561    /// ```
562    pub async fn delete(&self, ids: Vec<String>) -> Result<u64> {
563        for id in &ids {
564            document::validate_id(id)?;
565        }
566        self.append(ids.into_iter().map(WalOp::Delete).collect())
567            .await
568    }
569
570    /// Insert documents under an idempotency key, so that retrying the call
571    /// does not write the batch twice.
572    ///
573    /// Behaves like [`upsert`](Self::upsert), and the batch is committed as one
574    /// WAL entry. What is different is the key, in `write`: a first attempt is
575    /// [`WriteKey::new`], and a call that may repeat an earlier one is
576    /// [`WriteKey::retry`], which looks for the key in the WAL objects from a
577    /// seq the caller names before it writes anything. A found key returns the
578    /// seq of the original and writes nothing. The rules, and what they do not
579    /// cover, are on [`WriteKey`].
580    ///
581    /// The namespace must be at WAL level 3, which every namespace created by
582    /// this build is. One created by an older build has to be raised first with
583    /// [`upgrade_wal_format`](Self::upgrade_wal_format). A handle reads the
584    /// manifest for the level once, and only if it does not already know the
585    /// level is high enough. Unkeyed writes never read it.
586    ///
587    /// # Errors
588    ///
589    /// As for [`upsert`](Self::upsert), plus:
590    ///
591    /// - [`ItzmaError::InvalidKey`] unless the key is 1 to 128 bytes.
592    /// - [`ItzmaError::WalFormatTooOld`] if the namespace is below level 3.
593    /// - [`ItzmaError::KeyConflict`] if the key was used for a batch of a
594    ///   different size.
595    /// - [`ItzmaError::WalFormatTooNew`] if the manifest read for the level
596    ///   shows a format this build cannot read.
597    ///
598    /// # Examples
599    ///
600    /// ```
601    /// # #[tokio::main]
602    /// # async fn main() -> itzma_core::Result<()> {
603    /// use std::sync::Arc;
604    ///
605    /// use itzma_core::{Document, Metric, Namespace, Schema, WriteKey};
606    /// use object_store::memory::InMemory;
607    ///
608    /// let store = Arc::new(InMemory::new());
609    /// let ns = Namespace::create(store, "docs", Schema::new(1, Metric::L2)).await?;
610    /// let batch = || vec![Document { id: "a".into(), vector: vec![1.0], attrs: None, sparse: None }];
611    ///
612    /// let seq = ns.upsert_keyed(&WriteKey::new("load-7/batch-1"), batch()).await?;
613    ///
614    /// // The acknowledgement never arrived, so the caller tries again from
615    /// // the last seq it saw committed (here nothing, so 1).
616    /// let retry = WriteKey::retry("load-7/batch-1", 1);
617    /// assert_eq!(ns.upsert_keyed(&retry, batch()).await?, seq);
618    /// # Ok(())
619    /// # }
620    /// ```
621    pub async fn upsert_keyed(&self, write: &WriteKey, docs: Vec<Document>) -> Result<u64> {
622        for doc in &docs {
623            self.validate_doc(doc)?;
624        }
625        self.append_keyed(write, docs.into_iter().map(WalOp::Upsert).collect())
626            .await
627    }
628
629    /// Insert a columnar batch, one row a document: the same WAL
630    /// object, byte for byte, that [`upsert`](Self::upsert) writes for the
631    /// same documents, without building them. The batch is checked with
632    /// [`DocColumns::validate`] first, and one bad row rejects the whole call
633    /// with nothing written.
634    ///
635    /// # Errors
636    ///
637    /// The errors of [`upsert`](Self::upsert). An input with one defect gets
638    /// exactly `upsert`'s error; with several, the first one reported can
639    /// differ (see [`DocColumns::validate`]). A batch with a sparse column
640    /// needs WAL level 5 ([`ItzmaError::WalFormatTooOld`]).
641    ///
642    /// # Examples
643    ///
644    /// ```
645    /// # #[tokio::main]
646    /// # async fn main() -> itzma_core::Result<()> {
647    /// use std::sync::Arc;
648    ///
649    /// use itzma_core::{DocColumns, Metric, Namespace, Schema};
650    /// use object_store::memory::InMemory;
651    ///
652    /// let ns = Namespace::create(Arc::new(InMemory::new()), "docs", Schema::new(2, Metric::L2)).await?;
653    /// // Ids "a" and "b", vectors [1, 0] and [0, 1].
654    /// let batch = DocColumns::new(b"ab".to_vec(), vec![0, 1, 2], vec![1.0, 0.0, 0.0, 1.0], 2)?;
655    /// assert_eq!(ns.upsert_columns(&batch).await?, 1);
656    /// assert_eq!(ns.query(&[1.0, 0.0], 1).await?[0].id, "a");
657    /// # Ok(())
658    /// # }
659    /// ```
660    pub async fn upsert_columns(&self, cols: &DocColumns) -> Result<u64> {
661        cols.validate(&self.schema)?;
662        let bytes = wal_codec::encode_columns(cols, wal::MAX_BODY_BYTES)?;
663        self.append_bytes(bytes, cols.has_sparse()).await
664    }
665
666    /// Load a stream of columnar batches in bounded memory.
667    ///
668    /// The input is cut into chunks of about
669    /// [`StreamOptions::target_bytes`] of encoded body, wherever its own
670    /// batches happen to end, so the same rows always make the same chunks.
671    /// Each chunk is checked as [`upsert_columns`](Self::upsert_columns)
672    /// checks a batch and encoded on the compute pool while the previous one
673    /// is being written; exactly one PUT is in flight, so the chunks land in
674    /// order and a crash can never leave a hole between them. At most
675    /// [`StreamOptions::depth`] encoded chunks wait for the writer, so memory
676    /// is about `(depth + 2) * target_bytes` however long the input is.
677    ///
678    /// Each chunk is its own WAL object, made visible on its own: a reader
679    /// can see the first chunks of a load before the rest.
680    ///
681    /// The batches of one stream must have the same columns: the same `dim`,
682    /// the same attribute names, each attribute column of the same kind (an
683    /// all-null [`AttrColumn::Null`](crate::AttrColumn::Null) fits any kind; a number column cannot
684    /// switch between integers and floats from one batch to the next, which
685    /// `upsert` of documents would allow), and all a sparse column or none.
686    /// Otherwise the stream stops with [`ItzmaError::InvalidColumns`].
687    ///
688    /// # Errors
689    ///
690    /// A [`StreamError`]: the error, and in
691    /// [`landed`](StreamError::landed) what was written before it, whole and
692    /// in order. Chunks the encoder had already queued when a later chunk
693    /// failed its check are written first. The errors are those of
694    /// `upsert_columns`, plus an error from the input itself,
695    /// [`ItzmaError::EmptyBatch`] for an input with no rows, and
696    /// [`ItzmaError::InvalidConfig`] for bad options (before the input is
697    /// polled). To resume an unkeyed load, feed the input again from row
698    /// [`landed.rows`](StreamReport::rows).
699    ///
700    /// # Examples
701    ///
702    /// ```
703    /// # #[tokio::main]
704    /// # async fn main() -> itzma_core::Result<()> {
705    /// use std::sync::Arc;
706    ///
707    /// use itzma_core::{DocColumns, Metric, Namespace, Schema, StreamOptions};
708    /// use object_store::memory::InMemory;
709    ///
710    /// let ns = Namespace::create(Arc::new(InMemory::new()), "docs", Schema::new(1, Metric::L2)).await?;
711    /// let batches = vec![
712    ///     DocColumns::new(b"a".to_vec(), vec![0, 1], vec![1.0], 1),
713    ///     DocColumns::new(b"b".to_vec(), vec![0, 1], vec![2.0], 1),
714    /// ];
715    /// let report = ns
716    ///     .upsert_stream(futures::stream::iter(batches), &StreamOptions::default())
717    ///     .await
718    ///     .map_err(|e| e.error)?;
719    /// assert_eq!((report.rows, report.objects), (2, 1));
720    /// # Ok(())
721    /// # }
722    /// ```
723    pub async fn upsert_stream<S>(
724        &self,
725        input: S,
726        options: &StreamOptions,
727    ) -> std::result::Result<StreamReport, StreamError>
728    where
729        S: futures::Stream<Item = Result<DocColumns>> + Send,
730    {
731        stream::run(self, input, options, None).await
732    }
733
734    /// [`upsert_stream`](Self::upsert_stream) under an idempotency key: chunk
735    /// `n` is written under `<key>#<n>`, so the key can be at most 107 bytes
736    /// (room for `#` and any chunk number). Those chunk keys share the key
737    /// space of [`upsert_keyed`](Self::upsert_keyed): do not give a plain
738    /// keyed write a key of the form `<stream key>#<number>`, or the two can
739    /// be taken for each other.
740    /// A retry with [`WriteKey::retry`] and the same input and
741    /// `target_bytes` cuts the same chunks, finds the ones that landed by
742    /// their keys and writes only the rest, however the input is
743    /// batched the second time. Its `search_from` must be at or before the
744    /// first chunk the first attempt may have written: the failed attempt's
745    /// [`landed.first_seq`](StreamReport::first_seq), or, when that is `None`
746    /// (nothing was acknowledged, though the first put may have landed), the
747    /// namespace's next seq before the first attempt. The search reads the
748    /// headers from there once; each later chunk is looked for only past the
749    /// one before it.
750    ///
751    /// # Errors
752    ///
753    /// Those of `upsert_stream` and [`upsert_keyed`](Self::upsert_keyed);
754    /// [`ItzmaError::InvalidKey`] for a key over 107 bytes, before the input
755    /// is polled.
756    pub async fn upsert_stream_keyed<S>(
757        &self,
758        write: &WriteKey,
759        input: S,
760        options: &StreamOptions,
761    ) -> std::result::Result<StreamReport, StreamError>
762    where
763        S: futures::Stream<Item = Result<DocColumns>> + Send,
764    {
765        stream::run(self, input, options, Some(write)).await
766    }
767
768    /// [`upsert_columns`](Self::upsert_columns) under an idempotency key, with
769    /// the rules of [`upsert_keyed`](Self::upsert_keyed).
770    ///
771    /// # Errors
772    ///
773    /// Those of `upsert_columns` and `upsert_keyed`.
774    pub async fn upsert_columns_keyed(&self, write: &WriteKey, cols: &DocColumns) -> Result<u64> {
775        write.validate()?;
776        cols.validate(&self.schema)?;
777        let object = wal_codec::encode_columns_keyed(cols, wal::MAX_BODY_BYTES, &write.key)?;
778        self.append_bytes_keyed(write, object, cols.has_sparse())
779            .await
780    }
781
782    /// Remove documents by id under an idempotency key. The keyed form of
783    /// [`delete`](Self::delete), with the rules and errors of
784    /// [`upsert_keyed`](Self::upsert_keyed).
785    ///
786    /// A delete is where a replay does the most harm, since it can undo a
787    /// newer upsert of the same id. With a key, the retry finds the delete
788    /// already in the log and leaves it alone.
789    pub async fn delete_keyed(&self, write: &WriteKey, ids: Vec<String>) -> Result<u64> {
790        for id in &ids {
791            document::validate_id(id)?;
792        }
793        self.append_keyed(write, ids.into_iter().map(WalOp::Delete).collect())
794            .await
795    }
796
797    /// Raise the namespace's WAL format to at least `level`, so that writes
798    /// which need it are allowed.
799    ///
800    /// One compare-and-swap on the manifest. It only goes up: a level at or
801    /// below the current one changes nothing and writes nothing, and two
802    /// callers racing both succeed. Level 3 is what [`upsert_keyed`](Self::upsert_keyed)
803    /// needs, level 4 is what [`gc`](Self::gc) needs to fence WAL objects, and
804    /// level 5 is what a sparse-carrying [`upsert`](Self::upsert) or
805    /// [`upsert_keyed`](Self::upsert_keyed) needs (WAL object
806    /// versions 4 and 5). A namespace created by this build starts at 5.
807    ///
808    /// **Raise it only once every build that reads or compacts this namespace
809    /// reads the new format** (version 3 for level 3, fences for level 4, and
810    /// versions 4/5's sparse column for level 5). From the next manifest read, a build that does not is
811    /// refused with [`ItzmaError::WalFormatTooNew`] (the gate), which is what
812    /// keeps it away, but it cannot be undone: there is no way to lower the
813    /// level. Writers that already hold a handle keep writing what they wrote,
814    /// which stays readable.
815    ///
816    /// Needs conditional update on the store, which `LocalFileSystem` does not
817    /// implement.
818    ///
819    /// # Errors
820    ///
821    /// - [`ItzmaError::WalFormatTooNew`] if `level` is above what this build
822    ///   reads ([`wal::FORMAT_VERSION`]).
823    /// - [`ItzmaError::ManifestContention`] after 32 lost rounds.
824    /// - Anything [`manifest::load`] can return.
825    pub async fn upgrade_wal_format(&self, level: u32) -> Result<()> {
826        if level > wal::FORMAT_VERSION {
827            return Err(ItzmaError::WalFormatTooNew {
828                found: level,
829                supported: wal::FORMAT_VERSION,
830            });
831        }
832        manifest::update_if(&*self.store, &self.id, |m| {
833            if m.wal_format >= level {
834                return false;
835            }
836            m.wal_format = level;
837            true
838        })
839        .await?;
840        // Raised by this call or already there: either way the level is at
841        // least this.
842        self.wal_level.fetch_max(level, Ordering::Relaxed);
843        Ok(())
844    }
845
846    /// Raise the namespace's segment format to at least `level`, so that
847    /// compaction writes segments in that version.
848    ///
849    /// One compare-and-swap on the manifest. It only goes up: a level at or
850    /// below the current one changes nothing and writes nothing, and two
851    /// callers racing both succeed. Level 2 is the block-addressable layout.
852    /// Level 3 stores a typed namespace's attributes as columns with
853    /// a zone map per block, and a free-form namespace's as level 2 does. A
854    /// namespace created by this build starts at
855    /// [`segment::DEFAULT_FORMAT`], and one made before the levels existed is
856    /// at 1 and stays there until this is called.
857    ///
858    /// Nothing is rewritten. The segments already there keep their version, and
859    /// each later fold or merge writes the new one, so a namespace can hold
860    /// both. **Raise it only once every build that reads or compacts this
861    /// namespace reads the new version.** From the next manifest read, a build
862    /// that does not is refused with [`ItzmaError::SegmentFormatTooNew`] (the
863    /// gate), but the raise cannot be undone: there is no way to lower the
864    /// level.
865    ///
866    /// A compaction that stopped after writing a segment at the old level and
867    /// is rerun after the raise builds different bytes for the same key, and
868    /// [`compact`](Self::compact) reports [`ItzmaError::CorruptSegment`] rather
869    /// than publish over it. Nothing is published. Delete that
870    /// orphan segment object (it is listed as an orphan by
871    /// [`inspect::report`](crate::inspect::report)) and rerun.
872    ///
873    /// Needs conditional update on the store, which `LocalFileSystem` does not
874    /// implement.
875    ///
876    /// # Errors
877    ///
878    /// - [`ItzmaError::SegmentFormatTooNew`] if `level` is above what this
879    ///   build reads ([`segment::FORMAT_VERSION`]).
880    /// - [`ItzmaError::ManifestContention`] after 32 lost rounds.
881    /// - Anything [`manifest::load`] can return.
882    pub async fn upgrade_segment_format(&self, level: u32) -> Result<()> {
883        if level > segment::FORMAT_VERSION {
884            return Err(ItzmaError::SegmentFormatTooNew {
885                found: level,
886                supported: segment::FORMAT_VERSION,
887            });
888        }
889        manifest::update_if(&*self.store, &self.id, |m| {
890            if m.segment_format >= level {
891                return false;
892            }
893            m.segment_format = level;
894            true
895        })
896        .await?;
897        Ok(())
898    }
899
900    /// Fold the un-compacted WAL into a segment, or merge segments when there
901    /// are too many, and publish the result.
902    ///
903    /// What happens depends on the state:
904    ///
905    /// - WAL tail empty and at most `max_segments` segments: nothing to do.
906    /// - Adding one more segment would exceed `max_segments`: every segment
907    ///   and the tail are merged into one base segment.
908    /// - Otherwise: the tail becomes a new segment beside the existing ones.
909    ///
910    /// The segment is written with put-if-absent, then listed in the manifest
911    /// by one compare-and-swap. Writers are never blocked and never see the
912    /// manifest change. Queries running during a compaction are unaffected.
913    /// Any process may call this, as often as it likes, concurrently: racing
914    /// compactors build the same object, one wins the swap, and the rest get
915    /// [`Compaction::Superseded`]. A run that crashes before publishing leaves
916    /// an orphan segment that the next run verifies against the bytes it
917    /// builds and reuses. An orphan that differs makes `compact` fail with
918    /// [`ItzmaError::CorruptSegment`] and publish nothing.
919    ///
920    /// The swap also drops the manifest's index entries (see
921    /// [`index`](Self::index)) of any segment the run retires, so a merge clears
922    /// them, a fold keeps them, and the segment written starts without one.
923    ///
924    /// Compaction never deletes anything: not the WAL objects that were
925    /// folded, not superseded segments, not orphans. Superseded segments and
926    /// dead orphans are removed by a separate call to [`gc`](Self::gc), and
927    /// folded WAL objects are kept until that call fences them. If a
928    /// segment the run needs disappears, or a WAL object it reads has become a
929    /// fence, because a compaction and a garbage collection ran after it
930    /// loaded the manifest, the run reloads the manifest and returns
931    /// [`Compaction::Superseded`].
932    ///
933    /// Publishing needs conditional update on the store, which
934    /// `LocalFileSystem` does not implement. There a run fails at the publish
935    /// step with a storage error after writing its segment.
936    ///
937    /// # Errors
938    ///
939    /// - [`ItzmaError::ManifestContention`] after 32 lost publish rounds.
940    /// - [`ItzmaError::CorruptManifest`] / [`ItzmaError::CorruptSegment`] if
941    ///   the manifest or a segment it lists is damaged.
942    /// - [`ItzmaError::CorruptSegment`] also when an object already sits at
943    ///   the new segment's key with different bytes.
944    /// - [`ItzmaError::WalGap`] if the log has a hole.
945    /// - [`ItzmaError::InvalidConfig`] when a merge is due and
946    ///   `options.max_segment_bytes` is above the handle's read budget, before
947    ///   any segment is read or anything written. A fold does not need the
948    ///   check, so a handle with a small query budget still folds.
949    /// - [`ItzmaError::ReadBudgetExceeded`] if the tail, or one merge group,
950    ///   is more than the read budget: the tail and each group get a budget
951    ///   of their own, so a namespace bigger than the budget still
952    ///   merges. Nothing is published; groups written before the refused one
953    ///   stay as orphans that a rerun reuses or `gc` collects.
954    /// - [`ItzmaError::DimensionMismatch`] if a WAL document's vector does not
955    ///   match the schema (only possible for a hand-edited WAL).
956    /// - [`ItzmaError::UnsupportedFormat`], [`ItzmaError::Serde`] or
957    ///   [`ItzmaError::Storage`] for unreadable objects or backend failures.
958    ///
959    /// # Examples
960    ///
961    /// ```
962    /// # #[tokio::main]
963    /// # async fn main() -> itzma_core::Result<()> {
964    /// use std::sync::Arc;
965    ///
966    /// use itzma_core::{Compaction, CompactionOptions, Document, Metric, Namespace, Schema};
967    /// use object_store::memory::InMemory;
968    ///
969    /// let store = Arc::new(InMemory::new());
970    /// let ns = Namespace::create(store, "docs", Schema::new(1, Metric::L2)).await?;
971    /// ns.upsert(vec![Document { id: "a".into(), vector: vec![1.0], attrs: None, sparse: None }]).await?;
972    ///
973    /// let options = CompactionOptions::default();
974    /// let outcome = ns.compact(&options).await?;
975    /// assert!(matches!(outcome, Compaction::Published { folded_through: 1, .. }));
976    /// assert_eq!(ns.query(&[1.0], 1).await?[0].id, "a");
977    ///
978    /// // Nothing new has been written, so there is nothing to fold.
979    /// assert_eq!(ns.compact(&options).await?, Compaction::Nothing);
980    /// # Ok(())
981    /// # }
982    /// ```
983    pub async fn compact(&self, options: &CompactionOptions) -> Result<Compaction> {
984        let manifest = self.load_manifest().await?;
985        let outcome = compaction::run(
986            &*self.store,
987            &self.id,
988            self.schema.clone(),
989            manifest.clone(),
990            options,
991            self.read_budget,
992            &self.fetch_policy,
993        )
994        .await;
995        match outcome {
996            // A segment this run needed is gone, or a WAL object it read is now
997            // a fence. If the manifest has moved, a merge or a fold and a
998            // garbage collection ran after this run planned, which is the same
999            // as losing any other race.
1000            Err(err) if is_stale_read(&err) => {
1001                self.reload_if_moved(&manifest, err).await?;
1002                Ok(Compaction::Superseded)
1003            }
1004            other => other,
1005        }
1006    }
1007
1008    /// Build and publish an index for each live segment that has none.
1009    /// An index lets a query search a segment without reading it whole
1010    /// (see [`query`](Self::query)); a segment with no index is read whole, as it
1011    /// always was, so a namespace never has to be indexed.
1012    ///
1013    /// Segments are taken one at a time. For each one that is version 2 and has
1014    /// at least [`IndexOptions::min_rows`] documents, the data object is read
1015    /// (under a read budget of its own, so a namespace is not limited by the sum
1016    /// of its segments, but one segment must fit in it), the index object
1017    /// `segments/<id>/index-<generation>.bin` is written
1018    /// with put-if-absent, and one
1019    /// manifest compare-and-swap lists it. Until that swap the object is an
1020    /// orphan that changes nothing, and a run that stops there leaves one that the
1021    /// next run checks and reuses. Any valid index of the segment is accepted, so
1022    /// two indexers racing on the same segment both succeed and one is counted as
1023    /// [`already_indexed`](IndexReport::already_indexed).
1024    ///
1025    /// A fold or merge (`compact`) never indexes: it leaves the segment it writes
1026    /// without one, and a merge also drops the entries of the segments it retires.
1027    /// Call `index` again afterwards. [`IndexOptions::rebuild`] writes generation
1028    /// `n + 1` for a segment that already has generation `n`, and the old object
1029    /// is left for [`gc`](Self::gc), which removes index objects that no manifest
1030    /// names once they are `min_age` old.
1031    ///
1032    /// Needs conditional update on the store, like `compact`.
1033    ///
1034    /// # Errors
1035    ///
1036    /// - [`ItzmaError::SegmentFormatTooOld`] if the namespace is below segment
1037    ///   format 2. Nothing is touched.
1038    /// - [`ItzmaError::ReadBudgetExceeded`] if one segment is bigger than the
1039    ///   read budget.
1040    /// - [`ItzmaError::CorruptSegment`] if a segment is damaged. A segment a
1041    ///   compaction and a garbage collection removed after this call loaded the
1042    ///   manifest is counted as [`superseded`](IndexReport::superseded) instead.
1043    /// - [`ItzmaError::CorruptIndex`] if an object already sits at the new
1044    ///   index's key and does not fit the segment. Delete it and rerun.
1045    /// - [`ItzmaError::ManifestContention`] after 32 lost publish rounds.
1046    /// - Anything [`manifest::load`] can return.
1047    ///
1048    /// A failure part way leaves the segments before it indexed. Call again to
1049    /// finish.
1050    ///
1051    /// # Examples
1052    ///
1053    /// ```
1054    /// # #[tokio::main]
1055    /// # async fn main() -> itzma_core::Result<()> {
1056    /// use std::sync::Arc;
1057    ///
1058    /// use itzma_core::{CompactionOptions, Document, IndexOptions, Metric, Namespace, Schema};
1059    /// use object_store::memory::InMemory;
1060    ///
1061    /// let store = Arc::new(InMemory::new());
1062    /// let ns = Namespace::create(store, "docs", Schema::new(2, Metric::L2)).await?;
1063    /// ns.upsert(vec![Document { id: "a".into(), vector: vec![1.0, 0.0], attrs: None, sparse: None }]).await?;
1064    /// ns.compact(&CompactionOptions::default()).await?;
1065    ///
1066    /// // One document is under the default minimum, so nothing is indexed.
1067    /// let report = ns.index(&IndexOptions::default()).await?;
1068    /// assert_eq!((report.indexed, report.skipped_small), (0, 1));
1069    ///
1070    /// // A minimum of zero indexes it.
1071    /// let report = ns.index(&IndexOptions::default().min_rows(0)).await?;
1072    /// assert_eq!(report.indexed, 1);
1073    /// # Ok(())
1074    /// # }
1075    /// ```
1076    pub async fn index(&self, options: &IndexOptions) -> Result<IndexReport> {
1077        options.validate()?;
1078        let manifest = self.load_manifest().await?;
1079        if manifest.segment_format < MIN_SEGMENT_FORMAT {
1080            return Err(ItzmaError::SegmentFormatTooOld {
1081                have: manifest.segment_format,
1082                need: MIN_SEGMENT_FORMAT,
1083            });
1084        }
1085        let mut report = IndexReport::default();
1086        for id in &manifest.live_segments {
1087            let outcome = indexer::index_segment(
1088                &*self.store,
1089                &self.id,
1090                self.schema.dim,
1091                self.schema.metric,
1092                id,
1093                manifest.indexes.get(id),
1094                options,
1095                self.read_budget,
1096                &self.fetch_policy,
1097            )
1098            .await;
1099            let outcome = match outcome {
1100                // The segment is gone because a merge and a collection ran
1101                // after the manifest was loaded. If the manifest has not
1102                // moved, it is really missing and that is the error.
1103                Err(err) if is_stale_read(&err) => {
1104                    self.reload_if_moved(&manifest, err).await?;
1105                    Outcome::Superseded
1106                }
1107                other => other?,
1108            };
1109            report.record(outcome);
1110        }
1111        Ok(report)
1112    }
1113
1114    /// Build and publish a sparse inverted index for each live segment that
1115    /// has a `sparse.bin` and no sparse index yet. A segment with
1116    /// no sparse documents has no `sparse.bin` and is skipped — there is
1117    /// nothing to index. A segment with a sparse sidecar and no index is
1118    /// still searchable by [`query_sparse`](Self::query_sparse), read whole;
1119    /// the index only lets a query fetch the postings of its own terms
1120    /// instead.
1121    ///
1122    /// Mirrors [`index`](Self::index)'s shape: one segment at a time, an
1123    /// object written with put-if-absent, one manifest compare-and-swap.
1124    /// [`IndexSparseOptions::rebuild`] writes generation `n + 1` for a
1125    /// segment that already has generation `n`; the old object is left for
1126    /// [`gc`](Self::gc), which removes sparse index objects no manifest names
1127    /// once they are `min_age` old. A fold or merge (`compact`) never builds
1128    /// one, and a merge drops the entries of the segments it retires.
1129    ///
1130    /// Needs conditional update on the store, like `compact`.
1131    ///
1132    /// # Errors
1133    ///
1134    /// - [`ItzmaError::CorruptSegment`] if a `sparse.bin` is damaged. A
1135    ///   segment a compaction and a garbage collection removed after this
1136    ///   call loaded the manifest is counted as
1137    ///   [`superseded`](IndexSparseReport::superseded) instead.
1138    /// - [`ItzmaError::CorruptSparseIndex`] if an object already sits at the
1139    ///   new index's key and does not fit the segment. Delete it and rerun.
1140    /// - [`ItzmaError::ReadBudgetExceeded`] if one `sparse.bin` is bigger
1141    ///   than the read budget.
1142    /// - [`ItzmaError::ManifestContention`] after 32 lost publish rounds.
1143    /// - Anything [`manifest::load`] can return.
1144    ///
1145    /// A failure part way leaves the segments before it indexed. Call again
1146    /// to finish.
1147    ///
1148    /// # Examples
1149    ///
1150    /// ```
1151    /// # #[tokio::main]
1152    /// # async fn main() -> itzma_core::Result<()> {
1153    /// use std::sync::Arc;
1154    ///
1155    /// use itzma_core::{CompactionOptions, Document, IndexSparseOptions, Metric, Namespace, Schema};
1156    /// use object_store::memory::InMemory;
1157    ///
1158    /// let store = Arc::new(InMemory::new());
1159    /// let ns = Namespace::create(store, "docs", Schema::new(1, Metric::L2)).await?;
1160    /// ns.upsert(vec![Document {
1161    ///     id: "a".into(),
1162    ///     vector: vec![1.0],
1163    ///     attrs: None,
1164    ///     sparse: Some(vec![(7, 0.5)]),
1165    /// }])
1166    /// .await?;
1167    /// ns.compact(&CompactionOptions::default()).await?;
1168    ///
1169    /// let report = ns.index_sparse(&IndexSparseOptions::default()).await?;
1170    /// assert_eq!(report.indexed, 1);
1171    /// # Ok(())
1172    /// # }
1173    /// ```
1174    pub async fn index_sparse(&self, options: &IndexSparseOptions) -> Result<IndexSparseReport> {
1175        let manifest = self.load_manifest().await?;
1176        let mut report = IndexSparseReport::default();
1177        for id in &manifest.live_segments {
1178            let outcome = sparse_indexer::index_segment(
1179                &*self.store,
1180                &self.id,
1181                id,
1182                manifest.sparse_indexes.get(id),
1183                options,
1184                self.read_budget,
1185                &self.fetch_policy,
1186            )
1187            .await;
1188            let outcome = match outcome {
1189                // The segment is gone because a merge and a collection ran
1190                // after the manifest was loaded. If the manifest has not
1191                // moved, it is really missing and that is the error.
1192                Err(err) if is_stale_read(&err) => {
1193                    self.reload_if_moved(&manifest, err).await?;
1194                    sparse_indexer::Outcome::Superseded
1195                }
1196                other => other?,
1197            };
1198            report.record(outcome);
1199        }
1200        Ok(report)
1201    }
1202
1203    /// Delete the segments that a merge or a later fold has superseded, and
1204    /// the orphans that can no longer be reused (phase A). With
1205    /// [`GcOptions::fence_wal`] it also replaces folded WAL objects with fences
1206    /// (phase B).
1207    ///
1208    /// A segment is dead when it is not in the manifest, its last seq is at or
1209    /// below `wal_folded_through`, and it is not `1-<wal_folded_through>` (the
1210    /// id a merge over an empty tail would produce and reuse). Only dead
1211    /// segments are deleted, and only when both they and the live segment that
1212    /// replaced them are at least [`GcOptions::min_age`] old. Live segments,
1213    /// orphans past the fold point and the manifest are never touched. With
1214    /// [`GcOptions::dry_run`] nothing is deleted or fenced.
1215    ///
1216    /// **Fencing** is off unless asked for. A fence is an 8-byte object that
1217    /// takes the place of a WAL object at the same key, so put-if-absent still
1218    /// refuses a writer whose hint is stale, and the bytes of the old batch are
1219    /// gone. An object is fenced when its seq is at or below
1220    /// `wal_folded_through`, and both it and the live segment that holds its seq
1221    /// are at least `min_age` old. **After that the segments are the only copy of
1222    /// what those objects held.** A damaged segment can no longer be rebuilt from
1223    /// the WAL, and neither can a manifest reset to fold nothing. The namespace
1224    /// must be at WAL format level 4 (see
1225    /// [`upgrade_wal_format`](Self::upgrade_wal_format)), and every build that
1226    /// reads it must know fences, which the gate enforces. A fence has no
1227    /// idempotency key, so a keyed retry can find its original only until the
1228    /// object is fenced, at least `min_age` after the write.
1229    ///
1230    /// GC is a separate call because deleting has its own cost and failures,
1231    /// and nothing hosts a background job yet. It reads the manifest and never
1232    /// writes it, so it needs no conditional update and also works on
1233    /// `LocalFileSystem`. It may run at any time, from any number of processes
1234    /// at once, beside writers, compactors and queries. A query that loaded
1235    /// the manifest before a merge and reads after GC reloads and finishes on
1236    /// the new one, and so does a compaction (see [`query`](Self::query) and
1237    /// [`compact`](Self::compact)). That covers a fence in the tail as well as a
1238    /// missing segment. Roll out readers with that behavior before running GC.
1239    /// A fencing run lists the WAL only past a small hint object,
1240    /// `gc/fenced-through`, that it keeps up to date, so the listing
1241    /// does not grow with the fenced part of the log.
1242    ///
1243    /// Inside a live segment's directory it also deletes index objects
1244    /// that the manifest does not name: an older generation that a
1245    /// rebuild replaced, or an orphan of a build that never published. Such an
1246    /// object goes once it and the index that replaced it are `min_age` old (an
1247    /// orphan with no replacement needs only its own age). The index the
1248    /// manifest names is never deleted.
1249    ///
1250    /// GC deletes segments, so a document's old bytes stay in the store until
1251    /// the segments that held them are collected, and in the WAL until its
1252    /// objects are fenced.
1253    ///
1254    /// # Errors
1255    ///
1256    /// - [`ItzmaError::CorruptManifest`] if the manifest's segment list breaks
1257    ///   its invariant.
1258    /// - [`ItzmaError::WalFormatTooOld`] if `fence_wal` is set and the namespace
1259    ///   is below level 4. Nothing is changed.
1260    /// - [`ItzmaError::UnsupportedFormat`], [`ItzmaError::Serde`] or
1261    ///   [`ItzmaError::Storage`] for an unreadable manifest or a backend
1262    ///   failure. A failure part way leaves some dead segments deleted and
1263    ///   others not, and some objects fenced and others whole; rerunning
1264    ///   finishes the job.
1265    ///
1266    /// # Examples
1267    ///
1268    /// ```
1269    /// # #[tokio::main]
1270    /// # async fn main() -> itzma_core::Result<()> {
1271    /// use std::sync::Arc;
1272    /// use std::time::Duration;
1273    ///
1274    /// use itzma_core::{CompactionOptions, Document, GcOptions, Metric, Namespace, Schema};
1275    /// use object_store::memory::InMemory;
1276    ///
1277    /// let store = Arc::new(InMemory::new());
1278    /// let ns = Namespace::create(store, "docs", Schema::new(1, Metric::L2)).await?;
1279    /// let doc = |id: &str| Document { id: id.into(), vector: vec![1.0], attrs: None, sparse: None };
1280    ///
1281    /// // Two folds, then a merge that replaces both segments.
1282    /// let tight = CompactionOptions { max_segments: 1, max_segment_bytes: itzma_core::compaction::DEFAULT_MAX_SEGMENT_BYTES };
1283    /// ns.upsert(vec![doc("a")]).await?;
1284    /// ns.compact(&tight).await?;
1285    /// ns.upsert(vec![doc("b")]).await?;
1286    /// ns.compact(&tight).await?;
1287    ///
1288    /// // The default keeps anything younger than a day.
1289    /// assert_eq!(ns.gc(&GcOptions::default()).await?.segments_deleted, 0);
1290    ///
1291    /// let now = GcOptions { min_age: Duration::ZERO, ..GcOptions::default() };
1292    /// assert_eq!(ns.gc(&now).await?.segments_deleted, 1);
1293    /// assert_eq!(ns.query(&[1.0], 10).await?.len(), 2);
1294    ///
1295    /// // The WAL is only touched when asked. Both objects are folded now.
1296    /// assert_eq!(ns.gc(&now).await?.wal_objects_fenced, 0);
1297    /// let fencing = GcOptions { fence_wal: true, ..now };
1298    /// assert_eq!(ns.gc(&fencing).await?.wal_objects_fenced, 2);
1299    /// assert_eq!(ns.query(&[1.0], 10).await?.len(), 2);
1300    /// # Ok(())
1301    /// # }
1302    /// ```
1303    pub async fn gc(&self, options: &GcOptions) -> Result<GcReport> {
1304        let manifest = self.load_manifest().await?;
1305        gc::run(&*self.store, &self.id, &manifest, options).await
1306    }
1307
1308    /// Compact if the WAL tail is long enough, then collect, and report what
1309    /// happened. The caller decides when to call it, from a cron job
1310    /// or a loop. The library starts no task of its own.
1311    ///
1312    /// It lists the WAL tail past `wal_folded_through` (sizes and write times,
1313    /// no GETs) and runs [`compact`](Self::compact) with
1314    /// [`MaintenanceOptions::compaction`] if the tail is not empty and any
1315    /// [`CompactTrigger`](crate::CompactTrigger) threshold is crossed, or if
1316    /// there are more live segments than `max_segments`. Then, if
1317    /// [`MaintenanceOptions::gc`] is set, it runs [`gc`](Self::gc), which
1318    /// happens whether or not a compaction was due. The compaction goes first,
1319    /// so the segments it replaced are candidates at once.
1320    ///
1321    /// It is safe from any number of processes at once, because `compact` and
1322    /// `gc` are. A compaction that another process won reports
1323    /// [`Compaction::Superseded`]. A call that stopped part way is finished by
1324    /// calling it again. It reads the manifest twice, since `compact` loads its
1325    /// own.
1326    ///
1327    /// # Errors
1328    ///
1329    /// Those of [`compact`](Self::compact) and [`gc`](Self::gc), including
1330    /// [`ItzmaError::WalFormatTooNew`] and [`ItzmaError::WalFormatTooOld`]
1331    /// (`fence_wal` below level 4). A failure in the compaction stops the call
1332    /// before the collection.
1333    ///
1334    /// # Examples
1335    ///
1336    /// ```
1337    /// # #[tokio::main]
1338    /// # async fn main() -> itzma_core::Result<()> {
1339    /// use std::sync::Arc;
1340    ///
1341    /// use itzma_core::{CompactTrigger, Compaction, Document, MaintenanceOptions, Metric, Namespace, Schema};
1342    /// use object_store::memory::InMemory;
1343    ///
1344    /// let store = Arc::new(InMemory::new());
1345    /// let ns = Namespace::create(store, "docs", Schema::new(1, Metric::L2)).await?;
1346    /// let doc = |id: &str| Document { id: id.into(), vector: vec![1.0], attrs: None, sparse: None };
1347    ///
1348    /// // Fold once the tail has two objects.
1349    /// let options = MaintenanceOptions {
1350    ///     compact_when: CompactTrigger { tail_objects: 2, ..CompactTrigger::default() },
1351    ///     ..MaintenanceOptions::default()
1352    /// };
1353    ///
1354    /// ns.upsert(vec![doc("a")]).await?;
1355    /// assert_eq!(ns.maintain(&options).await?.compaction, None);
1356    ///
1357    /// ns.upsert(vec![doc("b")]).await?;
1358    /// let report = ns.maintain(&options).await?;
1359    /// assert_eq!(report.tail_objects, 2);
1360    /// assert!(matches!(report.compaction, Some(Compaction::Published { folded_through: 2, .. })));
1361    /// # Ok(())
1362    /// # }
1363    /// ```
1364    pub async fn maintain(&self, options: &MaintenanceOptions) -> Result<MaintenanceReport> {
1365        let manifest = self.load_manifest().await?;
1366        let objects =
1367            gc::list_wal_after(&*self.store, &self.id, manifest.wal_folded_through).await?;
1368        let tail = maintain::Tail::of(&objects);
1369        let compaction = if maintain::due(
1370            &options.compact_when,
1371            tail,
1372            manifest.live_segments.len(),
1373            options.compaction.max_segments,
1374            gc::now_millis(),
1375        ) {
1376            Some(self.compact(&options.compaction).await?)
1377        } else {
1378            None
1379        };
1380        let gc = match &options.gc {
1381            Some(gc_options) => Some(self.gc(gc_options).await?),
1382            None => None,
1383        };
1384        Ok(MaintenanceReport {
1385            tail_objects: tail.objects,
1386            tail_bytes: tail.bytes,
1387            compaction,
1388            gc,
1389        })
1390    }
1391
1392    /// A maintenance lease on this namespace, for a loop that should maintain
1393    /// only while no other process does. Nothing is read or written
1394    /// until the first [`tick`](MaintenanceLease::tick). Each call gives a new
1395    /// holder, so two leases from one handle compete like two processes.
1396    ///
1397    /// # Errors
1398    ///
1399    /// [`ItzmaError::InvalidConfig`] if `renew` is zero or `ttl` is less than
1400    /// twice `renew`.
1401    pub fn maintenance_lease(&self, options: LeaseOptions) -> Result<MaintenanceLease> {
1402        MaintenanceLease::new(Arc::clone(&self.store), &self.id, options)
1403    }
1404
1405    /// Commit ops through [`wal::append`], then advance the hint past the seq
1406    /// that was won. `fetch_max` keeps the hint from moving backwards when
1407    /// several tasks share a handle. A batch that carries a sparse vector
1408    /// needs the namespace at [`wal::SPARSE_FORMAT_VERSION`] first,
1409    /// checked before anything is written; a plain batch never reads the
1410    /// level.
1411    async fn append(&self, ops: Vec<WalOp>) -> Result<u64> {
1412        if has_sparse(&ops) {
1413            self.ensure_wal_level(wal::SPARSE_FORMAT_VERSION).await?;
1414        }
1415        let hint = self.next_seq.load(Ordering::Relaxed);
1416        let seq = wal::append(&*self.store, &self.id, hint, ops).await?;
1417        self.next_seq.fetch_max(seq + 1, Ordering::Relaxed);
1418        Ok(seq)
1419    }
1420
1421    /// Commit an object `wal_codec` already encoded, with [`append`]'s level
1422    /// check (`sparse`: the object has a sparse column) and hint bookkeeping.
1423    pub(crate) async fn append_bytes(&self, bytes: bytes::Bytes, sparse: bool) -> Result<u64> {
1424        if sparse {
1425            self.ensure_wal_level(wal::SPARSE_FORMAT_VERSION).await?;
1426        }
1427        let hint = self.next_seq.load(Ordering::Relaxed);
1428        let seq = wal::put_encoded(&*self.store, &self.id, hint, bytes).await?;
1429        self.next_seq.fetch_max(seq + 1, Ordering::Relaxed);
1430        Ok(seq)
1431    }
1432
1433    /// [`append_bytes`](Self::append_bytes) for a keyed object, with
1434    /// [`append_keyed`](Self::append_keyed)'s checks.
1435    pub(crate) async fn append_bytes_keyed(
1436        &self,
1437        write: &WriteKey,
1438        object: wal_codec::Keyed,
1439        sparse: bool,
1440    ) -> Result<u64> {
1441        write.validate()?;
1442        self.ensure_wal_level(wal::KEYED_FORMAT_VERSION).await?;
1443        if sparse {
1444            self.ensure_wal_level(wal::SPARSE_FORMAT_VERSION).await?;
1445        }
1446        let hint = self.next_seq.load(Ordering::Relaxed);
1447        let seq = wal::put_encoded_keyed(&*self.store, &self.id, hint, write, object).await?;
1448        self.next_seq.fetch_max(seq + 1, Ordering::Relaxed);
1449        Ok(seq)
1450    }
1451
1452    /// Commit ops under a key through [`wal::append_keyed`], after checking the
1453    /// key and the namespace's level (and, for a sparse-carrying batch, the
1454    /// sparse level too).
1455    async fn append_keyed(&self, write: &WriteKey, ops: Vec<WalOp>) -> Result<u64> {
1456        write.validate()?;
1457        if ops.is_empty() {
1458            return Err(ItzmaError::EmptyBatch);
1459        }
1460        self.ensure_wal_level(wal::KEYED_FORMAT_VERSION).await?;
1461        if has_sparse(&ops) {
1462            self.ensure_wal_level(wal::SPARSE_FORMAT_VERSION).await?;
1463        }
1464        let hint = self.next_seq.load(Ordering::Relaxed);
1465        let seq = wal::append_keyed(&*self.store, &self.id, hint, write, ops).await?;
1466        self.next_seq.fetch_max(seq + 1, Ordering::Relaxed);
1467        Ok(seq)
1468    }
1469
1470    /// Check that the namespace's WAL format is at least `need`. A handle
1471    /// that already knows it is does not read anything. Otherwise the manifest
1472    /// is read once, because another process may have raised the level since
1473    /// this handle opened.
1474    async fn ensure_wal_level(&self, need: u32) -> Result<()> {
1475        if self.wal_level.load(Ordering::Relaxed) >= need {
1476            return Ok(());
1477        }
1478        let (manifest, _version) = manifest::load(&*self.store, &self.id).await?;
1479        self.wal_level
1480            .fetch_max(manifest.wal_format, Ordering::Relaxed);
1481        if manifest.wal_format >= need {
1482            Ok(())
1483        } else {
1484            Err(ItzmaError::WalFormatTooOld {
1485                have: manifest.wal_format,
1486                need,
1487            })
1488        }
1489    }
1490
1491    /// Find the `top_k` documents closest to `vector`, closest first.
1492    ///
1493    /// Steps:
1494    ///
1495    /// 1. Validate `vector` against the schema.
1496    /// 2. Load the manifest (one GET, no cache) and check that its segment
1497    ///    list is contiguous and ends at `wal_folded_through`.
1498    /// 3. In parallel, fetch and decode the live segments (16 at a time) and
1499    ///    read the WAL entries after `wal_folded_through`, checking they are
1500    ///    contiguous. Each entry is folded into a layer of its own as it
1501    ///    arrives. Every object is charged to the read budget before its body
1502    ///    is read.
1503    /// 4. Scan each source for its closest documents and drop any that a
1504    ///    newer source holds as a document or a tombstone, so the last op on
1505    ///    an id wins, including deletes.
1506    /// 5. Keep the best `top_k` across sources (as [`crate::search::flat_top_k`]
1507    ///    would over the replayed documents).
1508    ///
1509    /// The metric comes from the schema. Distances follow the "lower is closer"
1510    /// convention documented on [`crate::search::distance`], and ties break by id.
1511    /// If fewer than `top_k` documents exist, all of them are returned; if
1512    /// `top_k` is 0 the result is empty.
1513    ///
1514    /// A query started after a compaction published sees the same documents as
1515    /// one started before it. A query racing a compaction works from the
1516    /// manifest it loaded. If garbage collection has since deleted a segment
1517    /// that manifest lists, the query loads the manifest again and reads
1518    /// against the new one, three attempts in all. A segment that is missing
1519    /// from an unchanged manifest is damage, and the query fails.
1520    ///
1521    /// # Cost
1522    ///
1523    /// Every call fetches all live segments and the un-compacted WAL tail and
1524    /// scans every document, so cost is O(live documents) plus one request
1525    /// per segment and per tail entry. Run [`compact`](Self::compact) to keep
1526    /// the tail short. Caching and indexes are what remove the rest.
1527    ///
1528    /// A query holds every live document in memory, so it reads at most the
1529    /// handle's read budget (see [`with_read_budget`](Self::with_read_budget)).
1530    ///
1531    /// # Errors
1532    ///
1533    /// - [`ItzmaError::DimensionMismatch`] / [`ItzmaError::InvalidVector`] for
1534    ///   a bad query vector.
1535    /// - [`ItzmaError::CorruptManifest`] if the segment list breaks its
1536    ///   invariant.
1537    /// - [`ItzmaError::CorruptSegment`] if a listed segment is missing from
1538    ///   the current manifest, damaged, or has the wrong dimension.
1539    /// - [`ItzmaError::WalGap`] if the log has a hole.
1540    /// - [`ItzmaError::ReadBudgetExceeded`] if the live segments and the tail
1541    ///   add up to more than the read budget.
1542    /// - [`ItzmaError::UnsupportedFormat`], [`ItzmaError::Serde`] or
1543    ///   [`ItzmaError::Storage`] for unreadable objects or backend failures.
1544    ///
1545    /// # Examples
1546    ///
1547    /// ```
1548    /// # #[tokio::main]
1549    /// # async fn main() -> itzma_core::Result<()> {
1550    /// use std::sync::Arc;
1551    ///
1552    /// use itzma_core::{AttrSchema, AttrType, Document, Metric, Namespace, Schema};
1553    /// use object_store::memory::InMemory;
1554    ///
1555    /// let store = Arc::new(InMemory::new());
1556    /// let schema = Schema::new(2, Metric::Cosine)
1557    ///     .with_attrs(AttrSchema::new().field("label", AttrType::Text));
1558    /// let ns = Namespace::create(store, "docs", schema).await?;
1559    /// let doc = |id: &str, v: [f32; 2]| Document {
1560    ///     id: id.into(),
1561    ///     vector: v.to_vec(),
1562    ///     attrs: Some(serde_json::json!({ "label": id })),
1563    ///     sparse: None,
1564    /// };
1565    /// ns.upsert(vec![doc("east", [1.0, 0.0]), doc("north", [0.0, 1.0])]).await?;
1566    ///
1567    /// let hits = ns.query(&[2.0, 0.1], 2).await?;
1568    /// assert_eq!(hits[0].id, "east");
1569    /// assert_eq!(hits[0].attrs, Some(serde_json::json!({ "label": "east" })));
1570    /// assert!(hits[0].distance < hits[1].distance);
1571    /// # Ok(())
1572    /// # }
1573    /// ```
1574    pub async fn query(&self, vector: &[f32], top_k: usize) -> Result<Vec<Hit>> {
1575        self.query_with(vector, top_k, &QueryOptions::default())
1576            .await
1577    }
1578
1579    /// [`query`](Self::query) with [`QueryOptions`]: how many candidates an
1580    /// index proposes per hit wanted ([`QueryOptions::rerank`]), how many of its
1581    /// partitions to search ([`QueryOptions::nprobe`]), and whether to ignore
1582    /// indexes and scan flat ([`QueryOptions::exact`]).
1583    ///
1584    /// [`QueryOptions::filter`] keeps only documents whose attributes match a
1585    /// [`Predicate`]. It is checked against the attribute schema
1586    /// before any read: an undeclared field is [`ItzmaError::UnknownAttr`], an
1587    /// operator that does not fit its field is [`ItzmaError::AttrTypeMismatch`],
1588    /// and a namespace with no attribute schema refuses it with
1589    /// [`ItzmaError::InvalidQuery`]. The answer is the closest `top_k` live
1590    /// documents that match, and has fewer only when fewer match. The newest
1591    /// version of an id is the one tested. A selective filter widens the search
1592    /// until it has enough matches or has read every row, bounded by the read
1593    /// budget.
1594    ///
1595    /// With no live segment holding an index this build can search (an empty
1596    /// namespace, one whose segments are not indexed, or `exact: true`), this is
1597    /// exactly the flat scan `query` has always done, and the options change
1598    /// nothing else.
1599    ///
1600    /// Otherwise a live segment with an index is read through it: its algorithm
1601    /// proposes `rerank * top_k` candidate rows by approximate distance (every
1602    /// row if `rerank` is `None`, which makes the answer equal the flat scan's),
1603    /// each is checked against every newer source (a segment or the WAL tail)
1604    /// and dropped if one holds it as a document or a tombstone, and what
1605    /// survives is rescored against its exact vector. A segment left short of
1606    /// `top_k` live candidates by shadowing is asked again for more before the
1607    /// next source is read. Segments without an index, and the WAL tail, are
1608    /// read whole and scanned flat, like today. The merge across sources keeps
1609    /// the closest `top_k` by exact distance, and only then are their attributes
1610    /// fetched.
1611    ///
1612    /// # Errors
1613    ///
1614    /// - [`ItzmaError::InvalidQuery`] for a `rerank` or `nprobe` of zero.
1615    /// - Everything [`query`](Self::query) can return.
1616    /// - [`ItzmaError::CorruptIndex`] for a damaged index, or one that proposed
1617    ///   a row past its segment. Never falls back to a flat scan; retry with
1618    ///   `exact: true`, or `index` with `rebuild` to replace it.
1619    ///
1620    /// # Examples
1621    ///
1622    /// ```
1623    /// # #[tokio::main]
1624    /// # async fn main() -> itzma_core::Result<()> {
1625    /// use std::sync::Arc;
1626    ///
1627    /// use itzma_core::{Document, Metric, Namespace, QueryOptions, Schema};
1628    /// use object_store::memory::InMemory;
1629    ///
1630    /// let store = Arc::new(InMemory::new());
1631    /// let ns = Namespace::create(store, "docs", Schema::new(1, Metric::L2)).await?;
1632    /// ns.upsert(vec![Document { id: "a".into(), vector: vec![1.0], attrs: None, sparse: None }]).await?;
1633    ///
1634    /// let exact = QueryOptions::default().exact(true);
1635    /// assert_eq!(ns.query(&[0.0], 1).await?, ns.query_with(&[0.0], 1, &exact).await?);
1636    /// # Ok(())
1637    /// # }
1638    /// ```
1639    pub async fn query_with(
1640        &self,
1641        vector: &[f32],
1642        top_k: usize,
1643        options: &QueryOptions,
1644    ) -> Result<Vec<Hit>> {
1645        self.schema.validate(vector)?;
1646        options.validate()?;
1647        self.check_filter(&options.filter)?;
1648        let mut budget = ReadBudget::new(self.read_budget);
1649        let mut plan = self.views.plan(&self.reader(&budget)).await?;
1650        let mut attempt = 1;
1651        loop {
1652            let outcome = self
1653                .query_once(vector, top_k, options, &plan, &budget)
1654                .await;
1655            match outcome {
1656                Err(err) if is_stale_read(&err) && attempt < MAX_READ_ATTEMPTS => {
1657                    budget = ReadBudget::new(self.read_budget);
1658                    plan = self.views.replan(&self.reader(&budget), &plan, err).await?;
1659                    attempt += 1;
1660                }
1661                done => return done,
1662            }
1663        }
1664    }
1665
1666    /// One attempt at a query against `manifest`, through the engine in
1667    /// `query.rs` (which reads every segment flat for `exact` or a namespace
1668    /// with no index it can search).
1669    async fn query_once(
1670        &self,
1671        vector: &[f32],
1672        top_k: usize,
1673        options: &QueryOptions,
1674        plan: &view::Plan,
1675        budget: &ReadBudget,
1676    ) -> Result<Vec<Hit>> {
1677        let manifest = &*plan.manifest;
1678        let reader = self.reader(budget);
1679        let tail = self.views.tail(&reader, plan);
1680        let decoded = self.decoded();
1681        let q = query::Query {
1682            store: &*self.query_store,
1683            namespace: &self.id,
1684            dim: self.schema.dim,
1685            metric: self.schema.metric,
1686            vector,
1687            top_k,
1688            options,
1689            budget,
1690            policy: &self.fetch_policy,
1691            registry: &Builtin,
1692            decoded: decoded.as_ref(),
1693        };
1694        query::run(&q, manifest, tail).await
1695    }
1696
1697    /// Find the `top_k` documents whose sparse vectors score highest against
1698    /// `query`, best first.
1699    ///
1700    /// `query` is a set of `(term id, weight)` pairs in the same vocabulary the
1701    /// documents' [`sparse`](Document::sparse) vectors use. A document's score
1702    /// is the dot product over the terms it shares with the query, an exact
1703    /// sum with no approximation, so there is no rerank step and nothing to
1704    /// tune. A document that shares no term with the query, or has no sparse
1705    /// vector, is never a hit. A term repeated in `query` counts as the sum of
1706    /// its weights.
1707    ///
1708    /// Hits are [`Hit`]s like [`query`](Self::query)'s, and follow the same
1709    /// convention: `distance` is lower for a closer match, so it is the score
1710    /// negated. Ties break by id.
1711    ///
1712    /// [`SparseQueryOptions::filter`] keeps only documents whose attributes
1713    /// match a [`Predicate`], with the same checks and meaning as
1714    /// [`QueryOptions::filter`].
1715    ///
1716    /// Shadowing works as it does for [`query_with`](Self::query_with): the
1717    /// newest version of an id decides, so an overwrite or a delete hides the
1718    /// older document's sparse vector. A segment with a sparse index
1719    /// ([`index_sparse`](Self::index_sparse)) is read in pieces, fetching only
1720    /// the postings of the query's own terms. Every other segment, and the WAL
1721    /// tail, is read whole and scored directly, so an unindexed namespace
1722    /// gives the same answer, only at a higher cost. Reads go through the
1723    /// handle's cache if [`with_cache`](Self::with_cache) set one, and are
1724    /// bounded by the read budget.
1725    ///
1726    /// # Errors
1727    ///
1728    /// - [`ItzmaError::InvalidQuery`] for a `top_k` of zero, an empty `query`
1729    ///   or a non-finite weight in it, before any storage call.
1730    /// - [`ItzmaError::CorruptSegment`] for a damaged `sparse.bin`.
1731    /// - [`ItzmaError::CorruptSparseIndex`] for a damaged sparse index, or one
1732    ///   that named a row past its segment. A query never falls back to a flat
1733    ///   scan over one; [`index_sparse`](Self::index_sparse) with `rebuild`
1734    ///   replaces it.
1735    /// - [`ItzmaError::ReadBudgetExceeded`] and the other errors of
1736    ///   [`query`](Self::query).
1737    ///
1738    /// # Examples
1739    ///
1740    /// ```
1741    /// # #[tokio::main]
1742    /// # async fn main() -> itzma_core::Result<()> {
1743    /// use std::sync::Arc;
1744    ///
1745    /// use itzma_core::{Document, Metric, Namespace, Schema, SparseQueryOptions};
1746    /// use object_store::memory::InMemory;
1747    ///
1748    /// let store = Arc::new(InMemory::new());
1749    /// let ns = Namespace::create(store, "docs", Schema::new(1, Metric::L2)).await?;
1750    /// let doc = |id: &str, terms: Vec<(u32, f32)>| Document {
1751    ///     id: id.into(),
1752    ///     vector: vec![0.0],
1753    ///     attrs: None,
1754    ///     sparse: Some(terms),
1755    /// };
1756    /// ns.upsert(vec![doc("cats", vec![(1, 2.0), (2, 1.0)]), doc("dogs", vec![(3, 2.0)])]).await?;
1757    ///
1758    /// let hits = ns.query_sparse(&vec![(1, 1.0), (2, 1.0)], 5, &SparseQueryOptions::default()).await?;
1759    /// assert_eq!(hits.len(), 1);
1760    /// assert_eq!(hits[0].id, "cats");
1761    /// assert_eq!(hits[0].distance, -3.0);
1762    /// # Ok(())
1763    /// # }
1764    /// ```
1765    pub async fn query_sparse(
1766        &self,
1767        query: &SparseVector,
1768        top_k: usize,
1769        options: &SparseQueryOptions,
1770    ) -> Result<Vec<Hit>> {
1771        sparse_query::validate(query, top_k)?;
1772        self.check_filter(&options.filter)?;
1773        let mut budget = ReadBudget::new(self.read_budget);
1774        let mut plan = self.views.plan(&self.reader(&budget)).await?;
1775        let mut attempt = 1;
1776        let decoded = self.decoded();
1777        loop {
1778            let q = sparse_query::Query {
1779                store: &*self.query_store,
1780                namespace: &self.id,
1781                dim: self.schema.dim,
1782                query,
1783                top_k,
1784                filter: options.filter.as_ref(),
1785                budget: &budget,
1786                policy: &self.fetch_policy,
1787                decoded: decoded.as_ref(),
1788            };
1789            let reader = self.reader(&budget);
1790            let tail = self.views.tail(&reader, &plan);
1791            match sparse_query::run(&q, &plan.manifest, tail).await {
1792                Err(err) if is_stale_read(&err) && attempt < MAX_READ_ATTEMPTS => {
1793                    budget = ReadBudget::new(self.read_budget);
1794                    plan = self.views.replan(&self.reader(&budget), &plan, err).await?;
1795                    attempt += 1;
1796                }
1797                done => return done,
1798            }
1799        }
1800    }
1801
1802    /// Return the documents whose attributes match `predicate`, in ascending id
1803    /// order, one page at a time.
1804    ///
1805    /// No vector is involved and none is read: a [`Row`](crate::Row) is an id
1806    /// and its attributes. The predicate is checked against the namespace's
1807    /// attribute schema first, so a field that is not declared or an operator
1808    /// that does not fit its type is an error and never an empty result. A
1809    /// comparison against a null field is false and [`Predicate::Not`] flips it
1810    /// (see [`Predicate`] for the difference from SQL).
1811    ///
1812    /// The newest version of an id decides it, as for every query: an upsert
1813    /// that no longer matches hides the older copy that did, and a delete hides
1814    /// it too. Ids are compared in byte order. A page holds at most
1815    /// [`FilterOptions::limit`] rows, and [`FilterPage::next`] is the id to pass
1816    /// as [`FilterOptions::after`] for the following one. Paging is not a
1817    /// snapshot: a write or a compaction between two pages can change what the
1818    /// second sees, and each page is consistent on its own.
1819    ///
1820    /// The cost is linear in the ids and attributes read, and a page stops once
1821    /// it has `limit` matches, so a loose filter is cheap and a selective one
1822    /// reads most of the namespace. Reads are bounded by the handle's read
1823    /// budget and go through its cache if [`with_cache`](Self::with_cache) set
1824    /// one. A scan that would go over the budget stops with
1825    /// [`ItzmaError::ReadBudgetExceeded`] and returns no partial page and no
1826    /// cursor, so a selective filter on a namespace bigger than the budget
1827    /// cannot be paged through until the budget is raised.
1828    ///
1829    /// # Errors
1830    ///
1831    /// - [`ItzmaError::InvalidQuery`] for a `limit` of zero or above 10,000, a
1832    ///   malformed predicate (see [`Predicate`]), or a namespace made before
1833    ///   typed attributes, which has nothing to filter on.
1834    /// - [`ItzmaError::UnknownAttr`] and [`ItzmaError::AttrTypeMismatch`] for a
1835    ///   predicate that does not fit the schema.
1836    /// - [`ItzmaError::ReadBudgetExceeded`] and the other errors of
1837    ///   [`query`](Self::query).
1838    ///
1839    /// # Examples
1840    ///
1841    /// ```
1842    /// # #[tokio::main]
1843    /// # async fn main() -> itzma_core::Result<()> {
1844    /// use std::sync::Arc;
1845    ///
1846    /// use itzma_core::{
1847    ///     AttrSchema, AttrType, Compare, Document, FilterOptions, Metric, Namespace,
1848    ///     Predicate, Schema,
1849    /// };
1850    /// use object_store::memory::InMemory;
1851    ///
1852    /// let schema = Schema::new(1, Metric::L2)
1853    ///     .with_attrs(AttrSchema::new().field("price", AttrType::Number));
1854    /// let ns = Namespace::create(Arc::new(InMemory::new()), "shop", schema).await?;
1855    /// let item = |id: &str, price: f64| Document {
1856    ///     id: id.into(),
1857    ///     vector: vec![0.0],
1858    ///     attrs: Some(serde_json::json!({ "price": price })),
1859    ///     sparse: None,
1860    /// };
1861    /// ns.upsert(vec![item("a", 5.0), item("b", 50.0), item("c", 12.0)]).await?;
1862    ///
1863    /// let cheap = Predicate::number("price", Compare::Lt, 20.0);
1864    /// let page = ns.filter(&cheap, &FilterOptions::default()).await?;
1865    /// let ids: Vec<&str> = page.rows.iter().map(|r| r.id.as_str()).collect();
1866    /// assert_eq!(ids, ["a", "c"]);
1867    /// # Ok(())
1868    /// # }
1869    /// ```
1870    pub async fn filter(
1871        &self,
1872        predicate: &Predicate,
1873        options: &FilterOptions,
1874    ) -> Result<FilterPage> {
1875        options.validate()?;
1876        if self.schema.attrs.is_free_form() {
1877            return Err(ItzmaError::InvalidQuery(
1878                "this namespace has no attribute schema, so there is nothing to filter on",
1879            ));
1880        }
1881        predicate.check(&self.schema.attrs)?;
1882        let mut budget = ReadBudget::new(self.read_budget);
1883        let mut plan = self.views.plan(&self.reader(&budget)).await?;
1884        let mut attempt = 1;
1885        let decoded = self.decoded();
1886        loop {
1887            let scan = filter::Scan {
1888                store: &*self.query_store,
1889                namespace: &self.id,
1890                dim: self.schema.dim,
1891                predicate,
1892                limit: options.limit,
1893                after: options.after.as_deref(),
1894                budget: &budget,
1895                policy: &self.fetch_policy,
1896                decoded: decoded.as_ref(),
1897            };
1898            let reader = self.reader(&budget);
1899            let tail = self.views.tail(&reader, &plan);
1900            match filter::run(&scan, &plan.manifest, tail).await {
1901                Err(err) if is_stale_read(&err) && attempt < MAX_READ_ATTEMPTS => {
1902                    budget = ReadBudget::new(self.read_budget);
1903                    plan = self.views.replan(&self.reader(&budget), &plan, err).await?;
1904                    attempt += 1;
1905                }
1906                done => return done,
1907            }
1908        }
1909    }
1910
1911    /// Refuse a filter that cannot run, before any storage call.
1912    fn check_filter(&self, filter: &Option<Predicate>) -> Result<()> {
1913        let Some(predicate) = filter else {
1914            return Ok(());
1915        };
1916        if self.schema.attrs.is_free_form() {
1917            return Err(ItzmaError::InvalidQuery(
1918                "this namespace has no attribute schema, so there is nothing to filter on",
1919            ));
1920        }
1921        predicate.check(&self.schema.attrs)
1922    }
1923
1924    /// Where this handle's queries read their snapshot from.
1925    fn reader<'a>(&'a self, budget: &'a ReadBudget) -> view::Reader<'a> {
1926        view::Reader {
1927            store: &*self.store,
1928            query_store: &*self.query_store,
1929            namespace: &self.id,
1930            own_last: self.next_seq.load(Ordering::Relaxed).saturating_sub(1),
1931            budget,
1932        }
1933    }
1934
1935    /// `err` came from reading against `stale`. If it says a segment is gone
1936    /// or a WAL object is a fence, and the manifest has changed since, the
1937    /// caller was only behind (a compaction and a garbage collection ran after
1938    /// it loaded): return the current manifest to try again. Any other error,
1939    /// or an unchanged manifest, means the object really is missing or the fence
1940    /// really is misplaced, and `err` comes back as it was.
1941    async fn reload_if_moved(&self, stale: &Manifest, err: ItzmaError) -> Result<Manifest> {
1942        if !is_stale_read(&err) {
1943            return Err(err);
1944        }
1945        let fresh = self.load_manifest().await?;
1946        if fresh == *stale { Err(err) } else { Ok(fresh) }
1947    }
1948
1949    /// Load the manifest and check its segment list against the invariant, so
1950    /// every reader fails the same way on a damaged manifest.
1951    async fn load_manifest(&self) -> Result<Manifest> {
1952        view::load_checked(&*self.store, &self.id).await
1953    }
1954}
1955
1956/// Garbage collection removes segments and index objects and fences WAL
1957/// objects, so a reader that loaded its manifest before a collection
1958/// can meet any of the three. All of them mean "reload and look again" before
1959/// they mean damage.
1960pub(crate) fn is_stale_read(err: &ItzmaError) -> bool {
1961    segment::is_missing(err)
1962        || index::is_missing(err)
1963        || sparse_index::is_missing(err)
1964        || wal_codec::is_fenced(err)
1965}
1966
1967/// Whether any upsert in `ops` carries a sparse vector — such a
1968/// batch needs [`wal::SPARSE_FORMAT_VERSION`] before it is written.
1969fn has_sparse(ops: &[WalOp]) -> bool {
1970    ops.iter()
1971        .any(|op| matches!(op, WalOp::Upsert(doc) if doc.sparse.is_some()))
1972}
1973
1974#[cfg(test)]
1975mod tests {
1976    use std::sync::Arc;
1977
1978    use object_store::memory::InMemory;
1979
1980    use super::*;
1981    use crate::document::Metric;
1982
1983    #[test]
1984    fn fetch_policy_defaults_to_object_store_and_with_fetch_policy_overrides_it() {
1985        let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
1986        let manifest = Manifest::new(Schema::new(1, Metric::L2));
1987        let ns = Namespace::from_manifest(store, "docs", &manifest);
1988        assert_eq!(ns.fetch_policy, FetchPolicy::object_store());
1989        let ns = ns.with_fetch_policy(FetchPolicy::local());
1990        assert_eq!(ns.fetch_policy, FetchPolicy::local());
1991    }
1992}