node-app-replica 7.7.43

Change-only replication for Node app backends: a per-collection ledger (epoch, version, tombstones) that answers a device's pull with nothing new, the changes, or a full copy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Property: a device that applies the node's answers in order always ends equal
//! to the app's list — across random upserts and deletes (recorded by `touch`/
//! `remove`, by `reconcile`, or left to a dirty pull), tombstone compaction past
//! the horizon (by age and by count), resets, database restores that send the
//! ledger back in time (with or without the clock moving past the rotation
//! interval, with or without an announce, with or without the app restarting),
//! node restarts, paged full copies and truncated change lists. And, after every
//! check: a device that is not paging and claims the ledger's head holds exactly
//! the app's list, whenever the app has reported every write.
//!
//! The node is modelled as section 4.3–4.4 describe it: it answers `0` from
//! memory when a device holds the head it remembers, records the head of every
//! complete reply that is not a later page of a full copy, and asks the app to
//! rotate when an announce is behind the highest version it has handed out in
//! that epoch (`PullReply::handed_out`: truncated replies and pages included). It
//! keeps those marks across its own restarts and loses only the remembered head.
//! Every answer goes through its wire encoding before the device applies it.

mod common;

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::sync::Mutex;

use common::*;
use node_app_replica::{
    AnnounceOutcome, Announcer, Collection, LedgerStore, MemoryLedger, PullRequest, Row,
    SyncAnswer, SyncEntry,
};
use proptest::prelude::*;
use serde_json::{json, Value};

const KEYS: u8 = 10;

/// The paths a run took, counted per test thread, so a test can show the
/// generator reaches every one of them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Path {
    NothingNewFromNode,
    NothingNewFromApp,
    Changes,
    ChangesCut,
    CopyFresh,
    CopyOtherEpoch,
    CopySameEpoch,
    PageContinued,
    /// A later page carried rows newer than the copy's version (`"h"`).
    PageCarriedNewer,
    PageRestarted,
    AnnounceRotated,
}

thread_local! {
    static SEEN: RefCell<BTreeMap<Path, u64>> = const { RefCell::new(BTreeMap::new()) };
}

fn saw(path: Path) {
    SEEN.with(|seen| *seen.borrow_mut().entry(path).or_insert(0) += 1);
}

#[derive(Debug, Clone, Copy)]
enum Mode {
    /// `touch` / `remove` at the write site.
    WriteSite,
    /// Whole-list `reconcile` right after the write.
    Reconcile,
    /// Only `mark_dirty`: the next pull that reaches the app reconciles. The node
    /// answers a device at the head it remembers without calling the app, so such
    /// a write reaches devices only once the app reconciles and announces (the
    /// periodic tick of section 9.3); the harness runs that tick before settling.
    Dirty,
}

#[derive(Debug, Clone)]
enum Op {
    Upsert {
        key: u8,
        value: u8,
        ord: i8,
        part: bool,
        mode: Mode,
    },
    Delete {
        key: u8,
        mode: Mode,
    },
    Announce,
    /// Seconds, or 31 days when `long`.
    Advance {
        secs: u16,
        long: bool,
    },
    Reset,
    Snapshot,
    /// Puts the database (rows and ledger) back to the last snapshot, as a
    /// restore from backup does. `advance`: the clock moves past the rotation
    /// interval first. `restart`: the app process restarts (it remembers nothing)
    /// and announces at start, before any write. `announce`: without a restart,
    /// the app announces at once.
    Restore {
        advance: bool,
        announce: bool,
        restart: bool,
    },
    /// The node restarts: it forgets the heads it remembered and keeps its
    /// per-epoch marks (persisted, as section 5.3 requires).
    NodeRestart,
    Sync {
        device: usize,
        limit: u32,
    },
}

fn mode() -> impl Strategy<Value = Mode> {
    prop_oneof![
        Just(Mode::WriteSite),
        Just(Mode::Reconcile),
        Just(Mode::Dirty)
    ]
}

