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
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Pooled `SQLite` connections with explicit session and transaction affinity.
//!
//! A [`ManagedConnection`] is a logical session. Clones share that session so
//! catalog, document, inverted-index, and vector stores participate in the
//! same explicit transaction. [`ManagedConnection::new_session`] creates an
//! isolated session over the same physical connection pool. Outside explicit
//! transactions operations check out independent connections, allowing WAL
//! readers to make real concurrent progress.

use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};

use parking_lot::{Mutex, RwLock};
use rusqlite::{Connection, OpenFlags};
use uqa_storage::{mvcc::VersionedKeyValueStore, KeyValueStore, StorageEncryptionKey};

use crate::compressed_vfs::{self, SQLiteCompressedContainerAnchor, SQLiteCompressionOptions};

mod identity;
mod logical;
mod native;
mod native_restore;
pub(crate) mod ownership;
mod pool;
mod restore;
use pool::ConnectionPool;
pub(crate) use pool::PooledConnection;
mod notifications;
mod serializable;
mod snapshot;
mod source;
use snapshot::PhysicalConnection;
pub(crate) use snapshot::{SnapshotIdentity, ValidatedRead};

#[derive(Debug, thiserror::Error)]
pub enum SQLiteError {
    #[error(transparent)]
    Memory(#[from] uqa_core::memory::MemoryError),
    #[error(transparent)]
    Cancelled(#[from] uqa_core::QueryCancelled),
    #[error("text analysis failed: {0}")]
    Analysis(#[from] uqa_analysis::AnalysisError),
    #[error("sqlite error: {0}")]
    SQLite(#[from] rusqlite::Error),
    #[error("encryption key must not be empty")]
    EmptyEncryptionKey,
    #[error("database requires an encryption key")]
    EncryptionKeyRequired,
    #[error("database is not encrypted but an encryption key was provided")]
    NotEncrypted,
    #[error("auxiliary database requires DELETE journaling, found {0}")]
    AuxiliaryJournalMode(String),
    #[error("compressed sqlite container error: {0}")]
    CompressedContainer(String),
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("catalog migration {version} failed: {source}")]
    Migration {
        version: u32,
        #[source]
        source: rusqlite::Error,
    },
    #[error("invalid persisted catalog schema version `{0}`")]
    InvalidSchemaVersion(String),
    #[error("catalog schema version {found} is newer than this engine supports ({supported})")]
    UnsupportedSchemaVersion { found: u32, supported: u32 },
    #[error("corrupt document blob for `{table}` doc {doc_id} field `{field}`: {reason}")]
    CorruptDocumentBlob {
        table: String,
        doc_id: u64,
        field: String,
        reason: String,
    },
    #[error("payload serialization failed: {0}")]
    Serde(#[from] serde_json::Error),
    #[error("storage backend error: {0}")]
    StorageBackend(String),
    #[error(transparent)]
    StorageSource(Box<uqa_storage::StorageBackendError>),
    #[error("transaction already active for this sqlite session")]
    TransactionAlreadyActive,
    #[error("no active transaction for this sqlite session")]
    NoActiveTransaction,
    #[error("sqlite transaction was aborted by an earlier storage error: {0}")]
    TransactionAborted(String),
    #[error("sqlite session cleanup failed: {0}")]
    SessionCleanupFailed(String),
    #[error("sqlite connection-pool checkout lost its connection")]
    MissingCheckedOutConnection,
    #[error("versioned storage requires its logical session; use with_physical only for explicit physical maintenance")]
    LogicalSessionRequired,
    #[error("database restoration requires all existing owners to close")]
    DatabaseRestoreBusy,
    #[error("record initialization requires incompatible database owners to close")]
    DatabaseCoordinationUpgradeBusy,
    #[error("database restoration is incomplete; resume the original source/target request")]
    DatabaseRestoreIncomplete,
    #[error("the SQLite session already has a different retention limit")]
    SessionOptionsMismatch,
    #[error("the SQLite session is bound to a different record mapping")]
    SessionMappingMismatch,
    #[error("the retained SQLite database source changed; close its owners and reopen explicitly")]
    DatabaseSourceChanged,
}

pub type Result<T> = std::result::Result<T, SQLiteError>;

const MIN_POOL_CONNECTIONS: usize = 4;
const MAX_POOL_CONNECTIONS: usize = 32;

/// Prepared statements each connection retains. Statements are built from record layouts and work-queue conditions, so one commit runs more distinct statements than a small cache holds, and preparing a projection upsert compiles every trigger of its table; a cache that evicts them prepares them again in each transaction.
pub(crate) const PREPARED_STATEMENT_CACHE_CAPACITY: usize = 256;

#[derive(Clone)]
enum ConnectionSpec {
    File {
        path: PathBuf,
        key: Option<StorageEncryptionKey>,
    },
    Auxiliary {
        path: PathBuf,
        key: Option<StorageEncryptionKey>,
    },
    Compressed {
        path: PathBuf,
        compression: SQLiteCompressionOptions,
        key: Option<StorageEncryptionKey>,
    },
    Memory,
}

impl ConnectionSpec {
    fn open(&self, initialize_database: bool) -> Result<Connection> {
        let conn = self.open_configured(initialize_database)?;
        conn.set_prepared_statement_cache_capacity(PREPARED_STATEMENT_CACHE_CAPACITY);
        Ok(conn)
    }

    fn open_configured(&self, initialize_database: bool) -> Result<Connection> {
        let mut flags = OpenFlags::default();
        if !initialize_database && matches!(self, Self::File { .. } | Self::Auxiliary { .. }) {
            flags.remove(OpenFlags::SQLITE_OPEN_CREATE);
        }
        match self {
            Self::File { path, key } | Self::Auxiliary { path, key } => {
                let conn = Connection::open_with_flags(path, flags)?;
                if let Some(key) = key {
                    ManagedConnection::apply_encryption_key(&conn, key.expose_secret())?;
                }
                crate::btree_index::equality::register(&conn)?;
                if matches!(self, Self::Auxiliary { .. }) {
                    // Registry writers already serialize their transactions.
                    // Retain the original journal mode instead of racing to
                    // promote a new registry to WAL during concurrent opens.
                    let mode: String =
                        conn.pragma_query_value(None, "journal_mode", |row| row.get(0))?;
                    if mode != "delete" {
                        return Err(SQLiteError::AuxiliaryJournalMode(mode));
                    }
                    ManagedConnection::configure_rollback_connection(&conn)?;
                } else {
                    if initialize_database {
                        ManagedConnection::enable_wal(&conn)?;
                    }
                    ManagedConnection::configure_wal_connection(&conn)?;
                }
                Ok(conn)
            }
            Self::Compressed {
                path, compression, ..
            } => {
                let conn =
                    Connection::open_with_flags_and_vfs(path, flags, compressed_vfs::VFS_NAME)?;
                crate::btree_index::equality::register(&conn)?;
                if initialize_database {
                    conn.pragma_update(None, "page_size", compression.page_size)?;
                    ManagedConnection::enable_compressed_journal(&conn)?;
                }
                ManagedConnection::configure_rollback_connection(&conn)?;
                Ok(conn)
            }
            Self::Memory => {
                let conn = Connection::open_in_memory()?;
                crate::btree_index::equality::register(&conn)?;
                if initialize_database {
                    ManagedConnection::enable_wal(&conn)?;
                }
                ManagedConnection::configure_wal_connection(&conn)?;
                Ok(conn)
            }
        }
    }
}

struct SessionState {
    write_cancellation: uqa_core::CancellationToken,
    affinity: uqa_storage::StorageSessionAffinity,
    /// Read guards cover ordinary operations. Transaction lifecycle calls take
    /// the write guard, making BEGIN/COMMIT/ROLLBACK linearizable with respect
    /// to every operation issued through the same logical session.
    gate: RwLock<()>,
    transaction: Mutex<Option<PooledConnection>>,
    transaction_failure: Mutex<Option<String>>,
    cleanup_failure: Mutex<Option<String>>,
    logical: OnceLock<Arc<logical::BoundRecordSession>>,
    native_restore: Mutex<Option<native_restore::NativeRestore>>,
    snapshot_branch: Mutex<Arc<()>>,
}

impl SessionState {
    fn new() -> Self {
        Self::with_cancellation(uqa_core::CancellationToken::new())
    }

    fn with_cancellation(write_cancellation: uqa_core::CancellationToken) -> Self {
        Self {
            write_cancellation,
            affinity: uqa_storage::StorageSessionAffinity::new(),
            gate: RwLock::new(()),
            transaction: Mutex::new(None),
            transaction_failure: Mutex::new(None),
            cleanup_failure: Mutex::new(None),
            logical: OnceLock::new(),
            native_restore: Mutex::new(None),
            snapshot_branch: Mutex::new(Arc::new(())),
        }
    }
}

impl Drop for SessionState {
    fn drop(&mut self) {
        // `PooledConnection::drop` performs the rollback and discards the
        // physical connection when rollback itself fails. Taking the pinned
        // handle here therefore cannot return a broken connection to the pool.
        self.native_restore.get_mut().take();
        self.transaction.get_mut().take();
    }
}

/// Logical `SQLite` session backed by a bounded physical connection pool.
/// Cloning preserves session/transaction affinity; call [`Self::new_session`]
/// for an independently isolated transaction context.
#[derive(Clone)]
pub struct ManagedConnection {
    pool: Arc<ConnectionPool>,
    session: Arc<SessionState>,
    record_access: bool,
}

impl ManagedConnection {
    /// Decoded document columns shared by every session of this database.
    pub(crate) fn decoded_columns(
        &self,
    ) -> &crate::document_store::decoded_columns::DecodedColumns {
        &self.pool.decoded_columns
    }

    fn surface_cleanup_failure(&self) -> Result<()> {
        if let Some(error) = self.session.cleanup_failure.lock().take() {
            return Err(SQLiteError::SessionCleanupFailed(error));
        }
        Ok(())
    }

    pub fn open(path: &Path) -> Result<Self> {
        if path == Path::new(":memory:") {
            return Self::open_in_memory();
        }
        Self::open_with_optional_key(path, None)
    }

    /// Retain the database credential for encrypted auxiliary storage, including
    /// compressed containers whose main-file encryption lives in the VFS.
    #[must_use]
    pub fn auxiliary_encryption_key(&self) -> Option<StorageEncryptionKey> {
        match &self.pool.spec {
            ConnectionSpec::File { key, .. }
            | ConnectionSpec::Auxiliary { key, .. }
            | ConnectionSpec::Compressed { key, .. } => key.clone(),
            ConnectionSpec::Memory => None,
        }
    }

    /// Lease an independent physical connection without joining this logical
    /// session's transaction. The pool retains encryption and connection policy.
    pub fn lease_connection(&self) -> Result<crate::SQLiteConnectionLease> {
        self.pool.checkout().map(crate::SQLiteConnectionLease)
    }

    /// Open database-owned auxiliary storage with its inherited credential and
    /// original DELETE journaling. Concurrent first opens never change journal
    /// modes. An incompatible existing mode is rejected without rewriting it.
    pub fn open_auxiliary(path: &Path, key: Option<StorageEncryptionKey>) -> Result<Self> {
        if path == Path::new(":memory:") || path.as_os_str().is_empty() {
            return Err(SQLiteError::StorageBackend(
                "auxiliary storage requires a database file".into(),
            ));
        }
        Self::from_spec(
            ConnectionSpec::Auxiliary {
                path: path.to_path_buf(),
                key,
            },
            default_pool_connections(),
        )
    }

    pub fn open_encrypted(path: &Path, key: &str) -> Result<Self> {
        Self::open_with_optional_key(path, Some(key))
    }

    pub fn open_compressed(path: &Path, compression: SQLiteCompressionOptions) -> Result<Self> {
        Self::open_compressed_with_optional_key(path, compression, None, None)
    }

    pub fn open_compressed_encrypted(
        path: &Path,
        key: &str,
        compression: SQLiteCompressionOptions,
    ) -> Result<Self> {
        if key.is_empty() {
            return Err(SQLiteError::EmptyEncryptionKey);
        }
        Self::open_compressed_with_optional_key(path, compression, Some(key), None)
    }

    /// Open an encrypted compressed database while enforcing an exact trusted
    /// external state anchor in the VFS main-file open path.
    pub fn open_compressed_encrypted_with_anchor(
        path: &Path,
        key: &str,
        compression: SQLiteCompressionOptions,
        trusted_anchor: SQLiteCompressedContainerAnchor,
    ) -> Result<Self> {
        if key.is_empty() {
            return Err(SQLiteError::EmptyEncryptionKey);
        }
        Self::open_compressed_with_optional_key(path, compression, Some(key), Some(trusted_anchor))
    }

    fn open_with_optional_key(path: &Path, key: Option<&str>) -> Result<Self> {
        let spec = ConnectionSpec::File {
            path: path.to_path_buf(),
            key: key.map(StorageEncryptionKey::new),
        };
        Self::from_spec(spec, default_pool_connections())
    }

    fn open_compressed_with_optional_key(
        path: &Path,
        compression: SQLiteCompressionOptions,
        key: Option<&str>,
        trusted_anchor: Option<SQLiteCompressedContainerAnchor>,
    ) -> Result<Self> {
        let compression = compression
            .validate()
            .map_err(SQLiteError::CompressedContainer)?;
        let owner = ownership::open(
            path,
            &uqa_storage::read_control::StorageReadControl::with_limit(
                uqa_storage::mvcc::VersionedSessionOptions::default().retained_bytes,
            ),
        )?;
        match trusted_anchor {
            Some(anchor) => compressed_vfs::register_database_with_anchor(
                path,
                compression,
                key.ok_or(SQLiteError::EncryptionKeyRequired)?,
                anchor,
            ),
            None => compressed_vfs::register_database(path, compression, key),
        }
        .map_err(SQLiteError::CompressedContainer)?;
        let spec = ConnectionSpec::Compressed {
            path: path.to_path_buf(),
            compression,
            key: key.map(StorageEncryptionKey::new),
        };
        Self::from_spec_owned(spec, default_pool_connections(), Some(owner))
    }

    pub fn open_in_memory() -> Result<Self> {
        // Independent `:memory:` connections do not share a database. Keep a
        // one-connection pool for this special target; file-backed databases
        // use the real multi-connection pool.
        Self::from_spec(ConnectionSpec::Memory, 1)
    }

    fn from_spec(spec: ConnectionSpec, max_connections: usize) -> Result<Self> {
        let owner = match &spec {
            ConnectionSpec::File { path, .. }
                if path.as_os_str().is_empty() || path == Path::new(":memory:") =>
            {
                None
            }
            ConnectionSpec::File { path, .. }
            | ConnectionSpec::Auxiliary { path, .. }
            | ConnectionSpec::Compressed { path, .. } => Some(ownership::open(
                path,
                &uqa_storage::read_control::StorageReadControl::with_limit(
                    uqa_storage::mvcc::VersionedSessionOptions::default().retained_bytes,
                ),
            )?),
            ConnectionSpec::Memory => None,
        };
        Self::from_spec_owned(spec, max_connections, owner)
    }

    fn from_spec_owned(
        spec: ConnectionSpec,
        max_connections: usize,
        owner: Option<Arc<ownership::DatabaseOwner>>,
    ) -> Result<Self> {
        let initial = spec.open(true)?;
        crate::mvcc::restore::reject_pending(&initial)?;
        Ok(Self {
            pool: ConnectionPool::new(spec, initial, max_connections, owner)?,
            session: Arc::new(SessionState::new()),
            record_access: false,
        })
    }

    pub(crate) fn database_owner(&self) -> Option<Arc<ownership::DatabaseOwner>> {
        self.pool.owner.clone()
    }

    fn apply_encryption_key(conn: &Connection, key: &str) -> Result<()> {
        if key.is_empty() {
            return Err(SQLiteError::EmptyEncryptionKey);
        }
        conn.pragma_update(None, "key", key)?;
        Ok(())
    }

    fn enable_wal(conn: &Connection) -> Result<()> {
        conn.pragma_update(None, "journal_mode", "WAL")?;
        Ok(())
    }

    fn configure_wal_connection(conn: &Connection) -> Result<()> {
        // Legacy physical operations retain a bounded busy wait. Versioned writes supply cancellable admission under a scoped timeout.
        conn.busy_timeout(std::time::Duration::from_secs(5))?;
        // Synchronous=NORMAL is the recommended pairing with WAL: safe
        // against power loss, faster than FULL.
        conn.pragma_update(None, "synchronous", "NORMAL")?;
        // Foreign keys are off by default; turn on so per-table cleanup
        // can use ON DELETE CASCADE later.
        conn.pragma_update(None, "foreign_keys", "ON")?;
        Ok(())
    }

    fn enable_compressed_journal(conn: &Connection) -> Result<()> {
        // The compressed VFS implements the byte-addressed database file.
        // Rollback journals stay raw because they are short-lived commit
        // machinery; compressing them only adds autocommit write amplification.
        // WAL requires shared-memory VFS methods, so compressed databases use
        // SQLite's rollback journal and keep temp storage in memory.
        conn.pragma_update(None, "journal_mode", "DELETE")?;
        Ok(())
    }

    fn configure_rollback_connection(conn: &Connection) -> Result<()> {
        conn.busy_timeout(std::time::Duration::from_secs(5))?;
        conn.pragma_update(None, "synchronous", "FULL")?;
        conn.pragma_update(None, "temp_store", "MEMORY")?;
        conn.pragma_update(None, "foreign_keys", "ON")?;
        Ok(())
    }

    /// Identity shared by handles using this session's native or logical transaction context.
    pub fn transaction_affinity(&self) -> uqa_storage::StorageSessionAffinity {
        let _gate = self.session.gate.read();
        self.session.logical.get().map_or_else(
            || self.session.affinity.clone(),
            |logical| logical.session_affinity(),
        )
    }

    /// Whether this session has an active native or logical record transaction.
    #[must_use]
    pub fn in_transaction(&self) -> bool {
        let _gate = self.session.gate.read();
        if let Some(logical) = self.session.logical.get() {
            return logical.in_transaction();
        }
        self.session.transaction.lock().is_some()
    }

    /// Whether this session has staged writes, including private logical records. Callers use this to enforce read-only execution boundaries before COMMIT.
    pub fn transaction_has_written(&self) -> Result<bool> {
        let _gate = self.session.gate.read();
        if let Some(logical) = self.session.logical.get() {
            return logical.transaction_has_written().map_err(Into::into);
        }
        let transaction = self.session.transaction.lock();
        let transaction = transaction
            .as_ref()
            .ok_or(SQLiteError::NoActiveTransaction)?;
        Ok(matches!(
            transaction.connection()?.transaction_state(Some("main"))?,
            rusqlite::TransactionState::Write
        ))
    }

    /// Whether this session's independent [`Self::data_version`] monitor can
    /// read without contending with the currently pinned transaction.
    ///
    /// A rollback-journal writer's pending lock blocks new readers while waiting for existing readers to finish. A rollback-journal read transaction must therefore also avoid the independent monitor: its own shared lock may be preventing that waiting writer from proceeding. Callers refresh through the pinned connection instead. WAL sessions and sessions without a pinned transaction permit the independent monitor.
    pub fn data_version_monitor_is_nonblocking(&self) -> Result<bool> {
        let _gate = self.session.gate.read();
        if self.session.logical.get().is_some() {
            return Ok(true);
        }
        if !matches!(
            &self.pool.spec,
            ConnectionSpec::Compressed { .. } | ConnectionSpec::Auxiliary { .. }
        ) {
            return Ok(true);
        }
        Ok(self.session.transaction.lock().is_none())
    }

    /// Whether one pooled connection may retain a read snapshot while another writes. Ordinary plain and encrypted `SQLite` databases use WAL; compressed containers and auxiliary files use rollback journaling and therefore require a detached engine snapshot before writer promotion.
    #[must_use]
    pub fn supports_concurrent_pinned_read_and_write(&self) -> bool {
        let _gate = self.session.gate.read();
        self.session.logical.get().is_some()
            || !matches!(
                &self.pool.spec,
                ConnectionSpec::Compressed { .. } | ConnectionSpec::Auxiliary { .. }
            )
    }

    /// Database change counter observed on one stable connection shared by
    /// every logical session over this pool. The value changes when another
    /// `SQLite` connection commits. In-memory databases have no independent
    /// connections and therefore return `None`.
    pub fn data_version(&self) -> Result<Option<u64>> {
        let _gate = self.session.gate.read();
        self.pool.check_source()?;
        if let Some(logical) = self.session.logical.get() {
            return logical.change_version().map_err(Into::into);
        }
        if matches!(&self.pool.spec, ConnectionSpec::Memory) {
            return Ok(None);
        }
        let mut monitor = self.pool.data_version_monitor.lock();
        if monitor.is_none() {
            *monitor = Some(self.pool.open_connection()?);
        }
        let monitor = monitor.as_ref().ok_or_else(|| {
            SQLiteError::StorageBackend(
                "data-version monitor was not initialized after opening it".into(),
            )
        })?;
        let version: i64 = monitor.pragma_query_value(None, "data_version", |row| row.get(0))?;
        let version = u64::try_from(version).map_err(|_| {
            SQLiteError::StorageBackend(format!(
                "SQLite returned a negative PRAGMA data_version: {version}"
            ))
        })?;
        Ok(Some(version))
    }

    /// `SQLite`'s change counter on the pool's monitor connection, which differs from an earlier read exactly when another connection of any session or process committed in between. `None` when the monitor may not read at any time: an in-memory database has no independent connection, and a rollback-journal reader waits for a pending writer, which may itself be waiting for a read this session has open.
    pub fn commit_monitor_version(&self) -> Result<Option<u64>> {
        if matches!(
            &self.pool.spec,
            ConnectionSpec::Memory
                | ConnectionSpec::Compressed { .. }
                | ConnectionSpec::Auxiliary { .. }
        ) {
            return Ok(None);
        }
        self.pool.check_source()?;
        let mut monitor = self.pool.data_version_monitor.lock();
        if monitor.is_none() {
            *monitor = Some(self.pool.open_connection()?);
        }
        let monitor = monitor.as_ref().ok_or_else(|| {
            SQLiteError::StorageBackend(
                "data-version monitor was not initialized after opening it".into(),
            )
        })?;
        let version: i64 = monitor
            .prepare_cached("PRAGMA data_version")?
            .query_row([], |row| row.get(0))?;
        u64::try_from(version).map(Some).map_err(|_| {
            SQLiteError::StorageBackend(format!(
                "SQLite returned a negative PRAGMA data_version: {version}"
            ))
        })
    }

    /// Complete logical record visibility, including the private root restored by savepoint undo. Legacy physical sessions retain their existing data-version refresh protocol.
    pub fn read_view_revision(
        &self,
    ) -> Result<Option<uqa_storage::key_value::KeyValueReadRevision>> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.read();
        self.session.logical.get().map_or(Ok(None), |logical| {
            logical.read_view_revision().map_err(Into::into)
        })
    }

    /// Establish the database snapshot for the active transaction without
    /// depending on the caller's first user query. `BEGIN DEFERRED` alone does
    /// not start a read transaction, so a writer could otherwise commit after
    /// the engine checks its cache generations but before the first catalog
    /// read. Reading `sqlite_schema` is database-wide and keeps the operation
    /// independent of any application table.
    pub fn pin_transaction_snapshot(&self) -> Result<()> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.read();
        if let Some(logical) = self.session.logical.get() {
            return if logical.in_transaction() {
                Ok(())
            } else {
                Err(SQLiteError::NoActiveTransaction)
            };
        }
        self.with_native(|connection| {
            if connection.is_autocommit() {
                return Err(SQLiteError::NoActiveTransaction);
            }
            let _: i64 =
                connection.query_row("SELECT COUNT(*) FROM sqlite_schema", [], |row| row.get(0))?;
            Ok(())
        })
    }

    /// Run a closure using this session. Outside a transaction the closure
    /// checks out a pooled connection; inside a transaction every clone is
    /// routed to the session's pinned connection.
    pub fn with<R>(&self, f: impl FnOnce(&Connection) -> Result<R>) -> Result<R> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.read();
        if self.session.logical.get().is_some() {
            return Err(SQLiteError::LogicalSessionRequired);
        }
        self.with_native(f)
    }

    /// The caller holds the session gate and has ruled out logical record access.
    fn with_native<R>(&self, f: impl FnOnce(&Connection) -> Result<R>) -> Result<R> {
        let transaction = self.session.transaction.lock();
        if let Some(connection) = transaction.as_ref() {
            if let Some(error) = self.session.transaction_failure.lock().as_ref() {
                return Err(SQLiteError::TransactionAborted(error.clone()));
            }
            self.check_native_access(connection.connection()?)?;
            let result = f(connection.connection()?);
            if let Err(error) = &result {
                let mut failure = self.session.transaction_failure.lock();
                if failure.is_none() {
                    *failure = Some(error.to_string());
                }
            }
            return result;
        }
        drop(transaction);
        let connection = self.pool.checkout()?;
        self.check_native_access(connection.connection()?)?;
        f(connection.connection()?)
    }

    pub fn with_mut<R>(&self, f: impl FnOnce(&mut Connection) -> Result<R>) -> Result<R> {
        self.with_physical_mut(|physical| f(&mut physical.connection))
    }

    fn with_physical_mut<R>(
        &self,
        f: impl FnOnce(&mut PhysicalConnection) -> Result<R>,
    ) -> Result<R> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.read();
        if self.session.logical.get().is_some() {
            return Err(SQLiteError::LogicalSessionRequired);
        }
        let mut transaction = self.session.transaction.lock();
        if let Some(connection) = transaction.as_mut() {
            if let Some(error) = self.session.transaction_failure.lock().as_ref() {
                return Err(SQLiteError::TransactionAborted(error.clone()));
            }
            self.check_native_access(connection.connection()?)?;
            let result = f(connection.physical_mut()?);
            if let Err(error) = &result {
                let mut failure = self.session.transaction_failure.lock();
                if failure.is_none() {
                    *failure = Some(error.to_string());
                }
            }
            return result;
        }
        drop(transaction);
        let mut connection = self.pool.checkout()?;
        self.check_native_access(connection.connection()?)?;
        f(connection.physical_mut()?)
    }

