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