Skip to main content

agentmux_srv_core/backend/user_sync/
log.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The change log and the state tables beside it (SPEC_USER_DATA_SYNC_LAYER §3.2, §5). Every change, made here or
5//! taken from another machine, is one row of `db_sync_log`, keyed by its origin machine and that machine's
6//! sequence number, so a catch-up is "everything after these sequences" and applying a record twice changes
7//! nothing. `db_sync_state` points at the log row that is each record's current state. `db_sync_mark` is the
8//! high-water mark of the head last accepted from a store, so an older head is refused (rollback).
9//!
10//! Functions take a `&Connection` so the whole layer is tested against in-memory stores of fake machines.
11
12use std::collections::BTreeMap;
13
14use rusqlite::{params, Connection, OptionalExtension, Row};
15use serde::{Deserialize, Serialize};
16
17use super::adapter::{Adapter, Merge, Side};
18use super::hlc::{Clock, SkewRefused, Version};
19use super::record::{BadRecord, Header, Record};
20
21/// The tables, all `IF NOT EXISTS` so [`init`] may run on every open (no schema version bump). Nothing calls
22/// `init` yet: the first collection's adapter does, when it starts writing the log.
23pub(crate) const SCHEMA: &str = "
24    CREATE TABLE IF NOT EXISTS db_sync_collections (
25        id         TEXT PRIMARY KEY,
26        kind       TEXT NOT NULL,
27        epoch      INTEGER NOT NULL DEFAULT 0,
28        tier       TEXT NOT NULL DEFAULT 'local',
29        created_at INTEGER NOT NULL DEFAULT 0
30    );
31    CREATE TABLE IF NOT EXISTS db_sync_log (
32        collection TEXT NOT NULL,
33        origin     TEXT NOT NULL,
34        seq        INTEGER NOT NULL,
35        record     TEXT NOT NULL,
36        wall_ms    INTEGER NOT NULL,
37        counter    INTEGER NOT NULL,
38        machine    TEXT NOT NULL,
39        epoch      INTEGER NOT NULL,
40        tombstone  INTEGER NOT NULL DEFAULT 0,
41        size       INTEGER NOT NULL,
42        base_wall    INTEGER,
43        base_counter INTEGER,
44        base_machine TEXT,
45        sig        TEXT NOT NULL,
46        body       BLOB NOT NULL,
47        PRIMARY KEY (collection, origin, seq)
48    );
49    CREATE TABLE IF NOT EXISTS db_sync_epoch_cut (
50        collection TEXT NOT NULL,
51        epoch      INTEGER NOT NULL,
52        origin     TEXT NOT NULL,
53        last_seq   INTEGER NOT NULL,
54        PRIMARY KEY (collection, epoch, origin)
55    );
56    CREATE INDEX IF NOT EXISTS idx_sync_log_record ON db_sync_log (collection, record);
57    CREATE TABLE IF NOT EXISTS db_sync_state (
58        collection TEXT NOT NULL,
59        record     TEXT NOT NULL,
60        origin     TEXT NOT NULL,
61        seq        INTEGER NOT NULL,
62        PRIMARY KEY (collection, record)
63    );
64    CREATE TABLE IF NOT EXISTS db_sync_recheck (
65        collection TEXT NOT NULL,
66        origin     TEXT NOT NULL,
67        seq        INTEGER NOT NULL,
68        PRIMARY KEY (collection, origin, seq)
69    );
70    CREATE TABLE IF NOT EXISTS db_sync_mark (
71        collection TEXT PRIMARY KEY,
72        generation INTEGER NOT NULL DEFAULT 0,
73        vector     TEXT NOT NULL DEFAULT '{}'
74    );";
75
76/// What a machine holds of a collection: for each origin, the highest sequence it has.
77pub type Vector = BTreeMap<String, u64>;
78/// The public keys pinned for each origin machine.
79pub type Pins = BTreeMap<String, [u8; 32]>;
80
81/// Days a deleted record's tombstone is kept: a board, and a Vault.
82pub const HORIZON_BOARD_DAYS: i64 = 30;
83pub const HORIZON_VAULT_DAYS: i64 = 90;
84
85/// Why a record was refused.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub enum Refused {
88    UnknownCollection,
89    UnknownOrigin,
90    Bad(BadRecord),
91    /// The record is at another key epoch than the collection's here (a removed member, or news not yet taken in).
92    Epoch { have: u32, got: u32 },
93    Skew(SkewRefused),
94    /// A sequence was skipped: ask the origin again from `have`.
95    Gap { have: u64 },
96    /// A head older than the one already accepted.
97    Rollback,
98}
99
100#[derive(Debug)]
101pub enum SyncError {
102    Refused(Refused),
103    Db(rusqlite::Error),
104    /// The caller's sealing of a body failed; nothing was written.
105    Seal(String),
106}
107
108impl From<rusqlite::Error> for SyncError {
109    fn from(e: rusqlite::Error) -> Self {
110        SyncError::Db(e)
111    }
112}
113
114impl From<Refused> for SyncError {
115    fn from(r: Refused) -> Self {
116        SyncError::Refused(r)
117    }
118}
119
120/// What applying a record did.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
122pub enum Outcome {
123    Applied,
124    KeptLocal,
125    Conflict,
126    /// Already held (same origin and sequence): nothing changed.
127    Duplicate,
128    /// Written at a key epoch after the others had stopped at it: kept so the origin's sequence is unbroken, and
129    /// changing no record's state (the origin writes it again at the current epoch).
130    Void,
131}
132
133/// The machine writing: its identifier, its signing key's seed and its clock.
134pub struct Signer<'a> {
135    pub machine: &'a str,
136    pub private: &'a [u8],
137    pub clock: &'a mut Clock,
138}
139
140pub fn init(conn: &Connection) -> rusqlite::Result<()> {
141    conn.execute_batch(SCHEMA)?;
142    conn.execute_batch(super::lock::SCHEMA)?;
143    conn.execute_batch(super::chain_store::SCHEMA)?;
144    conn.execute_batch(super::keys::SCHEMA)
145}
146
147pub fn ensure_collection(conn: &Connection, id: &str, kind: &str, now_ms: i64) -> rusqlite::Result<()> {
148    conn.execute(
149        "INSERT OR IGNORE INTO db_sync_collections (id, kind, created_at) VALUES (?1, ?2, ?3)",
150        params![id, kind, now_ms],
151    )?;
152    Ok(())
153}
154
155pub fn collection_epoch(conn: &Connection, id: &str) -> rusqlite::Result<Option<u32>> {
156    conn.query_row("SELECT epoch FROM db_sync_collections WHERE id = ?1", params![id], |r| r.get(0)).optional()
157}
158
159/// A member left: the collection moves to the next key epoch. `ended` is what the membership change says each
160/// remaining member had written at the epoch being left: a record at that old epoch is still taken (a member that
161/// had not yet caught up completes its catch-up) when it is within its origin's end; any other record at an old
162/// epoch is refused, so a removed member (which has no end) cannot write on at the old key.
163pub fn set_epoch(conn: &Connection, id: &str, epoch: u32, ended: &Vector) -> rusqlite::Result<()> {
164    let tx = conn.unchecked_transaction()?;
165    if let Some(old) = collection_epoch(&tx, id)? {
166        for (origin, last) in ended {
167            tx.execute(
168                "INSERT OR REPLACE INTO db_sync_epoch_cut (collection, epoch, origin, last_seq) VALUES (?1, ?2, ?3, ?4)",
169                params![id, old, origin, *last as i64],
170            )?;
171        }
172    }
173    tx.execute("UPDATE db_sync_collections SET epoch = ?2 WHERE id = ?1", params![id, epoch])?;
174    tx.commit()
175}
176
177/// Sets the collection's key epoch and the ends of the epochs before it to exactly what the membership chain says now,
178/// in either direction: a removal that lost a fork to another entry leaves no epoch and no ends behind. `cuts` holds,
179/// for each epoch left, what each remaining member had written at it. Several statements: the caller makes them one
180/// (`ops::sync_epoch` and `ops::store_chain` do), so a failure part-way leaves nothing changed.
181pub fn reset_epochs(conn: &Connection, id: &str, epoch: u32, cuts: &[(u32, &Vector)]) -> rusqlite::Result<()> {
182    let before = standing(conn, id)?;
183    conn.execute("DELETE FROM db_sync_epoch_cut WHERE collection = ?1", params![id])?;
184    for (left, ended) in cuts {
185        for (origin, last) in ended.iter() {
186            conn.execute(
187                "INSERT INTO db_sync_epoch_cut (collection, epoch, origin, last_seq) VALUES (?1, ?2, ?3, ?4)",
188                params![id, left, origin, *last as i64],
189            )?;
190        }
191    }
192    conn.execute("UPDATE db_sync_collections SET epoch = ?2 WHERE id = ?1", params![id, epoch])?;
193    // A row that was void and no longer is (its removal lost a fork), or the other way round, is to be settled by
194    // [`recheck`], which has the collection's adapter.
195    let after = standing(conn, id)?;
196    for (key, now) in &after {
197        if before.get(key).is_some_and(|was| was != now) {
198            conn.execute(
199                "INSERT OR IGNORE INTO db_sync_recheck (collection, origin, seq) VALUES (?1, ?2, ?3)",
200                params![id, key.0, key.1 as i64],
201            )?;
202        }
203    }
204    Ok(())
205}
206
207/// Whether each row of the collection counts: it is at the collection's epoch, or within the end its origin had at its
208/// own epoch. (A row at any other epoch is void: kept so its origin's sequence is unbroken, and changing nothing.)
209fn standing(conn: &Connection, id: &str) -> rusqlite::Result<BTreeMap<(String, u64), bool>> {
210    let mut stmt = conn.prepare(
211        "SELECT l.origin, l.seq, (l.epoch = (SELECT epoch FROM db_sync_collections WHERE id = ?1)
212                OR l.seq <= COALESCE((SELECT last_seq FROM db_sync_epoch_cut c
213                                      WHERE c.collection = ?1 AND c.origin = l.origin AND c.epoch = l.epoch), -1))
214         FROM db_sync_log l WHERE l.collection = ?1",
215    )?;
216    let rows = stmt.query_map(params![id], |r| Ok(((r.get::<_, String>(0)?, r.get::<_, i64>(1)? as u64), r.get::<_, bool>(2)?)))?;
217    rows.collect()
218}
219
220/// Settles the records that a change of the epoch ends moved rows in or out of ([`reset_epochs`] notes them): a write
221/// stored as void under a removal that then lost a fork counts now and is merged as it would have been, and one that
222/// no longer counts stops being its record's state. What counts is merged oldest version first, as the adapter would
223/// have taken the records in; what `me` wrote is kept whether or not it counts (it is written again at the current
224/// epoch, which supersedes it). Answers how many records' state moved.
225pub fn recheck(conn: &Connection, collection: &str, me: &str, adapter: &dyn Adapter) -> rusqlite::Result<usize> {
226    let tx = conn.unchecked_transaction()?;
227    let records: Vec<String> = {
228        let mut stmt = tx.prepare(
229            "SELECT DISTINCT l.record FROM db_sync_recheck r
230             JOIN db_sync_log l ON l.collection = r.collection AND l.origin = r.origin AND l.seq = r.seq
231             WHERE r.collection = ?1 ORDER BY l.record",
232        )?;
233        let rows = stmt.query_map(params![collection], |r| r.get(0))?;
234        rows.collect::<Result<_, _>>()?
235    };
236    let standing = standing(&tx, collection)?;
237    let mut moved = 0;
238    for record in records {
239        let mut counted: Vec<Record> = {
240            let mut stmt = tx.prepare(&format!("SELECT {COLS}, sig, body FROM db_sync_log WHERE collection = ?1 AND record = ?2"))?;
241            let rows = stmt.query_map(params![collection, record], record_of)?;
242            rows.collect::<Result<Vec<_>, _>>()?
243        };
244        counted.retain(|r| r.header.origin == me || standing.get(&(r.header.origin.clone(), r.header.seq)).copied().unwrap_or(false));
245        counted.sort_by(|a, b| a.header.version.cmp(&b.header.version));
246        let mut state: Option<&Header> = None;
247        for r in &counted {
248            match adapter.merge(state, &r.header) {
249                Merge::Applied | Merge::Conflict { current: Side::Incoming } => state = Some(&r.header),
250                Merge::KeptLocal | Merge::Conflict { current: Side::Local } => {}
251            }
252        }
253        let was = current(&tx, collection, &record)?.map(|r| (r.header.origin, r.header.seq));
254        if was != state.map(|h| (h.origin.clone(), h.seq)) {
255            moved += 1;
256            match state {
257                Some(h) => point_state(&tx, h)?,
258                None => {
259                    tx.execute("DELETE FROM db_sync_state WHERE collection = ?1 AND record = ?2", params![collection, record])?;
260                }
261            }
262        }
263    }
264    tx.execute("DELETE FROM db_sync_recheck WHERE collection = ?1", params![collection])?;
265    tx.commit()?;
266    Ok(moved)
267}
268
269/// The last sequence its origin had written at the epoch `h` is at, as the membership change that ended the epoch
270/// named it; none if that epoch ended without the origin being a remaining member.
271fn epoch_end(conn: &Connection, h: &Header) -> rusqlite::Result<Option<i64>> {
272    conn.query_row(
273        "SELECT last_seq FROM db_sync_epoch_cut WHERE collection = ?1 AND epoch = ?2 AND origin = ?3",
274        params![h.collection, h.epoch, h.origin],
275        |r| r.get(0),
276    )
277    .optional()
278}
279
280pub fn horizon_days(kind: &str) -> i64 {
281    if kind == "vault" {
282        HORIZON_VAULT_DAYS
283    } else {
284        HORIZON_BOARD_DAYS
285    }
286}
287
288const COLS: &str = "collection, record, wall_ms, counter, machine, origin, seq, epoch, tombstone, size, base_wall, base_counter, base_machine";
289
290fn header_of(r: &Row) -> rusqlite::Result<Header> {
291    let base = match r.get::<_, Option<i64>>(10)? {
292        Some(wall_ms) => Some(Version { wall_ms, counter: r.get(11)?, machine: r.get(12)? }),
293        None => None,
294    };
295    Ok(Header {
296        collection: r.get(0)?,
297        record: r.get(1)?,
298        version: Version { wall_ms: r.get(2)?, counter: r.get(3)?, machine: r.get(4)? },
299        base,
300        origin: r.get(5)?,
301        seq: r.get::<_, i64>(6)? as u64,
302        epoch: r.get(7)?,
303        tombstone: r.get::<_, i64>(8)? != 0,
304        size: r.get::<_, i64>(9)? as u64,
305    })
306}
307
308fn record_of(r: &Row) -> rusqlite::Result<Record> {
309    Ok(Record { header: header_of(r)?, sig: r.get(13)?, body: r.get(14)? })
310}
311
312fn have(conn: &Connection, collection: &str, origin: &str) -> rusqlite::Result<u64> {
313    let n: Option<i64> =
314        conn.query_row("SELECT MAX(seq) FROM db_sync_log WHERE collection = ?1 AND origin = ?2", params![collection, origin], |r| r.get(0))?;
315    Ok(n.unwrap_or(0) as u64)
316}
317
318/// What this machine holds: the highest sequence of each origin.
319pub fn vector(conn: &Connection, collection: &str) -> rusqlite::Result<Vector> {
320    let mut stmt = conn.prepare("SELECT origin, MAX(seq) FROM db_sync_log WHERE collection = ?1 GROUP BY origin")?;
321    let rows = stmt.query_map(params![collection], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)? as u64)))?;
322    rows.collect()
323}
324
325fn insert_log(conn: &Connection, rec: &Record) -> rusqlite::Result<()> {
326    let h = &rec.header;
327    let base = h.base.as_ref();
328    conn.execute(
329        "INSERT INTO db_sync_log (collection, origin, seq, record, wall_ms, counter, machine, epoch, tombstone, size,
330                                  base_wall, base_counter, base_machine, sig, body)
331         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
332        params![
333            h.collection, h.origin, h.seq as i64, h.record, h.version.wall_ms, h.version.counter, h.version.machine, h.epoch,
334            h.tombstone as i64, h.size as i64, base.map(|b| b.wall_ms), base.map(|b| b.counter), base.map(|b| b.machine.clone()),
335            rec.sig, rec.body
336        ],
337    )?;
338    Ok(())
339}
340
341fn point_state(conn: &Connection, h: &Header) -> rusqlite::Result<()> {
342    conn.execute(
343        "INSERT OR REPLACE INTO db_sync_state (collection, record, origin, seq) VALUES (?1, ?2, ?3, ?4)",
344        params![h.collection, h.record, h.origin, h.seq as i64],
345    )?;
346    Ok(())
347}
348
349/// A record's current state, as a whole record.
350pub fn current(conn: &Connection, collection: &str, record: &str) -> rusqlite::Result<Option<Record>> {
351    conn.query_row(
352        "SELECT l.collection, l.record, l.wall_ms, l.counter, l.machine, l.origin, l.seq, l.epoch, l.tombstone, l.size,
353                l.base_wall, l.base_counter, l.base_machine, l.sig, l.body
354         FROM db_sync_state s JOIN db_sync_log l ON l.collection = s.collection AND l.origin = s.origin AND l.seq = s.seq
355         WHERE s.collection = ?1 AND s.record = ?2",
356        params![collection, record],
357        record_of,
358    )
359    .optional()
360}
361
362/// Whether a collection other than `collection` holds `record` as a live record (not a tombstone): a record the log has
363/// moved to another collection is live in the new one while the old one ends it.
364pub fn live_elsewhere(conn: &Connection, collection: &str, record: &str) -> rusqlite::Result<bool> {
365    let n: i64 = conn.query_row(
366        "SELECT COUNT(*) FROM db_sync_state s JOIN db_sync_log l ON l.collection = s.collection AND l.origin = s.origin AND l.seq = s.seq
367         WHERE s.collection != ?1 AND s.record = ?2 AND l.tombstone = 0",
368        params![collection, record],
369        |r| r.get(0),
370    )?;
371    Ok(n > 0)
372}
373
374/// The highest version this store holds in a collection, from any origin.
375fn max_version(conn: &Connection, collection: &str) -> rusqlite::Result<Option<Version>> {
376    conn.query_row(
377        "SELECT wall_ms, counter, machine FROM db_sync_log WHERE collection = ?1
378         ORDER BY wall_ms DESC, counter DESC, machine DESC LIMIT 1",
379        params![collection],
380        |r| Ok(Version { wall_ms: r.get(0)?, counter: r.get(1)?, machine: r.get(2)? }),
381    )
382    .optional()
383}
384
385/// A change made here: the next sequence of this machine's log, the next version of its clock, signed. The clock
386/// is first raised to the highest version the log holds, so a clock made fresh after a restart (or a wall clock
387/// that stepped back) still makes a version after the record's current state, and the new write may point it.
388pub fn append_local(
389    conn: &Connection,
390    signer: &mut Signer,
391    collection: &str,
392    record: &str,
393    body: Vec<u8>,
394    tombstone: bool,
395    now_ms: i64,
396) -> Result<Record, SyncError> {
397    append_local_with(conn, signer, collection, record, tombstone, now_ms, |_| Ok(body))
398}
399
400/// What the header of a record being written will carry, handed to the caller before the body is made so it can
401/// seal the body for exactly that place (the associated data of the seal is these fields).
402#[derive(Debug, Clone, PartialEq, Eq)]
403pub struct SealAt {
404    pub collection: String,
405    pub record: String,
406    pub version: Version,
407    pub base: Option<Version>,
408    pub epoch: u32,
409}
410
411/// [`append_local`] with the body made by `seal` once the version, base and epoch are known. A tombstone has no
412/// body: `seal` is not called. An error from `seal` writes nothing.
413pub fn append_local_with(
414    conn: &Connection,
415    signer: &mut Signer,
416    collection: &str,
417    record: &str,
418    tombstone: bool,
419    now_ms: i64,
420    seal: impl FnOnce(&SealAt) -> Result<Vec<u8>, String>,
421) -> Result<Record, SyncError> {
422    let epoch = collection_epoch(conn, collection)?.ok_or(Refused::UnknownCollection)?;
423    if let Some(held) = max_version(conn, collection)? {
424        signer.clock.raise(&held);
425    }
426    let base = current(conn, collection, record)?.map(|r| r.header.version);
427    let version = signer.clock.tick(now_ms);
428    let body = if tombstone {
429        Vec::new()
430    } else {
431        seal(&SealAt { collection: collection.to_string(), record: record.to_string(), version: version.clone(), base: base.clone(), epoch })
432            .map_err(SyncError::Seal)?
433    };
434    let header = Header {
435        collection: collection.to_string(),
436        record: record.to_string(),
437        version,
438        base,
439        origin: signer.machine.to_string(),
440        seq: have(conn, collection, signer.machine)? + 1,
441        epoch,
442        tombstone,
443        size: body.len() as u64,
444    };
445    let rec = Record::sign(signer.private, header, body).ok_or(Refused::Bad(BadRecord::Malformed))?;
446    let tx = conn.unchecked_transaction()?;
447    insert_log(&tx, &rec)?;
448    point_state(&tx, &rec.header)?;
449    tx.commit()?;
450    Ok(rec)
451}
452
453/// A record from another machine. Refused unless it is at this collection's key epoch, from a pinned origin,
454/// correctly signed, not too far ahead of this clock and the next in its origin's sequence; applying one already
455/// held changes nothing. The adapter says whether it becomes the record's state.
456pub fn apply_remote(
457    conn: &Connection,
458    rec: &Record,
459    pins: &Pins,
460    clock: &mut Clock,
461    now_ms: i64,
462    adapter: &dyn Adapter,
463) -> Result<Outcome, SyncError> {
464    let h = &rec.header;
465    let epoch = collection_epoch(conn, &h.collection)?.ok_or(Refused::UnknownCollection)?;
466    // A record at an older epoch is taken only from an origin that remained when the epoch ended. Within the end it
467    // counts like any other; beyond it, it was written after the others had stopped at that key: it is kept in the
468    // log, so the origin's sequence stays unbroken, and it changes nothing (it is void).
469    let mut void = false;
470    if h.epoch > epoch {
471        return Err(Refused::Epoch { have: epoch, got: h.epoch }.into());
472    }
473    if h.epoch < epoch {
474        let end = epoch_end(conn, h)?.ok_or(Refused::Epoch { have: epoch, got: h.epoch })?;
475        void = h.seq as i64 > end;
476    }
477    let key = pins.get(&h.origin).ok_or(Refused::UnknownOrigin)?;
478    rec.verify(key).map_err(Refused::Bad)?;
479    let held = have(conn, &h.collection, &h.origin)?;
480    if h.seq <= held {
481        return Ok(Outcome::Duplicate);
482    }
483    if h.seq > held + 1 {
484        return Err(Refused::Gap { have: held }.into());
485    }
486    if void {
487        // Its date is checked as any record's is, but not taken in: a record that changes nothing must not move this
488        // machine's clock (its next writes would be refused as ahead by the others).
489        clock.clone().observe(&h.version, now_ms).map_err(Refused::Skew)?;
490        let tx = conn.unchecked_transaction()?;
491        insert_log(&tx, rec)?;
492        tx.commit()?;
493        return Ok(Outcome::Void);
494    }
495    clock.observe(&h.version, now_ms).map_err(Refused::Skew)?;
496    let tx = conn.unchecked_transaction()?;
497    insert_log(&tx, rec)?;
498    let local = current(&tx, &h.collection, &h.record)?.map(|r| r.header);
499    let merge = adapter.merge(local.as_ref(), h);
500    if matches!(merge, Merge::Applied | Merge::Conflict { current: Side::Incoming }) {
501        point_state(&tx, h)?;
502    }
503    tx.commit()?;
504    Ok(match merge {
505        Merge::Applied => Outcome::Applied,
506        Merge::KeptLocal => Outcome::KeptLocal,
507        Merge::Conflict { .. } => Outcome::Conflict,
508    })
509}
510
511/// What a peer lacks: the records after the sequences in `vector`, per origin, at most `limit`, oldest version first.
512/// A record at an epoch other than the collection's is served only if its origin remained when that epoch ended (the
513/// peer keeps one beyond the end as void): any other would be refused, so it is never sent and the peer's vector
514/// never waits on it.
515pub fn since(conn: &Connection, collection: &str, vector: &Vector, limit: usize) -> rusqlite::Result<Vec<Record>> {
516    let mut origins = conn.prepare("SELECT DISTINCT origin FROM db_sync_log WHERE collection = ?1 ORDER BY origin")?;
517    let names: Vec<String> = origins.query_map(params![collection], |r| r.get(0))?.collect::<Result<_, _>>()?;
518    let mut out = Vec::new();
519    for origin in names {
520        let after = vector.get(&origin).copied().unwrap_or(0) as i64;
521        let mut stmt = conn.prepare(&format!(
522            "SELECT {COLS}, sig, body FROM db_sync_log WHERE collection = ?1 AND origin = ?2 AND seq > ?3
523             AND (epoch = (SELECT epoch FROM db_sync_collections WHERE id = ?1)
524                  OR EXISTS (SELECT 1 FROM db_sync_epoch_cut c WHERE c.collection = ?1 AND c.origin = ?2 AND c.epoch = db_sync_log.epoch))
525             ORDER BY seq LIMIT ?4"
526        ))?;
527        let rows = stmt.query_map(params![collection, origin, after, limit as i64], record_of)?;
528        for r in rows {
529            out.push(r?);
530        }
531    }
532    // Oldest version first, so a record arrives after the ones it replaced (an origin's own versions rise with its
533    // sequence, so each origin's records still come in sequence, and a cut at `limit` keeps a prefix of each).
534    out.sort_by(|a, b| a.header.version.cmp(&b.header.version));
535    out.truncate(limit);
536    Ok(out)
537}
538
539/// What this machine wrote at an older key epoch beyond the end the membership change named for it, and that is still
540/// a record's current state: the writes the others refuse, to be written again at the current epoch.
541pub fn cut_off(conn: &Connection, collection: &str, origin: &str) -> rusqlite::Result<Vec<Record>> {
542    let mut stmt = conn.prepare(
543        "SELECT l.collection, l.record, l.wall_ms, l.counter, l.machine, l.origin, l.seq, l.epoch, l.tombstone, l.size,
544                l.base_wall, l.base_counter, l.base_machine, l.sig, l.body
545         FROM db_sync_state s JOIN db_sync_log l ON l.collection = s.collection AND l.origin = s.origin AND l.seq = s.seq
546         WHERE s.collection = ?1 AND l.origin = ?2 AND l.epoch < (SELECT epoch FROM db_sync_collections WHERE id = ?1)
547           AND l.seq > COALESCE((SELECT last_seq FROM db_sync_epoch_cut c WHERE c.collection = ?1 AND c.origin = ?2 AND c.epoch = l.epoch), l.seq)
548         ORDER BY l.seq",
549    )?;
550    let rows = stmt.query_map(params![collection, origin], record_of)?;
551    rows.collect()
552}
553
554/// The newest head accepted from a store: a generation (it rises when a store compacts or re-seals) and the vector.
555#[derive(Debug, Clone, Default, PartialEq, Eq)]
556pub struct Head {
557    pub generation: u64,
558    pub vector: Vector,
559}
560
561pub fn mark(conn: &Connection, collection: &str) -> rusqlite::Result<Head> {
562    let row: Option<(i64, String)> = conn
563        .query_row("SELECT generation, vector FROM db_sync_mark WHERE collection = ?1", params![collection], |r| Ok((r.get(0)?, r.get(1)?)))
564        .optional()?;
565    Ok(match row {
566        Some((g, v)) => Head { generation: g as u64, vector: serde_json::from_str(&v).unwrap_or_default() },
567        None => Head::default(),
568    })
569}
570
571/// Takes a head served by a store as the new high-water mark; refuses one lower than the mark (a lower generation,
572/// or the same generation with any origin behind where it was).
573pub fn accept_head(conn: &Connection, collection: &str, head: &Head) -> Result<(), SyncError> {
574    let m = mark(conn, collection)?;
575    let behind = head.generation < m.generation
576        || (head.generation == m.generation && m.vector.iter().any(|(o, s)| head.vector.get(o).copied().unwrap_or(0) < *s));
577    if behind {
578        return Err(Refused::Rollback.into());
579    }
580    conn.execute(
581        "INSERT OR REPLACE INTO db_sync_mark (collection, generation, vector) VALUES (?1, ?2, ?3)",
582        params![collection, head.generation as i64, serde_json::to_string(&head.vector).unwrap_or_else(|_| "{}".into())],
583    )?;
584    Ok(())
585}
586
587/// Records whose current state is a tombstone older than the collection's horizon: safe to forget once every
588/// member has acknowledged them.
589pub fn expired_tombstones(conn: &Connection, collection: &str, now_ms: i64) -> rusqlite::Result<Vec<String>> {
590    let kind: String = conn.query_row("SELECT kind FROM db_sync_collections WHERE id = ?1", params![collection], |r| r.get(0))?;
591    let cutoff = now_ms - horizon_days(&kind) * 86_400_000;
592    let mut stmt = conn.prepare(
593        "SELECT l.record FROM db_sync_state s JOIN db_sync_log l ON l.collection = s.collection AND l.origin = s.origin AND l.seq = s.seq
594         WHERE s.collection = ?1 AND l.tombstone = 1 AND l.wall_ms < ?2 ORDER BY l.record",
595    )?;
596    let rows = stmt.query_map(params![collection, cutoff], |r| r.get(0))?;
597    rows.collect()
598}
599
600/// A member that was last in contact before the horizon resyncs from scratch; what it changed offline goes to the
601/// conflict inbox, not silently lost.
602pub fn needs_full_resync(last_contact_ms: i64, now_ms: i64, horizon_days: i64) -> bool {
603    now_ms - last_contact_ms > horizon_days * 86_400_000
604}
605
606/// What kind of change a history line is.
607#[derive(Debug, Clone, Copy, PartialEq, Eq)]
608pub enum Change {
609    Created,
610    Updated,
611    Deleted,
612}
613
614/// A line of a collection's change history: who (which machine), when, what kind of change; never a value.
615#[derive(Debug, Clone, PartialEq, Eq)]
616pub struct HistoryEntry {
617    pub machine: String,
618    pub seq: u64,
619    pub wall_ms: i64,
620    pub record: String,
621    pub change: Change,
622}
623
624/// The collection's change history, newest first, from its log.
625pub fn history(conn: &Connection, collection: &str, limit: usize) -> rusqlite::Result<Vec<HistoryEntry>> {
626    let mut stmt = conn.prepare(
627        "SELECT origin, seq, wall_ms, counter, record, tombstone, machine FROM db_sync_log WHERE collection = ?1
628         ORDER BY wall_ms DESC, counter DESC, machine DESC LIMIT ?2",
629    )?;
630    let rows: Vec<(String, i64, i64, i64, String, i64, String)> = stmt
631        .query_map(params![collection, limit as i64], |r| {
632            Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?))
633        })?
634        .collect::<Result<_, _>>()?;
635    let mut out = Vec::new();
636    for (origin, seq, wall_ms, counter, record, tombstone, version_machine) in rows {
637        let change = if tombstone != 0 {
638            Change::Deleted
639        } else {
640            // The nearest earlier entry of the record: a change after a live one is an update; after a delete, or
641            // with nothing before it, the record is made (again).
642            let before: Option<i64> = conn
643                .query_row(
644                    "SELECT tombstone FROM db_sync_log WHERE collection = ?1 AND record = ?2
645                     AND (wall_ms < ?3 OR (wall_ms = ?3 AND (counter < ?4 OR (counter = ?4 AND machine < ?5))))
646                     ORDER BY wall_ms DESC, counter DESC, machine DESC LIMIT 1",
647                    params![collection, record, wall_ms, counter, version_machine],
648                    |r| r.get(0),
649                )
650                .optional()?;
651            if before == Some(0) {
652                Change::Updated
653            } else {
654                Change::Created
655            }
656        };
657        out.push(HistoryEntry { machine: origin, seq: seq as u64, wall_ms, record, change });
658    }
659    Ok(out)
660}