uqa-storage-sqlite 0.4.7

SQLite catalog, indexes, compressed storage, graph and key/value providers
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

use rusqlite::params;
use uqa_storage::mvcc::{CommitFailure, CommitSequence, CommitStatus, RecordWrite};

use super::*;

mod admission;
mod diskann;
mod identifiers;
mod receipts;
mod reclamation;
mod runs;

#[test]
fn bounded_value_reads_preserve_sqlite_record_limits_and_retained_versions() {
    let directory = tempfile::tempdir().unwrap();
    let store =
        crate::key_value::SQLiteKeyValueStore::open(&directory.path().join("bounded.db")).unwrap();
    uqa_storage::key_value::conformance::verify_bounded_value_reads(&store).unwrap();
}

fn control() -> StorageReadControl {
    StorageReadControl::with_limit(1 << 24)
}
fn prepared(key: &[u8], value: &[u8], control: &StorageReadControl) -> PreparedRecordCommit {
    PreparedRecordCommit::new(
        &[RecordWrite {
            key,
            expected: None,
            value: Some(value),
        }],
        control,
    )
    .unwrap()
}

#[test]
fn records_require_a_connection_local_permit_that_closes_after_every_operation() {
    let directory = tempfile::tempdir().unwrap();
    let path = directory.path().join("guard.db");
    let connection = ManagedConnection::open(&path).unwrap();
    let store = SQLiteRecordStore::new(&connection).unwrap();
    let control = control();
    store
        .allocate_identifiers(
            b"guard",
            uqa_storage::mvcc::IdentifierRequest::Observe(1),
            &control,
        )
        .unwrap();
    let id = store.allocate_transaction(&control).unwrap();
    store
        .commit(id, &prepared(b"a", b"live", &control), &control)
        .unwrap();
    for sql in [
        "DELETE FROM _uqa_mvcc_versions",
        "INSERT INTO _uqa_mvcc_runs VALUES (8, x'0000000000000000', x'0000000000000001', x'0000000000000001', 0, NULL)",
        "UPDATE _uqa_mvcc_heads SET sequence = x'0000000000000009'",
        "DELETE FROM _uqa_mvcc_metadata",
        "DELETE FROM _uqa_mvcc_transactions",
        "DELETE FROM _uqa_mvcc_identifiers",
    ] {
        assert!(connection
            .with(|connection| {
                connection.execute(sql, [])?;
                Ok(())
            })
            .is_err());
        assert!(rusqlite::Connection::open(&path)
            .unwrap()
            .execute(sql, [])
            .is_err());
    }
    connection
        .with(|connection| {
            assert_eq!(
                connection.query_row("PRAGMA synchronous", [], |row| row.get::<_, i64>(0))?,
                2
            );
            assert_eq!(
                connection.query_row("SELECT __uqa_mvcc_write_permit()", [], |row| row
                    .get::<_, i64>(0))?,
                0
            );
            Ok(())
        })
        .unwrap();
    assert_eq!(
        &***store
            .snapshot(&control)
            .unwrap()
            .get(b"a", &control)
            .unwrap()
            .unwrap()
            .value()
            .unwrap(),
        b"live"
    );
}

#[test]
fn incomplete_or_altered_formats_are_rejected_without_recreation() {
    for sql in [
        "DROP TABLE _uqa_mvcc_versions",
        "DROP TABLE _uqa_mvcc_runs",
        "DROP TRIGGER _uqa_mvcc_runs_UPDATE_guard",
        "DROP TABLE _uqa_mvcc_identifiers",
        "DROP TRIGGER _uqa_mvcc_identifiers_UPDATE_guard",
        "DROP TRIGGER _uqa_mvcc_heads_INSERT_guard",
        "ALTER TABLE _uqa_mvcc_heads ADD COLUMN unrecognized INTEGER",
    ] {
        let connection = ManagedConnection::open_in_memory().unwrap();
        SQLiteRecordStore::new(&connection).unwrap();
        connection
            .with(|connection| {
                connection.execute_batch(sql)?;
                Ok(())
            })
            .unwrap();
        assert!(SQLiteRecordStore::new(&connection).is_err());
        if let Some(table) = sql.strip_prefix("DROP TABLE ") {
            connection
                .with(|connection| {
                    assert_eq!(
                        connection.query_row(
                            "SELECT COUNT(*) FROM sqlite_schema WHERE name = ?1",
                            [table],
                            |row| row.get::<_, i64>(0)
                        )?,
                        0
                    );
                    Ok(())
                })
                .unwrap();
        }
    }
}

