OXYGENHUB
# c3d2ef6104c2 oxygen / crates / oxy-core / src / state.rs
91.4 KiB · Rust · last changed Git import: a large merge renders its tree in batches 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>) {
dbf06d34 Andy McCall ↶ 607
    // The graph's kept order, if any, follows the edits (see `Order`).
608
    let order = g.take_order();
609
    let mut inserts: Vec<(Vertex, Vertex, u32, u32)> = Vec::new();
610
    let mut deleted: Vec<crate::graph::AtomKey> = Vec::new();
e8d38e47 Andy McCall ↶ 611
    let mut next = 0u32;
612
    for e in edits {
613
        match e {
614
            Edit::Insert {
615
                after,
616
                before,
617
                lines,
618
                ..
619
            } => {
620
                let first = next;
dbf06d34 Andy McCall ↶ 621
                let count = lines.len() as u32;
622
                next += count;
623
                let (after, before) = (vertex(after.resolve(h)), vertex(before.resolve(h)));
624
                inserts.push((after, before, first, count));
625
                g.insert_owned(h, first, after, before, lines);
e8d38e47 Andy McCall ↶ 626
            }
627
            Edit::Delete { atoms, .. } => {
628
                for r in atoms {
dbf06d34 Andy McCall ↶ 629
                    let r = r.resolve(h);
630
                    deleted.extend((r.from..r.to).map(|i| (r.change, i)));
631
                    g.delete(h, &r);
e8d38e47 Andy McCall ↶ 632
                }
633
            }
634
            Edit::Replace { .. } => {}
635
        }
dbf06d34 Andy McCall ↶ 636
    }
637
    if let Some(o) = order {
638
        g.keep_order(o.splice(h, &inserts, &deleted));
ff0af1ee unknown 639
    }
640
}
641
57d8dc05 Andy McCall ↶ 642
/// Build the graphs of deferred entries: their checkpoint bases and the
643
/// texts of inserts read without their lines are loaded in one call, then
644
/// the graphs are built in parallel (they are independent).
645
fn build_deferred(
3f1b8fe2 Andy McCall ↶ 646
    taken: Vec<(NodeId, Deferred)>,
57d8dc05 Andy McCall ↶ 647
    load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
648
    read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
649
) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
3f1b8fe2 Andy McCall ↶ 650
    let mut taken: Vec<(NodeId, DeferredBody)> =
651
        taken.into_iter().map(|(n, d)| (n, d.into_body())).collect();
57d8dc05 Andy McCall ↶ 652
    let mut refs: Vec<ObjectRef> = taken
653
        .iter()
654
        .filter_map(|(_, d)| match &d.base {
655
            Some(DeferredBase::Blob(r)) => Some(*r),
656
            _ => None,
657
        })
658
        .collect();
659
    // Text blobs of inserts read without their lines, after the bases.
660
    let bases = refs.len();
661
    refs.extend(taken.iter().flat_map(|(_, d)| {
662
        d.texts.iter().filter_map(|t| match t {
663
            TextRef::Blob(r, _) => Some(*r),
664
            TextRef::Inline { .. } => None,
665
        })
666
    }));
667
    // And the encodings of changes whose inline inserts are needed,
668
    // each read once.
669
    let mut changes: HashMap<ChangeHash, Arc<Vec<u8>>> = HashMap::new();
670
    for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
671
        if let TextRef::Inline { change, .. } = t {
672
            if !changes.contains_key(change) {
673
                changes.insert(*change, read_change(change)?);
674
            }
675
        }
676
    }
677
    let mut blobs = if refs.is_empty() {
678
        Vec::new()
679
    } else {
680
        load(&refs)?
681
    };
682
    if blobs.len() != refs.len() {
683
        return Err(ObjectError::Schema("graph blobs: wrong count".into()));
684
    }
685
    let mut texts = blobs.split_off(bases).into_iter();
686
    let mut blobs = blobs.into_iter();
687
    // Pair each graph with its blob, then build them all in parallel:
688
    // graphs are independent.
3f1b8fe2 Andy McCall ↶ 689
    let mut work: Vec<(NodeId, DeferredBody, Option<Vec<u8>>)> = Vec::with_capacity(taken.len());
57d8dc05 Andy McCall ↶ 690
    for (node, mut d) in taken.drain(..) {
691
        // Fill in the lines of inserts read without them, in order.
692
        let mut want = std::mem::take(&mut d.texts).into_iter();
693
        for (_, edits) in d.edits.iter_mut() {
694
            for e in edits.iter_mut() {
695
                if let Edit::Insert { lines, .. } = e {
696
                    if lines.is_empty() {
697
                        *lines = match want.next() {
698
                            Some(TextRef::Blob(_, count)) => {
699
                                let content = texts.next().ok_or_else(|| {
700
                                    ObjectError::Schema("text blobs: wrong count".into())
701
                                })?;
702
                                crate::objects::text_lines(&content, count)?
703
                            }
704
                            Some(TextRef::Inline { change, start, end }) => {
705
                                let bytes = &changes[&change];
706
                                let range =
707
                                    bytes.get(start as usize..end as usize).ok_or_else(|| {
708
                                        ObjectError::Schema(
709
                                            "an inline insert lies outside its change".into(),
710
                                        )
711
                                    })?;
712
                                crate::objects::inline_lines(range)?
713
                            }
714
                            None => {
715
                                return Err(ObjectError::Schema(
716
                                    "an insert's text is missing".into(),
717
                                ))
718
                            }
719
                        };
720
                    }
721
                }
722
            }
723
        }
724
        let bytes = match &d.base {
725
            Some(DeferredBase::Blob(_)) => Some(
726
                blobs
727
                    .next()
728
                    .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
729
            ),
730
            _ => None,
731
        };
732
        work.push((node, d, bytes));
733
    }
734
    use rayon::prelude::*;
735
    let built: Vec<(NodeId, FileGraph)> = work
736
        .into_par_iter()
737
        .map(|(node, mut d, bytes)| {
738
            let mut graph = match (d.base.take(), bytes) {
739
                (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
740
                (Some(DeferredBase::Blob(_)), Some(bytes)) => {
741
                    FileGraph::from_value(&cbor::decode(&bytes)?)?
742
                }
743
                _ => FileGraph::default(),
744
            };
745
            for (h, edits) in std::mem::take(&mut d.edits) {
746
                apply_file_edits(&mut graph, h, edits);
747
            }
748
            Ok((node, graph))
749
        })
750
        .collect::<Result<_, ObjectError>>()?;
751
    Ok(built)
752
}
753
ff0af1ee unknown 754
impl State {
755
    pub fn new() -> Self {
756
        Self::default()
e8d38e47 Andy McCall ↶ 757
    }
758
759
    /// An empty state for history only: changes and tree are kept, file
760
    /// edits are recorded but no file graph is built until
761
    /// [`State::load_graphs`] asks for it. For log and other commands that
762
    /// need no file contents, or only a few files.
763
    pub fn new_history_only() -> Self {
764
        State {
765
            deferred: Some(HashMap::new()),
766
            ..Self::default()
767
        }
768
    }
769
e83354cd Andy McCall ↶ 770
    /// Whether `node`'s file graph is built (always, in a full state).
771
    pub fn is_built(&self, node: &NodeId) -> bool {
772
        self.deferred.is_none() || self.files.contains_key(node)
773
    }
774
86e1824f Andy McCall ↶ 775
    /// Whether this state builds file graphs only when asked
776
    /// ([`State::new_history_only`]), even if it has none waiting.
777
    pub fn is_history_only(&self) -> bool {
778
        self.deferred.is_some()
779
    }
780
e8d38e47 Andy McCall ↶ 781
    /// Whether this state holds every file graph.
782
    pub fn is_full(&self) -> bool {
783
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
784
    }
785
786
    /// The graph of `node`, which must be loaded: asking a history-only
787
    /// state for a graph it has not built is a bug, never an empty file.
788
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
789
        if let Some(d) = &self.deferred {
790
            assert!(
791
                !d.contains_key(node),
792
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
793
                node.short(12)
794
            );
795
        }
dfb23a3a Andy McCall ↶ 796
        self.files.get(node).map(|g| g.as_ref())
e8d38e47 Andy McCall ↶ 797
    }
798
799
    /// Operations over every file need every graph.
800
    fn require_full(&self, what: &str) {
801
        assert!(
802
            self.is_full(),
803
            "{what} needs every file graph; this state was loaded for history only"
804
        );
805
    }
806
807
    /// Build the graphs of `nodes` in a history-only state: from their
808
    /// checkpoint base (blobs read in one batch through `load`) and their
809
    /// deferred edits. Nodes already built, or with no graph, are skipped.
810
    pub fn load_graphs(
811
        &mut self,
812
        nodes: &[NodeId],
813
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
519c7c06 Andy McCall ↶ 814
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
e8d38e47 Andy McCall ↶ 815
    ) -> Result<(), ObjectError> {
816
        let Some(deferred) = self.deferred.as_mut() else {
817
            return Ok(());
818
        };
57d8dc05 Andy McCall ↶ 819
        let taken: Vec<(NodeId, Deferred)> = nodes
e8d38e47 Andy McCall ↶ 820
            .iter()
f6451fbb Andy McCall ↶ 821
            .filter_map(|n| deferred.remove(n).map(|d| (*n, Arc::unwrap_or_clone(d))))
e8d38e47 Andy McCall ↶ 822
            .collect();
57d8dc05 Andy McCall ↶ 823
        let built = build_deferred(taken, load, read_change)?;
dfb23a3a Andy McCall ↶ 824
        self.files
825
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
cc7a0056 Andy McCall ↶ 826
        Ok(())
57d8dc05 Andy McCall ↶ 827
    }