fn op(devices: usize) -> impl Strategy<Value = Op> {
    prop_oneof![
        6 => (0..KEYS, 0u8..4, -2i8..3, any::<bool>(), mode())
            .prop_map(|(key, value, ord, part, mode)| Op::Upsert { key, value, ord, part, mode }),
        3 => (0..KEYS, mode()).prop_map(|(key, mode)| Op::Delete { key, mode }),
        2 => Just(Op::Announce),
        2 => (0u16..90, prop::bool::weighted(0.15)).prop_map(|(secs, long)| Op::Advance { secs, long }),
        1 => Just(Op::Reset),
        1 => Just(Op::Snapshot),
        2 => (any::<bool>(), any::<bool>(), any::<bool>())
            .prop_map(|(advance, announce, restart)| Op::Restore { advance, announce, restart }),
        1 => Just(Op::NodeRestart),
        6 => (0..devices, 1u32..5).prop_map(|(device, limit)| Op::Sync { device, limit }),
    ]
}

fn make_row(key: u8, value: u8, ord: i8, part: bool) -> Row {
    let row = Row::new(
        format!("k{key}"),
        json!({ "v": value, "tag": [value, "x"] }),
    )
    .with_ord(i64::from(ord));
    if part {
        row.with_part(format!("g{}", value % 2))
    } else {
        row
    }
}

/// A store whose whole database (the app's rows live beside it in the harness)
/// can be saved and put back.
trait Restorable: LedgerStore {
    type Saved;
    fn save(&self) -> Self::Saved;
    fn restore(&self, saved: &Self::Saved);
}

struct MemoryStore(Mutex<MemoryLedger>);

impl LedgerStore for MemoryStore {
    fn ensure(&self, prefix: &str) -> Result<(), node_app_replica::ReplicaError> {
        self.0.lock().unwrap().ensure(prefix)
    }
    fn write(
        &self,
        prefix: &str,
        work: &mut dyn FnMut(
            &mut dyn node_app_replica::LedgerTx,
        ) -> Result<(), node_app_replica::ReplicaError>,
    ) -> Result<(), node_app_replica::ReplicaError> {
        // Clone the ledger out so the lock is not held across `work`.
        let ledger = self.0.lock().unwrap().clone();
        ledger.write(prefix, work)?;
        *self.0.lock().unwrap() = ledger;
        Ok(())
    }
}

impl Restorable for MemoryStore {
    type Saved = MemoryLedger;
    fn save(&self) -> MemoryLedger {
        self.0.lock().unwrap().clone()
    }
    fn restore(&self, saved: &MemoryLedger) {
        *self.0.lock().unwrap() = saved.clone();
    }
}

struct SqliteStore(rusqlite::Connection);

impl LedgerStore for SqliteStore {
    fn ensure(&self, prefix: &str) -> Result<(), node_app_replica::ReplicaError> {
        self.0.ensure(prefix)
    }
    fn write(
        &self,
        prefix: &str,
        work: &mut dyn FnMut(
            &mut dyn node_app_replica::LedgerTx,
        ) -> Result<(), node_app_replica::ReplicaError>,
    ) -> Result<(), node_app_replica::ReplicaError> {
        self.0.write(prefix, work)
    }
}

impl Restorable for SqliteStore {
    type Saved = ();
    fn save(&self) {
        self.0
            .execute_batch(
                "DROP TABLE IF EXISTS saved_c; DROP TABLE IF EXISTS saved_r;
                 CREATE TABLE saved_c AS SELECT * FROM friends_replica_collections;
                 CREATE TABLE saved_r AS SELECT * FROM friends_replica_rows;",
            )
            .unwrap();
    }
    fn restore(&self, _: &()) {
        self.0
            .execute_batch(
                "DELETE FROM friends_replica_collections;
                 INSERT INTO friends_replica_collections SELECT * FROM saved_c;
                 DELETE FROM friends_replica_rows;
                 INSERT INTO friends_replica_rows SELECT * FROM saved_r;",
            )
            .unwrap();
    }
}

/// The node: the remembered head (for `0` answers), and the highest version it
/// has handed out in each epoch it has seen (for the rotate decision of an
/// announce). Per epoch, not only the current one: a database restored twice to
/// the same backup comes back to an epoch the node has since moved past, and
/// only that epoch's mark shows the app is behind what devices hold.
#[derive(Default)]
struct Node {
    head: Mutex<Option<(String, u64)>>,
    handed_out: Mutex<BTreeMap<String, u64>>,
}

impl Node {
    fn note_handed_out(&self, epoch: &str, version: u64) {
        let mut marks = self.handed_out.lock().unwrap();
        let mark = marks.entry(epoch.to_string()).or_insert(0);
        *mark = (*mark).max(version);
    }
}