#[test]
fn an_active_native_transaction_is_rejected_without_losing_its_session() {
    let connection = ManagedConnection::open_in_memory().unwrap();
    connection.begin_transaction().unwrap();
    assert!(SQLiteRecordStore::new(&connection).is_err());
    assert!(connection.in_transaction());
    connection.rollback_transaction().unwrap();
    SQLiteRecordStore::new(&connection).unwrap();
}

pub(super) fn downgrade_record_format(store: &SQLiteRecordStore, format: i64) {
    store.with(|connection| {
        let _permit = schema::WritePermit::acquire(connection)?;
        let definition: String = connection.query_row("SELECT sql FROM sqlite_schema WHERE name = '_uqa_mvcc_metadata'", [], |row| row.get(0))?;
        assert!(definition.contains("CHECK(format = 54)"));
        let definition = if format < 43 { definition.split(", restore_target BLOB").next().unwrap().to_owned() + ")" } else if format < 44 { definition.split(", receipt_limit INTEGER").next().unwrap().to_owned() + ")" } else { definition };
        if format < 29 {
            assert_eq!(connection.query_row("SELECT count(*) FROM _uqa_mvcc_runs", [], |row| row.get::<_, i64>(0))?, 0);
            connection.execute_batch("DROP TABLE _uqa_mvcc_runs")?;
        }
        if format < 28 {
            connection.execute_batch("INSERT INTO _uqa_mvcc_versions (key, sequence, value) SELECT key, sequence, NULL FROM _uqa_mvcc_heads WHERE compacted = 1; ALTER TABLE _uqa_mvcc_heads DROP COLUMN compacted")?;
        }
        if format < 5 {
            assert_eq!(connection.query_row("SELECT count(*) FROM _uqa_mvcc_identifiers", [], |row| row.get::<_, i64>(0))?, 0);
            connection.execute_batch("DROP TABLE _uqa_mvcc_identifiers")?;
        }
        connection.execute_batch("ALTER TABLE _uqa_mvcc_metadata RENAME TO saved_metadata")?;
        connection.execute_batch(&definition.replace("CHECK(format = 54)", &format!("CHECK(format = {format})")))?;
        let restore = if format < 43 { "" } else if format < 44 { ", restore_target" } else { ", restore_target, receipt_limit" };
        connection.execute_batch(&format!("INSERT INTO _uqa_mvcc_metadata SELECT singleton, {format}, database_id, allocated, sequence, mapping{restore} FROM saved_metadata; DROP TABLE saved_metadata;"))?;
        if format < 44 {
        connection.execute_batch("ALTER TABLE _uqa_mvcc_transactions RENAME TO saved_transactions")?;
        connection.execute_batch(schema::PREVIOUS_TRANSACTIONS)?;
        connection.execute_batch("INSERT INTO _uqa_mvcc_transactions SELECT allocation, CASE status WHEN 3 THEN 1 WHEN 4 THEN 2 ELSE status END, sequence, fingerprint FROM saved_transactions; DROP TABLE saved_transactions;")?;
        for action in ["INSERT", "UPDATE", "DELETE"] { connection.execute_batch(&schema::trigger("_uqa_mvcc_transactions", action).1)?; }
        }
        for action in ["INSERT", "UPDATE", "DELETE"] { connection.execute_batch(&schema::trigger("_uqa_mvcc_metadata", action).1)?; }
        Ok(())
    }).unwrap();
}

