OXYGENHUB

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

1965 of 2121 lines run, 414 of 591 functions · run #253 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`]).
451423×
    pub(crate) fn write_flat(&self, w: &mut crate::flat::Writer) {
461423×
        w.fixed(&self.change_id.0);
471423×
        w.count(self.deps.len());
481423×
        for d in &self.deps {
491081×
            w.object(d);
501081×
        }
511423×
        w.object(&self.author);
521423×
        w.u64(self.hlc.wall_ms);
531423×
        w.u32(self.hlc.logical);
541423×
        w.bytes(self.message.as_bytes());
551423×
        w.u8(self.kind.tag() as u8);
561423×
    }
57
581627×
    pub(crate) fn read_flat(r: &mut crate::flat::Reader) -> Result<ChangeMeta, ObjectError> {
591627×
        let change_id = crate::ids::ChangeId(r.fixed::<16>()?);
601627×
        let mut deps = Vec::new();
611627×
        for _ in 0..r.count()? {
62830×
            deps.push(r.object()?);
63
        }
64
        Ok(ChangeMeta {
651627×
            change_id,
661627×
            deps,
671627×
            author: r.object()?,
68
            hlc: Hlc {
691627×
                wall_ms: r.u64()?,
701627×
                logical: r.u32()?,
71
            },
721627×
            message: r.text()?,
731627×
            kind: ChangeKind::from_tag(r.u8()? as u64)?,
74
        })
751627×
    }
76
7714324×
    pub fn of(c: &Change) -> ChangeMeta {
7814324×
        ChangeMeta {
7914324×
            change_id: c.change_id,
8014324×
            deps: c.deps.clone(),
8114324×
            author: c.author,
8214324×
            hlc: c.hlc,
8314324×
            message: c.message.clone(),
8414324×
            kind: c.kind,
8514324×
        }
8614324×
    }
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<[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 {
156140×
    fn from_body(body: DeferredBody) -> Deferred {
157140×
        Deferred {
158140×
            body: std::sync::OnceLock::from(body),
159140×
            ..Deferred::default()
160140×
        }
161140×
    }
162
163100227×
    fn body(&self) -> &DeferredBody {
164100227×
        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"),
16931326×
            None => DeferredBody::default(),
17036775×
        })
171100227×
    }
172
17333960×
    fn body_mut(&mut self) -> &mut DeferredBody {
17433960×
        self.body();
17533960×
        self.raw = None;
17633960×
        self.body.get_mut().expect("decoded above")
17733960×
    }
