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