OXYGENHUB

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

2250 of 2428 lines run, 485 of 686 functions · run #418 on main · run missed

1
//! A state: a dependency-closed set of changes, applied to a tree graph and
2
//! per-node file graphs (spec §8.3), with materialization (spec §9.5, §11).
3
4
use crate::cbor::{self, Value};
5
use crate::graph::{AtomKey, DepOracle, FileGraph, Materialized, Vertex};
6
use crate::hash::KeyId;
7
use crate::hash::{ChangeHash, ObjectRef};
8
use crate::ids::NodeId;
9
use crate::objects::{
10
    self as o, AtomRef, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, ObjectError, TreeOp,
11
};
12
use crate::tree::{TreeGraph, TreeView};
13
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
14
use std::sync::Arc;
15
16
/// Checkpoint payload version 2 (spec §11): file graphs by reference.
17
pub const CHECKPOINT_INDEX_VERSION: u64 = 2;
18
19
/// A file graph encoded in fewer bytes stays inline in a version 2 index.
20
pub const INLINE_GRAPH_LIMIT: usize = 2048;
21
22
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
23
pub enum StateError {
24
    #[error("change {1} depends on {0}, which is not in the state")]
25
    MissingDep(ChangeHash, ChangeHash),
26
}
27
28
/// One `Replace` edit: `(change, old blob, new blob)`.
29
type ReplaceRecord = (ChangeHash, Option<ObjectRef>, Option<ObjectRef>);
30
31
/// What a state remembers about a change: everything but its operations,
32
/// which live in the graphs once applied (and in the store).
33
#[derive(Clone, Debug, PartialEq, Eq)]
34
pub struct ChangeMeta {
35
    pub change_id: crate::ids::ChangeId,
36
    pub deps: Vec<ChangeHash>,
37
    pub author: KeyId,
38
    pub hlc: Hlc,
39
    pub message: String,
40
    pub kind: ChangeKind,
41
}
42
43
/// The log's order of changes: newest first by clock, then by hash, so
44
/// it is total.
451040×
pub fn log_order(a: (&ChangeHash, &Hlc), b: (&ChangeHash, &Hlc)) -> std::cmp::Ordering {
461040×
    b.1.cmp(a.1).then(b.0.cmp(a.0))
471040×
}
48
49
impl ChangeMeta {
50
    /// In the flat layout of local indexes and caches ([`crate::flat`]).
516531×
    pub(crate) fn write_flat(&self, w: &mut crate::flat::Writer) {
526531×
        w.fixed(&self.change_id.0);
536531×
        w.count(self.deps.len());
546531×
        for d in &self.deps {
556035×
            w.object(d);
566035×
        }
576531×
        w.object(&self.author);
586531×
        w.u64(self.hlc.wall_ms);
596531×
        w.u32(self.hlc.logical);
606531×
        w.bytes(self.message.as_bytes());
616531×
        w.u8(self.kind.tag() as u8);
626531×
    }
63
6411617×
    pub(crate) fn read_flat(r: &mut crate::flat::Reader) -> Result<ChangeMeta, ObjectError> {
6511617×
        let change_id = crate::ids::ChangeId(r.fixed::<16>()?);
6611617×
        let mut deps = Vec::new();
6711617×
        for _ in 0..r.count()? {
6810753×
            deps.push(r.object()?);
69
        }
70
        Ok(ChangeMeta {
7111617×
            change_id,
7211617×
            deps,
7311617×
            author: r.object()?,
74
            hlc: Hlc {
7511617×
                wall_ms: r.u64()?,
7611617×
                logical: r.u32()?,
77
            },
7811617×
            message: r.text()?,
7911617×
            kind: ChangeKind::from_tag(r.u8()? as u64)?,
80
        })
8111617×
    }
82
8317601×
    pub fn of(c: &Change) -> ChangeMeta {
8417601×
        ChangeMeta {
8517601×
            change_id: c.change_id,
8617601×
            deps: c.deps.clone(),
8717601×
            author: c.author,
8817601×
            hlc: c.hlc,
8917601×
            message: c.message.clone(),
9017601×
            kind: c.kind,
9117601×
        }
9217601×
    }
93
}
94
95
#[derive(Default)]
96
pub struct State {
97
    /// Shared between clones, like `files` and `deferred`: a state kept
98
    /// beside another that differs by a few changes shares the rest.
99
    changes: crate::fasthash::FastMap<ChangeHash, Arc<ChangeMeta>>,
100
    tree: TreeGraph,
101
    /// Shared between clones: a clone copies a graph only when an edit
102
    /// changes it (`Arc::make_mut`), so keeping several states that differ
103
    /// by a few changes costs little more than one.
104
    files: crate::fasthash::FastMap<NodeId, Arc<FileGraph>>,
105
    replaces: HashMap<NodeId, Vec<ReplaceRecord>>,
106
    /// Memoised transitive dependencies, bounded by the hashes they hold
107
    /// (each set is the whole history below a change, so keeping one for
108
    /// every change asked about grew with the square of history: #25). A
109
    /// mutex, not a `RefCell`, so a loaded state can be shared across
110
    /// threads by a host that caches it.
111
    closure: std::sync::RwLock<ClosureMemo>,
112
    /// Each change's level: 0 with no dependencies, else one more than its
113
    /// highest dependency. A change can only depend on changes of lower
114
    /// level, which bounds the walk [`DepOracle::depends_on`] does.
115
    levels: std::sync::RwLock<crate::fasthash::FastMap<ChangeHash, u32>>,
116
    /// `None` for a full state. For a history-only state (loaded for its
117
    /// changes and tree), the file graphs not built yet, by node: `files`
118
    /// holds only those loaded with [`State::load_graphs`].
119
    deferred: Option<crate::fasthash::FastMap<NodeId, Arc<Deferred>>>,
120
    /// The tree as readers see it ([`State::view`]), once worked out for
121
    /// a tree with name conflicts; cleared by every change added.
122
    unified_view: std::sync::OnceLock<TreeView>,
123
}
124
125
use crate::objects::TextRef;
126
127
/// A file graph a history-only state has not built: its base from a
128
/// version 2 checkpoint, if any, and the edits of later changes in the
129
/// order they were applied (spec §11). Building it later gives the same
130
/// graph, since graph construction does not depend on order (§8).
131
///
132
/// Read from a state index, it stays in the index, unread, until first
133
/// used: a command that builds a few files reads and checks only their
134
/// histories (oxygen#94).
135
#[derive(Clone, Default)]
136
struct Deferred {
137
    /// The history: `raw` read and decoded, with `more` after it. An
138
    /// error when `raw` does not match its hash.
139
    body: std::sync::OnceLock<Result<DeferredBody, String>>,
140
    /// The history as an index holds it, not read yet.
141
    raw: Option<RawHistory>,
142
    /// Changes added since the index was read, kept beside `raw`, so that
143
    /// adding one neither reads nor decodes the history.
144
    more: Vec<(ChangeHash, Vec<Edit>)>,
145
    more_texts: Vec<TextRef>,
146
    /// Its graph key, once worked out (or read from an index); reset by
147
    /// any edit added.
148
    key: std::sync::OnceLock<[u8; 32]>,
149
}
150
151
/// Where a state index's file histories are: the index file itself, read
152
/// on first use, or bytes in memory.
153
#[derive(Clone)]
154
pub enum Histories {
155
    Bytes(Arc<Vec<u8>>),
156
    /// The file, where its histories start, and how many bytes they take.
157
    File(Arc<std::fs::File>, u64, u64),
158
}
159
160
impl Histories {
16116646×
    fn len(&self) -> u64 {
16216646×
        match self {
1634517×
            Histories::Bytes(b) => b.len() as u64,
16412129×
            Histories::File(_, _, len) => *len,
165
        }
16616646×
    }
167
16821774×
    fn read(&self, at: u64, len: usize) -> std::io::Result<Vec<u8>> {
16921774×
        match self {
1704517×
            Histories::Bytes(b) => Ok(b[at as usize..at as usize + len].to_vec()),
17117257×
            Histories::File(f, start, _) => {
17217257×
                let mut buf = vec![0u8; len];
17317257×
                read_exact_at(f, &mut buf, start + at)?;
17417257×
                Ok(buf)
175
            }
176
        }
17721774×
    }
178
}
179
180
#[cfg(unix)]
18117257×
fn read_exact_at(f: &std::fs::File, buf: &mut [u8], at: u64) -> std::io::Result<()> {
18217257×
    std::os::unix::fs::FileExt::read_exact_at(f, buf, at)
18317257×
}
184
185
#[cfg(windows)]
186
fn read_exact_at(f: &std::fs::File, mut buf: &mut [u8], mut at: u64) -> std::io::Result<()> {
187
    while !buf.is_empty() {
188
        match std::os::windows::fs::FileExt::seek_read(f, buf, at)? {
189
            0 => return Err(std::io::ErrorKind::UnexpectedEof.into()),
190
            n => {
191
                buf = &mut buf[n..];
192
                at += n as u64;
193
            }
194
        }
195
    }
196
    Ok(())
197
}
198
199
/// One file's history in a state index: where it is and its hash.
200
#[derive(Clone)]
201
struct RawHistory {
202
    from: Histories,
203
    at: u64,
204
    len: usize,
205
    sum: [u8; 32],
206
}
207
208
impl RawHistory {
209
    /// The history's bytes, checked against the hash the index holds.
21021774×
    fn bytes(&self) -> Result<Vec<u8>, ObjectError> {
21121774×
        let damaged = |why: String| ObjectError::DamagedIndex(why);
21221774×
        let b = self
21321774×
            .from
21421774×
            .read(self.at, self.len)
21521774×
            .map_err(|e| damaged(format!("a file's history cannot be read: {e}")))?;
21621774×
        if *blake3::hash(&b).as_bytes() != self.sum {
2173×
            return Err(damaged("a file's history does not match its hash".into()));
21821771×
        }
21921771×
        Ok(b)
22021774×
    }
221
}
222
223
/// The closures kept, and how many hashes they hold in all.
224
#[derive(Default)]
225
struct ClosureMemo {
226
    sets: HashMap<ChangeHash, Arc<HashSet<ChangeHash>>>,
227
    held: usize,
228
}
229
230
/// The most hashes the closure memo holds before it starts again: a few
231
/// hundred megabytes at most.
232
const CLOSURE_MEMO_HASHES: usize = 4_000_000;
233
234
#[derive(Clone, Default)]
235
struct DeferredBody {
236
    base: Option<DeferredBase>,
237
    edits: Vec<(ChangeHash, Vec<Edit>)>,
238
    /// The text blob and line count of each insert in `edits` left without
239
    /// its lines, in order: read when the graph is built.
240
    texts: Vec<TextRef>,
241
}
242
243
impl Deferred {
244159×
    fn from_body(body: DeferredBody) -> Deferred {
245159×
        Deferred {
246159×
            body: std::sync::OnceLock::from(Ok(body)),
247159×
            ..Deferred::default()
248159×
        }
249159×
    }
250
251
    /// The history, read and checked on first use.
252106469×
    fn body(&self) -> Result<&DeferredBody, ObjectError> {
253106469×
        self.body
254106469×
            .get_or_init(|| {
25538832×
                let mut b = match &self.raw {
256
                    // Matching its hash, it is what `write_index` wrote: it
257
                    // decodes.
2585433×
                    Some(raw) => raw
2595433×
                        .bytes()
2605433×
                        .and_then(|b| State::read_deferred_body(&b))
2615433×
                        .map_err(|e| e.to_string())?,
26233399×
                    None => DeferredBody::default(),
263
                };
26438831×
                b.edits.extend(self.more.iter().cloned());
26538831×
                b.texts.extend(self.more_texts.iter().cloned());
26638831×
                Ok(b)
26738832×
            })
268106469×
            .as_ref()
269106469×
            .map_err(|e| ObjectError::DamagedIndex(e.clone()))
270106469×
    }
271
272
    /// Add a change's edits to the history: beside the index's encoding
273
    /// while it is unread, so that nothing is read or decoded to add them.
27437330×
    fn add(&mut self, h: ChangeHash, edits: Vec<Edit>, texts: Vec<TextRef>) {
27537330×
        if self.raw.is_some() && !matches!(self.body.get(), Some(Ok(_))) {
2765×
            self.more.push((h, edits));
2775×
            self.more_texts.extend(texts);
278
            // A body found damaged stays so: what was added cannot mend it.
2795×
            return;
28037325×
        }
281
        // No encoding to read, or decoded already: this cannot fail.
28237325×
        let b = self.body_mut().expect("a history in memory");
28337325×
        b.edits.push((h, edits));
28437325×
        b.texts.extend(texts);
28537330×
    }
286
28737325×
    fn body_mut(&mut self) -> Result<&mut DeferredBody, ObjectError> {
28837325×
        self.body()?;
28937325×
        self.raw = None;
29037325×
        self.more.clear();
29137325×
        self.more_texts.clear();
29237325×
        Ok(self
29337325×
            .body
29437325×
            .get_mut()
29537325×
            .and_then(|b| b.as_mut().ok())
29637325×
            .expect("decoded above"))
29737325×
    }
298
29924351×
    fn into_body(mut self) -> Result<DeferredBody, ObjectError> {
30024351×
        self.body()?;
30124350×
        Ok(self
30224350×
            .body
30324350×
            .take()
30424350×
            .and_then(|b| b.ok())
30524350×
            .expect("decoded above"))
30624351×
    }
307
}
308
309
#[derive(Clone)]
310
enum DeferredBase {
311
    Inline(Value),
312
    Blob(ObjectRef),
313
}
314
315
/// A local index of a history-only state (oxygen#41), in the flat layout
316
/// of [`crate::flat`]: its change metadata, tree (with its view), replace
317
/// records and every file's deferred history with its graph key, so a
318
/// command reads it rather than replaying history. Derived only: written
319
/// from a state loaded the long way, and read back as the same state.
320
impl State {
321
    const INDEX_MAGIC: &'static [u8] = b"oxy state index 4\n";
322
323
    /// The index of this state, or `None` when it has anything an index
324
    /// does not hold: a built graph, or text in memory (a change added
325
    /// whole rather than as its skeleton).
3261095×
    pub fn write_index(&self) -> Option<Vec<u8>> {
327
        use crate::flat::Writer;
3281095×
        let deferred = self.deferred.as_ref()?;
3291095×
        if !self.files.is_empty() {
3300×
            return None;
3311095×
        }
332
        // The changes first, as a block a reader can take on its own (see
333
        // [`State::read_index_changes`]).
3341095×
        let mut w = Writer::default();
3351095×
        w.fixed(Self::INDEX_MAGIC);
336
        // In log order, newest first (oxygen#94): the log takes them as
337
        // they come, with no map and no sort.
3381095×
        let mut changes: Vec<(&ChangeHash, &Arc<ChangeMeta>)> = self.changes.iter().collect();
3391095×
        changes.sort_unstable_by(|a, b| log_order((a.0, &a.1.hlc), (b.0, &b.1.hlc)));
3401095×
        w.count(changes.len());
3411095×
        for (h, m) in changes {
342210×
            w.object(h);
343210×
            m.write_flat(&mut w);
344210×
        }
3451095×
        let changes_block = std::mem::take(&mut w);
3461095×
        w.bytes(&changes_block.0);
347
        // The tree and the files' histories as blocks of their own, so a
348
        // reader decodes them side by side.
3491095×
        let mut tw = Writer::default();
3501095×
        self.tree.write_flat(&mut tw);
3511095×
        w.bytes(&tw.0);
3521095×
        let mut replaces: Vec<(&NodeId, &Vec<ReplaceRecord>)> = self.replaces.iter().collect();
3531095×
        replaces.sort_by_key(|(n, _)| **n);
3541095×
        w.count(replaces.len());
3551095×
        for (n, recs) in replaces {
3566×
            w.fixed(&n.0);
3576×
            w.count(recs.len());
358
            // In any order: which record is live does not depend on it.
3596×
            let mut recs: Vec<&ReplaceRecord> = recs.iter().collect();
3606×
            recs.sort();
3616×
            for (c, old, new) in recs {
3626×
                w.object(c);
3636×
                w.opt_object(old);
3646×
                w.opt_object(new);
3656×
            }
366
        }
3671095×
        let mut front = w;
368
        // The table: per file its key and where its history is, with the
369
        // history's hash, which is checked when it is read (oxygen#94).
3701095×
        let mut table = Writer::default();
3711095×
        let mut histories: Vec<u8> = Vec::new();
3721095×
        let mut nodes: Vec<(&NodeId, &Arc<Deferred>)> = deferred.iter().collect();
3731095×
        nodes.sort_by_key(|(n, _)| **n);
3741095×
        table.count(nodes.len());
37532670×
        for (n, d) in nodes {
37632670×
            let key = match d.key.get() {
37716341×
                Some(k) => *k,
378
                None => {
37916329×
                    let mut h = blake3::Hasher::new();
38016329×
                    h.update(b"oxy graph key 1\0");
38116329×
                    h.update(&n.0);
38216329×
                    let k = d.graph_key(h).ok()?;
38316329×
                    let _ = d.key.set(k);
38416329×
                    k
385
                }
386
            };
387
            // Unchanged since read: its bytes as they are, checked.
38832670×
            let bytes = match &d.raw {
38916341×
                Some(raw) if d.more.is_empty() => raw.bytes().ok()?,
39016329×
                _ => Self::write_deferred_body(d.body().ok()?)?,
391
            };
39232668×
            table.fixed(&n.0);
39332668×
            table.fixed(&key);
39432668×
            table.u64(histories.len() as u64);
39532668×
            table.u32(u32::try_from(bytes.len()).ok()?);
39632668×
            table.fixed(blake3::hash(&bytes).as_bytes());
39732668×
            histories.extend_from_slice(&bytes);
398
        }
3991093×
        front.bytes(&table.0);
4001093×
        let mut out = Writer::default();
4011093×
        out.u64(front.0.len() as u64);
4021093×
        out.fixed(&front.0);
4031093×
        out.fixed(&histories);
4041093×
        Some(out.0)
4051095×
    }
406
407
    /// One file's history as an index encodes it; `None` when it holds
408
    /// text in memory, which an index does not.
40916329×
    fn write_deferred_body(d: &DeferredBody) -> Option<Vec<u8>> {
410
        use crate::flat::Writer;
41132850×
        let atom = |w: &mut Writer, a: &AtomRef| match a {
41216323×
            AtomRef::Start => w.u8(0),
41316425×
            AtomRef::End => w.u8(1),
414102×
            AtomRef::Atom { change, index } => {
415102×
                w.u8(2);
416102×
                w.object(change);
417102×
                w.u32(*index);
418102×
            }
41932850×
        };
42016329×
        let mut w = Writer::default();
4216×
        match &d.base {
42216323×
            None => w.u8(0),
4230×
            Some(DeferredBase::Blob(r)) => {
4240×
                w.u8(1);
4250×
                w.object(r);
4260×
            }
4276×
            Some(DeferredBase::Inline(v)) => {
4286×
                w.u8(2);
4296×
                w.bytes(&cbor::encode(v));
4306×
            }
431
        }
432
        // Each change's edits with the texts of its inserts, sorted by
433
        // change: a graph does not depend on the order changes applied
434
        // in, and the index is then the same however history was read.
43516329×
        let mut texts = d.texts.iter();
43616329×
        let mut per_change: Vec<(&ChangeHash, &Vec<Edit>, Vec<&TextRef>)> = Vec::new();
43716425×
        for (c, edits) in &d.edits {
43816425×
            let n = edits
43916425×
                .iter()
44016425×
                .filter(|e| matches!(e, Edit::Insert { lines, .. } if lines.is_empty()))
44116425×
                .count();
44216425×
            per_change.push((c, edits, texts.by_ref().take(n).collect()));
443
        }
44416329×
        per_change.sort_by_key(|(c, _, _)| **c);
44516329×
        w.count(per_change.len());
44616425×
        for (c, edits, _) in &per_change {
44716425×
            w.object(c);
44816425×
            w.count(edits.len());
44916425×
            for e in edits.iter() {
45016425×
                match e {
451
                    Edit::Insert {
45216425×
                        node,
45316425×
                        after,
45416425×
                        before,
45516425×
                        lines,
456
                    } => {
45716425×
                        if !lines.is_empty() {
4580×
                            return None;
45916425×
                        }
46016425×
                        w.u8(0);
46116425×
                        w.fixed(&node.0);
46216425×
                        atom(&mut w, after);
46316425×
                        atom(&mut w, before);
464
                    }
4650×
                    Edit::Delete { node, atoms } => {
4660×
                        w.u8(1);
4670×
                        w.fixed(&node.0);
4680×
                        w.count(atoms.len());
4690×
                        for r in atoms {
4700×
                            w.object(&r.change);
4710×
                            w.u32(r.from);
4720×
                            w.u32(r.to);
4730×
                        }
474
                    }
4750×
                    Edit::Replace { .. } => return None,
476
                }
477
            }
478
        }
47916329×
        let texts: Vec<&TextRef> = per_change
48016329×
            .iter()
48116425×
            .flat_map(|(_, _, t)| t.iter().copied())
48216329×
            .collect();
48316329×
        w.count(texts.len());
48416425×
        for t in texts {
48516425×
            match t {
4860×
                TextRef::Blob(r, count, form) => {
4870×
                    w.u8(0);
4880×
                    w.object(r);
4890×
                    w.u32(*count);
4900×
                    w.u8(match form {
4910×
                        crate::objects::TextForm::Cbor => 0,
4920×
                        crate::objects::TextForm::Raw => 1,
4930×
                        crate::objects::TextForm::CborFallback => 2,
494
                    });
495
                }
49616425×
                TextRef::Inline { change, start, end } => {
49716425×
                    w.u8(1);
49816425×
                    w.object(change);
49916425×
                    w.u32(*start);
50016425×
                    w.u32(*end);
50116425×
                }
502
            }
503
        }
50416329×
        Some(w.0)
50516329×
    }
506
507
    /// The state an index holds (see [`State::write_index`]).
508281×
    pub fn read_index(bytes: &[u8]) -> Result<State, ObjectError> {
509281×
        let bad = || ObjectError::Schema("state index: truncated".into());
510281×
        let front_len =
511281×
            usize::try_from(crate::flat::Reader::new(bytes).u64()?).map_err(|_| bad())?;
512281×
        let front = bytes.get(8..8 + front_len).ok_or_else(bad)?;
513281×
        let histories = Histories::Bytes(Arc::new(bytes[8 + front_len..].to_vec()));
514281×
        Self::read_index_front(front, histories)
515281×
    }
516
517
    /// An index's front, everything but the files' histories, with where
518
    /// those are: each is read, and checked against the hash the front
519
    /// holds, only when its graph is built (oxygen#94).
5202285×
    pub fn read_index_front(bytes: &[u8], histories: Histories) -> Result<State, ObjectError> {
521
        use crate::flat::Reader;
5222285×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
5232285×
        let mut r = Reader::new(bytes);
5242285×
        let mut st = State::new_history_only();
525
        {
5262285×
            let _t = crate::timing::phase("index: changes");
5272285×
            st.changes = Self::read_index_changes(r.bytes()?)?;
528
        }
5292285×
        let tree_bytes = r.bytes()?;
5302285×
        for _ in 0..r.count()? {
5315×
            let n = NodeId(r.fixed::<16>()?);
5325×
            let mut recs = Vec::new();
5335×
            for _ in 0..r.count()? {
5345×
                recs.push((r.object()?, r.opt_object()?, r.opt_object()?));
535
            }
5365×
            st.replaces.insert(n, recs);
537
        }
5382285×
        let deferred_bytes = r.bytes()?;
5392285×
        if !r.at_end() {
5400×
            return Err(bad("trailing bytes"));
5412285×
        }
5422285×
        let (tree, deferred) = rayon::join(
5432285×
            || TreeGraph::read_flat(&mut Reader::new(tree_bytes)),
5442285×
            || Self::read_deferred(deferred_bytes, &histories),
545
        );
5462285×
        st.tree = tree?;
5472285×
        st.deferred = Some(deferred?);
5482285×
        Ok(st)
5492285×
    }
550
551
    /// The changes of a state index: its first block, which a reader can
552
    /// take without the rest.
5532285×
    pub fn read_index_changes(
5542285×
        bytes: &[u8],
5552285×
    ) -> Result<crate::fasthash::FastMap<ChangeHash, Arc<ChangeMeta>>, ObjectError> {
5562285×
        Ok(Self::read_index_changes_listed(bytes)?
5572285×
            .into_iter()
5582285×
            .map(|(h, m)| (h, Arc::new(m)))
5592285×
            .collect())
5602285×
    }
561
562
    /// The same changes as a list in the order the index keeps them, which
563
    /// a current index keeps in log order ([`log_order`]): what the log
564
    /// needs (oxygen#94).
5652455×
    pub fn read_index_changes_listed(
5662455×
        bytes: &[u8],
5672455×
    ) -> Result<Vec<(ChangeHash, ChangeMeta)>, ObjectError> {
568
        use crate::flat::Reader;
5692455×
        let mut r = Reader::new(bytes);
5702455×
        if r.fixed::<18>()?.as_slice() != Self::INDEX_MAGIC {
5710×
            return Err(ObjectError::Schema("state index: not a state index".into()));
5722455×
        }
5732455×
        let n = r.count()?;
5742455×
        let mut changes = Vec::with_capacity(n);
5752455×
        for _ in 0..n {
57610129×
            let h = r.object()?;
57710129×
            changes.push((h, ChangeMeta::read_flat(&mut r)?));
578
        }
5792454×
        if !r.at_end() {
5800×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
5812454×
        }
5822454×
        Ok(changes)
5832455×
    }
584
585
    /// The deferred block: each node with its graph key and its body,
586
    /// left encoded (see [`Deferred`]).
5872285×
    fn read_deferred(
5882285×
        table: &[u8],
5892285×
        histories: &Histories,
5902285×
    ) -> Result<crate::fasthash::FastMap<NodeId, Arc<Deferred>>, ObjectError> {
591
        use crate::flat::Reader;
5922285×
        let _t = crate::timing::phase("index: deferred");
5932285×
        let mut r = Reader::new(table);
5942285×
        let mut deferred = crate::fasthash::FastMap::default();
5952285×
        let n = r.count()?;
5962285×
        deferred.reserve(n);
5972285×
        for _ in 0..n {
59816646×
            let id = NodeId(r.fixed::<16>()?);
59916646×
            let key = r.fixed::<32>()?;
600
            // The length is of bytes in the histories, not in this table:
601
            // checked against the histories' size below.
60216646×
            let (at, len, sum) = (r.u64()?, r.u32()? as usize, r.fixed::<32>()?);
60316646×
            if at
60416646×
                .checked_add(len as u64)
60516646×
                .is_none_or(|end| end > histories.len())
606
            {
6070×
                return Err(ObjectError::Schema(
6080×
                    "state index: a file's history lies outside it".into(),
6090×
                ));
61016646×
            }
61116646×
            let d = Deferred {
61216646×
                raw: Some(RawHistory {
61316646×
                    from: histories.clone(),
61416646×
                    at,
61516646×
                    len,
61616646×
                    sum,
61716646×
                }),
61816646×
                key: std::sync::OnceLock::from(key),
61916646×
                ..Deferred::default()
62016646×
            };
62116646×
            deferred.insert(id, Arc::new(d));
622
        }
6232285×
        if !r.at_end() {
6240×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
6252285×
        }
6262285×
        Ok(deferred)
6272285×
    }
628
629
    /// One node's deferred history as the index encodes it.
6305432×
    fn read_deferred_body(bytes: &[u8]) -> Result<DeferredBody, ObjectError> {
631
        use crate::flat::Reader;
6325432×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
6335437×
        let node = |r: &mut Reader| -> Result<NodeId, ObjectError> { Ok(NodeId(r.fixed::<16>()?)) };
63410874×
        let atom = |r: &mut Reader| -> Result<AtomRef, ObjectError> {
63510874×
            Ok(match r.u8()? {
6365421×
                0 => AtomRef::Start,
6375437×
                1 => AtomRef::End,
638
                2 => AtomRef::Atom {
63916×
                    change: r.object()?,
64016×
                    index: r.u32()?,
641
                },
6420×
                _ => return Err(bad("atom")),
643
            })
64410874×
        };
6455432×
        let mut r = Reader::new(bytes);
6465432×
        let base = match r.u8()? {
6475421×
            0 => None,
6480×
            1 => Some(DeferredBase::Blob(r.object()?)),
64911×
            _ => Some(DeferredBase::Inline(cbor::decode(r.bytes()?)?)),
650
        };
6515432×
        let mut edits = Vec::new();
6525432×
        for _ in 0..r.count()? {
6535437×
            let c = r.object()?;
6545437×
            let mut es = Vec::new();
6555437×
            for _ in 0..r.count()? {
6565437×
                es.push(match r.u8()? {
657
                    0 => Edit::Insert {
6585437×
                        node: node(&mut r)?,
6595437×
                        after: atom(&mut r)?,
6605437×
                        before: atom(&mut r)?,
6615437×
                        lines: crate::lines::Lines::default(),
662
                    },
663
                    1 => {
6640×
                        let node = node(&mut r)?;
6650×
                        let mut atoms = Vec::new();
6660×
                        for _ in 0..r.count()? {
6670×
                            atoms.push(crate::objects::AtomRange {
6680×
                                change: r.object()?,
6690×
                                from: r.u32()?,
6700×
                                to: r.u32()?,
671
                            });
672
                        }
6730×
                        Edit::Delete { node, atoms }
674
                    }
6750×
                    _ => return Err(bad("edit")),
676
                });
677
            }
6785437×
            edits.push((c, es));
679
        }
6805432×
        let mut texts = Vec::new();
6815432×
        for _ in 0..r.count()? {
6825437×
            texts.push(match r.u8()? {
683
                0 => TextRef::Blob(
6840×
                    r.object()?,
6850×
                    r.u32()?,
6860×
                    match r.u8()? {
6870×
                        0 => crate::objects::TextForm::Cbor,
6880×
                        1 => crate::objects::TextForm::Raw,
6890×
                        _ => crate::objects::TextForm::CborFallback,
690
                    },
691
                ),
692
                _ => TextRef::Inline {
6935437×
                    change: r.object()?,
6945437×
                    start: r.u32()?,
6955437×
                    end: r.u32()?,
696
                },
697
            });
698
        }
6995432×
        if !r.at_end() {
7000×
            return Err(bad("trailing bytes in a file's history"));
7015432×
        }
7025432×
        Ok(DeferredBody { base, edits, texts })
7035432×
    }
704
}
705
706
impl Clone for State {
7071992×
    fn clone(&self) -> State {
7081992×
        State {
7091992×
            changes: self.changes.clone(),
7101992×
            tree: self.tree.clone(),
7111992×
            files: self.files.clone(),
7121992×
            replaces: self.replaces.clone(),
7131992×
            // A cache: the clone builds its own.
7141992×
            closure: Default::default(),
7151992×
            levels: Default::default(),
7161992×
            deferred: self.deferred.clone(),
7171992×
            unified_view: self.unified_view.clone(),
7181992×
        }
7191992×
    }
720
}
721
722
#[derive(Clone, Debug, PartialEq, Eq)]
723
pub enum FileContent {
724
    Text {
725
        bytes: Vec<u8>,
726
        materialized: Materialized,
727
    },
728
    /// Live blobs; more than one is a replace conflict (spec §9.3).
729
    Opaque {
730
        blobs: Vec<ObjectRef>,
731
    },
732
    Dir,
733
}
734
735
#[derive(Clone, Debug, PartialEq, Eq)]
736
pub struct FileState {
737
    pub node: NodeId,
738
    pub kind: NodeKind,
739
    pub mode: Mode,
740
    pub content: FileContent,
741
}
742
743
impl FileState {
74414015×
    pub fn is_conflicted(&self) -> bool {
74514015×
        match &self.content {
74613019×
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
747307×
            FileContent::Opaque { blobs } => blobs.len() > 1,
748689×
            FileContent::Dir => false,
749
        }
75014015×
    }
751
}
752
753
/// How one conflict settles without a person ([`State::settle_plans`]).
754
#[derive(Clone, Debug, PartialEq, Eq)]
755
pub struct Settle {
756
    /// Its sides' text, as its markers show them.
757
    pub sides: Vec<Vec<u8>>,
758
    /// The text that takes the markers' place, side by side, in order.
759
    pub kept: Vec<Vec<u8>>,
760
    /// Its sides are identical, and one is kept.
761
    pub identical: bool,
762
}
763
764
/// See `State::conflict_regions`.
765
#[derive(Clone, Debug, Default, PartialEq, Eq)]
766
pub struct ConflictRegions {
767
    pub plain: Vec<(AtomKey, Vec<u8>)>,
768
    pub region_atoms: Vec<AtomKey>,
769
    pub contributors: Vec<ChangeHash>,
770
}
771
772
/// The whole tree of a state, materialized.
773
#[derive(Clone, Debug, Default)]
774
pub struct Snapshot {
775
    pub tree: TreeView,
776
    pub files: BTreeMap<String, FileState>,
777
    /// Text files left unrendered by [`State::materialize_except`]: their
778
    /// `bytes` are empty and they are known not to be conflicted.
779
    pub unrendered: BTreeSet<String>,
780
}
781
782
impl Snapshot {
7832438×
    pub fn is_conflicted(&self) -> bool {
78413699×
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
7852438×
    }
786
}
787
78867378×
fn vertex(r: AtomRef) -> Vertex {
78967378×
    match r {
79027849×
        AtomRef::Start => Vertex::Start,
79129069×
        AtomRef::End => Vertex::End,
79210460×
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
793
    }
79467378×
}
795
796
/// Replace self references in a tree op with the concrete change hash.
79740430×
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
79840430×
    match op {
799959×
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
800959×
            node: *node,
801959×
            placement: placement.resolve(me),
802959×
        },
