uqa-storage 0.6.2

Document store, inverted index, IVF/HNSW vectors, B-tree, R*Tree, catalog
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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

use std::collections::BTreeMap;

use super::*;
use crate::mvcc::CommitSequence;

type Model = BTreeMap<Vec<u8>, (Option<CommitSequence>, Option<Vec<u8>>)>;

mod cursors;
mod revisions;
mod selection;

#[test]
fn explicit_memory_tier_limit_spills_with_admitted_metadata_and_survives_fork() {
    let control = StorageReadControl::with_limit(64 * 1024);
    let original = PrivateRecordChanges::with_memory_tier_limit(control.memory(), 0);
    let mut expected = Model::new();
    for index in 0..32 {
        stage(
            &original,
            &mut expected,
            index,
            Some("value".into()),
            &control,
        );
        assert!(original.owner.state.lock().records.len() <= 1);
    }
    assert!(spilled_runs(&original) > 0);
    let before = original.snapshot().unwrap();
    let fork = original.fork();
    let mut forked = expected.clone();
    for index in 32..64 {
        stage(&fork, &mut forked, index, Some("fork".into()), &control);
        assert!(fork.owner.state.lock().records.len() <= 1);
    }
    assert_matches(&before, &expected, &control);
    assert_matches(&original.snapshot().unwrap(), &expected, &control);
    assert_matches(&fork.snapshot().unwrap(), &forked, &control);
    let savepoint = StorageSavepointId::allocate();
    fork.savepoint(savepoint).unwrap();
    stage(&fork, &mut forked, 64, Some("later".into()), &control);
    fork.rollback_to_savepoint(savepoint).unwrap();
    forked.remove(&key(64));
    for index in 64..68 {
        stage(
            &fork,
            &mut forked,
            index,
            Some("after undo".into()),
            &control,
        );
        assert!(fork.owner.state.lock().records.len() <= 1);
    }
    assert_matches(&fork.snapshot().unwrap(), &forked, &control);
    fork.rollback().unwrap();
    forked.clear();
    for index in 68..72 {
        stage(
            &fork,
            &mut forked,
            index,
            Some("after rollback".into()),
            &control,
        );
        assert!(fork.owner.state.lock().records.len() <= 1);
    }
    assert!(spilled_runs(&fork) > 0);
    assert_matches(&fork.snapshot().unwrap(), &forked, &control);
    assert_matches(&before, &expected, &control);
    assert_matches(&original.snapshot().unwrap(), &expected, &control);
    assert!(control.memory().used() <= 64 * 1024);
}

#[test]
fn forked_private_roots_share_prefix_and_undo_independently() {
    let control = StorageReadControl::with_limit(1 << 20);
    let original = PrivateRecordChanges::new(control.memory());
    let mut initial = Model::new();
    for index in 0..512 {
        stage(
            &original,
            &mut initial,
            index,
            Some("x".repeat(2048)),
            &control,
        );
    }
    assert!(spilled_runs(&original) > 0);
    let used = control.memory().used();
    let fork = original.fork();
    assert_eq!(control.memory().used(), used);
    let savepoint = StorageSavepointId::allocate();
    fork.savepoint(savepoint).unwrap();
    let mut forked = initial.clone();
    stage(&fork, &mut forked, 0, None, &control);
    stage(&fork, &mut forked, 512, Some("fork".into()), &control);
    let mut changed = initial.clone();
    stage(
        &original,
        &mut changed,
        1,
        Some("original".into()),
        &control,
    );
    assert_matches(&fork.snapshot().unwrap(), &forked, &control);
    assert_matches(&original.snapshot().unwrap(), &changed, &control);
    fork.rollback_to_savepoint(savepoint).unwrap();
    assert_matches(&fork.snapshot().unwrap(), &initial, &control);
    assert_matches(&original.snapshot().unwrap(), &changed, &control);
}

fn key(index: usize) -> Vec<u8> {
    format!("k{index:06}").into_bytes()
}

fn expected(index: usize) -> Option<CommitSequence> {
    index
        .is_multiple_of(2)
        .then(|| CommitSequence::from_u64(index as u64 + 1))
}

/// Stage one change of key `index` and record it in `model`.
fn stage(
    changes: &PrivateRecordChanges,
    model: &mut Model,
    index: usize,
    value: Option<String>,
    control: &StorageReadControl,
) {
    let write = PreparedRecordWrite::copy_bytes(
        &key(index),
        expected(index),
        value.as_deref().map(str::as_bytes),
        control,
    )
    .unwrap();
    changes.apply_owned(&[write], control).unwrap();
    model.insert(key(index), (expected(index), value.map(String::into_bytes)));
}

fn spilled_runs(changes: &PrivateRecordChanges) -> usize {
    changes.owner.state.lock().runs.len()
}

