OXYGENHUB

Coverage / crates/oxy-core/src/state.rs 92.9%

2066 of 2223 lines run, 432 of 627 functions · run #260 on main · run missed

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, Mutex};
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`]).
451502×
    pub(crate) fn write_flat(&self, w: &mut crate::flat::Writer) {
461502×
        w.fixed(&self.change_id.0);
471502×
        w.count(self.deps.len());
481502×
        for d in &self.deps {
491065×
            w.object(d);
501065×
        }
511502×
        w.object(&self.author);
521502×
        w.u64(self.hlc.wall_ms);
531502×
        w.u32(self.hlc.logical);
541502×
        w.bytes(self.message.as_bytes());
551502×
        w.u8(self.kind.tag() as u8);
561502×
    }
57
581685×
    pub(crate) fn read_flat(r: &mut crate::flat::Reader) -> Result<ChangeMeta, ObjectError> {
591685×
        let change_id = crate::ids::ChangeId(r.fixed::<16>()?);
601685×
        let mut deps = Vec::new();
611685×
        for _ in 0..r.count()? {
62803×
            deps.push(r.object()?);
63
        }
64
        Ok(ChangeMeta {
651685×
            change_id,
661685×
            deps,
671685×
            author: r.object()?,
68
            hlc: Hlc {
691685×
                wall_ms: r.u64()?,
701685×
                logical: r.u32()?,
71
            },
721685×
            message: r.text()?,
731685×
            kind: ChangeKind::from_tag(r.u8()? as u64)?,
74
        })
751685×
    }
76
7715201×
    pub fn of(c: &Change) -> ChangeMeta {
7815201×
        ChangeMeta {
7915201×
            change_id: c.change_id,
8015201×
            deps: c.deps.clone(),
8115201×
            author: c.author,
8215201×
            hlc: c.hlc,
8315201×
            message: c.message.clone(),
8415201×
            kind: c.kind,
8515201×
        }
8615201×
    }
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: Mutex<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: Mutex<HashMap<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 {
15216722×
    fn len(&self) -> u64 {
15316722×
        match self {
1544564×
            Histories::Bytes(b) => b.len() as u64,
15512158×
            Histories::File(_, _, len) => *len,
156
        }
15716722×
    }
158
15921868×
    fn read(&self, at: u64, len: usize) -> std::io::Result<Vec<u8>> {
16021868×
        match self {
1614564×
            Histories::Bytes(b) => Ok(b[at as usize..at as usize + len].to_vec()),
16217304×
            Histories::File(f, start, _) => {
16317304×
                let mut buf = vec![0u8; len];
16417304×
                read_exact_at(f, &mut buf, start + at)?;
16517304×
                Ok(buf)
166
            }
167
        }
16821868×
    }
169
}
170
171
#[cfg(unix)]
17217304×
fn read_exact_at(f: &std::fs::File, buf: &mut [u8], at: u64) -> std::io::Result<()> {
17317304×
    std::os::unix::fs::FileExt::read_exact_at(f, buf, at)
17417304×
}
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.
20121868×
    fn bytes(&self) -> Result<Vec<u8>, ObjectError> {
20221868×
        let damaged = |why: String| ObjectError::DamagedIndex(why);
20321868×
        let b = self
20421868×
            .from
20521868×
            .read(self.at, self.len)
20621868×
            .map_err(|e| damaged(format!("a file's history cannot be read: {e}")))?;
20721868×
        if *blake3::hash(&b).as_bytes() != self.sum {
2082×
            return Err(damaged("a file's history does not match its hash".into()));
20921866×
        }
21021866×
        Ok(b)
21121868×
    }
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 {
235141×
    fn from_body(body: DeferredBody) -> Deferred {
236141×
        Deferred {
237141×
            body: std::sync::OnceLock::from(Ok(body)),
238141×
            ..Deferred::default()
239141×
        }
240141×
    }
241
242
    /// The history, read and checked on first use.
243102150×
    fn body(&self) -> Result<&DeferredBody, ObjectError> {
244102150×
        self.body
245102150×
            .get_or_init(|| {
24637485×
                let mut b = match &self.raw {
247
                    // Matching its hash, it is what `write_index` wrote: it
248
                    // decodes.
2495466×
                    Some(raw) => raw
2505466×
                        .bytes()
2515466×
                        .and_then(|b| State::read_deferred_body(&b))
2525466×
                        .map_err(|e| e.to_string())?,
25332019×
                    None => DeferredBody::default(),
254
                };
25537484×
                b.edits.extend(self.more.iter().cloned());
25637484×
                b.texts.extend(self.more_texts.iter().cloned());
25737484×
                Ok(b)
25837485×
            })
259102150×
            .as_ref()
260102150×
            .map_err(|e| ObjectError::DamagedIndex(e.clone()))
261102150×
    }
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.
26535238×
    fn add(&mut self, h: ChangeHash, edits: Vec<Edit>, texts: Vec<TextRef>) {
26635238×
        if self.raw.is_some() && !matches!(self.body.get(), Some(Ok(_))) {
2672×
            self.more.push((h, edits));
2682×
            self.more_texts.extend(texts);
269
            // A body found damaged stays so: what was added cannot mend it.
2702×
            return;
27135236×
        }
272
        // No encoding to read, or decoded already: this cannot fail.
27335236×
        let b = self.body_mut().expect("a history in memory");
27435236×
        b.edits.push((h, edits));
27535236×
        b.texts.extend(texts);
27635238×
    }
277
27835236×
    fn body_mut(&mut self) -> Result<&mut DeferredBody, ObjectError> {
27935236×
        self.body()?;
28035236×
        self.raw = None;
28135236×
        self.more.clear();
28235236×
        self.more_texts.clear();
28335236×
        Ok(self
28435236×
            .body
28535236×
            .get_mut()
28635236×
            .and_then(|b| b.as_mut().ok())
28735236×
            .expect("decoded above"))
28835236×
    }
289
29022612×
    fn into_body(mut self) -> Result<DeferredBody, ObjectError> {
29122612×
        self.body()?;
29222611×
        Ok(self
29322611×
            .body
29422611×
            .take()
29522611×
            .and_then(|b| b.ok())
29622611×
            .expect("decoded above"))
29722612×
    }
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).
317848×
    pub fn write_index(&self) -> Option<Vec<u8>> {
318
        use crate::flat::Writer;
319848×
        let deferred = self.deferred.as_ref()?;
320848×
        if !self.files.is_empty() {
3210×
            return None;
322848×
        }
323
        // The changes first, as a block a reader can take on its own (see
324
        // [`State::read_index_changes`]).
325848×
        let mut w = Writer::default();
326848×
        w.fixed(Self::INDEX_MAGIC);
327848×
        let mut changes: Vec<(&ChangeHash, &Arc<ChangeMeta>)> = self.changes.iter().collect();
328848×
        changes.sort_by_key(|(h, _)| **h);
329848×
        w.count(changes.len());
330848×
        for (h, m) in changes {
331248×
            w.object(h);
332248×
            m.write_flat(&mut w);
333248×
        }
334848×
        let changes_block = std::mem::take(&mut w);
335848×
        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.
338848×
        let mut tw = Writer::default();
339848×
        self.tree.write_flat(&mut tw);
340848×
        w.bytes(&tw.0);
341848×
        let mut replaces: Vec<(&NodeId, &Vec<ReplaceRecord>)> = self.replaces.iter().collect();
342848×
        replaces.sort_by_key(|(n, _)| **n);
343848×
        w.count(replaces.len());
344848×
        for (n, recs) in replaces {
3454×
            w.fixed(&n.0);
3464×
            w.count(recs.len());
347
            // In any order: which record is live does not depend on it.
3484×
            let mut recs: Vec<&ReplaceRecord> = recs.iter().collect();
3494×
            recs.sort();
3504×
            for (c, old, new) in recs {
3514×
                w.object(c);
3524×
                w.opt_object(old);
3534×
                w.opt_object(new);
3544×
            }
355
        }
356848×
        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).
359848×
        let mut table = Writer::default();
360848×
        let mut histories: Vec<u8> = Vec::new();
361848×
        let mut nodes: Vec<(&NodeId, &Arc<Deferred>)> = deferred.iter().collect();
362848×
        nodes.sort_by_key(|(n, _)| **n);
363848×
        table.count(nodes.len());
36432798×
        for (n, d) in nodes {
36532798×
            let key = match d.key.get() {
36616402×
                Some(k) => *k,
367
                None => {
36816396×
                    let mut h = blake3::Hasher::new();
36916396×
                    h.update(b"oxy graph key 1\0");
37016396×
                    h.update(&n.0);
37116396×
                    let k = d.graph_key(h).ok()?;
37216396×
                    let _ = d.key.set(k);
37316396×
                    k
374
                }
375
            };
376
            // Unchanged since read: its bytes as they are, checked.
37732798×
            let bytes = match &d.raw {
37816402×
                Some(raw) if d.more.is_empty() => raw.bytes().ok()?,
37916396×
                _ => Self::write_deferred_body(d.body().ok()?)?,
380
            };
38132797×
            table.fixed(&n.0);
38232797×
            table.fixed(&key);
38332797×
            table.u64(histories.len() as u64);
38432797×
            table.u32(u32::try_from(bytes.len()).ok()?);
38532797×
            table.fixed(blake3::hash(&bytes).as_bytes());
38632797×
            histories.extend_from_slice(&bytes);
387
        }
388847×
        front.bytes(&table.0);
389847×
        let mut out = Writer::default();
390847×
        out.u64(front.0.len() as u64);
391847×
        out.fixed(&front.0);
392847×
        out.fixed(&histories);
393847×
        Some(out.0)
394848×
    }
395
396
    /// One file's history as an index encodes it; `None` when it holds
397
    /// text in memory, which an index does not.
39816396×
    fn write_deferred_body(d: &DeferredBody) -> Option<Vec<u8>> {
399
        use crate::flat::Writer;
40033606×
        let atom = |w: &mut Writer, a: &AtomRef| match a {
40116399×
            AtomRef::Start => w.u8(0),
40216517×
            AtomRef::End => w.u8(1),
403690×
            AtomRef::Atom { change, index } => {
404690×
                w.u8(2);
405690×
                w.object(change);
406690×
                w.u32(*index);
407690×
            }
40833606×
        };
40916396×
        let mut w = Writer::default();
4103×
        match &d.base {
41116393×
            None => w.u8(0),
4120×
            Some(DeferredBase::Blob(r)) => {
4130×
                w.u8(1);
4140×
                w.object(r);
4150×
            }
4163×
            Some(DeferredBase::Inline(v)) => {
4173×
                w.u8(2);
4183×
                w.bytes(&cbor::encode(v));
4193×
            }
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.
42416396×
        let mut texts = d.texts.iter();
42516396×
        let mut per_change: Vec<(&ChangeHash, &Vec<Edit>, Vec<&TextRef>)> = Vec::new();
42616545×
        for (c, edits) in &d.edits {
42716545×
            let n = edits
42816545×
                .iter()
42916803×
                .filter(|e| matches!(e, Edit::Insert { lines, .. } if lines.is_empty()))
43016545×
                .count();
43116545×
            per_change.push((c, edits, texts.by_ref().take(n).collect()));
432
        }
43316396×
        per_change.sort_by_key(|(c, _, _)| **c);
43416396×
        w.count(per_change.len());
43516545×
        for (c, edits, _) in &per_change {
43616545×
            w.object(c);
43716545×
            w.count(edits.len());
43816843×
            for e in edits.iter() {
43916843×
                match e {
440
                    Edit::Insert {
44116803×
                        node,
44216803×
                        after,
44316803×
                        before,
44416803×
                        lines,
445
                    } => {
44616803×
                        if !lines.is_empty() {
4470×
                            return None;
44816803×
                        }
44916803×
                        w.u8(0);
45016803×
                        w.fixed(&node.0);
45116803×
                        atom(&mut w, after);
45216803×
                        atom(&mut w, before);
453
                    }
45440×
                    Edit::Delete { node, atoms } => {
45540×
                        w.u8(1);
45640×
                        w.fixed(&node.0);
45740×
                        w.count(atoms.len());
458286×
                        for r in atoms {
459286×
                            w.object(&r.change);
460286×
                            w.u32(r.from);
461286×
                            w.u32(r.to);
462286×
                        }
463
                    }
4640×
                    Edit::Replace { .. } => return None,
465
                }
466
            }
467
        }
46816396×
        let texts: Vec<&TextRef> = per_change
46916396×
            .iter()
47016545×
            .flat_map(|(_, _, t)| t.iter().copied())
47116396×
            .collect();
47216396×
        w.count(texts.len());
47316803×
        for t in texts {
47416803×
            match t {
4750×
                TextRef::Blob(r, count, form) => {
4760×
                    w.u8(0);
4770×
                    w.object(r);
4780×
                    w.u32(*count);
4790×
                    w.u8(match form {
4800×
                        crate::objects::TextForm::Cbor => 0,
4810×
                        crate::objects::TextForm::Raw => 1,
4820×
                        crate::objects::TextForm::CborFallback => 2,
483
                    });
484
                }
48516803×
                TextRef::Inline { change, start, end } => {
48616803×
                    w.u8(1);
48716803×
                    w.object(change);
48816803×
                    w.u32(*start);
48916803×
                    w.u32(*end);
49016803×
                }
491
            }
492
        }
49316396×
        Some(w.0)
49416396×
    }
495
496
    /// The state an index holds (see [`State::write_index`]).
497192×
    pub fn read_index(bytes: &[u8]) -> Result<State, ObjectError> {
498192×
        let bad = || ObjectError::Schema("state index: truncated".into());
499192×
        let front_len =
500192×
            usize::try_from(crate::flat::Reader::new(bytes).u64()?).map_err(|_| bad())?;
501192×
        let front = bytes.get(8..8 + front_len).ok_or_else(bad)?;
502192×
        let histories = Histories::Bytes(Arc::new(bytes[8 + front_len..].to_vec()));
503192×
        Self::read_index_front(front, histories)
504192×
    }
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).
5091774×
    pub fn read_index_front(bytes: &[u8], histories: Histories) -> Result<State, ObjectError> {
510
        use crate::flat::Reader;
5111774×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
5121774×
        let mut r = Reader::new(bytes);
5131774×
        let mut st = State::new_history_only();
514
        {
5151774×
            let _t = crate::timing::phase("index: changes");
5161774×
            st.changes = Self::read_index_changes(r.bytes()?)?;
517
        }
5181774×
        let tree_bytes = r.bytes()?;
5191774×
        for _ in 0..r.count()? {
5202×
            let n = NodeId(r.fixed::<16>()?);
5212×
            let mut recs = Vec::new();
5222×
            for _ in 0..r.count()? {
5232×
                recs.push((r.object()?, r.opt_object()?, r.opt_object()?));
524
            }
5252×
            st.replaces.insert(n, recs);
526
        }
5271774×
        let deferred_bytes = r.bytes()?;
5281774×
        if !r.at_end() {
5290×
            return Err(bad("trailing bytes"));
5301774×
        }
5311774×
        let (tree, deferred) = rayon::join(
5321774×
            || TreeGraph::read_flat(&mut Reader::new(tree_bytes)),
5331774×
            || Self::read_deferred(deferred_bytes, &histories),
534
        );
5351774×
        st.tree = tree?;
5361774×
        st.deferred = Some(deferred?);
5371774×
        Ok(st)
5381774×
    }
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).
5421928×
    pub fn read_index_changes(
5431928×
        bytes: &[u8],
5441928×
    ) -> Result<HashMap<ChangeHash, Arc<ChangeMeta>>, ObjectError> {
545
        use crate::flat::Reader;
5461928×
        let mut r = Reader::new(bytes);
5471928×
        if r.fixed::<18>()?.as_slice() != Self::INDEX_MAGIC {
5480×
            return Err(ObjectError::Schema("state index: not a state index".into()));
5491928×
        }
5501928×
        let n = r.count()?;
5511928×
        let mut changes = HashMap::with_capacity(n);
5521928×
        for _ in 0..n {
553160×
            let h = r.object()?;
554160×
            changes.insert(h, Arc::new(ChangeMeta::read_flat(&mut r)?));
555
        }
5561928×
        if !r.at_end() {
5570×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
5581928×
        }
5591928×
        Ok(changes)
5601928×
    }
561
562
    /// The deferred block: each node with its graph key and its body,
563
    /// left encoded (see [`Deferred`]).
5641774×
    fn read_deferred(
5651774×
        table: &[u8],
5661774×
        histories: &Histories,
5671774×
    ) -> Result<crate::fasthash::FastMap<NodeId, Arc<Deferred>>, ObjectError> {
568
        use crate::flat::Reader;
5691774×
        let _t = crate::timing::phase("index: deferred");
5701774×
        let mut r = Reader::new(table);
5711774×
        let mut deferred = crate::fasthash::FastMap::default();
5721774×
        let n = r.count()?;
5731774×
        deferred.reserve(n);
5741774×
        for _ in 0..n {
57516722×
            let id = NodeId(r.fixed::<16>()?);
57616722×
            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.
57916722×
            let (at, len, sum) = (r.u64()?, r.u32()? as usize, r.fixed::<32>()?);
58016722×
            if at
58116722×
                .checked_add(len as u64)
58216722×
                .is_none_or(|end| end > histories.len())
583
            {
5840×
                return Err(ObjectError::Schema(
5850×
                    "state index: a file's history lies outside it".into(),
5860×
                ));
58716722×
            }
58816722×
            let d = Deferred {
58916722×
                raw: Some(RawHistory {
59016722×
                    from: histories.clone(),
59116722×
                    at,
59216722×
                    len,
59316722×
                    sum,
59416722×
                }),
59516722×
                key: std::sync::OnceLock::from(key),
59616722×
                ..Deferred::default()
59716722×
            };
59816722×
            deferred.insert(id, Arc::new(d));
599
        }
6001774×
        if !r.at_end() {
6010×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
6021774×
        }
6031774×
        Ok(deferred)
6041774×
    }
605
606
    /// One node's deferred history as the index encodes it.
6075465×
    fn read_deferred_body(bytes: &[u8]) -> Result<DeferredBody, ObjectError> {
608
        use crate::flat::Reader;
6095465×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
6105476×
        let node = |r: &mut Reader| -> Result<NodeId, ObjectError> { Ok(NodeId(r.fixed::<16>()?)) };
61110952×
        let atom = |r: &mut Reader| -> Result<AtomRef, ObjectError> {
61210952×
            Ok(match r.u8()? {
6135459×
                0 => AtomRef::Start,
6145476×
                1 => AtomRef::End,
615
                2 => AtomRef::Atom {
61617×
                    change: r.object()?,
61717×
                    index: r.u32()?,
618
                },
6190×
                _ => return Err(bad("atom")),
620
            })
62110952×
        };
6225465×
        let mut r = Reader::new(bytes);
6235465×
        let base = match r.u8()? {
6245459×
            0 => None,
6250×
            1 => Some(DeferredBase::Blob(r.object()?)),
6266×
            _ => Some(DeferredBase::Inline(cbor::decode(r.bytes()?)?)),
627
        };
6285465×
        let mut edits = Vec::new();
6295465×
        for _ in 0..r.count()? {
6305476×
            let c = r.object()?;
6315476×
            let mut es = Vec::new();
6325476×
            for _ in 0..r.count()? {
6335476×
                es.push(match r.u8()? {
634
                    0 => Edit::Insert {
6355476×
                        node: node(&mut r)?,
6365476×
                        after: atom(&mut r)?,
6375476×
                        before: atom(&mut r)?,
6385476×
                        lines: crate::lines::Lines::default(),
639
                    },
640
                    1 => {
6410×
                        let node = node(&mut r)?;
6420×
                        let mut atoms = Vec::new();
6430×
                        for _ in 0..r.count()? {
6440×
                            atoms.push(crate::objects::AtomRange {
6450×
                                change: r.object()?,
6460×
                                from: r.u32()?,
6470×
                                to: r.u32()?,
648
                            });
649
                        }
6500×
                        Edit::Delete { node, atoms }
651
                    }
6520×
                    _ => return Err(bad("edit")),
653
                });
654
            }
6555476×
            edits.push((c, es));
656
        }
6575465×
        let mut texts = Vec::new();
6585465×
        for _ in 0..r.count()? {
6595476×
            texts.push(match r.u8()? {
660
                0 => TextRef::Blob(
6610×
                    r.object()?,
6620×
                    r.u32()?,
6630×
                    match r.u8()? {
6640×
                        0 => crate::objects::TextForm::Cbor,
6650×
                        1 => crate::objects::TextForm::Raw,
6660×
                        _ => crate::objects::TextForm::CborFallback,
667
                    },
668
                ),
669
                _ => TextRef::Inline {
6705476×
                    change: r.object()?,
6715476×
                    start: r.u32()?,
6725476×
                    end: r.u32()?,
673
                },
674
            });
675
        }
6765465×
        if !r.at_end() {
6770×
            return Err(bad("trailing bytes in a file's history"));
6785465×
        }
6795465×
        Ok(DeferredBody { base, edits, texts })
6805465×
    }
681
}
682
683
impl Clone for State {
6841332×
    fn clone(&self) -> State {
6851332×
        State {
6861332×
            changes: self.changes.clone(),
6871332×
            tree: self.tree.clone(),
6881332×
            files: self.files.clone(),
6891332×
            replaces: self.replaces.clone(),
6901332×
            // A cache: the clone builds its own.
6911332×
            closure: Mutex::new(ClosureMemo::default()),
6921332×
            levels: Mutex::new(HashMap::new()),
6931332×
            deferred: self.deferred.clone(),
6941332×
        }
6951332×
    }
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 {
72013493×
    pub fn is_conflicted(&self) -> bool {
72113493×
        match &self.content {
72212568×
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
723243×
            FileContent::Opaque { blobs } => blobs.len() > 1,
724682×
            FileContent::Dir => false,
725
        }
72613493×
    }
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 {
7481902×
    pub fn is_conflicted(&self) -> bool {
74913200×
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
7501902×
    }
751
}
752
75361652×
fn vertex(r: AtomRef) -> Vertex {
75461652×
    match r {
75525623×
        AtomRef::Start => Vertex::Start,
75627045×
        AtomRef::End => Vertex::End,
7578984×
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
758
    }
75961652×
}
760
761
/// Replace self references in a tree op with the concrete change hash.
76238414×
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
76338414×
    match op {
764767×
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
765767×
            node: *node,
766767×
            placement: placement.resolve(me),
767767×
        },
768
        TreeOp::Move {
769152×
            node,
770152×
            old,
771152×
            parent,
772152×
            name,
773152×
        } => TreeOp::Move {
774152×
            node: *node,
775152×
            old: old.resolve(me),
776152×
            parent: *parent,
777152×
            name: name.clone(),
778152×
        },
77922×
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
78022×
            node: *node,
78122×
            old: old.resolve(me),
78222×
            mode: *mode,
78322×
        },
78437473×
        add @ TreeOp::AddNode { .. } => add.clone(),
785
    }
78638414×
}
787
788
/// Apply one change's edits of one file (inserts and deletes; replaces
789
/// live beside the graphs) to that file's graph.
79025620×
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`).
79225620×
    let order = g.take_order();
