aboutsummaryrefslogtreecommitdiffstats
path: root/src/remake/delta.rs
blob: c3688cbff84e6c47dfa49504207971664e313ee9 (plain)
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
//! Replaying a node's changes after the base into the new epoch.
//!
//! Changes from the old epoch can't be applied to the new document (their history is
//! unrelated), so they are replayed as state: for every path that changed between two
//! sets of heads, the new document gets whatever the old document's merged view holds
//! there now (or a delete if nothing). Replayed values are fresh operations, so they win
//! over what the snapshot holds at the same path.
//!
//! Where a path goes is the remake kind's decision ([`Translator`]): the same path
//! (compaction), another path, nowhere (dropped), or quarantine. Protocol data under
//! `_continuum` always keeps its path.
//!
//! Granularity:
//! * Map entries are replayed per key, so changes to sibling keys made on different
//!   nodes don't overwrite each other.
//! * Lists and text are replayed whole: concurrent edits of the same list or text on two
//!   nodes around a remake resolve as last-writer-wins.
//! * Edits inside a map that lost a merge conflict produce no patch in Automerge and are
//!   not replayed. Such maps only exist briefly between concurrent creations.
//!
//! The protocol's own metadata (`_continuum/remakes`, `_continuum/epochs`) is never
//! replayed: the snapshot owns it.
//!
//! Replayed changes are the replaying node's, and name the user each write was made
//! for (`replica::Writer`), as rules by path judge them (`access::rules`): they are
//! grouped by user as by time. Another member's entry written without a user (its
//! alive stamp, its links) is left to that member to replay: only it may write it.
//!
//! Last writer wins, by the writers' clocks ([`replay_newest`]): a replayed value is a
//! fresh operation, which by Automerge's order beats everything the document it goes
//! into has, newer writes included. So a path is replayed only if no change in that
//! document touched it (or a path above or below it) later than the write being
//! replayed, as the changes' timestamps say; and the replayed changes carry the times
//! of the writes they replay, not of the replay, so later replays judge by those.
//!
//! Under a strict policy, a value its user signed (`access::envelope`) is replayed as
//! the chain that leads to it ([`signed_places`], [`chain`]): every envelope from the
//! one the new document holds there to the one the old document reads, each in a
//! change of its own, by its signer, at its own time, so that each replaces the one
//! before it as every node checks; and only where the new document holds a lower `seq`
//! there, as values signed by their users are read by `seq`, not by clocks. The links of
//! all places go in the order their changes were made ([`between`]), and the other
//! writes with them, clocks deciding only between changes neither of which saw the
//! other. A place is found from the
//! changes' operations as well as from the diff, which says nothing of a value that
//! changed beside Automerge's own choice.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

use crate::document::{ActorId, ChangeHash, Document, ReadDoc, Transactable};
use serde::{Deserialize, Serialize};
use tracing::{info, warn};

use super::kind::{Translation, Translator};
use crate::access::envelope;
use crate::document::at::At;
use crate::document::meta::{self, EPOCHS, REMAKES, VOTES};
use crate::document::store::{self, InLists, StoreError};

#[derive(Debug, Default, Clone)]
pub(crate) struct ReplayStats {
    pub(crate) replayed: usize,
    pub(crate) failed: usize,
    /// Paths the remake declared obsolete.
    pub(crate) dropped: usize,
    /// Paths not replayed because a newer write touched them ([`replay_newest`]), and
    /// left out (`Superseded::Drop`; with `Superseded::Quarantine`, they are among
    /// `quarantined`).
    pub(crate) superseded: usize,
    /// Paths the remake had no place for, with the reason.
    pub(crate) quarantined: Vec<(Vec<String>, String)>,
}

impl ReplayStats {
    /// Adds another replay's numbers (e.g. late changes replayed under the lock).
    pub(crate) fn absorb(&mut self, other: ReplayStats) {
        self.replayed += other.replayed;
        self.failed += other.failed;
        self.dropped += other.dropped;
        self.superseded += other.superseded;
        self.quarantined.extend(other.quarantined);
    }
}

/// What a replay does with a write that a newer one superseded (`--superseded-writes`):
/// leave it out, logged (last writer wins), or put it in the quarantine, where an
/// operator can still replay it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) enum Superseded {
    #[default]
    Drop,
    Quarantine,
}

/// Replays into `dst` what changed in `src` between `before` and `after` (both in
/// `src`), last writer wins: a path whose newest write there (by its change's
/// timestamp) is older than a change in `dst` touching it, or a path above or below it,
/// stays as `dst` has it (`superseded` says what becomes of the write). Ties go to the
/// replay. The replayed paths are committed by `node`, grouped by the time of the writes
/// they replay (under a strict policy, in the order their changes were made, with the
/// links) and the user each was made for, each change stamped with that time and naming
/// that user. Under a policy, each is judged as every node will judge it (in
/// `epoch`): one they would refuse is taken back, its paths quarantined.
#[allow(clippy::too_many_arguments)]
pub(crate) fn replay_newest(
    src: &Document,
    before: &[ChangeHash],
    after: &[ChangeHash],
    dst: &mut Document,
    epoch: crate::document::replica::Epoch,
    node: &str,
    translator: &Translator,
    superseded: Superseded,
) -> ReplayStats {
    let mut stats = ReplayStats::default();
    if before == after {
        return stats;
    }
    let changes = between(src, before, after);
    // One for each of `changes`, in their order.
    let written = touched(src, &changes);
    // Under a strict policy, the other writes go with the links by history too: one may
    // build on what a link grants (a capability, a key).
    let strict = At::new(src, after).is_some_and(|now| crate::access::policy::of(&now).strict());
    // Values their users signed, under a strict policy: replayed as chains, below.
    let (signed, paths) = signed_places(
        src,
        before,
        after,
        &written,
        changed_paths(src, before, after),
    );
    // Split where several users wrote below a path: each part replayed for its own.
    let paths = by_user(src, dst, &written, paths);
    let ours: Vec<(i64, Option<String>)> = paths
        .iter()
        .map(|path| {
            let at = newest(&written, path).map_or(0, |(at, _)| at);
            // Under a strict policy, the user of the change it goes as: the last by
            // history that wrote it (`last_written`).
            let user = if strict {
                last_written(src, &changes, &written, path).and_then(|made| written[made].1.clone())
            } else {
                writer(&written, path)
            };
            (at, user)
        })
        .collect();
    // Only changes newer than the oldest write replayed can supersede one; the
    // snapshot (time 0) never does.
    let oldest = ours.iter().map(|(at, _)| *at).min().unwrap_or(0);
    let newer: Vec<ChangeHash> = dst
        .get_changes(&[])
        .iter()
        .filter(|change| change.timestamp() > oldest)
        .map(|change| change.hash())
        .collect();
    let theirs = touched(dst, &newer);

    // By when they go (under a strict policy, the place of the last change that wrote
    // them among `changes`; elsewhere, its time) and their user: their time, and paths.
    let mut by_time: Groups = BTreeMap::new();
    // The links of the chains to signed values, each a change of its own: in the order
    // their changes were made, each after those it builds on, whatever the clocks say
    // (one may add the key the next is signed with).
    let mut ordered: BTreeMap<(usize, usize), Link> = BTreeMap::new();
    for place in signed {
        match chain(src, after, &changes, &place, dst) {
            Chain::Links(chain) => {
                for (made, when, envelope, user) in chain {
                    ordered.insert(
                        (made, ordered.len()),
                        (made as i64, when, place.clone(), envelope, user),
                    );
                }
            }
            Chain::Held => {
                stats.superseded += 1;
                if superseded == Superseded::Quarantine {
                    stats.quarantined.push((
                        place,
                        "the new epoch holds as high a `seq` there".to_owned(),
                    ));
                }
            }
            Chain::Broken(why) => stats.quarantined.push((place, why)),
        }
    }
    let mut at = i64::MIN;
    let links: Vec<Link> = ordered
        .into_values()
        .map(|(made, when, place, envelope, user)| {
            at = at.max(when);
            let goes = if strict { made } else { at };
            (goes, at, place, envelope, user)
        })
        .collect();
    for (path, (at, user)) in paths.into_iter().zip(ours) {
        if user.is_none() && others_entry(&path, node) {
            continue;
        }
        match newest(&theirs, &path) {
            Some((newer, _)) if newer > at => {
                stats.superseded += 1;
                if superseded == Superseded::Quarantine {
                    stats.quarantined.push((
                        path,
                        format!("a newer write (at {newer}, this one at {at}) superseded it"),
                    ));
                }
            }
            _ => {
                let goes = if strict {
                    last_written(src, &changes, &written, &path).map_or(0, |made| made as i64)
                } else {
                    at
                };
                let group = by_time.entry((goes, user)).or_insert((at, Vec::new()));
                group.0 = group.0.max(at);
                group.1.push(path);
            }
        }
    }
    crate::document::replica::authored(dst, node);
    let mut refused: HashSet<Vec<String>> = HashSet::new();
    let mut links = links.into_iter().peekable();
    for ((goes, user), (at, paths)) in by_time {
        // Of one change, its links after its other writes: both were judged without the
        // other, and a link can only take away there what the others relied on.
        while let Some((link_goes, ..)) = links.peek()
            && *link_goes < goes
        {
            let (_, when, place, envelope, signer) = links.next().expect("peeked");
            write_link(
                dst,
                epoch,
                node,
                when,
                &place,
                envelope,
                &signer,
                &mut refused,
                &mut stats,
            );
        }
        let before = dst.get_heads();
        let mut transaction = dst.transaction();
        let group = replay_paths(src, &mut transaction, &paths, translator);
        let writer = crate::document::replica::Writer {
            node,
            user: user.as_deref(),
        };
        let mut options = automerge::transaction::CommitOptions::default().with_time(at);
        if let Some(message) = writer.message() {
            options = options.with_message(message);
        }
        transaction.commit_with(options);
        // Judged as every node will judge it (`access::rules`): one they would refuse
        // goes to the quarantine instead, or everything this node writes after it
        // would be refused too.
        match judged(dst, epoch, &before) {
            Ok(()) => stats.absorb(group),
            Err(why) => {
                let actor = dst.get_actor().clone();
                match dst.fork_at(&before) {
                    // The author too: a fork has none, and the next group may be the
                    // actor's first change, whose footer names it.
                    Ok(kept) => {
                        *dst = kept.with_actor(actor);
                        crate::document::replica::authored(dst, node);
                    }
                    Err(error) => {
                        warn!(error = %error, "Could not take back a replay every node would refuse");
                        stats.absorb(group);
                        continue;
                    }
                }
                let reason = format!("every node would refuse it: {why}");
                stats
                    .quarantined
                    .extend(paths.into_iter().map(|path| (path, reason.clone())));
            }
        }
    }
    for (_, when, place, envelope, signer) in links {
        write_link(
            dst,
            epoch,
            node,
            when,
            &place,
            envelope,
            &signer,
            &mut refused,
            &mut stats,
        );
    }
    if stats.superseded > 0 {
        info!(
            superseded = stats.superseded,
            quarantined = superseded == Superseded::Quarantine,
            "Writes not replayed: newer ones touched their paths"
        );
    }
    if superseded == Superseded::Quarantine {
        // Counted as quarantined, not as left out.
        stats.superseded = 0;
    }
    stats
}

