OXYGENHUB
◆ v0.4.1 oxygen / crates / oxy-core / src / state.rs
100.4 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_spliced(o, 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
    /// The one text a file's history is, when it is a single insert of
951
    /// the whole file into nothing (a file added once and never edited,
952
    /// with no checkpoint base): its rendering is that text, so it needs
953
    /// no graph. `None` otherwise, or when the graph is built.
954
    pub fn single_text(&self, node: &NodeId) -> Option<TextRef> {
955
        if self.files.contains_key(node) {
956
            return None;
957
        }
958
        let d = self.deferred.as_ref()?.get(node)?.body();
959
        let [(_, edits)] = d.edits.as_slice() else {
960
            return None;
961
        };
962
        let [Edit::Insert {
963
            after: AtomRef::Start,
964
            before: AtomRef::End,
965
            lines,
966
            ..
967
        }] = edits.as_slice()
968
        else {
969
            return None;
970
        };
971
        match (&d.base, d.texts.as_slice()) {
972
            (None, [t]) if lines.is_empty() => Some(*t),
973
            _ => None,
974
        }
975
    }
976
977
    /// A key for the graph of `node` in a history-only state that has not
978
    /// built it: equal keys mean equal graphs, so equal renderings (a
979
    /// rendering depends only on the graph and on the changes' own
980
    /// immutable metadata). It names the node, its checkpoint base (a blob,
981
    /// an inline value, or none) and the set of later changes that edited
982
    /// the file.
983
    /// `None` for a full state or a graph already built.
984
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
985
        let deferred = self.deferred.as_ref()?;
986
        if self.files.contains_key(node) {
987
            return None;
988
        }
989
        let mut h = blake3::Hasher::new();
990
        h.update(b"oxy graph key 1\0");
991
        // A change's edits are applied per node: the node is part of it.
992
        h.update(&node.0);
993
        let Some(d) = deferred.get(node) else {
994
            // Never edited: the empty graph.
995
            h.update(&[0]);
996
            return Some(*h.finalize().as_bytes());
997
        };
998
        Some(*d.key.get_or_init(|| d.graph_key(h)))
999
    }
1000
1001
    pub fn len(&self) -> usize {
1002
        self.changes.len()
1003
    }
1004
1005
    /// Turn this history-only state's built graphs back into deferred
1006
    /// histories, each starting from its graph encoded as a checkpoint
1007
    /// graph and stored by `store` (it returns the blob's reference): what
1008
    /// they held stays, and memory goes back to what a history-only state
1009
    /// costs. A graph built later again decodes that blob and applies only
1010
    /// the edits that came after. Graph keys change (the base is now a
1011
    /// blob), which only means a cached rendering is not reused.
1012
    pub fn shed_graphs<E>(
1013
        &mut self,
1014
        mut store: impl FnMut(&[u8]) -> Result<ObjectRef, E>,
1015
    ) -> Result<usize, E> {
1016
        use rayon::prelude::*;
1017
        let Some(deferred) = self.deferred.as_mut() else {
1018
            return Ok(0);
1019
        };
1020
        let graphs: Vec<(NodeId, Arc<FileGraph>)> = self.files.drain().collect();
1021
        let encoded: Vec<(NodeId, Vec<u8>)> = graphs
1022
            .par_iter()
1023
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
1024
            .collect();
1025
        drop(graphs);
1026
        let shed = encoded.len();
1027
        for (node, bytes) in encoded {
1028
            let blob = store(&bytes)?;
1029
            deferred.insert(
1030
                node,
1031
                Arc::new(Deferred::from_body(DeferredBody {
1032
                    base: Some(DeferredBase::Blob(blob)),
1033
                    ..DeferredBody::default()
1034
                })),
1035
            );
1036
        }
1037
        Ok(shed)
1038
    }
1039
1040
    /// How many file graphs this state has built.
1041
    pub fn built_count(&self) -> usize {
1042
        self.files.len()
1043
    }
1044
1045
    /// Atoms in this state's built graphs, live and deleted: what their
1046
    /// memory follows, since a graph keeps every line its file ever had.
1047
    pub fn built_atoms(&self) -> usize {
1048
        self.files.values().map(|g| g.atom_count()).sum()
1049
    }
1050
1051
    /// Edits held in the deferred histories of files not built, and the
1052
    /// most any one file holds (for measuring, #25).
1053
    pub fn deferred_edit_count(&self) -> (usize, usize) {
1054
        let Some(d) = self.deferred.as_ref() else {
1055
            return (0, 0);
1056
        };
1057
        let mut total = 0;
1058
        let mut most = 0;
1059
        for v in d.values() {
1060
            let n: usize = v.body().edits.iter().map(|(_, e)| e.len()).sum();
1061
            total += n;
1062
            most = most.max(n);
1063
        }
1064
        (total, most)
1065
    }
1066
}
1067
1068
impl Deferred {
1069
    /// See [`State::graph_key`]: `h` has taken the node already.
1070
    fn graph_key(&self, mut h: blake3::Hasher) -> [u8; 32] {
1071
        let d = self.body();
1072
        match &d.base {
1073
            None => h.update(&[0]),
1074
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
1075
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
1076
        };
1077
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
1078
        changes.sort();
1079
        changes.dedup();
1080
        h.update(&(changes.len() as u64).to_le_bytes());
1081
        for c in changes {
1082
            h.update(&c.0);
1083
        }
1084
        *h.finalize().as_bytes()
1085
    }
1086
}
1087
1088
impl State {
1089
    pub fn is_empty(&self) -> bool {
1090
        self.changes.is_empty()
1091
    }
1092
    pub fn contains(&self, h: &ChangeHash) -> bool {
1093
        self.changes.contains_key(h)
1094
    }
1095
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
1096
        self.changes.get(h).map(|m| &**m)
1097
    }
1098
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
1099
        self.changes.iter().map(|(h, m)| (h, &**m))
1100
    }
1101
    pub fn tree(&self) -> &TreeGraph {
1102
        &self.tree
1103
    }
1104
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
1105
        self.graph(node)
1106
    }
1107
1108
    /// Add a change whose dependencies are already present.
1109
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
1110
        let h = change.hash();
1111
        self.add_hashed(h, change)
1112
    }
1113
1114
    /// [`State::add`] for a change whose hash `h` is already known (it was
1115
    /// just stored), so it is not encoded again.
1116
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
1117
        if self.changes.contains_key(&h) {
1118
            return Ok(h);
1119
        }
1120
        for d in &change.deps {
1121
            if !self.changes.contains_key(d) {
1122
                return Err(StateError::MissingDep(*d, h));
1123
            }
1124
        }
1125
        self.add_known(h, change, Vec::new());
1126
        Ok(h)
1127
    }
1128
1129
    /// Add a change in any order; call `validate` once all are in.
1130
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
1131
        let h = change.hash();
1132
        self.add_known(h, change, Vec::new());
1133
        h
1134
    }
1135
1136
    /// Add a change just stored under hash `h` to a history-only state that
1137
    /// has built some graphs: an edit of a built graph is applied whole
1138
    /// (from `full`), and one of a file not built waits without its text
1139
    /// (from `skeleton` and its `texts`, as the store reads it back), so the
1140
    /// state holds no text it has not built. A Git import adds each change
1141
    /// it makes this way, keeping memory to what changes.