828
829
    /// The graphs of `nodes`, built from this history-only state's deferred
830
    /// edits without building them in it: the state stays history only, so
831
    /// changes read without their lines can still be added to it and every
832
    /// graph keeps its key. For a caller that renders a few files of many
833
    /// states in turn (verifying an import).
834
    pub fn build_graphs_detached(
835
        &self,
836
        nodes: &[NodeId],
837
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
838
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
839
    ) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
840
        let Some(deferred) = self.deferred.as_ref() else {
841
            return Ok(Vec::new());
842
        };
843
        let copies: Vec<(NodeId, Deferred)> = nodes
844
            .iter()
f6451fbb Andy McCall ↶ 845
            .map(|n| {
846
                (
847
                    *n,
848
                    deferred.get(n).map(|d| (**d).clone()).unwrap_or_default(),
849
                )
850
            })
57d8dc05 Andy McCall ↶ 851
            .collect();
852
        build_deferred(copies, load, read_change)
853
    }
854
855
    /// Render a graph built for this state (see
856
    /// [`State::build_graphs_detached`]), as [`State::render_file`] does.
857
    pub fn render_graph(&self, g: &FileGraph) -> (Vec<u8>, Materialized) {
858
        let m = g.materialize(self);
859
        let bytes = g.render(&m, &|h| self.label(h));
860
        (bytes, m)
cc7a0056 Andy McCall ↶ 861
    }
862
69816d68 Andy McCall ↶ 863
    /// Every file graph a history-only state has not built, deleted files'
864
    /// included.
865
    pub fn unbuilt_nodes(&self) -> Vec<NodeId> {
866
        self.deferred
867
            .as_ref()
868
            .map(|d| d.keys().copied().collect())
869
            .unwrap_or_default()
870
    }
871
c5ce0367 Andy McCall ↶ 872
    /// Drop the built graphs of `nodes`, for a caller rendering a large
873
    /// tree a batch at a time. The state can no longer render those files,
874
    /// so it must not be used for them again.
875
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
876
        for n in nodes {
877
            self.files.remove(n);
878
        }
879
    }
880
cc7a0056 Andy McCall ↶ 881
    /// Build every graph a history-only state has not built, making it full.
882
    pub fn load_all_graphs(
883
        &mut self,
884
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
519c7c06 Andy McCall ↶ 885
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
cc7a0056 Andy McCall ↶ 886
    ) -> Result<(), ObjectError> {
887
        let nodes: Vec<NodeId> = match &self.deferred {
888
            Some(d) => d.keys().copied().collect(),
889
            None => return Ok(()),
890
        };
a4fad5b0 Andy McCall ↶ 891
        self.load_graphs(&nodes, load, read_change)?;
cc7a0056 Andy McCall ↶ 892
        self.deferred = None;
e8d38e47 Andy McCall ↶ 893
        Ok(())
cc7a0056 Andy McCall ↶ 894
    }
895
896
    /// A key for the graph of `node` in a history-only state that has not
897
    /// built it: equal keys mean equal graphs, so equal renderings (a
898
    /// rendering depends only on the graph and on the changes' own
899
    /// immutable metadata). It names the node, its checkpoint base (a blob,
900
    /// an inline value, or none) and the set of later changes that edited
901
    /// the file.
902
    /// `None` for a full state or a graph already built.
903
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
904
        let deferred = self.deferred.as_ref()?;
905
        if self.files.contains_key(node) {
906
            return None;
907
        }
908
        let mut h = blake3::Hasher::new();
909
        h.update(b"oxy graph key 1\0");
910
        // A change's edits are applied per node: the node is part of it.
911
        h.update(&node.0);
912
        let Some(d) = deferred.get(node) else {
913
            // Never edited: the empty graph.
914
            h.update(&[0]);
915
            return Some(*h.finalize().as_bytes());
916
        };
f9575918 Andy McCall ↶ 917
        Some(*d.key.get_or_init(|| d.graph_key(h)))
918
    }
919
920
    pub fn len(&self) -> usize {
921
        self.changes.len()
922
    }
fb5b6181 Andy McCall ↶ 923
fd280228 Andy McCall ↶ 924
    /// Turn this history-only state's built graphs back into deferred
925
    /// histories, each starting from its graph encoded as a checkpoint
926
    /// graph and stored by `store` (it returns the blob's reference): what
927
    /// they held stays, and memory goes back to what a history-only state
928
    /// costs. A graph built later again decodes that blob and applies only
929
    /// the edits that came after. Graph keys change (the base is now a
930
    /// blob), which only means a cached rendering is not reused.
931
    pub fn shed_graphs<E>(
932
        &mut self,
933
        mut store: impl FnMut(&[u8]) -> Result<ObjectRef, E>,
934
    ) -> Result<usize, E> {
935
        use rayon::prelude::*;
936
        let Some(deferred) = self.deferred.as_mut() else {
937
            return Ok(0);
938
        };
939
        let graphs: Vec<(NodeId, Arc<FileGraph>)> = self.files.drain().collect();
940
        let encoded: Vec<(NodeId, Vec<u8>)> = graphs
941
            .par_iter()
942
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
943
            .collect();
944
        drop(graphs);
945
        let shed = encoded.len();
946
        for (node, bytes) in encoded {
947
            let blob = store(&bytes)?;
948
            deferred.insert(
949
                node,
950
                Arc::new(Deferred::from_body(DeferredBody {
951
                    base: Some(DeferredBase::Blob(blob)),
952
                    ..DeferredBody::default()
953
                })),
954
            );
955
        }
956
        Ok(shed)
957
    }
958
fb5b6181 Andy McCall ↶ 959
    /// How many file graphs this state has built.
960
    pub fn built_count(&self) -> usize {
961
        self.files.len()
962
    }
f9575918 Andy McCall ↶ 963
}
964
965
impl Deferred {
966
    /// See [`State::graph_key`]: `h` has taken the node already.
967
    fn graph_key(&self, mut h: blake3::Hasher) -> [u8; 32] {
3f1b8fe2 Andy McCall ↶ 968
        let d = self.body();
cc7a0056 Andy McCall ↶ 969
        match &d.base {
970
            None => h.update(&[0]),
971
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
972
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
973
        };
974
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
975
        changes.sort();
976
        changes.dedup();
977
        h.update(&(changes.len() as u64).to_le_bytes());
978
        for c in changes {
979
            h.update(&c.0);
980
        }
f9575918 Andy McCall ↶ 981
        *h.finalize().as_bytes()
ff0af1ee unknown 982
    }
f9575918 Andy McCall ↶ 983
}
ff0af1ee unknown 984
f9575918 Andy McCall ↶ 985
impl State {
ff0af1ee unknown 986
    pub fn is_empty(&self) -> bool {
987
        self.changes.is_empty()
988
    }
989
    pub fn contains(&self, h: &ChangeHash) -> bool {
990
        self.changes.contains_key(h)
991
    }
252e8cb2 Andy McCall ↶ 992
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
f6451fbb Andy McCall ↶ 993
        self.changes.get(h).map(|m| &**m)
ff0af1ee unknown 994
    }
252e8cb2 Andy McCall ↶ 995
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
f6451fbb Andy McCall ↶ 996
        self.changes.iter().map(|(h, m)| (h, &**m))
ff0af1ee unknown 997
    }
998
    pub fn tree(&self) -> &TreeGraph {
999
        &self.tree
1000
    }
1001
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
e8d38e47 Andy McCall ↶ 1002
        self.graph(node)
ff0af1ee unknown 1003
    }
1004
1005
    /// Add a change whose dependencies are already present.
1006
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
1007
        let h = change.hash();
192fad1e Andy McCall ↶ 1008
        self.add_hashed(h, change)
1009
    }
1010
1011
    /// [`State::add`] for a change whose hash `h` is already known (it was
1012
    /// just stored), so it is not encoded again.
1013
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
ff0af1ee unknown 1014
        if self.changes.contains_key(&h) {
1015
            return Ok(h);
1016
        }
1017
        for d in &change.deps {
1018
            if !self.changes.contains_key(d) {
1019
                return Err(StateError::MissingDep(*d, h));
1020
            }
1021
        }
192fad1e Andy McCall ↶ 1022
        self.add_known(h, change, Vec::new());
1023
        Ok(h)
ff0af1ee unknown 1024
    }
1025
1026
    /// Add a change in any order; call `validate` once all are in.
1027
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
1028
        let h = change.hash();
86e1824f Andy McCall ↶ 1029
        self.add_known(h, change, Vec::new());
1030
        h
1031
    }
1032
ab4d4e31 Andy McCall ↶ 1033
    /// Add a change just stored under hash `h` to a history-only state that
1034
    /// has built some graphs: an edit of a built graph is applied whole
1035
    /// (from `full`), and one of a file not built waits without its text
