OXYGENHUB

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

2231 of 2393 lines run, 473 of 676 functions · run #395 on proposal/150 · 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.
451029×
pub fn log_order(a: (&ChangeHash, &Hlc), b: (&ChangeHash, &Hlc)) -> std::cmp::Ordering {
461029×
    b.1.cmp(a.1).then(b.0.cmp(a.0))
471029×
}
48
49
impl ChangeMeta {
50
    /// In the flat layout of local indexes and caches ([`crate::flat`]).
516637×
    pub(crate) fn write_flat(&self, w: &mut crate::flat::Writer) {
526637×
        w.fixed(&self.change_id.0);
536637×
        w.count(self.deps.len());
546637×
        for d in &self.deps {
556137×
            w.object(d);
566137×
        }
576637×
        w.object(&self.author);
586637×
        w.u64(self.hlc.wall_ms);
596637×
        w.u32(self.hlc.logical);
606637×
        w.bytes(self.message.as_bytes());
616637×
        w.u8(self.kind.tag() as u8);
626637×
    }
63
6411751×
    pub(crate) fn read_flat(r: &mut crate::flat::Reader) -> Result<ChangeMeta, ObjectError> {
6511751×
        let change_id = crate::ids::ChangeId(r.fixed::<16>()?);
6611751×
        let mut deps = Vec::new();
6711751×
        for _ in 0..r.count()? {
6810879×
            deps.push(r.object()?);
69
        }
70
        Ok(ChangeMeta {
7111751×
            change_id,
7211751×
            deps,
7311751×
            author: r.object()?,
74
            hlc: Hlc {
7511751×
                wall_ms: r.u64()?,
7611751×
                logical: r.u32()?,
77
            },
7811751×
            message: r.text()?,
7911751×
            kind: ChangeKind::from_tag(r.u8()? as u64)?,
80
        })
8111751×
    }
82
8318210×
    pub fn of(c: &Change) -> ChangeMeta {
8418210×
        ChangeMeta {
8518210×
            change_id: c.change_id,
8618210×
            deps: c.deps.clone(),
8718210×
            author: c.author,
8818210×
            hlc: c.hlc,
8918210×
            message: c.message.clone(),
9018210×
            kind: c.kind,
9118210×
        }
9218210×
    }
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 {
16116770×
    fn len(&self) -> u64 {
16216770×
        match self {
1634601×
            Histories::Bytes(b) => b.len() as u64,
16412169×
            Histories::File(_, _, len) => *len,
165
        }
16616770×
    }
167
16821938×
    fn read(&self, at: u64, len: usize) -> std::io::Result<Vec<u8>> {
16921938×
        match self {
1704601×
            Histories::Bytes(b) => Ok(b[at as usize..at as usize + len].to_vec()),
17117337×
            Histories::File(f, start, _) => {
17217337×
                let mut buf = vec![0u8; len];
17317337×
                read_exact_at(f, &mut buf, start + at)?;
17417337×
                Ok(buf)
175
            }
176
        }
17721938×
    }
178
}
179
180
#[cfg(unix)]
18117337×
fn read_exact_at(f: &std::fs::File, buf: &mut [u8], at: u64) -> std::io::Result<()> {
18217337×
    std::os::unix::fs::FileExt::read_exact_at(f, buf, at)
18317337×
}
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.
21021938×
    fn bytes(&self) -> Result<Vec<u8>, ObjectError> {
21121938×
        let damaged = |why: String| ObjectError::DamagedIndex(why);
21221938×
        let b = self
21321938×
            .from
21421938×
            .read(self.at, self.len)
21521938×
            .map_err(|e| damaged(format!("a file's history cannot be read: {e}")))?;
21621938×
        if *blake3::hash(&b).as_bytes() != self.sum {
2174×
            return Err(damaged("a file's history does not match its hash".into()));
21821934×
        }
21921934×
        Ok(b)
22021938×
    }
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.
252107357×
    fn body(&self) -> Result<&DeferredBody, ObjectError> {
253107357×
        self.body
254107357×
            .get_or_init(|| {
25539139×
                let mut b = match &self.raw {
256
                    // Matching its hash, it is what `write_index` wrote: it
257
                    // decodes.
2585513×
                    Some(raw) => raw
2595513×
                        .bytes()
2605513×
                        .and_then(|b| State::read_deferred_body(&b))
2615513×
                        .map_err(|e| e.to_string())?,
26233626×
                    None => DeferredBody::default(),
263
                };
26439138×
                b.edits.extend(self.more.iter().cloned());
26539138×
                b.texts.extend(self.more_texts.iter().cloned());
26639138×
                Ok(b)
26739139×
            })
268107357×
            .as_ref()
269107357×
            .map_err(|e| ObjectError::DamagedIndex(e.clone()))
270107357×
    }
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.
27437925×
    fn add(&mut self, h: ChangeHash, edits: Vec<Edit>, texts: Vec<TextRef>) {
27537925×
        if self.raw.is_some() && !matches!(self.body.get(), Some(Ok(_))) {
27645×
            self.more.push((h, edits));
27745×
            self.more_texts.extend(texts);
278
            // A body found damaged stays so: what was added cannot mend it.
27945×
            return;
28037880×
        }
281
        // No encoding to read, or decoded already: this cannot fail.
28237880×
        let b = self.body_mut().expect("a history in memory");
28337880×
        b.edits.push((h, edits));
28437880×
        b.texts.extend(texts);
28537925×
    }
286
28737880×
    fn body_mut(&mut self) -> Result<&mut DeferredBody, ObjectError> {
28837880×
        self.body()?;
28937880×
        self.raw = None;
29037880×
        self.more.clear();
29137880×
        self.more_texts.clear();
29237880×
        Ok(self
29337880×
            .body
29437880×
            .get_mut()
29537880×
            .and_then(|b| b.as_mut().ok())
29637880×
            .expect("decoded above"))
29737880×
    }
298
29924481×
    fn into_body(mut self) -> Result<DeferredBody, ObjectError> {
30024481×
        self.body()?;
30124480×
        Ok(self
30224480×
            .body
30324480×
            .take()
30424480×
            .and_then(|b| b.ok())
30524480×
            .expect("decoded above"))
30624481×
    }
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).
3261107×
    pub fn write_index(&self) -> Option<Vec<u8>> {
327
        use crate::flat::Writer;
3281107×
        let deferred = self.deferred.as_ref()?;
3291107×
        if !self.files.is_empty() {
3300×
            return None;
3311107×
        }
332
        // The changes first, as a block a reader can take on its own (see
333
        // [`State::read_index_changes`]).
3341107×
        let mut w = Writer::default();
3351107×
        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.
3381107×
        let mut changes: Vec<(&ChangeHash, &Arc<ChangeMeta>)> = self.changes.iter().collect();
3391107×
        changes.sort_unstable_by(|a, b| log_order((a.0, &a.1.hlc), (b.0, &b.1.hlc)));
3401107×
        w.count(changes.len());
3411107×
        for (h, m) in changes {
342222×
            w.object(h);
343222×
            m.write_flat(&mut w);
344222×
        }
3451107×
        let changes_block = std::mem::take(&mut w);
3461107×
        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.
3491107×
        let mut tw = Writer::default();
3501107×
        self.tree.write_flat(&mut tw);
3511107×
        w.bytes(&tw.0);
3521107×
        let mut replaces: Vec<(&NodeId, &Vec<ReplaceRecord>)> = self.replaces.iter().collect();
3531107×
        replaces.sort_by_key(|(n, _)| **n);
3541107×
        w.count(replaces.len());
3551107×
        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
        }
3671107×
        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).
3701107×
        let mut table = Writer::default();
3711107×
        let mut histories: Vec<u8> = Vec::new();
3721107×
        let mut nodes: Vec<(&NodeId, &Arc<Deferred>)> = deferred.iter().collect();
3731107×
        nodes.sort_by_key(|(n, _)| **n);
3741107×
        table.count(nodes.len());
37532832×
        for (n, d) in nodes {
37632832×
            let key = match d.key.get() {
37716425×
                Some(k) => *k,
378
                None => {
37916407×
                    let mut h = blake3::Hasher::new();
38016407×
                    h.update(b"oxy graph key 1\0");
38116407×
                    h.update(&n.0);
38216407×
                    let k = d.graph_key(h).ok()?;
38316407×
                    let _ = d.key.set(k);
38416407×
                    k
385
                }
386
            };
387
            // Unchanged since read: its bytes as they are, checked.
38832832×
            let bytes = match &d.raw {
38916465×
                Some(raw) if d.more.is_empty() => raw.bytes().ok()?,
39016407×
                _ => Self::write_deferred_body(d.body().ok()?)?,
391
            };
39232829×
            table.fixed(&n.0);
39332829×
            table.fixed(&key);
39432829×
            table.u64(histories.len() as u64);
39532829×
            table.u32(u32::try_from(bytes.len()).ok()?);
39632829×
            table.fixed(blake3::hash(&bytes).as_bytes());
39732829×
            histories.extend_from_slice(&bytes);
398
        }
3991104×
        front.bytes(&table.0);
4001104×
        let mut out = Writer::default();
4011104×
        out.u64(front.0.len() as u64);
4021104×
        out.fixed(&front.0);
4031104×
        out.fixed(&histories);
4041104×
        Some(out.0)
4051107×
    }
406
407
    /// One file's history as an index encodes it; `None` when it holds
408
    /// text in memory, which an index does not.
40916407×
    fn write_deferred_body(d: &DeferredBody) -> Option<Vec<u8>> {
410
        use crate::flat::Writer;
41133594×
        let atom = |w: &mut Writer, a: &AtomRef| match a {
41216407×
            AtomRef::Start => w.u8(0),
41316509×
            AtomRef::End => w.u8(1),
414678×
            AtomRef::Atom { change, index } => {
415678×
                w.u8(2);
416678×
                w.object(change);
417678×
                w.u32(*index);
418678×
            }
41933594×
        };
42016407×
        let mut w = Writer::default();
4216×
        match &d.base {
42216401×
            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.
43516407×
        let mut texts = d.texts.iter();
43616407×
        let mut per_change: Vec<(&ChangeHash, &Vec<Edit>, Vec<&TextRef>)> = Vec::new();
43716539×
        for (c, edits) in &d.edits {
43816539×
            let n = edits
43916539×
                .iter()
44016797×
                .filter(|e| matches!(e, Edit::Insert { lines, .. } if lines.is_empty()))
44116539×
                .count();
44216539×
            per_change.push((c, edits, texts.by_ref().take(n).collect()));
443
        }
44416407×
        per_change.sort_by_key(|(c, _, _)| **c);
44516407×
        w.count(per_change.len());
44616539×
        for (c, edits, _) in &per_change {
44716539×
            w.object(c);
44816539×
            w.count(edits.len());
44916839×
            for e in edits.iter() {
45016839×
                match e {
451
                    Edit::Insert {
45216797×
                        node,
45316797×
                        after,
45416797×
                        before,
45516797×
                        lines,
456
                    } => {
45716797×
                        if !lines.is_empty() {
4580×
                            return None;
45916797×
                        }
46016797×
                        w.u8(0);
46116797×
                        w.fixed(&node.0);
46216797×
                        atom(&mut w, after);
46316797×
                        atom(&mut w, before);
464
                    }
46542×
                    Edit::Delete { node, atoms } => {
46642×
                        w.u8(1);
46742×
                        w.fixed(&node.0);
46842×
                        w.count(atoms.len());
469288×
                        for r in atoms {
470288×
                            w.object(&r.change);
471288×
                            w.u32(r.from);
472288×
                            w.u32(r.to);
473288×
                        }
474
                    }
4750×
                    Edit::Replace { .. } => return None,
476
                }
477
            }
478
        }
47916407×
        let texts: Vec<&TextRef> = per_change
48016407×
            .iter()
48116539×
            .flat_map(|(_, _, t)| t.iter().copied())
48216407×
            .collect();
48316407×
        w.count(texts.len());
48416797×
        for t in texts {
48516797×
            match t {
4862×
                TextRef::Blob(r, count, form) => {
4872×
                    w.u8(0);
4882×
                    w.object(r);
4892×
                    w.u32(*count);
4902×
                    w.u8(match form {
4910×
                        crate::objects::TextForm::Cbor => 0,
4922×
                        crate::objects::TextForm::Raw => 1,
4930×
                        crate::objects::TextForm::CborFallback => 2,
494
                    });
495
                }
49616795×
                TextRef::Inline { change, start, end } => {
49716795×
                    w.u8(1);
49816795×
                    w.object(change);
49916795×
                    w.u32(*start);
50016795×
                    w.u32(*end);
50116795×
                }
502
            }
503
        }
50416407×
        Some(w.0)
50516407×
    }
506
507
    /// The state an index holds (see [`State::write_index`]).
508284×
    pub fn read_index(bytes: &[u8]) -> Result<State, ObjectError> {
509284×
        let bad = || ObjectError::Schema("state index: truncated".into());
510284×
        let front_len =
511284×
            usize::try_from(crate::flat::Reader::new(bytes).u64()?).map_err(|_| bad())?;
512284×
        let front = bytes.get(8..8 + front_len).ok_or_else(bad)?;
513284×
        let histories = Histories::Bytes(Arc::new(bytes[8 + front_len..].to_vec()));
514284×
        Self::read_index_front(front, histories)
515284×
    }
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).
5202341×
    pub fn read_index_front(bytes: &[u8], histories: Histories) -> Result<State, ObjectError> {
521
        use crate::flat::Reader;
5222341×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
5232341×
        let mut r = Reader::new(bytes);
5242341×
        let mut st = State::new_history_only();
525
        {
5262341×
            let _t = crate::timing::phase("index: changes");
5272341×
            st.changes = Self::read_index_changes(r.bytes()?)?;
528
        }
5292341×
        let tree_bytes = r.bytes()?;
5302341×
        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
        }
