Skip to main content

uqa_storage_sqlite/connection/
logical.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Connection clones and store handles share one logical transaction context.
8
9use uqa_storage::mvcc::{DatabaseId, VersionError, VersionedSessionOptions};
10use uqa_storage::read_control::StorageReadControl;
11use uqa_storage::StorageBackendResult;
12
13use super::{
14    Arc, Connection, KeyValueStore, ManagedConnection, Result, SQLiteError, SessionState,
15    VersionedKeyValueStore,
16};
17
18pub(super) struct BoundRecordSession {
19    pub(super) store: Arc<VersionedKeyValueStore>,
20    /// Stable native data namespace, separate from the store's transaction history identity.
21    pub(super) native: Option<DatabaseId>,
22}
23
24impl std::ops::Deref for BoundRecordSession {
25    type Target = VersionedKeyValueStore;
26
27    fn deref(&self) -> &Self::Target {
28        &self.store
29    }
30}
31
32impl BoundRecordSession {
33    pub(super) fn new_session_with_cancellation(
34        &self,
35        cancellation: &uqa_core::CancellationToken,
36    ) -> Self {
37        Self {
38            store: Arc::new(self.store.new_session_with_cancellation(cancellation)),
39            native: self.native,
40        }
41    }
42}
43
44impl ManagedConnection {
45    pub(crate) fn snapshot_registry(
46        &self,
47        identity: DatabaseId,
48    ) -> uqa_storage::mvcc::VersionResult<Arc<uqa_storage::mvcc::SnapshotRegistry>> {
49        let mut retained = self.pool.snapshot_registry.lock();
50        if let Some((old_identity, registry)) = retained.as_ref() {
51            if let Some(registry) = registry.upgrade() {
52                if *old_identity != identity {
53                    return Err(VersionError::WrongDatabase);
54                }
55                return Ok(registry);
56            }
57        }
58        let registry = Arc::new(uqa_storage::mvcc::SnapshotRegistry::default());
59        *retained = Some((identity, Arc::downgrade(&registry)));
60        Ok(registry)
61    }
62
63    /// Create an independent logical session over the same database pool.
64    /// Explicit transactions started on either session are isolated and never
65    /// capture operations issued through the other session.
66    #[must_use]
67    pub fn new_session(&self) -> Self {
68        self.new_session_with_cancellation(&uqa_core::CancellationToken::new())
69    }
70
71    /// Use a fresh transaction context while sharing the invoking execution's write cancellation. Existing sessions and clones keep their original token.
72    #[must_use]
73    pub fn new_session_with_cancellation(
74        &self,
75        cancellation: &uqa_core::CancellationToken,
76    ) -> Self {
77        let _gate = self.session.gate.read();
78        let session = SessionState::with_cancellation(cancellation.clone());
79        if let Some(logical) = self.session.logical.get() {
80            let _ = session.logical.set(Arc::new(
81                logical.new_session_with_cancellation(cancellation),
82            ));
83        }
84        Self {
85            pool: Arc::clone(&self.pool),
86            session: Arc::new(session),
87            record_access: self.record_access,
88        }
89    }
90
91    /// Admit a versioned maintenance writer to the original operation's allowance without changing any existing session's transaction or cancellation.
92    pub(crate) fn new_controlled_session(
93        &self,
94        control: &StorageReadControl,
95    ) -> StorageBackendResult<Self> {
96        control.check()?;
97        let _gate = self.session.gate.read();
98        let logical = self.session.logical.get().ok_or_else(|| {
99            uqa_storage::StorageBackendError::Other(
100                "controlled sessions require bound versioned records".into(),
101            )
102        })?;
103        let session = SessionState::with_cancellation(control.cancellation().clone());
104        let _ = session.logical.set(Arc::new(BoundRecordSession {
105            store: Arc::new(logical.store.new_controlled_session(control)),
106            native: logical.native,
107        }));
108        Ok(Self {
109            pool: Arc::clone(&self.pool),
110            session: Arc::new(session),
111            record_access: self.record_access,
112        })
113    }
114
115    /// 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.
116    pub(crate) fn new_retained_read_session(
117        &self,
118        cancellation: &uqa_core::CancellationToken,
119    ) -> Result<Self> {
120        self.surface_cleanup_failure()?;
121        let _gate = self.session.gate.read();
122        let logical = self
123            .session
124            .logical
125            .get()
126            .ok_or(SQLiteError::LogicalSessionRequired)?;
127        let store = logical.new_retained_read_session(cancellation)?;
128        let session = SessionState::with_cancellation(cancellation.clone());
129        let _ = session.logical.set(Arc::new(BoundRecordSession {
130            store: Arc::new(store),
131            native: logical.native,
132        }));
133        Ok(Self {
134            pool: Arc::clone(&self.pool),
135            session: Arc::new(session),
136            record_access: self.record_access,
137        })
138    }
139
140    /// Share the token used for autonomous allocation and record publication. Cleanup reads and rollback remain independent of this flag.
141    pub fn write_cancellation(&self) -> uqa_core::CancellationToken {
142        self.session.write_cancellation.clone()
143    }
144
145    /// Transaction ownership selected for this connection and inherited by its independent sessions.
146    pub fn transaction_model(&self) -> uqa_storage::StorageTransactionModel {
147        let _gate = self.session.gate.read();
148        self.session.logical.get().map_or(
149            uqa_storage::StorageTransactionModel::ProviderSerialized,
150            |logical| logical.transaction_model(),
151        )
152    }
153
154    pub(crate) fn record_connection(&self) -> Self {
155        Self {
156            pool: Arc::clone(&self.pool),
157            session: Arc::new(SessionState::new()),
158            record_access: true,
159        }
160    }
161
162    /// 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.
163    pub(crate) fn with_record_read<R>(
164        &self,
165        operation: impl FnOnce(&Connection, &std::cell::Cell<Option<super::ValidatedRead>>) -> Result<R>,
166    ) -> Result<R> {
167        self.surface_cleanup_failure()?;
168        let _gate = self.session.gate.read();
169        if !self.record_access || self.session.transaction.lock().is_some() {
170            return Err(SQLiteError::SessionMappingMismatch);
171        }
172        let connection = self.pool.checkout()?;
173        let physical = connection.physical()?;
174        operation(&physical.connection, &physical.validated_read)
175    }
176
177    pub(crate) fn with_record_connection<R>(
178        &self,
179        control: &StorageReadControl,
180        operation: impl FnOnce(&Connection) -> Result<R>,
181    ) -> Result<R> {
182        self.surface_cleanup_failure()?;
183        let _gate = self.session.gate.read();
184        if !self.record_access || self.session.transaction.lock().is_some() {
185            return Err(SQLiteError::SessionMappingMismatch);
186        }
187        let connection = self
188            .pool
189            .checkout_with_cancellation(Some(control.cancellation()))?;
190        operation(connection.connection()?)
191    }
192
193    pub(crate) fn bind_records(
194        &self,
195        options: VersionedSessionOptions,
196    ) -> Result<Arc<VersionedKeyValueStore>> {
197        self.surface_cleanup_failure()?;
198        let _gate = self.session.gate.write();
199        if let Some(logical) = self.session.logical.get() {
200            if logical.native.is_some() {
201                return Err(SQLiteError::SessionMappingMismatch);
202            }
203            if logical.options().retained_bytes != options.retained_bytes {
204                return Err(SQLiteError::SessionOptionsMismatch);
205            }
206            return Ok(Arc::clone(&logical.store));
207        }
208        if self.session.transaction.lock().is_some() {
209            return Err(SQLiteError::TransactionAlreadyActive);
210        }
211        let identity = self.storage_identity()?;
212        let records = crate::SQLiteRecordStore::for_key_value(
213            self,
214            &StorageReadControl::with_limit(options.retained_bytes),
215        )
216        .map_err(VersionError::into_storage_error)?;
217        let logical = Arc::new(VersionedKeyValueStore::new_with_cancellation(
218            Arc::new(records),
219            identity,
220            options,
221            self.write_cancellation(),
222        ));
223        self.session
224            .logical
225            .set(Arc::new(BoundRecordSession {
226                store: Arc::clone(&logical),
227                native: None,
228            }))
229            .map_err(|_| SQLiteError::SessionOptionsMismatch)?;
230        Ok(logical)
231    }
232
233    pub(crate) fn with_records<R>(
234        &self,
235        operation: impl FnOnce(&VersionedKeyValueStore) -> StorageBackendResult<R>,
236    ) -> StorageBackendResult<R> {
237        self.surface_cleanup_failure()?;
238        let _gate = self.session.gate.read();
239        let logical = self
240            .session
241            .logical
242            .get()
243            .ok_or(SQLiteError::LogicalSessionRequired)?;
244        if logical.native.is_some() {
245            return Err(SQLiteError::SessionMappingMismatch.into());
246        }
247        operation(logical)
248    }
249
250    pub(crate) fn retention_control(
251        &self,
252    ) -> Option<uqa_storage::read_control::StorageReadControl> {
253        self.session
254            .logical
255            .get()
256            .map(|logical| logical.retention_control())
257    }
258
259    pub(crate) fn begin_record_read(&self) -> Result<()> {
260        self.surface_cleanup_failure()?;
261        let _gate = self.session.gate.write();
262        let logical = self
263            .session
264            .logical
265            .get()
266            .ok_or(SQLiteError::LogicalSessionRequired)?;
267        if logical.in_transaction() {
268            return Err(SQLiteError::TransactionAlreadyActive);
269        }
270        logical.begin_read_transaction().map_err(Into::into)
271    }
272
273    /// 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.
274    pub fn refresh_transaction_snapshot(
275        &self,
276        cancellation: &uqa_core::CancellationToken,
277    ) -> Result<()> {
278        self.surface_cleanup_failure()?;
279        let _gate = self.session.gate.write();
280        self.session
281            .logical
282            .get()
283            .ok_or(SQLiteError::LogicalSessionRequired)?
284            .refresh_transaction_snapshot(cancellation)
285            .map_err(Into::into)
286    }
287
288    pub(super) fn check_native_access(&self, connection: &Connection) -> Result<()> {
289        if self.record_access {
290            return Ok(());
291        }
292        let versioned: bool = connection.prepare_cached(
293            "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE (name = '_key_value' AND type = 'view') OR name GLOB '_uqa_mvcc_native_*')",
294        )?.query_row([], |row| row.get(0))?;
295        if versioned {
296            return Err(SQLiteError::LogicalSessionRequired);
297        }
298        Ok(())
299    }
300
301    /// 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.
302    pub fn with_physical<R>(&self, operation: impl FnOnce(&Connection) -> Result<R>) -> Result<R> {
303        self.surface_cleanup_failure()?;
304        let _gate = self.session.gate.write();
305        if self.session.transaction.lock().is_some()
306            || self
307                .session
308                .logical
309                .get()
310                .is_some_and(|logical| logical.in_transaction())
311        {
312            return Err(SQLiteError::TransactionAlreadyActive);
313        }
314        let connection = self.pool.checkout()?;
315        operation(connection.connection()?)
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322    use uqa_storage::mvcc::{CommitErrorOutcome, CommitFailure, DatabaseId, StorageTransactionId};
323    use uqa_storage::StorageBackendError;
324
325    #[test]
326    fn record_checkout_cancellation_does_not_wait_for_a_retained_pool_connection() {
327        use std::{sync::mpsc, thread, time::Duration};
328
329        let connection = ManagedConnection::open_in_memory()
330            .unwrap()
331            .record_connection();
332        let held = connection.pool.checkout().unwrap();
333        let control = StorageReadControl::with_limit(1 << 20);
334        let cancellation = control.cancellation().clone();
335        let (started_tx, started_rx) = mpsc::channel();
336        let (finished_tx, finished_rx) = mpsc::channel();
337        thread::scope(|scope| {
338            let worker = scope.spawn(|| {
339                started_tx.send(()).unwrap();
340                let result = connection.with_record_connection(&control, |_| {
341                    panic!("cancelled checkout must not enter the operation")
342                });
343                finished_tx.send(result).unwrap();
344            });
345            started_rx.recv_timeout(Duration::from_secs(30)).unwrap();
346            cancellation.cancel();
347            let result = finished_rx.recv_timeout(Duration::from_secs(30));
348            drop(held);
349            worker.join().unwrap();
350            assert!(matches!(
351                result.unwrap(),
352                Err::<(), _>(SQLiteError::Cancelled(_))
353            ));
354        });
355    }
356
357    #[test]
358    fn storage_error_conversion_preserves_an_indeterminate_commit_identity() {
359        let transaction = StorageTransactionId::new(DatabaseId::from_bytes([7; 16]), 3).unwrap();
360        let original = StorageBackendError::backend(
361            "MVCC",
362            CommitFailure::Indeterminate {
363                transaction,
364                source: StorageBackendError::Other("commit reply lost".into()),
365            },
366        );
367        let converted = StorageBackendError::from(SQLiteError::from(original));
368        assert_eq!(
369            converted.commit_outcome(),
370            Some(CommitErrorOutcome::Indeterminate(transaction))
371        );
372        let StorageBackendError::Backend { backend, source } = converted else {
373            panic!("typed commit outcome was lost");
374        };
375        assert_eq!(backend, "MVCC");
376        assert!(
377            matches!(source.downcast_ref::<CommitFailure>(), Some(CommitFailure::Indeterminate { transaction: found, .. }) if *found == transaction)
378        );
379    }
380}