impl Announcer for Node {
    fn invoke(&self, capability: &str, payload: Value) -> Result<Value, String> {
        assert_eq!(capability, "core.replica.announce");
        let announce: node_app_replica::Announce = serde_json::from_value(payload).unwrap();
        let mark = self
            .handed_out
            .lock()
            .unwrap()
            .get(&announce.epoch)
            .copied();
        if mark.is_some_and(|mark| mark > announce.version) {
            return Ok(json!({"rotate": true}));
        }
        *self.head.lock().unwrap() = Some((announce.epoch.clone(), announce.version));
        self.note_handed_out(&announce.epoch, announce.version);
        Ok(json!({"ok": true}))
    }
}

#[derive(Debug, Default, Clone)]
struct Device {
    epoch: String,
    version: u64,
    rows: BTreeMap<String, Row>,
    /// A full copy in progress: page one's epoch and head, rows so far, last key.
    paging: Option<(String, u64, BTreeMap<String, Row>, String)>,
}

struct Harness<'a, S: Restorable> {
    store: &'a S,
    collection: Collection,
    keep: u64,
    env: &'static TestEnv,
    data: AppData,
    /// A `Dirty` write happened that no reconcile by the app has covered yet.
    unreported: bool,
    saved: Option<(AppData, bool, S::Saved)>,
    node: Node,
    devices: Vec<Device>,
}

