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