itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! The handle's view of a namespace between queries: the manifest
//! it last loaded and the WAL tail it folded on top of it, so a query lists
//! and folds only what is new, and a handle that opted in to a staleness
//! bound skips the manifest GET and the LIST altogether while the view is
//! young.

use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};

use object_store::ObjectStore;

use crate::budget::ReadBudget;
use crate::cpu::Lane;
use crate::error::{ItzmaError, Result};
use crate::layer::{self, Layer};
use crate::manifest::{self, Manifest};
use crate::namespace::is_stale_read;
use crate::{segment, wal};

/// The WAL past one `folded_through`, folded into a layer.
#[derive(Debug, Default)]
pub(crate) struct TailView {
    pub(crate) folded_through: u64,
    /// The last seq folded in, or `folded_through` when the tail is empty.
    pub(crate) last_seq: u64,
    pub(crate) layer: Arc<Layer>,
}

/// The tail past `folded_through`, reusing `base` when it was built on the
/// same `folded_through`: only objects past `base.last_seq` are listed,
/// fetched, charged and folded, onto a copy of its layer. `base` itself is
/// never changed, since queries may still hold it. A base on another
/// `folded_through` is ignored: a compaction moved it, and a fold cannot be
/// undone.
pub(crate) async fn extend(
    store: &dyn ObjectStore,
    namespace: &str,
    base: Option<&Arc<TailView>>,
    folded_through: u64,
    budget: &ReadBudget,
) -> Result<Arc<TailView>> {
    let base = base.filter(|view| view.folded_through == folded_through);
    let from = base.map_or(folded_through, |view| view.last_seq);
    let log = wal::stream_log(store, namespace, from, budget, Lane::Query).await?;
    let (new, last) = layer::fold_log(log).await?;
    let view = match (base, last) {
        (Some(base), None) => return Ok(base.clone()),
        (Some(base), Some(last)) => {
            let mut grown = (*base.layer).clone();
            grown.overlay(new);
            TailView {
                folded_through,
                last_seq: last,
                layer: Arc::new(grown),
            }
        }
        (None, last) => TailView {
            folded_through,
            last_seq: last.unwrap_or(folded_through),
            layer: Arc::new(new),
        },
    };
    Ok(Arc::new(view))
}

/// Load the manifest and check its segment list against the invariant, so
/// every reader fails the same way on a damaged manifest.
pub(crate) async fn load_checked(store: &dyn ObjectStore, namespace: &str) -> Result<Manifest> {
    let (manifest, _version) = manifest::load(store, namespace).await?;
    segment::validate_chain(&manifest.live_segments, manifest.wal_folded_through)?;
    Ok(manifest)
}

/// A snapshot the handle keeps between queries: a manifest and the tail it
/// folded on top of it.
#[derive(Debug)]
struct Snapshot {
    manifest: Arc<Manifest>,
    tail: Arc<TailView>,
    loaded_at: Instant,
}

/// What one query attempt starts from: the manifest it plans against, and
/// in bounded mode the tail it may use as it is. Without one, the tail is
/// read by [`Views::tail`], which the engines run alongside their segment
/// reads.
#[derive(Debug)]
pub(crate) struct Plan {
    pub(crate) manifest: Arc<Manifest>,
    loaded_at: Instant,
    ready: Option<Arc<TailView>>,
}

/// Where a view is read from, and for whom.
pub(crate) struct Reader<'a> {
    /// The manifest is always read here, never through a cache.
    pub(crate) store: &'a dyn ObjectStore,
    /// WAL objects go through the query store, like every query read.
    pub(crate) query_store: &'a dyn ObjectStore,
    pub(crate) namespace: &'a str,
    /// The highest seq this handle's own writes landed at, or anything at or
    /// below the view's `folded_through` when it has written nothing.
    pub(crate) own_last: u64,
    /// The query attempt's budget: the tail shares it with the segments.
    pub(crate) budget: &'a ReadBudget,
}

