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