/// Writes `envelope` at `place` in `dst`, a change of its own by `node` for `signer` at
/// `at`, judged as every node will judge it: one they would refuse is taken back, and
/// its place quarantined, and nothing more of that place's chain written.
#[allow(clippy::too_many_arguments)]
fn write_link(
    dst: &mut Document,
    epoch: crate::document::replica::Epoch,
    node: &str,
    at: i64,
    place: &[String],
    envelope: String,
    signer: &str,
    refused: &mut HashSet<Vec<String>>,
    stats: &mut ReplayStats,
) {
    if refused.contains(place) {
        return;
    }
    let before = dst.get_heads();
    let mut transaction = dst.transaction();
    if let Err(error) = store::write_path(
        &mut transaction,
        place,
        &serde_json::Value::String(envelope),
    ) {
        transaction.rollback();
        log_failure(place, &error);
        stats.failed += 1;
        refused.insert(place.to_vec());
        return;
    }
    let writer = crate::document::replica::Writer {
        node,
        user: Some(signer),
    };
    let mut options = automerge::transaction::CommitOptions::default().with_time(at);
    if let Some(message) = writer.message() {
        options = options.with_message(message);
    }
    transaction.commit_with(options);
    match judged(dst, epoch, &before) {
        Ok(()) => stats.replayed += 1,
        Err(why) => {
            let actor = dst.get_actor().clone();
            match dst.fork_at(&before) {
                Ok(kept) => {
                    *dst = kept.with_actor(actor);
                    crate::document::replica::authored(dst, node);
                }
                Err(error) => {
                    warn!(error = %error, "Could not take back a replay every node would refuse");
                    stats.replayed += 1;
                    return;
                }
            }
            refused.insert(place.to_vec());
            stats
                .quarantined
                .push((place.to_vec(), format!("every node would refuse it: {why}")));
        }
    }
}

/// Under a strict policy in `src` at `after` (`access::policy`), the places of values
/// their users sign (`access::envelope::signed_paths`) whose value, as a read shows it,
/// changed between `before` and `after`: found among `paths` (from the diff) and among
/// the paths the changes wrote (`written`), a path above such places split into its
/// keys. And the rest of `paths`. Without a strict policy, none, and `paths` as they are.
fn signed_places(
    src: &Document,
    before: &[ChangeHash],
    after: &[ChangeHash],
    written: &[Touched],
    paths: Vec<Vec<String>>,
) -> (Vec<Vec<String>>, Vec<Vec<String>>) {
    let (Some(then), Some(now)) = (At::new(src, before), At::new(src, after)) else {
        return (Vec::new(), paths);
    };
    if !crate::access::policy::of(&now).strict() {
        return (Vec::new(), paths);
    }
    let signed = envelope::signed_paths(&now);
    let mut places = BTreeSet::new();
    let mut rest = Vec::new();
    let mut todo: Vec<Vec<String>> = paths;
    todo.extend(
        written
            .iter()
            .flat_map(|(_, _, paths)| paths.iter())
            .filter(|path| envelope::is_signed(&signed, path))
            .cloned(),
    );
    while let Some(path) = todo.pop() {
        if envelope::is_signed(&signed, &path) {
            places.insert(path);
        } else if envelope::above_signed(&signed, &path) {
            let mut keys = store::keys_at(&now, &path)
                .ok()
                .flatten()
                .unwrap_or_default();
            keys.extend(
                store::keys_at(&then, &path)
                    .ok()
                    .flatten()
                    .unwrap_or_default(),
            );
            keys.sort();
            keys.dedup();
            for key in &keys {
                let mut child = path.clone();
                child.push(key.clone());
                todo.push(child);
            }
            if keys.is_empty() {
                rest.push(path);
            }
        } else {
            rest.push(path);
        }
    }
    rest.sort();
    rest.dedup();
    let places = places
        .into_iter()
        .filter(|place| store::read_path(&then, place).ok() != store::read_path(&now, place).ok())
        .collect();
    (places, rest)
}

/// A link to write: when it goes (as the other writes go), its time, its place, the
/// envelope and its signer.
type Link = (i64, i64, Vec<String>, String, String);

/// The other writes, by when they go and their user: their time, and their paths.
type Groups = BTreeMap<(i64, Option<String>), (i64, Vec<Vec<String>>)>;

/// What replaying a signed place takes.
enum Chain {
    /// The envelopes to write, in order, each with where its change is among those
    /// replayed (`between`), its time and its signer.
    Links(Vec<(usize, i64, String, String)>),
    /// The new document holds as high a `seq` there already.
    Held,
    /// No chain leads there from what the new document holds: why.
    Broken(String),
}

