OXYGENHUB

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

2112 of 2278 lines run, 445 of 644 functions · run #328 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
/// The log's order of changes: newest first by clock, then by hash, so
44
/// it is total.
451013×
pub fn log_order(a: (&ChangeHash, &Hlc), b: (&ChangeHash, &Hlc)) -> std::cmp::Ordering {
461013×
    b.1.cmp(a.1).then(b.0.cmp(a.0))
471013×
}
48
49
impl ChangeMeta {
50
    /// In the flat layout of local indexes and caches ([`crate::flat`]).
516535×
    pub(crate) fn write_flat(&self, w: &mut crate::flat::Writer) {
526535×
        w.fixed(&self.change_id.0);
536535×
        w.count(self.deps.len());
546535×
        for d in &self.deps {
556008×
            w.object(d);
566008×
        }
576535×
        w.object(&self.author);
586535×
        w.u64(self.hlc.wall_ms);
596535×
        w.u32(self.hlc.logical);
606535×
        w.bytes(self.message.as_bytes());
616535×
        w.u8(self.kind.tag() as u8);
626535×
    }
63
6411661×
    pub(crate) fn read_flat(r: &mut crate::flat::Reader) -> Result<ChangeMeta, ObjectError> {
6511661×
        let change_id = crate::ids::ChangeId(r.fixed::<16>()?);
6611661×
        let mut deps = Vec::new();
6711661×
        for _ in 0..r.count()? {
6810752×
            deps.push(r.object()?);
69
        }
70
        Ok(ChangeMeta {
7111661×
            change_id,
7211661×
            deps,
7311661×
            author: r.object()?,
74
            hlc: Hlc {
7511661×
                wall_ms: r.u64()?,
7611661×
                logical: r.u32()?,
77
            },
7811661×
            message: r.text()?,
7911661×
            kind: ChangeKind::from_tag(r.u8()? as u64)?,
80
        })
8111661×
    }
82
8315521×
    pub fn of(c: &Change) -> ChangeMeta {
8415521×
        ChangeMeta {
8515521×
            change_id: c.change_id,
8615521×
            deps: c.deps.clone(),
8715521×
            author: c.author,
8815521×
            hlc: c.hlc,
8915521×
            message: c.message.clone(),
9015521×
            kind: c.kind,
9115521×
        }
9215521×
    }
93
}
94
95
#[derive(Default)]
96
pub struct State {
97
    /// Shared between clones, like `files` and `deferred`: a state kept
98
    /// beside another that differs by a few changes shares the rest.
99
    changes: crate::fasthash::FastMap<ChangeHash, Arc<ChangeMeta>>,
100
    tree: TreeGraph,
101
    /// Shared between clones: a clone copies a graph only when an edit
102
    /// changes it (`Arc::make_mut`), so keeping several states that differ
103
    /// by a few changes costs little more than one.
104
    files: crate::fasthash::FastMap<NodeId, Arc<FileGraph>>,
105
    replaces: HashMap<NodeId, Vec<ReplaceRecord>>,
106
    /// Memoised transitive dependencies, bounded by the hashes they hold
107
    /// (each set is the whole history below a change, so keeping one for
108
    /// every change asked about grew with the square of history: #25). A
109
    /// mutex, not a `RefCell`, so a loaded state can be shared across
110
    /// threads by a host that caches it.
111
    closure: std::sync::RwLock<ClosureMemo>,
112
    /// Each change's level: 0 with no dependencies, else one more than its
113
    /// highest dependency. A change can only depend on changes of lower
114
    /// level, which bounds the walk [`DepOracle::depends_on`] does.
115
    levels: std::sync::RwLock<crate::fasthash::FastMap<ChangeHash, u32>>,
116
    /// `None` for a full state. For a history-only state (loaded for its
117
    /// changes and tree), the file graphs not built yet, by node: `files`
118
    /// holds only those loaded with [`State::load_graphs`].
119
    deferred: Option<crate::fasthash::FastMap<NodeId, Arc<Deferred>>>,
120
}
121
122
use crate::objects::TextRef;
123
124
/// A file graph a history-only state has not built: its base from a
125
/// version 2 checkpoint, if any, and the edits of later changes in the
126
/// order they were applied (spec §11). Building it later gives the same
127
/// graph, since graph construction does not depend on order (§8).
128
///
129
/// Read from a state index, it stays in the index, unread, until first
130
/// used: a command that builds a few files reads and checks only their
131
/// histories (oxygen#94).
132
#[derive(Clone, Default)]
133
struct Deferred {
134
    /// The history: `raw` read and decoded, with `more` after it. An
135
    /// error when `raw` does not match its hash.
136
    body: std::sync::OnceLock<Result<DeferredBody, String>>,
137
    /// The history as an index holds it, not read yet.
138
    raw: Option<RawHistory>,
139
    /// Changes added since the index was read, kept beside `raw`, so that
140
    /// adding one neither reads nor decodes the history.
141
    more: Vec<(ChangeHash, Vec<Edit>)>,
142
    more_texts: Vec<TextRef>,
143
    /// Its graph key, once worked out (or read from an index); reset by
144
    /// any edit added.
145
    key: std::sync::OnceLock<[u8; 32]>,
146
}
147
148
/// Where a state index's file histories are: the index file itself, read
149
/// on first use, or bytes in memory.
150
#[derive(Clone)]
151
pub enum Histories {
152
    Bytes(Arc<Vec<u8>>),
153
    /// The file, where its histories start, and how many bytes they take.
154
    File(Arc<std::fs::File>, u64, u64),
155
}
156
157
impl Histories {
15816694×
    fn len(&self) -> u64 {
15916694×
        match self {
1604527×
            Histories::Bytes(b) => b.len() as u64,
16112167×
            Histories::File(_, _, len) => *len,
162
        }
16316694×
    }
164
16521848×
    fn read(&self, at: u64, len: usize) -> std::io::Result<Vec<u8>> {
16621848×
        match self {
1674527×
            Histories::Bytes(b) => Ok(b[at as usize..at as usize + len].to_vec()),
16817321×
            Histories::File(f, start, _) => {
16917321×
                let mut buf = vec![0u8; len];
17017321×
                read_exact_at(f, &mut buf, start + at)?;
17117321×
                Ok(buf)
172
            }
173
        }
17421848×
    }
175
}
176
177
#[cfg(unix)]
17817321×
fn read_exact_at(f: &std::fs::File, buf: &mut [u8], at: u64) -> std::io::Result<()> {
17917321×
    std::os::unix::fs::FileExt::read_exact_at(f, buf, at)
18017321×
}
181
182
#[cfg(windows)]
183
fn read_exact_at(f: &std::fs::File, mut buf: &mut [u8], mut at: u64) -> std::io::Result<()> {
184
    while !buf.is_empty() {
185
        match std::os::windows::fs::FileExt::seek_read(f, buf, at)? {
186
            0 => return Err(std::io::ErrorKind::UnexpectedEof.into()),
187
            n => {
188
                buf = &mut buf[n..];
189
                at += n as u64;
190
            }
191
        }
192
    }
193
    Ok(())
194
}
195
196
/// One file's history in a state index: where it is and its hash.
197
#[derive(Clone)]
198
struct RawHistory {
199
    from: Histories,
200
    at: u64,
201
    len: usize,
202
    sum: [u8; 32],
203
}
204
205
impl RawHistory {
206
    /// The history's bytes, checked against the hash the index holds.
20721848×
    fn bytes(&self) -> Result<Vec<u8>, ObjectError> {
20821848×
        let damaged = |why: String| ObjectError::DamagedIndex(why);
20921848×
        let b = self
21021848×
            .from
21121848×
            .read(self.at, self.len)
21221848×
            .map_err(|e| damaged(format!("a file's history cannot be read: {e}")))?;
21321848×
        if *blake3::hash(&b).as_bytes() != self.sum {
2147×
            return Err(damaged("a file's history does not match its hash".into()));
21521841×
        }
21621841×
        Ok(b)
21721848×
    }
218
}
219
220
/// The closures kept, and how many hashes they hold in all.
221
#[derive(Default)]
222
struct ClosureMemo {
223
    sets: HashMap<ChangeHash, Arc<HashSet<ChangeHash>>>,
224
    held: usize,
225
}
226
227
/// The most hashes the closure memo holds before it starts again: a few
228
/// hundred megabytes at most.
229
const CLOSURE_MEMO_HASHES: usize = 4_000_000;
230
231
#[derive(Clone, Default)]
232
struct DeferredBody {
233
    base: Option<DeferredBase>,
234
    edits: Vec<(ChangeHash, Vec<Edit>)>,
235
    /// The text blob and line count of each insert in `edits` left without
236
    /// its lines, in order: read when the graph is built.
237
    texts: Vec<TextRef>,
238
}
239
240
impl Deferred {
241141×
    fn from_body(body: DeferredBody) -> Deferred {
242141×
        Deferred {
243141×
            body: std::sync::OnceLock::from(Ok(body)),
244141×
            ..Deferred::default()
245141×
        }
246141×
    }
247
248
    /// The history, read and checked on first use.
249102407×
    fn body(&self) -> Result<&DeferredBody, ObjectError> {
250102407×
        self.body
251102407×
            .get_or_init(|| {
25237655×
                let mut b = match &self.raw {
253
                    // Matching its hash, it is what `write_index` wrote: it
254
                    // decodes.
2555476×
                    Some(raw) => raw
2565476×
                        .bytes()
2575476×
                        .and_then(|b| State::read_deferred_body(&b))
2585476×
                        .map_err(|e| e.to_string())?,
25932179×
                    None => DeferredBody::default(),
260
                };
26137654×
                b.edits.extend(self.more.iter().cloned());
26237654×
                b.texts.extend(self.more_texts.iter().cloned());
26337654×
                Ok(b)
26437655×
            })
265102407×
            .as_ref()
266102407×
            .map_err(|e| ObjectError::DamagedIndex(e.clone()))
267102407×
    }
268
269
    /// Add a change's edits to the history: beside the index's encoding
270
    /// while it is unread, so that nothing is read or decoded to add them.
27135237×
    fn add(&mut self, h: ChangeHash, edits: Vec<Edit>, texts: Vec<TextRef>) {
27235237×
        if self.raw.is_some() && !matches!(self.body.get(), Some(Ok(_))) {
2732×
            self.more.push((h, edits));
2742×
            self.more_texts.extend(texts);
275
            // A body found damaged stays so: what was added cannot mend it.
2762×
            return;
27735235×
        }
278
        // No encoding to read, or decoded already: this cannot fail.
27935235×
        let b = self.body_mut().expect("a history in memory");
28035235×
        b.edits.push((h, edits));
28135235×
        b.texts.extend(texts);
28235237×
    }
283
28435235×
    fn body_mut(&mut self) -> Result<&mut DeferredBody, ObjectError> {
28535235×
        self.body()?;
28635235×
        self.raw = None;
28735235×
        self.more.clear();
28835235×
        self.more_texts.clear();
28935235×
        Ok(self
29035235×
            .body
29135235×
            .get_mut()
29235235×
            .and_then(|b| b.as_mut().ok())
29335235×
            .expect("decoded above"))
29435235×
    }
295
29622865×
    fn into_body(mut self) -> Result<DeferredBody, ObjectError> {
29722865×
        self.body()?;
29822864×
        Ok(self
29922864×
            .body
30022864×
            .take()
30122864×
            .and_then(|b| b.ok())
30222864×
            .expect("decoded above"))
30322865×
    }
304
}
305
306
#[derive(Clone)]
307
enum DeferredBase {
308
    Inline(Value),
309
    Blob(ObjectRef),
310
}
311
312
/// A local index of a history-only state (oxygen#41), in the flat layout
313
/// of [`crate::flat`]: its change metadata, tree (with its view), replace
314
/// records and every file's deferred history with its graph key, so a
315
/// command reads it rather than replaying history. Derived only: written
316
/// from a state loaded the long way, and read back as the same state.
317
impl State {
318
    const INDEX_MAGIC: &'static [u8] = b"oxy state index 4\n";
319
320
    /// The index of this state, or `None` when it has anything an index
321
    /// does not hold: a built graph, or text in memory (a change added
322
    /// whole rather than as its skeleton).
323947×
    pub fn write_index(&self) -> Option<Vec<u8>> {
324
        use crate::flat::Writer;
325947×
        let deferred = self.deferred.as_ref()?;
326947×
        if !self.files.is_empty() {
3270×
            return None;
328947×
        }
329
        // The changes first, as a block a reader can take on its own (see
330
        // [`State::read_index_changes`]).
331947×
        let mut w = Writer::default();
332947×
        w.fixed(Self::INDEX_MAGIC);
333
        // In log order, newest first (oxygen#94): the log takes them as
334
        // they come, with no map and no sort.
335947×
        let mut changes: Vec<(&ChangeHash, &Arc<ChangeMeta>)> = self.changes.iter().collect();
336947×
        changes.sort_unstable_by(|a, b| log_order((a.0, &a.1.hlc), (b.0, &b.1.hlc)));
337947×
        w.count(changes.len());
338947×
        for (h, m) in changes {
339254×
            w.object(h);
340254×
            m.write_flat(&mut w);
341254×
        }
342947×
        let changes_block = std::mem::take(&mut w);
343947×
        w.bytes(&changes_block.0);
344
        // The tree and the files' histories as blocks of their own, so a
345
        // reader decodes them side by side.
346947×
        let mut tw = Writer::default();
347947×
        self.tree.write_flat(&mut tw);
348947×
        w.bytes(&tw.0);
349947×
        let mut replaces: Vec<(&NodeId, &Vec<ReplaceRecord>)> = self.replaces.iter().collect();
350947×
        replaces.sort_by_key(|(n, _)| **n);
351947×
        w.count(replaces.len());
352947×
        for (n, recs) in replaces {
3534×
            w.fixed(&n.0);
3544×
            w.count(recs.len());
355
            // In any order: which record is live does not depend on it.
3564×
            let mut recs: Vec<&ReplaceRecord> = recs.iter().collect();
3574×
            recs.sort();
3584×
            for (c, old, new) in recs {
3594×
                w.object(c);
3604×
                w.opt_object(old);
3614×
                w.opt_object(new);
3624×
            }
363
        }
364947×
        let mut front = w;
365
        // The table: per file its key and where its history is, with the
366
        // history's hash, which is checked when it is read (oxygen#94).
367947×
        let mut table = Writer::default();
368947×
        let mut histories: Vec<u8> = Vec::new();
369947×
        let mut nodes: Vec<(&NodeId, &Arc<Deferred>)> = deferred.iter().collect();
370947×
        nodes.sort_by_key(|(n, _)| **n);
371947×
        table.count(nodes.len());
37232708×
        for (n, d) in nodes {
37332708×
            let key = match d.key.get() {
37416372×
                Some(k) => *k,
375
                None => {
37616336×
                    let mut h = blake3::Hasher::new();
37716336×
                    h.update(b"oxy graph key 1\0");
37816336×
                    h.update(&n.0);
37916336×
                    let k = d.graph_key(h).ok()?;
38016336×
                    let _ = d.key.set(k);
38116336×
                    k
382
                }
383
            };
384
            // Unchanged since read: its bytes as they are, checked.
38532708×
            let bytes = match &d.raw {
38616372×
                Some(raw) if d.more.is_empty() => raw.bytes().ok()?,
38716336×
                _ => Self::write_deferred_body(d.body().ok()?)?,
388
            };
38932702×
            table.fixed(&n.0);
39032702×
            table.fixed(&key);
39132702×
            table.u64(histories.len() as u64);
39232702×
            table.u32(u32::try_from(bytes.len()).ok()?);
39332702×
            table.fixed(blake3::hash(&bytes).as_bytes());
39432702×
            histories.extend_from_slice(&bytes);
395
        }
396941×
        front.bytes(&table.0);
397941×
        let mut out = Writer::default();
398941×
        out.u64(front.0.len() as u64);
399941×
        out.fixed(&front.0);
400941×
        out.fixed(&histories);
401941×
        Some(out.0)
402947×
    }
403
404
    /// One file's history as an index encodes it; `None` when it holds
405
    /// text in memory, which an index does not.
40616336×
    fn write_deferred_body(d: &DeferredBody) -> Option<Vec<u8>> {
407
        use crate::flat::Writer;
40832830×
        let atom = |w: &mut Writer, a: &AtomRef| match a {
40916333×
            AtomRef::Start => w.u8(0),
41016415×
            AtomRef::End => w.u8(1),
41182×
            AtomRef::Atom { change, index } => {
41282×
                w.u8(2);
41382×
                w.object(change);
41482×
                w.u32(*index);
41582×
            }
41632830×
        };
41716336×
        let mut w = Writer::default();
4183×
        match &d.base {
41916333×
            None => w.u8(0),
4200×
            Some(DeferredBase::Blob(r)) => {
4210×
                w.u8(1);
4220×
                w.object(r);
4230×
            }
4243×
            Some(DeferredBase::Inline(v)) => {
4253×
                w.u8(2);
4263×
                w.bytes(&cbor::encode(v));
4273×
            }
428
        }
429
        // Each change's edits with the texts of its inserts, sorted by
430
        // change: a graph does not depend on the order changes applied
431
        // in, and the index is then the same however history was read.
43216336×
        let mut texts = d.texts.iter();
43316336×
        let mut per_change: Vec<(&ChangeHash, &Vec<Edit>, Vec<&TextRef>)> = Vec::new();
43416415×
        for (c, edits) in &d.edits {
43516415×
            let n = edits
43616415×
                .iter()
43716415×
                .filter(|e| matches!(e, Edit::Insert { lines, .. } if lines.is_empty()))
43816415×
                .count();
43916415×
            per_change.push((c, edits, texts.by_ref().take(n).collect()));
440
        }
44116336×
        per_change.sort_by_key(|(c, _, _)| **c);
44216336×
        w.count(per_change.len());
44316415×
        for (c, edits, _) in &per_change {
44416415×
            w.object(c);
44516415×
            w.count(edits.len());
44616415×
            for e in edits.iter() {
44716415×
                match e {
448
                    Edit::Insert {
44916415×
                        node,
45016415×
                        after,
45116415×
                        before,
45216415×
                        lines,
453
                    } => {
45416415×
                        if !lines.is_empty() {
4550×
                            return None;
45616415×
                        }
45716415×
                        w.u8(0);
45816415×
                        w.fixed(&node.0);
45916415×
                        atom(&mut w, after);
46016415×
                        atom(&mut w, before);
461
                    }
4620×
                    Edit::Delete { node, atoms } => {
4630×
                        w.u8(1);
4640×
                        w.fixed(&node.0);
4650×
                        w.count(atoms.len());
4660×
                        for r in atoms {
4670×
                            w.object(&r.change);
4680×
                            w.u32(r.from);
4690×
                            w.u32(r.to);
4700×
                        }
471
                    }
4720×
                    Edit::Replace { .. } => return None,
473
                }
474
            }
475
        }
47616336×
        let texts: Vec<&TextRef> = per_change
47716336×
            .iter()
47816415×
            .flat_map(|(_, _, t)| t.iter().copied())
47916336×
            .collect();
48016336×
        w.count(texts.len());
48116415×
        for t in texts {
48216415×
            match t {
4830×
                TextRef::Blob(r, count, form) => {
4840×
                    w.u8(0);
4850×
                    w.object(r);
4860×
                    w.u32(*count);
4870×
                    w.u8(match form {
4880×
                        crate::objects::TextForm::Cbor => 0,
4890×
                        crate::objects::TextForm::Raw => 1,
4900×
                        crate::objects::TextForm::CborFallback => 2,
491
                    });
492
                }
49316415×
                TextRef::Inline { change, start, end } => {
49416415×
                    w.u8(1);
49516415×
                    w.object(change);
49616415×
                    w.u32(*start);
49716415×
                    w.u32(*end);
49816415×
                }
499
            }
500
        }
50116336×
        Some(w.0)
50216336×
    }
503
504
    /// The state an index holds (see [`State::write_index`]).
505221×
    pub fn read_index(bytes: &[u8]) -> Result<State, ObjectError> {
506221×
        let bad = || ObjectError::Schema("state index: truncated".into());
507221×
        let front_len =
508221×
            usize::try_from(crate::flat::Reader::new(bytes).u64()?).map_err(|_| bad())?;
509221×
        let front = bytes.get(8..8 + front_len).ok_or_else(bad)?;
510221×
        let histories = Histories::Bytes(Arc::new(bytes[8 + front_len..].to_vec()));
511221×
        Self::read_index_front(front, histories)
512221×
    }
513
514
    /// An index's front, everything but the files' histories, with where
515
    /// those are: each is read, and checked against the hash the front
516
    /// holds, only when its graph is built (oxygen#94).
5171875×
    pub fn read_index_front(bytes: &[u8], histories: Histories) -> Result<State, ObjectError> {
518
        use crate::flat::Reader;
5191875×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
5201875×
        let mut r = Reader::new(bytes);
5211875×
        let mut st = State::new_history_only();
522
        {
5231875×
            let _t = crate::timing::phase("index: changes");
5241875×
            st.changes = Self::read_index_changes(r.bytes()?)?;
525
        }
5261875×
        let tree_bytes = r.bytes()?;
5271875×
        for _ in 0..r.count()? {
5282×
            let n = NodeId(r.fixed::<16>()?);
5292×
            let mut recs = Vec::new();
5302×
            for _ in 0..r.count()? {
5312×
                recs.push((r.object()?, r.opt_object()?, r.opt_object()?));
532
            }
5332×
            st.replaces.insert(n, recs);
534
        }
5351875×
        let deferred_bytes = r.bytes()?;
5361875×
        if !r.at_end() {
5370×
            return Err(bad("trailing bytes"));
5381875×
        }
5391875×
        let (tree, deferred) = rayon::join(
5401875×
            || TreeGraph::read_flat(&mut Reader::new(tree_bytes)),
5411875×
            || Self::read_deferred(deferred_bytes, &histories),
542
        );
5431875×
        st.tree = tree?;
5441875×
        st.deferred = Some(deferred?);
5451875×
        Ok(st)
5461875×
    }
547
548
    /// The changes of a state index: its first block, which a reader can
549
    /// take without the rest.
5501875×
    pub fn read_index_changes(
5511875×
        bytes: &[u8],
5521875×
    ) -> Result<crate::fasthash::FastMap<ChangeHash, Arc<ChangeMeta>>, ObjectError> {
5531875×
        Ok(Self::read_index_changes_listed(bytes)?
5541875×
            .into_iter()
5551875×
            .map(|(h, m)| (h, Arc::new(m)))
5561875×
            .collect())
5571875×
    }
558
559
    /// The same changes as a list in the order the index keeps them, which
560
    /// a current index keeps in log order ([`log_order`]): what the log
561
    /// needs (oxygen#94).
5622037×
    pub fn read_index_changes_listed(
5632037×
        bytes: &[u8],
5642037×
    ) -> Result<Vec<(ChangeHash, ChangeMeta)>, ObjectError> {
565
        use crate::flat::Reader;
5662037×
        let mut r = Reader::new(bytes);
5672037×
        if r.fixed::<18>()?.as_slice() != Self::INDEX_MAGIC {
5680×
            return Err(ObjectError::Schema("state index: not a state index".into()));
5692037×
        }
5702037×
        let n = r.count()?;
5712037×
        let mut changes = Vec::with_capacity(n);
5722037×
        for _ in 0..n {
57310170×
            let h = r.object()?;
57410170×
            changes.push((h, ChangeMeta::read_flat(&mut r)?));
575
        }
5762036×
        if !r.at_end() {
5770×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
5782036×
        }
5792036×
        Ok(changes)
5802037×
    }
581
582
    /// The deferred block: each node with its graph key and its body,
583
    /// left encoded (see [`Deferred`]).
5841875×
    fn read_deferred(
5851875×
        table: &[u8],
5861875×
        histories: &Histories,
5871875×
    ) -> Result<crate::fasthash::FastMap<NodeId, Arc<Deferred>>, ObjectError> {
588
        use crate::flat::Reader;
5891875×
        let _t = crate::timing::phase("index: deferred");
5901875×
        let mut r = Reader::new(table);
5911875×
        let mut deferred = crate::fasthash::FastMap::default();
5921875×
        let n = r.count()?;
5931875×
        deferred.reserve(n);
5941875×
        for _ in 0..n {
59516694×
            let id = NodeId(r.fixed::<16>()?);
59616694×
            let key = r.fixed::<32>()?;
597
            // The length is of bytes in the histories, not in this table:
598
            // checked against the histories' size below.
59916694×
            let (at, len, sum) = (r.u64()?, r.u32()? as usize, r.fixed::<32>()?);
60016694×
            if at
60116694×
                .checked_add(len as u64)
60216694×
                .is_none_or(|end| end > histories.len())
603
            {
6040×
                return Err(ObjectError::Schema(
6050×
                    "state index: a file's history lies outside it".into(),
6060×
                ));
60716694×
            }
60816694×
            let d = Deferred {
60916694×
                raw: Some(RawHistory {
61016694×
                    from: histories.clone(),
61116694×
                    at,
61216694×
                    len,
61316694×
                    sum,
61416694×
                }),
61516694×
                key: std::sync::OnceLock::from(key),
61616694×
                ..Deferred::default()
61716694×
            };
61816694×
            deferred.insert(id, Arc::new(d));
619
        }
6201875×
        if !r.at_end() {
6210×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
6221875×
        }
6231875×
        Ok(deferred)
6241875×
    }
625
626
    /// One node's deferred history as the index encodes it.
6275475×
    fn read_deferred_body(bytes: &[u8]) -> Result<DeferredBody, ObjectError> {
628
        use crate::flat::Reader;
6295475×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
6305486×
        let node = |r: &mut Reader| -> Result<NodeId, ObjectError> { Ok(NodeId(r.fixed::<16>()?)) };
63110972×
        let atom = |r: &mut Reader| -> Result<AtomRef, ObjectError> {
63210972×
            Ok(match r.u8()? {
6335469×
                0 => AtomRef::Start,
6345486×
                1 => AtomRef::End,
635
                2 => AtomRef::Atom {
63617×
                    change: r.object()?,
63717×
                    index: r.u32()?,
638
                },
6390×
                _ => return Err(bad("atom")),
640
            })
64110972×
        };
6425475×
        let mut r = Reader::new(bytes);
6435475×
        let base = match r.u8()? {
6445469×
            0 => None,
6450×
            1 => Some(DeferredBase::Blob(r.object()?)),
6466×
            _ => Some(DeferredBase::Inline(cbor::decode(r.bytes()?)?)),
647
        };
6485475×
        let mut edits = Vec::new();
6495475×
        for _ in 0..r.count()? {
6505486×
            let c = r.object()?;
6515486×
            let mut es = Vec::new();
6525486×
            for _ in 0..r.count()? {
6535486×
                es.push(match r.u8()? {
654
                    0 => Edit::Insert {
6555486×
                        node: node(&mut r)?,
6565486×
                        after: atom(&mut r)?,
6575486×
                        before: atom(&mut r)?,
6585486×
                        lines: crate::lines::Lines::default(),
659
                    },
660
                    1 => {
6610×
                        let node = node(&mut r)?;
6620×
                        let mut atoms = Vec::new();
6630×
                        for _ in 0..r.count()? {
6640×
                            atoms.push(crate::objects::AtomRange {
6650×
                                change: r.object()?,
6660×
                                from: r.u32()?,
6670×
                                to: r.u32()?,
668
                            });
669
                        }
6700×
                        Edit::Delete { node, atoms }
671
                    }
6720×
                    _ => return Err(bad("edit")),
673
                });
674
            }
6755486×
            edits.push((c, es));
676
        }
6775475×
        let mut texts = Vec::new();
6785475×
        for _ in 0..r.count()? {
6795486×
            texts.push(match r.u8()? {
680
                0 => TextRef::Blob(
6810×
                    r.object()?,
6820×
                    r.u32()?,
6830×
                    match r.u8()? {
6840×
                        0 => crate::objects::TextForm::Cbor,
6850×
                        1 => crate::objects::TextForm::Raw,
6860×
                        _ => crate::objects::TextForm::CborFallback,
687
                    },
688
                ),
689
                _ => TextRef::Inline {
6905486×
                    change: r.object()?,
6915486×
                    start: r.u32()?,
6925486×
                    end: r.u32()?,
693
                },
694
            });
695
        }
6965475×
        if !r.at_end() {
6970×
            return Err(bad("trailing bytes in a file's history"));
6985475×
        }
6995475×
        Ok(DeferredBody { base, edits, texts })
7005475×
    }
701
}
702
703
impl Clone for State {
7041450×
    fn clone(&self) -> State {
7051450×
        State {
7061450×
            changes: self.changes.clone(),
7071450×
            tree: self.tree.clone(),
7081450×
            files: self.files.clone(),
7091450×
            replaces: self.replaces.clone(),
7101450×
            // A cache: the clone builds its own.
7111450×
            closure: Default::default(),
7121450×
            levels: Default::default(),
7131450×
            deferred: self.deferred.clone(),
7141450×
        }
7151450×
    }
716
}
717
718
#[derive(Clone, Debug, PartialEq, Eq)]
719
pub enum FileContent {
720
    Text {
721
        bytes: Vec<u8>,
722
        materialized: Materialized,
723
    },
724
    /// Live blobs; more than one is a replace conflict (spec §9.3).
725
    Opaque {
726
        blobs: Vec<ObjectRef>,
727
    },
728
    Dir,
729
}
730
731
#[derive(Clone, Debug, PartialEq, Eq)]
732
pub struct FileState {
733
    pub node: NodeId,
734
    pub kind: NodeKind,
735
    pub mode: Mode,
736
    pub content: FileContent,
737
}
738
739
impl FileState {
74013562×
    pub fn is_conflicted(&self) -> bool {
74113562×
        match &self.content {
74212651×
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
743243×
            FileContent::Opaque { blobs } => blobs.len() > 1,
744668×
            FileContent::Dir => false,
745
        }
74613562×
    }
747
}
748
749
/// See `State::conflict_regions`.
750
#[derive(Clone, Debug, Default, PartialEq, Eq)]
751
pub struct ConflictRegions {
752
    pub plain: Vec<(AtomKey, Vec<u8>)>,
753
    pub region_atoms: Vec<AtomKey>,
754
    pub contributors: Vec<ChangeHash>,
755
}
756
757
/// The whole tree of a state, materialized.
758
#[derive(Clone, Debug, Default)]
759
pub struct Snapshot {
760
    pub tree: TreeView,
761
    pub files: BTreeMap<String, FileState>,
762
    /// Text files left unrendered by [`State::materialize_except`]: their
763
    /// `bytes` are empty and they are known not to be conflicted.
764
    pub unrendered: BTreeSet<String>,
765
}
766
767
impl Snapshot {
7682010×
    pub fn is_conflicted(&self) -> bool {
76913243×
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
7702010×
    }
771
}
772
77361710×
fn vertex(r: AtomRef) -> Vertex {
77461710×
    match r {
77525950×
        AtomRef::Start => Vertex::Start,
77627346×
        AtomRef::End => Vertex::End,
7778414×
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
778
    }
77961710×
}
780
781
/// Replace self references in a tree op with the concrete change hash.
78238605×
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
78338605×
    match op {
784821×
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
785821×
            node: *node,
786821×
            placement: placement.resolve(me),
787821×
        },