178
17922357×
    fn into_body(mut self) -> DeferredBody {
18022357×
        self.body();
18122357×
        self.body.take().expect("decoded above")
18222357×
    }
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).
202777×
    pub fn write_index(&self) -> Option<Vec<u8>> {
203
        use crate::flat::Writer;
204777×
        let deferred = self.deferred.as_ref()?;
205777×
        if !self.files.is_empty() {
2060×
            return None;
207777×
        }
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`]).
219777×
        let mut w = Writer::default();
220777×
        w.fixed(Self::INDEX_MAGIC);
221777×
        let mut changes: Vec<(&ChangeHash, &Arc<ChangeMeta>)> = self.changes.iter().collect();
222777×
        changes.sort_by_key(|(h, _)| **h);
223777×
        w.count(changes.len());
224777×
        for (h, m) in changes {
225170×
            w.object(h);
226170×
            m.write_flat(&mut w);
227170×
        }
228777×
        let changes_block = std::mem::take(&mut w);
229777×
        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.
232777×
        let mut tw = Writer::default();
233777×
        self.tree.write_flat(&mut tw);
234777×
        w.bytes(&tw.0);
235777×
        let mut replaces: Vec<(&NodeId, &Vec<ReplaceRecord>)> = self.replaces.iter().collect();
236777×
        replaces.sort_by_key(|(n, _)| **n);
237777×
        w.count(replaces.len());
238777×
        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
        }
250777×
        let outer = w;
251777×
        let mut w = Writer::default();
252777×
        let mut nodes: Vec<(&NodeId, &Arc<Deferred>)> = deferred.iter().collect();
253777×
        nodes.sort_by_key(|(n, _)| **n);
254777×
        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
        }
354777×
        let mut outer = outer;
355777×
        outer.bytes(&w.0);
356777×
        Some(outer.0)
357777×
    }
358
359
    /// The state an index holds (see [`State::write_index`]).
3601691×
    pub fn read_index(bytes: &[u8]) -> Result<State, ObjectError> {
361
        use crate::flat::Reader;
3621691×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
3631691×
        let mut r = Reader::new(bytes);
3641691×
        let mut st = State::new_history_only();
365
        {
3661691×
            let _t = crate::timing::phase("index: changes");
3671691×
            st.changes = Self::read_index_changes(r.bytes()?)?;
368
        }
3691691×
        let tree_bytes = r.bytes()?;
3701691×
        for _ in 0..r.count()? {
3712×
            let n = NodeId(r.fixed::<16>()?);
3722×
            let mut recs = Vec::new();
3732×
            for _ in 0..r.count()? {
3742×
                recs.push((r.object()?, r.opt_object()?, r.opt_object()?));
375
            }
3762×
            st.replaces.insert(n, recs);
377
        }
3781691×
        let deferred_bytes = r.bytes()?;
3791691×
        if !r.at_end() {
3800×
            return Err(bad("trailing bytes"));
3811691×
        }
3821691×
        let (tree, deferred) = rayon::join(
3831691×
            || TreeGraph::read_flat(&mut Reader::new(tree_bytes)),
3841691×
            || Self::read_deferred(deferred_bytes),
385
        );
3861691×
        st.tree = tree?;
3871691×
        st.deferred = Some(deferred?);
3881691×
        Ok(st)
3891691×
    }
390
391
    /// The changes of a state index: its first block, which a reader can
392
    /// take without the rest (the log needs no more).
3931840×
    pub fn read_index_changes(
3941840×
        bytes: &[u8],
3951840×
    ) -> Result<HashMap<ChangeHash, Arc<ChangeMeta>>, ObjectError> {
396
        use crate::flat::Reader;
3971840×
        let mut r = Reader::new(bytes);
3981840×
        if r.fixed::<18>()?.as_slice() != Self::INDEX_MAGIC {
3990×
            return Err(ObjectError::Schema("state index: not a state index".into()));
4001840×
        }
4011840×
        let n = r.count()?;
4021840×
        let mut changes = HashMap::with_capacity(n);
4031840×
        for _ in 0..n {
404120×
            let h = r.object()?;
405120×
            changes.insert(h, Arc::new(ChangeMeta::read_flat(&mut r)?));
406
        }
4071840×
        if !r.at_end() {
4080×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
4091840×
        }
4101840×
        Ok(changes)
4111840×
    }
412
413
    /// The deferred block: each node with its graph key and its body,
414
    /// left encoded (see [`Deferred`]).
4151691×
    fn read_deferred(
4161691×
        bytes: &[u8],
4171691×
    ) -> Result<crate::fasthash::FastMap<NodeId, Arc<Deferred>>, ObjectError> {
418
        use crate::flat::Reader;
4191691×
        let _t = crate::timing::phase("index: deferred");
4201691×
        let all: Arc<[u8]> = Arc::from(bytes);
4211691×
        let mut r = Reader::new(bytes);
4221691×
        let mut deferred = crate::fasthash::FastMap::default();
4231691×
        let n = r.count()?;
4241691×
        deferred.reserve(n);
4251691×
        for _ in 0..n {
42616568×
            let id = NodeId(r.fixed::<16>()?);
42716568×
            let key = r.fixed::<32>()?;
42816568×
            let body = r.bytes()?;
42916568×
            let start = body.as_ptr() as usize - bytes.as_ptr() as usize;
43016568×
            let d = Deferred {
43116568×
                raw: Some((all.clone(), start..start + body.len())),
43216568×
                key: std::sync::OnceLock::from(key),
43316568×
                ..Deferred::default()
43416568×
            };
43516568×
            deferred.insert(id, Arc::new(d));
436
        }
4371691×
        if !r.at_end() {
4380×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
4391691×
        }
4401691×
        Ok(deferred)
4411691×
    }
442
443
    /// One node's deferred history as the index encodes it.
4445449×
    fn read_deferred_body(bytes: &[u8]) -> Result<DeferredBody, ObjectError> {
445
        use crate::flat::Reader;
4465449×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
4475449×
        let node = |r: &mut Reader| -> Result<NodeId, ObjectError> { Ok(NodeId(r.fixed::<16>()?)) };
44810892×
        let atom = |r: &mut Reader| -> Result<AtomRef, ObjectError> {
44910892×
            Ok(match r.u8()? {
4505445×
                0 => AtomRef::Start,
4515446×
                1 => AtomRef::End,
452
                2 => AtomRef::Atom {
4531×
                    change: r.object()?,
4541×
                    index: r.u32()?,
455
                },
4560×
                _ => return Err(bad("atom")),
457
            })
45810892×
        };
4595449×
        let mut r = Reader::new(bytes);
4605449×
        let base = match r.u8()? {
4615445×
            0 => None,
4620×
            1 => Some(DeferredBase::Blob(r.object()?)),
4634×
            _ => Some(DeferredBase::Inline(cbor::decode(r.bytes()?)?)),
464
        };
4655449×
        let mut edits = Vec::new();
4665449×
        for _ in 0..r.count()? {
4675446×
            let c = r.object()?;
4685446×
            let mut es = Vec::new();
4695446×
            for _ in 0..r.count()? {
4705446×
                es.push(match r.u8()? {
471
                    0 => Edit::Insert {
4725446×
                        node: node(&mut r)?,
4735446×
                        after: atom(&mut r)?,
4745446×
                        before: atom(&mut r)?,
4755446×
                        lines: crate::lines::Lines::default(),
476
                    },
477
                    1 => {
4780×
                        let node = node(&mut r)?;
4790×
                        let mut atoms = Vec::new();
4800×
                        for _ in 0..r.count()? {
4810×
                            atoms.push(crate::objects::AtomRange {
4820×
                                change: r.object()?,
4830×
                                from: r.u32()?,
4840×
                                to: r.u32()?,
485
                            });
486
                        }
4870×
                        Edit::Delete { node, atoms }
488
                    }
4890×
                    _ => return Err(bad("edit")),
490
                });
491
            }
4925446×
            edits.push((c, es));
493
        }
4945449×
        let mut texts = Vec::new();
4955449×
        for _ in 0..r.count()? {
4965446×
            texts.push(match r.u8()? {
497
                0 => TextRef::Blob(
4980×
                    r.object()?,
4990×
                    r.u32()?,
5000×
                    match r.u8()? {
5010×
                        0 => crate::objects::TextForm::Cbor,
5020×
                        1 => crate::objects::TextForm::Raw,
5030×
                        _ => crate::objects::TextForm::CborFallback,
504
                    },
505
                ),
506
                _ => TextRef::Inline {
5075446×
                    change: r.object()?,
5085446×
                    start: r.u32()?,
5095446×
                    end: r.u32()?,
510
                },
511
            });
512
        }
5135449×
        if !r.at_end() {
5140×
            return Err(bad("trailing bytes in a file's history"));
5155449×
        }
5165449×
        Ok(DeferredBody { base, edits, texts })
5175449×
    }
518
}
519
520
impl Clone for State {
5211268×
    fn clone(&self) -> State {
5221268×
        State {
5231268×
            changes: self.changes.clone(),
5241268×
            tree: self.tree.clone(),
5251268×
            files: self.files.clone(),
5261268×
            replaces: self.replaces.clone(),
5271268×
            // A cache: the clone builds its own.
5281268×
            closure: Mutex::new(ClosureMemo::default()),
5291268×
            levels: Mutex::new(HashMap::new()),
5301268×
            deferred: self.deferred.clone(),
5311268×
        }
5321268×
    }
533
}
534
535
#[derive(Clone, Debug, PartialEq, Eq)]
536
pub enum FileContent {
537
    Text {
538
        bytes: Vec<u8>,
539
        materialized: Materialized,
540
    },
541
    /// Live blobs; more than one is a replace conflict (spec §9.3).
542
    Opaque {
543
        blobs: Vec<ObjectRef>,
544
    },
545
    Dir,
546
}
547
548
#[derive(Clone, Debug, PartialEq, Eq)]
549
pub struct FileState {
550
    pub node: NodeId,
551
    pub kind: NodeKind,
552
    pub mode: Mode,
553
    pub content: FileContent,
554
}
555
556
impl FileState {
55713397×
    pub fn is_conflicted(&self) -> bool {
55813397×
        match &self.content {
55912477×
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
560240×
            FileContent::Opaque { blobs } => blobs.len() > 1,
561680×
            FileContent::Dir => false,
562
        }
56313397×
    }
564
}
565
566
/// See `State::conflict_regions`.
567
#[derive(Clone, Debug, Default, PartialEq, Eq)]
568
pub struct ConflictRegions {
569
    pub plain: Vec<(AtomKey, Vec<u8>)>,
570
    pub region_atoms: Vec<AtomKey>,
571
    pub contributors: Vec<ChangeHash>,
572
}
573
574
/// The whole tree of a state, materialized.
575
#[derive(Clone, Debug, Default)]
576
pub struct Snapshot {
577
    pub tree: TreeView,
578
    pub files: BTreeMap<String, FileState>,
579
    /// Text files left unrendered by [`State::materialize_except`]: their
580
    /// `bytes` are empty and they are known not to be conflicted.
581
    pub unrendered: BTreeSet<String>,
582
}
583
584
impl Snapshot {
5851848×
    pub fn is_conflicted(&self) -> bool {
58613098×
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
5871848×
    }
588
}
589
59060808×
fn vertex(r: AtomRef) -> Vertex {
59160808×
    match r {
59225217×
        AtomRef::Start => Vertex::Start,
59326762×
        AtomRef::End => Vertex::End,
5948829×
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
595
    }
59660808×
}
597
598
/// Replace self references in a tree op with the concrete change hash.
59937386×
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
60037386×
    match op {
601816×
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
602816×
            node: *node,
603816×
            placement: placement.resolve(me),
604816×
        },
605
        TreeOp::Move {
606120×
            node,
607120×
            old,
608120×
            parent,
609120×
            name,
610120×
        } => TreeOp::Move {
611120×
            node: *node,
612120×
            old: old.resolve(me),
613120×
            parent: *parent,
614120×
            name: name.clone(),
615120×
        },
61618×
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
61718×
            node: *node,
61818×
            old: old.resolve(me),
61918×
            mode: *mode,
62018×
        },
62136432×
        add @ TreeOp::AddNode { .. } => add.clone(),
622
    }
62337386×
}
624
625
/// Apply one change's edits of one file (inserts and deletes; replaces
626
/// live beside the graphs) to that file's graph.
62725164×
fn apply_file_edits(g: &mut FileGraph, h: ChangeHash, edits: Vec<Edit>) {
628
    // The graph's kept order, if any, follows the edits (see `Order`).
62925164×
    let order = g.take_order();
63025164×
    let mut inserts: Vec<(Vertex, Vertex, u32, u32)> = Vec::new();
63125164×
    let mut deleted: Vec<crate::graph::AtomKey> = Vec::new();
63225164×
    let mut next = 0u32;
63327256×
    for e in edits {
63427256×
        match e {
635
            Edit::Insert {
63625997×
                after,
63725997×
                before,
63825997×
                lines,
639
                ..
64025997×
            } => {
64125997×
                let first = next;
64225997×
                let count = lines.len() as u32;
64325997×
                next += count;
64425997×
                let (after, before) = (vertex(after.resolve(h)), vertex(before.resolve(h)));
64525997×
                inserts.push((after, before, first, count));
64625997×
                g.insert_owned(h, first, after, before, lines);
64725997×
            }
6481259×
            Edit::Delete { atoms, .. } => {
6492332×
                for r in atoms {
6502332×
                    let r = r.resolve(h);
6512413×
                    deleted.extend((r.from..r.to).map(|i| (r.change, i)));
6522332×
                    g.delete(h, &r);
653
                }
654
            }
6550×
            Edit::Replace { .. } => {}
656
        }
657
    }
65825164×
    if let Some(o) = order {
65966×
        g.keep_spliced(o, h, &inserts, &deleted);
66025098×
    }
66125164×
}
662
663
/// Build the graphs of deferred entries: their checkpoint bases and the
664
/// texts of inserts read without their lines are loaded in one call, then
665
/// the graphs are built in parallel (they are independent).
6663373×
fn build_deferred(
6673373×
    taken: Vec<(NodeId, Deferred)>,
6683373×
    load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
6693373×
    read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
6703373×
) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
6713373×
    let mut taken: Vec<(NodeId, DeferredBody)> =
67222357×
        taken.into_iter().map(|(n, d)| (n, d.into_body())).collect();
6733373×
    let mut refs: Vec<ObjectRef> = taken
6743373×
        .iter()
6753373×
        .filter_map(|(_, d)| match &d.base {
6766×
            Some(DeferredBase::Blob(r)) => Some(*r),
67722351×
            _ => None,
67822357×
        })
6793373×
        .collect();
680
    // Text blobs of inserts read without their lines, after the bases.
6813373×
    let bases = refs.len();
68222357×
    refs.extend(taken.iter().flat_map(|(_, d)| {
68325316×
        d.texts.iter().filter_map(|t| match t {
68470×
            TextRef::Blob(r, _, _) => Some(*r),
68525246×
            TextRef::Inline { .. } => None,
68625316×
        })
68722357×
    }));
688
    // And the encodings of changes whose inline inserts are needed,
689
    // each read once.
6903373×
    let reading = crate::timing::phase("graphs: read changes and blobs");
6913373×
    let mut changes: HashMap<ChangeHash, Arc<Vec<u8>>> = HashMap::new();
69225316×
    for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
69325316×
        if let TextRef::Inline { change, .. } = t {
69425246×
            if !changes.contains_key(change) {
6955453×
                changes.insert(*change, read_change(change)?);
69619793×
            }
69770×
        }
698
    }
6993373×
    let n_changes = changes.len();
7003373×
    drop(reading);
7013373×
    let reading = crate::timing::phase("graphs:   of which blobs");
7023373×
    let mut blobs = if refs.is_empty() {
7033302×
        Vec::new()
704
    } else {
70571×
        load(&refs)?
706
    };
7073370×
    if crate::timing::enabled() {
7082×
        eprintln!(
7092×
            "timing graphs: {} graphs, {n_changes} changes, {} blobs",
7102×
            taken.len(),
7112×
            refs.len()
7122×
        );
7133368×
    }
7143370×
    if blobs.len() != refs.len() {
7150×
        return Err(ObjectError::Schema("graph blobs: wrong count".into()));
7163370×
    }
7173370×
    drop(reading);
7183370×
    let lines = crate::timing::phase("graphs: hand out blobs");
7193370×
    let mut texts = blobs.split_off(bases).into_iter();
7203370×
    let mut blobs = blobs.into_iter();
721
    // Hand each graph its own blobs, in order, then fill in its inserts'
722
    // lines and build it, all in parallel: graphs are independent.
723
    type Work = (NodeId, DeferredBody, Option<Vec<u8>>, Vec<Vec<u8>>);
7243370×
    let mut work: Vec<Work> = Vec::with_capacity(taken.len());
72522354×
    for (node, d) in taken.drain(..) {
72622354×
        let wanted = d
72722354×
            .texts
72822354×
            .iter()
72925314×
            .filter(|t| matches!(t, TextRef::Blob(..)))
73022354×
            .count();
73122354×
        let mine: Vec<Vec<u8>> = texts.by_ref().take(wanted).collect();
73222354×
        if mine.len() != wanted {
7330×
            return Err(ObjectError::Schema("text blobs: wrong count".into()));
73422354×
        }
73522354×
        let bytes = match &d.base {
736
            Some(DeferredBase::Blob(_)) => Some(
7375×
                blobs
7385×
                    .next()
7395×
                    .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
740
            ),
74122349×
            _ => None,
742
        };
74322354×
        work.push((node, d, bytes, mine));
744
    }
7453370×
    drop(lines);
7463370×
    let _t = crate::timing::phase("graphs: lines and build");
747
    use rayon::prelude::*;
7483370×
    let changes = &changes;
7493370×
    let built: Vec<(NodeId, FileGraph)> = work
7503370×
        .into_par_iter()
75122354×
        .map(|(node, mut d, bytes, mine)| {
752
            // Fill in the lines of inserts read without them, in order.
75322354×
            let mut want = std::mem::take(&mut d.texts).into_iter();
75422354×
            let mut mine = mine.into_iter();
75524718×
            for (_, edits) in d.edits.iter_mut() {
75626373×
                for e in edits.iter_mut() {
75726373×
                    if let Edit::Insert { lines, .. } = e {
75825352×
                        if lines.is_empty() {
75925314×
                            *lines = match want.next() {
76068×
                                Some(TextRef::Blob(_, count, form)) => {
76168×
                                    let content = mine.next().ok_or_else(|| {
7620×
                                        ObjectError::Schema("text blobs: wrong count".into())
7630×
                                    })?;
76468×
                                    crate::objects::text_lines(&content, count, form)?
765
                                }
76625246×
                                Some(TextRef::Inline { change, start, end }) => {
76725246×
                                    let bytes = &changes[&change];
76825246×
                                    let range = bytes
76925246×
                                        .get(start as usize..end as usize)
77025246×
                                        .ok_or_else(|| {
7710×
                                            ObjectError::Schema(
7720×
                                                "an inline insert lies outside its change".into(),
7730×
                                            )
7740×
                                        })?;
77525246×
                                    crate::objects::inline_lines(range)?
776
                                }
777
                                None => {
7780×
                                    return Err(ObjectError::Schema(
7790×
                                        "an insert's text is missing".into(),
7800×
                                    ))
781
                                }
782
                            };
78338×
                        }
7841021×
                    }
785
                }
786
            }
78722354×
            let mut graph = match (d.base.take(), bytes) {
78896×
                (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
7895×
                (Some(DeferredBase::Blob(_)), Some(bytes)) => {
7905×
                    FileGraph::from_value(&cbor::decode(&bytes)?)?
791
                }
79222253×
                _ => FileGraph::default(),
793
            };
79424718×
            for (h, edits) in std::mem::take(&mut d.edits) {
79524718×
                apply_file_edits(&mut graph, h, edits);
79624718×
            }
79722354×
            Ok((node, graph))
79822354×
        })
7993370×
        .collect::<Result<_, ObjectError>>()?;
8003370×
    Ok(built)
8013373×
}
802
803
impl State {
804694×
    pub fn new() -> Self {
805694×
        Self::default()
806694×
    }
807
808
    /// An empty state for history only: changes and tree are kept, file
809
    /// edits are recorded but no file graph is built until
810
    /// [`State::load_graphs`] asks for it. For log and other commands that
811
    /// need no file contents, or only a few files.
8123121×
    pub fn new_history_only() -> Self {
8133121×
        State {
8143121×
            deferred: Some(Default::default()),
8153121×
            ..Self::default()
8163121×
        }
8173121×
    }
818
819
    /// Whether `node`'s file graph is built (always, in a full state).
82040×
    pub fn is_built(&self, node: &NodeId) -> bool {
82140×
        self.deferred.is_none() || self.files.contains_key(node)
82240×
    }
823
824
    /// Whether this state builds file graphs only when asked
825
    /// ([`State::new_history_only`]), even if it has none waiting.
8262972×
    pub fn is_history_only(&self) -> bool {
8272972×
        self.deferred.is_some()
8282972×
    }
829
830
    /// Whether this state holds every file graph.
8312573×
    pub fn is_full(&self) -> bool {
8322573×
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
8332573×
    }
834
835
    /// The graph of `node`, which must be loaded: asking a history-only
836
    /// state for a graph it has not built is a bug, never an empty file.
83724560×
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
83824560×
        if let Some(d) = &self.deferred {
8399845×
            assert!(
8409845×
                !d.contains_key(node),
841
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
8421×
                node.short(12)
843
            );
84414715×
        }
84524559×
        self.files.get(node).map(|g| g.as_ref())
84624559×
    }
847
848
    /// Operations over every file need every graph.
8492566×
    fn require_full(&self, what: &str) {
8502566×
        assert!(
8512566×
            self.is_full(),
852
            "{what} needs every file graph; this state was loaded for history only"
853
        );
8542565×
    }
855
856
    /// Build the graphs of `nodes` in a history-only state: from their
857
    /// checkpoint base (blobs read in one batch through `load`) and their
858
    /// deferred edits. Nodes already built, or with no graph, are skipped.
8593300×
    pub fn load_graphs(
8603300×
        &mut self,
8613300×
        nodes: &[NodeId],
8623300×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
8633300×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
8643300×
    ) -> Result<(), ObjectError> {
8653300×
        let Some(deferred) = self.deferred.as_mut() else {
8660×
            return Ok(());
867
        };
8683300×
        let taken: Vec<(NodeId, Deferred)> = nodes
8693300×
            .iter()
87022499×
            .filter_map(|n| deferred.remove(n).map(|d| (*n, Arc::unwrap_or_clone(d))))
8713300×
            .collect();
8723300×
        let built = build_deferred(taken, load, read_change)?;
8733297×
        self.files
87422293×
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
8753297×
        Ok(())
8763300×
    }
877
878
    /// The graphs of `nodes`, built from this history-only state's deferred
879
    /// edits without building them in it: the state stays history only, so
880
    /// changes read without their lines can still be added to it and every
881
    /// graph keeps its key. For a caller that renders a few files of many
882
    /// states in turn (verifying an import).
88373×
    pub fn build_graphs_detached(
88473×
        &self,
88573×
        nodes: &[NodeId],
88673×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
88773×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
88873×
    ) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
88973×
        let Some(deferred) = self.deferred.as_ref() else {
8900×
            return Ok(Vec::new());
891
        };
892
        // A file this state has built has no deferred history: its graph
893
        // is the built one, copied. Built from an empty history instead, it
894
        // rendered as an empty file, and a merge taking this path recorded
895
        // the whole file as inserted again, conflicting with itself (#71).
89673×
        let mut built: Vec<(NodeId, FileGraph)> = Vec::new();
89773×
        let mut copies: Vec<(NodeId, Deferred)> = Vec::new();
89873×
        for n in nodes {
89964×
            match (self.files.get(n), deferred.get(n)) {
9003×
                (Some(g), _) => built.push((*n, (**g).clone())),
90161×
                (None, d) => copies.push((*n, d.map(|d| (**d).clone()).unwrap_or_default())),
902
            }
903
        }
90473×
        let mut out = build_deferred(copies, load, read_change)?;
90573×
        out.extend(built);
90673×
        Ok(out)
90773×
    }
908
909
    /// Render a graph built for this state (see
910
    /// [`State::build_graphs_detached`]), as [`State::render_file`] does.
91164×
    pub fn render_graph(&self, g: &FileGraph) -> (Vec<u8>, Materialized) {
91264×
        let m = g.materialize(self);
91364×
        let bytes = g.render(&m, &|h| self.label(h));
91464×
        (bytes, m)
91564×
    }
916
917
    /// Every file graph a history-only state has not built, deleted files'
918
    /// included.
91976×
    pub fn unbuilt_nodes(&self) -> Vec<NodeId> {
92076×
        self.deferred
92176×
            .as_ref()
92276×
            .map(|d| d.keys().copied().collect())
92376×
            .unwrap_or_default()
92476×
    }
925
926
    /// Drop the built graphs of `nodes`, for a caller rendering a large
927
    /// tree a batch at a time. The state can no longer render those files,
928
    /// so it must not be used for them again.
929417×
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
9305986×
        for n in nodes {
9315986×
            self.files.remove(n);
9325986×
        }
933417×
    }
934
935
    /// Build every graph a history-only state has not built, making it full.
9361646×
    pub fn load_all_graphs(
9371646×
        &mut self,
9381646×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
9391646×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
9401646×
    ) -> Result<(), ObjectError> {
9411646×
        let nodes: Vec<NodeId> = match &self.deferred {
9421646×
            Some(d) => d.keys().copied().collect(),
9430×
            None => return Ok(()),
944
        };
9451646×
        self.load_graphs(&nodes, load, read_change)?;
9461646×
        self.deferred = None;
9471646×
        Ok(())
9481646×
    }
949
950
    /// The one text a file's history is, when it is a single insert of
951
    /// the whole file into nothing (a file added once and never edited,
952
    /// with no checkpoint base): its rendering is that text, so it needs
953
    /// no graph. `None` otherwise, or when the graph is built.
9545840×
    pub fn single_text(&self, node: &NodeId) -> Option<TextRef> {
9555840×
        if self.files.contains_key(node) {
9560×
            return None;
9575840×
        }
9585840×
        let d = self.deferred.as_ref()?.get(node)?.body();
9595787×
        let [(_, edits)] = d.edits.as_slice() else {
960242×
            return None;
961
        };
962
        let [Edit::Insert {
963
            after: AtomRef::Start,
964
            before: AtomRef::End,
9655545×
            lines,
966
            ..
9675545×
        }] = edits.as_slice()
968
        else {
9690×
            return None;
970
        };
9715545×
        match (&d.base, d.texts.as_slice()) {
9725545×
            (None, [t]) if lines.is_empty() => Some(*t),
9730×
            _ => None,
974
        }
9755840×
    }
976
977
    /// A key for the graph of `node` in a history-only state that has not
978
    /// built it: equal keys mean equal graphs, so equal renderings (a
979
    /// rendering depends only on the graph and on the changes' own
980
    /// immutable metadata). It names the node, its checkpoint base (a blob,
981
    /// an inline value, or none) and the set of later changes that edited
982
    /// the file.
983
    /// `None` for a full state or a graph already built.
98428394×
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
98528394×
        let deferred = self.deferred.as_ref()?;
98628359×
        if self.files.contains_key(node) {
987406×
            return None;
98827953×
        }
98927953×
        let mut h = blake3::Hasher::new();
99027953×
        h.update(b"oxy graph key 1\0");
991
        // A change's edits are applied per node: the node is part of it.
99227953×
        h.update(&node.0);
99327953×
        let Some(d) = deferred.get(node) else {
994
            // Never edited: the empty graph.
995174×
            h.update(&[0]);
996174×
            return Some(*h.finalize().as_bytes());
997
        };
99827779×
        Some(*d.key.get_or_init(|| d.graph_key(h)))
99928394×
    }
1000
10013252×
    pub fn len(&self) -> usize {
10023252×
        self.changes.len()
10033252×
    }
1004
1005
    /// Turn this history-only state's built graphs back into deferred
1006
    /// histories, each starting from its graph encoded as a checkpoint
1007
    /// graph and stored by `store` (it returns the blob's reference): what
1008
    /// they held stays, and memory goes back to what a history-only state
1009
    /// costs. A graph built later again decodes that blob and applies only
1010
    /// the edits that came after. Graph keys change (the base is now a
1011
    /// blob), which only means a cached rendering is not reused.
10121×
    pub fn shed_graphs<E>(
10131×
        &mut self,
10141×
        mut store: impl FnMut(&[u8]) -> Result<ObjectRef, E>,
10151×
    ) -> Result<usize, E> {
1016
        use rayon::prelude::*;
10171×
        let Some(deferred) = self.deferred.as_mut() else {
10180×
            return Ok(0);
1019
        };
10201×
        let graphs: Vec<(NodeId, Arc<FileGraph>)> = self.files.drain().collect();
10211×
        let encoded: Vec<(NodeId, Vec<u8>)> = graphs
10221×
            .par_iter()
10232×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
10241×
            .collect();
10251×
        drop(graphs);
10261×
        let shed = encoded.len();
10272×
        for (node, bytes) in encoded {
10282×
            let blob = store(&bytes)?;
10292×
            deferred.insert(
10302×
                node,
10312×
                Arc::new(Deferred::from_body(DeferredBody {
10322×
                    base: Some(DeferredBase::Blob(blob)),
10332×
                    ..DeferredBody::default()
10342×
                })),
1035
            );
1036
        }
10371×
        Ok(shed)
10381×
    }
1039
1040
    /// How many file graphs this state has built.
104171×
    pub fn built_count(&self) -> usize {
104271×
        self.files.len()
104371×
    }
1044
1045
    /// Atoms in this state's built graphs, live and deleted: what their
1046
    /// memory follows, since a graph keeps every line its file ever had.
104746×
    pub fn built_atoms(&self) -> usize {
104848×
        self.files.values().map(|g| g.atom_count()).sum()
104946×
    }
1050
1051
    /// Edits held in the deferred histories of files not built, and the
1052
    /// most any one file holds (for measuring, #25).
10530×
    pub fn deferred_edit_count(&self) -> (usize, usize) {
10540×
        let Some(d) = self.deferred.as_ref() else {
10550×
            return (0, 0);
1056
        };
10570×
        let mut total = 0;
10580×
        let mut most = 0;
10590×
        for v in d.values() {
10600×
            let n: usize = v.body().edits.iter().map(|(_, e)| e.len()).sum();
10610×
            total += n;
10620×
            most = most.max(n);
1063
        }
10640×
        (total, most)
10650×
    }
1066
}
1067
1068
impl Deferred {
1069
    /// See [`State::graph_key`]: `h` has taken the node already.
107021875×
    fn graph_key(&self, mut h: blake3::Hasher) -> [u8; 32] {
107121875×
        let d = self.body();
107213×
        match &d.base {
107321862×
            None => h.update(&[0]),
10740×
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
107513×
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
1076
        };
107721875×
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
107821875×
        changes.sort();
107921875×
        changes.dedup();
108021875×
        h.update(&(changes.len() as u64).to_le_bytes());
108123135×
        for c in changes {
108223135×
            h.update(&c.0);
108323135×
        }
108421875×
        *h.finalize().as_bytes()
108521875×
    }
1086
}
1087
1088
impl State {
10890×
    pub fn is_empty(&self) -> bool {
10900×
        self.changes.is_empty()
10910×
    }
109212585×
    pub fn contains(&self, h: &ChangeHash) -> bool {
109312585×
        self.changes.contains_key(h)
109412585×
    }
109564×
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
109664×
        self.changes.get(h).map(|m| &**m)
109764×
    }
10981263×
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
10993200×
        self.changes.iter().map(|(h, m)| (h, &**m))
11001263×
    }
110116886×
    pub fn tree(&self) -> &TreeGraph {
110216886×
        &self.tree
110316886×
    }
1104536×
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
1105536×
        self.graph(node)
1106536×
    }
1107
1108
    /// Add a change whose dependencies are already present.
11092855×
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
11102855×
        let h = change.hash();
11112855×
        self.add_hashed(h, change)
11122855×
    }
1113
1114
    /// [`State::add`] for a change whose hash `h` is already known (it was
1115
    /// just stored), so it is not encoded again.
11163465×
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
11173465×
        if self.changes.contains_key(&h) {
111836×
            return Ok(h);
11193429×
        }
11205007×
        for d in &change.deps {
11215007×
            if !self.changes.contains_key(d) {
11222×
                return Err(StateError::MissingDep(*d, h));
11235005×
            }
1124
        }
11253427×
        self.add_known(h, change, Vec::new());
11263427×
        Ok(h)
11273465×
    }
1128
1129
    /// Add a change in any order; call `validate` once all are in.
11301021×
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
11311021×
        let h = change.hash();
11321021×
        self.add_known(h, change, Vec::new());
11331021×
        h
11341021×
    }
1135
1136
    /// Add a change just stored under hash `h` to a history-only state that
1137
    /// has built some graphs: an edit of a built graph is applied whole
1138
    /// (from `full`), and one of a file not built waits without its text
1139
    /// (from `skeleton` and its `texts`, as the store reads it back), so the
1140
    /// state holds no text it has not built. A Git import adds each change
1141
    /// it makes this way, keeping memory to what changes.
114284×
    pub fn add_known_mixed(
114384×
        &mut self,
114484×
        h: ChangeHash,
114584×
        full: Change,
114684×
        skeleton: Change,
114784×
        texts: Vec<TextRef>,
114884×
    ) {
114984×
        if self.deferred.is_none() || self.changes.contains_key(&h) {
11500×
            self.add_known(h, full, Vec::new());
11510×
            return;
115284×
        }
1153
        let Change {
115484×
            version,
115584×
            change_id,
115684×
            deps,
115784×
            author,
115884×
            hlc,
115984×
            message,
116084×
            tree_ops,
116184×
            edits: full_edits,
116284×
            kind,
116384×
        } = full;
116484×
        let mut texts = texts.into_iter();
116584×
        let mut edits = Vec::with_capacity(full_edits.len());
116684×
        let mut kept = Vec::new();
116793×
        for (f, s) in full_edits.into_iter().zip(skeleton.edits) {
116893×
            let text = match &s {
116973×
                Edit::Insert { lines, .. } if lines.is_empty() => texts.next(),
117020×
                _ => None,
1171
            };
117293×
            if self.files.contains_key(&f.node()) {
117345×
                edits.push(f);
117448×
            } else {
117548×
                edits.push(s);
117648×
                kept.extend(text);
117748×
            }
1178
        }
117984×
        let c = Change {
118084×
            version,
118184×
            change_id,
118284×
            deps,
118384×
            author,
118484×
            hlc,
118584×
            message,
118684×
            tree_ops,
118784×
            edits,
118884×
            kind,
118984×
        };
119084×
        self.add_known(h, c, kept);
119184×
    }
1192
1193
    /// Add a change read from the store under hash `h`, without hashing it
1194
    /// again (for a version 2 change that means chunking all its text).
1195
    /// `texts` names, in order, the inserts left without their lines (see
1196
    /// [`crate::store::Store::get_change_lazy`]); only a history-only state
1197
    /// takes them, and only for graphs it has not built.
119811435×
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
119911435×
        if self.changes.contains_key(&h) {
12000×
            return;
120111435×
        }
120211435×
        let meta = ChangeMeta::of(&change);
120311435×
        self.apply_with(h, change, texts);
120411435×
        self.changes.insert(h, Arc::new(meta));
120511435×
        {
120611435×
            let mut m = self.closure.lock().unwrap();
120711435×
            m.sets.clear();
120811435×
            m.held = 0;
120911435×
        }
121011435×
    }
1211
1212
    // ------------------------------------------------------------ checkpoints (spec §11)
1213
1214
    /// Serialize the whole state in payload version 1: change metadata,
1215
    /// tree, file graphs, replaces, all in one value (spec §11).
1216380×
    pub fn checkpoint_payload(&self) -> Vec<u8> {
1217380×
        self.require_full("a checkpoint");
1218380×
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
1219380×
        nodes.sort();
1220380×
        let files = Value::Array(
1221380×
            nodes
1222380×
                .into_iter()
12231462×
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
1224380×
                .collect(),
1225
        );
1226380×
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
1227380×
    }
1228
1229
    /// Each file graph encoded on its own, by node, for a version 2 payload
1230
    /// (spec §11): the graphs of large files become blobs of their own.
123118×
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
1232
        use rayon::prelude::*;
123318×
        self.require_full("a checkpoint");
123418×
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
123553×
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
123618×
        nodes.sort_by_key(|(n, _)| **n);
123718×
        nodes
123818×
            .into_par_iter()
123953×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
124018×
            .collect()
124118×
    }
1242
1243
    /// The payload version 2 index for the graphs of
1244
    /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than
1245
    /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by
1246
    /// `blob_of` (the ObjectRef of the blob holding its encoding).
124718×
    pub fn checkpoint_index(
124818×
        &self,
124918×
        graphs: &[(NodeId, Vec<u8>)],
125018×
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
125118×
    ) -> Vec<u8> {
125218×
        let files = Value::Array(
125318×
            graphs
125418×
                .iter()
125553×
                .map(|(n, enc)| {
125653×
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
125746×
                        cbor::decode(enc).expect("an encoded graph decodes")
1258
                    } else {
12597×
                        Value::Bytes(blob_of(enc).0.to_vec())
1260
                    };
126153×
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
126253×
                })
126318×
                .collect(),
1264
        );
126518×
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
126618×
    }
1267
1268
    /// The payload map around `files`: changes, tree and replaces as in version 1.
1269398×
    fn payload_value(&self, version: u64, files: Value) -> Value {
1270398×
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
1271398×
        hashes.sort();
1272398×
        let changes = Value::Array(
1273398×
            hashes
1274398×
                .into_iter()
12752264×
                .map(|h| {
12762264×
                    let m = &self.changes[h];
12772264×
                    Value::Array(vec![
12782264×
                        Value::Bytes(h.0.to_vec()),
12792264×
                        Value::Bytes(m.change_id.0.to_vec()),
12802264×
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
12812264×
                        Value::Text(m.message.clone()),
12822264×
                        Value::Uint(m.hlc.wall_ms),
12832264×
                        Value::Uint(m.hlc.logical as u64),
12842264×
                        Value::Uint(m.kind.tag()),
12852264×
                        Value::Bytes(m.author.0.to_vec()),
1286
                    ])
12872264×
                })
1288398×
                .collect(),
1289
        );
1290398×
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
1291398×
        rnodes.sort();
1292398×
        let opt =
129310×
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
1294398×
        let replaces = Value::Array(
1295398×
            rnodes
1296398×
                .into_iter()
1297398×
                .map(|n| {
12985×
                    Value::Array(vec![
12995×
                        Value::Bytes(n.0.to_vec()),
1300
                        Value::Array(
13015×
                            self.replaces[n]
13025×
                                .iter()
13035×
                                .map(|(c, o, nw)| {
13045×
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
13055×
                                })
13065×
                                .collect(),
1307
                        ),
1308
                    ])
13095×
                })
1310398×
                .collect(),
1311
        );
1312398×
        Value::map([
1313398×
            (0, Value::Uint(version)),
1314398×
            (1, changes),
1315398×
            (2, self.tree.to_value()),
1316398×
            (3, files),
1317398×
            (4, replaces),
1318398×
        ])
1319398×
    }
1320
1321
    /// Decode a version 1 payload (the whole state in one value). A
1322
    /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`].
