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