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