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