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