/// The chain of envelopes `src` holds at `place` (written by `changes`) that leads from
/// what `dst` holds there to what `src` reads there at `after`, where the replay ends,
/// following `prev`.
fn chain(
    src: &Document,
    after: &[ChangeHash],
    changes: &[ChangeHash],
    place: &[String],
    dst: &Document,
) -> Chain {
    let raw = |doc: &dyn Fn() -> Option<serde_json::Value>| match doc() {
        Some(serde_json::Value::String(text)) => Some(text),
        _ => None,
    };
    let Some(end) = At::new(src, after) else {
        return Chain::Broken("the replay's end isn't in the old document".to_owned());
    };
    let Some(target) = raw(&|| store::read_path(&end, place).ok().flatten()) else {
        return Chain::Broken("no value its user signed is there to replay".to_owned());
    };
    let Ok(payload) = envelope::read(&target) else {
        return Chain::Broken("what is there isn't a value its user signed".to_owned());
    };
    let held = raw(&|| store::read_path(dst, place).ok().flatten())
        .filter(|text| envelope::read(text).is_ok());
    if let Some(seq) = held.as_deref().and_then(envelope::seq)
        && seq >= payload.seq
    {
        return Chain::Held;
    }
    // Every envelope the changes left at the place, by its digest, with where its first
    // change is among them and its time.
    let mut known: HashMap<String, (usize, i64, String)> = HashMap::new();
    for (made, hash) in changes.iter().enumerate() {
        let wrote = store::changed_by(src, hash, InLists::Whole)
            .is_some_and(|paths| paths.iter().any(|path| path == place));
        let Some(at) = wrote
            .then(|| At::new(src, std::slice::from_ref(hash)))
            .flatten()
        else {
            continue;
        };
        let time = src
            .get_change_by_hash(hash)
            .map_or(0, |change| change.timestamp());
        for value in store::read_candidates(&at, place).unwrap_or_default() {
            if let serde_json::Value::String(text) = value
                && envelope::read(&text).is_ok()
            {
                let digest = envelope::digest(Some(&text));
                known.entry(digest).or_insert((made, time, text));
            }
        }
    }
    let from = envelope::digest(held.as_deref());
    let mut links = Vec::new();
    let mut current = target;
    loop {
        let Ok(payload) = envelope::read(&current) else {
            return Chain::Broken("a link of its chain isn't a value its user signed".to_owned());
        };
        let (made, time) = known
            .get(&envelope::digest(Some(&current)))
            .map_or((changes.len(), 0), |(made, time, _)| (*made, *time));
        let prev = payload.prev.clone();
        links.push((made, time, current, payload.user));
        if prev == from {
            break;
        }
        match known.get(&prev) {
            Some((_, _, before)) if links.len() <= known.len() => current = before.clone(),
            _ => {
                return Chain::Broken(
                    "the new epoch holds another value there, not one it replaced".to_owned(),
                );
            }
        }
    }
    links.reverse();
    // Each after the one it replaces, as written.
    let mut made = 0;
    for link in &mut links {
        made = made.max(link.0);
        link.0 = made;
    }
    Chain::Links(links)
}

/// The change just committed to `doc` (the one head after `before`), judged under a
/// policy as every node will judge it on receipt; why it is refused, if it is.
fn judged(
    doc: &Document,
    epoch: crate::document::replica::Epoch,
    before: &[ChangeHash],
) -> Result<(), String> {
    // By the policy it was written under, as receivers judge it.
    let enforced = crate::document::at::At::new(doc, before)
        .is_some_and(|at| crate::access::policy::of(&at).enforced());
    if !enforced {
        return Ok(());
    }
    match doc.get_heads()[..] {
        [hash] if doc.get_heads() != before => {
            crate::access::rules::judge_held(doc, epoch, &hash).unwrap_or(Ok(()))
        }
        _ => Ok(()),
    }
}

/// The changes of `doc` after `before` up to `after`: those `after` builds on that
/// `before` doesn't, each after those it builds on; of changes neither builds on, the
/// earlier by its clock first, then the lower hash.
fn between(doc: &Document, before: &[ChangeHash], after: &[ChangeHash]) -> Vec<ChangeHash> {
    let all: HashMap<ChangeHash, (i64, Vec<ChangeHash>)> = doc
        .get_changes(before)
        .iter()
        .map(|change| (change.hash(), (change.timestamp(), change.deps().to_vec())))
        .collect();
    let mut found = HashSet::new();
    let mut todo: Vec<ChangeHash> = after.to_vec();
    while let Some(hash) = todo.pop() {
        if let Some((_, parents)) = all.get(&hash)
            && found.insert(hash)
        {
            todo.extend(parents.iter().copied());
        }
    }
    let mut waiting: HashMap<ChangeHash, usize> = HashMap::new();
    let mut builders: HashMap<ChangeHash, Vec<ChangeHash>> = HashMap::new();
    let mut ready: BTreeSet<(i64, ChangeHash)> = BTreeSet::new();
    for hash in &found {
        let (time, parents) = &all[hash];
        let inside: Vec<&ChangeHash> = parents.iter().filter(|p| found.contains(*p)).collect();
        for parent in &inside {
            builders.entry(**parent).or_default().push(*hash);
        }
        if inside.is_empty() {
            ready.insert((*time, *hash));
        } else {
            waiting.insert(*hash, inside.len());
        }
    }
    let mut ordered = Vec::with_capacity(found.len());
    while let Some((_, hash)) = ready.pop_first() {
        ordered.push(hash);
        for builder in builders.remove(&hash).unwrap_or_default() {
            let left = waiting.get_mut(&builder).expect("waits for its parents");
            *left -= 1;
            if *left == 0 {
                waiting.remove(&builder);
                ready.insert((all[&builder].0, builder));
            }
        }
    }
    ordered
}

/// A change's time, the user it names (`replica::user_of`), and the store paths it
/// touched.
type Touched = (i64, Option<String>, Vec<Vec<String>>);

/// For each of `changes` (in `doc`), in their order, its time, its user and the store
/// paths it touched, from its operations (`store::changed_by`: a diff per change would
/// cost what the maps it touched hold, `remake::bench`); none for one it can't read.
fn touched(doc: &Document, changes: &[ChangeHash]) -> Vec<Touched> {
    changes
        .iter()
        .map(|hash| {
            let Some(change) = doc.get_change_by_hash(hash) else {
                return (0, None, Vec::new());
            };
            let paths = store::changed_by(doc, hash, InLists::Whole).unwrap_or_default();
            let user = change
                .message()
                .and_then(|message| crate::document::replica::user_of(message))
                .map(str::to_owned);
            (change.timestamp(), user, paths)
        })
        .collect()
}

/// Where, among `changes` (in `src`; `written` is theirs, `touched`, in their order), the
/// last that wrote at `path` or below it, or replaced what was at a path above it, is: a
/// map one made on the way, where it found none, is no write of that change's at `path`.
fn last_written(
    src: &Document,
    changes: &[ChangeHash],
    written: &[Touched],
    path: &[String],
) -> Option<usize> {
    (0..written.len()).rev().find(|&made| {
        written[made].2.iter().any(|other| {
            other.starts_with(path)
                || path.starts_with(other) && found_at(src, &changes[made], other)
        })
    })
}

/// Whether the change `hash` (in `doc`) found something at `path` where it was made.
fn found_at(doc: &Document, hash: &ChangeHash, path: &[String]) -> bool {
    doc.get_change_by_hash(hash)
        .and_then(|change| At::new(doc, change.deps()))
        .is_some_and(|before| matches!(store::read_held(&before, path), Ok(Some(_))))
}

/// The time and user of the newest of `changes` that touched `path`, a path above it or
/// one below it (of two at once, the user named last in order).
fn newest(changes: &[Touched], path: &[String]) -> Option<(i64, Option<String>)> {
    changes
        .iter()
        .filter(|(_, _, paths)| {
            paths
                .iter()
                .any(|other| other.starts_with(path) || path.starts_with(other))
        })
        .map(|(at, user, _)| (*at, user.clone()))
        .max()
}

/// The user of the newest of `changes` that wrote at `path` or below it: whose write it
/// is (of two at once, the one named last in order).
fn writer(changes: &[Touched], path: &[String]) -> Option<String> {
    changes
        .iter()
        .filter(|(_, _, paths)| paths.iter().any(|other| other.starts_with(path)))
        .map(|(at, user, _)| (*at, user.clone()))
        .max()
        .and_then(|(_, user)| user)
}

/// `paths`, each a map that writes for more than one user changed below split into its
/// entries (in `src` or `dst`), until each part is one user's: a replayed change names
/// one user, and rules by path judge it by that user (`access::rules`).
fn by_user(
    src: &Document,
    dst: &Document,
    changes: &[Touched],
    paths: Vec<Vec<String>>,
) -> Vec<Vec<String>> {
    let mut out = Vec::new();
    let mut todo = paths;
    while let Some(path) = todo.pop() {
        let users: HashSet<&Option<String>> = changes
            .iter()
            .filter(|(_, _, paths)| paths.iter().any(|other| other.starts_with(&path)))
            .map(|(_, user, _)| user)
            .collect();
        let keys = store::keys_at(src, &path).ok().flatten();
        match keys {
            Some(mut keys) if users.len() > 1 => {
                keys.extend(
                    store::keys_at(dst, &path)
                        .ok()
                        .flatten()
                        .unwrap_or_default(),
                );
                keys.sort();
                keys.dedup();
                for key in keys {
                    let mut child = path.clone();
                    child.push(key);
                    todo.push(child);
                }
            }
            _ => out.push(path),
        }
    }
    out.sort();
    out
}

