OXYGENHUB
# 6f8aeb996558 oxygen / crates / oxy-core / src / state.rs
63.3 KiB · Rust · last changed Store large inserts as text blobs (change format 2) 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
            version: crate::objects::CHANGE_VERSION,
1088
            change_id: ChangeId::random(),
1089
            deps,
1090
            author: ObjectRef::ZERO,
1091
            hlc: Hlc {
1092
                wall_ms: 1,
1093
                logical: 0,
1094
            },
1095
            message: "m".into(),
1096
            tree_ops,
1097
            edits,
1098
            kind: ChangeKind::Normal,
1099
        };
1100
        c.normalize();
1101
        c
1102
    }
1103
1104
    #[test]
1105
    fn build_edit_and_materialize() {
1106
        let mut st = State::new();
1107
        let f = NodeId::random();
1108
        let c1 = change(
1109
            vec![],
1110
            vec![TreeOp::AddNode {
1111
                node: f,
1112
                kind: NodeKind::File,
1113
                mode: Mode::TEXT,
1114
                parent: NodeId::ROOT,
1115
                name: "a.txt".into(),
1116
            }],
1117
            vec![Edit::Insert {
1118
                node: f,
1119
                after: AtomRef::Start,
1120
                before: AtomRef::End,
1121
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()],
1122
            }],
1123
        );
1124
        let h1 = st.add(c1).unwrap();
1125
        // Depends on h1: append a line and delete "one".
1126
        let c2 = change(
1127
            vec![h1],
1128
            vec![],
1129
            vec![
1130
                Edit::Delete {
1131
                    node: f,
1132
                    atoms: vec![AtomRange {
1133
                        change: h1,
1134
                        from: 0,
1135
                        to: 1,
1136
                    }],
1137
                },
1138
                Edit::Insert {
1139
                    node: f,
1140
                    after: AtomRef::Atom {
1141
                        change: h1,
1142
                        index: 1,
1143
                    },
1144
                    before: AtomRef::End,
1145
                    lines: vec![b"three\n".to_vec()],
1146
                },
1147
            ],
1148
        );
1149
        let h2 = st.add(c2).unwrap();
1150
        assert_eq!(st.heads(), vec![h2]);
1151
        assert!(st.depends_on(&h2, &h1));
1152
        assert!(!st.depends_on(&h1, &h2));
1153
        let snap = st.materialize();
1154
        assert!(!snap.is_conflicted());
1155
        let a = &snap.files["a.txt"];
1156
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
1157
        assert_eq!(st.live_lines(&f).len(), 2);
1158
    }
1159
1160
    #[test]
1161
    fn missing_dependency_is_rejected() {
1162
        let mut st = State::new();
1163
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
1164
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
1165
    }
1166
1167
    #[test]
1168
    fn self_references_and_multi_insert_indexing() {
1169
        let mut st = State::new();
1170
        let f = NodeId::random();
1171
        let me = OpRef {
1172
            change: ObjectRef::ZERO,
1173
            index: 0,
1174
        };
1175
        let c1 = change(
1176
            vec![],
1177
            vec![
1178
                TreeOp::AddNode {
1179
                    node: f,
1180
                    kind: NodeKind::File,
1181
                    mode: Mode::TEXT,
1182
                    parent: NodeId::ROOT,
1183
                    name: "x".into(),
1184
                },
1185
                TreeOp::SetMode {
1186
                    node: f,
1187
                    old: me,
1188
                    mode: Mode {
1189
                        exec: true,
1190
                        opaque: false,
1191
                    },
1192
                },
1193
            ],
1194
            vec![
1195
                Edit::Insert {
1196
                    node: f,
1197
                    after: AtomRef::Start,
1198
                    before: AtomRef::End,
1199
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()],
1200
                },
1201
                // Insert between the two lines just inserted, using self references.
1202
                Edit::Insert {
1203
                    node: f,
1204
                    after: AtomRef::Atom {
1205
                        change: ObjectRef::ZERO,
1206
                        index: 0,
1207
                    },
1208
                    before: AtomRef::Atom {
1209
                        change: ObjectRef::ZERO,
1210
                        index: 1,
1211
                    },
1212
                    lines: vec![b"b\n".to_vec()],
1213
                },
1214
            ],
1215
        );
1216
        st.add(c1).unwrap();
1217
        let snap = st.materialize();
1218
        let x = &snap.files["x"];
1219
        assert_eq!(
1220
            x.mode,
1221
            Mode {
1222
                exec: true,
1223
                opaque: false
1224
            }
1225
        );
1226
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
1227
    }
1228
1229
    #[test]
