OXYGENHUB

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

2058 of 2224 lines run, 432 of 627 functions · run #263 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`]).
451444×
    pub(crate) fn write_flat(&self, w: &mut crate::flat::Writer) {
461444×
        w.fixed(&self.change_id.0);
471444×
        w.count(self.deps.len());
481444×
        for d in &self.deps {
49988×
            w.object(d);
50988×
        }
511444×
        w.object(&self.author);
521444×
        w.u64(self.hlc.wall_ms);
531444×
        w.u32(self.hlc.logical);
541444×
        w.bytes(self.message.as_bytes());
551444×
        w.u8(self.kind.tag() as u8);
561444×
    }
57
581536×
    pub(crate) fn read_flat(r: &mut crate::flat::Reader) -> Result<ChangeMeta, ObjectError> {
591536×
        let change_id = crate::ids::ChangeId(r.fixed::<16>()?);
601536×
        let mut deps = Vec::new();
611536×
        for _ in 0..r.count()? {
62732×
            deps.push(r.object()?);
63
        }
64
        Ok(ChangeMeta {
651536×
            change_id,
661536×
            deps,
671536×
            author: r.object()?,
68
            hlc: Hlc {
691536×
                wall_ms: r.u64()?,
701536×
                logical: r.u32()?,
71
            },
721536×
            message: r.text()?,
731536×
            kind: ChangeKind::from_tag(r.u8()? as u64)?,
74
        })
751536×
    }
76
7714768×
    pub fn of(c: &Change) -> ChangeMeta {
7814768×
        ChangeMeta {
7914768×
            change_id: c.change_id,
8014768×
            deps: c.deps.clone(),
8114768×
            author: c.author,
8214768×
            hlc: c.hlc,
8314768×
            message: c.message.clone(),
8414768×
            kind: c.kind,
8514768×
        }
8614768×
    }
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: crate::fasthash::FastMap<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 {
15216682×
    fn len(&self) -> u64 {
15316682×
        match self {
1544524×
            Histories::Bytes(b) => b.len() as u64,
15512158×
            Histories::File(_, _, len) => *len,
156
        }
15716682×
    }
158
15921830×
    fn read(&self, at: u64, len: usize) -> std::io::Result<Vec<u8>> {
16021830×
        match self {
1614524×
            Histories::Bytes(b) => Ok(b[at as usize..at as usize + len].to_vec()),
16217306×
            Histories::File(f, start, _) => {
16317306×
                let mut buf = vec![0u8; len];
16417306×
                read_exact_at(f, &mut buf, start + at)?;
16517306×
                Ok(buf)
166
            }
167
        }
16821830×
    }
169
}
170
171
#[cfg(unix)]
17217306×
fn read_exact_at(f: &std::fs::File, buf: &mut [u8], at: u64) -> std::io::Result<()> {
17317306×
    std::os::unix::fs::FileExt::read_exact_at(f, buf, at)
17417306×
}
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.
20121830×
    fn bytes(&self) -> Result<Vec<u8>, ObjectError> {
20221830×
        let damaged = |why: String| ObjectError::DamagedIndex(why);
20321830×
        let b = self
20421830×
            .from
20521830×
            .read(self.at, self.len)
20621830×
            .map_err(|e| damaged(format!("a file's history cannot be read: {e}")))?;
20721830×
        if *blake3::hash(&b).as_bytes() != self.sum {
2085×
            return Err(damaged("a file's history does not match its hash".into()));
20921825×
        }
21021825×
        Ok(b)
21121830×
    }
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.
243101662×
    fn body(&self) -> Result<&DeferredBody, ObjectError> {
244101662×
        self.body
245101662×
            .get_or_init(|| {
24637290×
                let mut b = match &self.raw {
247
                    // Matching its hash, it is what `write_index` wrote: it
248
                    // decodes.
2495468×
                    Some(raw) => raw
2505468×
                        .bytes()
2515468×
                        .and_then(|b| State::read_deferred_body(&b))
2525468×
                        .map_err(|e| e.to_string())?,
25331822×
                    None => DeferredBody::default(),
254
                };
25537289×
                b.edits.extend(self.more.iter().cloned());
25637289×
                b.texts.extend(self.more_texts.iter().cloned());
25737289×
                Ok(b)
25837290×
            })
259101662×
            .as_ref()
260101662×
            .map_err(|e| ObjectError::DamagedIndex(e.clone()))
261101662×
    }
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.
26534931×
    fn add(&mut self, h: ChangeHash, edits: Vec<Edit>, texts: Vec<TextRef>) {
26634931×
        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;
27134929×
        }
272
        // No encoding to read, or decoded already: this cannot fail.
27334929×
        let b = self.body_mut().expect("a history in memory");
27434929×
        b.edits.push((h, edits));
27534929×
        b.texts.extend(texts);
27634931×
    }
277
27834929×
    fn body_mut(&mut self) -> Result<&mut DeferredBody, ObjectError> {
27934929×
        self.body()?;
28034929×
        self.raw = None;
28134929×
        self.more.clear();
28234929×
        self.more_texts.clear();
28334929×
        Ok(self
28434929×
            .body
28534929×
            .get_mut()
28634929×
            .and_then(|b| b.as_mut().ok())
28734929×
            .expect("decoded above"))
28834929×
    }
289
29022583×
    fn into_body(mut self) -> Result<DeferredBody, ObjectError> {
29122583×
        self.body()?;
29222582×
        Ok(self
29322582×
            .body
29422582×
            .take()
29522582×
            .and_then(|b| b.ok())
29622582×
            .expect("decoded above"))
29722583×
    }
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).
317847×
    pub fn write_index(&self) -> Option<Vec<u8>> {
318
        use crate::flat::Writer;
319847×
        let deferred = self.deferred.as_ref()?;
320847×
        if !self.files.is_empty() {
3210×
            return None;
322847×
        }
323
        // The changes first, as a block a reader can take on its own (see
324
        // [`State::read_index_changes`]).
325847×
        let mut w = Writer::default();
326847×
        w.fixed(Self::INDEX_MAGIC);
327847×
        let mut changes: Vec<(&ChangeHash, &Arc<ChangeMeta>)> = self.changes.iter().collect();
328847×
        changes.sort_by_key(|(h, _)| **h);
329847×
        w.count(changes.len());
330847×
        for (h, m) in changes {
331238×
            w.object(h);
332238×
            m.write_flat(&mut w);
333238×
        }
334847×
        let changes_block = std::mem::take(&mut w);
335847×
        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.
338847×
        let mut tw = Writer::default();
339847×
        self.tree.write_flat(&mut tw);
340847×
        w.bytes(&tw.0);
341847×
        let mut replaces: Vec<(&NodeId, &Vec<ReplaceRecord>)> = self.replaces.iter().collect();
342847×
        replaces.sort_by_key(|(n, _)| **n);
343847×
        w.count(replaces.len());
344847×
        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
        }
356847×
        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).
359847×
        let mut table = Writer::default();
360847×
        let mut histories: Vec<u8> = Vec::new();
361847×
        let mut nodes: Vec<(&NodeId, &Arc<Deferred>)> = deferred.iter().collect();
362847×
        nodes.sort_by_key(|(n, _)| **n);
363847×
        table.count(nodes.len());
36432700×
        for (n, d) in nodes {
36532700×
            let key = match d.key.get() {
36616362×
                Some(k) => *k,
367
                None => {
36816338×
                    let mut h = blake3::Hasher::new();
36916338×
                    h.update(b"oxy graph key 1\0");
37016338×
                    h.update(&n.0);
37116338×
                    let k = d.graph_key(h).ok()?;
37216338×
                    let _ = d.key.set(k);
37316338×
                    k
374
                }
375
            };
376
            // Unchanged since read: its bytes as they are, checked.
37732700×
            let bytes = match &d.raw {
37816362×
                Some(raw) if d.more.is_empty() => raw.bytes().ok()?,
37916338×
                _ => Self::write_deferred_body(d.body().ok()?)?,
380
            };
38132696×
            table.fixed(&n.0);
38232696×
            table.fixed(&key);
38332696×
            table.u64(histories.len() as u64);
38432696×
            table.u32(u32::try_from(bytes.len()).ok()?);
38532696×
            table.fixed(blake3::hash(&bytes).as_bytes());
38632696×
            histories.extend_from_slice(&bytes);
387
        }
388843×
        front.bytes(&table.0);
389843×
        let mut out = Writer::default();
390843×
        out.u64(front.0.len() as u64);
391843×
        out.fixed(&front.0);
392843×
        out.fixed(&histories);
393843×
        Some(out.0)
394847×
    }
395
396
    /// One file's history as an index encodes it; `None` when it holds
397
    /// text in memory, which an index does not.
39816338×
    fn write_deferred_body(d: &DeferredBody) -> Option<Vec<u8>> {
399
        use crate::flat::Writer;
40032858×
        let atom = |w: &mut Writer, a: &AtomRef| match a {
40116335×
            AtomRef::Start => w.u8(0),
40216429×
            AtomRef::End => w.u8(1),
40394×
            AtomRef::Atom { change, index } => {
40494×
                w.u8(2);
40594×
                w.object(change);
40694×
                w.u32(*index);
40794×
            }
40832858×
        };
40916338×
        let mut w = Writer::default();
4103×
        match &d.base {
41116335×
            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.
42416338×
        let mut texts = d.texts.iter();
42516338×
        let mut per_change: Vec<(&ChangeHash, &Vec<Edit>, Vec<&TextRef>)> = Vec::new();
42616429×
        for (c, edits) in &d.edits {
42716429×
            let n = edits
42816429×
                .iter()
42916429×
                .filter(|e| matches!(e, Edit::Insert { lines, .. } if lines.is_empty()))
43016429×
                .count();
43116429×
            per_change.push((c, edits, texts.by_ref().take(n).collect()));
432
        }
43316338×
        per_change.sort_by_key(|(c, _, _)| **c);
43416338×
        w.count(per_change.len());
43516429×
        for (c, edits, _) in &per_change {
43616429×
            w.object(c);
43716429×
            w.count(edits.len());
43816429×
            for e in edits.iter() {
43916429×
                match e {
440
                    Edit::Insert {
44116429×
                        node,
44216429×
                        after,
44316429×
                        before,
44416429×
                        lines,
445
                    } => {
44616429×
                        if !lines.is_empty() {
4470×
                            return None;
44816429×
                        }
44916429×
                        w.u8(0);
45016429×
                        w.fixed(&node.0);
45116429×
                        atom(&mut w, after);
45216429×
                        atom(&mut w, before);
453
                    }
4540×
                    Edit::Delete { node, atoms } => {
4550×
                        w.u8(1);
4560×
                        w.fixed(&node.0);
4570×
                        w.count(atoms.len());
4580×
                        for r in atoms {
4590×
                            w.object(&r.change);
4600×
                            w.u32(r.from);
4610×
                            w.u32(r.to);
4620×
                        }
463
                    }
4640×
                    Edit::Replace { .. } => return None,
465
                }
466
            }
467
        }
46816338×
        let texts: Vec<&TextRef> = per_change
46916338×
            .iter()
47016429×
            .flat_map(|(_, _, t)| t.iter().copied())
47116338×
            .collect();
47216338×
        w.count(texts.len());
47316429×
        for t in texts {
47416429×
            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
                }
48516429×
                TextRef::Inline { change, start, end } => {
48616429×
                    w.u8(1);
48716429×
                    w.object(change);
48816429×
                    w.u32(*start);
48916429×
                    w.u32(*end);
49016429×
                }
491
            }
492
        }
49316338×
        Some(w.0)
49416338×
    }
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).
5091742×
    pub fn read_index_front(bytes: &[u8], histories: Histories) -> Result<State, ObjectError> {
510
        use crate::flat::Reader;
5111742×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
5121742×
        let mut r = Reader::new(bytes);
5131742×
        let mut st = State::new_history_only();
514
        {
5151742×
            let _t = crate::timing::phase("index: changes");
5161742×
            st.changes = Self::read_index_changes(r.bytes()?)?;
517
        }
5181742×
        let tree_bytes = r.bytes()?;
5191742×
        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
        }
5271742×
        let deferred_bytes = r.bytes()?;
5281742×
        if !r.at_end() {
5290×
            return Err(bad("trailing bytes"));
5301742×
        }
5311742×
        let (tree, deferred) = rayon::join(
5321742×
            || TreeGraph::read_flat(&mut Reader::new(tree_bytes)),
5331742×
            || Self::read_deferred(deferred_bytes, &histories),
534
        );
5351742×
        st.tree = tree?;
5361742×
        st.deferred = Some(deferred?);