788
        TreeOp::Move {
789152×
            node,
790152×
            old,
791152×
            parent,
792152×
            name,
793152×
        } => TreeOp::Move {
794152×
            node: *node,
795152×
            old: old.resolve(me),
796152×
            parent: *parent,
797152×
            name: name.clone(),
798152×
        },
79922×
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
80022×
            node: *node,
80122×
            old: old.resolve(me),
80222×
            mode: *mode,
80322×
        },
80437610×
        add @ TreeOp::AddNode { .. } => add.clone(),
805
    }
80638605×
}
807
808
/// Apply one change's edits of one file (inserts and deletes; replaces
809
/// live beside the graphs) to that file's graph.
81025782×
fn apply_file_edits(g: &mut FileGraph, h: ChangeHash, edits: Vec<Edit>) {
811
    // The graph's kept order, if any, follows the edits (see `Order`).
81225782×
    let order = g.take_order();
81325782×
    let mut inserts: Vec<(Vertex, Vertex, u32, u32)> = Vec::new();
81425782×
    let mut deleted: Vec<crate::graph::AtomKey> = Vec::new();
81525782×
    let mut next = 0u32;
81627874×
    for e in edits {
81727874×
        match e {
818
            Edit::Insert {
81926598×
                after,
82026598×
                before,
82126598×
                lines,
822
                ..
82326598×
            } => {
82426598×
                let first = next;
82526598×
                let count = lines.len() as u32;
82626598×
                next += count;
82726598×
                let (after, before) = (vertex(after.resolve(h)), vertex(before.resolve(h)));
82826598×
                inserts.push((after, before, first, count));
82926598×
                g.insert_owned(h, first, after, before, lines);
83026598×
            }
8311276×
            Edit::Delete { atoms, .. } => {
8322326×
                for r in atoms {
8332326×
                    let r = r.resolve(h);
8342405×
                    deleted.extend((r.from..r.to).map(|i| (r.change, i)));
8352326×
                    g.delete(h, &r);
836
                }
837
            }
8380×
            Edit::Replace { .. } => {}
839
        }
840
    }
84125782×
    if let Some(o) = order {
84257×
        g.keep_spliced(o, h, &inserts, &deleted);
84325725×
    }
84425782×
}
845
846
/// Build the graphs of deferred entries: their checkpoint bases and the
847
/// texts of inserts read without their lines are loaded in one call, then
848
/// the graphs are built in parallel (they are independent).
8493759×
fn build_deferred(
8503759×
    taken: Vec<(NodeId, Deferred)>,
8513759×
    load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
8523759×
    read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
8533759×
) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
8543759×
    let mut taken: Vec<(NodeId, DeferredBody)> = taken