    /// Rewrite the `SQLite` database into its minimum-sized file. `SQLite` requires `VACUUM` to run in autocommit mode, so the session write gate makes the transaction check and maintenance command one atomic session operation.
    pub fn vacuum(&self) -> Result<()> {
        self.maintain_storage(true)
    }

    /// Reclaim obsolete logical records and history without executing a physical `SQLite` `VACUUM`.
    pub fn reclaim_obsolete(&self) -> Result<()> {
        self.maintain_storage(false)
    }

    fn maintain_storage(&self, compact: bool) -> Result<()> {
        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);
        }
        if let Some(logical) = self.session.logical.get() {
            let source: Arc<dyn KeyValueStore> = if let Some(namespace) = logical.native {
                Arc::new(crate::diskann::Records::new(
                    logical.store.clone(),
                    namespace,
                    self.auxiliary_encryption_key(),
                )?)
            } else {
                logical.store.clone()
            };
            let retained = logical.retention_control();
            let control = uqa_storage::read_control::StorageReadControl::new(
                retained.memory(),
                &self.write_cancellation(),
            );
            uqa_storage::key_value::KeyValueDiskANNMaintenance::run(&source, &control)?;
            logical.reclaim_versions()?;
        }
        if compact {
            let connection = self.pool.checkout()?;
            connection.connection()?.execute_batch("VACUUM")?;
        }
        Ok(())
    }

    /// Open an explicit (non-deferred) transaction. Subsequent
    /// auto-commit hosts (catalog writes, FTS index updates, ...) all
    /// flow through the same connection so the transaction enclosing
    /// them is honoured. Use [`Self::commit_transaction`] /
    /// [`Self::rollback_transaction`] / [`Self::savepoint`] etc. for
    /// the lifecycle.
    pub fn begin_transaction(&self) -> Result<()> {
        self.begin_transaction_with("BEGIN IMMEDIATE")
    }

    /// Open a deferred transaction. Read-only SQL statements use this mode
    /// so WAL readers do not take the single writer reservation; if a scalar
    /// routine performs a write, `SQLite` upgrades the same transaction and
    /// still preserves the statement's atomic boundary.
    pub fn begin_deferred_transaction(&self) -> Result<()> {
        self.begin_transaction_with("BEGIN DEFERRED")
    }

    fn begin_transaction_with(&self, statement: &str) -> Result<()> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.write();
        if let Some(logical) = self.session.logical.get() {
            if logical.in_transaction() {
                return Err(SQLiteError::TransactionAlreadyActive);
            }
            return if statement == "BEGIN DEFERRED" {
                logical.begin_upgradeable_transaction()
            } else {
                logical.begin_transaction()
            }
            .map_err(Into::into);
        }
        let mut transaction = self.session.transaction.lock();
        if transaction.is_some() {
            return Err(SQLiteError::TransactionAlreadyActive);
        }
        let connection = self.pool.checkout()?;
        self.check_native_access(connection.connection()?)?;
        connection.connection()?.execute_batch(statement)?;
        self.session.transaction_failure.lock().take();
        *transaction = Some(connection);
        Ok(())
    }

    pub fn commit_transaction(&self) -> Result<()> {
        self.surface_cleanup_failure()?;
        self.finish_transaction("COMMIT")
    }

    pub fn rollback_transaction(&self) -> Result<()> {
        self.surface_cleanup_failure()?;
        self.finish_transaction("ROLLBACK")
    }

    /// Drop-only transaction cleanup. A rollback error is recorded on the
    /// logical session and is returned by its next operation instead of being
    /// mistaken for a successful rollback.
    pub(crate) fn rollback_transaction_on_drop(&self) {
        if let Err(error) = self.finish_transaction("ROLLBACK") {
            let mut failure = self.session.cleanup_failure.lock();
            if failure.is_none() {
                *failure = Some(error.to_string());
            }
        }
    }

    fn finish_transaction(&self, statement: &str) -> Result<()> {
        let _gate = self.session.gate.write();
        if let Some(logical) = self.session.logical.get() {
            if !logical.in_transaction() {
                return Err(SQLiteError::NoActiveTransaction);
            }
            return if statement == "COMMIT" {
                logical.commit_transaction()
            } else {
                logical.rollback_transaction()
            }
            .map_err(Into::into);
        }
        let mut transaction = self.session.transaction.lock();
        let connection = transaction
            .as_ref()
            .ok_or(SQLiteError::NoActiveTransaction)?;
        *self.session.snapshot_branch.lock() = Arc::new(());
        if statement == "COMMIT" {
            // Materialize the failure before entering the branch. Holding the
            // mutex guard created by an `if let` scrutinee until the end of
            // the branch would deadlock when cleanup takes the same lock.
            let transaction_failure = self.session.transaction_failure.lock().clone();
            if let Some(error) = transaction_failure {
                if let Err(rollback_error) = connection.connection()?.execute_batch("ROLLBACK") {
                    self.session.native_restore.lock().take();
                    transaction.take();
                    self.session.transaction_failure.lock().take();
                    return Err(SQLiteError::SQLite(rollback_error));
                }
                self.session.native_restore.lock().take();
                transaction.take();
                self.session.transaction_failure.lock().take();
                return Err(SQLiteError::TransactionAborted(error));
            }
        }
        let native = if statement == "COMMIT" && self.session.native_restore.lock().is_some() {
            match self.prepare_initial_native_binding(connection.connection()?) {
                Ok(native) => Some(native),
                Err(error) => {
                    *self.session.transaction_failure.lock() = Some(error.to_string());
                    return Err(error);
                }
            }
        } else {
            None
        };
        if let Err(error) = connection.connection()?.execute_batch(statement) {
            self.session.native_restore.lock().take();
            transaction.take();
            self.session.transaction_failure.lock().take();
            return Err(SQLiteError::SQLite(error));
        }
        self.session.native_restore.lock().take();
        transaction.take();
        self.session.transaction_failure.lock().take();
        if let Some(native) = native {
            self.install_initial_native_binding(native);
        }
        Ok(())
    }

    fn with_transaction<R>(
        &self,
        logical: impl FnOnce(&VersionedKeyValueStore) -> uqa_storage::StorageBackendResult<R>,
        native: impl FnOnce(&Connection) -> Result<R>,
    ) -> Result<R> {
        self.surface_cleanup_failure()?;
        let _gate = self.session.gate.read();
        if let Some(store) = self.session.logical.get() {
            if !store.in_transaction() {
                return Err(SQLiteError::NoActiveTransaction);
            }
            return logical(store).map_err(Into::into);
        }
        let transaction = self.session.transaction.lock();
        let connection = transaction
            .as_ref()
            .ok_or(SQLiteError::NoActiveTransaction)?;
        self.check_native_access(connection.connection()?)?;
        native(connection.connection()?)
    }

    pub fn savepoint(&self, name: &str) -> Result<()> {
        self.with_transaction(
            |logical| logical.savepoint(name),
            |connection| {
                let stmt = format!("SAVEPOINT \"{}\"", name.replace('"', "\"\""));
                connection.execute_batch(&stmt)?;
                Ok(())
            },
        )
    }

    pub fn release_savepoint(&self, name: &str) -> Result<()> {
        self.with_transaction(
            |logical| logical.release_savepoint(name),
            |connection| {
                let stmt = format!("RELEASE SAVEPOINT \"{}\"", name.replace('"', "\"\""));
                connection.execute_batch(&stmt)?;
                Ok(())
            },
        )
    }

    pub fn rollback_to_savepoint(&self, name: &str) -> Result<()> {
        self.with_transaction(
            |logical| logical.rollback_to_savepoint(name),
            |connection| {
                let stmt = format!("ROLLBACK TO SAVEPOINT \"{}\"", name.replace('"', "\"\""));
                connection.execute_batch(&stmt)?;
                self.session.transaction_failure.lock().take();
                *self.session.snapshot_branch.lock() = Arc::new(());
                Ok(())
            },
        )
    }
}