#[test]
fn metadata_reads_skip_spilled_values_and_preserve_live_deleted_and_shadowed_revisions() {
    use super::run::read_counts;
    use crate::mvcc::{MemoryVersionStore, MergedRecordSnapshot, RecordMetadata};

    let control = StorageReadControl::with_limit(512 << 10);
    let changes = PrivateRecordChanges::new(control.memory());
    let mut model = Model::new();
    for id in 0..32 {
        stage(
            &changes,
            &mut model,
            id,
            (id != 1).then(|| "x".repeat(64 << 10)),
            &control,
        );
    }
    assert!(spilled_runs(&changes) > 0);
    let store = MemoryVersionStore::new(&MemoryBudget::new(1 << 20));
    let committed = std::sync::Arc::new(store.snapshot().unwrap());
    let captured = MergedRecordSnapshot::new(committed.clone(), changes.snapshot().unwrap());
    let read = StorageReadControl::with_limit(4 << 10);
    read_counts::take();
    for (id, live) in [(0, true), (1, false), (31, true)] {
        assert_eq!(
            captured.metadata(&key(id), &read).unwrap(),
            Some(RecordMetadata {
                revision: expected(id),
                live
            })
        );
    }
    assert!(captured.metadata(b"missing", &read).unwrap().is_none());
    let counts = read_counts::take();
    assert!(
        counts.entries > 0,
        "metadata must have reached the spilled entry file"
    );
    assert_eq!(counts.values, 0, "metadata must not read the value file");
    assert!(
        captured.get(&key(0), &read).is_err(),
        "the payload exceeds this read allowance"
    );
    stage(&changes, &mut model, 0, None, &control);
    stage(&changes, &mut model, 1, Some("new".into()), &control);
    let current = MergedRecordSnapshot::new(committed, changes.snapshot().unwrap());
    assert!(!current.metadata(&key(0), &read).unwrap().unwrap().live);
    assert!(current.metadata(&key(1), &read).unwrap().unwrap().live);
    assert!(captured.metadata(&key(0), &read).unwrap().unwrap().live);
    assert!(!captured.metadata(&key(1), &read).unwrap().unwrap().live);
}

/// Every read of `snapshot` agrees with `model`.
fn assert_matches(snapshot: &PrivateRecordSnapshot, model: &Model, control: &StorageReadControl) {
    for (key, (expected, value)) in model {
        let write = snapshot.get(key, control).unwrap().unwrap();
        assert_eq!(write.expected(), *expected);
        assert_eq!(write.value(), value.as_deref());
    }
    assert!(snapshot.get(b"k", control).unwrap().is_none());
    assert!(snapshot.get(b"z", control).unwrap().is_none());
    // Pages of a bounded size, as readers take them.
    let mut expected_entries = model.iter();
    let mut after: Option<Vec<u8>> = None;
    loop {
        let page = snapshot.scan(b"k", after.as_deref(), 256, control).unwrap();
        if page.is_empty() {
            break;
        }
        for write in page.iter() {
            let (key, (expected, value)) = expected_entries.next().unwrap();
            assert_eq!(write.key(), key.as_slice());
            assert_eq!(write.expected(), *expected);
            assert_eq!(write.value(), value.as_deref());
        }
        after = page.last().map(|write| write.key().to_vec());
    }
    assert!(expected_entries.next().is_none());
    let after = model.keys().nth(model.len() / 2).unwrap();
    let keys = snapshot.scan_keys(b"k", Some(after), 10, control).unwrap();
    let expected_keys = model
        .keys()
        .filter(|key| *key > after)
        .take(10)
        .collect::<Vec<_>>();
    assert_eq!(
        keys.iter().map(PrivateRecordKey::key).collect::<Vec<_>>(),
        expected_keys
            .iter()
            .map(|key| key.as_slice())
            .collect::<Vec<_>>()
    );
    let last = snapshot
        .last_before(b"k", Some(after), control)
        .unwrap()
        .unwrap();
    assert_eq!(
        last.key(),
        model
            .range(..after.clone())
            .next_back()
            .unwrap()
            .0
            .as_slice()
    );
}

#[test]
fn resident_cursor_borrows_keys_without_allocating_merge_scratch() {
    let control = StorageReadControl::with_limit(1 << 20);
    let changes = PrivateRecordChanges::new(control.memory());
    for key in [b"before".as_slice(), b"first", b"second"] {
        changes
            .apply(
                &[RecordWrite {
                    key,
                    expected: None,
                    value: Some(key),
                }],
                &control,
            )
            .unwrap();
    }
    let state = changes.owner.state.lock();
    let allocation = allocation_counter::measure(|| {
        let mut cursor = TieredCursor::new(
            Some(&state.records),
            &state.runs,
            std::ops::Bound::Included(b"first".as_slice()),
            &control,
        )
        .unwrap();
        for expected in [b"first".as_slice(), b"second"] {
            assert_eq!(cursor.next(&control).unwrap().unwrap().key(), expected);
        }
        assert!(cursor.next(&control).unwrap().is_none());
        assert!(cursor.next(&control).unwrap().is_none());
    });
    assert_eq!(allocation.count_total, 0);
    assert_eq!(allocation.bytes_total, 0);
}

