OXYGENHUB

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

1969 of 2127 lines run, 419 of 599 functions · run #258 on main · run missed

1
//! A state: a dependency-closed set of changes, applied to a tree graph and
2
//! per-node file graphs (spec §8.3), with materialization (spec §9.5, §11).
3
4
use crate::cbor::{self, Value};
5
use crate::graph::{AtomKey, DepOracle, FileGraph, Materialized, Vertex};
6
use crate::hash::KeyId;
7
use crate::hash::{ChangeHash, ObjectRef};
8
use crate::ids::NodeId;
9
use crate::objects::{
10
    self as o, AtomRef, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, ObjectError, TreeOp,
11
};
12
use crate::tree::{TreeGraph, TreeView};
13
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
14
use std::sync::{Arc, Mutex};
15
16
/// Checkpoint payload version 2 (spec §11): file graphs by reference.
17
pub const CHECKPOINT_INDEX_VERSION: u64 = 2;
18
19
/// A file graph encoded in fewer bytes stays inline in a version 2 index.
20
pub const INLINE_GRAPH_LIMIT: usize = 2048;
21
22
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
23
pub enum StateError {
24
    #[error("change {1} depends on {0}, which is not in the state")]
25
    MissingDep(ChangeHash, ChangeHash),
26
}
27
28
/// One `Replace` edit: `(change, old blob, new blob)`.
29
type ReplaceRecord = (ChangeHash, Option<ObjectRef>, Option<ObjectRef>);
30
31
/// What a state remembers about a change: everything but its operations,
32
/// which live in the graphs once applied (and in the store).
33
#[derive(Clone, Debug, PartialEq, Eq)]
34
pub struct ChangeMeta {
35
    pub change_id: crate::ids::ChangeId,
36
    pub deps: Vec<ChangeHash>,
37
    pub author: KeyId,
38
    pub hlc: Hlc,
39
    pub message: String,
40
    pub kind: ChangeKind,
41
}
42
43
impl ChangeMeta {
44
    /// In the flat layout of local indexes and caches ([`crate::flat`]).
451485×
    pub(crate) fn write_flat(&self, w: &mut crate::flat::Writer) {
461485×
        w.fixed(&self.change_id.0);
471485×
        w.count(self.deps.len());
481485×
        for d in &self.deps {
491080×
            w.object(d);
501080×
        }
511485×
        w.object(&self.author);
521485×
        w.u64(self.hlc.wall_ms);
531485×
        w.u32(self.hlc.logical);
541485×
        w.bytes(self.message.as_bytes());
551485×
        w.u8(self.kind.tag() as u8);
561485×
    }
57
581588×
    pub(crate) fn read_flat(r: &mut crate::flat::Reader) -> Result<ChangeMeta, ObjectError> {
591588×
        let change_id = crate::ids::ChangeId(r.fixed::<16>()?);
601588×
        let mut deps = Vec::new();
611588×
        for _ in 0..r.count()? {
62852×
            deps.push(r.object()?);
63
        }
64
        Ok(ChangeMeta {
651588×
            change_id,
661588×
            deps,
671588×
            author: r.object()?,
68
            hlc: Hlc {
691588×
                wall_ms: r.u64()?,
701588×
                logical: r.u32()?,
71
            },
721588×
            message: r.text()?,
731588×
            kind: ChangeKind::from_tag(r.u8()? as u64)?,
74
        })
751588×
    }
76
7715650×
    pub fn of(c: &Change) -> ChangeMeta {
7815650×
        ChangeMeta {
7915650×
            change_id: c.change_id,
8015650×
            deps: c.deps.clone(),
8115650×
            author: c.author,
8215650×
            hlc: c.hlc,
8315650×
            message: c.message.clone(),
8415650×
            kind: c.kind,
8515650×
        }
8615650×
    }
87
}
88
89
#[derive(Default)]
90
pub struct State {
91
    /// Shared between clones, like `files` and `deferred`: a state kept
92
    /// beside another that differs by a few changes shares the rest.
93
    changes: HashMap<ChangeHash, Arc<ChangeMeta>>,
94
    tree: TreeGraph,
95
    /// Shared between clones: a clone copies a graph only when an edit
96
    /// changes it (`Arc::make_mut`), so keeping several states that differ
97
    /// by a few changes costs little more than one.
98
    files: crate::fasthash::FastMap<NodeId, Arc<FileGraph>>,
99
    replaces: HashMap<NodeId, Vec<ReplaceRecord>>,
100
    /// Memoised transitive dependencies, bounded by the hashes they hold
101
    /// (each set is the whole history below a change, so keeping one for
102
    /// every change asked about grew with the square of history: #25). A
103
    /// mutex, not a `RefCell`, so a loaded state can be shared across
104
    /// threads by a host that caches it.
105
    closure: Mutex<ClosureMemo>,
106
    /// Each change's level: 0 with no dependencies, else one more than its
107
    /// highest dependency. A change can only depend on changes of lower
108
    /// level, which bounds the walk [`DepOracle::depends_on`] does.
109
    levels: Mutex<HashMap<ChangeHash, u32>>,
110
    /// `None` for a full state. For a history-only state (loaded for its
111
    /// changes and tree), the file graphs not built yet, by node: `files`
112
    /// holds only those loaded with [`State::load_graphs`].
113
    deferred: Option<crate::fasthash::FastMap<NodeId, Arc<Deferred>>>,
114
}
115
116
use crate::objects::TextRef;
117
118
/// A file graph a history-only state has not built: its base from a
119
/// version 2 checkpoint, if any, and the edits of later changes in the
120
/// order they were applied (spec §11). Building it later gives the same
121
/// graph, since graph construction does not depend on order (§8).
122
///
123
/// Read from a state index, it stays encoded until first used: a command
124
/// that builds a few files decodes only their histories.
125
#[derive(Clone, Default)]
126
struct Deferred {
127
    body: std::sync::OnceLock<DeferredBody>,
128
    /// The body as the index encodes it, decoded into `body` on first use.
129
    raw: Option<(Arc<Vec<u8>>, std::ops::Range<usize>)>,
130
    /// Its graph key, once worked out (or read from an index); reset by
131
    /// any edit added.
132
    key: std::sync::OnceLock<[u8; 32]>,
133
}
134
135
/// The closures kept, and how many hashes they hold in all.
136
#[derive(Default)]
137
struct ClosureMemo {
138
    sets: HashMap<ChangeHash, Arc<HashSet<ChangeHash>>>,
139
    held: usize,
140
}
141
142
/// The most hashes the closure memo holds before it starts again: a few
143
/// hundred megabytes at most.
144
const CLOSURE_MEMO_HASHES: usize = 4_000_000;
145
146
#[derive(Clone, Default)]
147
struct DeferredBody {
148
    base: Option<DeferredBase>,
149
    edits: Vec<(ChangeHash, Vec<Edit>)>,
150
    /// The text blob and line count of each insert in `edits` left without
151
    /// its lines, in order: read when the graph is built.
152
    texts: Vec<TextRef>,
153
}
154
155
impl Deferred {
156141×
    fn from_body(body: DeferredBody) -> Deferred {
157141×
        Deferred {
158141×
            body: std::sync::OnceLock::from(body),
159141×
            ..Deferred::default()
160141×
        }
161141×
    }
162
163102211×
    fn body(&self) -> &DeferredBody {
164102211×
        self.body.get_or_init(|| match &self.raw {
165
            // The index was checked against its hash when read, and was
166
            // written by `write_index`: it decodes.
1675449×
            Some((bytes, range)) => State::read_deferred_body(&bytes[range.clone()])
1685449×
                .expect("a state index checked by its hash decodes"),
16932106×
            None => DeferredBody::default(),
17037555×
        })
171102211×
    }
172
17335408×
    fn body_mut(&mut self) -> &mut DeferredBody {
17435408×
        self.body();
17535408×
        self.raw = None;
17635408×
        self.body.get_mut().expect("decoded above")
17735408×
    }
178
17922642×
    fn into_body(mut self) -> DeferredBody {
18022642×
        self.body();
18122642×
        self.body.take().expect("decoded above")
18222642×
    }
183
}
184
185
#[derive(Clone)]
186
enum DeferredBase {
187
    Inline(Value),
188
    Blob(ObjectRef),
189
}
190
191
/// A local index of a history-only state (oxygen#41), in the flat layout
192
/// of [`crate::flat`]: its change metadata, tree (with its view), replace
193
/// records and every file's deferred history with its graph key, so a
194
/// command reads it rather than replaying history. Derived only: written
195
/// from a state loaded the long way, and read back as the same state.
196
impl State {
197
    const INDEX_MAGIC: &'static [u8] = b"oxy state index 3\n";
198
199
    /// The index of this state, or `None` when it has anything an index
200
    /// does not hold: a built graph, or text in memory (a change added
201
    /// whole rather than as its skeleton).
202808×
    pub fn write_index(&self) -> Option<Vec<u8>> {
203
        use crate::flat::Writer;
204808×
        let deferred = self.deferred.as_ref()?;
205808×
        if !self.files.is_empty() {
2060×
            return None;
207808×
        }
20832498×
        let atom = |w: &mut Writer, a: &AtomRef| match a {
20916245×
            AtomRef::Start => w.u8(0),
21016249×
            AtomRef::End => w.u8(1),
2114×
            AtomRef::Atom { change, index } => {
2124×
                w.u8(2);
2134×
                w.object(change);
2144×
                w.u32(*index);
2154×
            }
21632498×
        };
217
        // The changes first, as a block a reader can take on its own (see
218
        // [`State::read_index_changes`]).
219808×
        let mut w = Writer::default();
220808×
        w.fixed(Self::INDEX_MAGIC);
221808×
        let mut changes: Vec<(&ChangeHash, &Arc<ChangeMeta>)> = self.changes.iter().collect();
222808×
        changes.sort_by_key(|(h, _)| **h);
223808×
        w.count(changes.len());
224808×
        for (h, m) in changes {
225170×
            w.object(h);
226170×
            m.write_flat(&mut w);
227170×
        }
228808×
        let changes_block = std::mem::take(&mut w);
229808×
        w.bytes(&changes_block.0);
230
        // The tree and the files' histories as blocks of their own, so a
231
        // reader decodes them side by side.
232808×
        let mut tw = Writer::default();
233808×
        self.tree.write_flat(&mut tw);
234808×
        w.bytes(&tw.0);
235808×
        let mut replaces: Vec<(&NodeId, &Vec<ReplaceRecord>)> = self.replaces.iter().collect();
236808×
        replaces.sort_by_key(|(n, _)| **n);
237808×
        w.count(replaces.len());
238808×
        for (n, recs) in replaces {
2394×
            w.fixed(&n.0);
2404×
            w.count(recs.len());
241
            // In any order: which record is live does not depend on it.
2424×
            let mut recs: Vec<&ReplaceRecord> = recs.iter().collect();
2434×
            recs.sort();
2444×
            for (c, old, new) in recs {
2454×
                w.object(c);
2464×
                w.opt_object(old);
2474×
                w.opt_object(new);
2484×
            }
249
        }
250808×
        let outer = w;
251808×
        let mut w = Writer::default();
252808×
        let mut nodes: Vec<(&NodeId, &Arc<Deferred>)> = deferred.iter().collect();
253808×
        nodes.sort_by_key(|(n, _)| **n);
254808×
        w.count(nodes.len());
25532496×
        for (n, d) in nodes {
25632496×
            w.fixed(&n.0);
25732496×
            let mut h = blake3::Hasher::new();
25832496×
            h.update(b"oxy graph key 1\0");
25932496×
            h.update(&n.0);
26032496×
            w.fixed(d.key.get_or_init(|| d.graph_key(h)));
261
            // Unchanged since read (a change clears `raw`): copied as it is.
26232496×
            if let Some((bytes, range)) = &d.raw {
26316248×
                w.bytes(&bytes[range.clone()]);
26416248×
                continue;
26516248×
            }
26616248×
            let d = d.body();
26716248×
            let outer_w = std::mem::take(&mut w);
2683×
            match &d.base {
26916245×
                None => w.u8(0),
2700×
                Some(DeferredBase::Blob(r)) => {
2710×
                    w.u8(1);
2720×
                    w.object(r);
2730×
                }
2743×
                Some(DeferredBase::Inline(v)) => {
2753×
                    w.u8(2);
2763×
                    w.bytes(&cbor::encode(v));
2773×
                }
278
            }
279
            // Each change's edits with the texts of its inserts, sorted by
280
            // change: a graph does not depend on the order changes applied
281
            // in, and the index is then the same however history was read.
28216248×
            let mut texts = d.texts.iter();
28316248×
            let mut per_change: Vec<(&ChangeHash, &Vec<Edit>, Vec<&TextRef>)> = Vec::new();
28416249×
            for (c, edits) in &d.edits {
28516249×
                let n = edits
28616249×
                    .iter()
28716249×
                    .filter(|e| matches!(e, Edit::Insert { lines, .. } if lines.is_empty()))
28816249×
                    .count();
28916249×
                per_change.push((c, edits, texts.by_ref().take(n).collect()));
290
            }
29116248×
            per_change.sort_by_key(|(c, _, _)| **c);
29216248×
            w.count(per_change.len());
29316249×
            for (c, edits, _) in &per_change {
29416249×
                w.object(c);
29516249×
                w.count(edits.len());
29616249×
                for e in edits.iter() {
29716249×
                    match e {
298
                        Edit::Insert {
29916249×
                            node,
30016249×
                            after,
30116249×
                            before,
30216249×
                            lines,
303
                        } => {
30416249×
                            if !lines.is_empty() {
3050×
                                return None;
30616249×
                            }
30716249×
                            w.u8(0);
30816249×
                            w.fixed(&node.0);
30916249×
                            atom(&mut w, after);
31016249×
                            atom(&mut w, before);
311
                        }
3120×
                        Edit::Delete { node, atoms } => {
3130×
                            w.u8(1);
3140×
                            w.fixed(&node.0);
3150×
                            w.count(atoms.len());
3160×
                            for r in atoms {
3170×
                                w.object(&r.change);
3180×
                                w.u32(r.from);
3190×
                                w.u32(r.to);
3200×
                            }
321
                        }
3220×
                        Edit::Replace { .. } => return None,
323
                    }
324
                }
325
            }
32616248×
            let texts: Vec<&TextRef> = per_change
32716248×
                .iter()
32816249×
                .flat_map(|(_, _, t)| t.iter().copied())
32916248×
                .collect();
33016248×
            w.count(texts.len());
33116249×
            for t in texts {
33216249×
                match t {
3330×
                    TextRef::Blob(r, count, form) => {
3340×
                        w.u8(0);
3350×
                        w.object(r);
3360×
                        w.u32(*count);
3370×
                        w.u8(match form {
3380×
                            crate::objects::TextForm::Cbor => 0,
3390×
                            crate::objects::TextForm::Raw => 1,
3400×
                            crate::objects::TextForm::CborFallback => 2,
341
                        });
342
                    }
34316249×
                    TextRef::Inline { change, start, end } => {
34416249×
                        w.u8(1);
34516249×
                        w.object(change);
34616249×
                        w.u32(*start);
34716249×
                        w.u32(*end);
34816249×
                    }
349
                }
350
            }
35116248×
            let body = std::mem::replace(&mut w, outer_w);
35216248×
            w.bytes(&body.0);
353
        }
354808×
        let mut outer = outer;
355808×
        outer.bytes(&w.0);
356808×
        Some(outer.0)
357808×
    }
358
359
    /// The state an index holds (see [`State::write_index`]).
360187×
    pub fn read_index(bytes: &[u8]) -> Result<State, ObjectError> {
361187×
        Self::read_index_in(&Arc::new(bytes.to_vec()), 0)
362187×
    }
363
364
    /// As [`State::read_index`], for an index at `at` in `file`, which the
365
    /// files' histories keep pointing into rather than copying: most of an
366
    /// index is histories a command never decodes.
3671804×
    pub fn read_index_in(file: &Arc<Vec<u8>>, at: usize) -> Result<State, ObjectError> {
368
        use crate::flat::Reader;
3691804×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
3701804×
        let bytes = file.get(at..).ok_or_else(|| bad("truncated"))?;
3711804×
        let mut r = Reader::new(bytes);
3721804×
        let mut st = State::new_history_only();
373
        {
3741804×
            let _t = crate::timing::phase("index: changes");
3751804×
            st.changes = Self::read_index_changes(r.bytes()?)?;
376
        }
3771804×
        let tree_bytes = r.bytes()?;
3781804×
        for _ in 0..r.count()? {
3792×
            let n = NodeId(r.fixed::<16>()?);
3802×
            let mut recs = Vec::new();
3812×
            for _ in 0..r.count()? {
3822×
                recs.push((r.object()?, r.opt_object()?, r.opt_object()?));
383
            }
3842×
            st.replaces.insert(n, recs);
385
        }
3861804×
        let deferred_bytes = r.bytes()?;
3871804×
        if !r.at_end() {
3880×
            return Err(bad("trailing bytes"));
3891804×
        }
3901804×
        let start = deferred_bytes.as_ptr() as usize - file.as_ptr() as usize;
3911804×
        let (tree, deferred) = rayon::join(
3921804×
            || TreeGraph::read_flat(&mut Reader::new(tree_bytes)),
3931804×
            || Self::read_deferred(file, start..start + deferred_bytes.len()),
394
        );
3951804×
        st.tree = tree?;
3961804×
        st.deferred = Some(deferred?);
3971804×
        Ok(st)
3981804×
    }
399
400
    /// The changes of a state index: its first block, which a reader can
401
    /// take without the rest (the log needs no more).
4021957×
    pub fn read_index_changes(
4031957×
        bytes: &[u8],
4041957×
    ) -> Result<HashMap<ChangeHash, Arc<ChangeMeta>>, ObjectError> {
405
        use crate::flat::Reader;
4061957×
        let mut r = Reader::new(bytes);
4071957×
        if r.fixed::<18>()?.as_slice() != Self::INDEX_MAGIC {
4080×
            return Err(ObjectError::Schema("state index: not a state index".into()));
4091957×
        }
4101957×
        let n = r.count()?;
4111957×
        let mut changes = HashMap::with_capacity(n);
4121957×
        for _ in 0..n {
413120×
            let h = r.object()?;
414120×
            changes.insert(h, Arc::new(ChangeMeta::read_flat(&mut r)?));
415
        }
4161957×
        if !r.at_end() {
4170×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
4181957×
        }
4191957×
        Ok(changes)
4201957×
    }
421
422
    /// The deferred block: each node with its graph key and its body,
423
    /// left encoded (see [`Deferred`]).
4241804×
    fn read_deferred(
4251804×
        file: &Arc<Vec<u8>>,
4261804×
        within: std::ops::Range<usize>,
4271804×
    ) -> Result<crate::fasthash::FastMap<NodeId, Arc<Deferred>>, ObjectError> {
428
        use crate::flat::Reader;
4291804×
        let _t = crate::timing::phase("index: deferred");
4301804×
        let mut r = Reader::new(&file[within]);
4311804×
        let mut deferred = crate::fasthash::FastMap::default();
4321804×
        let n = r.count()?;
4331804×
        deferred.reserve(n);
4341804×
        for _ in 0..n {
43516568×
            let id = NodeId(r.fixed::<16>()?);
43616568×
            let key = r.fixed::<32>()?;
43716568×
            let body = r.bytes()?;
43816568×
            let start = body.as_ptr() as usize - file.as_ptr() as usize;
43916568×
            let d = Deferred {
44016568×
                raw: Some((file.clone(), start..start + body.len())),
44116568×
                key: std::sync::OnceLock::from(key),
44216568×
                ..Deferred::default()
44316568×
            };
44416568×
            deferred.insert(id, Arc::new(d));
445
        }
4461804×
        if !r.at_end() {
4470×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
4481804×
        }
4491804×
        Ok(deferred)
4501804×
    }
451
452
    /// One node's deferred history as the index encodes it.
4535449×
    fn read_deferred_body(bytes: &[u8]) -> Result<DeferredBody, ObjectError> {
454
        use crate::flat::Reader;
4555449×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
4565449×
        let node = |r: &mut Reader| -> Result<NodeId, ObjectError> { Ok(NodeId(r.fixed::<16>()?)) };
45710892×
        let atom = |r: &mut Reader| -> Result<AtomRef, ObjectError> {
45810892×
            Ok(match r.u8()? {
4595445×
                0 => AtomRef::Start,
4605446×
                1 => AtomRef::End,
461
                2 => AtomRef::Atom {
4621×
                    change: r.object()?,
4631×
                    index: r.u32()?,
464
                },
4650×
                _ => return Err(bad("atom")),
466
            })
46710892×
        };
4685449×
        let mut r = Reader::new(bytes);
4695449×
        let base = match r.u8()? {
4705445×
            0 => None,
4710×
            1 => Some(DeferredBase::Blob(r.object()?)),
4724×
            _ => Some(DeferredBase::Inline(cbor::decode(r.bytes()?)?)),
473
        };
4745449×
        let mut edits = Vec::new();
4755449×
        for _ in 0..r.count()? {
4765446×
            let c = r.object()?;
4775446×
            let mut es = Vec::new();
4785446×
            for _ in 0..r.count()? {
4795446×
                es.push(match r.u8()? {
480
                    0 => Edit::Insert {
4815446×
                        node: node(&mut r)?,
4825446×
                        after: atom(&mut r)?,
4835446×
                        before: atom(&mut r)?,
4845446×
                        lines: crate::lines::Lines::default(),
485
                    },
486
                    1 => {
4870×
                        let node = node(&mut r)?;
4880×
                        let mut atoms = Vec::new();
4890×
                        for _ in 0..r.count()? {
4900×
                            atoms.push(crate::objects::AtomRange {
4910×
                                change: r.object()?,
4920×
                                from: r.u32()?,
4930×
                                to: r.u32()?,
494
                            });
495
                        }
4960×
                        Edit::Delete { node, atoms }
497
                    }
4980×
                    _ => return Err(bad("edit")),
499
                });
500
            }
5015446×
            edits.push((c, es));
502
        }
5035449×
        let mut texts = Vec::new();
5045449×
        for _ in 0..r.count()? {
5055446×
            texts.push(match r.u8()? {
506
                0 => TextRef::Blob(
5070×
                    r.object()?,
5080×
                    r.u32()?,
5090×
                    match r.u8()? {
5100×
                        0 => crate::objects::TextForm::Cbor,
5110×
                        1 => crate::objects::TextForm::Raw,
5120×
                        _ => crate::objects::TextForm::CborFallback,
513
                    },
514
                ),
515
                _ => TextRef::Inline {
5165446×
                    change: r.object()?,
5175446×
                    start: r.u32()?,
5185446×
                    end: r.u32()?,
519
                },
520
            });
521
        }
5225449×
        if !r.at_end() {
5230×
            return Err(bad("trailing bytes in a file's history"));
5245449×
        }
5255449×
        Ok(DeferredBody { base, edits, texts })
5265449×
    }
527
}
528
529
impl Clone for State {
5301322×
    fn clone(&self) -> State {
5311322×
        State {
5321322×
            changes: self.changes.clone(),
5331322×
            tree: self.tree.clone(),
5341322×
            files: self.files.clone(),
5351322×
            replaces: self.replaces.clone(),
5361322×
            // A cache: the clone builds its own.
5371322×
            closure: Mutex::new(ClosureMemo::default()),
5381322×
            levels: Mutex::new(HashMap::new()),
5391322×
            deferred: self.deferred.clone(),
5401322×
        }
5411322×
    }
542
}
543
544
#[derive(Clone, Debug, PartialEq, Eq)]
545
pub enum FileContent {
546
    Text {
547
        bytes: Vec<u8>,
548
        materialized: Materialized,
549
    },
550
    /// Live blobs; more than one is a replace conflict (spec §9.3).
551
    Opaque {
552
        blobs: Vec<ObjectRef>,
553
    },
554
    Dir,
555
}
556
557
#[derive(Clone, Debug, PartialEq, Eq)]
558
pub struct FileState {
559
    pub node: NodeId,
560
    pub kind: NodeKind,
561
    pub mode: Mode,
562
    pub content: FileContent,
563
}
564
565
impl FileState {
56613674×
    pub fn is_conflicted(&self) -> bool {
56713674×
        match &self.content {
56812705×
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
569243×
            FileContent::Opaque { blobs } => blobs.len() > 1,
570726×
            FileContent::Dir => false,
571
        }
57213674×
    }
573
}
574
575
/// See `State::conflict_regions`.
576
#[derive(Clone, Debug, Default, PartialEq, Eq)]
577
pub struct ConflictRegions {
578
    pub plain: Vec<(AtomKey, Vec<u8>)>,
579
    pub region_atoms: Vec<AtomKey>,
580
    pub contributors: Vec<ChangeHash>,
581
}
582
583
/// The whole tree of a state, materialized.
584
#[derive(Clone, Debug, Default)]
585
pub struct Snapshot {
586
    pub tree: TreeView,
587
    pub files: BTreeMap<String, FileState>,
588
    /// Text files left unrendered by [`State::materialize_except`]: their
589
    /// `bytes` are empty and they are known not to be conflicted.
590
    pub unrendered: BTreeSet<String>,
591
}
592
593
impl Snapshot {
5941946×
    pub fn is_conflicted(&self) -> bool {
59513375×
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
5961946×
    }
597
}
598
59962188×
fn vertex(r: AtomRef) -> Vertex {
60062188×
    match r {
60125982×
        AtomRef::Start => Vertex::Start,
60227200×
        AtomRef::End => Vertex::End,
6039006×
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
604
    }
60562188×
}
606
607
/// Replace self references in a tree op with the concrete change hash.
60838733×
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
60938733×
    match op {
610867×
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
611867×
            node: *node,
612867×
            placement: placement.resolve(me),
613867×
        },