1230
    fn opaque_replace_and_conflict() {
1231
        let mut st = State::new();
1232
        let f = NodeId::random();
1233
        let b1 = ObjectRef([1; 32]);
1234
        let b2 = ObjectRef([2; 32]);
1235
        let b3 = ObjectRef([3; 32]);
1236
        let h1 = st
1237
            .add(change(
1238
                vec![],
1239
                vec![TreeOp::AddNode {
1240
                    node: f,
1241
                    kind: NodeKind::File,
1242
                    mode: Mode::OPAQUE,
1243
                    parent: NodeId::ROOT,
1244
                    name: "img".into(),
1245
                }],
1246
                vec![Edit::Replace {
1247
                    node: f,
1248
                    old: None,
1249
                    new: Some(b1),
1250
                }],
1251
            ))
1252
            .unwrap();
1253
        assert_eq!(st.live_blobs(&f), vec![b1]);
1254
        st.add(change(
1255
            vec![h1],
1256
            vec![],
1257
            vec![Edit::Replace {
1258
                node: f,
1259
                old: Some(b1),
1260
                new: Some(b2),
1261
            }],
1262
        ))
1263
        .unwrap();
1264
        st.add(change(
1265
            vec![h1],
1266
            vec![],
1267
            vec![Edit::Replace {
1268
                node: f,
1269
                old: Some(b1),
1270
                new: Some(b3),
1271
            }],
1272
        ))
1273
        .unwrap();
1274
        let snap = st.materialize();
1275
        assert!(snap.is_conflicted());
1276
        assert!(
1277
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
1278
        );
1279
    }
1280
1281
    #[test]
1282
    fn checkpoint_payload_round_trip_and_replay() {
1283
        let mut st = State::new();
1284
        let f = NodeId::random();
1285
        let h1 = st
1286
            .add(change(
1287
                vec![],
1288
                vec![TreeOp::AddNode {
1289
                    node: f,
1290
                    kind: NodeKind::File,
1291
                    mode: Mode::TEXT,
1292
                    parent: NodeId::ROOT,
1293
                    name: "a".into(),
1294
                }],
1295
                vec![Edit::Insert {
1296
                    node: f,
1297
                    after: AtomRef::Start,
1298
                    before: AtomRef::End,
1299
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()],
1300
                }],
1301
            ))
1302
            .unwrap();
1303
        let h2 = st
1304
            .add(change(
1305
                vec![h1],
1306
                vec![],
1307
                vec![Edit::Delete {
1308
                    node: f,
1309
                    atoms: vec![AtomRange {
1310
                        change: h1,
1311
                        from: 0,
1312
                        to: 1,
1313
                    }],
1314
                }],
1315
            ))
1316
            .unwrap();
1317
        let payload = st.checkpoint_payload();
1318
        let back = State::from_checkpoint_payload(&payload).unwrap();
1319
        assert_eq!(back.len(), 2);
1320
        assert_eq!(back.heads(), vec![h2]);
1321
        assert_eq!(back.get(&h1).unwrap().message, "m");
1322
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
1323
        // Replaying a further change onto the restored state equals a full build.
1324
        let c3 = change(
1325
            vec![h2],
1326
            vec![],
1327
            vec![Edit::Insert {
1328
                node: f,
1329
                after: AtomRef::Atom {
1330
                    change: h1,
1331
                    index: 1,
1332
                },
1333
                before: AtomRef::End,
1334
                lines: vec![b"3\n".to_vec()],
1335
            }],
1336
        );
1337
        let mut full = st.clone();
1338
        full.add(c3.clone()).unwrap();
1339
        let mut restored = back;
1340
        restored.add(c3).unwrap();
1341
        let (a, b) = (full.materialize(), restored.materialize());
1342
        assert_eq!(
1343
            a.files.keys().collect::<Vec<_>>(),
1344
            b.files.keys().collect::<Vec<_>>()
1345
        );
1346
        assert_eq!(a.files["a"].content, b.files["a"].content);
1347
        assert!(
1348
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
1349
        );
1350
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
1351
    }
1352
1353
    /// History-only states (O10f): the same state as a full load once its
1354
    /// graphs are built, by replay and from a version 2 checkpoint with
1355
    /// later changes; unloaded graphs are never read as empty.
1356
    #[test]
1357
    fn graph_keys_change_exactly_when_a_graph_does() {
1358
        let (f, g) = (NodeId::random(), NodeId::random());
1359
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1360
            node,
1361
            kind: NodeKind::File,
1362
            mode: Mode::TEXT,
1363
            parent: NodeId::ROOT,
1364
            name: name.into(),
1365
        };
