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