614
        TreeOp::Move {
615135×
            node,
616135×
            old,
617135×
            parent,
618135×
            name,
619135×
        } => TreeOp::Move {
620135×
            node: *node,
621135×
            old: old.resolve(me),
622135×
            parent: *parent,
623135×
            name: name.clone(),
624135×
        },
62522×
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
62622×
            node: *node,
62722×
            old: old.resolve(me),
62822×
            mode: *mode,
62922×
        },
63037709×
        add @ TreeOp::AddNode { .. } => add.clone(),
631
    }
63238733×
}
633
634
/// Apply one change's edits of one file (inserts and deletes; replaces
635
/// live beside the graphs) to that file's graph.
63625699×
fn apply_file_edits(g: &mut FileGraph, h: ChangeHash, edits: Vec<Edit>) {
637
    // The graph's kept order, if any, follows the edits (see `Order`).
63825699×
    let order = g.take_order();
63925699×
    let mut inserts: Vec<(Vertex, Vertex, u32, u32)> = Vec::new();
64025699×
    let mut deleted: Vec<crate::graph::AtomKey> = Vec::new();
64125699×
    let mut next = 0u32;
64227841×
    for e in edits {
64327841×
        match e {
644
            Edit::Insert {
64526422×
                after,
64626422×
                before,
64726422×
                lines,
648
                ..
64926422×
            } => {
65026422×
                let first = next;
65126422×
                let count = lines.len() as u32;
65226422×
                next += count;
65326422×
                let (after, before) = (vertex(after.resolve(h)), vertex(before.resolve(h)));
65426422×
                inserts.push((after, before, first, count));
65526422×
                g.insert_owned(h, first, after, before, lines);
65626422×
            }
6571419×
            Edit::Delete { atoms, .. } => {
6582469×
                for r in atoms {
6592469×
                    let r = r.resolve(h);
6602567×
                    deleted.extend((r.from..r.to).map(|i| (r.change, i)));
6612469×
                    g.delete(h, &r);
662
                }
663
            }
6640×
            Edit::Replace { .. } => {}
665
        }
666
    }
66725699×
    if let Some(o) = order {
66878×
        g.keep_spliced(o, h, &inserts, &deleted);
66925621×
    }
67025699×
}
671
672
/// Build the graphs of deferred entries: their checkpoint bases and the
673
/// texts of inserts read without their lines are loaded in one call, then
674
/// the graphs are built in parallel (they are independent).
6753542×
fn build_deferred(
6763542×
    taken: Vec<(NodeId, Deferred)>,
6773542×
    load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
6783542×
    read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
6793542×
) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
6803542×
    let mut taken: Vec<(NodeId, DeferredBody)> =
