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