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