79325620×
    let mut inserts: Vec<(Vertex, Vertex, u32, u32)> = Vec::new();
79425620×
    let mut deleted: Vec<crate::graph::AtomKey> = Vec::new();
79525620×
    let mut next = 0u32;
79627775×
    for e in edits {
79727775×
        match e {
798
            Edit::Insert {
79926405×
                after,
80026405×
                before,
80126405×
                lines,
802
                ..
80326405×
            } => {
80426405×
                let first = next;
80526405×
                let count = lines.len() as u32;
80626405×
                next += count;
80726405×
                let (after, before) = (vertex(after.resolve(h)), vertex(before.resolve(h)));
80826405×
                inserts.push((after, before, first, count));
80926405×
                g.insert_owned(h, first, after, before, lines);
81026405×
            }
8111370×
            Edit::Delete { atoms, .. } => {
8122437×
                for r in atoms {
8132437×
                    let r = r.resolve(h);
8142527×
                    deleted.extend((r.from..r.to).map(|i| (r.change, i)));
8152437×
                    g.delete(h, &r);
816
                }
817
            }
8180×
            Edit::Replace { .. } => {}
819
        }
820
    }
82125620×
    if let Some(o) = order {
82272×
        g.keep_spliced(o, h, &inserts, &deleted);
82325548×
    }