5382341×
        let deferred_bytes = r.bytes()?;
5392341×
        if !r.at_end() {
5400×
            return Err(bad("trailing bytes"));
5412341×
        }
5422341×
        let (tree, deferred) = rayon::join(
5432341×
            || TreeGraph::read_flat(&mut Reader::new(tree_bytes)),
5442341×
            || Self::read_deferred(deferred_bytes, &histories),
545
        );
5462341×
        st.tree = tree?;
5472341×
        st.deferred = Some(deferred?);
5482341×
        Ok(st)
5492341×
    }
550
551
    /// The changes of a state index: its first block, which a reader can
552
    /// take without the rest.
5532341×
    pub fn read_index_changes(
5542341×
        bytes: &[u8],
5552341×
    ) -> Result<crate::fasthash::FastMap<ChangeHash, Arc<ChangeMeta>>, ObjectError> {
5562341×
        Ok(Self::read_index_changes_listed(bytes)?
5572341×
            .into_iter()
5582341×
            .map(|(h, m)| (h, Arc::new(m)))
5592341×
            .collect())
5602341×
    }
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).
5652510×
    pub fn read_index_changes_listed(
5662510×
        bytes: &[u8],
5672510×
    ) -> Result<Vec<(ChangeHash, ChangeMeta)>, ObjectError> {
568
        use crate::flat::Reader;
5692510×
        let mut r = Reader::new(bytes);
5702510×
        if r.fixed::<18>()?.as_slice() != Self::INDEX_MAGIC {
5710×
            return Err(ObjectError::Schema("state index: not a state index".into()));
5722510×
        }
5732510×
        let n = r.count()?;
5742510×
        let mut changes = Vec::with_capacity(n);
5752510×
        for _ in 0..n {
57610137×
            let h = r.object()?;
57710137×
            changes.push((h, ChangeMeta::read_flat(&mut r)?));
578
        }
5792509×
        if !r.at_end() {
5800×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
5812509×
        }
5822509×
        Ok(changes)
5832510×
    }
584
585
    /// The deferred block: each node with its graph key and its body,
586
    /// left encoded (see [`Deferred`]).
5872341×
    fn read_deferred(
5882341×
        table: &[u8],
5892341×
        histories: &Histories,
5902341×
    ) -> Result<crate::fasthash::FastMap<NodeId, Arc<Deferred>>, ObjectError> {
591
        use crate::flat::Reader;
5922341×
        let _t = crate::timing::phase("index: deferred");
5932341×
        let mut r = Reader::new(table);
5942341×
        let mut deferred = crate::fasthash::FastMap::default();
5952341×
        let n = r.count()?;
5962341×
        deferred.reserve(n);
5972341×
        for _ in 0..n {
59816770×
            let id = NodeId(r.fixed::<16>()?);
59916770×
            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.
60216770×
            let (at, len, sum) = (r.u64()?, r.u32()? as usize, r.fixed::<32>()?);
60316770×
            if at
60416770×
                .checked_add(len as u64)
60516770×
                .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×
                ));
61016770×
            }
61116770×
            let d = Deferred {
61216770×
                raw: Some(RawHistory {
61316770×
                    from: histories.clone(),
61416770×
                    at,
61516770×
                    len,
61616770×
                    sum,
61716770×
                }),
61816770×
                key: std::sync::OnceLock::from(key),
61916770×
                ..Deferred::default()
62016770×
            };
62116770×
            deferred.insert(id, Arc::new(d));
622
        }
6232341×
        if !r.at_end() {
6240×
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
6252341×
        }
6262341×
        Ok(deferred)
6272341×
    }
628
629
    /// One node's deferred history as the index encodes it.
6305512×
    fn read_deferred_body(bytes: &[u8]) -> Result<DeferredBody, ObjectError> {
631
        use crate::flat::Reader;
6325512×
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
6335517×
        let node = |r: &mut Reader| -> Result<NodeId, ObjectError> { Ok(NodeId(r.fixed::<16>()?)) };
63411034×
        let atom = |r: &mut Reader| -> Result<AtomRef, ObjectError> {
63511034×
            Ok(match r.u8()? {
6365501×
                0 => AtomRef::Start,
6375517×
                1 => AtomRef::End,
638
                2 => AtomRef::Atom {
63916×
                    change: r.object()?,
64016×
                    index: r.u32()?,
641
                },
6420×
                _ => return Err(bad("atom")),
643
            })
64411034×
        };
6455512×
        let mut r = Reader::new(bytes);
6465512×
        let base = match r.u8()? {
6475501×
            0 => None,
6480×
            1 => Some(DeferredBase::Blob(r.object()?)),
64911×
            _ => Some(DeferredBase::Inline(cbor::decode(r.bytes()?)?)),
650
        };
6515512×
        let mut edits = Vec::new();
6525512×
        for _ in 0..r.count()? {
6535517×
            let c = r.object()?;
6545517×
            let mut es = Vec::new();
6555517×
            for _ in 0..r.count()? {
6565517×
                es.push(match r.u8()? {
657
                    0 => Edit::Insert {
6585517×
                        node: node(&mut r)?,
6595517×
                        after: atom(&mut r)?,
6605517×
                        before: atom(&mut r)?,
6615517×
                        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
            }
6785517×
            edits.push((c, es));
679
        }
6805512×
        let mut texts = Vec::new();
6815512×
        for _ in 0..r.count()? {
6825517×
            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 {
6935517×
                    change: r.object()?,
6945517×
                    start: r.u32()?,
6955517×
                    end: r.u32()?,
696
                },
697
            });
698
        }
6995512×
        if !r.at_end() {
7000×
            return Err(bad("trailing bytes in a file's history"));
7015512×
        }
7025512×
        Ok(DeferredBody { base, edits, texts })
7035512×
    }
704
}
705
706
impl Clone for State {
7071958×
    fn clone(&self) -> State {
7081958×
        State {
7091958×
            changes: self.changes.clone(),
7101958×
            tree: self.tree.clone(),
7111958×
            files: self.files.clone(),
7121958×
            replaces: self.replaces.clone(),
7131958×
            // A cache: the clone builds its own.
7141958×
            closure: Default::default(),
7151958×
            levels: Default::default(),
7161958×
            deferred: self.deferred.clone(),
7171958×
            unified_view: self.unified_view.clone(),
7181958×
        }
7191958×
    }
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 {
74414130×
    pub fn is_conflicted(&self) -> bool {
74514130×
        match &self.content {
74613097×
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
747300×
            FileContent::Opaque { blobs } => blobs.len() > 1,
748733×
            FileContent::Dir => false,
749
        }
75014130×
    }
751
}
752
753
/// See `State::conflict_regions`.
754
#[derive(Clone, Debug, Default, PartialEq, Eq)]
755
pub struct ConflictRegions {
756
    pub plain: Vec<(AtomKey, Vec<u8>)>,
757
    pub region_atoms: Vec<AtomKey>,
758
    pub contributors: Vec<ChangeHash>,
759
}
760
761
/// The whole tree of a state, materialized.
762
#[derive(Clone, Debug, Default)]
763
pub struct Snapshot {
764
    pub tree: TreeView,
765
    pub files: BTreeMap<String, FileState>,
766
    /// Text files left unrendered by [`State::materialize_except`]: their
767
    /// `bytes` are empty and they are known not to be conflicted.
768
    pub unrendered: BTreeSet<String>,
769
}
770
771
impl Snapshot {
7722476×
    pub fn is_conflicted(&self) -> bool {
77313824×
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
7742476×
    }
775
}
776
77768410×
fn vertex(r: AtomRef) -> Vertex {
77868410×
    match r {
77928123×
        AtomRef::Start => Vertex::Start,
78029461×
        AtomRef::End => Vertex::End,
78110826×
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
782
    }
78368410×
}
784
785
/// Replace self references in a tree op with the concrete change hash.
78640679×
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
78740679×
    match op {
788913×
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
789913×
            node: *node,
790913×
            placement: placement.resolve(me),
791913×
        },
792
        TreeOp::Move {
793213×
            node,
794213×
            old,
795213×
            parent,
796213×
            name,
797213×
        } => TreeOp::Move {
798213×
            node: *node,
799213×
            old: old.resolve(me),
800213×
            parent: *parent,
801213×
            name: name.clone(),
802213×
        },
80322×
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
80422×
            node: *node,
80522×
            old: old.resolve(me),
80622×
            mode: *mode,
80722×
        },
80839531×
        add @ TreeOp::AddNode { .. } => add.clone(),
809
    }
81040679×
}
811
812
/// Apply one change's edits of one file (inserts and deletes; replaces
813
/// live beside the graphs) to that file's graph.
81428561×
fn apply_file_edits(g: &mut FileGraph, h: ChangeHash, edits: Vec<Edit>) {
815
    // The graph's kept order, if any, follows the edits (see `Order`).
81628561×
    let order = g.take_order();
81728561×
    let mut inserts: Vec<(Vertex, Vertex, u32, u32)> = Vec::new();
81828561×
    let mut deleted: Vec<crate::graph::AtomKey> = Vec::new();
81928561×
    let mut next = 0u32;
82031208×
    for e in edits {
82131208×
        match e {
822
            Edit::Insert {
82329220×
                after,
82429220×
                before,
82529220×
                lines,
826
                ..
82729220×
            } => {
82829220×
                let first = next;
82929220×
                let count = lines.len() as u32;
83029220×
                next += count;
83129220×
                let (after, before) = (vertex(after.resolve(h)), vertex(before.resolve(h)));
83229220×
                inserts.push((after, before, first, count));
83329220×
                g.insert_owned(h, first, after, before, lines);
83429220×
            }
8351988×
            Edit::Delete { atoms, .. } => {
8363068×
                for r in atoms {
8373068×
                    let r = r.resolve(h);
8383141×
                    deleted.extend((r.from..r.to).map(|i| (r.change, i)));
8393068×
                    g.delete(h, &r);
840
                }
841
            }
8420×
            Edit::Replace { .. } => {}
843
        }
844
    }
84528561×
    if let Some(o) = order {
84682×
        g.keep_spliced(o, h, &inserts, &deleted);
84728479×
    }
84828561×
}
849
850
/// Build the graphs of deferred entries: their checkpoint bases and the
851
/// texts of inserts read without their lines are loaded in one call, then
852
/// the graphs are built in parallel (they are independent).
8534875×
fn build_deferred(
8544875×
    taken: Vec<(NodeId, Deferred)>,
8554875×
    load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
8564875×
    read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
8574875×
) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
8584875×
    let mut taken: Vec<(NodeId, DeferredBody)> = taken
8594875×
        .into_iter()
86024481×
        .map(|(n, d)| Ok((n, d.into_body()?)))
8614875×
        .collect::<Result<_, ObjectError>>()?;
8624874×
    let mut refs: Vec<ObjectRef> = taken
8634874×
        .iter()
8644874×
        .filter_map(|(_, d)| match &d.base {
8656×
            Some(DeferredBase::Blob(r)) => Some(*r),
86624474×
            _ => None,
86724480×
        })
8684874×
        .collect();
869
    // Text blobs of inserts read without their lines, after the bases.
8704874×
    let bases = refs.len();
87124480×
    refs.extend(taken.iter().flat_map(|(_, d)| {
87228507×
        d.texts.iter().filter_map(|t| match t {
87370×
            TextRef::Blob(r, _, _) => Some(*r),
87428437×
            TextRef::Inline { .. } => None,
87528507×
        })
87624480×
    }));
877
    // And the encodings of changes whose inline inserts are needed,
878
    // each read once.
8794874×
    let reading = crate::timing::phase("graphs: read changes and blobs");
8804874×
    let mut changes: HashMap<ChangeHash, Arc<Vec<u8>>> = HashMap::new();
88128507×
    for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
88228507×
        if let TextRef::Inline { change, .. } = t {
88328437×
            if !changes.contains_key(change) {
8847965×
                changes.insert(*change, read_change(change)?);
88520472×
            }
88670×
        }
887
    }
8884874×
    let n_changes = changes.len();
8894874×
    drop(reading);
8904874×
    let reading = crate::timing::phase("graphs:   of which blobs");
8914874×
    let mut blobs = if refs.is_empty() {
8924803×
        Vec::new()
893
    } else {
89471×
        load(&refs)?
895
    };
8964871×
    if crate::timing::enabled() {
8972×
        eprintln!(
8982×
            "timing graphs: {} graphs, {n_changes} changes, {} blobs",
8992×
            taken.len(),
9002×
            refs.len()
9012×
        );
9024869×
    }
9034871×
    if blobs.len() != refs.len() {
9040×
        return Err(ObjectError::Schema("graph blobs: wrong count".into()));
9054871×
    }
9064871×
    drop(reading);
9074871×
    let lines = crate::timing::phase("graphs: hand out blobs");
9084871×
    let mut texts = blobs.split_off(bases).into_iter();
9094871×
    let mut blobs = blobs.into_iter();
910
    // Hand each graph its own blobs, in order, then fill in its inserts'
911
    // lines and build it, all in parallel: graphs are independent.
912
    type Work = (NodeId, DeferredBody, Option<Vec<u8>>, Vec<Vec<u8>>);
9134871×
    let mut work: Vec<Work> = Vec::with_capacity(taken.len());
91424477×
    for (node, d) in taken.drain(..) {
91524477×
        let wanted = d
91624477×
            .texts
91724477×
            .iter()
91828505×
            .filter(|t| matches!(t, TextRef::Blob(..)))
91924477×
            .count();
92024477×
        let mine: Vec<Vec<u8>> = texts.by_ref().take(wanted).collect();
92124477×
        if mine.len() != wanted {
9220×
            return Err(ObjectError::Schema("text blobs: wrong count".into()));
92324477×
        }
92424477×
        let bytes = match &d.base {
925
            Some(DeferredBase::Blob(_)) => Some(
9265×
                blobs
9275×
                    .next()
9285×
                    .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
929
            ),
93024472×
            _ => None,
931
        };
93224477×
        work.push((node, d, bytes, mine));
933
    }
