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