82425620×
}
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).
8293525×
fn build_deferred(
8303525×
    taken: Vec<(NodeId, Deferred)>,
8313525×
    load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
8323525×
    read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
8333525×
) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
8343525×
    let mut taken: Vec<(NodeId, DeferredBody)> = taken
8353525×
        .into_iter()
83622612×
        .map(|(n, d)| Ok((n, d.into_body()?)))
8373525×
        .collect::<Result<_, ObjectError>>()?;
8383524×
    let mut refs: Vec<ObjectRef> = taken
8393524×
        .iter()
8403524×
        .filter_map(|(_, d)| match &d.base {
8416×
            Some(DeferredBase::Blob(r)) => Some(*r),
84222605×
            _ => None,
84322611×
        })
8443524×
        .collect();
845
    // Text blobs of inserts read without their lines, after the bases.
8463524×
    let bases = refs.len();
84722611×
    refs.extend(taken.iter().flat_map(|(_, d)| {
84825743×
        d.texts.iter().filter_map(|t| match t {
84970×
            TextRef::Blob(r, _, _) => Some(*r),
85025673×
            TextRef::Inline { .. } => None,
85125743×
        })
85222611×
    }));
853
    // And the encodings of changes whose inline inserts are needed,
854
    // each read once.
8553524×
    let reading = crate::timing::phase("graphs: read changes and blobs");
8563524×
    let mut changes: HashMap<ChangeHash, Arc<Vec<u8>>> = HashMap::new();
85725743×
    for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
85825743×
        if let TextRef::Inline { change, .. } = t {
85925673×
            if !changes.contains_key(change) {
8605736×
                changes.insert(*change, read_change(change)?);
86119937×
            }
86270×
        }
863
    }
8643524×
    let n_changes = changes.len();
8653524×
    drop(reading);
8663524×
    let reading = crate::timing::phase("graphs:   of which blobs");
8673524×
    let mut blobs = if refs.is_empty() {
8683453×
        Vec::new()
869
    } else {
87071×
        load(&refs)?
871
    };
8723521×
    if crate::timing::enabled() {
8732×
        eprintln!(
8742×
            "timing graphs: {} graphs, {n_changes} changes, {} blobs",
8752×
            taken.len(),
8762×
            refs.len()
8772×
        );
8783519×
    }
8793521×
    if blobs.len() != refs.len() {
8800×
        return Err(ObjectError::Schema("graph blobs: wrong count".into()));
8813521×
    }
8823521×
    drop(reading);
8833521×
    let lines = crate::timing::phase("graphs: hand out blobs");
8843521×
    let mut texts = blobs.split_off(bases).into_iter();
8853521×
    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>>);
8893521×
    let mut work: Vec<Work> = Vec::with_capacity(taken.len());
89022608×
    for (node, d) in taken.drain(..) {
89122608×
        let wanted = d
89222608×
            .texts
89322608×
            .iter()
89425741×
            .filter(|t| matches!(t, TextRef::Blob(..)))
89522608×
            .count();
89622608×
        let mine: Vec<Vec<u8>> = texts.by_ref().take(wanted).collect();
89722608×
        if mine.len() != wanted {
8980×
            return Err(ObjectError::Schema("text blobs: wrong count".into()));
89922608×
        }
90022608×
        let bytes = match &d.base {
901
            Some(DeferredBase::Blob(_)) => Some(
9025×
                blobs
9035×
                    .next()
9045×
                    .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
905
            ),
90622603×
            _ => None,
907
        };
90822608×
        work.push((node, d, bytes, mine));
909
    }
9103521×
    drop(lines);
9113521×
    let _t = crate::timing::phase("graphs: lines and build");
912
    use rayon::prelude::*;
9133521×
    let changes = &changes;
9143521×
    let built: Vec<(NodeId, FileGraph)> = work
9153521×
        .into_par_iter()
91622608×
        .map(|(node, mut d, bytes, mine)| {
917
            // Fill in the lines of inserts read without them, in order.
91822608×
            let mut want = std::mem::take(&mut d.texts).into_iter();
91922608×
            let mut mine = mine.into_iter();
92025150×
            for (_, edits) in d.edits.iter_mut() {
92126865×
                for e in edits.iter_mut() {
92226865×
                    if let Edit::Insert { lines, .. } = e {
92325748×
                        if lines.is_empty() {
92425741×
                            *lines = match want.next() {
92568×
                                Some(TextRef::Blob(_, count, form)) => {
92668×
                                    let content = mine.next().ok_or_else(|| {
9270×
                                        ObjectError::Schema("text blobs: wrong count".into())
9280×
                                    })?;
92968×
                                    crate::objects::text_lines(&content, count, form)?
930
                                }
93125673×
                                Some(TextRef::Inline { change, start, end }) => {
93225673×
                                    let bytes = &changes[&change];
93325673×
                                    let range = bytes
93425673×
                                        .get(start as usize..end as usize)
93525673×
                                        .ok_or_else(|| {
9360×
                                            ObjectError::Schema(
9370×
                                                "an inline insert lies outside its change".into(),
9380×
                                            )
9390×
                                        })?;
94025673×
                                    crate::objects::inline_lines(range)?
941
                                }
942
                                None => {
9430×
                                    return Err(ObjectError::Schema(
9440×
                                        "an insert's text is missing".into(),
9450×
                                    ))
946
                                }
947
                            };
9487×
                        }
9491117×
                    }
950
                }
951
            }
95222608×
            let mut graph = match (d.base.take(), bytes) {
95396×
                (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
9545×
                (Some(DeferredBase::Blob(_)), Some(bytes)) => {
9555×
                    FileGraph::from_value(&cbor::decode(&bytes)?)?
956
                }
95722507×
                _ => FileGraph::default(),
958
            };
95925150×
            for (h, edits) in std::mem::take(&mut d.edits) {
96025150×
                apply_file_edits(&mut graph, h, edits);
96125150×
            }
96222608×
            Ok((node, graph))
96322608×
        })
9643521×
        .collect::<Result<_, ObjectError>>()?;
9653521×
    Ok(built)
9663525×
}
967
968
impl State {
969683×
    pub fn new() -> Self {
970683×
        Self::default()
971683×
    }
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.
9773377×
    pub fn new_history_only() -> Self {
9783377×
        State {
9793377×
            deferred: Some(Default::default()),
9803377×
            ..Self::default()
9813377×
        }
9823377×
    }
983
984
    /// Whether `node`'s file graph is built (always, in a full state).
98540×
    pub fn is_built(&self, node: &NodeId) -> bool {
98640×
        self.deferred.is_none() || self.files.contains_key(node)
98740×
    }
988
989
    /// Whether this state builds file graphs only when asked
990
    /// ([`State::new_history_only`]), even if it has none waiting.
9913180×
    pub fn is_history_only(&self) -> bool {
9923180×
        self.deferred.is_some()
9933180×
    }
994
995
    /// Whether this state holds every file graph.
9962643×
    pub fn is_full(&self) -> bool {
9972643×
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
9982643×
    }
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.
100225066×
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
100325066×
        if let Some(d) = &self.deferred {
10049977×
            assert!(
10059977×
                !d.contains_key(node),
1006
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
10071×
                node.short(12)
1008
            );
100915089×
        }
101025065×
        self.files.get(node).map(|g| g.as_ref())
101125065×
    }
1012
1013
    /// Operations over every file need every graph.
10142636×
    fn require_full(&self, what: &str) {
10152636×
        assert!(
10162636×
            self.is_full(),
1017
            "{what} needs every file graph; this state was loaded for history only"
1018
        );
10192635×
    }
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.
10243450×
    pub fn load_graphs(
10253450×
        &mut self,
10263450×
        nodes: &[NodeId],
10273450×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
10283450×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
10293450×
    ) -> Result<(), ObjectError> {
10303450×
        let Some(deferred) = self.deferred.as_mut() else {
10310×
            return Ok(());
1032
        };
10333450×
        let taken: Vec<(NodeId, Deferred)> = nodes
10343450×
            .iter()
103522792×
            .filter_map(|n| deferred.remove(n).map(|d| (*n, Arc::unwrap_or_clone(d))))
10363450×
            .collect();
10373450×
        let built = build_deferred(taken, load, read_change)?;
10383446×
        self.files
103922549×
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
10403446×
        Ok(())
10413450×
    }
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).
104875×
    pub fn build_graphs_detached(
104975×
        &self,
105075×
        nodes: &[NodeId],
105175×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
105275×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
105375×
    ) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
105475×
        let Some(deferred) = self.deferred.as_ref() else {
10550×
            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).
106175×
        let mut built: Vec<(NodeId, FileGraph)> = Vec::new();
106275×
        let mut copies: Vec<(NodeId, Deferred)> = Vec::new();
106375×
        for n in nodes {
106462×
            match (self.files.get(n), deferred.get(n)) {
10653×
                (Some(g), _) => built.push((*n, (**g).clone())),
106659×
                (None, d) => copies.push((*n, d.map(|d| (**d).clone()).unwrap_or_default())),
1067
            }
1068
        }
106975×
        let mut out = build_deferred(copies, load, read_change)?;
107075×
        out.extend(built);
107175×
        Ok(out)
107275×
    }
1073
1074
    /// Render a graph built for this state (see
1075
    /// [`State::build_graphs_detached`]), as [`State::render_file`] does.
107662×
    pub fn render_graph(&self, g: &FileGraph) -> (Vec<u8>, Materialized) {
107762×
        let m = g.materialize(self);
107862×
        let bytes = g.render(&m, &|h| self.label(h));
107962×
        (bytes, m)
108062×
    }
1081
1082
    /// Every file graph a history-only state has not built, deleted files'
1083
    /// included.
108476×
    pub fn unbuilt_nodes(&self) -> Vec<NodeId> {
108576×
        self.deferred
108676×
            .as_ref()
108776×
            .map(|d| d.keys().copied().collect())
108876×
            .unwrap_or_default()
108976×
    }
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.
1094421×
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
10956031×
        for n in nodes {
10966031×
            self.files.remove(n);
10976031×
        }
1098421×
    }
1099
1100
    /// Build every graph a history-only state has not built, making it full.
11011724×
    pub fn load_all_graphs(
11021724×
        &mut self,
11031724×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
11041724×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
11051724×
    ) -> Result<(), ObjectError> {
11061724×
        let nodes: Vec<NodeId> = match &self.deferred {
11071724×
            Some(d) => d.keys().copied().collect(),
11080×
            None => return Ok(()),
1109
        };
11101724×
        self.load_graphs(&nodes, load, read_change)?;
11111724×
        self.deferred = None;
11121724×
        Ok(())
11131724×
    }
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.
11195885×
    pub fn single_text(&self, node: &NodeId) -> Option<TextRef> {
11205885×
        if self.files.contains_key(node) {
11210×
            return None;
11225885×
        }
1123
        // A history that cannot be read is no single text: building its
1124
        // graph reports why.
11255885×
        let d = self.deferred.as_ref()?.get(node)?.body().ok()?;
11265816×
        let [(_, edits)] = d.edits.as_slice() else {
1127259×
            return None;
1128
        };
1129
        let [Edit::Insert {
1130
            after: AtomRef::Start,
1131
            before: AtomRef::End,
11325557×
            lines,
1133
            ..
11345557×
        }] = edits.as_slice()
1135
        else {
11360×
            return None;
1137
        };
11385557×
        match (&d.base, d.texts.as_slice()) {
11395557×
            (None, [t]) if lines.is_empty() => Some(*t),
11400×
            _ => None,
1141
        }
11425885×
    }
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.
115128625×
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
115228625×
        let deferred = self.deferred.as_ref()?;
