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