9344871×
    drop(lines);
9354871×
    let _t = crate::timing::phase("graphs: lines and build");
936
    use rayon::prelude::*;
9374871×
    let changes = &changes;
9384871×
    let built: Vec<(NodeId, FileGraph)> = work
9394871×
        .into_par_iter()
94024477×
        .map(|(node, mut d, bytes, mine)| {
941
            // Fill in the lines of inserts read without them, in order.
94224477×
            let mut want = std::mem::take(&mut d.texts).into_iter();
94324477×
            let mut mine = mine.into_iter();
94428044×
            for (_, edits) in d.edits.iter_mut() {
94530225×
                for e in edits.iter_mut() {
94630225×
                    if let Edit::Insert { lines, .. } = e {
94728512×
                        if lines.is_empty() {
94828505×
                            *lines = match want.next() {
94968×
                                Some(TextRef::Blob(_, count, form)) => {
95068×
                                    let content = mine.next().ok_or_else(|| {
9510×
                                        ObjectError::Schema("text blobs: wrong count".into())
9520×
                                    })?;
95368×
                                    crate::objects::text_lines(&content, count, form)?
954
                                }
95528437×
                                Some(TextRef::Inline { change, start, end }) => {
95628437×
                                    let bytes = &changes[&change];
95728437×
                                    let range = bytes
95828437×
                                        .get(start as usize..end as usize)
95928437×
                                        .ok_or_else(|| {
9600×
                                            ObjectError::Schema(
9610×
                                                "an inline insert lies outside its change".into(),
9620×
                                            )
9630×
                                        })?;
96428437×
                                    crate::objects::inline_lines(range)?
965
                                }
966
                                None => {
9670×
                                    return Err(ObjectError::Schema(
9680×
                                        "an insert's text is missing".into(),
9690×
                                    ))
970
                                }
971
                            };
9727×
                        }
9731713×
                    }
974
                }
975
            }
97624477×
            let mut graph = match (d.base.take(), bytes) {
977109×
                (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
9785×
                (Some(DeferredBase::Blob(_)), Some(bytes)) => {
9795×
                    FileGraph::from_value(&cbor::decode(&bytes)?)?
980
                }
98124363×
                _ => FileGraph::default(),
982
            };
98328044×
            for (h, edits) in std::mem::take(&mut d.edits) {
98428044×
                apply_file_edits(&mut graph, h, edits);
98528044×
            }
98624477×
            Ok((node, graph))
98724477×
        })
9884871×
        .collect::<Result<_, ObjectError>>()?;
9894871×
    Ok(built)
9904875×
}
991
992
impl State {
993732×
    pub fn new() -> Self {
994732×
        Self::default()
995732×
    }
996
997
    /// An empty state for history only: changes and tree are kept, file
998
    /// edits are recorded but no file graph is built until
999
    /// [`State::load_graphs`] asks for it. For log and other commands that
1000
    /// need no file contents, or only a few files.
10014455×
    pub fn new_history_only() -> Self {
10024455×
        State {
10034455×
            deferred: Some(Default::default()),
10044455×
            ..Self::default()
10054455×
        }
10064455×
    }
1007
1008
    /// Whether `node`'s file graph is built (always, in a full state).
100940×
    pub fn is_built(&self, node: &NodeId) -> bool {
101040×
        self.deferred.is_none() || self.files.contains_key(node)
101140×
    }
1012
1013
    /// Whether this state builds file graphs only when asked
1014
    /// ([`State::new_history_only`]), even if it has none waiting.
10154152×
    pub fn is_history_only(&self) -> bool {
10164152×
        self.deferred.is_some()
10174152×
    }
1018
1019
    /// Whether this state holds every file graph.
10203443×
    pub fn is_full(&self) -> bool {
10213443×
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
10223443×
    }
1023
1024
    /// The graph of `node`, which must be loaded: asking a history-only
1025
    /// state for a graph it has not built is a bug, never an empty file.
102627713×
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
102727713×
        if let Some(d) = &self.deferred {
102810673×
            assert!(
102910673×
                !d.contains_key(node),
1030
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
10311×
                node.short(12)
1032
            );
103317040×
        }
103427712×
        self.files.get(node).map(|g| g.as_ref())
103527712×
    }
1036
1037
    /// Operations over every file need every graph.
10383436×
    fn require_full(&self, what: &str) {
10393436×
        assert!(
10403436×
            self.is_full(),
1041
            "{what} needs every file graph; this state was loaded for history only"
1042
        );
10433435×
    }
1044
1045
    /// Build the graphs of `nodes` in a history-only state: from their
1046
    /// checkpoint base (blobs read in one batch through `load`) and their
1047
    /// deferred edits. Nodes already built, or with no graph, are skipped.
10484798×
    pub fn load_graphs(
10494798×
        &mut self,
10504798×
        nodes: &[NodeId],
10514798×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
10524798×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
10534798×
    ) -> Result<(), ObjectError> {
10544798×
        let Some(deferred) = self.deferred.as_mut() else {
10550×
            return Ok(());
1056
        };
10574798×
        let taken: Vec<(NodeId, Deferred)> = nodes
10584798×
            .iter()
105924753×
            .filter_map(|n| deferred.remove(n).map(|d| (*n, Arc::unwrap_or_clone(d))))
10604798×
            .collect();
10614798×
        let built = build_deferred(taken, load, read_change)?;
10624794×
        self.files
106324416×
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
10644794×
        Ok(())
10654798×
    }
1066
1067
    /// The graphs of `nodes`, built from this history-only state's deferred
1068
    /// edits without building them in it: the state stays history only, so
1069
    /// changes read without their lines can still be added to it and every
1070
    /// graph keeps its key. For a caller that renders a few files of many
1071
    /// states in turn (verifying an import).
107277×
    pub fn build_graphs_detached(
107377×
        &self,
107477×
        nodes: &[NodeId],
107577×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
107677×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
107777×
    ) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
107877×
        let Some(deferred) = self.deferred.as_ref() else {
10790×
            return Ok(Vec::new());
1080
        };
1081
        // A file this state has built has no deferred history: its graph
1082
        // is the built one, copied. Built from an empty history instead, it
1083
        // rendered as an empty file, and a merge taking this path recorded
1084
        // the whole file as inserted again, conflicting with itself (#71).
108577×
        let mut built: Vec<(NodeId, FileGraph)> = Vec::new();
108677×
        let mut copies: Vec<(NodeId, Deferred)> = Vec::new();
108777×
        for n in nodes {
108864×
            match (self.files.get(n), deferred.get(n)) {
10893×
                (Some(g), _) => built.push((*n, (**g).clone())),
109061×
                (None, d) => copies.push((*n, d.map(|d| (**d).clone()).unwrap_or_default())),
1091
            }
1092
        }
109377×
        let mut out = build_deferred(copies, load, read_change)?;
109477×
        out.extend(built);
109577×
        Ok(out)
109677×
    }
1097
1098
    /// Render a graph built for this state (see
1099
    /// [`State::build_graphs_detached`]), as [`State::render_file`] does.
110064×
    pub fn render_graph(&self, g: &FileGraph) -> (Vec<u8>, Materialized) {
110164×
        let m = g.materialize(self);
110264×
        let bytes = g.render(&m, &|h| self.label(h));
110364×
        (bytes, m)
110464×
    }
1105
1106
    /// Every file graph a history-only state has not built, deleted files'
1107
    /// included.
110879×
    pub fn unbuilt_nodes(&self) -> Vec<NodeId> {
110979×
        self.deferred
111079×
            .as_ref()
111179×
            .map(|d| d.keys().copied().collect())
111279×
            .unwrap_or_default()
111379×
    }
1114
1115
    /// Drop the built graphs of `nodes`, for a caller rendering a large
1116
    /// tree a batch at a time. The state can no longer render those files,
1117
    /// so it must not be used for them again.
1118508×
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
11196127×
        for n in nodes {
11206127×
            self.files.remove(n);
11216127×
        }
1122508×
    }
1123
1124
    /// Build every graph a history-only state has not built, making it full.
11252521×
    pub fn load_all_graphs(
11262521×
        &mut self,
11272521×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
11282521×
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
11292521×
    ) -> Result<(), ObjectError> {
11302521×
        let nodes: Vec<NodeId> = match &self.deferred {
11312521×
            Some(d) => d.keys().copied().collect(),
11320×
            None => return Ok(()),
1133
        };
11342521×
        self.load_graphs(&nodes, load, read_change)?;
11352521×
        self.deferred = None;
11362521×
        Ok(())
11372521×
    }
1138
1139
    /// The one text a file's history is, when it is a single insert of
1140
    /// the whole file into nothing (a file added once and never edited,
1141
    /// with no checkpoint base): its rendering is that text, so it needs
1142
    /// no graph. `None` otherwise, or when the graph is built.
11435980×
    pub fn single_text(&self, node: &NodeId) -> Option<TextRef> {
11445980×
        if self.files.contains_key(node) {
114593×
            return None;
11465887×
        }
1147
        // A history that cannot be read is no single text: building its
1148
        // graph reports why.
11495887×
        let d = self.deferred.as_ref()?.get(node)?.body().ok()?;
11505849×
        let [(_, edits)] = d.edits.as_slice() else {
1151265×
            return None;
1152
        };
1153
        let [Edit::Insert {
1154
            after: AtomRef::Start,
1155
            before: AtomRef::End,
11565584×
            lines,
1157
            ..
11585584×
        }] = edits.as_slice()
1159
        else {
11600×
            return None;
1161
        };
11625584×
        match (&d.base, d.texts.as_slice()) {
11635584×
            (None, [t]) if lines.is_empty() => Some(*t),
11640×
            _ => None,
1165
        }
11665980×
    }
1167
1168
    /// A key for the graph of `node` in a history-only state that has not
1169
    /// built it: equal keys mean equal graphs, so equal renderings (a
1170
    /// rendering depends only on the graph and on the changes' own
1171
    /// immutable metadata). It names the node, its checkpoint base (a blob,
1172
    /// an inline value, or none) and the set of later changes that edited
1173
    /// the file.
1174
    /// `None` for a full state or a graph already built.
117529602×
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
117629602×
        let deferred = self.deferred.as_ref()?;
117729555×
        if self.files.contains_key(node) {
1178756×
            return None;
117928799×
        }
118028799×
        let mut h = blake3::Hasher::new();
118128799×
        h.update(b"oxy graph key 1\0");
1182
        // A change's edits are applied per node: the node is part of it.
118328799×
        h.update(&node.0);
118428799×
        let Some(d) = deferred.get(node) else {
1185
            // Never edited: the empty graph.
1186178×
            h.update(&[0]);
1187178×
            return Some(*h.finalize().as_bytes());
1188
        };
1189
        // A history that cannot be read has no key: the file is read.
119028621×
        if let Some(k) = d.key.get() {
119122288×
            return Some(*k);
11926333×
        }
11936333×
        let k = d.graph_key(h).ok()?;
11946333×
        Some(*d.key.get_or_init(|| k))
119529602×
    }
1196
11974391×
    pub fn len(&self) -> usize {
11984391×
        self.changes.len()
11994391×
    }
1200
1201
    /// Turn this history-only state's built graphs back into deferred
1202
    /// histories, each starting from its graph encoded as a checkpoint
1203
    /// graph and stored by `store` (it returns the blob's reference): what
1204
    /// they held stays, and memory goes back to what a history-only state
1205
    /// costs. A graph built later again decodes that blob and applies only
1206
    /// the edits that came after. Graph keys change (the base is now a
1207
    /// blob), which only means a cached rendering is not reused.
12081×
    pub fn shed_graphs<E>(
12091×
        &mut self,
12101×
        mut store: impl FnMut(&[u8]) -> Result<ObjectRef, E>,
12111×
    ) -> Result<usize, E> {
1212
        use rayon::prelude::*;
12131×
        let Some(deferred) = self.deferred.as_mut() else {
12140×
            return Ok(0);
1215
        };
12161×
        let graphs: Vec<(NodeId, Arc<FileGraph>)> = self.files.drain().collect();
12171×
        let encoded: Vec<(NodeId, Vec<u8>)> = graphs
12181×
            .par_iter()
12192×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
12201×
            .collect();
12211×
        drop(graphs);
12221×
        let shed = encoded.len();
12232×
        for (node, bytes) in encoded {
12242×
            let blob = store(&bytes)?;
12252×
            deferred.insert(
12262×
                node,
12272×
                Arc::new(Deferred::from_body(DeferredBody {
12282×
                    base: Some(DeferredBase::Blob(blob)),
12292×
                    ..DeferredBody::default()
12302×
                })),
1231
            );
1232
        }
12331×
        Ok(shed)
12341×
    }
1235
1236
    /// How many file graphs this state has built.
123777×
    pub fn built_count(&self) -> usize {
123877×
        self.files.len()
123977×
    }
1240
1241
    /// Atoms in this state's built graphs, live and deleted: what their
1242
    /// memory follows, since a graph keeps every line its file ever had.
124351×
    pub fn built_atoms(&self) -> usize {
124456×
        self.files.values().map(|g| g.atom_count()).sum()
124551×
    }
1246
1247
    /// Edits held in the deferred histories of files not built, and the
1248
    /// most any one file holds (for measuring, #25).
12490×
    pub fn deferred_edit_count(&self) -> (usize, usize) {
12500×
        let Some(d) = self.deferred.as_ref() else {
12510×
            return (0, 0);
1252
        };
12530×
        let mut total = 0;
12540×
        let mut most = 0;
12550×
        for v in d.values() {
12560×
            let n: usize = v
12570×
                .body()
12580×
                .map_or(0, |b| b.edits.iter().map(|(_, e)| e.len()).sum());
12590×
            total += n;
12600×
            most = most.max(n);
1261
        }
12620×
        (total, most)
12630×
    }