115328589×
        if self.files.contains_key(node) {
1154429×
            return None;
115528160×
        }
115628160×
        let mut h = blake3::Hasher::new();
115728160×
        h.update(b"oxy graph key 1\0");
1158
        // A change's edits are applied per node: the node is part of it.
115928160×
        h.update(&node.0);
116028160×
        let Some(d) = deferred.get(node) else {
1161
            // Never edited: the empty graph.
1162231×
            h.update(&[0]);
1163231×
            return Some(*h.finalize().as_bytes());
1164
        };
1165
        // A history that cannot be read has no key: the file is read.
116627929×
        if let Some(k) = d.key.get() {
116722235×
            return Some(*k);
11685694×
        }
11695694×
        let k = d.graph_key(h).ok()?;
11705694×
        Some(*d.key.get_or_init(|| k))
117128625×
    }
1172
11733371×
    pub fn len(&self) -> usize {
11743371×
        self.changes.len()
11753371×
    }
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.
11841×
    pub fn shed_graphs<E>(
11851×
        &mut self,
11861×
        mut store: impl FnMut(&[u8]) -> Result<ObjectRef, E>,
11871×
    ) -> Result<usize, E> {
1188
        use rayon::prelude::*;
11891×
        let Some(deferred) = self.deferred.as_mut() else {
11900×
            return Ok(0);
1191
        };
11921×
        let graphs: Vec<(NodeId, Arc<FileGraph>)> = self.files.drain().collect();
11931×
        let encoded: Vec<(NodeId, Vec<u8>)> = graphs
11941×
            .par_iter()
11952×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
11961×
            .collect();
11971×
        drop(graphs);
11981×
        let shed = encoded.len();
11992×
        for (node, bytes) in encoded {
12002×
            let blob = store(&bytes)?;
12012×
            deferred.insert(
12022×
                node,
12032×
                Arc::new(Deferred::from_body(DeferredBody {
12042×
                    base: Some(DeferredBase::Blob(blob)),
12052×
                    ..DeferredBody::default()
12062×
                })),
1207
            );
1208
        }
12091×
        Ok(shed)
12101×
    }
1211
1212
    /// How many file graphs this state has built.
121376×
    pub fn built_count(&self) -> usize {
121476×
        self.files.len()
121576×
    }
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.
121950×
    pub fn built_atoms(&self) -> usize {
122056×
        self.files.values().map(|g| g.atom_count()).sum()
122150×
    }
1222
1223
    /// Edits held in the deferred histories of files not built, and the
1224
    /// most any one file holds (for measuring, #25).
12250×
    pub fn deferred_edit_count(&self) -> (usize, usize) {
12260×
        let Some(d) = self.deferred.as_ref() else {
12270×
            return (0, 0);
1228
        };
12290×
        let mut total = 0;
12300×
        let mut most = 0;
12310×
        for v in d.values() {
12320×
            let n: usize = v
12330×
                .body()
12340×
                .map_or(0, |b| b.edits.iter().map(|(_, e)| e.len()).sum());
12350×
            total += n;
12360×
            most = most.max(n);
1237
        }
12380×
        (total, most)
12390×
    }
1240
}
1241
1242
impl Deferred {
1243
    /// See [`State::graph_key`]: `h` has taken the node already.
124422090×
    fn graph_key(&self, mut h: blake3::Hasher) -> Result<[u8; 32], ObjectError> {
124522090×
        let d = self.body()?;
124613×
        match &d.base {
124722077×
            None => h.update(&[0]),
12480×
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
124913×
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
1250
        };
125122090×
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
125222090×
        changes.sort();
125322090×
        changes.dedup();
125422090×
        h.update(&(changes.len() as u64).to_le_bytes());
125523558×
        for c in changes {
125623558×
            h.update(&c.0);
125723558×
        }
125822090×
        Ok(*h.finalize().as_bytes())
125922090×
    }
1260
}
1261
1262
impl State {
12630×
    pub fn is_empty(&self) -> bool {
12640×
        self.changes.is_empty()
12650×
    }
126613716×
    pub fn contains(&self, h: &ChangeHash) -> bool {
126713716×
        self.changes.contains_key(h)
126813716×
    }
126964×
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
127064×
        self.changes.get(h).map(|m| &**m)
127164×
    }
12721325×
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
12733343×
        self.changes.iter().map(|(h, m)| (h, &**m))
12741325×
    }
127517399×
    pub fn tree(&self) -> &TreeGraph {
127617399×
        &self.tree
127717399×
    }
1278570×
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
1279570×
        self.graph(node)
1280570×
    }
1281
1282
    /// Add a change whose dependencies are already present.
12832883×
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
12842883×
        let h = change.hash();
12852883×
        self.add_hashed(h, change)
12862883×
    }
1287
1288
    /// [`State::add`] for a change whose hash `h` is already known (it was
1289
    /// just stored), so it is not encoded again.
12903514×
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
12913514×
        if self.changes.contains_key(&h) {
129237×
            return Ok(h);
12933477×
        }
12945003×
        for d in &change.deps {
12955003×
            if !self.changes.contains_key(d) {
12962×
                return Err(StateError::MissingDep(*d, h));
12975001×
            }
1298
        }
12993475×
        self.add_known(h, change, Vec::new());
13003475×
        Ok(h)
13013514×
    }
1302
1303
    /// Add a change in any order; call `validate` once all are in.
13041032×
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
13051032×
        let h = change.hash();
13061032×
        self.add_known(h, change, Vec::new());
13071032×
        h
13081032×
    }
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.
131690×
    pub fn add_known_mixed(
131790×
        &mut self,
131890×
        h: ChangeHash,
131990×
        full: Change,
132090×
        skeleton: Change,
132190×
        texts: Vec<TextRef>,
132290×
    ) {
132390×
        if self.deferred.is_none() || self.changes.contains_key(&h) {
13240×
            self.add_known(h, full, Vec::new());
13250×
            return;
132690×
        }
1327
        let Change {
132890×
            version,
132990×
            change_id,
133090×
            deps,
133190×
            author,
133290×
            hlc,
133390×
            message,
133490×
            tree_ops,
133590×
            edits: full_edits,
133690×
            kind,
133790×
        } = full;
133890×
        let mut texts = texts.into_iter();
133990×
        let mut edits = Vec::with_capacity(full_edits.len());
134090×
        let mut kept = Vec::new();
134195×
        for (f, s) in full_edits.into_iter().zip(skeleton.edits) {
134295×
            let text = match &s {
134375×
                Edit::Insert { lines, .. } if lines.is_empty() => texts.next(),
134420×
                _ => None,
1345
            };
134695×
            if self.files.contains_key(&f.node()) {
134745×
                edits.push(f);
134850×
            } else {
134950×
                edits.push(s);
135050×
                kept.extend(text);
135150×
            }
1352
        }
135390×
        let c = Change {
135490×
            version,
135590×
            change_id,
135690×
            deps,
135790×
            author,
135890×
            hlc,
135990×
            message,
136090×
            tree_ops,
136190×
            edits,
136290×
            kind,
136390×
        };
136490×
        self.add_known(h, c, kept);
136590×
    }
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.
137212228×
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
137312228×
        if self.changes.contains_key(&h) {
13740×
            return;
137512228×
        }
137612228×
        let meta = ChangeMeta::of(&change);
137712228×
        self.apply_with(h, change, texts);
137812228×
        self.changes.insert(h, Arc::new(meta));
137912228×
        {
138012228×
            let mut m = self.closure.lock().unwrap();
138112228×
            m.sets.clear();
138212228×
            m.held = 0;
138312228×
        }
138412228×
    }
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).
1390380×
    pub fn checkpoint_payload(&self) -> Vec<u8> {
1391380×
        self.require_full("a checkpoint");
1392380×
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
1393380×
        nodes.sort();
1394380×
        let files = Value::Array(
1395380×
            nodes
1396380×
                .into_iter()
13971517×
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
1398380×
                .collect(),
1399
        );
1400380×
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
1401380×
    }
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.
140518×
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
1406
        use rayon::prelude::*;
140718×
        self.require_full("a checkpoint");
140818×
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
140953×
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
141018×
        nodes.sort_by_key(|(n, _)| **n);
141118×
        nodes
141218×
            .into_par_iter()
141353×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
141418×
            .collect()
141518×
    }
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).
142118×
    pub fn checkpoint_index(
142218×
        &self,
142318×
        graphs: &[(NodeId, Vec<u8>)],
142418×
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
142518×
    ) -> Vec<u8> {
142618×
        let files = Value::Array(
142718×
            graphs
142818×
                .iter()
142953×
                .map(|(n, enc)| {
143053×
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
143146×
                        cbor::decode(enc).expect("an encoded graph decodes")
1432
                    } else {
14337×
                        Value::Bytes(blob_of(enc).0.to_vec())
1434
                    };
143553×
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
143653×
                })
143718×
                .collect(),
1438
        );
143918×
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
144018×
    }
1441
1442
    /// The payload map around `files`: changes, tree and replaces as in version 1.