803
        TreeOp::Move {
804156×
            node,
805156×
            old,
806156×
            parent,
807156×
            name,
808156×
        } => TreeOp::Move {
809156×
            node: *node,
810156×
            old: old.resolve(me),
811156×
            parent: *parent,
812156×
            name: name.clone(),
813156×
        },
81422×
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
81522×
            node: *node,
81622×
            old: old.resolve(me),
81722×
            mode: *mode,
81822×
        },
81939293×
        add @ TreeOp::AddNode { .. } => add.clone(),
820
    }
82140430×
}
822
823
/// Apply one change's edits of one file (inserts and deletes; replaces
824
/// live beside the graphs) to that file's graph.
82528262×
fn apply_file_edits(g: &mut FileGraph, h: ChangeHash, edits: Vec<Edit>) {
826
    // The graph's kept order, if any, follows the edits (see `Order`).
82728262×
    let order = g.take_order();
82828262×
    let mut inserts: Vec<(Vertex, Vertex, u32, u32)> = Vec::new();
82928262×
    let mut deleted: Vec<crate::graph::AtomKey> = Vec::new();
83028262×
    let mut next = 0u32;
83130958×
    for e in edits {
83230958×
        match e {
833
            Edit::Insert {
83428971×
                after,
83528971×
                before,
83628971×
                lines,
837
                ..
83828971×
            } => {
83928971×
                let first = next;
84028971×
                let count = lines.len() as u32;
84128971×
                next += count;
84228971×
                let (after, before) = (vertex(after.resolve(h)), vertex(before.resolve(h)));
84328971×
                inserts.push((after, before, first, count));
84428971×
                g.insert_owned(h, first, after, before, lines);
84528971×
            }
8461987×
            Edit::Delete { atoms, .. } => {
8473090×
                for r in atoms {
8483090×
                    let r = r.resolve(h);
8493163×
                    deleted.extend((r.from..r.to).map(|i| (r.change, i)));
8503090×
                    g.delete(h, &r);
851
                }
852
            }
8530×
            Edit::Replace { .. } => {}
854
        }
855
    }
85628262×
    if let Some(o) = order {
85781×
        g.keep_spliced(o, h, &inserts, &deleted);
85828181×
    }
85928262×
}
860
861
/// Build the graphs of deferred entries: their checkpoint bases and the
862
/// texts of inserts read without their lines are loaded in one call, then
863
/// the graphs are built in parallel (they are independent).
8644822×
fn build_deferred(
8654822×
    taken: Vec<(NodeId, Deferred)>,
8664822×
    load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
8674822×
    read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
8684822×
) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
8694822×
    let mut taken: Vec<(NodeId, DeferredBody)> = taken
