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    pub(crate) fn with_record_connection<R>(
163        &self,
164        control: &StorageReadControl,
165        operation: impl FnOnce(&Connection) -> 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
173            .pool
174            .checkout_with_cancellation(Some(control.cancellation()))?;
175        operation(connection.connection()?)
176    }
177
178    pub(crate) fn bind_records(
179        &self,
180        options: VersionedSessionOptions,
181    ) -> Result<Arc<VersionedKeyValueStore>> {
182        self.surface_cleanup_failure()?;
183        let _gate = self.session.gate.write();
184        if let Some(logical) = self.session.logical.get() {
185            if logical.native.is_some() {
186                return Err(SQLiteError::SessionMappingMismatch);
187            }
188            if logical.options().retained_bytes != options.retained_bytes {
189                return Err(SQLiteError::SessionOptionsMismatch);
190            }
191            return Ok(Arc::clone(&logical.store));
192        }
193        if self.session.transaction.lock().is_some() {
194            return Err(SQLiteError::TransactionAlreadyActive);
195        }
196        let identity = self.storage_identity()?;
197        let records = crate::SQLiteRecordStore::for_key_value(
198            self,
199            &StorageReadControl::with_limit(options.retained_bytes),
200        )
201        .map_err(VersionError::into_storage_error)?;
202        let logical = Arc::new(VersionedKeyValueStore::new_with_cancellation(
203            Arc::new(records),
204            identity,
205            options,
206            self.write_cancellation(),
207        ));
208        self.session
209            .logical
210            .set(Arc::new(BoundRecordSession {
211                store: Arc::clone(&logical),
212                native: None,
213            }))
214            .map_err(|_| SQLiteError::SessionOptionsMismatch)?;
215        Ok(logical)
216    }
217
218    pub(crate) fn with_records<R>(
219        &self,
220        operation: impl FnOnce(&VersionedKeyValueStore) -> StorageBackendResult<R>,
221    ) -> StorageBackendResult<R> {
222        self.surface_cleanup_failure()?;
223        let _gate = self.session.gate.read();
224        let logical = self
225            .session
226            .logical
227            .get()
228            .ok_or(SQLiteError::LogicalSessionRequired)?;
229        if logical.native.is_some() {
230            return Err(SQLiteError::SessionMappingMismatch.into());
231        }
232        operation(logical)
233    }
234
235    pub(crate) fn retention_control(
236        &self,
237    ) -> Option<uqa_storage::read_control::StorageReadControl> {
238        self.session
239            .logical
240            .get()
241            .map(|logical| logical.retention_control())
242    }
243
244    pub(crate) fn begin_record_read(&self) -> Result<()> {
245        self.surface_cleanup_failure()?;
246        let _gate = self.session.gate.write();
247        let logical = self
248            .session
249            .logical
250            .get()
251            .ok_or(SQLiteError::LogicalSessionRequired)?;
252        if logical.in_transaction() {
253            return Err(SQLiteError::TransactionAlreadyActive);
254        }
255        logical.begin_read_transaction().map_err(Into::into)
256    }
257
258    /// 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.
259    pub fn refresh_transaction_snapshot(
260        &self,
261        cancellation: &uqa_core::CancellationToken,
262    ) -> Result<()> {
263        self.surface_cleanup_failure()?;
264        let _gate = self.session.gate.write();
265        self.session
266            .logical
267            .get()
268            .ok_or(SQLiteError::LogicalSessionRequired)?
269            .refresh_transaction_snapshot(cancellation)
270            .map_err(Into::into)
271    }
272
273    pub(super) fn check_native_access(&self, connection: &Connection) -> Result<()> {
274        if self.record_access {
275            return Ok(());
276        }
277        let versioned: bool = connection.prepare_cached(
278            "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE (name = '_key_value' AND type = 'view') OR name GLOB '_uqa_mvcc_native_*')",
279        )?.query_row([], |row| row.get(0))?;
280        if versioned {
281            return Err(SQLiteError::LogicalSessionRequired);
282        }
283        Ok(())
284    }
285
286    /// 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.
287    pub fn with_physical<R>(&self, operation: impl FnOnce(&Connection) -> Result<R>) -> Result<R> {
288        self.surface_cleanup_failure()?;
289        let _gate = self.session.gate.write();
290        if self.session.transaction.lock().is_some()
291            || self
292                .session
293                .logical
294                .get()
295                .is_some_and(|logical| logical.in_transaction())
296        {
297            return Err(SQLiteError::TransactionAlreadyActive);
298        }
299        let connection = self.pool.checkout()?;
300        operation(connection.connection()?)
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307    use uqa_storage::mvcc::{CommitErrorOutcome, CommitFailure, DatabaseId, StorageTransactionId};
308    use uqa_storage::StorageBackendError;
309
310    #[test]
311    fn record_checkout_cancellation_does_not_wait_for_a_retained_pool_connection() {
312        use std::{sync::mpsc, thread, time::Duration};
313
314        let connection = ManagedConnection::open_in_memory()
315            .unwrap()
316            .record_connection();
317        let held = connection.pool.checkout().unwrap();
318        let control = StorageReadControl::with_limit(1 << 20);
319        let cancellation = control.cancellation().clone();
320        let (started_tx, started_rx) = mpsc::channel();
321        let (finished_tx, finished_rx) = mpsc::channel();
322        thread::scope(|scope| {
323            let worker = scope.spawn(|| {
324                started_tx.send(()).unwrap();
325                let result = connection.with_record_connection(&control, |_| {
326                    panic!("cancelled checkout must not enter the operation")
327                });
328                finished_tx.send(result).unwrap();
329            });
330            started_rx.recv_timeout(Duration::from_secs(30)).unwrap();
331            cancellation.cancel();
332            let result = finished_rx.recv_timeout(Duration::from_secs(30));
333            drop(held);
334            worker.join().unwrap();
335            assert!(matches!(
336                result.unwrap(),
337                Err::<(), _>(SQLiteError::Cancelled(_))
338            ));
339        });
340    }
341
342    #[test]
343    fn storage_error_conversion_preserves_an_indeterminate_commit_identity() {
344        let transaction = StorageTransactionId::new(DatabaseId::from_bytes([7; 16]), 3).unwrap();
345        let original = StorageBackendError::backend(
346            "MVCC",
347            CommitFailure::Indeterminate {
348                transaction,
349                source: StorageBackendError::Other("commit reply lost".into()),
350            },
351        );
352        let converted = StorageBackendError::from(SQLiteError::from(original));
353        assert_eq!(
354            converted.commit_outcome(),
355            Some(CommitErrorOutcome::Indeterminate(transaction))
356        );
357        let StorageBackendError::Backend { backend, source } = converted else {
358            panic!("typed commit outcome was lost");
359        };
360        assert_eq!(backend, "MVCC");
361        assert!(
362            matches!(source.downcast_ref::<CommitFailure>(), Some(CommitFailure::Indeterminate { transaction: found, .. }) if *found == transaction)
363        );
364    }
365}