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