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