Skip to main content

itzma_core/
namespace.rs

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