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