/// A handle's last snapshot, and the staleness it may be used at.
#[derive(Debug, Default)]
pub(crate) struct Views {
    staleness: Option<Duration>,
    current: Mutex<Option<Arc<Snapshot>>>,
    /// Held while a bounded refresh runs, so concurrent queries past the bound
    /// wait for one refresh instead of each sending their own.
    refreshing: tokio::sync::Mutex<()>,
}

impl Views {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// A bound of zero is strict: a snapshot that is never young would only
    /// make every query wait its turn on the refresh lock.
    pub(crate) fn set_staleness(&mut self, staleness: Option<Duration>) {
        self.staleness = staleness.filter(|bound| !bound.is_zero());
    }

    /// The plan a query starts from. Strict (no staleness): a fresh manifest,
    /// and the tail left to [`tail`](Self::tail), which lists the WAL now.
    /// Bounded: the cached snapshot while it is younger than the bound; past
    /// it, one refresh (manifest and tail) shared by every query waiting on
    /// it.
    pub(crate) async fn plan(&self, r: &Reader<'_>) -> Result<Plan> {
        let Some(max_age) = self.staleness else {
            return fresh_plan(r).await;
        };
        if let Some(snap) = self.young(max_age) {
            return Ok(snap.plan());
        }
        let _turn = self.refreshing.lock().await;
        if let Some(snap) = self.young(max_age) {
            return Ok(snap.plan());
        }
        let plan = fresh_plan(r).await?;
        let base = self.current().map(|snap| snap.tail.clone());
        let folded_through = plan.manifest.wal_folded_through;
        match extend(
            r.query_store,
            r.namespace,
            base.as_ref(),
            folded_through,
            r.budget,
        )
        .await
        {
            Ok(tail) => Ok(self.publish(&plan, tail).plan()),
            // A fence under the manifest just loaded: let the attempt meet it
            // in `tail`, where it reloads like any stale read.
            Err(err) if is_stale_read(&err) => Ok(plan),
            Err(err) => Err(err),
        }
    }

    /// `err` came from an attempt on `stale`. If the manifest moved, the
    /// reader was only behind: plan again on the current one. Otherwise the
    /// object really is missing or the fence really is misplaced, and `err`
    /// comes back as it was.
    pub(crate) async fn replan(
        &self,
        r: &Reader<'_>,
        stale: &Plan,
        err: ItzmaError,
    ) -> Result<Plan> {
        if !is_stale_read(&err) {
            return Err(err);
        }
        let plan = fresh_plan(r).await?;
        if *plan.manifest == *stale.manifest {
            return Err(err);
        }
        Ok(plan)
    }

    /// The tail on `plan`'s manifest. A tail the plan already holds is used
    /// as it is, unless this handle wrote past it (read your own writes);
    /// otherwise the handle's last tail is extended with only what is new,
    /// and the result becomes its snapshot.
    pub(crate) async fn tail(&self, r: &Reader<'_>, plan: &Plan) -> Result<Arc<Layer>> {
        if let Some(ready) = plan.ready.as_ref().filter(|t| r.own_last <= t.last_seq) {
            return Ok(ready.layer.clone());
        }
        let base = match &plan.ready {
            Some(ready) => Some(ready.clone()),
            None => self.current().map(|snap| snap.tail.clone()),
        };
        let folded_through = plan.manifest.wal_folded_through;
        let tail = extend(
            r.query_store,
            r.namespace,
            base.as_ref(),
            folded_through,
            r.budget,
        )
        .await?;
        Ok(self.publish(plan, tail).tail.layer.clone())
    }

    fn young(&self, max_age: Duration) -> Option<Arc<Snapshot>> {
        self.current()
            .filter(|snap| snap.loaded_at.elapsed() < max_age)
    }