132337×
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
132437×
        State::from_checkpoint(bytes, |_| {
13251×
            Err(ObjectError::Schema(
13261×
                "a version 2 checkpoint needs its graph blobs".into(),
13271×
            ))
13281×
        })
132937×
    }
1330
1331
    /// Decode a checkpoint payload of either version (spec §11). For
1332
    /// version 2, `load` returns the contents of the named graph blobs, in
1333
    /// order; the graphs are then decoded in parallel.
133460×
    pub fn from_checkpoint(
133560×
        bytes: &[u8],
133660×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
133760×
    ) -> Result<State, ObjectError> {
1338
        use rayon::prelude::*;
133960×
        let v = cbor::decode(bytes)?;
134059×
        let m = o::map(&v, "checkpoint payload")?;
134159×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
134259×
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
13431×
            return Err(ObjectError::Schema(format!(
13441×
                "checkpoint payload version {version} is not supported"
13451×
            )));
134658×
        }
134758×
        let mut st = State::payload_common(m)?;
134858×
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
134958×
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
1350229×
        for f in entries {
1351229×
            let e = o::array(f, "file")?;
1352229×
            if e.len() != 2 {
13530×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1354229×
            }
1355229×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1356229×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1357229×
            parsed.push((node, &e[1]));
1358
        }
