OXYGENHUB
# efad40f9ac8e oxygen / crates / oxy-core / src / state.rs
106.9 KiB · Rust · last changed Binary files' current versions found without whole closures 24 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
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
1894
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
1895
        let mut live: Vec<ObjectRef> = self
1896
            .live_replaces(node)
1897
            .into_iter()
1898
            .map(|(_, n)| n)
1899
            .collect();
1900
        live.sort();
1901
        live.dedup();
1902
        live
1903
    }
1904
1905
    /// The replace records whose blob is live, with the change that set it
1906
    /// (spec §9.3). A record's blob is superseded by a later replacement of
1907
    /// that blob: one whose change depends on the record's change, as every
1908
    /// replacement depends on the change that made its old blob current
1909
    /// (§8.1). Two replacements that do not know each other both stay live
1910
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
1911
    /// A replacement without that dependency, from before the rule, is read
1912
    /// as before: it supersedes every record that did not come after it.
1913
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
1914
        let Some(rs) = self.replaces.get(node) else {
1915
            return vec![];
1916
        };
1917
        // Dependence by the bounded walk rather than whole closures: on a
1918
        // long history a closure is a hundred thousand changes, and the
1919
        // memo cannot keep them all (#107).
1920
        let dep =
1921
            |a: &ChangeHash, b: &ChangeHash| a != b && <Self as DepOracle>::depends_on(self, a, b);
1922
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
1923
            rs.iter()
1924
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && dep(s, q))
1925
        };
1926
        rs.iter()
1927
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
1928
            .filter(|(c, n)| {
1929
                !rs.iter().any(|(s, o, _)| {
1930
                    s != c && *o == Some(*n) && (dep(s, c) || (!knows_its_old(s, n) && !dep(c, s)))
1931
                })
1932
            })
1933
            .collect()
1934
    }
1935
1936
    /// Short label for conflict markers: `changeid-prefix "message"`.
1937
    pub fn label(&self, h: &ChangeHash) -> String {
1938
        match self.changes.get(h) {
1939
            Some(c) => format!(
1940
                "{} \"{}\"",
1941
                c.change_id.short(8),
1942
                c.message.lines().next().unwrap_or("")
1943
            ),
1944
            None => format!("#{}", h.short(12)),
1945
        }
1946
    }
1947
1948
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1949
    /// are not part of any conflict region in order, every live atom that is
1950
    /// part of a region, and every change that contributed to a region.
1951
    /// The changes that introduced the live blobs of an opaque node, for a
1952
    /// replace conflict (spec §9.3).
1953
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
1954
        let mut out: Vec<ChangeHash> = Vec::new();
1955
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
1956
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
1957
                out.push(*h);
1958
            }
1959
        }
1960
        out.sort();
1961
        out
1962
    }
1963
1964
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
1965
        let mut out = ConflictRegions::default();
1966
        let Some(g) = self.graph(node) else {
1967
            return out;
1968
        };
1969
        let m = g.materialize(self);
1970
        let mut contributors = BTreeSet::new();
1971
        for seg in &m.segments {
1972
            match seg {
1973
                crate::graph::Segment::Lines(atoms) => {
1974
                    for a in atoms {
1975
                        out.plain
1976
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
1977
                    }
1978
                }
1979
                crate::graph::Segment::Conflict(sides) => {
1980
                    for side in sides {
1981
                        for a in side {
1982
                            out.region_atoms.push(*a);
1983
                            contributors.insert(a.0);
1984
                        }
1985
                    }
1986
                }
1987
                crate::graph::Segment::Zombie { deleted, inserted } => {
1988
                    for a in deleted {
1989
                        contributors.insert(a.0);
1990
                        contributors.extend(g.deleters(a).copied());
1991
                    }
1992
                    for a in inserted {
1993
                        out.region_atoms.push(*a);
1994
                        contributors.insert(a.0);
1995
                    }
1996
                }
1997
            }
1998
        }
1999
        out.contributors = contributors.into_iter().collect();
2000
        out
2001
    }
2002
2003
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
2004
        let Some(g) = self.graph(node) else {
2005
            return (Vec::new(), Materialized::default());
2006
        };
2007
        let m = g.materialize(self);
2008
        let bytes = g.render(&m, &|h| self.label(h));
2009
        (bytes, m)
2010
    }
2011
2012
    /// Every file rendered, in parallel: files are independent, and