    fn current(&self) -> Option<Arc<Snapshot>> {
        self.current
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// Record `tail` on `plan`'s manifest as the handle's snapshot if it is
    /// the newest: a later `folded_through`, then a manifest loaded later
    /// (one that may have changed only its indexes), then more of the same
    /// tail. An own-write fold on an older manifest therefore never puts that
    /// manifest back over a refresh; a later query folds what it lacks. Two
    /// queries racing both produce correct views, and the newer one is kept.
    fn publish(&self, plan: &Plan, tail: Arc<TailView>) -> Arc<Snapshot> {
        let snap = Arc::new(Snapshot {
            manifest: plan.manifest.clone(),
            tail,
            loaded_at: plan.loaded_at,
        });
        let mut current = self.current.lock().unwrap_or_else(PoisonError::into_inner);
        let newer = current.as_ref().is_none_or(|old| snap.rank() >= old.rank());
        if newer {
            *current = Some(snap.clone());
        }
        snap
    }
}

impl Snapshot {
    fn rank(&self) -> (u64, Instant, u64) {
        (self.tail.folded_through, self.loaded_at, self.tail.last_seq)
    }

    fn plan(&self) -> Plan {
        Plan {
            manifest: self.manifest.clone(),
            loaded_at: self.loaded_at,
            ready: Some(self.tail.clone()),
        }
    }
}

/// A plan on a manifest loaded now, with the tail still to read.
async fn fresh_plan(r: &Reader<'_>) -> Result<Plan> {
    let loaded_at = Instant::now();
    let manifest = load_checked(r.store, r.namespace).await?;
    Ok(Plan {
        manifest: Arc::new(manifest),
        loaded_at,
        ready: None,
    })
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::time::{Duration, Instant};

    use object_store::memory::InMemory;
    use object_store::path::Path;

    use super::*;
    use crate::budget::ReadBudget;
    use crate::cpu::Lane;
    use crate::document::{Document, Metric, Schema, WalOp};
    use crate::layer::Layer;
    use crate::manifest::Manifest;

    fn key(view: &TailView) -> (u64, u64) {
        (view.folded_through, view.last_seq)
    }

    fn up(id: &str, v: f32) -> WalOp {
        WalOp::Upsert(Document {
            id: id.into(),
            vector: vec![v],
            attrs: None,
            sparse: None,
        })
    }

    async fn write(store: &InMemory, ops: Vec<WalOp>) -> u64 {
        crate::wal::append(store, "ns", 1, ops).await.unwrap()
    }

    async fn scratch(store: &InMemory, folded: u64) -> Layer {
        let budget = ReadBudget::unlimited();
        let log = crate::wal::stream_log(store, "ns", folded, &budget, Lane::Query)
            .await
            .unwrap();
        crate::layer::fold_log(log).await.unwrap().0
    }

    #[tokio::test]
    async fn an_empty_tail_is_a_view_at_folded_through() {
        let store = InMemory::new();
        let budget = ReadBudget::unlimited();
        let view = extend(&store, "ns", None, 0, &budget).await.unwrap();
        assert_eq!(key(&view), (0, 0));
        assert!(view.layer.is_empty());
    }

    #[tokio::test]
    async fn nothing_new_returns_the_same_view() {
        let store = InMemory::new();
        write(&store, vec![up("a", 1.0)]).await;
        let budget = ReadBudget::unlimited();
        let first = extend(&store, "ns", None, 0, &budget).await.unwrap();
        let again = extend(&store, "ns", Some(&first), 0, &budget)
            .await
            .unwrap();
        assert!(Arc::ptr_eq(&first, &again));
    }

    #[tokio::test]
    async fn extend_applies_deletes_and_reinserts_across_the_split() {
        let store = InMemory::new();
        write(&store, vec![up("a", 1.0), up("b", 1.0)]).await;
        write(&store, vec![WalOp::Delete("c".into())]).await;
        let budget = ReadBudget::unlimited();
        let base = extend(&store, "ns", None, 0, &budget).await.unwrap();
        write(&store, vec![WalOp::Delete("a".into()), up("c", 2.0)]).await;
        write(&store, vec![up("b", 3.0)]).await;
        let grown = extend(&store, "ns", Some(&base), 0, &budget).await.unwrap();
        assert_eq!(grown.last_seq, 4);
        assert_eq!(*grown.layer, scratch(&store, 0).await);
        // The base is untouched: queries still holding it see the old state.
        assert_eq!(base.last_seq, 2);
        assert!(base.layer.holds("a"));
    }

    #[tokio::test]
    async fn a_base_on_another_folded_through_is_ignored() {
        let store = InMemory::new();
        write(&store, vec![up("a", 1.0)]).await;
        write(&store, vec![up("b", 1.0)]).await;
        let budget = ReadBudget::unlimited();
        let old = extend(&store, "ns", None, 0, &budget).await.unwrap();
        let moved = extend(&store, "ns", Some(&old), 1, &budget).await.unwrap();
        assert_eq!(key(&moved), (1, 2));
        assert_eq!(*moved.layer, scratch(&store, 1).await);
    }

    #[tokio::test]
    async fn only_new_objects_are_charged() {
        let store = InMemory::new();
        write(&store, vec![up("a", 1.0)]).await;
        let first = ReadBudget::unlimited();
        let base = extend(&store, "ns", None, 0, &first).await.unwrap();
        write(&store, vec![up("b", 1.0)]).await;
        let second = ReadBudget::unlimited();
        extend(&store, "ns", Some(&base), 0, &second).await.unwrap();
        let both = ReadBudget::unlimited();
        extend(&store, "ns", None, 0, &both).await.unwrap();
        assert!(first.used() > 0 && second.used() > 0);
        assert_eq!(first.used() + second.used(), both.used());
    }

    fn reader<'a>(store: &'a InMemory, own_last: u64, budget: &'a ReadBudget) -> Reader<'a> {
        Reader {
            store,
            query_store: store,
            namespace: "ns",
            own_last,
            budget,
        }
    }

    async fn create(store: &InMemory) {
        let schema = Schema::new(1, Metric::L2);
        crate::Namespace::create(Arc::new(store.clone()), "ns", schema)
            .await
            .unwrap();
    }

    /// Plan, then read the tail, the way a query attempt does.
    async fn view(views: &Views, r: &Reader<'_>) -> (Plan, Arc<Layer>) {
        let plan = views.plan(r).await.unwrap();
        let tail = views.tail(r, &plan).await.unwrap();
        (plan, tail)
    }

    #[tokio::test]
    async fn a_strict_plan_sees_a_write_made_after_the_last_one() {
        let store = InMemory::new();
        create(&store).await;
        let views = Views::new();
        let budget = ReadBudget::unlimited();
        let (_, first) = view(&views, &reader(&store, 0, &budget)).await;
        assert!(first.is_empty());
        write(&store, vec![up("a", 1.0)]).await;
        let (plan, second) = view(&views, &reader(&store, 0, &budget)).await;
        assert!(plan.ready.is_none());
        assert!(second.holds("a"));
    }

    #[tokio::test]
    async fn a_young_bounded_view_is_reused_and_an_own_write_extends_it() {
        let store = InMemory::new();
        create(&store).await;
        let mut views = Views::new();
        views.set_staleness(Some(Duration::from_secs(3600)));
        let budget = ReadBudget::unlimited();
        let (first, _) = view(&views, &reader(&store, 0, &budget)).await;
        let seq = write(&store, vec![up("a", 1.0)]).await;
        // Someone else's write: invisible while the view is young.
        let (same, tail) = view(&views, &reader(&store, 0, &budget)).await;
        assert!(Arc::ptr_eq(&first.manifest, &same.manifest));
        assert!(tail.is_empty());
        // The same seq as this handle's own write: visible at once, on the
        // same manifest.
        let (own, tail) = view(&views, &reader(&store, seq, &budget)).await;
        assert!(tail.holds("a"));
        assert!(Arc::ptr_eq(&own.manifest, &first.manifest));
    }

    #[tokio::test]
    async fn an_old_bounded_view_is_refreshed() {
        let store = InMemory::new();
        create(&store).await;
        let mut views = Views::new();
        views.set_staleness(Some(Duration::from_millis(20)));
        let budget = ReadBudget::unlimited();
        view(&views, &reader(&store, 0, &budget)).await;
        write(&store, vec![up("a", 1.0)]).await;
        tokio::time::sleep(Duration::from_millis(40)).await;
        let (_, fresh) = view(&views, &reader(&store, 0, &budget)).await;
        assert!(fresh.holds("a"));
    }

    #[tokio::test]
    async fn replan_with_an_unchanged_manifest_returns_the_error() {
        let store = InMemory::new();
        create(&store).await;
        let views = Views::new();
        let budget = ReadBudget::unlimited();
        let plan = views.plan(&reader(&store, 0, &budget)).await.unwrap();
        let err = crate::segment::missing(&Path::from("ns/segments/x/data.bin"));
        let back = views
            .replan(&reader(&store, 0, &budget), &plan, err)
            .await
            .unwrap_err();
        assert!(crate::segment::is_missing(&back));
    }

    #[tokio::test]
    async fn a_zero_bound_is_strict() {
        let store = InMemory::new();
        create(&store).await;
        let mut views = Views::new();
        views.set_staleness(Some(Duration::ZERO));
        let budget = ReadBudget::unlimited();
        view(&views, &reader(&store, 0, &budget)).await;
        // Strict plans never carry a ready tail and never wait on the
        // bounded refresh lock.
        let plan = views.plan(&reader(&store, 0, &budget)).await.unwrap();
        assert!(plan.ready.is_none());
    }

    #[test]
    fn a_later_load_on_the_same_fold_wins_over_more_of_an_older_tail() {
        let views = Views::new();
        let older = Plan {
            manifest: Arc::new(Manifest::new(Schema::new(1, Metric::L2))),
            loaded_at: Instant::now(),
            ready: None,
        };
        let mut newer_manifest = Manifest::new(Schema::new(1, Metric::L2));
        newer_manifest.wal_format = 1;
        let newer = Plan {
            manifest: Arc::new(newer_manifest),
            loaded_at: older.loaded_at + Duration::from_millis(1),
            ready: None,
        };
        let tail = |last| {
            Arc::new(TailView {
                folded_through: 0,
                last_seq: last,
                layer: Arc::default(),
            })
        };
        // An own-write fold on the older manifest reached further than a
        // refresh that loaded later: the refresh's manifest is kept, so the
        // snapshot never goes back to an older manifest.
        views.publish(&older, tail(5));
        views.publish(&newer, tail(3));
        let kept = views.current().unwrap();
        assert!(Arc::ptr_eq(&kept.manifest, &newer.manifest));
        // The reverse order keeps it too.
        let views = Views::new();
        views.publish(&newer, tail(3));
        views.publish(&older, tail(5));
        assert!(Arc::ptr_eq(
            &views.current().unwrap().manifest,
            &newer.manifest
        ));
    }

    #[test]
    fn a_view_never_moves_backwards() {
        let views = Views::new();
        let plan = Plan {
            manifest: Arc::new(Manifest::new(Schema::new(1, Metric::L2))),
            loaded_at: Instant::now(),
            ready: None,
        };
        let tail = |folded, last| {
            Arc::new(TailView {
                folded_through: folded,
                last_seq: last,
                layer: Arc::default(),
            })
        };
        views.publish(&plan, tail(0, 5));
        views.publish(&plan, tail(0, 3));
        assert_eq!(key(&views.current().unwrap().tail), (0, 5));
        views.publish(&plan, tail(4, 4));
        assert_eq!(key(&views.current().unwrap().tail), (4, 4));
    }
}