1359
        // Version 2 names large graphs by blob: fetch those in one batch.
136058×
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
136158×
        if version == CHECKPOINT_INDEX_VERSION {
136220×
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
136320×
                .iter()
136490×
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
136520×
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
136620×
                .collect::<Result<_, ObjectError>>()?;
136720×
            if !wanted.is_empty() {
13687×
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
13693×
                let contents = {
13707×
                    let _t = crate::timing::phase("load:   graph blobs read");
13717×
                    load(&refs)?
1372
                };
13733×
                if contents.len() != refs.len() {
13740×
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
13753×
                }
13763×
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
137713×
            }
1378139×
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
13790×
            return Err(ObjectError::Schema(
13800×
                "a version 1 payload holds graphs inline".into(),
13810×
            ));
138238×
        }
1383
        // File graphs are independent; decode and build them in parallel.
138454×
        let graphs = parsed
138554×
            .par_iter()
1386223×
            .map(|(node, entry)| {
1387223×
                let graph = match fetched.get(node) {
13883×
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
1389220×
                    None => FileGraph::from_value(entry)?,
1390
                };
1391223×
                Ok((*node, graph))
1392223×
            })
139354×
            .collect::<Result<Vec<_>, ObjectError>>()?;
139454×
        st.files
1395223×
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
139654×
        Ok(st)
139760×
    }
1398
1399
    /// The graph blobs a payload names: empty for version 1.
14009×
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
14019×
        let v = cbor::decode(bytes)?;
14029×
        let m = o::map(&v, "checkpoint payload")?;
14039×
        let mut out = Vec::new();
140427×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
140527×
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
14066×
                out.push(o::oref(entry, "graph blob")?);
140721×
            }
1408
        }
14099×
        Ok(out)
14109×
    }
1411
1412
    /// Decode a checkpoint payload for history only: a version 2 payload's
1413
    /// graphs are noted, not read or built, and come later through
1414
    /// [`State::load_graphs`]. A version 1 payload holds them inline and is
1415
    /// decoded in full.
141641×
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
141741×
        let v = cbor::decode(bytes)?;
141841×
        let m = o::map(&v, "checkpoint payload")?;
141941×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
142041×
        if version != CHECKPOINT_INDEX_VERSION {
14211×
            return State::from_checkpoint_payload(bytes);
142240×
        }
142340×
        let mut st = State::payload_common(m)?;
142440×
        let mut deferred = crate::fasthash::FastMap::default();
1425138×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1426138×
            let e = o::array(f, "file")?;
1427138×
            if e.len() != 2 {
14280×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1429138×
            }
1430138×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1431138×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1432138×
            let base = match &e[1] {
14334×
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
1434134×
                other => DeferredBase::Inline(other.clone()),
1435
            };
