OXYGENHUB
# d616faf5d136 oxygen / crates / oxy-core / src / state.rs
72.3 KiB · Rust · last changed Snapshot: whole-tree passes as merge joins (refs #41) 1 month ago source blame history raw
1
//! A state: a dependency-closed set of changes, applied to a tree graph and
2
//! per-node file graphs (spec §8.3), with materialization (spec §9.5, §11).
3
4
use crate::cbor::{self, Value};
5
use crate::graph::{AtomKey, DepOracle, FileGraph, Materialized, Vertex};
6
use crate::hash::KeyId;
7
use crate::hash::{ChangeHash, ObjectRef};
8
use crate::ids::NodeId;
9
use crate::objects::{
10
    self as o, AtomRef, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, ObjectError, TreeOp,
11
};
12
use crate::tree::{TreeGraph, TreeView};
13
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
14
use std::sync::{Arc, Mutex};
15
16
/// Checkpoint payload version 2 (spec §11): file graphs by reference.
17
pub const CHECKPOINT_INDEX_VERSION: u64 = 2;
18
19
/// A file graph encoded in fewer bytes stays inline in a version 2 index.
20
pub const INLINE_GRAPH_LIMIT: usize = 2048;
21
22
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
23
pub enum StateError {
24
    #[error("change {1} depends on {0}, which is not in the state")]
25
    MissingDep(ChangeHash, ChangeHash),
26
}
27
28
/// One `Replace` edit: `(change, old blob, new blob)`.
29
type ReplaceRecord = (ChangeHash, Option<ObjectRef>, Option<ObjectRef>);
30
31
/// What a state remembers about a change: everything but its operations,
32
/// which live in the graphs once applied (and in the store).
33
#[derive(Clone, Debug, PartialEq, Eq)]
34
pub struct ChangeMeta {
35
    pub change_id: crate::ids::ChangeId,
36
    pub deps: Vec<ChangeHash>,
37
    pub author: KeyId,
38
    pub hlc: Hlc,
39
    pub message: String,
40
    pub kind: ChangeKind,
41
}
42
43
impl ChangeMeta {
44
    pub fn of(c: &Change) -> ChangeMeta {
45
        ChangeMeta {
46
            change_id: c.change_id,
47
            deps: c.deps.clone(),
48
            author: c.author,
49
            hlc: c.hlc,
50
            message: c.message.clone(),
51
            kind: c.kind,
52
        }
53
    }
54
}
55
56
#[derive(Default)]
57
pub struct State {
58
    changes: HashMap<ChangeHash, ChangeMeta>,
59
    tree: TreeGraph,
60
    /// Shared between clones: a clone copies a graph only when an edit
61
    /// changes it (`Arc::make_mut`), so keeping several states that differ
62
    /// by a few changes costs little more than one.
63
    files: HashMap<NodeId, Arc<FileGraph>>,
64
    replaces: HashMap<NodeId, Vec<ReplaceRecord>>,
65
    /// Memoised transitive dependencies. A mutex, not a `RefCell`, so a
66
    /// loaded state can be shared across threads by a host that caches it.
67
    closure: Mutex<HashMap<ChangeHash, Arc<HashSet<ChangeHash>>>>,
68
    /// `None` for a full state. For a history-only state (loaded for its
69
    /// changes and tree), the file graphs not built yet, by node: `files`
70
    /// holds only those loaded with [`State::load_graphs`].
71
    deferred: Option<HashMap<NodeId, Deferred>>,
72
}
73
74
use crate::objects::TextRef;
75
76
/// A file graph a history-only state has not built: its base from a
77
/// version 2 checkpoint, if any, and the edits of later changes in the
78
/// order they were applied (spec §11). Building it later gives the same
79
/// graph, since graph construction does not depend on order (§8).
80
#[derive(Clone, Default)]
81
struct Deferred {
82
    base: Option<DeferredBase>,
83
    edits: Vec<(ChangeHash, Vec<Edit>)>,
84
    /// The text blob and line count of each insert in `edits` left without
85
    /// its lines, in order: read when the graph is built.
86
    texts: Vec<TextRef>,
87
}
88
89
#[derive(Clone)]
90
enum DeferredBase {
91
    Inline(Value),
92
    Blob(ObjectRef),
93
}
94
95
impl Clone for State {
96
    fn clone(&self) -> State {
97
        State {
98
            changes: self.changes.clone(),
99
            tree: self.tree.clone(),
100
            files: self.files.clone(),
101
            replaces: self.replaces.clone(),
102
            closure: Mutex::new(self.closure.lock().unwrap().clone()),
103
            deferred: self.deferred.clone(),
104
        }
105
    }
106
}
107
108
#[derive(Clone, Debug, PartialEq, Eq)]
109
pub enum FileContent {
110
    Text {
111
        bytes: Vec<u8>,
112
        materialized: Materialized,
113
    },
114
    /// Live blobs; more than one is a replace conflict (spec §9.3).
115
    Opaque {
116
        blobs: Vec<ObjectRef>,
117
    },
118
    Dir,
119
}
120
121
#[derive(Clone, Debug, PartialEq, Eq)]
122
pub struct FileState {
123
    pub node: NodeId,
124
    pub kind: NodeKind,
125
    pub mode: Mode,
126
    pub content: FileContent,
127
}
128
129
impl FileState {
130
    pub fn is_conflicted(&self) -> bool {
131
        match &self.content {
132
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
133
            FileContent::Opaque { blobs } => blobs.len() > 1,
134
            FileContent::Dir => false,
135
        }
136
    }
137
}
138
139
/// See `State::conflict_regions`.
140
#[derive(Clone, Debug, Default, PartialEq, Eq)]
141
pub struct ConflictRegions {
142
    pub plain: Vec<(AtomKey, Vec<u8>)>,
143
    pub region_atoms: Vec<AtomKey>,
144
    pub contributors: Vec<ChangeHash>,
145
}
146
147
/// The whole tree of a state, materialized.
148
#[derive(Clone, Debug, Default)]
149
pub struct Snapshot {
150
    pub tree: TreeView,
151
    pub files: BTreeMap<String, FileState>,
152
    /// Text files left unrendered by [`State::materialize_except`]: their
153
    /// `bytes` are empty and they are known not to be conflicted.
154
    pub unrendered: BTreeSet<String>,
155
}
156
157
impl Snapshot {
158
    pub fn is_conflicted(&self) -> bool {
159
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
160
    }
161
}
162
163
fn vertex(r: AtomRef) -> Vertex {
164
    match r {
165
        AtomRef::Start => Vertex::Start,
166
        AtomRef::End => Vertex::End,
167
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
168
    }
169
}
170
171
/// Replace self references in a tree op with the concrete change hash.
172
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
173
    match op {
174
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
175
            node: *node,
176
            placement: placement.resolve(me),
177
        },
178
        TreeOp::Move {
179
            node,
180
            old,
181
            parent,
182
            name,
183
        } => TreeOp::Move {
184
            node: *node,
185
            old: old.resolve(me),
186
            parent: *parent,
187
            name: name.clone(),
188
        },
189
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
190
            node: *node,
191
            old: old.resolve(me),
192
            mode: *mode,
193
        },
194
        add @ TreeOp::AddNode { .. } => add.clone(),
195
    }
