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