Skip to main content

uqa_storage_sqlite/mvcc/
receipts.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Explicit acknowledgement and managed owner recovery preserve durable SSI references.
8
9mod allocations;
10mod liveness;
11pub(in crate::mvcc) use allocations::ManagedAllocations;
12#[cfg(not(any(windows, all(unix, not(target_os = "emscripten")))))]
13pub(in crate::mvcc) use liveness::local_file_registry;
14#[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
15pub(in crate::mvcc) use liveness::{lease_file, ReceiptLeaseFile};
16
17use rusqlite::{Connection, OptionalExtension};
18use uqa_core::memory::BudgetedVec;
19use uqa_storage::{
20    mvcc::{
21        receipt_lease_id, CommitStatus, DatabaseId, ReceiptAcknowledgement,
22        RetainedTransactionAllocation, SerializableGraph, SerializableLeases, StorageTransactionId,
23        VersionError, VersionResult,
24    },
25    read_control::StorageReadControl,
26};
27
28use super::synchronization::RelaxedSynchronization;
29use super::{admission, codec, native, write, PhysicalResult, SQLiteRecordStore};
30
31impl SQLiteRecordStore {
32    /// Set the shared database's maximum retained receipt count. Pending, unacknowledged and SSI-referenced receipts all count. Lowering the limit preserves existing entries and prevents allocation until release/reclamation makes room. The default is 65,536 entries; zero and values above `SQLite`'s positive i64 range are rejected.
33    pub fn set_receipt_retention_limit(
34        &self,
35        limit: u64,
36        control: &StorageReadControl,
37    ) -> VersionResult<()> {
38        let limit = i64::try_from(limit).ok().filter(|limit| *limit > 0).ok_or(
39            VersionError::InvalidEncoding("invalid receipt retention limit"),
40        )?;
41        self.with_write(control, |connection| {
42            let _permit = admission::permit(connection, control)?;
43            let transaction = admission::begin(connection, control)?;
44            native::check_mapping(&transaction, self.native)?;
45            codec::header(&transaction, self.identity)?;
46            transaction
47                .prepare_cached(
48                    "UPDATE _uqa_mvcc_metadata SET receipt_limit = ?1 WHERE singleton = 1",
49                )?
50                .execute([limit])?;
51            admission::commit(transaction, control)
52        })
53    }
54
55    pub(super) fn allocate_receipt_owner(
56        &self,
57        control: &StorageReadControl,
58    ) -> VersionResult<RetainedTransactionAllocation> {
59        if self.connection.database_path().is_some() {
60            return self.managed_allocations.allocate(self, control);
61        }
62        self.allocate_one_receipt_owner(control)
63    }
64
65    fn allocate_one_receipt_owner(
66        &self,
67        control: &StorageReadControl,
68    ) -> VersionResult<RetainedTransactionAllocation> {
69        self.with_receipt_admission(control, |leases| {
70            let mut owner = None;
71            let id = self.with_write(control, |connection| {
72                write::allocate_with_owner(
73                    connection,
74                    self.identity,
75                    self.native,
76                    true,
77                    control,
78                    |id| {
79                        owner = Some(leases.retain(receipt_lease_id(id), control)?);
80                        Ok(())
81                    },
82                )
83            })?;
84            RetainedTransactionAllocation::retain(
85                id,
86                owner.expect("lease precedes managed allocation"),
87            )
88        })
89    }
90
91    pub(super) fn reclaim_receipts(&self, control: &StorageReadControl) -> VersionResult<u64> {
92        // Finish and persist ordinary SSI recovery first. Deletion uses only a separately loaded durable graph, never the unpersisted mutations of that recovery.
93        self.recover_serializable(control)?;
94        let held = self.serializable_admission(control)?;
95        self.with_receipt_admission(control, |leases| {
96            let removed = self.with_write(control, |connection| {
97                reclaim(
98                    connection,
99                    self.identity,
100                    self.native,
101                    held.graph(),
102                    leases,
103                    control,
104                )
105            })?;
106            leases.reclaim();
107            Ok(removed)
108        })
109    }
110}
111
112pub(super) fn acknowledge(
113    connection: &Connection,
114    native: Option<native::NativeRecordNamespace>,
115    acknowledgement: ReceiptAcknowledgement,
116    control: &StorageReadControl,
117) -> PhysicalResult<()> {
118    control.check().map_err(VersionError::from)?;
119    let permit = admission::permit(connection, control)?;
120    let id = acknowledgement.transaction();
121    // An acknowledgement only releases its owner's right to resolve an outcome. A power loss that discards it leaves the receipt of a managed owner that is dead, which reclamation acknowledges on the owner's behalf. A manual owner is never acknowledged implicitly, so its acknowledgement keeps its own sync. The owner kind of an allocation never changes, and it is read before the transaction because the synchronization level cannot change inside one. Under a rollback journal that read waits for a writer that holds the database, so it is admitted as the transaction is: a busy database is waited for, not reported.
122    let managed = admission::retry(connection, true, control, || {
123        Ok(connection
124            .prepare_cached("SELECT managed FROM _uqa_mvcc_transactions WHERE allocation = ?1")?
125            .query_row([id.allocation().to_be_bytes().as_slice()], |row| {
126                row.get::<_, bool>(0)
127            })
128            .optional()?)
129    })?;
130    let _synchronization = if managed == Some(true) {
131        RelaxedSynchronization::relax(connection, &permit)?
132    } else {
133        None
134    };
135    let transaction = admission::begin(connection, control)?;
136    native::check_mapping(&transaction, native)?;
137    let header = codec::header(&transaction, id.database())?;
138    if id.allocation() > header.allocated {
139        return Err(VersionError::UnknownTransaction.into());
140    }
141    acknowledgement.validate(codec::status(&transaction, id)?)?;
142    transaction.prepare_cached("UPDATE _uqa_mvcc_transactions SET status = CASE status WHEN 1 THEN 3 WHEN 2 THEN 4 ELSE status END WHERE allocation = ?1")?.execute([id.allocation().to_be_bytes().as_slice()])?;
143    admission::commit(transaction, control)
144}
145
146/// A live managed lease keeps the terminal receipt available throughout this read. Dropping that lease after successful validation authorizes the existing recovery path; it never changes the durable outcome or SSI retention.
147pub(super) fn validate_retained(
148    connection: &Connection,
149    native: Option<native::NativeRecordNamespace>,
150    acknowledgement: ReceiptAcknowledgement,
151    control: &StorageReadControl,
152) -> PhysicalResult<bool> {
153    admission::retry(connection, true, control, || {
154        let read = connection.unchecked_transaction()?;
155        let id = acknowledgement.transaction();
156        native::check_mapping(&read, native)?;
157        let header = codec::header(&read, id.database())?;
158        if id.allocation() > header.allocated {
159            return Err(VersionError::UnknownTransaction.into());
160        }
161        acknowledgement.validate(codec::status(&read, id)?)?;
162        let managed = read
163            .prepare_cached("SELECT managed FROM _uqa_mvcc_transactions WHERE allocation = ?1")?
164            .query_row([id.allocation().to_be_bytes().as_slice()], |row| {
165                row.get::<_, bool>(0)
166            })
167            .optional()?;
168        control.check().map_err(VersionError::from)?;
169        read.commit()?;
170        Ok(managed == Some(true))
171    })
172}
173
174/// SSI and receipt admission remain held across this atomic main write. Authoritatively dead managed owners release their retry rights; manual owners never do so implicitly. Their original physical state still decides commit/abort, and every retained graph reference remains protected.
175fn reclaim(
176    connection: &Connection,
177    identity: DatabaseId,
178    native: Option<native::NativeRecordNamespace>,
179    graph: &SerializableGraph,
180    leases: &dyn SerializableLeases,
181    control: &StorageReadControl,
182) -> PhysicalResult<u64> {
183    let _permit = admission::permit(connection, control)?;
184    let transaction = admission::begin(connection, control)?;
185    native::check_mapping(&transaction, native)?;
186    let header = codec::header(&transaction, identity)?;
187    let mut selected = BudgetedVec::new(control.memory());
188    {
189        let mut statement = transaction.prepare_cached("SELECT allocation, status, managed FROM _uqa_mvcc_transactions WHERE status IN (3, 4) OR managed = 1 ORDER BY allocation")?;
190        let mut rows = statement.query([])?;
191        while let Some(row) = rows.next()? {
192            control.check().map_err(VersionError::from)?;
193            let allocation = codec::integer(codec::bytes(row, 0)?)?;
194            if allocation > header.allocated {
195                return Err(
196                    VersionError::InvalidEncoding("receipt exceeds allocation watermark").into(),
197                );
198            }
199            let id = StorageTransactionId::new(identity, allocation)?;
200            let status: i64 = row.get(1)?;
201            let acknowledged = matches!(status, 3 | 4);
202            if acknowledged && graph.retains_transaction_receipt(id) {
203                continue;
204            }
205            let managed: bool = row.get(2)?;
206            if acknowledged || (managed && !leases.is_alive(receipt_lease_id(id), control)?) {
207                // Decode authoritative status before preparing any change, including rejecting corruption. Unknown can never be inferred from owner death.
208                let status = codec::status(&transaction, id)?;
209                if status == CommitStatus::Unknown {
210                    return Err(VersionError::UnknownTransaction.into());
211                }
212                selected
213                    .push((
214                        allocation.to_be_bytes(),
215                        !graph.retains_transaction_receipt(id),
216                        matches!(status, CommitStatus::Committed(_)),
217                    ))
218                    .map_err(VersionError::from)?;
219                if selected.len() == 256 {
220                    break;
221                }
222            }
223        }
224    }
225    let mut removed = 0;
226    for (allocation, delete, committed) in selected.iter() {
227        control.check().map_err(VersionError::from)?;
228        if *delete {
229            transaction
230                .prepare_cached("DELETE FROM _uqa_mvcc_transactions WHERE allocation = ?1")?
231                .execute([allocation.as_slice()])?;
232            removed += 1;
233        } else {
234            transaction
235                .prepare_cached(
236                    "UPDATE _uqa_mvcc_transactions SET status = ?2 WHERE allocation = ?1",
237                )?
238                .execute(rusqlite::params![
239                    allocation.as_slice(),
240                    if *committed { 4 } else { 3 }
241                ])?;
242        }
243    }
244    admission::commit(transaction, control)?;
245    Ok(removed)
246}