8704822×
        .into_iter()
87124351×
        .map(|(n, d)| Ok((n, d.into_body()?)))
8724822×
        .collect::<Result<_, ObjectError>>()?;
8734821×
    let mut refs: Vec<ObjectRef> = taken
8744821×
        .iter()
8754821×
        .filter_map(|(_, d)| match &d.base {
8766×
            Some(DeferredBase::Blob(r)) => Some(*r),
87724344×
            _ => None,
87824350×
        })
8794821×
        .collect();
880
    // Text blobs of inserts read without their lines, after the bases.
8814821×
    let bases = refs.len();
88224350×
    refs.extend(taken.iter().flat_map(|(_, d)| {
88328271×
        d.texts.iter().filter_map(|t| match t {
88470×
            TextRef::Blob(r, _, _) => Some(*r),
88528201×
            TextRef::Inline { .. } => None,
88628271×
        })
88724350×
    }));
888
    // And the encodings of changes whose inline inserts are needed,
889
    // each read once.
8904821×
    let reading = crate::timing::phase("graphs: read changes and blobs");
8914821×
    let mut changes: HashMap<ChangeHash, Arc<Vec<u8>>> = HashMap::new();
89228271×
    for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
89328271×
        if let TextRef::Inline { change, .. } = t {
89428201×
            if !changes.contains_key(change) {
8957883×
                changes.insert(*change, read_change(change)?);
89620318×
            }
89770×
        }
898
    }
8994821×
    let n_changes = changes.len();
9004821×
    drop(reading);
9014821×
    let reading = crate::timing::phase("graphs:   of which blobs");
9024821×
    let mut blobs = if refs.is_empty() {
9034750×
        Vec::new()
904
    } else {
90571×
        load(&refs)?
906
    };
9074818×
    if crate::timing::enabled() {
9082×
        eprintln!(
9092×
            "timing graphs: {} graphs, {n_changes} changes, {} blobs",
9102×
            taken.len(),
9112×
            refs.len()
9122×
        );
9134816×
    }
9144818×
    if blobs.len() != refs.len() {
9150×
        return Err(ObjectError::Schema("graph blobs: wrong count".into()));
9164818×
    }
9174818×
    drop(reading);
9184818×
    let lines = crate::timing::phase("graphs: hand out blobs");
9194818×
    let mut texts = blobs.split_off(bases).into_iter();
9204818×
    let mut blobs = blobs.into_iter();
921
    // Hand each graph its own blobs, in order, then fill in its inserts'
922
    // lines and build it, all in parallel: graphs are independent.
923
    type Work = (NodeId, DeferredBody, Option<Vec<u8>>, Vec<Vec<u8>>);
9244818×
    let mut work: Vec<Work> = Vec::with_capacity(taken.len());
92524347×
    for (node, d) in taken.drain(..) {
92624347×
        let wanted = d
92724347×
            .texts
92824347×
            .iter()
92928269×
            .filter(|t| matches!(t, TextRef::Blob(..)))
93024347×
            .count();
93124347×
        let mine: Vec<Vec<u8>> = texts.by_ref().take(wanted).collect();
93224347×
        if mine.len() != wanted {
9330×
            return Err(ObjectError::Schema("text blobs: wrong count".into()));
93424347×
        }
93524347×
        let bytes = match &d.base {
936
            Some(DeferredBase::Blob(_)) => Some(
9375×
                blobs
9385×
                    .next()
9395×
                    .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
940
            ),
94124342×
            _ => None,
942
        };
94324347×
        work.push((node, d, bytes, mine));
944
    }
9454818×
    drop(lines);
9464818×
    let _t = crate::timing::phase("graphs: lines and build");
947
    use rayon::prelude::*;
9484818×
    let changes = &changes;
9494818×
    let built: Vec<(NodeId, FileGraph)> = work
9504818×
        .into_par_iter()
95124347×
        .map(|(node, mut d, bytes, mine)| {
952
            // Fill in the lines of inserts read without them, in order.
95324347×
            let mut want = std::mem::take(&mut d.texts).into_iter();
95424347×
            let mut mine = mine.into_iter();
95527760×
            for (_, edits) in d.edits.iter_mut() {
95629987×
                for e in edits.iter_mut() {
95729987×
                    if let Edit::Insert { lines, .. } = e {
95828276×
                        if lines.is_empty() {
95928269×
                            *lines = match want.next() {
96068×
                                Some(TextRef::Blob(_, count, form)) => {
96168×
                                    let content = mine.next().ok_or_else(|| {
9620×
                                        ObjectError::Schema("text blobs: wrong count".into())
9630×
                                    })?;
96468×
                                    crate::objects::text_lines(&content, count, form)?
965
                                }
96628201×
                                Some(TextRef::Inline { change, start, end }) => {
96728201×
                                    let bytes = &changes[&change];
96828201×
                                    let range = bytes
96928201×
                                        .get(start as usize..end as usize)
97028201×
                                        .ok_or_else(|| {
9710×
                                            ObjectError::Schema(
9720×
                                                "an inline insert lies outside its change".into(),
9730×
                                            )
9740×
                                        })?;
97528201×
                                    crate::objects::inline_lines(range)?
976
                                }
977
                                None => {
9780×
                                    return Err(ObjectError::Schema(
9790×
                                        "an insert's text is missing".into(),
9800×
                                    ))
981
                                }
982
                            };
9837×
                        }
9841711×
                    }
985
                }
986
            }
98724347×
            let mut graph = match (d.base.take(), bytes) {
988109×
                (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
9895×
                (Some(DeferredBase::Blob(_)), Some(bytes)) => {
9905×
                    FileGraph::from_value(&cbor::decode(&bytes)?)?
991
                }
99224233×
                _ => FileGraph::default(),
993
            };
99427760×
            for (h, edits) in std::mem::take(&mut d.edits) {
99527760×
                apply_file_edits(&mut graph, h, edits);
99627760×
            }
99724347×
            Ok((node, graph))
99824347×
        })
9994818×
        .collect::<Result<_, ObjectError>>()?;
10004818×
    Ok(built)
10014822×
}
1002
1003
impl State {
1004737×
    pub fn new() -> Self {
1005737×
        Self::default()
1006737×
    }
1007
1008
    /// An empty state for history only: changes and tree are kept, file
1009
    /// edits are recorded but no file graph is built until
1010
    /// [`State::load_graphs`] asks for it. For log and other commands that
1011
    /// need no file contents, or only a few files.
10124402×
    pub fn new_history_only() -> Self {
10134402×
        State {
10144402×
            deferred: Some(Default::default()),
10154402×
            ..Self::default()
10164402×
        }
10174402×
    }
1018
1019
    /// Whether `node`'s file graph is built (always, in a full state).
102040×
    pub fn is_built(&self, node: &NodeId) -> bool {
102140×
        self.deferred.is_none() || self.files.contains_key(node)
102240×
    }
1023
1024
    /// Whether this state builds file graphs only when asked
1025
    /// ([`State::new_history_only`]), even if it has none waiting.
10264107×
    pub fn is_history_only(&self) -> bool {
10274107×
        self.deferred.is_some()
10284107×
    }
1029
1030
    /// Whether this state holds every file graph.
10313451×
    pub fn is_full(&self) -> bool {
10323451×
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
10333451×
    }
1034
1035
    /// The graph of `node`, which must be loaded: asking a history-only
1036
    /// state for a graph it has not built is a bug, never an empty file.
103727514×
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
103827514×
        if let Some(d) = &self.deferred {
103910595×
            assert!(
104010595×
                !d.contains_key(node),
1041
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
10421×
                node.short(12)
1043
            );
104416919×
        }
104527513×
        self.files.get(node).map(|g| g.as_ref())
104627513×
    }
1047
1048
    /// Operations over every file need every graph.
10493444×
    fn require_full(&self, what: &str) {
10503444×
        assert!(
10513444×
            self.is_full(),
1052
            "{what} needs every file graph; this state was loaded for history only"
1053
        );
10543443×
    }
1055
1056
    /// Build the graphs of `nodes` in a history-only state: from their
1057
    /// checkpoint base (blobs read in one batch through `load`) and their
1058
    /// deferred edits. Nodes already built, or with no graph, are skipped.
10594745×
    pub fn load_graphs(
10604745×
        &mut self,
10614745×
        nodes: &[NodeId],
10624745×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
10634745×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
10644745×
    ) -> Result<(), ObjectError> {
10654745×
        let Some(deferred) = self.deferred.as_mut() else {
10660×
            return Ok(());
1067
        };
10684745×
        let taken: Vec<(NodeId, Deferred)> = nodes
10694745×
            .iter()
107024585×
            .filter_map(|n| deferred.remove(n).map(|d| (*n, Arc::unwrap_or_clone(d))))
10714745×
            .collect();
10724745×
        let built = build_deferred(taken, load, read_change)?;
10734741×
        self.files
107424286×
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
10754741×
        Ok(())
10764745×
    }
1077
1078
    /// The graphs of `nodes`, built from this history-only state's deferred
1079
    /// edits without building them in it: the state stays history only, so
1080
    /// changes read without their lines can still be added to it and every
1081
    /// graph keeps its key. For a caller that renders a few files of many
1082
    /// states in turn (verifying an import).
108377×
    pub fn build_graphs_detached(
108477×
        &self,
108577×
        nodes: &[NodeId],
108677×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
108777×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
108877×
    ) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
108977×
        let Some(deferred) = self.deferred.as_ref() else {
10900×
            return Ok(Vec::new());
1091
        };
1092
        // A file this state has built has no deferred history: its graph
1093
        // is the built one, copied. Built from an empty history instead, it
1094
        // rendered as an empty file, and a merge taking this path recorded
1095
        // the whole file as inserted again, conflicting with itself (#71).
109677×
        let mut built: Vec<(NodeId, FileGraph)> = Vec::new();
109777×
        let mut copies: Vec<(NodeId, Deferred)> = Vec::new();