196
}
197
198
/// Apply one change's edits of one file (inserts and deletes; replaces
199
/// live beside the graphs) to that file's graph.
200
fn apply_file_edits(g: &mut FileGraph, h: ChangeHash, edits: Vec<Edit>) {
201
    let mut next = 0u32;
202
    for e in edits {
203
        match e {
204
            Edit::Insert {
205
                after,
206
                before,
207
                lines,
208
                ..
209
            } => {
210
                let first = next;
211
                next += lines.len() as u32;
212
                g.insert_owned(
213
                    h,
214
                    first,
215
                    vertex(after.resolve(h)),
216
                    vertex(before.resolve(h)),
217
                    lines,
218
                );
219
            }
220
            Edit::Delete { atoms, .. } => {
221
                for r in atoms {
222
                    g.delete(h, &r.resolve(h));
223
                }
224
            }
225
            Edit::Replace { .. } => {}
226
        }
227
    }
228
}
229
230
impl State {
231
    pub fn new() -> Self {
232
        Self::default()
233
    }
234
235
    /// An empty state for history only: changes and tree are kept, file
236
    /// edits are recorded but no file graph is built until
237
    /// [`State::load_graphs`] asks for it. For log and other commands that
238
    /// need no file contents, or only a few files.
239
    pub fn new_history_only() -> Self {
240
        State {
241
            deferred: Some(HashMap::new()),
242
            ..Self::default()
243
        }
244
    }
245
246
    /// Whether this state builds file graphs only when asked
247
    /// ([`State::new_history_only`]), even if it has none waiting.
248
    pub fn is_history_only(&self) -> bool {
249
        self.deferred.is_some()
250
    }
251
252
    /// Whether this state holds every file graph.
253
    pub fn is_full(&self) -> bool {
254
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
255
    }
256
257
    /// The graph of `node`, which must be loaded: asking a history-only
258
    /// state for a graph it has not built is a bug, never an empty file.
259
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
260
        if let Some(d) = &self.deferred {
261
            assert!(
262
                !d.contains_key(node),
263
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
264
                node.short(12)
265
            );
266
        }
267
        self.files.get(node).map(|g| g.as_ref())
268
    }
269
270
    /// Operations over every file need every graph.
271
    fn require_full(&self, what: &str) {
272
        assert!(
273
            self.is_full(),
274
            "{what} needs every file graph; this state was loaded for history only"
275
        );
276
    }
277
278
    /// Build the graphs of `nodes` in a history-only state: from their
279
    /// checkpoint base (blobs read in one batch through `load`) and their
280
    /// deferred edits. Nodes already built, or with no graph, are skipped.
281
    pub fn load_graphs(
282
        &mut self,
283
        nodes: &[NodeId],
284
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
285
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
286
    ) -> Result<(), ObjectError> {
287
        let Some(deferred) = self.deferred.as_mut() else {
288
            return Ok(());
289
        };
290
        let mut taken: Vec<(NodeId, Deferred)> = nodes
291
            .iter()
292
            .filter_map(|n| deferred.remove(n).map(|d| (*n, d)))
293
            .collect();
294
        let mut refs: Vec<ObjectRef> = taken
295
            .iter()
296
            .filter_map(|(_, d)| match &d.base {
297
                Some(DeferredBase::Blob(r)) => Some(*r),
298
                _ => None,
299
            })
300
            .collect();
301
        // Text blobs of inserts read without their lines, after the bases.
302
        let bases = refs.len();
303
        refs.extend(taken.iter().flat_map(|(_, d)| {
304
            d.texts.iter().filter_map(|t| match t {
305
                TextRef::Blob(r, _) => Some(*r),
306
                TextRef::Inline { .. } => None,
307
            })
308
        }));
309
        // And the encodings of changes whose inline inserts are needed,
310
        // each read once.
311
        let mut changes: HashMap<ChangeHash, Arc<Vec<u8>>> = HashMap::new();
312
        for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
313
            if let TextRef::Inline { change, .. } = t {
314
                if !changes.contains_key(change) {
315
                    changes.insert(*change, read_change(change)?);
316
                }
317
            }
318
        }
319
        let mut blobs = if refs.is_empty() {
320
            Vec::new()
321
        } else {
322
            load(&refs)?
323
        };
324
        if blobs.len() != refs.len() {
325
            return Err(ObjectError::Schema("graph blobs: wrong count".into()));
326
        }
327
        let mut texts = blobs.split_off(bases).into_iter();
328
        let mut blobs = blobs.into_iter();
329
        // Pair each graph with its blob, then build them all in parallel:
330
        // graphs are independent.
331
        let mut work: Vec<(NodeId, Deferred, Option<Vec<u8>>)> = Vec::with_capacity(taken.len());
332
        for (node, mut d) in taken.drain(..) {
333
            // Fill in the lines of inserts read without them, in order.
334
            let mut want = std::mem::take(&mut d.texts).into_iter();
335
            for (_, edits) in d.edits.iter_mut() {
336
                for e in edits.iter_mut() {
337
                    if let Edit::Insert { lines, .. } = e {
338
                        if lines.is_empty() {
339
                            *lines = match want.next() {
340
                                Some(TextRef::Blob(_, count)) => {
341
                                    let content = texts.next().ok_or_else(|| {
342
                                        ObjectError::Schema("text blobs: wrong count".into())
343
                                    })?;
344
                                    crate::objects::text_lines(&content, count)?
345
                                }
346
                                Some(TextRef::Inline { change, start, end }) => {
347
                                    let bytes = &changes[&change];
348
                                    let range = bytes
349
                                        .get(start as usize..end as usize)
350
                                        .ok_or_else(|| {
351
                                            ObjectError::Schema(
352
                                                "an inline insert lies outside its change".into(),
353
                                            )
354
                                        })?;
355
                                    crate::objects::inline_lines(range)?
356
                                }
357
                                None => {
358
                                    return Err(ObjectError::Schema(
359
                                        "an insert's text is missing".into(),
360
                                    ))
361
                                }
362
                            };
363
                        }
364
                    }
365
                }
366
            }
367
            let bytes = match &d.base {
368
                Some(DeferredBase::Blob(_)) => Some(
369
                    blobs
370
                        .next()
371
                        .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
372
                ),
373
                _ => None,
374
            };
375
            work.push((node, d, bytes));
376
        }
377
        use rayon::prelude::*;
378
        let built: Vec<(NodeId, FileGraph)> = work
379
            .into_par_iter()
380
            .map(|(node, mut d, bytes)| {
381
                let mut graph = match (d.base.take(), bytes) {
382
                    (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
383
                    (Some(DeferredBase::Blob(_)), Some(bytes)) => {
384
                        FileGraph::from_value(&cbor::decode(&bytes)?)?
385
                    }
386
                    _ => FileGraph::default(),
387
                };
388
                for (h, edits) in std::mem::take(&mut d.edits) {
389
                    apply_file_edits(&mut graph, h, edits);
390
                }
391
                Ok((node, graph))
392
            })
393
            .collect::<Result<_, ObjectError>>()?;
394
        self.files
395
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
396
        Ok(())
397
    }
398
399
    /// Every file graph a history-only state has not built, deleted files'
400
    /// included.
401
    pub fn unbuilt_nodes(&self) -> Vec<NodeId> {
402
        self.deferred
403
            .as_ref()
404
            .map(|d| d.keys().copied().collect())
405
            .unwrap_or_default()
406
    }
407
408
    /// Drop the built graphs of `nodes`, for a caller rendering a large
409
    /// tree a batch at a time. The state can no longer render those files,
410
    /// so it must not be used for them again.
411
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
412
        for n in nodes {
413
            self.files.remove(n);
414
        }
415
    }
416
417
    /// Build every graph a history-only state has not built, making it full.
418
    pub fn load_all_graphs(
419
        &mut self,
420
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
421
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
422
    ) -> Result<(), ObjectError> {
423
        let nodes: Vec<NodeId> = match &self.deferred {
424
            Some(d) => d.keys().copied().collect(),
425
            None => return Ok(()),
426
        };
427
        self.load_graphs(&nodes, load, read_change)?;
428
        self.deferred = None;
429
        Ok(())
430
    }
431
432
    /// A key for the graph of `node` in a history-only state that has not
433
    /// built it: equal keys mean equal graphs, so equal renderings (a
434
    /// rendering depends only on the graph and on the changes' own
435
    /// immutable metadata). It names the node, its checkpoint base (a blob,
436
    /// an inline value, or none) and the set of later changes that edited
437
    /// the file.
438
    /// `None` for a full state or a graph already built.
439
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
440
        let deferred = self.deferred.as_ref()?;
441
        if self.files.contains_key(node) {
442
            return None;
443
        }
444
        let mut h = blake3::Hasher::new();
445
        h.update(b"oxy graph key 1\0");
446
        // A change's edits are applied per node: the node is part of it.
447
        h.update(&node.0);
448
        let Some(d) = deferred.get(node) else {
449
            // Never edited: the empty graph.
450
            h.update(&[0]);
451
            return Some(*h.finalize().as_bytes());
452
        };
