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
|
//! Deterministic snapshot of the document at agreed base heads.
//!
//! Every node builds the snapshot of a committed compaction on its own. For that to
//! work, the snapshot must be byte-identical everywhere: same operations, same order,
//! same actor, same timestamp. Its change hash then identifies the new epoch, and a
//! node whose build produces a different hash knows it must fetch the snapshot instead.
//!
//! Determinism rests on:
//! * the content: the merged view at the base heads (`store::materialize_into`), which
//! depends only on the base, not on how a node's history got there;
//! * a fixed actor derived from the compaction ID and generation;
//! * commit time 0 and no message;
//! * canonical (sorted) JSON for the metadata;
//! * the same Automerge version on every node (encodings may differ across versions).
//!
//! The snapshot carries its own metadata under `_continuum/epochs/<generation>`:
//! previous epoch, base heads, per-actor clock and retention policy. Later steps read it
//! at the snapshot change itself, so edits made afterwards through the store API can't
//! change what the protocol sees.
// Wired into the compaction protocol in step 4.
#![cfg_attr(not(test), allow(dead_code))]
use std::collections::BTreeMap;
use automerge::{transaction::CommitOptions, ActorId, AutoCommit, ChangeHash};
use serde_json::{json, Map as JsonMap, Value as JsonValue};
use sha2::{Digest, Sha256};
use crate::replica::Epoch;
use crate::store::{self, StoreError};
pub(crate) const META_ROOT: &str = "_continuum";
pub(crate) const COMPACTIONS: &str = "compactions";
pub(crate) const EPOCHS: &str = "epochs";
/// Everything that determines a snapshot besides the base content.
pub(crate) struct SnapshotParams<'a> {
/// ID of the committed compaction; seeds the snapshot actor.
pub(crate) compaction_id: &'a str,
/// The epoch being compacted. The snapshot starts generation `previous + 1`.
pub(crate) previous: Epoch,
/// Heads of the base. Every node must hold all of these changes.
pub(crate) base_heads: &'a [ChangeHash],
/// Retention policy from the compaction request; stored verbatim (canonicalized).
pub(crate) policy: &'a JsonValue,
}
pub(crate) struct Snapshot {
/// The new epoch: next generation, ID = hash of the snapshot change.
pub(crate) epoch: Epoch,
/// A document consisting of exactly that one change.
pub(crate) doc: AutoCommit,
/// Highest sequence number per actor (hex) contained in the base. A change
/// (actor, seq) is part of the snapshot iff seq <= clock[actor].
pub(crate) clock: BTreeMap<String, u64>,
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum SnapshotError {
#[error("base head {0} is not in the local document")]
MissingBase(ChangeHash),
#[error("snapshot produced {0} heads instead of exactly one")]
UnexpectedHeads(usize),
#[error(transparent)]
Doc(#[from] automerge::AutomergeError),
#[error(transparent)]
Store(#[from] StoreError),
}
/// Path of the metadata record for an epoch generation.
pub(crate) fn epoch_metadata_path(generation: u64) -> Vec<String> {
vec![
META_ROOT.to_owned(),
EPOCHS.to_owned(),
generation.to_string(),
]
}
/// Builds the snapshot of `source` at `params.base_heads`.
pub(crate) fn build(
source: &mut AutoCommit,
params: &SnapshotParams<'_>,
) -> Result<Snapshot, SnapshotError> {
// fork_at with unknown heads would quietly build something else.
for head in params.base_heads {
if source.get_change_by_hash(head).is_none() {
return Err(SnapshotError::MissingBase(*head));
}
}
let mut base = source.fork_at(params.base_heads)?;
let clock = clock_of(&mut base);
let generation = params.previous.generation + 1;
let mut snapshot =
AutoCommit::new().with_actor(snapshot_actor(params.compaction_id, generation));
// Compaction records describe the old epoch's protocol and stay behind.
store::materialize_into(&base, &mut snapshot, &is_compaction_record)?;
let mut base_heads: Vec<String> = params.base_heads.iter().map(|h| h.to_string()).collect();
base_heads.sort();
let metadata = canonical(json!({
"generation": generation,
"compactionId": params.compaction_id,
"previous": {
"generation": params.previous.generation,
"id": params.previous.id_hex(),
},
"baseHeads": base_heads,
"clock": clock,
"policy": params.policy,
}));
store::write_path(&mut snapshot, &epoch_metadata_path(generation), &metadata)?;
let _ = snapshot.commit_with(CommitOptions::default().with_time(0));
let heads = snapshot.get_heads();
let [id] = heads.as_slice() else {
return Err(SnapshotError::UnexpectedHeads(heads.len()));
};
Ok(Snapshot {
epoch: Epoch {
generation,
id: id.0,
},
doc: snapshot,
clock,
})
}
/// Highest sequence number per actor in `doc`'s history.
fn clock_of(doc: &mut AutoCommit) -> BTreeMap<String, u64> {
let mut clock = BTreeMap::new();
for change in doc.get_changes(&[]) {
let seq = clock.entry(change.actor_id().to_string()).or_insert(0);
*seq = (*seq).max(change.seq());
}
clock
}
/// The same 16-byte actor on every node, unique per compaction and generation.
fn snapshot_actor(compaction_id: &str, generation: u64) -> ActorId {
let digest = Sha256::new()
.chain_update(b"continuum.snapshot\0")
.chain_update(compaction_id.as_bytes())
.chain_update(b"\0")
.chain_update(generation.to_be_bytes())
.finalize();
ActorId::from(&digest[..16])
}
fn is_compaction_record(path: &[String]) -> bool {
matches!(path, [root, records] if root == META_ROOT && records == COMPACTIONS)
}
/// Rebuilds every object with sorted keys, so the result is the same whichever key
/// order serde_json happens to use (it keeps insertion order with `preserve_order`).
fn canonical(value: JsonValue) -> JsonValue {
match value {
JsonValue::Object(map) => {
let sorted: BTreeMap<String, JsonValue> = map
.into_iter()
.map(|(key, value)| (key, canonical(value)))
.collect();
JsonValue::Object(sorted.into_iter().collect::<JsonMap<_, _>>())
}
JsonValue::Array(items) => JsonValue::Array(items.into_iter().map(canonical).collect()),
other => other,
}
}
#[cfg(test)]
mod tests {
use super::*;
use automerge::{transaction::Transactable, ObjType, ReadDoc, ScalarValue, Value, ROOT};
fn doc(actor: &[u8]) -> AutoCommit {
AutoCommit::new().with_actor(ActorId::from(actor))
}
fn params<'a>(heads: &'a [ChangeHash], policy: &'a JsonValue) -> SnapshotParams<'a> {
SnapshotParams {
compaction_id: "c-1",
previous: Epoch::GENESIS,
base_heads: heads,
policy,
}
}
fn snapshot_of(source: &mut AutoCommit) -> Snapshot {
let heads = source.get_heads();
let policy = json!({});
build(source, ¶ms(&heads, &policy)).expect("snapshot")
}
/// The user-visible view, without our own metadata.
fn user_view(doc: &AutoCommit) -> JsonValue {
let mut view = store::read_path(doc, &[]).unwrap().unwrap();
view.as_object_mut().unwrap().remove(META_ROOT);
view
}
#[test]
fn same_view_different_history_same_snapshot() {
// One history: overwrites, increments, one-shot text.
let mut a = doc(b"actor-a");
a.put(ROOT, "x", 1_i64).unwrap();
a.commit();
a.put(ROOT, "x", 2_i64).unwrap();
a.put(ROOT, "c", ScalarValue::counter(0)).unwrap();
a.increment(ROOT, "c", 5).unwrap();
let text = a.put_object(ROOT, "t", ObjType::Text).unwrap();
a.splice_text(&text, 0, 0, "hello").unwrap();
let m = a.put_object(ROOT, "m", ObjType::Map).unwrap();
a.put(&m, "k", "v").unwrap();
a.commit();
// Another actor, other order, other steps, same result.
let mut b = doc(b"actor-b");
let m = b.put_object(ROOT, "m", ObjType::Map).unwrap();
b.put(&m, "k", "v").unwrap();
let text = b.put_object(ROOT, "t", ObjType::Text).unwrap();
b.splice_text(&text, 0, 0, "hel").unwrap();
b.commit();
b.splice_text(&text, 3, 0, "lo").unwrap();
b.put(ROOT, "c", ScalarValue::counter(5)).unwrap();
b.put(ROOT, "x", 2_i64).unwrap();
b.commit();
assert_eq!(user_view(&a), user_view(&b));
let snap_a = snapshot_of(&mut a);
let snap_b = snapshot_of(&mut b);
// Different histories mean different clocks, and the clock is part of the
// metadata. Equal views alone therefore give equal content but not equal IDs;
// equal bases do give equal IDs (see `rebuild_is_deterministic`).
assert_eq!(user_view(&snap_a.doc), user_view(&snap_b.doc));
assert_eq!(user_view(&snap_a.doc), user_view(&a));
}
#[test]
fn rebuild_is_deterministic() {
let mut a = doc(b"actor-a");
a.put(ROOT, "x", 1_i64).unwrap();
let list = a.put_object(ROOT, "l", ObjType::List).unwrap();
a.insert(&list, 0, "first").unwrap();
let inner = a.insert_object(&list, 1, ObjType::Map).unwrap();
a.put(&inner, "k", true).unwrap();
a.commit();
// A second node holding the same changes, received in a different way.
let mut b = doc(b"actor-b");
b.merge(&mut a.clone()).unwrap();
let first = snapshot_of(&mut a);
let again = snapshot_of(&mut a);
let elsewhere = snapshot_of(&mut b);
assert_eq!(first.epoch, again.epoch);
assert_eq!(first.epoch, elsewhere.epoch);
assert_eq!(first.epoch.generation, 1);
}
#[test]
fn conflicts_collapse_into_the_merged_view() {
let mut a = doc(b"actor-a");
let cfg = a.put_object(ROOT, "cfg", ObjType::Map).unwrap();
a.put(&cfg, "x", 1_i64).unwrap();
a.commit();
let mut b = doc(b"actor-b");
let cfg = b.put_object(ROOT, "cfg", ObjType::Map).unwrap();
b.put(&cfg, "y", 2_i64).unwrap();
b.commit();
a.merge(&mut b).unwrap();
let (_, conflicts) = store::read_path_with_conflicts(&a, &[]).unwrap().unwrap();
assert!(
!conflicts.is_empty(),
"test setup should produce a conflict"
);
let snap = snapshot_of(&mut a);
assert_eq!(user_view(&snap.doc), json!({ "cfg": { "x": 1, "y": 2 } }));
let (_, conflicts) = store::read_path_with_conflicts(&snap.doc, &[])
.unwrap()
.unwrap();
assert!(
conflicts.is_empty(),
"snapshot still has conflicts: {conflicts:?}"
);
}
#[test]
fn base_heads_bound_content_and_clock() {
let mut a = doc(b"actor-a");
for i in 0..3_i64 {
a.put(ROOT, format!("a{i}"), i).unwrap();
a.commit();
}
let mut b = doc(b"actor-b");
for i in 0..2_i64 {
b.put(ROOT, format!("b{i}"), i).unwrap();
b.commit();
}
a.merge(&mut b).unwrap();
let base = a.get_heads();
// After the base: must not appear in the snapshot or its clock.
a.put(ROOT, "late", true).unwrap();
a.commit();
let policy = json!({});
let snap = build(&mut a, ¶ms(&base, &policy)).unwrap();
let view = user_view(&snap.doc);
assert!(view.get("late").is_none());
assert_eq!(view["a2"], json!(2));
assert_eq!(view["b1"], json!(1));
let actor_a = ActorId::from(b"actor-a".as_slice()).to_string();
let actor_b = ActorId::from(b"actor-b".as_slice()).to_string();
assert_eq!(snap.clock.get(&actor_a), Some(&3));
assert_eq!(snap.clock.get(&actor_b), Some(&2));
}
#[test]
fn metadata_written_and_compaction_records_dropped() {
let mut a = doc(b"actor-a");
store::write_path(
&mut a,
&[META_ROOT.into(), COMPACTIONS.into(), "c-1".into()],
&json!({ "state": "committed" }),
)
.unwrap();
store::write_path(
&mut a,
&[META_ROOT.into(), "forgotten".into(), "pk".into()],
&json!({ "at": 1 }),
)
.unwrap();
a.commit();
let heads = a.get_heads();
let policy = json!({ "replayWindow": { "epochs": 1 } });
let snap = build(&mut a, ¶ms(&heads, &policy)).unwrap();
let meta = store::read_path(&snap.doc, &[META_ROOT.into()])
.unwrap()
.unwrap();
assert!(meta.get(COMPACTIONS).is_none());
assert_eq!(meta["forgotten"]["pk"]["at"], json!(1));
let epoch = &meta[EPOCHS]["1"];
assert_eq!(epoch["generation"], json!(1));
assert_eq!(epoch["compactionId"], json!("c-1"));
assert_eq!(epoch["previous"]["generation"], json!(0));
assert_eq!(epoch["policy"], policy);
assert_eq!(epoch["baseHeads"].as_array().unwrap().len(), heads.len());
}
#[test]
fn automerge_types_survive() {
let mut a = doc(b"actor-a");
a.put(ROOT, "c", ScalarValue::counter(3)).unwrap();
a.increment(ROOT, "c", 4).unwrap();
let text = a.put_object(ROOT, "t", ObjType::Text).unwrap();
a.splice_text(&text, 0, 0, "abc").unwrap();
a.put(ROOT, "bytes", ScalarValue::Bytes(vec![0, 1, 255]))
.unwrap();
a.put(ROOT, "ts", ScalarValue::Timestamp(1_700_000_000_000))
.unwrap();
a.put(ROOT, "neg_zero", -0.0_f64).unwrap();
a.commit();
let snap = snapshot_of(&mut a);
let d = &snap.doc;
match d.get(ROOT, "c").unwrap() {
Some((Value::Scalar(s), _)) => match s.as_ref() {
ScalarValue::Counter(c) => assert_eq!(i64::from(c.clone()), 7),
other => panic!("counter became {other:?}"),
},
other => panic!("unexpected {other:?}"),
}
let (_, text_id) = d.get(ROOT, "t").unwrap().unwrap();
assert_eq!(d.object_type(&text_id).unwrap(), ObjType::Text);
assert_eq!(d.text(&text_id).unwrap(), "abc");
match d.get(ROOT, "bytes").unwrap() {
Some((Value::Scalar(s), _)) => {
assert_eq!(s.as_ref(), &ScalarValue::Bytes(vec![0, 1, 255]))
}
other => panic!("unexpected {other:?}"),
}
match d.get(ROOT, "ts").unwrap() {
Some((Value::Scalar(s), _)) => {
assert_eq!(s.as_ref(), &ScalarValue::Timestamp(1_700_000_000_000))
}
other => panic!("unexpected {other:?}"),
}
match d.get(ROOT, "neg_zero").unwrap() {
Some((Value::Scalar(s), _)) => match s.as_ref() {
ScalarValue::F64(f) => assert_eq!(f.to_bits(), (-0.0_f64).to_bits()),
other => panic!("float became {other:?}"),
},
other => panic!("unexpected {other:?}"),
}
}
#[test]
fn snapshot_is_a_single_change_with_the_epoch_id() {
let mut a = doc(b"actor-a");
a.put(ROOT, "x", 1_i64).unwrap();
a.commit();
let mut snap = snapshot_of(&mut a);
let heads = snap.doc.get_heads();
assert_eq!(heads.len(), 1);
assert_eq!(heads[0].0, snap.epoch.id);
assert_eq!(snap.doc.get_changes(&[]).len(), 1);
}
#[test]
fn missing_base_is_rejected() {
let mut a = doc(b"actor-a");
a.put(ROOT, "x", 1_i64).unwrap();
a.commit();
let mut other = doc(b"actor-b");
other.put(ROOT, "y", 1_i64).unwrap();
other.commit();
let foreign = other.get_heads();
let policy = json!({});
assert!(matches!(
build(&mut a, ¶ms(&foreign, &policy)),
Err(SnapshotError::MissingBase(_))
));
}
#[test]
fn empty_document() {
let mut a = doc(b"actor-a");
let snap = snapshot_of(&mut a);
assert_eq!(snap.epoch.generation, 1);
assert!(snap.clock.is_empty());
assert_eq!(user_view(&snap.doc), json!({}));
}
}
|