1436138×
            deferred.insert(
1437138×
                node,
1438138×
                Arc::new(Deferred::from_body(DeferredBody {
1439138×
                    base: Some(base),
1440138×
                    ..DeferredBody::default()
1441138×
                })),
1442
            );
1443
        }
144440×
        st.deferred = Some(deferred);
144540×
        Ok(st)
144641×
    }
1447
1448
    /// Changes, tree and replaces of a payload of either version.
144998×
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
145098×
        let mut st = State::new();
1451495×
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
1452495×
            let e = o::array(c, "change meta")?;
1453495×
            if e.len() != 8 {
14540×
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
1455495×
            }
1456495×
            let hash = o::oref(&e[0], "hash")?;
1457495×
            let meta = ChangeMeta {
1458495×
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
1459495×
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
1460495×
                deps: o::array(&e[2], "deps")?
1461495×
                    .iter()
1462611×
                    .map(|d| o::oref(d, "dep"))
1463495×
                    .collect::<Result<Vec<_>, _>>()?,
1464495×
                message: o::text(&e[3], "message")?.to_owned(),
1465
                hlc: Hlc {
1466495×
                    wall_ms: o::uint(&e[4], "wall")?,
1467495×
                    logical: o::u32_(&e[5], "logical")?,
1468
                },
1469495×
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
1470495×
                author: o::oref(&e[7], "author")?,
1471
            };
1472495×
            st.changes.insert(hash, Arc::new(meta));
1473
        }
147498×
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
147598×
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
147624×
            if v.is_null() {
147712×
                Ok(None)
1478
            } else {
147912×
                o::oref(v, "blob").map(Some)
1480
            }
148124×
        };
148298×
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
148312×
            let e = o::array(r, "replace")?;
148412×
            if e.len() != 2 {
14850×
                return Err(ObjectError::Schema(
14860×
                    "replace: expected [node, records]".into(),
14870×
                ));
148812×
            }
148912×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
149012×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
149112×
            let mut recs = Vec::new();
149212×
            for rec in o::array(&e[1], "records")? {
149312×
                let x = o::array(rec, "record")?;
149412×
                if x.len() != 3 {
14950×
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
149612×
                }
149712×
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
1498
            }
149912×
            st.replaces.insert(node, recs);
1500
        }
150198×
        Ok(st)
150298×
    }
1503
15043143×
    pub fn validate(&self) -> Result<(), StateError> {
15058084×
        for (h, c) in &self.changes {
15068084×
            for d in &c.deps {
15075008×
                if !self.changes.contains_key(d) {
15080×
                    return Err(StateError::MissingDep(*d, *h));
15095008×
                }
1510
            }
1511
        }
15123143×
        Ok(())
15133143×
    }
1514
151511435×
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
151637386×
        for (i, op) in c.tree_ops.iter().enumerate() {
151737386×
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
151837386×
        }
151911435×
        if let Some(deferred) = self.deferred.as_mut() {
1520
            // History only: edits of files not built wait, grouped per file,
1521
            // with the texts of inserts read without their lines.
15226312×
            let mut texts = texts.into_iter();
15236312×
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
152436877×
            for e in c.edits {
152536877×
                match e {
1526589×
                    Edit::Replace { node, old, new } => {
1527589×
                        self.replaces.entry(node).or_default().push((h, old, new))
1528
                    }
152936288×
                    e => {
153036288×
                        let slot = per_node.entry(e.node()).or_default();
153134829×
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
153231254×
                            slot.1.extend(texts.next());
153331254×
                        }
153436288×
                        slot.0.push(e);
1535
                    }
1536
                }
1537
            }
153834406×
            for (node, (edits, node_texts)) in per_node {
153934406×
                match self.files.get_mut(&node) {
1540446×
                    Some(g) => {
1541446×
                        assert!(
1542446×
                            node_texts.is_empty(),
1543
                            "a change read without its text applied to a built graph"
1544
                        );
1545446×
                        apply_file_edits(Arc::make_mut(g), h, edits)
1546
                    }
154733960×
                    None => {
154833960×
                        let d = Arc::make_mut(deferred.entry(node).or_default());
154933960×
                        let b = d.body_mut();
155033960×
                        b.edits.push((h, edits));
155133960×
                        b.texts.extend(node_texts);
155233960×
                        d.key = Default::default();
155333960×
                    }
1554
                }
1555
            }
15566312×
            return;
15575123×
        }
15585123×
        assert!(
15595123×
            texts.is_empty(),
1560
            "a change read without its text applied to a full state"
1561
        );
15625123×
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
15635924×
        for e in c.edits {
15645924×
            match e {
1565
                Edit::Insert {
15664407×
                    node,
15674407×
                    after,
15684407×
                    before,
15694407×
                    lines,
15704407×
                } => {
15714407×
                    let idx = counters.entry(node).or_default();
15724407×
                    let first = *idx;
15734407×
                    *idx += lines.len() as u32;
15744407×
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
15754407×
                        h,
15764407×
                        first,
15774407×
                        vertex(after.resolve(h)),
15784407×
                        vertex(before.resolve(h)),
15794407×
                        lines,
15804407×
                    );
15814407×
                }
15821403×
                Edit::Delete { node, atoms } => {
15831403×
                    let g = Arc::make_mut(self.files.entry(node).or_default());
15841753×
                    for r in atoms {
15851753×
                        g.delete(h, &r.resolve(h));
15861753×
                    }
1587
                }
1588114×
                Edit::Replace { node, old, new } => {
1589114×
                    self.replaces.entry(node).or_default().push((h, old, new));
1590114×
                }
1591
            }
1592
        }
159311435×
    }
1594
1595
    /// Transitive dependencies of `h`, excluding `h` itself.
15969099×
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
15979099×
        if let Some(c) = self.closure.lock().unwrap().sets.get(h) {
15987639×
            return c.clone();
15991460×
        }
16001460×
        let mut out = HashSet::new();
16011460×
        let mut stack: Vec<ChangeHash> = self
16021460×
            .changes
16031460×
            .get(h)
16041460×
            .map(|c| c.deps.clone())
16051460×
            .unwrap_or_default();
160616991×
        while let Some(d) = stack.pop() {
160715531×
            if out.insert(d) {
160810996×
                if let Some(c) = self.changes.get(&d) {
160910996×
                    stack.extend(c.deps.iter().copied());
161010996×
                }
16114535×
            }
1612
        }
16131460×
        let rc = Arc::new(out);
16141460×
        let mut memo = self.closure.lock().unwrap();
16151460×
        if memo.held + rc.len() > CLOSURE_MEMO_HASHES {
16160×
            memo.sets.clear();
16170×
            memo.held = 0;
16181460×
        }
16191460×
        memo.held += rc.len();
16201460×
        memo.sets.insert(*h, rc.clone());
16211460×
        rc
16229099×
    }
1623
1624
    /// `h`'s level (see `levels`), worked out for it and its ancestors not
1625
    /// yet known, without recursion: histories are deeper than a stack. An
1626
    /// unknown change has level 0.
1627403807×
    fn level(&self, h: &ChangeHash) -> u32 {
1628403807×
        let mut levels = self.levels.lock().unwrap();
1629403807×
        if let Some(l) = levels.get(h) {
1630401775×
            return *l;
16312032×
        }
16322032×
        let mut stack: Vec<(ChangeHash, bool)> = vec![(*h, false)];
16336663×
        while let Some((c, expanded)) = stack.pop() {
16344631×
            if levels.contains_key(&c) {
163517×
                continue;
16364614×
            }
16374614×
            let deps: &[ChangeHash] = self
16384614×
                .changes
16394614×
                .get(&c)
16404614×
                .map(|m| m.deps.as_slice())
16414614×
                .unwrap_or(&[]);
16424614×
            if expanded {
16432307×
                let l = deps
16442307×
                    .iter()
16453114×
                    .map(|d| levels.get(d).map_or(0, |l| l + 1))
16462307×
                    .max()
16472307×
                    .unwrap_or(0);
16482307×
                levels.insert(c, l);
1649
            } else {
16502307×
                stack.push((c, true));
16513114×
                for d in deps {
16523114×
                    if !levels.contains_key(d) {
1653292×
                        stack.push((*d, false));
16542822×
                    }
1655
                }
1656
            }
1657
        }
16582032×
        levels[h]
1659403807×
    }
1660
1661
    /// Changes that no other change depends on directly, sorted.
1662397×
    pub fn heads(&self) -> Vec<ChangeHash> {
1663397×
        let depended: HashSet<&ChangeHash> =
16643434×
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
1665397×
        let mut heads: Vec<ChangeHash> = self
1666397×
            .changes
1667397×
            .keys()
16683434×
            .filter(|h| !depended.contains(h))
1669397×
            .copied()
1670397×
            .collect();
1671397×
        heads.sort();
1672397×
        heads
1673397×
    }
1674
1675
    /// Maximal elements among `hashes` (those not in the closure of another),
1676
    /// sorted. One walk down from all of them at once: whatever the walk
1677
    /// reaches is below some other element. Linear in the changes reached,
1678
    /// where comparing every pair's closures was quadratic in the number
1679
    /// of heads, which a bookmark of independent changes has many of.
16808297×
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
16818297×
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
16828297×
        let mut below: HashSet<ChangeHash> = HashSet::new();
16838297×
        let mut stack: Vec<ChangeHash> = set
16848297×
            .iter()
168514741×
            .filter_map(|h| self.changes.get(h))
168612542×
            .flat_map(|c| c.deps.iter().copied())
16878297×
            .collect();
168820900×
        while let Some(d) = stack.pop() {
168912603×
            if below.insert(d) {
16906160×
                if let Some(c) = self.changes.get(&d) {
16916160×
                    stack.extend(c.deps.iter().copied());
16926160×
                }
16936443×
            }
1694
        }
169514741×
        set.into_iter().filter(|h| !below.contains(h)).collect()
16968297×
    }
1697
16980×
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
16990×
        self.graph(node)
17000×
            .map(|g| g.materialize(self))
17010×
            .unwrap_or_default()
17020×
    }
1703
1704
    /// Live lines of a text node in materialized order.
170520×
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
170620×
        let Some(g) = self.graph(node) else {
17072×
            return vec![];
1708
        };
170918×
        let m = g.materialize(self);
171018×
        m.live_atoms()
171118×
            .into_iter()
171244×
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
171318×
            .collect()
171420×
    }
1715
1716
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
1717833×
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
1718833×
        let mut live: Vec<ObjectRef> = self
1719833×
            .live_replaces(node)
1720833×
            .into_iter()
1721833×
            .map(|(_, n)| n)
1722833×
            .collect();
1723833×
        live.sort();
1724833×
        live.dedup();
1725833×
        live
1726833×
    }
1727
1728
    /// The replace records whose blob is live, with the change that set it
1729
    /// (spec §9.3). A record's blob is superseded by a later replacement of
1730
    /// that blob: one whose change depends on the record's change, as every
1731
    /// replacement depends on the change that made its old blob current
1732
    /// (§8.1). Two replacements that do not know each other both stay live
1733
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
1734
    /// A replacement without that dependency, from before the rule, is read
1735
    /// as before: it supersedes every record that did not come after it.
1736870×
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
1737870×
        let Some(rs) = self.replaces.get(node) else {
17380×
            return vec![];
1739
        };
1740870×
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
174111×
            rs.iter()
174244×
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && self.closure(s).contains(q))
174311×
        };
1744870×
        rs.iter()