5371742×
        Ok(st)
5381742×
    }
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).
5421897×
    pub fn read_index_changes(
5431897×
        bytes: &[u8],
5441897×
    ) -> Result<crate::fasthash::FastMap<ChangeHash, Arc<ChangeMeta>>, ObjectError> {
545
        use crate::flat::Reader;
5461897×
        let mut r = Reader::new(bytes);
5471897×
        if r.fixed::<18>()?.as_slice() != Self::INDEX_MAGIC {
5480×
            return Err(ObjectError::Schema("state index: not a state index".into()));
5491897×
        }
5501897×
        let n = r.count()?;
5511897×
        let mut changes = crate::fasthash::FastMap::default();
5521897×
        changes.reserve(n);
5531897×
        for _ in 0..n {
554158×
            let h = r.object()?;
555158×
            changes.insert(h, Arc::new(ChangeMeta::read_flat(&mut r)?));
556
        }
5571897×
        if !r.at_end() {
5580×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
5591897×
        }
5601897×
        Ok(changes)
5611897×
    }
562
563
    /// The deferred block: each node with its graph key and its body,
564
    /// left encoded (see [`Deferred`]).
5651742×
    fn read_deferred(
5661742×
        table: &[u8],
5671742×
        histories: &Histories,
5681742×
    ) -> Result<crate::fasthash::FastMap<NodeId, Arc<Deferred>>, ObjectError> {
569
        use crate::flat::Reader;
5701742×
        let _t = crate::timing::phase("index: deferred");
5711742×
        let mut r = Reader::new(table);
5721742×
        let mut deferred = crate::fasthash::FastMap::default();
5731742×
        let n = r.count()?;
5741742×
        deferred.reserve(n);
5751742×
        for _ in 0..n {
57616682×
            let id = NodeId(r.fixed::<16>()?);
57716682×
            let key = r.fixed::<32>()?;
578
            // The length is of bytes in the histories, not in this table:
579
            // checked against the histories' size below.
58016682×
            let (at, len, sum) = (r.u64()?, r.u32()? as usize, r.fixed::<32>()?);
58116682×
            if at
58216682×
                .checked_add(len as u64)
58316682×
                .is_none_or(|end| end > histories.len())
584
            {
5850×
                return Err(ObjectError::Schema(
5860×
                    "state index: a file's history lies outside it".into(),
5870×
                ));
58816682×
            }
58916682×
            let d = Deferred {
59016682×
                raw: Some(RawHistory {
59116682×
                    from: histories.clone(),
59216682×
                    at,
59316682×
                    len,
59416682×
                    sum,
59516682×
                }),
59616682×
                key: std::sync::OnceLock::from(key),
59716682×
                ..Deferred::default()
59816682×
            };
59916682×
            deferred.insert(id, Arc::new(d));
600
        }
6011742×
        if !r.at_end() {
6020×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
6031742×
        }
6041742×
        Ok(deferred)
6051742×
    }
606
607
    /// One node's deferred history as the index encodes it.
6085467×
    fn read_deferred_body(bytes: &[u8]) -> Result<DeferredBody, ObjectError> {
609
        use crate::flat::Reader;
6105467×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
6115478×
        let node = |r: &mut Reader| -> Result<NodeId, ObjectError> { Ok(NodeId(r.fixed::<16>()?)) };
61210956×
        let atom = |r: &mut Reader| -> Result<AtomRef, ObjectError> {
61310956×
            Ok(match r.u8()? {
6145461×
                0 => AtomRef::Start,
6155478×
                1 => AtomRef::End,
616
                2 => AtomRef::Atom {
61717×
                    change: r.object()?,
61817×
                    index: r.u32()?,
619
                },
6200×
                _ => return Err(bad("atom")),
621
            })
62210956×
        };
6235467×
        let mut r = Reader::new(bytes);
6245467×
        let base = match r.u8()? {
6255461×
            0 => None,
6260×
            1 => Some(DeferredBase::Blob(r.object()?)),
6276×
            _ => Some(DeferredBase::Inline(cbor::decode(r.bytes()?)?)),
628
        };
6295467×
        let mut edits = Vec::new();
6305467×
        for _ in 0..r.count()? {
6315478×
            let c = r.object()?;
6325478×
            let mut es = Vec::new();
6335478×
            for _ in 0..r.count()? {
6345478×
                es.push(match r.u8()? {
635
                    0 => Edit::Insert {
6365478×
                        node: node(&mut r)?,
6375478×
                        after: atom(&mut r)?,
6385478×
                        before: atom(&mut r)?,
6395478×
                        lines: crate::lines::Lines::default(),
640
                    },
641
                    1 => {
6420×
                        let node = node(&mut r)?;
6430×
                        let mut atoms = Vec::new();
6440×
                        for _ in 0..r.count()? {
6450×
                            atoms.push(crate::objects::AtomRange {
6460×
                                change: r.object()?,
6470×
                                from: r.u32()?,
6480×
                                to: r.u32()?,
649
                            });
650
                        }
6510×
                        Edit::Delete { node, atoms }
652
                    }
6530×
                    _ => return Err(bad("edit")),
654
                });
655
            }
6565478×
            edits.push((c, es));
657
        }
6585467×
        let mut texts = Vec::new();
6595467×
        for _ in 0..r.count()? {
6605478×
            texts.push(match r.u8()? {
661
                0 => TextRef::Blob(
6620×
                    r.object()?,
6630×
                    r.u32()?,
6640×
                    match r.u8()? {
6650×
                        0 => crate::objects::TextForm::Cbor,
6660×
                        1 => crate::objects::TextForm::Raw,
6670×
                        _ => crate::objects::TextForm::CborFallback,
668
                    },
669
                ),
670
                _ => TextRef::Inline {
6715478×
                    change: r.object()?,
6725478×
                    start: r.u32()?,
6735478×
                    end: r.u32()?,
674
                },
675
            });
676
        }
6775467×
        if !r.at_end() {
6780×
            return Err(bad("trailing bytes in a file's history"));
6795467×
        }
6805467×
        Ok(DeferredBody { base, edits, texts })
6815467×
    }
682
}
683
684
impl Clone for State {
6851342×
    fn clone(&self) -> State {
6861342×
        State {
6871342×
            changes: self.changes.clone(),
6881342×
            tree: self.tree.clone(),
6891342×
            files: self.files.clone(),
6901342×
            replaces: self.replaces.clone(),
6911342×
            // A cache: the clone builds its own.
6921342×
            closure: Mutex::new(ClosureMemo::default()),
6931342×
            levels: Mutex::new(HashMap::new()),
6941342×
            deferred: self.deferred.clone(),
6951342×
        }
6961342×
    }
697
}
698
699
#[derive(Clone, Debug, PartialEq, Eq)]
700
pub enum FileContent {
701
    Text {
702
        bytes: Vec<u8>,
703
        materialized: Materialized,
704
    },
705
    /// Live blobs; more than one is a replace conflict (spec §9.3).
706
    Opaque {
707
        blobs: Vec<ObjectRef>,
708
    },
709
    Dir,
710
}
711
712
#[derive(Clone, Debug, PartialEq, Eq)]
713
pub struct FileState {
714
    pub node: NodeId,
715
    pub kind: NodeKind,
716
    pub mode: Mode,
717
    pub content: FileContent,
718
}
719
720
impl FileState {
72113354×
    pub fn is_conflicted(&self) -> bool {
72213354×
        match &self.content {
72312461×
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
724243×
            FileContent::Opaque { blobs } => blobs.len() > 1,
725650×
            FileContent::Dir => false,
726
        }
72713354×
    }
728
}
729
730
/// See `State::conflict_regions`.
731
#[derive(Clone, Debug, Default, PartialEq, Eq)]
732
pub struct ConflictRegions {
733
    pub plain: Vec<(AtomKey, Vec<u8>)>,
734
    pub region_atoms: Vec<AtomKey>,
735
    pub contributors: Vec<ChangeHash>,
736
}
737
738
/// The whole tree of a state, materialized.
739
#[derive(Clone, Debug, Default)]
740
pub struct Snapshot {
741
    pub tree: TreeView,
742
    pub files: BTreeMap<String, FileState>,
743
    /// Text files left unrendered by [`State::materialize_except`]: their
744
    /// `bytes` are empty and they are known not to be conflicted.
745
    pub unrendered: BTreeSet<String>,
746
}
747
748
impl Snapshot {
7491877×
    pub fn is_conflicted(&self) -> bool {
75013070×
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
7511877×
    }
752
}
753
75461060×
fn vertex(r: AtomRef) -> Vertex {
75561060×
    match r {
75625508×
        AtomRef::Start => Vertex::Start,
75726818×
        AtomRef::End => Vertex::End,
7588734×
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
759
    }
76061060×
}
761
762
/// Replace self references in a tree op with the concrete change hash.
76337859×
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
76437859×
    match op {
765655×
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
766655×
            node: *node,
767655×
            placement: placement.resolve(me),
768655×
        },
769
        TreeOp::Move {
770152×
            node,
771152×
            old,
772152×
            parent,
773152×
            name,
774152×
        } => TreeOp::Move {
775152×
            node: *node,
776152×
            old: old.resolve(me),
777152×
            parent: *parent,
778152×
            name: name.clone(),
779152×
        },
78022×
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
78122×
            node: *node,
78222×
            old: old.resolve(me),
78322×
            mode: *mode,
78422×
        },
78537030×
        add @ TreeOp::AddNode { .. } => add.clone(),
786
    }
78737859×
}
788
789
/// Apply one change's edits of one file (inserts and deletes; replaces
790
/// live beside the graphs) to that file's graph.
79125513×
fn apply_file_edits(g: &mut FileGraph, h: ChangeHash, edits: Vec<Edit>) {
792
    // The graph's kept order, if any, follows the edits (see `Order`).
79325513×
    let order = g.take_order();
79425513×
    let mut inserts: Vec<(Vertex, Vertex, u32, u32)> = Vec::new();
79525513×
    let mut deleted: Vec<crate::graph::AtomKey> = Vec::new();
79625513×
    let mut next = 0u32;
79727632×
    for e in edits {
79827632×
        match e {
799
            Edit::Insert {
80026316×
                after,
80126316×
                before,
80226316×
                lines,
803
                ..
80426316×
            } => {
80526316×
                let first = next;
80626316×
                let count = lines.len() as u32;
80726316×
                next += count;
80826316×
                let (after, before) = (vertex(after.resolve(h)), vertex(before.resolve(h)));
80926316×
                inserts.push((after, before, first, count));
81026316×
                g.insert_owned(h, first, after, before, lines);
81126316×
            }
8121316×
            Edit::Delete { atoms, .. } => {
8132384×
                for r in atoms {
8142384×
                    let r = r.resolve(h);
8152457×
                    deleted.extend((r.from..r.to).map(|i| (r.change, i)));
8162384×
                    g.delete(h, &r);
817
                }
818
            }
8190×
            Edit::Replace { .. } => {}
820
        }
821
    }
82225513×
    if let Some(o) = order {
82363×
        g.keep_spliced(o, h, &inserts, &deleted);
82425450×
    }
82525513×
}
826
827
/// Build the graphs of deferred entries: their checkpoint bases and the
828
/// texts of inserts read without their lines are loaded in one call, then
829
/// the graphs are built in parallel (they are independent).
8303506×
fn build_deferred(
8313506×
    taken: Vec<(NodeId, Deferred)>,
8323506×
    load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
8333506×
    read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
8343506×
) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
8353506×
    let mut taken: Vec<(NodeId, DeferredBody)> = taken
8363506×
        .into_iter()
83722583×
        .map(|(n, d)| Ok((n, d.into_body()?)))
8383506×
        .collect::<Result<_, ObjectError>>()?;
8393505×
    let mut refs: Vec<ObjectRef> = taken
8403505×
        .iter()
8413505×
        .filter_map(|(_, d)| match &d.base {
8426×
            Some(DeferredBase::Blob(r)) => Some(*r),
84322576×
            _ => None,
84422582×
        })
8453505×
        .collect();
846
    // Text blobs of inserts read without their lines, after the bases.
8473505×
    let bases = refs.len();
84822582×
    refs.extend(taken.iter().flat_map(|(_, d)| {
84925662×
        d.texts.iter().filter_map(|t| match t {
85070×
            TextRef::Blob(r, _, _) => Some(*r),
85125592×
            TextRef::Inline { .. } => None,
85225662×
        })
85322582×
    }));
854
    // And the encodings of changes whose inline inserts are needed,
855
    // each read once.
8563505×
    let reading = crate::timing::phase("graphs: read changes and blobs");