1366
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
1367
            node,
1368
            after: AtomRef::Start,
1369
            before: AtomRef::End,
1370
            lines: vec![line.to_vec()],
1371
        };
1372
        let c1 = change(
1373
            vec![],
1374
            vec![add(f, "f"), add(g, "g")],
1375
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
1376
        );
1377
        let h1 = c1.hash();
1378
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
1379
        let h2 = c2.hash();
1380
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
1381
        let load = |cs: &[&Change]| {
1382
            let mut st = State::new_history_only();
1383
            for c in cs {
1384
                st.add((*c).clone()).unwrap();
1385
            }
1386
            st
1387
        };
1388
        let s1 = load(&[&c1]);
1389
        let s2 = load(&[&c1, &c2]);
1390
        let s3 = load(&[&c1, &c2, &c3]);
1391
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
1392
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
1393
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
1394
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
1395
        assert_ne!(key(&s2, &f), key(&s3, &f));
1396
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
1397
        let mut built = load(&[&c1]);
1398
        built.load_graphs(&[f], |_| unreachable!()).unwrap();
1399
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
1400
        let mut full = State::new();
1401
        full.add(c1.clone()).unwrap();
1402
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
1403
1404
        // Through a version 2 checkpoint of c1, keys name its graph blobs
1405
        // or inline values: stable across loads, changed by later edits.
1406
        let graphs = full.checkpoint_file_graphs();
1407
        let index = full.checkpoint_index(&graphs, |enc| {
1408
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
1409
        });
1410
        let cp = |extra: &[&Change]| {
1411
            let mut st = State::from_checkpoint_history(&index).unwrap();
1412
            for c in extra {
1413
                st.add((*c).clone()).unwrap();
1414
            }
1415
            st
1416
        };
1417
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
1418
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
1419
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
1420
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
1421
1422
        // Partial rendering: skipped files are listed and empty, the others
1423
        // render as in a full state.
1424
        let mut part = load(&[&c1, &c2]);
1425
        part.load_graphs(&[g], |_| unreachable!()).unwrap();
1426
        let snap = part.materialize_except(&[f].into_iter().collect());
1427
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
1428
        let mut whole = State::new();
1429
        whole.add(c1.clone()).unwrap();
1430
        whole.add(c2.clone()).unwrap();
1431
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
1432
        assert!(
1433
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
1434
        );
1435
    }
1436
1437
    #[test]
1438
    fn history_only_states_build_the_same_graphs_on_demand() {
1439
        let small = NodeId::random();
1440
        let big = NodeId::random();
1441
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1442
            node,
1443
            kind: NodeKind::File,
1444
            mode: Mode::TEXT,
1445
            parent: NodeId::ROOT,
1446
            name: name.into(),
1447
        };
1448
        let lines: Vec<Vec<u8>> = (0..300)
1449
            .map(|i| format!("line {i}\n").into_bytes())
1450
            .collect();
1451
        let c1 = change(
1452
            vec![],
1453
            vec![add(small, "small"), add(big, "big")],
1454
            vec![
1455
                Edit::Insert {
1456
                    node: small,
1457
                    after: AtomRef::Start,
1458
                    before: AtomRef::End,
1459
                    lines: vec![b"x\n".to_vec()],
1460
                },
1461
                Edit::Insert {
1462
                    node: big,
1463
                    after: AtomRef::Start,
1464
                    before: AtomRef::End,
1465
                    lines,
1466
                },
1467
            ],
1468
        );
1469
        let h1 = c1.hash();
1470
        let c2 = change(
1471
            vec![h1],
1472
            vec![],
1473
            vec![
1474
                Edit::Delete {
1475
                    node: big,
1476
                    atoms: vec![AtomRange {
1477
                        change: h1,
1478
                        from: 2,
1479
                        to: 9,
1480
                    }],
1481
                },
1482
                Edit::Insert {
1483
                    node: big,
1484
                    after: AtomRef::Atom {
1485
                        change: h1,
1486
                        index: 20,
1487
                    },
1488
                    before: AtomRef::Atom {
1489
                        change: h1,
1490
                        index: 21,
1491
                    },
1492
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()],
1493
                },
1494
                Edit::Insert {
1495
                    node: small,
1496
                    after: AtomRef::Atom {
1497
                        change: h1,
1498
                        index: 0,
1499
                    },
1500
                    before: AtomRef::End,
1501
                    lines: vec![b"y\n".to_vec()],
1502
                },
1503
            ],
1504
        );
1505
        let h2 = c2.hash();
