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