68122642×
        taken.into_iter().map(|(n, d)| (n, d.into_body())).collect();
6823542×
    let mut refs: Vec<ObjectRef> = taken
6833542×
        .iter()
6843542×
        .filter_map(|(_, d)| match &d.base {
6856×
            Some(DeferredBase::Blob(r)) => Some(*r),
68622636×
            _ => None,
68722642×
        })
6883542×
        .collect();
689
    // Text blobs of inserts read without their lines, after the bases.
6903542×
    let bases = refs.len();
69122642×
    refs.extend(taken.iter().flat_map(|(_, d)| {
69225754×
        d.texts.iter().filter_map(|t| match t {
69370×
            TextRef::Blob(r, _, _) => Some(*r),
69425684×
            TextRef::Inline { .. } => None,
69525754×
        })
69622642×
    }));
697
    // And the encodings of changes whose inline inserts are needed,
698
    // each read once.
6993542×
    let reading = crate::timing::phase("graphs: read changes and blobs");
7003542×
    let mut changes: HashMap<ChangeHash, Arc<Vec<u8>>> = HashMap::new();
70125754×
    for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
70225754×
        if let TextRef::Inline { change, .. } = t {
70325684×
            if !changes.contains_key(change) {
7045776×
                changes.insert(*change, read_change(change)?);
70519908×
            }
70670×
        }
707
    }
7083542×
    let n_changes = changes.len();
7093542×
    drop(reading);
7103542×
    let reading = crate::timing::phase("graphs:   of which blobs");
7113542×
    let mut blobs = if refs.is_empty() {
7123471×
        Vec::new()
713
    } else {
71471×
        load(&refs)?
715
    };
7163539×
    if crate::timing::enabled() {
7172×
        eprintln!(
7182×
            "timing graphs: {} graphs, {n_changes} changes, {} blobs",
7192×
            taken.len(),
7202×
            refs.len()
7212×
        );
7223537×
    }
7233539×
    if blobs.len() != refs.len() {
7240×
        return Err(ObjectError::Schema("graph blobs: wrong count".into()));
7253539×
    }
7263539×
    drop(reading);
7273539×
    let lines = crate::timing::phase("graphs: hand out blobs");
7283539×
    let mut texts = blobs.split_off(bases).into_iter();
7293539×
    let mut blobs = blobs.into_iter();
730
    // Hand each graph its own blobs, in order, then fill in its inserts'
731
    // lines and build it, all in parallel: graphs are independent.
732
    type Work = (NodeId, DeferredBody, Option<Vec<u8>>, Vec<Vec<u8>>);
7333539×
    let mut work: Vec<Work> = Vec::with_capacity(taken.len());
73422639×
    for (node, d) in taken.drain(..) {
73522639×
        let wanted = d
73622639×
            .texts
73722639×
            .iter()
73825752×
            .filter(|t| matches!(t, TextRef::Blob(..)))
73922639×
            .count();
74022639×
        let mine: Vec<Vec<u8>> = texts.by_ref().take(wanted).collect();
74122639×
        if mine.len() != wanted {
7420×
            return Err(ObjectError::Schema("text blobs: wrong count".into()));
74322639×
        }
74422639×
        let bytes = match &d.base {
745
            Some(DeferredBase::Blob(_)) => Some(
7465×
                blobs
7475×
                    .next()
7485×
                    .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
749
            ),
75022634×
            _ => None,
751
        };
75222639×
        work.push((node, d, bytes, mine));
753
    }
7543539×
    drop(lines);
7553539×
    let _t = crate::timing::phase("graphs: lines and build");
756
    use rayon::prelude::*;
7573539×
    let changes = &changes;
7583539×
    let built: Vec<(NodeId, FileGraph)> = work
7593539×
        .into_par_iter()
76022639×
        .map(|(node, mut d, bytes, mine)| {
761
            // Fill in the lines of inserts read without them, in order.
76222639×
            let mut want = std::mem::take(&mut d.texts).into_iter();
76322639×
            let mut mine = mine.into_iter();
76425217×
            for (_, edits) in d.edits.iter_mut() {
76526917×
                for e in edits.iter_mut() {
76626917×
                    if let Edit::Insert { lines, .. } = e {
76725759×
                        if lines.is_empty() {
76825752×
                            *lines = match want.next() {
76968×
                                Some(TextRef::Blob(_, count, form)) => {
77068×
                                    let content = mine.next().ok_or_else(|| {
7710×
                                        ObjectError::Schema("text blobs: wrong count".into())
7720×
                                    })?;
77368×
                                    crate::objects::text_lines(&content, count, form)?
774
                                }
77525684×
                                Some(TextRef::Inline { change, start, end }) => {
77625684×
                                    let bytes = &changes[&change];
77725684×
                                    let range = bytes
77825684×
                                        .get(start as usize..end as usize)
77925684×
                                        .ok_or_else(|| {
7800×
                                            ObjectError::Schema(
7810×
                                                "an inline insert lies outside its change".into(),
7820×
                                            )
7830×
                                        })?;
78425684×
                                    crate::objects::inline_lines(range)?
785
                                }
786
                                None => {
7870×
                                    return Err(ObjectError::Schema(
7880×
                                        "an insert's text is missing".into(),
7890×
                                    ))
790
                                }
791
                            };
7927×
                        }
7931158×
                    }
794
                }
795
            }
79622639×
            let mut graph = match (d.base.take(), bytes) {
79796×
                (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
7985×
                (Some(DeferredBase::Blob(_)), Some(bytes)) => {
7995×
                    FileGraph::from_value(&cbor::decode(&bytes)?)?
800
                }
80122538×
                _ => FileGraph::default(),
802
            };
80325217×
            for (h, edits) in std::mem::take(&mut d.edits) {
80425217×
                apply_file_edits(&mut graph, h, edits);
80525217×
            }
80622639×
            Ok((node, graph))
80722639×
        })
8083539×
        .collect::<Result<_, ObjectError>>()?;
8093539×
    Ok(built)
8103542×
}
811
812
impl State {
813686×
    pub fn new() -> Self {
814686×
        Self::default()
815686×
    }
816
817
    /// An empty state for history only: changes and tree are kept, file
818
    /// edits are recorded but no file graph is built until
819
    /// [`State::load_graphs`] asks for it. For log and other commands that
820
    /// need no file contents, or only a few files.
8213399×
    pub fn new_history_only() -> Self {
8223399×
        State {
8233399×
            deferred: Some(Default::default()),
8243399×
            ..Self::default()
8253399×
        }
8263399×
    }
827
828
    /// Whether `node`'s file graph is built (always, in a full state).
82940×
    pub fn is_built(&self, node: &NodeId) -> bool {
83040×
        self.deferred.is_none() || self.files.contains_key(node)
83140×
    }
832
833
    /// Whether this state builds file graphs only when asked
834
    /// ([`State::new_history_only`]), even if it has none waiting.
8353229×
    pub fn is_history_only(&self) -> bool {
8363229×
        self.deferred.is_some()
8373229×
    }
838
839
    /// Whether this state holds every file graph.
8402659×
    pub fn is_full(&self) -> bool {
8412659×
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
8422659×
    }
843
844
    /// The graph of `node`, which must be loaded: asking a history-only
845
    /// state for a graph it has not built is a bug, never an empty file.
84625068×
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
84725068×
        if let Some(d) = &self.deferred {
8489965×
            assert!(
8499965×
                !d.contains_key(node),
850
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
8511×
                node.short(12)
852
            );
85315103×
        }
85425067×
        self.files.get(node).map(|g| g.as_ref())
85525067×
    }
856
857
    /// Operations over every file need every graph.
8582652×
    fn require_full(&self, what: &str) {
8592652×
        assert!(
8602652×
            self.is_full(),
861
            "{what} needs every file graph; this state was loaded for history only"
862
        );
8632651×
    }
864
865
    /// Build the graphs of `nodes` in a history-only state: from their
866
    /// checkpoint base (blobs read in one batch through `load`) and their
867
    /// deferred edits. Nodes already built, or with no graph, are skipped.
8683473×
    pub fn load_graphs(
8693473×
        &mut self,
8703473×
        nodes: &[NodeId],
8713473×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
8723473×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
8733473×
    ) -> Result<(), ObjectError> {
8743473×
        let Some(deferred) = self.deferred.as_mut() else {
8750×
            return Ok(());
876
        };
8773473×
        let taken: Vec<(NodeId, Deferred)> = nodes
8783473×
            .iter()
87922816×
            .filter_map(|n| deferred.remove(n).map(|d| (*n, Arc::unwrap_or_clone(d))))
8803473×
            .collect();
8813473×
        let built = build_deferred(taken, load, read_change)?;
8823470×
        self.files
88322582×
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
8843470×
        Ok(())
8853473×
    }
886
887
    /// The graphs of `nodes`, built from this history-only state's deferred
888
    /// edits without building them in it: the state stays history only, so
889
    /// changes read without their lines can still be added to it and every
890
    /// graph keeps its key. For a caller that renders a few files of many
891
    /// states in turn (verifying an import).
89269×
    pub fn build_graphs_detached(
89369×
        &self,
89469×
        nodes: &[NodeId],
89569×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
89669×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
89769×
    ) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
89869×
        let Some(deferred) = self.deferred.as_ref() else {
8990×
            return Ok(Vec::new());
900
        };
901
        // A file this state has built has no deferred history: its graph
902
        // is the built one, copied. Built from an empty history instead, it
903
        // rendered as an empty file, and a merge taking this path recorded
904
        // the whole file as inserted again, conflicting with itself (#71).
90569×
        let mut built: Vec<(NodeId, FileGraph)> = Vec::new();
90669×
        let mut copies: Vec<(NodeId, Deferred)> = Vec::new();
90769×
        for n in nodes {
90860×
            match (self.files.get(n), deferred.get(n)) {
9093×
                (Some(g), _) => built.push((*n, (**g).clone())),
91057×
                (None, d) => copies.push((*n, d.map(|d| (**d).clone()).unwrap_or_default())),
911
            }
912
        }
91369×
        let mut out = build_deferred(copies, load, read_change)?;
91469×
        out.extend(built);
91569×
        Ok(out)
91669×
    }
917
918
    /// Render a graph built for this state (see
919
    /// [`State::build_graphs_detached`]), as [`State::render_file`] does.
92060×
    pub fn render_graph(&self, g: &FileGraph) -> (Vec<u8>, Materialized) {
92160×
        let m = g.materialize(self);
92260×
        let bytes = g.render(&m, &|h| self.label(h));
92360×
        (bytes, m)
92460×
    }
