uqa-storage-sqlite 0.6.0

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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Connection clones and store handles share one logical transaction context.

use uqa_storage::mvcc::{DatabaseId, VersionError, VersionedSessionOptions};
use uqa_storage::read_control::StorageReadControl;
use uqa_storage::StorageBackendResult;

use super::{
    Arc, Connection, KeyValueStore, ManagedConnection, Result, SQLiteError, SessionState,
    VersionedKeyValueStore,
};

pub(super) struct BoundRecordSession {
    pub(super) store: Arc<VersionedKeyValueStore>,
    /// Stable native data namespace, separate from the store's transaction history identity.
    pub(super) native: Option<DatabaseId>,
}

impl std::ops::Deref for BoundRecordSession {
    type Target = VersionedKeyValueStore;

    fn deref(&self) -> &Self::Target {
        &self.store
    }
}

impl BoundRecordSession {
    pub(super) fn new_session_with_cancellation(
        &self,
        cancellation: &uqa_core::CancellationToken,
    ) -> Self {
        Self {
            store: Arc::new(self.store.new_session_with_cancellation(cancellation)),
            native: self.native,
        }
    }
}

impl ManagedConnection {
    pub(crate) fn require_sequence_value_durability(&self) -> Result<()> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.read();
        if let Some(logical) = self.session.logical.get() {
            logical.require_sequence_value_durability()?;
        }
        Ok(())
    }

    pub(crate) fn new_sequence_value_session(
        &self,
        cancellation: &uqa_core::CancellationToken,
    ) -> Result<Self> {
        cancellation.check()?;
        let _gate = self.session.gate.read();
        let session = SessionState::with_cancellation(cancellation.clone());
        if let Some(logical) = self.session.logical.get() {
            let _ = session.logical.set(Arc::new(BoundRecordSession {
                store: Arc::new(logical.new_sequence_value_session(cancellation)),
                native: logical.native,
            }));
        }
        Ok(Self {
            pool: Arc::clone(&self.pool),
            session: Arc::new(session),
            record_access: self.record_access,
        })
    }

    pub(crate) fn completed_commit(&self) -> Option<uqa_storage::mvcc::CommitReceipt> {
        // An optional cache hint must not consume the next operation's cleanup diagnostic.
        if self.session.cleanup_failure.lock().is_some() {
            return None;
        }
        let _gate = self.session.gate.read();
        self.session.logical.get()?.completed_commit()
    }

    pub(crate) fn committed_data_revision(&self) -> Option<uqa_storage::CommittedDataRevision> {
        if self.session.cleanup_failure.lock().is_some() {
            return None;
        }
        let _gate = self.session.gate.read();
        self.session
            .logical
            .get()
            .and_then(|logical| logical.committed_data_revision())
    }

    pub(crate) fn snapshot_registry(
        &self,
        identity: DatabaseId,
    ) -> uqa_storage::mvcc::VersionResult<Arc<uqa_storage::mvcc::SnapshotRegistry>> {
        let mut retained = self.pool.snapshot_registry.lock();
        if let Some((old_identity, registry)) = retained.as_ref() {
            if let Some(registry) = registry.upgrade() {
                if *old_identity != identity {
                    return Err(VersionError::WrongDatabase);
                }
                return Ok(registry);
            }
        }
        let registry = Arc::new(uqa_storage::mvcc::SnapshotRegistry::default());
        *retained = Some((identity, Arc::downgrade(&registry)));
        Ok(registry)
    }

    /// Create an independent logical session over the same database pool.
    /// Explicit transactions started on either session are isolated and never
    /// capture operations issued through the other session.
    #[must_use]
    pub fn new_session(&self) -> Self {
        self.new_session_with_cancellation(&uqa_core::CancellationToken::new())
    }

    /// Use a fresh transaction context while sharing the invoking execution's write cancellation. Existing sessions and clones keep their original token.
    #[must_use]
    pub fn new_session_with_cancellation(
        &self,
        cancellation: &uqa_core::CancellationToken,
    ) -> Self {
        let _gate = self.session.gate.read();
        let session = SessionState::with_cancellation(cancellation.clone());
        if let Some(logical) = self.session.logical.get() {
            let _ = session.logical.set(Arc::new(
                logical.new_session_with_cancellation(cancellation),
            ));
        }
        Self {
            pool: Arc::clone(&self.pool),
            session: Arc::new(session),
            record_access: self.record_access,
        }
    }

    /// Admit a versioned maintenance writer to the original operation's allowance without changing any existing session's transaction or cancellation.
    pub(crate) fn new_controlled_session(
        &self,
        control: &StorageReadControl,
    ) -> StorageBackendResult<Self> {
        control.check()?;
        let _gate = self.session.gate.read();
        let logical = self.session.logical.get().ok_or_else(|| {
            uqa_storage::StorageBackendError::Other(
                "controlled sessions require bound versioned records".into(),
            )
        })?;
        let session = SessionState::with_cancellation(control.cancellation().clone());
        let _ = session.logical.set(Arc::new(BoundRecordSession {
            store: Arc::new(logical.store.new_controlled_session(control)),
            native: logical.native,
        }));
        Ok(Self {
            pool: Arc::clone(&self.pool),
            session: Arc::new(session),
            record_access: self.record_access,
        })
    }

    /// Keep the bound record view and its logical reader attribution in an independent read-only connection. The source session retains ownership of publication and transaction completion.
    pub(crate) fn new_retained_read_session(
        &self,
        cancellation: &uqa_core::CancellationToken,
    ) -> Result<Self> {
        self.new_record_read_session(cancellation, |store| {
            store.new_retained_read_session(cancellation)
        })
    }

    pub(crate) fn capture_committed_read_boundary(
        &self,
    ) -> StorageBackendResult<Arc<uqa_storage::mvcc::CommittedReadBoundary>> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.read();
        let logical = self
            .session
            .logical
            .get()
            .ok_or(SQLiteError::LogicalSessionRequired)?;
        logical.capture_committed_read_boundary()
    }

    pub(crate) fn new_read_session_with_private_changes(
        &self,
        boundary: &uqa_storage::mvcc::CommittedReadBoundary,
        cancellation: &uqa_core::CancellationToken,
    ) -> Result<Self> {
        self.new_record_read_session(cancellation, |store| {
            store.new_read_session_with_private_changes(boundary, cancellation)
        })
    }

    fn new_record_read_session(
        &self,
        cancellation: &uqa_core::CancellationToken,
        retain: impl FnOnce(
            &uqa_storage::mvcc::VersionedKeyValueStore,
        ) -> StorageBackendResult<uqa_storage::mvcc::VersionedKeyValueStore>,
    ) -> Result<Self> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.read();
        let logical = self
            .session
            .logical
            .get()
            .ok_or(SQLiteError::LogicalSessionRequired)?;
        let store = retain(&logical.store)?;
        let session = SessionState::with_cancellation(cancellation.clone());
        let _ = session.logical.set(Arc::new(BoundRecordSession {
            store: Arc::new(store),
            native: logical.native,
        }));
        Ok(Self {
            pool: Arc::clone(&self.pool),
            session: Arc::new(session),
            record_access: self.record_access,
        })
    }

    /// Share the token used for autonomous allocation and record publication. Cleanup reads and rollback remain independent of this flag.
    pub fn write_cancellation(&self) -> uqa_core::CancellationToken {
        self.session.write_cancellation.clone()
    }

    /// Transaction ownership selected for this connection and inherited by its independent sessions.
    pub fn transaction_model(&self) -> uqa_storage::StorageTransactionModel {
        let _gate = self.session.gate.read();
        self.session.logical.get().map_or(
            uqa_storage::StorageTransactionModel::ProviderSerialized,
            |logical| logical.transaction_model(),
        )
    }

    pub(crate) fn record_connection(&self) -> Self {
        Self {
            pool: Arc::clone(&self.pool),
            session: Arc::new(SessionState::new()),
            record_access: true,
        }
    }

    /// Run a record read on a pooled connection, with the connection's memory of the committed state a store last validated. A record connection pins no transaction, so the connection serves this call alone.
    pub(crate) fn with_record_read<R>(
        &self,
        operation: impl FnOnce(&Connection, &std::cell::Cell<Option<super::ValidatedRead>>) -> Result<R>,
    ) -> Result<R> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.read();
        if !self.record_access || self.session.transaction.lock().is_some() {
            return Err(SQLiteError::SessionMappingMismatch);
        }
        let connection = self.pool.checkout()?;
        let physical = connection.physical()?;
        operation(&physical.connection, &physical.validated_read)
    }

    pub(crate) fn with_record_connection<R>(
        &self,
        control: &StorageReadControl,
        operation: impl FnOnce(&Connection) -> Result<R>,
    ) -> Result<R> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.read();
        if !self.record_access || self.session.transaction.lock().is_some() {
            return Err(SQLiteError::SessionMappingMismatch);
        }
        let connection = self
            .pool
            .checkout_with_cancellation(Some(control.cancellation()))?;
        operation(connection.connection()?)
    }

    pub(crate) fn bind_records(
        &self,
        options: VersionedSessionOptions,
    ) -> Result<Arc<VersionedKeyValueStore>> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.write();
        if let Some(logical) = self.session.logical.get() {
            if logical.native.is_some() {
                return Err(SQLiteError::SessionMappingMismatch);
            }
            if logical.options().retained_bytes != options.retained_bytes {
                return Err(SQLiteError::SessionOptionsMismatch);
            }
            return Ok(Arc::clone(&logical.store));
        }
        if self.session.transaction.lock().is_some() {
            return Err(SQLiteError::TransactionAlreadyActive);
        }
        let identity = self.storage_identity()?;
        let records = crate::SQLiteRecordStore::for_key_value(
            self,
            &StorageReadControl::with_limit(options.retained_bytes),
        )
        .map_err(VersionError::into_storage_error)?;
        let logical = Arc::new(VersionedKeyValueStore::new_with_cancellation(
            Arc::new(records),
            identity,
            options,
            self.write_cancellation(),
        ));
        self.session
            .logical
            .set(Arc::new(BoundRecordSession {
                store: Arc::clone(&logical),
                native: None,
            }))
            .map_err(|_| SQLiteError::SessionOptionsMismatch)?;
        Ok(logical)
    }

    pub(crate) fn with_records<R>(
        &self,
        operation: impl FnOnce(&VersionedKeyValueStore) -> StorageBackendResult<R>,
    ) -> StorageBackendResult<R> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.read();
        let logical = self
            .session
            .logical
            .get()
            .ok_or(SQLiteError::LogicalSessionRequired)?;
        if logical.native.is_some() {
            return Err(SQLiteError::SessionMappingMismatch.into());
        }
        operation(logical)
    }

    pub(crate) fn retention_control(
        &self,
    ) -> Option<uqa_storage::read_control::StorageReadControl> {
        self.session
            .logical
            .get()
            .map(|logical| logical.retention_control())
    }

    pub(crate) fn begin_record_read(&self) -> Result<()> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.write();
        let logical = self
            .session
            .logical
            .get()
            .ok_or(SQLiteError::LogicalSessionRequired)?;
        if logical.in_transaction() {
            return Err(SQLiteError::TransactionAlreadyActive);
        }
        logical.begin_read_transaction().map_err(Into::into)
    }

    /// Advance a bound native or Key/Value command view through the common session, without opening a physical writer. Legacy physical transactions require their existing transaction boundary instead.
    pub fn refresh_transaction_snapshot(
        &self,
        cancellation: &uqa_core::CancellationToken,
    ) -> Result<()> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.write();
        self.session
            .logical
            .get()
            .ok_or(SQLiteError::LogicalSessionRequired)?
            .refresh_transaction_snapshot(cancellation)
            .map_err(Into::into)
    }

    pub(super) fn check_native_access(&self, connection: &Connection) -> Result<()> {
        if self.record_access {
            return Ok(());
        }
        let versioned: bool = connection.prepare_cached(
            "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE (name = '_key_value' AND type = 'view') OR name GLOB '_uqa_mvcc_native_*')",
        )?.query_row([], |row| row.get(0))?;
        if versioned {
            return Err(SQLiteError::LogicalSessionRequired);
        }
        Ok(())
    }

    /// Access physical `SQLite` state for explicit diagnostics or maintenance outside any session transaction. This does not read private logical changes; ordinary stores must use their owning transaction interface. Record-table write guards remain active.
    pub fn with_physical<R>(&self, operation: impl FnOnce(&Connection) -> Result<R>) -> Result<R> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.write();
        if self.session.transaction.lock().is_some()
            || self
                .session
                .logical
                .get()
                .is_some_and(|logical| logical.in_transaction())
        {
            return Err(SQLiteError::TransactionAlreadyActive);
        }
        let connection = self.pool.checkout()?;
        operation(connection.connection()?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use uqa_storage::mvcc::{CommitErrorOutcome, CommitFailure, DatabaseId, StorageTransactionId};
    use uqa_storage::StorageBackendError;

    #[test]
    fn record_checkout_cancellation_does_not_wait_for_a_retained_pool_connection() {
        use std::{sync::mpsc, thread, time::Duration};

        let connection = ManagedConnection::open_in_memory()
            .unwrap()
            .record_connection();
        let held = connection.pool.checkout().unwrap();
        let control = StorageReadControl::with_limit(1 << 20);
        let cancellation = control.cancellation().clone();
        let (started_tx, started_rx) = mpsc::channel();
        let (finished_tx, finished_rx) = mpsc::channel();
        thread::scope(|scope| {
            let worker = scope.spawn(|| {
                started_tx.send(()).unwrap();
                let result = connection.with_record_connection(&control, |_| {
                    panic!("cancelled checkout must not enter the operation")
                });
                finished_tx.send(result).unwrap();
            });
            started_rx.recv_timeout(Duration::from_secs(30)).unwrap();
            cancellation.cancel();
            let result = finished_rx.recv_timeout(Duration::from_secs(30));
            drop(held);
            worker.join().unwrap();
            assert!(matches!(
                result.unwrap(),
                Err::<(), _>(SQLiteError::Cancelled(_))
            ));
        });
    }

    #[test]
    fn storage_error_conversion_preserves_an_indeterminate_commit_identity() {
        let transaction = StorageTransactionId::new(DatabaseId::from_bytes([7; 16]), 3).unwrap();
        let original = StorageBackendError::backend(
            "MVCC",
            CommitFailure::Indeterminate {
                transaction,
                source: StorageBackendError::Other("commit reply lost".into()),
            },
        );
        let converted = StorageBackendError::from(SQLiteError::from(original));
        assert_eq!(
            converted.commit_outcome(),
            Some(CommitErrorOutcome::Indeterminate(transaction))
        );
        let StorageBackendError::Backend { backend, source } = converted else {
            panic!("typed commit outcome was lost");
        };
        assert_eq!(backend, "MVCC");
        assert!(
            matches!(source.downcast_ref::<CommitFailure>(), Some(CommitFailure::Indeterminate { transaction: found, .. }) if *found == transaction)
        );
    }
}