1036
    /// (from `skeleton` and its `texts`, as the store reads it back), so the
1037
    /// state holds no text it has not built. A Git import adds each change
1038
    /// it makes this way, keeping memory to what changes.
1039
    pub fn add_known_mixed(
1040
        &mut self,
1041
        h: ChangeHash,
1042
        full: Change,
1043
        skeleton: Change,
1044
        texts: Vec<TextRef>,
1045
    ) {
1046
        if self.deferred.is_none() || self.changes.contains_key(&h) {
1047
            self.add_known(h, full, Vec::new());
1048
            return;
1049
        }
1050
        let Change {
1051
            version,
1052
            change_id,
1053
            deps,
1054
            author,
1055
            hlc,
1056
            message,
1057
            tree_ops,
1058
            edits: full_edits,
1059
            kind,
1060
        } = full;
1061
        let mut texts = texts.into_iter();
1062
        let mut edits = Vec::with_capacity(full_edits.len());
1063
        let mut kept = Vec::new();
1064
        for (f, s) in full_edits.into_iter().zip(skeleton.edits) {
1065
            let text = match &s {
1066
                Edit::Insert { lines, .. } if lines.is_empty() => texts.next(),
1067
                _ => None,
1068
            };
1069
            if self.files.contains_key(&f.node()) {
1070
                edits.push(f);
1071
            } else {
1072
                edits.push(s);
1073
                kept.extend(text);
1074
            }
1075
        }
1076
        let c = Change {
1077
            version,
1078
            change_id,
1079
            deps,
1080
            author,
1081
            hlc,
1082
            message,
1083
            tree_ops,
1084
            edits,
1085
            kind,
1086
        };
1087
        self.add_known(h, c, kept);
1088
    }
1089
86e1824f Andy McCall ↶ 1090
    /// Add a change read from the store under hash `h`, without hashing it
1091
    /// again (for a version 2 change that means chunking all its text).
1092
    /// `texts` names, in order, the inserts left without their lines (see
1093
    /// [`crate::store::Store::get_change_lazy`]); only a history-only state
1094
    /// takes them, and only for graphs it has not built.
a4fad5b0 Andy McCall ↶ 1095
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
ff0af1ee unknown 1096
        if self.changes.contains_key(&h) {
86e1824f Andy McCall ↶ 1097
            return;
ff0af1ee unknown 1098
        }
0bdc3f91 Andy McCall ↶ 1099
        let meta = ChangeMeta::of(&change);
86e1824f Andy McCall ↶ 1100
        self.apply_with(h, change, texts);
f6451fbb Andy McCall ↶ 1101
        self.changes.insert(h, Arc::new(meta));
119bbf50 Andy McCall ↶ 1102
        self.closure.lock().unwrap().clear();
ff0af1ee unknown 1103
    }
1104
252e8cb2 Andy McCall ↶ 1105
    // ------------------------------------------------------------ checkpoints (spec §11)
1106
afaba5f1 Andy McCall ↶ 1107
    /// Serialize the whole state in payload version 1: change metadata,
1108
    /// tree, file graphs, replaces, all in one value (spec §11).
252e8cb2 Andy McCall ↶ 1109
    pub fn checkpoint_payload(&self) -> Vec<u8> {
e8d38e47 Andy McCall ↶ 1110
        self.require_full("a checkpoint");
afaba5f1 Andy McCall ↶ 1111
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
1112
        nodes.sort();
1113
        let files = Value::Array(
1114
            nodes
1115
                .into_iter()
1116
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
1117
                .collect(),
1118
        );
1119
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
1120
    }
1121
1122
    /// Each file graph encoded on its own, by node, for a version 2 payload
1123
    /// (spec §11): the graphs of large files become blobs of their own.
1124
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
1125
        use rayon::prelude::*;
e8d38e47 Andy McCall ↶ 1126
        self.require_full("a checkpoint");
dfb23a3a Andy McCall ↶ 1127
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
1128
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
afaba5f1 Andy McCall ↶ 1129
        nodes.sort_by_key(|(n, _)| **n);
1130
        nodes
1131
            .into_par_iter()
1132
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
1133
            .collect()
1134
    }
1135
1136
    /// The payload version 2 index for the graphs of
1137
    /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than
1138
    /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by
1139
    /// `blob_of` (the ObjectRef of the blob holding its encoding).
1140
    pub fn checkpoint_index(
1141
        &self,
1142
        graphs: &[(NodeId, Vec<u8>)],
1143
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
1144
    ) -> Vec<u8> {
1145
        let files = Value::Array(
1146
            graphs
1147
                .iter()
1148
                .map(|(n, enc)| {
1149
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
1150
                        cbor::decode(enc).expect("an encoded graph decodes")
1151
                    } else {
1152
                        Value::Bytes(blob_of(enc).0.to_vec())
1153
                    };
1154
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
1155
                })
1156
                .collect(),
1157
        );
1158
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
1159
    }
1160
1161
    /// The payload map around `files`: changes, tree and replaces as in version 1.
1162
    fn payload_value(&self, version: u64, files: Value) -> Value {
252e8cb2 Andy McCall ↶ 1163
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
1164
        hashes.sort();
1165
        let changes = Value::Array(
1166
            hashes
1167
                .into_iter()
1168
                .map(|h| {
1169
                    let m = &self.changes[h];
1170
                    Value::Array(vec![
1171
                        Value::Bytes(h.0.to_vec()),
1172
                        Value::Bytes(m.change_id.0.to_vec()),
1173
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
1174
                        Value::Text(m.message.clone()),
1175
                        Value::Uint(m.hlc.wall_ms),
1176
                        Value::Uint(m.hlc.logical as u64),
1177
                        Value::Uint(m.kind.tag()),
1178
                        Value::Bytes(m.author.0.to_vec()),
1179
                    ])
1180
                })
75167672 Andy McCall 1181
                .collect(),
1182
        );
252e8cb2 Andy McCall ↶ 1183
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
1184
        rnodes.sort();
75167672 Andy McCall 1185
        let opt =
1186
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
252e8cb2 Andy McCall ↶ 1187
        let replaces = Value::Array(
1188
            rnodes
1189
                .into_iter()
1190
                .map(|n| {
1191
                    Value::Array(vec![
1192
                        Value::Bytes(n.0.to_vec()),
75167672 Andy McCall 1193
                        Value::Array(
1194
                            self.replaces[n]
1195
                                .iter()
1196
                                .map(|(c, o, nw)| {
1197
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
1198
                                })
1199
                                .collect(),
1200
                        ),
252e8cb2 Andy McCall ↶ 1201
                    ])
1202
                })
1203
                .collect(),
1204
        );
afaba5f1 Andy McCall ↶ 1205
        Value::map([
1206
            (0, Value::Uint(version)),
75167672 Andy McCall 1207
            (1, changes),
1208
            (2, self.tree.to_value()),
1209
            (3, files),
1210
            (4, replaces),
afaba5f1 Andy McCall ↶ 1211
        ])
252e8cb2 Andy McCall ↶ 1212
    }
1213
afaba5f1 Andy McCall ↶ 1214
    /// Decode a version 1 payload (the whole state in one value). A