/// Whether `path` is in another member's entry than `node`'s (`_continuum/members/<pk>`):
/// only that member writes it of its own (`access::rules`).
fn others_entry(path: &[String], node: &str) -> bool {
    matches!(path, [root, members, owner, ..]
        if root == meta::ROOT && members == meta::MEMBERS && owner != node)
}

/// Replays into `dst` everything that changed in `src` between `before` and `after`,
/// as one commit, whatever `dst` has (no last writer wins): what a replay copies, for
/// tests. Both head sets must be in `src`.
#[cfg(test)]
pub(crate) fn replay(
    src: &Document,
    before: &[ChangeHash],
    after: &[ChangeHash],
    dst: &mut Document,
    translator: &Translator,
) -> ReplayStats {
    if before == after {
        return ReplayStats::default();
    }

    let paths = changed_paths(src, before, after);
    let mut transaction = dst.transaction();
    let stats = replay_paths(src, &mut transaction, &paths, translator);
    transaction.commit();
    stats
}

/// Replays the state of `paths` (from [`changed_paths`]) from `src` into `dst` (the
/// caller commits). Lets callers find the paths outside a lock and copy them inside it.
pub(crate) fn replay_paths(
    src: &Document,
    dst: &mut impl Transactable,
    paths: &[Vec<String>],
    translator: &Translator,
) -> ReplayStats {
    let mut stats = ReplayStats::default();
    for path in paths {
        replay_path(src, dst, path, translator, &mut stats);
    }
    stats
}

fn replay_path(
    src: &Document,
    dst: &mut impl Transactable,
    path: &[String],
    translator: &Translator,
    stats: &mut ReplayStats,
) {
    if is_protocol_path(path) {
        return;
    }

    // Replacing an ancestor of the protocol metadata as a whole would clobber it; replay
    // its children one by one instead.
    if contains_protocol_path(path) {
        let mut keys = store::keys_at(src, path).ok().flatten().unwrap_or_default();
        keys.extend(store::keys_at(dst, path).ok().flatten().unwrap_or_default());
        keys.sort();
        keys.dedup();
        for key in keys {
            let mut child = path.to_vec();
            child.push(key);
            replay_path(src, dst, &child, translator, stats);
        }
        return;
    }

    let copied = match translator.translate(path) {
        Translation::Same => store::copy_path(src, dst, path),
        Translation::To(to) => store::copy_path_to(src, path, dst, &to),
        Translation::Drop => {
            stats.dropped += 1;
            return;
        }
        Translation::Quarantine(reason) => {
            stats.quarantined.push((path.to_vec(), reason));
            return;
        }
    };
    match copied {
        Ok(()) => stats.replayed += 1,
        Err(error) => {
            log_failure(path, &error);
            stats.failed += 1;
        }
    }
}

fn log_failure(path: &[String], error: &StoreError) {
    warn!(path = ?path, error = %error, "Could not replay change into the new epoch");
}

fn is_protocol_path(path: &[String]) -> bool {
    let [root, part, ..] = path else {
        return false;
    };
    root == meta::ROOT && [REMAKES, VOTES, EPOCHS].contains(&part.as_str())
}

/// True for the root and for `_continuum` itself.
fn contains_protocol_path(path: &[String]) -> bool {
    matches!(path, [] | [_]) && path.first().is_none_or(|root| root == meta::ROOT)
}

/// What a late node has that a snapshot lacks.
#[derive(Debug)]
pub(crate) struct Missing {
    /// Heads of everything except `own` changes the snapshot lacks (and changes built on
    /// them). Replaying from these heads to the document's heads replays exactly those.
    pub(crate) before: Vec<ChangeHash>,
    /// Changes by `own` that the snapshot lacks.
    pub(crate) own: usize,
}

/// Splits `doc`'s history against a snapshot `clock`: a change (actor, seq) is in the
/// snapshot iff seq <= clock[actor].
///
/// Only changes this node wrote itself (any of the actors in `own`: one per run and
/// epoch) are worth replaying when it rejoins: other nodes' changes after the base were
/// replayed by the nodes that switched, and replaying them again would overwrite newer
/// writes in the new epoch with stale ones.
pub(crate) fn missing_from_snapshot(
    doc: &Document,
    clock: &BTreeMap<String, u64>,
    own: &[ActorId],
) -> Missing {
    let own_hex: HashSet<String> = own.iter().map(ActorId::to_string).collect();
    let changes: Vec<(ChangeHash, Vec<ChangeHash>, bool)> = doc
        .get_changes(&[])
        .iter()
        .map(|change| {
            let actor = change.actor_id().to_string();
            let in_snapshot = clock.get(&actor).is_some_and(|&seq| change.seq() <= seq);
            let own_missing = own_hex.contains(&actor) && !in_snapshot;
            (change.hash(), change.deps().to_vec(), own_missing)
        })
        .collect();

    // Excluded: own missing changes and everything that (transitively) depends on them.
    // A fixpoint, so it doesn't rely on the order `get_changes` returns.
    let mut excluded: HashSet<ChangeHash> = changes
        .iter()
        .filter(|(_, _, own_missing)| *own_missing)
        .map(|(hash, _, _)| *hash)
        .collect();
    let own_count = excluded.len();
    loop {
        let before = excluded.len();
        for (hash, deps, _) in &changes {
            if !excluded.contains(hash) && deps.iter().any(|dep| excluded.contains(dep)) {
                excluded.insert(*hash);
            }
        }
        if excluded.len() == before {
            break;
        }
    }

    // Heads of the kept part: kept changes no kept change depends on.
    let kept: Vec<&(ChangeHash, Vec<ChangeHash>, bool)> = changes
        .iter()
        .filter(|(hash, _, _)| !excluded.contains(hash))
        .collect();
    let depended_on: HashSet<ChangeHash> = kept
        .iter()
        .flat_map(|(_, deps, _)| deps.iter().copied())
        .collect();
    let mut before: Vec<ChangeHash> = kept
        .iter()
        .map(|(hash, _, _)| *hash)
        .filter(|hash| !depended_on.contains(hash))
        .collect();
    before.sort();

    Missing {
        before,
        own: own_count,
    }
}

