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