2013
    /// rendering them is most of a snapshot's cost in a large tree.
2014
    pub fn materialize(&self) -> Snapshot {
2015
        use rayon::prelude::*;
2016
        self.require_full("materializing a state");
2017
        let tree = self.tree.view();
2018
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
2019
        let rendered: Vec<(String, FileState)> = entries
2020
            .par_iter()
2021
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
2022
            .collect();
2023
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
2024
        Snapshot {
2025
            tree,
2026
            files,
2027
            unrendered: BTreeSet::new(),
2028
        }
2029
    }
2030
2031
    /// Like [`State::materialize`], leaving the text files of nodes in
2032
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
2033
    /// file's graph must be loaded. For a caller that already knows those
2034
    /// files are unchanged and not conflicted.
2035
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
2036
        self.materialize_leaving(|_, e| skip.contains(&e.node))
2037
    }
2038
2039
    /// As [`State::materialize_except`], rendering only the text files at
2040
    /// `render` (a few, where the caller knows the rest unchanged).
2041
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
2042
        self.materialize_leaving(|p, _| !render.contains(p))
2043
    }
2044
2045
    /// As [`State::materialize_except`], rendering only the text files of
2046
    /// the nodes in `render` (a change's edited files), without a set of
2047
    /// every other file to leave out.
2048
    pub fn materialize_nodes(&self, render: &HashSet<NodeId>) -> Snapshot {
2049
        self.materialize_leaving(|_, e| !render.contains(&e.node))
2050
    }
2051
2052
    fn materialize_leaving(
2053
        &self,
2054
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
2055
    ) -> Snapshot {
2056
        use rayon::prelude::*;
2057
        let tree = self.tree.view();
2058
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
2059
        let rendered: Vec<(String, FileState, bool)> = entries
2060
            .par_iter()
2061
            .map(|(path, e)| {
2062
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
2063
                    let f = FileState {
2064
                        node: e.node,
2065
                        kind: e.kind,
2066
                        mode: e.mode,
2067
                        content: FileContent::Text {
2068
                            bytes: Vec::new(),
2069
                            materialized: Materialized::default(),
2070
                        },
2071
                    };
2072
                    (path.to_string(), f, true)
2073
                } else {
2074
                    (path.to_string(), self.file_state(e), false)
2075
                }
2076
            })
2077
            .collect();
2078
        // In the view's path order, so the maps are built without searching.
2079
        let unrendered: BTreeSet<String> = rendered
2080
            .iter()
2081
            .filter(|(_, _, skipped)| *skipped)
2082
            .map(|(p, _, _)| p.clone())
2083
            .collect();
2084
        let files: BTreeMap<String, FileState> =
2085
            rendered.into_iter().map(|(p, f, _)| (p, f)).collect();
2086
        Snapshot {
2087
            tree,
2088
            files,
2089
            unrendered,
2090
        }
2091
    }
2092
2093
    /// A snapshot of only `paths` (those `view` has), `view` being this
2094
    /// state's tree view: for a caller that works from what changed. The
2095
    /// graphs of those text files must be loaded.
2096
    pub fn materialize_paths<'p>(
2097
        &self,
2098
        view: crate::tree::TreeView,
2099
        paths: impl IntoIterator<Item = &'p str>,
2100
    ) -> Snapshot {
2101
        use rayon::prelude::*;
2102
        // On every core: a merge may render thousands (oxygen#96).
2103
        let entries: Vec<(&str, &crate::tree::TreeEntry)> = paths
2104
            .into_iter()
2105
            .filter_map(|p| Some((p, view.entries.get(p)?)))
2106
            .collect();
2107
        let files = entries
2108
            .par_iter()
2109
            .map(|(p, e)| (p.to_string(), self.file_state(e)))
2110
            .collect::<Vec<_>>()
2111
            .into_iter()
2112
            .collect();
2113
        Snapshot {
2114
            tree: view,
2115
            files,
2116
            unrendered: BTreeSet::new(),
2117
        }
2118
    }
2119
2120
    /// The state of one tree entry: a directory, an opaque file's live
2121
    /// blobs, or a text file rendered from its graph (which must be built).
2122
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
2123
        self.file_state(e)
2124
    }
2125
2126
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
2127
        {
2128
            let content = match e.kind {
2129
                NodeKind::Dir => FileContent::Dir,
2130
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
2131
                    blobs: self.live_blobs(&e.node),
2132
                },
2133
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
2134
                    blobs: self.live_blobs(&e.node),
2135
                },
