OXYGENHUB

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

2077 of 2234 lines run, 435 of 631 functions · run #264 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;
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`]).
451446×
    pub(crate) fn write_flat(&self, w: &mut crate::flat::Writer) {
461446×
        w.fixed(&self.change_id.0);
471446×
        w.count(self.deps.len());
481446×
        for d in &self.deps {
49973×
            w.object(d);
50973×
        }
511446×
        w.object(&self.author);
521446×
        w.u64(self.hlc.wall_ms);
531446×
        w.u32(self.hlc.logical);
541446×
        w.bytes(self.message.as_bytes());
551446×
        w.u8(self.kind.tag() as u8);
561446×
    }
57
581618×
    pub(crate) fn read_flat(r: &mut crate::flat::Reader) -> Result<ChangeMeta, ObjectError> {
591618×
        let change_id = crate::ids::ChangeId(r.fixed::<16>()?);
601618×
        let mut deps = Vec::new();
611618×
        for _ in 0..r.count()? {
62698×
            deps.push(r.object()?);
63
        }
64
        Ok(ChangeMeta {
651618×
            change_id,
661618×
            deps,
671618×
            author: r.object()?,
68
            hlc: Hlc {
691618×
                wall_ms: r.u64()?,
701618×
                logical: r.u32()?,
71
            },
721618×
            message: r.text()?,
731618×
            kind: ChangeKind::from_tag(r.u8()? as u64)?,
74
        })
751618×
    }
76
7714878×
    pub fn of(c: &Change) -> ChangeMeta {
7814878×
        ChangeMeta {
7914878×
            change_id: c.change_id,
8014878×
            deps: c.deps.clone(),
8114878×
            author: c.author,
8214878×
            hlc: c.hlc,
8314878×
            message: c.message.clone(),
8414878×
            kind: c.kind,
8514878×
        }
8614878×
    }
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: std::sync::RwLock<ClosureMemo>,
106
    /// Each change's level: 0 with no dependencies, else one more than its
107
    /// highest dependency. A change can only depend on changes of lower
108
    /// level, which bounds the walk [`DepOracle::depends_on`] does.
109
    levels: std::sync::RwLock<crate::fasthash::FastMap<ChangeHash, u32>>,
110
    /// `None` for a full state. For a history-only state (loaded for its
111
    /// changes and tree), the file graphs not built yet, by node: `files`
112
    /// holds only those loaded with [`State::load_graphs`].
113
    deferred: Option<crate::fasthash::FastMap<NodeId, Arc<Deferred>>>,
114
}
115
116
use crate::objects::TextRef;
117
118
/// A file graph a history-only state has not built: its base from a
119
/// version 2 checkpoint, if any, and the edits of later changes in the
120
/// order they were applied (spec §11). Building it later gives the same
121
/// graph, since graph construction does not depend on order (§8).
122
///
123
/// Read from a state index, it stays in the index, unread, until first
124
/// used: a command that builds a few files reads and checks only their
125
/// histories (oxygen#94).
126
#[derive(Clone, Default)]
127
struct Deferred {
128
    /// The history: `raw` read and decoded, with `more` after it. An
129
    /// error when `raw` does not match its hash.
130
    body: std::sync::OnceLock<Result<DeferredBody, String>>,
131
    /// The history as an index holds it, not read yet.
132
    raw: Option<RawHistory>,
133
    /// Changes added since the index was read, kept beside `raw`, so that
134
    /// adding one neither reads nor decodes the history.
135
    more: Vec<(ChangeHash, Vec<Edit>)>,
136
    more_texts: Vec<TextRef>,
137
    /// Its graph key, once worked out (or read from an index); reset by
138
    /// any edit added.
139
    key: std::sync::OnceLock<[u8; 32]>,
140
}
141
142
/// Where a state index's file histories are: the index file itself, read
143
/// on first use, or bytes in memory.
144
#[derive(Clone)]
145
pub enum Histories {
146
    Bytes(Arc<Vec<u8>>),
147
    /// The file, where its histories start, and how many bytes they take.
148
    File(Arc<std::fs::File>, u64, u64),
149
}
150
151
impl Histories {
15216722×
    fn len(&self) -> u64 {
15316722×
        match self {
1544564×
            Histories::Bytes(b) => b.len() as u64,
15512158×
            Histories::File(_, _, len) => *len,
156
        }
15716722×
    }
158
15921868×
    fn read(&self, at: u64, len: usize) -> std::io::Result<Vec<u8>> {
16021868×
        match self {
1614564×
            Histories::Bytes(b) => Ok(b[at as usize..at as usize + len].to_vec()),
16217304×
            Histories::File(f, start, _) => {
16317304×
                let mut buf = vec![0u8; len];
16417304×
                read_exact_at(f, &mut buf, start + at)?;
16517304×
                Ok(buf)
166
            }
167
        }
16821868×
    }
169
}
170
171
#[cfg(unix)]
17217304×
fn read_exact_at(f: &std::fs::File, buf: &mut [u8], at: u64) -> std::io::Result<()> {
17317304×
    std::os::unix::fs::FileExt::read_exact_at(f, buf, at)
17417304×
}
175
176
#[cfg(windows)]
177
fn read_exact_at(f: &std::fs::File, mut buf: &mut [u8], mut at: u64) -> std::io::Result<()> {
178
    while !buf.is_empty() {
179
        match std::os::windows::fs::FileExt::seek_read(f, buf, at)? {
180
            0 => return Err(std::io::ErrorKind::UnexpectedEof.into()),
181
            n => {
182
                buf = &mut buf[n..];
183
                at += n as u64;
184
            }
185
        }
186
    }
187
    Ok(())
188
}
189
190
/// One file's history in a state index: where it is and its hash.
191
#[derive(Clone)]
192
struct RawHistory {
193
    from: Histories,
194
    at: u64,
195
    len: usize,
196
    sum: [u8; 32],
197
}
198
199
impl RawHistory {
200
    /// The history's bytes, checked against the hash the index holds.
20121868×
    fn bytes(&self) -> Result<Vec<u8>, ObjectError> {
20221868×
        let damaged = |why: String| ObjectError::DamagedIndex(why);
20321868×
        let b = self
20421868×
            .from
20521868×
            .read(self.at, self.len)
20621868×
            .map_err(|e| damaged(format!("a file's history cannot be read: {e}")))?;
20721868×
        if *blake3::hash(&b).as_bytes() != self.sum {
2083×
            return Err(damaged("a file's history does not match its hash".into()));
20921865×
        }
21021865×
        Ok(b)
21121868×
    }
212
}
213
214
/// The closures kept, and how many hashes they hold in all.
215
#[derive(Default)]
216
struct ClosureMemo {
217
    sets: HashMap<ChangeHash, Arc<HashSet<ChangeHash>>>,
218
    held: usize,
219
}
220
221
/// The most hashes the closure memo holds before it starts again: a few
222
/// hundred megabytes at most.
223
const CLOSURE_MEMO_HASHES: usize = 4_000_000;
224
225
#[derive(Clone, Default)]
226
struct DeferredBody {
227
    base: Option<DeferredBase>,
228
    edits: Vec<(ChangeHash, Vec<Edit>)>,
229
    /// The text blob and line count of each insert in `edits` left without
230
    /// its lines, in order: read when the graph is built.
231
    texts: Vec<TextRef>,
232
}
233
234
impl Deferred {
235141×
    fn from_body(body: DeferredBody) -> Deferred {
236141×
        Deferred {
237141×
            body: std::sync::OnceLock::from(Ok(body)),
238141×
            ..Deferred::default()
239141×
        }
240141×
    }
241
242
    /// The history, read and checked on first use.
243101462×
    fn body(&self) -> Result<&DeferredBody, ObjectError> {
244101462×
        self.body
245101462×
            .get_or_init(|| {
24637272×
                let mut b = match &self.raw {
247
                    // Matching its hash, it is what `write_index` wrote: it
248
                    // decodes.
2495466×
                    Some(raw) => raw
2505466×
                        .bytes()
2515466×
                        .and_then(|b| State::read_deferred_body(&b))
2525466×
                        .map_err(|e| e.to_string())?,
25331806×
                    None => DeferredBody::default(),
254
                };
25537271×
                b.edits.extend(self.more.iter().cloned());
25637271×
                b.texts.extend(self.more_texts.iter().cloned());
25737271×
                Ok(b)
25837272×
            })
259101462×
            .as_ref()
260101462×
            .map_err(|e| ObjectError::DamagedIndex(e.clone()))
261101462×
    }
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.
26534805×
    fn add(&mut self, h: ChangeHash, edits: Vec<Edit>, texts: Vec<TextRef>) {
26634805×
        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;
27134803×
        }
272
        // No encoding to read, or decoded already: this cannot fail.
27334803×
        let b = self.body_mut().expect("a history in memory");
27434803×
        b.edits.push((h, edits));
27534803×
        b.texts.extend(texts);
27634805×
    }
277
27834803×
    fn body_mut(&mut self) -> Result<&mut DeferredBody, ObjectError> {
27934803×
        self.body()?;
28034803×
        self.raw = None;
28134803×
        self.more.clear();
28234803×
        self.more_texts.clear();
28334803×
        Ok(self
28434803×
            .body
28534803×
            .get_mut()
28634803×
            .and_then(|b| b.as_mut().ok())
28734803×
            .expect("decoded above"))
28834803×
    }
289
29022540×
    fn into_body(mut self) -> Result<DeferredBody, ObjectError> {
29122540×
        self.body()?;
29222539×
        Ok(self
29322539×
            .body
29422539×
            .take()
29522539×
            .and_then(|b| b.ok())
29622539×
            .expect("decoded above"))
29722540×
    }
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).
317844×
    pub fn write_index(&self) -> Option<Vec<u8>> {
318
        use crate::flat::Writer;
319844×
        let deferred = self.deferred.as_ref()?;
320844×
        if !self.files.is_empty() {
3210×
            return None;
322844×
        }
323
        // The changes first, as a block a reader can take on its own (see
324
        // [`State::read_index_changes`]).
325844×
        let mut w = Writer::default();
326844×
        w.fixed(Self::INDEX_MAGIC);
327844×
        let mut changes: Vec<(&ChangeHash, &Arc<ChangeMeta>)> = self.changes.iter().collect();
328844×
        changes.sort_by_key(|(h, _)| **h);
329844×
        w.count(changes.len());
330844×
        for (h, m) in changes {
331246×
            w.object(h);
332246×
            m.write_flat(&mut w);
333246×
        }
334844×
        let changes_block = std::mem::take(&mut w);
335844×
        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.
338844×
        let mut tw = Writer::default();
339844×
        self.tree.write_flat(&mut tw);
340844×
        w.bytes(&tw.0);
341844×
        let mut replaces: Vec<(&NodeId, &Vec<ReplaceRecord>)> = self.replaces.iter().collect();
342844×
        replaces.sort_by_key(|(n, _)| **n);
343844×
        w.count(replaces.len());
344844×
        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
        }
356844×
        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).
359844×
        let mut table = Writer::default();
360844×
        let mut histories: Vec<u8> = Vec::new();
361844×
        let mut nodes: Vec<(&NodeId, &Arc<Deferred>)> = deferred.iter().collect();
362844×
        nodes.sort_by_key(|(n, _)| **n);
363844×
        table.count(nodes.len());
36432792×
        for (n, d) in nodes {
36532792×
            let key = match d.key.get() {
36616402×
                Some(k) => *k,
367
                None => {
36816390×
                    let mut h = blake3::Hasher::new();
36916390×
                    h.update(b"oxy graph key 1\0");
37016390×
                    h.update(&n.0);
37116390×
                    let k = d.graph_key(h).ok()?;
37216390×
                    let _ = d.key.set(k);
37316390×
                    k
374
                }
375
            };
376
            // Unchanged since read: its bytes as they are, checked.
37732792×
            let bytes = match &d.raw {
37816402×
                Some(raw) if d.more.is_empty() => raw.bytes().ok()?,
37916390×
                _ => Self::write_deferred_body(d.body().ok()?)?,
380
            };
38132790×
            table.fixed(&n.0);
38232790×
            table.fixed(&key);
38332790×
            table.u64(histories.len() as u64);
38432790×
            table.u32(u32::try_from(bytes.len()).ok()?);
38532790×
            table.fixed(blake3::hash(&bytes).as_bytes());
38632790×
            histories.extend_from_slice(&bytes);
387
        }
388842×
        front.bytes(&table.0);
389842×
        let mut out = Writer::default();
390842×
        out.u64(front.0.len() as u64);
391842×
        out.fixed(&front.0);
392842×
        out.fixed(&histories);
393842×
        Some(out.0)
394844×
    }
395
396
    /// One file's history as an index encodes it; `None` when it holds
397
    /// text in memory, which an index does not.
39816390×
    fn write_deferred_body(d: &DeferredBody) -> Option<Vec<u8>> {
399
        use crate::flat::Writer;
40033582×
        let atom = |w: &mut Writer, a: &AtomRef| match a {
40116393×
            AtomRef::Start => w.u8(0),
40216505×
            AtomRef::End => w.u8(1),
403684×
            AtomRef::Atom { change, index } => {
404684×
                w.u8(2);
405684×
                w.object(change);
406684×
                w.u32(*index);
407684×
            }
40833582×
        };
40916390×
        let mut w = Writer::default();
4103×
        match &d.base {
41116387×
            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.
42416390×
        let mut texts = d.texts.iter();
42516390×
        let mut per_change: Vec<(&ChangeHash, &Vec<Edit>, Vec<&TextRef>)> = Vec::new();
42616533×
        for (c, edits) in &d.edits {
42716533×
            let n = edits
42816533×
                .iter()
42916791×
                .filter(|e| matches!(e, Edit::Insert { lines, .. } if lines.is_empty()))
43016533×
                .count();
43116533×
            per_change.push((c, edits, texts.by_ref().take(n).collect()));
432
        }
43316390×
        per_change.sort_by_key(|(c, _, _)| **c);
43416390×
        w.count(per_change.len());
43516533×
        for (c, edits, _) in &per_change {
43616533×
            w.object(c);
43716533×
            w.count(edits.len());
43816831×
            for e in edits.iter() {
43916831×
                match e {
440
                    Edit::Insert {
44116791×
                        node,
44216791×
                        after,
44316791×
                        before,
44416791×
                        lines,
445
                    } => {
44616791×
                        if !lines.is_empty() {
4470×
                            return None;
44816791×
                        }
44916791×
                        w.u8(0);
45016791×
                        w.fixed(&node.0);
45116791×
                        atom(&mut w, after);
45216791×
                        atom(&mut w, before);
453
                    }
45440×
                    Edit::Delete { node, atoms } => {
45540×
                        w.u8(1);
45640×
                        w.fixed(&node.0);
45740×
                        w.count(atoms.len());
458286×
                        for r in atoms {
459286×
                            w.object(&r.change);
460286×
                            w.u32(r.from);
461286×
                            w.u32(r.to);
462286×
                        }
463
                    }
4640×
                    Edit::Replace { .. } => return None,
465
                }
466
            }
467
        }
46816390×
        let texts: Vec<&TextRef> = per_change
46916390×
            .iter()
47016533×
            .flat_map(|(_, _, t)| t.iter().copied())
47116390×
            .collect();
47216390×
        w.count(texts.len());
47316791×
        for t in texts {
47416791×
            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
                }
48516791×
                TextRef::Inline { change, start, end } => {
48616791×
                    w.u8(1);
48716791×
                    w.object(change);
48816791×
                    w.u32(*start);
48916791×
                    w.u32(*end);
49016791×
                }
491
            }
492
        }
49316390×
        Some(w.0)
49416390×
    }
495
496
    /// The state an index holds (see [`State::write_index`]).
497193×
    pub fn read_index(bytes: &[u8]) -> Result<State, ObjectError> {
498193×
        let bad = || ObjectError::Schema("state index: truncated".into());
499193×
        let front_len =
500193×
            usize::try_from(crate::flat::Reader::new(bytes).u64()?).map_err(|_| bad())?;
501193×
        let front = bytes.get(8..8 + front_len).ok_or_else(bad)?;
502193×
        let histories = Histories::Bytes(Arc::new(bytes[8 + front_len..].to_vec()));
503193×
        Self::read_index_front(front, histories)
504193×
    }
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).
5091732×
    pub fn read_index_front(bytes: &[u8], histories: Histories) -> Result<State, ObjectError> {
510
        use crate::flat::Reader;
5111732×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
5121732×
        let mut r = Reader::new(bytes);
5131732×
        let mut st = State::new_history_only();
514
        {
5151732×
            let _t = crate::timing::phase("index: changes");
5161732×
            st.changes = Self::read_index_changes(r.bytes()?)?;
517
        }
5181732×
        let tree_bytes = r.bytes()?;
5191732×
        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
        }
5271732×
        let deferred_bytes = r.bytes()?;
5281732×
        if !r.at_end() {
5290×
            return Err(bad("trailing bytes"));
5301732×
        }
5311732×
        let (tree, deferred) = rayon::join(
5321732×
            || TreeGraph::read_flat(&mut Reader::new(tree_bytes)),
5331732×
            || Self::read_deferred(deferred_bytes, &histories),
534
        );
5351732×
        st.tree = tree?;
5361732×
        st.deferred = Some(deferred?);
5371732×
        Ok(st)
5381732×
    }
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).
5421887×
    pub fn read_index_changes(
5431887×
        bytes: &[u8],
5441887×
    ) -> Result<crate::fasthash::FastMap<ChangeHash, Arc<ChangeMeta>>, ObjectError> {
545
        use crate::flat::Reader;
5461887×
        let mut r = Reader::new(bytes);
5471887×
        if r.fixed::<18>()?.as_slice() != Self::INDEX_MAGIC {
5480×
            return Err(ObjectError::Schema("state index: not a state index".into()));
5491887×
        }
5501887×
        let n = r.count()?;
5511887×
        let mut changes = crate::fasthash::FastMap::default();
5521887×
        changes.reserve(n);
5531887×
        for _ in 0..n {
554160×
            let h = r.object()?;
555160×
            changes.insert(h, Arc::new(ChangeMeta::read_flat(&mut r)?));
556
        }
5571887×
        if !r.at_end() {
5580×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
5591887×
        }
5601887×
        Ok(changes)
5611887×
    }
562
563
    /// The deferred block: each node with its graph key and its body,
564
    /// left encoded (see [`Deferred`]).
5651732×
    fn read_deferred(
5661732×
        table: &[u8],
5671732×
        histories: &Histories,
5681732×
    ) -> Result<crate::fasthash::FastMap<NodeId, Arc<Deferred>>, ObjectError> {
569
        use crate::flat::Reader;
5701732×
        let _t = crate::timing::phase("index: deferred");
5711732×
        let mut r = Reader::new(table);
5721732×
        let mut deferred = crate::fasthash::FastMap::default();
5731732×
        let n = r.count()?;
5741732×
        deferred.reserve(n);
5751732×
        for _ in 0..n {
57616722×
            let id = NodeId(r.fixed::<16>()?);
57716722×
            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.
58016722×
            let (at, len, sum) = (r.u64()?, r.u32()? as usize, r.fixed::<32>()?);
58116722×
            if at
58216722×
                .checked_add(len as u64)
58316722×
                .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×
                ));
58816722×
            }
58916722×
            let d = Deferred {
59016722×
                raw: Some(RawHistory {
59116722×
                    from: histories.clone(),
59216722×
                    at,
59316722×
                    len,
59416722×
                    sum,
59516722×
                }),
59616722×
                key: std::sync::OnceLock::from(key),
59716722×
                ..Deferred::default()
59816722×
            };
59916722×
            deferred.insert(id, Arc::new(d));
600
        }
6011732×
        if !r.at_end() {
6020×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
6031732×
        }
6041732×
        Ok(deferred)
6051732×
    }
606
607
    /// One node's deferred history as the index encodes it.
6085465×
    fn read_deferred_body(bytes: &[u8]) -> Result<DeferredBody, ObjectError> {
609
        use crate::flat::Reader;
6105465×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
6115476×
        let node = |r: &mut Reader| -> Result<NodeId, ObjectError> { Ok(NodeId(r.fixed::<16>()?)) };
61210952×
        let atom = |r: &mut Reader| -> Result<AtomRef, ObjectError> {
61310952×
            Ok(match r.u8()? {
6145459×
                0 => AtomRef::Start,
6155476×
                1 => AtomRef::End,
616
                2 => AtomRef::Atom {
61717×
                    change: r.object()?,
61817×
                    index: r.u32()?,
619
                },
6200×
                _ => return Err(bad("atom")),
621
            })
62210952×
        };
6235465×
        let mut r = Reader::new(bytes);
6245465×
        let base = match r.u8()? {
6255459×
            0 => None,
6260×
            1 => Some(DeferredBase::Blob(r.object()?)),
6276×
            _ => Some(DeferredBase::Inline(cbor::decode(r.bytes()?)?)),
628
        };
6295465×
        let mut edits = Vec::new();
6305465×
        for _ in 0..r.count()? {
6315476×
            let c = r.object()?;
6325476×
            let mut es = Vec::new();
6335476×
            for _ in 0..r.count()? {
6345476×
                es.push(match r.u8()? {
635
                    0 => Edit::Insert {
6365476×
                        node: node(&mut r)?,
6375476×
                        after: atom(&mut r)?,
6385476×
                        before: atom(&mut r)?,
6395476×
                        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
            }
6565476×
            edits.push((c, es));
657
        }
6585465×
        let mut texts = Vec::new();
6595465×
        for _ in 0..r.count()? {
6605476×
            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 {
6715476×
                    change: r.object()?,
6725476×
                    start: r.u32()?,
6735476×
                    end: r.u32()?,
674
                },
675
            });
676
        }
6775465×
        if !r.at_end() {
6780×
            return Err(bad("trailing bytes in a file's history"));
6795465×
        }
6805465×
        Ok(DeferredBody { base, edits, texts })
6815465×
    }
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: Default::default(),
6931342×
            levels: Default::default(),
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 {
72113359×
    pub fn is_conflicted(&self) -> bool {
72213359×
        match &self.content {
72312476×
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
724243×
            FileContent::Opaque { blobs } => blobs.len() > 1,
725640×
            FileContent::Dir => false,
726
        }
72713359×
    }
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 {
7491870×
    pub fn is_conflicted(&self) -> bool {
75013066×
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
7511870×
    }
752
}
753
75460766×
fn vertex(r: AtomRef) -> Vertex {
75560766×
    match r {
75625646×
        AtomRef::Start => Vertex::Start,
75726754×
        AtomRef::End => Vertex::End,
7588366×
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
759
    }
76060766×
}
761
762
/// Replace self references in a tree op with the concrete change hash.
76337948×
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
76437948×
    match op {
765734×
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
766734×
            node: *node,
767734×
            placement: placement.resolve(me),
768734×
        },
769
        TreeOp::Move {
770170×
            node,
771170×
            old,
772170×
            parent,
773170×
            name,
774170×
        } => TreeOp::Move {
775170×
            node: *node,
776170×
            old: old.resolve(me),
777170×
            parent: *parent,
778170×
            name: name.clone(),
779170×
        },
78022×
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
78122×
            node: *node,
78222×
            old: old.resolve(me),
78322×
            mode: *mode,
78422×
        },
78537022×
        add @ TreeOp::AddNode { .. } => add.clone(),
786
    }
78737948×
}
788
789
/// Apply one change's edits of one file (inserts and deletes; replaces
790
/// live beside the graphs) to that file's graph.
79125419×
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`).
79325419×
    let order = g.take_order();
