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