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