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