8573505×
    let mut changes: HashMap<ChangeHash, Arc<Vec<u8>>> = HashMap::new();
85825662×
    for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
85925662×
        if let TextRef::Inline { change, .. } = t {
86025592×
            if !changes.contains_key(change) {
8615700×
                changes.insert(*change, read_change(change)?);
86219892×
            }
86370×
        }
864
    }
8653505×
    let n_changes = changes.len();
8663505×
    drop(reading);
8673505×
    let reading = crate::timing::phase("graphs:   of which blobs");
8683505×
    let mut blobs = if refs.is_empty() {
8693434×
        Vec::new()
870
    } else {
87171×
        load(&refs)?
872
    };
8733502×
    if crate::timing::enabled() {
8742×
        eprintln!(
8752×
            "timing graphs: {} graphs, {n_changes} changes, {} blobs",
8762×
            taken.len(),
8772×
            refs.len()
8782×
        );
8793500×
    }
8803502×
    if blobs.len() != refs.len() {
8810×
        return Err(ObjectError::Schema("graph blobs: wrong count".into()));
8823502×
    }
8833502×
    drop(reading);
8843502×
    let lines = crate::timing::phase("graphs: hand out blobs");
8853502×
    let mut texts = blobs.split_off(bases).into_iter();
8863502×
    let mut blobs = blobs.into_iter();
887
    // Hand each graph its own blobs, in order, then fill in its inserts'
888
    // lines and build it, all in parallel: graphs are independent.
889
    type Work = (NodeId, DeferredBody, Option<Vec<u8>>, Vec<Vec<u8>>);
8903502×
    let mut work: Vec<Work> = Vec::with_capacity(taken.len());
89122579×
    for (node, d) in taken.drain(..) {
89222579×
        let wanted = d
89322579×
            .texts
89422579×
            .iter()
89525660×
            .filter(|t| matches!(t, TextRef::Blob(..)))
89622579×
            .count();
89722579×
        let mine: Vec<Vec<u8>> = texts.by_ref().take(wanted).collect();
89822579×
        if mine.len() != wanted {
8990×
            return Err(ObjectError::Schema("text blobs: wrong count".into()));
90022579×
        }
90122579×
        let bytes = match &d.base {
902
            Some(DeferredBase::Blob(_)) => Some(
9035×
                blobs
9045×
                    .next()
9055×
                    .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
906
            ),
90722574×
            _ => None,
908
        };
90922579×
        work.push((node, d, bytes, mine));
910
    }
9113502×
    drop(lines);
9123502×
    let _t = crate::timing::phase("graphs: lines and build");
913
    use rayon::prelude::*;
9143502×
    let changes = &changes;
9153502×
    let built: Vec<(NodeId, FileGraph)> = work
9163502×
        .into_par_iter()
91722579×
        .map(|(node, mut d, bytes, mine)| {
918
            // Fill in the lines of inserts read without them, in order.
91922579×
            let mut want = std::mem::take(&mut d.texts).into_iter();
92022579×
            let mut mine = mine.into_iter();
92125054×
            for (_, edits) in d.edits.iter_mut() {
92226740×
                for e in edits.iter_mut() {
92326740×
                    if let Edit::Insert { lines, .. } = e {
92425667×
                        if lines.is_empty() {
92525660×
                            *lines = match want.next() {
92668×
                                Some(TextRef::Blob(_, count, form)) => {
92768×
                                    let content = mine.next().ok_or_else(|| {
9280×
                                        ObjectError::Schema("text blobs: wrong count".into())
9290×
                                    })?;
93068×
                                    crate::objects::text_lines(&content, count, form)?
931
                                }
93225592×
                                Some(TextRef::Inline { change, start, end }) => {
93325592×
                                    let bytes = &changes[&change];
93425592×
                                    let range = bytes
93525592×
                                        .get(start as usize..end as usize)
93625592×
                                        .ok_or_else(|| {
9370×
                                            ObjectError::Schema(
9380×
                                                "an inline insert lies outside its change".into(),
9390×
                                            )
9400×
                                        })?;
94125592×
                                    crate::objects::inline_lines(range)?
942
                                }
943
                                None => {
9440×
                                    return Err(ObjectError::Schema(
9450×
                                        "an insert's text is missing".into(),
9460×
                                    ))
947
                                }
948
                            };
9497×
                        }
9501073×
                    }
951
                }
952
            }
95322579×
            let mut graph = match (d.base.take(), bytes) {
95496×
                (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
9555×
                (Some(DeferredBase::Blob(_)), Some(bytes)) => {
9565×
                    FileGraph::from_value(&cbor::decode(&bytes)?)?
957
                }
95822478×
                _ => FileGraph::default(),
959
            };
96025054×
            for (h, edits) in std::mem::take(&mut d.edits) {
96125054×
                apply_file_edits(&mut graph, h, edits);
96225054×
            }
96322579×
            Ok((node, graph))
96422579×
        })
9653502×
        .collect::<Result<_, ObjectError>>()?;
9663502×
    Ok(built)
9673506×
}
968
969
impl State {
970683×
    pub fn new() -> Self {
971683×
        Self::default()
972683×
    }
973
974
    /// An empty state for history only: changes and tree are kept, file
975
    /// edits are recorded but no file graph is built until
976
    /// [`State::load_graphs`] asks for it. For log and other commands that
977
    /// need no file contents, or only a few files.
9783350×
    pub fn new_history_only() -> Self {
9793350×
        State {
9803350×
            deferred: Some(Default::default()),
9813350×
            ..Self::default()
9823350×
        }
9833350×
    }
984
985
    /// Whether `node`'s file graph is built (always, in a full state).
98640×
    pub fn is_built(&self, node: &NodeId) -> bool {
98740×
        self.deferred.is_none() || self.files.contains_key(node)
98840×
    }
989
990
    /// Whether this state builds file graphs only when asked
991
    /// ([`State::new_history_only`]), even if it has none waiting.
9923153×
    pub fn is_history_only(&self) -> bool {
9933153×
        self.deferred.is_some()
9943153×
    }
995
996
    /// Whether this state holds every file graph.
9972636×
    pub fn is_full(&self) -> bool {
9982636×
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
9992636×
    }
1000
1001
    /// The graph of `node`, which must be loaded: asking a history-only
1002
    /// state for a graph it has not built is a bug, never an empty file.
100324913×
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
100424913×
        if let Some(d) = &self.deferred {
10059965×
            assert!(
10069965×
                !d.contains_key(node),
1007
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
10081×
                node.short(12)
1009
            );
101014948×
        }
101124912×
        self.files.get(node).map(|g| g.as_ref())
101224912×
    }
1013
1014
    /// Operations over every file need every graph.
10152629×
    fn require_full(&self, what: &str) {
10162629×
        assert!(
10172629×
            self.is_full(),
1018
            "{what} needs every file graph; this state was loaded for history only"
1019
        );
10202628×
    }
1021
1022
    /// Build the graphs of `nodes` in a history-only state: from their
1023
    /// checkpoint base (blobs read in one batch through `load`) and their
1024
    /// deferred edits. Nodes already built, or with no graph, are skipped.
10253431×
    pub fn load_graphs(
10263431×
        &mut self,
10273431×
        nodes: &[NodeId],
10283431×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
10293431×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
10303431×
    ) -> Result<(), ObjectError> {
10313431×
        let Some(deferred) = self.deferred.as_mut() else {
10320×
            return Ok(());
1033
        };
10343431×
        let taken: Vec<(NodeId, Deferred)> = nodes
10353431×
            .iter()
103622747×
            .filter_map(|n| deferred.remove(n).map(|d| (*n, Arc::unwrap_or_clone(d))))
10373431×
            .collect();
10383431×
        let built = build_deferred(taken, load, read_change)?;
10393427×
        self.files
104022520×
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
10413427×
        Ok(())
10423431×
    }
1043
1044
    /// The graphs of `nodes`, built from this history-only state's deferred
1045
    /// edits without building them in it: the state stays history only, so
1046
    /// changes read without their lines can still be added to it and every
1047
    /// graph keeps its key. For a caller that renders a few files of many
1048
    /// states in turn (verifying an import).
104975×
    pub fn build_graphs_detached(
105075×
        &self,
105175×
        nodes: &[NodeId],
105275×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
105375×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
105475×
    ) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
105575×
        let Some(deferred) = self.deferred.as_ref() else {
10560×
            return Ok(Vec::new());
1057
        };
1058
        // A file this state has built has no deferred history: its graph
1059
        // is the built one, copied. Built from an empty history instead, it
1060
        // rendered as an empty file, and a merge taking this path recorded
1061
        // the whole file as inserted again, conflicting with itself (#71).
106275×
        let mut built: Vec<(NodeId, FileGraph)> = Vec::new();
106375×
        let mut copies: Vec<(NodeId, Deferred)> = Vec::new();
106475×
        for n in nodes {
106562×
            match (self.files.get(n), deferred.get(n)) {
10663×
                (Some(g), _) => built.push((*n, (**g).clone())),
106759×
                (None, d) => copies.push((*n, d.map(|d| (**d).clone()).unwrap_or_default())),
1068
            }
1069
        }
107075×
        let mut out = build_deferred(copies, load, read_change)?;
107175×
        out.extend(built);
107275×
        Ok(out)
107375×
    }
1074
1075
    /// Render a graph built for this state (see
1076
    /// [`State::build_graphs_detached`]), as [`State::render_file`] does.
107762×
    pub fn render_graph(&self, g: &FileGraph) -> (Vec<u8>, Materialized) {
107862×
        let m = g.materialize(self);
107962×
        let bytes = g.render(&m, &|h| self.label(h));
108062×
        (bytes, m)
108162×
    }
1082
1083
    /// Every file graph a history-only state has not built, deleted files'
1084
    /// included.
108576×
    pub fn unbuilt_nodes(&self) -> Vec<NodeId> {
108676×
        self.deferred
108776×
            .as_ref()
108876×
            .map(|d| d.keys().copied().collect())
108976×
            .unwrap_or_default()
109076×
    }
1091
1092
    /// Drop the built graphs of `nodes`, for a caller rendering a large
1093
    /// tree a batch at a time. The state can no longer render those files,
1094
    /// so it must not be used for them again.
1095423×
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
10966007×
        for n in nodes {
10976007×
            self.files.remove(n);
10986007×
        }
1099423×
    }
1100
1101
    /// Build every graph a history-only state has not built, making it full.
11021717×
    pub fn load_all_graphs(
11031717×
        &mut self,
11041717×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
11051717×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
11061717×
    ) -> Result<(), ObjectError> {
11071717×
        let nodes: Vec<NodeId> = match &self.deferred {
11081717×
            Some(d) => d.keys().copied().collect(),
11090×
            None => return Ok(()),
1110
        };
11111717×
        self.load_graphs(&nodes, load, read_change)?;
11121717×
        self.deferred = None;
11131717×
        Ok(())
11141717×
    }
1115
1116
    /// The one text a file's history is, when it is a single insert of
1117
    /// the whole file into nothing (a file added once and never edited,
1118
    /// with no checkpoint base): its rendering is that text, so it needs
1119
    /// no graph. `None` otherwise, or when the graph is built.
11205861×
    pub fn single_text(&self, node: &NodeId) -> Option<TextRef> {
11215861×
        if self.files.contains_key(node) {
11220×
            return None;
11235861×
        }
1124
        // A history that cannot be read is no single text: building its
1125
        // graph reports why.
11265861×
        let d = self.deferred.as_ref()?.get(node)?.body().ok()?;
11275795×
        let [(_, edits)] = d.edits.as_slice() else {
1128259×
            return None;
1129
        };
1130
        let [Edit::Insert {
1131
            after: AtomRef::Start,
1132
            before: AtomRef::End,
11335536×
            lines,
1134
            ..
11355536×
        }] = edits.as_slice()
1136
        else {
11370×
            return None;
1138
        };
11395536×
        match (&d.base, d.texts.as_slice()) {
11405536×
            (None, [t]) if lines.is_empty() => Some(*t),
11410×
            _ => None,
1142
        }
11435861×
    }
1144
1145
    /// A key for the graph of `node` in a history-only state that has not
1146
    /// built it: equal keys mean equal graphs, so equal renderings (a
1147
    /// rendering depends only on the graph and on the changes' own
1148
    /// immutable metadata). It names the node, its checkpoint base (a blob,
1149
    /// an inline value, or none) and the set of later changes that edited
1150
    /// the file.
1151
    /// `None` for a full state or a graph already built.
115228512×
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
115328512×
        let deferred = self.deferred.as_ref()?;