2136
                NodeKind::File => {
2137
                    let (bytes, materialized) = self.render_file(&e.node);
2138
                    FileContent::Text {
2139
                        bytes,
2140
                        materialized,
2141
                    }
2142
                }
2143
            };
2144
            FileState {
2145
                node: e.node,
2146
                kind: e.kind,
2147
                mode: e.mode,
2148
                content,
2149
            }
2150
        }
2151
    }
2152
}
2153
2154
impl DepOracle for State {
2155
    /// Whether `a` depends on `b`, by a walk down from `a` that stops at
2156
    /// changes no higher than `b`: they cannot have `b` below them. Nothing
2157
    /// of the walk is kept, so asking about many pairs costs no more memory
2158
    /// than one walk (#25); a closure already memoised answers at once.
2159
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
2160
        if a == b {
2161
            return true;
2162
        }
2163
        if let Some(c) = self.closure.read().unwrap().sets.get(a) {
2164
            return c.contains(b);
2165
        }
2166
        if !self.changes.contains_key(b) {
2167
            return false;
2168
        }
2169
        let lb = self.level(b);
2170
        if self.level(a) <= lb {
2171
            return false;
2172
        }
2173
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2174
        let mut stack: Vec<ChangeHash> = self
2175
            .changes
2176
            .get(a)
2177
            .map(|m| m.deps.clone())
2178
            .unwrap_or_default();
2179
        while let Some(c) = stack.pop() {
2180
            if c == *b {
2181
                return true;
2182
            }
2183
            if !seen.insert(c) || self.level(&c) <= lb {
2184
                continue;
2185
            }
2186
            if let Some(m) = self.changes.get(&c) {
2187
                stack.extend(m.deps.iter().copied());
2188
            }
2189
        }
2190
        false
2191
    }
2192
}
2193
2194
#[cfg(test)]
2195
mod tests {
2196
    use super::*;
2197
    use crate::ids::ChangeId;
2198
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
2199
2200
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
2201
        let mut c = Change {
2202
            version: crate::objects::CHANGE_VERSION,
2203
            change_id: ChangeId::random(),
2204
            deps,
2205
            author: ObjectRef::ZERO,
2206
            hlc: Hlc {
2207
                wall_ms: 1,
2208
                logical: 0,
2209
            },
2210
            message: "m".into(),
2211
            tree_ops,
2212
            edits,
2213
            kind: ChangeKind::Normal,
2214
        };
2215
        c.normalize();
2216
        c
2217
    }
2218
2219
    #[test]
2220
    fn build_edit_and_materialize() {
2221
        let mut st = State::new();
2222
        let f = NodeId::random();
2223
        let c1 = change(
2224
            vec![],
2225
            vec![TreeOp::AddNode {
2226
                node: f,
2227
                kind: NodeKind::File,
2228
                mode: Mode::TEXT,
2229
                parent: NodeId::ROOT,
2230
                name: "a.txt".into(),
2231
            }],
2232
            vec![Edit::Insert {
2233
                node: f,
2234
                after: AtomRef::Start,
2235
                before: AtomRef::End,
2236
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
2237
            }],
2238
        );
2239
        let h1 = st.add(c1).unwrap();
2240
        // Depends on h1: append a line and delete "one".
2241
        let c2 = change(
2242
            vec![h1],
2243
            vec![],
2244
            vec![
2245
                Edit::Delete {
2246
                    node: f,
2247
                    atoms: vec![AtomRange {
2248
                        change: h1,
2249
                        from: 0,
2250
                        to: 1,
2251
                    }],
2252
                },
2253
                Edit::Insert {
2254
                    node: f,
2255
                    after: AtomRef::Atom {
2256
                        change: h1,
2257
                        index: 1,
2258
                    },
2259
                    before: AtomRef::End,
2260
                    lines: vec![b"three\n".to_vec()].into(),
2261
                },
2262
            ],
2263
        );
2264
        let h2 = st.add(c2).unwrap();
2265
        assert_eq!(st.heads(), vec![h2]);
2266
        assert!(st.depends_on(&h2, &h1));
2267
        assert!(!st.depends_on(&h1, &h2));
2268
        let snap = st.materialize();
2269
        assert!(!snap.is_conflicted());
2270
        let a = &snap.files["a.txt"];
2271
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
2272
        assert_eq!(st.live_lines(&f).len(), 2);
2273
    }