17451004×
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
17461004×
            .filter(|(c, n)| {
17471284×
                !rs.iter().any(|(s, o, _)| {
17481284×
                    s != c
1749345×
                        && *o == Some(*n)
1750121×
                        && (self.closure(s).contains(c)
175111×
                            || (!knows_its_old(s, n) && !self.closure(c).contains(s)))
17521284×
                })
17531004×
            })
1754870×
            .collect()
1755870×
    }
1756
1757
    /// Short label for conflict markers: `changeid-prefix "message"`.
1758913×
    pub fn label(&self, h: &ChangeHash) -> String {
1759913×
        match self.changes.get(h) {
1760913×
            Some(c) => format!(
1761
                "{} \"{}\"",
1762913×
                c.change_id.short(8),
1763913×
                c.message.lines().next().unwrap_or("")
1764
            ),
17650×
            None => format!("#{}", h.short(12)),
1766
        }
1767913×
    }
1768
1769
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1770
    /// are not part of any conflict region in order, every live atom that is
1771
    /// part of a region, and every change that contributed to a region.
1772
    /// The changes that introduced the live blobs of an opaque node, for a
1773
    /// replace conflict (spec §9.3).
17742×
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
17752×
        let mut out: Vec<ChangeHash> = Vec::new();
17766×
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
17776×
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
17784×
                out.push(*h);
17794×
            }
1780
        }
17812×
        out.sort();
17822×
        out
17832×
    }
1784
178527×
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
178627×
        let mut out = ConflictRegions::default();
178727×
        let Some(g) = self.graph(node) else {
17880×
            return out;
1789
        };
179027×
        let m = g.materialize(self);
179127×
        let mut contributors = BTreeSet::new();
179263×
        for seg in &m.segments {
179363×
            match seg {
179436×
                crate::graph::Segment::Lines(atoms) => {
179536×
                    for a in atoms {
179636×
                        out.plain
179736×
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
179836×
                    }
1799
                }
180027×
                crate::graph::Segment::Conflict(sides) => {
180154×
                    for side in sides {
180256×
                        for a in side {
180356×
                            out.region_atoms.push(*a);
180456×
                            contributors.insert(a.0);
180556×
                        }
1806
                    }
1807
                }
18080×
                crate::graph::Segment::Zombie { deleted, inserted } => {
18090×
                    for a in deleted {
18100×
                        contributors.insert(a.0);
18110×
                        contributors.extend(g.deleters(a).copied());
18120×
                    }
18130×
                    for a in inserted {
18140×
                        out.region_atoms.push(*a);
18150×
                        contributors.insert(a.0);
18160×
                    }
1817
                }
1818
            }
1819
        }
182027×
        out.contributors = contributors.into_iter().collect();
182127×
        out
182227×
    }
1823
182423977×
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
182523977×
        let Some(g) = self.graph(node) else {
1826339×
            return (Vec::new(), Materialized::default());
1827
        };
182823638×
        let m = g.materialize(self);
182923638×
        let bytes = g.render(&m, &|h| self.label(h));
183023638×
        (bytes, m)
183123977×
    }
1832
1833
    /// Every file rendered, in parallel: files are independent, and
1834
    /// rendering them is most of a snapshot's cost in a large tree.
18352168×
    pub fn materialize(&self) -> Snapshot {
1836
        use rayon::prelude::*;
18372168×
        self.require_full("materializing a state");
18382168×
        let tree = self.tree.view();
18392168×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
18402168×
        let rendered: Vec<(String, FileState)> = entries
18412168×
            .par_iter()
184216212×
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
18432168×
            .collect();
18442168×
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
18452168×
        Snapshot {
18462168×
            tree,
18472168×
            files,
18482168×
            unrendered: BTreeSet::new(),
18492168×
        }
18502168×
    }
1851
1852
    /// Like [`State::materialize`], leaving the text files of nodes in
1853
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
1854
    /// file's graph must be loaded. For a caller that already knows those
1855
    /// files are unchanged and not conflicted.
185632×
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
185745×
        self.materialize_leaving(|_, e| skip.contains(&e.node))
185832×
    }
1859
1860
    /// As [`State::materialize_except`], rendering only the text files at
1861
    /// `render` (a few, where the caller knows the rest unchanged).
1862784×
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
18637800×
        self.materialize_leaving(|p, _| !render.contains(p))
1864784×
    }
1865
1866
    /// As [`State::materialize_except`], rendering only the text files of
1867
    /// the nodes in `render` (a change's edited files), without a set of
1868
    /// every other file to leave out.
1869217×
    pub fn materialize_nodes(&self, render: &HashSet<NodeId>) -> Snapshot {
1870584×
        self.materialize_leaving(|_, e| !render.contains(&e.node))
1871217×
    }
1872
18731033×
    fn materialize_leaving(
18741033×
        &self,
18751033×
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
18761033×
    ) -> Snapshot {
1877
        use rayon::prelude::*;
18781033×
        let tree = self.tree.view();
18791033×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
18801033×
        let rendered: Vec<(String, FileState, bool)> = entries
18811033×
            .par_iter()
18828806×
            .map(|(path, e)| {
18838806×
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
18844605×
                    let f = FileState {
18854605×
                        node: e.node,
18864605×
                        kind: e.kind,
18874605×
                        mode: e.mode,
18884605×
                        content: FileContent::Text {
18894605×
                            bytes: Vec::new(),
18904605×
                            materialized: Materialized::default(),
18914605×
                        },
18924605×
                    };
18934605×
                    (path.to_string(), f, true)
1894
                } else {
18954201×
                    (path.to_string(), self.file_state(e), false)
1896
                }
18978806×
            })
18981033×
            .collect();
1899
        // In the view's path order, so the maps are built without searching.
19001033×
        let unrendered: BTreeSet<String> = rendered
19011033×
            .iter()
19021033×
            .filter(|(_, _, skipped)| *skipped)
19034605×
            .map(|(p, _, _)| p.clone())
19041033×
            .collect();
19051033×
        let files: BTreeMap<String, FileState> =
19068806×
            rendered.into_iter().map(|(p, f, _)| (p, f)).collect();
19071033×
        Snapshot {
19081033×
            tree,
19091033×
            files,
19101033×
            unrendered,
19111033×
        }
19121033×
    }
1913
1914
    /// A snapshot of only `paths` (those `view` has), `view` being this
1915
    /// state's tree view: for a caller that works from what changed. The
1916
    /// graphs of those text files must be loaded.
191742×
    pub fn materialize_paths<'p>(
191842×
        &self,
191942×
        view: crate::tree::TreeView,
192042×
        paths: impl IntoIterator<Item = &'p str>,
192142×
    ) -> Snapshot {
192242×
        let files = paths
192342×
            .into_iter()
192471×
            .filter_map(|p| Some((p.to_string(), self.file_state(view.entries.get(p)?))))
192542×
            .collect();
192642×
        Snapshot {
192742×
            tree: view,
192842×
            files,
192942×
            unrendered: BTreeSet::new(),
193042×
        }
193142×
    }
1932
1933
    /// The state of one tree entry: a directory, an opaque file's live
1934
    /// blobs, or a text file rendered from its graph (which must be built).
19350×
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
19360×
        self.file_state(e)
19370×
    }
1938
193920464×
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
1940
        {
194120464×
            let content = match e.kind {
19421436×
                NodeKind::Dir => FileContent::Dir,
1943100×
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
1944100×
                    blobs: self.live_blobs(&e.node),
1945100×
                },
1946526×
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
1947526×
                    blobs: self.live_blobs(&e.node),
1948526×
                },
1949
                NodeKind::File => {
195018402×
                    let (bytes, materialized) = self.render_file(&e.node);
195118402×
                    FileContent::Text {
195218402×
                        bytes,
195318402×
                        materialized,
195418402×
                    }
1955
                }
1956
            };
195720464×
            FileState {
195820464×
                node: e.node,
195920464×
                kind: e.kind,
196020464×
                mode: e.mode,
196120464×
                content,
196220464×
            }
1963
        }
196420464×
    }
1965
}
1966
1967
impl DepOracle for State {
1968
    /// Whether `a` depends on `b`, by a walk down from `a` that stops at
1969
    /// changes no higher than `b`: they cannot have `b` below them. Nothing
1970
    /// of the walk is kept, so asking about many pairs costs no more memory
1971
    /// than one walk (#25); a closure already memoised answers at once.
197267576×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
197367576×
        if a == b {
1974800×
            return true;
197566776×
        }
197666776×
        if let Some(c) = self.closure.lock().unwrap().sets.get(a) {
19770×
            return c.contains(b);
197866776×
        }
197966776×
        if !self.changes.contains_key(b) {
1980800×
            return false;
198165976×
        }
198265976×
        let lb = self.level(b);
198365976×
        if self.level(a) <= lb {
198436182×
            return false;
198529794×
        }
198629794×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
198729794×
        let mut stack: Vec<ChangeHash> = self
198829794×
            .changes
198929794×
            .get(a)
199029794×
            .map(|m| m.deps.clone())
199129794×
            .unwrap_or_default();
1992360914×
        while let Some(c) = stack.pop() {
1993341576×
            if c == *b {
199410456×
                return true;
1995331120×
            }
1996331120×
            if !seen.insert(c) || self.level(&c) <= lb {
1997222482×
                continue;
1998108638×
            }
1999108638×
            if let Some(m) = self.changes.get(&c) {
2000108638×
                stack.extend(m.deps.iter().copied());
2001108638×
            }
2002
        }
200319338×
        false
200467576×
    }
2005
}
2006
2007
#[cfg(test)]
2008
mod tests {
2009
    use super::*;
2010
    use crate::ids::ChangeId;
2011
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
2012
20132023×
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
20142023×
        let mut c = Change {
20152023×
            version: crate::objects::CHANGE_VERSION,
20162023×
            change_id: ChangeId::random(),
20172023×
            deps,
20182023×
            author: ObjectRef::ZERO,
20192023×
            hlc: Hlc {
20202023×
                wall_ms: 1,
20212023×
                logical: 0,
20222023×
            },
20232023×
            message: "m".into(),
20242023×
            tree_ops,
20252023×
            edits,
20262023×
            kind: ChangeKind::Normal,
20272023×
        };
20282023×
        c.normalize();
20292023×
        c
20302023×
    }
2031
2032
    #[test]
20331×
    fn build_edit_and_materialize() {
20341×
        let mut st = State::new();
20351×
        let f = NodeId::random();
20361×
        let c1 = change(
20371×
            vec![],
20381×
            vec![TreeOp::AddNode {
20391×
                node: f,
20401×
                kind: NodeKind::File,
20411×
                mode: Mode::TEXT,
20421×
                parent: NodeId::ROOT,
20431×
                name: "a.txt".into(),
20441×
            }],
20451×
            vec![Edit::Insert {
20461×
                node: f,
20471×
                after: AtomRef::Start,
20481×
                before: AtomRef::End,
20491×
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
20501×
            }],
2051
        );
20521×
        let h1 = st.add(c1).unwrap();
2053
        // Depends on h1: append a line and delete "one".
20541×
        let c2 = change(
20551×
            vec![h1],
20561×
            vec![],
20571×
            vec![
20581×
                Edit::Delete {
20591×
                    node: f,
20601×
                    atoms: vec![AtomRange {
20611×
                        change: h1,
20621×
                        from: 0,
20631×
                        to: 1,
20641×
                    }],
20651×
                },
20661×
                Edit::Insert {
20671×
                    node: f,
20681×
                    after: AtomRef::Atom {
20691×
                        change: h1,
20701×
                        index: 1,
20711×
                    },
20721×
                    before: AtomRef::End,
20731×
                    lines: vec![b"three\n".to_vec()].into(),
20741×
                },
2075
            ],
2076
        );
20771×
        let h2 = st.add(c2).unwrap();
20781×
        assert_eq!(st.heads(), vec![h2]);
20791×
        assert!(st.depends_on(&h2, &h1));
20801×
        assert!(!st.depends_on(&h1, &h2));
20811×
        let snap = st.materialize();
20821×
        assert!(!snap.is_conflicted());
20831×
        let a = &snap.files["a.txt"];
20841×
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
20851×
        assert_eq!(st.live_lines(&f).len(), 2);
20861×
    }