453
        match &d.base {
454
            None => h.update(&[0]),
455
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
456
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
457
        };
458
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
459
        changes.sort();
460
        changes.dedup();
461
        h.update(&(changes.len() as u64).to_le_bytes());
462
        for c in changes {
463
            h.update(&c.0);
464
        }
465
        Some(*h.finalize().as_bytes())
466
    }
467
468
    pub fn len(&self) -> usize {
469
        self.changes.len()
470
    }
471
    pub fn is_empty(&self) -> bool {
472
        self.changes.is_empty()
473
    }
474
    pub fn contains(&self, h: &ChangeHash) -> bool {
475
        self.changes.contains_key(h)
476
    }
477
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
478
        self.changes.get(h)
479
    }
480
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
481
        self.changes.iter()
482
    }
483
    pub fn tree(&self) -> &TreeGraph {
484
        &self.tree
485
    }
486
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
487
        self.graph(node)
488
    }
489
490
    /// Add a change whose dependencies are already present.
491
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
492
        let h = change.hash();
493
        self.add_hashed(h, change)
494
    }
495
496
    /// [`State::add`] for a change whose hash `h` is already known (it was
497
    /// just stored), so it is not encoded again.
498
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
499
        if self.changes.contains_key(&h) {
500
            return Ok(h);
501
        }
502
        for d in &change.deps {
503
            if !self.changes.contains_key(d) {
504
                return Err(StateError::MissingDep(*d, h));
505
            }
506
        }
507
        self.add_known(h, change, Vec::new());
508
        Ok(h)
509
    }
510
511
    /// Add a change in any order; call `validate` once all are in.
512
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
513
        let h = change.hash();
514
        self.add_known(h, change, Vec::new());
515
        h
516
    }
517
518
    /// Add a change just stored under hash `h` to a history-only state that
519
    /// has built some graphs: an edit of a built graph is applied whole
520
    /// (from `full`), and one of a file not built waits without its text
521
    /// (from `skeleton` and its `texts`, as the store reads it back), so the
522
    /// state holds no text it has not built. A Git import adds each change
523
    /// it makes this way, keeping memory to what changes.
524
    pub fn add_known_mixed(
525
        &mut self,
526
        h: ChangeHash,
527
        full: Change,
528
        skeleton: Change,
529
        texts: Vec<TextRef>,
530
    ) {
531
        if self.deferred.is_none() || self.changes.contains_key(&h) {
532
            self.add_known(h, full, Vec::new());
533
            return;
534
        }
535
        let Change {
536
            version,
537
            change_id,
538
            deps,
539
            author,
540
            hlc,
541
            message,
542
            tree_ops,
543
            edits: full_edits,
544
            kind,
545
        } = full;
546
        let mut texts = texts.into_iter();
547
        let mut edits = Vec::with_capacity(full_edits.len());
548
        let mut kept = Vec::new();
549
        for (f, s) in full_edits.into_iter().zip(skeleton.edits) {
550
            let text = match &s {
551
                Edit::Insert { lines, .. } if lines.is_empty() => texts.next(),
552
                _ => None,
553
            };
554
            if self.files.contains_key(&f.node()) {
555
                edits.push(f);
556
            } else {
557
                edits.push(s);
558
                kept.extend(text);
559
            }
560
        }
561
        let c = Change {
562
            version,
563
            change_id,
564
            deps,
565
            author,
566
            hlc,
567
            message,
568
            tree_ops,
569
            edits,
570
            kind,
571
        };
572
        self.add_known(h, c, kept);
573
    }
574
575
    /// Add a change read from the store under hash `h`, without hashing it
576
    /// again (for a version 2 change that means chunking all its text).
577
    /// `texts` names, in order, the inserts left without their lines (see
578
    /// [`crate::store::Store::get_change_lazy`]); only a history-only state
579
    /// takes them, and only for graphs it has not built.
580
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
581
        if self.changes.contains_key(&h) {
582
            return;
583
        }
584
        let meta = ChangeMeta::of(&change);
585
        self.apply_with(h, change, texts);
586
        self.changes.insert(h, meta);
587
        self.closure.lock().unwrap().clear();
588
    }
589
590
    // ------------------------------------------------------------ checkpoints (spec §11)
591
592
    /// Serialize the whole state in payload version 1: change metadata,
593
    /// tree, file graphs, replaces, all in one value (spec §11).
594
    pub fn checkpoint_payload(&self) -> Vec<u8> {
595
        self.require_full("a checkpoint");
596
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
597
        nodes.sort();
598
        let files = Value::Array(
599
            nodes
600
                .into_iter()
601
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
602
                .collect(),
603
        );
604
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
605
    }
606
607
    /// Each file graph encoded on its own, by node, for a version 2 payload
608
    /// (spec §11): the graphs of large files become blobs of their own.
609
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
610
        use rayon::prelude::*;
611
        self.require_full("a checkpoint");
612
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
613
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
614
        nodes.sort_by_key(|(n, _)| **n);
615
        nodes
616
            .into_par_iter()
617
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
618
            .collect()
619
    }
620
621
    /// The payload version 2 index for the graphs of
622
    /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than
623
    /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by
624
    /// `blob_of` (the ObjectRef of the blob holding its encoding).
625
    pub fn checkpoint_index(
626
        &self,
627
        graphs: &[(NodeId, Vec<u8>)],
628
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
629
    ) -> Vec<u8> {
630
        let files = Value::Array(
631
            graphs
632
                .iter()
633
                .map(|(n, enc)| {
634
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
635
                        cbor::decode(enc).expect("an encoded graph decodes")
636
                    } else {
637
                        Value::Bytes(blob_of(enc).0.to_vec())
638
                    };
639
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
640
                })
641
                .collect(),
642
        );
643
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
644
    }
645
646
    /// The payload map around `files`: changes, tree and replaces as in version 1.
647
    fn payload_value(&self, version: u64, files: Value) -> Value {
648
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
649
        hashes.sort();
650
        let changes = Value::Array(
651
            hashes
652
                .into_iter()
653
                .map(|h| {
654
                    let m = &self.changes[h];
655
                    Value::Array(vec![
656
                        Value::Bytes(h.0.to_vec()),
657
                        Value::Bytes(m.change_id.0.to_vec()),
658
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
659
                        Value::Text(m.message.clone()),
660
                        Value::Uint(m.hlc.wall_ms),
661
                        Value::Uint(m.hlc.logical as u64),
662
                        Value::Uint(m.kind.tag()),
663
                        Value::Bytes(m.author.0.to_vec()),
664
                    ])
665
                })
666
                .collect(),
667
        );
668
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
669
        rnodes.sort();
670
        let opt =
671
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
672
        let replaces = Value::Array(
673
            rnodes
674
                .into_iter()
675
                .map(|n| {
676
                    Value::Array(vec![
677
                        Value::Bytes(n.0.to_vec()),
678
                        Value::Array(
679
                            self.replaces[n]
680
                                .iter()
681
                                .map(|(c, o, nw)| {
682
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
683
                                })
684
                                .collect(),
685
                        ),
686
                    ])
687
                })
688
                .collect(),
689
        );
690
        Value::map([
691
            (0, Value::Uint(version)),
692
            (1, changes),
693
            (2, self.tree.to_value()),
694
            (3, files),
695
            (4, replaces),
696
        ])
697
    }
698
699
    /// Decode a version 1 payload (the whole state in one value). A
