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