impl<S: Restorable> Harness<'_, S> {
    fn write(&mut self, key: String, row: Option<Row>, mode: Mode) {
        match &row {
            Some(row) => self.data.put(row.clone()),
            None => {
                self.data.rows.remove(&key);
            }
        }
        match (mode, row) {
            (Mode::WriteSite, Some(row)) => {
                self.collection.touch(self.store, &row).unwrap();
            }
            (Mode::WriteSite, None) => {
                self.collection.remove(self.store, &key).unwrap();
            }
            (Mode::Reconcile, _) => {
                self.collection
                    .reconcile(self.store, &self.data.list())
                    .unwrap();
                self.unreported = false;
            }
            (Mode::Dirty, _) => {
                self.collection.mark_dirty(self.store).unwrap();
                self.unreported = true;
            }
        }
    }

    /// One `core.replica.sync` for one device, as the node answers it; returns
    /// the answer after its wire round trip.
    fn sync(&mut self, index: usize, limit: u32) -> SyncAnswer {
        let device = &self.devices[index];
        let entry = match &device.paging {
            Some((epoch, version, _, last)) => SyncEntry {
                capability: self.collection.name().to_string(),
                schema: 1,
                epoch: epoch.clone(),
                version: *version,
                resume: Some(last.clone()),
            },
            None => SyncEntry {
                capability: self.collection.name().to_string(),
                schema: 1,
                epoch: device.epoch.clone(),
                version: device.version,
                resume: None,
            },
        };
        let wire_entry: SyncEntry =
            serde_json::from_str(&serde_json::to_string(&entry).unwrap()).unwrap();
        let remembered = self.node.head.lock().unwrap().clone();
        let answer = if wire_entry.resume.is_none()
            && remembered == Some((wire_entry.epoch.clone(), wire_entry.version))
        {
            saw(Path::NothingNewFromNode);
            SyncAnswer::NothingNew
        } else {
            let request: PullRequest = wire_entry.pull_request(limit);
            let data = self.data.clone();
            let reply = self
                .collection
                .answer(self.store, &request, data.loader())
                .unwrap()
                .reply;
            self.node.note_handed_out(reply.epoch(), reply.handed_out());
            if wire_entry.resume.is_some()
                && matches!(
                    reply,
                    node_app_replica::PullReply::FullCopy { head: Some(_), .. }
                )
            {
                saw(Path::PageCarriedNewer);
            }
            if !reply.is_truncated() && wire_entry.resume.is_none() {
                *self.node.head.lock().unwrap() =
                    Some((reply.epoch().to_string(), reply.version()));
            }
            if matches!(reply, node_app_replica::PullReply::NothingNew { .. }) {
                saw(Path::NothingNewFromApp);
            }
            SyncAnswer::from(reply)
        };
        let wire = serde_json::to_string(&answer).unwrap();
        let answer: SyncAnswer = serde_json::from_str(&wire).unwrap();
        self.apply(index, &entry, answer.clone());
        // A device's (epoch, version) names exactly the list it holds once it is
        // at the head: with every write reported, at the head means equal.
        let device = &self.devices[index];
        if !self.unreported && device.paging.is_none() {
            let head = self.collection.head(self.store).unwrap();
            if (head.epoch.as_str(), head.version) == (device.epoch.as_str(), device.version) {
                assert_eq!(
                    device.rows, self.data.rows,
                    "device {index} claims the head ({}, {}) but holds other rows",
                    head.epoch, head.version
                );
            }
        }
        answer
    }

    /// A new app process over the same database: nothing remembered in memory.
    fn fresh_collection(env: &'static TestEnv, keep: u64) -> Collection {
        Collection::new("friends.people.pull", "friends_", &[1])
            .with_environment(env)
            .with_tombstone_horizon(30 * DAY, keep)
    }

    fn apply(&mut self, index: usize, sent: &SyncEntry, answer: SyncAnswer) {
        let device = &mut self.devices[index];
        match answer {
            SyncAnswer::NothingNew => {}
            SyncAnswer::Changes {
                version,
                upserts,
                deletes,
                more,
            } => {
                saw(if more {
                    Path::ChangesCut
                } else {
                    Path::Changes
                });
                assert!(sent.resume.is_none(), "changes answered a full-copy page");
                assert!(
                    version > device.version,
                    "a changes reply went from {} to {version}",
                    device.version
                );
                for row in upserts {
                    device.rows.insert(row.key.clone(), row);
                }
                for key in deletes {
                    device.rows.remove(&key);
                }
                device.version = version;
            }
            SyncAnswer::FullCopy {
                epoch,
                version,
                rows,
                next,
            } => {
                let mut buffer = match device.paging.take() {
                    Some((e, v, buffer, _))
                        if sent.resume.is_some() && e == epoch && v == version =>
                    {
                        saw(Path::PageContinued);
                        buffer
                    }
                    // Page one, or the copy restarted.
                    _ => {
                        saw(if sent.resume.is_some() {
                            Path::PageRestarted
                        } else if sent.epoch.is_empty() {
                            Path::CopyFresh
                        } else if sent.epoch != epoch {
                            Path::CopyOtherEpoch
                        } else {
                            Path::CopySameEpoch
                        });
                        BTreeMap::new()
                    }
                };
                let mut previous = buffer.keys().next_back().cloned();
                for row in rows {
                    assert!(
                        previous.as_deref().map_or(true, |p| p < row.key.as_str()),
                        "full copy out of key order"
                    );
                    previous = Some(row.key.clone());
                    buffer.insert(row.key.clone(), row);
                }
                match next {
                    Some(last) => device.paging = Some((epoch, version, buffer, last)),
                    None => {
                        device.rows = buffer;
                        device.epoch = epoch;
                        device.version = version;
                    }
                }
            }
            SyncAnswer::Error(code) => panic!("unexpected error answer {code:?}"),
        }
    }

    fn announce(&mut self) {
        match self.collection.announce(self.store, &self.node) {
            AnnounceOutcome::Accepted(_) => {}
            AnnounceOutcome::Rotated(_) => saw(Path::AnnounceRotated),
            // A node that keeps its marks never asks a fresh epoch to rotate.
            AnnounceOutcome::RotationDeferred(_) => panic!("rotation deferred"),
            AnnounceOutcome::Failed { error, .. } => panic!("announce failed: {error}"),
        }
    }

    fn run(&mut self, op: &Op) {
        match *op {
            Op::Upsert {
                key,
                value,
                ord,
                part,
                mode,
            } => {
                let row = make_row(key, value, ord, part);
                self.write(row.key.clone(), Some(row), mode);
            }
            Op::Delete { key, mode } => self.write(format!("k{key}"), None, mode),
            Op::Announce => self.announce(),
            Op::Advance { secs, long } => self.env.advance(if long {
                31 * DAY
            } else {
                u64::from(secs) * 1_000
            }),
            Op::Reset => {
                self.collection.reset(self.store).unwrap();
            }
            Op::Snapshot => {
                self.saved = Some((self.data.clone(), self.unreported, self.store.save()))
            }
            Op::Restore {
                advance,
                announce,
                restart,
            } => {
                if let Some((data, unreported, saved)) = &self.saved {
                    self.data = data.clone();
                    self.unreported = *unreported;
                    self.store.restore(saved);
                    if advance {
                        self.env.advance(61_000);
                    }
                    if restart {
                        self.collection = Self::fresh_collection(self.env, self.keep);
                    }
                    if restart || announce {
                        self.announce();
                    }
                }
            }
            Op::NodeRestart => {
                *self.node.head.lock().unwrap() = None;
            }
            Op::Sync { device, limit } => {
                self.sync(device, limit);
            }
        }
    }

    /// The app's periodic tick (when a `Dirty` write is outstanding) and one
    /// announce, then every device asks until it is told nothing is new.
    fn settle_and_check(&mut self) {
        if self.unreported {
            self.collection
                .reconcile(self.store, &self.data.list())
                .unwrap();
            self.unreported = false;
        }
        self.announce();
        for index in 0..self.devices.len() {
            let mut rounds = 0;
            loop {
                rounds += 1;
                assert!(rounds < 200, "device {index} never settled");
                let answer = self.sync(index, 3);
                if answer == SyncAnswer::NothingNew && self.devices[index].paging.is_none() {
                    break;
                }
            }
            assert_eq!(
                self.devices[index].rows, self.data.rows,
                "device {index} differs from the app's list"
            );
            let head = self.collection.head(self.store).unwrap();
            assert_eq!(
                (
                    self.devices[index].epoch.as_str(),
                    self.devices[index].version
                ),
                (head.epoch.as_str(), head.version)
            );
        }
    }
}