1142
    pub fn add_known_mixed(
1143
        &mut self,
1144
        h: ChangeHash,
1145
        full: Change,
1146
        skeleton: Change,
1147
        texts: Vec<TextRef>,
1148
    ) {
1149
        if self.deferred.is_none() || self.changes.contains_key(&h) {
1150
            self.add_known(h, full, Vec::new());
1151
            return;
1152
        }
1153
        let Change {
1154
            version,
1155
            change_id,
1156
            deps,
1157
            author,
1158
            hlc,
1159
            message,
1160
            tree_ops,
1161
            edits: full_edits,
1162
            kind,
1163
        } = full;
1164
        let mut texts = texts.into_iter();
1165
        let mut edits = Vec::with_capacity(full_edits.len());
1166
        let mut kept = Vec::new();
1167
        for (f, s) in full_edits.into_iter().zip(skeleton.edits) {
1168
            let text = match &s {
1169
                Edit::Insert { lines, .. } if lines.is_empty() => texts.next(),
1170
                _ => None,
1171
            };
1172
            if self.files.contains_key(&f.node()) {
1173
                edits.push(f);
1174
            } else {
1175
                edits.push(s);
1176
                kept.extend(text);
1177
            }
1178
        }
1179
        let c = Change {
1180
            version,
1181
            change_id,
1182
            deps,
1183
            author,
1184
            hlc,
1185
            message,
1186
            tree_ops,
1187
            edits,
1188
            kind,
1189
        };
1190
        self.add_known(h, c, kept);
1191
    }
1192
1193
    /// Add a change read from the store under hash `h`, without hashing it
1194
    /// again (for a version 2 change that means chunking all its text).
1195
    /// `texts` names, in order, the inserts left without their lines (see
1196
    /// [`crate::store::Store::get_change_lazy`]); only a history-only state
1197
    /// takes them, and only for graphs it has not built.
1198
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
1199
        if self.changes.contains_key(&h) {
1200
            return;
1201
        }
1202
        let meta = ChangeMeta::of(&change);
1203
        self.apply_with(h, change, texts);
1204
        self.changes.insert(h, Arc::new(meta));
1205
        {
1206
            let mut m = self.closure.lock().unwrap();
1207
            m.sets.clear();
1208
            m.held = 0;
1209
        }
1210
    }
1211
1212
    // ------------------------------------------------------------ checkpoints (spec §11)
1213
1214
    /// Serialize the whole state in payload version 1: change metadata,
1215
    /// tree, file graphs, replaces, all in one value (spec §11).
1216
    pub fn checkpoint_payload(&self) -> Vec<u8> {
1217
        self.require_full("a checkpoint");
1218
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
1219
        nodes.sort();
1220
        let files = Value::Array(
1221
            nodes
1222
                .into_iter()
1223
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
1224
                .collect(),
1225
        );
1226
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
1227
    }
1228
1229
    /// Each file graph encoded on its own, by node, for a version 2 payload
1230
    /// (spec §11): the graphs of large files become blobs of their own.
1231
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
1232
        use rayon::prelude::*;
1233
        self.require_full("a checkpoint");
1234
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
1235
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
1236
        nodes.sort_by_key(|(n, _)| **n);
1237
        nodes
1238
            .into_par_iter()
1239
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
1240
            .collect()
1241
    }
1242
1243
    /// The payload version 2 index for the graphs of
1244
    /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than
1245
    /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by
1246
    /// `blob_of` (the ObjectRef of the blob holding its encoding).
1247
    pub fn checkpoint_index(
1248
        &self,
1249
        graphs: &[(NodeId, Vec<u8>)],
1250
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
1251
    ) -> Vec<u8> {
1252
        let files = Value::Array(
1253
            graphs
1254
                .iter()
1255
                .map(|(n, enc)| {
1256
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
1257
                        cbor::decode(enc).expect("an encoded graph decodes")
1258
                    } else {
1259
                        Value::Bytes(blob_of(enc).0.to_vec())
1260
                    };
1261
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
1262
                })
1263
                .collect(),
1264
        );
1265
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
1266
    }
1267
1268
    /// The payload map around `files`: changes, tree and replaces as in version 1.
1269
    fn payload_value(&self, version: u64, files: Value) -> Value {
1270
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
1271
        hashes.sort();
1272
        let changes = Value::Array(
1273
            hashes
1274
                .into_iter()
1275
                .map(|h| {
1276
                    let m = &self.changes[h];
1277
                    Value::Array(vec![
1278
                        Value::Bytes(h.0.to_vec()),
1279
                        Value::Bytes(m.change_id.0.to_vec()),
1280
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
1281
                        Value::Text(m.message.clone()),
1282
                        Value::Uint(m.hlc.wall_ms),
1283
                        Value::Uint(m.hlc.logical as u64),
1284
                        Value::Uint(m.kind.tag()),
1285
                        Value::Bytes(m.author.0.to_vec()),
1286
                    ])
1287
                })
1288
                .collect(),
1289
        );
1290
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
1291
        rnodes.sort();
1292
        let opt =
1293
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
1294
        let replaces = Value::Array(
1295
            rnodes
1296
                .into_iter()
1297
                .map(|n| {
1298
                    Value::Array(vec![
1299
                        Value::Bytes(n.0.to_vec()),
1300
                        Value::Array(
1301
                            self.replaces[n]
1302
                                .iter()
1303
                                .map(|(c, o, nw)| {
1304
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
1305
                                })
1306
                                .collect(),
1307
                        ),
1308
                    ])
1309
                })
1310
                .collect(),
1311
        );
1312
        Value::map([
1313
            (0, Value::Uint(version)),
1314
            (1, changes),
1315
            (2, self.tree.to_value()),
1316
            (3, files),
1317
            (4, replaces),
1318
        ])
1319
    }
1320
1321
    /// Decode a version 1 payload (the whole state in one value). A