79425419×
    let mut inserts: Vec<(Vertex, Vertex, u32, u32)> = Vec::new();
79525419×
    let mut deleted: Vec<crate::graph::AtomKey> = Vec::new();
79625419×
    let mut next = 0u32;
79727512×
    for e in edits {
79827512×
        match e {
799
            Edit::Insert {
80026215×
                after,
80126215×
                before,
80226215×
                lines,
803
                ..
80426215×
            } => {
80526215×
                let first = next;
80626215×
                let count = lines.len() as u32;
80726215×
                next += count;
80826215×
                let (after, before) = (vertex(after.resolve(h)), vertex(before.resolve(h)));
80926215×
                inserts.push((after, before, first, count));
81026215×
                g.insert_owned(h, first, after, before, lines);
81126215×
            }
8121297×
            Edit::Delete { atoms, .. } => {
8132345×
                for r in atoms {
8142345×
                    let r = r.resolve(h);
8152389×
                    deleted.extend((r.from..r.to).map(|i| (r.change, i)));
8162345×
                    g.delete(h, &r);
817
                }
818
            }
8190×
            Edit::Replace { .. } => {}
820
        }
821
    }
82225419×
    if let Some(o) = order {
82368×
        g.keep_spliced(o, h, &inserts, &deleted);
82425351×
    }
