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