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