2274
2275
    #[test]
2276
    fn missing_dependency_is_rejected() {
2277
        let mut st = State::new();
2278
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
2279
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
2280
    }
2281
2282
    #[test]
2283
    fn self_references_and_multi_insert_indexing() {
2284
        let mut st = State::new();
2285
        let f = NodeId::random();
2286
        let me = OpRef {
2287
            change: ObjectRef::ZERO,
2288
            index: 0,
2289
        };
2290
        let c1 = change(
2291
            vec![],
2292
            vec![
2293
                TreeOp::AddNode {
2294
                    node: f,
2295
                    kind: NodeKind::File,
2296
                    mode: Mode::TEXT,
2297
                    parent: NodeId::ROOT,
2298
                    name: "x".into(),
2299
                },
2300
                TreeOp::SetMode {
2301
                    node: f,
2302
                    old: me,
2303
                    mode: Mode {
2304
                        exec: true,
2305
                        opaque: false,
2306
                    },
2307
                },
2308
            ],
2309
            vec![
2310
                Edit::Insert {
2311
                    node: f,
2312
                    after: AtomRef::Start,
2313
                    before: AtomRef::End,
2314
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
2315
                },
2316
                // Insert between the two lines just inserted, using self references.
2317
                Edit::Insert {
2318
                    node: f,
2319
                    after: AtomRef::Atom {
2320
                        change: ObjectRef::ZERO,
2321
                        index: 0,
2322
                    },
2323
                    before: AtomRef::Atom {
2324
                        change: ObjectRef::ZERO,
2325
                        index: 1,
2326
                    },
2327
                    lines: vec![b"b\n".to_vec()].into(),
2328
                },
2329
            ],
2330
        );
2331
        st.add(c1).unwrap();
2332
        let snap = st.materialize();
2333
        let x = &snap.files["x"];
2334
        assert_eq!(
2335
            x.mode,
2336
            Mode {
2337
                exec: true,
2338
                opaque: false
2339
            }
2340
        );
2341
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
2342
    }
2343
2344
    #[test]
2345
    fn opaque_replace_and_conflict() {
2346
        let mut st = State::new();
2347
        let f = NodeId::random();
2348
        let b1 = ObjectRef([1; 32]);
2349
        let b2 = ObjectRef([2; 32]);
2350
        let b3 = ObjectRef([3; 32]);
2351
        let h1 = st
2352
            .add(change(
2353
                vec![],
2354
                vec![TreeOp::AddNode {
2355
                    node: f,
2356
                    kind: NodeKind::File,
2357
                    mode: Mode::OPAQUE,
2358
                    parent: NodeId::ROOT,
2359
                    name: "img".into(),
2360
                }],
2361
                vec![Edit::Replace {
2362
                    node: f,
2363
                    old: None,
2364
                    new: Some(b1),
2365
                }],
2366
            ))
2367
            .unwrap();
2368
        assert_eq!(st.live_blobs(&f), vec![b1]);
2369
        st.add(change(
2370
            vec![h1],
2371
            vec![],
2372
            vec![Edit::Replace {
2373
                node: f,
2374
                old: Some(b1),
2375
                new: Some(b2),
2376
            }],
2377
        ))
2378
        .unwrap();
2379
        st.add(change(
2380
            vec![h1],
2381
            vec![],
2382
            vec![Edit::Replace {
2383
                node: f,
2384
                old: Some(b1),
2385
                new: Some(b3),
2386
            }],
2387
        ))
2388
        .unwrap();
2389
        let snap = st.materialize();
2390
        assert!(snap.is_conflicted());
2391
        assert!(
2392
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2393
        );
2394
    }
2395
2396
    #[test]