82525419×
}
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).
8303488×
fn build_deferred(
8313488×
    taken: Vec<(NodeId, Deferred)>,
8323488×
    load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
8333488×
    read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
8343488×
) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
8353488×
    let mut taken: Vec<(NodeId, DeferredBody)> = taken
8363488×
        .into_iter()
83722540×
        .map(|(n, d)| Ok((n, d.into_body()?)))
8383488×
        .collect::<Result<_, ObjectError>>()?;
8393487×
    let mut refs: Vec<ObjectRef> = taken
8403487×
        .iter()
8413487×
        .filter_map(|(_, d)| match &d.base {
8426×
            Some(DeferredBase::Blob(r)) => Some(*r),
84322533×
            _ => None,
84422539×
        })
8453487×
        .collect();
846
    // Text blobs of inserts read without their lines, after the bases.
8473487×
    let bases = refs.len();
84822539×
    refs.extend(taken.iter().flat_map(|(_, d)| {
84925572×
        d.texts.iter().filter_map(|t| match t {
85070×
            TextRef::Blob(r, _, _) => Some(*r),
85125502×
            TextRef::Inline { .. } => None,
85225572×
        })
85322539×
    }));
854
    // And the encodings of changes whose inline inserts are needed,
855
    // each read once.
8563487×
    let reading = crate::timing::phase("graphs: read changes and blobs");
8573487×
    let mut changes: HashMap<ChangeHash, Arc<Vec<u8>>> = HashMap::new();
85825572×
    for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
85925572×
        if let TextRef::Inline { change, .. } = t {
86025502×
            if !changes.contains_key(change) {
8615664×
                changes.insert(*change, read_change(change)?);
86219838×
            }
86370×
        }
864
    }
8653487×
    let n_changes = changes.len();
8663487×
    drop(reading);
8673487×
    let reading = crate::timing::phase("graphs:   of which blobs");
8683487×
    let mut blobs = if refs.is_empty() {
8693416×
        Vec::new()
870
    } else {
87171×
        load(&refs)?
872
    };
8733484×
    if crate::timing::enabled() {
8742×
        eprintln!(
8752×
            "timing graphs: {} graphs, {n_changes} changes, {} blobs",
8762×
            taken.len(),
8772×
            refs.len()
8782×
        );
8793482×
    }
8803484×
    if blobs.len() != refs.len() {
8810×
        return Err(ObjectError::Schema("graph blobs: wrong count".into()));
8823484×
    }
8833484×
    drop(reading);
8843484×
    let lines = crate::timing::phase("graphs: hand out blobs");
8853484×
    let mut texts = blobs.split_off(bases).into_iter();
8863484×
    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>>);
8903484×
    let mut work: Vec<Work> = Vec::with_capacity(taken.len());
89122536×
    for (node, d) in taken.drain(..) {
89222536×
        let wanted = d
89322536×
            .texts
89422536×
            .iter()
89525570×
            .filter(|t| matches!(t, TextRef::Blob(..)))
89622536×
            .count();
89722536×
        let mine: Vec<Vec<u8>> = texts.by_ref().take(wanted).collect();
89822536×
        if mine.len() != wanted {
8990×
            return Err(ObjectError::Schema("text blobs: wrong count".into()));
90022536×
        }
90122536×
        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
            ),
90722531×
            _ => None,
908
        };
90922536×
        work.push((node, d, bytes, mine));
910
    }
9113484×
    drop(lines);
9123484×
    let _t = crate::timing::phase("graphs: lines and build");
913
    use rayon::prelude::*;
9143484×
    let changes = &changes;
9153484×
    let built: Vec<(NodeId, FileGraph)> = work
9163484×
        .into_par_iter()
91722536×
        .map(|(node, mut d, bytes, mine)| {
918
            // Fill in the lines of inserts read without them, in order.
91922536×
            let mut want = std::mem::take(&mut d.texts).into_iter();
92022536×
            let mut mine = mine.into_iter();
92124967×
            for (_, edits) in d.edits.iter_mut() {
92226631×
                for e in edits.iter_mut() {
92326631×
                    if let Edit::Insert { lines, .. } = e {
92425577×
                        if lines.is_empty() {
92525570×
                            *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
                                }
93225502×
                                Some(TextRef::Inline { change, start, end }) => {
93325502×
                                    let bytes = &changes[&change];
93425502×
                                    let range = bytes
93525502×
                                        .get(start as usize..end as usize)
93625502×
                                        .ok_or_else(|| {
9370×
                                            ObjectError::Schema(
9380×
                                                "an inline insert lies outside its change".into(),
9390×
                                            )
9400×
                                        })?;
94125502×
                                    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×
                        }
9501054×
                    }
951
                }
952
            }
95322536×
            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
                }
95822435×
                _ => FileGraph::default(),
959
            };
96024967×
            for (h, edits) in std::mem::take(&mut d.edits) {
96124967×
                apply_file_edits(&mut graph, h, edits);
96224967×
            }
96322536×
            Ok((node, graph))
96422536×
        })
9653484×
        .collect::<Result<_, ObjectError>>()?;
9663484×
    Ok(built)
9673488×
}
968
969
impl State {
970685×
    pub fn new() -> Self {
971685×
        Self::default()
972685×
    }
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.
9783327×
    pub fn new_history_only() -> Self {
9793327×
        State {
9803327×
            deferred: Some(Default::default()),
9813327×
            ..Self::default()
9823327×
        }
9833327×
    }
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.
9923131×
    pub fn is_history_only(&self) -> bool {
9933131×
        self.deferred.is_some()
9943131×
    }
995
996
    /// Whether this state holds every file graph.
9972632×
    pub fn is_full(&self) -> bool {
9982632×
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
9992632×
    }
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.
100324829×
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
100424829×
        if let Some(d) = &self.deferred {
10059922×
            assert!(
10069922×
                !d.contains_key(node),
1007
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
10081×
                node.short(12)
1009
            );
101014907×
        }
101124828×
        self.files.get(node).map(|g| g.as_ref())
101224828×
    }