1506
        let c3 = change(
1507
            vec![h2],
1508
            vec![],
1509
            vec![Edit::Delete {
1510
                node: small,
1511
                atoms: vec![AtomRange {
1512
                    change: h1,
1513
                    from: 0,
1514
                    to: 1,
1515
                }],
1516
            }],
1517
        );
1518
1519
        let mut full = State::new();
1520
        for c in [&c1, &c2, &c3] {
1521
            full.add(c.clone()).unwrap();
1522
        }
1523
        // By replay: nothing built until asked, then exactly the full graphs.
1524
        let mut hist = State::new_history_only();
1525
        for c in [&c1, &c2, &c3] {
1526
            hist.add(c.clone()).unwrap();
1527
        }
1528
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
1529
        assert_eq!(hist.len(), 3);
1530
        hist.load_graphs(&[big], |_| unreachable!("no checkpoint"))
1531
            .unwrap();
1532
        assert_eq!(
1533
            hist.render_file(&big).0,
1534
            full.render_file(&big).0,
1535
            "one file on its own"
1536
        );
1537
        assert!(!hist.is_full());
1538
        hist.load_graphs(&[small, big], |_| unreachable!()).unwrap();
1539
        assert!(hist.is_full());
1540
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
1541
1542
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
1543
        let mut base = State::new();
1544
        base.add(c1.clone()).unwrap();
1545
        base.add(c2.clone()).unwrap();
1546
        let graphs = base.checkpoint_file_graphs();
1547
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
1548
        let index = base.checkpoint_index(&graphs, |enc| {
1549
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
1550
            blobs.insert(r, enc.to_vec());
1551
            r
1552
        });
1553
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
1554
        from_cp.add(c3.clone()).unwrap();
1555
        assert!(!from_cp.is_full());
1556
        let mut fetched = 0;
1557
        from_cp
1558
            .load_graphs(&[small, big], |refs| {
1559
                fetched += refs.len();
1560
                refs.iter()
1561
                    .map(|r| {
1562
                        blobs
1563
                            .get(r)
1564
                            .cloned()
1565
                            .ok_or_else(|| ObjectError::Schema("missing".into()))
1566
                    })
1567
                    .collect()
1568
            })
1569
            .unwrap();
1570
        assert_eq!(
1571
            fetched, 1,
1572
            "the large graph's blob, in one batch; the small one was inline"
1573
        );
1574
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
1575
    }
1576
1577
    #[test]
1578
    #[should_panic(expected = "was not loaded")]
1579
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
1580
        let f = NodeId::random();
1581
        let mut st = State::new_history_only();
1582
        st.add(change(
1583
            vec![],
1584
            vec![TreeOp::AddNode {
1585
                node: f,
1586
                kind: NodeKind::File,
1587
                mode: Mode::TEXT,
1588
                parent: NodeId::ROOT,
1589
                name: "a".into(),
1590
            }],
1591
            vec![Edit::Insert {
1592
                node: f,
1593
                after: AtomRef::Start,
1594
                before: AtomRef::End,
1595
                lines: vec![b"a\n".to_vec()],
1596
            }],
1597
        ))
1598
        .unwrap();
1599
        st.render_file(&f);
1600
    }
1601
1602
    #[test]
1603
    #[should_panic(expected = "needs every file graph")]
1604
    fn materializing_a_history_only_state_is_refused() {
1605
        let f = NodeId::random();
1606
        let mut st = State::new_history_only();
1607
        st.add(change(
1608
            vec![],
1609
            vec![TreeOp::AddNode {
1610
                node: f,
1611
                kind: NodeKind::File,
1612
                mode: Mode::TEXT,
1613
                parent: NodeId::ROOT,
1614
                name: "a".into(),
1615
            }],
1616
            vec![Edit::Insert {
1617
                node: f,
1618
                after: AtomRef::Start,
1619
                before: AtomRef::End,
1620
                lines: vec![b"a\n".to_vec()],
1621
            }],
1622
        ))
1623
        .unwrap();
1624
        st.materialize();
1625
    }
1626
1627
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
1628
    /// blob; the state read back is the same as from version 1.
1629
    #[test]
1630
    fn checkpoint_index_round_trip_matches_version_1() {
1631
        let mut st = State::new();
1632
        let small = NodeId::random();
1633
        let big = NodeId::random();
1634
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1635
            node,
1636
            kind: NodeKind::File,
1637
            mode: Mode::TEXT,
1638
            parent: NodeId::ROOT,
1639
            name: name.into(),
1640
        };
1641
        let big_lines: Vec<Vec<u8>> = (0..400)
1642
            .map(|i| format!("line {i} of a long file\n").into_bytes())