8553759×
        .into_iter()
85622865×
        .map(|(n, d)| Ok((n, d.into_body()?)))
8573759×
        .collect::<Result<_, ObjectError>>()?;
8583758×
    let mut refs: Vec<ObjectRef> = taken
8593758×
        .iter()
8603758×
        .filter_map(|(_, d)| match &d.base {
8616×
            Some(DeferredBase::Blob(r)) => Some(*r),
86222858×
            _ => None,
86322864×
        })
8643758×
        .collect();
865
    // Text blobs of inserts read without their lines, after the bases.
8663758×
    let bases = refs.len();
86722864×
    refs.extend(taken.iter().flat_map(|(_, d)| {
86825946×
        d.texts.iter().filter_map(|t| match t {
86970×
            TextRef::Blob(r, _, _) => Some(*r),
87025876×
            TextRef::Inline { .. } => None,
87125946×
        })
87222864×
    }));
873
    // And the encodings of changes whose inline inserts are needed,
874
    // each read once.
8753758×
    let reading = crate::timing::phase("graphs: read changes and blobs");
8763758×
    let mut changes: HashMap<ChangeHash, Arc<Vec<u8>>> = HashMap::new();
87725946×
    for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
87825946×
        if let TextRef::Inline { change, .. } = t {
87925876×
            if !changes.contains_key(change) {
8805961×
                changes.insert(*change, read_change(change)?);
88119915×
            }
88270×
        }
883
    }
8843758×
    let n_changes = changes.len();
8853758×
    drop(reading);
8863758×
    let reading = crate::timing::phase("graphs:   of which blobs");
8873758×
    let mut blobs = if refs.is_empty() {
8883687×
        Vec::new()
889
    } else {
89071×
        load(&refs)?
891
    };
8923755×
    if crate::timing::enabled() {
8932×
        eprintln!(
8942×
            "timing graphs: {} graphs, {n_changes} changes, {} blobs",
8952×
            taken.len(),
8962×
            refs.len()
8972×
        );
8983753×
    }
8993755×
    if blobs.len() != refs.len() {
9000×
        return Err(ObjectError::Schema("graph blobs: wrong count".into()));
9013755×
    }
9023755×
    drop(reading);
9033755×
    let lines = crate::timing::phase("graphs: hand out blobs");
9043755×
    let mut texts = blobs.split_off(bases).into_iter();
9053755×
    let mut blobs = blobs.into_iter();
906
    // Hand each graph its own blobs, in order, then fill in its inserts'
907
    // lines and build it, all in parallel: graphs are independent.
908
    type Work = (NodeId, DeferredBody, Option<Vec<u8>>, Vec<Vec<u8>>);
9093755×
    let mut work: Vec<Work> = Vec::with_capacity(taken.len());
91022861×
    for (node, d) in taken.drain(..) {
91122861×
        let wanted = d
91222861×
            .texts
91322861×
            .iter()
91425944×
            .filter(|t| matches!(t, TextRef::Blob(..)))
91522861×
            .count();
91622861×
        let mine: Vec<Vec<u8>> = texts.by_ref().take(wanted).collect();
91722861×
        if mine.len() != wanted {
9180×
            return Err(ObjectError::Schema("text blobs: wrong count".into()));
91922861×
        }
92022861×
        let bytes = match &d.base {
921
            Some(DeferredBase::Blob(_)) => Some(
9225×
                blobs
9235×
                    .next()
9245×
                    .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
925
            ),
92622856×
            _ => None,
927
        };
92822861×
        work.push((node, d, bytes, mine));
929
    }
9303755×
    drop(lines);
9313755×
    let _t = crate::timing::phase("graphs: lines and build");
932
    use rayon::prelude::*;
9333755×
    let changes = &changes;
9343755×
    let built: Vec<(NodeId, FileGraph)> = work
9353755×
        .into_par_iter()
93622861×
        .map(|(node, mut d, bytes, mine)| {
937
            // Fill in the lines of inserts read without them, in order.
93822861×
            let mut want = std::mem::take(&mut d.texts).into_iter();
93922861×
            let mut mine = mine.into_iter();
94025333×
            for (_, edits) in d.edits.iter_mut() {
94126997×
                for e in edits.iter_mut() {
94226997×
                    if let Edit::Insert { lines, .. } = e {
94325951×
                        if lines.is_empty() {
94425944×
                            *lines = match want.next() {
94568×
                                Some(TextRef::Blob(_, count, form)) => {
94668×
                                    let content = mine.next().ok_or_else(|| {
9470×
                                        ObjectError::Schema("text blobs: wrong count".into())
9480×
                                    })?;
94968×
                                    crate::objects::text_lines(&content, count, form)?
950
                                }
95125876×
                                Some(TextRef::Inline { change, start, end }) => {
95225876×
                                    let bytes = &changes[&change];
95325876×
                                    let range = bytes
95425876×
                                        .get(start as usize..end as usize)
95525876×
                                        .ok_or_else(|| {
9560×
                                            ObjectError::Schema(
9570×
                                                "an inline insert lies outside its change".into(),
9580×
                                            )
9590×
                                        })?;
96025876×
                                    crate::objects::inline_lines(range)?
961
                                }
962
                                None => {
9630×
                                    return Err(ObjectError::Schema(
9640×
                                        "an insert's text is missing".into(),
9650×
                                    ))
966
                                }
967
                            };
9687×
                        }
9691046×
                    }
970
                }
971
            }
97222861×
            let mut graph = match (d.base.take(), bytes) {
97396×
                (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
9745×
                (Some(DeferredBase::Blob(_)), Some(bytes)) => {
9755×
                    FileGraph::from_value(&cbor::decode(&bytes)?)?
976
                }
97722760×
                _ => FileGraph::default(),
978
            };
97925333×
            for (h, edits) in std::mem::take(&mut d.edits) {
98025333×
                apply_file_edits(&mut graph, h, edits);
98125333×
            }
98222861×
            Ok((node, graph))
98322861×
        })
9843755×
        .collect::<Result<_, ObjectError>>()?;
9853755×
    Ok(built)
9863759×
}
987
988
impl State {
989693×
    pub fn new() -> Self {
990693×
        Self::default()
991693×
    }
992
993
    /// An empty state for history only: changes and tree are kept, file
994
    /// edits are recorded but no file graph is built until
995
    /// [`State::load_graphs`] asks for it. For log and other commands that
996
    /// need no file contents, or only a few files.
9973602×
    pub fn new_history_only() -> Self {
9983602×
        State {
9993602×
            deferred: Some(Default::default()),
10003602×
            ..Self::default()
10013602×
        }
10023602×
    }
1003
1004
    /// Whether `node`'s file graph is built (always, in a full state).
100540×
    pub fn is_built(&self, node: &NodeId) -> bool {
100640×
        self.deferred.is_none() || self.files.contains_key(node)
100740×
    }
1008
1009
    /// Whether this state builds file graphs only when asked
1010
    /// ([`State::new_history_only`]), even if it has none waiting.
10113360×
    pub fn is_history_only(&self) -> bool {
10123360×
        self.deferred.is_some()
10133360×
    }
1014
1015
    /// Whether this state holds every file graph.
10162780×
    pub fn is_full(&self) -> bool {
10172780×
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
10182780×
    }
1019
1020
    /// The graph of `node`, which must be loaded: asking a history-only
1021
    /// state for a graph it has not built is a bug, never an empty file.
102225257×
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
102325257×
        if let Some(d) = &self.deferred {
102410011×
            assert!(
102510011×
                !d.contains_key(node),
1026
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
10271×
                node.short(12)
1028
            );
102915246×
        }
103025256×
        self.files.get(node).map(|g| g.as_ref())
103125256×
    }
1032
1033
    /// Operations over every file need every graph.
10342773×
    fn require_full(&self, what: &str) {
10352773×
        assert!(
10362773×
            self.is_full(),
1037
            "{what} needs every file graph; this state was loaded for history only"
1038
        );
10392772×
    }
1040
1041
    /// Build the graphs of `nodes` in a history-only state: from their
1042
    /// checkpoint base (blobs read in one batch through `load`) and their
1043
    /// deferred edits. Nodes already built, or with no graph, are skipped.