109877×
        for n in nodes {
109964×
            match (self.files.get(n), deferred.get(n)) {
11003×
                (Some(g), _) => built.push((*n, (**g).clone())),
110161×
                (None, d) => copies.push((*n, d.map(|d| (**d).clone()).unwrap_or_default())),
1102
            }
1103
        }
110477×
        let mut out = build_deferred(copies, load, read_change)?;
110577×
        out.extend(built);
110677×
        Ok(out)
110777×
    }
1108
1109
    /// Render a graph built for this state (see
1110
    /// [`State::build_graphs_detached`]), as [`State::render_file`] does.
111164×
    pub fn render_graph(&self, g: &FileGraph) -> (Vec<u8>, Materialized) {
111264×
        let m = g.materialize(self);
111364×
        let bytes = g.render(&m, &|h| self.label(h));
111464×
        (bytes, m)
111564×
    }
1116
1117
    /// Every file graph a history-only state has not built, deleted files'
1118
    /// included.
111980×
    pub fn unbuilt_nodes(&self) -> Vec<NodeId> {
112080×
        self.deferred
112180×
            .as_ref()
112280×
            .map(|d| d.keys().copied().collect())
112380×
            .unwrap_or_default()
112480×
    }
1125
1126
    /// Drop the built graphs of `nodes`, for a caller rendering a large
1127
    /// tree a batch at a time. The state can no longer render those files,
1128
    /// so it must not be used for them again.
1129499×
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
11306061×
        for n in nodes {
11316061×
            self.files.remove(n);
11326061×
        }
1133499×
    }
1134
1135
    /// Build every graph a history-only state has not built, making it full.
11362523×
    pub fn load_all_graphs(
11372523×
        &mut self,
11382523×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
11392523×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
11402523×
    ) -> Result<(), ObjectError> {
11412523×
        let nodes: Vec<NodeId> = match &self.deferred {
11422523×
            Some(d) => d.keys().copied().collect(),
11430×
            None => return Ok(()),
1144
        };
11452523×
        self.load_graphs(&nodes, load, read_change)?;
11462523×
        self.deferred = None;
11472523×
        Ok(())
11482523×
    }
1149
1150
    /// The one text a file's history is, when it is a single insert of
1151
    /// the whole file into nothing (a file added once and never edited,
1152
    /// with no checkpoint base): its rendering is that text, so it needs
1153
    /// no graph. `None` otherwise, or when the graph is built.
11545914×
    pub fn single_text(&self, node: &NodeId) -> Option<TextRef> {
11555914×
        if self.files.contains_key(node) {
115658×
            return None;
11575856×
        }
1158
        // A history that cannot be read is no single text: building its
1159
        // graph reports why.
11605856×
        let d = self.deferred.as_ref()?.get(node)?.body().ok()?;
11615814×
        let [(_, edits)] = d.edits.as_slice() else {
1162256×
            return None;
1163
        };
1164
        let [Edit::Insert {
1165
            after: AtomRef::Start,
1166
            before: AtomRef::End,
11675558×
            lines,
1168
            ..
11695558×
        }] = edits.as_slice()
1170
        else {
11710×
            return None;
1172
        };
11735558×
        match (&d.base, d.texts.as_slice()) {
11745558×
            (None, [t]) if lines.is_empty() => Some(*t),
11750×
            _ => None,
1176
        }
11775914×
    }
1178
1179
    /// A key for the graph of `node` in a history-only state that has not
1180
    /// built it: equal keys mean equal graphs, so equal renderings (a
1181
    /// rendering depends only on the graph and on the changes' own
1182
    /// immutable metadata). It names the node, its checkpoint base (a blob,
1183
    /// an inline value, or none) and the set of later changes that edited
1184
    /// the file.
1185
    /// `None` for a full state or a graph already built.
118629379×
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
118729379×
        let deferred = self.deferred.as_ref()?;
118829331×
        if self.files.contains_key(node) {
1189636×
            return None;
119028695×
        }
119128695×
        let mut h = blake3::Hasher::new();
119228695×
        h.update(b"oxy graph key 1\0");
1193
        // A change's edits are applied per node: the node is part of it.
119428695×
        h.update(&node.0);
119528695×
        let Some(d) = deferred.get(node) else {
1196
            // Never edited: the empty graph.
1197208×
            h.update(&[0]);
1198208×
            return Some(*h.finalize().as_bytes());
1199
        };
1200
        // A history that cannot be read has no key: the file is read.
120128487×
        if let Some(k) = d.key.get() {
120222166×
            return Some(*k);
12036321×
        }
12046321×
        let k = d.graph_key(h).ok()?;
12056321×
        Some(*d.key.get_or_init(|| k))
120629379×
    }
1207
12084275×
    pub fn len(&self) -> usize {
12094275×
        self.changes.len()
12104275×
    }
1211
1212
    /// Turn this history-only state's built graphs back into deferred
1213
    /// histories, each starting from its graph encoded as a checkpoint
1214
    /// graph and stored by `store` (it returns the blob's reference): what
1215
    /// they held stays, and memory goes back to what a history-only state
1216
    /// costs. A graph built later again decodes that blob and applies only
1217
    /// the edits that came after. Graph keys change (the base is now a
1218
    /// blob), which only means a cached rendering is not reused.
12191×
    pub fn shed_graphs<E>(
12201×
        &mut self,
12211×
        mut store: impl FnMut(&[u8]) -> Result<ObjectRef, E>,
12221×
    ) -> Result<usize, E> {
1223
        use rayon::prelude::*;
12241×
        let Some(deferred) = self.deferred.as_mut() else {
12250×
            return Ok(0);
1226
        };
12271×
        let graphs: Vec<(NodeId, Arc<FileGraph>)> = self.files.drain().collect();
12281×
        let encoded: Vec<(NodeId, Vec<u8>)> = graphs
12291×
            .par_iter()
12302×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
12311×
            .collect();
12321×
        drop(graphs);
12331×
        let shed = encoded.len();
12342×
        for (node, bytes) in encoded {
12352×
            let blob = store(&bytes)?;
12362×
            deferred.insert(
12372×
                node,
12382×
                Arc::new(Deferred::from_body(DeferredBody {
12392×
                    base: Some(DeferredBase::Blob(blob)),
12402×
                    ..DeferredBody::default()
12412×
                })),
1242
            );
1243
        }
12441×
        Ok(shed)
12451×
    }
1246
1247
    /// How many file graphs this state has built.
124877×
    pub fn built_count(&self) -> usize {
124977×
        self.files.len()
125077×
    }
1251
1252
    /// Atoms in this state's built graphs, live and deleted: what their
1253
    /// memory follows, since a graph keeps every line its file ever had.
125451×
    pub fn built_atoms(&self) -> usize {
125556×
        self.files.values().map(|g| g.atom_count()).sum()
125651×
    }
1257
1258
    /// Edits held in the deferred histories of files not built, and the
1259
    /// most any one file holds (for measuring, #25).
12600×
    pub fn deferred_edit_count(&self) -> (usize, usize) {
12610×
        let Some(d) = self.deferred.as_ref() else {
12620×
            return (0, 0);
1263
        };
12640×
        let mut total = 0;
12650×
        let mut most = 0;
12660×
        for v in d.values() {
12670×
            let n: usize = v
12680×
                .body()
12690×
                .map_or(0, |b| b.edits.iter().map(|(_, e)| e.len()).sum());
12700×
            total += n;
12710×
            most = most.max(n);
1272
        }
12730×
        (total, most)
12740×
    }
1275
}
1276
1277
impl Deferred {
1278
    /// See [`State::graph_key`]: `h` has taken the node already.
127922650×
    fn graph_key(&self, mut h: blake3::Hasher) -> Result<[u8; 32], ObjectError> {
128022650×
        let d = self.body()?;
128118×
        match &d.base {
128222632×
            None => h.update(&[0]),
12830×
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
128418×
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
1285
        };
128622650×
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
128722650×
        changes.sort();
128822650×
        changes.dedup();
128922650×
        h.update(&(changes.len() as u64).to_le_bytes());
129024548×
        for c in changes {
129124548×
            h.update(&c.0);
129224548×
        }
129322650×
        Ok(*h.finalize().as_bytes())
129422650×
    }
1295
}
1296
1297
impl State {
12980×
    pub fn is_empty(&self) -> bool {
12990×
        self.changes.is_empty()
13000×
    }
130116024×
    pub fn contains(&self, h: &ChangeHash) -> bool {
130216024×
        self.changes.contains_key(h)
130316024×
    }
130471×
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
130571×
        self.changes.get(h).map(|m| &**m)
130671×
    }
13071990×
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
13084753×
        self.changes.iter().map(|(h, m)| (h, &**m))
13091990×
    }
131015910×
    pub fn tree(&self) -> &TreeGraph {
131115910×
        &self.tree
131215910×
    }
1313
1314
    /// The tree as every reader sees it: the tree graph's view, with the
1315
    /// same path added on several lines of history with identical content
1316
    /// shown as one entry rather than a name conflict (spec §9.2). The
1317
    /// text files among such candidates must be built in a history-only
1318
    /// state ([`State::unify_candidates`]); until they are, they are shown
1319
    /// as the conflict.
13207574×
    pub fn view(&self) -> TreeView {
13217574×
        if let Some(v) = self.unified_view.get() {
132264×
            return v.clone();
13237510×
        }
13247510×
        let raw = self.tree.view();
13257510×
        if !raw
13267510×
            .conflicts
13277510×
            .iter()
13287510×
            .any(|c| matches!(c, crate::tree::TreeConflict::Name { .. }))
1329
        {
13307121×
            return raw;
1331389×
        }
1332389×
        let (view, decided) = self.tree.unify(raw, |es| self.same_content(es));
1333389×
        if decided {
1334389×
            let _ = self.unified_view.set(view.clone());
1335389×
        }
1336389×
        view
13377574×
    }
1338
1339
    /// The text files [`State::view`] must compare and a history-only
1340
    /// state has not built: candidates of the tree's name conflicts.
13412495×
    pub fn unify_candidates(&self) -> Vec<NodeId> {
13422495×
        let Some(deferred) = &self.deferred else {
13430×
            return Vec::new();
1344
        };
13452495×
        if self.unified_view.get().is_some() {
13460×
            return Vec::new();
13472495×
        }
13482495×
        let raw = self.tree.view();
13492495×
        let mut out = Vec::new();
13502495×
        for c in &raw.conflicts {
1351119×
            if let crate::tree::TreeConflict::Name { nodes, .. } = c {
1352250×
                out.extend(nodes.iter().filter(|n| deferred.contains_key(*n)));
13530×
            }
1354
        }
13552495×
        out
13562495×
    }
1357
1358
    /// Whether the entries' contents are identical, unconflicted: the same
1359
    /// rendering for text files, the same single blob for opaque ones,
1360
    /// symlinks and subrepos. `None` for a text file not built yet.
1361389×
    fn same_content(&self, entries: &[&crate::tree::TreeEntry]) -> Option<bool> {
1362808×
        let text = |e: &crate::tree::TreeEntry| e.kind == NodeKind::File && !e.mode.opaque;
1363389×
        let mut first: Option<Vec<u8>> = None;
1364389×
        let mut first_blob: Option<ObjectRef> = None;
1365808×
        for e in entries {
1366808×
            if text(e) {
1367794×
                if self
1368794×
                    .deferred
1369794×
                    .as_ref()
1370794×
                    .is_some_and(|d| d.contains_key(&e.node))
1371
                {
13720×
                    return None;
1373794×
                }
1374794×
                let (bytes, m) = self.render_file(&e.node);
1375794×
                if m.is_conflicted() {
13760×
                    return Some(false);
1377794×
                }
1378412×
                match &first {
1379382×
                    None => first = Some(bytes),
1380412×
                    Some(b) if *b == bytes => {}
1381222×
                    Some(_) => return Some(false),
1382
                }
1383
            } else {
138414×
                let [blob] = self.live_blobs(&e.node)[..] else {
13850×
                    return Some(false);
1386
                };
13877×
                match first_blob {
13887×
                    None => first_blob = Some(blob),
13897×
                    Some(b) if b == blob => {}
13900×
                    Some(_) => return Some(false),
1391
                }
1392
            }
1393
        }
1394167×
        Some(true)
1395389×
    }
1396656×
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
1397656×
        self.graph(node)
1398656×
    }
1399
1400
    /// Add a change whose dependencies are already present.
14012824×
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
14022824×
        let h = change.hash();
14032824×
        self.add_hashed(h, change)
14042824×
    }
1405
1406
    /// [`State::add`] for a change whose hash `h` is already known (it was
1407
    /// just stored), so it is not encoded again.
14083601×
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
14093601×
        if self.changes.contains_key(&h) {
141048×
            return Ok(h);
14113553×
        }
14125026×
        for d in &change.deps {
14135026×
            if !self.changes.contains_key(d) {
14142×
                return Err(StateError::MissingDep(*d, h));
14155024×
            }
1416
        }
14173551×
        self.add_known(h, change, Vec::new());
14183551×
        Ok(h)
14193601×
    }
1420
1421
    /// Add a change in any order; call `validate` once all are in.
1422960×
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
1423960×
        let h = change.hash();
1424960×
        self.add_known(h, change, Vec::new());
1425960×
        h
1426960×
    }
1427
1428
    /// Add a change just stored under hash `h` to a history-only state that
1429
    /// has built some graphs: an edit of a built graph is applied whole
1430
    /// (from `full`), and one of a file not built waits without its text
1431
    /// (from `skeleton` and its `texts`, as the store reads it back), so the
1432
    /// state holds no text it has not built. A Git import adds each change
1433
    /// it makes this way, keeping memory to what changes.
143492×
    pub fn add_known_mixed(
143592×
        &mut self,
143692×
        h: ChangeHash,
143792×
        full: Change,
143892×
        skeleton: Change,
143992×
        texts: Vec<TextRef>,
144092×
    ) {
144192×
        if self.deferred.is_none() || self.changes.contains_key(&h) {
14420×
            self.add_known(h, full, Vec::new());
14430×
            return;
144492×
        }
1445
        let Change {
144692×
            version,
144792×
            change_id,
144892×
            deps,
144992×
            author,
145092×
            hlc,
145192×
            message,
145292×
            tree_ops,
145392×
            edits: full_edits,
145492×
            kind,
145592×
        } = full;
145692×
        let mut texts = texts.into_iter();
145792×
        let mut edits = Vec::with_capacity(full_edits.len());
145892×
        let mut kept = Vec::new();
145997×
        for (f, s) in full_edits.into_iter().zip(skeleton.edits) {
146097×
            let text = match &s {
146177×
                Edit::Insert { lines, .. } if lines.is_empty() => texts.next(),
146220×
                _ => None,
1463
            };
146497×
            if self.files.contains_key(&f.node()) {
146545×
                edits.push(f);
146652×
            } else {
146752×
                edits.push(s);
146852×
                kept.extend(text);
146952×
            }
1470
        }
147192×
        let c = Change {
147292×
            version,
147392×
            change_id,
147492×
            deps,
147592×
            author,
147692×
            hlc,
147792×
            message,
147892×
            tree_ops,
147992×
            edits,
148092×
            kind,
148192×
        };
148292×
        self.add_known(h, c, kept);
148392×
    }
1484
1485
    /// Add a change read from the store under hash `h`, without hashing it
1486
    /// again (for a version 2 change that means chunking all its text).
1487
    /// `texts` names, in order, the inserts left without their lines (see
1488
    /// [`crate::store::Store::get_change_lazy`]); only a history-only state
1489
    /// takes them, and only for graphs it has not built.
149014219×
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
149114219×
        if self.changes.contains_key(&h) {
14920×
            return;
149314219×
        }