1643
            .collect();
1644
        let h1 = st
1645
            .add(change(
1646
                vec![],
1647
                vec![add(small, "small"), add(big, "big")],
1648
                vec![
1649
                    Edit::Insert {
1650
                        node: small,
1651
                        after: AtomRef::Start,
1652
                        before: AtomRef::End,
1653
                        lines: vec![b"x\n".to_vec()],
1654
                    },
1655
                    Edit::Insert {
1656
                        node: big,
1657
                        after: AtomRef::Start,
1658
                        before: AtomRef::End,
1659
                        lines: big_lines,
1660
                    },
1661
                ],
1662
            ))
1663
            .unwrap();
1664
        st.add(change(
1665
            vec![h1],
1666
            vec![],
1667
            vec![Edit::Delete {
1668
                node: big,
1669
                atoms: vec![AtomRange {
1670
                    change: h1,
1671
                    from: 3,
1672
                    to: 7,
1673
                }],
1674
            }],
1675
        ))
1676
        .unwrap();
1677
1678
        let graphs = st.checkpoint_file_graphs();
1679
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
1680
        let index = st.checkpoint_index(&graphs, |enc| {
1681
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
1682
            blobs.insert(r, enc.to_vec());
1683
            r
1684
        });
1685
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
1686
        assert_eq!(
1687
            State::checkpoint_graph_refs(&index).unwrap(),
1688
            blobs.keys().copied().collect::<Vec<_>>()
1689
        );
1690
        assert!(
1691
            State::checkpoint_graph_refs(&st.checkpoint_payload())
1692
                .unwrap()
1693
                .is_empty(),
1694
            "version 1 names none"
1695
        );
1696
        assert!(index.len() < st.checkpoint_payload().len());
1697
1698
        let back = State::from_checkpoint(&index, |refs| {
1699
            refs.iter()
1700
                .map(|r| {
1701
                    blobs
1702
                        .get(r)
1703
                        .cloned()
1704
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
1705
                })
1706
                .collect()
1707
        })
1708
        .unwrap();
1709
        assert_eq!(
1710
            back.checkpoint_payload(),
1711
            st.checkpoint_payload(),
1712
            "the same state as version 1"
1713
        );
1714
        assert_eq!(
1715
            back.materialize().files["big"].content,
1716
            st.materialize().files["big"].content
1717
        );
1718
        // Deterministic: the same state gives the same index.
1719
        assert_eq!(
1720
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
1721
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
1722
            }),
1723
            index
1724
        );
1725
        // A missing graph blob is an error, not an empty file.
1726
        assert!(
1727
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
1728
        );
1729
        assert!(
1730
            State::from_checkpoint_payload(&index).is_err(),
1731
            "version 2 needs its blobs"
1732
        );
1733
        // Version 1 payloads still read, and unknown versions do not.
1734
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
1735
        let mut v3 = cbor::decode(&index).unwrap();
1736
        if let Value::Map(m) = &mut v3 {
1737
            m.insert(0, Value::Uint(3));
1738
        }
1739
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
1740
    }
1741
1742
    #[test]
1743
    fn maximal_elements() {
1744
        let mut st = State::new();
1745
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
1746
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
1747
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
1748
        let mut m = st.maximal(&[h1, h2, h3]);
1749
        m.sort();
1750
        let mut want = vec![h2, h3];
1751
        want.sort();
1752
        assert_eq!(m, want);
1753
        assert_eq!(st.heads(), want);
1754
    }
1755
1756
    /// The one-walk `maximal` agrees with the definition (not in the
1757
    /// closure of another element) on random graphs, with repeated and
1758
    /// unknown hashes among the input.
1759
    #[test]
1760
    fn maximal_matches_its_definition() {
1761
        use rand::{Rng, SeedableRng};
1762
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
1763
        for _ in 0..20 {
1764
            let mut st = State::new();
1765
            let mut all: Vec<ChangeHash> = Vec::new();
1766
            for _ in 0..60 {
1767
                let deps: Vec<ChangeHash> =
1768
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
1769
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
1770
            }
1771
            let mut pick: Vec<ChangeHash> =
1772
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
1773
            pick.extend(pick.clone().into_iter().take(3));
1774
            pick.push(ObjectRef([0xee; 32]));
1775
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
1776
            let want: Vec<ChangeHash> = set
1777
                .iter()
1778
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
1779
                .copied()
1780
                .collect();
1781
            assert_eq!(st.maximal(&pick), want);
1782
            assert_eq!(st.maximal(&all), st.heads());
1783
        }
1784
    }
1785
}