10443682×
    pub fn load_graphs(
10453682×
        &mut self,
10463682×
        nodes: &[NodeId],
10473682×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
10483682×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
10493682×
    ) -> Result<(), ObjectError> {
10503682×
        let Some(deferred) = self.deferred.as_mut() else {
10510×
            return Ok(());
1052
        };
10533682×
        let taken: Vec<(NodeId, Deferred)> = nodes
10543682×
            .iter()
105523048×
            .filter_map(|n| deferred.remove(n).map(|d| (*n, Arc::unwrap_or_clone(d))))
10563682×
            .collect();
10573682×
        let built = build_deferred(taken, load, read_change)?;
10583678×
        self.files
105922800×
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
10603678×
        Ok(())
10613682×
    }
1062
1063
    /// The graphs of `nodes`, built from this history-only state's deferred
1064
    /// edits without building them in it: the state stays history only, so
1065
    /// changes read without their lines can still be added to it and every
1066
    /// graph keeps its key. For a caller that renders a few files of many
1067
    /// states in turn (verifying an import).
106877×
    pub fn build_graphs_detached(
106977×
        &self,
107077×
        nodes: &[NodeId],
107177×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
107277×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
107377×
    ) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
107477×
        let Some(deferred) = self.deferred.as_ref() else {
10750×
            return Ok(Vec::new());
1076
        };
1077
        // A file this state has built has no deferred history: its graph
1078
        // is the built one, copied. Built from an empty history instead, it
1079
        // rendered as an empty file, and a merge taking this path recorded
1080
        // the whole file as inserted again, conflicting with itself (#71).
108177×
        let mut built: Vec<(NodeId, FileGraph)> = Vec::new();
108277×
        let mut copies: Vec<(NodeId, Deferred)> = Vec::new();
108377×
        for n in nodes {
108464×
            match (self.files.get(n), deferred.get(n)) {
10853×
                (Some(g), _) => built.push((*n, (**g).clone())),
108661×
                (None, d) => copies.push((*n, d.map(|d| (**d).clone()).unwrap_or_default())),
1087
            }
1088
        }
108977×
        let mut out = build_deferred(copies, load, read_change)?;
109077×
        out.extend(built);
109177×
        Ok(out)
109277×
    }
1093
1094
    /// Render a graph built for this state (see
1095
    /// [`State::build_graphs_detached`]), as [`State::render_file`] does.
109664×
    pub fn render_graph(&self, g: &FileGraph) -> (Vec<u8>, Materialized) {
109764×
        let m = g.materialize(self);
109864×
        let bytes = g.render(&m, &|h| self.label(h));
109964×
        (bytes, m)
110064×
    }
1101
1102
    /// Every file graph a history-only state has not built, deleted files'
1103
    /// included.
110477×
    pub fn unbuilt_nodes(&self) -> Vec<NodeId> {
110577×
        self.deferred
110677×
            .as_ref()
110777×
            .map(|d| d.keys().copied().collect())
110877×
            .unwrap_or_default()
110977×
    }
1110
1111
    /// Drop the built graphs of `nodes`, for a caller rendering a large
1112
    /// tree a batch at a time. The state can no longer render those files,
1113
    /// so it must not be used for them again.
1114442×
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
11156040×
        for n in nodes {
11166040×
            self.files.remove(n);
11176040×
        }
1118442×
    }
1119
1120
    /// Build every graph a history-only state has not built, making it full.
11211853×
    pub fn load_all_graphs(
11221853×
        &mut self,
11231853×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
11241853×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
11251853×
    ) -> Result<(), ObjectError> {
11261853×
        let nodes: Vec<NodeId> = match &self.deferred {
11271853×
            Some(d) => d.keys().copied().collect(),
11280×
            None => return Ok(()),
1129
        };
11301853×
        self.load_graphs(&nodes, load, read_change)?;
11311853×
        self.deferred = None;
11321853×
        Ok(())
11331853×
    }
1134
1135
    /// The one text a file's history is, when it is a single insert of
1136
    /// the whole file into nothing (a file added once and never edited,
1137
    /// with no checkpoint base): its rendering is that text, so it needs
1138
    /// no graph. `None` otherwise, or when the graph is built.
11395893×
    pub fn single_text(&self, node: &NodeId) -> Option<TextRef> {
11405893×
        if self.files.contains_key(node) {
11410×
            return None;
11425893×
        }
1143
        // A history that cannot be read is no single text: building its
1144
        // graph reports why.
11455893×
        let d = self.deferred.as_ref()?.get(node)?.body().ok()?;
11465814×
        let [(_, edits)] = d.edits.as_slice() else {
1147249×
            return None;
1148
        };
1149
        let [Edit::Insert {
1150
            after: AtomRef::Start,
1151
            before: AtomRef::End,
11525565×
            lines,
1153
            ..
11545565×
        }] = edits.as_slice()
1155
        else {
11560×
            return None;
1157
        };
11585565×
        match (&d.base, d.texts.as_slice()) {
11595565×
            (None, [t]) if lines.is_empty() => Some(*t),
11600×
            _ => None,
1161
        }
11625893×
    }
1163
1164
    /// A key for the graph of `node` in a history-only state that has not
1165
    /// built it: equal keys mean equal graphs, so equal renderings (a
1166
    /// rendering depends only on the graph and on the changes' own
1167
    /// immutable metadata). It names the node, its checkpoint base (a blob,
1168
    /// an inline value, or none) and the set of later changes that edited
1169
    /// the file.
1170
    /// `None` for a full state or a graph already built.
117128715×
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
117228715×
        let deferred = self.deferred.as_ref()?;
117328679×
        if self.files.contains_key(node) {
1174408×
            return None;
117528271×
        }
117628271×
        let mut h = blake3::Hasher::new();
117728271×
        h.update(b"oxy graph key 1\0");
1178
        // A change's edits are applied per node: the node is part of it.
117928271×
        h.update(&node.0);
118028271×
        let Some(d) = deferred.get(node) else {
1181
            // Never edited: the empty graph.
1182245×
            h.update(&[0]);
1183245×
            return Some(*h.finalize().as_bytes());
1184
        };
1185
        // A history that cannot be read has no key: the file is read.
118628026×
        if let Some(k) = d.key.get() {
118722205×
            return Some(*k);
11885821×
        }
11895821×
        let k = d.graph_key(h).ok()?;
11905821×
        Some(*d.key.get_or_init(|| k))
119128715×
    }
1192
11933495×
    pub fn len(&self) -> usize {
11943495×
        self.changes.len()
11953495×
    }
1196
1197
    /// Turn this history-only state's built graphs back into deferred
1198
    /// histories, each starting from its graph encoded as a checkpoint
1199
    /// graph and stored by `store` (it returns the blob's reference): what
1200
    /// they held stays, and memory goes back to what a history-only state
1201
    /// costs. A graph built later again decodes that blob and applies only
1202
    /// the edits that came after. Graph keys change (the base is now a
1203
    /// blob), which only means a cached rendering is not reused.
12041×
    pub fn shed_graphs<E>(
12051×
        &mut self,
12061×
        mut store: impl FnMut(&[u8]) -> Result<ObjectRef, E>,
12071×
    ) -> Result<usize, E> {
1208
        use rayon::prelude::*;
12091×
        let Some(deferred) = self.deferred.as_mut() else {
12100×
            return Ok(0);
1211
        };
12121×
        let graphs: Vec<(NodeId, Arc<FileGraph>)> = self.files.drain().collect();
12131×
        let encoded: Vec<(NodeId, Vec<u8>)> = graphs
12141×
            .par_iter()
12152×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
12161×
            .collect();
12171×
        drop(graphs);
12181×
        let shed = encoded.len();
12192×
        for (node, bytes) in encoded {
12202×
            let blob = store(&bytes)?;
12212×
            deferred.insert(
12222×
                node,
12232×
                Arc::new(Deferred::from_body(DeferredBody {
12242×
                    base: Some(DeferredBase::Blob(blob)),
12252×
                    ..DeferredBody::default()
12262×
                })),
1227
            );
1228
        }
12291×
        Ok(shed)
12301×
    }
1231
1232
    /// How many file graphs this state has built.
123377×
    pub fn built_count(&self) -> usize {
123477×
        self.files.len()
123577×
    }
1236
1237
    /// Atoms in this state's built graphs, live and deleted: what their
1238
    /// memory follows, since a graph keeps every line its file ever had.
123951×
    pub fn built_atoms(&self) -> usize {
124056×
        self.files.values().map(|g| g.atom_count()).sum()
124151×
    }
1242
1243
    /// Edits held in the deferred histories of files not built, and the
1244
    /// most any one file holds (for measuring, #25).
12450×
    pub fn deferred_edit_count(&self) -> (usize, usize) {
12460×
        let Some(d) = self.deferred.as_ref() else {
12470×
            return (0, 0);
1248
        };
12490×
        let mut total = 0;
12500×
        let mut most = 0;
12510×
        for v in d.values() {
12520×
            let n: usize = v
12530×
                .body()
12540×
                .map_or(0, |b| b.edits.iter().map(|(_, e)| e.len()).sum());
12550×
            total += n;
12560×
            most = most.max(n);
1257
        }
12580×
        (total, most)
12590×
    }
1260
}
1261
1262
impl Deferred {
1263
    /// See [`State::graph_key`]: `h` has taken the node already.
126422157×
    fn graph_key(&self, mut h: blake3::Hasher) -> Result<[u8; 32], ObjectError> {
126522157×
        let d = self.body()?;
126613×
        match &d.base {
126722144×
            None => h.update(&[0]),
12680×
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
126913×
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
1270
        };
127122157×
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
127222157×
        changes.sort();
127322157×
        changes.dedup();
127422157×
        h.update(&(changes.len() as u64).to_le_bytes());
127523520×
        for c in changes {
127623520×
            h.update(&c.0);
127723520×
        }
127822157×
        Ok(*h.finalize().as_bytes())
127922157×
    }
1280
}
1281
1282
impl State {
12830×
    pub fn is_empty(&self) -> bool {
12840×
        self.changes.is_empty()
12850×
    }
128613765×
    pub fn contains(&self, h: &ChangeHash) -> bool {
128713765×
        self.changes.contains_key(h)
128813765×
    }
128964×
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
129064×
        self.changes.get(h).map(|m| &**m)
129164×
    }
12921443×
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
12933520×
        self.changes.iter().map(|(h, m)| (h, &**m))
12941443×
    }
129517686×
    pub fn tree(&self) -> &TreeGraph {
129617686×
        &self.tree
129717686×
    }
1298535×
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
1299535×
        self.graph(node)
1300535×
    }
1301
1302
    /// Add a change whose dependencies are already present.
13032844×
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
13042844×
        let h = change.hash();
13052844×
        self.add_hashed(h, change)
13062844×
    }
1307
1308
    /// [`State::add`] for a change whose hash `h` is already known (it was
1309
    /// just stored), so it is not encoded again.
13103505×
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
13113505×
        if self.changes.contains_key(&h) {
131237×
            return Ok(h);
13133468×
        }
13144932×
        for d in &change.deps {
13154932×
            if !self.changes.contains_key(d) {
13162×
                return Err(StateError::MissingDep(*d, h));
13174930×
            }
1318
        }
13193466×
        self.add_known(h, change, Vec::new());
13203466×
        Ok(h)
13213505×
    }
1322
1323
    /// Add a change in any order; call `validate` once all are in.
1324982×
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
1325982×
        let h = change.hash();
1326982×
        self.add_known(h, change, Vec::new());
1327982×
        h
1328982×
    }
1329
1330
    /// Add a change just stored under hash `h` to a history-only state that
1331
    /// has built some graphs: an edit of a built graph is applied whole
1332
    /// (from `full`), and one of a file not built waits without its text
1333
    /// (from `skeleton` and its `texts`, as the store reads it back), so the
1334
    /// state holds no text it has not built. A Git import adds each change
1335
    /// it makes this way, keeping memory to what changes.
133692×
    pub fn add_known_mixed(
133792×
        &mut self,
133892×
        h: ChangeHash,
133992×
        full: Change,
134092×
        skeleton: Change,
134192×
        texts: Vec<TextRef>,
134292×
    ) {
134392×
        if self.deferred.is_none() || self.changes.contains_key(&h) {
13440×
            self.add_known(h, full, Vec::new());
13450×
            return;
134692×
        }
1347
        let Change {
134892×
            version,
134992×
            change_id,
135092×
            deps,
135192×
            author,
135292×
            hlc,
135392×
            message,
135492×
            tree_ops,
135592×
            edits: full_edits,
135692×
            kind,
135792×
        } = full;
135892×
        let mut texts = texts.into_iter();
135992×
        let mut edits = Vec::with_capacity(full_edits.len());
136092×
        let mut kept = Vec::new();
136197×
        for (f, s) in full_edits.into_iter().zip(skeleton.edits) {
136297×
            let text = match &s {
136377×
                Edit::Insert { lines, .. } if lines.is_empty() => texts.next(),
136420×
                _ => None,
1365
            };
136697×
            if self.files.contains_key(&f.node()) {
136745×
                edits.push(f);
136852×
            } else {
136952×
                edits.push(s);
137052×
                kept.extend(text);
137152×
            }
1372
        }
137392×
        let c = Change {
137492×
            version,
137592×
            change_id,
137692×
            deps,
137792×
            author,
137892×
            hlc,
137992×
            message,
138092×
            tree_ops,
138192×
            edits,
138292×
            kind,
138392×
        };
138492×
        self.add_known(h, c, kept);
138592×
    }
1386
1387
    /// Add a change read from the store under hash `h`, without hashing it
1388
    /// again (for a version 2 change that means chunking all its text).
1389
    /// `texts` names, in order, the inserts left without their lines (see
1390
    /// [`crate::store::Store::get_change_lazy`]); only a history-only state
1391
    /// takes them, and only for graphs it has not built.
139212340×
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
139312340×
        if self.changes.contains_key(&h) {
13940×
            return;
139512340×
        }
139612340×
        let meta = ChangeMeta::of(&change);
139712340×
        self.apply_with(h, change, texts);
139812340×
        self.changes.insert(h, Arc::new(meta));
139912340×
        {
140012340×
            let mut m = self.closure.write().unwrap();
140112340×
            m.sets.clear();
140212340×
            m.held = 0;
140312340×
        }