115428477×
        if self.files.contains_key(node) {
1155418×
            return None;
115628059×
        }
115728059×
        let mut h = blake3::Hasher::new();
115828059×
        h.update(b"oxy graph key 1\0");
1159
        // A change's edits are applied per node: the node is part of it.
116028059×
        h.update(&node.0);
116128059×
        let Some(d) = deferred.get(node) else {
1162
            // Never edited: the empty graph.
1163209×
            h.update(&[0]);
1164209×
            return Some(*h.finalize().as_bytes());
1165
        };
1166
        // A history that cannot be read has no key: the file is read.
116727850×
        if let Some(k) = d.key.get() {
116822171×
            return Some(*k);
11695679×
        }
11705679×
        let k = d.graph_key(h).ok()?;
11715679×
        Some(*d.key.get_or_init(|| k))
117228512×
    }
1173
11743291×
    pub fn len(&self) -> usize {
11753291×
        self.changes.len()
11763291×
    }
1177
1178
    /// Turn this history-only state's built graphs back into deferred
1179
    /// histories, each starting from its graph encoded as a checkpoint
1180
    /// graph and stored by `store` (it returns the blob's reference): what
1181
    /// they held stays, and memory goes back to what a history-only state
1182
    /// costs. A graph built later again decodes that blob and applies only
1183
    /// the edits that came after. Graph keys change (the base is now a
1184
    /// blob), which only means a cached rendering is not reused.
11851×
    pub fn shed_graphs<E>(
11861×
        &mut self,
11871×
        mut store: impl FnMut(&[u8]) -> Result<ObjectRef, E>,
11881×
    ) -> Result<usize, E> {
1189
        use rayon::prelude::*;
11901×
        let Some(deferred) = self.deferred.as_mut() else {
11910×
            return Ok(0);
1192
        };
11931×
        let graphs: Vec<(NodeId, Arc<FileGraph>)> = self.files.drain().collect();
11941×
        let encoded: Vec<(NodeId, Vec<u8>)> = graphs
11951×
            .par_iter()
11962×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
11971×
            .collect();
11981×
        drop(graphs);
11991×
        let shed = encoded.len();
12002×
        for (node, bytes) in encoded {
12012×
            let blob = store(&bytes)?;
12022×
            deferred.insert(
12032×
                node,
12042×
                Arc::new(Deferred::from_body(DeferredBody {
12052×
                    base: Some(DeferredBase::Blob(blob)),
12062×
                    ..DeferredBody::default()
12072×
                })),
1208
            );
1209
        }
12101×
        Ok(shed)
12111×
    }
1212
1213
    /// How many file graphs this state has built.
121476×
    pub fn built_count(&self) -> usize {
121576×
        self.files.len()
121676×
    }
1217
1218
    /// Atoms in this state's built graphs, live and deleted: what their
1219
    /// memory follows, since a graph keeps every line its file ever had.
122050×
    pub fn built_atoms(&self) -> usize {
122156×
        self.files.values().map(|g| g.atom_count()).sum()
122250×
    }
1223
1224
    /// Edits held in the deferred histories of files not built, and the
1225
    /// most any one file holds (for measuring, #25).
12260×
    pub fn deferred_edit_count(&self) -> (usize, usize) {
12270×
        let Some(d) = self.deferred.as_ref() else {
12280×
            return (0, 0);
1229
        };
12300×
        let mut total = 0;
12310×
        let mut most = 0;
12320×
        for v in d.values() {
12330×
            let n: usize = v
12340×
                .body()
12350×
                .map_or(0, |b| b.edits.iter().map(|(_, e)| e.len()).sum());
12360×
            total += n;
12370×
            most = most.max(n);
1238
        }
12390×
        (total, most)
12400×
    }
1241
}
1242
1243
impl Deferred {
1244
    /// See [`State::graph_key`]: `h` has taken the node already.
124522017×
    fn graph_key(&self, mut h: blake3::Hasher) -> Result<[u8; 32], ObjectError> {
124622017×
        let d = self.body()?;
124713×
        match &d.base {
124822004×
            None => h.update(&[0]),
12490×
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
125013×
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
1251
        };
125222017×
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
125322017×
        changes.sort();
125422017×
        changes.dedup();
125522017×
        h.update(&(changes.len() as u64).to_le_bytes());
125623432×
        for c in changes {
125723432×
            h.update(&c.0);
125823432×
        }
125922017×
        Ok(*h.finalize().as_bytes())
126022017×
    }
1261
}
1262
1263
impl State {
12640×
    pub fn is_empty(&self) -> bool {
12650×
        self.changes.is_empty()
12660×
    }
126712777×
    pub fn contains(&self, h: &ChangeHash) -> bool {
126812777×
        self.changes.contains_key(h)
126912777×
    }
127064×
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
127164×
        self.changes.get(h).map(|m| &**m)
127264×
    }
12731335×
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
12743374×
        self.changes.iter().map(|(h, m)| (h, &**m))
12751335×
    }
127617286×
    pub fn tree(&self) -> &TreeGraph {
127717286×
        &self.tree
127817286×
    }
1279550×
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
1280550×
        self.graph(node)
1281550×
    }
1282
1283
    /// Add a change whose dependencies are already present.
12842795×
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
12852795×
        let h = change.hash();
12862795×
        self.add_hashed(h, change)
12872795×
    }
1288
1289
    /// [`State::add`] for a change whose hash `h` is already known (it was
1290
    /// just stored), so it is not encoded again.
12913410×
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
12923410×
        if self.changes.contains_key(&h) {
129336×
            return Ok(h);
12943374×
        }
12954878×
        for d in &change.deps {
12964878×
            if !self.changes.contains_key(d) {
12972×
                return Err(StateError::MissingDep(*d, h));
12984876×
            }
1299
        }
13003372×
        self.add_known(h, change, Vec::new());
13013372×
        Ok(h)
13023410×
    }
1303
1304
    /// Add a change in any order; call `validate` once all are in.
1305922×
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
1306922×
        let h = change.hash();
1307922×
        self.add_known(h, change, Vec::new());
1308922×
        h
1309922×
    }
1310
1311
    /// Add a change just stored under hash `h` to a history-only state that
1312
    /// has built some graphs: an edit of a built graph is applied whole
1313
    /// (from `full`), and one of a file not built waits without its text
1314
    /// (from `skeleton` and its `texts`, as the store reads it back), so the
1315
    /// state holds no text it has not built. A Git import adds each change
1316
    /// it makes this way, keeping memory to what changes.
131790×
    pub fn add_known_mixed(
131890×
        &mut self,
131990×
        h: ChangeHash,
132090×
        full: Change,
132190×
        skeleton: Change,
132290×
        texts: Vec<TextRef>,
132390×
    ) {
132490×
        if self.deferred.is_none() || self.changes.contains_key(&h) {
13250×
            self.add_known(h, full, Vec::new());
13260×
            return;
132790×
        }
1328
        let Change {
132990×
            version,
133090×
            change_id,
133190×
            deps,
133290×
            author,
133390×
            hlc,
133490×
            message,
133590×
            tree_ops,
133690×
            edits: full_edits,
133790×
            kind,
133890×
        } = full;
133990×
        let mut texts = texts.into_iter();
134090×
        let mut edits = Vec::with_capacity(full_edits.len());
134190×
        let mut kept = Vec::new();
134295×
        for (f, s) in full_edits.into_iter().zip(skeleton.edits) {
134395×
            let text = match &s {
134475×
                Edit::Insert { lines, .. } if lines.is_empty() => texts.next(),
134520×
                _ => None,
1346
            };
134795×
            if self.files.contains_key(&f.node()) {
134845×
                edits.push(f);
134950×
            } else {
135050×
                edits.push(s);
135150×
                kept.extend(text);
135250×
            }
1353
        }
135490×
        let c = Change {
135590×
            version,
135690×
            change_id,
135790×
            deps,
135890×
            author,
135990×
            hlc,
136090×
            message,
136190×
            tree_ops,
136290×
            edits,
136390×
            kind,
136490×
        };
136590×
        self.add_known(h, c, kept);
136690×
    }
1367
1368
    /// Add a change read from the store under hash `h`, without hashing it
1369
    /// again (for a version 2 change that means chunking all its text).
1370
    /// `texts` names, in order, the inserts left without their lines (see
1371
    /// [`crate::store::Store::get_change_lazy`]); only a history-only state
1372
    /// takes them, and only for graphs it has not built.
137311787×
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
137411787×
        if self.changes.contains_key(&h) {
13750×
            return;
137611787×
        }
137711787×
        let meta = ChangeMeta::of(&change);
137811787×
        self.apply_with(h, change, texts);
137911787×
        self.changes.insert(h, Arc::new(meta));
138011787×
        {
138111787×
            let mut m = self.closure.lock().unwrap();
138211787×
            m.sets.clear();
138311787×
            m.held = 0;
138411787×
        }
138511787×
    }
1386
1387
    // ------------------------------------------------------------ checkpoints (spec §11)
1388
1389
    /// Serialize the whole state in payload version 1: change metadata,
1390
    /// tree, file graphs, replaces, all in one value (spec §11).
1391380×
    pub fn checkpoint_payload(&self) -> Vec<u8> {
1392380×
        self.require_full("a checkpoint");
1393380×
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
1394380×
        nodes.sort();
1395380×
        let files = Value::Array(
1396380×
            nodes
1397380×
                .into_iter()
13981374×
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
1399380×
                .collect(),
1400
        );
1401380×
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
1402380×
    }
1403
1404
    /// Each file graph encoded on its own, by node, for a version 2 payload
1405
    /// (spec §11): the graphs of large files become blobs of their own.
140618×
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
1407
        use rayon::prelude::*;
140818×
        self.require_full("a checkpoint");
140918×
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
141053×
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
141118×
        nodes.sort_by_key(|(n, _)| **n);
141218×
        nodes
141318×
            .into_par_iter()
141453×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
141518×
            .collect()
141618×
    }
1417
1418
    /// The payload version 2 index for the graphs of
1419
    /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than
1420
    /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by
1421
    /// `blob_of` (the ObjectRef of the blob holding its encoding).
142218×
    pub fn checkpoint_index(
142318×
        &self,
142418×
        graphs: &[(NodeId, Vec<u8>)],
142518×
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
142618×
    ) -> Vec<u8> {
142718×
        let files = Value::Array(
142818×
            graphs
142918×
                .iter()
143053×
                .map(|(n, enc)| {
143153×
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
143246×
                        cbor::decode(enc).expect("an encoded graph decodes")
1433
                    } else {
14347×
                        Value::Bytes(blob_of(enc).0.to_vec())
1435
                    };
143653×
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
143753×
                })
143818×
                .collect(),
1439
        );
144018×
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
144118×
    }
1442
1443
    /// The payload map around `files`: changes, tree and replaces as in version 1.
1444398×
    fn payload_value(&self, version: u64, files: Value) -> Value {
1445398×
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
1446398×
        hashes.sort();
1447398×
        let changes = Value::Array(
1448398×
            hashes
1449398×
                .into_iter()
14502099×
                .map(|h| {
14512099×
                    let m = &self.changes[h];
14522099×
                    Value::Array(vec![
14532099×
                        Value::Bytes(h.0.to_vec()),
14542099×
                        Value::Bytes(m.change_id.0.to_vec()),
14552099×
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
14562099×
                        Value::Text(m.message.clone()),
14572099×
                        Value::Uint(m.hlc.wall_ms),
14582099×
                        Value::Uint(m.hlc.logical as u64),
14592099×
                        Value::Uint(m.kind.tag()),
14602099×
                        Value::Bytes(m.author.0.to_vec()),
1461
                    ])
14622099×
                })
1463398×
                .collect(),
1464
        );
1465398×
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
1466398×
        rnodes.sort();
1467398×
        let opt =
146810×
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
1469398×
        let replaces = Value::Array(
1470398×
            rnodes
1471398×
                .into_iter()
1472398×
                .map(|n| {
14735×
                    Value::Array(vec![
14745×
                        Value::Bytes(n.0.to_vec()),
1475
                        Value::Array(
14765×
                            self.replaces[n]
14775×
                                .iter()
14785×
                                .map(|(c, o, nw)| {
14795×
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
14805×
                                })
14815×
                                .collect(),
1482
                        ),
1483
                    ])
14845×
                })
1485398×
                .collect(),
1486
        );
1487398×
        Value::map([
1488398×
            (0, Value::Uint(version)),
1489398×
            (1, changes),
1490398×
            (2, self.tree.to_value()),
1491398×
            (3, files),
1492398×
            (4, replaces),
1493398×
        ])
1494398×
    }