/// The minimal set of store paths covering every change between `before` and `after`:
/// sorted, and no path is a prefix of another.
pub(crate) fn changed_paths(
    doc: &Document,
    before: &[ChangeHash],
    after: &[ChangeHash],
) -> Vec<Vec<String>> {
    let mut paths: Vec<Vec<String>> = store::changed(doc, before, after, InLists::Whole)
        .into_iter()
        .map(|changed| changed.path)
        .collect();
    paths.sort();
    paths.dedup();

    // Sorted order puts a prefix right before its extensions, so comparing with the
    // last kept path is enough.
    let mut minimal: Vec<Vec<String>> = Vec::new();
    for path in paths {
        if minimal.last().is_some_and(|kept| path.starts_with(kept)) {
            continue;
        }
        minimal.push(path);
    }
    minimal
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::document::testing::{change, try_change};
    use automerge::{ObjType, ROOT, ReadDoc, ScalarValue, transaction::Transactable};
    use serde_json::json;

    fn view(doc: &Document) -> serde_json::Value {
        store::read_path(doc, &[]).unwrap().unwrap()
    }

    /// A random store write as the API makes it (one change): a scalar or a small map
    /// at a path up to three keys deep, or a delete. Writes the store refuses (e.g. into
    /// a scalar) are rolled back.
    fn random_write(rng: &mut crate::testrand::Rng, doc: &mut Document) {
        const KEYS: [&str; 3] = ["a", "b", "c"];
        let depth = rng.between(1, 3);
        let path: Vec<String> = (0..depth).map(|_| rng.pick(&KEYS).to_string()).collect();
        let _ = if rng.chance(0.2) {
            try_change(doc, |doc| store::delete_path(doc, &path, false))
        } else {
            let value = match rng.below(4) {
                0 => json!(rng.below(100)),
                1 => json!(format!("s{}", rng.below(100))),
                2 => json!(rng.chance(0.5)),
                _ => {
                    let mut map = serde_json::Map::new();
                    map.insert(rng.pick(&KEYS).to_string(), json!(rng.below(100)));
                    serde_json::Value::Object(map)
                }
            };
            try_change(doc, |doc| store::write_path(doc, &path, &value))
        };
    }

    /// Compaction's promise: a snapshot of the base plus everything replayed since gives
    /// the old document's content, whatever several nodes wrote concurrently.
    #[test]
    fn replay_reproduces_the_document() {
        crate::testrand::for_seeds(200, |rng| {
            let actor = |i: u8| ActorId::from(&[i; 16][..]);
            let mut old = Document::new().with_actor(actor(0));
            for _ in 0..rng.between(0, 8) {
                random_write(rng, &mut old);
            }
            let base = old.get_heads();
            let mut new = Document::new().with_actor(actor(100));
            change(&mut new, |new| {
                store::materialize_into(&old, new, &|_| false).unwrap()
            });

            let mut nodes: Vec<Document> = (1..=rng.between(1, 3))
                .map(|i| old.fork().with_actor(actor(i as u8)))
                .collect();
            for _ in 0..rng.between(1, 20) {
                let node = rng.below(nodes.len());
                random_write(rng, &mut nodes[node]);
            }
            for node in &mut nodes {
                old.merge(node).unwrap();
            }
            let after = old.get_heads();

            let stats = replay(&old, &base, &after, &mut new, &Translator::default());
            assert_eq!(stats.failed, 0);
            assert_eq!(view(&new), view(&old));
        });
    }

    /// Every non-empty-object value of `json` with its path.
    fn leaves(
        json: &serde_json::Value,
        path: &mut Vec<String>,
        out: &mut Vec<(Vec<String>, String)>,
    ) {
        match json {
            serde_json::Value::Object(map) => {
                for (key, value) in map {
                    path.push(key.clone());
                    leaves(value, path, out);
                    path.pop();
                }
            }
            other => out.push((path.clone(), other.to_string())),
        }
    }

    /// Over random histories (writes and deletes, some on concurrent forks): the paths
    /// are sorted, none is a prefix of another, and together they cover every value that
    /// differs between before and after.
    #[test]
    fn changed_paths_cover_every_change_minimally() {
        crate::testrand::for_seeds(300, |rng| {
            let actor = |i: u8| ActorId::from(&[i; 16][..]);
            let mut doc = Document::new().with_actor(actor(0));
            for _ in 0..rng.between(0, 8) {
                random_write(rng, &mut doc);
            }
            let before = doc.get_heads();
            let mut forks: Vec<Document> = (1..=rng.between(1, 3))
                .map(|i| doc.fork().with_actor(actor(i as u8)))
                .collect();
            for _ in 0..rng.between(0, 12) {
                let fork = rng.below(forks.len());
                random_write(rng, &mut forks[fork]);
            }
            for fork in &mut forks {
                doc.merge(fork).unwrap();
            }
            let after = doc.get_heads();

            let paths = changed_paths(&doc, &before, &after);
            for pair in paths.windows(2) {
                assert!(pair[0] < pair[1], "not sorted: {paths:?}");
                assert!(!pair[1].starts_with(&pair[0]), "not minimal: {paths:?}");
            }

            let mut old = Vec::new();
            leaves(
                &view(&doc.fork_at(&before).unwrap()),
                &mut Vec::new(),
                &mut old,
            );
            let mut new = Vec::new();
            leaves(&view(&doc), &mut Vec::new(), &mut new);
            let differing = old
                .iter()
                .filter(|leaf| !new.contains(leaf))
                .chain(new.iter().filter(|leaf| !old.contains(leaf)));
            for (path, _) in differing {
                assert!(
                    paths.iter().any(|changed| path.starts_with(changed)),
                    "{path:?} changed, but {paths:?} don't cover it"
                );
            }
        });
    }

    #[test]
    fn minimal_paths() {
        let mut doc = Document::new();
        change(&mut doc, |doc| doc.put(ROOT, "untouched", 1_i64).unwrap());
        let before = doc.get_heads();

        change(&mut doc, |doc| {
            let m = doc.put_object(ROOT, "m", ObjType::Map).unwrap();
            doc.put(&m, "a", 1_i64).unwrap();
            doc.put(ROOT, "x", 1_i64).unwrap();
            doc.put(ROOT, "c", ScalarValue::counter(0)).unwrap();
        });
        let middle = doc.get_heads();
        change(&mut doc, |doc| {
            doc.increment(ROOT, "c", 2).unwrap();
            let list = doc.put_object(ROOT, "l", ObjType::List).unwrap();
            doc.insert(&list, 0, "e").unwrap();
        });
        let after = doc.get_heads();

        let all = changed_paths(&doc, &before, &after);
        assert_eq!(
            all,
            vec![
                vec!["c".to_owned()],
                vec!["l".to_owned()],
                vec!["m".to_owned()],
                vec!["x".to_owned()],
            ]
        );

        let later = changed_paths(&doc, &middle, &after);
        assert_eq!(later, vec![vec!["c".to_owned()], vec!["l".to_owned()]]);
    }

    /// Writes to `doc` as one change made at `at` (Unix ms).
    fn write_at(
        doc: &mut Document,
        at: i64,
        f: impl FnOnce(&mut automerge::transaction::Transaction<'_>),
    ) {
        let mut transaction = doc.transaction();
        f(&mut transaction);
        transaction.commit_with(automerge::transaction::CommitOptions::default().with_time(at));
    }

    /// Under a policy, a replayed write every node would refuse (its user may no longer
    /// write there in the new epoch) goes to the quarantine, not into the document; the
    /// rest goes in.
    #[test]
    fn replays_every_node_would_refuse_quarantined() {
        let path = |text: &str| -> Vec<String> { text.split('/').map(str::to_owned).collect() };
        let alice = crate::access::registry::entry(
            "root",
            1,
            &[(path("notes"), &[crate::access::Right::Write][..])],
        );
        let mut old = Document::new();
        change(&mut old, |doc| {
            store::write_path(doc, &path("_continuum/swarm"), &json!("s")).unwrap();
            store::write_path(
                doc,
                &path("_continuum/access/policy"),
                &json!({"version": 1}),
            )
            .unwrap();
            store::write_path(doc, &path("_continuum/members/node"), &json!({})).unwrap();
            store::write_path(doc, &path("_continuum/users/alice"), &alice).unwrap();
            store::write_path(doc, &path("_continuum/users/bob"), &alice).unwrap();
        });
        crate::document::replica::authored(&mut old, "node");
        let base = old.get_heads();
        // In the new epoch, bob may write nothing any more.
        let mut new = old.clone().with_actor(automerge::ActorId::random());
        change(&mut new, |doc| {
            store::write_path(
                doc,
                &path("_continuum/users/bob"),
                &crate::access::registry::entry("root", 1, &[]),
            )
            .unwrap();
        });
        let mut commit = |user: &str, write: &str| {
            let mut transaction = old.transaction();
            store::write_path(&mut transaction, &path(write), &json!(1)).unwrap();
            transaction.commit_with(
                automerge::transaction::CommitOptions::default()
                    .with_time(10)
                    .with_message(format!("User: {user}")),
            );
        };
        commit("alice", "notes/x");
        commit("bob", "notes/y");
        let after = old.get_heads();
        let stats = replay_newest(
            &old,
            &base,
            &after,
            &mut new,
            crate::document::replica::Epoch::GENESIS,
            "node",
            &Translator::default(),
            Superseded::Drop,
        );
        assert_eq!(stats.replayed, 1);
        assert_eq!(stats.quarantined.len(), 1);
        assert_eq!(stats.quarantined[0].0, path("notes/y"));
        assert!(store::read_path(&new, &path("notes/x")).unwrap().is_some());
        assert!(store::read_path(&new, &path("notes/y")).unwrap().is_none());
    }

    /// A strict swarm's document, with alice, whose key is `key`, writing `config`,
    /// a value its user signs; and the envelope alice signs there, after `prev`.
    fn strict_with(key: &ed25519_dalek::SigningKey) -> Document {
        use crate::access::sshsig;
        let path = |text: &str| -> Vec<String> { text.split('/').map(str::to_owned).collect() };
        let mut alice = crate::access::registry::entry(
            "root",
            1,
            &[(path("config"), &[crate::access::Right::Write][..])],
        );
        alice["keys"] = json!({ "k": sshsig::PublicKey(key.verifying_key().to_bytes()).line() });
        let mut doc = Document::new();
        change(&mut doc, |doc| {
            store::write_path(doc, &path("_continuum/swarm"), &json!("s")).unwrap();
            store::write_path(
                doc,
                &path("_continuum/access/policy"),
                &json!({"version": 1, "values": "signed"}),
            )
            .unwrap();
            store::write_path(
                doc,
                &path("_continuum/access/userSigned"),
                &json!([["config"]]),
            )
            .unwrap();
            store::write_path(doc, &path("_continuum/members/node"), &json!({})).unwrap();
            store::write_path(doc, &path("_continuum/users/alice"), &alice).unwrap();
        });
        crate::document::replica::authored(&mut doc, "node");
        doc
    }

    fn signed_after(key: &ed25519_dalek::SigningKey, prev: Option<&str>, value: i64) -> String {
        signed_at(key, "config", prev, value)
    }

    fn signed_at(
        key: &ed25519_dalek::SigningKey,
        place: &str,
        prev: Option<&str>,
        value: i64,
    ) -> String {
        use crate::access::sshsig;
        let payload = crate::document::signed::Payload {
            value: json!(value),
            swarm: "s".to_owned(),
            path: vec![place.to_owned()],
            user: "alice".to_owned(),
            at: 1,
            seq: prev.and_then(envelope::seq).map_or(0, |seq| seq + 1),
            prev: envelope::digest(prev),
        };
        let bytes = payload.signed();
        envelope::seal(&bytes, &sshsig::sign(key, envelope::NAMESPACE, &bytes)).unwrap()
    }

    fn alice_writes(doc: &mut Document, at: i64, envelope: &str) {
        alice_writes_at(doc, at, "config", envelope);
    }

    fn alice_writes_at(doc: &mut Document, at: i64, place: &str, envelope: &str) {
        let mut transaction = doc.transaction();
        store::write_path(&mut transaction, &[place.to_owned()], &json!(envelope)).unwrap();
        transaction.commit_with(
            automerge::transaction::CommitOptions::default()
                .with_time(at)
                .with_message("User: alice".to_owned()),
        );
    }

    /// Under a strict policy, a value its user signed, written twice since the base, is
    /// replayed as its chain: each envelope after the one the new document holds, in
    /// order, so that every node takes each. Of two written at once, only the one the
    /// chain leads through.
    #[test]
    fn signed_values_replay_as_chains() {
        let key = ed25519_dalek::SigningKey::from_bytes(&[7; 32]);
        let mut old = strict_with(&key);
        let first = signed_after(&key, None, 1);
        alice_writes(&mut old, 5, &first);
        let base = old.get_heads();
        let new = old.clone().with_actor(automerge::ActorId::random());

        // Two written at once after the first, and one more after the second of them.
        let mut side = old.fork_at(&base).unwrap();
        let aside = signed_after(&key, Some(&first), 2);
        alice_writes(&mut side, 10, &aside);
        let second = signed_after(&key, Some(&first), 3);
        alice_writes(&mut old, 10, &second);
        let third = signed_after(&key, Some(&second), 4);
        alice_writes(&mut old, 20, &third);
        old.merge(&mut side).unwrap();
        assert_eq!(
            store::read_path(&old, &["config".to_owned()]).unwrap(),
            Some(json!(third))
        );

        let mut replayed = new.clone();
        let stats = replay_newest(
            &old,
            &base,
            &old.get_heads(),
            &mut replayed,
            crate::document::replica::Epoch::GENESIS,
            "node",
            &Translator::default(),
            Superseded::Drop,
        );
        assert!(stats.quarantined.is_empty(), "{:?}", stats.quarantined);
        assert_eq!(stats.replayed, 2);
        assert_eq!(
            store::read_candidates(&replayed, &["config".to_owned()]).unwrap(),
            [json!(third)]
        );

        // Where the new document holds as high a `seq` already: nothing.
        let stats = replay_newest(
            &old,
            &base,
            &old.get_heads(),
            &mut replayed,
            crate::document::replica::Epoch::GENESIS,
            "node",
            &Translator::default(),
            Superseded::Drop,
        );
        assert_eq!(stats.replayed, 0);
        assert!(stats.quarantined.is_empty());
    }

    /// Replayed in two parts, as a rejoin does (what was written before it began, then
    /// what was written during it): each part's chain leads to what the old document
    /// reads where that part ends.
    #[test]
    fn signed_values_replay_in_parts() {
        let key = ed25519_dalek::SigningKey::from_bytes(&[7; 32]);
        let mut old = strict_with(&key);
        let first = signed_after(&key, None, 1);
        alice_writes(&mut old, 5, &first);
        let base = old.get_heads();
        let mut replayed = old.clone().with_actor(automerge::ActorId::random());
        let second = signed_after(&key, Some(&first), 2);
        alice_writes(&mut old, 10, &second);
        let began = old.get_heads();
        let third = signed_after(&key, Some(&second), 3);
        alice_writes(&mut old, 20, &third);
        let fourth = signed_after(&key, Some(&third), 4);
        alice_writes(&mut old, 30, &fourth);
        for (from, to) in [(&base, &began), (&began, &old.get_heads())] {
            let stats = replay_newest(
                &old,
                from,
                to,
                &mut replayed,
                crate::document::replica::Epoch::GENESIS,
                "node",
                &Translator::default(),
                Superseded::Drop,
            );
            assert!(stats.quarantined.is_empty(), "{:?}", stats.quarantined);
        }
        assert_eq!(
            store::read_candidates(&replayed, &["config".to_owned()]).unwrap(),
            [json!(fourth)]
        );
    }

    /// The links of several places replayed in the order their changes were made, each
    /// after those it builds on, whatever the clocks say.
    #[test]
    fn signed_values_replay_in_the_order_written() {
        use crate::access::{Right, sshsig};
        let path = |text: &str| -> Vec<String> { text.split('/').map(str::to_owned).collect() };
        let key = ed25519_dalek::SigningKey::from_bytes(&[7; 32]);
        let mut old = strict_with(&key);
        let mut alice = crate::access::registry::entry(
            "root",
            1,
            &[
                (path("config"), &[Right::Write][..]),
                (path("other"), &[Right::Write][..]),
            ],
        );
        alice["keys"] = json!({ "k": sshsig::PublicKey(key.verifying_key().to_bytes()).line() });
        change(&mut old, |doc| {
            store::write_path(
                doc,
                &path("_continuum/access/userSigned"),
                &json!([["config"], ["other"]]),
            )
            .unwrap();
            store::write_path(doc, &path("_continuum/users/alice"), &alice).unwrap();
        });
        let base = old.get_heads();
        let mut replayed = old.clone().with_actor(automerge::ActorId::random());
        let since = replayed.get_heads();
        // The second made after the first, by a clock that is behind.
        alice_writes_at(&mut old, 50, "config", &signed_at(&key, "config", None, 1));
        alice_writes_at(&mut old, 10, "other", &signed_at(&key, "other", None, 2));
        let stats = replay_newest(
            &old,
            &base,
            &old.get_heads(),
            &mut replayed,
            crate::document::replica::Epoch::GENESIS,
            "node",
            &Translator::default(),
            Superseded::Drop,
        );
        assert!(stats.quarantined.is_empty(), "{:?}", stats.quarantined);
        let written: Vec<Vec<Vec<String>>> = replayed
            .get_changes(&since)
            .iter()
            .filter_map(|change| store::changed_by(&replayed, &change.hash(), InLists::Whole))
            .collect();
        assert_eq!(written, [vec![path("config")], vec![path("other")]]);
    }

    /// Under a strict policy, the other writes go with the links by history too: one made
    /// after a link, by a clock that is behind, still after it (it may build on what the
    /// link grants).
    #[test]
    fn other_writes_replay_after_the_links_they_follow() {
        use crate::access::{Right, sshsig};
        let path = |text: &str| -> Vec<String> { text.split('/').map(str::to_owned).collect() };
        let key = ed25519_dalek::SigningKey::from_bytes(&[7; 32]);
        let mut old = strict_with(&key);
        let mut alice = crate::access::registry::entry(
            "root",
            1,
            &[
                (path("config"), &[Right::Write][..]),
                (path("notes"), &[Right::Write][..]),
            ],
        );
        alice["keys"] = json!({ "k": sshsig::PublicKey(key.verifying_key().to_bytes()).line() });
        change(&mut old, |doc| {
            store::write_path(doc, &path("_continuum/users/alice"), &alice).unwrap();
        });
        let base = old.get_heads();
        let mut replayed = old.clone().with_actor(automerge::ActorId::random());
        let since = replayed.get_heads();
        alice_writes_at(&mut old, 50, "config", &signed_at(&key, "config", None, 1));
        let mut transaction = old.transaction();
        store::write_path(&mut transaction, &path("notes"), &json!(1)).unwrap();
        transaction.commit_with(
            automerge::transaction::CommitOptions::default()
                .with_time(10)
                .with_message("User: alice".to_owned()),
        );
        let stats = replay_newest(
            &old,
            &base,
            &old.get_heads(),
            &mut replayed,
            crate::document::replica::Epoch::GENESIS,
            "node",
            &Translator::default(),
            Superseded::Drop,
        );
        assert!(stats.quarantined.is_empty(), "{:?}", stats.quarantined);
        let written: Vec<Vec<Vec<String>>> = replayed
            .get_changes(&since)
            .iter()
            .filter_map(|change| store::changed_by(&replayed, &change.hash(), InLists::Whole))
            .collect();
        assert_eq!(written, [vec![path("config")], vec![path("notes")]]);
    }

    /// Under a strict policy, a map made on the way is no write of the change that made it
    /// at what another wrote below it: two users writing their first entries at once, each
    /// making the map above them, each have theirs replayed as their own.
    #[test]
    fn maps_made_on_the_way_name_no_user() {
        use crate::access::Right;
        let path = |text: &str| -> Vec<String> { text.split('/').map(str::to_owned).collect() };
        let key = ed25519_dalek::SigningKey::from_bytes(&[7; 32]);
        let mut old = strict_with(&key);
        change(&mut old, |doc| {
            for (user, entry) in [("alice", "servers/eu"), ("bob", "servers/us")] {
                let rights = crate::access::registry::entry(
                    "root",
                    1,
                    &[(path(entry), &[Right::Write][..])],
                );
                store::write_path(doc, &path(&format!("_continuum/users/{user}")), &rights)
                    .unwrap();
            }
        });
        let base = old.get_heads();
        let mut replayed = old.clone().with_actor(automerge::ActorId::random());
        let mut bob = old.clone().with_actor(automerge::ActorId::random());
        for (doc, user, entry, at) in [
            (&mut old, "alice", "servers/eu", 10),
            (&mut bob, "bob", "servers/us", 20),
        ] {
            let mut transaction = doc.transaction();
            store::write_path(&mut transaction, &path(entry), &json!(1)).unwrap();
            transaction.commit_with(
                automerge::transaction::CommitOptions::default()
                    .with_time(at)
                    .with_message(format!("User: {user}")),
            );
        }
        old.merge(&mut bob).unwrap();
        let stats = replay_newest(
            &old,
            &base,
            &old.get_heads(),
            &mut replayed,
            crate::document::replica::Epoch::GENESIS,
            "node",
            &Translator::default(),
            Superseded::Drop,
        );
        assert!(stats.quarantined.is_empty(), "{:?}", stats.quarantined);
        for entry in ["servers/eu", "servers/us"] {
            assert_eq!(
                store::read_path(&replayed, &path(entry)).unwrap(),
                Some(json!(1))
            );
        }
    }

    /// The first group refused: those after it still replayed, still the node's (a
    /// fork, taking the refused one back, has no author of its own).
    #[test]
    fn replays_after_a_first_one_refused() {
        let path = |text: &str| -> Vec<String> { text.split('/').map(str::to_owned).collect() };
        let alice = crate::access::registry::entry(
            "root",
            1,
            &[(path("notes"), &[crate::access::Right::Write][..])],
        );
        let mut old = Document::new();
        change(&mut old, |doc| {
            store::write_path(doc, &path("_continuum/swarm"), &json!("s")).unwrap();
            store::write_path(
                doc,
                &path("_continuum/access/policy"),
                &json!({"version": 1}),
            )
            .unwrap();
            store::write_path(doc, &path("_continuum/members/node"), &json!({})).unwrap();
            store::write_path(doc, &path("_continuum/users/alice"), &alice).unwrap();
            store::write_path(doc, &path("_continuum/users/bob"), &alice).unwrap();
        });
        crate::document::replica::authored(&mut old, "node");
        let base = old.get_heads();
        // In the new epoch, bob may write nothing any more: by another actor, so the
        // replaying one's first change is the first group.
        let mut revoker = old.clone().with_actor(automerge::ActorId::random());
        change(&mut revoker, |doc| {
            store::write_path(
                doc,
                &path("_continuum/users/bob"),
                &crate::access::registry::entry("root", 1, &[]),
            )
            .unwrap();
        });
        let mut new = old.clone().with_actor(automerge::ActorId::random());
        new.merge(&mut revoker).unwrap();
        let mut commit = |user: &str, write: &str, at: i64| {
            let mut transaction = old.transaction();
            store::write_path(&mut transaction, &path(write), &json!(1)).unwrap();
            transaction.commit_with(
                automerge::transaction::CommitOptions::default()
                    .with_time(at)
                    .with_message(format!("User: {user}")),
            );
        };
        commit("bob", "notes/y", 5);
        commit("alice", "notes/x", 10);
        let after = old.get_heads();
        let stats = replay_newest(
            &old,
            &base,
            &after,
            &mut new,
            crate::document::replica::Epoch::GENESIS,
            "node",
            &Translator::default(),
            Superseded::Drop,
        );
        assert_eq!(stats.quarantined.len(), 1, "{:?}", stats.quarantined);
        assert_eq!(stats.quarantined[0].0, path("notes/y"));
        assert_eq!(stats.replayed, 1);
        assert!(store::read_path(&new, &path("notes/x")).unwrap().is_some());
    }

    /// Replayed changes are the replaying node's and name each write's user; another
    /// member's entry, written without a user, is left to that member.
    #[test]
    fn replays_keep_their_writers() {
        let path = |text: &str| -> Vec<String> { text.split('/').map(str::to_owned).collect() };
        let mut old = Document::new();
        change(&mut old, |doc| {
            store::write_path(doc, &path("_continuum/members/node"), &json!({})).unwrap();
            store::write_path(doc, &path("_continuum/members/other"), &json!({})).unwrap();
        });
        let base = old.get_heads();
        let mut new = old.clone().with_actor(automerge::ActorId::random());
        let mut commit = |at: i64, user: Option<&str>, write: &str, value: serde_json::Value| {
            let mut transaction = old.transaction();
            store::write_path(&mut transaction, &path(write), &value).unwrap();
            let mut options = automerge::transaction::CommitOptions::default().with_time(at);
            if let Some(user) = user {
                options = options.with_message(format!("User: {user}"));
            }
            transaction.commit_with(options);
        };
        commit(10, Some("alice"), "notes/x", json!(1));
        commit(10, Some("bob"), "notes/y", json!(2));
        commit(11, None, "_continuum/members/other/alive", json!(11));
        commit(11, None, "_continuum/members/node/alive", json!(11));
        let after = old.get_heads();
        let new_heads = new.get_heads();
        let stats = replay_newest(
            &old,
            &base,
            &after,
            &mut new,
            crate::document::replica::Epoch::GENESIS,
            "node",
            &Translator::default(),
            Superseded::Drop,
        );
        assert_eq!(stats.replayed, 3);
        assert!(
            store::read_path(&new, &path("_continuum/members/other/alive"))
                .unwrap()
                .is_none()
        );
        assert_eq!(
            store::read_path(&new, &path("_continuum/members/node/alive")).unwrap(),
            Some(json!(11))
        );
        // One change per user and time, each by the node, naming its user.
        let replayed: Vec<(Option<String>, i64)> = new
            .get_changes(&new_heads)
            .iter()
            .map(|change| (change.message().map(str::to_owned), change.timestamp()))
            .collect();
        assert_eq!(
            replayed,
            vec![
                (Some("User: alice".to_owned()), 10),
                (Some("User: bob".to_owned()), 10),
                (None, 11),
            ]
        );
        assert_eq!(
            new.get_author().map(|author| author.as_bytes().to_vec()),
            Some(b"node".to_vec())
        );
    }

    /// An old document with `x`, `m/a` and `m/b` written at 10 after the base, and a new
    /// one holding the base; `newer` writes to the new one first.
    fn superseding(
        newer: impl FnOnce(&mut Document),
        superseded: Superseded,
    ) -> (Document, ReplayStats) {
        let mut old = Document::new();
        write_at(&mut old, 1, |old| {
            let m = old.put_object(ROOT, "m", ObjType::Map).unwrap();
            old.put(&m, "a", "base").unwrap();
        });
        let base = old.get_heads();
        let mut new = Document::new();
        write_at(&mut new, 0, |new| {
            store::materialize_into(&old, new, &|_| false).unwrap();
        });
        newer(&mut new);
        write_at(&mut old, 10, |old| {
            old.put(ROOT, "x", "old").unwrap();
            let (_, m) = old.get(ROOT, "m").unwrap().unwrap();
            old.put(&m, "a", "old").unwrap();
            old.put(&m, "b", "old").unwrap();
        });
        let after = old.get_heads();
        let stats = replay_newest(
            &old,
            &base,
            &after,
            &mut new,
            crate::document::replica::Epoch::GENESIS,
            "node",
            &Translator::default(),
            superseded,
        );
        (new, stats)
    }

    #[test]
    fn replay_newest_keeps_newer_writes() {
        // Nothing newer: everything replayed, at the time it was written.
        let (new, stats) = superseding(|_| {}, Superseded::Drop);
        assert_eq!((stats.replayed, stats.superseded), (3, 0));
        assert_eq!(
            view(&new),
            json!({ "x": "old", "m": { "a": "old", "b": "old" } })
        );
        let times: Vec<i64> = new.get_changes(&[]).iter().map(|c| c.timestamp()).collect();
        assert_eq!(times, [0, 10]);

        // A newer write at the path wins; an older one doesn't.
        let (new, stats) = superseding(
            |new| write_at(new, 20, |new| new.put(ROOT, "x", "newer").unwrap()),
            Superseded::Drop,
        );
        assert_eq!((stats.replayed, stats.superseded), (2, 1));
        assert_eq!(view(&new)["x"], json!("newer"));
        assert_eq!(view(&new)["m"], json!({ "a": "old", "b": "old" }));
        let (new, _) = superseding(
            |new| write_at(new, 5, |new| new.put(ROOT, "x", "older").unwrap()),
            Superseded::Drop,
        );
        assert_eq!(view(&new)["x"], json!("old"));

        // Per key: a newer `m/a` wins over the replayed `m/a`, not over `m/b`.
        let (new, stats) = superseding(
            |new| {
                write_at(new, 20, |new| {
                    let (_, m) = new.get(ROOT, "m").unwrap().unwrap();
                    new.put(&m, "a", "newer").unwrap();
                })
            },
            Superseded::Drop,
        );
        assert_eq!(stats.superseded, 1);
        assert_eq!(view(&new)["m"], json!({ "a": "newer", "b": "old" }));
        // A newer write above the paths (`m` replaced) wins over both.
        let (new, stats) = superseding(
            |new| write_at(new, 20, |new| new.put(ROOT, "m", "a scalar now").unwrap()),
            Superseded::Drop,
        );
        assert_eq!(stats.superseded, 2);
        assert_eq!(view(&new)["m"], json!("a scalar now"));

        // Quarantined instead, with the time of each.
        let (_, stats) = superseding(
            |new| write_at(new, 20, |new| new.put(ROOT, "x", "newer").unwrap()),
            Superseded::Quarantine,
        );
        assert_eq!(stats.superseded, 0);
        assert_eq!(stats.quarantined.len(), 1);
        assert_eq!(stats.quarantined[0].0, ["x"]);
    }

    /// A newer write below a replayed path wins too: the replay would replace it.
    #[test]
    fn replay_newest_keeps_newer_writes_below() {
        let mut old = Document::new();
        write_at(&mut old, 1, |old| old.put(ROOT, "base", true).unwrap());
        let base = old.get_heads();
        let mut new = Document::new();
        write_at(&mut new, 0, |new| {
            store::materialize_into(&old, new, &|_| false).unwrap();
            new.put_object(ROOT, "m", ObjType::Map).unwrap();
        });
        write_at(&mut new, 20, |new| {
            let (_, m) = new.get(ROOT, "m").unwrap().unwrap();
            new.put(&m, "a", "newer").unwrap();
        });
        // The whole map, older.
        write_at(&mut old, 10, |old| {
            let m = old.put_object(ROOT, "m", ObjType::Map).unwrap();
            old.put(&m, "a", "old").unwrap();
        });
        let after = old.get_heads();
        let stats = replay_newest(
            &old,
            &base,
            &after,
            &mut new,
            crate::document::replica::Epoch::GENESIS,
            "node",
            &Translator::default(),
            Superseded::Drop,
        );
        assert_eq!(stats.superseded, 1);
        assert_eq!(view(&new)["m"], json!({ "a": "newer" }));
    }

    #[test]
    fn replays_state_per_key() {
        // Base shared by the old document and the snapshot.
        let mut old = Document::new();
        let m = change(&mut old, |old| {
            let m = old.put_object(ROOT, "m", ObjType::Map).unwrap();
            old.put(&m, "keep", "base").unwrap();
            old.put(&m, "change", "base").unwrap();
            old.put(ROOT, "gone", true).unwrap();
            m
        });
        let base = old.get_heads();

        let mut new = Document::new();
        change(&mut new, |new| {
            store::materialize_into(&old, new, &|_| false).unwrap();
            // Something the new epoch already holds that the delta must not clobber.
            let Some((_, m_new)) = new.get(ROOT, "m").unwrap() else {
                panic!("m missing");
            };
            new.put(&m_new, "keep", "new epoch").unwrap();
        });

        // The delta: one key changed, one key deleted.
        change(&mut old, |old| {
            old.put(&m, "change", "delta").unwrap();
            old.delete(ROOT, "gone").unwrap();
        });
        let after = old.get_heads();

        let stats = replay(&old, &base, &after, &mut new, &Translator::default());
        assert_eq!(stats.failed, 0);
        assert_eq!(
            view(&new),
            json!({ "m": { "keep": "new epoch", "change": "delta" } })
        );
    }

    #[test]
    fn missing_counts_only_own_changes() {
        let own = ActorId::from(&b"own-actor"[..]);
        let other = ActorId::from(&b"other-actor"[..]);

        let mut doc = Document::new().with_actor(own.clone());
        change(&mut doc, |doc| doc.put(ROOT, "base", 1_i64).unwrap());
        let base = doc.get_heads();

        // The snapshot contains the base only.
        let clock: BTreeMap<String, u64> = [(own.to_string(), 1)].into_iter().collect();

        // A foreign change after the base (replayed by its own node) ...
        let mut foreign = doc.fork().with_actor(other);
        change(&mut foreign, |foreign| {
            foreign.put(ROOT, "theirs", 1_i64).unwrap()
        });
        doc.merge(&mut foreign).unwrap();
        let with_foreign = doc.get_heads();

        // ... and one of ours.
        change(&mut doc, |doc| doc.put(ROOT, "mine", 1_i64).unwrap());
        let after = doc.get_heads();

        let missing = missing_from_snapshot(&doc, &clock, std::slice::from_ref(&own));
        assert_eq!(missing.own, 1);
        assert_eq!(missing.before, with_foreign);
        assert_ne!(missing.before, base);
        assert_eq!(
            changed_paths(&doc, &missing.before, &after),
            vec![vec!["mine".to_owned()]]
        );

        // Nothing of ours missing: nothing to replay.
        let full: BTreeMap<String, u64> = [(own.to_string(), 2)].into_iter().collect();
        let none = missing_from_snapshot(&doc, &full, std::slice::from_ref(&own));
        assert_eq!(none.own, 0);
        let mut heads = after.clone();
        heads.sort();
        assert_eq!(none.before, heads);
    }

    #[test]
    fn protocol_metadata_is_never_replayed() {
        let mut old = Document::new();
        change(&mut old, |old| old.put(ROOT, "x", 1_i64).unwrap());
        let base = old.get_heads();

        let mut new = Document::new();
        change(&mut new, |new| {
            store::write_path(
                new,
                &meta::path(&[EPOCHS, "1"]),
                &json!({ "generation": 1 }),
            )
            .unwrap()
        });

        // The old epoch replaces `_continuum` wholesale and writes a remake record.
        change(&mut old, |old| {
            store::write_path(old, &meta::path(&[]), &json!({ "forgotten": { "pk": 1 } })).unwrap();
            store::write_path(old, &meta::path(&[REMAKES, "c"]), &json!({ "x": 1 })).unwrap();
        });
        let after = old.get_heads();

        replay(&old, &base, &after, &mut new, &Translator::default());
        let meta = &view(&new)[meta::ROOT];
        assert_eq!(meta[EPOCHS]["1"]["generation"], json!(1));
        assert_eq!(meta["forgotten"]["pk"], json!(1));
        assert!(meta.get(REMAKES).is_none());
    }
}