1013
1014
    /// Operations over every file need every graph.
10152625×
    fn require_full(&self, what: &str) {
10162625×
        assert!(
10172625×
            self.is_full(),
1018
            "{what} needs every file graph; this state was loaded for history only"
1019
        );
10202624×
    }
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.
10253413×
    pub fn load_graphs(
10263413×
        &mut self,
10273413×
        nodes: &[NodeId],
10283413×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
10293413×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
10303413×
    ) -> Result<(), ObjectError> {
10313413×
        let Some(deferred) = self.deferred.as_mut() else {
10320×
            return Ok(());
1033
        };
10343413×
        let taken: Vec<(NodeId, Deferred)> = nodes
10353413×
            .iter()
103622700×
            .filter_map(|n| deferred.remove(n).map(|d| (*n, Arc::unwrap_or_clone(d))))
10373413×
            .collect();
10383413×
        let built = build_deferred(taken, load, read_change)?;
10393409×
        self.files
104022477×
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
10413409×
        Ok(())
10423413×
    }
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.
1095412×
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
10965966×
        for n in nodes {
10975966×
            self.files.remove(n);
10985966×
        }
1099412×
    }
1100
1101
    /// Build every graph a history-only state has not built, making it full.
11021713×
    pub fn load_all_graphs(
11031713×
        &mut self,
11041713×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
11051713×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
11061713×
    ) -> Result<(), ObjectError> {
11071713×
        let nodes: Vec<NodeId> = match &self.deferred {
11081713×
            Some(d) => d.keys().copied().collect(),
11090×
            None => return Ok(()),
1110
        };
11111713×
        self.load_graphs(&nodes, load, read_change)?;
11121713×
        self.deferred = None;
11131713×
        Ok(())
11141713×
    }
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.
11205820×
    pub fn single_text(&self, node: &NodeId) -> Option<TextRef> {
11215820×
        if self.files.contains_key(node) {
11220×
            return None;
11235820×
        }
1124
        // A history that cannot be read is no single text: building its
1125
        // graph reports why.
11265820×
        let d = self.deferred.as_ref()?.get(node)?.body().ok()?;
11275761×
        let [(_, edits)] = d.edits.as_slice() else {
1128233×
            return None;
1129
        };
1130
        let [Edit::Insert {
1131
            after: AtomRef::Start,
1132
            before: AtomRef::End,
11335528×
            lines,
1134
            ..
11355528×
        }] = edits.as_slice()
1136
        else {
11370×
            return None;
1138
        };
11395528×
        match (&d.base, d.texts.as_slice()) {
11405528×
            (None, [t]) if lines.is_empty() => Some(*t),
11410×
            _ => None,
1142
        }
11435820×
    }
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.
115228411×
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
115328411×
        let deferred = self.deferred.as_ref()?;
115428375×
        if self.files.contains_key(node) {
1155411×
            return None;
115627964×
        }
115727964×
        let mut h = blake3::Hasher::new();
115827964×
        h.update(b"oxy graph key 1\0");
1159
        // A change's edits are applied per node: the node is part of it.
116027964×
        h.update(&node.0);
116127964×
        let Some(d) = deferred.get(node) else {
1162
            // Never edited: the empty graph.
1163206×
            h.update(&[0]);
1164206×
            return Some(*h.finalize().as_bytes());
1165
        };
1166
        // A history that cannot be read has no key: the file is read.
116727758×
        if let Some(k) = d.key.get() {
116822180×
            return Some(*k);
11695578×
        }
11705578×
        let k = d.graph_key(h).ok()?;
11715578×
        Some(*d.key.get_or_init(|| k))
117228411×
    }
1173
11743273×
    pub fn len(&self) -> usize {
11753273×
        self.changes.len()
11763273×
    }
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.
124521968×
    fn graph_key(&self, mut h: blake3::Hasher) -> Result<[u8; 32], ObjectError> {
124621968×
        let d = self.body()?;
124713×
        match &d.base {
124821955×
            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
        };
125221968×
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
125321968×
        changes.sort();
125421968×
        changes.dedup();
125521968×
        h.update(&(changes.len() as u64).to_le_bytes());
125623323×
        for c in changes {
125723323×
            h.update(&c.0);
125823323×
        }
125921968×
        Ok(*h.finalize().as_bytes())
126021968×
    }
1261
}
1262
1263
impl State {
12640×
    pub fn is_empty(&self) -> bool {
12650×
        self.changes.is_empty()
12660×
    }
126712922×
    pub fn contains(&self, h: &ChangeHash) -> bool {
126812922×
        self.changes.contains_key(h)
126912922×
    }
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)> {
12743377×
        self.changes.iter().map(|(h, m)| (h, &**m))
12751335×
    }
127617270×
    pub fn tree(&self) -> &TreeGraph {
127717270×
        &self.tree
127817270×
    }
1279550×
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
1280550×
        self.graph(node)
1281550×
    }
1282
1283
    /// Add a change whose dependencies are already present.
12842811×
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
12852811×
        let h = change.hash();
12862811×
        self.add_hashed(h, change)
12872811×
    }
1288
1289
    /// [`State::add`] for a change whose hash `h` is already known (it was
1290
    /// just stored), so it is not encoded again.
12913430×
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
12923430×
        if self.changes.contains_key(&h) {
129337×
            return Ok(h);
12943393×
        }
12954874×
        for d in &change.deps {
12964874×
            if !self.changes.contains_key(d) {
12972×
                return Err(StateError::MissingDep(*d, h));
12984872×
            }
1299
        }
13003391×
        self.add_known(h, change, Vec::new());
13013391×
        Ok(h)
13023430×
    }
1303
1304
    /// Add a change in any order; call `validate` once all are in.
1305942×
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
1306942×
        let h = change.hash();
1307942×
        self.add_known(h, change, Vec::new());
1308942×
        h
1309942×
    }
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.
137311885×
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
137411885×
        if self.changes.contains_key(&h) {
13750×
            return;
137611885×
        }
137711885×
        let meta = ChangeMeta::of(&change);
137811885×
        self.apply_with(h, change, texts);
137911885×
        self.changes.insert(h, Arc::new(meta));
138011885×
        {
138111885×
            let mut m = self.closure.write().unwrap();
138211885×
            m.sets.clear();
138311885×
            m.held = 0;
138411885×
        }
138511885×
    }
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()
13981407×
                .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()
14502143×
                .map(|h| {
14512143×
                    let m = &self.changes[h];
14522143×
                    Value::Array(vec![
14532143×
                        Value::Bytes(h.0.to_vec()),
14542143×
                        Value::Bytes(m.change_id.0.to_vec()),
14552143×
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
14562143×
                        Value::Text(m.message.clone()),
14572143×
                        Value::Uint(m.hlc.wall_ms),
14582143×
                        Value::Uint(m.hlc.logical as u64),
14592143×
                        Value::Uint(m.kind.tag()),
14602143×
                        Value::Bytes(m.author.0.to_vec()),
1461
                    ])
14622143×
                })
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());
1525224×
        for f in entries {
1526224×
            let e = o::array(f, "file")?;
1527224×
            if e.len() != 2 {
15280×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1529224×
            }
1530224×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1531224×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1532224×
            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×
            }
1553134×
        } 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()
1561218×
            .map(|(node, entry)| {
1562218×
                let graph = match fetched.get(node) {
15633×
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
1564215×
                    None => FileGraph::from_value(entry)?,
1565
                };
1566218×
                Ok((*node, graph))
1567218×
            })
156854×
            .collect::<Result<Vec<_>, ObjectError>>()?;
156954×
        st.files
1570218×
            .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();
1626492×
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
1627492×
            let e = o::array(c, "change meta")?;
1628492×
            if e.len() != 8 {
16290×
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
1630492×
            }
1631492×
            let hash = o::oref(&e[0], "hash")?;
1632492×
            let meta = ChangeMeta {
1633492×
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
1634492×
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
1635492×
                deps: o::array(&e[2], "deps")?
1636492×
                    .iter()
1637596×
                    .map(|d| o::oref(d, "dep"))
1638492×
                    .collect::<Result<Vec<_>, _>>()?,
1639492×
                message: o::text(&e[3], "message")?.to_owned(),
1640
                hlc: Hlc {
1641492×
                    wall_ms: o::uint(&e[4], "wall")?,
1642492×
                    logical: o::u32_(&e[5], "logical")?,
1643
                },
1644492×
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
1645492×
                author: o::oref(&e[7], "author")?,
1646
            };
1647492×
            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
16793302×
    pub fn validate(&self) -> Result<(), StateError> {
16808566×
        for (h, c) in &self.changes {
16818566×
            for d in &c.deps {
16825028×
                if !self.changes.contains_key(d) {
16830×
                    return Err(StateError::MissingDep(*d, *h));
16845028×
                }
1685
            }
1686
        }
16873302×
        Ok(())
16883302×
    }
1689
169011885×
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
169137948×
        for (i, op) in c.tree_ops.iter().enumerate() {
169237948×
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
169337948×
        }
169411885×
        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.
16976883×
            let mut texts = texts.into_iter();
16986883×
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
169937803×
            for e in c.edits {
170037803×
                match e {
1701613×
                    Edit::Replace { node, old, new } => {
1702613×
                        self.replaces.entry(node).or_default().push((h, old, new))
1703
                    }
170437190×
                    e => {
170537190×
                        let slot = per_node.entry(e.node()).or_default();
170635573×
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
170732028×
                            slot.1.extend(texts.next());
170832028×
                        }
170937190×
                        slot.0.push(e);
1710
                    }
1711
                }
1712
            }
171335257×
            for (node, (edits, node_texts)) in per_node {
171435257×
                match self.files.get_mut(&node) {
1715452×
                    Some(g) => {
1716452×
                        assert!(
1717452×
                            node_texts.is_empty(),
1718
                            "a change read without its text applied to a built graph"
1719
                        );
1720452×
                        apply_file_edits(Arc::make_mut(g), h, edits)
1721
                    }
172234805×
                    None => {
172334805×
                        let d = Arc::make_mut(deferred.entry(node).or_default());
172434805×
                        d.add(h, edits, node_texts);
172534805×
                        d.key = Default::default();
172634805×
                    }
1727
                }
1728
            }
17296883×
            return;
17305002×
        }
17315002×
        assert!(
17325002×
            texts.is_empty(),
1733
            "a change read without its text applied to a full state"
1734
        );