149414219×
        let meta = ChangeMeta::of(&change);
149514219×
        self.unified_view = Default::default();
149614219×
        self.apply_with(h, change, texts);
149714219×
        self.changes.insert(h, Arc::new(meta));
149814219×
        {
149914219×
            let mut m = self.closure.write().unwrap();
150014219×
            m.sets.clear();
150114219×
            m.held = 0;
150214219×
        }
150314219×
    }
1504
1505
    // ------------------------------------------------------------ checkpoints (spec §11)
1506
1507
    /// Serialize the whole state in payload version 1: change metadata,
1508
    /// tree, file graphs, replaces, all in one value (spec §11).
1509380×
    pub fn checkpoint_payload(&self) -> Vec<u8> {
1510380×
        self.require_full("a checkpoint");
1511380×
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
1512380×
        nodes.sort();
1513380×
        let files = Value::Array(
1514380×
            nodes
1515380×
                .into_iter()
15161473×
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
1517380×
                .collect(),
1518
        );
1519380×
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
1520380×
    }
1521
1522
    /// Each file graph encoded on its own, by node, for a version 2 payload
1523
    /// (spec §11): the graphs of large files become blobs of their own.
152419×
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
1525
        use rayon::prelude::*;
152619×
        self.require_full("a checkpoint");
152719×
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
152854×
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
152919×
        nodes.sort_by_key(|(n, _)| **n);
153019×
        nodes
153119×
            .into_par_iter()
153254×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
153319×
            .collect()
153419×
    }
1535
1536
    /// The payload version 2 index for the graphs of
1537
    /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than
1538
    /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by
1539
    /// `blob_of` (the ObjectRef of the blob holding its encoding).
154019×
    pub fn checkpoint_index(
154119×
        &self,
154219×
        graphs: &[(NodeId, Vec<u8>)],
154319×
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
154419×
    ) -> Vec<u8> {
154519×
        let files = Value::Array(
154619×
            graphs
154719×
                .iter()
154854×
                .map(|(n, enc)| {
154954×
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
155047×
                        cbor::decode(enc).expect("an encoded graph decodes")
1551
                    } else {
15527×
                        Value::Bytes(blob_of(enc).0.to_vec())
1553
                    };
155454×
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
155554×
                })
155619×
                .collect(),
1557
        );
155819×
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
155919×
    }
1560
1561
    /// The payload map around `files`: changes, tree and replaces as in version 1.
1562399×
    fn payload_value(&self, version: u64, files: Value) -> Value {
1563399×
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
1564399×
        hashes.sort();
1565399×
        let changes = Value::Array(
1566399×
            hashes
1567399×
                .into_iter()
15682178×
                .map(|h| {
15692178×
                    let m = &self.changes[h];
15702178×
                    Value::Array(vec![
15712178×
                        Value::Bytes(h.0.to_vec()),
15722178×
                        Value::Bytes(m.change_id.0.to_vec()),
15732178×
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
15742178×
                        Value::Text(m.message.clone()),
15752178×
                        Value::Uint(m.hlc.wall_ms),
15762178×
                        Value::Uint(m.hlc.logical as u64),
15772178×
                        Value::Uint(m.kind.tag()),
15782178×
                        Value::Bytes(m.author.0.to_vec()),
1579
                    ])
15802178×
                })
1581399×
                .collect(),
1582
        );
1583399×
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
1584399×
        rnodes.sort();
1585399×
        let opt =
158612×
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
1587399×
        let replaces = Value::Array(
1588399×
            rnodes
1589399×
                .into_iter()
1590399×
                .map(|n| {
15916×
                    Value::Array(vec![
15926×
                        Value::Bytes(n.0.to_vec()),
1593
                        Value::Array(
15946×
                            self.replaces[n]
15956×
                                .iter()
15966×
                                .map(|(c, o, nw)| {
15976×
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
15986×
                                })
15996×
                                .collect(),
1600
                        ),
1601
                    ])
16026×
                })
1603399×
                .collect(),
1604
        );
1605399×
        Value::map([
1606399×
            (0, Value::Uint(version)),
1607399×
            (1, changes),
1608399×
            (2, self.tree.to_value()),
1609399×
            (3, files),
1610399×
            (4, replaces),
1611399×
        ])
1612399×
    }
1613
1614
    /// Decode a version 1 payload (the whole state in one value). A
