Skip to main content

itzma_core/
manifest.rs

1//! The namespace manifest and its compare-and-swap update.
2//!
3//! The manifest is the one mutable object in a namespace. It records the
4//! schema, which segment files are live, and how much of the WAL has been
5//! folded into segments. Everything else in a namespace is written once and
6//! never modified.
7//!
8//! It also carries the namespace's WAL and segment format levels, which is how
9//! a newer build tells older ones to stay away (see [`Manifest::wal_format`]
10//! and [`Manifest::segment_format`]).
11//!
12//! Two operations change it, and both rely on the object store to arbitrate
13//! between concurrent writers:
14//!
15//! - [`create`] writes it with put-if-absent, so exactly one caller creates a
16//!   namespace.
17//! - [`update`] and [`update_if`] rewrite it with a conditional put tied to
18//!   the version that was read, so concurrent updates cannot silently
19//!   overwrite each other. Compaction publishes segments through
20//!   [`update_if`].
21
22use std::collections::BTreeMap;
23
24use bytes::Bytes;
25use object_store::path::Path;
26use object_store::{ObjectStore, ObjectStoreExt, PutMode, PutOptions, UpdateVersion};
27use serde::{Deserialize, Serialize};
28
29use crate::document::Schema;
30use crate::error::{ItzmaError, Result};
31use crate::{segment, wal};
32
33/// Version stamped into every manifest. [`load`] rejects any other value with
34/// [`ItzmaError::UnsupportedFormat`].
35pub const FORMAT_VERSION: u32 = 1;
36
37/// How many read-modify-write rounds [`update`] tries before giving up with
38/// [`ItzmaError::ManifestContention`].
39pub const MAX_UPDATE_ATTEMPTS: u32 = 32;
40
41/// The contents of `<namespace>/manifest/current.json`.
42///
43/// # JSON form
44///
45/// ```json
46/// {
47///   "format_version": 1,
48///   "schema": {"dim": 2, "metric": "l2"},
49///   "live_segments": [],
50///   "wal_folded_through": 0,
51///   "wal_format": 5,
52///   "segment_format": 2,
53///   "indexes": {},
54///   "sparse_indexes": {}
55/// }
56/// ```
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
58pub struct Manifest {
59    /// Encoding version of this object. See [`FORMAT_VERSION`].
60    pub format_version: u32,
61    /// Vector shape and metric, fixed when the namespace was created.
62    pub schema: Schema,
63    /// Ids of the live segments, oldest first. Each id names the WAL range
64    /// the segment covers (see [`segment`]); the ranges are
65    /// contiguous, start at 1, and end at `wal_folded_through`. Empty until
66    /// the first compaction.
67    pub live_segments: Vec<String>,
68    /// Highest WAL sequence number already folded into segments. WAL objects
69    /// up to and including this seq are ignored on read, and the next append
70    /// starts at `wal_folded_through + 1`. Zero means nothing has been folded.
71    pub wal_folded_through: u64,
72    /// The highest WAL object format this namespace may contain. A build
73    /// whose own [`wal::FORMAT_VERSION`] is lower refuses the namespace in
74    /// [`load`] with [`ItzmaError::WalFormatTooNew`], before it reads any WAL
75    /// object it could not decode.
76    ///
77    /// Only a newer build raises this, once every build that touches the
78    /// namespace can read the new format, with
79    /// [`Namespace::upgrade_wal_format`](crate::Namespace::upgrade_wal_format).
80    /// A keyed write needs level 3.
81    pub wal_format: u32,
82    /// The newest segment format compaction may write into this namespace, and
83    /// the highest one it may contain. A build whose own
84    /// [`segment::FORMAT_VERSION`] is lower refuses the namespace in [`load`]
85    /// with [`ItzmaError::SegmentFormatTooNew`].
86    ///
87    /// A build that reads version 3 also reads version 2, so the level only
88    /// decides what a fold or merge writes: at 2 it writes version 2, at 3
89    /// version 3. It is raised, once every build that touches the namespace
90    /// reads the new version, with
91    /// [`Namespace::upgrade_segment_format`](crate::Namespace::upgrade_segment_format).
92    pub segment_format: u32,
93    /// The index built for each live segment that has one, by segment id.
94    /// A segment that is not listed is read whole, as before. A
95    /// manifest without the field has none. Derived data: compaction drops an
96    /// entry when it retires the segment, and nothing else depends on it.
97    #[serde(default)]
98    pub indexes: BTreeMap<String, IndexEntry>,
99    /// The sparse inverted index built for each live segment that has one,
100    /// by segment id. A segment not listed here has no sparse
101    /// index — it may still have `sparse.bin` and be searched flat by
102    /// `Namespace::query_sparse`. A manifest without the field has none.
103    #[serde(default)]
104    pub sparse_indexes: BTreeMap<String, SparseIndexEntry>,
105}
106
107/// Which index object belongs to a segment: the object is
108/// `segments/<id>/index-<generation>.bin` and was built by the algorithm
109/// `kind`.
110///
111/// JSON form: `{"gen": 1, "kind": "sq8"}`.
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113pub struct IndexEntry {
114    /// Starts at 1 and goes up by one each time the segment is re-indexed, so a
115    /// rebuild never overwrites the object a reader may be using. (`gen` is a
116    /// reserved word in Rust 2024, hence the rename.)
117    #[serde(rename = "gen")]
118    pub generation: u32,
119    /// The algorithm's name, `sq8` for the only one built so far. A name this
120    /// build does not know is left alone, never guessed at.
121    pub kind: String,
122}
123
124/// Which sparse inverted-index object belongs to a segment: the object is
125/// `segments/<id>/sparse-idx-<generation>.bin`. Unlike
126/// [`IndexEntry`] there is no `kind` — one algorithm, an inverted index over
127/// term-weight pairs.
128///
129/// JSON form: `{"gen": 1}`.
130#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131pub struct SparseIndexEntry {
132    /// Starts at 1 and goes up by one each time the segment's sparse index is
133    /// rebuilt, so a rebuild never overwrites the object a reader may be
134    /// using.
135    #[serde(rename = "gen")]
136    pub generation: u32,
137}
138
139impl Manifest {
140    /// A fresh manifest for a new namespace: current format version, no
141    /// segments, nothing folded, the newest WAL format this build writes and
142    /// the segment level new namespaces start at ([`segment::DEFAULT_FORMAT`]).
143    pub fn new(schema: Schema) -> Self {
144        Self {
145            format_version: FORMAT_VERSION,
146            schema,
147            live_segments: Vec::new(),
148            wal_folded_through: 0,
149            wal_format: wal::FORMAT_VERSION,
150            segment_format: segment::DEFAULT_FORMAT,
151            indexes: BTreeMap::new(),
152            sparse_indexes: BTreeMap::new(),
153        }
154    }
155}
156
157/// Object key of a namespace's manifest: `<namespace>/manifest/current.json`.
158///
159/// Does not validate `namespace`; that is [`Namespace`](crate::Namespace)'s job.
160pub fn manifest_path(namespace: &str) -> Path {
161    Path::from(format!("{namespace}/manifest/current.json"))
162}
163
164/// Serialize to JSON bytes, tagging any failure with a label instead of a key
165/// since the object has not been written yet.
166fn encode(manifest: &Manifest) -> Result<Bytes> {
167    serde_json::to_vec(manifest)
168        .map(Bytes::from)
169        .map_err(|source| ItzmaError::Serde {
170            path: "manifest".into(),
171            source,
172        })
173}
174
175/// Write the manifest for a new namespace, failing if one already exists.
176///
177/// Uses `PutMode::Create` (put-if-absent), which the store performs
178/// atomically. When several callers race to create the same id, exactly one
179/// succeeds and the rest see [`ItzmaError::NamespaceExists`].
180///
181/// # Errors
182///
183/// - [`ItzmaError::NamespaceExists`] if the manifest is already there.
184/// - [`ItzmaError::Storage`] for any other backend failure.
185///
186/// # Examples
187///
188/// ```
189/// # #[tokio::main]
190/// # async fn main() -> itzma_core::Result<()> {
191/// use itzma_core::manifest::{self, Manifest};
192/// use itzma_core::{ItzmaError, Metric, Schema};
193/// use object_store::memory::InMemory;
194///
195/// let store = InMemory::new();
196/// let m = Manifest::new(Schema::new(3, Metric::Cosine));
197///
198/// manifest::create(&store, "docs", &m).await?;
199/// let again = manifest::create(&store, "docs", &m).await;
200/// assert!(matches!(again, Err(ItzmaError::NamespaceExists(_))));
201/// # Ok(())
202/// # }
203/// ```
204pub async fn create(store: &dyn ObjectStore, namespace: &str, manifest: &Manifest) -> Result<()> {
205    let opts = PutOptions::from(PutMode::Create);
206    match store
207        .put_opts(&manifest_path(namespace), encode(manifest)?.into(), opts)
208        .await
209    {
210        Ok(_) => Ok(()),
211        Err(object_store::Error::AlreadyExists { .. }) => {
212            Err(ItzmaError::NamespaceExists(namespace.to_string()))
213        }
214        Err(e) => Err(e.into()),
215    }
216}
217
218/// Read and decode the manifest, returning it with the version token needed
219/// to update it conditionally.
220///
221/// The returned [`UpdateVersion`] carries the object's ETag and version id,
222/// whichever the backend provides. Hand it to `PutMode::Update` to say "only
223/// write if nobody changed this since I read it".
224///
225/// # Errors
226///
227/// - [`ItzmaError::NamespaceNotFound`] if there is no manifest.
228/// - [`ItzmaError::Serde`] if the object is not valid manifest JSON. The error
229///   names the object key.
230/// - [`ItzmaError::UnsupportedFormat`] if `format_version` is not
231///   [`FORMAT_VERSION`].
232/// - [`ItzmaError::WalFormatTooNew`] if `wal_format` is above what this build
233///   reads. Every operation on a namespace starts here, so this is the one
234///   place an older build is turned away, and it has written nothing yet.
235/// - [`ItzmaError::SegmentFormatTooNew`] if `segment_format` is above what this
236///   build reads. Checked after the WAL level, and turned away the same way.
237/// - [`ItzmaError::Storage`] for any other backend failure.
238pub async fn load(store: &dyn ObjectStore, namespace: &str) -> Result<(Manifest, UpdateVersion)> {
239    let path = manifest_path(namespace);
240    let result = match store.get(&path).await {
241        Ok(r) => r,
242        Err(object_store::Error::NotFound { .. }) => {
243            return Err(ItzmaError::NamespaceNotFound(namespace.to_string()));
244        }
245        Err(e) => return Err(e.into()),
246    };
247    let version = UpdateVersion {
248        e_tag: result.meta.e_tag.clone(),
249        version: result.meta.version.clone(),
250    };
251    let bytes = result.bytes().await?;
252    let manifest: Manifest =
253        serde_json::from_slice(&bytes).map_err(|source| ItzmaError::Serde {
254            path: path.to_string(),
255            source,
256        })?;
257    if manifest.format_version != FORMAT_VERSION {
258        return Err(ItzmaError::UnsupportedFormat {
259            version: manifest.format_version,
260        });
261    }
262    if manifest.wal_format > wal::FORMAT_VERSION {
263        return Err(ItzmaError::WalFormatTooNew {
264            found: manifest.wal_format,
265            supported: wal::FORMAT_VERSION,
266        });
267    }
268    if manifest.segment_format > segment::FORMAT_VERSION {
269        return Err(ItzmaError::SegmentFormatTooNew {
270            found: manifest.segment_format,
271            supported: segment::FORMAT_VERSION,
272        });
273    }
274    Ok((manifest, version))
275}
276
277/// Atomically change the manifest, unless the closure declines.
278///
279/// Like [`update`], each round loads the current manifest and applies `f`, and
280/// writes the result back with `PutMode::Update` tied to the version that was
281/// read. A lost race restarts the round from a fresh read. The closure may
282/// therefore run several times and **must be re-runnable**.
283///
284/// The closure returns `true` to publish its change and `false` to decline.
285/// Declining writes nothing and returns `Ok(None)`. Compaction uses this to
286/// say "publish my segment only if the manifest still looks the way it did
287/// when I planned it".
288///
289/// # Errors
290///
291/// Same as [`update`]: [`ItzmaError::ManifestContention`] after 32 lost
292/// rounds, anything [`load`] can return, and [`ItzmaError::Storage`] for
293/// backend failures other than a lost race.
294///
295/// # Examples
296///
297/// ```
298/// # #[tokio::main]
299/// # async fn main() -> itzma_core::Result<()> {
300/// use itzma_core::manifest::{self, Manifest};
301/// use itzma_core::{Metric, Schema};
302/// use object_store::memory::InMemory;
303///
304/// let store = InMemory::new();
305/// manifest::create(&store, "docs", &Manifest::new(Schema::new(3, Metric::L2))).await?;
306///
307/// // Publish only if nothing has been folded yet.
308/// let first = manifest::update_if(&store, "docs", |m| {
309///     if m.wal_folded_through != 0 {
310///         return false;
311///     }
312///     m.wal_folded_through = 4;
313///     true
314/// })
315/// .await?;
316/// assert_eq!(first.map(|m| m.wal_folded_through), Some(4));
317///
318/// // The same call now declines.
319/// let second = manifest::update_if(&store, "docs", |m| m.wal_folded_through == 0).await?;
320/// assert!(second.is_none());
321/// # Ok(())
322/// # }
323/// ```
324pub async fn update_if<F>(
325    store: &dyn ObjectStore,
326    namespace: &str,
327    mut f: F,
328) -> Result<Option<Manifest>>
329where
330    F: FnMut(&mut Manifest) -> bool,
331{
332    let path = manifest_path(namespace);
333    for _ in 0..MAX_UPDATE_ATTEMPTS {
334        let (mut manifest, version) = load(store, namespace).await?;
335        if !f(&mut manifest) {
336            return Ok(None);
337        }
338        let opts = PutOptions::from(PutMode::Update(version));
339        match store.put_opts(&path, encode(&manifest)?.into(), opts).await {
340            Ok(_) => return Ok(Some(manifest)),
341            Err(object_store::Error::Precondition { .. }) => continue,
342            Err(e) => return Err(e.into()),
343        }
344    }
345    Err(ItzmaError::ManifestContention {
346        attempts: MAX_UPDATE_ATTEMPTS,
347    })
348}
349
350/// Atomically change the manifest by read, modify, conditional write.
351///
352/// Each round loads the current manifest, applies `f` to it, and writes the
353/// result back with `PutMode::Update` tied to the version that was read. If
354/// another writer got in first the store answers with a precondition failure,
355/// and the round restarts from a fresh read, so `f` runs again on the new
356/// contents. That means `f` may be called several times and **must be
357/// re-runnable**: derive the change from the manifest it is given, and do not
358/// carry state between calls.
359///
360/// The winning manifest is returned. After [`MAX_UPDATE_ATTEMPTS`] lost rounds
361/// the call gives up. Use [`update_if`] when the change should be abandoned
362/// if the manifest is no longer what the caller expected.
363///
364/// # Errors
365///
366/// - [`ItzmaError::ManifestContention`] after 32 lost rounds.
367/// - Anything [`load`] can return.
368/// - [`ItzmaError::Storage`] if the backend rejects the write for any reason
369///   other than a lost race. `LocalFileSystem` does not implement conditional
370///   update, so on that backend this is always a `NotImplemented` storage
371///   error. Use `InMemory` or a cloud store.
372///
373/// # Examples
374///
375/// ```
376/// # #[tokio::main]
377/// # async fn main() -> itzma_core::Result<()> {
378/// use itzma_core::manifest::{self, Manifest};
379/// use itzma_core::{Metric, Schema};
380/// use object_store::memory::InMemory;
381///
382/// let store = InMemory::new();
383/// let m = Manifest::new(Schema::new(3, Metric::L2));
384/// manifest::create(&store, "docs", &m).await?;
385///
386/// let updated = manifest::update(&store, "docs", |m| m.wal_folded_through += 1).await?;
387/// assert_eq!(updated.wal_folded_through, 1);
388/// # Ok(())
389/// # }
390/// ```
391pub async fn update<F>(store: &dyn ObjectStore, namespace: &str, mut f: F) -> Result<Manifest>
392where
393    F: FnMut(&mut Manifest),
394{
395    let outcome = update_if(store, namespace, |m| {
396        f(m);
397        true
398    })
399    .await?;
400    match outcome {
401        Some(manifest) => Ok(manifest),
402        None => unreachable!("the closure above always accepts"),
403    }
404}