700
    /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`].
701
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
702
        State::from_checkpoint(bytes, |_| {
703
            Err(ObjectError::Schema(
704
                "a version 2 checkpoint needs its graph blobs".into(),
705
            ))
706
        })
707
    }
708
709
    /// Decode a checkpoint payload of either version (spec §11). For
710
    /// version 2, `load` returns the contents of the named graph blobs, in
711
    /// order; the graphs are then decoded in parallel.
712
    pub fn from_checkpoint(
713
        bytes: &[u8],
714
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
715
    ) -> Result<State, ObjectError> {
716
        use rayon::prelude::*;
717
        let v = cbor::decode(bytes)?;
718
        let m = o::map(&v, "checkpoint payload")?;
719
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
720
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
721
            return Err(ObjectError::Schema(format!(
722
                "checkpoint payload version {version} is not supported"
723
            )));
724
        }
725
        let mut st = State::payload_common(m)?;
726
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
727
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
728
        for f in entries {
729
            let e = o::array(f, "file")?;
730
            if e.len() != 2 {
731
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
732
            }
733
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
734
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
735
            parsed.push((node, &e[1]));
736
        }
737
        // Version 2 names large graphs by blob: fetch those in one batch.
738
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
739
        if version == CHECKPOINT_INDEX_VERSION {
740
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
741
                .iter()
742
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
743
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
744
                .collect::<Result<_, ObjectError>>()?;
745
            if !wanted.is_empty() {
746
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
747
                let contents = {
748
                    let _t = crate::timing::phase("load:   graph blobs read");
749
                    load(&refs)?
750
                };
751
                if contents.len() != refs.len() {
752
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
753
                }
754
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
755
            }
756
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
757
            return Err(ObjectError::Schema(
758
                "a version 1 payload holds graphs inline".into(),
759
            ));
760
        }
761
        // File graphs are independent; decode and build them in parallel.
762
        let graphs = parsed
763
            .par_iter()
764
            .map(|(node, entry)| {
765
                let graph = match fetched.get(node) {
766
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
767
                    None => FileGraph::from_value(entry)?,
768
                };
769
                Ok((*node, graph))
770
            })
771
            .collect::<Result<Vec<_>, ObjectError>>()?;
772
        st.files
773
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
774
        Ok(st)
775
    }
776
777
    /// The graph blobs a payload names: empty for version 1.
778
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
779
        let v = cbor::decode(bytes)?;
780
        let m = o::map(&v, "checkpoint payload")?;
781
        let mut out = Vec::new();
782
        for f in o::array(o::field(m, 3, "files")?, "files")? {
783
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
784
                out.push(o::oref(entry, "graph blob")?);
785
            }
786
        }
787
        Ok(out)
788
    }
789
790
    /// Decode a checkpoint payload for history only: a version 2 payload's
791
    /// graphs are noted, not read or built, and come later through
792
    /// [`State::load_graphs`]. A version 1 payload holds them inline and is
793
    /// decoded in full.
794
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
795
        let v = cbor::decode(bytes)?;
796
        let m = o::map(&v, "checkpoint payload")?;
797
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
798
        if version != CHECKPOINT_INDEX_VERSION {
799
            return State::from_checkpoint_payload(bytes);
800
        }
801
        let mut st = State::payload_common(m)?;
802
        let mut deferred = HashMap::new();
803
        for f in o::array(o::field(m, 3, "files")?, "files")? {
804
            let e = o::array(f, "file")?;
805
            if e.len() != 2 {
806
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
807
            }
808
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
809
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
810
            let base = match &e[1] {
811
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
812
                other => DeferredBase::Inline(other.clone()),
813
            };
814
            deferred.insert(
815
                node,
816
                Deferred {
817
                    base: Some(base),
818
                    edits: Vec::new(),
819
                    texts: Vec::new(),
820
                },
821
            );
822
        }
823
        st.deferred = Some(deferred);
824
        Ok(st)
825
    }
826
827
    /// Changes, tree and replaces of a payload of either version.
828
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
829
        let mut st = State::new();
830
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
831
            let e = o::array(c, "change meta")?;
832
            if e.len() != 8 {
833
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
834
            }
835
            let hash = o::oref(&e[0], "hash")?;
836
            let meta = ChangeMeta {
837
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
838
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
839
                deps: o::array(&e[2], "deps")?
840
                    .iter()
841
                    .map(|d| o::oref(d, "dep"))
842
                    .collect::<Result<Vec<_>, _>>()?,
843
                message: o::text(&e[3], "message")?.to_owned(),
844
                hlc: Hlc {
845
                    wall_ms: o::uint(&e[4], "wall")?,
846
                    logical: o::u32_(&e[5], "logical")?,
847
                },
848
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
849
                author: o::oref(&e[7], "author")?,
850
            };
851
            st.changes.insert(hash, meta);
852
        }
853
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
854
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
855
            if v.is_null() {
856
                Ok(None)
857
            } else {
858
                o::oref(v, "blob").map(Some)
859
            }
860
        };
861
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
862
            let e = o::array(r, "replace")?;
863
            if e.len() != 2 {
864
                return Err(ObjectError::Schema(
865
                    "replace: expected [node, records]".into(),
866
                ));
867
            }
868
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
869
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
870
            let mut recs = Vec::new();
871
            for rec in o::array(&e[1], "records")? {
872
                let x = o::array(rec, "record")?;
873
                if x.len() != 3 {
874
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
875
                }
876
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
877
            }
878
            st.replaces.insert(node, recs);
879
        }
880
        Ok(st)
881
    }
882
883
    pub fn validate(&self) -> Result<(), StateError> {
884
        for (h, c) in &self.changes {
885
            for d in &c.deps {
886
                if !self.changes.contains_key(d) {
887
                    return Err(StateError::MissingDep(*d, *h));
888
                }
889
            }
890
        }
891
        Ok(())
892
    }
893
894
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
895
        for (i, op) in c.tree_ops.iter().enumerate() {
896
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
897
        }
898
        if let Some(deferred) = self.deferred.as_mut() {
899
            // History only: edits of files not built wait, grouped per file,
900
            // with the texts of inserts read without their lines.
901
            let mut texts = texts.into_iter();
902
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
903
            for e in c.edits {
904
                match e {
905
                    Edit::Replace { node, old, new } => {
906
                        self.replaces.entry(node).or_default().push((h, old, new))
907
                    }
908
                    e => {
909
                        let slot = per_node.entry(e.node()).or_default();
910
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
911
                            slot.1.extend(texts.next());
912
                        }
913
                        slot.0.push(e);
914
                    }
915
                }
916
            }
917
            for (node, (edits, node_texts)) in per_node {
918
                match self.files.get_mut(&node) {
919
                    Some(g) => {
920
                        assert!(
921
                            node_texts.is_empty(),
922
                            "a change read without its text applied to a built graph"
923
                        );
924
                        apply_file_edits(Arc::make_mut(g), h, edits)
925
                    }
926
                    None => {
927
                        let d = deferred.entry(node).or_default();
928
                        d.edits.push((h, edits));
929
                        d.texts.extend(node_texts);
930
                    }
931
                }
932
            }
933
            return;
934
        }
935
        assert!(
936
            texts.is_empty(),
937
            "a change read without its text applied to a full state"
938
        );
939
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
940
        for e in c.edits {
941
            match e {
942
                Edit::Insert {
943
                    node,
944
                    after,
945
                    before,
946
                    lines,
947
                } => {
948
                    let idx = counters.entry(node).or_default();
949
                    let first = *idx;
950
                    *idx += lines.len() as u32;
951
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
952
                        h,
953
                        first,
954
                        vertex(after.resolve(h)),
955
                        vertex(before.resolve(h)),
956
                        lines,
957
                    );
958
                }
959
                Edit::Delete { node, atoms } => {
960
                    let g = Arc::make_mut(self.files.entry(node).or_default());
961
                    for r in atoms {
962
                        g.delete(h, &r.resolve(h));
963
                    }
964
                }
965
                Edit::Replace { node, old, new } => {
966
                    self.replaces.entry(node).or_default().push((h, old, new));
967
                }
968
            }
969
        }
970
    }
971
972
    /// Transitive dependencies of `h`, excluding `h` itself.
973
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
974
        if let Some(c) = self.closure.lock().unwrap().get(h) {
975
            return c.clone();
976
        }
977
        let mut out = HashSet::new();
978
        let mut stack: Vec<ChangeHash> = self
979
            .changes
980
            .get(h)
981
            .map(|c| c.deps.clone())
982
            .unwrap_or_default();
983
        while let Some(d) = stack.pop() {
984
            if out.insert(d) {
985
                if let Some(c) = self.changes.get(&d) {
986
                    stack.extend(c.deps.iter().copied());
987
                }
988
            }
989
        }
990
        let rc = Arc::new(out);
991
        self.closure.lock().unwrap().insert(*h, rc.clone());
992
        rc
993
    }
994
995
    /// Changes that no other change depends on directly, sorted.
996
    pub fn heads(&self) -> Vec<ChangeHash> {
997
        let depended: HashSet<&ChangeHash> =
998
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
999
        let mut heads: Vec<ChangeHash> = self
1000
            .changes
1001
            .keys()
1002
            .filter(|h| !depended.contains(h))
1003
            .copied()
1004
            .collect();
1005
        heads.sort();
1006
        heads
1007
    }
1008
1009
    /// Maximal elements among `hashes` (those not in the closure of another),
1010
    /// sorted. One walk down from all of them at once: whatever the walk
1011
    /// reaches is below some other element. Linear in the changes reached,
1012
    /// where comparing every pair's closures was quadratic in the number
1013
    /// of heads, which a bookmark of independent changes has many of.
1014
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
1015
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
1016
        let mut below: HashSet<ChangeHash> = HashSet::new();
1017
        let mut stack: Vec<ChangeHash> = set
1018
            .iter()
1019
            .filter_map(|h| self.changes.get(h))
1020
            .flat_map(|c| c.deps.iter().copied())
1021
            .collect();
1022
        while let Some(d) = stack.pop() {
1023
            if below.insert(d) {
1024
                if let Some(c) = self.changes.get(&d) {
1025
                    stack.extend(c.deps.iter().copied());
1026
                }
1027
            }
1028
        }
1029
        set.into_iter().filter(|h| !below.contains(h)).collect()
1030
    }
1031
1032
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
1033
        self.graph(node)
1034
            .map(|g| g.materialize(self))
1035
            .unwrap_or_default()
1036
    }
1037
1038
    /// Live lines of a text node in materialized order.
1039
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
1040
        let Some(g) = self.graph(node) else {
1041
            return vec![];
1042
        };
1043
        let m = g.materialize(self);
1044
        m.live_atoms()
1045
            .into_iter()
1046
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
1047
            .collect()
1048
    }
1049
1050
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
1051
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
1052
        let mut live: Vec<ObjectRef> = self
1053
            .live_replaces(node)
1054
            .into_iter()
1055
            .map(|(_, n)| n)
1056
            .collect();
1057
        live.sort();
1058
        live.dedup();
1059
        live
1060
    }
1061
1062
    /// The replace records whose blob is live, with the change that set it
1063
    /// (spec §9.3). A record's blob is superseded by a later replacement of
1064
    /// that blob: one whose change depends on the record's change, as every
1065
    /// replacement depends on the change that made its old blob current
1066
    /// (§8.1). Two replacements that do not know each other both stay live
1067
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
1068
    /// A replacement without that dependency, from before the rule, is read
1069
    /// as before: it supersedes every record that did not come after it.
1070
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
1071
        let Some(rs) = self.replaces.get(node) else {
1072
            return vec![];
1073
        };
1074
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
1075
            rs.iter()
1076
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && self.closure(s).contains(q))
1077
        };
1078
        rs.iter()
1079
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
1080
            .filter(|(c, n)| {
1081
                !rs.iter().any(|(s, o, _)| {
1082
                    s != c
1083
                        && *o == Some(*n)
1084
                        && (self.closure(s).contains(c)
1085
                            || (!knows_its_old(s, n) && !self.closure(c).contains(s)))
1086
                })
1087
            })
1088
            .collect()
1089
    }
1090
1091
    /// Short label for conflict markers: `changeid-prefix "message"`.
1092
    pub fn label(&self, h: &ChangeHash) -> String {
1093
        match self.changes.get(h) {
1094
            Some(c) => format!(
1095
                "{} \"{}\"",
1096
                c.change_id.short(8),
1097
                c.message.lines().next().unwrap_or("")
1098
            ),
1099
            None => format!("#{}", h.short(12)),
1100
        }
1101
    }
1102
1103
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1104
    /// are not part of any conflict region in order, every live atom that is
1105
    /// part of a region, and every change that contributed to a region.
1106
    /// The changes that introduced the live blobs of an opaque node, for a
1107
    /// replace conflict (spec §9.3).
1108
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
1109
        let mut out: Vec<ChangeHash> = Vec::new();
1110
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
1111
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
1112
                out.push(*h);
1113
            }
1114
        }
1115
        out.sort();
1116
        out
1117
    }
1118
1119
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
1120
        let mut out = ConflictRegions::default();
1121
        let Some(g) = self.graph(node) else {
1122
            return out;
1123
        };
1124
        let m = g.materialize(self);
1125
        let mut contributors = BTreeSet::new();
1126
        for seg in &m.segments {
1127
            match seg {
1128
                crate::graph::Segment::Lines(atoms) => {
1129
                    for a in atoms {
1130
                        out.plain
1131
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
1132
                    }
1133
                }
1134
                crate::graph::Segment::Conflict(sides) => {
1135
                    for side in sides {
1136
                        for a in side {
1137
                            out.region_atoms.push(*a);
1138
                            contributors.insert(a.0);
1139
                        }
1140
                    }
1141
                }
1142
                crate::graph::Segment::Zombie { deleted, inserted } => {
1143
                    for a in deleted {
1144
                        contributors.insert(a.0);
1145
                        contributors.extend(g.deleters(a).copied());
1146
                    }
1147
                    for a in inserted {
1148
                        out.region_atoms.push(*a);
1149
                        contributors.insert(a.0);
1150
                    }
1151
                }
1152
            }
1153
        }
1154
        out.contributors = contributors.into_iter().collect();
1155
        out
1156
    }
1157
1158
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
1159
        let Some(g) = self.graph(node) else {
1160
            return (Vec::new(), Materialized::default());
1161
        };
1162
        let m = g.materialize(self);
1163
        let bytes = g.render(&m, &|h| self.label(h));
1164
        (bytes, m)
1165
    }
1166
1167
    /// Every file rendered, in parallel: files are independent, and
1168
    /// rendering them is most of a snapshot's cost in a large tree.
1169
    pub fn materialize(&self) -> Snapshot {
1170
        use rayon::prelude::*;
1171
        self.require_full("materializing a state");
1172
        let tree = self.tree.view();
1173
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
1174
        let rendered: Vec<(String, FileState)> = entries
1175
            .par_iter()
1176
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
1177
            .collect();
1178
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
1179
        Snapshot {
1180
            tree,
1181
            files,
1182
            unrendered: BTreeSet::new(),
1183
        }
1184
    }
1185
1186
    /// Like [`State::materialize`], leaving the text files of nodes in
1187
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
1188
    /// file's graph must be loaded. For a caller that already knows those
1189
    /// files are unchanged and not conflicted.
1190
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
1191
        self.materialize_leaving(|_, e| skip.contains(&e.node))
1192
    }
1193
1194
    /// As [`State::materialize_except`], rendering only the text files at
1195
    /// `render` (a few, where the caller knows the rest unchanged).
1196
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
1197
        self.materialize_leaving(|p, _| !render.contains(p))
1198
    }
1199
1200
    fn materialize_leaving(
1201
        &self,
1202
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
1203
    ) -> Snapshot {
1204
        use rayon::prelude::*;
1205
        let tree = self.tree.view();
1206
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
1207
        let rendered: Vec<(String, FileState, bool)> = entries
1208
            .par_iter()
1209
            .map(|(path, e)| {
1210
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
1211
                    let f = FileState {
1212
                        node: e.node,
1213
                        kind: e.kind,
1214
                        mode: e.mode,
1215
                        content: FileContent::Text {
1216
                            bytes: Vec::new(),
1217
                            materialized: Materialized::default(),
1218
                        },
1219
                    };
1220
                    (path.to_string(), f, true)
1221
                } else {
1222
                    (path.to_string(), self.file_state(e), false)
1223
                }
1224
            })
1225
            .collect();
1226
        let mut files = BTreeMap::new();
1227
        let mut unrendered = BTreeSet::new();
1228
        for (p, f, skipped) in rendered {
1229
            if skipped {
1230
                unrendered.insert(p.clone());
1231
            }
1232
            files.insert(p, f);
1233
        }
1234
        Snapshot {
1235
            tree,
1236
            files,
1237
            unrendered,
1238
        }
1239
    }
1240
1241
    /// A snapshot of only `paths` (those `view` has), `view` being this
1242
    /// state's tree view: for a caller that works from what changed. The
1243
    /// graphs of those text files must be loaded.
1244
    pub fn materialize_paths<'p>(
1245
        &self,
1246
        view: crate::tree::TreeView,
1247
        paths: impl IntoIterator<Item = &'p str>,
1248
    ) -> Snapshot {
1249
        let files = paths
1250
            .into_iter()
1251
            .filter_map(|p| Some((p.to_string(), self.file_state(view.entries.get(p)?))))
1252
            .collect();
1253
        Snapshot {
1254
            tree: view,
1255
            files,
1256
            unrendered: BTreeSet::new(),
1257
        }
1258
    }
1259
1260
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
1261
        {
1262
            let content = match e.kind {
1263
                NodeKind::Dir => FileContent::Dir,
1264
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
1265
                    blobs: self.live_blobs(&e.node),
1266
                },
1267
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
1268
                    blobs: self.live_blobs(&e.node),
1269
                },
1270
                NodeKind::File => {
1271
                    let (bytes, materialized) = self.render_file(&e.node);
1272
                    FileContent::Text {
1273
                        bytes,
1274
                        materialized,
1275
                    }
1276
                }
1277
            };
1278
            FileState {
1279
                node: e.node,
1280
                kind: e.kind,
1281
                mode: e.mode,
1282
                content,
1283
            }
1284
        }
1285
    }
1286
}
1287
1288
impl DepOracle for State {
1289
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
1290
        a == b || self.closure(a).contains(b)
1291
    }
1292
}
1293
1294
#[cfg(test)]
1295
mod tests {
1296
    use super::*;
1297
    use crate::ids::ChangeId;
1298
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
1299
1300
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
1301
        let mut c = Change {
1302
            version: crate::objects::CHANGE_VERSION,
1303
            change_id: ChangeId::random(),
1304
            deps,
1305
            author: ObjectRef::ZERO,
1306
            hlc: Hlc {
1307
                wall_ms: 1,
1308
                logical: 0,
1309
            },
1310
            message: "m".into(),
1311
            tree_ops,
1312
            edits,
1313
            kind: ChangeKind::Normal,
1314
        };
1315
        c.normalize();
1316
        c
1317
    }
1318
1319
    #[test]
1320
    fn build_edit_and_materialize() {
1321
        let mut st = State::new();
1322
        let f = NodeId::random();
1323
        let c1 = change(
1324
            vec![],
1325
            vec![TreeOp::AddNode {
1326
                node: f,
1327
                kind: NodeKind::File,
1328
                mode: Mode::TEXT,
1329
                parent: NodeId::ROOT,
1330
                name: "a.txt".into(),
1331
            }],
1332
            vec![Edit::Insert {
1333
                node: f,
1334
                after: AtomRef::Start,
1335
                before: AtomRef::End,
1336
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
1337
            }],
1338
        );
1339
        let h1 = st.add(c1).unwrap();
1340
        // Depends on h1: append a line and delete "one".
1341
        let c2 = change(
1342
            vec![h1],
1343
            vec![],
1344
            vec![
1345
                Edit::Delete {
1346
                    node: f,
1347
                    atoms: vec![AtomRange {
1348
                        change: h1,
1349
                        from: 0,
1350
                        to: 1,
1351
                    }],
1352
                },
1353
                Edit::Insert {
1354
                    node: f,
1355
                    after: AtomRef::Atom {
1356
                        change: h1,
1357
                        index: 1,
1358
                    },
1359
                    before: AtomRef::End,
1360
                    lines: vec![b"three\n".to_vec()].into(),
1361
                },
1362
            ],
1363
        );
1364
        let h2 = st.add(c2).unwrap();
1365
        assert_eq!(st.heads(), vec![h2]);
1366
        assert!(st.depends_on(&h2, &h1));
1367
        assert!(!st.depends_on(&h1, &h2));
1368
        let snap = st.materialize();
1369
        assert!(!snap.is_conflicted());
1370
        let a = &snap.files["a.txt"];
1371
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
1372
        assert_eq!(st.live_lines(&f).len(), 2);
1373
    }
1374
1375
    #[test]
1376
    fn missing_dependency_is_rejected() {
1377
        let mut st = State::new();
1378
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
1379
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
1380
    }
1381
1382
    #[test]
1383
    fn self_references_and_multi_insert_indexing() {
1384
        let mut st = State::new();
1385
        let f = NodeId::random();
1386
        let me = OpRef {
1387
            change: ObjectRef::ZERO,
1388
            index: 0,
1389
        };
1390
        let c1 = change(
1391
            vec![],
1392
            vec![
1393
                TreeOp::AddNode {
1394
                    node: f,
1395
                    kind: NodeKind::File,
1396
                    mode: Mode::TEXT,
1397
                    parent: NodeId::ROOT,
1398
                    name: "x".into(),
1399
                },
1400
                TreeOp::SetMode {
1401
                    node: f,
1402
                    old: me,
1403
                    mode: Mode {
1404
                        exec: true,
1405
                        opaque: false,
1406
                    },
1407
                },
1408
            ],
1409
            vec![
1410
                Edit::Insert {
1411
                    node: f,
1412
                    after: AtomRef::Start,
1413
                    before: AtomRef::End,
1414
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
1415
                },
1416
                // Insert between the two lines just inserted, using self references.
1417
                Edit::Insert {
1418
                    node: f,
1419
                    after: AtomRef::Atom {
1420
                        change: ObjectRef::ZERO,
1421
                        index: 0,
1422
                    },
1423
                    before: AtomRef::Atom {
1424
                        change: ObjectRef::ZERO,
1425
                        index: 1,
1426
                    },
1427
                    lines: vec![b"b\n".to_vec()].into(),
1428
                },
1429
            ],
1430
        );
1431
        st.add(c1).unwrap();
1432
        let snap = st.materialize();
1433
        let x = &snap.files["x"];
1434
        assert_eq!(
1435
            x.mode,
1436
            Mode {
1437
                exec: true,
1438
                opaque: false
1439
            }
1440
        );
1441
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
1442
    }
1443
1444
    #[test]
1445
    fn opaque_replace_and_conflict() {
1446
        let mut st = State::new();
1447
        let f = NodeId::random();
1448
        let b1 = ObjectRef([1; 32]);
1449
        let b2 = ObjectRef([2; 32]);
1450
        let b3 = ObjectRef([3; 32]);
1451
        let h1 = st
1452
            .add(change(
1453
                vec![],
1454
                vec![TreeOp::AddNode {
1455
                    node: f,
1456
                    kind: NodeKind::File,
1457
                    mode: Mode::OPAQUE,
1458
                    parent: NodeId::ROOT,
1459
                    name: "img".into(),
1460
                }],
1461
                vec![Edit::Replace {
1462
                    node: f,
1463
                    old: None,
1464
                    new: Some(b1),
1465
                }],
1466
            ))
1467
            .unwrap();
1468
        assert_eq!(st.live_blobs(&f), vec![b1]);
1469
        st.add(change(
1470
            vec![h1],
1471
            vec![],
1472
            vec![Edit::Replace {
1473
                node: f,
1474
                old: Some(b1),
1475
                new: Some(b2),
1476
            }],
1477
        ))
1478
        .unwrap();
1479
        st.add(change(
1480
            vec![h1],
1481
            vec![],
1482
            vec![Edit::Replace {
1483
                node: f,
1484
                old: Some(b1),
1485
                new: Some(b3),
1486
            }],
1487
        ))
1488
        .unwrap();
1489
        let snap = st.materialize();
1490
        assert!(snap.is_conflicted());
1491
        assert!(
1492
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
1493
        );
1494
    }
1495
1496
    #[test]
1497
    fn checkpoint_payload_round_trip_and_replay() {
1498
        let mut st = State::new();
1499
        let f = NodeId::random();
1500
        let h1 = st
1501
            .add(change(
1502
                vec![],
1503
                vec![TreeOp::AddNode {
1504
                    node: f,
1505
                    kind: NodeKind::File,
1506
                    mode: Mode::TEXT,
1507
                    parent: NodeId::ROOT,
1508
                    name: "a".into(),
1509
                }],
1510
                vec![Edit::Insert {
1511
                    node: f,
1512
                    after: AtomRef::Start,
1513
                    before: AtomRef::End,
1514
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
1515
                }],
1516
            ))
1517
            .unwrap();
1518
        let h2 = st
1519
            .add(change(
1520
                vec![h1],
1521
                vec![],
1522
                vec![Edit::Delete {
1523
                    node: f,
1524
                    atoms: vec![AtomRange {
1525
                        change: h1,
1526
                        from: 0,
1527
                        to: 1,
1528
                    }],
1529
                }],
1530
            ))
1531
            .unwrap();
1532
        let payload = st.checkpoint_payload();
1533
        let back = State::from_checkpoint_payload(&payload).unwrap();
1534
        assert_eq!(back.len(), 2);
1535
        assert_eq!(back.heads(), vec![h2]);
1536
        assert_eq!(back.get(&h1).unwrap().message, "m");
1537
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
1538
        // Replaying a further change onto the restored state equals a full build.
1539
        let c3 = change(
1540
            vec![h2],
1541
            vec![],
1542
            vec![Edit::Insert {
1543
                node: f,
1544
                after: AtomRef::Atom {
1545
                    change: h1,
1546
                    index: 1,
1547
                },
1548
                before: AtomRef::End,
1549
                lines: vec![b"3\n".to_vec()].into(),
1550
            }],
1551
        );
1552
        let mut full = st.clone();
1553
        full.add(c3.clone()).unwrap();
1554
        let mut restored = back;
1555
        restored.add(c3).unwrap();
1556
        let (a, b) = (full.materialize(), restored.materialize());
1557
        assert_eq!(
1558
            a.files.keys().collect::<Vec<_>>(),
1559
            b.files.keys().collect::<Vec<_>>()
1560
        );
1561
        assert_eq!(a.files["a"].content, b.files["a"].content);
1562
        assert!(
1563
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
1564
        );
1565
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
1566
    }
1567
1568
    /// History-only states (O10f): the same state as a full load once its
1569
    /// graphs are built, by replay and from a version 2 checkpoint with
1570
    /// later changes; unloaded graphs are never read as empty.
1571
    #[test]
1572
    fn graph_keys_change_exactly_when_a_graph_does() {
1573
        let (f, g) = (NodeId::random(), NodeId::random());
1574
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1575
            node,
1576
            kind: NodeKind::File,
1577
            mode: Mode::TEXT,
1578
            parent: NodeId::ROOT,
1579
            name: name.into(),
1580
        };
1581
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
1582
            node,
1583
            after: AtomRef::Start,
1584
            before: AtomRef::End,
1585
            lines: vec![line.to_vec()].into(),
1586
        };
1587
        let c1 = change(
1588
            vec![],
1589
            vec![add(f, "f"), add(g, "g")],
1590
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
1591
        );
1592
        let h1 = c1.hash();
1593
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
1594
        let h2 = c2.hash();
1595
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
1596
        let load = |cs: &[&Change]| {
1597
            let mut st = State::new_history_only();
1598
            for c in cs {
1599
                st.add((*c).clone()).unwrap();
1600
            }
1601
            st
1602
        };
1603
        let s1 = load(&[&c1]);
1604
        let s2 = load(&[&c1, &c2]);
1605
        let s3 = load(&[&c1, &c2, &c3]);
1606
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
1607
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
1608
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
1609
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
1610
        assert_ne!(key(&s2, &f), key(&s3, &f));
1611
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
1612
        let mut built = load(&[&c1]);
1613
        built
1614
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
1615
            .unwrap();
1616
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
1617
        let mut full = State::new();
1618
        full.add(c1.clone()).unwrap();
1619
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
1620
1621
        // Through a version 2 checkpoint of c1, keys name its graph blobs
1622
        // or inline values: stable across loads, changed by later edits.
1623
        let graphs = full.checkpoint_file_graphs();
1624
        let index = full.checkpoint_index(&graphs, |enc| {
1625
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
1626
        });
1627
        let cp = |extra: &[&Change]| {
1628
            let mut st = State::from_checkpoint_history(&index).unwrap();
1629
            for c in extra {
1630
                st.add((*c).clone()).unwrap();
1631
            }
1632
            st
1633
        };
1634
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
1635
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
1636
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
1637
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
1638
1639
        // Partial rendering: skipped files are listed and empty, the others
1640
        // render as in a full state.
1641
        let mut part = load(&[&c1, &c2]);
1642
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
1643
            .unwrap();
1644
        let snap = part.materialize_except(&[f].into_iter().collect());
1645
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
1646
        let mut whole = State::new();
1647
        whole.add(c1.clone()).unwrap();
1648
        whole.add(c2.clone()).unwrap();
1649
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
1650
        assert!(
1651
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
1652
        );
1653
    }
1654
1655
    #[test]
1656
    fn history_only_states_build_the_same_graphs_on_demand() {
1657
        let small = NodeId::random();
1658
        let big = NodeId::random();
1659
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1660
            node,
1661
            kind: NodeKind::File,
1662
            mode: Mode::TEXT,
1663
            parent: NodeId::ROOT,
1664
            name: name.into(),
1665
        };
1666
        let lines: crate::lines::Lines = (0..300)
1667
            .map(|i| format!("line {i}\n").into_bytes())
1668
            .collect();
1669
        let c1 = change(
1670
            vec![],
1671
            vec![add(small, "small"), add(big, "big")],
1672
            vec![
1673
                Edit::Insert {
1674
                    node: small,
1675
                    after: AtomRef::Start,
1676
                    before: AtomRef::End,
1677
                    lines: vec![b"x\n".to_vec()].into(),
1678
                },
1679
                Edit::Insert {
1680
                    node: big,
1681
                    after: AtomRef::Start,
1682
                    before: AtomRef::End,
1683
                    lines,
1684
                },
1685
            ],
1686
        );
1687
        let h1 = c1.hash();
1688
        let c2 = change(
1689
            vec![h1],
1690
            vec![],
1691
            vec![
1692
                Edit::Delete {
1693
                    node: big,
1694
                    atoms: vec![AtomRange {
1695
                        change: h1,
1696
                        from: 2,
1697
                        to: 9,
1698
                    }],
1699
                },
1700
                Edit::Insert {
1701
                    node: big,
1702
                    after: AtomRef::Atom {
1703
                        change: h1,
1704
                        index: 20,
1705
                    },
1706
                    before: AtomRef::Atom {
1707
                        change: h1,
1708
                        index: 21,
1709
                    },
1710
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
1711
                },
1712
                Edit::Insert {
1713
                    node: small,
1714
                    after: AtomRef::Atom {
1715
                        change: h1,
1716
                        index: 0,
1717
                    },
1718
                    before: AtomRef::End,
1719
                    lines: vec![b"y\n".to_vec()].into(),
1720
                },
1721
            ],
1722
        );
1723
        let h2 = c2.hash();
1724
        let c3 = change(
1725
            vec![h2],
1726
            vec![],
1727
            vec![Edit::Delete {
1728
                node: small,
1729
                atoms: vec![AtomRange {
1730
                    change: h1,
1731
                    from: 0,
1732
                    to: 1,
1733
                }],
1734
            }],
1735
        );
1736
1737
        let mut full = State::new();
1738
        for c in [&c1, &c2, &c3] {
1739
            full.add(c.clone()).unwrap();
1740
        }
1741
        // By replay: nothing built until asked, then exactly the full graphs.
1742
        let mut hist = State::new_history_only();
1743
        for c in [&c1, &c2, &c3] {
1744
            hist.add(c.clone()).unwrap();
1745
        }
1746
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
1747
        assert_eq!(hist.len(), 3);
1748
        hist.load_graphs(
1749
            &[big],
1750
            |_| unreachable!("no checkpoint"),
1751
            |_| unreachable!(),
1752
        )
1753
        .unwrap();
1754
        assert_eq!(
1755
            hist.render_file(&big).0,
1756
            full.render_file(&big).0,
1757
            "one file on its own"
1758
        );
1759
        assert!(!hist.is_full());
1760
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
1761
            .unwrap();
1762
        assert!(hist.is_full());
1763
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
1764
1765
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
1766
        let mut base = State::new();
1767
        base.add(c1.clone()).unwrap();
1768
        base.add(c2.clone()).unwrap();
1769
        let graphs = base.checkpoint_file_graphs();
1770
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
1771
        let index = base.checkpoint_index(&graphs, |enc| {
1772
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
1773
            blobs.insert(r, enc.to_vec());
1774
            r
1775
        });
1776
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
1777
        from_cp.add(c3.clone()).unwrap();
1778
        assert!(!from_cp.is_full());
1779
        let mut fetched = 0;
1780
        from_cp
1781
            .load_graphs(
1782
                &[small, big],
1783
                |refs| {
1784
                    fetched += refs.len();
1785
                    refs.iter()
1786
                        .map(|r| {
1787
                            blobs
1788
                                .get(r)
1789
                                .cloned()
1790
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
1791
                        })
1792
                        .collect()
1793
                },
1794
                |_| unreachable!(),
1795
            )
1796
            .unwrap();
1797
        assert_eq!(
1798
            fetched, 1,
1799
            "the large graph's blob, in one batch; the small one was inline"
1800
        );
1801
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
1802
    }
1803
1804
    #[test]
1805
    #[should_panic(expected = "was not loaded")]
1806
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
1807
        let f = NodeId::random();
1808
        let mut st = State::new_history_only();
1809
        st.add(change(
1810
            vec![],
1811
            vec![TreeOp::AddNode {
1812
                node: f,
1813
                kind: NodeKind::File,
1814
                mode: Mode::TEXT,
1815
                parent: NodeId::ROOT,
1816
                name: "a".into(),
1817
            }],
1818
            vec![Edit::Insert {
1819
                node: f,
1820
                after: AtomRef::Start,
1821
                before: AtomRef::End,
1822
                lines: vec![b"a\n".to_vec()].into(),
1823
            }],
1824
        ))
1825
        .unwrap();
1826
        st.render_file(&f);
1827
    }
1828
1829
    #[test]
1830
    #[should_panic(expected = "needs every file graph")]
1831
    fn materializing_a_history_only_state_is_refused() {
1832
        let f = NodeId::random();
1833
        let mut st = State::new_history_only();
1834
        st.add(change(
1835
            vec![],
1836
            vec![TreeOp::AddNode {
1837
                node: f,
1838
                kind: NodeKind::File,
1839
                mode: Mode::TEXT,
1840
                parent: NodeId::ROOT,
1841
                name: "a".into(),
1842
            }],
1843
            vec![Edit::Insert {
1844
                node: f,
1845
                after: AtomRef::Start,
1846
                before: AtomRef::End,
1847
                lines: vec![b"a\n".to_vec()].into(),
1848
            }],
1849
        ))
1850
        .unwrap();
1851
        st.materialize();
1852
    }
1853
1854
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
1855
    /// blob; the state read back is the same as from version 1.
1856
    #[test]
1857
    fn checkpoint_index_round_trip_matches_version_1() {
1858
        let mut st = State::new();
1859
        let small = NodeId::random();
1860
        let big = NodeId::random();
1861
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1862
            node,
1863
            kind: NodeKind::File,
1864
            mode: Mode::TEXT,
1865
            parent: NodeId::ROOT,
1866
            name: name.into(),
1867
        };
1868
        let big_lines: crate::lines::Lines = (0..400)
1869
            .map(|i| format!("line {i} of a long file\n").into_bytes())
1870
            .collect();
1871
        let h1 = st
1872
            .add(change(
1873
                vec![],
1874
                vec![add(small, "small"), add(big, "big")],
1875
                vec![
1876
                    Edit::Insert {
1877
                        node: small,
1878
                        after: AtomRef::Start,
1879
                        before: AtomRef::End,
1880
                        lines: vec![b"x\n".to_vec()].into(),
1881
                    },
1882
                    Edit::Insert {
1883
                        node: big,
1884
                        after: AtomRef::Start,
1885
                        before: AtomRef::End,
1886
                        lines: big_lines,
1887
                    },
1888
                ],
1889
            ))
1890
            .unwrap();
1891
        st.add(change(
1892
            vec![h1],
1893
            vec![],
1894
            vec![Edit::Delete {
1895
                node: big,
1896
                atoms: vec![AtomRange {
1897
                    change: h1,
1898
                    from: 3,
1899
                    to: 7,
1900
                }],
1901
            }],
1902
        ))
1903
        .unwrap();
1904
1905
        let graphs = st.checkpoint_file_graphs();
1906
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
1907
        let index = st.checkpoint_index(&graphs, |enc| {
1908
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
1909
            blobs.insert(r, enc.to_vec());
1910
            r
1911
        });
1912
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
1913
        assert_eq!(
1914
            State::checkpoint_graph_refs(&index).unwrap(),
1915
            blobs.keys().copied().collect::<Vec<_>>()
1916
        );
1917
        assert!(
1918
            State::checkpoint_graph_refs(&st.checkpoint_payload())
1919
                .unwrap()
1920
                .is_empty(),
1921
            "version 1 names none"
1922
        );
1923
        assert!(index.len() < st.checkpoint_payload().len());
1924
1925
        let back = State::from_checkpoint(&index, |refs| {
1926
            refs.iter()
1927
                .map(|r| {
1928
                    blobs
1929
                        .get(r)
1930
                        .cloned()
1931
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
1932
                })
1933
                .collect()
1934
        })
1935
        .unwrap();
1936
        assert_eq!(
1937
            back.checkpoint_payload(),
1938
            st.checkpoint_payload(),
1939
            "the same state as version 1"
1940
        );
1941
        assert_eq!(
1942
            back.materialize().files["big"].content,
1943
            st.materialize().files["big"].content
1944
        );
1945
        // Deterministic: the same state gives the same index.
1946
        assert_eq!(
1947
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
1948
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
1949
            }),
1950
            index
1951
        );
1952
        // A missing graph blob is an error, not an empty file.
1953
        assert!(
1954
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
1955
        );
1956
        assert!(
1957
            State::from_checkpoint_payload(&index).is_err(),
1958
            "version 2 needs its blobs"
1959
        );
1960
        // Version 1 payloads still read, and unknown versions do not.
1961
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
1962
        let mut v3 = cbor::decode(&index).unwrap();
1963
        if let Value::Map(m) = &mut v3 {
1964
            m.insert(0, Value::Uint(3));
1965
        }
1966
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
1967
    }
1968
1969
    #[test]
1970
    fn maximal_elements() {
1971
        let mut st = State::new();
1972
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
1973
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
1974
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
1975
        let mut m = st.maximal(&[h1, h2, h3]);
1976
        m.sort();
1977
        let mut want = vec![h2, h3];
1978
        want.sort();
1979
        assert_eq!(m, want);
1980
        assert_eq!(st.heads(), want);
1981
    }
1982
1983
    /// The one-walk `maximal` agrees with the definition (not in the
1984
    /// closure of another element) on random graphs, with repeated and
1985
    /// unknown hashes among the input.
1986
    #[test]
1987
    fn maximal_matches_its_definition() {
1988
        use rand::{Rng, SeedableRng};
1989
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
1990
        for _ in 0..20 {
1991
            let mut st = State::new();
1992
            let mut all: Vec<ChangeHash> = Vec::new();
1993
            for _ in 0..60 {
1994
                let deps: Vec<ChangeHash> =
1995
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
1996
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
1997
            }
1998
            let mut pick: Vec<ChangeHash> =
1999
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
2000
            pick.extend(pick.clone().into_iter().take(3));
2001
            pick.push(ObjectRef([0xee; 32]));
2002
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
2003
            let want: Vec<ChangeHash> = set
2004
                .iter()
2005
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
2006
                .copied()
2007
                .collect();
2008
            assert_eq!(st.maximal(&pick), want);
2009
            assert_eq!(st.maximal(&all), st.heads());
2010
        }
2011
    }
2012
}