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