925
926
    /// Every file graph a history-only state has not built, deleted files'
927
    /// included.
92876×
    pub fn unbuilt_nodes(&self) -> Vec<NodeId> {
92976×
        self.deferred
93076×
            .as_ref()
93176×
            .map(|d| d.keys().copied().collect())
93276×
            .unwrap_or_default()
93376×
    }
934
935
    /// Drop the built graphs of `nodes`, for a caller rendering a large
936
    /// tree a batch at a time. The state can no longer render those files,
937
    /// so it must not be used for them again.
938433×
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
9396054×
        for n in nodes {
9406054×
            self.files.remove(n);
9416054×
        }
942433×
    }
943
944
    /// Build every graph a history-only state has not built, making it full.
9451740×
    pub fn load_all_graphs(
9461740×
        &mut self,
9471740×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
9481740×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
9491740×
    ) -> Result<(), ObjectError> {
9501740×
        let nodes: Vec<NodeId> = match &self.deferred {
9511740×
            Some(d) => d.keys().copied().collect(),
9520×
            None => return Ok(()),
953
        };
9541740×
        self.load_graphs(&nodes, load, read_change)?;
9551740×
        self.deferred = None;
9561740×
        Ok(())
9571740×
    }
958
959
    /// The one text a file's history is, when it is a single insert of
960
    /// the whole file into nothing (a file added once and never edited,
961
    /// with no checkpoint base): its rendering is that text, so it needs
962
    /// no graph. `None` otherwise, or when the graph is built.
9635908×
    pub fn single_text(&self, node: &NodeId) -> Option<TextRef> {
9645908×
        if self.files.contains_key(node) {
9650×
            return None;
9665908×
        }
9675908×
        let d = self.deferred.as_ref()?.get(node)?.body();
9685840×
        let [(_, edits)] = d.edits.as_slice() else {
969261×
            return None;
970
        };
971
        let [Edit::Insert {
972
            after: AtomRef::Start,
973
            before: AtomRef::End,
9745579×
            lines,
975
            ..
9765579×
        }] = edits.as_slice()
977
        else {
9780×
            return None;
979
        };
9805579×
        match (&d.base, d.texts.as_slice()) {
9815579×
            (None, [t]) if lines.is_empty() => Some(*t),
9820×
            _ => None,
983
        }
9845908×
    }
985
986
    /// A key for the graph of `node` in a history-only state that has not
987
    /// built it: equal keys mean equal graphs, so equal renderings (a
988
    /// rendering depends only on the graph and on the changes' own
989
    /// immutable metadata). It names the node, its checkpoint base (a blob,
990
    /// an inline value, or none) and the set of later changes that edited
991
    /// the file.
992
    /// `None` for a full state or a graph already built.
99328731×
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
99428731×
        let deferred = self.deferred.as_ref()?;
99528697×
        if self.files.contains_key(node) {
996441×
            return None;
99728256×
        }
99828256×
        let mut h = blake3::Hasher::new();
99928256×
        h.update(b"oxy graph key 1\0");
1000
        // A change's edits are applied per node: the node is part of it.
100128256×
        h.update(&node.0);
100228256×
        let Some(d) = deferred.get(node) else {
1003
            // Never edited: the empty graph.
1004226×
            h.update(&[0]);
1005226×
            return Some(*h.finalize().as_bytes());
1006
        };
100728030×
        Some(*d.key.get_or_init(|| d.graph_key(h)))
100828731×
    }
1009
10103493×
    pub fn len(&self) -> usize {
10113493×
        self.changes.len()
10123493×
    }
1013
1014
    /// Turn this history-only state's built graphs back into deferred
1015
    /// histories, each starting from its graph encoded as a checkpoint
1016
    /// graph and stored by `store` (it returns the blob's reference): what
1017
    /// they held stays, and memory goes back to what a history-only state
1018
    /// costs. A graph built later again decodes that blob and applies only
1019
    /// the edits that came after. Graph keys change (the base is now a
1020
    /// blob), which only means a cached rendering is not reused.
10211×
    pub fn shed_graphs<E>(
10221×
        &mut self,
10231×
        mut store: impl FnMut(&[u8]) -> Result<ObjectRef, E>,
10241×
    ) -> Result<usize, E> {
1025
        use rayon::prelude::*;
10261×
        let Some(deferred) = self.deferred.as_mut() else {
10270×
            return Ok(0);
1028
        };
10291×
        let graphs: Vec<(NodeId, Arc<FileGraph>)> = self.files.drain().collect();
10301×
        let encoded: Vec<(NodeId, Vec<u8>)> = graphs
10311×
            .par_iter()
10322×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
10331×
            .collect();
10341×
        drop(graphs);
10351×
        let shed = encoded.len();
10362×
        for (node, bytes) in encoded {
10372×
            let blob = store(&bytes)?;
10382×
            deferred.insert(
10392×
                node,
10402×
                Arc::new(Deferred::from_body(DeferredBody {
10412×
                    base: Some(DeferredBase::Blob(blob)),
10422×
                    ..DeferredBody::default()
10432×
                })),
1044
            );
1045
        }
10461×
        Ok(shed)
10471×
    }
1048
1049
    /// How many file graphs this state has built.
105071×
    pub fn built_count(&self) -> usize {
105171×
        self.files.len()
105271×
    }
1053
1054
    /// Atoms in this state's built graphs, live and deleted: what their
1055
    /// memory follows, since a graph keeps every line its file ever had.
105646×
    pub fn built_atoms(&self) -> usize {
105753×
        self.files.values().map(|g| g.atom_count()).sum()
105846×
    }
1059
1060
    /// Edits held in the deferred histories of files not built, and the
1061
    /// most any one file holds (for measuring, #25).
10620×
    pub fn deferred_edit_count(&self) -> (usize, usize) {
10630×
        let Some(d) = self.deferred.as_ref() else {
10640×
            return (0, 0);
1065
        };
10660×
        let mut total = 0;
10670×
        let mut most = 0;
10680×
        for v in d.values() {
10690×
            let n: usize = v.body().edits.iter().map(|(_, e)| e.len()).sum();
10700×
            total += n;
10710×
            most = most.max(n);
1072
        }
10730×
        (total, most)
10740×
    }
1075
}
1076
1077
impl Deferred {
1078
    /// See [`State::graph_key`]: `h` has taken the node already.
107922073×
    fn graph_key(&self, mut h: blake3::Hasher) -> [u8; 32] {
108022073×
        let d = self.body();
108113×
        match &d.base {
108222060×
            None => h.update(&[0]),
10830×
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
108413×
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
1085
        };
108622073×
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
108722073×
        changes.sort();
108822073×
        changes.dedup();
108922073×
        h.update(&(changes.len() as u64).to_le_bytes());
109023466×
        for c in changes {
109123466×
            h.update(&c.0);
109223466×
        }
109322073×
        *h.finalize().as_bytes()
109422073×
    }
1095
}
1096
1097
impl State {
10980×
    pub fn is_empty(&self) -> bool {
10990×
        self.changes.is_empty()
11000×
    }
110114791×
    pub fn contains(&self, h: &ChangeHash) -> bool {
110214791×
        self.changes.contains_key(h)
110314791×
    }
110464×
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
110564×
        self.changes.get(h).map(|m| &**m)
110664×
    }
11071317×
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
11083323×
        self.changes.iter().map(|(h, m)| (h, &**m))
11091317×
    }
111017249×
    pub fn tree(&self) -> &TreeGraph {
111117249×
        &self.tree
111217249×
    }
1113586×
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
1114586×
        self.graph(node)
1115586×
    }
1116
1117
    /// Add a change whose dependencies are already present.
11182955×
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
11192955×
        let h = change.hash();
11202955×
        self.add_hashed(h, change)
11212955×
    }
1122
1123
    /// [`State::add`] for a change whose hash `h` is already known (it was
1124
    /// just stored), so it is not encoded again.
11253602×
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
11263602×
        if self.changes.contains_key(&h) {
112735×
            return Ok(h);
11283567×
        }
11295092×
        for d in &change.deps {
11305092×
            if !self.changes.contains_key(d) {
11312×
                return Err(StateError::MissingDep(*d, h));
11325090×
            }
1133
        }
11343565×
        self.add_known(h, change, Vec::new());
11353565×
        Ok(h)
11363602×
    }
1137
1138
    /// Add a change in any order; call `validate` once all are in.
11391122×
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
11401122×
        let h = change.hash();
11411122×
        self.add_known(h, change, Vec::new());
11421122×
        h
11431122×
    }
1144
1145
    /// Add a change just stored under hash `h` to a history-only state that
1146
    /// has built some graphs: an edit of a built graph is applied whole
1147
    /// (from `full`), and one of a file not built waits without its text
1148
    /// (from `skeleton` and its `texts`, as the store reads it back), so the
1149
    /// state holds no text it has not built. A Git import adds each change
1150
    /// it makes this way, keeping memory to what changes.
115184×
    pub fn add_known_mixed(
115284×
        &mut self,
115384×
        h: ChangeHash,
115484×
        full: Change,
115584×
        skeleton: Change,
115684×
        texts: Vec<TextRef>,
115784×
    ) {
115884×
        if self.deferred.is_none() || self.changes.contains_key(&h) {
11590×
            self.add_known(h, full, Vec::new());
11600×
            return;
116184×
        }
1162
        let Change {
116384×
            version,
116484×
            change_id,
116584×
            deps,
116684×
            author,
116784×
            hlc,
116884×
            message,
116984×
            tree_ops,
117084×
            edits: full_edits,
117184×
            kind,
117284×
        } = full;
117384×
        let mut texts = texts.into_iter();
117484×
        let mut edits = Vec::with_capacity(full_edits.len());
117584×
        let mut kept = Vec::new();
117693×
        for (f, s) in full_edits.into_iter().zip(skeleton.edits) {
117793×
            let text = match &s {
117873×
                Edit::Insert { lines, .. } if lines.is_empty() => texts.next(),
117920×
                _ => None,
1180
            };
118193×
            if self.files.contains_key(&f.node()) {
118245×
                edits.push(f);
118348×
            } else {
118448×
                edits.push(s);
118548×
                kept.extend(text);
118648×
            }
1187
        }
118884×
        let c = Change {
118984×
            version,
119084×
            change_id,
119184×
            deps,
119284×
            author,
119384×
            hlc,
119484×
            message,
119584×
            tree_ops,
119684×
            edits,
119784×
            kind,
119884×
        };
119984×
        self.add_known(h, c, kept);
120084×
    }
1201
1202
    /// Add a change read from the store under hash `h`, without hashing it
1203
    /// again (for a version 2 change that means chunking all its text).
1204
    /// `texts` names, in order, the inserts left without their lines (see
1205
    /// [`crate::store::Store::get_change_lazy`]); only a history-only state
1206
    /// takes them, and only for graphs it has not built.
120712723×
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
120812723×
        if self.changes.contains_key(&h) {
12090×
            return;
121012723×
        }
121112723×
        let meta = ChangeMeta::of(&change);
121212723×
        self.apply_with(h, change, texts);
121312723×
        self.changes.insert(h, Arc::new(meta));
121412723×
        {
121512723×
            let mut m = self.closure.lock().unwrap();
121612723×
            m.sets.clear();
121712723×
            m.held = 0;
121812723×
        }
121912723×
    }
1220
1221
    // ------------------------------------------------------------ checkpoints (spec §11)
1222
1223
    /// Serialize the whole state in payload version 1: change metadata,
1224
    /// tree, file graphs, replaces, all in one value (spec §11).
1225380×
    pub fn checkpoint_payload(&self) -> Vec<u8> {
1226380×
        self.require_full("a checkpoint");
1227380×
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
1228380×
        nodes.sort();
1229380×
        let files = Value::Array(
1230380×
            nodes
1231380×
                .into_iter()
12321550×
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
1233380×
                .collect(),
1234
        );
1235380×
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
1236380×
    }
1237
1238
    /// Each file graph encoded on its own, by node, for a version 2 payload
1239
    /// (spec §11): the graphs of large files become blobs of their own.
124018×
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
1241
        use rayon::prelude::*;
124218×
        self.require_full("a checkpoint");
124318×
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
124453×
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
124518×
        nodes.sort_by_key(|(n, _)| **n);
124618×
        nodes
124718×
            .into_par_iter()
124853×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
124918×
            .collect()
125018×
    }
1251
1252
    /// The payload version 2 index for the graphs of
1253
    /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than
1254
    /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by
1255
    /// `blob_of` (the ObjectRef of the blob holding its encoding).
125618×
    pub fn checkpoint_index(
125718×
        &self,
125818×
        graphs: &[(NodeId, Vec<u8>)],
125918×
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
126018×
    ) -> Vec<u8> {
126118×
        let files = Value::Array(
126218×
            graphs
126318×
                .iter()
126453×
                .map(|(n, enc)| {
126553×
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
126646×
                        cbor::decode(enc).expect("an encoded graph decodes")
1267
                    } else {
12687×
                        Value::Bytes(blob_of(enc).0.to_vec())
1269
                    };
127053×
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
127153×
                })
127218×
                .collect(),
1273
        );