140412340×
    }
1405
1406
    // ------------------------------------------------------------ checkpoints (spec §11)
1407
1408
    /// Serialize the whole state in payload version 1: change metadata,
1409
    /// tree, file graphs, replaces, all in one value (spec §11).
1410380×
    pub fn checkpoint_payload(&self) -> Vec<u8> {
1411380×
        self.require_full("a checkpoint");
1412380×
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
1413380×
        nodes.sort();
1414380×
        let files = Value::Array(
1415380×
            nodes
1416380×
                .into_iter()
14171440×
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
1418380×
                .collect(),
1419
        );
1420380×
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
1421380×
    }
1422
1423
    /// Each file graph encoded on its own, by node, for a version 2 payload
1424
    /// (spec §11): the graphs of large files become blobs of their own.
142518×
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
1426
        use rayon::prelude::*;
142718×
        self.require_full("a checkpoint");
142818×
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
142953×
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
143018×
        nodes.sort_by_key(|(n, _)| **n);
143118×
        nodes
143218×
            .into_par_iter()
143353×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
143418×
            .collect()
143518×
    }
1436
1437
    /// The payload version 2 index for the graphs of
1438
    /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than
1439
    /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by
1440
    /// `blob_of` (the ObjectRef of the blob holding its encoding).
144118×
    pub fn checkpoint_index(
144218×
        &self,
144318×
        graphs: &[(NodeId, Vec<u8>)],
144418×
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
144518×
    ) -> Vec<u8> {
144618×
        let files = Value::Array(
144718×
            graphs
144818×
                .iter()
144953×
                .map(|(n, enc)| {
145053×
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
145146×
                        cbor::decode(enc).expect("an encoded graph decodes")
1452
                    } else {
14537×
                        Value::Bytes(blob_of(enc).0.to_vec())
1454
                    };
145553×
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
145653×
                })
145718×
                .collect(),
1458
        );
145918×
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
146018×
    }
1461
1462
    /// The payload map around `files`: changes, tree and replaces as in version 1.
1463398×
    fn payload_value(&self, version: u64, files: Value) -> Value {
1464398×
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
1465398×
        hashes.sort();
1466398×
        let changes = Value::Array(
1467398×
            hashes
1468398×
                .into_iter()
14692231×
                .map(|h| {
14702231×
                    let m = &self.changes[h];
14712231×
                    Value::Array(vec![
14722231×
                        Value::Bytes(h.0.to_vec()),
14732231×
                        Value::Bytes(m.change_id.0.to_vec()),
14742231×
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
14752231×
                        Value::Text(m.message.clone()),
14762231×
                        Value::Uint(m.hlc.wall_ms),
14772231×
                        Value::Uint(m.hlc.logical as u64),
14782231×
                        Value::Uint(m.kind.tag()),
14792231×
                        Value::Bytes(m.author.0.to_vec()),
1480
                    ])
14812231×
                })
1482398×
                .collect(),
1483
        );
1484398×
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
1485398×
        rnodes.sort();
1486398×
        let opt =
148710×
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
1488398×
        let replaces = Value::Array(
1489398×
            rnodes
1490398×
                .into_iter()
1491398×
                .map(|n| {
14925×
                    Value::Array(vec![
14935×
                        Value::Bytes(n.0.to_vec()),
1494
                        Value::Array(
14955×
                            self.replaces[n]
14965×
                                .iter()
14975×
                                .map(|(c, o, nw)| {
14985×
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
14995×
                                })
15005×
                                .collect(),
1501
                        ),
1502
                    ])
15035×
                })
1504398×
                .collect(),
1505
        );
1506398×
        Value::map([
1507398×
            (0, Value::Uint(version)),
1508398×
            (1, changes),
1509398×
            (2, self.tree.to_value()),
1510398×
            (3, files),
1511398×
            (4, replaces),
1512398×
        ])
1513398×
    }
1514
1515
    /// Decode a version 1 payload (the whole state in one value). A