fn default_pool_connections() -> usize {
    std::thread::available_parallelism()
        .map_or(MIN_POOL_CONNECTIONS, |parallelism| parallelism.get() * 2)
        .clamp(MIN_POOL_CONNECTIONS, MAX_POOL_CONNECTIONS)
}

#[cfg(test)]
mod tests;

impl From<uqa_storage::mvcc::VersionError> for SQLiteError {
    fn from(error: uqa_storage::mvcc::VersionError) -> Self {
        Self::from(error.into_storage_error())
    }
}

impl From<SQLiteError> for uqa_storage::StorageBackendError {
    fn from(source: SQLiteError) -> Self {
        match source {
            SQLiteError::Memory(error) => Self::Memory(error),
            SQLiteError::Cancelled(error) => Self::Cancelled(error),
            SQLiteError::StorageSource(error) => *error,
            source => Self::backend("SQLite", source),
        }
    }
}

impl From<SQLiteError> for uqa_storage::TransactionError {
    fn from(source: SQLiteError) -> Self {
        Self::Storage(source.into())
    }
}

impl From<uqa_storage::StorageBackendError> for SQLiteError {
    fn from(error: uqa_storage::StorageBackendError) -> Self {
        use uqa_storage::StorageBackendError;
        match error {
            StorageBackendError::Memory(error) => Self::Memory(error),
            StorageBackendError::Cancelled(error) => Self::Cancelled(error),
            StorageBackendError::Analysis(error) => Self::Analysis(error),
            StorageBackendError::Serde(error) => Self::Serde(error),
            StorageBackendError::Backend { backend, source } => match source.downcast::<Self>() {
                Ok(error) => *error,
                Err(source) => {
                    Self::StorageSource(Box::new(StorageBackendError::Backend { backend, source }))
                }
            },
            StorageBackendError::Other(message) => Self::StorageBackend(message),
        }
    }
}