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