17355002×
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
17365694×
        for e in c.edits {
17375694×
            match e {
1738
                Edit::Insert {
17394168×
                    node,
17404168×
                    after,
17414168×
                    before,
17424168×
                    lines,
17434168×
                } => {
17444168×
                    let idx = counters.entry(node).or_default();
17454168×
                    let first = *idx;
17464168×
                    *idx += lines.len() as u32;
17474168×
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
17484168×
                        h,
17494168×
                        first,
17504168×
                        vertex(after.resolve(h)),
17514168×
                        vertex(before.resolve(h)),
17524168×
                        lines,
17534168×
                    );
17544168×
                }
17551418×
                Edit::Delete { node, atoms } => {
17561418×
                    let g = Arc::make_mut(self.files.entry(node).or_default());
17571707×
                    for r in atoms {
17581707×
                        g.delete(h, &r.resolve(h));
17591707×
                    }
1760
                }
1761108×
                Edit::Replace { node, old, new } => {
1762108×
                    self.replaces.entry(node).or_default().push((h, old, new));
1763108×
                }
1764
            }
1765
        }
176611885×
    }
1767
1768
    /// Transitive dependencies of `h`, excluding `h` itself.
17699232×
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
17709232×
        if let Some(c) = self.closure.read().unwrap().sets.get(h) {
17717768×
            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.write().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
17959232×
    }
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.
1800400154×
    fn level(&self, h: &ChangeHash) -> u32 {
1801
        // Nearly always known: read without excluding the other threads
1802
        // rendering beside this one (oxygen#96).
1803400154×
        if let Some(l) = self.levels.read().unwrap().get(h) {
1804398096×
            return *l;
18052058×
        }
18062058×
        let mut levels = self.levels.write().unwrap();
18072058×
        if let Some(l) = levels.get(h) {
18085×
            return *l;
18092053×
        }
18102053×
        let mut stack: Vec<(ChangeHash, bool)> = vec![(*h, false)];
18116806×
        while let Some((c, expanded)) = stack.pop() {
18124753×
            if levels.contains_key(&c) {
181327×
                continue;
18144726×
            }
18154726×
            let deps: &[ChangeHash] = self
18164726×
                .changes
18174726×
                .get(&c)
18184726×
                .map(|m| m.deps.as_slice())
18194726×
                .unwrap_or(&[]);
18204726×
            if expanded {
18212363×
                let l = deps
18222363×
                    .iter()
18233146×
                    .map(|d| levels.get(d).map_or(0, |l| l + 1))
18242363×
                    .max()
18252363×
                    .unwrap_or(0);
18262363×
                levels.insert(c, l);
1827
            } else {
18282363×
                stack.push((c, true));
18293146×
                for d in deps {
18303146×
                    if !levels.contains_key(d) {
1831337×
                        stack.push((*d, false));
18322809×
                    }
1833
                }
1834
            }
1835
        }
18362053×
        levels[h]
1837400154×
    }
1838
1839
    /// Changes that no other change depends on directly, sorted.
1840397×
    pub fn heads(&self) -> Vec<ChangeHash> {
1841397×
        let depended: crate::fasthash::FastSet<&ChangeHash> =
18423313×
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
1843397×
        let mut heads: Vec<ChangeHash> = self
1844397×
            .changes
1845397×
            .keys()
18463313×
            .filter(|h| !depended.contains(h))
1847397×
            .copied()
1848397×
            .collect();
1849397×
        heads.sort();
1850397×
        heads
1851397×
    }
1852
1853
    /// Maximal elements among `hashes` (those not in the closure of another),
1854
    /// sorted. One walk down from all of them at once: whatever the walk
1855
    /// reaches is below some other element. Linear in the changes reached,
1856
    /// where comparing every pair's closures was quadratic in the number
1857
    /// of heads, which a bookmark of independent changes has many of.
18588379×
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
18598379×
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
18608379×
        let mut below: crate::fasthash::FastSet<ChangeHash> = Default::default();
18618379×
        let mut stack: Vec<ChangeHash> = set
18628379×
            .iter()
186315046×
            .filter_map(|h| self.changes.get(h))
186412795×
            .flat_map(|c| c.deps.iter().copied())
18658379×
            .collect();
186620587×
        while let Some(d) = stack.pop() {
186712208×
            if below.insert(d) {
18685970×
                if let Some(c) = self.changes.get(&d) {
18695970×
                    stack.extend(c.deps.iter().copied());
18705970×
                }
18716238×
            }
1872
        }
187315046×
        set.into_iter().filter(|h| !below.contains(h)).collect()
18748379×
    }
1875
18760×
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
18770×
        self.graph(node)
18780×
            .map(|g| g.materialize(self))
18790×
            .unwrap_or_default()
18800×
    }
1881
1882
    /// Live lines of a text node in materialized order.
188320×
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
188420×
        let Some(g) = self.graph(node) else {
18852×
            return vec![];
1886
        };
188718×
        let m = g.materialize(self);
188818×
        m.live_atoms()
188918×
            .into_iter()
189044×
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
189118×
            .collect()
189220×
    }
1893
1894
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
1895842×
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
1896842×
        let mut live: Vec<ObjectRef> = self
1897842×
            .live_replaces(node)
1898842×
            .into_iter()
1899842×
            .map(|(_, n)| n)
1900842×
            .collect();
1901842×
        live.sort();
1902842×
        live.dedup();
1903842×
        live
1904842×
    }
1905
1906
    /// The replace records whose blob is live, with the change that set it
1907
    /// (spec §9.3). A record's blob is superseded by a later replacement of
1908
    /// that blob: one whose change depends on the record's change, as every
1909
    /// replacement depends on the change that made its old blob current
1910
    /// (§8.1). Two replacements that do not know each other both stay live
1911
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
1912
    /// A replacement without that dependency, from before the rule, is read
1913
    /// as before: it supersedes every record that did not come after it.
1914881×
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
1915881×
        let Some(rs) = self.replaces.get(node) else {
19160×
            return vec![];
1917
        };
1918881×
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
191911×
            rs.iter()
192044×
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && self.closure(s).contains(q))
192111×
        };
1922881×
        rs.iter()
19231020×
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
19241020×
            .filter(|(c, n)| {
19251301×
                !rs.iter().any(|(s, o, _)| {
19261301×
                    s != c
1927353×
                        && *o == Some(*n)
1928126×
                        && (self.closure(s).contains(c)
192911×
                            || (!knows_its_old(s, n) && !self.closure(c).contains(s)))
19301301×
                })
19311020×
            })
1932881×
            .collect()
1933881×
    }
1934
1935
    /// Short label for conflict markers: `changeid-prefix "message"`.
1936820×
    pub fn label(&self, h: &ChangeHash) -> String {
1937820×
        match self.changes.get(h) {
1938820×
            Some(c) => format!(
1939
                "{} \"{}\"",
1940820×
                c.change_id.short(8),
1941820×
                c.message.lines().next().unwrap_or("")
1942
            ),
19430×
            None => format!("#{}", h.short(12)),
1944
        }
1945820×
    }
1946
1947
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1948
    /// are not part of any conflict region in order, every live atom that is
1949
    /// part of a region, and every change that contributed to a region.
1950
    /// The changes that introduced the live blobs of an opaque node, for a
1951
    /// replace conflict (spec §9.3).
19522×
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
19532×
        let mut out: Vec<ChangeHash> = Vec::new();
19546×
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
19556×
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
19564×
                out.push(*h);
19574×
            }
1958
        }
19592×
        out.sort();
19602×
        out
19612×
    }
1962
196327×
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
196427×
        let mut out = ConflictRegions::default();
196527×
        let Some(g) = self.graph(node) else {
19660×
            return out;
1967
        };
196827×
        let m = g.materialize(self);
196927×
        let mut contributors = BTreeSet::new();
197063×
        for seg in &m.segments {
197163×
            match seg {
197236×
                crate::graph::Segment::Lines(atoms) => {
197336×
                    for a in atoms {
197436×
                        out.plain
197536×
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
197636×
                    }
1977
                }
197827×
                crate::graph::Segment::Conflict(sides) => {
197954×
                    for side in sides {
198056×
                        for a in side {
198156×
                            out.region_atoms.push(*a);
198256×
                            contributors.insert(a.0);
198356×
                        }
1984
                    }
1985
                }
19860×
                crate::graph::Segment::Zombie { deleted, inserted } => {
19870×
                    for a in deleted {
19880×
                        contributors.insert(a.0);
19890×
                        contributors.extend(g.deleters(a).copied());
19900×
                    }
19910×
                    for a in inserted {
19920×
                        out.region_atoms.push(*a);
19930×
                        contributors.insert(a.0);
19940×
                    }
1995
                }
1996
            }
1997
        }
199827×
        out.contributors = contributors.into_iter().collect();
199927×
        out
200027×
    }
2001
200224232×
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
200324232×
        let Some(g) = self.graph(node) else {
2004430×
            return (Vec::new(), Materialized::default());
2005
        };
200623802×
        let m = g.materialize(self);
200723802×
        let bytes = g.render(&m, &|h| self.label(h));
200823802×
        (bytes, m)
200924232×
    }
2010
2011
    /// Every file rendered, in parallel: files are independent, and
2012
    /// rendering them is most of a snapshot's cost in a large tree.
20132227×
    pub fn materialize(&self) -> Snapshot {
2014
        use rayon::prelude::*;
20152227×
        self.require_full("materializing a state");
20162227×
        let tree = self.tree.view();
20172227×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
20182227×
        let rendered: Vec<(String, FileState)> = entries
20192227×
            .par_iter()
202016448×
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
20212227×
            .collect();
20222227×
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
20232227×
        Snapshot {
20242227×
            tree,
20252227×
            files,
20262227×
            unrendered: BTreeSet::new(),
20272227×
        }
20282227×
    }
2029
2030
    /// Like [`State::materialize`], leaving the text files of nodes in
2031
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
2032
    /// file's graph must be loaded. For a caller that already knows those
2033
    /// files are unchanged and not conflicted.
203419×
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
203519×
        self.materialize_leaving(|_, e| skip.contains(&e.node))
203619×
    }
2037
2038
    /// As [`State::materialize_except`], rendering only the text files at
2039
    /// `render` (a few, where the caller knows the rest unchanged).
2040803×
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
20417831×
        self.materialize_leaving(|p, _| !render.contains(p))
