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