2397
    fn checkpoint_payload_round_trip_and_replay() {
2398
        let mut st = State::new();
2399
        let f = NodeId::random();
2400
        let h1 = st
2401
            .add(change(
2402
                vec![],
2403
                vec![TreeOp::AddNode {
2404
                    node: f,
2405
                    kind: NodeKind::File,
2406
                    mode: Mode::TEXT,
2407
                    parent: NodeId::ROOT,
2408
                    name: "a".into(),
2409
                }],
2410
                vec![Edit::Insert {
2411
                    node: f,
2412
                    after: AtomRef::Start,
2413
                    before: AtomRef::End,
2414
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
2415
                }],
2416
            ))
2417
            .unwrap();
2418
        let h2 = st
2419
            .add(change(
2420
                vec![h1],
2421
                vec![],
2422
                vec![Edit::Delete {
2423
                    node: f,
2424
                    atoms: vec![AtomRange {
2425
                        change: h1,
2426
                        from: 0,
2427
                        to: 1,
2428
                    }],
2429
                }],
2430
            ))
2431
            .unwrap();
2432
        let payload = st.checkpoint_payload();
2433
        let back = State::from_checkpoint_payload(&payload).unwrap();
2434
        assert_eq!(back.len(), 2);
2435
        assert_eq!(back.heads(), vec![h2]);
2436
        assert_eq!(back.get(&h1).unwrap().message, "m");
2437
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2438
        // Replaying a further change onto the restored state equals a full build.
2439
        let c3 = change(
2440
            vec![h2],
2441
            vec![],
2442
            vec![Edit::Insert {
2443
                node: f,
2444
                after: AtomRef::Atom {
2445
                    change: h1,
2446
                    index: 1,
2447
                },
2448
                before: AtomRef::End,
2449
                lines: vec![b"3\n".to_vec()].into(),
2450
            }],
2451
        );
2452
        let mut full = st.clone();
2453
        full.add(c3.clone()).unwrap();
2454
        let mut restored = back;
2455
        restored.add(c3).unwrap();
2456
        let (a, b) = (full.materialize(), restored.materialize());
2457
        assert_eq!(
2458
            a.files.keys().collect::<Vec<_>>(),
2459
            b.files.keys().collect::<Vec<_>>()
2460
        );
2461
        assert_eq!(a.files["a"].content, b.files["a"].content);
2462
        assert!(
2463
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2464
        );
2465
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
2466
    }
2467
2468
    /// History-only states (O10f): the same state as a full load once its
2469
    /// graphs are built, by replay and from a version 2 checkpoint with
2470
    /// later changes; unloaded graphs are never read as empty.
2471
    #[test]
2472
    fn graph_keys_change_exactly_when_a_graph_does() {
2473
        let (f, g) = (NodeId::random(), NodeId::random());
2474
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2475
            node,
2476
            kind: NodeKind::File,
2477
            mode: Mode::TEXT,
2478
            parent: NodeId::ROOT,
2479
            name: name.into(),
2480
        };
2481
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
2482
            node,
2483
            after: AtomRef::Start,
2484
            before: AtomRef::End,
2485
            lines: vec![line.to_vec()].into(),
2486
        };
2487
        let c1 = change(
2488
            vec![],
2489
            vec![add(f, "f"), add(g, "g")],
2490
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2491
        );
2492
        let h1 = c1.hash();
2493
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
2494
        let h2 = c2.hash();
2495
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
2496
        let load = |cs: &[&Change]| {
2497
            let mut st = State::new_history_only();
2498
            for c in cs {
2499
                st.add((*c).clone()).unwrap();
2500
            }
2501
            st
2502
        };
2503
        let s1 = load(&[&c1]);
2504
        let s2 = load(&[&c1, &c2]);
2505
        let s3 = load(&[&c1, &c2, &c3]);
2506
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
2507
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
2508
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
2509
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
2510
        assert_ne!(key(&s2, &f), key(&s3, &f));
2511
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
2512
        let mut built = load(&[&c1]);
2513
        built
2514
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
2515
            .unwrap();
2516
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
2517
        let mut full = State::new();
2518
        full.add(c1.clone()).unwrap();
2519
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2520
2521
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2522
        // or inline values: stable across loads, changed by later edits.
2523
        let graphs = full.checkpoint_file_graphs();
2524
        let index = full.checkpoint_index(&graphs, |enc| {
2525
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
2526
        });
2527
        let cp = |extra: &[&Change]| {
2528
            let mut st = State::from_checkpoint_history(&index).unwrap();
2529
            for c in extra {
2530
                st.add((*c).clone()).unwrap();
2531
            }
2532
            st
2533
        };
2534
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
2535
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
2536
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
2537
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2538
2539
        // Partial rendering: skipped files are listed and empty, the others
2540
        // render as in a full state.
2541
        let mut part = load(&[&c1, &c2]);
2542
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
2543
            .unwrap();