1443398×
    fn payload_value(&self, version: u64, files: Value) -> Value {
1444398×
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
1445398×
        hashes.sort();
1446398×
        let changes = Value::Array(
1447398×
            hashes
1448398×
                .into_iter()
14492341×
                .map(|h| {
14502341×
                    let m = &self.changes[h];
14512341×
                    Value::Array(vec![
14522341×
                        Value::Bytes(h.0.to_vec()),
14532341×
                        Value::Bytes(m.change_id.0.to_vec()),
14542341×
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
14552341×
                        Value::Text(m.message.clone()),
14562341×
                        Value::Uint(m.hlc.wall_ms),
14572341×
                        Value::Uint(m.hlc.logical as u64),
14582341×
                        Value::Uint(m.kind.tag()),
14592341×
                        Value::Bytes(m.author.0.to_vec()),
1460
                    ])
14612341×
                })
1462398×
                .collect(),
1463
        );
1464398×
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
1465398×
        rnodes.sort();
1466398×
        let opt =
146710×
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
1468398×
        let replaces = Value::Array(
1469398×
            rnodes
1470398×
                .into_iter()
1471398×
                .map(|n| {
14725×
                    Value::Array(vec![
14735×
                        Value::Bytes(n.0.to_vec()),
1474
                        Value::Array(
14755×
                            self.replaces[n]
14765×
                                .iter()
14775×
                                .map(|(c, o, nw)| {
14785×
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
14795×
                                })
14805×
                                .collect(),
1481
                        ),
1482
                    ])
14835×
                })
1484398×
                .collect(),
1485
        );
1486398×
        Value::map([
1487398×
            (0, Value::Uint(version)),
1488398×
            (1, changes),
1489398×
            (2, self.tree.to_value()),
1490398×
            (3, files),
1491398×
            (4, replaces),
1492398×
        ])
1493398×
    }
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`].
149737×
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
149837×
        State::from_checkpoint(bytes, |_| {
14991×
            Err(ObjectError::Schema(
15001×
                "a version 2 checkpoint needs its graph blobs".into(),
15011×
            ))
15021×
        })
150337×
    }
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.
150860×
    pub fn from_checkpoint(
150960×
        bytes: &[u8],
151060×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
151160×
    ) -> Result<State, ObjectError> {
1512
        use rayon::prelude::*;
151360×
        let v = cbor::decode(bytes)?;
151459×
        let m = o::map(&v, "checkpoint payload")?;
151559×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
151659×
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
15171×
            return Err(ObjectError::Schema(format!(
15181×
                "checkpoint payload version {version} is not supported"
15191×
            )));
152058×
        }
152158×
        let mut st = State::payload_common(m)?;
152258×
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
152358×
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
1524234×
        for f in entries {
1525234×
            let e = o::array(f, "file")?;
1526234×
            if e.len() != 2 {
15270×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1528234×
            }
1529234×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1530234×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1531234×
            parsed.push((node, &e[1]));
1532
        }
1533
        // Version 2 names large graphs by blob: fetch those in one batch.
153458×
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
153558×
        if version == CHECKPOINT_INDEX_VERSION {
153620×
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
153720×
                .iter()
153890×
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
153920×
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
154020×
                .collect::<Result<_, ObjectError>>()?;
154120×
            if !wanted.is_empty() {
15427×
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
15433×
                let contents = {
15447×
                    let _t = crate::timing::phase("load:   graph blobs read");
15457×
                    load(&refs)?
1546
                };
15473×
                if contents.len() != refs.len() {
15480×
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
15493×
                }
15503×
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
155113×
            }
1552144×
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
15530×
            return Err(ObjectError::Schema(
15540×
                "a version 1 payload holds graphs inline".into(),
15550×
            ));
155638×
        }
1557
        // File graphs are independent; decode and build them in parallel.
155854×
        let graphs = parsed
155954×
            .par_iter()
1560228×
            .map(|(node, entry)| {
1561228×
                let graph = match fetched.get(node) {
15623×
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
1563225×
                    None => FileGraph::from_value(entry)?,
1564
                };
1565228×
                Ok((*node, graph))
1566228×
            })
156754×
            .collect::<Result<Vec<_>, ObjectError>>()?;
156854×
        st.files
1569228×
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
157054×
        Ok(st)
157160×
    }
1572
1573
    /// The graph blobs a payload names: empty for version 1.
15749×
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
15759×
        let v = cbor::decode(bytes)?;
15769×
        let m = o::map(&v, "checkpoint payload")?;
15779×
        let mut out = Vec::new();
157827×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
157927×
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
15806×
                out.push(o::oref(entry, "graph blob")?);
158121×
            }
1582
        }
15839×
        Ok(out)
15849×
    }
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.
159042×
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
159142×
        let v = cbor::decode(bytes)?;
159242×
        let m = o::map(&v, "checkpoint payload")?;
159342×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
159442×
        if version != CHECKPOINT_INDEX_VERSION {
15951×
            return State::from_checkpoint_payload(bytes);
159641×
        }
159741×
        let mut st = State::payload_common(m)?;
159841×
        let mut deferred = crate::fasthash::FastMap::default();
1599139×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1600139×
            let e = o::array(f, "file")?;
1601139×
            if e.len() != 2 {
16020×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1603139×
            }
1604139×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1605139×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1606139×
            let base = match &e[1] {
16074×
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
1608135×
                other => DeferredBase::Inline(other.clone()),
1609
            };
1610139×
            deferred.insert(
1611139×
                node,
1612139×
                Arc::new(Deferred::from_body(DeferredBody {
1613139×
                    base: Some(base),
1614139×
                    ..DeferredBody::default()
1615139×
                })),
1616
            );
1617
        }
161841×
        st.deferred = Some(deferred);
161941×
        Ok(st)
162042×
    }
1621
1622
    /// Changes, tree and replaces of a payload of either version.
162399×
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
162499×
        let mut st = State::new();
1625510×
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
1626510×
            let e = o::array(c, "change meta")?;
1627510×
            if e.len() != 8 {
16280×
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
1629510×
            }
1630510×
            let hash = o::oref(&e[0], "hash")?;
1631510×
            let meta = ChangeMeta {
1632510×
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
1633510×
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
1634510×
                deps: o::array(&e[2], "deps")?
1635510×
                    .iter()
1636622×
                    .map(|d| o::oref(d, "dep"))
1637510×
                    .collect::<Result<Vec<_>, _>>()?,
1638510×
                message: o::text(&e[3], "message")?.to_owned(),
1639
                hlc: Hlc {
1640510×
                    wall_ms: o::uint(&e[4], "wall")?,
1641510×
                    logical: o::u32_(&e[5], "logical")?,
1642
                },
1643510×
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
1644510×
                author: o::oref(&e[7], "author")?,
1645
            };
1646510×
            st.changes.insert(hash, Arc::new(meta));
1647
        }
164899×
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
164999×
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
165024×
            if v.is_null() {
165112×
                Ok(None)
1652
            } else {
165312×
                o::oref(v, "blob").map(Some)
1654
            }
165524×
        };
165699×
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
165712×
            let e = o::array(r, "replace")?;
165812×
            if e.len() != 2 {
16590×
                return Err(ObjectError::Schema(
16600×
                    "replace: expected [node, records]".into(),
16610×
                ));
166212×
            }
166312×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
166412×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
166512×
            let mut recs = Vec::new();
166612×
            for rec in o::array(&e[1], "records")? {
166712×
                let x = o::array(rec, "record")?;
166812×
                if x.len() != 3 {
16690×
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
167012×
                }
167112×
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
1672
            }
167312×
            st.replaces.insert(node, recs);
1674
        }
167599×
        Ok(st)
167699×
    }
1677
16783351×
    pub fn validate(&self) -> Result<(), StateError> {
16798824×
        for (h, c) in &self.changes {
16808824×
            for d in &c.deps {
16815395×
                if !self.changes.contains_key(d) {
16820×
                    return Err(StateError::MissingDep(*d, *h));
16835395×
                }
1684
            }
1685
        }
16863351×
        Ok(())
16873351×
    }
1688
168912228×
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
169038414×
        for (i, op) in c.tree_ops.iter().enumerate() {
169138414×
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
169238414×
        }
169312228×
        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.
16967083×
            let mut texts = texts.into_iter();
16977083×
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
169838371×
            for e in c.edits {
169938371×
                match e {
1700613×
                    Edit::Replace { node, old, new } => {
1701613×
                        self.replaces.entry(node).or_default().push((h, old, new))
1702
                    }
170337758×
                    e => {
170437758×
                        let slot = per_node.entry(e.node()).or_default();
170535993×
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
170632425×
                            slot.1.extend(texts.next());
170732425×
                        }
170837758×
                        slot.0.push(e);
1709
                    }
1710
                }
1711
            }
171235708×
            for (node, (edits, node_texts)) in per_node {
171335708×
                match self.files.get_mut(&node) {
1714470×
                    Some(g) => {
1715470×
                        assert!(
1716470×
                            node_texts.is_empty(),
1717
                            "a change read without its text applied to a built graph"
1718
                        );
1719470×
                        apply_file_edits(Arc::make_mut(g), h, edits)
1720
                    }
172135238×
                    None => {
172235238×
                        let d = Arc::make_mut(deferred.entry(node).or_default());
172335238×
                        d.add(h, edits, node_texts);
172435238×
                        d.key = Default::default();
172535238×
                    }
1726
                }
1727
            }
17287083×
            return;
17295145×
        }
17305145×
        assert!(
17315145×
            texts.is_empty(),
1732
            "a change read without its text applied to a full state"
1733
        );
17345145×
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
17356047×
        for e in c.edits {
17366047×
            match e {
1737
                Edit::Insert {
17384421×
                    node,
17394421×
                    after,
17404421×
                    before,
17414421×
                    lines,
17424421×
                } => {
17434421×
                    let idx = counters.entry(node).or_default();
17444421×
                    let first = *idx;
17454421×
                    *idx += lines.len() as u32;
17464421×
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
17474421×
                        h,
17484421×
                        first,
17494421×
                        vertex(after.resolve(h)),
17504421×
                        vertex(before.resolve(h)),
17514421×
                        lines,
17524421×
                    );
17534421×
                }
17541518×
                Edit::Delete { node, atoms } => {
17551518×
                    let g = Arc::make_mut(self.files.entry(node).or_default());
17561857×
                    for r in atoms {
17571857×
                        g.delete(h, &r.resolve(h));
17581857×
                    }
1759
                }
1760108×
                Edit::Replace { node, old, new } => {
1761108×
                    self.replaces.entry(node).or_default().push((h, old, new));
1762108×
                }
1763
            }
1764
        }
176512228×
    }
1766
1767
    /// Transitive dependencies of `h`, excluding `h` itself.
17689153×
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
17699153×
        if let Some(c) = self.closure.lock().unwrap().sets.get(h) {
17707689×
            return c.clone();
17711464×
        }
17721464×
        let mut out = HashSet::new();
17731464×
        let mut stack: Vec<ChangeHash> = self
17741464×
            .changes
17751464×
            .get(h)
17761464×
            .map(|c| c.deps.clone())
17771464×
            .unwrap_or_default();
177816999×
        while let Some(d) = stack.pop() {
177915535×
            if out.insert(d) {
178011000×
                if let Some(c) = self.changes.get(&d) {
178111000×
                    stack.extend(c.deps.iter().copied());
178211000×
                }
17834535×
            }
1784
        }
17851464×
        let rc = Arc::new(out);
17861464×
        let mut memo = self.closure.lock().unwrap();
17871464×
        if memo.held + rc.len() > CLOSURE_MEMO_HASHES {
17880×
            memo.sets.clear();
17890×
            memo.held = 0;
17901464×
        }
17911464×
        memo.held += rc.len();
17921464×
        memo.sets.insert(*h, rc.clone());
17931464×
        rc
17949153×
    }
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.
1799405453×
    fn level(&self, h: &ChangeHash) -> u32 {
1800405453×
        let mut levels = self.levels.lock().unwrap();
1801405453×
        if let Some(l) = levels.get(h) {
1802403218×
            return *l;
18032235×
        }
18042235×
        let mut stack: Vec<(ChangeHash, bool)> = vec![(*h, false)];
18057494×
        while let Some((c, expanded)) = stack.pop() {
18065259×
            if levels.contains_key(&c) {
180741×
                continue;
18085218×
            }
18095218×
            let deps: &[ChangeHash] = self
18105218×
                .changes
18115218×
                .get(&c)
18125218×
                .map(|m| m.deps.as_slice())
18135218×
                .unwrap_or(&[]);
18145218×
            if expanded {
18152609×
                let l = deps
18162609×
                    .iter()
18173436×
                    .map(|d| levels.get(d).map_or(0, |l| l + 1))
18182609×
                    .max()
18192609×
                    .unwrap_or(0);
18202609×
                levels.insert(c, l);
1821
            } else {
18222609×
                stack.push((c, true));
18233436×
                for d in deps {
18243436×
                    if !levels.contains_key(d) {
1825415×
                        stack.push((*d, false));
18263021×
                    }
1827
                }
1828
            }
1829
        }
18302235×
        levels[h]
1831405453×
    }
1832
1833
    /// Changes that no other change depends on directly, sorted.
1834397×
    pub fn heads(&self) -> Vec<ChangeHash> {
1835397×
        let depended: HashSet<&ChangeHash> =
18363511×
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
1837397×
        let mut heads: Vec<ChangeHash> = self
1838397×
            .changes
1839397×
            .keys()
18403511×
            .filter(|h| !depended.contains(h))
1841397×
            .copied()
1842397×
            .collect();
1843397×
        heads.sort();
1844397×
        heads
1845397×
    }
1846
1847
    /// Maximal elements among `hashes` (those not in the closure of another),
1848
    /// sorted. One walk down from all of them at once: whatever the walk
1849
    /// reaches is below some other element. Linear in the changes reached,
1850
    /// where comparing every pair's closures was quadratic in the number
1851
    /// of heads, which a bookmark of independent changes has many of.
18528583×
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
18538583×
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
18548583×
        let mut below: HashSet<ChangeHash> = HashSet::new();
18558583×
        let mut stack: Vec<ChangeHash> = set
18568583×
            .iter()
185715330×
            .filter_map(|h| self.changes.get(h))
185813010×
            .flat_map(|c| c.deps.iter().copied())
18598583×
            .collect();
186021324×
        while let Some(d) = stack.pop() {
186112741×
            if below.insert(d) {
18626271×
                if let Some(c) = self.changes.get(&d) {
18636271×
                    stack.extend(c.deps.iter().copied());
18646271×
                }
18656470×
            }
1866
        }
186715330×
        set.into_iter().filter(|h| !below.contains(h)).collect()
18688583×
    }
1869
18700×
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
18710×
        self.graph(node)
18720×
            .map(|g| g.materialize(self))
18730×
            .unwrap_or_default()
18740×
    }
1875
1876
    /// Live lines of a text node in materialized order.
187720×
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
187820×
        let Some(g) = self.graph(node) else {
18792×
            return vec![];
1880
        };
188118×
        let m = g.materialize(self);
188218×
        m.live_atoms()
188318×
            .into_iter()
188444×
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
188518×
            .collect()
188620×
    }
1887
1888
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
1889842×
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
1890842×
        let mut live: Vec<ObjectRef> = self
1891842×
            .live_replaces(node)
1892842×
            .into_iter()
1893842×
            .map(|(_, n)| n)
1894842×
            .collect();
1895842×
        live.sort();
1896842×
        live.dedup();
1897842×
        live
1898842×
    }
1899
1900
    /// The replace records whose blob is live, with the change that set it
1901
    /// (spec §9.3). A record's blob is superseded by a later replacement of
1902
    /// that blob: one whose change depends on the record's change, as every
1903
    /// replacement depends on the change that made its old blob current
1904
    /// (§8.1). Two replacements that do not know each other both stay live
1905
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
1906
    /// A replacement without that dependency, from before the rule, is read
1907
    /// as before: it supersedes every record that did not come after it.
1908881×
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
1909881×
        let Some(rs) = self.replaces.get(node) else {
19100×
            return vec![];
1911
        };
1912881×
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
191311×
            rs.iter()
191445×
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && self.closure(s).contains(q))
191511×
        };
1916881×
        rs.iter()
19171020×
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
19181020×
            .filter(|(c, n)| {
19191297×
                !rs.iter().any(|(s, o, _)| {
19201297×
                    s != c
1921355×
                        && *o == Some(*n)
1922126×
                        && (self.closure(s).contains(c)
192311×
                            || (!knows_its_old(s, n) && !self.closure(c).contains(s)))
19241297×
                })
19251020×
            })
1926881×
            .collect()
1927881×
    }
1928
1929
    /// Short label for conflict markers: `changeid-prefix "message"`.
19301263×
    pub fn label(&self, h: &ChangeHash) -> String {
19311263×
        match self.changes.get(h) {
19321263×
            Some(c) => format!(
1933
                "{} \"{}\"",
19341263×
                c.change_id.short(8),
19351263×
                c.message.lines().next().unwrap_or("")
1936
            ),
19370×
            None => format!("#{}", h.short(12)),
1938
        }
19391263×
    }
1940
1941
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1942
    /// are not part of any conflict region in order, every live atom that is
1943
    /// part of a region, and every change that contributed to a region.
1944
    /// The changes that introduced the live blobs of an opaque node, for a
1945
    /// replace conflict (spec §9.3).
19462×
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
19472×
        let mut out: Vec<ChangeHash> = Vec::new();
19486×
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
19496×
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
19504×
                out.push(*h);
19514×
            }
1952
        }
19532×
        out.sort();
19542×
        out
19552×
    }
1956
195727×
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
195827×
        let mut out = ConflictRegions::default();
195927×
        let Some(g) = self.graph(node) else {
19600×
            return out;
1961
        };
196227×
        let m = g.materialize(self);
196327×
        let mut contributors = BTreeSet::new();
196463×
        for seg in &m.segments {
196563×
            match seg {
196636×
                crate::graph::Segment::Lines(atoms) => {
196736×
                    for a in atoms {
196836×
                        out.plain
196936×
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
197036×
                    }
1971
                }
197227×
                crate::graph::Segment::Conflict(sides) => {
197354×
                    for side in sides {
197456×
                        for a in side {
197556×
                            out.region_atoms.push(*a);
197656×
                            contributors.insert(a.0);
197756×
                        }
1978
                    }
1979
                }
19800×
                crate::graph::Segment::Zombie { deleted, inserted } => {
19810×
                    for a in deleted {
19820×
                        contributors.insert(a.0);
19830×
                        contributors.extend(g.deleters(a).copied());
19840×
                    }
19850×
                    for a in inserted {
19860×
                        out.region_atoms.push(*a);
19870×
                        contributors.insert(a.0);
19880×
                    }
1989
                }
1990
            }
1991
        }
199227×
        out.contributors = contributors.into_iter().collect();
199327×
        out
199427×
    }
1995
199624449×
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
199724449×
        let Some(g) = self.graph(node) else {
1998466×
            return (Vec::new(), Materialized::default());
1999
        };
200023983×
        let m = g.materialize(self);
200123983×
        let bytes = g.render(&m, &|h| self.label(h));
200223983×
        (bytes, m)
200324449×
    }
2004
2005
    /// Every file rendered, in parallel: files are independent, and
2006
    /// rendering them is most of a snapshot's cost in a large tree.
20072238×
    pub fn materialize(&self) -> Snapshot {
2008
        use rayon::prelude::*;
20092238×
        self.require_full("materializing a state");
20102238×
        let tree = self.tree.view();
20112238×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
20122238×
        let rendered: Vec<(String, FileState)> = entries
20132238×
            .par_iter()
201416643×
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
20152238×
            .collect();
20162238×
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
20172238×
        Snapshot {
20182238×
            tree,
20192238×
            files,
20202238×
            unrendered: BTreeSet::new(),
20212238×
        }
20222238×
    }
2023
2024
    /// Like [`State::materialize`], leaving the text files of nodes in
2025
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
2026
    /// file's graph must be loaded. For a caller that already knows those
2027
    /// files are unchanged and not conflicted.
202819×
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
202919×
        self.materialize_leaving(|_, e| skip.contains(&e.node))
203019×
    }
2031
2032
    /// As [`State::materialize_except`], rendering only the text files at
2033
    /// `render` (a few, where the caller knows the rest unchanged).
2034802×
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
20357816×
        self.materialize_leaving(|p, _| !render.contains(p))
2036802×
    }
2037
2038
    /// As [`State::materialize_except`], rendering only the text files of
2039
    /// the nodes in `render` (a change's edited files), without a set of
2040
    /// every other file to leave out.
2041230×
    pub fn materialize_nodes(&self, render: &HashSet<NodeId>) -> Snapshot {
2042621×
        self.materialize_leaving(|_, e| !render.contains(&e.node))
2043230×
    }
2044
20451051×
    fn materialize_leaving(
20461051×
        &self,
20471051×
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
20481051×
    ) -> Snapshot {
2049
        use rayon::prelude::*;
20501051×
        let tree = self.tree.view();
20511051×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
20521051×
        let rendered: Vec<(String, FileState, bool)> = entries
20531051×
            .par_iter()
20548800×
            .map(|(path, e)| {
20558800×
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
20564592×
                    let f = FileState {
20574592×
                        node: e.node,
20584592×
                        kind: e.kind,
20594592×
                        mode: e.mode,
20604592×
                        content: FileContent::Text {
20614592×
                            bytes: Vec::new(),
20624592×
                            materialized: Materialized::default(),
20634592×
                        },
20644592×
                    };
20654592×
                    (path.to_string(), f, true)
2066
                } else {
20674208×
                    (path.to_string(), self.file_state(e), false)
2068
                }
20698800×
            })
20701051×
            .collect();
2071
        // In the view's path order, so the maps are built without searching.
20721051×
        let unrendered: BTreeSet<String> = rendered
20731051×
            .iter()
20741051×
            .filter(|(_, _, skipped)| *skipped)
20754592×
            .map(|(p, _, _)| p.clone())
20761051×
            .collect();
20771051×
        let files: BTreeMap<String, FileState> =
20788800×
            rendered.into_iter().map(|(p, f, _)| (p, f)).collect();
20791051×
        Snapshot {
20801051×
            tree,
20811051×
            files,
20821051×
            unrendered,
20831051×
        }
20841051×
    }
2085
2086
    /// A snapshot of only `paths` (those `view` has), `view` being this
2087
    /// state's tree view: for a caller that works from what changed. The
2088
    /// graphs of those text files must be loaded.
208987×
    pub fn materialize_paths<'p>(
209087×
        &self,
209187×
        view: crate::tree::TreeView,
209287×
        paths: impl IntoIterator<Item = &'p str>,
209387×
    ) -> Snapshot {
209487×
        let files = paths
209587×
            .into_iter()
2096128×
            .filter_map(|p| Some((p.to_string(), self.file_state(view.entries.get(p)?))))
209787×
            .collect();
209887×
        Snapshot {
209987×
            tree: view,
210087×
            files,
210187×
            unrendered: BTreeSet::new(),
210287×
        }
210387×
    }
2104
2105
    /// The state of one tree entry: a directory, an opaque file's live
2106
    /// blobs, or a text file rendered from its graph (which must be built).
21070×
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
21080×
        self.file_state(e)
21090×
    }
2110
211120956×
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
2112
        {
211320956×
            let content = match e.kind {
21141478×
                NodeKind::Dir => FileContent::Dir,
2115100×
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
2116100×
                    blobs: self.live_blobs(&e.node),
2117100×
                },
2118541×
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
2119541×
                    blobs: self.live_blobs(&e.node),
2120541×
                },
2121
                NodeKind::File => {
212218837×
                    let (bytes, materialized) = self.render_file(&e.node);
212318837×
                    FileContent::Text {
212418837×
                        bytes,
212518837×
                        materialized,
212618837×
                    }
2127
                }
2128
            };
212920956×
            FileState {
213020956×
                node: e.node,
213120956×
                kind: e.kind,
213220956×
                mode: e.mode,
213320956×
                content,
213420956×
            }
2135
        }
213620956×
    }
2137
}
2138
2139
impl DepOracle for State {
2140
    /// Whether `a` depends on `b`, by a walk down from `a` that stops at
2141
    /// changes no higher than `b`: they cannot have `b` below them. Nothing
2142
    /// of the walk is kept, so asking about many pairs costs no more memory
2143
    /// than one walk (#25); a closure already memoised answers at once.
214468247×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
214568247×
        if a == b {
2146800×
            return true;
214767447×
        }
214867447×
        if let Some(c) = self.closure.lock().unwrap().sets.get(a) {
21490×
            return c.contains(b);
215067447×
        }
215167447×
        if !self.changes.contains_key(b) {
2152800×
            return false;
215366647×
        }
215466647×
        let lb = self.level(b);
215566647×
        if self.level(a) <= lb {
215636698×
            return false;
215729949×
        }
215829949×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
215929949×
        let mut stack: Vec<ChangeHash> = self
216029949×
            .changes
216129949×
            .get(a)
216229949×
            .map(|m| m.deps.clone())
216329949×
            .unwrap_or_default();
2164361853×
        while let Some(c) = stack.pop() {
2165342421×
            if c == *b {
216610517×
                return true;
2167331904×
            }
2168331904×
            if !seen.insert(c) || self.level(&c) <= lb {
2169223717×
                continue;
2170108187×
            }
2171108187×
            if let Some(m) = self.changes.get(&c) {
2172108187×
                stack.extend(m.deps.iter().copied());
2173108187×
            }
2174
        }
217519432×
        false
217668247×
    }
2177
}
2178
2179
#[cfg(test)]
2180
mod tests {
2181
    use super::*;
2182
    use crate::ids::ChangeId;
2183
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
2184
21852023×
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
21862023×
        let mut c = Change {
21872023×
            version: crate::objects::CHANGE_VERSION,
21882023×
            change_id: ChangeId::random(),
21892023×
            deps,
21902023×
            author: ObjectRef::ZERO,
21912023×
            hlc: Hlc {
21922023×
                wall_ms: 1,
21932023×
                logical: 0,
21942023×
            },
21952023×
            message: "m".into(),
21962023×
            tree_ops,
21972023×
            edits,
21982023×
            kind: ChangeKind::Normal,
21992023×
        };
22002023×
        c.normalize();
22012023×
        c
22022023×
    }
2203
2204
    #[test]
22051×
    fn build_edit_and_materialize() {
22061×
        let mut st = State::new();
22071×
        let f = NodeId::random();
22081×
        let c1 = change(
22091×
            vec![],
22101×
            vec![TreeOp::AddNode {
22111×
                node: f,
22121×
                kind: NodeKind::File,
22131×
                mode: Mode::TEXT,
22141×
                parent: NodeId::ROOT,
22151×
                name: "a.txt".into(),
22161×
            }],
22171×
            vec![Edit::Insert {
22181×
                node: f,
22191×
                after: AtomRef::Start,
22201×
                before: AtomRef::End,
22211×
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
22221×
            }],
2223
        );
22241×
        let h1 = st.add(c1).unwrap();
2225
        // Depends on h1: append a line and delete "one".
22261×
        let c2 = change(
22271×
            vec![h1],
22281×
            vec![],
22291×
            vec![
22301×
                Edit::Delete {
22311×
                    node: f,
22321×
                    atoms: vec![AtomRange {
22331×
                        change: h1,
22341×
                        from: 0,
22351×
                        to: 1,
22361×
                    }],
22371×
                },
22381×
                Edit::Insert {
22391×
                    node: f,
22401×
                    after: AtomRef::Atom {
22411×
                        change: h1,
22421×
                        index: 1,
22431×
                    },
22441×
                    before: AtomRef::End,
22451×
                    lines: vec![b"three\n".to_vec()].into(),
22461×
                },
2247
            ],
2248
        );
22491×
        let h2 = st.add(c2).unwrap();
22501×
        assert_eq!(st.heads(), vec![h2]);
22511×
        assert!(st.depends_on(&h2, &h1));
22521×
        assert!(!st.depends_on(&h1, &h2));
22531×
        let snap = st.materialize();
22541×
        assert!(!snap.is_conflicted());
22551×
        let a = &snap.files["a.txt"];
22561×
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
22571×
        assert_eq!(st.live_lines(&f).len(), 2);
22581×
    }
2259
2260
    #[test]
22611×
    fn missing_dependency_is_rejected() {
22621×
        let mut st = State::new();
22631×
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
22641×
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
22651×
    }
2266
2267
    #[test]
22681×
    fn self_references_and_multi_insert_indexing() {
22691×
        let mut st = State::new();
22701×
        let f = NodeId::random();
22711×
        let me = OpRef {
22721×
            change: ObjectRef::ZERO,
22731×
            index: 0,
22741×
        };
22751×
        let c1 = change(
22761×
            vec![],
22771×
            vec![
22781×
                TreeOp::AddNode {
22791×
                    node: f,
22801×
                    kind: NodeKind::File,
22811×
                    mode: Mode::TEXT,
22821×
                    parent: NodeId::ROOT,
22831×
                    name: "x".into(),
22841×
                },
22851×
                TreeOp::SetMode {
22861×
                    node: f,
22871×
                    old: me,
22881×
                    mode: Mode {
22891×
                        exec: true,
22901×
                        opaque: false,
22911×
                    },
22921×
                },
2293
            ],
22941×
            vec![
22951×
                Edit::Insert {
22961×
                    node: f,
22971×
                    after: AtomRef::Start,
22981×
                    before: AtomRef::End,
22991×
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
23001×
                },
2301
                // Insert between the two lines just inserted, using self references.
23021×
                Edit::Insert {
23031×
                    node: f,
23041×
                    after: AtomRef::Atom {
23051×
                        change: ObjectRef::ZERO,
23061×
                        index: 0,
23071×
                    },
23081×
                    before: AtomRef::Atom {
23091×
                        change: ObjectRef::ZERO,
23101×
                        index: 1,
23111×
                    },
23121×
                    lines: vec![b"b\n".to_vec()].into(),
23131×
                },
2314
            ],
2315
        );
23161×
        st.add(c1).unwrap();
23171×
        let snap = st.materialize();
23181×
        let x = &snap.files["x"];
23191×
        assert_eq!(
2320
            x.mode,
2321
            Mode {
2322
                exec: true,
2323
                opaque: false
2324
            }
2325
        );
23261×
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
23271×
    }
2328
2329
    #[test]
23301×
    fn opaque_replace_and_conflict() {
23311×
        let mut st = State::new();
23321×
        let f = NodeId::random();
23331×
        let b1 = ObjectRef([1; 32]);
23341×
        let b2 = ObjectRef([2; 32]);
23351×
        let b3 = ObjectRef([3; 32]);
23361×
        let h1 = st
23371×
            .add(change(
23381×
                vec![],
23391×
                vec![TreeOp::AddNode {
23401×
                    node: f,
23411×
                    kind: NodeKind::File,
23421×
                    mode: Mode::OPAQUE,
23431×
                    parent: NodeId::ROOT,
23441×
                    name: "img".into(),
23451×
                }],
23461×
                vec![Edit::Replace {
23471×
                    node: f,
23481×
                    old: None,
23491×
                    new: Some(b1),
23501×
                }],
2351
            ))
23521×
            .unwrap();
23531×
        assert_eq!(st.live_blobs(&f), vec![b1]);
23541×
        st.add(change(
23551×
            vec![h1],
23561×
            vec![],
23571×
            vec![Edit::Replace {
23581×
                node: f,
23591×
                old: Some(b1),
23601×
                new: Some(b2),
23611×
            }],
2362
        ))
23631×
        .unwrap();
23641×
        st.add(change(
23651×
            vec![h1],
23661×
            vec![],
23671×
            vec![Edit::Replace {
23681×
                node: f,
23691×
                old: Some(b1),
23701×
                new: Some(b3),
23711×
            }],
2372
        ))
23731×
        .unwrap();
23741×
        let snap = st.materialize();
23751×
        assert!(snap.is_conflicted());
23761×
        assert!(
23771×
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2378
        );
23791×
    }
2380
2381
    #[test]
23821×
    fn checkpoint_payload_round_trip_and_replay() {
23831×
        let mut st = State::new();
23841×
        let f = NodeId::random();
23851×
        let h1 = st
23861×
            .add(change(
23871×
                vec![],
23881×
                vec![TreeOp::AddNode {
23891×
                    node: f,
23901×
                    kind: NodeKind::File,
23911×
                    mode: Mode::TEXT,
23921×
                    parent: NodeId::ROOT,
23931×
                    name: "a".into(),
23941×
                }],
23951×
                vec![Edit::Insert {
23961×
                    node: f,
23971×
                    after: AtomRef::Start,
23981×
                    before: AtomRef::End,
23991×
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
24001×
                }],
2401
            ))
24021×
            .unwrap();
24031×
        let h2 = st
24041×
            .add(change(
24051×
                vec![h1],
24061×
                vec![],
24071×
                vec![Edit::Delete {
24081×
                    node: f,
24091×
                    atoms: vec![AtomRange {
24101×
                        change: h1,
24111×
                        from: 0,
24121×
                        to: 1,
24131×
                    }],
24141×
                }],
2415
            ))
24161×
            .unwrap();
24171×
        let payload = st.checkpoint_payload();
24181×
        let back = State::from_checkpoint_payload(&payload).unwrap();
24191×
        assert_eq!(back.len(), 2);
24201×
        assert_eq!(back.heads(), vec![h2]);
24211×
        assert_eq!(back.get(&h1).unwrap().message, "m");
24221×
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2423
        // Replaying a further change onto the restored state equals a full build.
24241×
        let c3 = change(
24251×
            vec![h2],
24261×
            vec![],
24271×
            vec![Edit::Insert {
24281×
                node: f,
24291×
                after: AtomRef::Atom {
24301×
                    change: h1,
24311×
                    index: 1,
24321×
                },
24331×
                before: AtomRef::End,
24341×
                lines: vec![b"3\n".to_vec()].into(),
24351×
            }],
2436
        );
24371×
        let mut full = st.clone();
24381×
        full.add(c3.clone()).unwrap();
24391×
        let mut restored = back;
24401×
        restored.add(c3).unwrap();
24411×
        let (a, b) = (full.materialize(), restored.materialize());
24421×
        assert_eq!(
24431×
            a.files.keys().collect::<Vec<_>>(),
24441×
            b.files.keys().collect::<Vec<_>>()
2445
        );
24461×
        assert_eq!(a.files["a"].content, b.files["a"].content);
24471×
        assert!(
24481×
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2449
        );
24501×
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
24511×
    }
2452
2453
    /// History-only states (O10f): the same state as a full load once its
2454
    /// graphs are built, by replay and from a version 2 checkpoint with
2455
    /// later changes; unloaded graphs are never read as empty.
2456
    #[test]
24571×
    fn graph_keys_change_exactly_when_a_graph_does() {
24581×
        let (f, g) = (NodeId::random(), NodeId::random());
24591×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
24602×
            node,
24612×
            kind: NodeKind::File,
2462
            mode: Mode::TEXT,
2463
            parent: NodeId::ROOT,
24642×
            name: name.into(),
24652×
        };
24661×
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
24674×
            node,
24684×
            after: AtomRef::Start,
24694×
            before: AtomRef::End,
24704×
            lines: vec![line.to_vec()].into(),
24714×
        };
24721×
        let c1 = change(
24731×
            vec![],
24741×
            vec![add(f, "f"), add(g, "g")],
24751×
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2476
        );
24771×
        let h1 = c1.hash();
24781×
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
24791×
        let h2 = c2.hash();
24801×
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
24816×
        let load = |cs: &[&Change]| {
24826×
            let mut st = State::new_history_only();
248310×
            for c in cs {
248410×
                st.add((*c).clone()).unwrap();
248510×
            }
24866×
            st
24876×
        };
24881×
        let s1 = load(&[&c1]);
24891×
        let s2 = load(&[&c1, &c2]);
24901×
        let s3 = load(&[&c1, &c2, &c3]);
249118×
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
24921×
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
24931×
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
24941×
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
24951×
        assert_ne!(key(&s2, &f), key(&s3, &f));
24961×
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
24971×
        let mut built = load(&[&c1]);
24981×
        built
24991×
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
25001×
            .unwrap();
25011×
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
25021×
        let mut full = State::new();
25031×
        full.add(c1.clone()).unwrap();
25041×
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2505
2506
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2507
        // or inline values: stable across loads, changed by later edits.
25081×
        let graphs = full.checkpoint_file_graphs();
25091×
        let index = full.checkpoint_index(&graphs, |enc| {
25100×
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
25110×
        });
25128×
        let cp = |extra: &[&Change]| {
25138×
            let mut st = State::from_checkpoint_history(&index).unwrap();
25148×
            for c in extra {
25155×
                st.add((*c).clone()).unwrap();
25165×
            }
25178×
            st
25188×
        };
25191×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
25201×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
25211×
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
25221×
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2523
2524
        // Partial rendering: skipped files are listed and empty, the others
2525
        // render as in a full state.
25261×
        let mut part = load(&[&c1, &c2]);
25271×
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
25281×
            .unwrap();
25291×
        let snap = part.materialize_except(&[f].into_iter().collect());
25301×
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
25311×
        let mut whole = State::new();
25321×
        whole.add(c1.clone()).unwrap();
25331×
        whole.add(c2.clone()).unwrap();
25341×
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
25351×
        assert!(
25361×
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2537
        );
25381×
    }
2539
2540
    #[test]
25411×
    fn history_only_states_build_the_same_graphs_on_demand() {
25421×
        let small = NodeId::random();
25431×
        let big = NodeId::random();
25441×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
25452×
            node,
25462×
            kind: NodeKind::File,
2547
            mode: Mode::TEXT,
2548
            parent: NodeId::ROOT,
25492×
            name: name.into(),
25502×
        };
25511×
        let lines: crate::lines::Lines = (0..300)
2552300×
            .map(|i| format!("line {i}\n").into_bytes())
25531×
            .collect();
25541×
        let c1 = change(
25551×
            vec![],
25561×
            vec![add(small, "small"), add(big, "big")],
25571×
            vec![
25581×
                Edit::Insert {
25591×
                    node: small,
25601×
                    after: AtomRef::Start,
25611×
                    before: AtomRef::End,
25621×
                    lines: vec![b"x\n".to_vec()].into(),
25631×
                },
25641×
                Edit::Insert {
25651×
                    node: big,
25661×
                    after: AtomRef::Start,
25671×
                    before: AtomRef::End,
25681×
                    lines,
25691×
                },
2570
            ],
2571
        );
25721×
        let h1 = c1.hash();
25731×
        let c2 = change(
25741×
            vec![h1],
25751×
            vec![],
25761×
            vec![
25771×
                Edit::Delete {
25781×
                    node: big,
25791×
                    atoms: vec![AtomRange {
25801×
                        change: h1,
25811×
                        from: 2,
25821×
                        to: 9,
25831×
                    }],
25841×
                },
25851×
                Edit::Insert {
25861×
                    node: big,
25871×
                    after: AtomRef::Atom {
25881×
                        change: h1,
25891×
                        index: 20,
25901×
                    },
25911×
                    before: AtomRef::Atom {
25921×
                        change: h1,
25931×
                        index: 21,
25941×
                    },
25951×
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
25961×
                },
25971×
                Edit::Insert {
25981×
                    node: small,
25991×
                    after: AtomRef::Atom {
26001×
                        change: h1,
26011×
                        index: 0,
26021×
                    },
26031×
                    before: AtomRef::End,
26041×
                    lines: vec![b"y\n".to_vec()].into(),
26051×
                },
2606
            ],
2607
        );
26081×
        let h2 = c2.hash();
26091×
        let c3 = change(
26101×
            vec![h2],
26111×
            vec![],
26121×
            vec![Edit::Delete {
26131×
                node: small,
26141×
                atoms: vec![AtomRange {
26151×
                    change: h1,
26161×
                    from: 0,
26171×
                    to: 1,
26181×
                }],
26191×
            }],
2620
        );
2621
26221×
        let mut full = State::new();
26233×
        for c in [&c1, &c2, &c3] {
26243×
            full.add(c.clone()).unwrap();
26253×
        }
2626
        // By replay: nothing built until asked, then exactly the full graphs.
26271×
        let mut hist = State::new_history_only();
26283×
        for c in [&c1, &c2, &c3] {
26293×
            hist.add(c.clone()).unwrap();
26303×
        }
26311×
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
26321×
        assert_eq!(hist.len(), 3);
26331×
        hist.load_graphs(
26341×
            &[big],
26350×
            |_| unreachable!("no checkpoint"),
26360×
            |_| unreachable!(),
2637
        )
26381×
        .unwrap();
26391×
        assert_eq!(
26401×
            hist.render_file(&big).0,
26411×
            full.render_file(&big).0,
2642
            "one file on its own"
2643
        );
26441×
        assert!(!hist.is_full());
26451×
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
26461×
            .unwrap();
26471×
        assert!(hist.is_full());
26481×
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2649
2650
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
26511×
        let mut base = State::new();
26521×
        base.add(c1.clone()).unwrap();
26531×
        base.add(c2.clone()).unwrap();
26541×
        let graphs = base.checkpoint_file_graphs();
26551×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
26561×
        let index = base.checkpoint_index(&graphs, |enc| {
26571×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
26581×
            blobs.insert(r, enc.to_vec());
26591×
            r
26601×
        });
26611×
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
26621×
        from_cp.add(c3.clone()).unwrap();
26631×
        assert!(!from_cp.is_full());
26641×
        let mut fetched = 0;
26651×
        from_cp
26661×
            .load_graphs(
26671×
                &[small, big],
26681×
                |refs| {
26691×
                    fetched += refs.len();
26701×
                    refs.iter()
26711×
                        .map(|r| {
26721×
                            blobs
26731×
                                .get(r)
26741×
                                .cloned()
26751×
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
26761×
                        })
26771×
                        .collect()
26781×
                },
26790×
                |_| unreachable!(),
2680
            )
26811×
            .unwrap();
26821×
        assert_eq!(
2683
            fetched, 1,
2684
            "the large graph's blob, in one batch; the small one was inline"
2685
        );
26861×
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
26871×
    }
2688
2689
    #[test]
2690
    #[should_panic(expected = "was not loaded")]
26911×
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
26921×
        let f = NodeId::random();
26931×
        let mut st = State::new_history_only();
26941×
        st.add(change(
26951×
            vec![],
26961×
            vec![TreeOp::AddNode {
26971×
                node: f,
26981×
                kind: NodeKind::File,
26991×
                mode: Mode::TEXT,
27001×
                parent: NodeId::ROOT,
27011×
                name: "a".into(),
27021×
            }],
27031×
            vec![Edit::Insert {
27041×
                node: f,
27051×
                after: AtomRef::Start,
27061×
                before: AtomRef::End,
27071×
                lines: vec![b"a\n".to_vec()].into(),
27081×
            }],
2709
        ))
27101×
        .unwrap();
27111×
        st.render_file(&f);
27121×
    }
2713
2714
    #[test]
2715
    #[should_panic(expected = "needs every file graph")]
27161×
    fn materializing_a_history_only_state_is_refused() {
27171×
        let f = NodeId::random();
27181×
        let mut st = State::new_history_only();
27191×
        st.add(change(
27201×
            vec![],
27211×
            vec![TreeOp::AddNode {
27221×
                node: f,
27231×
                kind: NodeKind::File,
27241×
                mode: Mode::TEXT,
27251×
                parent: NodeId::ROOT,
27261×
                name: "a".into(),
27271×
            }],
27281×
            vec![Edit::Insert {
27291×
                node: f,
27301×
                after: AtomRef::Start,
27311×
                before: AtomRef::End,
27321×
                lines: vec![b"a\n".to_vec()].into(),
27331×
            }],
2734
        ))
27351×
        .unwrap();
27361×
        st.materialize();
27371×
    }
2738
2739
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
2740
    /// blob; the state read back is the same as from version 1.
2741
    #[test]
27421×
    fn checkpoint_index_round_trip_matches_version_1() {
27431×
        let mut st = State::new();
27441×
        let small = NodeId::random();
27451×
        let big = NodeId::random();
27461×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
27472×
            node,
27482×
            kind: NodeKind::File,
2749
            mode: Mode::TEXT,
2750
            parent: NodeId::ROOT,
27512×
            name: name.into(),
27522×
        };
27531×
        let big_lines: crate::lines::Lines = (0..400)
2754400×
            .map(|i| format!("line {i} of a long file\n").into_bytes())
27551×
            .collect();
27561×
        let h1 = st
27571×
            .add(change(
27581×
                vec![],
27591×
                vec![add(small, "small"), add(big, "big")],
27601×
                vec![
27611×
                    Edit::Insert {
27621×
                        node: small,
27631×
                        after: AtomRef::Start,
27641×
                        before: AtomRef::End,
27651×
                        lines: vec![b"x\n".to_vec()].into(),
27661×
                    },
27671×
                    Edit::Insert {
27681×
                        node: big,
27691×
                        after: AtomRef::Start,
27701×
                        before: AtomRef::End,
27711×
                        lines: big_lines,
27721×
                    },
2773
                ],
2774
            ))
27751×
            .unwrap();
27761×
        st.add(change(
27771×
            vec![h1],
27781×
            vec![],
27791×
            vec![Edit::Delete {
27801×
                node: big,
27811×
                atoms: vec![AtomRange {
27821×
                    change: h1,
27831×
                    from: 3,
27841×
                    to: 7,
27851×
                }],
27861×
            }],
2787
        ))
27881×
        .unwrap();
2789
27901×
        let graphs = st.checkpoint_file_graphs();
27911×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
27921×
        let index = st.checkpoint_index(&graphs, |enc| {
27931×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
27941×
            blobs.insert(r, enc.to_vec());
27951×
            r
27961×
        });
27971×
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
27981×
        assert_eq!(
27991×
            State::checkpoint_graph_refs(&index).unwrap(),
28001×
            blobs.keys().copied().collect::<Vec<_>>()
2801
        );
28021×
        assert!(
28031×
            State::checkpoint_graph_refs(&st.checkpoint_payload())
28041×
                .unwrap()
28051×
                .is_empty(),
2806
            "version 1 names none"
2807
        );
28081×
        assert!(index.len() < st.checkpoint_payload().len());
2809
28101×
        let back = State::from_checkpoint(&index, |refs| {
28111×
            refs.iter()
28121×
                .map(|r| {
28131×
                    blobs
28141×
                        .get(r)
28151×
                        .cloned()
28161×
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
28171×
                })
28181×
                .collect()
28191×
        })
28201×
        .unwrap();
28211×
        assert_eq!(
28221×
            back.checkpoint_payload(),
28231×
            st.checkpoint_payload(),
2824
            "the same state as version 1"
2825
        );
28261×
        assert_eq!(
28271×
            back.materialize().files["big"].content,
28281×
            st.materialize().files["big"].content
2829
        );
2830
        // Deterministic: the same state gives the same index.
28311×
        assert_eq!(
28321×
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
28331×
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
28341×
            }),
2835
            index
2836
        );
2837
        // A missing graph blob is an error, not an empty file.
28381×
        assert!(
28391×
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
2840
        );
28411×
        assert!(
28421×
            State::from_checkpoint_payload(&index).is_err(),
2843
            "version 2 needs its blobs"
2844
        );
2845
        // Version 1 payloads still read, and unknown versions do not.
28461×
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
28471×
        let mut v3 = cbor::decode(&index).unwrap();
28481×
        if let Value::Map(m) = &mut v3 {
28491×
            m.insert(0, Value::Uint(3));
28501×
        }
28511×
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
28521×
    }
2853
2854
    #[test]
28551×
    fn maximal_elements() {
28561×
        let mut st = State::new();
28571×
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
28581×
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
28591×
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
28601×
        let mut m = st.maximal(&[h1, h2, h3]);
28611×
        m.sort();
28621×
        let mut want = vec![h2, h3];
28631×
        want.sort();
28641×
        assert_eq!(m, want);
28651×
        assert_eq!(st.heads(), want);
28661×
    }
2867
2868
    /// The bounded walk of `depends_on` agrees with the closure on random
2869
    /// graphs, and the memo stays within its bound.
2870
    #[test]
28711×
    fn depends_on_matches_the_closure() {
2872
        use rand::{Rng, SeedableRng};
28731×
        let mut rng = rand::rngs::StdRng::seed_from_u64(11);
28741×
        for _ in 0..10 {
287510×
            let mut st = State::new();
287610×
            let mut all: Vec<ChangeHash> = Vec::new();
287710×
            for _ in 0..80 {
2878800×
                let deps: Vec<ChangeHash> =
287931600×
                    all.iter().copied().filter(|_| rng.gen_bool(0.06)).collect();
2880800×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2881
            }
288210×
            let unknown = ObjectRef([0xee; 32]);
2883800×
            for a in &all {
2884800×
                let want = st.closure(a).clone();
2885800×
                st.closure.lock().unwrap().sets.clear();
2886800×
                st.closure.lock().unwrap().held = 0;
288764800×
                for b in all.iter().chain([&unknown]) {
288864800×
                    assert_eq!(
288964800×
                        st.depends_on(a, b),
289064800×
                        a == b || want.contains(b),
2891
                        "{a:?} on {b:?}"
2892
                    );
2893
                }
2894
            }
289510×
            assert!(st.closure.lock().unwrap().held <= CLOSURE_MEMO_HASHES);
2896
        }
28971×
    }
2898
2899
    /// The one-walk `maximal` agrees with the definition (not in the
2900
    /// closure of another element) on random graphs, with repeated and
2901
    /// unknown hashes among the input.
2902
    #[test]
29031×
    fn maximal_matches_its_definition() {
2904
        use rand::{Rng, SeedableRng};
29051×
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
29061×
        for _ in 0..20 {
290720×
            let mut st = State::new();
290820×
            let mut all: Vec<ChangeHash> = Vec::new();
290920×
            for _ in 0..60 {
29101200×
                let deps: Vec<ChangeHash> =
291135400×
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
29121200×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2913
            }
291420×
            let mut pick: Vec<ChangeHash> =
29151200×
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
291620×
            pick.extend(pick.clone().into_iter().take(3));
291720×
            pick.push(ObjectRef([0xee; 32]));
291820×
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
291920×
            let want: Vec<ChangeHash> = set
292020×
                .iter()
29218361×
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
292220×
                .copied()
292320×
                .collect();
292420×
            assert_eq!(st.maximal(&pick), want);
292520×
            assert_eq!(st.maximal(&all), st.heads());
2926
        }
29271×
    }
2928
}