Skip to main content

itzma_core/
wal.rs

1//! The write-ahead log, sequenced by put-if-absent.
2//!
3//! Each write batch becomes one object, `<namespace>/wal/<seq>.json`, where
4//! `<seq>` is a `u64` zero-padded to 20 digits so that listing in key order is
5//! listing in sequence order. Sequence numbers start at 1. The object's
6//! content is binary (`wal_codec.rs`). The `.json` suffix is kept so
7//! that every writer fights for the same key.
8//!
9//! There is no coordinator and no lock. A writer claims a sequence number by
10//! creating that key with `PutMode::Create`, which the object store performs
11//! atomically: of any number of writers racing for the same key, exactly one
12//! wins. A loser learns which seqs are taken by listing, jumps past them, and
13//! tries again. Once the put returns, the batch is durable.
14//!
15//! **Invariant:** a writer only tries seq `n + 1` after it knows `n` exists
16//! (it wrote `n`, or it saw `n` in a listing). So the log is always a
17//! contiguous run with no holes, and [`read_log`] treats a hole as corruption.
18
19use bytes::Bytes;
20use futures::stream::{self, BoxStream, StreamExt, TryStreamExt};
21use object_store::path::Path;
22use object_store::{ObjectStore, ObjectStoreExt, PutMode, PutOptions, PutPayload};
23use serde::{Deserialize, Serialize};
24
25use crate::budget::ReadBudget;
26use crate::cpu::{self, Cost, Lane};
27use crate::document::WalOp;
28use crate::error::{ItzmaError, Result};
29use crate::wal_codec::{self, Peek};
30
31/// The newest WAL object format this build reads, and so the highest
32/// `wal_format` a namespace can hold before this build refuses it.
33/// [`read_log`] reads versions 2 (binary), 3 (binary with an idempotency
34/// key), 4 (binary with a sparse-vector column) and 5 (4 plus a key), and
35/// rejects any other with
36/// [`ItzmaError::UnsupportedFormat`]. A decoded [`WalEntry`] carries the
37/// version of the object it came from. Level 4 (the gate level, not to be
38/// confused with WAL object version 4 above: the two numbering schemes
39/// happen to coincide from here on) adds the fence marker that garbage
40/// collection leaves at the key of an old object, which is not a batch and
41/// never comes out of [`read_log`] except as an error.
42///
43/// [`append`] still writes version 2 for an ordinary batch. A keyed write
44/// produces version 3, needing a namespace at level [`KEYED_FORMAT_VERSION`];
45/// a batch with any sparse vector produces version 4 (or 5 if also keyed),
46/// needing level [`SPARSE_FORMAT_VERSION`].
47pub const FORMAT_VERSION: u32 = SPARSE_FORMAT_VERSION;
48
49/// The WAL format of an object with an idempotency key, and the level a
50/// namespace's `wal_format` must have reached before a keyed write is allowed.
51pub const KEYED_FORMAT_VERSION: u32 = 3;
52
53/// The level a namespace's `wal_format` must have reached before
54/// [`Namespace::gc`](crate::Namespace::gc) may fence WAL objects.
55pub const FENCE_FORMAT_VERSION: u32 = 4;
56
57/// The level a namespace's `wal_format` must have reached before a batch
58/// carrying a sparse vector may be written: WAL object version 4 (or 5,
59/// keyed). A plain batch never needs this level and stays at version 2 (or
60/// 3, keyed) regardless of how high the namespace's level is.
61pub const SPARSE_FORMAT_VERSION: u32 = 5;
62
63/// How many sequence numbers [`append`] tries before giving up with
64/// [`ItzmaError::WriteContention`].
65pub const MAX_APPEND_ATTEMPTS: u32 = 32;
66
67/// The largest batch [`append`] accepts, measured as the uncompressed body of
68/// the object: 64 MiB, about 21,000 vectors of 768 dimensions.
69///
70/// This is a writer policy under the format's own ceiling (a u32 `body_len`,
71/// which readers accept), so it can change without a format version. It sits
72/// well under the default read budget ([`DEFAULT_READ_BUDGET`](crate::DEFAULT_READ_BUDGET))
73/// so that one batch can never be too big for a reader to load. It
74/// was 1 GiB before that. Objects written under the old limit are still
75/// read. A bigger batch is refused with [`ItzmaError::BatchTooLarge`] before
76/// anything is built or written.
77pub const MAX_BODY_BYTES: usize = 64 << 20;
78
79/// A listing that shows a gap is re-listed this many times before erroring,
80/// because a multi-page listing can race a writer.
81const MAX_LIST_ATTEMPTS: u32 = 3;
82const FETCH_CONCURRENCY: usize = 16;
83
84/// The contents of one WAL object: a batch of ops that was committed together.
85///
86/// This is the decoded shape of one object, whichever version it came from:
87/// `format_version` is 2, or 3 for an object with a key.
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89pub struct WalEntry {
90    /// Encoding version of the object this came from: 2, or 3 with a key.
91    pub format_version: u32,
92    /// The idempotency key the batch was written with. Only version 3 objects
93    /// have one.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub key: Option<String>,
96    /// The batch, in the order the caller supplied it. Never empty.
97    pub ops: Vec<WalOp>,
98}
99
100/// A caller-chosen name for one write, so that retrying it does not append the
101/// batch twice.
102///
103/// The key goes into the header of the WAL object. Nothing can tell from the
104/// key alone whether it was used before, so a retry says where to look:
105///
106/// - [`WriteKey::new`] is a first attempt. The batch is written as it is, with
107///   no lookup, one put.
108/// - [`WriteKey::retry`] may be a retry. Before writing, the writer reads the
109///   headers of the WAL objects from `search_from` to the end, and if one
110///   carries the key it returns that object's seq and writes nothing.
111///   `search_from` has to be at or before the original's seq. The last seq the
112///   caller saw committed, plus one, is always safe. `1` is safe too and reads
113///   the whole log.
114///
115/// Either way, a put that runs into the writer's own object at the seq it is
116/// trying (the store's own retry after a lost acknowledgement does this)
117/// recognises it and returns that seq.
118///
119/// A key names one batch. Using it for a different batch is
120/// [`ItzmaError::KeyConflict`] when the two bodies differ in length, and
121/// silently drops the second batch when they do not, so derive keys from the
122/// batch, for example `<job>/<batch number>`.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct WriteKey {
125    /// 1 to 128 bytes. Checked when the write is made, not here.
126    pub key: String,
127    /// Where a retry starts looking for an earlier attempt. `None` skips the
128    /// lookup.
129    pub search_from: Option<u64>,
130}
131
132impl WriteKey {
133    /// A first attempt: no lookup, one put.
134    pub fn new(key: impl Into<String>) -> Self {
135        Self {
136            key: key.into(),
137            search_from: None,
138        }
139    }
140
141    /// A possible retry: look for the key in the WAL objects from
142    /// `search_from` before writing.
143    pub fn retry(key: impl Into<String>, search_from: u64) -> Self {
144        Self {
145            key: key.into(),
146            search_from: Some(search_from),
147        }
148    }
149}
150
151impl WriteKey {
152    /// The key checks that need no storage, so a caller can run them first.
153    pub(crate) fn validate(&self) -> Result<()> {
154        wal_codec::validate_key(&self.key).map(|_| ())
155    }
156}
157
158/// The key and body length of the batch being written, which is what an
159/// earlier object has to match to count as this write.
160#[derive(Clone, Copy)]
161struct Ours<'a> {
162    key: &'a str,
163    body_len: u32,
164}
165
166impl Ours<'_> {
167    /// `found` carries this write's key at `seq`. It is this write if the body
168    /// has the same length, and a reused key if not.
169    fn claim(self, seq: u64, found: &Peek) -> Result<u64> {
170        if found.body_len == self.body_len {
171            Ok(seq)
172        } else {
173            Err(ItzmaError::KeyConflict {
174                key: self.key.to_string(),
175            })
176        }
177    }
178}
179
180/// Key prefix under which a namespace's WAL objects live: `<namespace>/wal`.
181///
182/// Does not validate `namespace`; that is [`Namespace`](crate::Namespace)'s job.
183pub fn wal_prefix(namespace: &str) -> Path {
184    Path::from(format!("{namespace}/wal"))
185}
186
187/// Object key for one WAL entry: `<namespace>/wal/<seq, 20 digits>.json`.
188///
189/// ```
190/// use itzma_core::wal::wal_path;
191///
192/// assert_eq!(
193///     wal_path("docs", 7).as_ref(),
194///     "docs/wal/00000000000000000007.json"
195/// );
196/// ```
197pub fn wal_path(namespace: &str, seq: u64) -> Path {
198    Path::from(format!("{namespace}/wal/{seq:020}.json"))
199}
200
201/// Recover the sequence number from a WAL key, or `None` for anything that is
202/// not `<digits>.json`. Foreign files under `wal/` are skipped, not fatal.
203pub(crate) fn parse_seq(path: &Path) -> Option<u64> {
204    path.filename()?.strip_suffix(".json")?.parse().ok()
205}
206
207/// Commit a batch of ops as the next WAL entry and return its sequence number.
208///
209/// `hint` is where to start probing. Callers keep it at "one past the last seq
210/// I know about", which is right in the common single-writer case and costs
211/// one put. If that seq is taken, the put fails with `AlreadyExists`; the
212/// function then lists the WAL, jumps to one past the highest seq it can see,
213/// and tries again. A stale hint therefore costs an extra listing, never
214/// correctness. A `hint` of 0 is treated as 1, since seq 0 is reserved to mean
215/// "nothing folded".
216///
217/// The batch is written in the binary format (`wal_codec`). The returned seq is
218/// durable: the object exists in the store when this returns. Ops are written
219/// as given; validating them against a schema is the caller's job, except that
220/// the format stores the upserts' vectors as one matrix, so they must all have
221/// the same length.
222///
223/// Storage errors other than a lost race are returned immediately, not
224/// retried. If the call fails after a put whose response was lost (a network
225/// error, say), the entry may in fact exist, so a blind retry can apply the
226/// batch twice. Upserts and deletes are idempotent by id, so replaying in
227/// order is safe, but a replay can overwrite a newer write. [`append_keyed`]
228/// is the write whose retry is a no-op.
229///
230/// # Errors
231///
232/// - [`ItzmaError::EmptyBatch`] if `ops` is empty.
233/// - [`ItzmaError::BatchTooLarge`] if the batch is over [`MAX_BODY_BYTES`].
234/// - [`ItzmaError::DimensionMismatch`] if the upserts' vectors differ in
235///   length.
236/// - [`ItzmaError::Serde`] if an attribute cannot be serialized.
237/// - [`ItzmaError::WriteContention`] after 32 lost races.
238/// - [`ItzmaError::Storage`] for any other backend failure.
239///
240/// # Examples
241///
242/// ```
243/// # #[tokio::main]
244/// # async fn main() -> itzma_core::Result<()> {
245/// use itzma_core::wal;
246/// use itzma_core::{Document, WalOp};
247/// use object_store::memory::InMemory;
248///
249/// let store = InMemory::new();
250/// let op = |id: &str| WalOp::Upsert(Document {
251///     id: id.into(),
252///     vector: vec![1.0],
253///     attrs: None,
254///     sparse: None,
255/// });
256///
257/// assert_eq!(wal::append(&store, "docs", 1, vec![op("a")]).await?, 1);
258/// // A stale hint lands on the next free seq anyway.
259/// assert_eq!(wal::append(&store, "docs", 1, vec![op("b")]).await?, 2);
260/// # Ok(())
261/// # }
262/// ```
263pub async fn append(
264    store: &dyn ObjectStore,
265    namespace: &str,
266    hint: u64,
267    ops: Vec<WalOp>,
268) -> Result<u64> {
269    append_limited(store, namespace, hint, ops, MAX_BODY_BYTES).await
270}
271
272/// [`append`] with the size limit as a parameter, so a test can hit it with a
273/// tiny batch.
274async fn append_limited(
275    store: &dyn ObjectStore,
276    namespace: &str,
277    hint: u64,
278    ops: Vec<WalOp>,
279    max_body: usize,
280) -> Result<u64> {
281    if ops.is_empty() {
282        return Err(ItzmaError::EmptyBatch);
283    }
284    let bytes = wal_codec::encode(&ops, max_body)?;
285    put_encoded(store, namespace, hint, bytes).await
286}
287
288/// Put an object [`wal_codec`] already encoded at the first free seq from
289/// `hint` on, as [`append`] does after encoding.
290pub(crate) async fn put_encoded(
291    store: &dyn ObjectStore,
292    namespace: &str,
293    hint: u64,
294    bytes: Bytes,
295) -> Result<u64> {
296    put_next(store, namespace, hint, bytes, None).await
297}
298
299/// Commit a batch under an idempotency key and return the sequence number it
300/// is at. The retry rules are on [`WriteKey`].
301///
302/// The batch is written as a version 3 object, which a namespace
303/// only takes once its `wal_format` has been raised to
304/// [`KEYED_FORMAT_VERSION`]. This function does not check that, because it
305/// does not read the manifest: [`Namespace::upsert_keyed`](crate::Namespace::upsert_keyed)
306/// does. Called directly on a store, it writes version 3 objects into any log.
307///
308/// `hint` works as for [`append`]. On a `PutMode::Create` collision the writer
309/// reads the header of the object it ran into, and if that object has this
310/// key, the write is already there and its seq is returned.
311///
312/// # Errors
313///
314/// As for [`append`], plus:
315///
316/// - [`ItzmaError::InvalidKey`] unless the key is 1 to 128 bytes.
317/// - [`ItzmaError::KeyConflict`] if an object with this key holds a batch of a
318///   different size. Nothing is written.
319/// - [`ItzmaError::CorruptWal`] or [`ItzmaError::UnsupportedFormat`] if a
320///   header the search reads is damaged.
321///
322/// # Examples
323///
324/// ```
325/// # #[tokio::main]
326/// # async fn main() -> itzma_core::Result<()> {
327/// use itzma_core::wal::{self, WriteKey};
328/// use itzma_core::{Document, WalOp};
329/// use object_store::memory::InMemory;
330///
331/// let store = InMemory::new();
332/// let batch = || vec![WalOp::Upsert(Document {
333///     id: "a".into(),
334///     vector: vec![1.0],
335///     attrs: None,
336///     sparse: None,
337/// })];
338///
339/// let seq = wal::append_keyed(&store, "docs", 1, &WriteKey::new("load-7/batch-1"), batch()).await?;
340///
341/// // The acknowledgement was lost, so the caller tries again from seq 1.
342/// let retry = WriteKey::retry("load-7/batch-1", 1);
343/// assert_eq!(wal::append_keyed(&store, "docs", 1, &retry, batch()).await?, seq);
344/// assert_eq!(wal::read_log(&store, "docs", 0).await?.len(), 1);
345/// # Ok(())
346/// # }
347/// ```
348pub async fn append_keyed(
349    store: &dyn ObjectStore,
350    namespace: &str,
351    hint: u64,
352    write: &WriteKey,
353    ops: Vec<WalOp>,
354) -> Result<u64> {
355    if ops.is_empty() {
356        return Err(ItzmaError::EmptyBatch);
357    }
358    let object = wal_codec::encode_keyed(&ops, MAX_BODY_BYTES, &write.key)?;
359    put_encoded_keyed(store, namespace, hint, write, object).await
360}
361
362/// Put a keyed object [`wal_codec`] already encoded, with [`append_keyed`]'s
363/// search for an earlier attempt and its collision rule.
364pub(crate) async fn put_encoded_keyed(
365    store: &dyn ObjectStore,
366    namespace: &str,
367    hint: u64,
368    write: &WriteKey,
369    object: wal_codec::Keyed,
370) -> Result<u64> {
371    let ours = Ours {
372        key: &write.key,
373        body_len: object.body_len,
374    };
375    if let Some(from) = write.search_from {
376        if let Some(seq) = find_key(store, namespace, from, ours).await? {
377            return Ok(seq);
378        }
379    }
380    put_next(store, namespace, hint, object.bytes, Some(ours)).await
381}
382
383/// Put `bytes` at the first free seq from `hint` on. With `ours`, a collision
384/// with an object that is this write returns its seq instead of moving on.
385async fn put_next(
386    store: &dyn ObjectStore,
387    namespace: &str,
388    hint: u64,
389    bytes: Bytes,
390    ours: Option<Ours<'_>>,
391) -> Result<u64> {
392    // Seq 0 is reserved: listings start strictly after `wal_folded_through`.
393    let mut seq = hint.max(1);
394    for _ in 0..MAX_APPEND_ATTEMPTS {
395        let opts = PutOptions::from(PutMode::Create);
396        let payload = PutPayload::from(bytes.clone());
397        match store
398            .put_opts(&wal_path(namespace, seq), payload, opts)
399            .await
400        {
401            Ok(_) => return Ok(seq),
402            Err(object_store::Error::AlreadyExists { .. }) => {
403                if let Some(ours) = ours {
404                    if let Some(found) = own_object_at(store, namespace, seq, ours).await? {
405                        return Ok(found);
406                    }
407                }
408                seq = next_free_after(store, namespace, seq).await?;
409            }
410            Err(e) => return Err(e.into()),
411        }
412    }
413    Err(ItzmaError::WriteContention {
414        attempts: MAX_APPEND_ATTEMPTS,
415    })
416}
417
418/// The seq of the object at `seq` if it carries `ours`'s key.
419async fn own_object_at(
420    store: &dyn ObjectStore,
421    namespace: &str,
422    seq: u64,
423    ours: Ours<'_>,
424) -> Result<Option<u64>> {
425    match peek_at(store, &wal_path(namespace, seq)).await? {
426        Some(found) if found.key == ours.key => ours.claim(seq, &found).map(Some),
427        _ => Ok(None),
428    }
429}
430
431/// The lowest seq at or after `from` whose object carries `ours`'s key.
432/// Lists the WAL past `from` and reads each object's header, 16 at a time.
433async fn find_key(
434    store: &dyn ObjectStore,
435    namespace: &str,
436    from: u64,
437    ours: Ours<'_>,
438) -> Result<Option<u64>> {
439    let prefix = wal_prefix(namespace);
440    let offset = wal_path(namespace, from.saturating_sub(1));
441    let mut found: Vec<(u64, Path)> = store
442        .list_with_offset(Some(&prefix), &offset)
443        .try_filter_map(|m| async move { Ok(parse_seq(&m.location).map(|seq| (seq, m.location))) })
444        .try_collect()
445        .await?;
446    found.sort_by_key(|(seq, _)| *seq);
447
448    let mut heads = stream::iter(found)
449        .map(|(seq, path)| async move { Ok::<_, ItzmaError>((seq, peek_at(store, &path).await?)) })
450        .buffered(FETCH_CONCURRENCY);
451    while let Some((seq, head)) = heads.try_next().await? {
452        if let Some(found) = head {
453            if found.key == ours.key {
454                return ours.claim(seq, &found).map(Some);
455            }
456        }
457    }
458    Ok(None)
459}
460
461/// The key and body length in an object's header, from a ranged GET of its
462/// first bytes. `None` for an object that has no key.
463async fn peek_at(store: &dyn ObjectStore, path: &Path) -> Result<Option<Peek>> {
464    let head = store
465        .get_range(path, 0..wal_codec::HEADER_PEEK_LEN as u64)
466        .await?;
467    wal_codec::peek_key(path.as_ref(), &head)
468}
469
470/// One past the highest seq at or after `collided`. Lists with an offset, so
471/// only entries newer than the collision are fetched from the store.
472async fn next_free_after(store: &dyn ObjectStore, namespace: &str, collided: u64) -> Result<u64> {
473    let prefix = wal_prefix(namespace);
474    let metas: Vec<_> = store
475        .list_with_offset(Some(&prefix), &wal_path(namespace, collided))
476        .try_collect()
477        .await?;
478    let highest = metas
479        .iter()
480        .filter_map(|m| parse_seq(&m.location))
481        .max()
482        .unwrap_or(collided)
483        .max(collided);
484    Ok(highest + 1)
485}
486
487/// Read every WAL entry after `folded_through`, in sequence order.
488///
489/// Lists the WAL past `folded_through` (exclusive), checks the seqs form an
490/// unbroken run starting at `folded_through + 1`, then fetches and decodes the
491/// objects with up to 16 requests in flight. The result pairs each seq with
492/// its entry and is empty for a namespace that has no un-folded writes.
493///
494/// A listing is not a snapshot: on a store that pages results, a writer can
495/// commit between pages and make a healthy log look like it has a hole. So a
496/// listing that shows a gap is repeated, up to 3 times in total, before the
497/// gap is believed.
498///
499/// Reads are consistent with writes that have already returned: object-store
500/// listings are strongly consistent, so an entry that [`append`] has returned
501/// for will appear.
502///
503/// # Errors
504///
505/// - [`ItzmaError::WalGap`] if the seqs are not contiguous.
506/// - [`ItzmaError::UnsupportedFormat`] if an object's version is neither 2
507///   nor 3.
508/// - [`ItzmaError::CorruptWal`] if an object is damaged or is not a WAL
509///   object at all (bad magic). The error names
510///   the object key. So does a fence inside the range, since it holds
511///   no batch: a namespace whose old objects were fenced can be read only from
512///   its fold point on.
513/// - [`ItzmaError::Storage`] for any backend failure.
514///
515/// # Examples
516///
517/// ```
518/// # #[tokio::main]
519/// # async fn main() -> itzma_core::Result<()> {
520/// use itzma_core::WalOp;
521/// use itzma_core::wal;
522/// use object_store::memory::InMemory;
523///
524/// let store = InMemory::new();
525/// let ops = vec![WalOp::Delete("a".into())];
526/// wal::append(&store, "docs", 1, ops.clone()).await?;
527///
528/// let log = wal::read_log(&store, "docs", 0).await?;
529/// assert_eq!(log.len(), 1);
530/// assert_eq!(log[0].0, 1);
531/// assert_eq!(log[0].1.ops, ops);
532///
533/// // Entries at or below `folded_through` are skipped.
534/// assert!(wal::read_log(&store, "docs", 1).await?.is_empty());
535/// # Ok(())
536/// # }
537/// ```
538pub async fn read_log(
539    store: &dyn ObjectStore,
540    namespace: &str,
541    folded_through: u64,
542) -> Result<Vec<(u64, WalEntry)>> {
543    let budget = ReadBudget::unlimited();
544    stream_log(store, namespace, folded_through, &budget, Lane::Maintenance)
545        .await?
546        .try_collect()
547        .await
548}
549
550/// List the WAL past `folded_through` and check it is one unbroken run, then
551/// return its entries as a stream in seq order, fetched 16 at a time. The
552/// caller folds each entry as it arrives, so the tail is never held twice.
553/// Every object is charged to `budget` before its body is read.
554///
555/// The listing and the gap check are [`read_log`]'s, including the repeat
556/// listings before a gap is believed. Errors from fetching or decoding an
557/// object come out of the stream.
558pub(crate) async fn stream_log<'a>(
559    store: &'a dyn ObjectStore,
560    namespace: &str,
561    folded_through: u64,
562    budget: &'a ReadBudget,
563    lane: Lane,
564) -> Result<BoxStream<'a, Result<(u64, WalEntry)>>> {
565    let found = list_tail(store, namespace, folded_through).await?;
566    Ok(
567        stream::iter(found)
568            .map(move |(seq, path)| async move {
569                Ok((seq, fetch_one(store, &path, budget, lane).await?))
570            })
571            .buffered(FETCH_CONCURRENCY)
572            .boxed(),
573    )
574}
575
576async fn list_tail(
577    store: &dyn ObjectStore,
578    namespace: &str,
579    folded_through: u64,
580) -> Result<Vec<(u64, Path)>> {
581    let prefix = wal_prefix(namespace);
582    let offset = wal_path(namespace, folded_through);
583    let mut gap = (0, 0);
584    for _ in 0..MAX_LIST_ATTEMPTS {
585        let mut found: Vec<(u64, Path)> = store
586            .list_with_offset(Some(&prefix), &offset)
587            .try_filter_map(
588                |m| async move { Ok(parse_seq(&m.location).map(|seq| (seq, m.location))) },
589            )
590            .try_collect()
591            .await?;
592        found.sort_by_key(|(seq, _)| *seq);
593
594        let mismatch = found
595            .iter()
596            .zip(folded_through + 1..)
597            .find(|((seq, _), want)| seq != want)
598            .map(|((seq, _), want)| (want, *seq));
599        match mismatch {
600            None => return Ok(found),
601            Some(g) => gap = g,
602        }
603    }
604    Err(ItzmaError::WalGap {
605        expected: gap.0,
606        found: gap.1,
607    })
608}
609
610/// GET and decode one object. The charge is made as soon as the header is in
611/// hand, from the first bytes of the same response, so a bigger object than
612/// the budget allows is not downloaded to the end. A binary object is charged
613/// the larger of its size and its declared `body_len` (a compressed object
614/// decodes to `body_len`).
615async fn fetch_one(
616    store: &dyn ObjectStore,
617    path: &Path,
618    budget: &ReadBudget,
619    lane: Lane,
620) -> Result<WalEntry> {
621    let got = store.get(path).await?;
622    let size = got.meta.size;
623    let mut chunks = got.into_stream();
624    let mut bytes: Vec<u8> = Vec::new();
625    let mut charged = false;
626    while let Some(chunk) = chunks.try_next().await? {
627        bytes.extend_from_slice(&chunk);
628        if !charged && bytes.len() >= wal_codec::HEADER_LEN {
629            charge(budget, path, size, &bytes)?;
630            charged = true;
631        }
632    }
633    if !charged {
634        charge(budget, path, size, &bytes)?;
635    }
636    let cost = decode_cost(path.as_ref(), &bytes);
637    let path = path.clone();
638    cpu::run(lane, cost, move || decode_object(&path, &bytes)).await
639}
640
641/// What decoding `bytes` costs: a compressed object decodes to its declared
642/// `body_len`, which can be hundreds of times its stored size.
643fn decode_cost(path: &str, bytes: &[u8]) -> Cost {
644    let declared = wal_codec::declared_body_len(path, bytes)
645        .ok()
646        .flatten()
647        .and_then(|n| usize::try_from(n).ok())
648        .unwrap_or(0);
649    Cost::Bytes(bytes.len().max(declared))
650}
651
652fn charge(budget: &ReadBudget, path: &Path, size: u64, prefix: &[u8]) -> Result<()> {
653    let declared = wal_codec::declared_body_len(path.as_ref(), prefix)?.unwrap_or(0);
654    budget.charge(path.as_ref(), size.max(declared))
655}
656
657/// Version 2 and 3 objects start with the `ITZW` magic, and a fence with `ITZF`,
658/// which is not a batch and comes back as [`wal_codec::fenced`]. Anything
659/// else is [`ItzmaError::CorruptWal`] ("bad magic").
660fn decode_object(path: &Path, bytes: &[u8]) -> Result<WalEntry> {
661    if wal_codec::is_fence(bytes) {
662        wal_codec::check_fence(path.as_ref(), bytes)?;
663        return Err(wal_codec::fenced(path.as_ref()));
664    }
665    wal_codec::decode(path.as_ref(), bytes)
666}
667
668#[cfg(test)]
669mod tests {
670    use futures::TryStreamExt;
671    use object_store::memory::InMemory;
672
673    use super::*;
674    use crate::document::Document;
675
676    fn op(id: &str) -> WalOp {
677        WalOp::Upsert(Document {
678            id: id.into(),
679            vector: vec![1.0, 2.0],
680            attrs: None,
681            sparse: None,
682        })
683    }
684
685    #[test]
686    fn a_compressed_object_costs_what_it_decodes_to() {
687        // Ten thousand copies of one document: ZSTD shrinks the body a lot.
688        let ops: Vec<WalOp> = (0..10_000).map(|i| op(&format!("d{i:05}"))).collect();
689        let bytes = wal_codec::encode(&ops, usize::MAX).unwrap();
690        let body = wal_codec::declared_body_len("p", &bytes).unwrap().unwrap();
691        assert!(body > bytes.len() as u64 * 4, "the body compressed");
692        let cost = decode_cost("p", &bytes).units();
693        assert_eq!(cost, crate::cpu::Cost::Bytes(body as usize).units());
694    }
695
696    #[tokio::test]
697    async fn a_batch_over_the_limit_is_refused_and_the_store_is_untouched() {
698        let store = InMemory::new();
699        append(&store, "ns", 1, vec![op("a")]).await.unwrap();
700        let before: Vec<_> = store.list(None).try_collect().await.unwrap();
701
702        let err = append_limited(&store, "ns", 2, vec![op("b")], 8)
703            .await
704            .unwrap_err();
705        assert!(
706            matches!(err, ItzmaError::BatchTooLarge { max: 8, .. }),
707            "{err:?}"
708        );
709
710        let after: Vec<_> = store.list(None).try_collect().await.unwrap();
711        assert_eq!(before, after);
712    }
713
714    #[test]
715    fn the_build_reads_fences_and_says_so() {
716        assert_eq!(FENCE_FORMAT_VERSION, 4);
717        assert_eq!(SPARSE_FORMAT_VERSION, 5);
718        assert_eq!(FORMAT_VERSION, SPARSE_FORMAT_VERSION);
719    }
720
721    #[test]
722    fn a_fence_decodes_to_the_fenced_error() {
723        let path = wal_path("ns", 1);
724        let err = decode_object(&path, &wal_codec::fence()).unwrap_err();
725        assert!(wal_codec::is_fenced(&err), "{err:?}");
726    }
727
728    #[test]
729    fn a_damaged_fence_is_not_the_fenced_error() {
730        let path = wal_path("ns", 1);
731        let mut longer = wal_codec::fence().to_vec();
732        longer.push(0);
733        let err = decode_object(&path, &longer).unwrap_err();
734        assert!(matches!(err, ItzmaError::CorruptWal { .. }), "{err:?}");
735        assert!(!wal_codec::is_fenced(&err));
736    }
737
738    #[tokio::test]
739    async fn read_log_stops_at_a_fence_inside_its_range() {
740        let store = InMemory::new();
741        append(&store, "ns", 1, vec![op("a")]).await.unwrap();
742        append(&store, "ns", 2, vec![op("b")]).await.unwrap();
743        store
744            .put(&wal_path("ns", 1), wal_codec::fence().into())
745            .await
746            .unwrap();
747
748        let err = read_log(&store, "ns", 0).await.unwrap_err();
749        assert!(wal_codec::is_fenced(&err), "{err:?}");
750        // From the fold point on, the fence is not in range.
751        let tail = read_log(&store, "ns", 1).await.unwrap();
752        assert_eq!(tail.len(), 1);
753        assert_eq!(tail[0].0, 2);
754    }
755}