2544
        let snap = part.materialize_except(&[f].into_iter().collect());
2545
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
2546
        let mut whole = State::new();
2547
        whole.add(c1.clone()).unwrap();
2548
        whole.add(c2.clone()).unwrap();
2549
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
2550
        assert!(
2551
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2552
        );
2553
    }
2554
2555
    #[test]
2556
    fn history_only_states_build_the_same_graphs_on_demand() {
2557
        let small = NodeId::random();
2558
        let big = NodeId::random();
2559
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2560
            node,
2561
            kind: NodeKind::File,
2562
            mode: Mode::TEXT,
2563
            parent: NodeId::ROOT,
2564
            name: name.into(),
2565
        };
2566
        let lines: crate::lines::Lines = (0..300)
2567
            .map(|i| format!("line {i}\n").into_bytes())
2568
            .collect();
2569
        let c1 = change(
2570
            vec![],
2571
            vec![add(small, "small"), add(big, "big")],
2572
            vec![
2573
                Edit::Insert {
2574
                    node: small,
2575
                    after: AtomRef::Start,
2576
                    before: AtomRef::End,
2577
                    lines: vec![b"x\n".to_vec()].into(),
2578
                },
2579
                Edit::Insert {
2580
                    node: big,
2581
                    after: AtomRef::Start,
2582
                    before: AtomRef::End,
2583
                    lines,
2584
                },
2585
            ],
2586
        );
2587
        let h1 = c1.hash();
2588
        let c2 = change(
2589
            vec![h1],
2590
            vec![],
2591
            vec![
2592
                Edit::Delete {
2593
                    node: big,
2594
                    atoms: vec![AtomRange {
2595
                        change: h1,
2596
                        from: 2,
2597
                        to: 9,
2598
                    }],
2599
                },
2600
                Edit::Insert {
2601
                    node: big,
2602
                    after: AtomRef::Atom {
2603
                        change: h1,
2604
                        index: 20,
2605
                    },
2606
                    before: AtomRef::Atom {
2607
                        change: h1,
2608
                        index: 21,
2609
                    },
2610
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
2611
                },
2612
                Edit::Insert {
2613
                    node: small,
2614
                    after: AtomRef::Atom {
2615
                        change: h1,
2616
                        index: 0,
2617
                    },
2618
                    before: AtomRef::End,
2619
                    lines: vec![b"y\n".to_vec()].into(),
2620
                },
2621
            ],
2622
        );
2623
        let h2 = c2.hash();
2624
        let c3 = change(
2625
            vec![h2],
2626
            vec![],
2627
            vec![Edit::Delete {
2628
                node: small,
2629
                atoms: vec![AtomRange {
2630
                    change: h1,
2631
                    from: 0,
2632
                    to: 1,
2633
                }],
2634
            }],
2635
        );
2636
2637
        let mut full = State::new();
2638
        for c in [&c1, &c2, &c3] {
2639
            full.add(c.clone()).unwrap();
2640
        }
2641
        // By replay: nothing built until asked, then exactly the full graphs.
2642
        let mut hist = State::new_history_only();
2643
        for c in [&c1, &c2, &c3] {
2644
            hist.add(c.clone()).unwrap();
2645
        }
2646
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
2647
        assert_eq!(hist.len(), 3);
2648
        hist.load_graphs(
2649
            &[big],
2650
            |_| unreachable!("no checkpoint"),
2651
            |_| unreachable!(),
2652
        )
2653
        .unwrap();
2654
        assert_eq!(
2655
            hist.render_file(&big).0,
2656
            full.render_file(&big).0,
2657
            "one file on its own"
2658
        );
2659
        assert!(!hist.is_full());
2660
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
2661
            .unwrap();
2662
        assert!(hist.is_full());
2663
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2664
2665
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
2666
        let mut base = State::new();
2667
        base.add(c1.clone()).unwrap();
2668
        base.add(c2.clone()).unwrap();
2669
        let graphs = base.checkpoint_file_graphs();
2670
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
2671
        let index = base.checkpoint_index(&graphs, |enc| {
2672
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
2673
            blobs.insert(r, enc.to_vec());
2674
            r
2675
        });
2676
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
2677
        from_cp.add(c3.clone()).unwrap();
2678
        assert!(!from_cp.is_full());
2679
        let mut fetched = 0;
2680
        from_cp
