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