fn check<S: Restorable>(store: &S, ops: &[Op], devices: usize, keep: u64) {
    let env = TestEnv::leak(T0, &[]);
    let collection = Harness::<S>::fresh_collection(env, keep);
    collection.ensure(store).unwrap();
    let mut harness = Harness {
        store,
        collection,
        keep,
        env,
        data: AppData::default(),
        unreported: false,
        saved: None,
        node: Node::default(),
        devices: vec![Device::default(); devices],
    };
    for op in ops {
        harness.run(op);
    }
    harness.settle_and_check();
    // And again after more changes, from wherever each device stands.
    harness.run(&Op::Upsert {
        key: 0,
        value: 9,
        ord: 0,
        part: false,
        mode: Mode::WriteSite,
    });
    harness.run(&Op::Delete {
        key: 1,
        mode: Mode::Reconcile,
    });
    harness.settle_and_check();
}

proptest! {
    #![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]

    #[test]
    fn devices_converge_on_the_memory_store(
        ops in prop::collection::vec(op(3), 1..80),
        keep in 1u64..6,
    ) {
        check(&MemoryStore(Mutex::new(MemoryLedger::new())), &ops, 3, keep);
    }
}

proptest! {
    #![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]

    #[test]
    fn devices_converge_on_the_sqlite_store(
        ops in prop::collection::vec(op(2), 1..60),
        keep in 1u64..6,
    ) {
        check(&SqliteStore(sqlite()), &ops, 2, keep);
    }
}

/// The generator is only as good as the paths it reaches: every kind of answer,
/// both outcomes of a resumed page, and a rotation asked for by the node.
#[test]
fn the_generator_reaches_every_path() {
    use proptest::test_runner::{Config, TestRunner};
    SEEN.with(|seen| seen.borrow_mut().clear());
    let mut runner = TestRunner::new(Config {
        cases: 400,
        ..Config::default()
    });
    runner
        .run(
            &(prop::collection::vec(op(3), 1..80), 1u64..6),
            |(ops, keep)| {
                check(&MemoryStore(Mutex::new(MemoryLedger::new())), &ops, 3, keep);
                Ok(())
            },
        )
        .unwrap();
    let seen = SEEN.with(|seen| seen.borrow().clone());
    for path in [
        Path::NothingNewFromNode,
        Path::NothingNewFromApp,
        Path::Changes,
        Path::ChangesCut,
        Path::CopyFresh,
        Path::CopyOtherEpoch,
        Path::CopySameEpoch,
        Path::PageContinued,
        Path::PageCarriedNewer,
        Path::PageRestarted,
        Path::AnnounceRotated,
    ] {
        assert!(
            seen.get(&path).copied().unwrap_or(0) > 0,
            "never reached {path:?}: {seen:?}"
        );
    }
    eprintln!("paths reached in 400 cases: {seen:?}");
}