2681
            .load_graphs(
2682
                &[small, big],
2683
                |refs| {
2684
                    fetched += refs.len();
2685
                    refs.iter()
2686
                        .map(|r| {
2687
                            blobs
2688
                                .get(r)
2689
                                .cloned()
2690
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
2691
                        })
2692
                        .collect()
2693
                },
2694
                |_| unreachable!(),
2695
            )
2696
            .unwrap();
2697
        assert_eq!(
2698
            fetched, 1,
2699
            "the large graph's blob, in one batch; the small one was inline"
2700
        );
2701
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
2702
    }
2703
2704
    #[test]
2705
    #[should_panic(expected = "was not loaded")]
2706
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
2707
        let f = NodeId::random();
2708
        let mut st = State::new_history_only();
2709
        st.add(change(
2710
            vec![],
2711
            vec![TreeOp::AddNode {
2712
                node: f,
2713
                kind: NodeKind::File,
2714
                mode: Mode::TEXT,
2715
                parent: NodeId::ROOT,
2716
                name: "a".into(),
2717
            }],
2718
            vec![Edit::Insert {
2719
                node: f,
2720
                after: AtomRef::Start,
2721
                before: AtomRef::End,
2722
                lines: vec![b"a\n".to_vec()].into(),
2723
            }],
2724
        ))
2725
        .unwrap();
2726
        st.render_file(&f);
2727
    }
2728
2729
    #[test]
2730
    #[should_panic(expected = "needs every file graph")]
2731
    fn materializing_a_history_only_state_is_refused() {
2732
        let f = NodeId::random();
2733
        let mut st = State::new_history_only();
2734
        st.add(change(
2735
            vec![],
2736
            vec![TreeOp::AddNode {
2737
                node: f,
2738
                kind: NodeKind::File,
2739
                mode: Mode::TEXT,
2740
                parent: NodeId::ROOT,
2741
                name: "a".into(),
2742
            }],
2743
            vec![Edit::Insert {
2744
                node: f,
2745
                after: AtomRef::Start,
2746
                before: AtomRef::End,
2747
                lines: vec![b"a\n".to_vec()].into(),
2748
            }],
2749
        ))
2750
        .unwrap();
2751
        st.materialize();
2752
    }
2753
2754
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
2755
    /// blob; the state read back is the same as from version 1.
2756
    #[test]
2757
    fn checkpoint_index_round_trip_matches_version_1() {
2758
        let mut st = State::new();
2759
        let small = NodeId::random();
2760
        let big = NodeId::random();
2761
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2762
            node,
2763
            kind: NodeKind::File,
2764
            mode: Mode::TEXT,
2765
            parent: NodeId::ROOT,
2766
            name: name.into(),
2767
        };
2768
        let big_lines: crate::lines::Lines = (0..400)
2769
            .map(|i| format!("line {i} of a long file\n").into_bytes())
2770
            .collect();
2771
        let h1 = st
2772
            .add(change(
2773
                vec![],
2774
                vec![add(small, "small"), add(big, "big")],
2775
                vec![
2776
                    Edit::Insert {
2777
                        node: small,
2778
                        after: AtomRef::Start,
2779
                        before: AtomRef::End,
2780
                        lines: vec![b"x\n".to_vec()].into(),
2781
                    },
2782
                    Edit::Insert {
2783
                        node: big,
2784
                        after: AtomRef::Start,
2785
                        before: AtomRef::End,
2786
                        lines: big_lines,
2787
                    },
2788
                ],
2789
            ))
2790
            .unwrap();
2791
        st.add(change(
2792
            vec![h1],
2793
            vec![],
2794
            vec![Edit::Delete {
2795
                node: big,
2796
                atoms: vec![AtomRange {
2797
                    change: h1,
2798
                    from: 3,
2799
                    to: 7,
2800
                }],
2801
            }],
2802
        ))
2803
        .unwrap();
2804
2805
        let graphs = st.checkpoint_file_graphs();
2806
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
2807
        let index = st.checkpoint_index(&graphs, |enc| {
2808
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
2809
            blobs.insert(r, enc.to_vec());
2810
            r
2811
        });
2812
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
2813
        assert_eq!(
2814
            State::checkpoint_graph_refs(&index).unwrap(),
2815
            blobs.keys().copied().collect::<Vec<_>>()
2816
        );
