Skip to main content

pulsify_sqlite/
store.rs

1use crate::{Error, Result};
2use pulsify_protocol::{
3    validate_rows, validate_vector, AppendResult, PatchRow, PatchStore, VersionVector,
4    MAX_VECTOR_ENTRIES,
5};
6use rusqlite::{params, Connection, OptionalExtension, Transaction, TransactionBehavior};
7use std::collections::{BTreeMap, BTreeSet};
8use std::path::Path;
9use std::time::Duration;
10
11/// Byte-for-byte `SQLITE_PATCH_SCHEMA` from `pulsify-core/storage`.
12pub const SCHEMA: &str = "
13CREATE TABLE IF NOT EXISTS pulsify_op_rows (
14 doc_id TEXT NOT NULL, sid INTEGER NOT NULL, time_start INTEGER NOT NULL,
15 span INTEGER NOT NULL CHECK(span > 0), time_end INTEGER GENERATED ALWAYS AS (time_start + span) STORED,
16 dependencies TEXT NOT NULL, operations BLOB NOT NULL, ready INTEGER NOT NULL DEFAULT 0,
17 packed INTEGER NOT NULL DEFAULT 0,
18 PRIMARY KEY(doc_id, sid, time_start)
19) WITHOUT ROWID;
20DROP INDEX IF EXISTS pulsify_rows_frontier;
21CREATE INDEX IF NOT EXISTS pulsify_rows_pending ON pulsify_op_rows(doc_id) WHERE ready = 0;
22CREATE TABLE IF NOT EXISTS pulsify_doc_clocks (
23 doc_id TEXT NOT NULL, sid INTEGER NOT NULL, clock INTEGER NOT NULL,
24 PRIMARY KEY(doc_id, sid)
25) WITHOUT ROWID;
26CREATE VIEW IF NOT EXISTS pulsify_dangling_op_rows AS SELECT * FROM pulsify_op_rows WHERE ready = 0;
27";
28
29/// Byte-for-byte `SQLITE_PACKED_MIGRATION`: added to a table created before packed segments.
30pub const PACKED_MIGRATION: &str =
31    "ALTER TABLE pulsify_op_rows ADD COLUMN packed INTEGER NOT NULL DEFAULT 0";
32
33/// Immutable rows keyed by `(doc_id, sid, time_start)`. Rows stay pending until
34/// their actor prefix is contiguous and their dependencies are stored.
35pub struct SqliteStore {
36    db: Connection,
37}
38
39impl SqliteStore {
40    /// Opens or creates a durable database file (WAL, synchronous FULL).
41    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
42        let db = Connection::open(path)?;
43        db.busy_timeout(Duration::from_secs(5))?;
44        db.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;")?;
45        Self::new(db)
46    }
47    pub fn open_in_memory() -> Result<Self> {
48        Self::new(Connection::open_in_memory()?)
49    }
50    /// Installs the schema on an existing connection.
51    pub fn new(db: Connection) -> Result<Self> {
52        db.execute_batch(SCHEMA)?;
53        // CREATE TABLE IF NOT EXISTS leaves an older table as it is.
54        let packed = || -> Result<bool> {
55            Ok(db.query_row(
56                "SELECT COUNT(*) FROM pragma_table_info('pulsify_op_rows') WHERE name='packed'",
57                [],
58                |r| r.get(0),
59            )?)
60        };
61        if !packed()? {
62            if let Err(error) = db.execute_batch(PACKED_MIGRATION) {
63                // Another process that opened the file at the same time added it.
64                if !packed()? {
65                    return Err(error.into());
66                }
67            }
68        }
69        Ok(Self { db })
70    }
71    pub fn connection(&self) -> &Connection {
72        &self.db
73    }
74
75    /// Validates and stores rows of one document in one IMMEDIATE transaction.
76    /// Exact retransmissions are ignored; a conflict rolls back the whole batch.
77    pub fn append(&mut self, rows: &[PatchRow]) -> Result<AppendResult> {
78        let Some(doc_id) = validate_rows(rows)? else {
79            return Ok(AppendResult::default());
80        };
81        let tx = self
82            .db
83            .transaction_with_behavior(TransactionBehavior::Immediate)?;
84        let result = append_rows(&tx, doc_id, rows)?;
85        tx.commit()?;
86        Ok(result)
87    }
88
89    pub fn vector(&self, doc_id: &str) -> Result<VersionVector> {
90        validate_doc_id(doc_id)?;
91        read_vector(&self.db, doc_id)
92    }
93
94    /// Ready rows the peer lacks, ordered by actor and clock.
95    pub fn missing(&self, doc_id: &str, remote: &VersionVector) -> Result<Vec<PatchRow>> {
96        validate_doc_id(doc_id)?;
97        validate_vector(remote)?;
98        read_missing(&self.db, doc_id, remote)
99    }
100
101    /// `missing` and `vector` from one consistent snapshot.
102    pub fn sync_state(
103        &mut self,
104        doc_id: &str,
105        remote: &VersionVector,
106    ) -> Result<(Vec<PatchRow>, VersionVector)> {
107        validate_doc_id(doc_id)?;
108        validate_vector(remote)?;
109        let tx = self.db.transaction()?;
110        let rows = read_missing(&tx, doc_id, remote)?;
111        let vector = read_vector(&tx, doc_id)?;
112        tx.commit()?;
113        Ok((rows, vector))
114    }
115}
116
117impl PatchStore for SqliteStore {
118    type Error = Error;
119    fn append(&mut self, rows: &[PatchRow]) -> Result<AppendResult> {
120        SqliteStore::append(self, rows)
121    }
122    fn vector(&self, doc_id: &str) -> Result<VersionVector> {
123        SqliteStore::vector(self, doc_id)
124    }
125    fn missing(&self, doc_id: &str, remote: &VersionVector) -> Result<Vec<PatchRow>> {
126        SqliteStore::missing(self, doc_id, remote)
127    }
128    fn sync_state(
129        &mut self,
130        doc_id: &str,
131        remote: &VersionVector,
132    ) -> Result<(Vec<PatchRow>, VersionVector)> {
133        SqliteStore::sync_state(self, doc_id, remote)
134    }
135}
136
137pub fn validate_doc_id(doc_id: &str) -> Result<()> {
138    Ok(pulsify_protocol::validate_doc_id(doc_id)?)
139}
140
141fn own_clock(vv: &VersionVector, sid: u64) -> u64 {
142    vv.iter()
143        .find(|(id, _)| *id == sid)
144        .map_or(0, |(_, clock)| *clock)
145}
146
147fn conflict(message: &str) -> Error {
148    Error::new("CONFLICT", message)
149}
150
151/// The stored envelope of a neighbouring segment of the same actor.
152struct Segment {
153    clock: u64,
154    span: u64,
155    dependencies: VersionVector,
156}
157
158fn assert_compatible(row: &PatchRow, other: &Segment) -> Result<()> {
159    if row.clock < other.clock + other.span && other.clock < row.clock + row.span {
160        return Err(conflict("Overlapping immutable storage segments"));
161    }
162    let (previous_end, next_dependency) = if row.clock < other.clock {
163        (
164            row.clock + row.span,
165            own_clock(&other.dependencies, row.sid),
166        )
167    } else {
168        (
169            other.clock + other.span,
170            own_clock(&row.dependencies, row.sid),
171        )
172    };
173    if next_dependency < previous_end {
174        return Err(conflict("Actor history fork"));
175    }
176    Ok(())
177}
178
179fn corrupt() -> Error {
180    Error::new("CONNECTION_FAILED", "Corrupt packed segment")
181}
182
183/// The rows of a packed segment, as `SqlitePatchStore.compact` folded them:
184/// for each, `span`, the dependencies and the operation bytes, numbers as
185/// LEB128 varuints. They are contiguous from the segment's clock to its end.
186fn unpack(doc_id: &str, sid: u64, clock: u64, span: u64, bytes: &[u8]) -> Result<Vec<PatchRow>> {
187    let mut offset = 0;
188    let read = |offset: &mut usize| -> Result<u64> {
189        let mut value = 0u64;
190        for shift in (0..).step_by(7) {
191            let byte = *bytes.get(*offset).ok_or_else(corrupt)?;
192            *offset += 1;
193            if shift > 49 {
194                return Err(corrupt());
195            }
196            value |= u64::from(byte & 127) << shift;
197            if byte < 128 {
198                break;
199            }
200        }
201        Ok(value)
202    };
203    let mut rows = Vec::new();
204    let mut next = clock;
205    while offset < bytes.len() {
206        let span = read(&mut offset)?;
207        let count = read(&mut offset)?;
208        let mut dependencies = VersionVector::new();
209        for _ in 0..count {
210            dependencies.push((read(&mut offset)?, read(&mut offset)?));
211        }
212        let length = read(&mut offset)? as usize;
213        let operations = offset
214            .checked_add(length)
215            .and_then(|end| bytes.get(offset..end))
216            .filter(|operations| span > 0 && !operations.is_empty())
217            .ok_or_else(corrupt)?;
218        rows.push(PatchRow {
219            doc_id: doc_id.to_owned(),
220            sid,
221            clock: next,
222            span,
223            dependencies,
224            operations: operations.to_vec(),
225        });
226        offset += length;
227        next = next.checked_add(span).ok_or_else(corrupt)?;
228    }
229    if rows.is_empty() || next != clock + span {
230        return Err(corrupt());
231    }
232    Ok(rows)
233}
234
235fn same_row(stored: &PatchRow, row: &PatchRow) -> bool {
236    stored.span == row.span
237        && stored.dependencies == row.dependencies
238        && stored.operations == row.operations
239}
240
241fn append_rows(tx: &Transaction<'_>, doc_id: &str, rows: &[PatchRow]) -> Result<AppendResult> {
242    let mut get = tx.prepare_cached(
243        "SELECT span,dependencies,operations,packed FROM pulsify_op_rows WHERE doc_id=?1 AND sid=?2 AND time_start=?3",
244    )?;
245    let mut neighbours = tx.prepare_cached(
246        "SELECT time_start,span,dependencies,packed FROM pulsify_op_rows WHERE doc_id=?1 AND sid=?2 AND
247 (time_start=(SELECT MAX(time_start) FROM pulsify_op_rows WHERE doc_id=?1 AND sid=?2 AND time_start<?3)
248 OR time_start=(SELECT MIN(time_start) FROM pulsify_op_rows WHERE doc_id=?1 AND sid=?2 AND time_start>?3))",
249    )?;
250    let mut insert = tx.prepare_cached(
251        "INSERT INTO pulsify_op_rows(doc_id,sid,time_start,span,dependencies,operations,ready) VALUES(?,?,?,?,?,?,?)",
252    )?;
253    let mut frontier: BTreeMap<u64, u64> = read_vector(tx, doc_id)?.into_iter().collect();
254    // Pending rows are few: read them through the partial index, which the
255    // planner would otherwise skip for the primary key and read the whole
256    // document. Its entries end with the primary key, so they come sorted.
257    let mut pending = tx
258        .prepare_cached(
259            "SELECT sid,time_start,time_end,dependencies FROM pulsify_op_rows INDEXED BY pulsify_rows_pending WHERE doc_id=? AND ready=0 ORDER BY sid,time_start",
260        )?
261        .query_map([doc_id], |r| {
262            Ok((
263                r.get::<_, i64>(0)? as u64,
264                r.get::<_, i64>(1)? as u64,
265                r.get::<_, i64>(2)? as u64,
266                r.get::<_, String>(3)?,
267            ))
268        })?
269        .collect::<rusqlite::Result<Vec<_>>>()?
270        .into_iter()
271        .map(|(sid, start, end, dependencies)| {
272            Ok((sid, start, end, serde_json::from_str(&dependencies)?))
273        })
274        .collect::<Result<Vec<(u64, u64, u64, VersionVector)>>>()?;
275    let mut pending_actors: BTreeSet<u64> = pending.iter().map(|row| row.0).collect();
276    let mut changed_actors = BTreeSet::new();
277    let (mut inserted, mut ready) = (0, 0);
278    'rows: for row in rows {
279        let (sid, clock) = (row.sid as i64, row.clock as i64);
280        // A row that is ready on arrival (the common, in-order case) skips the
281        // pending index and the promotion UPDATE.
282        let ready_now = row.clock == frontier.get(&row.sid).copied().unwrap_or(1)
283            && row
284                .dependencies
285                .iter()
286                .all(|(actor, clock)| frontier.get(actor).copied().unwrap_or(0) >= *clock);
287        if ready_now && !pending_actors.contains(&row.sid) {
288            // Ready rows of an actor tile [1, frontier) and it has no pending
289            // row, so no stored row starts at or after this one: it is neither
290            // a duplicate nor overlapping, and the previous row ends exactly at
291            // the frontier. Only the fork check remains, without reading it.
292            if row.clock > 1 && own_clock(&row.dependencies, row.sid) < row.clock {
293                return Err(conflict("Actor history fork"));
294            }
295            insert.execute(params![
296                doc_id,
297                sid,
298                clock,
299                row.span as i64,
300                serde_json::to_string(&row.dependencies)?,
301                row.operations,
302                true,
303            ])?;
304            inserted += 1;
305            frontier.insert(row.sid, row.clock + row.span);
306            changed_actors.insert(row.sid);
307            ready += 1;
308            continue;
309        }
310        // The stored row at a key: itself, or the rows packed inside it.
311        let mut stored = |start: i64| -> Result<Option<Vec<PatchRow>>> {
312            let Some((span, dependencies, operations, packed)) = get
313                .query_row(params![doc_id, sid, start], |r| {
314                    Ok((
315                        r.get::<_, i64>(0)?,
316                        r.get::<_, String>(1)?,
317                        r.get::<_, Vec<u8>>(2)?,
318                        r.get::<_, bool>(3)?,
319                    ))
320                })
321                .optional()?
322            else {
323                return Ok(None);
324            };
325            Ok(Some(if packed {
326                unpack(doc_id, row.sid, start as u64, span as u64, &operations)?
327            } else {
328                vec![PatchRow {
329                    doc_id: doc_id.to_owned(),
330                    sid: row.sid,
331                    clock: start as u64,
332                    span: span as u64,
333                    dependencies: serde_json::from_str(&dependencies)?,
334                    operations,
335                }]
336            }))
337        };
338        if let Some(existing) = stored(clock)? {
339            // A packed segment starts with the row that had its key.
340            if !same_row(&existing[0], row) {
341                return Err(conflict("Conflicting storage segment"));
342            }
343            continue;
344        }
345        let found = neighbours
346            .query_map(params![doc_id, sid, clock], |r| {
347                Ok((
348                    r.get::<_, i64>(0)?,
349                    r.get::<_, i64>(1)?,
350                    r.get::<_, String>(2)?,
351                    r.get::<_, bool>(3)?,
352                ))
353            })?
354            .collect::<rusqlite::Result<Vec<_>>>()?;
355        for (start, span, dependencies, packed) in found {
356            let mut segment = Segment {
357                clock: start as u64,
358                span: span as u64,
359                dependencies: serde_json::from_str(&dependencies)?,
360            };
361            // Seen from outside, a packed segment checks like its rows. A row
362            // that starts inside is compared to the row it hits.
363            if packed && segment.clock < row.clock && row.clock < segment.clock + segment.span {
364                let inner = stored(start)?.ok_or_else(corrupt)?;
365                if let Some(same) = inner.iter().find(|each| each.clock == row.clock) {
366                    if !same_row(same, row) {
367                        return Err(conflict("Conflicting storage segment"));
368                    }
369                    continue 'rows;
370                }
371                let hit = inner
372                    .into_iter()
373                    .rev()
374                    .find(|each| each.clock < row.clock)
375                    .ok_or_else(corrupt)?;
376                segment = Segment {
377                    clock: hit.clock,
378                    span: hit.span,
379                    dependencies: hit.dependencies,
380                };
381            }
382            assert_compatible(row, &segment)?;
383        }
384        insert.execute(params![
385            doc_id,
386            sid,
387            clock,
388            row.span as i64,
389            serde_json::to_string(&row.dependencies)?,
390            row.operations,
391            ready_now,
392        ])?;
393        inserted += 1;
394        if ready_now {
395            frontier.insert(row.sid, row.clock + row.span);
396            changed_actors.insert(row.sid);
397            ready += 1;
398        } else {
399            pending.push((
400                row.sid,
401                row.clock,
402                row.clock + row.span,
403                row.dependencies.clone(),
404            ));
405            pending_actors.insert(row.sid);
406        }
407    }
408    let actors: BTreeSet<u64> = frontier
409        .keys()
410        .chain(pending_actors.iter())
411        .copied()
412        .collect();
413    if actors.len() > MAX_VECTOR_ENTRIES {
414        return Err(Error::new(
415            "LIMIT_EXCEEDED",
416            "Document actor limit exceeded",
417        ));
418    }
419    let mut promote = tx.prepare_cached(
420        "UPDATE pulsify_op_rows SET ready=1 WHERE doc_id=? AND sid=? AND time_start=?",
421    )?;
422    pending.sort_by_key(|row| (row.0, row.1));
423    loop {
424        let mut changed = false;
425        let mut waiting = Vec::new();
426        for row in pending {
427            let (sid, start, end, ref dependencies) = row;
428            let contiguous = start == frontier.get(&sid).copied().unwrap_or(1);
429            let covered = dependencies
430                .iter()
431                .all(|(actor, clock)| frontier.get(actor).copied().unwrap_or(0) >= *clock);
432            if !contiguous || !covered {
433                waiting.push(row);
434                continue;
435            }
436            promote.execute(params![doc_id, sid as i64, start as i64])?;
437            let clock = frontier.entry(sid).or_insert(0);
438            *clock = (*clock).max(end);
439            changed_actors.insert(sid);
440            ready += 1;
441            changed = true;
442        }
443        pending = waiting;
444        if !changed {
445            break;
446        }
447    }
448    let mut advance = tx.prepare_cached(
449        "INSERT INTO pulsify_doc_clocks(doc_id,sid,clock) VALUES(?,?,?) ON CONFLICT(doc_id,sid) DO UPDATE SET clock=MAX(clock,excluded.clock)",
450    )?;
451    for sid in changed_actors {
452        advance.execute(params![doc_id, sid as i64, frontier[&sid] as i64])?;
453    }
454    Ok(AppendResult {
455        inserted,
456        ready,
457        pending: pending.len(),
458        vector: Some(frontier.into_iter().collect()),
459    })
460}
461
462fn read_vector(db: &Connection, doc_id: &str) -> Result<VersionVector> {
463    Ok(db
464        .prepare_cached("SELECT sid,clock FROM pulsify_doc_clocks WHERE doc_id=? ORDER BY sid")?
465        .query_map([doc_id], |r| {
466            Ok((r.get::<_, i64>(0)? as u64, r.get::<_, i64>(1)? as u64))
467        })?
468        .collect::<rusqlite::Result<_>>()?)
469}
470
471fn read_missing(db: &Connection, doc_id: &str, remote: &VersionVector) -> Result<Vec<PatchRow>> {
472    let map = |r: &rusqlite::Row<'_>| {
473        Ok((
474            r.get::<_, i64>(0)?,
475            r.get::<_, i64>(1)?,
476            r.get::<_, i64>(2)?,
477            r.get::<_, String>(3)?,
478            r.get::<_, Vec<u8>>(4)?,
479            r.get::<_, bool>(5)?,
480        ))
481    };
482    let found = if remote.is_empty() {
483        db.prepare_cached(
484            "SELECT sid,time_start,span,dependencies,operations,packed FROM pulsify_op_rows WHERE doc_id=? AND ready=1 ORDER BY sid,time_start",
485        )?
486        .query_map([doc_id], map)?
487        .collect::<rusqlite::Result<Vec<_>>>()?
488    } else {
489        // Same primary key seek per behind actor as `SqlitePatchStore.missing`.
490        db.prepare_cached(
491            "WITH remote(sid,clock) AS (SELECT json_extract(value,'$[0]'),json_extract(value,'$[1]') FROM json_each(?1)),
492 actors(sid,since) AS (SELECT c.sid,COALESCE(r.clock,0) FROM pulsify_doc_clocks c LEFT JOIN remote r ON r.sid=c.sid
493  WHERE c.doc_id=?2 AND c.clock>COALESCE(r.clock,0))
494 SELECT o.sid,o.time_start,o.span,o.dependencies,o.operations,o.packed FROM actors a CROSS JOIN pulsify_op_rows o WHERE o.doc_id=?2 AND o.sid=a.sid
495 AND o.time_start>=COALESCE((SELECT MAX(time_start) FROM pulsify_op_rows WHERE doc_id=?2 AND sid=a.sid AND time_start<=a.since),0)
496 AND o.ready=1 AND o.time_end>a.since ORDER BY o.sid,o.time_start",
497        )?
498        .query_map(params![serde_json::to_string(remote)?, doc_id], map)?
499        .collect::<rusqlite::Result<Vec<_>>>()?
500    };
501    let mut rows = Vec::with_capacity(found.len());
502    for (sid, clock, span, dependencies, operations, packed) in found {
503        let (sid, clock, span) = (sid as u64, clock as u64, span as u64);
504        if packed {
505            // Packed segments never reach a peer: it gets the rows inside.
506            let since = own_clock(remote, sid);
507            rows.extend(
508                unpack(doc_id, sid, clock, span, &operations)?
509                    .into_iter()
510                    .filter(|inner| inner.end() > since),
511            );
512        } else {
513            rows.push(PatchRow {
514                doc_id: doc_id.to_owned(),
515                sid,
516                clock,
517                span,
518                dependencies: serde_json::from_str(&dependencies)?,
519                operations,
520            });
521        }
522    }
523    Ok(rows)
524}
525
526#[cfg(test)]
527pub(crate) mod tests {
528    use super::*;
529    use pulsify_protocol::MAX_MESSAGE_ROWS;
530
531    pub const A: u64 = 65536;
532    pub const B: u64 = 65537;
533
534    pub fn row(sid: u64, clock: u64, span: u64, dependencies: &[(u64, u64)]) -> PatchRow {
535        PatchRow {
536            doc_id: "doc".into(),
537            sid,
538            clock,
539            span,
540            dependencies: dependencies.to_vec(),
541            operations: vec![sid as u8, clock as u8, span as u8],
542        }
543    }
544    /// A contiguous segment of one actor, depending on its previous segment.
545    pub fn next(sid: u64, clock: u64, span: u64) -> PatchRow {
546        if clock == 1 {
547            row(sid, 1, span, &[])
548        } else {
549            row(sid, clock, span, &[(sid, clock)])
550        }
551    }
552    fn count(store: &SqliteStore, sql: &str) -> i64 {
553        store.connection().query_row(sql, [], |r| r.get(0)).unwrap()
554    }
555
556    #[test]
557    fn stores_and_reads_contiguous_rows() {
558        let mut store = SqliteStore::open_in_memory().unwrap();
559        let result = store
560            .append(&[next(A, 1, 2), next(A, 3, 1), next(B, 1, 4)])
561            .unwrap();
562        assert_eq!(
563            result,
564            AppendResult {
565                inserted: 3,
566                ready: 3,
567                pending: 0,
568                vector: Some(vec![(A, 4), (B, 5)]),
569            }
570        );
571        assert_eq!(store.vector("doc").unwrap(), vec![(A, 4), (B, 5)]);
572        assert_eq!(store.missing("doc", &vec![]).unwrap().len(), 3);
573        let missing = store.missing("doc", &vec![(A, 3)]).unwrap();
574        assert_eq!(missing, vec![next(A, 3, 1), next(B, 1, 4)]);
575        assert!(store
576            .missing("doc", &vec![(A, 4), (B, 5)])
577            .unwrap()
578            .is_empty());
579        assert!(store.missing("other", &vec![]).unwrap().is_empty());
580        assert!(store.vector("other").unwrap().is_empty());
581        let stored: String = store
582            .connection()
583            .query_row(
584                "SELECT dependencies FROM pulsify_op_rows WHERE sid=? AND time_start=3",
585                [A as i64],
586                |r| r.get(0),
587            )
588            .unwrap();
589        assert_eq!(stored, "[[65536,3]]");
590    }
591
592    fn varuint(out: &mut Vec<u8>, mut value: u64) {
593        while value >= 128 {
594            out.push((value % 128) as u8 | 128);
595            value /= 128;
596        }
597        out.push(value as u8);
598    }
599    /// Folds every row of `sid` into one packed segment, as the TypeScript store does.
600    fn pack(store: &SqliteStore, sid: u64) {
601        let rows: Vec<_> = store
602            .missing("doc", &vec![])
603            .unwrap()
604            .into_iter()
605            .filter(|row| row.sid == sid)
606            .collect();
607        let mut payload = Vec::new();
608        for row in &rows {
609            varuint(&mut payload, row.span);
610            varuint(&mut payload, row.dependencies.len() as u64);
611            for (sid, clock) in &row.dependencies {
612                varuint(&mut payload, *sid);
613                varuint(&mut payload, *clock);
614            }
615            varuint(&mut payload, row.operations.len() as u64);
616            payload.extend(&row.operations);
617        }
618        let (first, last) = (&rows[0], rows.last().unwrap());
619        let db = store.connection();
620        db.execute(
621            "DELETE FROM pulsify_op_rows WHERE sid=? AND time_start>?",
622            params![sid as i64, first.clock as i64],
623        )
624        .unwrap();
625        db.execute(
626            "UPDATE pulsify_op_rows SET span=?,operations=?,packed=1 WHERE sid=?",
627            params![(last.end() - first.clock) as i64, payload, sid as i64],
628        )
629        .unwrap();
630    }
631
632    #[test]
633    fn packed_segments_read_and_check_like_their_rows() {
634        let mut store = SqliteStore::open_in_memory().unwrap();
635        let mut wide = row(A, 6, 1, &[(A, 6), (B, 2)]);
636        wide.operations = (0..300u32).map(|byte| byte as u8).collect();
637        let rows = vec![
638            next(A, 1, 2),
639            next(A, 3, 3),
640            wide,
641            next(A, 7, 1),
642            next(B, 1, 4),
643        ];
644        store.append(&rows).unwrap();
645        let remotes = [
646            vec![],
647            vec![(A, 2)],
648            vec![(A, 3)],
649            vec![(A, 4), (B, 9)],
650            vec![(A, 7)],
651            vec![(A, 8)],
652        ];
653        let expected: Vec<_> = remotes
654            .iter()
655            .map(|remote| store.missing("doc", remote).unwrap())
656            .collect();
657        pack(&store, A);
658        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 2);
659        for (remote, expected) in remotes.iter().zip(&expected) {
660            assert_eq!(&store.missing("doc", remote).unwrap(), expected);
661        }
662        assert_eq!(store.vector("doc").unwrap(), vec![(A, 8), (B, 5)]);
663        // Resends of the first row of the segment and of rows inside it.
664        assert_eq!(store.append(&rows).unwrap().inserted, 0);
665        let mut changed_first = next(A, 1, 2);
666        changed_first.operations = vec![9];
667        let mut changed_inner = next(A, 7, 1);
668        changed_inner.operations = vec![9];
669        for (bad, message) in [
670            (changed_first, "Conflicting storage segment"),
671            (changed_inner, "Conflicting storage segment"),
672            (next(A, 3, 2), "Conflicting storage segment"),
673            (next(A, 4, 1), "Overlapping immutable storage segments"),
674            (row(A, 8, 1, &[(A, 7)]), "Actor history fork"),
675        ] {
676            let error = store.append(&[bad]).unwrap_err();
677            assert_eq!((error.code, error.message.as_str()), ("CONFLICT", message));
678        }
679        assert_eq!(store.append(&[next(A, 8, 2)]).unwrap().ready, 1);
680        assert_eq!(
681            store.missing("doc", &vec![(A, 7), (B, 5)]).unwrap(),
682            vec![next(A, 7, 1), next(A, 8, 2)]
683        );
684    }
685
686    #[test]
687    fn migrates_a_database_created_before_packed_segments() {
688        let db = Connection::open_in_memory().unwrap();
689        db.execute_batch(&SCHEMA.replace(" packed INTEGER NOT NULL DEFAULT 0,\n", ""))
690            .unwrap();
691        db.execute(
692            "INSERT INTO pulsify_op_rows(doc_id,sid,time_start,span,dependencies,operations,ready) VALUES('doc',?,1,2,'[]',x'010203',1)",
693            [A as i64],
694        )
695        .unwrap();
696        db.execute(
697            "INSERT INTO pulsify_doc_clocks VALUES('doc',?,3)",
698            [A as i64],
699        )
700        .unwrap();
701        let mut store = SqliteStore::new(db).unwrap();
702        assert_eq!(store.missing("doc", &vec![]).unwrap().len(), 1);
703        assert_eq!(store.append(&[next(A, 3, 1)]).unwrap().ready, 1);
704        assert_eq!(
705            count(
706                &store,
707                "SELECT COUNT(*) FROM pulsify_op_rows WHERE packed=0"
708            ),
709            2
710        );
711        // Opening it again changes nothing.
712        let db = std::mem::replace(&mut store.db, Connection::open_in_memory().unwrap());
713        assert_eq!(
714            SqliteStore::new(db).unwrap().vector("doc").unwrap(),
715            vec![(A, 4)]
716        );
717    }
718
719    #[test]
720    fn exact_duplicates_are_idempotent() {
721        let mut store = SqliteStore::open_in_memory().unwrap();
722        store.append(&[next(A, 1, 2)]).unwrap();
723        let again = store.append(&[next(A, 1, 2), next(A, 1, 2)]).unwrap();
724        assert_eq!(again.inserted, 0);
725        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 1);
726        assert_eq!(store.append(&[]).unwrap(), AppendResult::default());
727    }
728
729    #[test]
730    fn conflicts_roll_back_the_whole_batch() {
731        let mut store = SqliteStore::open_in_memory().unwrap();
732        store.append(&[next(A, 1, 2)]).unwrap();
733        let mut changed = next(A, 1, 2);
734        changed.operations = vec![9];
735        let cases = [
736            (changed, "Conflicting storage segment"),
737            (next(A, 2, 2), "Overlapping immutable storage segments"),
738            (row(A, 3, 1, &[(A, 2)]), "Actor history fork"),
739        ];
740        for (bad, message) in cases {
741            let error = store.append(&[next(B, 1, 1), bad]).unwrap_err();
742            assert_eq!((error.code, error.message.as_str()), ("CONFLICT", message));
743            assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 1);
744            assert_eq!(store.vector("doc").unwrap(), vec![(A, 3)]);
745        }
746        // Forks are detected against later neighbours and rows of the same batch.
747        store.append(&[row(A, 5, 1, &[(A, 3)])]).unwrap();
748        let error = store.append(&[next(A, 3, 2)]).unwrap_err();
749        assert_eq!(error.message, "Actor history fork");
750        let error = store
751            .append(&[next(A, 6, 1), row(A, 7, 1, &[(A, 4)])])
752            .unwrap_err();
753        assert_eq!(error.message, "Actor history fork");
754        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 2);
755    }
756
757    #[test]
758    fn gaps_and_missing_dependencies_stay_pending_until_promoted() {
759        let mut store = SqliteStore::open_in_memory().unwrap();
760        let gap = store.append(&[next(A, 3, 2)]).unwrap();
761        assert_eq!((gap.inserted, gap.ready, gap.pending), (1, 0, 1));
762        let dependent = store.append(&[row(B, 1, 1, &[(A, 5)])]).unwrap();
763        assert_eq!((dependent.ready, dependent.pending), (0, 2));
764        assert!(store.vector("doc").unwrap().is_empty());
765        assert!(store.missing("doc", &vec![]).unwrap().is_empty());
766        assert_eq!(
767            count(&store, "SELECT COUNT(*) FROM pulsify_dangling_op_rows"),
768            2
769        );
770        let filled = store.append(&[next(A, 1, 2)]).unwrap();
771        assert_eq!((filled.inserted, filled.ready, filled.pending), (1, 3, 0));
772        assert_eq!(store.vector("doc").unwrap(), vec![(A, 5), (B, 2)]);
773        assert_eq!(
774            store.missing("doc", &vec![]).unwrap(),
775            vec![next(A, 1, 2), next(A, 3, 2), row(B, 1, 1, &[(A, 5)])]
776        );
777        assert_eq!(
778            count(&store, "SELECT COUNT(*) FROM pulsify_op_rows WHERE ready=0"),
779            0
780        );
781    }
782
783    #[test]
784    fn in_order_rows_skip_pending_and_keep_every_check() {
785        let mut store = SqliteStore::open_in_memory().unwrap();
786        let batch: Vec<_> = (1..=5).map(|clock| next(A, clock, 1)).collect();
787        let result = store.append(&batch).unwrap();
788        assert_eq!((result.inserted, result.ready), (5, 5));
789        assert_eq!(result.vector, Some(vec![(A, 6)]));
790        assert_eq!(
791            count(&store, "SELECT COUNT(*) FROM pulsify_op_rows WHERE ready=0"),
792            0
793        );
794        // Resends stay idempotent, a different payload conflicts.
795        assert_eq!(store.append(&batch[1..3]).unwrap().inserted, 0);
796        let mut changed = next(A, 3, 1);
797        changed.operations.push(0);
798        let error = store.append(&[changed]).unwrap_err();
799        assert_eq!(error.message, "Conflicting storage segment");
800        // A fork at the frontier is caught without reading the previous row,
801        // and rolls back the whole batch.
802        for fork in [row(A, 6, 1, &[]), row(A, 6, 1, &[(A, 5)])] {
803            let error = store.append(&[next(B, 1, 1), fork]).unwrap_err();
804            assert_eq!(error.message, "Actor history fork");
805        }
806        assert_eq!(store.vector("doc").unwrap(), vec![(A, 6)]);
807        // In-order rows of A while B has a pending row; an overlap with it conflicts.
808        store.append(&[next(B, 3, 1)]).unwrap();
809        let both = store.append(&[next(A, 6, 1), next(B, 1, 2)]).unwrap();
810        assert_eq!((both.ready, both.pending), (3, 0));
811        assert_eq!(both.vector, Some(vec![(A, 7), (B, 4)]));
812        store.append(&[next(B, 6, 1)]).unwrap();
813        let error = store.append(&[next(B, 4, 3)]).unwrap_err();
814        assert_eq!(error.message, "Overlapping immutable storage segments");
815    }
816
817    #[test]
818    fn rejects_invalid_rows_and_documents() {
819        let mut store = SqliteStore::open_in_memory().unwrap();
820        let mut other_doc = next(B, 1, 1);
821        other_doc.doc_id = "other".into();
822        let mut empty = next(A, 1, 1);
823        empty.operations.clear();
824        for rows in [
825            vec![next(A, 1, 1), other_doc],
826            vec![row(1, 1, 1, &[])],
827            vec![row(A, 0, 1, &[])],
828            vec![row(A, 1, 0, &[])],
829            vec![row(A, 2, 1, &[(A, 3)])],
830            vec![row(A, 1, 1, &[(B, 1), (A, 1)])],
831            vec![empty],
832        ] {
833            assert_eq!(store.append(&rows).unwrap_err().code, "INVALID_MESSAGE");
834        }
835        let too_many: Vec<_> = (1..=MAX_MESSAGE_ROWS as u64 + 1)
836            .map(|clock| next(A, clock, 1))
837            .collect();
838        assert_eq!(store.append(&too_many).unwrap_err().code, "LIMIT_EXCEEDED");
839        assert_eq!(store.vector("").unwrap_err().code, "INVALID_MESSAGE");
840        assert_eq!(store.vector("a\0b").unwrap_err().code, "INVALID_MESSAGE");
841        assert_eq!(
842            store.vector(&"x".repeat(1025)).unwrap_err().code,
843            "INVALID_MESSAGE"
844        );
845        assert_eq!(
846            store
847                .missing("doc", &vec![(B, 1), (A, 1)])
848                .unwrap_err()
849                .code,
850            "INVALID_MESSAGE"
851        );
852        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 0);
853    }
854
855    #[test]
856    fn limits_the_number_of_actors() {
857        let mut store = SqliteStore::open_in_memory().unwrap();
858        let rows: Vec<_> = (0..MAX_VECTOR_ENTRIES as u64)
859            .map(|i| next(A + i, 1, 1))
860            .collect();
861        store.append(&rows).unwrap();
862        let error = store
863            .append(&[next(A + MAX_VECTOR_ENTRIES as u64, 2, 1)])
864            .unwrap_err();
865        assert_eq!(error.code, "LIMIT_EXCEEDED");
866        assert_eq!(store.vector("doc").unwrap().len(), MAX_VECTOR_ENTRIES);
867        assert_eq!(
868            count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"),
869            MAX_VECTOR_ENTRIES as i64
870        );
871    }
872
873    #[test]
874    fn persists_across_reopen() {
875        let path = std::env::temp_dir().join(format!(
876            "pulsify-sqlite-{}-{:?}.sqlite",
877            std::process::id(),
878            std::thread::current().id()
879        ));
880        let _ = std::fs::remove_file(&path);
881        {
882            let mut store = SqliteStore::open(&path).unwrap();
883            store.append(&[next(A, 1, 3), next(A, 5, 1)]).unwrap();
884        }
885        let mut store = SqliteStore::open(&path).unwrap();
886        assert_eq!(store.vector("doc").unwrap(), vec![(A, 4)]);
887        assert_eq!(store.append(&[next(A, 4, 1)]).unwrap().ready, 2);
888        let (rows, vector) = store.sync_state("doc", &vec![(A, 4)]).unwrap();
889        assert_eq!(vector, vec![(A, 6)]);
890        assert_eq!(rows, vec![next(A, 4, 1), next(A, 5, 1)]);
891        drop(store);
892        for suffix in ["", "-wal", "-shm"] {
893            let _ = std::fs::remove_file(format!("{}{suffix}", path.display()));
894        }
895    }
896}