#[test]
fn shared_changes_keep_one_strong_counter_until_the_final_owner_drops() {
    let memory = MemoryBudget::new(1024);
    let bytes = size_of::<Owner>() + size_of::<usize>();
    let mut changes = None;
    let allocated = allocation_counter::measure(|| {
        changes = Some(PrivateRecordChanges::new(&memory));
    });
    assert_eq!(allocated.count_total, 1);
    assert_eq!(allocated.bytes_total, bytes as u64);
    let retained = changes.as_ref().unwrap().share_owner();
    let shared = allocation_counter::measure(|| drop(changes));
    assert_eq!(shared.count_total, 0);
    assert_eq!(shared.bytes_current, 0);
    let released = allocation_counter::measure(|| drop(retained));
    assert_eq!(released.count_current, -1);
    assert_eq!(released.bytes_current, -(bytes as i64));
}

#[test]
fn a_transaction_larger_than_its_allowance_spills_and_reads_its_newest_changes() {
    let control = StorageReadControl::with_limit(1 << 20);
    let changes = PrivateRecordChanges::new(control.memory());
    let mut model = Model::new();
    for index in 0..12_000 {
        stage(
            &changes,
            &mut model,
            index,
            Some(format!("first {index}")),
            &control,
        );
    }
    for index in (0..12_000).step_by(3) {
        stage(
            &changes,
            &mut model,
            index,
            Some(format!("second {index}")),
            &control,
        );
    }
    for index in (0..12_000).step_by(7) {
        stage(&changes, &mut model, index, None, &control);
    }
    assert!(spilled_runs(&changes) > 0);
    // Merging bounds the runs: fewer than FAN_IN in each size class.
    assert!(
        spilled_runs(&changes) < 12,
        "{} runs",
        spilled_runs(&changes)
    );
    assert!(control.memory().used() < control.memory().limit() / 2);
    assert_matches(&changes.snapshot().unwrap(), &model, &control);
    // The final changes of a spilled transaction are a spilled run, read one block at a time.
    let prepared = changes.prepare(&control).unwrap();
    assert!(prepared.resident().is_none());
    assert_eq!(prepared.len(), model.len());
    let mut writes = prepared.writes();
    for (key, (expected, value)) in &model {
        let write = writes.next(&control).unwrap().unwrap();
        assert_eq!(write.key(), key.as_slice());
        assert_eq!(write.expected(), *expected);
        assert_eq!(write.value(), value.as_deref());
    }
    assert!(writes.next(&control).unwrap().is_none());
}

#[test]
fn savepoints_and_command_views_keep_the_tiers_they_saw_across_spills() {
    let control = StorageReadControl::with_limit(1 << 20);
    let changes = PrivateRecordChanges::new(control.memory());
    let mut model = Model::new();
    for index in 0..3_000 {
        stage(
            &changes,
            &mut model,
            index,
            Some(format!("before {index}")),
            &control,
        );
    }
    let saved = model.clone();
    let savepoint = StorageSavepointId::allocate();
    changes.savepoint(savepoint).unwrap();
    let view = changes.snapshot().unwrap();
    let runs = spilled_runs(&changes);
    for index in 0..9_000 {
        stage(
            &changes,
            &mut model,
            index,
            Some(format!("after {index}")),
            &control,
        );
    }
    assert!(spilled_runs(&changes) > runs);
    assert_matches(&view, &saved, &control);
    assert_matches(&changes.snapshot().unwrap(), &model, &control);
    changes.rollback_to_savepoint(savepoint).unwrap();
    assert_eq!(spilled_runs(&changes), runs);
    assert_matches(&changes.snapshot().unwrap(), &saved, &control);
    changes.rollback().unwrap();
    assert!(!changes.has_written());
}

#[test]
fn a_repeated_change_keeps_the_precondition_of_its_spilled_first_change() {
    let control = StorageReadControl::with_limit(1 << 20);
    let changes = PrivateRecordChanges::new(control.memory());
    let mut model = Model::new();
    for index in 0..6_000 {
        stage(
            &changes,
            &mut model,
            index,
            Some(format!("value {index}")),
            &control,
        );
    }
    assert!(spilled_runs(&changes) > 0);
    let conflicting = PreparedRecordWrite::copy_bytes(
        &key(0),
        Some(CommitSequence::from_u64(99)),
        Some(b"other"),
        &control,
    )
    .unwrap();
    assert!(matches!(
        changes.apply_owned(&[conflicting], &control),
        Err(VersionError::WriteConflict { mutation: 0, .. })
    ));
    assert!(
        changes.write_kind(&key(0), &control).unwrap()
            == Some(super::super::commit::RecordWriteKind::Canonical)
    );
    stage(&changes, &mut model, 0, Some("again".into()), &control);
    assert_matches(&changes.snapshot().unwrap(), &model, &control);
}