1322
    /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`].
1323
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
1324
        State::from_checkpoint(bytes, |_| {
1325
            Err(ObjectError::Schema(
1326
                "a version 2 checkpoint needs its graph blobs".into(),
1327
            ))
1328
        })
1329
    }
1330
1331
    /// Decode a checkpoint payload of either version (spec §11). For
1332
    /// version 2, `load` returns the contents of the named graph blobs, in
1333
    /// order; the graphs are then decoded in parallel.
1334
    pub fn from_checkpoint(
1335
        bytes: &[u8],
1336
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
1337
    ) -> Result<State, ObjectError> {
1338
        use rayon::prelude::*;
1339
        let v = cbor::decode(bytes)?;
1340
        let m = o::map(&v, "checkpoint payload")?;
1341
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
1342
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
1343
            return Err(ObjectError::Schema(format!(
1344
                "checkpoint payload version {version} is not supported"
1345
            )));
1346
        }
1347
        let mut st = State::payload_common(m)?;
1348
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
1349
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
1350
        for f in entries {
1351
            let e = o::array(f, "file")?;
1352
            if e.len() != 2 {
1353
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1354
            }
1355
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1356
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1357
            parsed.push((node, &e[1]));
1358
        }
1359
        // Version 2 names large graphs by blob: fetch those in one batch.
1360
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
1361
        if version == CHECKPOINT_INDEX_VERSION {
1362
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
1363
                .iter()
1364
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
1365
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
1366
                .collect::<Result<_, ObjectError>>()?;
1367
            if !wanted.is_empty() {
1368
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
1369
                let contents = {
1370
                    let _t = crate::timing::phase("load:   graph blobs read");
1371
                    load(&refs)?
1372
                };
1373
                if contents.len() != refs.len() {
1374
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
1375
                }
1376
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
1377
            }
1378
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
1379
            return Err(ObjectError::Schema(
1380
                "a version 1 payload holds graphs inline".into(),
1381
            ));
1382
        }
1383
        // File graphs are independent; decode and build them in parallel.
1384
        let graphs = parsed
1385
            .par_iter()
1386
            .map(|(node, entry)| {
1387
                let graph = match fetched.get(node) {
1388
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
1389
                    None => FileGraph::from_value(entry)?,
1390
                };
1391
                Ok((*node, graph))
1392
            })
1393
            .collect::<Result<Vec<_>, ObjectError>>()?;
1394
        st.files
1395
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
1396
        Ok(st)
1397
    }
1398
1399
    /// The graph blobs a payload names: empty for version 1.
1400
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
1401
        let v = cbor::decode(bytes)?;
1402
        let m = o::map(&v, "checkpoint payload")?;
1403
        let mut out = Vec::new();
1404
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1405
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
1406
                out.push(o::oref(entry, "graph blob")?);
1407
            }
1408
        }
1409
        Ok(out)
1410
    }
1411
1412
    /// Decode a checkpoint payload for history only: a version 2 payload's
1413
    /// graphs are noted, not read or built, and come later through
1414
    /// [`State::load_graphs`]. A version 1 payload holds them inline and is
1415
    /// decoded in full.
1416
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
1417
        let v = cbor::decode(bytes)?;
1418
        let m = o::map(&v, "checkpoint payload")?;
1419
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
1420
        if version != CHECKPOINT_INDEX_VERSION {
1421
            return State::from_checkpoint_payload(bytes);
1422
        }
1423
        let mut st = State::payload_common(m)?;
1424
        let mut deferred = crate::fasthash::FastMap::default();
1425
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1426
            let e = o::array(f, "file")?;
1427
            if e.len() != 2 {
1428
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1429
            }
1430
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1431
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1432
            let base = match &e[1] {
1433
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
1434
                other => DeferredBase::Inline(other.clone()),
1435
            };
1436
            deferred.insert(
1437
                node,
1438
                Arc::new(Deferred::from_body(DeferredBody {
1439
                    base: Some(base),
1440
                    ..DeferredBody::default()
1441
                })),
1442
            );
1443
        }
1444
        st.deferred = Some(deferred);
1445
        Ok(st)
1446
    }
1447
1448
    /// Changes, tree and replaces of a payload of either version.
1449
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
1450
        let mut st = State::new();
1451
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
1452
            let e = o::array(c, "change meta")?;
1453
            if e.len() != 8 {
1454
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
1455
            }
1456
            let hash = o::oref(&e[0], "hash")?;
1457
            let meta = ChangeMeta {
1458
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
1459
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
1460
                deps: o::array(&e[2], "deps")?
1461
                    .iter()
1462
                    .map(|d| o::oref(d, "dep"))
1463
                    .collect::<Result<Vec<_>, _>>()?,
1464
                message: o::text(&e[3], "message")?.to_owned(),
1465
                hlc: Hlc {
1466
                    wall_ms: o::uint(&e[4], "wall")?,
1467
                    logical: o::u32_(&e[5], "logical")?,
1468
                },
1469
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
1470
                author: o::oref(&e[7], "author")?,
1471
            };
1472
            st.changes.insert(hash, Arc::new(meta));
1473
        }
1474
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
1475
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
1476
            if v.is_null() {
1477
                Ok(None)
1478
            } else {
1479
                o::oref(v, "blob").map(Some)
1480
            }
1481
        };
1482
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
1483
            let e = o::array(r, "replace")?;
1484
            if e.len() != 2 {
1485
                return Err(ObjectError::Schema(
1486
                    "replace: expected [node, records]".into(),
1487
                ));
1488
            }
1489
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1490
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1491
            let mut recs = Vec::new();
1492
            for rec in o::array(&e[1], "records")? {
1493
                let x = o::array(rec, "record")?;
1494
                if x.len() != 3 {
1495
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
1496
                }
1497
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
1498
            }
1499
            st.replaces.insert(node, recs);
1500
        }
1501
        Ok(st)
1502
    }
1503
1504
    pub fn validate(&self) -> Result<(), StateError> {
1505
        for (h, c) in &self.changes {
1506
            for d in &c.deps {
1507
                if !self.changes.contains_key(d) {
1508
                    return Err(StateError::MissingDep(*d, *h));
1509
                }
1510
            }
1511
        }
1512
        Ok(())
1513
    }
1514
1515
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
1516
        for (i, op) in c.tree_ops.iter().enumerate() {
1517
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
1518
        }
1519
        if let Some(deferred) = self.deferred.as_mut() {
1520
            // History only: edits of files not built wait, grouped per file,
1521
            // with the texts of inserts read without their lines.
1522
            let mut texts = texts.into_iter();
1523
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
1524
            for e in c.edits {
1525
                match e {
1526
                    Edit::Replace { node, old, new } => {
1527
                        self.replaces.entry(node).or_default().push((h, old, new))
1528
                    }
1529
                    e => {
1530
                        let slot = per_node.entry(e.node()).or_default();
1531
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
1532
                            slot.1.extend(texts.next());
1533
                        }
1534
                        slot.0.push(e);
1535
                    }
1536
                }
1537
            }
1538
            for (node, (edits, node_texts)) in per_node {
1539
                match self.files.get_mut(&node) {
1540
                    Some(g) => {
1541
                        assert!(
1542
                            node_texts.is_empty(),
1543
                            "a change read without its text applied to a built graph"
1544
                        );
1545
                        apply_file_edits(Arc::make_mut(g), h, edits)
1546
                    }
1547
                    None => {
1548
                        let d = Arc::make_mut(deferred.entry(node).or_default());
1549
                        let b = d.body_mut();
1550
                        b.edits.push((h, edits));
1551
                        b.texts.extend(node_texts);
1552
                        d.key = Default::default();
1553
                    }
1554
                }
1555
            }
1556
            return;
1557
        }
1558
        assert!(
1559
            texts.is_empty(),
1560
            "a change read without its text applied to a full state"
1561
        );
1562
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
1563
        for e in c.edits {
1564
            match e {
1565
                Edit::Insert {
1566
                    node,
1567
                    after,
1568
                    before,
1569
                    lines,
1570
                } => {
1571
                    let idx = counters.entry(node).or_default();
1572
                    let first = *idx;
1573
                    *idx += lines.len() as u32;
1574
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
1575
                        h,
1576
                        first,
1577
                        vertex(after.resolve(h)),
1578
                        vertex(before.resolve(h)),
1579
                        lines,
1580
                    );
1581
                }
1582
                Edit::Delete { node, atoms } => {
1583
                    let g = Arc::make_mut(self.files.entry(node).or_default());
1584
                    for r in atoms {
1585
                        g.delete(h, &r.resolve(h));
1586
                    }
1587
                }
1588
                Edit::Replace { node, old, new } => {
1589
                    self.replaces.entry(node).or_default().push((h, old, new));
1590
                }
1591
            }
1592
        }
1593
    }
1594
1595
    /// Transitive dependencies of `h`, excluding `h` itself.
1596
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
1597
        if let Some(c) = self.closure.lock().unwrap().sets.get(h) {
1598
            return c.clone();
1599
        }
1600
        let mut out = HashSet::new();
1601
        let mut stack: Vec<ChangeHash> = self
1602
            .changes
1603
            .get(h)
1604
            .map(|c| c.deps.clone())
1605
            .unwrap_or_default();
1606
        while let Some(d) = stack.pop() {
1607
            if out.insert(d) {
1608
                if let Some(c) = self.changes.get(&d) {
1609
                    stack.extend(c.deps.iter().copied());
1610
                }
1611
            }
1612
        }
1613
        let rc = Arc::new(out);
1614
        let mut memo = self.closure.lock().unwrap();
1615
        if memo.held + rc.len() > CLOSURE_MEMO_HASHES {
1616
            memo.sets.clear();
1617
            memo.held = 0;
1618
        }
1619
        memo.held += rc.len();
1620
        memo.sets.insert(*h, rc.clone());
1621
        rc
1622
    }
1623
1624
    /// `h`'s level (see `levels`), worked out for it and its ancestors not
1625
    /// yet known, without recursion: histories are deeper than a stack. An
1626
    /// unknown change has level 0.
1627
    fn level(&self, h: &ChangeHash) -> u32 {
1628
        let mut levels = self.levels.lock().unwrap();
1629
        if let Some(l) = levels.get(h) {
1630
            return *l;
1631
        }
1632
        let mut stack: Vec<(ChangeHash, bool)> = vec![(*h, false)];
1633
        while let Some((c, expanded)) = stack.pop() {
1634
            if levels.contains_key(&c) {
1635
                continue;
1636
            }
1637
            let deps: &[ChangeHash] = self
1638
                .changes
1639
                .get(&c)
1640
                .map(|m| m.deps.as_slice())
1641
                .unwrap_or(&[]);
1642
            if expanded {
1643
                let l = deps
1644
                    .iter()
1645
                    .map(|d| levels.get(d).map_or(0, |l| l + 1))
1646
                    .max()
1647
                    .unwrap_or(0);
1648
                levels.insert(c, l);
1649
            } else {
1650
                stack.push((c, true));
1651
                for d in deps {
1652
                    if !levels.contains_key(d) {
1653
                        stack.push((*d, false));
1654
                    }
1655
                }
1656
            }
1657
        }
1658
        levels[h]
1659
    }
1660
1661
    /// Changes that no other change depends on directly, sorted.
1662
    pub fn heads(&self) -> Vec<ChangeHash> {
1663
        let depended: HashSet<&ChangeHash> =
1664
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
1665
        let mut heads: Vec<ChangeHash> = self
1666
            .changes
1667
            .keys()
1668
            .filter(|h| !depended.contains(h))
1669
            .copied()
1670
            .collect();
1671
        heads.sort();
1672
        heads
1673
    }
1674
1675
    /// Maximal elements among `hashes` (those not in the closure of another),
1676
    /// sorted. One walk down from all of them at once: whatever the walk
1677
    /// reaches is below some other element. Linear in the changes reached,
1678
    /// where comparing every pair's closures was quadratic in the number
1679
    /// of heads, which a bookmark of independent changes has many of.
1680
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
1681
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
1682
        let mut below: HashSet<ChangeHash> = HashSet::new();
1683
        let mut stack: Vec<ChangeHash> = set
1684
            .iter()
1685
            .filter_map(|h| self.changes.get(h))
1686
            .flat_map(|c| c.deps.iter().copied())
1687
            .collect();
1688
        while let Some(d) = stack.pop() {
1689
            if below.insert(d) {
1690
                if let Some(c) = self.changes.get(&d) {
1691
                    stack.extend(c.deps.iter().copied());
1692
                }
1693
            }
1694
        }
1695
        set.into_iter().filter(|h| !below.contains(h)).collect()
1696
    }
1697
1698
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
1699
        self.graph(node)
1700
            .map(|g| g.materialize(self))
1701
            .unwrap_or_default()
1702
    }
1703
1704
    /// Live lines of a text node in materialized order.
1705
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
1706
        let Some(g) = self.graph(node) else {
1707
            return vec![];
1708
        };
1709
        let m = g.materialize(self);
1710
        m.live_atoms()
1711
            .into_iter()
1712
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
1713
            .collect()
1714
    }
1715
1716
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
1717
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
1718
        let mut live: Vec<ObjectRef> = self
1719
            .live_replaces(node)
1720
            .into_iter()
1721
            .map(|(_, n)| n)
1722
            .collect();
1723
        live.sort();
1724
        live.dedup();
1725
        live
1726
    }
1727
1728
    /// The replace records whose blob is live, with the change that set it
1729
    /// (spec §9.3). A record's blob is superseded by a later replacement of
1730
    /// that blob: one whose change depends on the record's change, as every
1731
    /// replacement depends on the change that made its old blob current
1732
    /// (§8.1). Two replacements that do not know each other both stay live
1733
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
1734
    /// A replacement without that dependency, from before the rule, is read
1735
    /// as before: it supersedes every record that did not come after it.
1736
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
1737
        let Some(rs) = self.replaces.get(node) else {
1738
            return vec![];
1739
        };
1740
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
1741
            rs.iter()
1742
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && self.closure(s).contains(q))
1743
        };
1744
        rs.iter()
1745
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
1746
            .filter(|(c, n)| {
1747
                !rs.iter().any(|(s, o, _)| {
1748
                    s != c
1749
                        && *o == Some(*n)
1750
                        && (self.closure(s).contains(c)
1751
                            || (!knows_its_old(s, n) && !self.closure(c).contains(s)))
1752
                })
1753
            })
1754
            .collect()
1755
    }
1756
1757
    /// Short label for conflict markers: `changeid-prefix "message"`.
1758
    pub fn label(&self, h: &ChangeHash) -> String {
1759
        match self.changes.get(h) {
1760
            Some(c) => format!(
1761
                "{} \"{}\"",
1762
                c.change_id.short(8),
1763
                c.message.lines().next().unwrap_or("")
1764
            ),
1765
            None => format!("#{}", h.short(12)),
1766
        }
1767
    }
1768
1769
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1770
    /// are not part of any conflict region in order, every live atom that is
1771
    /// part of a region, and every change that contributed to a region.
1772
    /// The changes that introduced the live blobs of an opaque node, for a
1773
    /// replace conflict (spec §9.3).
1774
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
1775
        let mut out: Vec<ChangeHash> = Vec::new();
1776
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
1777
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
1778
                out.push(*h);
1779
            }
1780
        }
1781
        out.sort();
1782
        out
1783
    }
1784
1785
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
1786
        let mut out = ConflictRegions::default();
1787
        let Some(g) = self.graph(node) else {
1788
            return out;
1789
        };
1790
        let m = g.materialize(self);
1791
        let mut contributors = BTreeSet::new();
1792
        for seg in &m.segments {
1793
            match seg {
1794
                crate::graph::Segment::Lines(atoms) => {
1795
                    for a in atoms {
1796
                        out.plain
1797
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
1798
                    }
1799
                }
1800
                crate::graph::Segment::Conflict(sides) => {
1801
                    for side in sides {
1802
                        for a in side {
1803
                            out.region_atoms.push(*a);
1804
                            contributors.insert(a.0);
1805
                        }
1806
                    }
1807
                }
1808
                crate::graph::Segment::Zombie { deleted, inserted } => {
1809
                    for a in deleted {
1810
                        contributors.insert(a.0);
1811
                        contributors.extend(g.deleters(a).copied());
1812
                    }
1813
                    for a in inserted {
1814
                        out.region_atoms.push(*a);
1815
                        contributors.insert(a.0);
1816
                    }
1817
                }
1818
            }
1819
        }
1820
        out.contributors = contributors.into_iter().collect();
1821
        out
1822
    }
1823
1824
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
1825
        let Some(g) = self.graph(node) else {
1826
            return (Vec::new(), Materialized::default());
1827
        };
1828
        let m = g.materialize(self);
1829
        let bytes = g.render(&m, &|h| self.label(h));
1830
        (bytes, m)
1831
    }
1832
1833
    /// Every file rendered, in parallel: files are independent, and
1834
    /// rendering them is most of a snapshot's cost in a large tree.
1835
    pub fn materialize(&self) -> Snapshot {
1836
        use rayon::prelude::*;
1837
        self.require_full("materializing a state");
1838
        let tree = self.tree.view();
1839
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
1840
        let rendered: Vec<(String, FileState)> = entries
1841
            .par_iter()
1842
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
1843
            .collect();
1844
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
1845
        Snapshot {
1846
            tree,
1847
            files,
1848
            unrendered: BTreeSet::new(),
1849
        }
1850
    }
1851
1852
    /// Like [`State::materialize`], leaving the text files of nodes in
1853
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
1854
    /// file's graph must be loaded. For a caller that already knows those
1855
    /// files are unchanged and not conflicted.
1856
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
1857
        self.materialize_leaving(|_, e| skip.contains(&e.node))
1858
    }
1859
1860
    /// As [`State::materialize_except`], rendering only the text files at
1861
    /// `render` (a few, where the caller knows the rest unchanged).
1862
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
1863
        self.materialize_leaving(|p, _| !render.contains(p))
1864
    }
1865
1866
    /// As [`State::materialize_except`], rendering only the text files of
1867
    /// the nodes in `render` (a change's edited files), without a set of
1868
    /// every other file to leave out.
1869
    pub fn materialize_nodes(&self, render: &HashSet<NodeId>) -> Snapshot {
1870
        self.materialize_leaving(|_, e| !render.contains(&e.node))
1871
    }
1872
1873
    fn materialize_leaving(
1874
        &self,
1875
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
1876
    ) -> Snapshot {
1877
        use rayon::prelude::*;
1878
        let tree = self.tree.view();
1879
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
1880
        let rendered: Vec<(String, FileState, bool)> = entries
1881
            .par_iter()
1882
            .map(|(path, e)| {
1883
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
1884
                    let f = FileState {
1885
                        node: e.node,
1886
                        kind: e.kind,
1887
                        mode: e.mode,
1888
                        content: FileContent::Text {
1889
                            bytes: Vec::new(),
1890
                            materialized: Materialized::default(),
1891
                        },
1892
                    };
1893
                    (path.to_string(), f, true)
1894
                } else {
1895
                    (path.to_string(), self.file_state(e), false)
1896
                }
1897
            })
1898
            .collect();
1899
        // In the view's path order, so the maps are built without searching.
1900
        let unrendered: BTreeSet<String> = rendered
1901
            .iter()
1902
            .filter(|(_, _, skipped)| *skipped)
1903
            .map(|(p, _, _)| p.clone())
1904
            .collect();
1905
        let files: BTreeMap<String, FileState> =
1906
            rendered.into_iter().map(|(p, f, _)| (p, f)).collect();
1907
        Snapshot {
1908
            tree,
1909
            files,
1910
            unrendered,
1911
        }
1912
    }
1913
1914
    /// A snapshot of only `paths` (those `view` has), `view` being this
1915
    /// state's tree view: for a caller that works from what changed. The
1916
    /// graphs of those text files must be loaded.
1917
    pub fn materialize_paths<'p>(
1918
        &self,
1919
        view: crate::tree::TreeView,
1920
        paths: impl IntoIterator<Item = &'p str>,
1921
    ) -> Snapshot {
1922
        let files = paths
1923
            .into_iter()
1924
            .filter_map(|p| Some((p.to_string(), self.file_state(view.entries.get(p)?))))
1925
            .collect();
1926
        Snapshot {
1927
            tree: view,
1928
            files,
1929
            unrendered: BTreeSet::new(),
1930
        }
1931
    }
1932
1933
    /// The state of one tree entry: a directory, an opaque file's live
1934
    /// blobs, or a text file rendered from its graph (which must be built).
1935
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
1936
        self.file_state(e)
1937
    }
1938
1939
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
1940
        {
1941
            let content = match e.kind {
1942
                NodeKind::Dir => FileContent::Dir,
1943
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
1944
                    blobs: self.live_blobs(&e.node),
1945
                },
1946
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
1947
                    blobs: self.live_blobs(&e.node),
1948
                },
1949
                NodeKind::File => {
1950
                    let (bytes, materialized) = self.render_file(&e.node);
1951
                    FileContent::Text {
1952
                        bytes,
1953
                        materialized,
1954
                    }
1955
                }
1956
            };
1957
            FileState {
1958
                node: e.node,
1959
                kind: e.kind,
1960
                mode: e.mode,
1961
                content,
1962
            }
1963
        }
1964
    }
1965
}
1966
1967
impl DepOracle for State {
1968
    /// Whether `a` depends on `b`, by a walk down from `a` that stops at
1969
    /// changes no higher than `b`: they cannot have `b` below them. Nothing
1970
    /// of the walk is kept, so asking about many pairs costs no more memory
1971
    /// than one walk (#25); a closure already memoised answers at once.
1972
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
1973
        if a == b {
1974
            return true;
1975
        }
1976
        if let Some(c) = self.closure.lock().unwrap().sets.get(a) {
1977
            return c.contains(b);
1978
        }
1979
        if !self.changes.contains_key(b) {
1980
            return false;
1981
        }
1982
        let lb = self.level(b);
1983
        if self.level(a) <= lb {
1984
            return false;
1985
        }
1986
        let mut seen: HashSet<ChangeHash> = HashSet::new();
1987
        let mut stack: Vec<ChangeHash> = self
1988
            .changes
1989
            .get(a)
1990
            .map(|m| m.deps.clone())
1991
            .unwrap_or_default();
1992
        while let Some(c) = stack.pop() {
1993
            if c == *b {
1994
                return true;
1995
            }
1996
            if !seen.insert(c) || self.level(&c) <= lb {
1997
                continue;
1998
            }
1999
            if let Some(m) = self.changes.get(&c) {
2000
                stack.extend(m.deps.iter().copied());
2001
            }
2002
        }
2003
        false
2004
    }
2005
}
2006
2007
#[cfg(test)]
2008
mod tests {
2009
    use super::*;
2010
    use crate::ids::ChangeId;
2011
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
2012
2013
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
2014
        let mut c = Change {
2015
            version: crate::objects::CHANGE_VERSION,
2016
            change_id: ChangeId::random(),
2017
            deps,
2018
            author: ObjectRef::ZERO,
2019
            hlc: Hlc {
2020
                wall_ms: 1,
2021
                logical: 0,
2022
            },
2023
            message: "m".into(),
2024
            tree_ops,
2025
            edits,
2026
            kind: ChangeKind::Normal,
2027
        };
2028
        c.normalize();
2029
        c
2030
    }
2031
2032
    #[test]
2033
    fn build_edit_and_materialize() {
2034
        let mut st = State::new();
2035
        let f = NodeId::random();
2036
        let c1 = change(
2037
            vec![],
2038
            vec![TreeOp::AddNode {
2039
                node: f,
2040
                kind: NodeKind::File,
2041
                mode: Mode::TEXT,
2042
                parent: NodeId::ROOT,
2043
                name: "a.txt".into(),
2044
            }],
2045
            vec![Edit::Insert {
2046
                node: f,
2047
                after: AtomRef::Start,
2048
                before: AtomRef::End,
2049
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
2050
            }],
2051
        );
2052
        let h1 = st.add(c1).unwrap();
2053
        // Depends on h1: append a line and delete "one".
2054
        let c2 = change(
2055
            vec![h1],
2056
            vec![],
2057
            vec![
2058
                Edit::Delete {
2059
                    node: f,
2060
                    atoms: vec![AtomRange {
2061
                        change: h1,
2062
                        from: 0,
2063
                        to: 1,
2064
                    }],
2065
                },
2066
                Edit::Insert {
2067
                    node: f,
2068
                    after: AtomRef::Atom {
2069
                        change: h1,
2070
                        index: 1,
2071
                    },
2072
                    before: AtomRef::End,
2073
                    lines: vec![b"three\n".to_vec()].into(),
2074
                },
2075
            ],
2076
        );
2077
        let h2 = st.add(c2).unwrap();
2078
        assert_eq!(st.heads(), vec![h2]);
2079
        assert!(st.depends_on(&h2, &h1));
2080
        assert!(!st.depends_on(&h1, &h2));
2081
        let snap = st.materialize();
2082
        assert!(!snap.is_conflicted());
2083
        let a = &snap.files["a.txt"];
2084
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
2085
        assert_eq!(st.live_lines(&f).len(), 2);
2086
    }
2087
2088
    #[test]
2089
    fn missing_dependency_is_rejected() {
2090
        let mut st = State::new();
2091
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
2092
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
2093
    }
2094
2095
    #[test]
2096
    fn self_references_and_multi_insert_indexing() {
2097
        let mut st = State::new();
2098
        let f = NodeId::random();
2099
        let me = OpRef {
2100
            change: ObjectRef::ZERO,
2101
            index: 0,
2102
        };
2103
        let c1 = change(
2104
            vec![],
2105
            vec![
2106
                TreeOp::AddNode {
2107
                    node: f,
2108
                    kind: NodeKind::File,
2109
                    mode: Mode::TEXT,
2110
                    parent: NodeId::ROOT,
2111
                    name: "x".into(),
2112
                },
2113
                TreeOp::SetMode {
2114
                    node: f,
2115
                    old: me,
2116
                    mode: Mode {
2117
                        exec: true,
2118
                        opaque: false,
2119
                    },
2120
                },
2121
            ],
2122
            vec![
2123
                Edit::Insert {
2124
                    node: f,
2125
                    after: AtomRef::Start,
2126
                    before: AtomRef::End,
2127
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
2128
                },
2129
                // Insert between the two lines just inserted, using self references.
2130
                Edit::Insert {
2131
                    node: f,
2132
                    after: AtomRef::Atom {
2133
                        change: ObjectRef::ZERO,
2134
                        index: 0,
2135
                    },
2136
                    before: AtomRef::Atom {
2137
                        change: ObjectRef::ZERO,
2138
                        index: 1,
2139
                    },
2140
                    lines: vec![b"b\n".to_vec()].into(),
2141
                },
2142
            ],
2143
        );
2144
        st.add(c1).unwrap();
2145
        let snap = st.materialize();
2146
        let x = &snap.files["x"];
2147
        assert_eq!(
2148
            x.mode,
2149
            Mode {
2150
                exec: true,
2151
                opaque: false
2152
            }
2153
        );
2154
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
2155
    }
2156
2157
    #[test]
2158
    fn opaque_replace_and_conflict() {
2159
        let mut st = State::new();
2160
        let f = NodeId::random();
2161
        let b1 = ObjectRef([1; 32]);
2162
        let b2 = ObjectRef([2; 32]);
2163
        let b3 = ObjectRef([3; 32]);
2164
        let h1 = st
2165
            .add(change(
2166
                vec![],
2167
                vec![TreeOp::AddNode {
2168
                    node: f,
2169
                    kind: NodeKind::File,
2170
                    mode: Mode::OPAQUE,
2171
                    parent: NodeId::ROOT,
2172
                    name: "img".into(),
2173
                }],
2174
                vec![Edit::Replace {
2175
                    node: f,
2176
                    old: None,
2177
                    new: Some(b1),
2178
                }],
2179
            ))
2180
            .unwrap();
2181
        assert_eq!(st.live_blobs(&f), vec![b1]);
2182
        st.add(change(
2183
            vec![h1],
2184
            vec![],
2185
            vec![Edit::Replace {
2186
                node: f,
2187
                old: Some(b1),
2188
                new: Some(b2),
2189
            }],
2190
        ))
2191
        .unwrap();
2192
        st.add(change(
2193
            vec![h1],
2194
            vec![],
2195
            vec![Edit::Replace {
2196
                node: f,
2197
                old: Some(b1),
2198
                new: Some(b3),
2199
            }],
2200
        ))
2201
        .unwrap();
2202
        let snap = st.materialize();
2203
        assert!(snap.is_conflicted());
2204
        assert!(
2205
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2206
        );
2207
    }
2208
2209
    #[test]
2210
    fn checkpoint_payload_round_trip_and_replay() {
2211
        let mut st = State::new();
2212
        let f = NodeId::random();
2213
        let h1 = st
2214
            .add(change(
2215
                vec![],
2216
                vec![TreeOp::AddNode {
2217
                    node: f,
2218
                    kind: NodeKind::File,
2219
                    mode: Mode::TEXT,
2220
                    parent: NodeId::ROOT,
2221
                    name: "a".into(),
2222
                }],
2223
                vec![Edit::Insert {
2224
                    node: f,
2225
                    after: AtomRef::Start,
2226
                    before: AtomRef::End,
2227
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
2228
                }],
2229
            ))
2230
            .unwrap();
2231
        let h2 = st
2232
            .add(change(
2233
                vec![h1],
2234
                vec![],
2235
                vec![Edit::Delete {
2236
                    node: f,
2237
                    atoms: vec![AtomRange {
2238
                        change: h1,
2239
                        from: 0,
2240
                        to: 1,
2241
                    }],
2242
                }],
2243
            ))
2244
            .unwrap();
2245
        let payload = st.checkpoint_payload();
2246
        let back = State::from_checkpoint_payload(&payload).unwrap();
2247
        assert_eq!(back.len(), 2);
2248
        assert_eq!(back.heads(), vec![h2]);
2249
        assert_eq!(back.get(&h1).unwrap().message, "m");
2250
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2251
        // Replaying a further change onto the restored state equals a full build.
2252
        let c3 = change(
2253
            vec![h2],
2254
            vec![],
2255
            vec![Edit::Insert {
2256
                node: f,
2257
                after: AtomRef::Atom {
2258
                    change: h1,
2259
                    index: 1,
2260
                },
2261
                before: AtomRef::End,
2262
                lines: vec![b"3\n".to_vec()].into(),
2263
            }],
2264
        );
2265
        let mut full = st.clone();
2266
        full.add(c3.clone()).unwrap();
2267
        let mut restored = back;
2268
        restored.add(c3).unwrap();
2269
        let (a, b) = (full.materialize(), restored.materialize());
2270
        assert_eq!(
2271
            a.files.keys().collect::<Vec<_>>(),
2272
            b.files.keys().collect::<Vec<_>>()
2273
        );
2274
        assert_eq!(a.files["a"].content, b.files["a"].content);
2275
        assert!(
2276
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2277
        );
2278
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
2279
    }
2280
2281
    /// History-only states (O10f): the same state as a full load once its
2282
    /// graphs are built, by replay and from a version 2 checkpoint with
2283
    /// later changes; unloaded graphs are never read as empty.
2284
    #[test]
2285
    fn graph_keys_change_exactly_when_a_graph_does() {
2286
        let (f, g) = (NodeId::random(), NodeId::random());
2287
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2288
            node,
2289
            kind: NodeKind::File,
2290
            mode: Mode::TEXT,
2291
            parent: NodeId::ROOT,
2292
            name: name.into(),
2293
        };
2294
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
2295
            node,
2296
            after: AtomRef::Start,
2297
            before: AtomRef::End,
2298
            lines: vec![line.to_vec()].into(),
2299
        };
2300
        let c1 = change(
2301
            vec![],
2302
            vec![add(f, "f"), add(g, "g")],
2303
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2304
        );
2305
        let h1 = c1.hash();
2306
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
2307
        let h2 = c2.hash();
2308
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
2309
        let load = |cs: &[&Change]| {
2310
            let mut st = State::new_history_only();
2311
            for c in cs {
2312
                st.add((*c).clone()).unwrap();
2313
            }
2314
            st
2315
        };
2316
        let s1 = load(&[&c1]);
2317
        let s2 = load(&[&c1, &c2]);
2318
        let s3 = load(&[&c1, &c2, &c3]);
2319
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
2320
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
2321
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
2322
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
2323
        assert_ne!(key(&s2, &f), key(&s3, &f));
2324
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
2325
        let mut built = load(&[&c1]);
2326
        built
2327
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
2328
            .unwrap();
2329
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
2330
        let mut full = State::new();
2331
        full.add(c1.clone()).unwrap();
2332
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2333
2334
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2335
        // or inline values: stable across loads, changed by later edits.
2336
        let graphs = full.checkpoint_file_graphs();
2337
        let index = full.checkpoint_index(&graphs, |enc| {
2338
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
2339
        });
2340
        let cp = |extra: &[&Change]| {
2341
            let mut st = State::from_checkpoint_history(&index).unwrap();
2342
            for c in extra {
2343
                st.add((*c).clone()).unwrap();
2344
            }
2345
            st
2346
        };
2347
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
2348
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
2349
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
2350
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2351
2352
        // Partial rendering: skipped files are listed and empty, the others
2353
        // render as in a full state.
2354
        let mut part = load(&[&c1, &c2]);
2355
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
2356
            .unwrap();
2357
        let snap = part.materialize_except(&[f].into_iter().collect());
2358
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
2359
        let mut whole = State::new();
2360
        whole.add(c1.clone()).unwrap();
2361
        whole.add(c2.clone()).unwrap();
2362
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
2363
        assert!(
2364
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2365
        );
2366
    }
2367
2368
    #[test]
2369
    fn history_only_states_build_the_same_graphs_on_demand() {
2370
        let small = NodeId::random();
2371
        let big = NodeId::random();
2372
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2373
            node,
2374
            kind: NodeKind::File,
2375
            mode: Mode::TEXT,
2376
            parent: NodeId::ROOT,
2377
            name: name.into(),
2378
        };
2379
        let lines: crate::lines::Lines = (0..300)
2380
            .map(|i| format!("line {i}\n").into_bytes())
2381
            .collect();
2382
        let c1 = change(
2383
            vec![],
2384
            vec![add(small, "small"), add(big, "big")],
2385
            vec![
2386
                Edit::Insert {
2387
                    node: small,
2388
                    after: AtomRef::Start,
2389
                    before: AtomRef::End,
2390
                    lines: vec![b"x\n".to_vec()].into(),
2391
                },
2392
                Edit::Insert {
2393
                    node: big,
2394
                    after: AtomRef::Start,
2395
                    before: AtomRef::End,
2396
                    lines,
2397
                },
2398
            ],
2399
        );
2400
        let h1 = c1.hash();
2401
        let c2 = change(
2402
            vec![h1],
2403
            vec![],
2404
            vec![
2405
                Edit::Delete {
2406
                    node: big,
2407
                    atoms: vec![AtomRange {
2408
                        change: h1,
2409
                        from: 2,
2410
                        to: 9,
2411
                    }],
2412
                },
2413
                Edit::Insert {
2414
                    node: big,
2415
                    after: AtomRef::Atom {
2416
                        change: h1,
2417
                        index: 20,
2418
                    },
2419
                    before: AtomRef::Atom {
2420
                        change: h1,
2421
                        index: 21,
2422
                    },
2423
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
2424
                },
2425
                Edit::Insert {
2426
                    node: small,
2427
                    after: AtomRef::Atom {
2428
                        change: h1,
2429
                        index: 0,
2430
                    },
2431
                    before: AtomRef::End,
2432
                    lines: vec![b"y\n".to_vec()].into(),
2433
                },
2434
            ],
2435
        );
2436
        let h2 = c2.hash();
2437
        let c3 = change(
2438
            vec![h2],
2439
            vec![],
2440
            vec![Edit::Delete {
2441
                node: small,
2442
                atoms: vec![AtomRange {
2443
                    change: h1,
2444
                    from: 0,
2445
                    to: 1,
2446
                }],
2447
            }],
2448
        );
2449
2450
        let mut full = State::new();
2451
        for c in [&c1, &c2, &c3] {
2452
            full.add(c.clone()).unwrap();
2453
        }
2454
        // By replay: nothing built until asked, then exactly the full graphs.
2455
        let mut hist = State::new_history_only();
2456
        for c in [&c1, &c2, &c3] {
2457
            hist.add(c.clone()).unwrap();
2458
        }
2459
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
2460
        assert_eq!(hist.len(), 3);
2461
        hist.load_graphs(
2462
            &[big],
2463
            |_| unreachable!("no checkpoint"),
2464
            |_| unreachable!(),
2465
        )
2466
        .unwrap();
2467
        assert_eq!(
2468
            hist.render_file(&big).0,
2469
            full.render_file(&big).0,
2470
            "one file on its own"
2471
        );
2472
        assert!(!hist.is_full());
2473
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
2474
            .unwrap();
2475
        assert!(hist.is_full());
2476
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2477
2478
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
2479
        let mut base = State::new();
2480
        base.add(c1.clone()).unwrap();
2481
        base.add(c2.clone()).unwrap();
2482
        let graphs = base.checkpoint_file_graphs();
2483
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
2484
        let index = base.checkpoint_index(&graphs, |enc| {
2485
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
2486
            blobs.insert(r, enc.to_vec());
2487
            r
2488
        });
2489
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
2490
        from_cp.add(c3.clone()).unwrap();
2491
        assert!(!from_cp.is_full());
2492
        let mut fetched = 0;
2493
        from_cp
2494
            .load_graphs(
2495
                &[small, big],
2496
                |refs| {
2497
                    fetched += refs.len();
2498
                    refs.iter()
2499
                        .map(|r| {
2500
                            blobs
2501
                                .get(r)
2502
                                .cloned()
2503
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
2504
                        })
2505
                        .collect()
2506
                },
2507
                |_| unreachable!(),
2508
            )
2509
            .unwrap();
2510
        assert_eq!(
2511
            fetched, 1,
2512
            "the large graph's blob, in one batch; the small one was inline"
2513
        );
2514
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
2515
    }
2516
2517
    #[test]
2518
    #[should_panic(expected = "was not loaded")]
2519
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
2520
        let f = NodeId::random();
2521
        let mut st = State::new_history_only();
2522
        st.add(change(
2523
            vec![],
2524
            vec![TreeOp::AddNode {
2525
                node: f,
2526
                kind: NodeKind::File,
2527
                mode: Mode::TEXT,
2528
                parent: NodeId::ROOT,
2529
                name: "a".into(),
2530
            }],
2531
            vec![Edit::Insert {
2532
                node: f,
2533
                after: AtomRef::Start,
2534
                before: AtomRef::End,
2535
                lines: vec![b"a\n".to_vec()].into(),
2536
            }],
2537
        ))
2538
        .unwrap();
2539
        st.render_file(&f);
2540
    }
2541
2542
    #[test]
2543
    #[should_panic(expected = "needs every file graph")]
2544
    fn materializing_a_history_only_state_is_refused() {
2545
        let f = NodeId::random();
2546
        let mut st = State::new_history_only();
2547
        st.add(change(
2548
            vec![],
2549
            vec![TreeOp::AddNode {
2550
                node: f,
2551
                kind: NodeKind::File,
2552
                mode: Mode::TEXT,
2553
                parent: NodeId::ROOT,
2554
                name: "a".into(),
2555
            }],
2556
            vec![Edit::Insert {
2557
                node: f,
2558
                after: AtomRef::Start,
2559
                before: AtomRef::End,
2560
                lines: vec![b"a\n".to_vec()].into(),
2561
            }],
2562
        ))
2563
        .unwrap();
2564
        st.materialize();
2565
    }
2566
2567
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
2568
    /// blob; the state read back is the same as from version 1.
2569
    #[test]
2570
    fn checkpoint_index_round_trip_matches_version_1() {
2571
        let mut st = State::new();
2572
        let small = NodeId::random();
2573
        let big = NodeId::random();
2574
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2575
            node,
2576
            kind: NodeKind::File,
2577
            mode: Mode::TEXT,
2578
            parent: NodeId::ROOT,
2579
            name: name.into(),
2580
        };
2581
        let big_lines: crate::lines::Lines = (0..400)
2582
            .map(|i| format!("line {i} of a long file\n").into_bytes())
2583
            .collect();
2584
        let h1 = st
2585
            .add(change(
2586
                vec![],
2587
                vec![add(small, "small"), add(big, "big")],
2588
                vec![
2589
                    Edit::Insert {
2590
                        node: small,
2591
                        after: AtomRef::Start,
2592
                        before: AtomRef::End,
2593
                        lines: vec![b"x\n".to_vec()].into(),
2594
                    },
2595
                    Edit::Insert {
2596
                        node: big,
2597
                        after: AtomRef::Start,
2598
                        before: AtomRef::End,
2599
                        lines: big_lines,
2600
                    },
2601
                ],
2602
            ))
2603
            .unwrap();
2604
        st.add(change(
2605
            vec![h1],
2606
            vec![],
2607
            vec![Edit::Delete {
2608
                node: big,
2609
                atoms: vec![AtomRange {
2610
                    change: h1,
2611
                    from: 3,
2612
                    to: 7,
2613
                }],
2614
            }],
2615
        ))
2616
        .unwrap();
2617
2618
        let graphs = st.checkpoint_file_graphs();
2619
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
2620
        let index = st.checkpoint_index(&graphs, |enc| {
2621
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
2622
            blobs.insert(r, enc.to_vec());
2623
            r
2624
        });
2625
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
2626
        assert_eq!(
2627
            State::checkpoint_graph_refs(&index).unwrap(),
2628
            blobs.keys().copied().collect::<Vec<_>>()
2629
        );
2630
        assert!(
2631
            State::checkpoint_graph_refs(&st.checkpoint_payload())
2632
                .unwrap()
2633
                .is_empty(),
2634
            "version 1 names none"
2635
        );
2636
        assert!(index.len() < st.checkpoint_payload().len());
2637
2638
        let back = State::from_checkpoint(&index, |refs| {
2639
            refs.iter()
2640
                .map(|r| {
2641
                    blobs
2642
                        .get(r)
2643
                        .cloned()
2644
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
2645
                })
2646
                .collect()
2647
        })
2648
        .unwrap();
2649
        assert_eq!(
2650
            back.checkpoint_payload(),
2651
            st.checkpoint_payload(),
2652
            "the same state as version 1"
2653
        );
2654
        assert_eq!(
2655
            back.materialize().files["big"].content,
2656
            st.materialize().files["big"].content
2657
        );
2658
        // Deterministic: the same state gives the same index.
2659
        assert_eq!(
2660
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
2661
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
2662
            }),
2663
            index
2664
        );
2665
        // A missing graph blob is an error, not an empty file.
2666
        assert!(
2667
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
2668
        );
2669
        assert!(
2670
            State::from_checkpoint_payload(&index).is_err(),
2671
            "version 2 needs its blobs"
2672
        );
2673
        // Version 1 payloads still read, and unknown versions do not.
2674
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
2675
        let mut v3 = cbor::decode(&index).unwrap();
2676
        if let Value::Map(m) = &mut v3 {
2677
            m.insert(0, Value::Uint(3));
2678
        }
2679
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
2680
    }
2681
2682
    #[test]
2683
    fn maximal_elements() {
2684
        let mut st = State::new();
2685
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
2686
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
2687
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
2688
        let mut m = st.maximal(&[h1, h2, h3]);
2689
        m.sort();
2690
        let mut want = vec![h2, h3];
2691
        want.sort();
2692
        assert_eq!(m, want);
2693
        assert_eq!(st.heads(), want);
2694
    }
2695
2696
    /// The bounded walk of `depends_on` agrees with the closure on random
2697
    /// graphs, and the memo stays within its bound.
2698
    #[test]
2699
    fn depends_on_matches_the_closure() {
2700
        use rand::{Rng, SeedableRng};
2701
        let mut rng = rand::rngs::StdRng::seed_from_u64(11);
2702
        for _ in 0..10 {
2703
            let mut st = State::new();
2704
            let mut all: Vec<ChangeHash> = Vec::new();
2705
            for _ in 0..80 {
2706
                let deps: Vec<ChangeHash> =
2707
                    all.iter().copied().filter(|_| rng.gen_bool(0.06)).collect();
2708
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2709
            }
2710
            let unknown = ObjectRef([0xee; 32]);
2711
            for a in &all {
2712
                let want = st.closure(a).clone();
2713
                st.closure.lock().unwrap().sets.clear();
2714
                st.closure.lock().unwrap().held = 0;
2715
                for b in all.iter().chain([&unknown]) {
2716
                    assert_eq!(
2717
                        st.depends_on(a, b),
2718
                        a == b || want.contains(b),
2719
                        "{a:?} on {b:?}"
2720
                    );
2721
                }
2722
            }
2723
            assert!(st.closure.lock().unwrap().held <= CLOSURE_MEMO_HASHES);
2724
        }
2725
    }
2726
2727
    /// The one-walk `maximal` agrees with the definition (not in the
2728
    /// closure of another element) on random graphs, with repeated and
2729
    /// unknown hashes among the input.
2730
    #[test]
2731
    fn maximal_matches_its_definition() {
2732
        use rand::{Rng, SeedableRng};
2733
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
2734
        for _ in 0..20 {
2735
            let mut st = State::new();
2736
            let mut all: Vec<ChangeHash> = Vec::new();
2737
            for _ in 0..60 {
2738
                let deps: Vec<ChangeHash> =
2739
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
2740
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2741
            }
2742
            let mut pick: Vec<ChangeHash> =
2743
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
2744
            pick.extend(pick.clone().into_iter().take(3));
2745
            pick.push(ObjectRef([0xee; 32]));
2746
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
2747
            let want: Vec<ChangeHash> = set
2748
                .iter()
2749
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
2750
                .copied()
2751
                .collect();
2752
            assert_eq!(st.maximal(&pick), want);
2753
            assert_eq!(st.maximal(&all), st.heads());
2754
        }
2755
    }
2756
}