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 liveness;
10#[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
11pub(in crate::mvcc) use liveness::lease_file;
12#[cfg(not(any(windows, all(unix, not(target_os = "emscripten")))))]
13pub(in crate::mvcc) use liveness::local_file_registry;
14
15use rusqlite::Connection;
16use uqa_core::memory::BudgetedVec;
17use uqa_storage::{
18    mvcc::{
19        receipt_lease_id, CommitStatus, DatabaseId, ReceiptAcknowledgement,
20        RetainedTransactionAllocation, SerializableGraph, SerializableLeases, StorageTransactionId,
21        VersionError, VersionResult,
22    },
23    read_control::StorageReadControl,
24};
25
26use super::{admission, codec, native, write, PhysicalResult, SQLiteRecordStore};
27
28impl SQLiteRecordStore {
29    /// 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.
30    pub fn set_receipt_retention_limit(
31        &self,
32        limit: u64,
33        control: &StorageReadControl,
34    ) -> VersionResult<()> {
35        let limit = i64::try_from(limit).ok().filter(|limit| *limit > 0).ok_or(
36            VersionError::InvalidEncoding("invalid receipt retention limit"),
37        )?;
38        self.with_write(control, |connection| {
39            let _permit = admission::permit(connection, control)?;
40            let transaction = admission::begin(connection, control)?;
41            native::check_mapping(&transaction, self.native)?;
42            codec::header(&transaction, self.identity)?;
43            transaction.execute(
44                "UPDATE _uqa_mvcc_metadata SET receipt_limit = ?1 WHERE singleton = 1",
45                [limit],
46            )?;
47            admission::commit(transaction, control)
48        })
49    }
50
51    pub(super) fn allocate_receipt_owner(
52        &self,
53        control: &StorageReadControl,
54    ) -> VersionResult<RetainedTransactionAllocation> {
55        self.with_receipt_admission(control, |leases| {
56            let mut owner = None;
57            let id = self.with_write(control, |connection| {
58                write::allocate_with_owner(
59                    connection,
60                    self.identity,
61                    self.native,
62                    true,
63                    control,
64                    |id| {
65                        owner = Some(leases.retain(receipt_lease_id(id), control)?);
66                        Ok(())
67                    },
68                )
69            })?;
70            RetainedTransactionAllocation::retain(
71                id,
72                owner.expect("lease precedes managed allocation"),
73            )
74        })
75    }
76
77    pub(super) fn reclaim_receipts(&self, control: &StorageReadControl) -> VersionResult<u64> {
78        // Finish and persist ordinary SSI recovery first. Deletion uses only a separately loaded durable graph, never the unpersisted mutations of that recovery.
79        self.recover_serializable(control)?;
80        let held = self.serializable_admission(control)?;
81        self.with_receipt_admission(control, |leases| {
82            let removed = self.with_write(control, |connection| {
83                reclaim(
84                    connection,
85                    self.identity,
86                    self.native,
87                    held.graph(),
88                    leases,
89                    control,
90                )
91            })?;
92            leases.reclaim();
93            Ok(removed)
94        })
95    }
96}
97
98pub(super) fn acknowledge(
99    connection: &Connection,
100    native: Option<native::NativeRecordNamespace>,
101    acknowledgement: ReceiptAcknowledgement,
102    control: &StorageReadControl,
103) -> PhysicalResult<()> {
104    control.check().map_err(VersionError::from)?;
105    let _permit = admission::permit(connection, control)?;
106    let transaction = admission::begin(connection, control)?;
107    native::check_mapping(&transaction, native)?;
108    let id = acknowledgement.transaction();
109    let header = codec::header(&transaction, id.database())?;
110    if id.allocation() > header.allocated {
111        return Err(VersionError::UnknownTransaction.into());
112    }
113    acknowledgement.validate(codec::status(&transaction, id)?)?;
114    transaction.execute("UPDATE _uqa_mvcc_transactions SET status = CASE status WHEN 1 THEN 3 WHEN 2 THEN 4 ELSE status END WHERE allocation = ?1", [id.allocation().to_be_bytes().as_slice()])?;
115    admission::commit(transaction, control)
116}
117
118/// 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.
119fn reclaim(
120    connection: &Connection,
121    identity: DatabaseId,
122    native: Option<native::NativeRecordNamespace>,
123    graph: &SerializableGraph,
124    leases: &dyn SerializableLeases,
125    control: &StorageReadControl,
126) -> PhysicalResult<u64> {
127    let _permit = admission::permit(connection, control)?;
128    let transaction = admission::begin(connection, control)?;
129    native::check_mapping(&transaction, native)?;
130    let header = codec::header(&transaction, identity)?;
131    let mut selected = BudgetedVec::new(control.memory());
132    {
133        let mut statement = transaction.prepare("SELECT allocation, status, managed FROM _uqa_mvcc_transactions WHERE status IN (3, 4) OR managed = 1 ORDER BY allocation")?;
134        let mut rows = statement.query([])?;
135        while let Some(row) = rows.next()? {
136            control.check().map_err(VersionError::from)?;
137            let allocation = codec::integer(codec::bytes(row, 0)?)?;
138            if allocation > header.allocated {
139                return Err(
140                    VersionError::InvalidEncoding("receipt exceeds allocation watermark").into(),
141                );
142            }
143            let id = StorageTransactionId::new(identity, allocation)?;
144            let status: i64 = row.get(1)?;
145            let acknowledged = matches!(status, 3 | 4);
146            if acknowledged && graph.retains_transaction_receipt(id) {
147                continue;
148            }
149            let managed: bool = row.get(2)?;
150            if acknowledged || (managed && !leases.is_alive(receipt_lease_id(id), control)?) {
151                // Decode authoritative status before preparing any change, including rejecting corruption. Unknown can never be inferred from owner death.
152                let status = codec::status(&transaction, id)?;
153                if status == CommitStatus::Unknown {
154                    return Err(VersionError::UnknownTransaction.into());
155                }
156                selected
157                    .push((
158                        allocation.to_be_bytes(),
159                        !graph.retains_transaction_receipt(id),
160                        matches!(status, CommitStatus::Committed(_)),
161                    ))
162                    .map_err(VersionError::from)?;
163                if selected.len() == 256 {
164                    break;
165                }
166            }
167        }
168    }
169    let mut removed = 0;
170    for (allocation, delete, committed) in selected.iter() {
171        control.check().map_err(VersionError::from)?;
172        if *delete {
173            transaction.execute(
174                "DELETE FROM _uqa_mvcc_transactions WHERE allocation = ?1",
175                [allocation.as_slice()],
176            )?;
177            removed += 1;
178        } else {
179            transaction.execute(
180                "UPDATE _uqa_mvcc_transactions SET status = ?2 WHERE allocation = ?1",
181                rusqlite::params![allocation.as_slice(), if *committed { 4 } else { 3 }],
182            )?;
183        }
184    }
185    admission::commit(transaction, control)?;
186    Ok(removed)
187}