#[test]
fn allocated_predecessor_formats_reject_missing_identifier_state_or_guards() {
    for sql in [
        "DROP TABLE _uqa_mvcc_identifiers",
        "DROP TRIGGER _uqa_mvcc_identifiers_INSERT_guard",
    ] {
        let connection = ManagedConnection::open_in_memory().unwrap();
        let store = SQLiteRecordStore::new(&connection).unwrap();
        store
            .allocate_identifiers(
                b"reserved",
                uqa_storage::mvcc::IdentifierRequest::Observe(999),
                &control(),
            )
            .unwrap();
        downgrade_record_format(&store, 5);
        store
            .with(|connection| {
                let _permit = schema::WritePermit::acquire(connection)?;
                connection.execute_batch(sql)?;
                Ok(())
            })
            .unwrap();
        assert!(SQLiteRecordStore::new(&connection).is_err());
        store
            .with(|connection| {
                assert_eq!(
                    connection.query_row("SELECT format FROM _uqa_mvcc_metadata", [], |row| row
                        .get::<_, i64>(0))?,
                    5
                );
                let name = if sql.starts_with("DROP TABLE") {
                    "_uqa_mvcc_identifiers"
                } else {
                    "_uqa_mvcc_identifiers_INSERT_guard"
                };
                assert_eq!(
                    connection.query_row(
                        "SELECT count(*) FROM sqlite_schema WHERE name=?1",
                        [name],
                        |row| row.get::<_, i64>(0)
                    )?,
                    0
                );
                Ok(())
            })
            .unwrap();
    }
}

fn reject_predecessor_access(
    store: &SQLiteRecordStore,
    snapshot: &dyn CommittedRecordSnapshot,
    pending: StorageTransactionId,
    prepared: &PreparedRecordCommit,
    control: &StorageReadControl,
) {
    assert!(matches!(
        store.allocate_transaction(control),
        Err(VersionError::InvalidEncoding("unknown record format"))
    ));
    assert!(matches!(
        snapshot.get(b"migration", control),
        Err(VersionError::InvalidEncoding("unknown record format"))
    ));
    assert!(matches!(
        store.commit(pending, prepared, control),
        Err(CommitFailure::Rejected(VersionError::InvalidEncoding(
            "unknown record format"
        )))
    ));
    assert!(matches!(
        store.abort(pending, control),
        Err(VersionError::InvalidEncoding("unknown record format"))
    ));
}

#[test]
fn record_format_upgrade_preserves_history_identity_allocations_and_receipts() {
    let control = control();
    for (mode, format) in (0..3).flat_map(|mode| (1..=53).map(move |format| (mode, format))) {
        let connection = ManagedConnection::open_in_memory().unwrap();
        if mode == 2 {
            crate::Catalog::open(connection.clone()).unwrap();
        }
        let open = || match mode {
            0 => SQLiteRecordStore::new(&connection),
            1 => SQLiteRecordStore::for_key_value(&connection, &control),
            _ => SQLiteRecordStore::for_native(&connection, &control),
        };
        let store = open().unwrap();
        let transaction = store.allocate_transaction(&control).unwrap();
        let prepared = if mode == 2 {
            PreparedRecordCommit::new(&[], &control).unwrap()
        } else {
            prepared(b"migration", b"preserved", &control)
        };
        let receipt = store.commit(transaction, &prepared, &control).unwrap();
        let pending = store.allocate_transaction(&control).unwrap();
        let snapshot = store.snapshot(&control).unwrap();
        let before = snapshot.scan(b"", None, 64, &control).unwrap();
        if format >= 5 {
            store
                .allocate_identifiers(
                    b"migration-identities",
                    uqa_storage::mvcc::IdentifierRequest::Observe(999),
                    &control,
                )
                .unwrap();
        }
        downgrade_record_format(&store, format);
        reject_predecessor_access(&store, &*snapshot, pending, &prepared, &control);
        let upgraded = open().unwrap();
        if format >= 5 {
            assert_eq!(
                upgraded
                    .allocate_identifiers(
                        b"migration-identities",
                        uqa_storage::mvcc::IdentifierRequest::Observe(0),
                        &control
                    )
                    .unwrap()
                    .watermark(),
                999
            );
        }
        assert_eq!(upgraded.database_id(), store.database_id());
        assert_eq!(
            upgraded.snapshot(&control).unwrap().sequence(),
            snapshot.sequence()
        );
        assert_eq!(
            upgraded.commit_status(transaction, &control).unwrap(),
            CommitStatus::Committed(receipt)
        );
        assert_eq!(
            upgraded.commit_status(pending, &control).unwrap(),
            CommitStatus::Pending
        );
        let after = upgraded
            .snapshot(&control)
            .unwrap()
            .scan(b"", None, 64, &control)
            .unwrap();
        assert_eq!(before.len(), after.len());
        for (old, new) in before.iter().zip(after.iter()) {
            assert_eq!(&*old.key, &*new.key);
            assert_eq!(old.version.sequence(), new.version.sequence());
            assert_eq!(
                old.version.value().map(|value| &***value),
                new.version.value().map(|value| &***value)
            );
        }
        assert!(
            upgraded
                .allocate_transaction(&control)
                .unwrap()
                .allocation()
                > pending.allocation()
        );
        upgraded
            .with(|connection| {
                assert_eq!(
                    connection.query_row("SELECT format FROM _uqa_mvcc_metadata", [], |row| row
                        .get::<_, i64>(0))?,
                    54
                );
                Ok(())
            })
            .unwrap();
        open().unwrap();
    }
}