1615
    /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`].
161637×
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
161737×
        State::from_checkpoint(bytes, |_| {
16181×
            Err(ObjectError::Schema(
16191×
                "a version 2 checkpoint needs its graph blobs".into(),
16201×
            ))
16211×
        })
162237×
    }
1623
1624
    /// Decode a checkpoint payload of either version (spec §11). For
1625
    /// version 2, `load` returns the contents of the named graph blobs, in
1626
    /// order; the graphs are then decoded in parallel.
162760×
    pub fn from_checkpoint(
162860×
        bytes: &[u8],
162960×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
163060×
    ) -> Result<State, ObjectError> {
1631
        use rayon::prelude::*;
163260×
        let v = cbor::decode(bytes)?;
163359×
        let m = o::map(&v, "checkpoint payload")?;
163459×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
163559×
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
16361×
            return Err(ObjectError::Schema(format!(
16371×
                "checkpoint payload version {version} is not supported"
16381×
            )));
163958×
        }
164058×
        let mut st = State::payload_common(m)?;
164158×
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
164258×
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
1643230×
        for f in entries {
1644230×
            let e = o::array(f, "file")?;
1645230×
            if e.len() != 2 {
16460×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1647230×
            }
1648230×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1649230×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1650230×
            parsed.push((node, &e[1]));
1651
        }
1652
        // Version 2 names large graphs by blob: fetch those in one batch.
165358×
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
165458×
        if version == CHECKPOINT_INDEX_VERSION {
165520×
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
165620×
                .iter()
165790×
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
165820×
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
165920×
                .collect::<Result<_, ObjectError>>()?;
166020×
            if !wanted.is_empty() {
16617×
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
16623×
                let contents = {
16637×
                    let _t = crate::timing::phase("load:   graph blobs read");
16647×
                    load(&refs)?
1665
                };
16663×
                if contents.len() != refs.len() {
16670×
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
16683×
                }
16693×
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
167013×
            }
1671140×
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
16720×
            return Err(ObjectError::Schema(
16730×
                "a version 1 payload holds graphs inline".into(),
16740×
            ));
167538×
        }
1676
        // File graphs are independent; decode and build them in parallel.
167754×
        let graphs = parsed
167854×
            .par_iter()
1679224×
            .map(|(node, entry)| {
1680224×
                let graph = match fetched.get(node) {
16813×
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
1682221×
                    None => FileGraph::from_value(entry)?,
1683
                };
1684224×
                Ok((*node, graph))
1685224×
            })
168654×
            .collect::<Result<Vec<_>, ObjectError>>()?;
168754×
        st.files
1688224×
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
168954×
        Ok(st)
169060×
    }
1691
1692
    /// The graph blobs a payload names: empty for version 1.
169311×
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
169411×
        let v = cbor::decode(bytes)?;
169511×
        let m = o::map(&v, "checkpoint payload")?;
169611×
        let mut out = Vec::new();
169729×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
169829×
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
16996×
                out.push(o::oref(entry, "graph blob")?);
170023×
            }
1701
        }
170211×
        Ok(out)
170311×
    }
1704
1705
    /// Decode a checkpoint payload for history only: a version 2 payload's
1706
    /// graphs are noted, not read or built, and come later through
1707
    /// [`State::load_graphs`]. A version 1 payload holds them inline and is
1708
    /// decoded in full.
170960×
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
171060×
        let v = cbor::decode(bytes)?;
171160×
        let m = o::map(&v, "checkpoint payload")?;
171260×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
171360×
        if version != CHECKPOINT_INDEX_VERSION {
17141×
            return State::from_checkpoint_payload(bytes);
171559×
        }
171659×
        let mut st = State::payload_common(m)?;
171759×
        let mut deferred = crate::fasthash::FastMap::default();
1718157×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1719157×
            let e = o::array(f, "file")?;
1720157×
            if e.len() != 2 {
17210×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1722157×
            }
1723157×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1724157×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1725157×
            let base = match &e[1] {
17264×
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
1727153×
                other => DeferredBase::Inline(other.clone()),
1728
            };
1729157×
            deferred.insert(
1730157×
                node,
1731157×
                Arc::new(Deferred::from_body(DeferredBody {
1732157×
                    base: Some(base),
1733157×
                    ..DeferredBody::default()
1734157×
                })),
1735
            );
1736
        }
173759×
        st.deferred = Some(deferred);
173859×
        Ok(st)
173960×
    }
1740
1741
    /// Changes, tree and replaces of a payload of either version.
1742117×
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
1743117×
        let mut st = State::new();
1744537×
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
1745537×
            let e = o::array(c, "change meta")?;
1746537×
            if e.len() != 8 {
17470×
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
1748537×
            }
1749537×
            let hash = o::oref(&e[0], "hash")?;
1750537×
            let meta = ChangeMeta {
1751537×
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
1752537×
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
1753537×
                deps: o::array(&e[2], "deps")?
1754537×
                    .iter()
1755642×
                    .map(|d| o::oref(d, "dep"))
1756537×
                    .collect::<Result<Vec<_>, _>>()?,
1757537×
                message: o::text(&e[3], "message")?.to_owned(),
1758
                hlc: Hlc {
1759537×
                    wall_ms: o::uint(&e[4], "wall")?,
1760537×
                    logical: o::u32_(&e[5], "logical")?,
1761
                },
1762537×
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
1763537×
                author: o::oref(&e[7], "author")?,
1764
            };
1765537×
            st.changes.insert(hash, Arc::new(meta));
1766
        }
1767117×
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
1768117×
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
176958×
            if v.is_null() {
177029×
                Ok(None)
1771
            } else {
177229×
                o::oref(v, "blob").map(Some)
1773
            }
177458×
        };
1775117×
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
177629×
            let e = o::array(r, "replace")?;
177729×
            if e.len() != 2 {
17780×
                return Err(ObjectError::Schema(
17790×
                    "replace: expected [node, records]".into(),
17800×
                ));
178129×
            }
178229×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
178329×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
178429×
            let mut recs = Vec::new();
178529×
            for rec in o::array(&e[1], "records")? {
178629×
                let x = o::array(rec, "record")?;
178729×
                if x.len() != 3 {
17880×
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
178929×
                }
179029×
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
1791
            }
179229×
            st.replaces.insert(node, recs);
1793
        }
1794117×
        Ok(st)
1795117×
    }
1796
17974290×
    pub fn validate(&self) -> Result<(), StateError> {
179810749×
        for (h, c) in &self.changes {
179910749×
            for d in &c.deps {
18006346×
                if !self.changes.contains_key(d) {
18010×
                    return Err(StateError::MissingDep(*d, *h));
18026346×
                }
1803
            }
1804
        }
18054290×
        Ok(())
18064290×
    }
1807
180814219×
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
180940430×
        for (i, op) in c.tree_ops.iter().enumerate() {
181040430×
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
181140430×
        }
181214219×
        if let Some(deferred) = self.deferred.as_mut() {
1813
            // History only: edits of files not built wait, grouped per file,
1814
            // with the texts of inserts read without their lines.
18158903×
            let mut texts = texts.into_iter();
18168903×
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
181741229×
            for e in c.edits {
181841229×
                match e {
1819883×
                    Edit::Replace { node, old, new } => {
1820883×
                        self.replaces.entry(node).or_default().push((h, old, new))
1821
                    }
182240346×
                    e => {
182340346×
                        let slot = per_node.entry(e.node()).or_default();
182438072×
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
182534358×
                            slot.1.extend(texts.next());
182634358×
                        }
182740346×
                        slot.0.push(e);
1828
                    }
1829
                }
1830
            }
183137832×
            for (node, (edits, node_texts)) in per_node {
183237832×
                match self.files.get_mut(&node) {
1833502×
                    Some(g) => {
1834502×
                        assert!(
1835502×
                            node_texts.is_empty(),
1836
                            "a change read without its text applied to a built graph"
1837
                        );
1838502×
                        apply_file_edits(Arc::make_mut(g), h, edits)
1839
                    }
184037330×
                    None => {
184137330×
                        let d = Arc::make_mut(deferred.entry(node).or_default());
184237330×
                        d.add(h, edits, node_texts);
184337330×
                        d.key = Default::default();
184437330×
                    }
1845
                }
1846
            }
18478903×
            return;
18485316×
        }
18495316×
        assert!(
18505316×
            texts.is_empty(),
1851
            "a change read without its text applied to a full state"
1852
        );
18535316×
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
18546401×
        for e in c.edits {
18556401×
            match e {
1856
                Edit::Insert {
18574718×
                    node,
18584718×
                    after,
18594718×
                    before,
18604718×
                    lines,
18614718×
                } => {
18624718×
                    let idx = counters.entry(node).or_default();
18634718×
                    let first = *idx;
18644718×
                    *idx += lines.len() as u32;
18654718×
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
18664718×
                        h,
18674718×
                        first,
18684718×
                        vertex(after.resolve(h)),
18694718×
                        vertex(before.resolve(h)),
18704718×
                        lines,
18714718×
                    );
18724718×
                }
18731560×
                Edit::Delete { node, atoms } => {
18741560×
                    let g = Arc::make_mut(self.files.entry(node).or_default());
18751872×
                    for r in atoms {
18761872×
                        g.delete(h, &r.resolve(h));
18771872×
                    }
1878
                }
1879123×
                Edit::Replace { node, old, new } => {
1880123×
                    self.replaces.entry(node).or_default().push((h, old, new));
1881123×
                }
1882
            }
1883
        }
188414219×
    }
1885
1886
    /// Transitive dependencies of `h`, excluding `h` itself.
18879197×
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
18889197×
        if let Some(c) = self.closure.read().unwrap().sets.get(h) {
18897797×
            return c.clone();
18901400×
        }
18911400×
        let mut out = HashSet::new();
18921400×
        let mut stack: Vec<ChangeHash> = self
18931400×
            .changes
18941400×
            .get(h)
18951400×
            .map(|c| c.deps.clone())
18961400×
            .unwrap_or_default();
189716842×
        while let Some(d) = stack.pop() {
189815442×
            if out.insert(d) {
189910925×
                if let Some(c) = self.changes.get(&d) {
190010925×
                    stack.extend(c.deps.iter().copied());
190110925×
                }
19024517×
            }
1903
        }
19041400×
        let rc = Arc::new(out);
19051400×
        let mut memo = self.closure.write().unwrap();
19061400×
        if memo.held + rc.len() > CLOSURE_MEMO_HASHES {
19070×
            memo.sets.clear();
19080×
            memo.held = 0;
19091400×
        }
19101400×
        memo.held += rc.len();
19111400×
        memo.sets.insert(*h, rc.clone());
19121400×
        rc
19139197×
    }
1914
1915
    /// `h`'s level (see `levels`), worked out for it and its ancestors not
1916
    /// yet known, without recursion: histories are deeper than a stack. An
1917
    /// unknown change has level 0.
1918381664×
    fn level(&self, h: &ChangeHash) -> u32 {
1919
        // Nearly always known: read without excluding the other threads
1920
        // rendering beside this one (oxygen#96).
1921381664×
        if let Some(l) = self.levels.read().unwrap().get(h) {
1922378591×
            return *l;
19233073×
        }
19243073×
        let mut levels = self.levels.write().unwrap();
19253073×
        if let Some(l) = levels.get(h) {
192613×
            return *l;
19273060×
        }
19283060×
        let mut stack: Vec<(ChangeHash, bool)> = vec![(*h, false)];
19299918×
        while let Some((c, expanded)) = stack.pop() {
19306858×
            if levels.contains_key(&c) {
193132×
                continue;
19326826×
            }
19336826×
            let deps: &[ChangeHash] = self
19346826×
                .changes
19356826×
                .get(&c)
19366826×
                .map(|m| m.deps.as_slice())
19376826×
                .unwrap_or(&[]);
19386826×
            if expanded {
19393413×
                let l = deps
19403413×
                    .iter()
19413964×
                    .map(|d| levels.get(d).map_or(0, |l| l + 1))
19423413×
                    .max()
19433413×
                    .unwrap_or(0);
19443413×
                levels.insert(c, l);
1945
            } else {
19463413×
                stack.push((c, true));
19473964×
                for d in deps {
19483964×
                    if !levels.contains_key(d) {
1949385×
                        stack.push((*d, false));
19503579×
                    }
1951
                }
1952
            }
1953
        }
19543060×
        levels[h]
1955381664×
    }
1956
1957
    /// Changes that no other change depends on directly, sorted.
1958397×
    pub fn heads(&self) -> Vec<ChangeHash> {
1959397×
        let depended: crate::fasthash::FastSet<&ChangeHash> =
19603346×
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
1961397×
        let mut heads: Vec<ChangeHash> = self
1962397×
            .changes
1963397×
            .keys()
19643346×
            .filter(|h| !depended.contains(h))
1965397×
            .copied()
1966397×
            .collect();
1967397×
        heads.sort();
1968397×
        heads
1969397×
    }
1970
1971
    /// Maximal elements among `hashes` (those not in the closure of another),
1972
    /// sorted. One walk down from all of them at once: whatever the walk
1973
    /// reaches is below some other element. Linear in the changes reached,
1974
    /// where comparing every pair's closures was quadratic in the number
1975
    /// of heads, which a bookmark of independent changes has many of.
197610862×
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
197710862×
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
197810862×
        let mut below: crate::fasthash::FastSet<ChangeHash> = Default::default();
197910862×
        let mut stack: Vec<ChangeHash> = set
198010862×
            .iter()
198118908×
            .filter_map(|h| self.changes.get(h))
198215901×
            .flat_map(|c| c.deps.iter().copied())
198310862×
            .collect();
198425760×
        while let Some(d) = stack.pop() {
198514898×
            if below.insert(d) {
19867333×
                if let Some(c) = self.changes.get(&d) {
19877333×
                    stack.extend(c.deps.iter().copied());
19887333×
                }
19897565×
            }
1990
        }
199118908×
        set.into_iter().filter(|h| !below.contains(h)).collect()
199210862×
    }
1993
19940×
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
19950×
        self.graph(node)
19960×
            .map(|g| g.materialize(self))
19970×
            .unwrap_or_default()
19980×
    }
1999
2000
    /// Live lines of a text node in materialized order.
200121×
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
200221×
        let Some(g) = self.graph(node) else {
20032×
            return vec![];
2004
        };
200519×
        let m = g.materialize(self);
200619×
        m.live_atoms()
200719×
            .into_iter()
200845×
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
200919×
            .collect()
201021×
    }
2011
2012
    /// The nodes with replace records: opaque files, as their blobs go.
20134×
    pub fn opaque_nodes(&self) -> Vec<NodeId> {
20144×
        let mut nodes: Vec<NodeId> = self.replaces.keys().copied().collect();
20154×
        nodes.sort();
20164×
        nodes
20174×
    }
2018
2019
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
20201096×
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
20211096×
        let mut live: Vec<ObjectRef> = self
20221096×
            .live_replaces(node)
20231096×
            .into_iter()
20241096×
            .map(|(_, n)| n)
20251096×
            .collect();
20261096×
        live.sort();
20271096×
        live.dedup();
20281096×
        live
20291096×
    }
2030
2031
    /// The replace records whose blob is live, with the change that set it
2032
    /// (spec §9.3). A record's blob is superseded by a later replacement of
2033
    /// that blob: one whose change depends on the record's change, as every
2034
    /// replacement depends on the change that made its old blob current
2035
    /// (§8.1). Two replacements that do not know each other both stay live
2036
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
2037
    /// A replacement without that dependency, from before the rule, is read
2038
    /// as before: it supersedes every record that did not come after it.
20391157×
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
20401157×
        let Some(rs) = self.replaces.get(node) else {
20410×
            return vec![];
2042
        };
2043
        // Dependence by the bounded walk rather than whole closures: on a
2044
        // long history a closure is a hundred thousand changes, and the
2045
        // memo cannot keep them all (#107).
20461157×
        let dep =
2047265×
            |a: &ChangeHash, b: &ChangeHash| a != b && <Self as DepOracle>::depends_on(self, a, b);
20481157×
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
204911×
            rs.iter()
205020×
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && dep(s, q))
205111×
        };
20521157×
        rs.iter()
20531478×
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
20541478×
            .filter(|(c, n)| {
20552131×
                !rs.iter().any(|(s, o, _)| {
20562131×
                    s != c && *o == Some(*n) && (dep(s, c) || (!knows_its_old(s, n) && !dep(c, s)))
20572131×
                })
20581478×
            })
20591157×
            .collect()
20601157×
    }
2061
2062
    /// Short label for conflict markers: `changeid-prefix "message"`.
20631321×
    pub fn label(&self, h: &ChangeHash) -> String {
20641321×
        match self.changes.get(h) {
20651321×
            Some(c) => format!(
2066
                "{} \"{}\"",
20671321×
                c.change_id.short(8),
20681321×
                c.message.lines().next().unwrap_or("")
2069
            ),
20700×
            None => format!("#{}", h.short(12)),
2071
        }
20721321×
    }
2073
2074
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
2075
    /// are not part of any conflict region in order, every live atom that is
2076
    /// part of a region, and every change that contributed to a region.
2077
    /// The changes that introduced the live blobs of an opaque node, for a
2078
    /// replace conflict (spec §9.3).
20795×
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
20805×
        let mut out: Vec<ChangeHash> = Vec::new();
208115×
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
208215×
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
208310×
                out.push(*h);
208410×
            }
2085
        }
20865×
        out.sort();
20875×
        out
20885×
    }
2089
209054×
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
209154×
        let mut out = ConflictRegions::default();
209254×
        let Some(g) = self.graph(node) else {
20930×
            return out;
2094
        };
209554×
        let m = g.materialize(self);
209654×
        let mut contributors = BTreeSet::new();
2097143×
        for seg in &m.segments {
2098143×
            match seg {
209989×
                crate::graph::Segment::Lines(atoms) => {
2100114×
                    for a in atoms {
2101114×
                        out.plain
2102114×
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
2103114×
                    }
2104
                }
210554×
                crate::graph::Segment::Conflict(sides) => {
2106108×
                    for side in sides {
2107110×
                        for a in side {
2108110×
                            out.region_atoms.push(*a);
2109110×
                            contributors.insert(a.0);
2110110×
                        }
2111
                    }
2112
                }
21130×
                crate::graph::Segment::Zombie { deleted, inserted } => {
21140×
                    for a in deleted {
21150×
                        contributors.insert(a.0);
21160×
                        contributors.extend(g.deleters(a).copied());
21170×
                    }
21180×
                    for a in inserted {
21190×
                        out.region_atoms.push(*a);
21200×
                        contributors.insert(a.0);
21210×
                    }
2122
                }
2123
            }
2124
        }
212554×
        out.contributors = contributors.into_iter().collect();
212654×
        out
212754×
    }
2128
2129
    /// A file graph materialized with each conflict's sides earliest change
2130
    /// first (oxygen#121), by the clock of the oldest change on a side, so
2131
    /// markers read in the order the work was done and `oxy resolve --both`
2132
    /// keeps that order.
213326158×
    fn materialize_ordered(&self, g: &FileGraph) -> Materialized {
213426158×
        let mut m = g.materialize(self);
213526158×
        let when = |h: &ChangeHash| match self.changes.get(h) {
2136980×
            Some(c) => (false, c.hlc, *h),
21370×
            None => (true, Default::default(), *h),
2138980×
        };
213926967×
        for seg in &mut m.segments {
214026967×
            if let crate::graph::Segment::Conflict(sides) = seg {
2141980×
                sides.sort_by_cached_key(|s| s.iter().map(|a| when(&a.0)).min());
214226501×
            }
2143
        }
214426158×
        m
214526158×
    }
2146
2147
    /// For each conflict of a text node, in marker order (spec §9.5): the
2148
    /// text of its sides, earliest change first, when it is an adjacent
2149
    /// insertion that keeping both sides settles (oxygen#121); `None` for
2150
    /// the others.
21516×
    pub fn both_sides(&self, node: &NodeId) -> Vec<Option<Vec<Vec<u8>>>> {
21526×
        let Some(g) = self.graph(node) else {
21530×
            return Vec::new();
2154
        };
21556×
        let m = self.materialize_ordered(g);
21566×
        let mut out = Vec::new();
215718×
        for (i, seg) in m.segments.iter().enumerate() {
21586×
            match seg {
215912×
                crate::graph::Segment::Lines(_) => {}
21606×
                crate::graph::Segment::Conflict(sides) if g.adjacent_insertion(&m, i, self) => {
21614×
                    out.push(Some(
21624×
                        sides
21634×
                            .iter()
21648×
                            .map(|s| {
21658×
                                s.iter()
21668×
                                    .flat_map(|a| g.content(a).unwrap_or_default().to_vec())
21678×
                                    .collect()
21688×
                            })
21694×
                            .collect(),
2170
                    ));
2171
                }
21722×
                _ => out.push(None),
2173
            }
2174
        }
21756×
        out
21766×
    }
2177
2178
    /// How each conflict of a text node settles without a person, in
2179
    /// marker order (spec §9.5); `None` for one that needs a person. A
2180
    /// conflict whose sides are identical keeps one of them, in any file
2181
    /// (oxygen#146): two bookmarks that resolved the same conflict the same
2182
    /// way agree. With `union` (the file is `merge=union`, oxygen#145), an
2183
    /// adjacent insertion keeps every side, earliest change first.
218467×
    pub fn settle_plans(&self, node: &NodeId, union: bool) -> Vec<Option<Settle>> {
218567×
        let Some(g) = self.graph(node) else {
21860×
            return Vec::new();
2187
        };
218867×
        let m = self.materialize_ordered(g);
218988×
        let text = |s: &[AtomKey]| -> Vec<u8> {
219088×
            s.iter()
219193×
                .flat_map(|a| g.content(a).unwrap_or_default().to_vec())
219288×
                .collect()
219388×
        };
219467×
        let mut out = Vec::new();
2195167×
        for (i, seg) in m.segments.iter().enumerate() {
2196167×
            match seg {
219783×
                crate::graph::Segment::Lines(_) => {}
219844×
                crate::graph::Segment::Conflict(sides) => {
219988×
                    let texts: Vec<Vec<u8>> = sides.iter().map(|s| text(s)).collect();
220088×
                    out.push(if texts.len() > 1 && texts.iter().all(|t| *t == texts[0]) {
22019×
                        Some(Settle {
22029×
                            kept: vec![texts[0].clone()],
22039×
                            sides: texts,
22049×
                            identical: true,
22059×
                        })
220635×
                    } else if union && g.adjacent_insertion(&m, i, self) {
22072×
                        Some(Settle {
22082×
                            kept: texts.clone(),
22092×
                            sides: texts,
22102×
                            identical: false,
22112×
                        })
2212
                    } else {
221333×
                        None
2214
                    });
2215
                }
221640×
                _ => out.push(None),
2217
            }
2218
        }
221967×
        out
222067×
    }
2221
222226710×
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
222326710×
        let Some(g) = self.graph(node) else {
2224624×
            return (Vec::new(), Materialized::default());
2225
        };
222626086×
        let m = self.materialize_ordered(g);
222726086×
        let bytes = g.render(&m, &|h| self.label(h));
222826086×
        (bytes, m)
222926710×
    }
2230
2231
    /// Every file rendered, in parallel: files are independent, and
2232
    /// rendering them is most of a snapshot's cost in a large tree.
22333045×
    pub fn materialize(&self) -> Snapshot {
2234
        use rayon::prelude::*;
22353045×
        self.require_full("materializing a state");
22363045×
        let tree = self.view();
22373045×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
22383045×
        let rendered: Vec<(String, FileState)> = entries
22393045×
            .par_iter()
224018069×
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
22413045×
            .collect();
22423045×
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
22433045×
        Snapshot {
22443045×
            tree,
22453045×
            files,
22463045×
            unrendered: BTreeSet::new(),
22473045×
        }
22483045×
    }
2249
2250
    /// Like [`State::materialize`], leaving the text files of nodes in
2251
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
2252
    /// file's graph must be loaded. For a caller that already knows those
2253
    /// files are unchanged and not conflicted. Its tree is the tree
2254
    /// graph's own view, as a Git import builds against it: same-path
2255
    /// additions are not unified ([`State::view`]), since the import's
2256
    /// merge records Git's tree for them itself.
225720×
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
225820×
        self.materialize_leaving(self.tree.view(), |_, e| skip.contains(&e.node))
225920×
    }
2260
2261
    /// As [`State::materialize_except`], rendering only the text files at
2262
    /// `render` (a few, where the caller knows the rest unchanged), with
2263
    /// the tree as [`State::view`] has it.
22641031×
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
22657983×
        self.materialize_leaving(self.view(), |p, _| !render.contains(p))
22661031×
    }
2267
2268
    /// As [`State::materialize_only`], rendering only the text files of
2269
    /// the nodes in `render` (a change's edited files), without a set of
2270
    /// every other file to leave out.
2271232×
    pub fn materialize_nodes(&self, render: &HashSet<NodeId>) -> Snapshot {
2272594×
        self.materialize_leaving(self.view(), |_, e| !render.contains(&e.node))
2273232×
    }
2274
22751283×
    fn materialize_leaving(
22761283×
        &self,
22771283×
        tree: TreeView,
22781283×
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
22791283×
    ) -> Snapshot {
2280
        use rayon::prelude::*;
22811283×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
22821283×
        let rendered: Vec<(String, FileState, bool)> = entries
22831283×
            .par_iter()
22848953×
            .map(|(path, e)| {
22858953×
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
22864566×
                    let f = FileState {
22874566×
                        node: e.node,
22884566×
                        kind: e.kind,
22894566×
                        mode: e.mode,
22904566×
                        content: FileContent::Text {
22914566×
                            bytes: Vec::new(),
22924566×
                            materialized: Materialized::default(),
22934566×
                        },
22944566×
                    };
22954566×
                    (path.to_string(), f, true)
2296
                } else {
22974387×
                    (path.to_string(), self.file_state(e), false)
2298
                }
22998953×
            })
23001283×
            .collect();
2301
        // In the view's path order, so the maps are built without searching.
23021283×
        let unrendered: BTreeSet<String> = rendered
23031283×
            .iter()
23041283×
            .filter(|(_, _, skipped)| *skipped)
23054566×
            .map(|(p, _, _)| p.clone())
23061283×
            .collect();
23071283×
        let files: BTreeMap<String, FileState> =
23088953×
            rendered.into_iter().map(|(p, f, _)| (p, f)).collect();
23091283×
        Snapshot {
23101283×
            tree,
23111283×
            files,
23121283×
            unrendered,
23131283×
        }
23141283×
    }
2315
2316
    /// A snapshot of only `paths` (those `view` has), `view` being this
2317
    /// state's tree view: for a caller that works from what changed. The
2318
    /// graphs of those text files must be loaded.
231990×
    pub fn materialize_paths<'p>(
232090×
        &self,
232190×
        view: crate::tree::TreeView,
232290×
        paths: impl IntoIterator<Item = &'p str>,
232390×
    ) -> Snapshot {
2324
        use rayon::prelude::*;
2325
        // On every core: a merge may render thousands (oxygen#96).
232690×
        let entries: Vec<(&str, &crate::tree::TreeEntry)> = paths
232790×
            .into_iter()
2328131×
            .filter_map(|p| Some((p, view.entries.get(p)?)))
232990×
            .collect();
233090×
        let files = entries
233190×
            .par_iter()
2332107×
            .map(|(p, e)| (p.to_string(), self.file_state(e)))
233390×
            .collect::<Vec<_>>()
233490×
            .into_iter()
233590×
            .collect();
233690×
        Snapshot {
233790×
            tree: view,
233890×
            files,
233990×
            unrendered: BTreeSet::new(),
234090×
        }
234190×
    }
2342
2343
    /// The state of one tree entry: a directory, an opaque file's live
2344
    /// blobs, or a text file rendered from its graph (which must be built).
23450×
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
23460×
        self.file_state(e)
23470×
    }
2348
234922563×
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
2350
        {
235122563×
            let content = match e.kind {
23521569×
                NodeKind::Dir => FileContent::Dir,
2353189×
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
2354189×
                    blobs: self.live_blobs(&e.node),
2355189×
                },
2356624×
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
2357624×
                    blobs: self.live_blobs(&e.node),
2358624×
                },
2359
                NodeKind::File => {
236020181×
                    let (bytes, materialized) = self.render_file(&e.node);
236120181×
                    FileContent::Text {
236220181×
                        bytes,
236320181×
                        materialized,
236420181×
                    }
2365
                }
2366
            };
236722563×
            FileState {
236822563×
                node: e.node,
236922563×
                kind: e.kind,
237022563×
                mode: e.mode,
237122563×
                content,
237222563×
            }
2373
        }
237422563×
    }
2375
}
2376
2377
impl DepOracle for State {
2378
    /// Whether `a` depends on `b`, by a walk down from `a` that stops at
2379
    /// changes no higher than `b`: they cannot have `b` below them. Nothing
2380
    /// of the walk is kept, so asking about many pairs costs no more memory
2381
    /// than one walk (#25); a closure already memoised answers at once.
238266953×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
238366953×
        if a == b {
2384803×
            return true;
238566150×
        }
238666150×
        if let Some(c) = self.closure.read().unwrap().sets.get(a) {
23870×
            return c.contains(b);
238866150×
        }
238966150×
        if !self.changes.contains_key(b) {
2390800×
            return false;
239165350×
        }
239265350×
        let lb = self.level(b);
239365350×
        if self.level(a) <= lb {
239436027×
            return false;
239529323×
        }
239629323×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2397
        // A dependency is looked for as it is found, before the walk goes
2398
        // below it: most questions are about a direct one (spec §8.1 makes
2399
        // a deletion depend on the inserter of the line after it, which is
2400
        // what a render asks about), and a depth-first walk that only
2401
        // looked when it came back up went through thousands of changes
2402
        // first (oxygen#137: 4.4 billion steps rendering the VS Code tree).
240329323×
        let mut stack: Vec<ChangeHash> = self
240429323×
            .changes
240529323×
            .get(a)
240629323×
            .map(|m| m.deps.clone())
240729323×
            .unwrap_or_default();
240829323×
        if stack.contains(b) {
24093362×
            return true;
241025961×
        }
2411324970×
        while let Some(c) = stack.pop() {
2412305720×
            if c == *b {
24130×
                return true;
2414305720×
            }
2415305720×
            if !seen.insert(c) || self.level(&c) <= lb {
2416205254×
                continue;
2417100466×
            }
2418100466×
            if let Some(m) = self.changes.get(&c) {
2419100466×
                if m.deps.contains(b) {
24206711×
                    return true;
242193755×
                }
242293755×
                stack.extend(m.deps.iter().copied());
24230×
            }
2424
        }
242519250×
        false
242666953×
    }
2427
}
2428
2429
#[cfg(test)]
2430
mod tests {
2431
    use super::*;
2432
2433
    /// A changes block of thousands comes back whole and in order, and a
2434
    /// truncated one is refused (oxygen#94).
2435
    #[test]
24361×
    fn a_long_changes_block_decodes_in_order() {
2437
        use crate::flat::Writer;
24381×
        let metas: Vec<(ChangeHash, ChangeMeta)> = (0..5000u32)
24395000×
            .map(|i| {
24405000×
                let mut h = [0u8; 32];
24415000×
                h[..4].copy_from_slice(&i.to_le_bytes());
24425000×
                let meta = ChangeMeta {
24435000×
                    change_id: crate::ids::ChangeId([i as u8; 16]),
24445000×
                    deps: (0..i % 3).map(|d| ObjectRef([d as u8; 32])).collect(),
24455000×
                    author: ObjectRef([7; 32]),
24465000×
                    hlc: Hlc {
24475000×
                        wall_ms: 1_000_000 - i as u64,
24485000×
                        logical: i,
24495000×
                    },
24505000×
                    message: "x".repeat((i % 50) as usize),
24515000×
                    kind: ChangeKind::Normal,
2452
                };
24535000×
                (ObjectRef(h), meta)
24545000×
            })
24551×
            .collect();
24561×
        let mut w = Writer::default();
24571×
        w.fixed(State::INDEX_MAGIC);
24581×
        w.count(metas.len());
24595000×
        for (h, m) in &metas {
24605000×
            w.object(h);
24615000×
            m.write_flat(&mut w);
24625000×
        }
24631×
        assert_eq!(State::read_index_changes_listed(&w.0).unwrap(), metas);
24641×
        let mut cut = w.0.clone();
24651×
        cut.pop();
24661×
        assert!(
24671×
            State::read_index_changes_listed(&cut).is_err(),
2468
            "a truncated block is refused"
2469
        );
24701×
    }
2471
    use crate::ids::ChangeId;
2472
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
2473
24742023×
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
24752023×
        let mut c = Change {
24762023×
            version: crate::objects::CHANGE_VERSION,
24772023×
            change_id: ChangeId::random(),
24782023×
            deps,
24792023×
            author: ObjectRef::ZERO,
24802023×
            hlc: Hlc {
24812023×
                wall_ms: 1,
24822023×
                logical: 0,
24832023×
            },
24842023×
            message: "m".into(),
24852023×
            tree_ops,
24862023×
            edits,
24872023×
            kind: ChangeKind::Normal,
24882023×
        };
24892023×
        c.normalize();
24902023×
        c
24912023×
    }
2492
2493
    #[test]
24941×
    fn build_edit_and_materialize() {
24951×
        let mut st = State::new();
24961×
        let f = NodeId::random();
24971×
        let c1 = change(
24981×
            vec![],
24991×
            vec![TreeOp::AddNode {
25001×
                node: f,
25011×
                kind: NodeKind::File,
25021×
                mode: Mode::TEXT,
25031×
                parent: NodeId::ROOT,
25041×
                name: "a.txt".into(),
25051×
            }],
25061×
            vec![Edit::Insert {
25071×
                node: f,
25081×
                after: AtomRef::Start,
25091×
                before: AtomRef::End,
25101×
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
25111×
            }],
2512
        );
25131×
        let h1 = st.add(c1).unwrap();
2514
        // Depends on h1: append a line and delete "one".
25151×
        let c2 = change(
25161×
            vec![h1],
25171×
            vec![],
25181×
            vec![
25191×
                Edit::Delete {
25201×
                    node: f,
25211×
                    atoms: vec![AtomRange {
25221×
                        change: h1,
25231×
                        from: 0,
25241×
                        to: 1,
25251×
                    }],
25261×
                },
25271×
                Edit::Insert {
25281×
                    node: f,
25291×
                    after: AtomRef::Atom {
25301×
                        change: h1,
25311×
                        index: 1,
25321×
                    },
25331×
                    before: AtomRef::End,
25341×
                    lines: vec![b"three\n".to_vec()].into(),
25351×
                },
2536
            ],
2537
        );
25381×
        let h2 = st.add(c2).unwrap();
25391×
        assert_eq!(st.heads(), vec![h2]);
25401×
        assert!(st.depends_on(&h2, &h1));
25411×
        assert!(!st.depends_on(&h1, &h2));
25421×
        let snap = st.materialize();
25431×
        assert!(!snap.is_conflicted());
25441×
        let a = &snap.files["a.txt"];
25451×
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
25461×
        assert_eq!(st.live_lines(&f).len(), 2);
25471×
    }
2548
2549
    #[test]
25501×
    fn missing_dependency_is_rejected() {
25511×
        let mut st = State::new();
25521×
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
25531×
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
25541×
    }
2555
2556
    #[test]
25571×
    fn self_references_and_multi_insert_indexing() {
25581×
        let mut st = State::new();
25591×
        let f = NodeId::random();
25601×
        let me = OpRef {
25611×
            change: ObjectRef::ZERO,
25621×
            index: 0,
25631×
        };
25641×
        let c1 = change(
25651×
            vec![],
25661×
            vec![
25671×
                TreeOp::AddNode {
25681×
                    node: f,
25691×
                    kind: NodeKind::File,
25701×
                    mode: Mode::TEXT,
25711×
                    parent: NodeId::ROOT,
25721×
                    name: "x".into(),
25731×
                },
25741×
                TreeOp::SetMode {
25751×
                    node: f,
25761×
                    old: me,
25771×
                    mode: Mode {
25781×
                        exec: true,
25791×
                        opaque: false,
25801×
                    },
25811×
                },
2582
            ],
25831×
            vec![
25841×
                Edit::Insert {
25851×
                    node: f,
25861×
                    after: AtomRef::Start,
25871×
                    before: AtomRef::End,
25881×
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
25891×
                },
2590
                // Insert between the two lines just inserted, using self references.
25911×
                Edit::Insert {
25921×
                    node: f,
25931×
                    after: AtomRef::Atom {
25941×
                        change: ObjectRef::ZERO,
25951×
                        index: 0,
25961×
                    },
25971×
                    before: AtomRef::Atom {
25981×
                        change: ObjectRef::ZERO,
25991×
                        index: 1,
26001×
                    },
26011×
                    lines: vec![b"b\n".to_vec()].into(),
26021×
                },
2603
            ],
2604
        );
26051×
        st.add(c1).unwrap();
26061×
        let snap = st.materialize();
26071×
        let x = &snap.files["x"];
26081×
        assert_eq!(
2609
            x.mode,
2610
            Mode {
2611
                exec: true,
2612
                opaque: false
2613
            }
2614
        );
26151×
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
26161×
    }
2617
2618
    #[test]
26191×
    fn opaque_replace_and_conflict() {
26201×
        let mut st = State::new();
26211×
        let f = NodeId::random();
26221×
        let b1 = ObjectRef([1; 32]);
26231×
        let b2 = ObjectRef([2; 32]);
26241×
        let b3 = ObjectRef([3; 32]);
26251×
        let h1 = st
26261×
            .add(change(
26271×
                vec![],
26281×
                vec![TreeOp::AddNode {
26291×
                    node: f,
26301×
                    kind: NodeKind::File,
26311×
                    mode: Mode::OPAQUE,
26321×
                    parent: NodeId::ROOT,
26331×
                    name: "img".into(),
26341×
                }],
26351×
                vec![Edit::Replace {
26361×
                    node: f,
26371×
                    old: None,
26381×
                    new: Some(b1),
26391×
                }],
2640
            ))
26411×
            .unwrap();
26421×
        assert_eq!(st.live_blobs(&f), vec![b1]);
26431×
        st.add(change(
26441×
            vec![h1],
26451×
            vec![],
26461×
            vec![Edit::Replace {
26471×
                node: f,
26481×
                old: Some(b1),
26491×
                new: Some(b2),
26501×
            }],
2651
        ))
26521×
        .unwrap();
26531×
        st.add(change(
26541×
            vec![h1],
26551×
            vec![],
26561×
            vec![Edit::Replace {
26571×
                node: f,
26581×
                old: Some(b1),
26591×
                new: Some(b3),
26601×
            }],
2661
        ))
26621×
        .unwrap();
26631×
        let snap = st.materialize();
26641×
        assert!(snap.is_conflicted());
26651×
        assert!(
26661×
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2667
        );
26681×
    }
2669
2670
    #[test]
26711×
    fn checkpoint_payload_round_trip_and_replay() {
26721×
        let mut st = State::new();
26731×
        let f = NodeId::random();
26741×
        let h1 = st
26751×
            .add(change(
26761×
                vec![],
26771×
                vec![TreeOp::AddNode {
26781×
                    node: f,
26791×
                    kind: NodeKind::File,
26801×
                    mode: Mode::TEXT,
26811×
                    parent: NodeId::ROOT,
26821×
                    name: "a".into(),
26831×
                }],
26841×
                vec![Edit::Insert {
26851×
                    node: f,
26861×
                    after: AtomRef::Start,
26871×
                    before: AtomRef::End,
26881×
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
26891×
                }],
2690
            ))
26911×
            .unwrap();
26921×
        let h2 = st
26931×
            .add(change(
26941×
                vec![h1],
26951×
                vec![],
26961×
                vec![Edit::Delete {
26971×
                    node: f,
26981×
                    atoms: vec![AtomRange {
26991×
                        change: h1,
27001×
                        from: 0,
27011×
                        to: 1,
27021×
                    }],
27031×
                }],
2704
            ))
27051×
            .unwrap();
27061×
        let payload = st.checkpoint_payload();
27071×
        let back = State::from_checkpoint_payload(&payload).unwrap();
27081×
        assert_eq!(back.len(), 2);
27091×
        assert_eq!(back.heads(), vec![h2]);
27101×
        assert_eq!(back.get(&h1).unwrap().message, "m");
27111×
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2712
        // Replaying a further change onto the restored state equals a full build.
27131×
        let c3 = change(
27141×
            vec![h2],
27151×
            vec![],
27161×
            vec![Edit::Insert {
27171×
                node: f,
27181×
                after: AtomRef::Atom {
27191×
                    change: h1,
27201×
                    index: 1,
27211×
                },
27221×
                before: AtomRef::End,
27231×
                lines: vec![b"3\n".to_vec()].into(),
27241×
            }],
2725
        );
27261×
        let mut full = st.clone();
27271×
        full.add(c3.clone()).unwrap();
27281×
        let mut restored = back;
27291×
        restored.add(c3).unwrap();
27301×
        let (a, b) = (full.materialize(), restored.materialize());
27311×
        assert_eq!(
27321×
            a.files.keys().collect::<Vec<_>>(),
27331×
            b.files.keys().collect::<Vec<_>>()
2734
        );
27351×
        assert_eq!(a.files["a"].content, b.files["a"].content);
27361×
        assert!(
27371×
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2738
        );
27391×
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
27401×
    }
2741
2742
    /// History-only states (O10f): the same state as a full load once its
2743
    /// graphs are built, by replay and from a version 2 checkpoint with
2744
    /// later changes; unloaded graphs are never read as empty.
2745
    #[test]
27461×
    fn graph_keys_change_exactly_when_a_graph_does() {
27471×
        let (f, g) = (NodeId::random(), NodeId::random());
27481×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
27492×
            node,
27502×
            kind: NodeKind::File,
2751
            mode: Mode::TEXT,
2752
            parent: NodeId::ROOT,
27532×
            name: name.into(),
27542×
        };
27551×
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
27564×
            node,
27574×
            after: AtomRef::Start,
27584×
            before: AtomRef::End,
27594×
            lines: vec![line.to_vec()].into(),
27604×
        };
27611×
        let c1 = change(
27621×
            vec![],
27631×
            vec![add(f, "f"), add(g, "g")],
27641×
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2765
        );
27661×
        let h1 = c1.hash();
27671×
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
27681×
        let h2 = c2.hash();
27691×
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
27706×
        let load = |cs: &[&Change]| {
27716×
            let mut st = State::new_history_only();
277210×
            for c in cs {
277310×
                st.add((*c).clone()).unwrap();
277410×
            }
27756×
            st
27766×
        };
27771×
        let s1 = load(&[&c1]);
27781×
        let s2 = load(&[&c1, &c2]);
27791×
        let s3 = load(&[&c1, &c2, &c3]);
278018×
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
27811×
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
27821×
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
27831×
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
27841×
        assert_ne!(key(&s2, &f), key(&s3, &f));
27851×
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
27861×
        let mut built = load(&[&c1]);
27871×
        built
27881×
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
27891×
            .unwrap();
27901×
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
27911×
        let mut full = State::new();
27921×
        full.add(c1.clone()).unwrap();
27931×
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2794
2795
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2796
        // or inline values: stable across loads, changed by later edits.
27971×
        let graphs = full.checkpoint_file_graphs();
27981×
        let index = full.checkpoint_index(&graphs, |enc| {
27990×
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
28000×
        });
28018×
        let cp = |extra: &[&Change]| {
28028×
            let mut st = State::from_checkpoint_history(&index).unwrap();
28038×
            for c in extra {
28045×
                st.add((*c).clone()).unwrap();
28055×
            }
28068×
            st
28078×
        };
28081×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
28091×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
28101×
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
28111×
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2812
2813
        // Partial rendering: skipped files are listed and empty, the others
2814
        // render as in a full state.
28151×
        let mut part = load(&[&c1, &c2]);
28161×
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
28171×
            .unwrap();
28181×
        let snap = part.materialize_except(&[f].into_iter().collect());
28191×
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
28201×
        let mut whole = State::new();
28211×
        whole.add(c1.clone()).unwrap();
28221×
        whole.add(c2.clone()).unwrap();
28231×
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
28241×
        assert!(
28251×
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2826
        );
28271×
    }
2828
2829
    #[test]
28301×
    fn history_only_states_build_the_same_graphs_on_demand() {
28311×
        let small = NodeId::random();
28321×
        let big = NodeId::random();
28331×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
28342×
            node,
28352×
            kind: NodeKind::File,
2836
            mode: Mode::TEXT,
2837
            parent: NodeId::ROOT,
28382×
            name: name.into(),
28392×
        };
28401×
        let lines: crate::lines::Lines = (0..300)
2841300×
            .map(|i| format!("line {i}\n").into_bytes())
28421×
            .collect();
28431×
        let c1 = change(
28441×
            vec![],
28451×
            vec![add(small, "small"), add(big, "big")],
28461×
            vec![
28471×
                Edit::Insert {
28481×
                    node: small,
28491×
                    after: AtomRef::Start,
28501×
                    before: AtomRef::End,
28511×
                    lines: vec![b"x\n".to_vec()].into(),
28521×
                },
28531×
                Edit::Insert {
28541×
                    node: big,
28551×
                    after: AtomRef::Start,
28561×
                    before: AtomRef::End,
28571×
                    lines,
28581×
                },
2859
            ],
2860
        );
28611×
        let h1 = c1.hash();
28621×
        let c2 = change(
28631×
            vec![h1],
28641×
            vec![],
28651×
            vec![
28661×
                Edit::Delete {
28671×
                    node: big,
28681×
                    atoms: vec![AtomRange {
28691×
                        change: h1,
28701×
                        from: 2,
28711×
                        to: 9,
28721×
                    }],
28731×
                },
28741×
                Edit::Insert {
28751×
                    node: big,
28761×
                    after: AtomRef::Atom {
28771×
                        change: h1,
28781×
                        index: 20,
28791×
                    },
28801×
                    before: AtomRef::Atom {
28811×
                        change: h1,
28821×
                        index: 21,
28831×
                    },
28841×
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
28851×
                },
28861×
                Edit::Insert {
28871×
                    node: small,
28881×
                    after: AtomRef::Atom {
28891×
                        change: h1,
28901×
                        index: 0,
28911×
                    },
28921×
                    before: AtomRef::End,
28931×
                    lines: vec![b"y\n".to_vec()].into(),
28941×
                },
2895
            ],
2896
        );
28971×
        let h2 = c2.hash();
28981×
        let c3 = change(
28991×
            vec![h2],
29001×
            vec![],
29011×
            vec![Edit::Delete {
29021×
                node: small,
29031×
                atoms: vec![AtomRange {
29041×
                    change: h1,
29051×
                    from: 0,
29061×
                    to: 1,
29071×
                }],
29081×
            }],
2909
        );
2910
29111×
        let mut full = State::new();
29123×
        for c in [&c1, &c2, &c3] {
29133×
            full.add(c.clone()).unwrap();
29143×
        }
2915
        // By replay: nothing built until asked, then exactly the full graphs.
29161×
        let mut hist = State::new_history_only();
29173×
        for c in [&c1, &c2, &c3] {
29183×
            hist.add(c.clone()).unwrap();
29193×
        }
29201×
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
29211×
        assert_eq!(hist.len(), 3);
29221×
        hist.load_graphs(
29231×
            &[big],
29240×
            |_| unreachable!("no checkpoint"),
29250×
            |_| unreachable!(),
2926
        )
29271×
        .unwrap();
29281×
        assert_eq!(
29291×
            hist.render_file(&big).0,
29301×
            full.render_file(&big).0,
2931
            "one file on its own"
2932
        );
29331×
        assert!(!hist.is_full());
29341×
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
29351×
            .unwrap();
29361×
        assert!(hist.is_full());
29371×
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2938
2939
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
29401×
        let mut base = State::new();
29411×
        base.add(c1.clone()).unwrap();
29421×
        base.add(c2.clone()).unwrap();
29431×
        let graphs = base.checkpoint_file_graphs();
29441×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
29451×
        let index = base.checkpoint_index(&graphs, |enc| {
29461×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
29471×
            blobs.insert(r, enc.to_vec());
29481×
            r
29491×
        });
29501×
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
29511×
        from_cp.add(c3.clone()).unwrap();
29521×
        assert!(!from_cp.is_full());
29531×
        let mut fetched = 0;
29541×
        from_cp
29551×
            .load_graphs(
29561×
                &[small, big],
29571×
                |refs| {
29581×
                    fetched += refs.len();
29591×
                    refs.iter()
29601×
                        .map(|r| {
29611×
                            blobs
29621×
                                .get(r)
29631×
                                .cloned()
29641×
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
29651×
                        })
29661×
                        .collect()
29671×
                },
29680×
                |_| unreachable!(),
2969
            )
29701×
            .unwrap();
29711×
        assert_eq!(
2972
            fetched, 1,
2973
            "the large graph's blob, in one batch; the small one was inline"
2974
        );
29751×
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
29761×
    }
2977
2978
    #[test]
2979
    #[should_panic(expected = "was not loaded")]
29801×
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
29811×
        let f = NodeId::random();
29821×
        let mut st = State::new_history_only();
29831×
        st.add(change(
29841×
            vec![],
29851×
            vec![TreeOp::AddNode {
29861×
                node: f,
29871×
                kind: NodeKind::File,
29881×
                mode: Mode::TEXT,
29891×
                parent: NodeId::ROOT,
29901×
                name: "a".into(),
29911×
            }],
29921×
            vec![Edit::Insert {
29931×
                node: f,
29941×
                after: AtomRef::Start,
29951×
                before: AtomRef::End,
29961×
                lines: vec![b"a\n".to_vec()].into(),
29971×
            }],
2998
        ))
29991×
        .unwrap();
30001×
        st.render_file(&f);
30011×
    }
3002
3003
    #[test]
3004
    #[should_panic(expected = "needs every file graph")]
30051×
    fn materializing_a_history_only_state_is_refused() {
30061×
        let f = NodeId::random();
30071×
        let mut st = State::new_history_only();
30081×
        st.add(change(
30091×
            vec![],
30101×
            vec![TreeOp::AddNode {
30111×
                node: f,
30121×
                kind: NodeKind::File,
30131×
                mode: Mode::TEXT,
30141×
                parent: NodeId::ROOT,
30151×
                name: "a".into(),
30161×
            }],
30171×
            vec![Edit::Insert {
30181×
                node: f,
30191×
                after: AtomRef::Start,
30201×
                before: AtomRef::End,
30211×
                lines: vec![b"a\n".to_vec()].into(),
30221×
            }],
3023
        ))
30241×
        .unwrap();
30251×
        st.materialize();
30261×
    }
3027
3028
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
3029
    /// blob; the state read back is the same as from version 1.
3030
    #[test]
30311×
    fn checkpoint_index_round_trip_matches_version_1() {
30321×
        let mut st = State::new();
30331×
        let small = NodeId::random();
30341×
        let big = NodeId::random();
30351×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
30362×
            node,
30372×
            kind: NodeKind::File,
3038
            mode: Mode::TEXT,
3039
            parent: NodeId::ROOT,
30402×
            name: name.into(),
30412×
        };
30421×
        let big_lines: crate::lines::Lines = (0..400)
3043400×
            .map(|i| format!("line {i} of a long file\n").into_bytes())
30441×
            .collect();
30451×
        let h1 = st
30461×
            .add(change(
30471×
                vec![],
30481×
                vec![add(small, "small"), add(big, "big")],
30491×
                vec![
30501×
                    Edit::Insert {
30511×
                        node: small,
30521×
                        after: AtomRef::Start,
30531×
                        before: AtomRef::End,
30541×
                        lines: vec![b"x\n".to_vec()].into(),
30551×
                    },
30561×
                    Edit::Insert {
30571×
                        node: big,
30581×
                        after: AtomRef::Start,
30591×
                        before: AtomRef::End,
30601×
                        lines: big_lines,
30611×
                    },
3062
                ],
3063
            ))
30641×
            .unwrap();
30651×
        st.add(change(
30661×
            vec![h1],
30671×
            vec![],
30681×
            vec![Edit::Delete {
30691×
                node: big,
30701×
                atoms: vec![AtomRange {
30711×
                    change: h1,
30721×
                    from: 3,
30731×
                    to: 7,
30741×
                }],
30751×
            }],
3076
        ))
30771×
        .unwrap();
3078
30791×
        let graphs = st.checkpoint_file_graphs();
30801×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
30811×
        let index = st.checkpoint_index(&graphs, |enc| {
30821×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
30831×
            blobs.insert(r, enc.to_vec());
30841×
            r
30851×
        });
30861×
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
30871×
        assert_eq!(
30881×
            State::checkpoint_graph_refs(&index).unwrap(),
30891×
            blobs.keys().copied().collect::<Vec<_>>()
3090
        );
30911×
        assert!(
30921×
            State::checkpoint_graph_refs(&st.checkpoint_payload())
30931×
                .unwrap()
30941×
                .is_empty(),
3095
            "version 1 names none"
3096
        );
30971×
        assert!(index.len() < st.checkpoint_payload().len());
3098
30991×
        let back = State::from_checkpoint(&index, |refs| {
31001×
            refs.iter()
31011×
                .map(|r| {
31021×
                    blobs
31031×
                        .get(r)
31041×
                        .cloned()
31051×
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
31061×
                })
31071×
                .collect()
31081×
        })
31091×
        .unwrap();
31101×
        assert_eq!(
31111×
            back.checkpoint_payload(),
31121×
            st.checkpoint_payload(),
3113
            "the same state as version 1"
3114
        );
31151×
        assert_eq!(
31161×
            back.materialize().files["big"].content,
31171×
            st.materialize().files["big"].content
3118
        );
3119
        // Deterministic: the same state gives the same index.
31201×
        assert_eq!(
31211×
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
31221×
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
31231×
            }),
3124
            index
3125
        );
3126
        // A missing graph blob is an error, not an empty file.
31271×
        assert!(
31281×
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
3129
        );
31301×
        assert!(
31311×
            State::from_checkpoint_payload(&index).is_err(),
3132
            "version 2 needs its blobs"
3133
        );
3134
        // Version 1 payloads still read, and unknown versions do not.
31351×
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
31361×
        let mut v3 = cbor::decode(&index).unwrap();
31371×
        if let Value::Map(m) = &mut v3 {
31381×
            m.insert(0, Value::Uint(3));
31391×
        }
31401×
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
31411×
    }
3142
3143
    #[test]
31441×
    fn maximal_elements() {
31451×
        let mut st = State::new();
31461×
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
31471×
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
31481×
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
31491×
        let mut m = st.maximal(&[h1, h2, h3]);
31501×
        m.sort();
31511×
        let mut want = vec![h2, h3];
31521×
        want.sort();
31531×
        assert_eq!(m, want);
31541×
        assert_eq!(st.heads(), want);
31551×
    }
3156
3157
    /// The bounded walk of `depends_on` agrees with the closure on random
3158
    /// graphs, and the memo stays within its bound.
3159
    #[test]
31601×
    fn depends_on_matches_the_closure() {
3161
        use rand::{Rng, SeedableRng};
31621×
        let mut rng = rand::rngs::StdRng::seed_from_u64(11);
31631×
        for _ in 0..10 {
316410×
            let mut st = State::new();
316510×
            let mut all: Vec<ChangeHash> = Vec::new();
316610×
            for _ in 0..80 {
3167800×
                let deps: Vec<ChangeHash> =
316831600×
                    all.iter().copied().filter(|_| rng.gen_bool(0.06)).collect();
3169800×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
3170
            }
317110×
            let unknown = ObjectRef([0xee; 32]);
3172800×
            for a in &all {
3173800×
                let want = st.closure(a).clone();
3174800×
                st.closure.write().unwrap().sets.clear();
3175800×
                st.closure.write().unwrap().held = 0;
317664800×
                for b in all.iter().chain([&unknown]) {
317764800×
                    assert_eq!(
317864800×
                        st.depends_on(a, b),
317964800×
                        a == b || want.contains(b),
3180
                        "{a:?} on {b:?}"
3181
                    );
3182
                }
3183
            }
318410×
            assert!(st.closure.write().unwrap().held <= CLOSURE_MEMO_HASHES);
3185
        }
31861×
    }
3187
3188
    /// The one-walk `maximal` agrees with the definition (not in the
3189
    /// closure of another element) on random graphs, with repeated and
3190
    /// unknown hashes among the input.
3191
    #[test]
31921×
    fn maximal_matches_its_definition() {
3193
        use rand::{Rng, SeedableRng};
31941×
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
31951×
        for _ in 0..20 {
319620×
            let mut st = State::new();
319720×
            let mut all: Vec<ChangeHash> = Vec::new();
319820×
            for _ in 0..60 {
31991200×
                let deps: Vec<ChangeHash> =
320035400×
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
32011200×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
3202
            }
320320×
            let mut pick: Vec<ChangeHash> =
32041200×
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
320520×
            pick.extend(pick.clone().into_iter().take(3));
320620×
            pick.push(ObjectRef([0xee; 32]));
320720×
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
320820×
            let want: Vec<ChangeHash> = set
320920×
                .iter()
32108552×
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
321120×
                .copied()
321220×
                .collect();
321320×
            assert_eq!(st.maximal(&pick), want);
321420×
            assert_eq!(st.maximal(&all), st.heads());
3215
        }
32161×
    }
3217
}