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