2042803×
    }
2043
2044
    /// As [`State::materialize_except`], rendering only the text files of
2045
    /// the nodes in `render` (a change's edited files), without a set of
2046
    /// every other file to leave out.
2047212×
    pub fn materialize_nodes(&self, render: &HashSet<NodeId>) -> Snapshot {
2048566×
        self.materialize_leaving(|_, e| !render.contains(&e.node))
2049212×
    }
2050
20511034×
    fn materialize_leaving(
20521034×
        &self,
20531034×
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
20541034×
    ) -> Snapshot {
2055
        use rayon::prelude::*;
20561034×
        let tree = self.tree.view();
20571034×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
20581034×
        let rendered: Vec<(String, FileState, bool)> = entries
20591034×
            .par_iter()
20608744×
            .map(|(path, e)| {
20618744×
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
20624561×
                    let f = FileState {
20634561×
                        node: e.node,
20644561×
                        kind: e.kind,
20654561×
                        mode: e.mode,
20664561×
                        content: FileContent::Text {
20674561×
                            bytes: Vec::new(),
20684561×
                            materialized: Materialized::default(),
20694561×
                        },
20704561×
                    };
20714561×
                    (path.to_string(), f, true)
2072
                } else {
20734183×
                    (path.to_string(), self.file_state(e), false)
2074
                }
20758744×
            })
20761034×
            .collect();
2077
        // In the view's path order, so the maps are built without searching.
20781034×
        let unrendered: BTreeSet<String> = rendered
20791034×
            .iter()
20801034×
            .filter(|(_, _, skipped)| *skipped)
20814561×
            .map(|(p, _, _)| p.clone())
20821034×
            .collect();
20831034×
        let files: BTreeMap<String, FileState> =
20848744×
            rendered.into_iter().map(|(p, f, _)| (p, f)).collect();
20851034×
        Snapshot {
20861034×
            tree,
20871034×
            files,
20881034×
            unrendered,
20891034×
        }
20901034×
    }
2091
2092
    /// A snapshot of only `paths` (those `view` has), `view` being this
2093
    /// state's tree view: for a caller that works from what changed. The
2094
    /// graphs of those text files must be loaded.
209587×
    pub fn materialize_paths<'p>(
209687×
        &self,
209787×
        view: crate::tree::TreeView,
209887×
        paths: impl IntoIterator<Item = &'p str>,
209987×
    ) -> Snapshot {
2100
        use rayon::prelude::*;
2101
        // On every core: a merge may render thousands (oxygen#96).
210287×
        let entries: Vec<(&str, &crate::tree::TreeEntry)> = paths
210387×
            .into_iter()
2104128×
            .filter_map(|p| Some((p, view.entries.get(p)?)))
210587×
            .collect();
210687×
        let files = entries
210787×
            .par_iter()
2108105×
            .map(|(p, e)| (p.to_string(), self.file_state(e)))
210987×
            .collect::<Vec<_>>()
211087×
            .into_iter()
211187×
            .collect();
211287×
        Snapshot {
211387×
            tree: view,
211487×
            files,
211587×
            unrendered: BTreeSet::new(),
211687×
        }
211787×
    }
2118
2119
    /// The state of one tree entry: a directory, an opaque file's live
2120
    /// blobs, or a text file rendered from its graph (which must be built).
21210×
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
21220×
        self.file_state(e)
21230×
    }
2124
212520736×
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
2126
        {
212720736×
            let content = match e.kind {
21281439×
                NodeKind::Dir => FileContent::Dir,
2129100×
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
2130100×
                    blobs: self.live_blobs(&e.node),
2131100×
                },
2132541×
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
2133541×
                    blobs: self.live_blobs(&e.node),
2134541×
                },
2135
                NodeKind::File => {
213618656×
                    let (bytes, materialized) = self.render_file(&e.node);
213718656×
                    FileContent::Text {
213818656×
                        bytes,
213918656×
                        materialized,
214018656×
                    }
2141
                }
2142
            };
214320736×
            FileState {
214420736×
                node: e.node,
214520736×
                kind: e.kind,
214620736×
                mode: e.mode,
214720736×
                content,
214820736×
            }
2149
        }
215020736×
    }
2151
}
2152
2153
impl DepOracle for State {
2154
    /// Whether `a` depends on `b`, by a walk down from `a` that stops at
2155
    /// changes no higher than `b`: they cannot have `b` below them. Nothing
2156
    /// of the walk is kept, so asking about many pairs costs no more memory
2157
    /// than one walk (#25); a closure already memoised answers at once.
215865970×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
215965970×
        if a == b {
2160800×
            return true;
216165170×
        }
216265170×
        if let Some(c) = self.closure.read().unwrap().sets.get(a) {
21630×
            return c.contains(b);
216465170×
        }
216565170×
        if !self.changes.contains_key(b) {
2166800×
            return false;
216764370×
        }
216864370×
        let lb = self.level(b);
216964370×
        if self.level(a) <= lb {
217035675×
            return false;
217128695×
        }
217228695×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
217328695×
        let mut stack: Vec<ChangeHash> = self
217428695×
            .changes
217528695×
            .get(a)
217628695×
            .map(|m| m.deps.clone())
217728695×
            .unwrap_or_default();
2178358708×
        while let Some(c) = stack.pop() {
2179339439×
            if c == *b {
21809426×
                return true;
2181330013×
            }
2182330013×
            if !seen.insert(c) || self.level(&c) <= lb {
2183222413×
                continue;
2184107600×
            }
2185107600×
            if let Some(m) = self.changes.get(&c) {
2186107600×
                stack.extend(m.deps.iter().copied());
2187107600×
            }
2188
        }
218919269×
        false
219065970×
    }
2191
}
2192
2193
#[cfg(test)]
2194
mod tests {
2195
    use super::*;
2196
    use crate::ids::ChangeId;
2197
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
2198
21992023×
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
22002023×
        let mut c = Change {
22012023×
            version: crate::objects::CHANGE_VERSION,
22022023×
            change_id: ChangeId::random(),
22032023×
            deps,
22042023×
            author: ObjectRef::ZERO,
22052023×
            hlc: Hlc {
22062023×
                wall_ms: 1,
22072023×
                logical: 0,
22082023×
            },
22092023×
            message: "m".into(),
22102023×
            tree_ops,
22112023×
            edits,
22122023×
            kind: ChangeKind::Normal,
22132023×
        };
22142023×
        c.normalize();
22152023×
        c
22162023×
    }
2217
2218
    #[test]
22191×
    fn build_edit_and_materialize() {
22201×
        let mut st = State::new();
22211×
        let f = NodeId::random();
22221×
        let c1 = change(
22231×
            vec![],
22241×
            vec![TreeOp::AddNode {
22251×
                node: f,
22261×
                kind: NodeKind::File,
22271×
                mode: Mode::TEXT,
22281×
                parent: NodeId::ROOT,
22291×
                name: "a.txt".into(),
22301×
            }],
22311×
            vec![Edit::Insert {
22321×
                node: f,
22331×
                after: AtomRef::Start,
22341×
                before: AtomRef::End,
22351×
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
22361×
            }],
2237
        );
22381×
        let h1 = st.add(c1).unwrap();
2239
        // Depends on h1: append a line and delete "one".
22401×
        let c2 = change(
22411×
            vec![h1],
22421×
            vec![],
22431×
            vec![
22441×
                Edit::Delete {
22451×
                    node: f,
22461×
                    atoms: vec![AtomRange {
22471×
                        change: h1,
22481×
                        from: 0,
22491×
                        to: 1,
22501×
                    }],
22511×
                },
22521×
                Edit::Insert {
22531×
                    node: f,
22541×
                    after: AtomRef::Atom {
22551×
                        change: h1,
22561×
                        index: 1,
22571×
                    },
22581×
                    before: AtomRef::End,
22591×
                    lines: vec![b"three\n".to_vec()].into(),
22601×
                },
2261
            ],
2262
        );
22631×
        let h2 = st.add(c2).unwrap();
22641×
        assert_eq!(st.heads(), vec![h2]);
22651×
        assert!(st.depends_on(&h2, &h1));
22661×
        assert!(!st.depends_on(&h1, &h2));
22671×
        let snap = st.materialize();
22681×
        assert!(!snap.is_conflicted());
22691×
        let a = &snap.files["a.txt"];
22701×
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
22711×
        assert_eq!(st.live_lines(&f).len(), 2);
22721×
    }
2273
2274
    #[test]
22751×
    fn missing_dependency_is_rejected() {
22761×
        let mut st = State::new();
22771×
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
22781×
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
22791×
    }
2280
2281
    #[test]
22821×
    fn self_references_and_multi_insert_indexing() {
22831×
        let mut st = State::new();
22841×
        let f = NodeId::random();
22851×
        let me = OpRef {
22861×
            change: ObjectRef::ZERO,
22871×
            index: 0,
22881×
        };
22891×
        let c1 = change(
22901×
            vec![],
22911×
            vec![
22921×
                TreeOp::AddNode {
22931×
                    node: f,
22941×
                    kind: NodeKind::File,
22951×
                    mode: Mode::TEXT,
22961×
                    parent: NodeId::ROOT,
22971×
                    name: "x".into(),
22981×
                },
22991×
                TreeOp::SetMode {
23001×
                    node: f,
23011×
                    old: me,
23021×
                    mode: Mode {
23031×
                        exec: true,
23041×
                        opaque: false,
23051×
                    },
23061×
                },
2307
            ],
23081×
            vec![
23091×
                Edit::Insert {
23101×
                    node: f,
23111×
                    after: AtomRef::Start,
23121×
                    before: AtomRef::End,
23131×
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
23141×
                },
2315
                // Insert between the two lines just inserted, using self references.
23161×
                Edit::Insert {
23171×
                    node: f,
23181×
                    after: AtomRef::Atom {
23191×
                        change: ObjectRef::ZERO,
23201×
                        index: 0,
23211×
                    },
23221×
                    before: AtomRef::Atom {
23231×
                        change: ObjectRef::ZERO,
23241×
                        index: 1,
23251×
                    },
23261×
                    lines: vec![b"b\n".to_vec()].into(),
23271×
                },
2328
            ],
2329
        );
23301×
        st.add(c1).unwrap();
23311×
        let snap = st.materialize();
23321×
        let x = &snap.files["x"];
23331×
        assert_eq!(
2334
            x.mode,
2335
            Mode {
2336
                exec: true,
2337
                opaque: false
2338
            }
2339
        );
23401×
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
23411×
    }