2087
2088
    #[test]
20891×
    fn missing_dependency_is_rejected() {
20901×
        let mut st = State::new();
20911×
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
20921×
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
20931×
    }
2094
2095
    #[test]
20961×
    fn self_references_and_multi_insert_indexing() {
20971×
        let mut st = State::new();
20981×
        let f = NodeId::random();
20991×
        let me = OpRef {
21001×
            change: ObjectRef::ZERO,
21011×
            index: 0,
21021×
        };
21031×
        let c1 = change(
21041×
            vec![],
21051×
            vec![
21061×
                TreeOp::AddNode {
21071×
                    node: f,
21081×
                    kind: NodeKind::File,
21091×
                    mode: Mode::TEXT,
21101×
                    parent: NodeId::ROOT,
21111×
                    name: "x".into(),
21121×
                },
21131×
                TreeOp::SetMode {
21141×
                    node: f,
21151×
                    old: me,
21161×
                    mode: Mode {
21171×
                        exec: true,
21181×
                        opaque: false,
21191×
                    },
21201×
                },
2121
            ],
21221×
            vec![
21231×
                Edit::Insert {
21241×
                    node: f,
21251×
                    after: AtomRef::Start,
21261×
                    before: AtomRef::End,
21271×
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
21281×
                },
2129
                // Insert between the two lines just inserted, using self references.
21301×
                Edit::Insert {
21311×
                    node: f,
21321×
                    after: AtomRef::Atom {
21331×
                        change: ObjectRef::ZERO,
21341×
                        index: 0,
21351×
                    },
21361×
                    before: AtomRef::Atom {
21371×
                        change: ObjectRef::ZERO,
21381×
                        index: 1,
21391×
                    },
21401×
                    lines: vec![b"b\n".to_vec()].into(),
21411×
                },
2142
            ],
2143
        );
21441×
        st.add(c1).unwrap();
21451×
        let snap = st.materialize();
21461×
        let x = &snap.files["x"];
21471×
        assert_eq!(
2148
            x.mode,
2149
            Mode {
2150
                exec: true,
2151
                opaque: false
2152
            }
2153
        );
21541×
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
21551×
    }
2156
2157
    #[test]
21581×
    fn opaque_replace_and_conflict() {
21591×
        let mut st = State::new();
21601×
        let f = NodeId::random();
21611×
        let b1 = ObjectRef([1; 32]);
21621×
        let b2 = ObjectRef([2; 32]);
21631×
        let b3 = ObjectRef([3; 32]);
21641×
        let h1 = st
21651×
            .add(change(
21661×
                vec![],
21671×
                vec![TreeOp::AddNode {
21681×
                    node: f,
21691×
                    kind: NodeKind::File,
21701×
                    mode: Mode::OPAQUE,
21711×
                    parent: NodeId::ROOT,
21721×
                    name: "img".into(),
21731×
                }],
21741×
                vec![Edit::Replace {
21751×
                    node: f,
21761×
                    old: None,
21771×
                    new: Some(b1),
21781×
                }],
2179
            ))
21801×
            .unwrap();
21811×
        assert_eq!(st.live_blobs(&f), vec![b1]);
21821×
        st.add(change(
21831×
            vec![h1],
21841×
            vec![],
21851×
            vec![Edit::Replace {
21861×
                node: f,
21871×
                old: Some(b1),
21881×
                new: Some(b2),
21891×
            }],
2190
        ))
21911×
        .unwrap();
21921×
        st.add(change(
21931×
            vec![h1],
21941×
            vec![],
21951×
            vec![Edit::Replace {
21961×
                node: f,
21971×
                old: Some(b1),
21981×
                new: Some(b3),
21991×
            }],
2200
        ))
22011×
        .unwrap();
22021×
        let snap = st.materialize();
22031×
        assert!(snap.is_conflicted());
22041×
        assert!(
22051×
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2206
        );
22071×
    }
2208
2209
    #[test]
22101×
    fn checkpoint_payload_round_trip_and_replay() {
22111×
        let mut st = State::new();
22121×
        let f = NodeId::random();
22131×
        let h1 = st
22141×
            .add(change(
22151×
                vec![],
22161×
                vec![TreeOp::AddNode {
22171×
                    node: f,
22181×
                    kind: NodeKind::File,
22191×
                    mode: Mode::TEXT,
22201×
                    parent: NodeId::ROOT,
22211×
                    name: "a".into(),
22221×
                }],
22231×
                vec![Edit::Insert {
22241×
                    node: f,
22251×
                    after: AtomRef::Start,
22261×
                    before: AtomRef::End,
22271×
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
22281×
                }],
2229
            ))
22301×
            .unwrap();
22311×
        let h2 = st
22321×
            .add(change(
22331×
                vec![h1],
22341×
                vec![],
22351×
                vec![Edit::Delete {
22361×
                    node: f,
22371×
                    atoms: vec![AtomRange {
22381×
                        change: h1,
22391×
                        from: 0,
22401×
                        to: 1,
22411×
                    }],
22421×
                }],
2243
            ))
22441×
            .unwrap();
22451×
        let payload = st.checkpoint_payload();
22461×
        let back = State::from_checkpoint_payload(&payload).unwrap();
22471×
        assert_eq!(back.len(), 2);
22481×
        assert_eq!(back.heads(), vec![h2]);
22491×
        assert_eq!(back.get(&h1).unwrap().message, "m");
22501×
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2251
        // Replaying a further change onto the restored state equals a full build.
22521×
        let c3 = change(
22531×
            vec![h2],
22541×
            vec![],
22551×
            vec![Edit::Insert {
22561×
                node: f,
22571×
                after: AtomRef::Atom {
22581×
                    change: h1,
22591×
                    index: 1,
22601×
                },
22611×
                before: AtomRef::End,
22621×
                lines: vec![b"3\n".to_vec()].into(),
22631×
            }],
2264
        );
22651×
        let mut full = st.clone();
22661×
        full.add(c3.clone()).unwrap();
22671×
        let mut restored = back;
22681×
        restored.add(c3).unwrap();
22691×
        let (a, b) = (full.materialize(), restored.materialize());
22701×
        assert_eq!(
22711×
            a.files.keys().collect::<Vec<_>>(),
22721×
            b.files.keys().collect::<Vec<_>>()
2273
        );
22741×
        assert_eq!(a.files["a"].content, b.files["a"].content);
22751×
        assert!(
22761×
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2277
        );
22781×
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
22791×
    }
2280
2281
    /// History-only states (O10f): the same state as a full load once its
2282
    /// graphs are built, by replay and from a version 2 checkpoint with
2283
    /// later changes; unloaded graphs are never read as empty.
2284
    #[test]
22851×
    fn graph_keys_change_exactly_when_a_graph_does() {
22861×
        let (f, g) = (NodeId::random(), NodeId::random());
22871×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
22882×
            node,
22892×
            kind: NodeKind::File,
2290
            mode: Mode::TEXT,
2291
            parent: NodeId::ROOT,
22922×
            name: name.into(),
22932×
        };
22941×
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
22954×
            node,
22964×
            after: AtomRef::Start,
22974×
            before: AtomRef::End,
22984×
            lines: vec![line.to_vec()].into(),
22994×
        };
23001×
        let c1 = change(
23011×
            vec![],
23021×
            vec![add(f, "f"), add(g, "g")],
23031×
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2304
        );
23051×
        let h1 = c1.hash();
23061×
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
23071×
        let h2 = c2.hash();
23081×
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
23096×
        let load = |cs: &[&Change]| {
23106×
            let mut st = State::new_history_only();
231110×
            for c in cs {
231210×
                st.add((*c).clone()).unwrap();
231310×
            }
23146×
            st
23156×
        };
23161×
        let s1 = load(&[&c1]);
23171×
        let s2 = load(&[&c1, &c2]);
23181×
        let s3 = load(&[&c1, &c2, &c3]);
231918×
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
23201×
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
23211×
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
23221×
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
23231×
        assert_ne!(key(&s2, &f), key(&s3, &f));
23241×
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
23251×
        let mut built = load(&[&c1]);
23261×
        built
23271×
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
23281×
            .unwrap();
23291×
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
23301×
        let mut full = State::new();
23311×
        full.add(c1.clone()).unwrap();
23321×
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2333
2334
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2335
        // or inline values: stable across loads, changed by later edits.
23361×
        let graphs = full.checkpoint_file_graphs();
23371×
        let index = full.checkpoint_index(&graphs, |enc| {
23380×
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
23390×
        });
23408×
        let cp = |extra: &[&Change]| {
23418×
            let mut st = State::from_checkpoint_history(&index).unwrap();
23428×
            for c in extra {
23435×
                st.add((*c).clone()).unwrap();
23445×
            }
23458×
            st
23468×
        };
23471×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
23481×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
23491×
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
23501×
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2351
2352
        // Partial rendering: skipped files are listed and empty, the others
2353
        // render as in a full state.
23541×
        let mut part = load(&[&c1, &c2]);
23551×
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
23561×
            .unwrap();
23571×
        let snap = part.materialize_except(&[f].into_iter().collect());
23581×
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
23591×
        let mut whole = State::new();
23601×
        whole.add(c1.clone()).unwrap();
23611×
        whole.add(c2.clone()).unwrap();
23621×
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
23631×
        assert!(
23641×
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2365
        );
23661×
    }
2367
2368
    #[test]
23691×
    fn history_only_states_build_the_same_graphs_on_demand() {
23701×
        let small = NodeId::random();
23711×
        let big = NodeId::random();
23721×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
23732×
            node,
23742×
            kind: NodeKind::File,
2375
            mode: Mode::TEXT,
2376
            parent: NodeId::ROOT,
23772×
            name: name.into(),
23782×
        };
23791×
        let lines: crate::lines::Lines = (0..300)
2380300×
            .map(|i| format!("line {i}\n").into_bytes())
23811×
            .collect();
23821×
        let c1 = change(
23831×
            vec![],
23841×
            vec![add(small, "small"), add(big, "big")],
23851×
            vec![
23861×
                Edit::Insert {
23871×
                    node: small,
23881×
                    after: AtomRef::Start,
23891×
                    before: AtomRef::End,
23901×
                    lines: vec![b"x\n".to_vec()].into(),
23911×
                },
23921×
                Edit::Insert {
23931×
                    node: big,
23941×
                    after: AtomRef::Start,
23951×
                    before: AtomRef::End,
23961×
                    lines,
23971×
                },
2398
            ],
2399
        );
24001×
        let h1 = c1.hash();
24011×
        let c2 = change(
24021×
            vec![h1],
24031×
            vec![],
24041×
            vec![
24051×
                Edit::Delete {
24061×
                    node: big,
24071×
                    atoms: vec![AtomRange {
24081×
                        change: h1,
24091×
                        from: 2,
24101×
                        to: 9,
24111×
                    }],
24121×
                },
24131×
                Edit::Insert {
24141×
                    node: big,
24151×
                    after: AtomRef::Atom {
24161×
                        change: h1,
24171×
                        index: 20,
24181×
                    },
24191×
                    before: AtomRef::Atom {
24201×
                        change: h1,
24211×
                        index: 21,
24221×
                    },
24231×
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
24241×
                },
24251×
                Edit::Insert {
24261×
                    node: small,
24271×
                    after: AtomRef::Atom {
24281×
                        change: h1,
24291×
                        index: 0,
24301×
                    },
24311×
                    before: AtomRef::End,
24321×
                    lines: vec![b"y\n".to_vec()].into(),
24331×
                },
2434
            ],
2435
        );