2817
        assert!(
2818
            State::checkpoint_graph_refs(&st.checkpoint_payload())
2819
                .unwrap()
2820
                .is_empty(),
2821
            "version 1 names none"
2822
        );
2823
        assert!(index.len() < st.checkpoint_payload().len());
2824
2825
        let back = State::from_checkpoint(&index, |refs| {
2826
            refs.iter()
2827
                .map(|r| {
2828
                    blobs
2829
                        .get(r)
2830
                        .cloned()
2831
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
2832
                })
2833
                .collect()
2834
        })
2835
        .unwrap();
2836
        assert_eq!(
2837
            back.checkpoint_payload(),
2838
            st.checkpoint_payload(),
2839
            "the same state as version 1"
2840
        );
2841
        assert_eq!(
2842
            back.materialize().files["big"].content,
2843
            st.materialize().files["big"].content
2844
        );
2845
        // Deterministic: the same state gives the same index.
2846
        assert_eq!(
2847
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
2848
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
2849
            }),
2850
            index
2851
        );
2852
        // A missing graph blob is an error, not an empty file.
2853
        assert!(
2854
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
2855
        );
2856
        assert!(
2857
            State::from_checkpoint_payload(&index).is_err(),
2858
            "version 2 needs its blobs"
2859
        );
2860
        // Version 1 payloads still read, and unknown versions do not.
2861
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
2862
        let mut v3 = cbor::decode(&index).unwrap();
2863
        if let Value::Map(m) = &mut v3 {
2864
            m.insert(0, Value::Uint(3));
2865
        }
2866
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
2867
    }
2868
2869
    #[test]
2870
    fn maximal_elements() {
2871
        let mut st = State::new();
2872
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
2873
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
2874
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
2875
        let mut m = st.maximal(&[h1, h2, h3]);
2876
        m.sort();
2877
        let mut want = vec![h2, h3];
2878
        want.sort();
2879
        assert_eq!(m, want);
2880
        assert_eq!(st.heads(), want);
2881
    }
2882
2883
    /// The bounded walk of `depends_on` agrees with the closure on random
2884
    /// graphs, and the memo stays within its bound.
2885
    #[test]
2886
    fn depends_on_matches_the_closure() {
2887
        use rand::{Rng, SeedableRng};
2888
        let mut rng = rand::rngs::StdRng::seed_from_u64(11);
2889
        for _ in 0..10 {
2890
            let mut st = State::new();
2891
            let mut all: Vec<ChangeHash> = Vec::new();
2892
            for _ in 0..80 {
2893
                let deps: Vec<ChangeHash> =
2894
                    all.iter().copied().filter(|_| rng.gen_bool(0.06)).collect();
2895
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2896
            }
2897
            let unknown = ObjectRef([0xee; 32]);
2898
            for a in &all {
2899
                let want = st.closure(a).clone();
2900
                st.closure.write().unwrap().sets.clear();
2901
                st.closure.write().unwrap().held = 0;
2902
                for b in all.iter().chain([&unknown]) {
2903
                    assert_eq!(
2904
                        st.depends_on(a, b),
2905
                        a == b || want.contains(b),
2906
                        "{a:?} on {b:?}"
2907
                    );
2908
                }
2909
            }
2910
            assert!(st.closure.write().unwrap().held <= CLOSURE_MEMO_HASHES);
2911
        }
2912
    }
2913
2914
    /// The one-walk `maximal` agrees with the definition (not in the
2915
    /// closure of another element) on random graphs, with repeated and
2916
    /// unknown hashes among the input.
2917
    #[test]
2918
    fn maximal_matches_its_definition() {
2919
        use rand::{Rng, SeedableRng};
2920
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
2921
        for _ in 0..20 {
2922
            let mut st = State::new();
2923
            let mut all: Vec<ChangeHash> = Vec::new();
2924
            for _ in 0..60 {
2925
                let deps: Vec<ChangeHash> =
2926
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
2927
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2928
            }
2929
            let mut pick: Vec<ChangeHash> =
2930
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
2931
            pick.extend(pick.clone().into_iter().take(3));
2932
            pick.push(ObjectRef([0xee; 32]));
2933
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
2934
            let want: Vec<ChangeHash> = set
2935
                .iter()
2936
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
2937
                .copied()
2938
                .collect();
2939
            assert_eq!(st.maximal(&pick), want);
2940
            assert_eq!(st.maximal(&all), st.heads());
2941
        }
2942
    }
2943
}