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