Skip to main content

pulsify_sqlite/
store.rs

1use crate::{Error, Result};
2use pulsify_protocol::{document_prefixes, DocumentStore};
3use pulsify_protocol::{
4    is_gap, last_register_of, validate_rows, validate_vector, AppendResult, PatchRow, PatchStore,
5    VersionVector, GAP_OPERATIONS, MAX_VECTOR_ENTRIES,
6};
7use rusqlite::{params, Connection, OptionalExtension, Transaction, TransactionBehavior};
8use std::collections::hash_map::Entry;
9use std::collections::HashMap;
10use std::collections::{BTreeMap, BTreeSet};
11use std::path::Path;
12use std::time::Duration;
13
14/// Byte-for-byte `SQLITE_PATCH_SCHEMA` from `pulsify-core/storage`.
15pub const SCHEMA: &str = "
16CREATE TABLE IF NOT EXISTS pulsify_tombstones (prefix TEXT PRIMARY KEY) WITHOUT ROWID;
17CREATE TABLE IF NOT EXISTS pulsify_op_rows (
18 doc_id TEXT NOT NULL, sid INTEGER NOT NULL, time_start INTEGER NOT NULL,
19 span INTEGER NOT NULL CHECK(span > 0), time_end INTEGER GENERATED ALWAYS AS (time_start + span) STORED,
20 dependencies TEXT NOT NULL, operations BLOB NOT NULL, ready INTEGER NOT NULL DEFAULT 0,
21 packed INTEGER NOT NULL DEFAULT 0,
22 PRIMARY KEY(doc_id, sid, time_start)
23) WITHOUT ROWID;
24DROP INDEX IF EXISTS pulsify_rows_frontier;
25CREATE INDEX IF NOT EXISTS pulsify_rows_pending ON pulsify_op_rows(doc_id) WHERE ready = 0;
26CREATE TABLE IF NOT EXISTS pulsify_doc_clocks (
27 doc_id TEXT NOT NULL, sid INTEGER NOT NULL, clock INTEGER NOT NULL,
28 PRIMARY KEY(doc_id, sid)
29) WITHOUT ROWID;
30CREATE VIEW IF NOT EXISTS pulsify_dangling_op_rows AS SELECT * FROM pulsify_op_rows WHERE ready = 0;
31CREATE TABLE IF NOT EXISTS pulsify_values (
32 doc_id TEXT NOT NULL, sid INTEGER NOT NULL, register BLOB NOT NULL, clock INTEGER NOT NULL,
33 dependencies TEXT NOT NULL, operations BLOB NOT NULL,
34 PRIMARY KEY(doc_id, sid, register)
35) WITHOUT ROWID;
36CREATE INDEX IF NOT EXISTS pulsify_values_clock ON pulsify_values(doc_id, sid, clock);
37";
38
39/// Byte-for-byte `SQLITE_REGISTERS_MIGRATION`: moves the last-value rows of a
40/// database written by an unreleased layout, which indexed them in
41/// `pulsify_registers`, to `pulsify_values`, and drops its gap rows.
42pub const REGISTERS_MIGRATION: &str = "
43INSERT OR REPLACE INTO pulsify_values(doc_id,sid,register,clock,dependencies,operations)
44 SELECT o.doc_id,o.sid,r.register,o.time_start,o.dependencies,o.operations FROM pulsify_registers r
45 JOIN pulsify_op_rows o ON o.doc_id=r.doc_id AND o.sid=r.sid AND o.time_start=r.clock
46 WHERE o.ready=1 AND o.packed=0;
47DELETE FROM pulsify_op_rows WHERE ready=1 AND packed=0 AND (operations=X'03010000' OR EXISTS(
48 SELECT 1 FROM pulsify_registers r WHERE r.doc_id=pulsify_op_rows.doc_id AND r.sid=pulsify_op_rows.sid
49 AND r.clock=pulsify_op_rows.time_start));
50DROP TABLE pulsify_registers;
51";
52
53/// Byte-for-byte `SQLITE_PACKED_MIGRATION`: added to a table created before packed segments.
54pub const PACKED_MIGRATION: &str =
55    "ALTER TABLE pulsify_op_rows ADD COLUMN packed INTEGER NOT NULL DEFAULT 0";
56
57/// Rows keyed by `(doc_id, sid, time_start)`, whose operations are immutable.
58/// Rows stay pending until their actor prefix is contiguous and their
59/// dependencies are stored. A field without history keeps each actor's newest
60/// write to it in `pulsify_values`, overwritten in place: the sequence numbers
61/// of the writes it replaces hold nothing, and spans are computed when rows
62/// are read.
63pub struct SqliteStore {
64    db: Connection,
65}
66
67impl SqliteStore {
68    /// Opens or creates a durable database file (WAL, synchronous FULL).
69    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
70        let db = Connection::open(path)?;
71        db.busy_timeout(Duration::from_secs(5))?;
72        db.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;")?;
73        Self::new(db)
74    }
75    pub fn open_in_memory() -> Result<Self> {
76        Self::new(Connection::open_in_memory()?)
77    }
78    /// Installs the schema on an existing connection.
79    pub fn new(mut db: Connection) -> Result<Self> {
80        // An append and a read keep about twenty statements between them.
81        db.set_prepared_statement_cache_capacity(64);
82        db.execute_batch(SCHEMA)?;
83        // CREATE TABLE IF NOT EXISTS leaves an older table as it is.
84        let packed = || -> Result<bool> {
85            Ok(db.query_row(
86                "SELECT COUNT(*) FROM pragma_table_info('pulsify_op_rows') WHERE name='packed'",
87                [],
88                |r| r.get(0),
89            )?)
90        };
91        if !packed()? {
92            if let Err(error) = db.execute_batch(PACKED_MIGRATION) {
93                // Another process that opened the file at the same time added it.
94                if !packed()? {
95                    return Err(error.into());
96                }
97            }
98        }
99        let registers = |db: &Connection| -> Result<bool> {
100            Ok(db.query_row(
101                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='pulsify_registers'",
102                [],
103                |r| r.get::<_, i64>(0),
104            )? > 0)
105        };
106        if registers(&db)? {
107            let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
108            // Another process may have moved them first.
109            if registers(&tx)? {
110                tx.execute_batch(REGISTERS_MIGRATION)?;
111            }
112            tx.commit()?;
113        }
114        Ok(Self { db })
115    }
116    /// Retain local recovery data and permanently block the prefix, in one transaction.
117    pub fn mark_deleted(&mut self, doc_id: &str, frames: &[Vec<u8>]) -> Result<()> {
118        validate_doc_id(doc_id)?;
119        let result = (|| -> Result<()> {
120            let tx = self
121                .db
122                .transaction_with_behavior(TransactionBehavior::Immediate)?;
123            for frame in frames {
124                let message = pulsify_protocol::decode(frame)?;
125                if !pulsify_protocol::covers_document(doc_id, &message.doc_id) {
126                    return Err(Error::new(
127                        "INVALID_MESSAGE",
128                        "Recovery row outside deleted subtree",
129                    ));
130                }
131                let pulsify_protocol::Body::SyncBack { rows, .. } = message.body else {
132                    return Err(Error::new("INVALID_MESSAGE", "Invalid recovery frame"));
133                };
134                if !rows.is_empty() {
135                    append_rows(&tx, &message.doc_id, &rows)?;
136                }
137            }
138            if !is_deleted(&tx, doc_id)? {
139                tx.execute(
140                    "DELETE FROM pulsify_tombstones WHERE prefix>=?1 AND prefix<?2",
141                    params![format!("{doc_id}/"), format!("{doc_id}0")],
142                )?;
143                tx.execute("INSERT INTO pulsify_tombstones(prefix) VALUES(?)", [doc_id])?;
144            }
145            tx.commit()?;
146            Ok(())
147        })();
148        // Even failed recovery must not make an authoritatively deleted ID live.
149        self.delete_documents(doc_id, true)?;
150        result
151    }
152    pub fn connection(&self) -> &Connection {
153        &self.db
154    }
155
156    /// Validates and stores rows of one document in one IMMEDIATE transaction.
157    /// Retransmissions are ignored; a conflict rolls back the whole batch.
158    pub fn append(&mut self, rows: &[PatchRow]) -> Result<AppendResult> {
159        let Some(doc_id) = validate_rows(rows)? else {
160            return Ok(AppendResult::default());
161        };
162        let tx = self
163            .db
164            .transaction_with_behavior(TransactionBehavior::Immediate)?;
165        assert_live(&tx, doc_id)?;
166        let result = append_rows(&tx, doc_id, rows)?;
167        tx.commit()?;
168        Ok(result)
169    }
170
171    pub fn vector(&self, doc_id: &str) -> Result<VersionVector> {
172        validate_doc_id(doc_id)?;
173        assert_live(&self.db, doc_id)?;
174        read_vector(&self.db, doc_id)
175    }
176
177    /// Ready rows the peer lacks, ordered by actor and clock.
178    pub fn missing(&self, doc_id: &str, remote: &VersionVector) -> Result<Vec<PatchRow>> {
179        validate_doc_id(doc_id)?;
180        validate_vector(remote)?;
181        assert_live(&self.db, doc_id)?;
182        read_missing(&self.db, doc_id, remote)
183    }
184
185    /// `missing` and `vector` from one consistent snapshot.
186    pub fn sync_state(
187        &mut self,
188        doc_id: &str,
189        remote: &VersionVector,
190    ) -> Result<(Vec<PatchRow>, VersionVector)> {
191        validate_doc_id(doc_id)?;
192        validate_vector(remote)?;
193        let tx = self.db.transaction()?;
194        assert_live(&tx, doc_id)?;
195        let rows = read_missing(&tx, doc_id, remote)?;
196        let vector = read_vector(&tx, doc_id)?;
197        tx.commit()?;
198        Ok((rows, vector))
199    }
200}
201
202fn is_deleted(db: &Connection, doc_id: &str) -> Result<bool> {
203    validate_doc_id(doc_id)?;
204    let mut get = db.prepare_cached("SELECT 1 FROM pulsify_tombstones WHERE prefix=?")?;
205    for prefix in document_prefixes(doc_id) {
206        if get.exists([prefix])? {
207            return Ok(true);
208        }
209    }
210    Ok(false)
211}
212fn assert_live(db: &Connection, doc_id: &str) -> Result<()> {
213    if is_deleted(db, doc_id)? {
214        return Err(Error::new(
215            "NOT_FOUND",
216            format!("Document {doc_id} was permanently deleted"),
217        ));
218    }
219    Ok(())
220}
221impl DocumentStore for SqliteStore {
222    fn is_deleted(&self, doc_id: &str) -> Result<bool> {
223        is_deleted(&self.db, doc_id)
224    }
225    fn delete_documents(&mut self, doc_id: &str, preserve_rows: bool) -> Result<usize> {
226        validate_doc_id(doc_id)?;
227        let tx = self
228            .db
229            .transaction_with_behavior(TransactionBehavior::Immediate)?;
230        let lower = format!("{doc_id}/");
231        let upper = format!("{doc_id}0");
232        if !is_deleted(&tx, doc_id)? {
233            tx.execute(
234                "DELETE FROM pulsify_tombstones WHERE prefix=?1 OR (prefix>=?2 AND prefix<?3)",
235                params![doc_id, lower, upper],
236            )?;
237            tx.execute("INSERT INTO pulsify_tombstones(prefix) VALUES(?)", [doc_id])?;
238        }
239        let mut count = 0;
240        if !preserve_rows {
241            count = tx.query_row("SELECT COUNT(*) FROM (SELECT doc_id FROM pulsify_op_rows WHERE doc_id=?1 OR (doc_id>=?2 AND doc_id<?3) UNION SELECT doc_id FROM pulsify_values WHERE doc_id=?1 OR (doc_id>=?2 AND doc_id<?3))", params![doc_id, lower, upper], |r| r.get::<_, i64>(0))? as usize;
242            for table in ["pulsify_op_rows", "pulsify_values", "pulsify_doc_clocks"] {
243                tx.execute(
244                    &format!("DELETE FROM {table} WHERE doc_id=?1 OR (doc_id>=?2 AND doc_id<?3)"),
245                    params![doc_id, lower, upper],
246                )?;
247            }
248        }
249        tx.commit()?;
250        Ok(count)
251    }
252    fn recover_rows(&self, doc_id: &str) -> Result<Vec<PatchRow>> {
253        validate_doc_id(doc_id)?;
254        read_missing(&self.db, doc_id, &vec![])
255    }
256    fn documents(&self, doc_id: &str, after: &str, limit: usize) -> Result<Vec<String>> {
257        assert_live(&self.db, doc_id)?;
258        if limit == 0 || limit > 4096 {
259            return Err(Error::new("INVALID_MESSAGE", "Invalid document limit"));
260        }
261        let mut result = Vec::new();
262        if self
263            .db
264            .prepare_cached(
265                "SELECT 1 FROM pulsify_doc_clocks WHERE doc_id=?1 AND doc_id>?2 LIMIT 1",
266            )?
267            .exists(params![doc_id, after])?
268        {
269            result.push(doc_id.to_owned());
270        }
271        // Range seeks plus indexed ancestor lookups: never scan the tombstone table.
272        let lower = format!("{doc_id}/");
273        let upper = format!("{doc_id}0");
274        let mut cursor = after.to_owned();
275        let mut query = self.db.prepare_cached("SELECT DISTINCT doc_id FROM pulsify_doc_clocks WHERE doc_id>=MAX(?1,?2) AND doc_id<?3 AND doc_id>?2 ORDER BY doc_id LIMIT ?4")?;
276        while result.len() < limit {
277            let candidates = query
278                .query_map(
279                    params![lower, cursor, upper, (limit - result.len()) as i64],
280                    |r| r.get::<_, String>(0),
281                )?
282                .collect::<std::result::Result<Vec<_>, _>>()?;
283            let Some(last) = candidates.last() else {
284                break;
285            };
286            cursor = last.clone();
287            for id in candidates {
288                if !is_deleted(&self.db, &id)? {
289                    result.push(id);
290                }
291            }
292        }
293        Ok(result)
294    }
295}
296
297impl PatchStore for SqliteStore {
298    type Error = Error;
299    fn append(&mut self, rows: &[PatchRow]) -> Result<AppendResult> {
300        SqliteStore::append(self, rows)
301    }
302    fn vector(&self, doc_id: &str) -> Result<VersionVector> {
303        SqliteStore::vector(self, doc_id)
304    }
305    fn missing(&self, doc_id: &str, remote: &VersionVector) -> Result<Vec<PatchRow>> {
306        SqliteStore::missing(self, doc_id, remote)
307    }
308    fn sync_state(
309        &mut self,
310        doc_id: &str,
311        remote: &VersionVector,
312    ) -> Result<(Vec<PatchRow>, VersionVector)> {
313        SqliteStore::sync_state(self, doc_id, remote)
314    }
315}
316
317pub fn validate_doc_id(doc_id: &str) -> Result<()> {
318    Ok(pulsify_protocol::validate_doc_id(doc_id)?)
319}
320
321fn own_clock(vv: &VersionVector, sid: u64) -> u64 {
322    vv.iter()
323        .find(|(id, _)| *id == sid)
324        .map_or(0, |(_, clock)| *clock)
325}
326
327fn conflict(message: &str) -> Error {
328    Error::new("CONFLICT", message)
329}
330
331fn corrupt() -> Error {
332    Error::new("CONNECTION_FAILED", "Corrupt packed segment")
333}
334
335/// The rows of a packed segment, as `SqlitePatchStore.compact` folded them:
336/// for each, `span`, the dependencies and the operation bytes, numbers as
337/// LEB128 varuints. Their spans tile the segment, from its clock to its end:
338/// a span runs to the next row, and a gap row fills a hole before a row that
339/// extended the segment.
340fn unpack(doc_id: &str, sid: u64, clock: u64, span: u64, bytes: &[u8]) -> Result<Vec<PatchRow>> {
341    let mut offset = 0;
342    let read = |offset: &mut usize| -> Result<u64> {
343        let mut value = 0u64;
344        for shift in (0..).step_by(7) {
345            let byte = *bytes.get(*offset).ok_or_else(corrupt)?;
346            *offset += 1;
347            if shift > 49 {
348                return Err(corrupt());
349            }
350            value |= u64::from(byte & 127) << shift;
351            if byte < 128 {
352                break;
353            }
354        }
355        Ok(value)
356    };
357    let mut rows = Vec::new();
358    let mut next = clock;
359    while offset < bytes.len() {
360        let span = read(&mut offset)?;
361        let count = read(&mut offset)?;
362        let mut dependencies = VersionVector::new();
363        for _ in 0..count {
364            dependencies.push((read(&mut offset)?, read(&mut offset)?));
365        }
366        let length = read(&mut offset)? as usize;
367        let operations = offset
368            .checked_add(length)
369            .and_then(|end| bytes.get(offset..end))
370            .filter(|operations| span > 0 && !operations.is_empty())
371            .ok_or_else(corrupt)?;
372        rows.push(PatchRow {
373            doc_id: doc_id.to_owned(),
374            sid,
375            clock: next,
376            span,
377            dependencies,
378            operations: operations.to_vec(),
379        });
380        offset += length;
381        next = next.checked_add(span).ok_or_else(corrupt)?;
382    }
383    if rows.is_empty() || next != clock + span {
384        return Err(corrupt());
385    }
386    Ok(rows)
387}
388
389/// A stored row, as an append reads it.
390struct Stored {
391    clock: u64,
392    span: u64,
393    operations: Vec<u8>,
394    packed: bool,
395}
396impl Stored {
397    const COLUMNS: &'static str = "time_start,span,operations,packed";
398    fn read(r: &rusqlite::Row<'_>) -> rusqlite::Result<Self> {
399        Ok(Self {
400            clock: r.get::<_, i64>(0)? as u64,
401            span: r.get::<_, i64>(1)? as u64,
402            operations: r.get(2)?,
403            packed: r.get(3)?,
404        })
405    }
406    fn end(&self) -> u64 {
407        self.clock + self.span
408    }
409}
410
411/// A row that waits for its predecessors or its dependencies.
412struct Waiting {
413    sid: u64,
414    start: u64,
415    end: u64,
416    dependencies: VersionVector,
417}
418
419/// Other operations at the same identity. A gap row stands for any replaced write.
420fn differ(held: &[u8], incoming: &[u8]) -> bool {
421    !is_gap(held) && !is_gap(incoming) && held != incoming
422}
423fn covered(frontier: &BTreeMap<u64, u64>, dependencies: &VersionVector) -> bool {
424    dependencies
425        .iter()
426        .all(|(actor, clock)| frontier.get(actor).copied().unwrap_or(0) >= *clock)
427}
428
429/// The rows of one document, inside the transaction of an append.
430struct Rows<'a> {
431    tx: &'a Transaction<'a>,
432    doc_id: &'a str,
433}
434impl Rows<'_> {
435    fn get(&self, sid: u64, clock: u64) -> Result<Option<Stored>> {
436        Ok(self
437            .tx
438            .prepare_cached(&format!(
439                "SELECT {} FROM pulsify_op_rows WHERE doc_id=? AND sid=? AND time_start=?",
440                Stored::COLUMNS
441            ))?
442            .query_row(params![self.doc_id, sid as i64, clock as i64], Stored::read)
443            .optional()?)
444    }
445    /// The last row of the actor that starts before this sequence number.
446    fn before(&self, sid: u64, clock: u64) -> Result<Option<Stored>> {
447        Ok(self
448            .tx
449            .prepare_cached(&format!(
450                "SELECT {} FROM pulsify_op_rows WHERE doc_id=? AND sid=? AND time_start<? ORDER BY time_start DESC LIMIT 1",
451                Stored::COLUMNS
452            ))?
453            .query_row(params![self.doc_id, sid as i64, clock as i64], Stored::read)
454            .optional()?)
455    }
456    fn insert(
457        &self,
458        sid: u64,
459        clock: u64,
460        span: u64,
461        dependencies: &str,
462        operations: &[u8],
463        ready: bool,
464    ) -> Result<()> {
465        self.tx
466            .prepare_cached(
467                "INSERT INTO pulsify_op_rows(doc_id,sid,time_start,span,dependencies,operations,ready) VALUES(?,?,?,?,?,?,?)",
468            )?
469            .execute(params![
470                self.doc_id,
471                sid as i64,
472                clock as i64,
473                span as i64,
474                dependencies,
475                operations,
476                ready,
477            ])?;
478        Ok(())
479    }
480    fn set_span(&self, sid: u64, clock: u64, span: u64) -> Result<()> {
481        self.tx
482            .prepare_cached(
483                "UPDATE pulsify_op_rows SET span=? WHERE doc_id=? AND sid=? AND time_start=?",
484            )?
485            .execute(params![span as i64, self.doc_id, sid as i64, clock as i64])?;
486        Ok(())
487    }
488    /// Removes the rows of an actor that wait in `[from, to)`: they were replaced.
489    fn remove_waiting(&self, sid: u64, from: u64, to: u64) -> Result<()> {
490        self.tx
491            .prepare_cached(
492                "DELETE FROM pulsify_op_rows WHERE doc_id=? AND sid=? AND ready=0 AND time_start>=? AND time_start<?",
493            )?
494            .execute(params![self.doc_id, sid as i64, from as i64, to as i64])?;
495        Ok(())
496    }
497    /// The operations held at this sequence number: a stored row, a row inside
498    /// a packed segment, or an actor's value of a register.
499    fn held_at(
500        &self,
501        values: &mut HashMap<u64, HashMap<u64, Vec<u8>>>,
502        sid: u64,
503        clock: u64,
504    ) -> Result<Option<Vec<u8>>> {
505        let unpack = |stored: &Stored| {
506            unpack(
507                self.doc_id,
508                sid,
509                stored.clock,
510                stored.span,
511                &stored.operations,
512            )
513        };
514        if let Some(exact) = self.get(sid, clock)? {
515            if !exact.packed {
516                return Ok(Some(exact.operations));
517            }
518            // A packed segment starts with the row that had its key.
519            return Ok(unpack(&exact)?.into_iter().next().map(|row| row.operations));
520        }
521        if let Some(previous) = self.before(sid, clock)? {
522            if previous.packed && clock < previous.end() {
523                if let Some(inner) = unpack(&previous)?
524                    .into_iter()
525                    .find(|row| row.clock == clock)
526                {
527                    return Ok(Some(inner.operations));
528                }
529            }
530        }
531        // Where each value of the actor is, read once for rows sent again.
532        let clocks = match values.entry(sid) {
533            Entry::Occupied(entry) => entry.into_mut(),
534            Entry::Vacant(entry) => entry.insert(
535                self.tx
536                    .prepare_cached(
537                        "SELECT clock,register FROM pulsify_values WHERE doc_id=? AND sid=?",
538                    )?
539                    .query_map(params![self.doc_id, sid as i64], |r| {
540                        Ok((r.get::<_, i64>(0)? as u64, r.get::<_, Vec<u8>>(1)?))
541                    })?
542                    .collect::<rusqlite::Result<HashMap<_, _>>>()?,
543            ),
544        };
545        let Some(register) = clocks.get(&clock) else {
546            return Ok(None);
547        };
548        Ok(Some(
549            self.tx
550                .prepare_cached(
551                    "SELECT operations FROM pulsify_values WHERE doc_id=? AND sid=? AND register=?",
552                )?
553                .query_row(params![self.doc_id, sid as i64, register], |r| r.get(0))?,
554        ))
555    }
556    /// Stores a ready row: a last-value row as its actor's value of the
557    /// register, replacing the older one; a gap row not at all, as the
558    /// frontier says how far the actor goes. Whether it stays a row.
559    fn keep(
560        &self,
561        values: &mut HashMap<u64, HashMap<u64, Vec<u8>>>,
562        sid: u64,
563        clock: u64,
564        dependencies: &str,
565        operations: &[u8],
566    ) -> Result<bool> {
567        let Some(last) = last_register_of(operations) else {
568            return Ok(!is_gap(operations));
569        };
570        self.tx
571            .prepare_cached(
572                "INSERT INTO pulsify_values(doc_id,sid,register,clock,dependencies,operations) VALUES(?,?,?,?,?,?) ON CONFLICT(doc_id,sid,register) DO UPDATE SET clock=excluded.clock,dependencies=excluded.dependencies,operations=excluded.operations",
573            )?
574            .execute(params![
575                self.doc_id,
576                sid as i64,
577                last.register,
578                clock as i64,
579                dependencies,
580                operations,
581            ])?;
582        values.remove(&sid);
583        Ok(false)
584    }
585}
586
587/// Mirror of `SqlitePatchStore.append`, statement for statement.
588fn append_rows(tx: &Transaction<'_>, doc_id: &str, rows: &[PatchRow]) -> Result<AppendResult> {
589    let stored = Rows { tx, doc_id };
590    let mut after = tx.prepare_cached(
591        "SELECT dependencies FROM pulsify_op_rows WHERE doc_id=? AND sid=? AND time_start>=? ORDER BY time_start LIMIT 1",
592    )?;
593    let mut frontier: BTreeMap<u64, u64> = read_vector(tx, doc_id)?.into_iter().collect();
594    // Pending rows are few: read them through the partial index, which the
595    // planner would otherwise skip for the primary key and read the whole
596    // document. Its entries end with the primary key, so they come sorted.
597    let mut pending = tx
598        .prepare_cached(
599            "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",
600        )?
601        .query_map([doc_id], |r| {
602            Ok((
603                r.get::<_, i64>(0)? as u64,
604                r.get::<_, i64>(1)? as u64,
605                r.get::<_, i64>(2)? as u64,
606                r.get::<_, String>(3)?,
607            ))
608        })?
609        .collect::<rusqlite::Result<Vec<_>>>()?
610        .into_iter()
611        .map(|(sid, start, end, dependencies)| {
612            Ok(Waiting {
613                sid,
614                start,
615                end,
616                dependencies: serde_json::from_str(&dependencies)?,
617            })
618        })
619        .collect::<Result<Vec<Waiting>>>()?;
620    let mut pending_actors: BTreeSet<u64> = pending.iter().map(|row| row.sid).collect();
621    let mut changed_actors = BTreeSet::new();
622    let mut values = HashMap::new();
623    let (mut inserted, mut ready) = (0, 0);
624    for row in rows {
625        let (sid, clock, end) = (row.sid, row.clock, row.clock + row.span);
626        let reached = frontier.get(&sid).copied().unwrap_or(1);
627        if clock < reached {
628            // Known, or replaced here: only its contents can conflict, and
629            // only its span can say that more writes were replaced.
630            if let Some(held) = stored.held_at(&mut values, sid, clock)? {
631                if differ(&held, &row.operations) {
632                    return Err(conflict("Conflicting storage segment"));
633                }
634            }
635            if end <= reached {
636                continue;
637            }
638            // Rows that waited below the new frontier were replaced.
639            stored.remove_waiting(sid, reached, end)?;
640            pending.retain(|each| each.sid != sid || each.start >= end);
641            frontier.insert(sid, end);
642            changed_actors.insert(sid);
643            inserted += 1;
644            continue;
645        }
646        // A row that is ready on arrival (the common, in-order case) skips the
647        // pending index and the promotion UPDATE.
648        let ready_now = clock == reached && covered(&frontier, &row.dependencies);
649        if ready_now && !pending_actors.contains(&sid) {
650            // Ready rows of an actor start below the frontier and it has no
651            // pending row, so no stored row starts at or after this one: it is
652            // neither a duplicate nor overlapping. Only the fork check remains,
653            // without reading anything.
654            if clock > 1 && own_clock(&row.dependencies, sid) < clock {
655                return Err(conflict("Actor history fork"));
656            }
657        } else {
658            if let Some(existing) = stored.get(sid, clock)? {
659                // A waiting row with the same start: only contents conflict.
660                if differ(&existing.operations, &row.operations) {
661                    return Err(conflict("Conflicting storage segment"));
662                }
663                // The longer span knows of more replaced writes, the waiting
664                // rows that start inside it among them.
665                if row.span > existing.span {
666                    stored.set_span(sid, clock, row.span)?;
667                    stored.remove_waiting(sid, clock + 1, end)?;
668                    pending
669                        .retain(|each| each.sid != sid || each.start <= clock || each.start >= end);
670                    for each in pending.iter_mut() {
671                        if each.sid == sid && each.start == clock {
672                            each.end = end;
673                        }
674                    }
675                }
676                continue;
677            }
678            let own = own_clock(&row.dependencies, sid);
679            if let Some(previous) = stored.before(sid, clock)? {
680                // It starts among the writes a waiting row has replaced.
681                if previous.end() > clock {
682                    continue;
683                }
684                if own < previous.end() {
685                    return Err(conflict("Actor history fork"));
686                }
687            }
688            // The first row past its span builds on it, like the journal checks.
689            let next = after
690                .query_row(params![doc_id, sid as i64, end as i64], |r| {
691                    r.get::<_, String>(0)
692                })
693                .optional()?;
694            if let Some(next) = next {
695                let dependencies: VersionVector = serde_json::from_str(&next)?;
696                if own_clock(&dependencies, sid) < end {
697                    return Err(conflict("Actor history fork"));
698                }
699            }
700            // Rows still waiting that this row has replaced.
701            stored.remove_waiting(sid, clock + 1, end)?;
702            pending.retain(|each| each.sid != sid || each.start <= clock || each.start >= end);
703        }
704        let dependencies = serde_json::to_string(&row.dependencies)?;
705        inserted += 1;
706        if ready_now {
707            if stored.keep(&mut values, sid, clock, &dependencies, &row.operations)? {
708                stored.insert(sid, clock, row.span, &dependencies, &row.operations, true)?;
709            }
710            frontier.insert(sid, end);
711            changed_actors.insert(sid);
712            ready += 1;
713        } else {
714            stored.insert(sid, clock, row.span, &dependencies, &row.operations, false)?;
715            pending.push(Waiting {
716                sid,
717                start: clock,
718                end,
719                dependencies: row.dependencies.clone(),
720            });
721            pending_actors.insert(sid);
722        }
723    }
724    let actors: BTreeSet<u64> = frontier
725        .keys()
726        .chain(pending_actors.iter())
727        .copied()
728        .collect();
729    if actors.len() > MAX_VECTOR_ENTRIES {
730        return Err(Error::new(
731            "LIMIT_EXCEEDED",
732            "Document actor limit exceeded",
733        ));
734    }
735    let mut promote = tx.prepare_cached(
736        "UPDATE pulsify_op_rows SET ready=1 WHERE doc_id=? AND sid=? AND time_start=?",
737    )?;
738    let mut remove =
739        tx.prepare_cached("DELETE FROM pulsify_op_rows WHERE doc_id=? AND sid=? AND time_start=?")?;
740    pending.sort_by_key(|row| (row.sid, row.start));
741    loop {
742        let mut changed = false;
743        let mut waiting = Vec::new();
744        for row in pending {
745            let contiguous = row.start == frontier.get(&row.sid).copied().unwrap_or(1);
746            if !contiguous || !covered(&frontier, &row.dependencies) {
747                waiting.push(row);
748                continue;
749            }
750            let (dependencies, operations): (String, Vec<u8>) = tx
751                .prepare_cached(
752                    "SELECT dependencies,operations FROM pulsify_op_rows WHERE doc_id=? AND sid=? AND time_start=?",
753                )?
754                .query_row(params![doc_id, row.sid as i64, row.start as i64], |r| {
755                    Ok((r.get(0)?, r.get(1)?))
756                })?;
757            if stored.keep(&mut values, row.sid, row.start, &dependencies, &operations)? {
758                promote.execute(params![doc_id, row.sid as i64, row.start as i64])?;
759            } else {
760                remove.execute(params![doc_id, row.sid as i64, row.start as i64])?;
761            }
762            let clock = frontier.entry(row.sid).or_insert(0);
763            *clock = (*clock).max(row.end);
764            changed_actors.insert(row.sid);
765            ready += 1;
766            changed = true;
767        }
768        pending = waiting;
769        if !changed {
770            break;
771        }
772    }
773    let mut advance = tx.prepare_cached(
774        "INSERT INTO pulsify_doc_clocks(doc_id,sid,clock) VALUES(?,?,?) ON CONFLICT(doc_id,sid) DO UPDATE SET clock=MAX(clock,excluded.clock)",
775    )?;
776    for sid in changed_actors {
777        advance.execute(params![doc_id, sid as i64, frontier[&sid] as i64])?;
778    }
779    Ok(AppendResult {
780        inserted,
781        ready,
782        pending: pending.len(),
783        vector: Some(frontier.into_iter().collect()),
784    })
785}
786
787fn read_vector(db: &Connection, doc_id: &str) -> Result<VersionVector> {
788    Ok(db
789        .prepare_cached("SELECT sid,clock FROM pulsify_doc_clocks WHERE doc_id=? ORDER BY sid")?
790        .query_map([doc_id], |r| {
791            Ok((r.get::<_, i64>(0)? as u64, r.get::<_, i64>(1)? as u64))
792        })?
793        .collect::<rusqlite::Result<_>>()?)
794}
795
796/// Mirror of `SqlitePatchStore.missing`: the rows still held, with spans
797/// computed from the next one, and a gap row where none holds the remote clock.
798fn read_missing(db: &Connection, doc_id: &str, remote: &VersionVector) -> Result<Vec<PatchRow>> {
799    let behind: Vec<(u64, u64)> = read_vector(db, doc_id)?
800        .into_iter()
801        .filter(|(sid, clock)| *clock > own_clock(remote, *sid))
802        .collect();
803    if behind.is_empty() {
804        return Ok(Vec::new());
805    }
806    let remote_json = serde_json::to_string(remote)?;
807    // Each table is read from its last row starting at or before the remote
808    // clock: one primary key seek per behind actor for the rows, one pass
809    // over its values, as `SqlitePatchStore.missing` does.
810    let sql = |table: &str, clock: &str, columns: &str| {
811        if remote.is_empty() {
812            format!("SELECT {columns} FROM {table} o WHERE o.doc_id=?2")
813        } else {
814            format!(
815                "WITH remote(sid,clock) AS (SELECT json_extract(value,'$[0]'),json_extract(value,'$[1]') FROM json_each(?1)),
816 actors(sid,since) AS (SELECT c.sid,MAX(COALESCE(r.clock,0),1) FROM pulsify_doc_clocks c LEFT JOIN remote r ON r.sid=c.sid
817  WHERE c.doc_id=?2 AND c.clock>COALESCE(r.clock,0))
818 SELECT {columns} FROM actors a CROSS JOIN {table} o WHERE o.doc_id=?2 AND o.sid=a.sid
819 AND o.{clock}>=COALESCE((SELECT MAX({clock}) FROM {table} WHERE doc_id=?2 AND sid=a.sid AND {clock}<=a.since),0)"
820            )
821        }
822    };
823    let bind = |statement: &mut rusqlite::CachedStatement<'_>| -> rusqlite::Result<()> {
824        if !remote.is_empty() {
825            statement.raw_bind_parameter(1, &remote_json)?;
826        }
827        statement.raw_bind_parameter(2, doc_id)
828    };
829    let mut held: BTreeMap<u64, Vec<PatchRow>> = BTreeMap::new();
830    let mut hold = |row: PatchRow| {
831        if !is_gap(&row.operations) {
832            held.entry(row.sid).or_default().push(row);
833        }
834    };
835    let mut statement = db.prepare_cached(&sql(
836        "pulsify_op_rows",
837        "time_start",
838        "o.sid,o.time_start,o.span,o.dependencies,o.operations,o.packed,o.ready",
839    ))?;
840    bind(&mut statement)?;
841    let mut found = statement.raw_query();
842    while let Some(r) = found.next()? {
843        if !r.get::<_, bool>(6)? {
844            continue;
845        }
846        let (sid, clock, span) = (
847            r.get::<_, i64>(0)? as u64,
848            r.get::<_, i64>(1)? as u64,
849            r.get::<_, i64>(2)? as u64,
850        );
851        let operations: Vec<u8> = r.get(4)?;
852        if r.get::<_, bool>(5)? {
853            // Packed segments never reach a peer: it gets the rows inside.
854            unpack(doc_id, sid, clock, span, &operations)?
855                .into_iter()
856                .for_each(&mut hold);
857        } else {
858            hold(PatchRow {
859                doc_id: doc_id.to_owned(),
860                sid,
861                clock,
862                span,
863                dependencies: serde_json::from_str(&r.get::<_, String>(3)?)?,
864                operations,
865            });
866        }
867    }
868    drop(found);
869    let mut statement = db.prepare_cached(&sql(
870        "pulsify_values",
871        "clock",
872        "o.sid,o.clock,o.dependencies,o.operations",
873    ))?;
874    bind(&mut statement)?;
875    let mut found = statement.raw_query();
876    while let Some(r) = found.next()? {
877        hold(PatchRow {
878            doc_id: doc_id.to_owned(),
879            sid: r.get::<_, i64>(0)? as u64,
880            clock: r.get::<_, i64>(1)? as u64,
881            span: 1,
882            dependencies: serde_json::from_str(&r.get::<_, String>(2)?)?,
883            operations: r.get(3)?,
884        });
885    }
886    drop(found);
887    let mut rows = Vec::new();
888    for (sid, frontier) in behind {
889        let mut held = held.remove(&sid).unwrap_or_default();
890        held.sort_by_key(|row| row.clock);
891        serve(
892            &mut rows,
893            doc_id,
894            sid,
895            held,
896            own_clock(remote, sid),
897            frontier,
898        );
899    }
900    Ok(rows)
901}
902
903/// The rows an actor still holds, sorted by clock, as a peer receives them:
904/// each one's span runs to the next one, the last one's to the frontier. A
905/// peer whose knowledge ends at `since` gets the row that holds it and those
906/// after it, or a gap row up to the first one when no row holds it.
907fn serve(
908    rows: &mut Vec<PatchRow>,
909    doc_id: &str,
910    sid: u64,
911    held: Vec<PatchRow>,
912    since: u64,
913    frontier: u64,
914) {
915    let from = since.max(1);
916    let first = held.partition_point(|row| row.clock <= from);
917    if first == 0 {
918        let end = held.first().map_or(frontier, |row| row.clock);
919        rows.push(PatchRow {
920            doc_id: doc_id.to_owned(),
921            sid,
922            clock: from,
923            span: end - from,
924            dependencies: if from > 1 { vec![(sid, from)] } else { vec![] },
925            operations: GAP_OPERATIONS.to_vec(),
926        });
927    }
928    let ends: Vec<u64> = held
929        .iter()
930        .skip(1)
931        .map(|row| row.clock)
932        .chain([frontier])
933        .collect();
934    for (row, end) in held.into_iter().zip(ends).skip(first.saturating_sub(1)) {
935        rows.push(PatchRow {
936            span: end - row.clock,
937            ..row
938        });
939    }
940}
941
942#[cfg(test)]
943pub(crate) mod tests {
944    use super::*;
945    use pulsify_protocol::MAX_MESSAGE_ROWS;
946
947    pub const A: u64 = 65536;
948    pub const B: u64 = 65537;
949
950    #[test]
951    fn subtree_listing_uses_indexed_tombstone_checks() {
952        let mut store = SqliteStore::open_in_memory().unwrap();
953        let tx = store.db.transaction().unwrap();
954        {
955            let mut marker = tx
956                .prepare("INSERT INTO pulsify_tombstones(prefix) VALUES(?)")
957                .unwrap();
958            let mut clock = tx
959                .prepare("INSERT INTO pulsify_doc_clocks(doc_id,sid,clock) VALUES(?,?,2)")
960                .unwrap();
961            for i in 0..10_000 {
962                marker.execute([format!("r/dead/{i}")]).unwrap();
963            }
964            for i in 0..100 {
965                clock
966                    .execute(params![format!("r/dead/{i}/child"), A as i64])
967                    .unwrap();
968            }
969            for i in 0..2000 {
970                for sid in [A, B] {
971                    clock
972                        .execute(params![format!("r/live/{i:04}"), sid as i64])
973                        .unwrap();
974                }
975            }
976        }
977        tx.commit().unwrap();
978        let started = std::time::Instant::now();
979        let mut found = Vec::new();
980        loop {
981            let after = found.last().map(String::as_str).unwrap_or("");
982            let page = store.documents("r", after, 128).unwrap();
983            if page.is_empty() {
984                break;
985            }
986            found.extend(page);
987        }
988        assert!(started.elapsed() < Duration::from_secs(2));
989        assert_eq!(
990            found,
991            (0..2000)
992                .map(|i| format!("r/live/{i:04}"))
993                .collect::<Vec<_>>()
994        );
995    }
996
997    pub fn row(sid: u64, clock: u64, span: u64, dependencies: &[(u64, u64)]) -> PatchRow {
998        PatchRow {
999            doc_id: "doc".into(),
1000            sid,
1001            clock,
1002            span,
1003            dependencies: dependencies.to_vec(),
1004            operations: vec![sid as u8, clock as u8, span as u8],
1005        }
1006    }
1007    /// A contiguous segment of one actor, depending on its previous segment.
1008    pub fn next(sid: u64, clock: u64, span: u64) -> PatchRow {
1009        if clock == 1 {
1010            row(sid, 1, span, &[])
1011        } else {
1012            row(sid, clock, span, &[(sid, clock)])
1013        }
1014    }
1015    fn count(store: &SqliteStore, sql: &str) -> i64 {
1016        store.connection().query_row(sql, [], |r| r.get(0)).unwrap()
1017    }
1018
1019    #[test]
1020    fn stores_and_reads_contiguous_rows() {
1021        let mut store = SqliteStore::open_in_memory().unwrap();
1022        let result = store
1023            .append(&[next(A, 1, 2), next(A, 3, 1), next(B, 1, 4)])
1024            .unwrap();
1025        assert_eq!(
1026            result,
1027            AppendResult {
1028                inserted: 3,
1029                ready: 3,
1030                pending: 0,
1031                vector: Some(vec![(A, 4), (B, 5)]),
1032            }
1033        );
1034        assert_eq!(store.vector("doc").unwrap(), vec![(A, 4), (B, 5)]);
1035        assert_eq!(store.missing("doc", &vec![]).unwrap().len(), 3);
1036        let missing = store.missing("doc", &vec![(A, 3)]).unwrap();
1037        assert_eq!(missing, vec![next(A, 3, 1), next(B, 1, 4)]);
1038        assert!(store
1039            .missing("doc", &vec![(A, 4), (B, 5)])
1040            .unwrap()
1041            .is_empty());
1042        assert!(store.missing("other", &vec![]).unwrap().is_empty());
1043        assert!(store.vector("other").unwrap().is_empty());
1044        let stored: String = store
1045            .connection()
1046            .query_row(
1047                "SELECT dependencies FROM pulsify_op_rows WHERE sid=? AND time_start=3",
1048                [A as i64],
1049                |r| r.get(0),
1050            )
1051            .unwrap();
1052        assert_eq!(stored, "[[65536,3]]");
1053    }
1054
1055    fn varuint(out: &mut Vec<u8>, mut value: u64) {
1056        while value >= 128 {
1057            out.push((value % 128) as u8 | 128);
1058            value /= 128;
1059        }
1060        out.push(value as u8);
1061    }
1062    /// Folds every stored row of `sid` into one packed segment, as the
1063    /// TypeScript store does: a span runs to the next row.
1064    fn pack(store: &SqliteStore, sid: u64) {
1065        let db = store.connection();
1066        let rows: Vec<(u64, u64, String, Vec<u8>)> = db
1067            .prepare("SELECT time_start,span,dependencies,operations FROM pulsify_op_rows WHERE sid=? AND ready=1 ORDER BY time_start")
1068            .unwrap()
1069            .query_map([sid as i64], |r| {
1070                Ok((
1071                    r.get::<_, i64>(0)? as u64,
1072                    r.get::<_, i64>(1)? as u64,
1073                    r.get(2)?,
1074                    r.get(3)?,
1075                ))
1076            })
1077            .unwrap()
1078            .collect::<rusqlite::Result<_>>()
1079            .unwrap();
1080        let mut payload = Vec::new();
1081        for (index, (clock, span, dependencies, operations)) in rows.iter().enumerate() {
1082            let span = rows.get(index + 1).map_or(*span, |next| next.0 - clock);
1083            let dependencies: VersionVector = serde_json::from_str(dependencies).unwrap();
1084            varuint(&mut payload, span);
1085            varuint(&mut payload, dependencies.len() as u64);
1086            for (sid, clock) in &dependencies {
1087                varuint(&mut payload, *sid);
1088                varuint(&mut payload, *clock);
1089            }
1090            varuint(&mut payload, operations.len() as u64);
1091            payload.extend(operations);
1092        }
1093        let (first, last) = (&rows[0], rows.last().unwrap());
1094        db.execute(
1095            "DELETE FROM pulsify_op_rows WHERE sid=? AND time_start>? AND ready=1",
1096            params![sid as i64, first.0 as i64],
1097        )
1098        .unwrap();
1099        db.execute(
1100            "UPDATE pulsify_op_rows SET span=?,operations=?,packed=1 WHERE sid=? AND time_start=?",
1101            params![
1102                (last.0 + last.1 - first.0) as i64,
1103                payload,
1104                sid as i64,
1105                first.0 as i64
1106            ],
1107        )
1108        .unwrap();
1109    }
1110
1111    #[test]
1112    fn packed_segments_read_and_check_like_their_rows() {
1113        let mut store = SqliteStore::open_in_memory().unwrap();
1114        let mut wide = row(A, 6, 1, &[(A, 6), (B, 2)]);
1115        wide.operations = (0..300u32).map(|byte| byte as u8).collect();
1116        let rows = vec![
1117            next(A, 1, 2),
1118            next(A, 3, 3),
1119            wide,
1120            next(A, 7, 1),
1121            next(B, 1, 4),
1122        ];
1123        store.append(&rows).unwrap();
1124        let remotes = [
1125            vec![],
1126            vec![(A, 2)],
1127            vec![(A, 3)],
1128            vec![(A, 4), (B, 9)],
1129            vec![(A, 7)],
1130            vec![(A, 8)],
1131        ];
1132        let expected: Vec<_> = remotes
1133            .iter()
1134            .map(|remote| store.missing("doc", remote).unwrap())
1135            .collect();
1136        pack(&store, A);
1137        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 2);
1138        for (remote, expected) in remotes.iter().zip(&expected) {
1139            assert_eq!(&store.missing("doc", remote).unwrap(), expected);
1140        }
1141        assert_eq!(store.vector("doc").unwrap(), vec![(A, 8), (B, 5)]);
1142        // Resends of the first row of the segment and of rows inside it.
1143        assert_eq!(store.append(&rows).unwrap().inserted, 0);
1144        let mut changed_first = next(A, 1, 2);
1145        changed_first.operations = vec![9];
1146        let mut changed_inner = next(A, 7, 1);
1147        changed_inner.operations = vec![9];
1148        for (bad, message) in [
1149            (changed_first, "Conflicting storage segment"),
1150            (changed_inner, "Conflicting storage segment"),
1151            (next(A, 3, 2), "Conflicting storage segment"),
1152            (row(A, 8, 1, &[(A, 7)]), "Actor history fork"),
1153        ] {
1154            let error = store.append(&[bad]).unwrap_err();
1155            assert_eq!((error.code, error.message.as_str()), ("CONFLICT", message));
1156        }
1157        // A row that starts inside a row of the segment was replaced: ignored.
1158        assert_eq!(store.append(&[next(A, 4, 1)]).unwrap().inserted, 0);
1159        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 2);
1160        assert_eq!(store.append(&[next(A, 8, 2)]).unwrap().ready, 1);
1161        assert_eq!(
1162            store.missing("doc", &vec![(A, 7), (B, 5)]).unwrap(),
1163            vec![next(A, 7, 1), next(A, 8, 2)]
1164        );
1165    }
1166
1167    #[test]
1168    fn migrates_a_database_created_before_packed_segments() {
1169        let db = Connection::open_in_memory().unwrap();
1170        db.execute_batch(&SCHEMA.replace(" packed INTEGER NOT NULL DEFAULT 0,\n", ""))
1171            .unwrap();
1172        db.execute(
1173            "INSERT INTO pulsify_op_rows(doc_id,sid,time_start,span,dependencies,operations,ready) VALUES('doc',?,1,2,'[]',x'010203',1)",
1174            [A as i64],
1175        )
1176        .unwrap();
1177        db.execute(
1178            "INSERT INTO pulsify_doc_clocks VALUES('doc',?,3)",
1179            [A as i64],
1180        )
1181        .unwrap();
1182        let mut store = SqliteStore::new(db).unwrap();
1183        assert_eq!(store.missing("doc", &vec![]).unwrap().len(), 1);
1184        assert_eq!(store.append(&[next(A, 3, 1)]).unwrap().ready, 1);
1185        assert_eq!(
1186            count(
1187                &store,
1188                "SELECT COUNT(*) FROM pulsify_op_rows WHERE packed=0"
1189            ),
1190            2
1191        );
1192        // Opening it again changes nothing.
1193        let db = std::mem::replace(&mut store.db, Connection::open_in_memory().unwrap());
1194        assert_eq!(
1195            SqliteStore::new(db).unwrap().vector("doc").unwrap(),
1196            vec![(A, 4)]
1197        );
1198    }
1199
1200    #[test]
1201    fn exact_duplicates_are_idempotent() {
1202        let mut store = SqliteStore::open_in_memory().unwrap();
1203        store.append(&[next(A, 1, 2)]).unwrap();
1204        let again = store.append(&[next(A, 1, 2), next(A, 1, 2)]).unwrap();
1205        assert_eq!(again.inserted, 0);
1206        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 1);
1207        assert_eq!(store.append(&[]).unwrap(), AppendResult::default());
1208    }
1209
1210    #[test]
1211    fn conflicts_roll_back_the_whole_batch() {
1212        let mut store = SqliteStore::open_in_memory().unwrap();
1213        store.append(&[next(A, 1, 2)]).unwrap();
1214        let mut changed = next(A, 1, 2);
1215        changed.operations = vec![9];
1216        let cases = [
1217            (changed, "Conflicting storage segment"),
1218            (row(A, 3, 1, &[(A, 2)]), "Actor history fork"),
1219        ];
1220        for (bad, message) in cases {
1221            let error = store.append(&[next(B, 1, 1), bad]).unwrap_err();
1222            assert_eq!((error.code, error.message.as_str()), ("CONFLICT", message));
1223            assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 1);
1224            assert_eq!(store.vector("doc").unwrap(), vec![(A, 3)]);
1225        }
1226        // Forks are detected against later neighbours and rows of the same batch.
1227        store.append(&[row(A, 5, 1, &[(A, 3)])]).unwrap();
1228        let error = store.append(&[next(A, 3, 2)]).unwrap_err();
1229        assert_eq!(error.message, "Actor history fork");
1230        let error = store
1231            .append(&[next(A, 6, 1), row(A, 7, 1, &[(A, 4)])])
1232            .unwrap_err();
1233        assert_eq!(error.message, "Actor history fork");
1234        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 2);
1235    }
1236
1237    #[test]
1238    fn gaps_and_missing_dependencies_stay_pending_until_promoted() {
1239        let mut store = SqliteStore::open_in_memory().unwrap();
1240        let gap = store.append(&[next(A, 3, 2)]).unwrap();
1241        assert_eq!((gap.inserted, gap.ready, gap.pending), (1, 0, 1));
1242        let dependent = store.append(&[row(B, 1, 1, &[(A, 5)])]).unwrap();
1243        assert_eq!((dependent.ready, dependent.pending), (0, 2));
1244        assert!(store.vector("doc").unwrap().is_empty());
1245        assert!(store.missing("doc", &vec![]).unwrap().is_empty());
1246        assert_eq!(
1247            count(&store, "SELECT COUNT(*) FROM pulsify_dangling_op_rows"),
1248            2
1249        );
1250        let filled = store.append(&[next(A, 1, 2)]).unwrap();
1251        assert_eq!((filled.inserted, filled.ready, filled.pending), (1, 3, 0));
1252        assert_eq!(store.vector("doc").unwrap(), vec![(A, 5), (B, 2)]);
1253        assert_eq!(
1254            store.missing("doc", &vec![]).unwrap(),
1255            vec![next(A, 1, 2), next(A, 3, 2), row(B, 1, 1, &[(A, 5)])]
1256        );
1257        assert_eq!(
1258            count(&store, "SELECT COUNT(*) FROM pulsify_op_rows WHERE ready=0"),
1259            0
1260        );
1261    }
1262
1263    #[test]
1264    fn in_order_rows_skip_pending_and_keep_every_check() {
1265        let mut store = SqliteStore::open_in_memory().unwrap();
1266        let batch: Vec<_> = (1..=5).map(|clock| next(A, clock, 1)).collect();
1267        let result = store.append(&batch).unwrap();
1268        assert_eq!((result.inserted, result.ready), (5, 5));
1269        assert_eq!(result.vector, Some(vec![(A, 6)]));
1270        assert_eq!(
1271            count(&store, "SELECT COUNT(*) FROM pulsify_op_rows WHERE ready=0"),
1272            0
1273        );
1274        // Resends stay idempotent, a different payload conflicts.
1275        assert_eq!(store.append(&batch[1..3]).unwrap().inserted, 0);
1276        let mut changed = next(A, 3, 1);
1277        changed.operations.push(0);
1278        let error = store.append(&[changed]).unwrap_err();
1279        assert_eq!(error.message, "Conflicting storage segment");
1280        // A fork at the frontier is caught without reading the previous row,
1281        // and rolls back the whole batch.
1282        for fork in [row(A, 6, 1, &[]), row(A, 6, 1, &[(A, 5)])] {
1283            let error = store.append(&[next(B, 1, 1), fork]).unwrap_err();
1284            assert_eq!(error.message, "Actor history fork");
1285        }
1286        assert_eq!(store.vector("doc").unwrap(), vec![(A, 6)]);
1287        // In-order rows of A while B has a pending row; an overlap with it conflicts.
1288        store.append(&[next(B, 3, 1)]).unwrap();
1289        let both = store.append(&[next(A, 6, 1), next(B, 1, 2)]).unwrap();
1290        assert_eq!((both.ready, both.pending), (3, 0));
1291        assert_eq!(both.vector, Some(vec![(A, 7), (B, 4)]));
1292        // A row whose span covers a waiting row replaces it.
1293        store.append(&[next(B, 6, 1)]).unwrap();
1294        let wide = store.append(&[next(B, 4, 3)]).unwrap();
1295        assert_eq!((wide.inserted, wide.ready, wide.pending), (1, 1, 0));
1296        assert_eq!(wide.vector, Some(vec![(A, 7), (B, 7)]));
1297        assert_eq!(
1298            store.missing("doc", &vec![(A, 7), (B, 4)]).unwrap(),
1299            vec![next(B, 4, 3)]
1300        );
1301    }
1302
1303    /// One kind 7 write of `sid` to the numeric field `field` of the node "n":
1304    /// a last-value row.
1305    pub fn write(sid: u64, clock: u64, lamport: u8, field: u8) -> PatchRow {
1306        PatchRow {
1307            operations: vec![
1308                3,
1309                lamport,
1310                0,
1311                1,
1312                7,
1313                1,
1314                b'n',
1315                1,
1316                field,
1317                sid as u8,
1318                clock as u8,
1319            ],
1320            ..next(sid, clock, 1)
1321        }
1322    }
1323    /// What stays of replaced writes that no earlier row can cover.
1324    pub fn gap(sid: u64, clock: u64, span: u64) -> PatchRow {
1325        PatchRow {
1326            operations: GAP_OPERATIONS.to_vec(),
1327            ..next(sid, clock, span)
1328        }
1329    }
1330    /// The ready rows of "doc": actor, start and span.
1331    fn spans(store: &SqliteStore) -> Vec<(u64, u64, u64)> {
1332        store
1333            .missing("doc", &vec![])
1334            .unwrap()
1335            .iter()
1336            .map(|row| (row.sid, row.clock, row.span))
1337            .collect()
1338    }
1339    /// The values: actor, field, then the clock of the write that holds it.
1340    fn values(store: &SqliteStore) -> Vec<(u64, u8, u64)> {
1341        store
1342            .connection()
1343            .prepare("SELECT sid,register,clock FROM pulsify_values WHERE doc_id='doc' ORDER BY sid,register")
1344            .unwrap()
1345            .query_map([], |r| {
1346                let register: Vec<u8> = r.get(1)?;
1347                assert_eq!(register[..3], [1, b'n', 1]);
1348                Ok((r.get::<_, i64>(0)? as u64, register[3], r.get::<_, i64>(2)? as u64))
1349            })
1350            .unwrap()
1351            .collect::<rusqlite::Result<_>>()
1352            .unwrap()
1353    }
1354    fn changes(store: &SqliteStore) -> i64 {
1355        count(store, "SELECT total_changes()")
1356    }
1357
1358    #[test]
1359    fn a_register_rewritten_many_times_keeps_one_row_per_actor() {
1360        let mut store = SqliteStore::open_in_memory().unwrap();
1361        store.append(&[next(A, 1, 1), next(B, 1, 1)]).unwrap();
1362        for clock in 2..=300u64 {
1363            // Two registers of A, one of which B also writes, with older times.
1364            let before = changes(&store);
1365            let mine = store
1366                .append(&[write(A, clock, 100, (clock % 2) as u8)])
1367                .unwrap();
1368            assert_eq!((mine.inserted, mine.ready, mine.pending), (1, 1, 0));
1369            let late = store.append(&[write(B, clock, 1, 0)]).unwrap();
1370            assert_eq!((late.inserted, late.ready), (1, 1));
1371            assert_eq!(late.vector, Some(vec![(A, clock + 1), (B, clock + 1)]));
1372            // A value and a clock per write.
1373            assert_eq!(changes(&store) - before, 4);
1374        }
1375        // Each actor keeps its first row and its last write to each register,
1376        // whatever the other actor wrote: replicas pick the winner.
1377        assert_eq!(
1378            spans(&store),
1379            vec![
1380                (A, 1, 298),
1381                (A, 299, 1),
1382                (A, 300, 1),
1383                (B, 1, 299),
1384                (B, 300, 1)
1385            ]
1386        );
1387        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 2);
1388        assert_eq!(values(&store), vec![(A, 0, 300), (A, 1, 299), (B, 0, 300)]);
1389        assert_eq!(
1390            store.missing("doc", &vec![(A, 299), (B, 301)]).unwrap(),
1391            vec![write(A, 299, 100, 1), write(A, 300, 100, 0)]
1392        );
1393        // Sent again, whole or with the spans a peer holds, nothing changes.
1394        let mut again = store.missing("doc", &vec![]).unwrap();
1395        again.extend((2..=300).map(|clock| write(A, clock, 100, (clock % 2) as u8)));
1396        assert_eq!(store.append(&again).unwrap().inserted, 0);
1397        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_values"), 3);
1398        // A newer write of the same actor overwrites its value in place.
1399        store.append(&[write(B, 301, 100, 0)]).unwrap();
1400        store.append(&[write(A, 301, 100, 0)]).unwrap();
1401        assert_eq!(values(&store), vec![(A, 0, 301), (A, 1, 299), (B, 0, 301)]);
1402        assert_eq!(
1403            spans(&store),
1404            vec![
1405                (A, 1, 298),
1406                (A, 299, 2),
1407                (A, 301, 1),
1408                (B, 1, 300),
1409                (B, 301, 1)
1410            ]
1411        );
1412    }
1413
1414    #[test]
1415    fn every_actor_keeps_its_own_last_write() {
1416        let mut store = SqliteStore::open_in_memory().unwrap();
1417        store.append(&[next(A, 1, 1), write(A, 2, 9, 0)]).unwrap();
1418        // An older write of another actor is kept: it is that actor's last one.
1419        let late = store.append(&[next(B, 1, 1), write(B, 2, 3, 0)]).unwrap();
1420        assert_eq!((late.inserted, late.ready, late.pending), (2, 2, 0));
1421        assert_eq!(
1422            spans(&store),
1423            vec![(A, 1, 1), (A, 2, 1), (B, 1, 1), (B, 2, 1)]
1424        );
1425        // On promotion: it waited for the row before it, and replaces B's value.
1426        let waiting = store.append(&[write(B, 4, 4, 0), next(B, 5, 1)]).unwrap();
1427        assert_eq!((waiting.ready, waiting.pending), (0, 2));
1428        let filled = store.append(&[next(B, 3, 1)]).unwrap();
1429        assert_eq!((filled.inserted, filled.ready, filled.pending), (1, 3, 0));
1430        assert_eq!(
1431            spans(&store),
1432            vec![
1433                (A, 1, 1),
1434                (A, 2, 1),
1435                (B, 1, 2),
1436                (B, 3, 1),
1437                (B, 4, 1),
1438                (B, 5, 1)
1439            ]
1440        );
1441        assert_eq!(values(&store), vec![(A, 0, 2), (B, 0, 4)]);
1442        store.append(&[write(B, 6, 10, 0)]).unwrap();
1443        assert_eq!(
1444            spans(&store),
1445            vec![
1446                (A, 1, 1),
1447                (A, 2, 1),
1448                (B, 1, 2),
1449                (B, 3, 2),
1450                (B, 5, 1),
1451                (B, 6, 1)
1452            ]
1453        );
1454        assert_eq!(values(&store), vec![(A, 0, 2), (B, 0, 6)]);
1455        assert_eq!(store.vector("doc").unwrap(), vec![(A, 3), (B, 7)]);
1456        // Other kinds and transactions of several operations are history: kept.
1457        let mut kept = write(A, 3, 50, 0);
1458        kept.operations[3] = 2;
1459        let mut plain = write(A, 4, 50, 0);
1460        plain.operations[4] = 1;
1461        store.append(&[kept, plain]).unwrap();
1462        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 6);
1463        assert_eq!(values(&store), vec![(A, 0, 2), (B, 0, 6)]);
1464    }
1465
1466    #[test]
1467    fn replaced_writes_are_served_as_spans_and_gap_rows() {
1468        let mut store = SqliteStore::open_in_memory().unwrap();
1469        store.append(&[write(A, 1, 1, 0)]).unwrap();
1470        store.append(&[write(B, 1, 2, 0)]).unwrap();
1471        assert_eq!(
1472            store.missing("doc", &vec![]).unwrap(),
1473            vec![write(A, 1, 1, 0), write(B, 1, 2, 0)]
1474        );
1475        // Nothing holds A's first sequence numbers any more: a gap row stands
1476        // for them, depending on what came before it.
1477        store
1478            .append(&[write(A, 2, 1, 0), write(A, 3, 1, 0)])
1479            .unwrap();
1480        assert_eq!(
1481            store.missing("doc", &vec![(B, 2)]).unwrap(),
1482            vec![gap(A, 1, 2), write(A, 3, 1, 0)]
1483        );
1484        assert_eq!(
1485            store.missing("doc", &vec![(A, 2), (B, 2)]).unwrap(),
1486            vec![gap(A, 2, 1), write(A, 3, 1, 0)]
1487        );
1488        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 0);
1489        // A peer sends a gap row where this store holds a row, and the reverse:
1490        // neither is a conflict, and the row that is held stays.
1491        let result = store.append(&[gap(B, 1, 1), write(A, 1, 1, 0)]).unwrap();
1492        assert_eq!(result.inserted, 0);
1493        // A gap row that arrives only moves the frontier.
1494        let before = changes(&store);
1495        store.append(&[gap(B, 2, 3), gap(A + 2, 1, 2)]).unwrap();
1496        assert_eq!(changes(&store) - before, 2);
1497        assert_eq!(
1498            spans(&store),
1499            vec![(A, 1, 2), (A, 3, 1), (B, 1, 4), (A + 2, 1, 2)]
1500        );
1501        assert_eq!(
1502            store.vector("doc").unwrap(),
1503            vec![(A, 4), (B, 5), (A + 2, 3)]
1504        );
1505        // A hole between history rows, and values beside a packed segment.
1506        store
1507            .append(&[next(B, 5, 1), write(B, 6, 3, 1), next(B, 7, 1)])
1508            .unwrap();
1509        store.append(&[write(B, 8, 4, 1), next(B, 9, 1)]).unwrap();
1510        let remotes = [
1511            vec![],
1512            vec![(B, 6)],
1513            vec![(B, 7)],
1514            vec![(B, 8)],
1515            vec![(B, 9)],
1516        ];
1517        let expected: Vec<_> = remotes
1518            .iter()
1519            .map(|remote| store.missing("doc", remote).unwrap())
1520            .collect();
1521        assert_eq!(
1522            expected[2]
1523                .iter()
1524                .filter(|row| row.sid == B)
1525                .collect::<Vec<_>>(),
1526            vec![&next(B, 7, 1), &write(B, 8, 4, 1), &next(B, 9, 1)]
1527        );
1528        assert_eq!(
1529            expected[1]
1530                .iter()
1531                .filter(|row| row.sid == B)
1532                .collect::<Vec<_>>(),
1533            vec![
1534                &PatchRow {
1535                    span: 2,
1536                    ..next(B, 5, 1)
1537                },
1538                &next(B, 7, 1),
1539                &write(B, 8, 4, 1),
1540                &next(B, 9, 1)
1541            ]
1542        );
1543        pack(&store, B);
1544        assert_eq!(
1545            count(
1546                &store,
1547                "SELECT COUNT(*) FROM pulsify_op_rows WHERE packed=1"
1548            ),
1549            1
1550        );
1551        for (remote, expected) in remotes.iter().zip(&expected) {
1552            assert_eq!(&store.missing("doc", remote).unwrap(), expected);
1553        }
1554        let changed = PatchRow {
1555            operations: vec![9],
1556            ..next(B, 7, 1)
1557        };
1558        let error = store.append(&[changed]).unwrap_err();
1559        assert_eq!(error.message, "Conflicting storage segment");
1560        assert_eq!(values(&store), vec![(A, 0, 3), (B, 0, 1), (B, 1, 8)]);
1561    }
1562
1563    #[test]
1564    fn other_contents_at_a_stored_identity_still_conflict() {
1565        let mut store = SqliteStore::open_in_memory().unwrap();
1566        store
1567            .append(&[next(A, 1, 1), write(A, 2, 5, 0), next(A, 5, 2)])
1568            .unwrap();
1569        let changed = |mut row: PatchRow| {
1570            row.operations.push(1);
1571            row
1572        };
1573        for bad in [
1574            // A ready row, a last-value row and a row that waits, whatever the span.
1575            changed(next(A, 1, 1)),
1576            changed(next(A, 1, 4)),
1577            changed(write(A, 2, 5, 0)),
1578            changed(next(A, 2, 1)),
1579            changed(next(A, 5, 2)),
1580            changed(next(A, 5, 9)),
1581        ] {
1582            let error = store.append(&[next(B, 1, 1), bad]).unwrap_err();
1583            assert_eq!(
1584                (error.code, error.message.as_str()),
1585                ("CONFLICT", "Conflicting storage segment")
1586            );
1587        }
1588        assert_eq!(store.vector("doc").unwrap(), vec![(A, 3)]);
1589        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 2);
1590        assert_eq!(values(&store), vec![(A, 0, 2)]);
1591        // Once replaced, a row is no longer compared: its sequence number holds nothing.
1592        store.append(&[write(A, 3, 6, 0)]).unwrap();
1593        assert_eq!(spans(&store), vec![(A, 1, 2), (A, 3, 1)]);
1594        assert_eq!(
1595            store
1596                .append(&[changed(write(A, 2, 5, 0))])
1597                .unwrap()
1598                .inserted,
1599            0
1600        );
1601        let error = store.append(&[changed(next(A, 1, 2))]).unwrap_err();
1602        assert_eq!(error.code, "CONFLICT");
1603    }
1604
1605    #[test]
1606    fn opens_a_database_created_before_fields_without_history() {
1607        let db = Connection::open_in_memory().unwrap();
1608        let old = SCHEMA
1609            .split("CREATE TABLE IF NOT EXISTS pulsify_values")
1610            .next()
1611            .unwrap();
1612        db.execute_batch(old).unwrap();
1613        db.execute(
1614            "INSERT INTO pulsify_op_rows(doc_id,sid,time_start,span,dependencies,operations,ready) VALUES('doc',?,1,1,'[]',x'010203',1)",
1615            [A as i64],
1616        )
1617        .unwrap();
1618        db.execute(
1619            "INSERT INTO pulsify_doc_clocks VALUES('doc',?,2)",
1620            [A as i64],
1621        )
1622        .unwrap();
1623        // Its rows are history rows.
1624        let mut store = SqliteStore::new(db).unwrap();
1625        store
1626            .append(&[write(A, 2, 1, 0), write(A, 3, 2, 0)])
1627            .unwrap();
1628        assert_eq!(spans(&store), vec![(A, 1, 2), (A, 3, 1)]);
1629        assert_eq!(values(&store), vec![(A, 0, 3)]);
1630    }
1631
1632    #[test]
1633    fn moves_the_rows_of_the_register_index_to_values() {
1634        // The unreleased layout: one row per register, indexed, spans grown
1635        // over replaced writes, and gap rows where no row could grow.
1636        let db = Connection::open_in_memory().unwrap();
1637        db.execute_batch(&format!(
1638            "{}CREATE TABLE pulsify_registers (
1639 doc_id TEXT NOT NULL, register BLOB NOT NULL, sid INTEGER NOT NULL, clock INTEGER NOT NULL,
1640 lamport INTEGER NOT NULL,
1641 PRIMARY KEY(doc_id, register)
1642) WITHOUT ROWID;",
1643            SCHEMA
1644                .split("CREATE TABLE IF NOT EXISTS pulsify_values")
1645                .next()
1646                .unwrap()
1647        ))
1648        .unwrap();
1649        let insert = |row: &PatchRow, ready: bool| {
1650            db.execute(
1651                "INSERT INTO pulsify_op_rows(doc_id,sid,time_start,span,dependencies,operations,ready) VALUES('doc',?,?,?,?,?,?)",
1652                params![
1653                    row.sid as i64,
1654                    row.clock as i64,
1655                    row.span as i64,
1656                    serde_json::to_string(&row.dependencies).unwrap(),
1657                    row.operations,
1658                    ready
1659                ],
1660            )
1661            .unwrap();
1662        };
1663        let a3 = write(A, 3, 5, 0);
1664        let b2 = write(B, 2, 7, 1);
1665        for row in [next(A, 1, 2), a3.clone(), gap(B, 1, 1), b2.clone()] {
1666            insert(&row, true);
1667        }
1668        insert(&gap(B, 5, 1), false);
1669        for (row, lamport) in [(&a3, 5), (&b2, 7)] {
1670            db.execute(
1671                "INSERT INTO pulsify_registers VALUES('doc',?,?,?,?)",
1672                params![
1673                    last_register_of(&row.operations).unwrap().register,
1674                    row.sid as i64,
1675                    row.clock as i64,
1676                    lamport
1677                ],
1678            )
1679            .unwrap();
1680        }
1681        db.execute_batch(&format!(
1682            "INSERT INTO pulsify_doc_clocks VALUES('doc',{A},4),('doc',{B},3);"
1683        ))
1684        .unwrap();
1685        let mut store = SqliteStore::new(db).unwrap();
1686        assert_eq!(
1687            count(
1688                &store,
1689                "SELECT COUNT(*) FROM sqlite_master WHERE name='pulsify_registers'"
1690            ),
1691            0
1692        );
1693        assert_eq!(values(&store), vec![(A, 0, 3), (B, 1, 2)]);
1694        // The waiting gap row stays; the ready one is a hole now.
1695        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 2);
1696        assert_eq!(
1697            store.missing("doc", &vec![]).unwrap(),
1698            vec![next(A, 1, 2), a3, gap(B, 1, 1), b2]
1699        );
1700        let result = store.append(&[next(B, 3, 2), write(A, 4, 6, 0)]).unwrap();
1701        assert_eq!((result.ready, result.pending), (3, 0));
1702        assert_eq!(values(&store), vec![(A, 0, 4), (B, 1, 2)]);
1703        assert_eq!(
1704            spans(&store),
1705            vec![(A, 1, 3), (A, 4, 1), (B, 1, 1), (B, 2, 1), (B, 3, 3)]
1706        );
1707    }
1708
1709    #[test]
1710    fn rejects_invalid_rows_and_documents() {
1711        let mut store = SqliteStore::open_in_memory().unwrap();
1712        let mut other_doc = next(B, 1, 1);
1713        other_doc.doc_id = "other".into();
1714        let mut empty = next(A, 1, 1);
1715        empty.operations.clear();
1716        for rows in [
1717            vec![next(A, 1, 1), other_doc],
1718            vec![row(1, 1, 1, &[])],
1719            vec![row(A, 0, 1, &[])],
1720            vec![row(A, 1, 0, &[])],
1721            vec![row(A, 2, 1, &[(A, 3)])],
1722            vec![row(A, 1, 1, &[(B, 1), (A, 1)])],
1723            vec![empty],
1724        ] {
1725            assert_eq!(store.append(&rows).unwrap_err().code, "INVALID_MESSAGE");
1726        }
1727        let too_many: Vec<_> = (1..=MAX_MESSAGE_ROWS as u64 + 1)
1728            .map(|clock| next(A, clock, 1))
1729            .collect();
1730        assert_eq!(store.append(&too_many).unwrap_err().code, "LIMIT_EXCEEDED");
1731        assert_eq!(store.vector("").unwrap_err().code, "INVALID_MESSAGE");
1732        assert_eq!(store.vector("a\0b").unwrap_err().code, "INVALID_MESSAGE");
1733        assert_eq!(
1734            store.vector(&"x".repeat(1025)).unwrap_err().code,
1735            "INVALID_MESSAGE"
1736        );
1737        assert_eq!(
1738            store
1739                .missing("doc", &vec![(B, 1), (A, 1)])
1740                .unwrap_err()
1741                .code,
1742            "INVALID_MESSAGE"
1743        );
1744        assert_eq!(count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"), 0);
1745    }
1746
1747    #[test]
1748    fn limits_the_number_of_actors() {
1749        let mut store = SqliteStore::open_in_memory().unwrap();
1750        let rows: Vec<_> = (0..MAX_VECTOR_ENTRIES as u64)
1751            .map(|i| next(A + i, 1, 1))
1752            .collect();
1753        store.append(&rows).unwrap();
1754        let error = store
1755            .append(&[next(A + MAX_VECTOR_ENTRIES as u64, 2, 1)])
1756            .unwrap_err();
1757        assert_eq!(error.code, "LIMIT_EXCEEDED");
1758        assert_eq!(store.vector("doc").unwrap().len(), MAX_VECTOR_ENTRIES);
1759        assert_eq!(
1760            count(&store, "SELECT COUNT(*) FROM pulsify_op_rows"),
1761            MAX_VECTOR_ENTRIES as i64
1762        );
1763    }
1764
1765    #[test]
1766    fn persists_across_reopen() {
1767        let path = std::env::temp_dir().join(format!(
1768            "pulsify-sqlite-{}-{:?}.sqlite",
1769            std::process::id(),
1770            std::thread::current().id()
1771        ));
1772        let _ = std::fs::remove_file(&path);
1773        {
1774            let mut store = SqliteStore::open(&path).unwrap();
1775            store.append(&[next(A, 1, 3), next(A, 5, 1)]).unwrap();
1776        }
1777        let mut store = SqliteStore::open(&path).unwrap();
1778        assert_eq!(store.vector("doc").unwrap(), vec![(A, 4)]);
1779        assert_eq!(store.append(&[next(A, 4, 1)]).unwrap().ready, 2);
1780        let (rows, vector) = store.sync_state("doc", &vec![(A, 4)]).unwrap();
1781        assert_eq!(vector, vec![(A, 6)]);
1782        assert_eq!(rows, vec![next(A, 4, 1), next(A, 5, 1)]);
1783        drop(store);
1784        for suffix in ["", "-wal", "-shm"] {
1785            let _ = std::fs::remove_file(format!("{}{suffix}", path.display()));
1786        }
1787    }
1788}