1516
    /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`].
151737×
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
151837×
        State::from_checkpoint(bytes, |_| {
15191×
            Err(ObjectError::Schema(
15201×
                "a version 2 checkpoint needs its graph blobs".into(),
15211×
            ))
15221×
        })
152337×
    }
1524
1525
    /// Decode a checkpoint payload of either version (spec §11). For
1526
    /// version 2, `load` returns the contents of the named graph blobs, in
1527
    /// order; the graphs are then decoded in parallel.
152860×
    pub fn from_checkpoint(
152960×
        bytes: &[u8],
153060×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
153160×
    ) -> Result<State, ObjectError> {
1532
        use rayon::prelude::*;
153360×
        let v = cbor::decode(bytes)?;
153459×
        let m = o::map(&v, "checkpoint payload")?;
153559×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
153659×
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
15371×
            return Err(ObjectError::Schema(format!(
15381×
                "checkpoint payload version {version} is not supported"
15391×
            )));
154058×
        }
154158×
        let mut st = State::payload_common(m)?;
154258×
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
154358×
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
1544227×
        for f in entries {
1545227×
            let e = o::array(f, "file")?;
1546227×
            if e.len() != 2 {
15470×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1548227×
            }
1549227×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1550227×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1551227×
            parsed.push((node, &e[1]));
1552
        }
1553
        // Version 2 names large graphs by blob: fetch those in one batch.
155458×
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
155558×
        if version == CHECKPOINT_INDEX_VERSION {
155620×
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
155720×
                .iter()
155890×
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
155920×
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
156020×
                .collect::<Result<_, ObjectError>>()?;
156120×
            if !wanted.is_empty() {
15627×
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
15633×
                let contents = {
15647×
                    let _t = crate::timing::phase("load:   graph blobs read");
15657×
                    load(&refs)?
1566
                };
15673×
                if contents.len() != refs.len() {
15680×
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
15693×
                }
15703×
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
157113×
            }
1572137×
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
15730×
            return Err(ObjectError::Schema(
15740×
                "a version 1 payload holds graphs inline".into(),
15750×
            ));
157638×
        }
1577
        // File graphs are independent; decode and build them in parallel.
157854×
        let graphs = parsed
157954×
            .par_iter()
1580221×
            .map(|(node, entry)| {
1581221×
                let graph = match fetched.get(node) {
15823×
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
1583218×
                    None => FileGraph::from_value(entry)?,
1584
                };
1585221×
                Ok((*node, graph))
1586221×
            })
158754×
            .collect::<Result<Vec<_>, ObjectError>>()?;
158854×
        st.files
1589221×
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
159054×
        Ok(st)
159160×
    }
1592
1593
    /// The graph blobs a payload names: empty for version 1.
15949×
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
15959×
        let v = cbor::decode(bytes)?;
15969×
        let m = o::map(&v, "checkpoint payload")?;
15979×
        let mut out = Vec::new();
159827×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
159927×
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
16006×
                out.push(o::oref(entry, "graph blob")?);
160121×
            }
1602
        }
16039×
        Ok(out)
16049×
    }
1605
1606
    /// Decode a checkpoint payload for history only: a version 2 payload's
1607
    /// graphs are noted, not read or built, and come later through
1608
    /// [`State::load_graphs`]. A version 1 payload holds them inline and is
1609
    /// decoded in full.
161042×
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
161142×
        let v = cbor::decode(bytes)?;
161242×
        let m = o::map(&v, "checkpoint payload")?;
161342×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
161442×
        if version != CHECKPOINT_INDEX_VERSION {
16151×
            return State::from_checkpoint_payload(bytes);
161641×
        }
161741×
        let mut st = State::payload_common(m)?;
161841×
        let mut deferred = crate::fasthash::FastMap::default();
1619139×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1620139×
            let e = o::array(f, "file")?;
1621139×
            if e.len() != 2 {
16220×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1623139×
            }
1624139×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1625139×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1626139×
            let base = match &e[1] {
16274×
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
1628135×
                other => DeferredBase::Inline(other.clone()),
1629
            };
1630139×
            deferred.insert(
1631139×
                node,
1632139×
                Arc::new(Deferred::from_body(DeferredBody {
1633139×
                    base: Some(base),
1634139×
                    ..DeferredBody::default()
1635139×
                })),
1636
            );
1637
        }
163841×
        st.deferred = Some(deferred);
163941×
        Ok(st)
164042×
    }
1641
1642
    /// Changes, tree and replaces of a payload of either version.
164399×
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
164499×
        let mut st = State::new();
1645500×
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
1646500×
            let e = o::array(c, "change meta")?;
1647500×
            if e.len() != 8 {
16480×
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
1649500×
            }
1650500×
            let hash = o::oref(&e[0], "hash")?;
1651500×
            let meta = ChangeMeta {
1652500×
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
1653500×
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
1654500×
                deps: o::array(&e[2], "deps")?
1655500×
                    .iter()
1656607×
                    .map(|d| o::oref(d, "dep"))
1657500×
                    .collect::<Result<Vec<_>, _>>()?,
1658500×
                message: o::text(&e[3], "message")?.to_owned(),
1659
                hlc: Hlc {
1660500×
                    wall_ms: o::uint(&e[4], "wall")?,
1661500×
                    logical: o::u32_(&e[5], "logical")?,
1662
                },
1663500×
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
1664500×
                author: o::oref(&e[7], "author")?,
1665
            };
1666500×
            st.changes.insert(hash, Arc::new(meta));
1667
        }
166899×
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
166999×
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
167024×
            if v.is_null() {
167112×
                Ok(None)
1672
            } else {
167312×
                o::oref(v, "blob").map(Some)
1674
            }
167524×
        };
167699×
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
167712×
            let e = o::array(r, "replace")?;
167812×
            if e.len() != 2 {
16790×
                return Err(ObjectError::Schema(
16800×
                    "replace: expected [node, records]".into(),
16810×
                ));
168212×
            }
168312×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
168412×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
168512×
            let mut recs = Vec::new();
168612×
            for rec in o::array(&e[1], "records")? {
168712×
                let x = o::array(rec, "record")?;
168812×
                if x.len() != 3 {
16890×
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
169012×
                }
169112×
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
1692
            }
169312×
            st.replaces.insert(node, recs);
1694
        }
169599×
        Ok(st)
169699×
    }
1697
16983531×
    pub fn validate(&self) -> Result<(), StateError> {
16998944×
        for (h, c) in &self.changes {
17008944×
            for d in &c.deps {
17015255×
                if !self.changes.contains_key(d) {
17020×
                    return Err(StateError::MissingDep(*d, *h));
17035255×
                }
1704
            }
1705
        }
17063531×
        Ok(())
17073531×
    }
1708
170912340×
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
171038605×
        for (i, op) in c.tree_ops.iter().enumerate() {
171138605×
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
171238605×
        }
171312340×
        if let Some(deferred) = self.deferred.as_mut() {
1714
            // History only: edits of files not built wait, grouped per file,
1715
            // with the texts of inserts read without their lines.
17167254×
            let mut texts = texts.into_iter();
17177254×
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
171838212×
            for e in c.edits {
171938212×
                match e {
1720614×
                    Edit::Replace { node, old, new } => {
1721614×
                        self.replaces.entry(node).or_default().push((h, old, new))
1722
                    }
172337598×
                    e => {
172437598×
                        let slot = per_node.entry(e.node()).or_default();
172536037×
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
172632446×
                            slot.1.extend(texts.next());
172732446×
                        }
172837598×
                        slot.0.push(e);
1729
                    }
1730
                }
1731
            }
173235686×
            for (node, (edits, node_texts)) in per_node {
173335686×
                match self.files.get_mut(&node) {
1734449×
                    Some(g) => {
1735449×
                        assert!(
1736449×
                            node_texts.is_empty(),
1737
                            "a change read without its text applied to a built graph"
1738
                        );
1739449×
                        apply_file_edits(Arc::make_mut(g), h, edits)
1740
                    }
174135237×
                    None => {
174235237×
                        let d = Arc::make_mut(deferred.entry(node).or_default());
174335237×
                        d.add(h, edits, node_texts);
174435237×
                        d.key = Default::default();
174535237×
                    }
1746
                }
1747
            }
17487254×
            return;
17495086×
        }
17505086×
        assert!(
17515086×
            texts.is_empty(),
1752
            "a change read without its text applied to a full state"
1753
        );
17545086×
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
17555630×
        for e in c.edits {
17565630×
            match e {
1757
                Edit::Insert {
17584257×
                    node,
17594257×
                    after,
17604257×
                    before,
17614257×
                    lines,
17624257×
                } => {
17634257×
                    let idx = counters.entry(node).or_default();
17644257×
                    let first = *idx;
17654257×
                    *idx += lines.len() as u32;
17664257×
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
17674257×
                        h,
17684257×
                        first,
17694257×
                        vertex(after.resolve(h)),
17704257×
                        vertex(before.resolve(h)),
17714257×
                        lines,
17724257×
                    );
17734257×
                }
17741260×
                Edit::Delete { node, atoms } => {
17751260×
                    let g = Arc::make_mut(self.files.entry(node).or_default());
17761559×
                    for r in atoms {
17771559×
                        g.delete(h, &r.resolve(h));
17781559×
                    }
1779
                }
1780113×
                Edit::Replace { node, old, new } => {
1781113×
                    self.replaces.entry(node).or_default().push((h, old, new));
1782113×
                }
1783
            }
1784
        }
178512340×
    }
1786
1787
    /// Transitive dependencies of `h`, excluding `h` itself.
17888989×
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
17898989×
        if let Some(c) = self.closure.read().unwrap().sets.get(h) {
17907610×
            return c.clone();
17911379×
        }
17921379×
        let mut out = HashSet::new();
17931379×
        let mut stack: Vec<ChangeHash> = self
17941379×
            .changes
17951379×
            .get(h)
17961379×
            .map(|c| c.deps.clone())
17971379×
            .unwrap_or_default();
179816761×
        while let Some(d) = stack.pop() {
179915382×
            if out.insert(d) {
180010881×
                if let Some(c) = self.changes.get(&d) {
180110881×
                    stack.extend(c.deps.iter().copied());
180210881×
                }
18034501×
            }
1804
        }
18051379×
        let rc = Arc::new(out);
18061379×
        let mut memo = self.closure.write().unwrap();
18071379×
        if memo.held + rc.len() > CLOSURE_MEMO_HASHES {
18080×
            memo.sets.clear();
18090×
            memo.held = 0;
18101379×
        }
18111379×
        memo.held += rc.len();
18121379×
        memo.sets.insert(*h, rc.clone());
18131379×
        rc
18148989×
    }
1815
1816
    /// `h`'s level (see `levels`), worked out for it and its ancestors not
1817
    /// yet known, without recursion: histories are deeper than a stack. An
1818
    /// unknown change has level 0.
1819401238×
    fn level(&self, h: &ChangeHash) -> u32 {
1820
        // Nearly always known: read without excluding the other threads
1821
        // rendering beside this one (oxygen#96).
1822401238×
        if let Some(l) = self.levels.read().unwrap().get(h) {
1823398960×
            return *l;
18242278×
        }
18252278×
        let mut levels = self.levels.write().unwrap();
18262278×
        if let Some(l) = levels.get(h) {
182720×
            return *l;
18282258×
        }
18292258×
        let mut stack: Vec<(ChangeHash, bool)> = vec![(*h, false)];
18307540×
        while let Some((c, expanded)) = stack.pop() {
18315282×
            if levels.contains_key(&c) {
183228×
                continue;
18335254×
            }
18345254×
            let deps: &[ChangeHash] = self
18355254×
                .changes
18365254×
                .get(&c)
18375254×
                .map(|m| m.deps.as_slice())
18385254×
                .unwrap_or(&[]);
18395254×
            if expanded {
18402627×
                let l = deps
18412627×
                    .iter()
18423373×
                    .map(|d| levels.get(d).map_or(0, |l| l + 1))
18432627×
                    .max()
18442627×
                    .unwrap_or(0);
18452627×
                levels.insert(c, l);
1846
            } else {
18472627×
                stack.push((c, true));
18483373×
                for d in deps {
18493373×
                    if !levels.contains_key(d) {
1850397×
                        stack.push((*d, false));
18512976×
                    }
1852
                }
1853
            }
1854
        }
18552258×
        levels[h]
1856401238×
    }
1857
1858
    /// Changes that no other change depends on directly, sorted.
1859397×
    pub fn heads(&self) -> Vec<ChangeHash> {
1860397×
        let depended: crate::fasthash::FastSet<&ChangeHash> =
18613401×
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
1862397×
        let mut heads: Vec<ChangeHash> = self
1863397×
            .changes
1864397×
            .keys()
18653401×
            .filter(|h| !depended.contains(h))
1866397×
            .copied()
1867397×
            .collect();
1868397×
        heads.sort();
1869397×
        heads
1870397×
    }
1871
1872
    /// Maximal elements among `hashes` (those not in the closure of another),
1873
    /// sorted. One walk down from all of them at once: whatever the walk
1874
    /// reaches is below some other element. Linear in the changes reached,
1875
    /// where comparing every pair's closures was quadratic in the number
1876
    /// of heads, which a bookmark of independent changes has many of.
18778996×
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
18788996×
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
18798996×
        let mut below: crate::fasthash::FastSet<ChangeHash> = Default::default();
18808996×
        let mut stack: Vec<ChangeHash> = set
18818996×
            .iter()
188215760×
            .filter_map(|h| self.changes.get(h))
188313387×
            .flat_map(|c| c.deps.iter().copied())
18848996×
            .collect();
188521555×
        while let Some(d) = stack.pop() {
188612559×
            if below.insert(d) {
18876176×
                if let Some(c) = self.changes.get(&d) {
18886176×
                    stack.extend(c.deps.iter().copied());
18896176×
                }
18906383×
            }
1891
        }
189215760×
        set.into_iter().filter(|h| !below.contains(h)).collect()
18938996×
    }
1894
18950×
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
18960×
        self.graph(node)
18970×
            .map(|g| g.materialize(self))
18980×
            .unwrap_or_default()
18990×
    }
1900
1901
    /// Live lines of a text node in materialized order.
190220×
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
190320×
        let Some(g) = self.graph(node) else {
19042×
            return vec![];
1905
        };
190618×
        let m = g.materialize(self);
190718×
        m.live_atoms()
190818×
            .into_iter()
190944×
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
191018×
            .collect()
191120×
    }
1912
1913
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
1914846×
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
1915846×
        let mut live: Vec<ObjectRef> = self
1916846×
            .live_replaces(node)
1917846×
            .into_iter()
1918846×
            .map(|(_, n)| n)
1919846×
            .collect();
1920846×
        live.sort();
1921846×
        live.dedup();
1922846×
        live
1923846×
    }
1924
1925
    /// The replace records whose blob is live, with the change that set it
1926
    /// (spec §9.3). A record's blob is superseded by a later replacement of
1927
    /// that blob: one whose change depends on the record's change, as every
1928
    /// replacement depends on the change that made its old blob current
1929
    /// (§8.1). Two replacements that do not know each other both stay live
1930
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
1931
    /// A replacement without that dependency, from before the rule, is read
1932
    /// as before: it supersedes every record that did not come after it.
1933886×
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
1934886×
        let Some(rs) = self.replaces.get(node) else {
19350×
            return vec![];
1936
        };
1937
        // Dependence by the bounded walk rather than whole closures: on a
1938
        // long history a closure is a hundred thousand changes, and the
1939
        // memo cannot keep them all (#107).
1940886×
        let dep =
1941147×
            |a: &ChangeHash, b: &ChangeHash| a != b && <Self as DepOracle>::depends_on(self, a, b);
1942886×
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
194311×
            rs.iter()
194421×
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && dep(s, q))
194511×
        };
1946886×
        rs.iter()
19471026×
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
19481026×
            .filter(|(c, n)| {
19491309×
                !rs.iter().any(|(s, o, _)| {
19501309×
                    s != c && *o == Some(*n) && (dep(s, c) || (!knows_its_old(s, n) && !dep(c, s)))
19511309×
                })
19521026×
            })
1953886×
            .collect()
1954886×
    }
1955
1956
    /// Short label for conflict markers: `changeid-prefix "message"`.
19571010×
    pub fn label(&self, h: &ChangeHash) -> String {
19581010×
        match self.changes.get(h) {
19591010×
            Some(c) => format!(
1960
                "{} \"{}\"",
19611010×
                c.change_id.short(8),
19621010×
                c.message.lines().next().unwrap_or("")
1963
            ),
19640×
            None => format!("#{}", h.short(12)),
1965
        }
19661010×
    }
1967
1968
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1969
    /// are not part of any conflict region in order, every live atom that is
1970
    /// part of a region, and every change that contributed to a region.
1971
    /// The changes that introduced the live blobs of an opaque node, for a
1972
    /// replace conflict (spec §9.3).
19732×
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
19742×
        let mut out: Vec<ChangeHash> = Vec::new();
19756×
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
19766×
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
19774×
                out.push(*h);
19784×
            }
1979
        }
19802×
        out.sort();
19812×
        out
19822×
    }
1983
198427×
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
198527×
        let mut out = ConflictRegions::default();
198627×
        let Some(g) = self.graph(node) else {
19870×
            return out;
1988
        };
198927×
        let m = g.materialize(self);
199027×
        let mut contributors = BTreeSet::new();
199163×
        for seg in &m.segments {
199263×
            match seg {
199336×
                crate::graph::Segment::Lines(atoms) => {
199436×
                    for a in atoms {
199536×
                        out.plain
199636×
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
199736×
                    }
1998
                }
199927×
                crate::graph::Segment::Conflict(sides) => {
200054×
                    for side in sides {
200156×
                        for a in side {
200256×
                            out.region_atoms.push(*a);
200356×
                            contributors.insert(a.0);
200456×
                        }
2005
                    }
2006
                }
20070×
                crate::graph::Segment::Zombie { deleted, inserted } => {
20080×
                    for a in deleted {
20090×
                        contributors.insert(a.0);
20100×
                        contributors.extend(g.deleters(a).copied());
20110×
                    }
20120×
                    for a in inserted {
20130×
                        out.region_atoms.push(*a);
20140×
                        contributors.insert(a.0);
20150×
                    }
2016
                }
2017
            }
2018
        }
201927×
        out.contributors = contributors.into_iter().collect();
202027×
        out
202127×
    }
2022
202324675×
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
202424675×
        let Some(g) = self.graph(node) else {
2025510×
            return (Vec::new(), Materialized::default());
2026
        };
202724165×
        let m = g.materialize(self);
202824165×
        let bytes = g.render(&m, &|h| self.label(h));
202924165×
        (bytes, m)
203024675×
    }
2031
2032
    /// Every file rendered, in parallel: files are independent, and
2033
    /// rendering them is most of a snapshot's cost in a large tree.
20342375×
    pub fn materialize(&self) -> Snapshot {
2035
        use rayon::prelude::*;
20362375×
        self.require_full("materializing a state");
20372375×
        let tree = self.tree.view();
20382375×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
20392375×
        let rendered: Vec<(String, FileState)> = entries
20402375×
            .par_iter()
204116843×
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
20422375×
            .collect();
20432375×
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
20442375×
        Snapshot {
20452375×
            tree,
20462375×
            files,
20472375×
            unrendered: BTreeSet::new(),
20482375×
        }
20492375×
    }
2050
2051
    /// Like [`State::materialize`], leaving the text files of nodes in
2052
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
2053
    /// file's graph must be loaded. For a caller that already knows those
2054
    /// files are unchanged and not conflicted.
205520×
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
205620×
        self.materialize_leaving(|_, e| skip.contains(&e.node))
205720×
    }
2058
2059
    /// As [`State::materialize_except`], rendering only the text files at
2060
    /// `render` (a few, where the caller knows the rest unchanged).
2061869×
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
20627868×
        self.materialize_leaving(|p, _| !render.contains(p))
2063869×
    }
2064
2065
    /// As [`State::materialize_except`], rendering only the text files of
2066
    /// the nodes in `render` (a change's edited files), without a set of
2067
    /// every other file to leave out.
2068222×
    pub fn materialize_nodes(&self, render: &HashSet<NodeId>) -> Snapshot {
2069590×
        self.materialize_leaving(|_, e| !render.contains(&e.node))
2070222×
    }
2071
20721111×
    fn materialize_leaving(
20731111×
        &self,
20741111×
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
20751111×
    ) -> Snapshot {
2076
        use rayon::prelude::*;
20771111×
        let tree = self.tree.view();
20781111×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
20791111×
        let rendered: Vec<(String, FileState, bool)> = entries
20801111×
            .par_iter()
20818814×
            .map(|(path, e)| {
20828814×
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
20834590×
                    let f = FileState {
20844590×
                        node: e.node,
20854590×
                        kind: e.kind,
20864590×
                        mode: e.mode,
20874590×
                        content: FileContent::Text {
20884590×
                            bytes: Vec::new(),
20894590×
                            materialized: Materialized::default(),
20904590×
                        },
20914590×
                    };
20924590×
                    (path.to_string(), f, true)
2093
                } else {
20944224×
                    (path.to_string(), self.file_state(e), false)
2095
                }
20968814×
            })
20971111×
            .collect();
2098
        // In the view's path order, so the maps are built without searching.
20991111×
        let unrendered: BTreeSet<String> = rendered
21001111×
            .iter()
21011111×
            .filter(|(_, _, skipped)| *skipped)
21024590×
            .map(|(p, _, _)| p.clone())
21031111×
            .collect();
21041111×
        let files: BTreeMap<String, FileState> =
21058814×
            rendered.into_iter().map(|(p, f, _)| (p, f)).collect();
21061111×
        Snapshot {
21071111×
            tree,
21081111×
            files,
21091111×
            unrendered,
21101111×
        }
21111111×
    }
2112
2113
    /// A snapshot of only `paths` (those `view` has), `view` being this
2114
    /// state's tree view: for a caller that works from what changed. The
2115
    /// graphs of those text files must be loaded.
211689×
    pub fn materialize_paths<'p>(
211789×
        &self,
211889×
        view: crate::tree::TreeView,
211989×
        paths: impl IntoIterator<Item = &'p str>,
212089×
    ) -> Snapshot {
2121
        use rayon::prelude::*;
2122
        // On every core: a merge may render thousands (oxygen#96).
212389×
        let entries: Vec<(&str, &crate::tree::TreeEntry)> = paths
212489×
            .into_iter()
2125130×
            .filter_map(|p| Some((p, view.entries.get(p)?)))
212689×
            .collect();
212789×
        let files = entries
212889×
            .par_iter()
2129106×
            .map(|(p, e)| (p.to_string(), self.file_state(e)))
213089×
            .collect::<Vec<_>>()
213189×
            .into_iter()
213289×
            .collect();
213389×
        Snapshot {
213489×
            tree: view,
213589×
            files,
213689×
            unrendered: BTreeSet::new(),
213789×
        }
213889×
    }
2139
2140
    /// The state of one tree entry: a directory, an opaque file's live
2141
    /// blobs, or a text file rendered from its graph (which must be built).
21420×
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
21430×
        self.file_state(e)
21440×
    }
2145
214621173×
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
2147
        {
214821173×
            let content = match e.kind {
21491492×
                NodeKind::Dir => FileContent::Dir,
2150104×
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
2151104×
                    blobs: self.live_blobs(&e.node),
2152104×
                },
2153541×
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
2154541×
                    blobs: self.live_blobs(&e.node),
2155541×
                },
2156
                NodeKind::File => {
215719036×
                    let (bytes, materialized) = self.render_file(&e.node);
215819036×
                    FileContent::Text {
215919036×
                        bytes,
216019036×
                        materialized,
216119036×
                    }
2162
                }
2163
            };
216421173×
            FileState {
216521173×
                node: e.node,
216621173×
                kind: e.kind,
216721173×
                mode: e.mode,
216821173×
                content,
216921173×
            }
2170
        }
217121173×
    }
2172
}
2173
2174
impl DepOracle for State {
2175
    /// Whether `a` depends on `b`, by a walk down from `a` that stops at
2176
    /// changes no higher than `b`: they cannot have `b` below them. Nothing
2177
    /// of the walk is kept, so asking about many pairs costs no more memory
2178
    /// than one walk (#25); a closure already memoised answers at once.
217966371×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
218066371×
        if a == b {
2181800×
            return true;
218265571×
        }
218365571×
        if let Some(c) = self.closure.read().unwrap().sets.get(a) {
21840×
            return c.contains(b);
218565571×
        }
218665571×
        if !self.changes.contains_key(b) {
2187800×
            return false;
218864771×
        }
218964771×
        let lb = self.level(b);
219064771×
        if self.level(a) <= lb {
219135952×
            return false;
219228819×
        }
219328819×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
219428819×
        let mut stack: Vec<ChangeHash> = self
219528819×
            .changes
219628819×
            .get(a)
219728819×
            .map(|m| m.deps.clone())
219828819×
            .unwrap_or_default();
2199359811×
        while let Some(c) = stack.pop() {
2200340555×
            if c == *b {
22019563×
                return true;
2202330992×
            }
2203330992×
            if !seen.insert(c) || self.level(&c) <= lb {
2204222508×
                continue;
2205108484×
            }
2206108484×
            if let Some(m) = self.changes.get(&c) {
2207108484×
                stack.extend(m.deps.iter().copied());
2208108484×
            }
2209
        }
221019256×
        false
221166371×
    }
2212
}
2213
2214
#[cfg(test)]
2215
mod tests {
2216
    use super::*;
2217
2218
    /// A changes block of thousands comes back whole and in order, and a
2219
    /// truncated one is refused (oxygen#94).
2220
    #[test]
22211×
    fn a_long_changes_block_decodes_in_order() {
2222
        use crate::flat::Writer;
22231×
        let metas: Vec<(ChangeHash, ChangeMeta)> = (0..5000u32)
22245000×
            .map(|i| {
22255000×
                let mut h = [0u8; 32];
22265000×
                h[..4].copy_from_slice(&i.to_le_bytes());
22275000×
                let meta = ChangeMeta {
22285000×
                    change_id: crate::ids::ChangeId([i as u8; 16]),
22295000×
                    deps: (0..i % 3).map(|d| ObjectRef([d as u8; 32])).collect(),
22305000×
                    author: ObjectRef([7; 32]),
22315000×
                    hlc: Hlc {
22325000×
                        wall_ms: 1_000_000 - i as u64,
22335000×
                        logical: i,
22345000×
                    },
22355000×
                    message: "x".repeat((i % 50) as usize),
22365000×
                    kind: ChangeKind::Normal,
2237
                };
22385000×
                (ObjectRef(h), meta)
22395000×
            })
22401×
            .collect();
22411×
        let mut w = Writer::default();
22421×
        w.fixed(State::INDEX_MAGIC);
22431×
        w.count(metas.len());
22445000×
        for (h, m) in &metas {
22455000×
            w.object(h);
22465000×
            m.write_flat(&mut w);
22475000×
        }
22481×
        assert_eq!(State::read_index_changes_listed(&w.0).unwrap(), metas);
22491×
        let mut cut = w.0.clone();
22501×
        cut.pop();
22511×
        assert!(
22521×
            State::read_index_changes_listed(&cut).is_err(),
2253
            "a truncated block is refused"
2254
        );
22551×
    }
2256
    use crate::ids::ChangeId;
2257
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
2258
22592023×
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
22602023×
        let mut c = Change {
22612023×
            version: crate::objects::CHANGE_VERSION,
22622023×
            change_id: ChangeId::random(),
22632023×
            deps,
22642023×
            author: ObjectRef::ZERO,
22652023×
            hlc: Hlc {
22662023×
                wall_ms: 1,
22672023×
                logical: 0,
22682023×
            },
22692023×
            message: "m".into(),
22702023×
            tree_ops,
22712023×
            edits,
22722023×
            kind: ChangeKind::Normal,
22732023×
        };
22742023×
        c.normalize();
22752023×
        c
22762023×
    }
2277
2278
    #[test]
22791×
    fn build_edit_and_materialize() {
22801×
        let mut st = State::new();
22811×
        let f = NodeId::random();
22821×
        let c1 = change(
22831×
            vec![],
22841×
            vec![TreeOp::AddNode {
22851×
                node: f,
22861×
                kind: NodeKind::File,
22871×
                mode: Mode::TEXT,
22881×
                parent: NodeId::ROOT,
22891×
                name: "a.txt".into(),
22901×
            }],
22911×
            vec![Edit::Insert {
22921×
                node: f,
22931×
                after: AtomRef::Start,
22941×
                before: AtomRef::End,
22951×
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
22961×
            }],
2297
        );
22981×
        let h1 = st.add(c1).unwrap();
2299
        // Depends on h1: append a line and delete "one".
23001×
        let c2 = change(
23011×
            vec![h1],
23021×
            vec![],
23031×
            vec![
23041×
                Edit::Delete {
23051×
                    node: f,
23061×
                    atoms: vec![AtomRange {
23071×
                        change: h1,
23081×
                        from: 0,
23091×
                        to: 1,
23101×
                    }],
23111×
                },
23121×
                Edit::Insert {
23131×
                    node: f,
23141×
                    after: AtomRef::Atom {
23151×
                        change: h1,
23161×
                        index: 1,
23171×
                    },
23181×
                    before: AtomRef::End,
23191×
                    lines: vec![b"three\n".to_vec()].into(),
23201×
                },
2321
            ],
2322
        );
23231×
        let h2 = st.add(c2).unwrap();
23241×
        assert_eq!(st.heads(), vec![h2]);
23251×
        assert!(st.depends_on(&h2, &h1));
23261×
        assert!(!st.depends_on(&h1, &h2));
23271×
        let snap = st.materialize();
23281×
        assert!(!snap.is_conflicted());
23291×
        let a = &snap.files["a.txt"];
23301×
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
23311×
        assert_eq!(st.live_lines(&f).len(), 2);
23321×
    }
2333
2334
    #[test]
23351×
    fn missing_dependency_is_rejected() {
23361×
        let mut st = State::new();
23371×
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
23381×
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
23391×
    }
2340
2341
    #[test]
23421×
    fn self_references_and_multi_insert_indexing() {
23431×
        let mut st = State::new();
23441×
        let f = NodeId::random();
23451×
        let me = OpRef {
23461×
            change: ObjectRef::ZERO,
23471×
            index: 0,
23481×
        };
23491×
        let c1 = change(
23501×
            vec![],
23511×
            vec![
23521×
                TreeOp::AddNode {
23531×
                    node: f,
23541×
                    kind: NodeKind::File,
23551×
                    mode: Mode::TEXT,
23561×
                    parent: NodeId::ROOT,
23571×
                    name: "x".into(),
23581×
                },
23591×
                TreeOp::SetMode {
23601×
                    node: f,
23611×
                    old: me,
23621×
                    mode: Mode {
23631×
                        exec: true,
23641×
                        opaque: false,
23651×
                    },
23661×
                },
2367
            ],
23681×
            vec![
23691×
                Edit::Insert {
23701×
                    node: f,
23711×
                    after: AtomRef::Start,
23721×
                    before: AtomRef::End,
23731×
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
23741×
                },
2375
                // Insert between the two lines just inserted, using self references.
23761×
                Edit::Insert {
23771×
                    node: f,
23781×
                    after: AtomRef::Atom {
23791×
                        change: ObjectRef::ZERO,
23801×
                        index: 0,
23811×
                    },
23821×
                    before: AtomRef::Atom {
23831×
                        change: ObjectRef::ZERO,
23841×
                        index: 1,
23851×
                    },
23861×
                    lines: vec![b"b\n".to_vec()].into(),
23871×
                },
2388
            ],
2389
        );
23901×
        st.add(c1).unwrap();
23911×
        let snap = st.materialize();
23921×
        let x = &snap.files["x"];
23931×
        assert_eq!(
2394
            x.mode,
2395
            Mode {
2396
                exec: true,
2397
                opaque: false
2398
            }
2399
        );
24001×
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
24011×
    }
2402
2403
    #[test]
24041×
    fn opaque_replace_and_conflict() {
24051×
        let mut st = State::new();
24061×
        let f = NodeId::random();
24071×
        let b1 = ObjectRef([1; 32]);
24081×
        let b2 = ObjectRef([2; 32]);
24091×
        let b3 = ObjectRef([3; 32]);
24101×
        let h1 = st
24111×
            .add(change(
24121×
                vec![],
24131×
                vec![TreeOp::AddNode {
24141×
                    node: f,
24151×
                    kind: NodeKind::File,
24161×
                    mode: Mode::OPAQUE,
24171×
                    parent: NodeId::ROOT,
24181×
                    name: "img".into(),
24191×
                }],
24201×
                vec![Edit::Replace {
24211×
                    node: f,
24221×
                    old: None,
24231×
                    new: Some(b1),
24241×
                }],
2425
            ))
24261×
            .unwrap();
24271×
        assert_eq!(st.live_blobs(&f), vec![b1]);
24281×
        st.add(change(
24291×
            vec![h1],
24301×
            vec![],
24311×
            vec![Edit::Replace {
24321×
                node: f,
24331×
                old: Some(b1),
24341×
                new: Some(b2),
24351×
            }],
2436
        ))
24371×
        .unwrap();
24381×
        st.add(change(
24391×
            vec![h1],
24401×
            vec![],
24411×
            vec![Edit::Replace {
24421×
                node: f,
24431×
                old: Some(b1),
24441×
                new: Some(b3),
24451×
            }],
2446
        ))
24471×
        .unwrap();
24481×
        let snap = st.materialize();
24491×
        assert!(snap.is_conflicted());
24501×
        assert!(
24511×
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2452
        );
24531×
    }
2454
2455
    #[test]
24561×
    fn checkpoint_payload_round_trip_and_replay() {
24571×
        let mut st = State::new();
24581×
        let f = NodeId::random();
24591×
        let h1 = st
24601×
            .add(change(
24611×
                vec![],
24621×
                vec![TreeOp::AddNode {
24631×
                    node: f,
24641×
                    kind: NodeKind::File,
24651×
                    mode: Mode::TEXT,
24661×
                    parent: NodeId::ROOT,
24671×
                    name: "a".into(),
24681×
                }],
24691×
                vec![Edit::Insert {
24701×
                    node: f,
24711×
                    after: AtomRef::Start,
24721×
                    before: AtomRef::End,
24731×
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
24741×
                }],
2475
            ))
24761×
            .unwrap();
24771×
        let h2 = st
24781×
            .add(change(
24791×
                vec![h1],
24801×
                vec![],
24811×
                vec![Edit::Delete {
24821×
                    node: f,
24831×
                    atoms: vec![AtomRange {
24841×
                        change: h1,
24851×
                        from: 0,
24861×
                        to: 1,
24871×
                    }],
24881×
                }],
2489
            ))
24901×
            .unwrap();
24911×
        let payload = st.checkpoint_payload();
24921×
        let back = State::from_checkpoint_payload(&payload).unwrap();
24931×
        assert_eq!(back.len(), 2);
24941×
        assert_eq!(back.heads(), vec![h2]);
24951×
        assert_eq!(back.get(&h1).unwrap().message, "m");
24961×
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2497
        // Replaying a further change onto the restored state equals a full build.
24981×
        let c3 = change(
24991×
            vec![h2],
25001×
            vec![],
25011×
            vec![Edit::Insert {
25021×
                node: f,
25031×
                after: AtomRef::Atom {
25041×
                    change: h1,
25051×
                    index: 1,
25061×
                },
25071×
                before: AtomRef::End,
25081×
                lines: vec![b"3\n".to_vec()].into(),
25091×
            }],
2510
        );
25111×
        let mut full = st.clone();
25121×
        full.add(c3.clone()).unwrap();
25131×
        let mut restored = back;
25141×
        restored.add(c3).unwrap();
25151×
        let (a, b) = (full.materialize(), restored.materialize());
25161×
        assert_eq!(
25171×
            a.files.keys().collect::<Vec<_>>(),
25181×
            b.files.keys().collect::<Vec<_>>()
2519
        );
25201×
        assert_eq!(a.files["a"].content, b.files["a"].content);
25211×
        assert!(
25221×
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2523
        );
25241×
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
25251×
    }
2526
2527
    /// History-only states (O10f): the same state as a full load once its
2528
    /// graphs are built, by replay and from a version 2 checkpoint with
2529
    /// later changes; unloaded graphs are never read as empty.
2530
    #[test]
25311×
    fn graph_keys_change_exactly_when_a_graph_does() {
25321×
        let (f, g) = (NodeId::random(), NodeId::random());
25331×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
25342×
            node,
25352×
            kind: NodeKind::File,
2536
            mode: Mode::TEXT,
2537
            parent: NodeId::ROOT,
25382×
            name: name.into(),
25392×
        };
25401×
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
25414×
            node,
25424×
            after: AtomRef::Start,
25434×
            before: AtomRef::End,
25444×
            lines: vec![line.to_vec()].into(),
25454×
        };
25461×
        let c1 = change(
25471×
            vec![],
25481×
            vec![add(f, "f"), add(g, "g")],
25491×
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2550
        );
25511×
        let h1 = c1.hash();
25521×
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
25531×
        let h2 = c2.hash();
25541×
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
25556×
        let load = |cs: &[&Change]| {
25566×
            let mut st = State::new_history_only();
255710×
            for c in cs {
255810×
                st.add((*c).clone()).unwrap();
255910×
            }
25606×
            st
25616×
        };
25621×
        let s1 = load(&[&c1]);
25631×
        let s2 = load(&[&c1, &c2]);
25641×
        let s3 = load(&[&c1, &c2, &c3]);
256518×
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
25661×
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
25671×
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
25681×
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
25691×
        assert_ne!(key(&s2, &f), key(&s3, &f));
25701×
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
25711×
        let mut built = load(&[&c1]);
25721×
        built
25731×
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
25741×
            .unwrap();
25751×
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
25761×
        let mut full = State::new();
25771×
        full.add(c1.clone()).unwrap();
25781×
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2579
2580
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2581
        // or inline values: stable across loads, changed by later edits.
25821×
        let graphs = full.checkpoint_file_graphs();
25831×
        let index = full.checkpoint_index(&graphs, |enc| {
25840×
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
25850×
        });
25868×
        let cp = |extra: &[&Change]| {
25878×
            let mut st = State::from_checkpoint_history(&index).unwrap();
25888×
            for c in extra {
25895×
                st.add((*c).clone()).unwrap();
25905×
            }
25918×
            st
25928×
        };
25931×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
25941×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
25951×
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
25961×
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2597
2598
        // Partial rendering: skipped files are listed and empty, the others
2599
        // render as in a full state.
26001×
        let mut part = load(&[&c1, &c2]);
26011×
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
26021×
            .unwrap();
26031×
        let snap = part.materialize_except(&[f].into_iter().collect());
26041×
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
26051×
        let mut whole = State::new();
26061×
        whole.add(c1.clone()).unwrap();
26071×
        whole.add(c2.clone()).unwrap();
26081×
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
26091×
        assert!(
26101×
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2611
        );
26121×
    }
2613
2614
    #[test]
26151×
    fn history_only_states_build_the_same_graphs_on_demand() {
26161×
        let small = NodeId::random();
26171×
        let big = NodeId::random();
26181×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
26192×
            node,
26202×
            kind: NodeKind::File,
2621
            mode: Mode::TEXT,
2622
            parent: NodeId::ROOT,
26232×
            name: name.into(),
26242×
        };
26251×
        let lines: crate::lines::Lines = (0..300)
2626300×
            .map(|i| format!("line {i}\n").into_bytes())
26271×
            .collect();
26281×
        let c1 = change(
26291×
            vec![],
26301×
            vec![add(small, "small"), add(big, "big")],
26311×
            vec![
26321×
                Edit::Insert {
26331×
                    node: small,
26341×
                    after: AtomRef::Start,
26351×
                    before: AtomRef::End,
26361×
                    lines: vec![b"x\n".to_vec()].into(),
26371×
                },
26381×
                Edit::Insert {
26391×
                    node: big,
26401×
                    after: AtomRef::Start,
26411×
                    before: AtomRef::End,
26421×
                    lines,
26431×
                },
2644
            ],
2645
        );
26461×
        let h1 = c1.hash();
26471×
        let c2 = change(
26481×
            vec![h1],
26491×
            vec![],
26501×
            vec![
26511×
                Edit::Delete {
26521×
                    node: big,
26531×
                    atoms: vec![AtomRange {
26541×
                        change: h1,
26551×
                        from: 2,
26561×
                        to: 9,
26571×
                    }],
26581×
                },
26591×
                Edit::Insert {
26601×
                    node: big,
26611×
                    after: AtomRef::Atom {
26621×
                        change: h1,
26631×
                        index: 20,
26641×
                    },
26651×
                    before: AtomRef::Atom {
26661×
                        change: h1,
26671×
                        index: 21,
26681×
                    },
26691×
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
26701×
                },
26711×
                Edit::Insert {
26721×
                    node: small,
26731×
                    after: AtomRef::Atom {
26741×
                        change: h1,
26751×
                        index: 0,
26761×
                    },
26771×
                    before: AtomRef::End,
26781×
                    lines: vec![b"y\n".to_vec()].into(),
26791×
                },
2680
            ],
2681
        );
26821×
        let h2 = c2.hash();
26831×
        let c3 = change(
26841×
            vec![h2],
26851×
            vec![],
26861×
            vec![Edit::Delete {
26871×
                node: small,
26881×
                atoms: vec![AtomRange {
26891×
                    change: h1,
26901×
                    from: 0,
26911×
                    to: 1,
26921×
                }],
26931×
            }],
2694
        );
2695
26961×
        let mut full = State::new();
26973×
        for c in [&c1, &c2, &c3] {
26983×
            full.add(c.clone()).unwrap();
26993×
        }
2700
        // By replay: nothing built until asked, then exactly the full graphs.
27011×
        let mut hist = State::new_history_only();
27023×
        for c in [&c1, &c2, &c3] {
27033×
            hist.add(c.clone()).unwrap();
27043×
        }
27051×
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
27061×
        assert_eq!(hist.len(), 3);
27071×
        hist.load_graphs(
27081×
            &[big],
27090×
            |_| unreachable!("no checkpoint"),
27100×
            |_| unreachable!(),
2711
        )
27121×
        .unwrap();
27131×
        assert_eq!(
27141×
            hist.render_file(&big).0,
27151×
            full.render_file(&big).0,
2716
            "one file on its own"
2717
        );
27181×
        assert!(!hist.is_full());
27191×
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
27201×
            .unwrap();
27211×
        assert!(hist.is_full());
27221×
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2723
2724
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
27251×
        let mut base = State::new();
27261×
        base.add(c1.clone()).unwrap();
27271×
        base.add(c2.clone()).unwrap();
27281×
        let graphs = base.checkpoint_file_graphs();
27291×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
27301×
        let index = base.checkpoint_index(&graphs, |enc| {
27311×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
27321×
            blobs.insert(r, enc.to_vec());
27331×
            r
27341×
        });
27351×
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
27361×
        from_cp.add(c3.clone()).unwrap();
27371×
        assert!(!from_cp.is_full());
27381×
        let mut fetched = 0;
27391×
        from_cp
27401×
            .load_graphs(
27411×
                &[small, big],
27421×
                |refs| {
27431×
                    fetched += refs.len();
27441×
                    refs.iter()
27451×
                        .map(|r| {
27461×
                            blobs
27471×
                                .get(r)
27481×
                                .cloned()
27491×
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
27501×
                        })
27511×
                        .collect()
27521×
                },
27530×
                |_| unreachable!(),
2754
            )
27551×
            .unwrap();
27561×
        assert_eq!(
2757
            fetched, 1,
2758
            "the large graph's blob, in one batch; the small one was inline"
2759
        );
27601×
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
27611×
    }
2762
2763
    #[test]
2764
    #[should_panic(expected = "was not loaded")]
27651×
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
27661×
        let f = NodeId::random();
27671×
        let mut st = State::new_history_only();
27681×
        st.add(change(
27691×
            vec![],
27701×
            vec![TreeOp::AddNode {
27711×
                node: f,
27721×
                kind: NodeKind::File,
27731×
                mode: Mode::TEXT,
27741×
                parent: NodeId::ROOT,
27751×
                name: "a".into(),
27761×
            }],
27771×
            vec![Edit::Insert {
27781×
                node: f,
27791×
                after: AtomRef::Start,
27801×
                before: AtomRef::End,
27811×
                lines: vec![b"a\n".to_vec()].into(),
27821×
            }],
2783
        ))
27841×
        .unwrap();
27851×
        st.render_file(&f);
27861×
    }
2787
2788
    #[test]
2789
    #[should_panic(expected = "needs every file graph")]
27901×
    fn materializing_a_history_only_state_is_refused() {
27911×
        let f = NodeId::random();
27921×
        let mut st = State::new_history_only();
27931×
        st.add(change(
27941×
            vec![],
27951×
            vec![TreeOp::AddNode {
27961×
                node: f,
27971×
                kind: NodeKind::File,
27981×
                mode: Mode::TEXT,
27991×
                parent: NodeId::ROOT,
28001×
                name: "a".into(),
28011×
            }],
28021×
            vec![Edit::Insert {
28031×
                node: f,
28041×
                after: AtomRef::Start,
28051×
                before: AtomRef::End,
28061×
                lines: vec![b"a\n".to_vec()].into(),
28071×
            }],
2808
        ))
28091×
        .unwrap();
28101×
        st.materialize();
28111×
    }
2812
2813
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
2814
    /// blob; the state read back is the same as from version 1.
2815
    #[test]
28161×
    fn checkpoint_index_round_trip_matches_version_1() {
28171×
        let mut st = State::new();
28181×
        let small = NodeId::random();
28191×
        let big = NodeId::random();
28201×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
28212×
            node,
28222×
            kind: NodeKind::File,
2823
            mode: Mode::TEXT,
2824
            parent: NodeId::ROOT,
28252×
            name: name.into(),
28262×
        };
28271×
        let big_lines: crate::lines::Lines = (0..400)
2828400×
            .map(|i| format!("line {i} of a long file\n").into_bytes())
28291×
            .collect();
28301×
        let h1 = st
28311×
            .add(change(
28321×
                vec![],
28331×
                vec![add(small, "small"), add(big, "big")],
28341×
                vec![
28351×
                    Edit::Insert {
28361×
                        node: small,
28371×
                        after: AtomRef::Start,
28381×
                        before: AtomRef::End,
28391×
                        lines: vec![b"x\n".to_vec()].into(),
28401×
                    },
28411×
                    Edit::Insert {
28421×
                        node: big,
28431×
                        after: AtomRef::Start,
28441×
                        before: AtomRef::End,
28451×
                        lines: big_lines,
28461×
                    },
2847
                ],
2848
            ))
28491×
            .unwrap();
28501×
        st.add(change(
28511×
            vec![h1],
28521×
            vec![],
28531×
            vec![Edit::Delete {
28541×
                node: big,
28551×
                atoms: vec![AtomRange {
28561×
                    change: h1,
28571×
                    from: 3,
28581×
                    to: 7,
28591×
                }],
28601×
            }],
2861
        ))
28621×
        .unwrap();
2863
28641×
        let graphs = st.checkpoint_file_graphs();
28651×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
28661×
        let index = st.checkpoint_index(&graphs, |enc| {
28671×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
28681×
            blobs.insert(r, enc.to_vec());
28691×
            r
28701×
        });
28711×
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
28721×
        assert_eq!(
28731×
            State::checkpoint_graph_refs(&index).unwrap(),
28741×
            blobs.keys().copied().collect::<Vec<_>>()
2875
        );
28761×
        assert!(
28771×
            State::checkpoint_graph_refs(&st.checkpoint_payload())
28781×
                .unwrap()
28791×
                .is_empty(),
2880
            "version 1 names none"
2881
        );
28821×
        assert!(index.len() < st.checkpoint_payload().len());
2883
28841×
        let back = State::from_checkpoint(&index, |refs| {
28851×
            refs.iter()
28861×
                .map(|r| {
28871×
                    blobs
28881×
                        .get(r)
28891×
                        .cloned()
28901×
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
28911×
                })
28921×
                .collect()
28931×
        })
28941×
        .unwrap();
28951×
        assert_eq!(
28961×
            back.checkpoint_payload(),
28971×
            st.checkpoint_payload(),
2898
            "the same state as version 1"
2899
        );
29001×
        assert_eq!(
29011×
            back.materialize().files["big"].content,
29021×
            st.materialize().files["big"].content
2903
        );
2904
        // Deterministic: the same state gives the same index.
29051×
        assert_eq!(
29061×
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
29071×
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
29081×
            }),
2909
            index
2910
        );
2911
        // A missing graph blob is an error, not an empty file.
29121×
        assert!(
29131×
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
2914
        );
29151×
        assert!(
29161×
            State::from_checkpoint_payload(&index).is_err(),
2917
            "version 2 needs its blobs"
2918
        );
2919
        // Version 1 payloads still read, and unknown versions do not.
29201×
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
29211×
        let mut v3 = cbor::decode(&index).unwrap();
29221×
        if let Value::Map(m) = &mut v3 {
29231×
            m.insert(0, Value::Uint(3));
29241×
        }
29251×
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
29261×
    }
2927
2928
    #[test]
29291×
    fn maximal_elements() {
29301×
        let mut st = State::new();
29311×
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
29321×
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
29331×
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
29341×
        let mut m = st.maximal(&[h1, h2, h3]);
29351×
        m.sort();
29361×
        let mut want = vec![h2, h3];
29371×
        want.sort();
29381×
        assert_eq!(m, want);
29391×
        assert_eq!(st.heads(), want);
29401×
    }
2941
2942
    /// The bounded walk of `depends_on` agrees with the closure on random
2943
    /// graphs, and the memo stays within its bound.
2944
    #[test]
29451×
    fn depends_on_matches_the_closure() {
2946
        use rand::{Rng, SeedableRng};
29471×
        let mut rng = rand::rngs::StdRng::seed_from_u64(11);
29481×
        for _ in 0..10 {
294910×
            let mut st = State::new();
295010×
            let mut all: Vec<ChangeHash> = Vec::new();
295110×
            for _ in 0..80 {
2952800×
                let deps: Vec<ChangeHash> =
295331600×
                    all.iter().copied().filter(|_| rng.gen_bool(0.06)).collect();
2954800×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2955
            }
295610×
            let unknown = ObjectRef([0xee; 32]);
2957800×
            for a in &all {
2958800×
                let want = st.closure(a).clone();
2959800×
                st.closure.write().unwrap().sets.clear();
2960800×
                st.closure.write().unwrap().held = 0;
296164800×
                for b in all.iter().chain([&unknown]) {
296264800×
                    assert_eq!(
296364800×
                        st.depends_on(a, b),
296464800×
                        a == b || want.contains(b),
2965
                        "{a:?} on {b:?}"
2966
                    );
2967
                }
2968
            }
296910×
            assert!(st.closure.write().unwrap().held <= CLOSURE_MEMO_HASHES);
2970
        }
29711×
    }
2972
2973
    /// The one-walk `maximal` agrees with the definition (not in the
2974
    /// closure of another element) on random graphs, with repeated and
2975
    /// unknown hashes among the input.
2976
    #[test]
29771×
    fn maximal_matches_its_definition() {
2978
        use rand::{Rng, SeedableRng};
29791×
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
29801×
        for _ in 0..20 {
298120×
            let mut st = State::new();
298220×
            let mut all: Vec<ChangeHash> = Vec::new();
298320×
            for _ in 0..60 {
29841200×
                let deps: Vec<ChangeHash> =
298535400×
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
29861200×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2987
            }
298820×
            let mut pick: Vec<ChangeHash> =
29891200×
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
299020×
            pick.extend(pick.clone().into_iter().take(3));
299120×
            pick.push(ObjectRef([0xee; 32]));
299220×
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
299320×
            let want: Vec<ChangeHash> = set
299420×
                .iter()
29958358×
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
299620×
                .copied()
299720×
                .collect();
299820×
            assert_eq!(st.maximal(&pick), want);
299920×
            assert_eq!(st.maximal(&all), st.heads());
3000
        }
30011×
    }
3002
}