1495
1496
    /// Decode a version 1 payload (the whole state in one value). A
1497
    /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`].
149837×
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
149937×
        State::from_checkpoint(bytes, |_| {
15001×
            Err(ObjectError::Schema(
15011×
                "a version 2 checkpoint needs its graph blobs".into(),
15021×
            ))
15031×
        })
150437×
    }
1505
1506
    /// Decode a checkpoint payload of either version (spec §11). For
1507
    /// version 2, `load` returns the contents of the named graph blobs, in
1508
    /// order; the graphs are then decoded in parallel.
150960×
    pub fn from_checkpoint(
151060×
        bytes: &[u8],
151160×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
151260×
    ) -> Result<State, ObjectError> {
1513
        use rayon::prelude::*;
151460×
        let v = cbor::decode(bytes)?;
151559×
        let m = o::map(&v, "checkpoint payload")?;
151659×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
151759×
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
15181×
            return Err(ObjectError::Schema(format!(
15191×
                "checkpoint payload version {version} is not supported"
15201×
            )));
152158×
        }
152258×
        let mut st = State::payload_common(m)?;
152358×
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
152458×
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
1525221×
        for f in entries {
1526221×
            let e = o::array(f, "file")?;
1527221×
            if e.len() != 2 {
15280×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1529221×
            }
1530221×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1531221×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1532221×
            parsed.push((node, &e[1]));
1533
        }
1534
        // Version 2 names large graphs by blob: fetch those in one batch.
153558×
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
153658×
        if version == CHECKPOINT_INDEX_VERSION {
153720×
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
153820×
                .iter()
153990×
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
154020×
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
154120×
                .collect::<Result<_, ObjectError>>()?;
154220×
            if !wanted.is_empty() {
15437×
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
15443×
                let contents = {
15457×
                    let _t = crate::timing::phase("load:   graph blobs read");
15467×
                    load(&refs)?
1547
                };
15483×
                if contents.len() != refs.len() {
15490×
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
15503×
                }
15513×
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
155213×
            }
1553131×
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
15540×
            return Err(ObjectError::Schema(
15550×
                "a version 1 payload holds graphs inline".into(),
15560×
            ));
155738×
        }
1558
        // File graphs are independent; decode and build them in parallel.
155954×
        let graphs = parsed
156054×
            .par_iter()
1561215×
            .map(|(node, entry)| {
1562215×
                let graph = match fetched.get(node) {
15633×
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
1564212×
                    None => FileGraph::from_value(entry)?,
1565
                };
1566215×
                Ok((*node, graph))
1567215×
            })
156854×
            .collect::<Result<Vec<_>, ObjectError>>()?;
156954×
        st.files
1570215×
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
157154×
        Ok(st)
157260×
    }
1573
1574
    /// The graph blobs a payload names: empty for version 1.
15759×
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
15769×
        let v = cbor::decode(bytes)?;
15779×
        let m = o::map(&v, "checkpoint payload")?;
15789×
        let mut out = Vec::new();
157927×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
158027×
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
15816×
                out.push(o::oref(entry, "graph blob")?);
158221×
            }
1583
        }
15849×
        Ok(out)
15859×
    }
1586
1587
    /// Decode a checkpoint payload for history only: a version 2 payload's
1588
    /// graphs are noted, not read or built, and come later through
1589
    /// [`State::load_graphs`]. A version 1 payload holds them inline and is
1590
    /// decoded in full.
159142×
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
159242×
        let v = cbor::decode(bytes)?;
159342×
        let m = o::map(&v, "checkpoint payload")?;
159442×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
159542×
        if version != CHECKPOINT_INDEX_VERSION {
15961×
            return State::from_checkpoint_payload(bytes);
159741×
        }
159841×
        let mut st = State::payload_common(m)?;
159941×
        let mut deferred = crate::fasthash::FastMap::default();
1600139×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1601139×
            let e = o::array(f, "file")?;
1602139×
            if e.len() != 2 {
16030×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1604139×
            }
1605139×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1606139×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1607139×
            let base = match &e[1] {
16084×
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
1609135×
                other => DeferredBase::Inline(other.clone()),
1610
            };
1611139×
            deferred.insert(
1612139×
                node,
1613139×
                Arc::new(Deferred::from_body(DeferredBody {
1614139×
                    base: Some(base),
1615139×
                    ..DeferredBody::default()
1616139×
                })),
1617
            );
1618
        }
161941×
        st.deferred = Some(deferred);
162041×
        Ok(st)
162142×
    }
1622
1623
    /// Changes, tree and replaces of a payload of either version.
162499×
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
162599×
        let mut st = State::new();
1626488×
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
1627488×
            let e = o::array(c, "change meta")?;
1628488×
            if e.len() != 8 {
16290×
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
1630488×
            }
1631488×
            let hash = o::oref(&e[0], "hash")?;
1632488×
            let meta = ChangeMeta {
1633488×
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
1634488×
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
1635488×
                deps: o::array(&e[2], "deps")?
1636488×
                    .iter()
1637597×
                    .map(|d| o::oref(d, "dep"))
1638488×
                    .collect::<Result<Vec<_>, _>>()?,
1639488×
                message: o::text(&e[3], "message")?.to_owned(),
1640
                hlc: Hlc {
1641488×
                    wall_ms: o::uint(&e[4], "wall")?,
1642488×
                    logical: o::u32_(&e[5], "logical")?,
1643
                },
1644488×
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
1645488×
                author: o::oref(&e[7], "author")?,
1646
            };
1647488×
            st.changes.insert(hash, Arc::new(meta));
1648
        }
164999×
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
165099×
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
165124×
            if v.is_null() {
165212×
                Ok(None)
1653
            } else {
165412×
                o::oref(v, "blob").map(Some)
1655
            }
165624×
        };
165799×
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
165812×
            let e = o::array(r, "replace")?;
165912×
            if e.len() != 2 {
16600×
                return Err(ObjectError::Schema(
16610×
                    "replace: expected [node, records]".into(),
16620×
                ));
166312×
            }
166412×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
166512×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
166612×
            let mut recs = Vec::new();
166712×
            for rec in o::array(&e[1], "records")? {
166812×
                let x = o::array(rec, "record")?;
166912×
                if x.len() != 3 {
16700×
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
167112×
                }
167212×
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
1673
            }
167412×
            st.replaces.insert(node, recs);
1675
        }
167699×
        Ok(st)
167799×
    }
1678
16793324×
    pub fn validate(&self) -> Result<(), StateError> {
16808486×
        for (h, c) in &self.changes {
16818486×
            for d in &c.deps {
16825069×
                if !self.changes.contains_key(d) {
16830×
                    return Err(StateError::MissingDep(*d, *h));
16845069×
                }
1685
            }
1686
        }
16873324×
        Ok(())
16883324×
    }
1689
169011787×
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
169137859×
        for (i, op) in c.tree_ops.iter().enumerate() {
169237859×
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
169337859×
        }
169411787×
        if let Some(deferred) = self.deferred.as_mut() {
1695
            // History only: edits of files not built wait, grouped per file,
1696
            // with the texts of inserts read without their lines.
16976859×
            let mut texts = texts.into_iter();
16986859×
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
169937988×
            for e in c.edits {
170037988×
                match e {
1701613×
                    Edit::Replace { node, old, new } => {
1702613×
                        self.replaces.entry(node).or_default().push((h, old, new))
1703
                    }
170437375×
                    e => {
170537375×
                        let slot = per_node.entry(e.node()).or_default();
170635697×
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
170732143×
                            slot.1.extend(texts.next());
170832143×
                        }
170937375×
                        slot.0.push(e);
1710
                    }
1711
                }
1712
            }
171335390×
            for (node, (edits, node_texts)) in per_node {
171435390×
                match self.files.get_mut(&node) {
1715459×
                    Some(g) => {
1716459×
                        assert!(
1717459×
                            node_texts.is_empty(),
1718
                            "a change read without its text applied to a built graph"
1719
                        );
1720459×
                        apply_file_edits(Arc::make_mut(g), h, edits)
1721
                    }
172234931×
                    None => {
172334931×
                        let d = Arc::make_mut(deferred.entry(node).or_default());
172434931×
                        d.add(h, edits, node_texts);
172534931×
                        d.key = Default::default();
172634931×
                    }
1727
                }
1728
            }
17296859×
            return;
17304928×
        }
17314928×
        assert!(
17324928×
            texts.is_empty(),
1733
            "a change read without its text applied to a full state"
1734
        );
17354928×
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
17365740×
        for e in c.edits {
17375740×
            match e {
1738
                Edit::Insert {
17394214×
                    node,
17404214×
                    after,
17414214×
                    before,
17424214×
                    lines,
17434214×
                } => {
17444214×
                    let idx = counters.entry(node).or_default();
17454214×
                    let first = *idx;
17464214×
                    *idx += lines.len() as u32;
17474214×
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
17484214×
                        h,
17494214×
                        first,
17504214×
                        vertex(after.resolve(h)),
17514214×
                        vertex(before.resolve(h)),
17524214×
                        lines,
17534214×
                    );
17544214×
                }
17551418×
                Edit::Delete { node, atoms } => {
17561418×
                    let g = Arc::make_mut(self.files.entry(node).or_default());
17571767×
                    for r in atoms {
17581767×
                        g.delete(h, &r.resolve(h));
17591767×
                    }
1760
                }
1761108×
                Edit::Replace { node, old, new } => {
1762108×
                    self.replaces.entry(node).or_default().push((h, old, new));
1763108×
                }
1764
            }
1765
        }
176611787×
    }
1767
1768
    /// Transitive dependencies of `h`, excluding `h` itself.
17699166×
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
17709166×
        if let Some(c) = self.closure.lock().unwrap().sets.get(h) {
17717702×
            return c.clone();
17721464×
        }
17731464×
        let mut out = HashSet::new();
17741464×
        let mut stack: Vec<ChangeHash> = self
17751464×
            .changes
17761464×
            .get(h)
17771464×
            .map(|c| c.deps.clone())
17781464×
            .unwrap_or_default();
177916999×
        while let Some(d) = stack.pop() {
178015535×
            if out.insert(d) {
178111000×
                if let Some(c) = self.changes.get(&d) {
178211000×
                    stack.extend(c.deps.iter().copied());
178311000×
                }
17844535×
            }
1785
        }
17861464×
        let rc = Arc::new(out);
17871464×
        let mut memo = self.closure.lock().unwrap();
17881464×
        if memo.held + rc.len() > CLOSURE_MEMO_HASHES {
17890×
            memo.sets.clear();
17900×
            memo.held = 0;
17911464×
        }
17921464×
        memo.held += rc.len();
17931464×
        memo.sets.insert(*h, rc.clone());
17941464×
        rc
17959166×
    }
1796
1797
    /// `h`'s level (see `levels`), worked out for it and its ancestors not
1798
    /// yet known, without recursion: histories are deeper than a stack. An
1799
    /// unknown change has level 0.
1800404832×
    fn level(&self, h: &ChangeHash) -> u32 {
1801404832×
        let mut levels = self.levels.lock().unwrap();
1802404832×
        if let Some(l) = levels.get(h) {
1803402688×
            return *l;
18042144×
        }
18052144×
        let mut stack: Vec<(ChangeHash, bool)> = vec![(*h, false)];
18067011×
        while let Some((c, expanded)) = stack.pop() {
18074867×
            if levels.contains_key(&c) {
18081×
                continue;
18094866×
            }
18104866×
            let deps: &[ChangeHash] = self
18114866×
                .changes
18124866×
                .get(&c)
18134866×
                .map(|m| m.deps.as_slice())
18144866×
                .unwrap_or(&[]);
18154866×
            if expanded {
18162433×
                let l = deps
18172433×
                    .iter()
18183269×
                    .map(|d| levels.get(d).map_or(0, |l| l + 1))
18192433×
                    .max()
18202433×
                    .unwrap_or(0);
18212433×
                levels.insert(c, l);
1822
            } else {
18232433×
                stack.push((c, true));
18243269×
                for d in deps {
18253269×
                    if !levels.contains_key(d) {
1826290×
                        stack.push((*d, false));
18272979×
                    }
1828
                }
1829
            }
1830
        }
18312144×
        levels[h]
1832404832×
    }
1833
1834
    /// Changes that no other change depends on directly, sorted.
1835397×
    pub fn heads(&self) -> Vec<ChangeHash> {
1836397×
        let depended: crate::fasthash::FastSet<&ChangeHash> =
18373269×
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
1838397×
        let mut heads: Vec<ChangeHash> = self
1839397×
            .changes
1840397×
            .keys()
18413269×
            .filter(|h| !depended.contains(h))
1842397×
            .copied()
1843397×
            .collect();
1844397×
        heads.sort();
1845397×
        heads
1846397×
    }
1847
1848
    /// Maximal elements among `hashes` (those not in the closure of another),
1849
    /// sorted. One walk down from all of them at once: whatever the walk
1850
    /// reaches is below some other element. Linear in the changes reached,
1851
    /// where comparing every pair's closures was quadratic in the number
1852
    /// of heads, which a bookmark of independent changes has many of.
18538435×
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
18548435×
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
18558435×
        let mut below: crate::fasthash::FastSet<ChangeHash> = Default::default();
18568435×
        let mut stack: Vec<ChangeHash> = set
18578435×
            .iter()
185814758×
            .filter_map(|h| self.changes.get(h))
185912559×
            .flat_map(|c| c.deps.iter().copied())
18608435×
            .collect();
186120625×
        while let Some(d) = stack.pop() {
186212190×
            if below.insert(d) {
18636031×
                if let Some(c) = self.changes.get(&d) {
18646031×
                    stack.extend(c.deps.iter().copied());
18656031×
                }
18666159×
            }
1867
        }
186814758×
        set.into_iter().filter(|h| !below.contains(h)).collect()
18698435×
    }
1870
18710×
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
18720×
        self.graph(node)
18730×
            .map(|g| g.materialize(self))
18740×
            .unwrap_or_default()
18750×
    }
1876
1877
    /// Live lines of a text node in materialized order.
187820×
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
187920×
        let Some(g) = self.graph(node) else {
18802×
            return vec![];
1881
        };
188218×
        let m = g.materialize(self);
188318×
        m.live_atoms()
188418×
            .into_iter()
188544×
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
188618×
            .collect()
188720×
    }
1888
1889
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
1890842×
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
1891842×
        let mut live: Vec<ObjectRef> = self
1892842×
            .live_replaces(node)
1893842×
            .into_iter()
1894842×
            .map(|(_, n)| n)
1895842×
            .collect();
1896842×
        live.sort();
1897842×
        live.dedup();
1898842×
        live
1899842×
    }
1900
1901
    /// The replace records whose blob is live, with the change that set it
1902
    /// (spec §9.3). A record's blob is superseded by a later replacement of
1903
    /// that blob: one whose change depends on the record's change, as every
1904
    /// replacement depends on the change that made its old blob current
1905
    /// (§8.1). Two replacements that do not know each other both stay live
1906
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
1907
    /// A replacement without that dependency, from before the rule, is read
1908
    /// as before: it supersedes every record that did not come after it.
1909881×
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
1910881×
        let Some(rs) = self.replaces.get(node) else {
19110×
            return vec![];
1912
        };
1913881×
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
191411×
            rs.iter()
191544×
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && self.closure(s).contains(q))
191611×
        };
1917881×
        rs.iter()
19181020×
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
19191020×
            .filter(|(c, n)| {
19201298×
                !rs.iter().any(|(s, o, _)| {
19211298×
                    s != c
1922355×
                        && *o == Some(*n)
1923126×
                        && (self.closure(s).contains(c)
192411×
                            || (!knows_its_old(s, n) && !self.closure(c).contains(s)))
19251298×
                })
19261020×
            })
1927881×
            .collect()
1928881×
    }
1929
1930
    /// Short label for conflict markers: `changeid-prefix "message"`.
19311039×
    pub fn label(&self, h: &ChangeHash) -> String {
19321039×
        match self.changes.get(h) {
19331039×
            Some(c) => format!(
1934
                "{} \"{}\"",
19351039×
                c.change_id.short(8),
19361039×
                c.message.lines().next().unwrap_or("")
1937
            ),
19380×
            None => format!("#{}", h.short(12)),
1939
        }
19401039×
    }
1941
1942
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1943
    /// are not part of any conflict region in order, every live atom that is
1944
    /// part of a region, and every change that contributed to a region.
1945
    /// The changes that introduced the live blobs of an opaque node, for a
1946
    /// replace conflict (spec §9.3).
19472×
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
19482×
        let mut out: Vec<ChangeHash> = Vec::new();
19496×
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
19506×
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
19514×
                out.push(*h);
19524×
            }
1953
        }
19542×
        out.sort();
19552×
        out
19562×
    }
1957
195827×
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
195927×
        let mut out = ConflictRegions::default();
196027×
        let Some(g) = self.graph(node) else {
19610×
            return out;
1962
        };
196327×
        let m = g.materialize(self);
196427×
        let mut contributors = BTreeSet::new();
196563×
        for seg in &m.segments {
196663×
            match seg {
196736×
                crate::graph::Segment::Lines(atoms) => {
196836×
                    for a in atoms {
196936×
                        out.plain
197036×
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
197136×
                    }
1972
                }
197327×
                crate::graph::Segment::Conflict(sides) => {
197454×
                    for side in sides {
197556×
                        for a in side {
197656×
                            out.region_atoms.push(*a);
197756×
                            contributors.insert(a.0);
197856×
                        }
1979
                    }
1980
                }
19810×
                crate::graph::Segment::Zombie { deleted, inserted } => {
19820×
                    for a in deleted {
19830×
                        contributors.insert(a.0);
19840×
                        contributors.extend(g.deleters(a).copied());
19850×
                    }
19860×
                    for a in inserted {
19870×
                        out.region_atoms.push(*a);
19880×
                        contributors.insert(a.0);
19890×
                    }
1990
                }
1991
            }
1992
        }
199327×
        out.contributors = contributors.into_iter().collect();
199427×
        out
199527×
    }
1996
199724316×
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
199824316×
        let Some(g) = self.graph(node) else {
1999436×
            return (Vec::new(), Materialized::default());
2000
        };
200123880×
        let m = g.materialize(self);
200223880×
        let bytes = g.render(&m, &|h| self.label(h));
200323880×
        (bytes, m)
200424316×
    }
2005
2006
    /// Every file rendered, in parallel: files are independent, and
2007
    /// rendering them is most of a snapshot's cost in a large tree.
20082231×
    pub fn materialize(&self) -> Snapshot {
2009
        use rayon::prelude::*;
20102231×
        self.require_full("materializing a state");
20112231×
        let tree = self.tree.view();
20122231×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
20132231×
        let rendered: Vec<(String, FileState)> = entries
20142231×
            .par_iter()
201516489×
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
20162231×
            .collect();
20172231×
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
20182231×
        Snapshot {
20192231×
            tree,
20202231×
            files,
20212231×
            unrendered: BTreeSet::new(),
20222231×
        }
20232231×
    }
2024
2025
    /// Like [`State::materialize`], leaving the text files of nodes in
2026
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
2027
    /// file's graph must be loaded. For a caller that already knows those
2028
    /// files are unchanged and not conflicted.
202919×
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
203019×
        self.materialize_leaving(|_, e| skip.contains(&e.node))
203119×
    }
2032
2033
    /// As [`State::materialize_except`], rendering only the text files at
2034
    /// `render` (a few, where the caller knows the rest unchanged).
2035810×
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
20367831×
        self.materialize_leaving(|p, _| !render.contains(p))
2037810×
    }
2038
2039
    /// As [`State::materialize_except`], rendering only the text files of
2040
    /// the nodes in `render` (a change's edited files), without a set of
2041
    /// every other file to leave out.
2042208×
    pub fn materialize_nodes(&self, render: &HashSet<NodeId>) -> Snapshot {
2043552×
        self.materialize_leaving(|_, e| !render.contains(&e.node))
2044208×
    }
2045
20461037×
    fn materialize_leaving(
20471037×
        &self,
20481037×
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
20491037×
    ) -> Snapshot {
2050
        use rayon::prelude::*;
20511037×
        let tree = self.tree.view();
20521037×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
20531037×
        let rendered: Vec<(String, FileState, bool)> = entries
20541037×
            .par_iter()
20558729×
            .map(|(path, e)| {
20568729×
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
20574537×
                    let f = FileState {
20584537×
                        node: e.node,
20594537×
                        kind: e.kind,
20604537×
                        mode: e.mode,
20614537×
                        content: FileContent::Text {
20624537×
                            bytes: Vec::new(),
20634537×
                            materialized: Materialized::default(),
20644537×
                        },
20654537×
                    };
20664537×
                    (path.to_string(), f, true)
2067
                } else {
20684192×
                    (path.to_string(), self.file_state(e), false)
2069
                }
20708729×
            })
20711037×
            .collect();
2072
        // In the view's path order, so the maps are built without searching.
20731037×
        let unrendered: BTreeSet<String> = rendered
20741037×
            .iter()
20751037×
            .filter(|(_, _, skipped)| *skipped)
20764537×
            .map(|(p, _, _)| p.clone())
20771037×
            .collect();
20781037×
        let files: BTreeMap<String, FileState> =
20798729×
            rendered.into_iter().map(|(p, f, _)| (p, f)).collect();
20801037×
        Snapshot {
20811037×
            tree,
20821037×
            files,
20831037×
            unrendered,
20841037×
        }
20851037×
    }
2086
2087
    /// A snapshot of only `paths` (those `view` has), `view` being this
2088
    /// state's tree view: for a caller that works from what changed. The
2089
    /// graphs of those text files must be loaded.
209087×
    pub fn materialize_paths<'p>(
209187×
        &self,
209287×
        view: crate::tree::TreeView,
209387×
        paths: impl IntoIterator<Item = &'p str>,
209487×
    ) -> Snapshot {
209587×
        let files = paths
209687×
            .into_iter()
2097128×
            .filter_map(|p| Some((p.to_string(), self.file_state(view.entries.get(p)?))))
209887×
            .collect();
209987×
        Snapshot {
210087×
            tree: view,
210187×
            files,
210287×
            unrendered: BTreeSet::new(),
210387×
        }
210487×
    }
2105
2106
    /// The state of one tree entry: a directory, an opaque file's live
2107
    /// blobs, or a text file rendered from its graph (which must be built).
21080×
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
21090×
        self.file_state(e)
21100×
    }
2111
211220786×
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
2113
        {
211420786×
            let content = match e.kind {
21151438×
                NodeKind::Dir => FileContent::Dir,
2116100×
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
2117100×
                    blobs: self.live_blobs(&e.node),
2118100×
                },
2119541×
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
2120541×
                    blobs: self.live_blobs(&e.node),
2121541×
                },
2122
                NodeKind::File => {
212318707×
                    let (bytes, materialized) = self.render_file(&e.node);
212418707×
                    FileContent::Text {
212518707×
                        bytes,
212618707×
                        materialized,
212718707×
                    }
2128
                }
2129
            };
213020786×
            FileState {
213120786×
                node: e.node,
213220786×
                kind: e.kind,
213320786×
                mode: e.mode,
213420786×
                content,
213520786×
            }
2136
        }
213720786×
    }
2138
}
2139
2140
impl DepOracle for State {
2141
    /// Whether `a` depends on `b`, by a walk down from `a` that stops at
2142
    /// changes no higher than `b`: they cannot have `b` below them. Nothing
2143
    /// of the walk is kept, so asking about many pairs costs no more memory
2144
    /// than one walk (#25); a closure already memoised answers at once.
214567934×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
214667934×
        if a == b {
2147800×
            return true;
214867134×
        }
214967134×
        if let Some(c) = self.closure.lock().unwrap().sets.get(a) {
21500×
            return c.contains(b);
215167134×
        }
215267134×
        if !self.changes.contains_key(b) {
2153800×
            return false;
215466334×
        }
215566334×
        let lb = self.level(b);
215666334×
        if self.level(a) <= lb {
215736424×
            return false;
215829910×
        }
215929910×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
216029910×
        let mut stack: Vec<ChangeHash> = self
216129910×
            .changes
216229910×
            .get(a)
216329910×
            .map(|m| m.deps.clone())
216429910×
            .unwrap_or_default();
2165362385×
        while let Some(c) = stack.pop() {
2166342985×
            if c == *b {
216710510×
                return true;
2168332475×
            }
2169332475×
            if !seen.insert(c) || self.level(&c) <= lb {
2170224402×
                continue;
2171108073×
            }
2172108073×
            if let Some(m) = self.changes.get(&c) {
2173108073×
                stack.extend(m.deps.iter().copied());
2174108073×
            }
2175
        }
217619400×
        false
217767934×
    }
2178
}
2179
2180
#[cfg(test)]
2181
mod tests {
2182
    use super::*;
2183
    use crate::ids::ChangeId;
2184
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
2185
21862023×
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
21872023×
        let mut c = Change {
21882023×
            version: crate::objects::CHANGE_VERSION,
21892023×
            change_id: ChangeId::random(),
21902023×
            deps,
21912023×
            author: ObjectRef::ZERO,
21922023×
            hlc: Hlc {
21932023×
                wall_ms: 1,
21942023×
                logical: 0,
21952023×
            },
21962023×
            message: "m".into(),
21972023×
            tree_ops,
21982023×
            edits,
21992023×
            kind: ChangeKind::Normal,
22002023×
        };
22012023×
        c.normalize();
22022023×
        c
22032023×
    }
2204
2205
    #[test]
22061×
    fn build_edit_and_materialize() {
22071×
        let mut st = State::new();
22081×
        let f = NodeId::random();
22091×
        let c1 = change(
22101×
            vec![],
22111×
            vec![TreeOp::AddNode {
22121×
                node: f,
22131×
                kind: NodeKind::File,
22141×
                mode: Mode::TEXT,
22151×
                parent: NodeId::ROOT,
22161×
                name: "a.txt".into(),
22171×
            }],
22181×
            vec![Edit::Insert {
22191×
                node: f,
22201×
                after: AtomRef::Start,
22211×
                before: AtomRef::End,
22221×
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
22231×
            }],
2224
        );
22251×
        let h1 = st.add(c1).unwrap();
2226
        // Depends on h1: append a line and delete "one".
22271×
        let c2 = change(
22281×
            vec![h1],
22291×
            vec![],
22301×
            vec![
22311×
                Edit::Delete {
22321×
                    node: f,
22331×
                    atoms: vec![AtomRange {
22341×
                        change: h1,
22351×
                        from: 0,
22361×
                        to: 1,
22371×
                    }],
22381×
                },
22391×
                Edit::Insert {
22401×
                    node: f,
22411×
                    after: AtomRef::Atom {
22421×
                        change: h1,
22431×
                        index: 1,
22441×
                    },
22451×
                    before: AtomRef::End,
22461×
                    lines: vec![b"three\n".to_vec()].into(),
22471×
                },
2248
            ],
2249
        );
22501×
        let h2 = st.add(c2).unwrap();
22511×
        assert_eq!(st.heads(), vec![h2]);
22521×
        assert!(st.depends_on(&h2, &h1));
22531×
        assert!(!st.depends_on(&h1, &h2));
22541×
        let snap = st.materialize();
22551×
        assert!(!snap.is_conflicted());
22561×
        let a = &snap.files["a.txt"];
22571×
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
22581×
        assert_eq!(st.live_lines(&f).len(), 2);
22591×
    }
2260
2261
    #[test]
22621×
    fn missing_dependency_is_rejected() {
22631×
        let mut st = State::new();
22641×
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
22651×
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
22661×
    }
2267
2268
    #[test]
22691×
    fn self_references_and_multi_insert_indexing() {
22701×
        let mut st = State::new();
22711×
        let f = NodeId::random();
22721×
        let me = OpRef {
22731×
            change: ObjectRef::ZERO,
22741×
            index: 0,
22751×
        };
22761×
        let c1 = change(
22771×
            vec![],
22781×
            vec![
22791×
                TreeOp::AddNode {
22801×
                    node: f,
22811×
                    kind: NodeKind::File,
22821×
                    mode: Mode::TEXT,
22831×
                    parent: NodeId::ROOT,
22841×
                    name: "x".into(),
22851×
                },
22861×
                TreeOp::SetMode {
22871×
                    node: f,
22881×
                    old: me,
22891×
                    mode: Mode {
22901×
                        exec: true,
22911×
                        opaque: false,
22921×
                    },
22931×
                },
2294
            ],
22951×
            vec![
22961×
                Edit::Insert {
22971×
                    node: f,
22981×
                    after: AtomRef::Start,
22991×
                    before: AtomRef::End,
23001×
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
23011×
                },
2302
                // Insert between the two lines just inserted, using self references.
23031×
                Edit::Insert {
23041×
                    node: f,
23051×
                    after: AtomRef::Atom {
23061×
                        change: ObjectRef::ZERO,
23071×
                        index: 0,
23081×
                    },
23091×
                    before: AtomRef::Atom {
23101×
                        change: ObjectRef::ZERO,
23111×
                        index: 1,
23121×
                    },
23131×
                    lines: vec![b"b\n".to_vec()].into(),
23141×
                },
2315
            ],
2316
        );
23171×
        st.add(c1).unwrap();
23181×
        let snap = st.materialize();
23191×
        let x = &snap.files["x"];
23201×
        assert_eq!(
2321
            x.mode,
2322
            Mode {
2323
                exec: true,
2324
                opaque: false
2325
            }
2326
        );
23271×
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
23281×
    }
2329
2330
    #[test]
23311×
    fn opaque_replace_and_conflict() {
23321×
        let mut st = State::new();
23331×
        let f = NodeId::random();
23341×
        let b1 = ObjectRef([1; 32]);
23351×
        let b2 = ObjectRef([2; 32]);
23361×
        let b3 = ObjectRef([3; 32]);
23371×
        let h1 = st
23381×
            .add(change(
23391×
                vec![],
23401×
                vec![TreeOp::AddNode {
23411×
                    node: f,
23421×
                    kind: NodeKind::File,
23431×
                    mode: Mode::OPAQUE,
23441×
                    parent: NodeId::ROOT,
23451×
                    name: "img".into(),
23461×
                }],
23471×
                vec![Edit::Replace {
23481×
                    node: f,
23491×
                    old: None,
23501×
                    new: Some(b1),
23511×
                }],
2352
            ))
23531×
            .unwrap();
23541×
        assert_eq!(st.live_blobs(&f), vec![b1]);
23551×
        st.add(change(
23561×
            vec![h1],
23571×
            vec![],
23581×
            vec![Edit::Replace {
23591×
                node: f,
23601×
                old: Some(b1),
23611×
                new: Some(b2),
23621×
            }],
2363
        ))
23641×
        .unwrap();
23651×
        st.add(change(
23661×
            vec![h1],
23671×
            vec![],
23681×
            vec![Edit::Replace {
23691×
                node: f,
23701×
                old: Some(b1),
23711×
                new: Some(b3),
23721×
            }],
2373
        ))
23741×
        .unwrap();
23751×
        let snap = st.materialize();
23761×
        assert!(snap.is_conflicted());
23771×
        assert!(
23781×
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2379
        );
23801×
    }
2381
2382
    #[test]
23831×
    fn checkpoint_payload_round_trip_and_replay() {
23841×
        let mut st = State::new();
23851×
        let f = NodeId::random();
23861×
        let h1 = st
23871×
            .add(change(
23881×
                vec![],
23891×
                vec![TreeOp::AddNode {
23901×
                    node: f,
23911×
                    kind: NodeKind::File,
23921×
                    mode: Mode::TEXT,
23931×
                    parent: NodeId::ROOT,
23941×
                    name: "a".into(),
23951×
                }],
23961×
                vec![Edit::Insert {
23971×
                    node: f,
23981×
                    after: AtomRef::Start,
23991×
                    before: AtomRef::End,
24001×
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
24011×
                }],
2402
            ))
24031×
            .unwrap();
24041×
        let h2 = st
24051×
            .add(change(
24061×
                vec![h1],
24071×
                vec![],
24081×
                vec![Edit::Delete {
24091×
                    node: f,
24101×
                    atoms: vec![AtomRange {
24111×
                        change: h1,
24121×
                        from: 0,
24131×
                        to: 1,
24141×
                    }],
24151×
                }],
2416
            ))
24171×
            .unwrap();
24181×
        let payload = st.checkpoint_payload();
24191×
        let back = State::from_checkpoint_payload(&payload).unwrap();
24201×
        assert_eq!(back.len(), 2);
24211×
        assert_eq!(back.heads(), vec![h2]);
24221×
        assert_eq!(back.get(&h1).unwrap().message, "m");
24231×
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2424
        // Replaying a further change onto the restored state equals a full build.
24251×
        let c3 = change(
24261×
            vec![h2],
24271×
            vec![],
24281×
            vec![Edit::Insert {
24291×
                node: f,
24301×
                after: AtomRef::Atom {
24311×
                    change: h1,
24321×
                    index: 1,
24331×
                },
24341×
                before: AtomRef::End,
24351×
                lines: vec![b"3\n".to_vec()].into(),
24361×
            }],
2437
        );
24381×
        let mut full = st.clone();
24391×
        full.add(c3.clone()).unwrap();
24401×
        let mut restored = back;
24411×
        restored.add(c3).unwrap();
24421×
        let (a, b) = (full.materialize(), restored.materialize());
24431×
        assert_eq!(
24441×
            a.files.keys().collect::<Vec<_>>(),
24451×
            b.files.keys().collect::<Vec<_>>()
2446
        );
24471×
        assert_eq!(a.files["a"].content, b.files["a"].content);
24481×
        assert!(
24491×
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2450
        );
24511×
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
24521×
    }
2453
2454
    /// History-only states (O10f): the same state as a full load once its
2455
    /// graphs are built, by replay and from a version 2 checkpoint with
2456
    /// later changes; unloaded graphs are never read as empty.
2457
    #[test]
24581×
    fn graph_keys_change_exactly_when_a_graph_does() {
24591×
        let (f, g) = (NodeId::random(), NodeId::random());
24601×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
24612×
            node,
24622×
            kind: NodeKind::File,
2463
            mode: Mode::TEXT,
2464
            parent: NodeId::ROOT,
24652×
            name: name.into(),
24662×
        };
24671×
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
24684×
            node,
24694×
            after: AtomRef::Start,
24704×
            before: AtomRef::End,
24714×
            lines: vec![line.to_vec()].into(),
24724×
        };
24731×
        let c1 = change(
24741×
            vec![],
24751×
            vec![add(f, "f"), add(g, "g")],
24761×
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2477
        );
24781×
        let h1 = c1.hash();
24791×
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
24801×
        let h2 = c2.hash();
24811×
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
24826×
        let load = |cs: &[&Change]| {
24836×
            let mut st = State::new_history_only();
248410×
            for c in cs {
248510×
                st.add((*c).clone()).unwrap();
248610×
            }
24876×
            st
24886×
        };
24891×
        let s1 = load(&[&c1]);
24901×
        let s2 = load(&[&c1, &c2]);
24911×
        let s3 = load(&[&c1, &c2, &c3]);
249218×
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
24931×
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
24941×
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
24951×
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
24961×
        assert_ne!(key(&s2, &f), key(&s3, &f));
24971×
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
24981×
        let mut built = load(&[&c1]);
24991×
        built
25001×
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
25011×
            .unwrap();
25021×
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
25031×
        let mut full = State::new();
25041×
        full.add(c1.clone()).unwrap();
25051×
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2506
2507
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2508
        // or inline values: stable across loads, changed by later edits.
25091×
        let graphs = full.checkpoint_file_graphs();
25101×
        let index = full.checkpoint_index(&graphs, |enc| {
25110×
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
25120×
        });
25138×
        let cp = |extra: &[&Change]| {
25148×
            let mut st = State::from_checkpoint_history(&index).unwrap();
25158×
            for c in extra {
25165×
                st.add((*c).clone()).unwrap();
25175×
            }
25188×
            st
25198×
        };
25201×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
25211×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
25221×
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
25231×
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2524
2525
        // Partial rendering: skipped files are listed and empty, the others
2526
        // render as in a full state.
25271×
        let mut part = load(&[&c1, &c2]);
25281×
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
25291×
            .unwrap();
25301×
        let snap = part.materialize_except(&[f].into_iter().collect());
25311×
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
25321×
        let mut whole = State::new();
25331×
        whole.add(c1.clone()).unwrap();
25341×
        whole.add(c2.clone()).unwrap();
25351×
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
25361×
        assert!(
25371×
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2538
        );
25391×
    }
2540
2541
    #[test]
25421×
    fn history_only_states_build_the_same_graphs_on_demand() {
25431×
        let small = NodeId::random();
25441×
        let big = NodeId::random();
25451×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
25462×
            node,
25472×
            kind: NodeKind::File,
2548
            mode: Mode::TEXT,
2549
            parent: NodeId::ROOT,
25502×
            name: name.into(),
25512×
        };
25521×
        let lines: crate::lines::Lines = (0..300)
2553300×
            .map(|i| format!("line {i}\n").into_bytes())
25541×
            .collect();
25551×
        let c1 = change(
25561×
            vec![],
25571×
            vec![add(small, "small"), add(big, "big")],
25581×
            vec![
25591×
                Edit::Insert {
25601×
                    node: small,
25611×
                    after: AtomRef::Start,
25621×
                    before: AtomRef::End,
25631×
                    lines: vec![b"x\n".to_vec()].into(),
25641×
                },
25651×
                Edit::Insert {
25661×
                    node: big,
25671×
                    after: AtomRef::Start,
25681×
                    before: AtomRef::End,
25691×
                    lines,
25701×
                },
2571
            ],
2572
        );
25731×
        let h1 = c1.hash();
25741×
        let c2 = change(
25751×
            vec![h1],
25761×
            vec![],
25771×
            vec![
25781×
                Edit::Delete {
25791×
                    node: big,
25801×
                    atoms: vec![AtomRange {
25811×
                        change: h1,
25821×
                        from: 2,
25831×
                        to: 9,
25841×
                    }],
25851×
                },
25861×
                Edit::Insert {
25871×
                    node: big,
25881×
                    after: AtomRef::Atom {
25891×
                        change: h1,
25901×
                        index: 20,
25911×
                    },
25921×
                    before: AtomRef::Atom {
25931×
                        change: h1,
25941×
                        index: 21,
25951×
                    },
25961×
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
25971×
                },
25981×
                Edit::Insert {
25991×
                    node: small,
26001×
                    after: AtomRef::Atom {
26011×
                        change: h1,
26021×
                        index: 0,
26031×
                    },
26041×
                    before: AtomRef::End,
26051×
                    lines: vec![b"y\n".to_vec()].into(),
26061×
                },
2607
            ],
2608
        );
26091×
        let h2 = c2.hash();
26101×
        let c3 = change(
26111×
            vec![h2],
26121×
            vec![],
26131×
            vec![Edit::Delete {
26141×
                node: small,
26151×
                atoms: vec![AtomRange {
26161×
                    change: h1,
26171×
                    from: 0,
26181×
                    to: 1,
26191×
                }],
26201×
            }],
2621
        );
2622
26231×
        let mut full = State::new();
26243×
        for c in [&c1, &c2, &c3] {
26253×
            full.add(c.clone()).unwrap();
26263×
        }
2627
        // By replay: nothing built until asked, then exactly the full graphs.
26281×
        let mut hist = State::new_history_only();
26293×
        for c in [&c1, &c2, &c3] {
26303×
            hist.add(c.clone()).unwrap();
26313×
        }
26321×
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
26331×
        assert_eq!(hist.len(), 3);
26341×
        hist.load_graphs(
26351×
            &[big],
26360×
            |_| unreachable!("no checkpoint"),
26370×
            |_| unreachable!(),
2638
        )
26391×
        .unwrap();
26401×
        assert_eq!(
26411×
            hist.render_file(&big).0,
26421×
            full.render_file(&big).0,
2643
            "one file on its own"
2644
        );
26451×
        assert!(!hist.is_full());
26461×
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
26471×
            .unwrap();
26481×
        assert!(hist.is_full());
26491×
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2650
2651
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
26521×
        let mut base = State::new();
26531×
        base.add(c1.clone()).unwrap();
26541×
        base.add(c2.clone()).unwrap();
26551×
        let graphs = base.checkpoint_file_graphs();
26561×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
26571×
        let index = base.checkpoint_index(&graphs, |enc| {
26581×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
26591×
            blobs.insert(r, enc.to_vec());
26601×
            r
26611×
        });
26621×
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
26631×
        from_cp.add(c3.clone()).unwrap();
26641×
        assert!(!from_cp.is_full());
26651×
        let mut fetched = 0;
26661×
        from_cp
26671×
            .load_graphs(
26681×
                &[small, big],
26691×
                |refs| {
26701×
                    fetched += refs.len();
26711×
                    refs.iter()
26721×
                        .map(|r| {
26731×
                            blobs
26741×
                                .get(r)
26751×
                                .cloned()
26761×
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
26771×
                        })
26781×
                        .collect()
26791×
                },
26800×
                |_| unreachable!(),
2681
            )
26821×
            .unwrap();
26831×
        assert_eq!(
2684
            fetched, 1,
2685
            "the large graph's blob, in one batch; the small one was inline"
2686
        );
26871×
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
26881×
    }
2689
2690
    #[test]
2691
    #[should_panic(expected = "was not loaded")]
26921×
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
26931×
        let f = NodeId::random();
26941×
        let mut st = State::new_history_only();
26951×
        st.add(change(
26961×
            vec![],
26971×
            vec![TreeOp::AddNode {
26981×
                node: f,
26991×
                kind: NodeKind::File,
27001×
                mode: Mode::TEXT,
27011×
                parent: NodeId::ROOT,
27021×
                name: "a".into(),
27031×
            }],
27041×
            vec![Edit::Insert {
27051×
                node: f,
27061×
                after: AtomRef::Start,
27071×
                before: AtomRef::End,
27081×
                lines: vec![b"a\n".to_vec()].into(),
27091×
            }],
2710
        ))
27111×
        .unwrap();
27121×
        st.render_file(&f);
27131×
    }
2714
2715
    #[test]
2716
    #[should_panic(expected = "needs every file graph")]
27171×
    fn materializing_a_history_only_state_is_refused() {
27181×
        let f = NodeId::random();
27191×
        let mut st = State::new_history_only();
27201×
        st.add(change(
27211×
            vec![],
27221×
            vec![TreeOp::AddNode {
27231×
                node: f,
27241×
                kind: NodeKind::File,
27251×
                mode: Mode::TEXT,
27261×
                parent: NodeId::ROOT,
27271×
                name: "a".into(),
27281×
            }],
27291×
            vec![Edit::Insert {
27301×
                node: f,
27311×
                after: AtomRef::Start,
27321×
                before: AtomRef::End,
27331×
                lines: vec![b"a\n".to_vec()].into(),
27341×
            }],
2735
        ))
27361×
        .unwrap();
27371×
        st.materialize();
27381×
    }
2739
2740
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
2741
    /// blob; the state read back is the same as from version 1.
2742
    #[test]
27431×
    fn checkpoint_index_round_trip_matches_version_1() {
27441×
        let mut st = State::new();
27451×
        let small = NodeId::random();
27461×
        let big = NodeId::random();
27471×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
27482×
            node,
27492×
            kind: NodeKind::File,
2750
            mode: Mode::TEXT,
2751
            parent: NodeId::ROOT,
27522×
            name: name.into(),
27532×
        };
27541×
        let big_lines: crate::lines::Lines = (0..400)
2755400×
            .map(|i| format!("line {i} of a long file\n").into_bytes())
27561×
            .collect();
27571×
        let h1 = st
27581×
            .add(change(
27591×
                vec![],
27601×
                vec![add(small, "small"), add(big, "big")],
27611×
                vec![
27621×
                    Edit::Insert {
27631×
                        node: small,
27641×
                        after: AtomRef::Start,
27651×
                        before: AtomRef::End,
27661×
                        lines: vec![b"x\n".to_vec()].into(),
27671×
                    },
27681×
                    Edit::Insert {
27691×
                        node: big,
27701×
                        after: AtomRef::Start,
27711×
                        before: AtomRef::End,
27721×
                        lines: big_lines,
27731×
                    },
2774
                ],
2775
            ))
27761×
            .unwrap();
27771×
        st.add(change(
27781×
            vec![h1],
27791×
            vec![],
27801×
            vec![Edit::Delete {
27811×
                node: big,
27821×
                atoms: vec![AtomRange {
27831×
                    change: h1,
27841×
                    from: 3,
27851×
                    to: 7,
27861×
                }],
27871×
            }],
2788
        ))
27891×
        .unwrap();
2790
27911×
        let graphs = st.checkpoint_file_graphs();
27921×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
27931×
        let index = st.checkpoint_index(&graphs, |enc| {
27941×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
27951×
            blobs.insert(r, enc.to_vec());
27961×
            r
27971×
        });
27981×
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
27991×
        assert_eq!(
28001×
            State::checkpoint_graph_refs(&index).unwrap(),
28011×
            blobs.keys().copied().collect::<Vec<_>>()
2802
        );
28031×
        assert!(
28041×
            State::checkpoint_graph_refs(&st.checkpoint_payload())
28051×
                .unwrap()
28061×
                .is_empty(),
2807
            "version 1 names none"
2808
        );
28091×
        assert!(index.len() < st.checkpoint_payload().len());
2810
28111×
        let back = State::from_checkpoint(&index, |refs| {
28121×
            refs.iter()
28131×
                .map(|r| {
28141×
                    blobs
28151×
                        .get(r)
28161×
                        .cloned()
28171×
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
28181×
                })
28191×
                .collect()
28201×
        })
28211×
        .unwrap();
28221×
        assert_eq!(
28231×
            back.checkpoint_payload(),
28241×
            st.checkpoint_payload(),
2825
            "the same state as version 1"
2826
        );
28271×
        assert_eq!(
28281×
            back.materialize().files["big"].content,
28291×
            st.materialize().files["big"].content
2830
        );
2831
        // Deterministic: the same state gives the same index.
28321×
        assert_eq!(
28331×
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
28341×
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
28351×
            }),
2836
            index
2837
        );
2838
        // A missing graph blob is an error, not an empty file.
28391×
        assert!(
28401×
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
2841
        );
28421×
        assert!(
28431×
            State::from_checkpoint_payload(&index).is_err(),
2844
            "version 2 needs its blobs"
2845
        );
2846
        // Version 1 payloads still read, and unknown versions do not.
28471×
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
28481×
        let mut v3 = cbor::decode(&index).unwrap();
28491×
        if let Value::Map(m) = &mut v3 {
28501×
            m.insert(0, Value::Uint(3));
28511×
        }
28521×
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
28531×
    }
2854
2855
    #[test]
28561×
    fn maximal_elements() {
28571×
        let mut st = State::new();
28581×
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
28591×
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
28601×
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
28611×
        let mut m = st.maximal(&[h1, h2, h3]);
28621×
        m.sort();
28631×
        let mut want = vec![h2, h3];
28641×
        want.sort();
28651×
        assert_eq!(m, want);
28661×
        assert_eq!(st.heads(), want);
28671×
    }
2868
2869
    /// The bounded walk of `depends_on` agrees with the closure on random
2870
    /// graphs, and the memo stays within its bound.
2871
    #[test]
28721×
    fn depends_on_matches_the_closure() {
2873
        use rand::{Rng, SeedableRng};
28741×
        let mut rng = rand::rngs::StdRng::seed_from_u64(11);
28751×
        for _ in 0..10 {
287610×
            let mut st = State::new();
287710×
            let mut all: Vec<ChangeHash> = Vec::new();
287810×
            for _ in 0..80 {
2879800×
                let deps: Vec<ChangeHash> =
288031600×
                    all.iter().copied().filter(|_| rng.gen_bool(0.06)).collect();
2881800×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2882
            }
288310×
            let unknown = ObjectRef([0xee; 32]);
2884800×
            for a in &all {
2885800×
                let want = st.closure(a).clone();
2886800×
                st.closure.lock().unwrap().sets.clear();
2887800×
                st.closure.lock().unwrap().held = 0;
288864800×
                for b in all.iter().chain([&unknown]) {
288964800×
                    assert_eq!(
289064800×
                        st.depends_on(a, b),
289164800×
                        a == b || want.contains(b),
2892
                        "{a:?} on {b:?}"
2893
                    );
2894
                }
2895
            }
289610×
            assert!(st.closure.lock().unwrap().held <= CLOSURE_MEMO_HASHES);
2897
        }
28981×
    }
2899
2900
    /// The one-walk `maximal` agrees with the definition (not in the
2901
    /// closure of another element) on random graphs, with repeated and
2902
    /// unknown hashes among the input.
2903
    #[test]
29041×
    fn maximal_matches_its_definition() {
2905
        use rand::{Rng, SeedableRng};
29061×
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
29071×
        for _ in 0..20 {
290820×
            let mut st = State::new();
290920×
            let mut all: Vec<ChangeHash> = Vec::new();
291020×
            for _ in 0..60 {
29111200×
                let deps: Vec<ChangeHash> =
291235400×
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
29131200×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2914
            }
291520×
            let mut pick: Vec<ChangeHash> =
29161200×
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
291720×
            pick.extend(pick.clone().into_iter().take(3));
291820×
            pick.push(ObjectRef([0xee; 32]));
291920×
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
292020×
            let want: Vec<ChangeHash> = set
292120×
                .iter()
29228366×
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
292320×
                .copied()
292420×
                .collect();
292520×
            assert_eq!(st.maximal(&pick), want);
292620×
            assert_eq!(st.maximal(&all), st.heads());
2927
        }
29281×
    }
2929
}