2342
2343
    #[test]
23441×
    fn opaque_replace_and_conflict() {
23451×
        let mut st = State::new();
23461×
        let f = NodeId::random();
23471×
        let b1 = ObjectRef([1; 32]);
23481×
        let b2 = ObjectRef([2; 32]);
23491×
        let b3 = ObjectRef([3; 32]);
23501×
        let h1 = st
23511×
            .add(change(
23521×
                vec![],
23531×
                vec![TreeOp::AddNode {
23541×
                    node: f,
23551×
                    kind: NodeKind::File,
23561×
                    mode: Mode::OPAQUE,
23571×
                    parent: NodeId::ROOT,
23581×
                    name: "img".into(),
23591×
                }],
23601×
                vec![Edit::Replace {
23611×
                    node: f,
23621×
                    old: None,
23631×
                    new: Some(b1),
23641×
                }],
2365
            ))
23661×
            .unwrap();
23671×
        assert_eq!(st.live_blobs(&f), vec![b1]);
23681×
        st.add(change(
23691×
            vec![h1],
23701×
            vec![],
23711×
            vec![Edit::Replace {
23721×
                node: f,
23731×
                old: Some(b1),
23741×
                new: Some(b2),
23751×
            }],
2376
        ))
23771×
        .unwrap();
23781×
        st.add(change(
23791×
            vec![h1],
23801×
            vec![],
23811×
            vec![Edit::Replace {
23821×
                node: f,
23831×
                old: Some(b1),
23841×
                new: Some(b3),
23851×
            }],
2386
        ))
23871×
        .unwrap();
23881×
        let snap = st.materialize();
23891×
        assert!(snap.is_conflicted());
23901×
        assert!(
23911×
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2392
        );
23931×
    }
2394
2395
    #[test]
23961×
    fn checkpoint_payload_round_trip_and_replay() {
23971×
        let mut st = State::new();
23981×
        let f = NodeId::random();
23991×
        let h1 = st
24001×
            .add(change(
24011×
                vec![],
24021×
                vec![TreeOp::AddNode {
24031×
                    node: f,
24041×
                    kind: NodeKind::File,
24051×
                    mode: Mode::TEXT,
24061×
                    parent: NodeId::ROOT,
24071×
                    name: "a".into(),
24081×
                }],
24091×
                vec![Edit::Insert {
24101×
                    node: f,
24111×
                    after: AtomRef::Start,
24121×
                    before: AtomRef::End,
24131×
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
24141×
                }],
2415
            ))
24161×
            .unwrap();
24171×
        let h2 = st
24181×
            .add(change(
24191×
                vec![h1],
24201×
                vec![],
24211×
                vec![Edit::Delete {
24221×
                    node: f,
24231×
                    atoms: vec![AtomRange {
24241×
                        change: h1,
24251×
                        from: 0,
24261×
                        to: 1,
24271×
                    }],
24281×
                }],
2429
            ))
24301×
            .unwrap();
24311×
        let payload = st.checkpoint_payload();
24321×
        let back = State::from_checkpoint_payload(&payload).unwrap();
24331×
        assert_eq!(back.len(), 2);
24341×
        assert_eq!(back.heads(), vec![h2]);
24351×
        assert_eq!(back.get(&h1).unwrap().message, "m");
24361×
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2437
        // Replaying a further change onto the restored state equals a full build.
24381×
        let c3 = change(
24391×
            vec![h2],
24401×
            vec![],
24411×
            vec![Edit::Insert {
24421×
                node: f,
24431×
                after: AtomRef::Atom {
24441×
                    change: h1,
24451×
                    index: 1,
24461×
                },
24471×
                before: AtomRef::End,
24481×
                lines: vec![b"3\n".to_vec()].into(),
24491×
            }],
2450
        );
24511×
        let mut full = st.clone();
24521×
        full.add(c3.clone()).unwrap();
24531×
        let mut restored = back;
24541×
        restored.add(c3).unwrap();
24551×
        let (a, b) = (full.materialize(), restored.materialize());
24561×
        assert_eq!(
24571×
            a.files.keys().collect::<Vec<_>>(),
24581×
            b.files.keys().collect::<Vec<_>>()
2459
        );
24601×
        assert_eq!(a.files["a"].content, b.files["a"].content);
24611×
        assert!(
24621×
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2463
        );
24641×
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
24651×
    }
2466
2467
    /// History-only states (O10f): the same state as a full load once its
2468
    /// graphs are built, by replay and from a version 2 checkpoint with
2469
    /// later changes; unloaded graphs are never read as empty.
2470
    #[test]
24711×
    fn graph_keys_change_exactly_when_a_graph_does() {
24721×
        let (f, g) = (NodeId::random(), NodeId::random());
24731×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
24742×
            node,
24752×
            kind: NodeKind::File,
2476
            mode: Mode::TEXT,
2477
            parent: NodeId::ROOT,
24782×
            name: name.into(),
24792×
        };
24801×
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
24814×
            node,
24824×
            after: AtomRef::Start,
24834×
            before: AtomRef::End,
24844×
            lines: vec![line.to_vec()].into(),
24854×
        };
24861×
        let c1 = change(
24871×
            vec![],
24881×
            vec![add(f, "f"), add(g, "g")],
24891×
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2490
        );
24911×
        let h1 = c1.hash();
24921×
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
24931×
        let h2 = c2.hash();
24941×
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
24956×
        let load = |cs: &[&Change]| {
24966×
            let mut st = State::new_history_only();
249710×
            for c in cs {
249810×
                st.add((*c).clone()).unwrap();
249910×
            }
25006×
            st
25016×
        };
25021×
        let s1 = load(&[&c1]);
25031×
        let s2 = load(&[&c1, &c2]);
25041×
        let s3 = load(&[&c1, &c2, &c3]);
250518×
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
25061×
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
25071×
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
25081×
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
25091×
        assert_ne!(key(&s2, &f), key(&s3, &f));
25101×
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
25111×
        let mut built = load(&[&c1]);
25121×
        built
25131×
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
25141×
            .unwrap();
25151×
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
25161×
        let mut full = State::new();
25171×
        full.add(c1.clone()).unwrap();
25181×
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2519
2520
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2521
        // or inline values: stable across loads, changed by later edits.
25221×
        let graphs = full.checkpoint_file_graphs();
25231×
        let index = full.checkpoint_index(&graphs, |enc| {
25240×
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
25250×
        });
25268×
        let cp = |extra: &[&Change]| {
25278×
            let mut st = State::from_checkpoint_history(&index).unwrap();
25288×
            for c in extra {
25295×
                st.add((*c).clone()).unwrap();
25305×
            }
25318×
            st
25328×
        };
25331×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
25341×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
25351×
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
25361×
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2537
2538
        // Partial rendering: skipped files are listed and empty, the others
2539
        // render as in a full state.
25401×
        let mut part = load(&[&c1, &c2]);
25411×
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
25421×
            .unwrap();
25431×
        let snap = part.materialize_except(&[f].into_iter().collect());
25441×
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
25451×
        let mut whole = State::new();
25461×
        whole.add(c1.clone()).unwrap();
25471×
        whole.add(c2.clone()).unwrap();
25481×
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
25491×
        assert!(
25501×
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2551
        );
25521×
    }
2553
2554
    #[test]
25551×
    fn history_only_states_build_the_same_graphs_on_demand() {
25561×
        let small = NodeId::random();
25571×
        let big = NodeId::random();
25581×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
25592×
            node,
25602×
            kind: NodeKind::File,
2561
            mode: Mode::TEXT,
2562
            parent: NodeId::ROOT,
25632×
            name: name.into(),
25642×
        };
25651×
        let lines: crate::lines::Lines = (0..300)
2566300×
            .map(|i| format!("line {i}\n").into_bytes())
25671×
            .collect();
25681×
        let c1 = change(
25691×
            vec![],
25701×
            vec![add(small, "small"), add(big, "big")],
25711×
            vec![
25721×
                Edit::Insert {
25731×
                    node: small,
25741×
                    after: AtomRef::Start,
25751×
                    before: AtomRef::End,
25761×
                    lines: vec![b"x\n".to_vec()].into(),
25771×
                },
25781×
                Edit::Insert {
25791×
                    node: big,
25801×
                    after: AtomRef::Start,
25811×
                    before: AtomRef::End,
25821×
                    lines,
25831×
                },
2584
            ],
2585
        );
25861×
        let h1 = c1.hash();
25871×
        let c2 = change(
25881×
            vec![h1],
25891×
            vec![],
25901×
            vec![
25911×
                Edit::Delete {
25921×
                    node: big,
25931×
                    atoms: vec![AtomRange {
25941×
                        change: h1,
25951×
                        from: 2,
25961×
                        to: 9,
25971×
                    }],
25981×
                },
25991×
                Edit::Insert {
26001×
                    node: big,
26011×
                    after: AtomRef::Atom {
26021×
                        change: h1,
26031×
                        index: 20,
26041×
                    },
26051×
                    before: AtomRef::Atom {
26061×
                        change: h1,
26071×
                        index: 21,
26081×
                    },
26091×
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
26101×
                },
26111×
                Edit::Insert {
26121×
                    node: small,
26131×
                    after: AtomRef::Atom {
26141×
                        change: h1,
26151×
                        index: 0,
26161×
                    },
26171×
                    before: AtomRef::End,
26181×
                    lines: vec![b"y\n".to_vec()].into(),
26191×
                },
2620
            ],
2621
        );
26221×
        let h2 = c2.hash();
26231×
        let c3 = change(
26241×
            vec![h2],
26251×
            vec![],
26261×
            vec![Edit::Delete {
26271×
                node: small,
26281×
                atoms: vec![AtomRange {
26291×
                    change: h1,
26301×
                    from: 0,
26311×
                    to: 1,
26321×
                }],
26331×
            }],
2634
        );
2635
26361×
        let mut full = State::new();
26373×
        for c in [&c1, &c2, &c3] {
26383×
            full.add(c.clone()).unwrap();
26393×
        }
2640
        // By replay: nothing built until asked, then exactly the full graphs.
26411×
        let mut hist = State::new_history_only();
26423×
        for c in [&c1, &c2, &c3] {
26433×
            hist.add(c.clone()).unwrap();
26443×
        }