127418×
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
127518×
    }
1276
1277
    /// The payload map around `files`: changes, tree and replaces as in version 1.
1278398×
    fn payload_value(&self, version: u64, files: Value) -> Value {
1279398×
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
1280398×
        hashes.sort();
1281398×
        let changes = Value::Array(
1282398×
            hashes
1283398×
                .into_iter()
12842539×
                .map(|h| {
12852539×
                    let m = &self.changes[h];
12862539×
                    Value::Array(vec![
12872539×
                        Value::Bytes(h.0.to_vec()),
12882539×
                        Value::Bytes(m.change_id.0.to_vec()),
12892539×
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
12902539×
                        Value::Text(m.message.clone()),
12912539×
                        Value::Uint(m.hlc.wall_ms),
12922539×
                        Value::Uint(m.hlc.logical as u64),
12932539×
                        Value::Uint(m.kind.tag()),
12942539×
                        Value::Bytes(m.author.0.to_vec()),
1295
                    ])
12962539×
                })
1297398×
                .collect(),
1298
        );
1299398×
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
1300398×
        rnodes.sort();
1301398×
        let opt =
130210×
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
1303398×
        let replaces = Value::Array(
1304398×
            rnodes
1305398×
                .into_iter()
1306398×
                .map(|n| {
13075×
                    Value::Array(vec![
13085×
                        Value::Bytes(n.0.to_vec()),
1309
                        Value::Array(
13105×
                            self.replaces[n]
13115×
                                .iter()
13125×
                                .map(|(c, o, nw)| {
13135×
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
13145×
                                })
13155×
                                .collect(),
1316
                        ),
1317
                    ])
13185×
                })
1319398×
                .collect(),
1320
        );
1321398×
        Value::map([
1322398×
            (0, Value::Uint(version)),
1323398×
            (1, changes),
1324398×
            (2, self.tree.to_value()),
1325398×
            (3, files),
1326398×
            (4, replaces),
1327398×
        ])
1328398×
    }
1329
1330
    /// Decode a version 1 payload (the whole state in one value). A
