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