#[test]
fn failed_record_format_upgrade_restores_the_old_schema_and_allows_repair() {
    for format in 1..=53 {
        let connection = ManagedConnection::open_in_memory().unwrap();
        let store = SQLiteRecordStore::new(&connection).unwrap();
        downgrade_record_format(&store, format);
        store.with(|connection| {
        let _permit = schema::WritePermit::acquire(connection)?;
        connection.execute_batch("PRAGMA ignore_check_constraints = ON; UPDATE _uqa_mvcc_metadata SET mapping = 99; PRAGMA ignore_check_constraints = OFF;")?;
        Ok(())
    }).unwrap();
        assert!(SQLiteRecordStore::new(&connection).is_err());
        store
            .with(|connection| {
                assert_eq!(
                    connection.query_row("SELECT format FROM _uqa_mvcc_metadata", [], |row| row
                        .get::<_, i64>(0))?,
                    format
                );
                assert_eq!(
                connection.query_row(
                    "SELECT count(*) FROM sqlite_schema WHERE name IN ('_uqa_mvcc_previous_metadata', '_uqa_mvcc_identifiers')",
                    [],
                    |row| row.get::<_, i64>(0)
                )?,
                i64::from(format >= 5)
            );
                let _permit = schema::WritePermit::acquire(connection)?;
                connection.execute_batch("UPDATE _uqa_mvcc_metadata SET mapping = 0")?;
                Ok(())
            })
            .unwrap();
        SQLiteRecordStore::new(&connection).unwrap();
    }
}

#[rstest::rstest]
fn closed_record_format_files_upgrade_in_every_sqlite_mode(
    #[values(0, 1, 2, 3)] mode: usize,
    #[values(
        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
    )]
    format: i64,
) {
    closed_record_formats_upgrade(mode, format);
}

#[rstest::rstest]
fn latest_record_format_files_upgrade_in_every_sqlite_mode(
    #[values(0, 1, 2, 3)] mode: usize,
    #[values(46, 47, 48, 49, 50, 51, 52, 53)] format: i64,
) {
    closed_record_formats_upgrade(mode, format);
}

fn closed_record_formats_upgrade(mode: usize, format: i64) {
    let control = control();
    let directory = tempfile::tempdir().unwrap();
    let path = directory.path().join("record-upgrade.db");
    let open = || {
        match mode {
            0 => ManagedConnection::open(&path),
            1 => ManagedConnection::open_encrypted(&path, "record upgrade key"),
            2 => ManagedConnection::open_compressed(
                &path,
                crate::SQLiteCompressionOptions::default(),
            ),
            _ => ManagedConnection::open_compressed_encrypted(
                &path,
                "record upgrade key",
                crate::SQLiteCompressionOptions::default(),
            ),
        }
        .unwrap()
    };
    let (identity, receipt) = {
        let connection = open();
        let store = SQLiteRecordStore::for_key_value(&connection, &control).unwrap();
        let transaction = store.allocate_transaction(&control).unwrap();
        let receipt = store
            .commit(
                transaction,
                &prepared(b"retained", b"original bytes", &control),
                &control,
            )
            .unwrap();
        downgrade_record_format(&store, format);
        (store.database_id(), receipt)
    };
    for _ in 0..2 {
        let connection = open();
        let store = SQLiteRecordStore::for_key_value(&connection, &control).unwrap();
        assert_eq!(store.database_id(), identity);
        assert_eq!(
            store.commit_status(receipt.transaction, &control).unwrap(),
            CommitStatus::Committed(receipt)
        );
        let value = store
            .snapshot(&control)
            .unwrap()
            .get(b"retained", &control)
            .unwrap()
            .unwrap();
        assert_eq!(&***value.value().unwrap(), b"original bytes");
        assert_eq!(value.sequence(), receipt.sequence);
    }
}

