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