Skip to main content

coven_database/
write_boundary.rs

1//! Checked entry boundaries, their immutable coverage, and slot selection.
2use crate::sqlite::StoreSql;
3use crate::write_encoding::{audience, counter, damaged};
4use crate::{DbError, StoreState, StoreVersion};
5use coven_format::{
6    admin::SnapshotId, snapshot_rows::ChangeVerdict, value::Slot, write::WriteHeader,
7};
8use coven_foundation::id_source::DeviceId;
9use coven_merge::Audience;
10use sqlive::rusqlite::params;
11use std::collections::BTreeSet;
12
13/// A checked raise/reset and the snapshot named by that entry. Its selection is
14/// derived from kept entries, independently of whether coverage has been read.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum Boundary {
17    /// A breaking schema raise.
18    SchemaChange(StoreVersion),
19    /// A reset of the named snapshot's audience.
20    Reset {
21        /// The reset's counted slot.
22        entry: Slot,
23        /// Its snapshot, including the audience.
24        snapshot: SnapshotId,
25    },
26}
27
28impl Boundary {
29    /// The checked entry that owns this boundary.
30    pub fn entry(&self) -> Slot {
31        match self {
32            Self::SchemaChange(version) => version.entry,
33            Self::Reset { entry, .. } => *entry,
34        }
35    }
36
37    /// The immutable snapshot named by this boundary.
38    pub fn snapshot(&self) -> &SnapshotId {
39        match self {
40            Self::SchemaChange(version) => &version.snapshot,
41            Self::Reset { snapshot, .. } => snapshot,
42        }
43    }
44
45    /// The no-op rule for a raise: one that doesn't go past the version its
46    /// audience has reached, a circle's base included, changes nothing.
47    pub fn schema_in_place(state: &StoreState, version: u32, snapshot: &SnapshotId) -> bool {
48        version <= state.reached(&snapshot.audience)
49    }
50
51    /// Repeating the current reset does not introduce a new boundary.
52    pub fn reset_in_place(state: &StoreState, snapshot: &SnapshotId) -> bool {
53        state.resets.get(&snapshot.audience) == Some(snapshot)
54    }
55
56    /// Whether applying this checked boundary leaves the applied state unchanged.
57    pub fn already_in_place(&self, state: &StoreState) -> bool {
58        match self {
59            Self::SchemaChange(version) => {
60                Self::schema_in_place(state, version.number, &version.snapshot)
61            }
62            Self::Reset { snapshot, .. } => Self::reset_in_place(state, snapshot),
63        }
64    }
65
66    /// Realize a non-no-op boundary after the preceding prefix authorizes it.
67    pub fn apply(&self, state: &mut StoreState) {
68        match self {
69            Self::SchemaChange(version) => {
70                state.schema.insert(version.snapshot.audience.clone(), version.clone());
71            }
72            Self::Reset { snapshot, .. } => {
73                state.resets.insert(snapshot.audience.clone(), snapshot.clone());
74            }
75        }
76    }
77
78    pub(crate) fn load_selected(database: &StoreSql) -> Result<Vec<Self>, DbError> {
79        Ok(retained(database)?.into_iter().map(|row| row.boundary).collect())
80    }
81}
82
83/// A checked raise or reset and its authenticated snapshot coverage.
84#[derive(Clone, Debug, PartialEq, Eq)]
85pub struct BoundaryCoverage {
86    /// The checked change, including its original slot and snapshot identity.
87    pub boundary: Boundary,
88    /// The slot coverage authenticated by its snapshot prefix.
89    pub included: u64,
90}
91
92/// Keep a checked boundary, once, at its entry's slot. No later reset of
93/// its audience names coverage below it (§16.3).
94pub(crate) fn record(database: &StoreSql, boundary: &Boundary) -> Result<(), DbError> {
95    let (kind, version) = match boundary {
96        Boundary::SchemaChange(version) => ("schema", Some(version.number)),
97        Boundary::Reset { .. } => ("reset", None),
98    };
99    let entry = boundary.entry();
100    let snapshot = boundary.snapshot();
101    crate::reset_bytes::bound(database, &snapshot.audience, entry.get())?;
102    database.execute(
103        "INSERT INTO _coven_boundaries(slot,kind,version,audience,snapshot_device,snapshot_number)
104         VALUES(?1,?2,?3,?4,?5,?6) ON CONFLICT(slot) DO NOTHING",
105        params![
106            entry.get().to_be_bytes().as_slice(),
107            kind,
108            version,
109            &snapshot.audience,
110            snapshot.device,
111            snapshot.number.to_be_bytes().as_slice()
112        ],
113    )?;
114    Ok(())
115}
116
117/// Keep a boundary with its authenticated coverage and realize it in the
118/// data view: whether this applied it, which a boundary already applied
119/// does not. Coverage once checked never changes.
120pub(crate) fn record_coverage(
121    database: &StoreSql,
122    coverage: &BoundaryCoverage,
123) -> Result<bool, DbError> {
124    record(database, &coverage.boundary)?;
125    let previous: (Option<Vec<u8>>, bool) = database.query_row(
126        "SELECT included,applied FROM _coven_boundaries WHERE slot=?1",
127        [coverage.boundary.entry().get().to_be_bytes().as_slice()],
128        |row| Ok((row.get(0)?, row.get(1)?)),
129    )?;
130    let included = coverage.included.to_be_bytes().to_vec();
131    if let Some(checked) = previous.0 {
132        if checked != included {
133            return Err(crate::snapshot_error::invalid("checked boundary coverage changed"));
134        }
135    }
136    if previous.1 {
137        return Ok(false);
138    }
139    database.execute(
140        "UPDATE _coven_boundaries SET included=?2,applied=1 WHERE slot=?1",
141        params![coverage.boundary.entry().get().to_be_bytes().as_slice(), included],
142    )?;
143    Ok(true)
144}
145
146/// Install the reload's effective readable boundaries, retaining every
147/// checked coverage fact. The applied bit records the committed data view,
148/// not slot selection. It also distinguishes a repeated reset reload.
149pub(crate) fn replace(
150    database: &StoreSql,
151    boundaries: Vec<BoundaryCoverage>,
152) -> Result<Vec<Slot>, DbError> {
153    let mut ids = BTreeSet::new();
154    for boundary in &boundaries {
155        if !ids.insert(boundary.boundary.entry()) {
156            return Err(crate::snapshot_error::invalid("reload repeats a boundary slot"));
157        }
158    }
159    let previous: BTreeSet<_> = database
160        .query("SELECT slot FROM _coven_boundaries WHERE applied=1 AND kind='reset'", [], |row| {
161            crate::store_state_tables::slot(row, 0)
162        })?
163        .into_iter()
164        .collect();
165    let changed_resets = boundaries
166        .iter()
167        .filter_map(|coverage| match &coverage.boundary {
168            Boundary::Reset { entry, .. } if ids.contains(entry) && !previous.contains(entry) => {
169                Some(*entry)
170            }
171            _ => None,
172        })
173        .collect();
174    database.execute("DELETE FROM _coven_boundaries", [])?;
175    for boundary in &boundaries {
176        record_coverage(database, boundary)?;
177    }
178    Ok(changed_resets)
179}
180
181struct RetainedBoundary {
182    boundary: Boundary,
183    included: Option<u64>,
184    applied: bool,
185}
186
187fn retained(database: &StoreSql) -> Result<Vec<RetainedBoundary>, DbError> {
188    Ok(database.query(
189        "SELECT b.kind,b.version,b.audience,b.snapshot_device,b.snapshot_number,b.slot,b.included,b.applied
190         FROM _coven_boundaries b ORDER BY b.slot",
191        [],
192        |row| {
193            let snapshot = SnapshotId {
194                audience: audience(row, 2)?,
195                device: row.get::<_, DeviceId>(3)?,
196                number: counter(row.get(4)?)?,
197            };
198            let entry = crate::store_state_tables::slot(row, 5)?;
199            let boundary = match (row.get::<_, String>(0)?.as_str(), row.get::<_, Option<u32>>(1)?) {
200                ("schema", Some(number)) => Boundary::SchemaChange(StoreVersion { number, snapshot, entry }),
201                ("reset", None) => Boundary::Reset { entry, snapshot },
202                _ => return Err(damaged(0, sqlive::rusqlite::types::Type::Text)),
203            };
204            let included = row.get::<_, Option<Vec<u8>>>(6)?.map(counter).transpose()?;
205            Ok(RetainedBoundary { boundary, included, applied: row.get(7)? })
206        },
207    )?)
208}
209
210/// What a realized boundary decides about an uncovered part of its audience.
211#[derive(Clone, Debug, PartialEq, Eq)]
212pub(crate) enum BoundaryRule {
213    /// An older-schema part needs admission through the raise's retained
214    /// breaking steps (§18.6).
215    Raise(u32),
216    /// A reset ignores a part whose write had not read this entry (§19.4).
217    Reset(Slot),
218}
219
220/// The boundary facts realized by the current data projection.
221pub(crate) struct WriteBoundary {
222    pub(crate) audience: Audience,
223    pub(crate) rule: BoundaryRule,
224    pub(crate) included: u64,
225}
226
227impl WriteBoundary {
228    pub(crate) fn load(database: &StoreSql) -> Result<Vec<Self>, DbError> {
229        let mut state = StoreState::default();
230        let mut result = Vec::new();
231        for row in retained(database)? {
232            if row.boundary.already_in_place(&state) {
233                continue;
234            }
235            row.boundary.apply(&mut state);
236            if row.applied {
237                result.push(Self {
238                    audience: row.boundary.snapshot().audience.clone(),
239                    rule: match &row.boundary {
240                        Boundary::SchemaChange(version) => BoundaryRule::Raise(version.number),
241                        Boundary::Reset { entry, .. } => BoundaryRule::Reset(*entry),
242                    },
243                    included: row.included.ok_or(DbError::DamagedDatabase)?,
244                });
245            }
246        }
247        Ok(result)
248    }
249
250    /// The realized boundaries, with each unpublished raise capture judging
251    /// its audience as its kept raise will: a migrated device applies
252    /// received writes before its raise is kept, so a capture taken again
253    /// after its catch-up covers them (§16.3, §18.5). A capture whose
254    /// audience already realized a raise to its version adds nothing.
255    pub(crate) fn judging(database: &StoreSql) -> Result<Vec<Self>, DbError> {
256        let mut boundaries = Self::load(database)?;
257        for (audience, version, included) in crate::raise_capture::provisional(database)? {
258            let realized = boundaries.iter().any(|b| {
259                b.audience == audience
260                    && matches!(b.rule, BoundaryRule::Raise(number) if number >= version)
261            });
262            if !realized {
263                boundaries.push(Self { audience, rule: BoundaryRule::Raise(version), included });
264            }
265        }
266        Ok(boundaries)
267    }
268
269    /// This boundary's verdict on an uncovered part of its audience: a kept
270    /// reset ignores a part whose write had not read the reset entry (§19.4);
271    /// a raise returns a candidate schema exclusion, resolved by the interpreter
272    /// using the retained breaking steps (§18.6).
273    pub(crate) fn excludes(
274        &self,
275        header: &WriteHeader,
276        audience: &Audience,
277        slot: Option<Slot>,
278    ) -> Option<ChangeVerdict> {
279        if *audience != self.audience || slot.is_some_and(|slot| slot.get() <= self.included) {
280            return None;
281        }
282        match &self.rule {
283            BoundaryRule::Raise(version) => {
284                (header.schema_version < *version).then_some(ChangeVerdict::Excluded(*version))
285            }
286            BoundaryRule::Reset(entry) => {
287                (header.read_through < entry.get()).then_some(ChangeVerdict::Ignored(*entry))
288            }
289        }
290    }
291
292    /// Whether the selected boundaries ignore one part (§18.6): its changes
293    /// stay as evidence and are never checked or merged.
294    pub(crate) fn ignore(
295        boundaries: &[Self],
296        header: &WriteHeader,
297        audience: &Audience,
298        slot: Option<Slot>,
299    ) -> bool {
300        matches!(
301            Self::part_verdict(boundaries, header, audience, slot),
302            Some(ChangeVerdict::Ignored(_))
303        )
304    }
305
306    /// The selected boundaries' combined verdict on one part. Reset
307    /// eligibility comes first, so an ignored part never gains a schema loss;
308    /// otherwise the highest excluding raise names the loss.
309    pub(crate) fn part_verdict(
310        boundaries: &[Self],
311        header: &WriteHeader,
312        audience: &Audience,
313        slot: Option<Slot>,
314    ) -> Option<ChangeVerdict> {
315        let verdicts: Vec<_> = boundaries
316            .iter()
317            .filter_map(|boundary| boundary.excludes(header, audience, slot))
318            .collect();
319        verdicts
320            .iter()
321            .find(|verdict| matches!(verdict, ChangeVerdict::Ignored(_)))
322            .cloned()
323            .or_else(|| {
324                verdicts
325                    .iter()
326                    .filter_map(|verdict| match verdict {
327                        ChangeVerdict::Excluded(version) => Some(*version),
328                        _ => None,
329                    })
330                    .max()
331                    .map(ChangeVerdict::Excluded)
332            })
333    }
334}
335#[cfg(test)]
336#[path = "write_boundary_tests.rs"]
337pub(crate) mod tests;