1215
    /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`].
252e8cb2 Andy McCall ↶ 1216
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
afaba5f1 Andy McCall ↶ 1217
        State::from_checkpoint(bytes, |_| {
1218
            Err(ObjectError::Schema(
1219
                "a version 2 checkpoint needs its graph blobs".into(),
1220
            ))
1221
        })
1222
    }
1223
1224
    /// Decode a checkpoint payload of either version (spec §11). For
1225
    /// version 2, `load` returns the contents of the named graph blobs, in
1226
    /// order; the graphs are then decoded in parallel.
1227
    pub fn from_checkpoint(
1228
        bytes: &[u8],
1229
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
1230
    ) -> Result<State, ObjectError> {
1231
        use rayon::prelude::*;
252e8cb2 Andy McCall ↶ 1232
        let v = cbor::decode(bytes)?;
1233
        let m = o::map(&v, "checkpoint payload")?;
afaba5f1 Andy McCall ↶ 1234
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
1235
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
1236
            return Err(ObjectError::Schema(format!(
1237
                "checkpoint payload version {version} is not supported"
1238
            )));
1239
        }
1240
        let mut st = State::payload_common(m)?;
1241
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
1242
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
1243
        for f in entries {
1244
            let e = o::array(f, "file")?;
1245
            if e.len() != 2 {
1246
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1247
            }
1248
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1249
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1250
            parsed.push((node, &e[1]));
1251
        }
1252
        // Version 2 names large graphs by blob: fetch those in one batch.
1253
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
1254
        if version == CHECKPOINT_INDEX_VERSION {
1255
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
1256
                .iter()
1257
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
1258
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
1259
                .collect::<Result<_, ObjectError>>()?;
1260
            if !wanted.is_empty() {
1261
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
1262
                let contents = {
1263
                    let _t = crate::timing::phase("load:   graph blobs read");
1264
                    load(&refs)?
1265
                };
1266
                if contents.len() != refs.len() {
1267
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
1268
                }
1269
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
1270
            }
1271
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
1272
            return Err(ObjectError::Schema(
1273
                "a version 1 payload holds graphs inline".into(),
1274
            ));
1275
        }
1276
        // File graphs are independent; decode and build them in parallel.
1277
        let graphs = parsed
1278
            .par_iter()
1279
            .map(|(node, entry)| {
1280
                let graph = match fetched.get(node) {
1281
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
1282
                    None => FileGraph::from_value(entry)?,
1283
                };
1284
                Ok((*node, graph))
1285
            })
1286
            .collect::<Result<Vec<_>, ObjectError>>()?;
dfb23a3a Andy McCall ↶ 1287
        st.files
1288
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
afaba5f1 Andy McCall ↶ 1289
        Ok(st)
1290
    }
1291
1292
    /// The graph blobs a payload names: empty for version 1.
1293
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
1294
        let v = cbor::decode(bytes)?;
1295
        let m = o::map(&v, "checkpoint payload")?;
1296
        let mut out = Vec::new();
1297
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1298
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
1299
                out.push(o::oref(entry, "graph blob")?);
1300
            }
1301
        }
1302
        Ok(out)
e8d38e47 Andy McCall ↶ 1303
    }
1304
1305
    /// Decode a checkpoint payload for history only: a version 2 payload's
1306
    /// graphs are noted, not read or built, and come later through
1307
    /// [`State::load_graphs`]. A version 1 payload holds them inline and is
1308
    /// decoded in full.
1309
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
1310
        let v = cbor::decode(bytes)?;
1311
        let m = o::map(&v, "checkpoint payload")?;
1312
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
1313
        if version != CHECKPOINT_INDEX_VERSION {
1314
            return State::from_checkpoint_payload(bytes);
1315
        }
1316
        let mut st = State::payload_common(m)?;
1317
        let mut deferred = HashMap::new();
1318
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1319
            let e = o::array(f, "file")?;
1320
            if e.len() != 2 {
1321
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1322
            }
1323
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1324
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1325
            let base = match &e[1] {
1326
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
1327
                other => DeferredBase::Inline(other.clone()),
1328
            };
1329
            deferred.insert(
1330
                node,
3f1b8fe2 Andy McCall ↶ 1331
                Arc::new(Deferred::from_body(DeferredBody {
e8d38e47 Andy McCall ↶ 1332
                    base: Some(base),
3f1b8fe2 Andy McCall ↶ 1333
                    ..DeferredBody::default()
1334
                })),
e8d38e47 Andy McCall ↶ 1335
            );
1336
        }
1337
        st.deferred = Some(deferred);
1338
        Ok(st)
afaba5f1 Andy McCall ↶ 1339
    }
1340
1341
    /// Changes, tree and replaces of a payload of either version.
1342
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
252e8cb2 Andy McCall ↶ 1343
        let mut st = State::new();
1344
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
1345
            let e = o::array(c, "change meta")?;
1346
            if e.len() != 8 {
1347
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
1348
            }
1349
            let hash = o::oref(&e[0], "hash")?;
1350
            let meta = ChangeMeta {
75167672 Andy McCall 1351
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
1352
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
1353
                deps: o::array(&e[2], "deps")?
1354
                    .iter()
1355
                    .map(|d| o::oref(d, "dep"))
1356
                    .collect::<Result<Vec<_>, _>>()?,
252e8cb2 Andy McCall ↶ 1357
                message: o::text(&e[3], "message")?.to_owned(),
75167672 Andy McCall 1358
                hlc: Hlc {
1359
                    wall_ms: o::uint(&e[4], "wall")?,
1360
                    logical: o::u32_(&e[5], "logical")?,
1361
                },
252e8cb2 Andy McCall ↶ 1362
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
1363
                author: o::oref(&e[7], "author")?,
1364
            };
f6451fbb Andy McCall ↶ 1365
            st.changes.insert(hash, Arc::new(meta));
252e8cb2 Andy McCall ↶ 1366
        }
1367
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
75167672 Andy McCall 1368
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
1369
            if v.is_null() {
1370
                Ok(None)
1371
            } else {
1372
                o::oref(v, "blob").map(Some)
1373
            }
1374
        };
252e8cb2 Andy McCall ↶ 1375
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
1376
            let e = o::array(r, "replace")?;
1377
            if e.len() != 2 {
75167672 Andy McCall 1378
                return Err(ObjectError::Schema(
1379
                    "replace: expected [node, records]".into(),
1380
                ));
252e8cb2 Andy McCall ↶ 1381
            }
75167672 Andy McCall 1382
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1383
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
252e8cb2 Andy McCall ↶ 1384
            let mut recs = Vec::new();
1385
            for rec in o::array(&e[1], "records")? {
1386
                let x = o::array(rec, "record")?;
1387
                if x.len() != 3 {
1388
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
1389
                }
1390
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
1391
            }
1392
            st.replaces.insert(node, recs);
1393
        }
1394
        Ok(st)
1395
    }
1396
ff0af1ee unknown 1397
    pub fn validate(&self) -> Result<(), StateError> {
1398
        for (h, c) in &self.changes {
1399
            for d in &c.deps {
1400
                if !self.changes.contains_key(d) {
1401
                    return Err(StateError::MissingDep(*d, *h));
1402
                }
1403
            }
1404
        }
1405
        Ok(())
1406
    }
1407
a4fad5b0 Andy McCall ↶ 1408
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
ff0af1ee unknown 1409
        for (i, op) in c.tree_ops.iter().enumerate() {
1410
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
1411
        }
e8d38e47 Andy McCall ↶ 1412
        if let Some(deferred) = self.deferred.as_mut() {
86e1824f Andy McCall ↶ 1413
            // History only: edits of files not built wait, grouped per file,
1414
            // with the texts of inserts read without their lines.
1415
            let mut texts = texts.into_iter();
1416
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
e8d38e47 Andy McCall ↶ 1417
            for e in c.edits {
1418
                match e {
1419
                    Edit::Replace { node, old, new } => {
1420
                        self.replaces.entry(node).or_default().push((h, old, new))
1421
                    }
86e1824f Andy McCall ↶ 1422
                    e => {
1423
                        let slot = per_node.entry(e.node()).or_default();
1424
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
1425
                            slot.1.extend(texts.next());
1426
                        }
1427
                        slot.0.push(e);
1428
                    }
e8d38e47 Andy McCall ↶ 1429
                }
1430
            }
86e1824f Andy McCall ↶ 1431
            for (node, (edits, node_texts)) in per_node {
e8d38e47 Andy McCall ↶ 1432
                match self.files.get_mut(&node) {
86e1824f Andy McCall ↶ 1433
                    Some(g) => {
1434
                        assert!(
1435
                            node_texts.is_empty(),
1436
                            "a change read without its text applied to a built graph"
1437
                        );
1438
                        apply_file_edits(Arc::make_mut(g), h, edits)
1439
                    }
1440
                    None => {
f6451fbb Andy McCall ↶ 1441
                        let d = Arc::make_mut(deferred.entry(node).or_default());
3f1b8fe2 Andy McCall ↶ 1442
                        let b = d.body_mut();
1443
                        b.edits.push((h, edits));
1444
                        b.texts.extend(node_texts);
f9575918 Andy McCall ↶ 1445
                        d.key = Default::default();
86e1824f Andy McCall ↶ 1446
                    }
e8d38e47 Andy McCall ↶ 1447
                }
1448
            }
1449
            return;
1450
        }
86e1824f Andy McCall ↶ 1451
        assert!(
1452
            texts.is_empty(),
1453
            "a change read without its text applied to a full state"
1454
        );
ff0af1ee unknown 1455
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
0bdc3f91 Andy McCall ↶ 1456
        for e in c.edits {
ff0af1ee unknown 1457
            match e {
75167672 Andy McCall 1458
                Edit::Insert {
1459
                    node,
1460
                    after,
1461
                    before,
1462
                    lines,
1463
                } => {
0bdc3f91 Andy McCall ↶ 1464
                    let idx = counters.entry(node).or_default();
ff0af1ee unknown 1465
                    let first = *idx;
1466
                    *idx += lines.len() as u32;
dfb23a3a Andy McCall ↶ 1467
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
75167672 Andy McCall 1468
                        h,
1469
                        first,
1470
                        vertex(after.resolve(h)),
1471
                        vertex(before.resolve(h)),
1472
                        lines,
1473
                    );
ff0af1ee unknown 1474
                }
1475
                Edit::Delete { node, atoms } => {
dfb23a3a Andy McCall ↶ 1476
                    let g = Arc::make_mut(self.files.entry(node).or_default());
ff0af1ee unknown 1477
                    for r in atoms {
1478
                        g.delete(h, &r.resolve(h));
1479
                    }
1480
                }
1481
                Edit::Replace { node, old, new } => {
0bdc3f91 Andy McCall ↶ 1482
                    self.replaces.entry(node).or_default().push((h, old, new));
ff0af1ee unknown 1483
                }
1484
            }
1485
        }
1486
    }
1487
1488
    /// Transitive dependencies of `h`, excluding `h` itself.
119bbf50 Andy McCall ↶ 1489
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
1490
        if let Some(c) = self.closure.lock().unwrap().get(h) {
ff0af1ee unknown 1491
            return c.clone();
1492
        }
1493
        let mut out = HashSet::new();
75167672 Andy McCall 1494
        let mut stack: Vec<ChangeHash> = self
1495
            .changes
1496
            .get(h)
1497
            .map(|c| c.deps.clone())
1498
            .unwrap_or_default();
ff0af1ee unknown 1499
        while let Some(d) = stack.pop() {
1500
            if out.insert(d) {
1501
                if let Some(c) = self.changes.get(&d) {
1502
                    stack.extend(c.deps.iter().copied());
1503
                }
1504
            }
1505
        }
119bbf50 Andy McCall ↶ 1506
        let rc = Arc::new(out);
1507
        self.closure.lock().unwrap().insert(*h, rc.clone());
ff0af1ee unknown 1508
        rc
1509
    }
1510
1511
    /// Changes that no other change depends on directly, sorted.
1512
    pub fn heads(&self) -> Vec<ChangeHash> {
75167672 Andy McCall 1513
        let depended: HashSet<&ChangeHash> =
1514
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
1515
        let mut heads: Vec<ChangeHash> = self
1516
            .changes
1517
            .keys()
1518
            .filter(|h| !depended.contains(h))
1519
            .copied()
1520
            .collect();
ff0af1ee unknown 1521
        heads.sort();
1522
        heads
1523
    }
1524
07eb99be Andy McCall ↶ 1525
    /// Maximal elements among `hashes` (those not in the closure of another),
1526
    /// sorted. One walk down from all of them at once: whatever the walk
1527
    /// reaches is below some other element. Linear in the changes reached,
1528
    /// where comparing every pair's closures was quadratic in the number
1529
    /// of heads, which a bookmark of independent changes has many of.
ff0af1ee unknown 1530
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
1531
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
07eb99be Andy McCall ↶ 1532
        let mut below: HashSet<ChangeHash> = HashSet::new();
1533
        let mut stack: Vec<ChangeHash> = set
1534
            .iter()
1535
            .filter_map(|h| self.changes.get(h))
1536
            .flat_map(|c| c.deps.iter().copied())
1537
            .collect();
1538
        while let Some(d) = stack.pop() {
1539
            if below.insert(d) {
1540
                if let Some(c) = self.changes.get(&d) {
1541
                    stack.extend(c.deps.iter().copied());
1542
                }
1543
            }
1544
        }
1545
        set.into_iter().filter(|h| !below.contains(h)).collect()
ff0af1ee unknown 1546
    }
1547
1548
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
e8d38e47 Andy McCall ↶ 1549
        self.graph(node)
75167672 Andy McCall 1550
            .map(|g| g.materialize(self))
1551
            .unwrap_or_default()
ff0af1ee unknown 1552
    }
1553
1554
    /// Live lines of a text node in materialized order.
1555
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
e8d38e47 Andy McCall ↶ 1556
        let Some(g) = self.graph(node) else {
75167672 Andy McCall 1557
            return vec![];
1558
        };
ff0af1ee unknown 1559
        let m = g.materialize(self);
75167672 Andy McCall 1560
        m.live_atoms()
1561
            .into_iter()
1562
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
1563
            .collect()
ff0af1ee unknown 1564
    }
1565
1566
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
1567
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
62794ecc Andy McCall ↶ 1568
        let mut live: Vec<ObjectRef> = self
1569
            .live_replaces(node)
1570
            .into_iter()
1571
            .map(|(_, n)| n)
75167672 Andy McCall 1572
            .collect();
ff0af1ee unknown 1573
        live.sort();
1574
        live.dedup();
1575
        live
1576
    }
1577
62794ecc Andy McCall ↶ 1578
    /// The replace records whose blob is live, with the change that set it
1579
    /// (spec §9.3). A record's blob is superseded by a later replacement of
1580
    /// that blob: one whose change depends on the record's change, as every
1581
    /// replacement depends on the change that made its old blob current
1582
    /// (§8.1). Two replacements that do not know each other both stay live
1583
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
1584
    /// A replacement without that dependency, from before the rule, is read
1585
    /// as before: it supersedes every record that did not come after it.
1586
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
1587
        let Some(rs) = self.replaces.get(node) else {
1588
            return vec![];
1589
        };
1590
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
1591
            rs.iter()
1592
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && self.closure(s).contains(q))
1593
        };
1594
        rs.iter()
1595
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
1596
            .filter(|(c, n)| {
1597
                !rs.iter().any(|(s, o, _)| {
1598
                    s != c
1599
                        && *o == Some(*n)
1600
                        && (self.closure(s).contains(c)
1601
                            || (!knows_its_old(s, n) && !self.closure(c).contains(s)))
1602
                })
1603
            })
1604
            .collect()
1605
    }
1606
ff0af1ee unknown 1607
    /// Short label for conflict markers: `changeid-prefix "message"`.
1608
    pub fn label(&self, h: &ChangeHash) -> String {
1609
        match self.changes.get(h) {
75167672 Andy McCall 1610
            Some(c) => format!(
1611
                "{} \"{}\"",
1612
                c.change_id.short(8),
1613
                c.message.lines().next().unwrap_or("")
1614
            ),
ff0af1ee unknown 1615
            None => format!("#{}", h.short(12)),
1616
        }
1617
    }
1618
20247a03 Andy McCall ↶ 1619
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1620
    /// are not part of any conflict region in order, every live atom that is
1621
    /// part of a region, and every change that contributed to a region.
50a046e4 Andy McCall ↶ 1622
    /// The changes that introduced the live blobs of an opaque node, for a
1623
    /// replace conflict (spec §9.3).
1624
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
1625
        let mut out: Vec<ChangeHash> = Vec::new();
1626
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
1627
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
1628
                out.push(*h);
1629
            }
1630
        }
1631
        out.sort();
1632
        out
1633
    }
1634
20247a03 Andy McCall ↶ 1635
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
1636
        let mut out = ConflictRegions::default();
e8d38e47 Andy McCall ↶ 1637
        let Some(g) = self.graph(node) else {
75167672 Andy McCall 1638
            return out;
1639
        };
20247a03 Andy McCall ↶ 1640
        let m = g.materialize(self);
1641
        let mut contributors = BTreeSet::new();
1642
        for seg in &m.segments {
1643
            match seg {
1644
                crate::graph::Segment::Lines(atoms) => {
1645
                    for a in atoms {
75167672 Andy McCall 1646
                        out.plain
1647
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
20247a03 Andy McCall ↶ 1648
                    }
1649
                }
1650
                crate::graph::Segment::Conflict(sides) => {
1651
                    for side in sides {
1652
                        for a in side {
1653
                            out.region_atoms.push(*a);
1654
                            contributors.insert(a.0);
1655
                        }
1656
                    }
1657
                }
1658
                crate::graph::Segment::Zombie { deleted, inserted } => {
1659
                    for a in deleted {
1660
                        contributors.insert(a.0);
1661
                        contributors.extend(g.deleters(a).copied());
1662
                    }
1663
                    for a in inserted {
1664
                        out.region_atoms.push(*a);
1665
                        contributors.insert(a.0);
1666
                    }
1667
                }
1668
            }
1669
        }
1670
        out.contributors = contributors.into_iter().collect();
1671
        out
1672
    }
1673
ff0af1ee unknown 1674
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
e8d38e47 Andy McCall ↶ 1675
        let Some(g) = self.graph(node) else {
75167672 Andy McCall 1676
            return (Vec::new(), Materialized::default());
1677
        };
ff0af1ee unknown 1678
        let m = g.materialize(self);
1679
        let bytes = g.render(&m, &|h| self.label(h));
1680
        (bytes, m)
1681
    }
1682
e7ddd552 Andy McCall ↶ 1683
    /// Every file rendered, in parallel: files are independent, and
1684
    /// rendering them is most of a snapshot's cost in a large tree.
ff0af1ee unknown 1685
    pub fn materialize(&self) -> Snapshot {
e7ddd552 Andy McCall ↶ 1686
        use rayon::prelude::*;
e8d38e47 Andy McCall ↶ 1687
        self.require_full("materializing a state");
ff0af1ee unknown 1688
        let tree = self.tree.view();
e7ddd552 Andy McCall ↶ 1689
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
1690
        let rendered: Vec<(String, FileState)> = entries
1691
            .par_iter()
1692
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
1693
            .collect();
1694
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
cc7a0056 Andy McCall ↶ 1695
        Snapshot {
1696
            tree,
1697
            files,
1698
            unrendered: BTreeSet::new(),
1699
        }
1700
    }
1701
1702
    /// Like [`State::materialize`], leaving the text files of nodes in
1703
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
1704
    /// file's graph must be loaded. For a caller that already knows those
1705
    /// files are unchanged and not conflicted.
1706
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
1707
        use rayon::prelude::*;
1708
        let tree = self.tree.view();
1709
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
1710
        let rendered: Vec<(String, FileState, bool)> = entries
1711
            .par_iter()
1712
            .map(|(path, e)| {
1713
                if e.kind == NodeKind::File && !e.mode.opaque && skip.contains(&e.node) {
1714
                    let f = FileState {
1715
                        node: e.node,
1716
                        kind: e.kind,
1717
                        mode: e.mode,
1718
                        content: FileContent::Text {
1719
                            bytes: Vec::new(),
1720
                            materialized: Materialized::default(),
1721
                        },
1722
                    };
1723
                    (path.to_string(), f, true)
1724
                } else {
1725
                    (path.to_string(), self.file_state(e), false)
1726
                }
1727
            })
1728
            .collect();
1729
        let mut files = BTreeMap::new();
1730
        let mut unrendered = BTreeSet::new();
1731
        for (p, f, skipped) in rendered {
1732
            if skipped {
1733
                unrendered.insert(p.clone());
1734
            }
1735
            files.insert(p, f);
1736
        }
1737
        Snapshot {
1738
            tree,
1739
            files,
1740
            unrendered,
1741
        }
e7ddd552 Andy McCall ↶ 1742
    }
1743
2306a4d2 Andy McCall ↶ 1744
    /// A snapshot of only `paths` (those `view` has), `view` being this
1745
    /// state's tree view: for a caller that works from what changed. The
1746
    /// graphs of those text files must be loaded.
1747
    pub fn materialize_paths<'p>(
1748
        &self,
1749
        view: crate::tree::TreeView,
1750
        paths: impl IntoIterator<Item = &'p str>,
1751
    ) -> Snapshot {
1752
        let files = paths
1753
            .into_iter()
1754
            .filter_map(|p| Some((p.to_string(), self.file_state(view.entries.get(p)?))))
1755
            .collect();
1756
        Snapshot {
1757
            tree: view,
1758
            files,
1759
            unrendered: BTreeSet::new(),
1760
        }
1761
    }
1762
c3d2ef61 Andy McCall ↶ 1763
    /// The state of one tree entry: a directory, an opaque file's live
1764
    /// blobs, or a text file rendered from its graph (which must be built).
1765
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
1766
        self.file_state(e)
1767
    }
1768
e7ddd552 Andy McCall ↶ 1769
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
1770
        {
ff0af1ee unknown 1771
            let content = match e.kind {
1772
                NodeKind::Dir => FileContent::Dir,
75167672 Andy McCall 1773
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
1774
                    blobs: self.live_blobs(&e.node),
1775
                },
1776
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
1777
                    blobs: self.live_blobs(&e.node),
1778
                },
ff0af1ee unknown 1779
                NodeKind::File => {
1780
                    let (bytes, materialized) = self.render_file(&e.node);
75167672 Andy McCall 1781
                    FileContent::Text {
1782
                        bytes,
1783
                        materialized,
1784
                    }
ff0af1ee unknown 1785
                }
1786
            };
e7ddd552 Andy McCall ↶ 1787
            FileState {
1788
                node: e.node,
1789
                kind: e.kind,
1790
                mode: e.mode,
1791
                content,
1792
            }
ff0af1ee unknown 1793
        }
1794
    }
1795
}
1796
1797
impl DepOracle for State {
1798
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
1799
        a == b || self.closure(a).contains(b)
1800
    }
1801
}
1802
1803
#[cfg(test)]
1804
mod tests {
1805
    use super::*;
1806
    use crate::ids::ChangeId;
1807
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
1808
1809
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
1810
        let mut c = Change {
6f8aeb99 Andy McCall ↶ 1811
            version: crate::objects::CHANGE_VERSION,
ff0af1ee unknown 1812
            change_id: ChangeId::random(),
1813
            deps,
1814
            author: ObjectRef::ZERO,
75167672 Andy McCall 1815
            hlc: Hlc {
1816
                wall_ms: 1,
1817
                logical: 0,
1818
            },
ff0af1ee unknown 1819
            message: "m".into(),
1820
            tree_ops,
1821
            edits,
1822
            kind: ChangeKind::Normal,
1823
        };
1824
        c.normalize();
1825
        c
1826
    }
1827
1828
    #[test]
1829
    fn build_edit_and_materialize() {
1830
        let mut st = State::new();
1831
        let f = NodeId::random();
1832
        let c1 = change(
1833
            vec![],
75167672 Andy McCall 1834
            vec![TreeOp::AddNode {
1835
                node: f,
1836
                kind: NodeKind::File,
1837
                mode: Mode::TEXT,
1838
                parent: NodeId::ROOT,
1839
                name: "a.txt".into(),
1840
            }],
1841
            vec![Edit::Insert {
1842
                node: f,
1843
                after: AtomRef::Start,
1844
                before: AtomRef::End,
01a47cd7 Andy McCall ↶ 1845
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
75167672 Andy McCall 1846
            }],
ff0af1ee unknown 1847
        );
1848
        let h1 = st.add(c1).unwrap();
1849
        // Depends on h1: append a line and delete "one".
1850
        let c2 = change(
1851
            vec![h1],
1852
            vec![],
1853
            vec![
75167672 Andy McCall 1854
                Edit::Delete {
1855
                    node: f,
1856
                    atoms: vec![AtomRange {
1857
                        change: h1,
1858
                        from: 0,
1859
                        to: 1,
1860
                    }],
1861
                },
1862
                Edit::Insert {
1863
                    node: f,
1864
                    after: AtomRef::Atom {
1865
                        change: h1,
1866
                        index: 1,
1867
                    },
1868
                    before: AtomRef::End,
01a47cd7 Andy McCall ↶ 1869
                    lines: vec![b"three\n".to_vec()].into(),
75167672 Andy McCall 1870
                },
ff0af1ee unknown 1871
            ],
1872
        );
1873
        let h2 = st.add(c2).unwrap();
1874
        assert_eq!(st.heads(), vec![h2]);
1875
        assert!(st.depends_on(&h2, &h1));
1876
        assert!(!st.depends_on(&h1, &h2));
1877
        let snap = st.materialize();
1878
        assert!(!snap.is_conflicted());
1879
        let a = &snap.files["a.txt"];
1880
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
1881
        assert_eq!(st.live_lines(&f).len(), 2);
1882
    }
1883
1884
    #[test]
1885
    fn missing_dependency_is_rejected() {
1886
        let mut st = State::new();
1887
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
1888
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
1889
    }
1890
1891
    #[test]
1892
    fn self_references_and_multi_insert_indexing() {
1893
        let mut st = State::new();
1894
        let f = NodeId::random();
75167672 Andy McCall 1895
        let me = OpRef {
1896
            change: ObjectRef::ZERO,
1897
            index: 0,
1898
        };
ff0af1ee unknown 1899
        let c1 = change(
1900
            vec![],
1901
            vec![
75167672 Andy McCall 1902
                TreeOp::AddNode {
1903
                    node: f,
1904
                    kind: NodeKind::File,
1905
                    mode: Mode::TEXT,
1906
                    parent: NodeId::ROOT,
1907
                    name: "x".into(),
1908
                },
1909
                TreeOp::SetMode {
1910
                    node: f,
1911
                    old: me,
1912
                    mode: Mode {
1913
                        exec: true,
1914
                        opaque: false,
1915
                    },
1916
                },
ff0af1ee unknown 1917
            ],
1918
            vec![
75167672 Andy McCall 1919
                Edit::Insert {
1920
                    node: f,
1921
                    after: AtomRef::Start,
1922
                    before: AtomRef::End,
01a47cd7 Andy McCall ↶ 1923
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
75167672 Andy McCall 1924
                },
ff0af1ee unknown 1925
                // Insert between the two lines just inserted, using self references.
1926
                Edit::Insert {
1927
                    node: f,
75167672 Andy McCall 1928
                    after: AtomRef::Atom {
1929
                        change: ObjectRef::ZERO,
1930
                        index: 0,
1931
                    },
1932
                    before: AtomRef::Atom {
1933
                        change: ObjectRef::ZERO,
1934
                        index: 1,
1935
                    },
01a47cd7 Andy McCall ↶ 1936
                    lines: vec![b"b\n".to_vec()].into(),
ff0af1ee unknown 1937
                },
1938
            ],
1939
        );
1940
        st.add(c1).unwrap();
1941
        let snap = st.materialize();
1942
        let x = &snap.files["x"];
75167672 Andy McCall 1943
        assert_eq!(
1944
            x.mode,
1945
            Mode {
1946
                exec: true,
1947
                opaque: false
1948
            }
1949
        );
ff0af1ee unknown 1950
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
1951
    }
1952
1953
    #[test]
1954
    fn opaque_replace_and_conflict() {
1955
        let mut st = State::new();
1956
        let f = NodeId::random();
1957
        let b1 = ObjectRef([1; 32]);
1958
        let b2 = ObjectRef([2; 32]);
1959
        let b3 = ObjectRef([3; 32]);
75167672 Andy McCall 1960
        let h1 = st
1961
            .add(change(
1962
                vec![],
1963
                vec![TreeOp::AddNode {
1964
                    node: f,
1965
                    kind: NodeKind::File,
1966
                    mode: Mode::OPAQUE,
1967
                    parent: NodeId::ROOT,
1968
                    name: "img".into(),
1969
                }],
1970
                vec![Edit::Replace {
1971
                    node: f,
1972
                    old: None,
1973
                    new: Some(b1),
1974
                }],
1975
            ))
1976
            .unwrap();
1977
        assert_eq!(st.live_blobs(&f), vec![b1]);
1978
        st.add(change(
1979
            vec![h1],
1980
            vec![],
1981
            vec![Edit::Replace {
1982
                node: f,
1983
                old: Some(b1),
1984
                new: Some(b2),
1985
            }],
1986
        ))
1987
        .unwrap();
1988
        st.add(change(
1989
            vec![h1],
ff0af1ee unknown 1990
            vec![],
75167672 Andy McCall 1991
            vec![Edit::Replace {
1992
                node: f,
1993
                old: Some(b1),
1994
                new: Some(b3),
1995
            }],
ff0af1ee unknown 1996
        ))
1997
        .unwrap();
1998
        let snap = st.materialize();
1999
        assert!(snap.is_conflicted());
75167672 Andy McCall 2000
        assert!(
2001
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2002
        );
ff0af1ee unknown 2003
    }
2004
2005
    #[test]
252e8cb2 Andy McCall ↶ 2006
    fn checkpoint_payload_round_trip_and_replay() {
2007
        let mut st = State::new();
2008
        let f = NodeId::random();
75167672 Andy McCall 2009
        let h1 = st
2010
            .add(change(
2011
                vec![],
2012
                vec![TreeOp::AddNode {
2013
                    node: f,
2014
                    kind: NodeKind::File,
2015
                    mode: Mode::TEXT,
2016
                    parent: NodeId::ROOT,
2017
                    name: "a".into(),
2018
                }],
2019
                vec![Edit::Insert {
2020
                    node: f,
2021
                    after: AtomRef::Start,
2022
                    before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2023
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
75167672 Andy McCall 2024
                }],
2025
            ))
2026
            .unwrap();
2027
        let h2 = st
2028
            .add(change(
2029
                vec![h1],
2030
                vec![],
2031
                vec![Edit::Delete {
2032
                    node: f,
2033
                    atoms: vec![AtomRange {
2034
                        change: h1,
2035
                        from: 0,
2036
                        to: 1,
2037
                    }],
2038
                }],
2039
            ))
2040
            .unwrap();
252e8cb2 Andy McCall ↶ 2041
        let payload = st.checkpoint_payload();
2042
        let back = State::from_checkpoint_payload(&payload).unwrap();
2043
        assert_eq!(back.len(), 2);
2044
        assert_eq!(back.heads(), vec![h2]);
2045
        assert_eq!(back.get(&h1).unwrap().message, "m");
2046
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2047
        // Replaying a further change onto the restored state equals a full build.
75167672 Andy McCall 2048
        let c3 = change(
2049
            vec![h2],
2050
            vec![],
2051
            vec![Edit::Insert {
2052
                node: f,
2053
                after: AtomRef::Atom {
2054
                    change: h1,
2055
                    index: 1,
2056
                },
2057
                before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2058
                lines: vec![b"3\n".to_vec()].into(),
75167672 Andy McCall 2059
            }],
2060
        );
252e8cb2 Andy McCall ↶ 2061
        let mut full = st.clone();
2062
        full.add(c3.clone()).unwrap();
2063
        let mut restored = back;
2064
        restored.add(c3).unwrap();
2065
        let (a, b) = (full.materialize(), restored.materialize());
75167672 Andy McCall 2066
        assert_eq!(
2067
            a.files.keys().collect::<Vec<_>>(),
2068
            b.files.keys().collect::<Vec<_>>()
2069
        );
252e8cb2 Andy McCall ↶ 2070
        assert_eq!(a.files["a"].content, b.files["a"].content);
75167672 Andy McCall 2071
        assert!(
2072
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2073
        );
252e8cb2 Andy McCall ↶ 2074
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
e8d38e47 Andy McCall ↶ 2075
    }
2076
2077
    /// History-only states (O10f): the same state as a full load once its
2078
    /// graphs are built, by replay and from a version 2 checkpoint with
2079
    /// later changes; unloaded graphs are never read as empty.
cc7a0056 Andy McCall ↶ 2080
    #[test]
2081
    fn graph_keys_change_exactly_when_a_graph_does() {
2082
        let (f, g) = (NodeId::random(), NodeId::random());
2083
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2084
            node,
2085
            kind: NodeKind::File,
2086
            mode: Mode::TEXT,
2087
            parent: NodeId::ROOT,
2088
            name: name.into(),
2089
        };
2090
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
2091
            node,
2092
            after: AtomRef::Start,
2093
            before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2094
            lines: vec![line.to_vec()].into(),
cc7a0056 Andy McCall ↶ 2095
        };
2096
        let c1 = change(
2097
            vec![],
2098
            vec![add(f, "f"), add(g, "g")],
2099
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2100
        );
2101
        let h1 = c1.hash();
2102
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
2103
        let h2 = c2.hash();
2104
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
2105
        let load = |cs: &[&Change]| {
2106
            let mut st = State::new_history_only();
2107
            for c in cs {
2108
                st.add((*c).clone()).unwrap();
2109
            }
2110
            st
2111
        };
2112
        let s1 = load(&[&c1]);
2113
        let s2 = load(&[&c1, &c2]);
2114
        let s3 = load(&[&c1, &c2, &c3]);
2115
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
2116
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
2117
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
2118
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
2119
        assert_ne!(key(&s2, &f), key(&s3, &f));
2120
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
2121
        let mut built = load(&[&c1]);
a4fad5b0 Andy McCall ↶ 2122
        built
2123
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
2124
            .unwrap();
cc7a0056 Andy McCall ↶ 2125
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
2126
        let mut full = State::new();
2127
        full.add(c1.clone()).unwrap();
2128
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2129
2130
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2131
        // or inline values: stable across loads, changed by later edits.
2132
        let graphs = full.checkpoint_file_graphs();
2133
        let index = full.checkpoint_index(&graphs, |enc| {
2134
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
2135
        });
2136
        let cp = |extra: &[&Change]| {
2137
            let mut st = State::from_checkpoint_history(&index).unwrap();
2138
            for c in extra {
2139
                st.add((*c).clone()).unwrap();
2140
            }
2141
            st
2142
        };
2143
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
2144
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
2145
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
2146
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2147
2148
        // Partial rendering: skipped files are listed and empty, the others
2149
        // render as in a full state.
2150
        let mut part = load(&[&c1, &c2]);
a4fad5b0 Andy McCall ↶ 2151
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
2152
            .unwrap();
cc7a0056 Andy McCall ↶ 2153
        let snap = part.materialize_except(&[f].into_iter().collect());
2154
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
2155
        let mut whole = State::new();
2156
        whole.add(c1.clone()).unwrap();
2157
        whole.add(c2.clone()).unwrap();
2158
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
2159
        assert!(
2160
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2161
        );
2162
    }
2163
e8d38e47 Andy McCall ↶ 2164
    #[test]
2165
    fn history_only_states_build_the_same_graphs_on_demand() {
2166
        let small = NodeId::random();
2167
        let big = NodeId::random();
2168
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2169
            node,
2170
            kind: NodeKind::File,
2171
            mode: Mode::TEXT,
2172
            parent: NodeId::ROOT,
2173
            name: name.into(),
2174
        };
01a47cd7 Andy McCall ↶ 2175
        let lines: crate::lines::Lines = (0..300)
e8d38e47 Andy McCall ↶ 2176
            .map(|i| format!("line {i}\n").into_bytes())
2177
            .collect();
2178
        let c1 = change(
2179
            vec![],
2180
            vec![add(small, "small"), add(big, "big")],
2181
            vec![
2182
                Edit::Insert {
2183
                    node: small,
2184
                    after: AtomRef::Start,
2185
                    before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2186
                    lines: vec![b"x\n".to_vec()].into(),
e8d38e47 Andy McCall ↶ 2187
                },
2188
                Edit::Insert {
2189
                    node: big,
2190
                    after: AtomRef::Start,
2191
                    before: AtomRef::End,
2192
                    lines,
2193
                },
2194
            ],
2195
        );
2196
        let h1 = c1.hash();
2197
        let c2 = change(
2198
            vec![h1],
2199
            vec![],
2200
            vec![
2201
                Edit::Delete {
2202
                    node: big,
2203
                    atoms: vec![AtomRange {
2204
                        change: h1,
2205
                        from: 2,
2206
                        to: 9,
2207
                    }],
2208
                },
2209
                Edit::Insert {
2210
                    node: big,
2211
                    after: AtomRef::Atom {
2212
                        change: h1,
2213
                        index: 20,
2214
                    },
2215
                    before: AtomRef::Atom {
2216
                        change: h1,
2217
                        index: 21,
2218
                    },
01a47cd7 Andy McCall ↶ 2219
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
e8d38e47 Andy McCall ↶ 2220
                },
2221
                Edit::Insert {
2222
                    node: small,
2223
                    after: AtomRef::Atom {
2224
                        change: h1,
2225
                        index: 0,
2226
                    },
2227
                    before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2228
                    lines: vec![b"y\n".to_vec()].into(),
e8d38e47 Andy McCall ↶ 2229
                },
2230
            ],
2231
        );
2232
        let h2 = c2.hash();
2233
        let c3 = change(
2234
            vec![h2],
2235
            vec![],
2236
            vec![Edit::Delete {
2237
                node: small,
2238
                atoms: vec![AtomRange {
2239
                    change: h1,
2240
                    from: 0,
2241
                    to: 1,
2242
                }],
2243
            }],
2244
        );
2245
2246
        let mut full = State::new();
2247
        for c in [&c1, &c2, &c3] {
2248
            full.add(c.clone()).unwrap();
2249
        }
2250
        // By replay: nothing built until asked, then exactly the full graphs.
2251
        let mut hist = State::new_history_only();
2252
        for c in [&c1, &c2, &c3] {
2253
            hist.add(c.clone()).unwrap();
2254
        }
2255
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
2256
        assert_eq!(hist.len(), 3);
a4fad5b0 Andy McCall ↶ 2257
        hist.load_graphs(
2258
            &[big],
2259
            |_| unreachable!("no checkpoint"),
2260
            |_| unreachable!(),
2261
        )
2262
        .unwrap();
e8d38e47 Andy McCall ↶ 2263
        assert_eq!(
2264
            hist.render_file(&big).0,
2265
            full.render_file(&big).0,
2266
            "one file on its own"
2267
        );
2268
        assert!(!hist.is_full());
a4fad5b0 Andy McCall ↶ 2269
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
2270
            .unwrap();
e8d38e47 Andy McCall ↶ 2271
        assert!(hist.is_full());
2272
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2273
2274
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
2275
        let mut base = State::new();
2276
        base.add(c1.clone()).unwrap();
2277
        base.add(c2.clone()).unwrap();
2278
        let graphs = base.checkpoint_file_graphs();
2279
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
2280
        let index = base.checkpoint_index(&graphs, |enc| {
2281
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
2282
            blobs.insert(r, enc.to_vec());
2283
            r
2284
        });
2285
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
2286
        from_cp.add(c3.clone()).unwrap();
2287
        assert!(!from_cp.is_full());
2288
        let mut fetched = 0;
2289
        from_cp
a4fad5b0 Andy McCall ↶ 2290
            .load_graphs(
2291
                &[small, big],
2292
                |refs| {
2293
                    fetched += refs.len();
2294
                    refs.iter()
2295
                        .map(|r| {
2296
                            blobs
2297
                                .get(r)
2298
                                .cloned()
2299
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
2300
                        })
2301
                        .collect()
2302
                },
2303
                |_| unreachable!(),
2304
            )
e8d38e47 Andy McCall ↶ 2305
            .unwrap();
2306
        assert_eq!(
2307
            fetched, 1,
2308
            "the large graph's blob, in one batch; the small one was inline"
2309
        );
2310
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
2311
    }
2312
2313
    #[test]
2314
    #[should_panic(expected = "was not loaded")]
2315
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
2316
        let f = NodeId::random();
2317
        let mut st = State::new_history_only();
2318
        st.add(change(
2319
            vec![],
2320
            vec![TreeOp::AddNode {
2321
                node: f,
2322
                kind: NodeKind::File,
2323
                mode: Mode::TEXT,
2324
                parent: NodeId::ROOT,
2325
                name: "a".into(),
2326
            }],
2327
            vec![Edit::Insert {
2328
                node: f,
2329
                after: AtomRef::Start,
2330
                before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2331
                lines: vec![b"a\n".to_vec()].into(),
e8d38e47 Andy McCall ↶ 2332
            }],
2333
        ))
2334
        .unwrap();
2335
        st.render_file(&f);
2336
    }
2337
2338
    #[test]
2339
    #[should_panic(expected = "needs every file graph")]
2340
    fn materializing_a_history_only_state_is_refused() {
2341
        let f = NodeId::random();
2342
        let mut st = State::new_history_only();
2343
        st.add(change(
2344
            vec![],
2345
            vec![TreeOp::AddNode {
2346
                node: f,
2347
                kind: NodeKind::File,
2348
                mode: Mode::TEXT,
2349
                parent: NodeId::ROOT,
2350
                name: "a".into(),
2351
            }],
2352
            vec![Edit::Insert {
2353
                node: f,
2354
                after: AtomRef::Start,
2355
                before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2356
                lines: vec![b"a\n".to_vec()].into(),
e8d38e47 Andy McCall ↶ 2357
            }],
2358
        ))
2359
        .unwrap();
2360
        st.materialize();
afaba5f1 Andy McCall ↶ 2361
    }
2362
2363
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
2364
    /// blob; the state read back is the same as from version 1.
2365
    #[test]
2366
    fn checkpoint_index_round_trip_matches_version_1() {
2367
        let mut st = State::new();
2368
        let small = NodeId::random();
2369
        let big = NodeId::random();
2370
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2371
            node,
2372
            kind: NodeKind::File,
2373
            mode: Mode::TEXT,
2374
            parent: NodeId::ROOT,
2375
            name: name.into(),
2376
        };
01a47cd7 Andy McCall ↶ 2377
        let big_lines: crate::lines::Lines = (0..400)
afaba5f1 Andy McCall ↶ 2378
            .map(|i| format!("line {i} of a long file\n").into_bytes())
2379
            .collect();
2380
        let h1 = st
2381
            .add(change(
2382
                vec![],
2383
                vec![add(small, "small"), add(big, "big")],
2384
                vec![
2385
                    Edit::Insert {
2386
                        node: small,
2387
                        after: AtomRef::Start,
2388
                        before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2389
                        lines: vec![b"x\n".to_vec()].into(),
afaba5f1 Andy McCall ↶ 2390
                    },
2391
                    Edit::Insert {
2392
                        node: big,
2393
                        after: AtomRef::Start,
2394
                        before: AtomRef::End,
2395
                        lines: big_lines,
2396
                    },
2397
                ],
2398
            ))
2399
            .unwrap();
2400
        st.add(change(
2401
            vec![h1],
2402
            vec![],
2403
            vec![Edit::Delete {
2404
                node: big,
2405
                atoms: vec![AtomRange {
2406
                    change: h1,
2407
                    from: 3,
2408
                    to: 7,
2409
                }],
2410
            }],
2411
        ))
2412
        .unwrap();
2413
2414
        let graphs = st.checkpoint_file_graphs();
2415
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
2416
        let index = st.checkpoint_index(&graphs, |enc| {
2417
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
2418
            blobs.insert(r, enc.to_vec());
2419
            r
2420
        });
2421
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
2422
        assert_eq!(
2423
            State::checkpoint_graph_refs(&index).unwrap(),
2424
            blobs.keys().copied().collect::<Vec<_>>()
2425
        );
2426
        assert!(
2427
            State::checkpoint_graph_refs(&st.checkpoint_payload())
2428
                .unwrap()
2429
                .is_empty(),
2430
            "version 1 names none"
2431
        );
2432
        assert!(index.len() < st.checkpoint_payload().len());
2433
2434
        let back = State::from_checkpoint(&index, |refs| {
2435
            refs.iter()
2436
                .map(|r| {
2437
                    blobs
2438
                        .get(r)
2439
                        .cloned()
2440
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
2441
                })
2442
                .collect()
2443
        })
2444
        .unwrap();
2445
        assert_eq!(
2446
            back.checkpoint_payload(),
2447
            st.checkpoint_payload(),
2448
            "the same state as version 1"
2449
        );
2450
        assert_eq!(
2451
            back.materialize().files["big"].content,
2452
            st.materialize().files["big"].content
2453
        );
2454
        // Deterministic: the same state gives the same index.
2455
        assert_eq!(
2456
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
2457
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
2458
            }),
2459
            index
2460
        );
2461
        // A missing graph blob is an error, not an empty file.
2462
        assert!(
2463
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
2464
        );
2465
        assert!(
2466
            State::from_checkpoint_payload(&index).is_err(),
2467
            "version 2 needs its blobs"
2468
        );
2469
        // Version 1 payloads still read, and unknown versions do not.
2470
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
2471
        let mut v3 = cbor::decode(&index).unwrap();
2472
        if let Value::Map(m) = &mut v3 {
2473
            m.insert(0, Value::Uint(3));
2474
        }
2475
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
252e8cb2 Andy McCall ↶ 2476
    }
2477
2478
    #[test]
ff0af1ee unknown 2479
    fn maximal_elements() {
2480
        let mut st = State::new();
2481
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
2482
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
2483
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
2484
        let mut m = st.maximal(&[h1, h2, h3]);
2485
        m.sort();
2486
        let mut want = vec![h2, h3];
2487
        want.sort();
2488
        assert_eq!(m, want);
2489
        assert_eq!(st.heads(), want);
2490
    }
07eb99be Andy McCall ↶ 2491
2492
    /// The one-walk `maximal` agrees with the definition (not in the
2493
    /// closure of another element) on random graphs, with repeated and
2494
    /// unknown hashes among the input.
2495
    #[test]
2496
    fn maximal_matches_its_definition() {
2497
        use rand::{Rng, SeedableRng};
2498
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
2499
        for _ in 0..20 {
2500
            let mut st = State::new();
2501
            let mut all: Vec<ChangeHash> = Vec::new();
2502
            for _ in 0..60 {
2503
                let deps: Vec<ChangeHash> =
2504
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
2505
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2506
            }
2507
            let mut pick: Vec<ChangeHash> =
2508
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
2509
            pick.extend(pick.clone().into_iter().take(3));
2510
            pick.push(ObjectRef([0xee; 32]));
2511
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
2512
            let want: Vec<ChangeHash> = set
2513
                .iter()
2514
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
2515
                .copied()
2516
                .collect();
2517
            assert_eq!(st.maximal(&pick), want);
2518
            assert_eq!(st.maximal(&all), st.heads());
2519
        }
2520
    }
ff0af1ee unknown 2521
}