26451×
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
26461×
        assert_eq!(hist.len(), 3);
26471×
        hist.load_graphs(
26481×
            &[big],
26490×
            |_| unreachable!("no checkpoint"),
26500×
            |_| unreachable!(),
2651
        )
26521×
        .unwrap();
26531×
        assert_eq!(
26541×
            hist.render_file(&big).0,
26551×
            full.render_file(&big).0,
2656
            "one file on its own"
2657
        );
26581×
        assert!(!hist.is_full());
26591×
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
26601×
            .unwrap();
26611×
        assert!(hist.is_full());
26621×
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2663
2664
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
26651×
        let mut base = State::new();
26661×
        base.add(c1.clone()).unwrap();
26671×
        base.add(c2.clone()).unwrap();
26681×
        let graphs = base.checkpoint_file_graphs();
26691×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
26701×
        let index = base.checkpoint_index(&graphs, |enc| {
26711×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
26721×
            blobs.insert(r, enc.to_vec());
26731×
            r
26741×
        });
26751×
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
26761×
        from_cp.add(c3.clone()).unwrap();
26771×
        assert!(!from_cp.is_full());
26781×
        let mut fetched = 0;
26791×
        from_cp
26801×
            .load_graphs(
26811×
                &[small, big],
26821×
                |refs| {
26831×
                    fetched += refs.len();
26841×
                    refs.iter()
26851×
                        .map(|r| {
26861×
                            blobs
26871×
                                .get(r)
26881×
                                .cloned()
26891×
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
26901×
                        })
26911×
                        .collect()
26921×
                },
26930×
                |_| unreachable!(),
2694
            )
26951×
            .unwrap();
26961×
        assert_eq!(
2697
            fetched, 1,
2698
            "the large graph's blob, in one batch; the small one was inline"
2699
        );
27001×
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
27011×
    }
2702
2703
    #[test]
2704
    #[should_panic(expected = "was not loaded")]
27051×
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
27061×
        let f = NodeId::random();
27071×
        let mut st = State::new_history_only();
27081×
        st.add(change(
27091×
            vec![],
27101×
            vec![TreeOp::AddNode {
27111×
                node: f,
27121×
                kind: NodeKind::File,
27131×
                mode: Mode::TEXT,
27141×
                parent: NodeId::ROOT,
27151×
                name: "a".into(),
27161×
            }],
27171×
            vec![Edit::Insert {
27181×
                node: f,
27191×
                after: AtomRef::Start,
27201×
                before: AtomRef::End,
27211×
                lines: vec![b"a\n".to_vec()].into(),
27221×
            }],
2723
        ))
27241×
        .unwrap();
27251×
        st.render_file(&f);
27261×
    }
2727
2728
    #[test]
2729
    #[should_panic(expected = "needs every file graph")]
27301×
    fn materializing_a_history_only_state_is_refused() {
27311×
        let f = NodeId::random();
27321×
        let mut st = State::new_history_only();
27331×
        st.add(change(
27341×
            vec![],
27351×
            vec![TreeOp::AddNode {
27361×
                node: f,
27371×
                kind: NodeKind::File,
27381×
                mode: Mode::TEXT,
27391×
                parent: NodeId::ROOT,
27401×
                name: "a".into(),
27411×
            }],
27421×
            vec![Edit::Insert {
27431×
                node: f,
27441×
                after: AtomRef::Start,
27451×
                before: AtomRef::End,
27461×
                lines: vec![b"a\n".to_vec()].into(),
27471×
            }],
2748
        ))
27491×
        .unwrap();
27501×
        st.materialize();
27511×
    }
2752
2753
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
2754
    /// blob; the state read back is the same as from version 1.
2755
    #[test]
27561×
    fn checkpoint_index_round_trip_matches_version_1() {
27571×
        let mut st = State::new();
27581×
        let small = NodeId::random();
27591×
        let big = NodeId::random();
27601×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
27612×
            node,
27622×
            kind: NodeKind::File,
2763
            mode: Mode::TEXT,
2764
            parent: NodeId::ROOT,
27652×
            name: name.into(),
27662×
        };
27671×
        let big_lines: crate::lines::Lines = (0..400)
2768400×
            .map(|i| format!("line {i} of a long file\n").into_bytes())
27691×
            .collect();
27701×
        let h1 = st
27711×
            .add(change(
27721×
                vec![],
27731×
                vec![add(small, "small"), add(big, "big")],
27741×
                vec![
27751×
                    Edit::Insert {
27761×
                        node: small,
27771×
                        after: AtomRef::Start,
27781×
                        before: AtomRef::End,
27791×
                        lines: vec![b"x\n".to_vec()].into(),
27801×
                    },
27811×
                    Edit::Insert {
27821×
                        node: big,
27831×
                        after: AtomRef::Start,
27841×
                        before: AtomRef::End,
27851×
                        lines: big_lines,
27861×
                    },
2787
                ],
2788
            ))
27891×
            .unwrap();
27901×
        st.add(change(
27911×
            vec![h1],
27921×
            vec![],
27931×
            vec![Edit::Delete {
27941×
                node: big,
27951×
                atoms: vec![AtomRange {
27961×
                    change: h1,
27971×
                    from: 3,
27981×
                    to: 7,
27991×
                }],
28001×
            }],
2801
        ))
28021×
        .unwrap();
2803
28041×
        let graphs = st.checkpoint_file_graphs();
28051×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
28061×
        let index = st.checkpoint_index(&graphs, |enc| {
28071×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
28081×
            blobs.insert(r, enc.to_vec());
28091×
            r
28101×
        });
28111×
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
28121×
        assert_eq!(
28131×
            State::checkpoint_graph_refs(&index).unwrap(),
28141×
            blobs.keys().copied().collect::<Vec<_>>()
2815
        );
28161×
        assert!(
28171×
            State::checkpoint_graph_refs(&st.checkpoint_payload())
28181×
                .unwrap()
28191×
                .is_empty(),
2820
            "version 1 names none"
2821
        );
28221×
        assert!(index.len() < st.checkpoint_payload().len());
2823
28241×
        let back = State::from_checkpoint(&index, |refs| {
28251×
            refs.iter()
28261×
                .map(|r| {
28271×
                    blobs
28281×
                        .get(r)
28291×
                        .cloned()
28301×
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
28311×
                })
28321×
                .collect()
28331×
        })
28341×
        .unwrap();
28351×
        assert_eq!(
28361×
            back.checkpoint_payload(),
28371×
            st.checkpoint_payload(),
2838
            "the same state as version 1"
2839
        );
28401×
        assert_eq!(
28411×
            back.materialize().files["big"].content,
28421×
            st.materialize().files["big"].content
2843
        );
2844
        // Deterministic: the same state gives the same index.
28451×
        assert_eq!(
28461×
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
28471×
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
28481×
            }),
2849
            index
2850
        );
2851
        // A missing graph blob is an error, not an empty file.
28521×
        assert!(
28531×
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
2854
        );
28551×
        assert!(
28561×
            State::from_checkpoint_payload(&index).is_err(),
2857
            "version 2 needs its blobs"
2858
        );
2859
        // Version 1 payloads still read, and unknown versions do not.
28601×
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
28611×
        let mut v3 = cbor::decode(&index).unwrap();
28621×
        if let Value::Map(m) = &mut v3 {
28631×
            m.insert(0, Value::Uint(3));
28641×
        }
28651×
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
28661×
    }
2867
2868
    #[test]
28691×
    fn maximal_elements() {
28701×
        let mut st = State::new();
28711×
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
28721×
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
28731×
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
28741×
        let mut m = st.maximal(&[h1, h2, h3]);
28751×
        m.sort();
28761×
        let mut want = vec![h2, h3];
28771×
        want.sort();
28781×
        assert_eq!(m, want);
28791×
        assert_eq!(st.heads(), want);
28801×
    }
2881
2882
    /// The bounded walk of `depends_on` agrees with the closure on random
2883
    /// graphs, and the memo stays within its bound.
2884
    #[test]
28851×
    fn depends_on_matches_the_closure() {
2886
        use rand::{Rng, SeedableRng};
28871×
        let mut rng = rand::rngs::StdRng::seed_from_u64(11);
28881×
        for _ in 0..10 {
288910×
            let mut st = State::new();
289010×
            let mut all: Vec<ChangeHash> = Vec::new();
289110×
            for _ in 0..80 {
2892800×
                let deps: Vec<ChangeHash> =
289331600×
                    all.iter().copied().filter(|_| rng.gen_bool(0.06)).collect();
2894800×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2895
            }
289610×
            let unknown = ObjectRef([0xee; 32]);
2897800×
            for a in &all {
2898800×
                let want = st.closure(a).clone();
2899800×
                st.closure.write().unwrap().sets.clear();
2900800×
                st.closure.write().unwrap().held = 0;
290164800×
                for b in all.iter().chain([&unknown]) {
290264800×
                    assert_eq!(
290364800×
                        st.depends_on(a, b),
290464800×
                        a == b || want.contains(b),
2905
                        "{a:?} on {b:?}"
2906
                    );
2907
                }
2908
            }
290910×
            assert!(st.closure.write().unwrap().held <= CLOSURE_MEMO_HASHES);
2910
        }
29111×
    }
2912
2913
    /// The one-walk `maximal` agrees with the definition (not in the
2914
    /// closure of another element) on random graphs, with repeated and
2915
    /// unknown hashes among the input.
2916
    #[test]
29171×
    fn maximal_matches_its_definition() {
2918
        use rand::{Rng, SeedableRng};
29191×
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
29201×
        for _ in 0..20 {
292120×
            let mut st = State::new();
292220×
            let mut all: Vec<ChangeHash> = Vec::new();
292320×
            for _ in 0..60 {
29241200×
                let deps: Vec<ChangeHash> =
292535400×
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
29261200×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2927
            }
292820×
            let mut pick: Vec<ChangeHash> =
29291200×
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
293020×
            pick.extend(pick.clone().into_iter().take(3));
293120×
            pick.push(ObjectRef([0xee; 32]));
293220×
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
293320×
            let want: Vec<ChangeHash> = set
293420×
                .iter()
29358456×
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
293620×
                .copied()
293720×
                .collect();
293820×
            assert_eq!(st.maximal(&pick), want);
293920×
            assert_eq!(st.maximal(&all), st.heads());
2940
        }
29411×
    }
2942
}