24361×
        let h2 = c2.hash();
24371×
        let c3 = change(
24381×
            vec![h2],
24391×
            vec![],
24401×
            vec![Edit::Delete {
24411×
                node: small,
24421×
                atoms: vec![AtomRange {
24431×
                    change: h1,
24441×
                    from: 0,
24451×
                    to: 1,
24461×
                }],
24471×
            }],
2448
        );
2449
24501×
        let mut full = State::new();
24513×
        for c in [&c1, &c2, &c3] {
24523×
            full.add(c.clone()).unwrap();
24533×
        }
2454
        // By replay: nothing built until asked, then exactly the full graphs.
24551×
        let mut hist = State::new_history_only();
24563×
        for c in [&c1, &c2, &c3] {
24573×
            hist.add(c.clone()).unwrap();
24583×
        }
24591×
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
24601×
        assert_eq!(hist.len(), 3);
24611×
        hist.load_graphs(
24621×
            &[big],
24630×
            |_| unreachable!("no checkpoint"),
24640×
            |_| unreachable!(),
2465
        )
24661×
        .unwrap();
24671×
        assert_eq!(
24681×
            hist.render_file(&big).0,
24691×
            full.render_file(&big).0,
2470
            "one file on its own"
2471
        );
24721×
        assert!(!hist.is_full());
24731×
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
24741×
            .unwrap();
24751×
        assert!(hist.is_full());
24761×
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2477
2478
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
24791×
        let mut base = State::new();
24801×
        base.add(c1.clone()).unwrap();
24811×
        base.add(c2.clone()).unwrap();
24821×
        let graphs = base.checkpoint_file_graphs();
24831×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
24841×
        let index = base.checkpoint_index(&graphs, |enc| {
24851×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
24861×
            blobs.insert(r, enc.to_vec());
24871×
            r
24881×
        });
24891×
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
24901×
        from_cp.add(c3.clone()).unwrap();
24911×
        assert!(!from_cp.is_full());
24921×
        let mut fetched = 0;
24931×
        from_cp
24941×
            .load_graphs(
24951×
                &[small, big],
24961×
                |refs| {
24971×
                    fetched += refs.len();
24981×
                    refs.iter()
24991×
                        .map(|r| {
25001×
                            blobs
25011×
                                .get(r)
25021×
                                .cloned()
25031×
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
25041×
                        })
25051×
                        .collect()
25061×
                },
25070×
                |_| unreachable!(),
2508
            )
25091×
            .unwrap();
25101×
        assert_eq!(
2511
            fetched, 1,
2512
            "the large graph's blob, in one batch; the small one was inline"
2513
        );
25141×
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
25151×
    }
2516
2517
    #[test]
2518
    #[should_panic(expected = "was not loaded")]
25191×
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
25201×
        let f = NodeId::random();
25211×
        let mut st = State::new_history_only();
25221×
        st.add(change(
25231×
            vec![],
25241×
            vec![TreeOp::AddNode {
25251×
                node: f,
25261×
                kind: NodeKind::File,
25271×
                mode: Mode::TEXT,
25281×
                parent: NodeId::ROOT,
25291×
                name: "a".into(),
25301×
            }],
25311×
            vec![Edit::Insert {
25321×
                node: f,
25331×
                after: AtomRef::Start,
25341×
                before: AtomRef::End,
25351×
                lines: vec![b"a\n".to_vec()].into(),
25361×
            }],
2537
        ))
25381×
        .unwrap();
25391×
        st.render_file(&f);
25401×
    }
2541
2542
    #[test]
2543
    #[should_panic(expected = "needs every file graph")]
25441×
    fn materializing_a_history_only_state_is_refused() {
25451×
        let f = NodeId::random();
25461×
        let mut st = State::new_history_only();
25471×
        st.add(change(
25481×
            vec![],
25491×
            vec![TreeOp::AddNode {
25501×
                node: f,
25511×
                kind: NodeKind::File,
25521×
                mode: Mode::TEXT,
25531×
                parent: NodeId::ROOT,
25541×
                name: "a".into(),
25551×
            }],
25561×
            vec![Edit::Insert {
25571×
                node: f,
25581×
                after: AtomRef::Start,
25591×
                before: AtomRef::End,
25601×
                lines: vec![b"a\n".to_vec()].into(),
25611×
            }],
2562
        ))
25631×
        .unwrap();
25641×
        st.materialize();
25651×
    }
2566
2567
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
2568
    /// blob; the state read back is the same as from version 1.
2569
    #[test]
25701×
    fn checkpoint_index_round_trip_matches_version_1() {
25711×
        let mut st = State::new();
25721×
        let small = NodeId::random();
25731×
        let big = NodeId::random();
25741×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
25752×
            node,
25762×
            kind: NodeKind::File,
2577
            mode: Mode::TEXT,
2578
            parent: NodeId::ROOT,
25792×
            name: name.into(),
25802×
        };
25811×
        let big_lines: crate::lines::Lines = (0..400)
2582400×
            .map(|i| format!("line {i} of a long file\n").into_bytes())
25831×
            .collect();
25841×
        let h1 = st
25851×
            .add(change(
25861×
                vec![],
25871×
                vec![add(small, "small"), add(big, "big")],
25881×
                vec![
25891×
                    Edit::Insert {
25901×
                        node: small,
25911×
                        after: AtomRef::Start,
25921×
                        before: AtomRef::End,
25931×
                        lines: vec![b"x\n".to_vec()].into(),
25941×
                    },
25951×
                    Edit::Insert {
25961×
                        node: big,
25971×
                        after: AtomRef::Start,
25981×
                        before: AtomRef::End,
25991×
                        lines: big_lines,
26001×
                    },
2601
                ],
2602
            ))
26031×
            .unwrap();
26041×
        st.add(change(
26051×
            vec![h1],
26061×
            vec![],
26071×
            vec![Edit::Delete {
26081×
                node: big,
26091×
                atoms: vec![AtomRange {
26101×
                    change: h1,
26111×
                    from: 3,
26121×
                    to: 7,
26131×
                }],
26141×
            }],
2615
        ))
26161×
        .unwrap();
2617
26181×
        let graphs = st.checkpoint_file_graphs();
26191×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
26201×
        let index = st.checkpoint_index(&graphs, |enc| {
26211×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
26221×
            blobs.insert(r, enc.to_vec());
26231×
            r
26241×
        });
26251×
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
26261×
        assert_eq!(
26271×
            State::checkpoint_graph_refs(&index).unwrap(),
26281×
            blobs.keys().copied().collect::<Vec<_>>()
2629
        );
26301×
        assert!(
26311×
            State::checkpoint_graph_refs(&st.checkpoint_payload())
26321×
                .unwrap()
26331×
                .is_empty(),
2634
            "version 1 names none"
2635
        );
26361×
        assert!(index.len() < st.checkpoint_payload().len());
2637
26381×
        let back = State::from_checkpoint(&index, |refs| {
26391×
            refs.iter()
26401×
                .map(|r| {
26411×
                    blobs
26421×
                        .get(r)
26431×
                        .cloned()
26441×
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
26451×
                })
26461×
                .collect()
26471×
        })
26481×
        .unwrap();
26491×
        assert_eq!(
26501×
            back.checkpoint_payload(),
26511×
            st.checkpoint_payload(),
2652
            "the same state as version 1"
2653
        );
26541×
        assert_eq!(
26551×
            back.materialize().files["big"].content,
26561×
            st.materialize().files["big"].content
2657
        );
2658
        // Deterministic: the same state gives the same index.
26591×
        assert_eq!(
26601×
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
26611×
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
26621×
            }),
2663
            index
2664
        );
2665
        // A missing graph blob is an error, not an empty file.
26661×
        assert!(
26671×
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
2668
        );
26691×
        assert!(
26701×
            State::from_checkpoint_payload(&index).is_err(),
2671
            "version 2 needs its blobs"
2672
        );
2673
        // Version 1 payloads still read, and unknown versions do not.
26741×
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
26751×
        let mut v3 = cbor::decode(&index).unwrap();
26761×
        if let Value::Map(m) = &mut v3 {
26771×
            m.insert(0, Value::Uint(3));
26781×
        }
26791×
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
26801×
    }
2681
2682
    #[test]
26831×
    fn maximal_elements() {
26841×
        let mut st = State::new();
26851×
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
26861×
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
26871×
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
26881×
        let mut m = st.maximal(&[h1, h2, h3]);
26891×
        m.sort();
26901×
        let mut want = vec![h2, h3];
26911×
        want.sort();
26921×
        assert_eq!(m, want);
26931×
        assert_eq!(st.heads(), want);
26941×
    }
2695
2696
    /// The bounded walk of `depends_on` agrees with the closure on random
2697
    /// graphs, and the memo stays within its bound.
2698
    #[test]
26991×
    fn depends_on_matches_the_closure() {
2700
        use rand::{Rng, SeedableRng};
27011×
        let mut rng = rand::rngs::StdRng::seed_from_u64(11);
27021×
        for _ in 0..10 {
270310×
            let mut st = State::new();
270410×
            let mut all: Vec<ChangeHash> = Vec::new();
270510×
            for _ in 0..80 {
2706800×
                let deps: Vec<ChangeHash> =
270731600×
                    all.iter().copied().filter(|_| rng.gen_bool(0.06)).collect();
2708800×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2709
            }
271010×
            let unknown = ObjectRef([0xee; 32]);
2711800×
            for a in &all {
2712800×
                let want = st.closure(a).clone();
2713800×
                st.closure.lock().unwrap().sets.clear();
2714800×
                st.closure.lock().unwrap().held = 0;
271564800×
                for b in all.iter().chain([&unknown]) {
271664800×
                    assert_eq!(
271764800×
                        st.depends_on(a, b),
271864800×
                        a == b || want.contains(b),
2719
                        "{a:?} on {b:?}"
2720
                    );
2721
                }
2722
            }
272310×
            assert!(st.closure.lock().unwrap().held <= CLOSURE_MEMO_HASHES);
2724
        }
27251×
    }
2726
2727
    /// The one-walk `maximal` agrees with the definition (not in the
2728
    /// closure of another element) on random graphs, with repeated and
2729
    /// unknown hashes among the input.
2730
    #[test]
27311×
    fn maximal_matches_its_definition() {
2732
        use rand::{Rng, SeedableRng};
27331×
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
27341×
        for _ in 0..20 {
273520×
            let mut st = State::new();
273620×
            let mut all: Vec<ChangeHash> = Vec::new();
273720×
            for _ in 0..60 {
27381200×
                let deps: Vec<ChangeHash> =
273935400×
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
27401200×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
2741
            }
274220×
            let mut pick: Vec<ChangeHash> =
27431200×
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
274420×
            pick.extend(pick.clone().into_iter().take(3));
274520×
            pick.push(ObjectRef([0xee; 32]));
274620×
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
274720×
            let want: Vec<ChangeHash> = set
274820×
                .iter()
27498327×
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
275020×
                .copied()
275120×
                .collect();
275220×
            assert_eq!(st.maximal(&pick), want);
275320×
            assert_eq!(st.maximal(&all), st.heads());
2754
        }
27551×
    }
2756
}