1264
}
1265
1266
impl Deferred {
1267
    /// See [`State::graph_key`]: `h` has taken the node already.
126822740×
    fn graph_key(&self, mut h: blake3::Hasher) -> Result<[u8; 32], ObjectError> {
126922740×
        let d = self.body()?;
127018×
        match &d.base {
127122722×
            None => h.update(&[0]),
12720×
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
127318×
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
1274
        };
127522740×
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
127622740×
        changes.sort();
127722740×
        changes.dedup();
127822740×
        h.update(&(changes.len() as u64).to_le_bytes());
127924774×
        for c in changes {
128024774×
            h.update(&c.0);
128124774×
        }
128222740×
        Ok(*h.finalize().as_bytes())
128322740×
    }
1284
}
1285
1286
impl State {
12870×
    pub fn is_empty(&self) -> bool {
12880×
        self.changes.is_empty()
12890×
    }
129016978×
    pub fn contains(&self, h: &ChangeHash) -> bool {
129116978×
        self.changes.contains_key(h)
129216978×
    }
129371×
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
129471×
        self.changes.get(h).map(|m| &**m)
129571×
    }
12961956×
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
12974625×
        self.changes.iter().map(|(h, m)| (h, &**m))
12981956×
    }
129915903×
    pub fn tree(&self) -> &TreeGraph {
130015903×
        &self.tree
130115903×
    }
1302
1303
    /// The tree as every reader sees it: the tree graph's view, with the
1304
    /// same path added on several lines of history with identical content
1305
    /// shown as one entry rather than a name conflict (spec §9.2). The
1306
    /// text files among such candidates must be built in a history-only
1307
    /// state ([`State::unify_candidates`]); until they are, they are shown
1308
    /// as the conflict.
13097653×
    pub fn view(&self) -> TreeView {
13107653×
        if let Some(v) = self.unified_view.get() {
131175×
            return v.clone();
13127578×
        }
13137578×
        let raw = self.tree.view();
13147578×
        if !raw
13157578×
            .conflicts
13167578×
            .iter()
13177578×
            .any(|c| matches!(c, crate::tree::TreeConflict::Name { .. }))
1318
        {
13197134×
            return raw;
1320444×
        }
1321444×
        let (view, decided) = self.tree.unify(raw, |es| self.same_content(es));
1322444×
        if decided {
1323444×
            let _ = self.unified_view.set(view.clone());
1324444×
        }
1325444×
        view
13267653×
    }
1327
1328
    /// The text files [`State::view`] must compare and a history-only
1329
    /// state has not built: candidates of the tree's name conflicts.
13302554×
    pub fn unify_candidates(&self) -> Vec<NodeId> {
13312554×
        let Some(deferred) = &self.deferred else {
13320×
            return Vec::new();
1333
        };
13342554×
        if self.unified_view.get().is_some() {
13350×
            return Vec::new();
13362554×
        }
13372554×
        let raw = self.tree.view();
13382554×
        let mut out = Vec::new();
13392554×
        for c in &raw.conflicts {
1340141×
            if let crate::tree::TreeConflict::Name { nodes, .. } = c {
1341314×
                out.extend(nodes.iter().filter(|n| deferred.contains_key(*n)));
13420×
            }
1343
        }
13442554×
        out
13452554×
    }
1346
1347
    /// Whether the entries' contents are identical, unconflicted: the same
1348
    /// rendering for text files, the same single blob for opaque ones,
1349
    /// symlinks and subrepos. `None` for a text file not built yet.
1350444×
    fn same_content(&self, entries: &[&crate::tree::TreeEntry]) -> Option<bool> {
1351918×
        let text = |e: &crate::tree::TreeEntry| e.kind == NodeKind::File && !e.mode.opaque;
1352444×
        let mut first: Option<Vec<u8>> = None;
1353444×
        let mut first_blob: Option<ObjectRef> = None;
1354918×
        for e in entries {
1355918×
            if text(e) {
1356904×
                if self
1357904×
                    .deferred
1358904×
                    .as_ref()
1359904×
                    .is_some_and(|d| d.contains_key(&e.node))
1360
                {
13610×
                    return None;
1362904×
                }
1363904×
                let (bytes, m) = self.render_file(&e.node);
1364904×
                if m.is_conflicted() {
13650×
                    return Some(false);
1366904×
                }
1367467×
                match &first {
1368437×
                    None => first = Some(bytes),
1369467×
                    Some(b) if *b == bytes => {}
1370322×
                    Some(_) => return Some(false),
1371
                }
1372
            } else {
137314×
                let [blob] = self.live_blobs(&e.node)[..] else {
13740×
                    return Some(false);
1375
                };
13767×
                match first_blob {
13777×
                    None => first_blob = Some(blob),
13787×
                    Some(b) if b == blob => {}
13790×
                    Some(_) => return Some(false),
1380
                }
1381
            }
1382
        }
1383122×
        Some(true)
1384444×
    }
1385649×
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
1386649×
        self.graph(node)
1387649×
    }
1388
1389
    /// Add a change whose dependencies are already present.
13902904×
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
13912904×
        let h = change.hash();
13922904×
        self.add_hashed(h, change)
13932904×
    }
1394
1395
    /// [`State::add`] for a change whose hash `h` is already known (it was
1396
    /// just stored), so it is not encoded again.
13973691×
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
13983691×
        if self.changes.contains_key(&h) {
139947×
            return Ok(h);
14003644×
        }
14015134×
        for d in &change.deps {
14025134×
            if !self.changes.contains_key(d) {
14032×
                return Err(StateError::MissingDep(*d, h));
14045132×
            }
1405
        }
14063642×
        self.add_known(h, change, Vec::new());
14073642×
        Ok(h)
14083691×
    }
1409
1410
    /// Add a change in any order; call `validate` once all are in.
14111060×
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
14121060×
        let h = change.hash();
14131060×
        self.add_known(h, change, Vec::new());
14141060×
        h
14151060×
    }
1416
1417
    /// Add a change just stored under hash `h` to a history-only state that
1418
    /// has built some graphs: an edit of a built graph is applied whole
1419
    /// (from `full`), and one of a file not built waits without its text
1420
    /// (from `skeleton` and its `texts`, as the store reads it back), so the
1421
    /// state holds no text it has not built. A Git import adds each change
1422
    /// it makes this way, keeping memory to what changes.
142392×
    pub fn add_known_mixed(
142492×
        &mut self,
142592×
        h: ChangeHash,
142692×
        full: Change,
142792×
        skeleton: Change,
142892×
        texts: Vec<TextRef>,
142992×
    ) {
143092×
        if self.deferred.is_none() || self.changes.contains_key(&h) {
14310×
            self.add_known(h, full, Vec::new());
14320×
            return;
143392×
        }
1434
        let Change {
143592×
            version,
143692×
            change_id,
143792×
            deps,
143892×
            author,
143992×
            hlc,
144092×
            message,
144192×
            tree_ops,
144292×
            edits: full_edits,
144392×
            kind,
144492×
        } = full;
144592×
        let mut texts = texts.into_iter();
144692×
        let mut edits = Vec::with_capacity(full_edits.len());
144792×
        let mut kept = Vec::new();
144897×
        for (f, s) in full_edits.into_iter().zip(skeleton.edits) {
144997×
            let text = match &s {
145077×
                Edit::Insert { lines, .. } if lines.is_empty() => texts.next(),
145120×
                _ => None,
1452
            };
145397×
            if self.files.contains_key(&f.node()) {
145445×
                edits.push(f);
145552×
            } else {
145652×
                edits.push(s);
145752×
                kept.extend(text);
145852×
            }
1459
        }
146092×
        let c = Change {
146192×
            version,
146292×
            change_id,
146392×
            deps,
146492×
            author,
146592×
            hlc,
146692×
            message,
146792×
            tree_ops,
146892×
            edits,
146992×
            kind,
147092×
        };
147192×
        self.add_known(h, c, kept);
147292×
    }
1473
1474
    /// Add a change read from the store under hash `h`, without hashing it
1475
    /// again (for a version 2 change that means chunking all its text).
1476
    /// `texts` names, in order, the inserts left without their lines (see
1477
    /// [`crate::store::Store::get_change_lazy`]); only a history-only state
1478
    /// takes them, and only for graphs it has not built.
147914750×
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
148014750×
        if self.changes.contains_key(&h) {
14810×
            return;
148214750×
        }
148314750×
        let meta = ChangeMeta::of(&change);
148414750×
        self.unified_view = Default::default();
148514750×
        self.apply_with(h, change, texts);
148614750×
        self.changes.insert(h, Arc::new(meta));
148714750×
        {
148814750×
            let mut m = self.closure.write().unwrap();
148914750×
            m.sets.clear();
149014750×
            m.held = 0;
149114750×
        }
149214750×
    }
1493
1494
    // ------------------------------------------------------------ checkpoints (spec §11)
1495
1496
    /// Serialize the whole state in payload version 1: change metadata,
1497
    /// tree, file graphs, replaces, all in one value (spec §11).
1498380×
    pub fn checkpoint_payload(&self) -> Vec<u8> {
1499380×
        self.require_full("a checkpoint");
1500380×
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
1501380×
        nodes.sort();
1502380×
        let files = Value::Array(
1503380×
            nodes
1504380×
                .into_iter()
15051550×
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
1506380×
                .collect(),
1507
        );
1508380×
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
1509380×
    }
1510
1511
    /// Each file graph encoded on its own, by node, for a version 2 payload
1512
    /// (spec §11): the graphs of large files become blobs of their own.
151319×
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
1514
        use rayon::prelude::*;
151519×
        self.require_full("a checkpoint");
151619×
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
151754×
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
151819×
        nodes.sort_by_key(|(n, _)| **n);
151919×
        nodes
152019×
            .into_par_iter()
152154×
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
152219×
            .collect()
152319×
    }
1524
1525
    /// The payload version 2 index for the graphs of
1526
    /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than
1527
    /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by
1528
    /// `blob_of` (the ObjectRef of the blob holding its encoding).
152919×
    pub fn checkpoint_index(
153019×
        &self,
153119×
        graphs: &[(NodeId, Vec<u8>)],
153219×
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
153319×
    ) -> Vec<u8> {
153419×
        let files = Value::Array(
153519×
            graphs
153619×
                .iter()
153754×
                .map(|(n, enc)| {
153854×
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
153947×
                        cbor::decode(enc).expect("an encoded graph decodes")
1540
                    } else {
15417×
                        Value::Bytes(blob_of(enc).0.to_vec())
1542
                    };
154354×
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
154454×
                })
154519×
                .collect(),
1546
        );
154719×
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
154819×
    }
1549
1550
    /// The payload map around `files`: changes, tree and replaces as in version 1.
1551399×
    fn payload_value(&self, version: u64, files: Value) -> Value {
1552399×
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
1553399×
        hashes.sort();
1554399×
        let changes = Value::Array(
1555399×
            hashes
1556399×
                .into_iter()
15572398×
                .map(|h| {
15582398×
                    let m = &self.changes[h];
15592398×
                    Value::Array(vec![
15602398×
                        Value::Bytes(h.0.to_vec()),
15612398×
                        Value::Bytes(m.change_id.0.to_vec()),
15622398×
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
15632398×
                        Value::Text(m.message.clone()),
15642398×
                        Value::Uint(m.hlc.wall_ms),
15652398×
                        Value::Uint(m.hlc.logical as u64),
15662398×
                        Value::Uint(m.kind.tag()),
15672398×
                        Value::Bytes(m.author.0.to_vec()),
1568
                    ])
15692398×
                })
1570399×
                .collect(),
1571
        );
1572399×
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
1573399×
        rnodes.sort();
1574399×
        let opt =
157512×
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
1576399×
        let replaces = Value::Array(
1577399×
            rnodes
1578399×
                .into_iter()
1579399×
                .map(|n| {
15806×
                    Value::Array(vec![
15816×
                        Value::Bytes(n.0.to_vec()),
1582
                        Value::Array(
15836×
                            self.replaces[n]
15846×
                                .iter()
15856×
                                .map(|(c, o, nw)| {
15866×
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
15876×
                                })
15886×
                                .collect(),
1589
                        ),
1590
                    ])
15916×
                })
1592399×
                .collect(),
1593
        );
1594399×
        Value::map([
1595399×
            (0, Value::Uint(version)),
1596399×
            (1, changes),
1597399×
            (2, self.tree.to_value()),
1598399×
            (3, files),
1599399×
            (4, replaces),
1600399×
        ])
1601399×
    }
1602
1603
    /// Decode a version 1 payload (the whole state in one value). A