1331
    /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`].
133237×
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
133337×
        State::from_checkpoint(bytes, |_| {
13341×
            Err(ObjectError::Schema(
13351×
                "a version 2 checkpoint needs its graph blobs".into(),
13361×
            ))
13371×
        })
133837×
    }
1339
1340
    /// Decode a checkpoint payload of either version (spec §11). For
1341
    /// version 2, `load` returns the contents of the named graph blobs, in
1342
    /// order; the graphs are then decoded in parallel.
134360×
    pub fn from_checkpoint(
134460×
        bytes: &[u8],
134560×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
134660×
    ) -> Result<State, ObjectError> {
1347
        use rayon::prelude::*;
134860×
        let v = cbor::decode(bytes)?;
134959×
        let m = o::map(&v, "checkpoint payload")?;
135059×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
135159×
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
13521×
            return Err(ObjectError::Schema(format!(
13531×
                "checkpoint payload version {version} is not supported"
13541×
            )));
135558×
        }
135658×
        let mut st = State::payload_common(m)?;
135758×
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
135858×
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
1359237×
        for f in entries {
1360237×
            let e = o::array(f, "file")?;
1361237×
            if e.len() != 2 {
13620×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1363237×
            }
1364237×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1365237×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1366237×
            parsed.push((node, &e[1]));
1367
        }
1368
        // Version 2 names large graphs by blob: fetch those in one batch.
136958×
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
137058×
        if version == CHECKPOINT_INDEX_VERSION {
137120×
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
137220×
                .iter()
137390×
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
137420×
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
137520×
                .collect::<Result<_, ObjectError>>()?;
137620×
            if !wanted.is_empty() {
13777×
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
13783×
                let contents = {
13797×
                    let _t = crate::timing::phase("load:   graph blobs read");
13807×
                    load(&refs)?
1381
                };
13823×
                if contents.len() != refs.len() {
13830×
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
13843×
                }
13853×
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
138613×
            }
1387147×
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
13880×
            return Err(ObjectError::Schema(
13890×
                "a version 1 payload holds graphs inline".into(),
13900×
            ));
139138×
        }
1392
        // File graphs are independent; decode and build them in parallel.
139354×
        let graphs = parsed
139454×
            .par_iter()
1395231×
            .map(|(node, entry)| {
1396231×
                let graph = match fetched.get(node) {
13973×
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
1398228×
                    None => FileGraph::from_value(entry)?,
1399
                };
1400231×
                Ok((*node, graph))
1401231×
            })
140254×
            .collect::<Result<Vec<_>, ObjectError>>()?;
140354×
        st.files
1404231×
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
140554×
        Ok(st)
140660×
    }
1407
1408
    /// The graph blobs a payload names: empty for version 1.
14099×
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
14109×
        let v = cbor::decode(bytes)?;
14119×
        let m = o::map(&v, "checkpoint payload")?;
14129×
        let mut out = Vec::new();
141327×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
141427×
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
14156×
                out.push(o::oref(entry, "graph blob")?);
141621×
            }
1417
        }
14189×
        Ok(out)
14199×
    }
1420
1421
    /// Decode a checkpoint payload for history only: a version 2 payload's
1422
    /// graphs are noted, not read or built, and come later through
1423
    /// [`State::load_graphs`]. A version 1 payload holds them inline and is
1424
    /// decoded in full.
142542×
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
142642×
        let v = cbor::decode(bytes)?;
142742×
        let m = o::map(&v, "checkpoint payload")?;
142842×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
142942×
        if version != CHECKPOINT_INDEX_VERSION {
14301×
            return State::from_checkpoint_payload(bytes);
143141×
        }
143241×
        let mut st = State::payload_common(m)?;
143341×
        let mut deferred = crate::fasthash::FastMap::default();
1434139×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1435139×
            let e = o::array(f, "file")?;
1436139×
            if e.len() != 2 {
14370×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1438139×
            }
1439139×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1440139×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1441139×
            let base = match &e[1] {
14424×
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
1443135×
                other => DeferredBase::Inline(other.clone()),
1444
            };
1445139×
            deferred.insert(
1446139×
                node,
1447139×
                Arc::new(Deferred::from_body(DeferredBody {
1448139×
                    base: Some(base),
1449139×
                    ..DeferredBody::default()
1450139×
                })),
1451
            );
1452
        }
145341×
        st.deferred = Some(deferred);
145441×
        Ok(st)
145542×
    }
1456
1457
    /// Changes, tree and replaces of a payload of either version.
145899×
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
145999×
        let mut st = State::new();
1460528×
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
1461528×
            let e = o::array(c, "change meta")?;
1462528×
            if e.len() != 8 {
14630×
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
1464528×
            }
1465528×
            let hash = o::oref(&e[0], "hash")?;
1466528×
            let meta = ChangeMeta {
1467528×
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
1468528×
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
1469528×
                deps: o::array(&e[2], "deps")?
1470528×
                    .iter()
1471640×
                    .map(|d| o::oref(d, "dep"))
1472528×
                    .collect::<Result<Vec<_>, _>>()?,
1473528×
                message: o::text(&e[3], "message")?.to_owned(),
1474
                hlc: Hlc {
1475528×
                    wall_ms: o::uint(&e[4], "wall")?,
1476528×
                    logical: o::u32_(&e[5], "logical")?,
1477
                },
1478528×
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
1479528×
                author: o::oref(&e[7], "author")?,
1480
            };
1481528×
            st.changes.insert(hash, Arc::new(meta));
1482
        }
148399×
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
148499×
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
148524×
            if v.is_null() {
148612×
                Ok(None)
1487
            } else {
148812×
                o::oref(v, "blob").map(Some)
1489
            }
149024×
        };
149199×
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
149212×
            let e = o::array(r, "replace")?;
149312×
            if e.len() != 2 {
14940×
                return Err(ObjectError::Schema(
14950×
                    "replace: expected [node, records]".into(),
14960×
                ));
149712×
            }
149812×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
149912×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
150012×
            let mut recs = Vec::new();
150112×
            for rec in o::array(&e[1], "records")? {
150212×
                let x = o::array(rec, "record")?;
150312×
                if x.len() != 3 {
15040×
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
150512×
                }
150612×
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
1507
            }
150812×
            st.replaces.insert(node, recs);
1509
        }
151099×
        Ok(st)
151199×
    }
1512
15133401×
    pub fn validate(&self) -> Result<(), StateError> {
15149242×
        for (h, c) in &self.changes {
15159242×
            for d in &c.deps {
15165665×
                if !self.changes.contains_key(d) {
15170×
                    return Err(StateError::MissingDep(*d, *h));
15185665×
                }
1519
            }
1520
        }
15213401×
        Ok(())
15223401×
    }
1523
152412723×
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
152538733×
        for (i, op) in c.tree_ops.iter().enumerate() {
152638733×
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
152738733×
        }
152812723×
        if let Some(deferred) = self.deferred.as_mut() {
1529
            // History only: edits of files not built wait, grouped per file,
1530
            // with the texts of inserts read without their lines.
15317297×
            let mut texts = texts.into_iter();
15327297×
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
153338555×
            for e in c.edits {
153438555×
                match e {
1535613×
                    Edit::Replace { node, old, new } => {
1536613×
                        self.replaces.entry(node).or_default().push((h, old, new))
1537
                    }
153837942×
                    e => {
153937942×
                        let slot = per_node.entry(e.node()).or_default();
154036062×
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
154132489×
                            slot.1.extend(texts.next());
154232489×
                        }
154337942×
                        slot.0.push(e);
1544
                    }
1545
                }
1546
            }
154735890×
            for (node, (edits, node_texts)) in per_node {
154835890×
                match self.files.get_mut(&node) {
1549482×
                    Some(g) => {
1550482×
                        assert!(
1551482×
                            node_texts.is_empty(),
1552
                            "a change read without its text applied to a built graph"
1553
                        );
1554482×
                        apply_file_edits(Arc::make_mut(g), h, edits)
1555
                    }
155635408×
                    None => {
155735408×
                        let d = Arc::make_mut(deferred.entry(node).or_default());
155835408×
                        let b = d.body_mut();
155935408×
                        b.edits.push((h, edits));
156035408×
                        b.texts.extend(node_texts);
156135408×
                        d.key = Default::default();
156235408×
                    }
1563
                }
1564
            }
15657297×
            return;
15665426×
        }
15675426×
        assert!(
15685426×
            texts.is_empty(),
1569
            "a change read without its text applied to a full state"
1570
        );
15715426×
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
15726378×
        for e in c.edits {
15736378×
            match e {
1574
                Edit::Insert {
15754672×
                    node,
15764672×
                    after,
15774672×
                    before,
15784672×
                    lines,
15794672×
                } => {
15804672×
                    let idx = counters.entry(node).or_default();
15814672×
                    let first = *idx;
15824672×
                    *idx += lines.len() as u32;
15834672×
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
15844672×
                        h,
15854672×
                        first,
15864672×
                        vertex(after.resolve(h)),
15874672×
                        vertex(before.resolve(h)),
15884672×
                        lines,
15894672×
                    );
15904672×
                }
15911598×
                Edit::Delete { node, atoms } => {
15921598×
                    let g = Arc::make_mut(self.files.entry(node).or_default());
15931897×
                    for r in atoms {
15941897×
                        g.delete(h, &r.resolve(h));
15951897×
                    }
1596
                }
1597108×
                Edit::Replace { node, old, new } => {
1598108×
                    self.replaces.entry(node).or_default().push((h, old, new));
1599108×
                }
1600
            }
1601
        }
160212723×
    }
1603
1604
    /// Transitive dependencies of `h`, excluding `h` itself.
16059416×
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
16069416×
        if let Some(c) = self.closure.lock().unwrap().sets.get(h) {
16077952×
            return c.clone();
16081464×
        }
16091464×
        let mut out = HashSet::new();
16101464×
        let mut stack: Vec<ChangeHash> = self
16111464×
            .changes
16121464×
            .get(h)
16131464×
            .map(|c| c.deps.clone())
16141464×
            .unwrap_or_default();
161516999×
        while let Some(d) = stack.pop() {
161615535×
            if out.insert(d) {
161711000×
                if let Some(c) = self.changes.get(&d) {
161811000×
                    stack.extend(c.deps.iter().copied());
161911000×
                }
16204535×
            }
1621
        }
16221464×
        let rc = Arc::new(out);
16231464×
        let mut memo = self.closure.lock().unwrap();
16241464×
        if memo.held + rc.len() > CLOSURE_MEMO_HASHES {
16250×
            memo.sets.clear();
16260×
            memo.held = 0;
16271464×
        }
16281464×
        memo.held += rc.len();
16291464×
        memo.sets.insert(*h, rc.clone());
16301464×
        rc
16319416×
    }
1632
1633
    /// `h`'s level (see `levels`), worked out for it and its ancestors not
1634
    /// yet known, without recursion: histories are deeper than a stack. An
1635
    /// unknown change has level 0.
1636404688×
    fn level(&self, h: &ChangeHash) -> u32 {
1637404688×
        let mut levels = self.levels.lock().unwrap();
1638404688×
        if let Some(l) = levels.get(h) {
1639402522×
            return *l;
16402166×
        }
16412166×
        let mut stack: Vec<(ChangeHash, bool)> = vec![(*h, false)];
16427311×
        while let Some((c, expanded)) = stack.pop() {
16435145×
            if levels.contains_key(&c) {
164425×
                continue;
16455120×
            }
16465120×
            let deps: &[ChangeHash] = self
16475120×
                .changes
16485120×
                .get(&c)
16495120×
                .map(|m| m.deps.as_slice())
16505120×
                .unwrap_or(&[]);
16515120×
            if expanded {
16522560×
                let l = deps
16532560×
                    .iter()
16543400×
                    .map(|d| levels.get(d).map_or(0, |l| l + 1))
16552560×
                    .max()
16562560×
                    .unwrap_or(0);
16572560×
                levels.insert(c, l);
1658
            } else {
16592560×
                stack.push((c, true));
16603400×
                for d in deps {
16613400×
                    if !levels.contains_key(d) {
1662419×
                        stack.push((*d, false));
16632981×
                    }
1664
                }
1665
            }
1666
        }
16672166×
        levels[h]
1668404688×
    }
1669
1670
    /// Changes that no other change depends on directly, sorted.
1671397×
    pub fn heads(&self) -> Vec<ChangeHash> {
1672397×
        let depended: HashSet<&ChangeHash> =
16733709×
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
1674397×
        let mut heads: Vec<ChangeHash> = self
1675397×
            .changes
1676397×
            .keys()
16773709×
            .filter(|h| !depended.contains(h))
1678397×
            .copied()
1679397×
            .collect();
1680397×
        heads.sort();
1681397×
        heads
1682397×
    }
1683
1684
    /// Maximal elements among `hashes` (those not in the closure of another),
1685
    /// sorted. One walk down from all of them at once: whatever the walk
1686
    /// reaches is below some other element. Linear in the changes reached,
1687
    /// where comparing every pair's closures was quadratic in the number
1688
    /// of heads, which a bookmark of independent changes has many of.
16898836×
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
16908836×
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
16918836×
        let mut below: HashSet<ChangeHash> = HashSet::new();
16928836×
        let mut stack: Vec<ChangeHash> = set
16938836×
            .iter()
169416097×
            .filter_map(|h| self.changes.get(h))
169513641×
            .flat_map(|c| c.deps.iter().copied())
16968836×
            .collect();
169721995×
        while let Some(d) = stack.pop() {
169813159×
            if below.insert(d) {
16996411×
                if let Some(c) = self.changes.get(&d) {
17006411×
                    stack.extend(c.deps.iter().copied());
17016411×
                }
17026748×
            }
1703
        }
170416097×
        set.into_iter().filter(|h| !below.contains(h)).collect()
17058836×
    }
1706
17070×
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
17080×
        self.graph(node)
17090×
            .map(|g| g.materialize(self))
17100×
            .unwrap_or_default()
17110×
    }
1712
1713
    /// Live lines of a text node in materialized order.
171420×
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
171520×
        let Some(g) = self.graph(node) else {
17162×
            return vec![];
1717
        };
171818×
        let m = g.materialize(self);
171918×
        m.live_atoms()
172018×
            .into_iter()
172144×
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
172218×
            .collect()
172320×
    }
1724
1725
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
1726842×
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
1727842×
        let mut live: Vec<ObjectRef> = self
1728842×
            .live_replaces(node)
1729842×
            .into_iter()
1730842×
            .map(|(_, n)| n)
1731842×
            .collect();
1732842×
        live.sort();
1733842×
        live.dedup();
1734842×
        live
1735842×
    }
1736
1737
    /// The replace records whose blob is live, with the change that set it
1738
    /// (spec §9.3). A record's blob is superseded by a later replacement of
1739
    /// that blob: one whose change depends on the record's change, as every
1740
    /// replacement depends on the change that made its old blob current
1741
    /// (§8.1). Two replacements that do not know each other both stay live
1742
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
1743
    /// A replacement without that dependency, from before the rule, is read
1744
    /// as before: it supersedes every record that did not come after it.
1745881×
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
1746881×
        let Some(rs) = self.replaces.get(node) else {
17470×
            return vec![];
1748
        };
1749881×
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
175011×
            rs.iter()
175121×
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && self.closure(s).contains(q))
175211×
        };
1753881×
        rs.iter()
17541020×
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
17551020×
            .filter(|(c, n)| {
17561308×
                !rs.iter().any(|(s, o, _)| {
17571308×
                    s != c
1758357×
                        && *o == Some(*n)
1759126×
                        && (self.closure(s).contains(c)
176011×
                            || (!knows_its_old(s, n) && !self.closure(c).contains(s)))
17611308×
                })
17621020×
            })
1763881×
            .collect()
1764881×
    }
1765
1766
    /// Short label for conflict markers: `changeid-prefix "message"`.
17671155×
    pub fn label(&self, h: &ChangeHash) -> String {
17681155×
        match self.changes.get(h) {
17691155×
            Some(c) => format!(
1770
                "{} \"{}\"",
17711155×
                c.change_id.short(8),
17721155×
                c.message.lines().next().unwrap_or("")
1773
            ),
17740×
            None => format!("#{}", h.short(12)),
1775
        }
17761155×
    }
1777
1778
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1779
    /// are not part of any conflict region in order, every live atom that is
1780
    /// part of a region, and every change that contributed to a region.
1781
    /// The changes that introduced the live blobs of an opaque node, for a
1782
    /// replace conflict (spec §9.3).
17832×
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
17842×
        let mut out: Vec<ChangeHash> = Vec::new();
17856×
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
17866×
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
17874×
                out.push(*h);
17884×
            }
1789
        }
17902×
        out.sort();
17912×
        out
17922×
    }
1793
179427×
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
179527×
        let mut out = ConflictRegions::default();
179627×
        let Some(g) = self.graph(node) else {
17970×
            return out;
1798
        };
179927×
        let m = g.materialize(self);
180027×
        let mut contributors = BTreeSet::new();
180163×
        for seg in &m.segments {
180263×
            match seg {
180336×
                crate::graph::Segment::Lines(atoms) => {
180436×
                    for a in atoms {
180536×
                        out.plain
180636×
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
180736×
                    }
1808
                }
180927×
                crate::graph::Segment::Conflict(sides) => {
181054×
                    for side in sides {
181156×
                        for a in side {
181256×
                            out.region_atoms.push(*a);
181356×
                            contributors.insert(a.0);
181456×
                        }
1815
                    }
1816
                }
18170×
                crate::graph::Segment::Zombie { deleted, inserted } => {
18180×
                    for a in deleted {
18190×
                        contributors.insert(a.0);
18200×
                        contributors.extend(g.deleters(a).copied());
18210×
                    }
18220×
                    for a in inserted {
18230×
                        out.region_atoms.push(*a);
18240×
                        contributors.insert(a.0);
18250×
                    }
1826
                }
1827
            }
1828
        }
182927×
        out.contributors = contributors.into_iter().collect();
183027×
        out
183127×
    }
1832
183324435×
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
183424435×
        let Some(g) = self.graph(node) else {
1835450×
            return (Vec::new(), Materialized::default());
1836
        };
183723985×
        let m = g.materialize(self);
183823985×
        let bytes = g.render(&m, &|h| self.label(h));
183923985×
        (bytes, m)
184024435×
    }
1841
1842
    /// Every file rendered, in parallel: files are independent, and
1843
    /// rendering them is most of a snapshot's cost in a large tree.
18442254×
    pub fn materialize(&self) -> Snapshot {
1845
        use rayon::prelude::*;
18462254×
        self.require_full("materializing a state");
18472254×
        let tree = self.tree.view();
18482254×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
18492254×
        let rendered: Vec<(String, FileState)> = entries
18502254×
            .par_iter()
185116652×
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
18522254×
            .collect();
18532254×
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
18542254×
        Snapshot {
18552254×
            tree,
18562254×
            files,
18572254×
            unrendered: BTreeSet::new(),
18582254×
        }
18592254×
    }
1860
1861
    /// Like [`State::materialize`], leaving the text files of nodes in
1862
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
1863
    /// file's graph must be loaded. For a caller that already knows those
1864
    /// files are unchanged and not conflicted.
186518×
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
186618×
        self.materialize_leaving(|_, e| skip.contains(&e.node))
186718×
    }
1868
1869
    /// As [`State::materialize_except`], rendering only the text files at
1870
    /// `render` (a few, where the caller knows the rest unchanged).
1871806×
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
18727810×
        self.materialize_leaving(|p, _| !render.contains(p))
1873806×
    }
1874
1875
    /// As [`State::materialize_except`], rendering only the text files of
1876
    /// the nodes in `render` (a change's edited files), without a set of
1877
    /// every other file to leave out.
1878246×
    pub fn materialize_nodes(&self, render: &HashSet<NodeId>) -> Snapshot {
1879678×
        self.materialize_leaving(|_, e| !render.contains(&e.node))
1880246×
    }
1881
18821070×
    fn materialize_leaving(
18831070×
        &self,
18841070×
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
18851070×
    ) -> Snapshot {
1886
        use rayon::prelude::*;
18871070×
        let tree = self.tree.view();
18881070×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
18891070×
        let rendered: Vec<(String, FileState, bool)> = entries
18901070×
            .par_iter()
18918873×
            .map(|(path, e)| {
18928873×
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
18934641×
                    let f = FileState {
18944641×
                        node: e.node,
18954641×
                        kind: e.kind,
18964641×
                        mode: e.mode,
18974641×
                        content: FileContent::Text {
18984641×
                            bytes: Vec::new(),
18994641×
                            materialized: Materialized::default(),
19004641×
                        },
19014641×
                    };
19024641×
                    (path.to_string(), f, true)
1903
                } else {
19044232×
                    (path.to_string(), self.file_state(e), false)
1905
                }
19068873×
            })
19071070×
            .collect();
1908
        // In the view's path order, so the maps are built without searching.
19091070×
        let unrendered: BTreeSet<String> = rendered
19101070×
            .iter()
19111070×
            .filter(|(_, _, skipped)| *skipped)
19124641×
            .map(|(p, _, _)| p.clone())
19131070×
            .collect();
19141070×
        let files: BTreeMap<String, FileState> =
19158873×
            rendered.into_iter().map(|(p, f, _)| (p, f)).collect();
19161070×
        Snapshot {
19171070×
            tree,
19181070×
            files,
19191070×
            unrendered,
19201070×
        }
19211070×
    }
1922
1923
    /// A snapshot of only `paths` (those `view` has), `view` being this
1924
    /// state's tree view: for a caller that works from what changed. The
1925
    /// graphs of those text files must be loaded.
192665×
    pub fn materialize_paths<'p>(
192765×
        &self,
192865×
        view: crate::tree::TreeView,
192965×
        paths: impl IntoIterator<Item = &'p str>,
193065×
    ) -> Snapshot {
193165×
        let files = paths
193265×
            .into_iter()
193397×
            .filter_map(|p| Some((p.to_string(), self.file_state(view.entries.get(p)?))))
193465×
            .collect();
193565×
        Snapshot {
193665×
            tree: view,
193765×
            files,
193865×
            unrendered: BTreeSet::new(),
193965×
        }
194065×
    }
1941
1942
    /// The state of one tree entry: a directory, an opaque file's live
1943
    /// blobs, or a text file rendered from its graph (which must be built).
19440×
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
19450×
        self.file_state(e)
19460×
    }
1947
194820961×
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
1949
        {
195020961×
            let content = match e.kind {
19511497×
                NodeKind::Dir => FileContent::Dir,
1952100×
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
1953100×
                    blobs: self.live_blobs(&e.node),
1954100×
                },
1955541×
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
1956541×
                    blobs: self.live_blobs(&e.node),
1957541×
                },
1958
                NodeKind::File => {
195918823×
                    let (bytes, materialized) = self.render_file(&e.node);
196018823×
                    FileContent::Text {
196118823×
                        bytes,
196218823×
                        materialized,
196318823×
                    }
1964
                }
1965
            };
196620961×
            FileState {
196720961×
                node: e.node,
196820961×
                kind: e.kind,
196920961×
                mode: e.mode,
197020961×
                content,
197120961×
            }
1972
        }
197320961×
    }
1974
}
1975
1976
impl DepOracle for State {
1977
    /// Whether `a` depends on `b`, by a walk down from `a` that stops at
1978
    /// changes no higher than `b`: they cannot have `b` below them. Nothing
1979
    /// of the walk is kept, so asking about many pairs costs no more memory
1980
    /// than one walk (#25); a closure already memoised answers at once.
198168109×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
198268109×
        if a == b {
1983800×
            return true;
198467309×
        }
198567309×
        if let Some(c) = self.closure.lock().unwrap().sets.get(a) {
19860×
            return c.contains(b);
198767309×
        }
198867309×
        if !self.changes.contains_key(b) {
1989800×
            return false;
199066509×
        }
199166509×
        let lb = self.level(b);
199266509×
        if self.level(a) <= lb {
199336519×
            return false;
199429990×
        }
199529990×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
199629990×
        let mut stack: Vec<ChangeHash> = self
199729990×
            .changes
199829990×
            .get(a)
199929990×
            .map(|m| m.deps.clone())
200029990×
            .unwrap_or_default();
2001360766×
        while let Some(c) = stack.pop() {
2002341307×
            if c == *b {
200310531×
                return true;
2004330776×
            }
2005330776×
            if !seen.insert(c) || self.level(&c) <= lb {
2006223022×
                continue;
2007107754×
            }
2008107754×
            if let Some(m) = self.changes.get(&c) {
2009107754×
                stack.extend(m.deps.iter().copied());
2010107754×
            }
2011
        }
201219459×
        false
201368109×
    }
2014
}
2015
2016
#[cfg(test)]
2017
mod tests {
2018
    use super::*;
2019
    use crate::ids::ChangeId;
2020
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
2021
20222023×
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
20232023×
        let mut c = Change {
20242023×
            version: crate::objects::CHANGE_VERSION,
20252023×
            change_id: ChangeId::random(),
20262023×
            deps,
20272023×
            author: ObjectRef::ZERO,
20282023×
            hlc: Hlc {
20292023×
                wall_ms: 1,
20302023×
                logical: 0,
20312023×
            },
20322023×
            message: "m".into(),
20332023×
            tree_ops,
20342023×
            edits,
20352023×
            kind: ChangeKind::Normal,
20362023×
        };
20372023×
        c.normalize();
20382023×
        c
20392023×
    }
2040
2041
    #[test]
20421×
    fn build_edit_and_materialize() {
20431×
        let mut st = State::new();
20441×
        let f = NodeId::random();
20451×
        let c1 = change(
20461×
            vec![],
20471×
            vec![TreeOp::AddNode {
20481×
                node: f,
20491×
                kind: NodeKind::File,
20501×
                mode: Mode::TEXT,
20511×
                parent: NodeId::ROOT,
20521×
                name: "a.txt".into(),
20531×
            }],
20541×
            vec![Edit::Insert {
20551×
                node: f,
20561×
                after: AtomRef::Start,
20571×
                before: AtomRef::End,
20581×
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
20591×
            }],
2060
        );
20611×
        let h1 = st.add(c1).unwrap();
2062
        // Depends on h1: append a line and delete "one".
20631×
        let c2 = change(
20641×
            vec![h1],
20651×
            vec![],
20661×
            vec![
20671×
                Edit::Delete {
20681×
                    node: f,
20691×
                    atoms: vec![AtomRange {
20701×
                        change: h1,
20711×
                        from: 0,
20721×
                        to: 1,
20731×
                    }],
20741×
                },
20751×
                Edit::Insert {
20761×
                    node: f,
20771×
                    after: AtomRef::Atom {
20781×
                        change: h1,
20791×
                        index: 1,
20801×
                    },
20811×
                    before: AtomRef::End,
20821×
                    lines: vec![b"three\n".to_vec()].into(),
20831×
                },
2084
            ],
2085
        );
20861×
        let h2 = st.add(c2).unwrap();
20871×
        assert_eq!(st.heads(), vec![h2]);
20881×
        assert!(st.depends_on(&h2, &h1));
20891×
        assert!(!st.depends_on(&h1, &h2));
20901×
        let snap = st.materialize();
20911×
        assert!(!snap.is_conflicted());
20921×
        let a = &snap.files["a.txt"];
20931×
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
20941×
        assert_eq!(st.live_lines(&f).len(), 2);
20951×
    }
2096
2097
    #[test]
20981×
    fn missing_dependency_is_rejected() {
20991×
        let mut st = State::new();
21001×
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
21011×
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
21021×
    }
2103
2104
    #[test]
21051×
    fn self_references_and_multi_insert_indexing() {
21061×
        let mut st = State::new();
21071×
        let f = NodeId::random();
21081×
        let me = OpRef {
21091×
            change: ObjectRef::ZERO,
21101×
            index: 0,
21111×
        };
21121×
        let c1 = change(
21131×
            vec![],
21141×
            vec![
21151×
                TreeOp::AddNode {
21161×
                    node: f,
21171×
                    kind: NodeKind::File,
21181×
                    mode: Mode::TEXT,
21191×
                    parent: NodeId::ROOT,
21201×
                    name: "x".into(),
21211×
                },
21221×
                TreeOp::SetMode {
21231×
                    node: f,
21241×
                    old: me,
21251×
                    mode: Mode {
21261×
                        exec: true,
21271×
                        opaque: false,
21281×
                    },
21291×
                },
2130
            ],
21311×
            vec![
21321×
                Edit::Insert {
21331×
                    node: f,
21341×
                    after: AtomRef::Start,
21351×
                    before: AtomRef::End,
21361×
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
21371×
                },
2138
                // Insert between the two lines just inserted, using self references.
21391×
                Edit::Insert {
21401×
                    node: f,
21411×
                    after: AtomRef::Atom {
21421×
                        change: ObjectRef::ZERO,
21431×
                        index: 0,
21441×
                    },
21451×
                    before: AtomRef::Atom {
21461×
                        change: ObjectRef::ZERO,
21471×
                        index: 1,
21481×
                    },
21491×
                    lines: vec![b"b\n".to_vec()].into(),
21501×
                },
2151
            ],
2152
        );
21531×
        st.add(c1).unwrap();
21541×
        let snap = st.materialize();
21551×
        let x = &snap.files["x"];
21561×
        assert_eq!(
2157
            x.mode,
2158
            Mode {
2159
                exec: true,
2160
                opaque: false
2161
            }
2162
        );
21631×
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
21641×
    }
2165
2166
    #[test]
21671×
    fn opaque_replace_and_conflict() {
21681×
        let mut st = State::new();
21691×
        let f = NodeId::random();
21701×
        let b1 = ObjectRef([1; 32]);
21711×
        let b2 = ObjectRef([2; 32]);
21721×
        let b3 = ObjectRef([3; 32]);
21731×
        let h1 = st
21741×
            .add(change(
21751×
                vec![],
21761×
                vec![TreeOp::AddNode {
21771×
                    node: f,
21781×
                    kind: NodeKind::File,
21791×
                    mode: Mode::OPAQUE,
21801×
                    parent: NodeId::ROOT,
21811×
                    name: "img".into(),
21821×
                }],
21831×
                vec![Edit::Replace {
21841×
                    node: f,
21851×
                    old: None,
21861×
                    new: Some(b1),
21871×
                }],
2188
            ))
21891×
            .unwrap();
21901×
        assert_eq!(st.live_blobs(&f), vec![b1]);
21911×
        st.add(change(
21921×
            vec![h1],
21931×
            vec![],
21941×
            vec![Edit::Replace {
21951×
                node: f,
21961×
                old: Some(b1),
21971×
                new: Some(b2),
21981×
            }],
2199
        ))
22001×
        .unwrap();
22011×
        st.add(change(
22021×
            vec![h1],
22031×
            vec![],
22041×
            vec![Edit::Replace {
22051×
                node: f,
22061×
                old: Some(b1),
22071×
                new: Some(b3),
22081×
            }],
2209
        ))
22101×
        .unwrap();
22111×
        let snap = st.materialize();
22121×
        assert!(snap.is_conflicted());
22131×
        assert!(
22141×
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2215
        );
22161×
    }
2217
2218
    #[test]
22191×
    fn checkpoint_payload_round_trip_and_replay() {
22201×
        let mut st = State::new();
22211×
        let f = NodeId::random();
22221×
        let h1 = st
22231×
            .add(change(
22241×
                vec![],
22251×
                vec![TreeOp::AddNode {
22261×
                    node: f,
22271×
                    kind: NodeKind::File,
22281×
                    mode: Mode::TEXT,
22291×
                    parent: NodeId::ROOT,
22301×
                    name: "a".into(),
22311×
                }],
22321×
                vec![Edit::Insert {
22331×
                    node: f,
22341×
                    after: AtomRef::Start,
22351×
                    before: AtomRef::End,
22361×
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
22371×
                }],
2238
            ))
22391×
            .unwrap();
22401×
        let h2 = st
22411×
            .add(change(
22421×
                vec![h1],
22431×
                vec![],
22441×
                vec![Edit::Delete {
22451×
                    node: f,
22461×
                    atoms: vec![AtomRange {
22471×
                        change: h1,
22481×
                        from: 0,
22491×
                        to: 1,
22501×
                    }],
22511×
                }],
2252
            ))
22531×
            .unwrap();
22541×
        let payload = st.checkpoint_payload();
22551×
        let back = State::from_checkpoint_payload(&payload).unwrap();
22561×
        assert_eq!(back.len(), 2);
22571×
        assert_eq!(back.heads(), vec![h2]);
22581×
        assert_eq!(back.get(&h1).unwrap().message, "m");
22591×
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2260
        // Replaying a further change onto the restored state equals a full build.
22611×
        let c3 = change(
22621×
            vec![h2],
22631×
            vec![],
22641×
            vec![Edit::Insert {
22651×
                node: f,
22661×
                after: AtomRef::Atom {
22671×
                    change: h1,
22681×
                    index: 1,
22691×
                },
22701×
                before: AtomRef::End,
22711×
                lines: vec![b"3\n".to_vec()].into(),
22721×
            }],
2273
        );
22741×
        let mut full = st.clone();
22751×
        full.add(c3.clone()).unwrap();
22761×
        let mut restored = back;
22771×
        restored.add(c3).unwrap();
22781×
        let (a, b) = (full.materialize(), restored.materialize());
22791×
        assert_eq!(
22801×
            a.files.keys().collect::<Vec<_>>(),
22811×
            b.files.keys().collect::<Vec<_>>()
2282
        );
22831×
        assert_eq!(a.files["a"].content, b.files["a"].content);
22841×
        assert!(
22851×
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2286
        );
22871×
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
22881×
    }
2289
2290
    /// History-only states (O10f): the same state as a full load once its
2291
    /// graphs are built, by replay and from a version 2 checkpoint with
2292
    /// later changes; unloaded graphs are never read as empty.
2293
    #[test]
22941×
    fn graph_keys_change_exactly_when_a_graph_does() {
22951×
        let (f, g) = (NodeId::random(), NodeId::random());
22961×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
22972×
            node,
22982×
            kind: NodeKind::File,
2299
            mode: Mode::TEXT,
2300
            parent: NodeId::ROOT,
23012×
            name: name.into(),
23022×
        };
23031×
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
23044×
            node,
23054×
            after: AtomRef::Start,
23064×
            before: AtomRef::End,
23074×
            lines: vec![line.to_vec()].into(),
23084×
        };
23091×
        let c1 = change(
23101×
            vec![],
23111×
            vec![add(f, "f"), add(g, "g")],
23121×
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2313
        );
23141×
        let h1 = c1.hash();
23151×
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
23161×
        let h2 = c2.hash();
23171×
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
23186×
        let load = |cs: &[&Change]| {
23196×
            let mut st = State::new_history_only();
232010×
            for c in cs {
232110×
                st.add((*c).clone()).unwrap();
232210×
            }
23236×
            st
23246×
        };
23251×
        let s1 = load(&[&c1]);
23261×
        let s2 = load(&[&c1, &c2]);
23271×
        let s3 = load(&[&c1, &c2, &c3]);
232818×
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
23291×
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
23301×
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
23311×
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
23321×
        assert_ne!(key(&s2, &f), key(&s3, &f));
23331×
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
23341×
        let mut built = load(&[&c1]);
23351×
        built
23361×
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
23371×
            .unwrap();
23381×
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
23391×
        let mut full = State::new();
23401×
        full.add(c1.clone()).unwrap();
23411×
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2342
2343
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2344
        // or inline values: stable across loads, changed by later edits.
23451×
        let graphs = full.checkpoint_file_graphs();
23461×
        let index = full.checkpoint_index(&graphs, |enc| {
23470×
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
23480×
        });
23498×
        let cp = |extra: &[&Change]| {
23508×
            let mut st = State::from_checkpoint_history(&index).unwrap();
23518×
            for c in extra {
23525×
                st.add((*c).clone()).unwrap();
23535×
            }
23548×
            st
23558×
        };
23561×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
23571×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
23581×
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
23591×
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2360
2361
        // Partial rendering: skipped files are listed and empty, the others
2362
        // render as in a full state.
23631×
        let mut part = load(&[&c1, &c2]);
23641×
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
23651×
            .unwrap();
23661×
        let snap = part.materialize_except(&[f].into_iter().collect());
23671×
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
23681×
        let mut whole = State::new();
23691×
        whole.add(c1.clone()).unwrap();
23701×
        whole.add(c2.clone()).unwrap();
23711×
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
23721×
        assert!(
23731×
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2374
        );
23751×
    }
2376
2377
    #[test]
23781×
    fn history_only_states_build_the_same_graphs_on_demand() {
23791×
        let small = NodeId::random();
23801×
        let big = NodeId::random();
23811×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
23822×
            node,
23832×
            kind: NodeKind::File,
2384
            mode: Mode::TEXT,
2385
            parent: NodeId::ROOT,
23862×
            name: name.into(),
23872×
        };
23881×
        let lines: crate::lines::Lines = (0..300)
2389300×
            .map(|i| format!("line {i}\n").into_bytes())
23901×
            .collect();
23911×
        let c1 = change(
23921×
            vec![],
23931×
            vec![add(small, "small"), add(big, "big")],
23941×
            vec![
23951×
                Edit::Insert {
23961×
                    node: small,
23971×
                    after: AtomRef::Start,
23981×
                    before: AtomRef::End,
23991×
                    lines: vec![b"x\n".to_vec()].into(),
24001×
                },
24011×
                Edit::Insert {
24021×
                    node: big,
24031×
                    after: AtomRef::Start,
24041×
                    before: AtomRef::End,
24051×
                    lines,
24061×
                },
2407
            ],
2408
        );
24091×
        let h1 = c1.hash();
24101×
        let c2 = change(
24111×
            vec![h1],
24121×
            vec![],
24131×
            vec![
24141×
                Edit::Delete {
24151×
                    node: big,
24161×
                    atoms: vec![AtomRange {
24171×
                        change: h1,
24181×
                        from: 2,
24191×
                        to: 9,
24201×
                    }],
24211×
                },
24221×
                Edit::Insert {
24231×
                    node: big,
24241×
                    after: AtomRef::Atom {
24251×
                        change: h1,
24261×
                        index: 20,
24271×
                    },
24281×
                    before: AtomRef::Atom {
24291×
                        change: h1,
24301×
                        index: 21,
24311×
                    },
24321×
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
24331×
                },
24341×
                Edit::Insert {
24351×
                    node: small,
24361×
                    after: AtomRef::Atom {
24371×
                        change: h1,
24381×
                        index: 0,
24391×
                    },
24401×
                    before: AtomRef::End,
24411×
                    lines: vec![b"y\n".to_vec()].into(),
24421×
                },
2443
            ],
2444
        );
24451×
        let h2 = c2.hash();
24461×
        let c3 = change(
24471×
            vec![h2],
24481×
            vec![],
24491×
            vec![Edit::Delete {
24501×
                node: small,
24511×
                atoms: vec![AtomRange {
24521×
                    change: h1,
24531×
                    from: 0,
24541×
                    to: 1,
24551×
                }],
24561×
            }],
2457
        );
2458
24591×
        let mut full = State::new();
24603×
        for c in [&c1, &c2, &c3] {
24613×
            full.add(c.clone()).unwrap();
24623×
        }
2463
        // By replay: nothing built until asked, then exactly the full graphs.
24641×
        let mut hist = State::new_history_only();
24653×
        for c in [&c1, &c2, &c3] {
24663×
            hist.add(c.clone()).unwrap();
24673×
        }
24681×
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
24691×
        assert_eq!(hist.len(), 3);
24701×
        hist.load_graphs(
24711×
            &[big],
24720×
            |_| unreachable!("no checkpoint"),
24730×
            |_| unreachable!(),
2474
        )
24751×
        .unwrap();
24761×
        assert_eq!(
24771×
            hist.render_file(&big).0,
24781×
            full.render_file(&big).0,
2479
            "one file on its own"
2480
        );
24811×
        assert!(!hist.is_full());
24821×
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
24831×
            .unwrap();
24841×
        assert!(hist.is_full());
24851×
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2486
2487
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
24881×
        let mut base = State::new();
24891×
        base.add(c1.clone()).unwrap();
24901×
        base.add(c2.clone()).unwrap();
24911×
        let graphs = base.checkpoint_file_graphs();
24921×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
24931×
        let index = base.checkpoint_index(&graphs, |enc| {
24941×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
24951×
            blobs.insert(r, enc.to_vec());
24961×
            r
24971×
        });
24981×
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
24991×
        from_cp.add(c3.clone()).unwrap();
25001×
        assert!(!from_cp.is_full());
25011×
        let mut fetched = 0;
25021×
        from_cp
25031×
            .load_graphs(
25041×
                &[small, big],
25051×
                |refs| {
25061×
                    fetched += refs.len();
25071×
                    refs.iter()
25081×
                        .map(|r| {
25091×
                            blobs
25101×
                                .get(r)
25111×
                                .cloned()
25121×
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
25131×
                        })
25141×
                        .collect()
25151×
                },
25160×
                |_| unreachable!(),
2517
            )
25181×
            .unwrap();
25191×
        assert_eq!(
2520
            fetched, 1,
2521
            "the large graph's blob, in one batch; the small one was inline"
2522
        );
25231×
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
25241×
    }
2525
2526
    #[test]
2527
    #[should_panic(expected = "was not loaded")]
25281×
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
25291×
        let f = NodeId::random();
25301×
        let mut st = State::new_history_only();
25311×
        st.add(change(
25321×
            vec![],
25331×
            vec![TreeOp::AddNode {
25341×
                node: f,
25351×
                kind: NodeKind::File,
25361×
                mode: Mode::TEXT,
25371×
                parent: NodeId::ROOT,
25381×
                name: "a".into(),
25391×
            }],
25401×
            vec![Edit::Insert {
25411×
                node: f,
25421×
                after: AtomRef::Start,
25431×
                before: AtomRef::End,
25441×
                lines: vec![b"a\n".to_vec()].into(),
25451×
            }],
2546
        ))
25471×
        .unwrap();
25481×
        st.render_file(&f);
25491×
    }
2550
2551
    #[test]
2552
    #[should_panic(expected = "needs every file graph")]
25531×
    fn materializing_a_history_only_state_is_refused() {
25541×
        let f = NodeId::random();
25551×
        let mut st = State::new_history_only();
25561×
        st.add(change(
25571×
            vec![],
25581×
            vec![TreeOp::AddNode {
25591×
                node: f,
25601×
                kind: NodeKind::File,
25611×
                mode: Mode::TEXT,
25621×
                parent: NodeId::ROOT,
25631×
                name: "a".into(),
25641×
            }],
25651×
            vec![Edit::Insert {
25661×
                node: f,
25671×
                after: AtomRef::Start,
25681×
                before: AtomRef::End,
25691×
                lines: vec![b"a\n".to_vec()].into(),
25701×
            }],
2571
        ))
25721×
        .unwrap();
25731×
        st.materialize();
25741×
    }
2575
2576
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
2577
    /// blob; the state read back is the same as from version 1.
2578
    #[test]
25791×
    fn checkpoint_index_round_trip_matches_version_1() {
25801×
        let mut st = State::new();
25811×
        let small = NodeId::random();
25821×
        let big = NodeId::random();
25831×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
25842×
            node,
25852×
            kind: NodeKind::File,
2586
            mode: Mode::TEXT,
2587
            parent: NodeId::ROOT,
25882×
            name: name.into(),
25892×
        };
25901×
        let big_lines: crate::lines::Lines = (0..400)
2591400×
            .map(|i| format!("line {i} of a long file\n").into_bytes())
25921×
            .collect();
25931×
        let h1 = st
25941×
            .add(change(
25951×
                vec![],
25961×
                vec![add(small, "small"), add(big, "big")],
25971×
                vec![
25981×
                    Edit::Insert {
25991×
                        node: small,
26001×
                        after: AtomRef::Start,
26011×
                        before: AtomRef::End,
26021×
                        lines: vec![b"x\n".to_vec()].into(),
26031×
                    },
26041×
                    Edit::Insert {
26051×
                        node: big,
26061×
                        after: AtomRef::Start,
26071×
                        before: AtomRef::End,
26081×
                        lines: big_lines,
26091×
                    },
2610
                ],
2611
            ))
26121×
            .unwrap();
26131×
        st.add(change(
26141×
            vec![h1],
26151×
            vec![],
26161×
            vec![Edit::Delete {
26171×
                node: big,
26181×
                atoms: vec![AtomRange {
26191×
                    change: h1,
26201×
                    from: 3,
26211×
                    to: 7,
26221×
                }],
26231×
            }],
2624
        ))
26251×
        .unwrap();
2626
26271×
        let graphs = st.checkpoint_file_graphs();
26281×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
26291×
        let index = st.checkpoint_index(&graphs, |enc| {
26301×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
26311×
            blobs.insert(r, enc.to_vec());
26321×
            r
26331×
        });
26341×
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
26351×
        assert_eq!(
26361×
            State::checkpoint_graph_refs(&index).unwrap(),
26371×
            blobs.keys().copied().collect::<Vec<_>>()
2638
        );
26391×
        assert!(
26401×
            State::checkpoint_graph_refs(&st.checkpoint_payload())
26411×
                .unwrap()
26421×
                .is_empty(),
2643
            "version 1 names none"
2644
        );
26451×
        assert!(index.len() < st.checkpoint_payload().len());
2646
26471×
        let back = State::from_checkpoint(&index, |refs| {
26481×
            refs.iter()
26491×
                .map(|r| {
26501×
                    blobs
26511×
                        .get(r)
26521×
                        .cloned()
26531×
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
26541×
                })
26551×
                .collect()
26561×
        })
26571×
        .unwrap();
26581×
        assert_eq!(
26591×
            back.checkpoint_payload(),
26601×
            st.checkpoint_payload(),
2661
            "the same state as version 1"
2662
        );
26631×
        assert_eq!(
26641×
            back.materialize().files["big"].content,
26651×
            st.materialize().files["big"].content
2666
        );
2667
        // Deterministic: the same state gives the same index.
26681×
        assert_eq!(
26691×
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
26701×
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
26711×
            }),
2672
            index
2673
        );
2674
        // A missing graph blob is an error, not an empty file.
26751×
        assert!(
26761×
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
2677
        );
26781×
        assert!(
26791×
            State::from_checkpoint_payload(&index).is_err(),
2680
            "version 2 needs its blobs"
2681
        );
2682
        // Version 1 payloads still read, and unknown versions do not.
26831×
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
26841×
        let mut v3 = cbor::decode(&index).unwrap();
26851×
        if let Value::Map(m) = &mut v3 {
26861×
            m.insert(0, Value::Uint(3));
26871×
        }
26881×
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
26891×
    }
2690
2691
    #[test]
26921×
    fn maximal_elements() {
26931×
        let mut st = State::new();
26941×
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
26951×
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
26961×
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
26971×
        let mut m = st.maximal(&[h1, h2, h3]);
26981×
        m.sort();
26991×
        let mut want = vec![h2, h3];
27001×
        want.sort();
27011×
        assert_eq!(m, want);
27021×
        assert_eq!(st.heads(), want);
27031×
    }
2704
2705
    /// The bounded walk of `depends_on` agrees with the closure on random
2706
    /// graphs, and the memo stays within its bound.
2707
    #[test]
27081×
    fn depends_on_matches_the_closure() {
2709
        use rand::{Rng, SeedableRng};
27101×
        let mut rng = rand::rngs::StdRng::seed_from_u64(11);
27111×
        for _ in 0..10 {
271210×
            let mut st = State::new();
271310×
            let mut all: Vec<ChangeHash> = Vec::new();
271410×
            for _ in 0..80 {
2715800×
                let deps: Vec<ChangeHash> =
271631600×
                    all.iter().copied().filter(|_| rng.gen_bool(0.06)).collect();
2717800×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2718
            }
271910×
            let unknown = ObjectRef([0xee; 32]);
2720800×
            for a in &all {
2721800×
                let want = st.closure(a).clone();
2722800×
                st.closure.lock().unwrap().sets.clear();
2723800×
                st.closure.lock().unwrap().held = 0;
272464800×
                for b in all.iter().chain([&unknown]) {
272564800×
                    assert_eq!(
272664800×
                        st.depends_on(a, b),
272764800×
                        a == b || want.contains(b),
2728
                        "{a:?} on {b:?}"
2729
                    );
2730
                }
2731
            }
273210×
            assert!(st.closure.lock().unwrap().held <= CLOSURE_MEMO_HASHES);
2733
        }
27341×
    }
2735
2736
    /// The one-walk `maximal` agrees with the definition (not in the
2737
    /// closure of another element) on random graphs, with repeated and
2738
    /// unknown hashes among the input.
2739
    #[test]
27401×
    fn maximal_matches_its_definition() {
2741
        use rand::{Rng, SeedableRng};
27421×
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
27431×
        for _ in 0..20 {
274420×
            let mut st = State::new();
274520×
            let mut all: Vec<ChangeHash> = Vec::new();
274620×
            for _ in 0..60 {
27471200×
                let deps: Vec<ChangeHash> =
274835400×
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
27491200×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2750
            }
275120×
            let mut pick: Vec<ChangeHash> =
27521200×
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
275320×
            pick.extend(pick.clone().into_iter().take(3));
275420×
            pick.push(ObjectRef([0xee; 32]));
275520×
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
275620×
            let want: Vec<ChangeHash> = set
275720×
                .iter()
27588641×
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
275920×
                .copied()
276020×
                .collect();
276120×
            assert_eq!(st.maximal(&pick), want);
276220×
            assert_eq!(st.maximal(&all), st.heads());
2763
        }
27641×
    }
2765
}