Skip to main content

qualia_core_db/sensing/local_custody/
quota.rs

1//! Conservative caller-owned aggregate admission for one protected root.
2//!
3//! Charges survive every publication error and unwind. There is no refund or
4//! directory scan; recovery may construct a new ledger only from a freshly
5//! authenticated usage snapshot. This is cooperative in-process accounting,
6//! not a durable cross-process quota or a filesystem allocation limit.
7use super::{
8    chain::{publish_chain_bundle, ChainAuthority, ChainPublication, ChainPublicationError},
9    entry_size, publish_bundle, validate_root, CustodyAuthority, CustodyError, PublishedBundle,
10    SidecarReceipt, SIDECAR_BYTES,
11};
12use std::path::Path;
13
14pub mod recovery;
15pub use recovery::RecoveryRootScope;
16pub mod staging;
17pub use staging::StagingCharge;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub struct QuotaLimits {
21    pub encoded_bytes: u64,
22    pub entries: u64,
23}
24
25/// Host snapshot must include committed, orphan and uncertain bundle charges.
26/// The opaque snapshot ID must bind the root and current usage under the host's
27/// trusted freshness and lease policy. Counts exclude OS/runtime allocations.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub struct QuotaSnapshot {
30    pub id: [u8; 32],
31    pub encoded_bytes: u64,
32    pub entries: u64,
33}
34
35pub trait QuotaSnapshotAuthority {
36    fn admit_usage(&self, root: &Path, limits: QuotaLimits, snapshot: QuotaSnapshot) -> bool;
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum QuotaError {
41    InvalidScope,
42    InvalidLimits,
43    SnapshotDenied,
44    ScopeMismatch,
45    AlreadyCharged,
46    SlotsExhausted,
47    BytesExceeded,
48    EntriesExceeded,
49    Overflow,
50}
51
52/// N bounds additional publication attempts tracked in this ledger. The host
53/// must hold its aggregate-quota lease for the ledger's complete lifetime.
54pub struct CustodyQuota<'root, const N: usize> {
55    root: &'root Path,
56    limits: QuotaLimits,
57    usage: QuotaSnapshot,
58    charged: [Option<[u8; 32]>; N],
59    recovery_owner: usize,
60    recovery_scope_serial: u64,
61}
62
63impl<'root, const N: usize> CustodyQuota<'root, N> {
64    pub fn from_authenticated_usage(
65        root: &'root Path,
66        limits: QuotaLimits,
67        snapshot: QuotaSnapshot,
68        authority: &impl QuotaSnapshotAuthority,
69    ) -> Result<Self, QuotaError> {
70        validate_root(root).map_err(|_| QuotaError::InvalidScope)?;
71        if N == 0
72            || limits.encoded_bytes == 0
73            || limits.entries == 0
74            || snapshot.encoded_bytes > limits.encoded_bytes
75            || snapshot.entries > limits.entries
76            || snapshot.id.iter().all(|byte| *byte == 0)
77        {
78            return Err(QuotaError::InvalidLimits);
79        }
80        if !authority.admit_usage(root, limits, snapshot) {
81            return Err(QuotaError::SnapshotDenied);
82        }
83        Ok(Self {
84            root,
85            limits,
86            usage: snapshot,
87            charged: [None; N],
88            recovery_owner: recovery::next_recovery_owner()?,
89            recovery_scope_serial: 0,
90        })
91    }
92
93    /// Current charged usage, including attempts that may not have published.
94    /// This does not mint a fresh authenticated snapshot identifier.
95    pub const fn charged_usage(&self) -> (u64, u64) {
96        (self.usage.encoded_bytes, self.usage.entries)
97    }
98
99    fn charge(
100        &mut self,
101        root: &Path,
102        checkpoint: [u8; 32],
103        bytes: usize,
104    ) -> Result<(), QuotaError> {
105        let bytes = u64::try_from(bytes).map_err(|_| QuotaError::Overflow)?;
106        self.charge_u64(root, checkpoint, bytes)
107    }
108
109    fn charge_u64(
110        &mut self,
111        root: &Path,
112        checkpoint: [u8; 32],
113        bytes: u64,
114    ) -> Result<(), QuotaError> {
115        if root != self.root {
116            return Err(QuotaError::ScopeMismatch);
117        }
118        if self.charged.contains(&Some(checkpoint)) {
119            return Err(QuotaError::AlreadyCharged);
120        }
121        let index = self
122            .charged
123            .iter()
124            .position(Option::is_none)
125            .ok_or(QuotaError::SlotsExhausted)?;
126        let total = self
127            .usage
128            .encoded_bytes
129            .checked_add(bytes)
130            .ok_or(QuotaError::Overflow)?;
131        let entries = self
132            .usage
133            .entries
134            .checked_add(1)
135            .ok_or(QuotaError::Overflow)?;
136        if total > self.limits.encoded_bytes {
137            return Err(QuotaError::BytesExceeded);
138        }
139        if entries > self.limits.entries {
140            return Err(QuotaError::EntriesExceeded);
141        }
142        self.usage.encoded_bytes = total;
143        self.usage.entries = entries;
144        self.charged[index] = Some(checkpoint);
145        Ok(())
146    }
147}
148
149#[derive(Debug)]
150pub enum QuotaPublicationError<E> {
151    Quota(QuotaError),
152    Preflight(CustodyError),
153    /// The charge is retained even if the attempt failed before publication.
154    AttemptCharged {
155        checkpoint: [u8; 32],
156        bytes: usize,
157        error: E,
158    },
159}
160
161fn admit<const N: usize>(
162    root: &Path,
163    sidecar: &[u8; SIDECAR_BYTES],
164    payload: &[u8],
165    receipt: &SidecarReceipt,
166    budget: usize,
167    quota: &mut CustodyQuota<'_, N>,
168    authority: &mut impl CustodyAuthority,
169) -> Result<usize, QuotaPublicationError<CustodyError>> {
170    validate_root(root).map_err(QuotaPublicationError::Preflight)?;
171    let total = entry_size(payload.len(), budget).map_err(QuotaPublicationError::Preflight)?;
172    receipt
173        .verify_with_authority(sidecar, payload, payload.len(), authority)
174        .map_err(|e| QuotaPublicationError::Preflight(CustodyError::Receipt(e)))?;
175    if !authority.permit_publish(root, receipt, sidecar, payload, total) {
176        return Err(QuotaPublicationError::Preflight(
177            CustodyError::PermissionDenied,
178        ));
179    }
180    quota
181        .charge(root, receipt.checkpoint(), total)
182        .map_err(QuotaPublicationError::Quota)?;
183    Ok(total)
184}
185
186/// Admit aggregate encoded bundle bytes before any producer I/O. The encoded
187/// byte cap excludes filesystem overhead and head/lock files; host disk quotas
188/// must cover those. Authority still revalidates policy during publication.
189#[allow(clippy::too_many_arguments)]
190pub fn publish_bundle_with_quota<const N: usize>(
191    root: &Path,
192    sidecar: &[u8; SIDECAR_BYTES],
193    payload: &[u8],
194    receipt: &SidecarReceipt,
195    budget: usize,
196    quota: &mut CustodyQuota<'_, N>,
197    authority: &mut impl CustodyAuthority,
198) -> Result<PublishedBundle, QuotaPublicationError<CustodyError>> {
199    let bytes = admit(root, sidecar, payload, receipt, budget, quota, authority)?;
200    publish_bundle(root, sidecar, payload, receipt, budget, authority).map_err(|error| {
201        QuotaPublicationError::AttemptCharged {
202            checkpoint: receipt.checkpoint(),
203            bytes,
204            error,
205        }
206    })
207}
208
209#[allow(clippy::too_many_arguments)]
210pub fn publish_chain_bundle_with_quota<const N: usize>(
211    root: &Path,
212    sidecar: &[u8; SIDECAR_BYTES],
213    payload: &[u8],
214    receipt: &SidecarReceipt,
215    budget: usize,
216    quota: &mut CustodyQuota<'_, N>,
217    authority: &mut impl ChainAuthority,
218) -> Result<ChainPublication, QuotaPublicationError<ChainPublicationError>> {
219    let bytes =
220        admit(root, sidecar, payload, receipt, budget, quota, authority).map_err(|error| {
221            match error {
222                QuotaPublicationError::Quota(error) => QuotaPublicationError::Quota(error),
223                QuotaPublicationError::Preflight(error) => QuotaPublicationError::Preflight(error),
224                QuotaPublicationError::AttemptCharged { .. } => {
225                    unreachable!("admission does not publish")
226                }
227            }
228        })?;
229    publish_chain_bundle(root, sidecar, payload, receipt, budget, authority).map_err(|error| {
230        QuotaPublicationError::AttemptCharged {
231            checkpoint: receipt.checkpoint(),
232            bytes,
233            error,
234        }
235    })
236}
237
238#[cfg(test)]
239mod tests;