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