1604
    /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`].
160537×
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
160637×
        State::from_checkpoint(bytes, |_| {
16071×
            Err(ObjectError::Schema(
16081×
                "a version 2 checkpoint needs its graph blobs".into(),
16091×
            ))
16101×
        })
161137×
    }
1612
1613
    /// Decode a checkpoint payload of either version (spec §11). For
1614
    /// version 2, `load` returns the contents of the named graph blobs, in
1615
    /// order; the graphs are then decoded in parallel.
161660×
    pub fn from_checkpoint(
161760×
        bytes: &[u8],
161860×
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
161960×
    ) -> Result<State, ObjectError> {
1620
        use rayon::prelude::*;
162160×
        let v = cbor::decode(bytes)?;
162259×
        let m = o::map(&v, "checkpoint payload")?;
162359×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
162459×
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
16251×
            return Err(ObjectError::Schema(format!(
16261×
                "checkpoint payload version {version} is not supported"
16271×
            )));
162858×
        }
162958×
        let mut st = State::payload_common(m)?;
163058×
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
163158×
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
1632237×
        for f in entries {
1633237×
            let e = o::array(f, "file")?;
1634237×
            if e.len() != 2 {
16350×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1636237×
            }
1637237×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1638237×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1639237×
            parsed.push((node, &e[1]));
1640
        }
1641
        // Version 2 names large graphs by blob: fetch those in one batch.
164258×
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
164358×
        if version == CHECKPOINT_INDEX_VERSION {
164420×
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
164520×
                .iter()
164690×
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
164720×
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
164820×
                .collect::<Result<_, ObjectError>>()?;
164920×
            if !wanted.is_empty() {
16507×
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
16513×
                let contents = {
16527×
                    let _t = crate::timing::phase("load:   graph blobs read");
16537×
                    load(&refs)?
1654
                };
16553×
                if contents.len() != refs.len() {
16560×
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
16573×
                }
16583×
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
165913×
            }
1660147×
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
16610×
            return Err(ObjectError::Schema(
16620×
                "a version 1 payload holds graphs inline".into(),
16630×
            ));
166438×
        }
1665
        // File graphs are independent; decode and build them in parallel.
166654×
        let graphs = parsed
166754×
            .par_iter()
1668231×
            .map(|(node, entry)| {
1669231×
                let graph = match fetched.get(node) {
16703×
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
1671228×
                    None => FileGraph::from_value(entry)?,
1672
                };
1673231×
                Ok((*node, graph))
1674231×
            })
167554×
            .collect::<Result<Vec<_>, ObjectError>>()?;
167654×
        st.files
1677231×
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
167854×
        Ok(st)
167960×
    }
1680
1681
    /// The graph blobs a payload names: empty for version 1.
168211×
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
168311×
        let v = cbor::decode(bytes)?;
168411×
        let m = o::map(&v, "checkpoint payload")?;
168511×
        let mut out = Vec::new();
168629×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
168729×
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
16886×
                out.push(o::oref(entry, "graph blob")?);
168923×
            }
1690
        }
169111×
        Ok(out)
169211×
    }
1693
1694
    /// Decode a checkpoint payload for history only: a version 2 payload's
1695
    /// graphs are noted, not read or built, and come later through
1696
    /// [`State::load_graphs`]. A version 1 payload holds them inline and is
1697
    /// decoded in full.
169860×
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
169960×
        let v = cbor::decode(bytes)?;
170060×
        let m = o::map(&v, "checkpoint payload")?;
170160×
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
170260×
        if version != CHECKPOINT_INDEX_VERSION {
17031×
            return State::from_checkpoint_payload(bytes);
170459×
        }
170559×
        let mut st = State::payload_common(m)?;
170659×
        let mut deferred = crate::fasthash::FastMap::default();
1707157×
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1708157×
            let e = o::array(f, "file")?;
1709157×
            if e.len() != 2 {
17100×
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1711157×
            }
1712157×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1713157×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1714157×
            let base = match &e[1] {
17154×
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
1716153×
                other => DeferredBase::Inline(other.clone()),
1717
            };
1718157×
            deferred.insert(
1719157×
                node,
1720157×
                Arc::new(Deferred::from_body(DeferredBody {
1721157×
                    base: Some(base),
1722157×
                    ..DeferredBody::default()
1723157×
                })),
1724
            );
1725
        }
172659×
        st.deferred = Some(deferred);
172759×
        Ok(st)
172860×
    }
1729
1730
    /// Changes, tree and replaces of a payload of either version.
1731117×
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
1732117×
        let mut st = State::new();
1733557×
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
1734557×
            let e = o::array(c, "change meta")?;
1735557×
            if e.len() != 8 {
17360×
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
1737557×
            }
1738557×
            let hash = o::oref(&e[0], "hash")?;
1739557×
            let meta = ChangeMeta {
1740557×
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
1741557×
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
1742557×
                deps: o::array(&e[2], "deps")?
1743557×
                    .iter()
1744665×
                    .map(|d| o::oref(d, "dep"))
1745557×
                    .collect::<Result<Vec<_>, _>>()?,
1746557×
                message: o::text(&e[3], "message")?.to_owned(),
1747
                hlc: Hlc {
1748557×
                    wall_ms: o::uint(&e[4], "wall")?,
1749557×
                    logical: o::u32_(&e[5], "logical")?,
1750
                },
1751557×
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
1752557×
                author: o::oref(&e[7], "author")?,
1753
            };
1754557×
            st.changes.insert(hash, Arc::new(meta));
1755
        }
1756117×
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
1757117×
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
175858×
            if v.is_null() {
175929×
                Ok(None)
1760
            } else {
176129×
                o::oref(v, "blob").map(Some)
1762
            }
176358×
        };
1764117×
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
176529×
            let e = o::array(r, "replace")?;
176629×
            if e.len() != 2 {
17670×
                return Err(ObjectError::Schema(
17680×
                    "replace: expected [node, records]".into(),
17690×
                ));
177029×
            }
177129×
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
177229×
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
177329×
            let mut recs = Vec::new();
177429×
            for rec in o::array(&e[1], "records")? {
177529×
                let x = o::array(rec, "record")?;
177629×
                if x.len() != 3 {
17770×
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
177829×
                }
177929×
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
1780
            }
178129×
            st.replaces.insert(node, recs);
1782
        }
1783117×
        Ok(st)
1784117×
    }
1785
17864335×
    pub fn validate(&self) -> Result<(), StateError> {
178711190×
        for (h, c) in &self.changes {
178811190×
            for d in &c.deps {
17896734×
                if !self.changes.contains_key(d) {
17900×
                    return Err(StateError::MissingDep(*d, *h));
17916734×
                }
1792
            }
1793
        }
17944335×
        Ok(())
17954335×
    }
1796
179714750×
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
179840679×
        for (i, op) in c.tree_ops.iter().enumerate() {
179940679×
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
180040679×
        }
180114750×
        if let Some(deferred) = self.deferred.as_mut() {
1802
            // History only: edits of files not built wait, grouped per file,
1803
            // with the texts of inserts read without their lines.
18049198×
            let mut texts = texts.into_iter();
18059198×
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
180641823×
            for e in c.edits {
180741823×
                match e {
1808857×
                    Edit::Replace { node, old, new } => {
1809857×
                        self.replaces.entry(node).or_default().push((h, old, new))
1810
                    }
181140966×
                    e => {
181240966×
                        let slot = per_node.entry(e.node()).or_default();
181338566×
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
181434837×
                            slot.1.extend(texts.next());
181534837×
                        }
181640966×
                        slot.0.push(e);
1817
                    }
1818
                }
1819
            }
182038442×
            for (node, (edits, node_texts)) in per_node {
182138442×
                match self.files.get_mut(&node) {
1822517×
                    Some(g) => {
1823517×
                        assert!(
1824517×
                            node_texts.is_empty(),
1825
                            "a change read without its text applied to a built graph"
1826
                        );
1827517×
                        apply_file_edits(Arc::make_mut(g), h, edits)
1828
                    }
182937925×
                    None => {
183037925×
                        let d = Arc::make_mut(deferred.entry(node).or_default());
183137925×
                        d.add(h, edits, node_texts);
183237925×
                        d.key = Default::default();
183337925×
                    }
1834
                }
1835
            }
18369198×
            return;
18375552×
        }
18385552×
        assert!(
18395552×
            texts.is_empty(),
1840
            "a change read without its text applied to a full state"
1841
        );
18425552×
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
18436670×
        for e in c.edits {
18446670×
            match e {
1845
                Edit::Insert {
18464985×
                    node,
18474985×
                    after,
18484985×
                    before,
18494985×
                    lines,
18504985×
                } => {
18514985×
                    let idx = counters.entry(node).or_default();
18524985×
                    let first = *idx;
18534985×
                    *idx += lines.len() as u32;
18544985×
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
18554985×
                        h,
18564985×
                        first,
18574985×
                        vertex(after.resolve(h)),
18584985×
                        vertex(before.resolve(h)),
18594985×
                        lines,
18604985×
                    );
18614985×
                }
18621565×
                Edit::Delete { node, atoms } => {
18631565×
                    let g = Arc::make_mut(self.files.entry(node).or_default());
18641870×
                    for r in atoms {
18651870×
                        g.delete(h, &r.resolve(h));
18661870×
                    }
1867
                }
1868120×
                Edit::Replace { node, old, new } => {
1869120×
                    self.replaces.entry(node).or_default().push((h, old, new));
1870120×
                }
1871
            }
1872
        }
187314750×
    }
1874
1875
    /// Transitive dependencies of `h`, excluding `h` itself.
18769269×
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
18779269×
        if let Some(c) = self.closure.read().unwrap().sets.get(h) {
18787869×
            return c.clone();
18791400×
        }
18801400×
        let mut out = HashSet::new();
18811400×
        let mut stack: Vec<ChangeHash> = self
18821400×
            .changes
18831400×
            .get(h)
18841400×
            .map(|c| c.deps.clone())
18851400×
            .unwrap_or_default();
188616842×
        while let Some(d) = stack.pop() {
188715442×
            if out.insert(d) {
188810925×
                if let Some(c) = self.changes.get(&d) {
188910925×
                    stack.extend(c.deps.iter().copied());
189010925×
                }
18914517×
            }
1892
        }
18931400×
        let rc = Arc::new(out);
18941400×
        let mut memo = self.closure.write().unwrap();
18951400×
        if memo.held + rc.len() > CLOSURE_MEMO_HASHES {
18960×
            memo.sets.clear();
18970×
            memo.held = 0;
18981400×
        }
18991400×
        memo.held += rc.len();
19001400×
        memo.sets.insert(*h, rc.clone());
19011400×
        rc
19029269×
    }
1903
1904
    /// `h`'s level (see `levels`), worked out for it and its ancestors not
1905
    /// yet known, without recursion: histories are deeper than a stack. An
1906
    /// unknown change has level 0.
1907380898×
    fn level(&self, h: &ChangeHash) -> u32 {
1908
        // Nearly always known: read without excluding the other threads
1909
        // rendering beside this one (oxygen#96).
1910380898×
        if let Some(l) = self.levels.read().unwrap().get(h) {
1911378154×
            return *l;
19122744×
        }
19132744×
        let mut levels = self.levels.write().unwrap();
19142744×
        if let Some(l) = levels.get(h) {
191510×
            return *l;
19162734×
        }
19172734×
        let mut stack: Vec<(ChangeHash, bool)> = vec![(*h, false)];
19188862×
        while let Some((c, expanded)) = stack.pop() {
19196128×
            if levels.contains_key(&c) {
192026×
                continue;
19216102×
            }
19226102×
            let deps: &[ChangeHash] = self
19236102×
                .changes
19246102×
                .get(&c)
19256102×
                .map(|m| m.deps.as_slice())
19266102×
                .unwrap_or(&[]);
19276102×
            if expanded {
19283051×
                let l = deps
19293051×
                    .iter()
19303602×
                    .map(|d| levels.get(d).map_or(0, |l| l + 1))
19313051×
                    .max()
19323051×
                    .unwrap_or(0);
19333051×
                levels.insert(c, l);
1934
            } else {
19353051×
                stack.push((c, true));
19363602×
                for d in deps {
19373602×
                    if !levels.contains_key(d) {
1938343×
                        stack.push((*d, false));
19393259×
                    }
1940
                }
1941
            }
1942
        }
19432734×
        levels[h]
1944380898×
    }
1945
1946
    /// Changes that no other change depends on directly, sorted.
1947397×
    pub fn heads(&self) -> Vec<ChangeHash> {
1948397×
        let depended: crate::fasthash::FastSet<&ChangeHash> =
19493566×
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
1950397×
        let mut heads: Vec<ChangeHash> = self
1951397×
            .changes
1952397×
            .keys()
19533566×
            .filter(|h| !depended.contains(h))
1954397×
            .copied()
1955397×
            .collect();
1956397×
        heads.sort();
1957397×
        heads
1958397×
    }
1959
1960
    /// Maximal elements among `hashes` (those not in the closure of another),
1961
    /// sorted. One walk down from all of them at once: whatever the walk
1962
    /// reaches is below some other element. Linear in the changes reached,
1963
    /// where comparing every pair's closures was quadratic in the number
1964
    /// of heads, which a bookmark of independent changes has many of.
196511111×
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
196611111×
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
196711111×
        let mut below: crate::fasthash::FastSet<ChangeHash> = Default::default();
196811111×
        let mut stack: Vec<ChangeHash> = set
196911111×
            .iter()
197019657×
            .filter_map(|h| self.changes.get(h))
197116493×
            .flat_map(|c| c.deps.iter().copied())
197211111×
            .collect();
197326666×
        while let Some(d) = stack.pop() {
197415555×
            if below.insert(d) {
19757610×
                if let Some(c) = self.changes.get(&d) {
19767610×
                    stack.extend(c.deps.iter().copied());
19777610×
                }
19787945×
            }
1979
        }
198019657×
        set.into_iter().filter(|h| !below.contains(h)).collect()
198111111×
    }
1982
19830×
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
19840×
        self.graph(node)
19850×
            .map(|g| g.materialize(self))
19860×
            .unwrap_or_default()
19870×
    }
1988
1989
    /// Live lines of a text node in materialized order.
199021×
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
199121×
        let Some(g) = self.graph(node) else {
19922×
            return vec![];
1993
        };
199419×
        let m = g.materialize(self);
199519×
        m.live_atoms()
199619×
            .into_iter()
199745×
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
199819×
            .collect()
199921×
    }
2000
2001
    /// The nodes with replace records: opaque files, as their blobs go.
20024×
    pub fn opaque_nodes(&self) -> Vec<NodeId> {
20034×
        let mut nodes: Vec<NodeId> = self.replaces.keys().copied().collect();
20044×
        nodes.sort();
20054×
        nodes
20064×
    }
2007
2008
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
20091086×
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
20101086×
        let mut live: Vec<ObjectRef> = self
20111086×
            .live_replaces(node)
20121086×
            .into_iter()
20131086×
            .map(|(_, n)| n)
20141086×
            .collect();
20151086×
        live.sort();
20161086×
        live.dedup();
20171086×
        live
20181086×
    }
2019
2020
    /// The replace records whose blob is live, with the change that set it
2021
    /// (spec §9.3). A record's blob is superseded by a later replacement of
2022
    /// that blob: one whose change depends on the record's change, as every
2023
    /// replacement depends on the change that made its old blob current
2024
    /// (§8.1). Two replacements that do not know each other both stay live
2025
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
2026
    /// A replacement without that dependency, from before the rule, is read
2027
    /// as before: it supersedes every record that did not come after it.
20281147×
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
20291147×
        let Some(rs) = self.replaces.get(node) else {
20300×
            return vec![];
2031
        };
2032
        // Dependence by the bounded walk rather than whole closures: on a
2033
        // long history a closure is a hundred thousand changes, and the
2034
        // memo cannot keep them all (#107).
20351147×
        let dep =
2036265×
            |a: &ChangeHash, b: &ChangeHash| a != b && <Self as DepOracle>::depends_on(self, a, b);
20371147×
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
203811×
            rs.iter()
203945×
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && dep(s, q))
204011×
        };
20411147×
        rs.iter()
20421468×
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
20431468×
            .filter(|(c, n)| {
20442124×
                !rs.iter().any(|(s, o, _)| {
20452124×
                    s != c && *o == Some(*n) && (dep(s, c) || (!knows_its_old(s, n) && !dep(c, s)))
20462124×
                })
20471468×
            })
20481147×
            .collect()
20491147×
    }
2050
2051
    /// Short label for conflict markers: `changeid-prefix "message"`.
20521371×
    pub fn label(&self, h: &ChangeHash) -> String {
20531371×
        match self.changes.get(h) {
20541371×
            Some(c) => format!(
2055
                "{} \"{}\"",
20561371×
                c.change_id.short(8),
20571371×
                c.message.lines().next().unwrap_or("")
2058
            ),
20590×
            None => format!("#{}", h.short(12)),
2060
        }
20611371×
    }
2062
2063
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
2064
    /// are not part of any conflict region in order, every live atom that is
2065
    /// part of a region, and every change that contributed to a region.
2066
    /// The changes that introduced the live blobs of an opaque node, for a
2067
    /// replace conflict (spec §9.3).
20685×
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
20695×
        let mut out: Vec<ChangeHash> = Vec::new();
207015×
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
207115×
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
207210×
                out.push(*h);
207310×
            }
2074
        }
20755×
        out.sort();
20765×
        out
20775×
    }
2078
207947×
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
208047×
        let mut out = ConflictRegions::default();
208147×
        let Some(g) = self.graph(node) else {
20820×
            return out;
2083
        };
208447×
        let m = g.materialize(self);
208547×
        let mut contributors = BTreeSet::new();
2086122×
        for seg in &m.segments {
2087122×
            match seg {
208875×
                crate::graph::Segment::Lines(atoms) => {
2089100×
                    for a in atoms {
2090100×
                        out.plain
2091100×
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
2092100×
                    }
2093
                }
209447×
                crate::graph::Segment::Conflict(sides) => {
209594×
                    for side in sides {
209696×
                        for a in side {
209796×
                            out.region_atoms.push(*a);
209896×
                            contributors.insert(a.0);
209996×
                        }
2100
                    }
2101
                }
21020×
                crate::graph::Segment::Zombie { deleted, inserted } => {
21030×
                    for a in deleted {
21040×
                        contributors.insert(a.0);
21050×
                        contributors.extend(g.deleters(a).copied());
21060×
                    }
21070×
                    for a in inserted {
21080×
                        out.region_atoms.push(*a);
21090×
                        contributors.insert(a.0);
21100×
                    }
2111
                }
2112
            }
2113
        }
211447×
        out.contributors = contributors.into_iter().collect();
211547×
        out
211647×
    }
2117
2118
    /// A file graph materialized with each conflict's sides earliest change
2119
    /// first (oxygen#121), by the clock of the oldest change on a side, so
2120
    /// markers read in the order the work was done and `oxy resolve --both`
2121
    /// keeps that order.
212226458×
    fn materialize_ordered(&self, g: &FileGraph) -> Materialized {
212326458×
        let mut m = g.materialize(self);
212426458×
        let when = |h: &ChangeHash| match self.changes.get(h) {
21251151×
            Some(c) => (false, c.hlc, *h),
21260×
            None => (true, Default::default(), *h),
21271151×
        };
212827254×
        for seg in &mut m.segments {
212927254×
            if let crate::graph::Segment::Conflict(sides) = seg {
21301151×
                sides.sort_by_cached_key(|s| s.iter().map(|a| when(&a.0)).min());
213126760×
            }
2132
        }
213326458×
        m
213426458×
    }
2135
2136
    /// For each conflict of a text node, in marker order (spec §9.5): the
2137
    /// text of its sides, earliest change first, when it is an adjacent
2138
    /// insertion that keeping both sides settles (oxygen#121); `None` for
2139
    /// the others.
21409×
    pub fn both_sides(&self, node: &NodeId) -> Vec<Option<Vec<Vec<u8>>>> {
21419×
        let Some(g) = self.graph(node) else {
21420×
            return Vec::new();
2143
        };
21449×
        let m = self.materialize_ordered(g);
21459×
        let mut out = Vec::new();
214626×
        for (i, seg) in m.segments.iter().enumerate() {
21479×
            match seg {
214817×
                crate::graph::Segment::Lines(_) => {}
21499×
                crate::graph::Segment::Conflict(sides) if g.adjacent_insertion(&m, i, self) => {
21506×
                    out.push(Some(
21516×
                        sides
21526×
                            .iter()
215312×
                            .map(|s| {
215412×
                                s.iter()
215512×
                                    .flat_map(|a| g.content(a).unwrap_or_default().to_vec())
215612×
                                    .collect()
215712×
                            })
21586×
                            .collect(),
2159
                    ));
2160
                }
21613×
                _ => out.push(None),
2162
            }
2163
        }
21649×
        out
21659×
    }
2166
216726987×
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
216826987×
        let Some(g) = self.graph(node) else {
2169537×
            return (Vec::new(), Materialized::default());
2170
        };
217126450×
        let m = self.materialize_ordered(g);
217226450×
        let bytes = g.render(&m, &|h| self.label(h));
217326450×
        (bytes, m)
217426987×
    }
2175
2176
    /// Every file rendered, in parallel: files are independent, and
2177
    /// rendering them is most of a snapshot's cost in a large tree.
21783037×
    pub fn materialize(&self) -> Snapshot {
2179
        use rayon::prelude::*;
21803037×
        self.require_full("materializing a state");
21813037×
        let tree = self.view();
21823037×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
21833037×
        let rendered: Vec<(String, FileState)> = entries
21843037×
            .par_iter()
218518216×
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
21863037×
            .collect();
21873037×
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
21883037×
        Snapshot {
21893037×
            tree,
21903037×
            files,
21913037×
            unrendered: BTreeSet::new(),
21923037×
        }
21933037×
    }
2194
2195
    /// Like [`State::materialize`], leaving the text files of nodes in
2196
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
2197
    /// file's graph must be loaded. For a caller that already knows those
2198
    /// files are unchanged and not conflicted. Its tree is the tree
2199
    /// graph's own view, as a Git import builds against it: same-path
2200
    /// additions are not unified ([`State::view`]), since the import's
2201
    /// merge records Git's tree for them itself.
220220×
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
220320×
        self.materialize_leaving(self.tree.view(), |_, e| skip.contains(&e.node))
220420×
    }
2205
2206
    /// As [`State::materialize_except`], rendering only the text files at
2207
    /// `render` (a few, where the caller knows the rest unchanged), with
2208
    /// the tree as [`State::view`] has it.
22091029×
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
22107974×
        self.materialize_leaving(self.view(), |p, _| !render.contains(p))
22111029×
    }
2212
2213
    /// As [`State::materialize_only`], rendering only the text files of
2214
    /// the nodes in `render` (a change's edited files), without a set of
2215
    /// every other file to leave out.
2216252×
    pub fn materialize_nodes(&self, render: &HashSet<NodeId>) -> Snapshot {
2217655×
        self.materialize_leaving(self.view(), |_, e| !render.contains(&e.node))
2218252×
    }
2219
22201301×
    fn materialize_leaving(
22211301×
        &self,
22221301×
        tree: TreeView,
22231301×
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
22241301×
    ) -> Snapshot {
2225
        use rayon::prelude::*;
22261301×
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
22271301×
        let rendered: Vec<(String, FileState, bool)> = entries
22281301×
            .par_iter()
22299029×
            .map(|(path, e)| {
22309029×
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
22314606×
                    let f = FileState {
22324606×
                        node: e.node,
22334606×
                        kind: e.kind,
22344606×
                        mode: e.mode,
22354606×
                        content: FileContent::Text {
22364606×
                            bytes: Vec::new(),
22374606×
                            materialized: Materialized::default(),
22384606×
                        },
22394606×
                    };
22404606×
                    (path.to_string(), f, true)
2241
                } else {
22424423×
                    (path.to_string(), self.file_state(e), false)
2243
                }
22449029×
            })
22451301×
            .collect();
2246
        // In the view's path order, so the maps are built without searching.
22471301×
        let unrendered: BTreeSet<String> = rendered
22481301×
            .iter()
22491301×
            .filter(|(_, _, skipped)| *skipped)
22504606×
            .map(|(p, _, _)| p.clone())
22511301×
            .collect();
22521301×
        let files: BTreeMap<String, FileState> =
22539029×
            rendered.into_iter().map(|(p, f, _)| (p, f)).collect();
22541301×
        Snapshot {
22551301×
            tree,
22561301×
            files,
22571301×
            unrendered,
22581301×
        }
22591301×
    }
2260
2261
    /// A snapshot of only `paths` (those `view` has), `view` being this
2262
    /// state's tree view: for a caller that works from what changed. The
2263
    /// graphs of those text files must be loaded.
226490×
    pub fn materialize_paths<'p>(
226590×
        &self,
226690×
        view: crate::tree::TreeView,
226790×
        paths: impl IntoIterator<Item = &'p str>,
226890×
    ) -> Snapshot {
2269
        use rayon::prelude::*;
2270
        // On every core: a merge may render thousands (oxygen#96).
227190×
        let entries: Vec<(&str, &crate::tree::TreeEntry)> = paths
227290×
            .into_iter()
2273131×
            .filter_map(|p| Some((p, view.entries.get(p)?)))
227490×
            .collect();
227590×
        let files = entries
227690×
            .par_iter()
2277107×
            .map(|(p, e)| (p.to_string(), self.file_state(e)))
227890×
            .collect::<Vec<_>>()
227990×
            .into_iter()
228090×
            .collect();
228190×
        Snapshot {
228290×
            tree: view,
228390×
            files,
228490×
            unrendered: BTreeSet::new(),
228590×
        }
228690×
    }
2287
2288
    /// The state of one tree entry: a directory, an opaque file's live
2289
    /// blobs, or a text file rendered from its graph (which must be built).
22900×
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
22910×
        self.file_state(e)
22920×
    }
2293
229422746×
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
2295
        {
229622746×
            let content = match e.kind {
22971629×
                NodeKind::Dir => FileContent::Dir,
2298181×
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
2299181×
                    blobs: self.live_blobs(&e.node),
2300181×
                },
2301624×
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
2302624×
                    blobs: self.live_blobs(&e.node),
2303624×
                },
2304
                NodeKind::File => {
230520312×
                    let (bytes, materialized) = self.render_file(&e.node);
230620312×
                    FileContent::Text {
230720312×
                        bytes,
230820312×
                        materialized,
230920312×
                    }
2310
                }
2311
            };
231222746×
            FileState {
231322746×
                node: e.node,
231422746×
                kind: e.kind,
231522746×
                mode: e.mode,
231622746×
                content,
231722746×
            }
2318
        }
231922746×
    }
2320
}
2321
2322
impl DepOracle for State {
2323
    /// Whether `a` depends on `b`, by a walk down from `a` that stops at
2324
    /// changes no higher than `b`: they cannot have `b` below them. Nothing
2325
    /// of the walk is kept, so asking about many pairs costs no more memory
2326
    /// than one walk (#25); a closure already memoised answers at once.
232766605×
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
232866605×
        if a == b {
2329802×
            return true;
233065803×
        }
233165803×
        if let Some(c) = self.closure.read().unwrap().sets.get(a) {
23320×
            return c.contains(b);
233365803×
        }
233465803×
        if !self.changes.contains_key(b) {
2335800×
            return false;
233665003×
        }
233765003×
        let lb = self.level(b);
233865003×
        if self.level(a) <= lb {
233935848×
            return false;
234029155×
        }
234129155×
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
2342
        // A dependency is looked for as it is found, before the walk goes
2343
        // below it: most questions are about a direct one (spec §8.1 makes
2344
        // a deletion depend on the inserter of the line after it, which is
2345
        // what a render asks about), and a depth-first walk that only
2346
        // looked when it came back up went through thousands of changes
2347
        // first (oxygen#137: 4.4 billion steps rendering the VS Code tree).
234829155×
        let mut stack: Vec<ChangeHash> = self
234929155×
            .changes
235029155×
            .get(a)
235129155×
            .map(|m| m.deps.clone())
235229155×
            .unwrap_or_default();
235329155×
        if stack.contains(b) {
23543181×
            return true;
235525974×
        }
2356323707×
        while let Some(c) = stack.pop() {
2357304444×
            if c == *b {
23580×
                return true;
2359304444×
            }
2360304444×
            if !seen.insert(c) || self.level(&c) <= lb {
2361204008×
                continue;
2362100436×
            }
2363100436×
            if let Some(m) = self.changes.get(&c) {
2364100436×
                if m.deps.contains(b) {
23656711×
                    return true;
236693725×
                }
236793725×
                stack.extend(m.deps.iter().copied());
23680×
            }
2369
        }
237019263×
        false
237166605×
    }
2372
}
2373
2374
#[cfg(test)]
2375
mod tests {
2376
    use super::*;
2377
2378
    /// A changes block of thousands comes back whole and in order, and a
2379
    /// truncated one is refused (oxygen#94).
2380
    #[test]
23811×
    fn a_long_changes_block_decodes_in_order() {
2382
        use crate::flat::Writer;
23831×
        let metas: Vec<(ChangeHash, ChangeMeta)> = (0..5000u32)
23845000×
            .map(|i| {
23855000×
                let mut h = [0u8; 32];
23865000×
                h[..4].copy_from_slice(&i.to_le_bytes());
23875000×
                let meta = ChangeMeta {
23885000×
                    change_id: crate::ids::ChangeId([i as u8; 16]),
23895000×
                    deps: (0..i % 3).map(|d| ObjectRef([d as u8; 32])).collect(),
23905000×
                    author: ObjectRef([7; 32]),
23915000×
                    hlc: Hlc {
23925000×
                        wall_ms: 1_000_000 - i as u64,
23935000×
                        logical: i,
23945000×
                    },
23955000×
                    message: "x".repeat((i % 50) as usize),
23965000×
                    kind: ChangeKind::Normal,
2397
                };
23985000×
                (ObjectRef(h), meta)
23995000×
            })
24001×
            .collect();
24011×
        let mut w = Writer::default();
24021×
        w.fixed(State::INDEX_MAGIC);
24031×
        w.count(metas.len());
24045000×
        for (h, m) in &metas {
24055000×
            w.object(h);
24065000×
            m.write_flat(&mut w);
24075000×
        }
24081×
        assert_eq!(State::read_index_changes_listed(&w.0).unwrap(), metas);
24091×
        let mut cut = w.0.clone();
24101×
        cut.pop();
24111×
        assert!(
24121×
            State::read_index_changes_listed(&cut).is_err(),
2413
            "a truncated block is refused"
2414
        );
24151×
    }
2416
    use crate::ids::ChangeId;
2417
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
2418
24192023×
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
24202023×
        let mut c = Change {
24212023×
            version: crate::objects::CHANGE_VERSION,
24222023×
            change_id: ChangeId::random(),
24232023×
            deps,
24242023×
            author: ObjectRef::ZERO,
24252023×
            hlc: Hlc {
24262023×
                wall_ms: 1,
24272023×
                logical: 0,
24282023×
            },
24292023×
            message: "m".into(),
24302023×
            tree_ops,
24312023×
            edits,
24322023×
            kind: ChangeKind::Normal,
24332023×
        };
24342023×
        c.normalize();
24352023×
        c
24362023×
    }
2437
2438
    #[test]
24391×
    fn build_edit_and_materialize() {
24401×
        let mut st = State::new();
24411×
        let f = NodeId::random();
24421×
        let c1 = change(
24431×
            vec![],
24441×
            vec![TreeOp::AddNode {
24451×
                node: f,
24461×
                kind: NodeKind::File,
24471×
                mode: Mode::TEXT,
24481×
                parent: NodeId::ROOT,
24491×
                name: "a.txt".into(),
24501×
            }],
24511×
            vec![Edit::Insert {
24521×
                node: f,
24531×
                after: AtomRef::Start,
24541×
                before: AtomRef::End,
24551×
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
24561×
            }],
2457
        );
24581×
        let h1 = st.add(c1).unwrap();
2459
        // Depends on h1: append a line and delete "one".
24601×
        let c2 = change(
24611×
            vec![h1],
24621×
            vec![],
24631×
            vec![
24641×
                Edit::Delete {
24651×
                    node: f,
24661×
                    atoms: vec![AtomRange {
24671×
                        change: h1,
24681×
                        from: 0,
24691×
                        to: 1,
24701×
                    }],
24711×
                },
24721×
                Edit::Insert {
24731×
                    node: f,
24741×
                    after: AtomRef::Atom {
24751×
                        change: h1,
24761×
                        index: 1,
24771×
                    },
24781×
                    before: AtomRef::End,
24791×
                    lines: vec![b"three\n".to_vec()].into(),
24801×
                },
2481
            ],
2482
        );
24831×
        let h2 = st.add(c2).unwrap();
24841×
        assert_eq!(st.heads(), vec![h2]);
24851×
        assert!(st.depends_on(&h2, &h1));
24861×
        assert!(!st.depends_on(&h1, &h2));
24871×
        let snap = st.materialize();
24881×
        assert!(!snap.is_conflicted());
24891×
        let a = &snap.files["a.txt"];
24901×
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
24911×
        assert_eq!(st.live_lines(&f).len(), 2);
24921×
    }
2493
2494
    #[test]
24951×
    fn missing_dependency_is_rejected() {
24961×
        let mut st = State::new();
24971×
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
24981×
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
24991×
    }
2500
2501
    #[test]
25021×
    fn self_references_and_multi_insert_indexing() {
25031×
        let mut st = State::new();
25041×
        let f = NodeId::random();
25051×
        let me = OpRef {
25061×
            change: ObjectRef::ZERO,
25071×
            index: 0,
25081×
        };
25091×
        let c1 = change(
25101×
            vec![],
25111×
            vec![
25121×
                TreeOp::AddNode {
25131×
                    node: f,
25141×
                    kind: NodeKind::File,
25151×
                    mode: Mode::TEXT,
25161×
                    parent: NodeId::ROOT,
25171×
                    name: "x".into(),
25181×
                },
25191×
                TreeOp::SetMode {
25201×
                    node: f,
25211×
                    old: me,
25221×
                    mode: Mode {
25231×
                        exec: true,
25241×
                        opaque: false,
25251×
                    },
25261×
                },
2527
            ],
25281×
            vec![
25291×
                Edit::Insert {
25301×
                    node: f,
25311×
                    after: AtomRef::Start,
25321×
                    before: AtomRef::End,
25331×
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
25341×
                },
2535
                // Insert between the two lines just inserted, using self references.
25361×
                Edit::Insert {
25371×
                    node: f,
25381×
                    after: AtomRef::Atom {
25391×
                        change: ObjectRef::ZERO,
25401×
                        index: 0,
25411×
                    },
25421×
                    before: AtomRef::Atom {
25431×
                        change: ObjectRef::ZERO,
25441×
                        index: 1,
25451×
                    },
25461×
                    lines: vec![b"b\n".to_vec()].into(),
25471×
                },
2548
            ],
2549
        );
25501×
        st.add(c1).unwrap();
25511×
        let snap = st.materialize();
25521×
        let x = &snap.files["x"];
25531×
        assert_eq!(
2554
            x.mode,
2555
            Mode {
2556
                exec: true,
2557
                opaque: false
2558
            }
2559
        );
25601×
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
25611×
    }
2562
2563
    #[test]
25641×
    fn opaque_replace_and_conflict() {
25651×
        let mut st = State::new();
25661×
        let f = NodeId::random();
25671×
        let b1 = ObjectRef([1; 32]);
25681×
        let b2 = ObjectRef([2; 32]);
25691×
        let b3 = ObjectRef([3; 32]);
25701×
        let h1 = st
25711×
            .add(change(
25721×
                vec![],
25731×
                vec![TreeOp::AddNode {
25741×
                    node: f,
25751×
                    kind: NodeKind::File,
25761×
                    mode: Mode::OPAQUE,
25771×
                    parent: NodeId::ROOT,
25781×
                    name: "img".into(),
25791×
                }],
25801×
                vec![Edit::Replace {
25811×
                    node: f,
25821×
                    old: None,
25831×
                    new: Some(b1),
25841×
                }],
2585
            ))
25861×
            .unwrap();
25871×
        assert_eq!(st.live_blobs(&f), vec![b1]);
25881×
        st.add(change(
25891×
            vec![h1],
25901×
            vec![],
25911×
            vec![Edit::Replace {
25921×
                node: f,
25931×
                old: Some(b1),
25941×
                new: Some(b2),
25951×
            }],
2596
        ))
25971×
        .unwrap();
25981×
        st.add(change(
25991×
            vec![h1],
26001×
            vec![],
26011×
            vec![Edit::Replace {
26021×
                node: f,
26031×
                old: Some(b1),
26041×
                new: Some(b3),
26051×
            }],
2606
        ))
26071×
        .unwrap();
26081×
        let snap = st.materialize();
26091×
        assert!(snap.is_conflicted());
26101×
        assert!(
26111×
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2612
        );
26131×
    }
2614
2615
    #[test]
26161×
    fn checkpoint_payload_round_trip_and_replay() {
26171×
        let mut st = State::new();
26181×
        let f = NodeId::random();
26191×
        let h1 = st
26201×
            .add(change(
26211×
                vec![],
26221×
                vec![TreeOp::AddNode {
26231×
                    node: f,
26241×
                    kind: NodeKind::File,
26251×
                    mode: Mode::TEXT,
26261×
                    parent: NodeId::ROOT,
26271×
                    name: "a".into(),
26281×
                }],
26291×
                vec![Edit::Insert {
26301×
                    node: f,
26311×
                    after: AtomRef::Start,
26321×
                    before: AtomRef::End,
26331×
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
26341×
                }],
2635
            ))
26361×
            .unwrap();
26371×
        let h2 = st
26381×
            .add(change(
26391×
                vec![h1],
26401×
                vec![],
26411×
                vec![Edit::Delete {
26421×
                    node: f,
26431×
                    atoms: vec![AtomRange {
26441×
                        change: h1,
26451×
                        from: 0,
26461×
                        to: 1,
26471×
                    }],
26481×
                }],
2649
            ))
26501×
            .unwrap();
26511×
        let payload = st.checkpoint_payload();
26521×
        let back = State::from_checkpoint_payload(&payload).unwrap();
26531×
        assert_eq!(back.len(), 2);
26541×
        assert_eq!(back.heads(), vec![h2]);
26551×
        assert_eq!(back.get(&h1).unwrap().message, "m");
26561×
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2657
        // Replaying a further change onto the restored state equals a full build.
26581×
        let c3 = change(
26591×
            vec![h2],
26601×
            vec![],
26611×
            vec![Edit::Insert {
26621×
                node: f,
26631×
                after: AtomRef::Atom {
26641×
                    change: h1,
26651×
                    index: 1,
26661×
                },
26671×
                before: AtomRef::End,
26681×
                lines: vec![b"3\n".to_vec()].into(),
26691×
            }],
2670
        );
26711×
        let mut full = st.clone();
26721×
        full.add(c3.clone()).unwrap();
26731×
        let mut restored = back;
26741×
        restored.add(c3).unwrap();
26751×
        let (a, b) = (full.materialize(), restored.materialize());
26761×
        assert_eq!(
26771×
            a.files.keys().collect::<Vec<_>>(),
26781×
            b.files.keys().collect::<Vec<_>>()
2679
        );
26801×
        assert_eq!(a.files["a"].content, b.files["a"].content);
26811×
        assert!(
26821×
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2683
        );
26841×
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
26851×
    }
2686
2687
    /// History-only states (O10f): the same state as a full load once its
2688
    /// graphs are built, by replay and from a version 2 checkpoint with
2689
    /// later changes; unloaded graphs are never read as empty.
2690
    #[test]
26911×
    fn graph_keys_change_exactly_when_a_graph_does() {
26921×
        let (f, g) = (NodeId::random(), NodeId::random());
26931×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
26942×
            node,
26952×
            kind: NodeKind::File,
2696
            mode: Mode::TEXT,
2697
            parent: NodeId::ROOT,
26982×
            name: name.into(),
26992×
        };
27001×
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
27014×
            node,
27024×
            after: AtomRef::Start,
27034×
            before: AtomRef::End,
27044×
            lines: vec![line.to_vec()].into(),
27054×
        };
27061×
        let c1 = change(
27071×
            vec![],
27081×
            vec![add(f, "f"), add(g, "g")],
27091×
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2710
        );
27111×
        let h1 = c1.hash();
27121×
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
27131×
        let h2 = c2.hash();
27141×
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
27156×
        let load = |cs: &[&Change]| {
27166×
            let mut st = State::new_history_only();
271710×
            for c in cs {
271810×
                st.add((*c).clone()).unwrap();
271910×
            }
27206×
            st
27216×
        };
27221×
        let s1 = load(&[&c1]);
27231×
        let s2 = load(&[&c1, &c2]);
27241×
        let s3 = load(&[&c1, &c2, &c3]);
272518×
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
27261×
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
27271×
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
27281×
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
27291×
        assert_ne!(key(&s2, &f), key(&s3, &f));
27301×
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
27311×
        let mut built = load(&[&c1]);
27321×
        built
27331×
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
27341×
            .unwrap();
27351×
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
27361×
        let mut full = State::new();
27371×
        full.add(c1.clone()).unwrap();
27381×
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2739
2740
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2741
        // or inline values: stable across loads, changed by later edits.
27421×
        let graphs = full.checkpoint_file_graphs();
27431×
        let index = full.checkpoint_index(&graphs, |enc| {
27440×
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
27450×
        });
27468×
        let cp = |extra: &[&Change]| {
27478×
            let mut st = State::from_checkpoint_history(&index).unwrap();
27488×
            for c in extra {
27495×
                st.add((*c).clone()).unwrap();
27505×
            }
27518×
            st
27528×
        };
27531×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
27541×
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
27551×
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
27561×
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2757
2758
        // Partial rendering: skipped files are listed and empty, the others
2759
        // render as in a full state.
27601×
        let mut part = load(&[&c1, &c2]);
27611×
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
27621×
            .unwrap();
27631×
        let snap = part.materialize_except(&[f].into_iter().collect());
27641×
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
27651×
        let mut whole = State::new();
27661×
        whole.add(c1.clone()).unwrap();
27671×
        whole.add(c2.clone()).unwrap();
27681×
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
27691×
        assert!(
27701×
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2771
        );
27721×
    }
2773
2774
    #[test]
27751×
    fn history_only_states_build_the_same_graphs_on_demand() {
27761×
        let small = NodeId::random();
27771×
        let big = NodeId::random();
27781×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
27792×
            node,
27802×
            kind: NodeKind::File,
2781
            mode: Mode::TEXT,
2782
            parent: NodeId::ROOT,
27832×
            name: name.into(),
27842×
        };
27851×
        let lines: crate::lines::Lines = (0..300)
2786300×
            .map(|i| format!("line {i}\n").into_bytes())
27871×
            .collect();
27881×
        let c1 = change(
27891×
            vec![],
27901×
            vec![add(small, "small"), add(big, "big")],
27911×
            vec![
27921×
                Edit::Insert {
27931×
                    node: small,
27941×
                    after: AtomRef::Start,
27951×
                    before: AtomRef::End,
27961×
                    lines: vec![b"x\n".to_vec()].into(),
27971×
                },
27981×
                Edit::Insert {
27991×
                    node: big,
28001×
                    after: AtomRef::Start,
28011×
                    before: AtomRef::End,
28021×
                    lines,
28031×
                },
2804
            ],
2805
        );
28061×
        let h1 = c1.hash();
28071×
        let c2 = change(
28081×
            vec![h1],
28091×
            vec![],
28101×
            vec![
28111×
                Edit::Delete {
28121×
                    node: big,
28131×
                    atoms: vec![AtomRange {
28141×
                        change: h1,
28151×
                        from: 2,
28161×
                        to: 9,
28171×
                    }],
28181×
                },
28191×
                Edit::Insert {
28201×
                    node: big,
28211×
                    after: AtomRef::Atom {
28221×
                        change: h1,
28231×
                        index: 20,
28241×
                    },
28251×
                    before: AtomRef::Atom {
28261×
                        change: h1,
28271×
                        index: 21,
28281×
                    },
28291×
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
28301×
                },
28311×
                Edit::Insert {
28321×
                    node: small,
28331×
                    after: AtomRef::Atom {
28341×
                        change: h1,
28351×
                        index: 0,
28361×
                    },
28371×
                    before: AtomRef::End,
28381×
                    lines: vec![b"y\n".to_vec()].into(),
28391×
                },
2840
            ],
2841
        );
28421×
        let h2 = c2.hash();
28431×
        let c3 = change(
28441×
            vec![h2],
28451×
            vec![],
28461×
            vec![Edit::Delete {
28471×
                node: small,
28481×
                atoms: vec![AtomRange {
28491×
                    change: h1,
28501×
                    from: 0,
28511×
                    to: 1,
28521×
                }],
28531×
            }],
2854
        );
2855
28561×
        let mut full = State::new();
28573×
        for c in [&c1, &c2, &c3] {
28583×
            full.add(c.clone()).unwrap();
28593×
        }
2860
        // By replay: nothing built until asked, then exactly the full graphs.
28611×
        let mut hist = State::new_history_only();
28623×
        for c in [&c1, &c2, &c3] {
28633×
            hist.add(c.clone()).unwrap();
28643×
        }
28651×
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
28661×
        assert_eq!(hist.len(), 3);
28671×
        hist.load_graphs(
28681×
            &[big],
28690×
            |_| unreachable!("no checkpoint"),
28700×
            |_| unreachable!(),
2871
        )
28721×
        .unwrap();
28731×
        assert_eq!(
28741×
            hist.render_file(&big).0,
28751×
            full.render_file(&big).0,
2876
            "one file on its own"
2877
        );
28781×
        assert!(!hist.is_full());
28791×
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
28801×
            .unwrap();
28811×
        assert!(hist.is_full());
28821×
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2883
2884
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
28851×
        let mut base = State::new();
28861×
        base.add(c1.clone()).unwrap();
28871×
        base.add(c2.clone()).unwrap();
28881×
        let graphs = base.checkpoint_file_graphs();
28891×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
28901×
        let index = base.checkpoint_index(&graphs, |enc| {
28911×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
28921×
            blobs.insert(r, enc.to_vec());
28931×
            r
28941×
        });
28951×
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
28961×
        from_cp.add(c3.clone()).unwrap();
28971×
        assert!(!from_cp.is_full());
28981×
        let mut fetched = 0;
28991×
        from_cp
29001×
            .load_graphs(
29011×
                &[small, big],
29021×
                |refs| {
29031×
                    fetched += refs.len();
29041×
                    refs.iter()
29051×
                        .map(|r| {
29061×
                            blobs
29071×
                                .get(r)
29081×
                                .cloned()
29091×
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
29101×
                        })
29111×
                        .collect()
29121×
                },
29130×
                |_| unreachable!(),
2914
            )
29151×
            .unwrap();
29161×
        assert_eq!(
2917
            fetched, 1,
2918
            "the large graph's blob, in one batch; the small one was inline"
2919
        );
29201×
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
29211×
    }
2922
2923
    #[test]
2924
    #[should_panic(expected = "was not loaded")]
29251×
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
29261×
        let f = NodeId::random();
29271×
        let mut st = State::new_history_only();
29281×
        st.add(change(
29291×
            vec![],
29301×
            vec![TreeOp::AddNode {
29311×
                node: f,
29321×
                kind: NodeKind::File,
29331×
                mode: Mode::TEXT,
29341×
                parent: NodeId::ROOT,
29351×
                name: "a".into(),
29361×
            }],
29371×
            vec![Edit::Insert {
29381×
                node: f,
29391×
                after: AtomRef::Start,
29401×
                before: AtomRef::End,
29411×
                lines: vec![b"a\n".to_vec()].into(),
29421×
            }],
2943
        ))
29441×
        .unwrap();
29451×
        st.render_file(&f);
29461×
    }
2947
2948
    #[test]
2949
    #[should_panic(expected = "needs every file graph")]
29501×
    fn materializing_a_history_only_state_is_refused() {
29511×
        let f = NodeId::random();
29521×
        let mut st = State::new_history_only();
29531×
        st.add(change(
29541×
            vec![],
29551×
            vec![TreeOp::AddNode {
29561×
                node: f,
29571×
                kind: NodeKind::File,
29581×
                mode: Mode::TEXT,
29591×
                parent: NodeId::ROOT,
29601×
                name: "a".into(),
29611×
            }],
29621×
            vec![Edit::Insert {
29631×
                node: f,
29641×
                after: AtomRef::Start,
29651×
                before: AtomRef::End,
29661×
                lines: vec![b"a\n".to_vec()].into(),
29671×
            }],
2968
        ))
29691×
        .unwrap();
29701×
        st.materialize();
29711×
    }
2972
2973
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
2974
    /// blob; the state read back is the same as from version 1.
2975
    #[test]
29761×
    fn checkpoint_index_round_trip_matches_version_1() {
29771×
        let mut st = State::new();
29781×
        let small = NodeId::random();
29791×
        let big = NodeId::random();
29801×
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
29812×
            node,
29822×
            kind: NodeKind::File,
2983
            mode: Mode::TEXT,
2984
            parent: NodeId::ROOT,
29852×
            name: name.into(),
29862×
        };
29871×
        let big_lines: crate::lines::Lines = (0..400)
2988400×
            .map(|i| format!("line {i} of a long file\n").into_bytes())
29891×
            .collect();
29901×
        let h1 = st
29911×
            .add(change(
29921×
                vec![],
29931×
                vec![add(small, "small"), add(big, "big")],
29941×
                vec![
29951×
                    Edit::Insert {
29961×
                        node: small,
29971×
                        after: AtomRef::Start,
29981×
                        before: AtomRef::End,
29991×
                        lines: vec![b"x\n".to_vec()].into(),
30001×
                    },
30011×
                    Edit::Insert {
30021×
                        node: big,
30031×
                        after: AtomRef::Start,
30041×
                        before: AtomRef::End,
30051×
                        lines: big_lines,
30061×
                    },
3007
                ],
3008
            ))
30091×
            .unwrap();
30101×
        st.add(change(
30111×
            vec![h1],
30121×
            vec![],
30131×
            vec![Edit::Delete {
30141×
                node: big,
30151×
                atoms: vec![AtomRange {
30161×
                    change: h1,
30171×
                    from: 3,
30181×
                    to: 7,
30191×
                }],
30201×
            }],
3021
        ))
30221×
        .unwrap();
3023
30241×
        let graphs = st.checkpoint_file_graphs();
30251×
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
30261×
        let index = st.checkpoint_index(&graphs, |enc| {
30271×
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
30281×
            blobs.insert(r, enc.to_vec());
30291×
            r
30301×
        });
30311×
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
30321×
        assert_eq!(
30331×
            State::checkpoint_graph_refs(&index).unwrap(),
30341×
            blobs.keys().copied().collect::<Vec<_>>()
3035
        );
30361×
        assert!(
30371×
            State::checkpoint_graph_refs(&st.checkpoint_payload())
30381×
                .unwrap()
30391×
                .is_empty(),
3040
            "version 1 names none"
3041
        );
30421×
        assert!(index.len() < st.checkpoint_payload().len());
3043
30441×
        let back = State::from_checkpoint(&index, |refs| {
30451×
            refs.iter()
30461×
                .map(|r| {
30471×
                    blobs
30481×
                        .get(r)
30491×
                        .cloned()
30501×
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
30511×
                })
30521×
                .collect()
30531×
        })
30541×
        .unwrap();
30551×
        assert_eq!(
30561×
            back.checkpoint_payload(),
30571×
            st.checkpoint_payload(),
3058
            "the same state as version 1"
3059
        );
30601×
        assert_eq!(
30611×
            back.materialize().files["big"].content,
30621×
            st.materialize().files["big"].content
3063
        );
3064
        // Deterministic: the same state gives the same index.
30651×
        assert_eq!(
30661×
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
30671×
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
30681×
            }),
3069
            index
3070
        );
3071
        // A missing graph blob is an error, not an empty file.
30721×
        assert!(
30731×
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
3074
        );
30751×
        assert!(
30761×
            State::from_checkpoint_payload(&index).is_err(),
3077
            "version 2 needs its blobs"
3078
        );
3079
        // Version 1 payloads still read, and unknown versions do not.
30801×
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
30811×
        let mut v3 = cbor::decode(&index).unwrap();
30821×
        if let Value::Map(m) = &mut v3 {
30831×
            m.insert(0, Value::Uint(3));
30841×
        }
30851×
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
30861×
    }
3087
3088
    #[test]
30891×
    fn maximal_elements() {
30901×
        let mut st = State::new();
30911×
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
30921×
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
30931×
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
30941×
        let mut m = st.maximal(&[h1, h2, h3]);
30951×
        m.sort();
30961×
        let mut want = vec![h2, h3];
30971×
        want.sort();
30981×
        assert_eq!(m, want);
30991×
        assert_eq!(st.heads(), want);
31001×
    }
3101
3102
    /// The bounded walk of `depends_on` agrees with the closure on random
3103
    /// graphs, and the memo stays within its bound.
3104
    #[test]
31051×
    fn depends_on_matches_the_closure() {
3106
        use rand::{Rng, SeedableRng};
31071×
        let mut rng = rand::rngs::StdRng::seed_from_u64(11);
31081×
        for _ in 0..10 {
310910×
            let mut st = State::new();
311010×
            let mut all: Vec<ChangeHash> = Vec::new();
311110×
            for _ in 0..80 {
3112800×
                let deps: Vec<ChangeHash> =
311331600×
                    all.iter().copied().filter(|_| rng.gen_bool(0.06)).collect();
3114800×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
3115
            }
311610×
            let unknown = ObjectRef([0xee; 32]);
3117800×
            for a in &all {
3118800×
                let want = st.closure(a).clone();
3119800×
                st.closure.write().unwrap().sets.clear();
3120800×
                st.closure.write().unwrap().held = 0;
312164800×
                for b in all.iter().chain([&unknown]) {
312264800×
                    assert_eq!(
312364800×
                        st.depends_on(a, b),
312464800×
                        a == b || want.contains(b),
3125
                        "{a:?} on {b:?}"
3126
                    );
3127
                }
3128
            }
312910×
            assert!(st.closure.write().unwrap().held <= CLOSURE_MEMO_HASHES);
3130
        }
31311×
    }
3132
3133
    /// The one-walk `maximal` agrees with the definition (not in the
3134
    /// closure of another element) on random graphs, with repeated and
3135
    /// unknown hashes among the input.
3136
    #[test]
31371×
    fn maximal_matches_its_definition() {
3138
        use rand::{Rng, SeedableRng};
31391×
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
31401×
        for _ in 0..20 {
314120×
            let mut st = State::new();
314220×
            let mut all: Vec<ChangeHash> = Vec::new();
314320×
            for _ in 0..60 {
31441200×
                let deps: Vec<ChangeHash> =
314535400×
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
31461200×
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
3147
            }
314820×
            let mut pick: Vec<ChangeHash> =
31491200×
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
315020×
            pick.extend(pick.clone().into_iter().take(3));
315120×
            pick.push(ObjectRef([0xee; 32]));
315220×
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
315320×
            let want: Vec<ChangeHash> = set
315420×
                .iter()
31558620×
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
315620×
                .copied()
315720×
                .collect();
315820×
            assert_eq!(st.maximal(&pick), want);
315920×
            assert_eq!(st.maximal(&all), st.heads());
3160
        }
31611×
    }
3162
}