#[test]
fn unwinding_rolls_back_physical_changes_and_closes_write_permission() {
    let connection = ManagedConnection::open_in_memory().unwrap();
    let store = SQLiteRecordStore::new(&connection).unwrap();
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _: VersionResult<()> = store.with(|connection| {
            let _permit = schema::WritePermit::acquire(connection)?;
            let transaction = schema::begin(connection)?;
            transaction.execute(
                "UPDATE _uqa_mvcc_metadata SET sequence = ?1",
                params![7_u64.to_be_bytes().as_slice()],
            )?;
            panic!("injected provider unwind");
        });
    }));
    assert!(result.is_err());
    assert_eq!(
        store.snapshot(&control()).unwrap().sequence(),
        CommitSequence::INITIAL
    );
    connection
        .with(|connection| {
            assert_eq!(
                connection.query_row("SELECT __uqa_mvcc_write_permit()", [], |row| row
                    .get::<_, i64>(0))?,
                0
            );
            assert!(connection
                .execute("DELETE FROM _uqa_mvcc_metadata", [])
                .is_err());
            Ok(())
        })
        .unwrap();
}

#[test]
fn unsigned_allocations_and_sequences_reach_their_limit_without_wrapping() {
    let connection = ManagedConnection::open_in_memory().unwrap();
    let store = SQLiteRecordStore::new(&connection).unwrap();
    let control = control();
    let first = store.allocate_transaction(&control).unwrap();
    store
        .with(|connection| {
            let _permit = schema::WritePermit::acquire(connection)?;
            connection.execute(
                "UPDATE _uqa_mvcc_metadata SET allocated = ?1, sequence = ?1",
                params![(u64::MAX - 1).to_be_bytes().as_slice()],
            )?;
            Ok(())
        })
        .unwrap();
    let last = store.allocate_transaction(&control).unwrap();
    assert_eq!(last.allocation(), u64::MAX);
    let receipt = store
        .commit(first, &prepared(b"a", b"last", &control), &control)
        .unwrap();
    assert_eq!(receipt.sequence, CommitSequence::from_u64(u64::MAX));
    assert!(matches!(
        store.allocate_transaction(&control),
        Err(VersionError::TransactionIdsExhausted)
    ));
    assert!(matches!(
        store.commit(last, &prepared(b"b", b"never", &control), &control),
        Err(CommitFailure::Rejected(VersionError::SequenceExhausted))
    ));
    assert!(store
        .snapshot(&control)
        .unwrap()
        .get(b"b", &control)
        .unwrap()
        .is_none());
    assert_eq!(store.abort(last, &control).unwrap(), CommitStatus::Aborted);
}

#[test]
fn sqlite_full_rolls_back_partial_staging_and_preserves_the_pending_receipt() {
    let connection = ManagedConnection::open_in_memory().unwrap();
    let store = SQLiteRecordStore::new(&connection).unwrap();
    let control = control();
    let id = store.allocate_transaction(&control).unwrap();
    connection
        .with(|connection| {
            let pages: i64 = connection.query_row("PRAGMA page_count", [], |row| row.get(0))?;
            connection.pragma_update(None, "max_page_count", pages)?;
            Ok(())
        })
        .unwrap();
    let large = vec![8; 1 << 20];
    let prepared = PreparedRecordCommit::new(
        &[
            RecordWrite {
                key: b"a",
                expected: None,
                value: Some(b"small"),
            },
            RecordWrite {
                key: b"z",
                expected: None,
                value: Some(&large),
            },
        ],
        &control,
    )
    .unwrap();
    assert!(matches!(
        store.commit(id, &prepared, &control),
        Err(CommitFailure::Rejected(VersionError::Storage(_)))
    ));
    assert_eq!(
        store.commit_status(id, &control).unwrap(),
        CommitStatus::Pending
    );
    assert!(store
        .snapshot(&control)
        .unwrap()
        .get(b"a", &control)
        .unwrap()
        .is_none());
    connection
        .with(|connection| {
            connection.pragma_update(None, "max_page_count", 10000)?;
            Ok(())
        })
        .unwrap();
    store.commit(id, &prepared, &control).unwrap();
    assert_eq!(
        &***store
            .snapshot(&control)
            .unwrap()
            .get(b"z", &control)
            .unwrap()
            .unwrap()
            .value()
            .unwrap(),
        large.as_slice()
    );
}