OXYGENHUB
◆ v0.7.0 oxygen / crates / oxy-core / src / state.rs
113.6 KiB · Rust · last changed A big tree renders many times faster, and is not rendered twice (refs #137) 10 days ago source blame history raw
ff0af1ee unknown 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
75167672 Andy McCall 4
use crate::cbor::{self, Value};
ff0af1ee unknown 5
use crate::graph::{AtomKey, DepOracle, FileGraph, Materialized, Vertex};
75167672 Andy McCall 6
use crate::hash::KeyId;
ff0af1ee unknown 7
use crate::hash::{ChangeHash, ObjectRef};
8
use crate::ids::NodeId;
75167672 Andy McCall 9
use crate::objects::{
10
    self as o, AtomRef, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, ObjectError, TreeOp,
11
};
ff0af1ee unknown 12
use crate::tree::{TreeGraph, TreeView};
9d333fc9 Andy McCall ↶ 13
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
aedfe465 Andy McCall ↶ 14
use std::sync::Arc;
ff0af1ee unknown 15
afaba5f1 Andy McCall ↶ 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
ff0af1ee unknown 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
55e5a16a unknown ↶ 28
/// One `Replace` edit: `(change, old blob, new blob)`.
29
type ReplaceRecord = (ChangeHash, Option<ObjectRef>, Option<ObjectRef>);
30
252e8cb2 Andy McCall ↶ 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
74b4a3c6 Andy McCall ↶ 43
/// The log's order of changes: newest first by clock, then by hash, so
44
/// it is total.
45
pub fn log_order(a: (&ChangeHash, &Hlc), b: (&ChangeHash, &Hlc)) -> std::cmp::Ordering {
46
    b.1.cmp(a.1).then(b.0.cmp(a.0))
47
}
48
252e8cb2 Andy McCall ↶ 49
impl ChangeMeta {
ce14f0d6 Andy McCall ↶ 50
    /// In the flat layout of local indexes and caches ([`crate::flat`]).
51
    pub(crate) fn write_flat(&self, w: &mut crate::flat::Writer) {
52
        w.fixed(&self.change_id.0);
53
        w.count(self.deps.len());
54
        for d in &self.deps {
55
            w.object(d);
56
        }
57
        w.object(&self.author);
58
        w.u64(self.hlc.wall_ms);
59
        w.u32(self.hlc.logical);
60
        w.bytes(self.message.as_bytes());
61
        w.u8(self.kind.tag() as u8);
62
    }
63
64
    pub(crate) fn read_flat(r: &mut crate::flat::Reader) -> Result<ChangeMeta, ObjectError> {
65
        let change_id = crate::ids::ChangeId(r.fixed::<16>()?);
66
        let mut deps = Vec::new();
67
        for _ in 0..r.count()? {
68
            deps.push(r.object()?);
69
        }
70
        Ok(ChangeMeta {
71
            change_id,
72
            deps,
73
            author: r.object()?,
74
            hlc: Hlc {
75
                wall_ms: r.u64()?,
76
                logical: r.u32()?,
77
            },
78
            message: r.text()?,
79
            kind: ChangeKind::from_tag(r.u8()? as u64)?,
80
        })
81
    }
82
252e8cb2 Andy McCall ↶ 83
    pub fn of(c: &Change) -> ChangeMeta {
75167672 Andy McCall 84
        ChangeMeta {
85
            change_id: c.change_id,
86
            deps: c.deps.clone(),
87
            author: c.author,
88
            hlc: c.hlc,
89
            message: c.message.clone(),
90
            kind: c.kind,
91
        }
252e8cb2 Andy McCall ↶ 92
    }
93
}
94
119bbf50 Andy McCall ↶ 95
#[derive(Default)]
ff0af1ee unknown 96
pub struct State {
f6451fbb Andy McCall ↶ 97
    /// Shared between clones, like `files` and `deferred`: a state kept
98
    /// beside another that differs by a few changes shares the rest.
ac03130a Andy McCall ↶ 99
    changes: crate::fasthash::FastMap<ChangeHash, Arc<ChangeMeta>>,
ff0af1ee unknown 100
    tree: TreeGraph,
dfb23a3a Andy McCall ↶ 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.
36e51aa8 Andy McCall ↶ 104
    files: crate::fasthash::FastMap<NodeId, Arc<FileGraph>>,
55e5a16a unknown ↶ 105
    replaces: HashMap<NodeId, Vec<ReplaceRecord>>,
d45dab04 Andy McCall ↶ 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.
aedfe465 Andy McCall ↶ 111
    closure: std::sync::RwLock<ClosureMemo>,
d45dab04 Andy McCall ↶ 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.
aedfe465 Andy McCall ↶ 115
    levels: std::sync::RwLock<crate::fasthash::FastMap<ChangeHash, u32>>,
e8d38e47 Andy McCall ↶ 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`].
36e51aa8 Andy McCall ↶ 119
    deferred: Option<crate::fasthash::FastMap<NodeId, Arc<Deferred>>>,
c2e1d090 Andy McCall 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>,
ff0af1ee unknown 123
}
124
a4fad5b0 Andy McCall ↶ 125
use crate::objects::TextRef;
86e1824f Andy McCall ↶ 126
e8d38e47 Andy McCall ↶ 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).
3f1b8fe2 Andy McCall ↶ 131
///
5552e69c Andy McCall ↶ 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).
e8d38e47 Andy McCall ↶ 135
#[derive(Clone, Default)]
136
struct Deferred {
5552e69c Andy McCall ↶ 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>,
3f1b8fe2 Andy McCall ↶ 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
5552e69c Andy McCall ↶ 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 {
161
    fn len(&self) -> u64 {
162
        match self {
163
            Histories::Bytes(b) => b.len() as u64,
164
            Histories::File(_, _, len) => *len,
165
        }
166
    }
167
168
    fn read(&self, at: u64, len: usize) -> std::io::Result<Vec<u8>> {
169
        match self {
170
            Histories::Bytes(b) => Ok(b[at as usize..at as usize + len].to_vec()),
171
            Histories::File(f, start, _) => {
172
                let mut buf = vec![0u8; len];
173
                read_exact_at(f, &mut buf, start + at)?;
174
                Ok(buf)
175
            }
176
        }
177
    }
178
}
179
180
#[cfg(unix)]
181
fn read_exact_at(f: &std::fs::File, buf: &mut [u8], at: u64) -> std::io::Result<()> {
182
    std::os::unix::fs::FileExt::read_exact_at(f, buf, at)
183
}
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.
210
    fn bytes(&self) -> Result<Vec<u8>, ObjectError> {
211
        let damaged = |why: String| ObjectError::DamagedIndex(why);
212
        let b = self
213
            .from
214
            .read(self.at, self.len)
215
            .map_err(|e| damaged(format!("a file's history cannot be read: {e}")))?;
216
        if *blake3::hash(&b).as_bytes() != self.sum {
217
            return Err(damaged("a file's history does not match its hash".into()));
218
        }
219
        Ok(b)
220
    }
221
}
222
d45dab04 Andy McCall ↶ 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
3f1b8fe2 Andy McCall ↶ 234
#[derive(Clone, Default)]
235
struct DeferredBody {
e8d38e47 Andy McCall ↶ 236
    base: Option<DeferredBase>,
237
    edits: Vec<(ChangeHash, Vec<Edit>)>,
86e1824f Andy McCall ↶ 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.
a4fad5b0 Andy McCall ↶ 240
    texts: Vec<TextRef>,
3f1b8fe2 Andy McCall ↶ 241
}
242
243
impl Deferred {
244
    fn from_body(body: DeferredBody) -> Deferred {
245
        Deferred {
5552e69c Andy McCall ↶ 246
            body: std::sync::OnceLock::from(Ok(body)),
3f1b8fe2 Andy McCall ↶ 247
            ..Deferred::default()
248
        }
5552e69c Andy McCall ↶ 249
    }
250
251
    /// The history, read and checked on first use.
252
    fn body(&self) -> Result<&DeferredBody, ObjectError> {
253
        self.body
254
            .get_or_init(|| {
255
                let mut b = match &self.raw {
256
                    // Matching its hash, it is what `write_index` wrote: it
257
                    // decodes.
258
                    Some(raw) => raw
259
                        .bytes()
260
                        .and_then(|b| State::read_deferred_body(&b))
261
                        .map_err(|e| e.to_string())?,
262
                    None => DeferredBody::default(),
263
                };
264
                b.edits.extend(self.more.iter().cloned());
265
                b.texts.extend(self.more_texts.iter().cloned());
266
                Ok(b)
267
            })
268
            .as_ref()
269
            .map_err(|e| ObjectError::DamagedIndex(e.clone()))
3f1b8fe2 Andy McCall ↶ 270
    }
271
5552e69c Andy McCall ↶ 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.
274
    fn add(&mut self, h: ChangeHash, edits: Vec<Edit>, texts: Vec<TextRef>) {
275
        if self.raw.is_some() && !matches!(self.body.get(), Some(Ok(_))) {
276
            self.more.push((h, edits));
277
            self.more_texts.extend(texts);
278
            // A body found damaged stays so: what was added cannot mend it.
279
            return;
280
        }
281
        // No encoding to read, or decoded already: this cannot fail.
282
        let b = self.body_mut().expect("a history in memory");
283
        b.edits.push((h, edits));
284
        b.texts.extend(texts);
3f1b8fe2 Andy McCall ↶ 285
    }
286
5552e69c Andy McCall ↶ 287
    fn body_mut(&mut self) -> Result<&mut DeferredBody, ObjectError> {
288
        self.body()?;
3f1b8fe2 Andy McCall ↶ 289
        self.raw = None;
5552e69c Andy McCall ↶ 290
        self.more.clear();
291
        self.more_texts.clear();
292
        Ok(self
293
            .body
294
            .get_mut()
295
            .and_then(|b| b.as_mut().ok())
296
            .expect("decoded above"))
3f1b8fe2 Andy McCall ↶ 297
    }
298
5552e69c Andy McCall ↶ 299
    fn into_body(mut self) -> Result<DeferredBody, ObjectError> {
300
        self.body()?;
301
        Ok(self
302
            .body
303
            .take()
304
            .and_then(|b| b.ok())
305
            .expect("decoded above"))
3f1b8fe2 Andy McCall ↶ 306
    }
e8d38e47 Andy McCall ↶ 307
}
308
309
#[derive(Clone)]
310
enum DeferredBase {
311
    Inline(Value),
312
    Blob(ObjectRef),
f9575918 Andy McCall ↶ 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 {
5552e69c Andy McCall ↶ 321
    const INDEX_MAGIC: &'static [u8] = b"oxy state index 4\n";
f9575918 Andy McCall ↶ 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).
326
    pub fn write_index(&self) -> Option<Vec<u8>> {
327
        use crate::flat::Writer;
328
        let deferred = self.deferred.as_ref()?;
329
        if !self.files.is_empty() {
330
            return None;
331
        }
4cce912a Andy McCall ↶ 332
        // The changes first, as a block a reader can take on its own (see
333
        // [`State::read_index_changes`]).
f9575918 Andy McCall ↶ 334
        let mut w = Writer::default();
335
        w.fixed(Self::INDEX_MAGIC);
74b4a3c6 Andy McCall ↶ 336
        // In log order, newest first (oxygen#94): the log takes them as
337
        // they come, with no map and no sort.
f9575918 Andy McCall ↶ 338
        let mut changes: Vec<(&ChangeHash, &Arc<ChangeMeta>)> = self.changes.iter().collect();
74b4a3c6 Andy McCall ↶ 339
        changes.sort_unstable_by(|a, b| log_order((a.0, &a.1.hlc), (b.0, &b.1.hlc)));
f9575918 Andy McCall ↶ 340
        w.count(changes.len());
341
        for (h, m) in changes {
342
            w.object(h);
ce14f0d6 Andy McCall ↶ 343
            m.write_flat(&mut w);
f9575918 Andy McCall ↶ 344
        }
4cce912a Andy McCall ↶ 345
        let changes_block = std::mem::take(&mut w);
346
        w.bytes(&changes_block.0);
f9575918 Andy McCall ↶ 347
        // The tree and the files' histories as blocks of their own, so a
348
        // reader decodes them side by side.
349
        let mut tw = Writer::default();
350
        self.tree.write_flat(&mut tw);
351
        w.bytes(&tw.0);
352
        let mut replaces: Vec<(&NodeId, &Vec<ReplaceRecord>)> = self.replaces.iter().collect();
353
        replaces.sort_by_key(|(n, _)| **n);
354
        w.count(replaces.len());
355
        for (n, recs) in replaces {
356
            w.fixed(&n.0);
357
            w.count(recs.len());
358
            // In any order: which record is live does not depend on it.
359
            let mut recs: Vec<&ReplaceRecord> = recs.iter().collect();
360
            recs.sort();
361
            for (c, old, new) in recs {
362
                w.object(c);
363
                w.opt_object(old);
364
                w.opt_object(new);
365
            }
366
        }
5552e69c Andy McCall ↶ 367
        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).
370
        let mut table = Writer::default();
371
        let mut histories: Vec<u8> = Vec::new();
f9575918 Andy McCall ↶ 372
        let mut nodes: Vec<(&NodeId, &Arc<Deferred>)> = deferred.iter().collect();
373
        nodes.sort_by_key(|(n, _)| **n);
5552e69c Andy McCall ↶ 374
        table.count(nodes.len());
f9575918 Andy McCall ↶ 375
        for (n, d) in nodes {
5552e69c Andy McCall ↶ 376
            let key = match d.key.get() {
377
                Some(k) => *k,
378
                None => {
379
                    let mut h = blake3::Hasher::new();
380
                    h.update(b"oxy graph key 1\0");
381
                    h.update(&n.0);
382
                    let k = d.graph_key(h).ok()?;
383
                    let _ = d.key.set(k);
384
                    k
f9575918 Andy McCall ↶ 385
                }
5552e69c Andy McCall ↶ 386
            };
387
            // Unchanged since read: its bytes as they are, checked.
388
            let bytes = match &d.raw {
389
                Some(raw) if d.more.is_empty() => raw.bytes().ok()?,
390
                _ => Self::write_deferred_body(d.body().ok()?)?,
391
            };
392
            table.fixed(&n.0);
393
            table.fixed(&key);
394
            table.u64(histories.len() as u64);
395
            table.u32(u32::try_from(bytes.len()).ok()?);
396
            table.fixed(blake3::hash(&bytes).as_bytes());
397
            histories.extend_from_slice(&bytes);
398
        }
399
        front.bytes(&table.0);
400
        let mut out = Writer::default();
401
        out.u64(front.0.len() as u64);
402
        out.fixed(&front.0);
403
        out.fixed(&histories);
404
        Some(out.0)
405
    }
406
407
    /// One file's history as an index encodes it; `None` when it holds
408
    /// text in memory, which an index does not.
409
    fn write_deferred_body(d: &DeferredBody) -> Option<Vec<u8>> {
410
        use crate::flat::Writer;
411
        let atom = |w: &mut Writer, a: &AtomRef| match a {
412
            AtomRef::Start => w.u8(0),
413
            AtomRef::End => w.u8(1),
414
            AtomRef::Atom { change, index } => {
415
                w.u8(2);
416
                w.object(change);
417
                w.u32(*index);
f9575918 Andy McCall ↶ 418
            }
5552e69c Andy McCall ↶ 419
        };
420
        let mut w = Writer::default();
421
        match &d.base {
422
            None => w.u8(0),
423
            Some(DeferredBase::Blob(r)) => {
424
                w.u8(1);
425
                w.object(r);
f9575918 Andy McCall ↶ 426
            }
5552e69c Andy McCall ↶ 427
            Some(DeferredBase::Inline(v)) => {
428
                w.u8(2);
429
                w.bytes(&cbor::encode(v));
f9575918 Andy McCall ↶ 430
            }
5552e69c Andy McCall ↶ 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.
435
        let mut texts = d.texts.iter();
436
        let mut per_change: Vec<(&ChangeHash, &Vec<Edit>, Vec<&TextRef>)> = Vec::new();
437
        for (c, edits) in &d.edits {
438
            let n = edits
f9575918 Andy McCall ↶ 439
                .iter()
5552e69c Andy McCall ↶ 440
                .filter(|e| matches!(e, Edit::Insert { lines, .. } if lines.is_empty()))
441
                .count();
442
            per_change.push((c, edits, texts.by_ref().take(n).collect()));
443
        }
444
        per_change.sort_by_key(|(c, _, _)| **c);
445
        w.count(per_change.len());
446
        for (c, edits, _) in &per_change {
447
            w.object(c);
448
            w.count(edits.len());
449
            for e in edits.iter() {
450
                match e {
451
                    Edit::Insert {
452
                        node,
453
                        after,
454
                        before,
455
                        lines,
456
                    } => {
457
                        if !lines.is_empty() {
458
                            return None;
459
                        }
f9575918 Andy McCall ↶ 460
                        w.u8(0);
5552e69c Andy McCall ↶ 461
                        w.fixed(&node.0);
462
                        atom(&mut w, after);
463
                        atom(&mut w, before);
f9575918 Andy McCall ↶ 464
                    }
5552e69c Andy McCall ↶ 465
                    Edit::Delete { node, atoms } => {
f9575918 Andy McCall ↶ 466
                        w.u8(1);
5552e69c Andy McCall ↶ 467
                        w.fixed(&node.0);
468
                        w.count(atoms.len());
469
                        for r in atoms {
470
                            w.object(&r.change);
471
                            w.u32(r.from);
472
                            w.u32(r.to);
473
                        }
f9575918 Andy McCall ↶ 474
                    }
5552e69c Andy McCall ↶ 475
                    Edit::Replace { .. } => return None,
f9575918 Andy McCall ↶ 476
                }
477
            }
478
        }
5552e69c Andy McCall ↶ 479
        let texts: Vec<&TextRef> = per_change
480
            .iter()
481
            .flat_map(|(_, _, t)| t.iter().copied())
482
            .collect();
483
        w.count(texts.len());
484
        for t in texts {
485
            match t {
486
                TextRef::Blob(r, count, form) => {
487
                    w.u8(0);
488
                    w.object(r);
489
                    w.u32(*count);
490
                    w.u8(match form {
491
                        crate::objects::TextForm::Cbor => 0,
492
                        crate::objects::TextForm::Raw => 1,
493
                        crate::objects::TextForm::CborFallback => 2,
494
                    });
495
                }
496
                TextRef::Inline { change, start, end } => {
497
                    w.u8(1);
498
                    w.object(change);
499
                    w.u32(*start);
500
                    w.u32(*end);
501
                }
502
            }
503
        }
504
        Some(w.0)
f9575918 Andy McCall ↶ 505
    }
506
507
    /// The state an index holds (see [`State::write_index`]).
508
    pub fn read_index(bytes: &[u8]) -> Result<State, ObjectError> {
5552e69c Andy McCall ↶ 509
        let bad = || ObjectError::Schema("state index: truncated".into());
510
        let front_len =
511
            usize::try_from(crate::flat::Reader::new(bytes).u64()?).map_err(|_| bad())?;
512
        let front = bytes.get(8..8 + front_len).ok_or_else(bad)?;
513
        let histories = Histories::Bytes(Arc::new(bytes[8 + front_len..].to_vec()));
514
        Self::read_index_front(front, histories)
79b5a90f Andy McCall ↶ 515
    }
516
5552e69c Andy McCall ↶ 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).
520
    pub fn read_index_front(bytes: &[u8], histories: Histories) -> Result<State, ObjectError> {
f9575918 Andy McCall ↶ 521
        use crate::flat::Reader;
522
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
523
        let mut r = Reader::new(bytes);
4cce912a Andy McCall ↶ 524
        let mut st = State::new_history_only();
525
        {
526
            let _t = crate::timing::phase("index: changes");
527
            st.changes = Self::read_index_changes(r.bytes()?)?;
528
        }
529
        let tree_bytes = r.bytes()?;
530
        for _ in 0..r.count()? {
531
            let n = NodeId(r.fixed::<16>()?);
532
            let mut recs = Vec::new();
533
            for _ in 0..r.count()? {
534
                recs.push((r.object()?, r.opt_object()?, r.opt_object()?));
535
            }
536
            st.replaces.insert(n, recs);
537
        }
538
        let deferred_bytes = r.bytes()?;
539
        if !r.at_end() {
540
            return Err(bad("trailing bytes"));
541
        }
542
        let (tree, deferred) = rayon::join(
543
            || TreeGraph::read_flat(&mut Reader::new(tree_bytes)),
5552e69c Andy McCall ↶ 544
            || Self::read_deferred(deferred_bytes, &histories),
4cce912a Andy McCall ↶ 545
        );
546
        st.tree = tree?;
547
        st.deferred = Some(deferred?);
548
        Ok(st)
549
    }
550
551
    /// The changes of a state index: its first block, which a reader can
74b4a3c6 Andy McCall ↶ 552
    /// take without the rest.
4cce912a Andy McCall ↶ 553
    pub fn read_index_changes(
554
        bytes: &[u8],
ac03130a Andy McCall ↶ 555
    ) -> Result<crate::fasthash::FastMap<ChangeHash, Arc<ChangeMeta>>, ObjectError> {
74b4a3c6 Andy McCall ↶ 556
        Ok(Self::read_index_changes_listed(bytes)?
557
            .into_iter()
558
            .map(|(h, m)| (h, Arc::new(m)))
559
            .collect())
560
    }
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).
565
    pub fn read_index_changes_listed(
566
        bytes: &[u8],
567
    ) -> Result<Vec<(ChangeHash, ChangeMeta)>, ObjectError> {
4cce912a Andy McCall ↶ 568
        use crate::flat::Reader;
569
        let mut r = Reader::new(bytes);
f9575918 Andy McCall ↶ 570
        if r.fixed::<18>()?.as_slice() != Self::INDEX_MAGIC {
4cce912a Andy McCall ↶ 571
            return Err(ObjectError::Schema("state index: not a state index".into()));
f9575918 Andy McCall ↶ 572
        }
573
        let n = r.count()?;
74b4a3c6 Andy McCall ↶ 574
        let mut changes = Vec::with_capacity(n);
f9575918 Andy McCall ↶ 575
        for _ in 0..n {
576
            let h = r.object()?;
74b4a3c6 Andy McCall ↶ 577
            changes.push((h, ChangeMeta::read_flat(&mut r)?));
f9575918 Andy McCall ↶ 578
        }
579
        if !r.at_end() {
4cce912a Andy McCall ↶ 580
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
f9575918 Andy McCall ↶ 581
        }
4cce912a Andy McCall ↶ 582
        Ok(changes)
f9575918 Andy McCall ↶ 583
    }
584
3f1b8fe2 Andy McCall ↶ 585
    /// The deferred block: each node with its graph key and its body,
586
    /// left encoded (see [`Deferred`]).
36e51aa8 Andy McCall ↶ 587
    fn read_deferred(
5552e69c Andy McCall ↶ 588
        table: &[u8],
589
        histories: &Histories,
36e51aa8 Andy McCall ↶ 590
    ) -> Result<crate::fasthash::FastMap<NodeId, Arc<Deferred>>, ObjectError> {
f9575918 Andy McCall ↶ 591
        use crate::flat::Reader;
592
        let _t = crate::timing::phase("index: deferred");
5552e69c Andy McCall ↶ 593
        let mut r = Reader::new(table);
36e51aa8 Andy McCall ↶ 594
        let mut deferred = crate::fasthash::FastMap::default();
3f1b8fe2 Andy McCall ↶ 595
        let n = r.count()?;
596
        deferred.reserve(n);
597
        for _ in 0..n {
598
            let id = NodeId(r.fixed::<16>()?);
599
            let key = r.fixed::<32>()?;
5552e69c Andy McCall ↶ 600
            // The length is of bytes in the histories, not in this table:
601
            // checked against the histories' size below.
602
            let (at, len, sum) = (r.u64()?, r.u32()? as usize, r.fixed::<32>()?);
603
            if at
604
                .checked_add(len as u64)
605
                .is_none_or(|end| end > histories.len())
606
            {
607
                return Err(ObjectError::Schema(
608
                    "state index: a file's history lies outside it".into(),
609
                ));
610
            }
3f1b8fe2 Andy McCall ↶ 611
            let d = Deferred {
5552e69c Andy McCall ↶ 612
                raw: Some(RawHistory {
613
                    from: histories.clone(),
614
                    at,
615
                    len,
616
                    sum,
617
                }),
3f1b8fe2 Andy McCall ↶ 618
                key: std::sync::OnceLock::from(key),
619
                ..Deferred::default()
620
            };
621
            deferred.insert(id, Arc::new(d));
622
        }
623
        if !r.at_end() {
624
            return Err(ObjectError::Schema("state index: trailing bytes".into()));
625
        }
626
        Ok(deferred)
627
    }
628
629
    /// One node's deferred history as the index encodes it.
630
    fn read_deferred_body(bytes: &[u8]) -> Result<DeferredBody, ObjectError> {
631
        use crate::flat::Reader;
f9575918 Andy McCall ↶ 632
        let bad = |what: &str| ObjectError::Schema(format!("state index: {what}"));
633
        let node = |r: &mut Reader| -> Result<NodeId, ObjectError> { Ok(NodeId(r.fixed::<16>()?)) };
634
        let atom = |r: &mut Reader| -> Result<AtomRef, ObjectError> {
635
            Ok(match r.u8()? {
636
                0 => AtomRef::Start,
637
                1 => AtomRef::End,
638
                2 => AtomRef::Atom {
639
                    change: r.object()?,
640
                    index: r.u32()?,
641
                },
642
                _ => return Err(bad("atom")),
643
            })
644
        };
645
        let mut r = Reader::new(bytes);
3f1b8fe2 Andy McCall ↶ 646
        let base = match r.u8()? {
647
            0 => None,
648
            1 => Some(DeferredBase::Blob(r.object()?)),
649
            _ => Some(DeferredBase::Inline(cbor::decode(r.bytes()?)?)),
650
        };
651
        let mut edits = Vec::new();
652
        for _ in 0..r.count()? {
653
            let c = r.object()?;
654
            let mut es = Vec::new();
f9575918 Andy McCall ↶ 655
            for _ in 0..r.count()? {
3f1b8fe2 Andy McCall ↶ 656
                es.push(match r.u8()? {
657
                    0 => Edit::Insert {
658
                        node: node(&mut r)?,
659
                        after: atom(&mut r)?,
660
                        before: atom(&mut r)?,
661
                        lines: crate::lines::Lines::default(),
f9575918 Andy McCall ↶ 662
                    },
3f1b8fe2 Andy McCall ↶ 663
                    1 => {
664
                        let node = node(&mut r)?;
665
                        let mut atoms = Vec::new();
666
                        for _ in 0..r.count()? {
667
                            atoms.push(crate::objects::AtomRange {
668
                                change: r.object()?,
669
                                from: r.u32()?,
670
                                to: r.u32()?,
671
                            });
672
                        }
673
                        Edit::Delete { node, atoms }
674
                    }
675
                    _ => return Err(bad("edit")),
f9575918 Andy McCall ↶ 676
                });
677
            }
3f1b8fe2 Andy McCall ↶ 678
            edits.push((c, es));
679
        }
680
        let mut texts = Vec::new();
681
        for _ in 0..r.count()? {
682
            texts.push(match r.u8()? {
683
                0 => TextRef::Blob(
684
                    r.object()?,
685
                    r.u32()?,
686
                    match r.u8()? {
687
                        0 => crate::objects::TextForm::Cbor,
688
                        1 => crate::objects::TextForm::Raw,
689
                        _ => crate::objects::TextForm::CborFallback,
690
                    },
691
                ),
692
                _ => TextRef::Inline {
693
                    change: r.object()?,
694
                    start: r.u32()?,
695
                    end: r.u32()?,
696
                },
697
            });
f9575918 Andy McCall ↶ 698
        }
699
        if !r.at_end() {
3f1b8fe2 Andy McCall ↶ 700
            return Err(bad("trailing bytes in a file's history"));
f9575918 Andy McCall ↶ 701
        }
3f1b8fe2 Andy McCall ↶ 702
        Ok(DeferredBody { base, edits, texts })
f9575918 Andy McCall ↶ 703
    }
e8d38e47 Andy McCall ↶ 704
}
705
119bbf50 Andy McCall ↶ 706
impl Clone for State {
707
    fn clone(&self) -> State {
708
        State {
709
            changes: self.changes.clone(),
710
            tree: self.tree.clone(),
711
            files: self.files.clone(),
712
            replaces: self.replaces.clone(),
f6451fbb Andy McCall ↶ 713
            // A cache: the clone builds its own.
aedfe465 Andy McCall ↶ 714
            closure: Default::default(),
715
            levels: Default::default(),
e8d38e47 Andy McCall ↶ 716
            deferred: self.deferred.clone(),
c2e1d090 Andy McCall 717
            unified_view: self.unified_view.clone(),
119bbf50 Andy McCall ↶ 718
        }
719
    }
720
}
721
ff0af1ee unknown 722
#[derive(Clone, Debug, PartialEq, Eq)]
723
pub enum FileContent {
75167672 Andy McCall 724
    Text {
725
        bytes: Vec<u8>,
726
        materialized: Materialized,
727
    },
ff0af1ee unknown 728
    /// Live blobs; more than one is a replace conflict (spec §9.3).
75167672 Andy McCall 729
    Opaque {
730
        blobs: Vec<ObjectRef>,
731
    },
ff0af1ee unknown 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 {
744
    pub fn is_conflicted(&self) -> bool {
745
        match &self.content {
746
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
747
            FileContent::Opaque { blobs } => blobs.len() > 1,
748
            FileContent::Dir => false,
749
        }
750
    }
751
}
752
20247a03 Andy McCall ↶ 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
ff0af1ee unknown 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>,
cc7a0056 Andy McCall ↶ 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>,
ff0af1ee unknown 769
}
770
771
impl Snapshot {
772
    pub fn is_conflicted(&self) -> bool {
773
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
774
    }
775
}
776
777
fn vertex(r: AtomRef) -> Vertex {
778
    match r {
779
        AtomRef::Start => Vertex::Start,
780
        AtomRef::End => Vertex::End,
781
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
782
    }
783
}
784
785
/// Replace self references in a tree op with the concrete change hash.
786
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
787
    match op {
75167672 Andy McCall 788
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
789
            node: *node,
790
            placement: placement.resolve(me),
791
        },
792
        TreeOp::Move {
793
            node,
794
            old,
795
            parent,
796
            name,
797
        } => TreeOp::Move {
798
            node: *node,
799
            old: old.resolve(me),
800
            parent: *parent,
801
            name: name.clone(),
802
        },
803
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
804
            node: *node,
805
            old: old.resolve(me),
806
            mode: *mode,
807
        },
ff0af1ee unknown 808
        add @ TreeOp::AddNode { .. } => add.clone(),
e8d38e47 Andy McCall ↶ 809
    }
810
}
811
812
/// Apply one change's edits of one file (inserts and deletes; replaces
813
/// live beside the graphs) to that file's graph.
814
fn apply_file_edits(g: &mut FileGraph, h: ChangeHash, edits: Vec<Edit>) {
dbf06d34 Andy McCall ↶ 815
    // The graph's kept order, if any, follows the edits (see `Order`).
816
    let order = g.take_order();
817
    let mut inserts: Vec<(Vertex, Vertex, u32, u32)> = Vec::new();
818
    let mut deleted: Vec<crate::graph::AtomKey> = Vec::new();
e8d38e47 Andy McCall ↶ 819
    let mut next = 0u32;
820
    for e in edits {
821
        match e {
822
            Edit::Insert {
823
                after,
824
                before,
825
                lines,
826
                ..
827
            } => {
828
                let first = next;
dbf06d34 Andy McCall ↶ 829
                let count = lines.len() as u32;
830
                next += count;
831
                let (after, before) = (vertex(after.resolve(h)), vertex(before.resolve(h)));
832
                inserts.push((after, before, first, count));
833
                g.insert_owned(h, first, after, before, lines);
e8d38e47 Andy McCall ↶ 834
            }
835
            Edit::Delete { atoms, .. } => {
836
                for r in atoms {
dbf06d34 Andy McCall ↶ 837
                    let r = r.resolve(h);
838
                    deleted.extend((r.from..r.to).map(|i| (r.change, i)));
839
                    g.delete(h, &r);
e8d38e47 Andy McCall ↶ 840
                }
841
            }
842
            Edit::Replace { .. } => {}
843
        }
dbf06d34 Andy McCall ↶ 844
    }
845
    if let Some(o) = order {
7eac74ab Andy McCall ↶ 846
        g.keep_spliced(o, h, &inserts, &deleted);
ff0af1ee unknown 847
    }
848
}
849
57d8dc05 Andy McCall ↶ 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).
853
fn build_deferred(
3f1b8fe2 Andy McCall ↶ 854
    taken: Vec<(NodeId, Deferred)>,
57d8dc05 Andy McCall ↶ 855
    load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
856
    read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
857
) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
5552e69c Andy McCall ↶ 858
    let mut taken: Vec<(NodeId, DeferredBody)> = taken
859
        .into_iter()
860
        .map(|(n, d)| Ok((n, d.into_body()?)))
861
        .collect::<Result<_, ObjectError>>()?;
57d8dc05 Andy McCall ↶ 862
    let mut refs: Vec<ObjectRef> = taken
863
        .iter()
864
        .filter_map(|(_, d)| match &d.base {
865
            Some(DeferredBase::Blob(r)) => Some(*r),
866
            _ => None,
867
        })
868
        .collect();
869
    // Text blobs of inserts read without their lines, after the bases.
870
    let bases = refs.len();
871
    refs.extend(taken.iter().flat_map(|(_, d)| {
872
        d.texts.iter().filter_map(|t| match t {
0f93f49c Andy McCall ↶ 873
            TextRef::Blob(r, _, _) => Some(*r),
57d8dc05 Andy McCall ↶ 874
            TextRef::Inline { .. } => None,
875
        })
876
    }));
877
    // And the encodings of changes whose inline inserts are needed,
878
    // each read once.
638fb214 Andy McCall ↶ 879
    let reading = crate::timing::phase("graphs: read changes and blobs");
57d8dc05 Andy McCall ↶ 880
    let mut changes: HashMap<ChangeHash, Arc<Vec<u8>>> = HashMap::new();
881
    for t in taken.iter().flat_map(|(_, d)| d.texts.iter()) {
882
        if let TextRef::Inline { change, .. } = t {
883
            if !changes.contains_key(change) {
884
                changes.insert(*change, read_change(change)?);
885
            }
886
        }
887
    }
360aa74a Andy McCall ↶ 888
    let n_changes = changes.len();
889
    drop(reading);
890
    let reading = crate::timing::phase("graphs:   of which blobs");
57d8dc05 Andy McCall ↶ 891
    let mut blobs = if refs.is_empty() {
892
        Vec::new()
893
    } else {
894
        load(&refs)?
895
    };
360aa74a Andy McCall ↶ 896
    if crate::timing::enabled() {
897
        eprintln!(
898
            "timing graphs: {} graphs, {n_changes} changes, {} blobs",
899
            taken.len(),
900
            refs.len()
901
        );
902
    }
57d8dc05 Andy McCall ↶ 903
    if blobs.len() != refs.len() {
904
        return Err(ObjectError::Schema("graph blobs: wrong count".into()));
905
    }
638fb214 Andy McCall ↶ 906
    drop(reading);
acadb5ed Andy McCall ↶ 907
    let lines = crate::timing::phase("graphs: hand out blobs");
57d8dc05 Andy McCall ↶ 908
    let mut texts = blobs.split_off(bases).into_iter();
909
    let mut blobs = blobs.into_iter();
acadb5ed Andy McCall ↶ 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>>);
913
    let mut work: Vec<Work> = Vec::with_capacity(taken.len());
914
    for (node, d) in taken.drain(..) {
915
        let wanted = d
916
            .texts
917
            .iter()
918
            .filter(|t| matches!(t, TextRef::Blob(..)))
919
            .count();
920
        let mine: Vec<Vec<u8>> = texts.by_ref().take(wanted).collect();
921
        if mine.len() != wanted {
922
            return Err(ObjectError::Schema("text blobs: wrong count".into()));
57d8dc05 Andy McCall ↶ 923
        }
924
        let bytes = match &d.base {
925
            Some(DeferredBase::Blob(_)) => Some(
926
                blobs
927
                    .next()
928
                    .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
929
            ),
930
            _ => None,
931
        };
acadb5ed Andy McCall ↶ 932
        work.push((node, d, bytes, mine));
57d8dc05 Andy McCall ↶ 933
    }
638fb214 Andy McCall ↶ 934
    drop(lines);
acadb5ed Andy McCall ↶ 935
    let _t = crate::timing::phase("graphs: lines and build");
57d8dc05 Andy McCall ↶ 936
    use rayon::prelude::*;
acadb5ed Andy McCall ↶ 937
    let changes = &changes;
57d8dc05 Andy McCall ↶ 938
    let built: Vec<(NodeId, FileGraph)> = work
939
        .into_par_iter()
acadb5ed Andy McCall ↶ 940
        .map(|(node, mut d, bytes, mine)| {
941
            // Fill in the lines of inserts read without them, in order.
942
            let mut want = std::mem::take(&mut d.texts).into_iter();
943
            let mut mine = mine.into_iter();
944
            for (_, edits) in d.edits.iter_mut() {
945
                for e in edits.iter_mut() {
946
                    if let Edit::Insert { lines, .. } = e {
947
                        if lines.is_empty() {
948
                            *lines = match want.next() {
949
                                Some(TextRef::Blob(_, count, form)) => {
950
                                    let content = mine.next().ok_or_else(|| {
951
                                        ObjectError::Schema("text blobs: wrong count".into())
952
                                    })?;
953
                                    crate::objects::text_lines(&content, count, form)?
954
                                }
955
                                Some(TextRef::Inline { change, start, end }) => {
956
                                    let bytes = &changes[&change];
957
                                    let range = bytes
958
                                        .get(start as usize..end as usize)
959
                                        .ok_or_else(|| {
960
                                            ObjectError::Schema(
961
                                                "an inline insert lies outside its change".into(),
962
                                            )
963
                                        })?;
964
                                    crate::objects::inline_lines(range)?
965
                                }
966
                                None => {
967
                                    return Err(ObjectError::Schema(
968
                                        "an insert's text is missing".into(),
969
                                    ))
970
                                }
971
                            };
972
                        }
973
                    }
974
                }
975
            }
57d8dc05 Andy McCall ↶ 976
            let mut graph = match (d.base.take(), bytes) {
977
                (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
978
                (Some(DeferredBase::Blob(_)), Some(bytes)) => {
979
                    FileGraph::from_value(&cbor::decode(&bytes)?)?
980
                }
981
                _ => FileGraph::default(),
982
            };
983
            for (h, edits) in std::mem::take(&mut d.edits) {
984
                apply_file_edits(&mut graph, h, edits);
985
            }
986
            Ok((node, graph))
987
        })
988
        .collect::<Result<_, ObjectError>>()?;
989
    Ok(built)
990
}
991
ff0af1ee unknown 992
impl State {
993
    pub fn new() -> Self {
994
        Self::default()
e8d38e47 Andy McCall ↶ 995
    }
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.
1001
    pub fn new_history_only() -> Self {
1002
        State {
36e51aa8 Andy McCall ↶ 1003
            deferred: Some(Default::default()),
e8d38e47 Andy McCall ↶ 1004
            ..Self::default()
1005
        }
1006
    }
1007
e83354cd Andy McCall ↶ 1008
    /// Whether `node`'s file graph is built (always, in a full state).
1009
    pub fn is_built(&self, node: &NodeId) -> bool {
1010
        self.deferred.is_none() || self.files.contains_key(node)
1011
    }
1012
86e1824f Andy McCall ↶ 1013
    /// Whether this state builds file graphs only when asked
1014
    /// ([`State::new_history_only`]), even if it has none waiting.
1015
    pub fn is_history_only(&self) -> bool {
1016
        self.deferred.is_some()
1017
    }
1018
e8d38e47 Andy McCall ↶ 1019
    /// Whether this state holds every file graph.
1020
    pub fn is_full(&self) -> bool {
1021
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
1022
    }
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.
1026
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
1027
        if let Some(d) = &self.deferred {
1028
            assert!(
1029
                !d.contains_key(node),
1030
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
1031
                node.short(12)
1032
            );
1033
        }
dfb23a3a Andy McCall ↶ 1034
        self.files.get(node).map(|g| g.as_ref())
e8d38e47 Andy McCall ↶ 1035
    }
1036
1037
    /// Operations over every file need every graph.
1038
    fn require_full(&self, what: &str) {
1039
        assert!(
1040
            self.is_full(),
1041
            "{what} needs every file graph; this state was loaded for history only"
1042
        );
1043
    }
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.
1048
    pub fn load_graphs(
1049
        &mut self,
1050
        nodes: &[NodeId],
1051
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
519c7c06 Andy McCall ↶ 1052
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
e8d38e47 Andy McCall ↶ 1053
    ) -> Result<(), ObjectError> {
1054
        let Some(deferred) = self.deferred.as_mut() else {
1055
            return Ok(());
1056
        };
57d8dc05 Andy McCall ↶ 1057
        let taken: Vec<(NodeId, Deferred)> = nodes
e8d38e47 Andy McCall ↶ 1058
            .iter()
f6451fbb Andy McCall ↶ 1059
            .filter_map(|n| deferred.remove(n).map(|d| (*n, Arc::unwrap_or_clone(d))))
e8d38e47 Andy McCall ↶ 1060
            .collect();
57d8dc05 Andy McCall ↶ 1061
        let built = build_deferred(taken, load, read_change)?;
dfb23a3a Andy McCall ↶ 1062
        self.files
1063
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
cc7a0056 Andy McCall ↶ 1064
        Ok(())
57d8dc05 Andy McCall ↶ 1065
    }
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).
1072
    pub fn build_graphs_detached(
1073
        &self,
1074
        nodes: &[NodeId],
1075
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
1076
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
1077
    ) -> Result<Vec<(NodeId, FileGraph)>, ObjectError> {
1078
        let Some(deferred) = self.deferred.as_ref() else {
1079
            return Ok(Vec::new());
1080
        };
33be2409 Andy McCall ↶ 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).
1085
        let mut built: Vec<(NodeId, FileGraph)> = Vec::new();
1086
        let mut copies: Vec<(NodeId, Deferred)> = Vec::new();
1087
        for n in nodes {
1088
            match (self.files.get(n), deferred.get(n)) {
1089
                (Some(g), _) => built.push((*n, (**g).clone())),
1090
                (None, d) => copies.push((*n, d.map(|d| (**d).clone()).unwrap_or_default())),
1091
            }
1092
        }
1093
        let mut out = build_deferred(copies, load, read_change)?;
1094
        out.extend(built);
1095
        Ok(out)
57d8dc05 Andy McCall ↶ 1096
    }
1097
1098
    /// Render a graph built for this state (see
1099
    /// [`State::build_graphs_detached`]), as [`State::render_file`] does.
1100
    pub fn render_graph(&self, g: &FileGraph) -> (Vec<u8>, Materialized) {
1101
        let m = g.materialize(self);
1102
        let bytes = g.render(&m, &|h| self.label(h));
1103
        (bytes, m)
cc7a0056 Andy McCall ↶ 1104
    }
1105
69816d68 Andy McCall ↶ 1106
    /// Every file graph a history-only state has not built, deleted files'
1107
    /// included.
1108
    pub fn unbuilt_nodes(&self) -> Vec<NodeId> {
1109
        self.deferred
1110
            .as_ref()
1111
            .map(|d| d.keys().copied().collect())
1112
            .unwrap_or_default()
1113
    }
1114
c5ce0367 Andy McCall ↶ 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.
1118
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
1119
        for n in nodes {
1120
            self.files.remove(n);
1121
        }
1122
    }
1123
cc7a0056 Andy McCall ↶ 1124
    /// Build every graph a history-only state has not built, making it full.
1125
    pub fn load_all_graphs(
1126
        &mut self,
1127
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
519c7c06 Andy McCall ↶ 1128
        read_change: impl Fn(&ChangeHash) -> Result<Arc<Vec<u8>>, ObjectError>,
cc7a0056 Andy McCall ↶ 1129
    ) -> Result<(), ObjectError> {
1130
        let nodes: Vec<NodeId> = match &self.deferred {
1131
            Some(d) => d.keys().copied().collect(),
1132
            None => return Ok(()),
1133
        };
a4fad5b0 Andy McCall ↶ 1134
        self.load_graphs(&nodes, load, read_change)?;
cc7a0056 Andy McCall ↶ 1135
        self.deferred = None;
e8d38e47 Andy McCall ↶ 1136
        Ok(())
cc7a0056 Andy McCall ↶ 1137
    }
1138
091fef80 Andy McCall ↶ 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.
1143
    pub fn single_text(&self, node: &NodeId) -> Option<TextRef> {
1144
        if self.files.contains_key(node) {
1145
            return None;
1146
        }
5552e69c Andy McCall ↶ 1147
        // A history that cannot be read is no single text: building its
1148
        // graph reports why.
1149
        let d = self.deferred.as_ref()?.get(node)?.body().ok()?;
091fef80 Andy McCall ↶ 1150
        let [(_, edits)] = d.edits.as_slice() else {
1151
            return None;
1152
        };
1153
        let [Edit::Insert {
1154
            after: AtomRef::Start,
1155
            before: AtomRef::End,
1156
            lines,
1157
            ..
1158
        }] = edits.as_slice()
1159
        else {
1160
            return None;
1161
        };
1162
        match (&d.base, d.texts.as_slice()) {
1163
            (None, [t]) if lines.is_empty() => Some(*t),
1164
            _ => None,
1165
        }
1166
    }
1167
cc7a0056 Andy McCall ↶ 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.
1175
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
1176
        let deferred = self.deferred.as_ref()?;
1177
        if self.files.contains_key(node) {
1178
            return None;
1179
        }
1180
        let mut h = blake3::Hasher::new();
1181
        h.update(b"oxy graph key 1\0");
1182
        // A change's edits are applied per node: the node is part of it.
1183
        h.update(&node.0);
1184
        let Some(d) = deferred.get(node) else {
1185
            // Never edited: the empty graph.
1186
            h.update(&[0]);
1187
            return Some(*h.finalize().as_bytes());
1188
        };
5552e69c Andy McCall ↶ 1189
        // A history that cannot be read has no key: the file is read.
1190
        if let Some(k) = d.key.get() {
1191
            return Some(*k);
1192
        }
1193
        let k = d.graph_key(h).ok()?;
1194
        Some(*d.key.get_or_init(|| k))
f9575918 Andy McCall ↶ 1195
    }
1196
1197
    pub fn len(&self) -> usize {
1198
        self.changes.len()
1199
    }
fb5b6181 Andy McCall ↶ 1200
fd280228 Andy McCall ↶ 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.
1208
    pub fn shed_graphs<E>(
1209
        &mut self,
1210
        mut store: impl FnMut(&[u8]) -> Result<ObjectRef, E>,
1211
    ) -> Result<usize, E> {
1212
        use rayon::prelude::*;
1213
        let Some(deferred) = self.deferred.as_mut() else {
1214
            return Ok(0);
1215
        };
1216
        let graphs: Vec<(NodeId, Arc<FileGraph>)> = self.files.drain().collect();
1217
        let encoded: Vec<(NodeId, Vec<u8>)> = graphs
1218
            .par_iter()
1219
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
1220
            .collect();
1221
        drop(graphs);
1222
        let shed = encoded.len();
1223
        for (node, bytes) in encoded {
1224
            let blob = store(&bytes)?;
1225
            deferred.insert(
1226
                node,
1227
                Arc::new(Deferred::from_body(DeferredBody {
1228
                    base: Some(DeferredBase::Blob(blob)),
1229
                    ..DeferredBody::default()
1230
                })),
1231
            );
1232
        }
1233
        Ok(shed)
1234
    }
1235
fb5b6181 Andy McCall ↶ 1236
    /// How many file graphs this state has built.
1237
    pub fn built_count(&self) -> usize {
1238
        self.files.len()
1239
    }
d45dab04 Andy McCall ↶ 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.
1243
    pub fn built_atoms(&self) -> usize {
1244
        self.files.values().map(|g| g.atom_count()).sum()
1245
    }
1246
1247
    /// Edits held in the deferred histories of files not built, and the
1248
    /// most any one file holds (for measuring, #25).
1249
    pub fn deferred_edit_count(&self) -> (usize, usize) {
1250
        let Some(d) = self.deferred.as_ref() else {
1251
            return (0, 0);
1252
        };
1253
        let mut total = 0;
1254
        let mut most = 0;
1255
        for v in d.values() {
5552e69c Andy McCall ↶ 1256
            let n: usize = v
1257
                .body()
1258
                .map_or(0, |b| b.edits.iter().map(|(_, e)| e.len()).sum());
d45dab04 Andy McCall ↶ 1259
            total += n;
1260
            most = most.max(n);
1261
        }
1262
        (total, most)
1263
    }
f9575918 Andy McCall ↶ 1264
}
1265
1266
impl Deferred {
1267
    /// See [`State::graph_key`]: `h` has taken the node already.
5552e69c Andy McCall ↶ 1268
    fn graph_key(&self, mut h: blake3::Hasher) -> Result<[u8; 32], ObjectError> {
1269
        let d = self.body()?;
cc7a0056 Andy McCall ↶ 1270
        match &d.base {
1271
            None => h.update(&[0]),
1272
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
1273
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
1274
        };
1275
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
1276
        changes.sort();
1277
        changes.dedup();
1278
        h.update(&(changes.len() as u64).to_le_bytes());
1279
        for c in changes {
1280
            h.update(&c.0);
1281
        }
5552e69c Andy McCall ↶ 1282
        Ok(*h.finalize().as_bytes())
ff0af1ee unknown 1283
    }
f9575918 Andy McCall ↶ 1284
}
ff0af1ee unknown 1285
f9575918 Andy McCall ↶ 1286
impl State {
ff0af1ee unknown 1287
    pub fn is_empty(&self) -> bool {
1288
        self.changes.is_empty()
1289
    }
1290
    pub fn contains(&self, h: &ChangeHash) -> bool {
1291
        self.changes.contains_key(h)
1292
    }
252e8cb2 Andy McCall ↶ 1293
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
f6451fbb Andy McCall ↶ 1294
        self.changes.get(h).map(|m| &**m)
ff0af1ee unknown 1295
    }
252e8cb2 Andy McCall ↶ 1296
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
f6451fbb Andy McCall ↶ 1297
        self.changes.iter().map(|(h, m)| (h, &**m))
ff0af1ee unknown 1298
    }
1299
    pub fn tree(&self) -> &TreeGraph {
1300
        &self.tree
1301
    }
c2e1d090 Andy McCall 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.
1309
    pub fn view(&self) -> TreeView {
1310
        if let Some(v) = self.unified_view.get() {
1311
            return v.clone();
1312
        }
1313
        let raw = self.tree.view();
1314
        if !raw
1315
            .conflicts
1316
            .iter()
1317
            .any(|c| matches!(c, crate::tree::TreeConflict::Name { .. }))
1318
        {
1319
            return raw;
1320
        }
1321
        let (view, decided) = self.tree.unify(raw, |es| self.same_content(es));
1322
        if decided {
1323
            let _ = self.unified_view.set(view.clone());
1324
        }
1325
        view
1326
    }
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.
1330
    pub fn unify_candidates(&self) -> Vec<NodeId> {
1331
        let Some(deferred) = &self.deferred else {
1332
            return Vec::new();
1333
        };
1334
        if self.unified_view.get().is_some() {
1335
            return Vec::new();
1336
        }
1337
        let raw = self.tree.view();
1338
        let mut out = Vec::new();
1339
        for c in &raw.conflicts {
1340
            if let crate::tree::TreeConflict::Name { nodes, .. } = c {
1341
                out.extend(nodes.iter().filter(|n| deferred.contains_key(*n)));
1342
            }
1343
        }
1344
        out
1345
    }
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.
1350
    fn same_content(&self, entries: &[&crate::tree::TreeEntry]) -> Option<bool> {
1351
        let text = |e: &crate::tree::TreeEntry| e.kind == NodeKind::File && !e.mode.opaque;
1352
        let mut first: Option<Vec<u8>> = None;
1353
        let mut first_blob: Option<ObjectRef> = None;
1354
        for e in entries {
1355
            if text(e) {
1356
                if self
1357
                    .deferred
1358
                    .as_ref()
1359
                    .is_some_and(|d| d.contains_key(&e.node))
1360
                {
1361
                    return None;
1362
                }
1363
                let (bytes, m) = self.render_file(&e.node);
1364
                if m.is_conflicted() {
1365
                    return Some(false);
1366
                }
1367
                match &first {
1368
                    None => first = Some(bytes),
1369
                    Some(b) if *b == bytes => {}
1370
                    Some(_) => return Some(false),
1371
                }
1372
            } else {
1373
                let [blob] = self.live_blobs(&e.node)[..] else {
1374
                    return Some(false);
1375
                };
1376
                match first_blob {
1377
                    None => first_blob = Some(blob),
1378
                    Some(b) if b == blob => {}
1379
                    Some(_) => return Some(false),
1380
                }
1381
            }
1382
        }
1383
        Some(true)
1384
    }
ff0af1ee unknown 1385
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
e8d38e47 Andy McCall ↶ 1386
        self.graph(node)
ff0af1ee unknown 1387
    }
1388
1389
    /// Add a change whose dependencies are already present.
1390
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
1391
        let h = change.hash();
192fad1e Andy McCall ↶ 1392
        self.add_hashed(h, change)
1393
    }
1394
1395
    /// [`State::add`] for a change whose hash `h` is already known (it was
1396
    /// just stored), so it is not encoded again.
1397
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
ff0af1ee unknown 1398
        if self.changes.contains_key(&h) {
1399
            return Ok(h);
1400
        }
1401
        for d in &change.deps {
1402
            if !self.changes.contains_key(d) {
1403
                return Err(StateError::MissingDep(*d, h));
1404
            }
1405
        }
192fad1e Andy McCall ↶ 1406
        self.add_known(h, change, Vec::new());
1407
        Ok(h)
ff0af1ee unknown 1408
    }
1409
1410
    /// Add a change in any order; call `validate` once all are in.
1411
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
1412
        let h = change.hash();
86e1824f Andy McCall ↶ 1413
        self.add_known(h, change, Vec::new());
1414
        h
1415
    }
1416
ab4d4e31 Andy McCall ↶ 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.
1423
    pub fn add_known_mixed(
1424
        &mut self,
1425
        h: ChangeHash,
1426
        full: Change,
1427
        skeleton: Change,
1428
        texts: Vec<TextRef>,
1429
    ) {
1430
        if self.deferred.is_none() || self.changes.contains_key(&h) {
1431
            self.add_known(h, full, Vec::new());
1432
            return;
1433
        }
1434
        let Change {
1435
            version,
1436
            change_id,
1437
            deps,
1438
            author,
1439
            hlc,
1440
            message,
1441
            tree_ops,
1442
            edits: full_edits,
1443
            kind,
1444
        } = full;
1445
        let mut texts = texts.into_iter();
1446
        let mut edits = Vec::with_capacity(full_edits.len());
1447
        let mut kept = Vec::new();
1448
        for (f, s) in full_edits.into_iter().zip(skeleton.edits) {
1449
            let text = match &s {
1450
                Edit::Insert { lines, .. } if lines.is_empty() => texts.next(),
1451
                _ => None,
1452
            };
1453
            if self.files.contains_key(&f.node()) {
1454
                edits.push(f);
1455
            } else {
1456
                edits.push(s);
1457
                kept.extend(text);
1458
            }
1459
        }
1460
        let c = Change {
1461
            version,
1462
            change_id,
1463
            deps,
1464
            author,
1465
            hlc,
1466
            message,
1467
            tree_ops,
1468
            edits,
1469
            kind,
1470
        };
1471
        self.add_known(h, c, kept);
1472
    }
1473
86e1824f Andy McCall ↶ 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.
a4fad5b0 Andy McCall ↶ 1479
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<TextRef>) {
ff0af1ee unknown 1480
        if self.changes.contains_key(&h) {
86e1824f Andy McCall ↶ 1481
            return;
ff0af1ee unknown 1482
        }
0bdc3f91 Andy McCall ↶ 1483
        let meta = ChangeMeta::of(&change);
c2e1d090 Andy McCall 1484
        self.unified_view = Default::default();
86e1824f Andy McCall ↶ 1485
        self.apply_with(h, change, texts);
f6451fbb Andy McCall ↶ 1486
        self.changes.insert(h, Arc::new(meta));
d45dab04 Andy McCall ↶ 1487
        {
aedfe465 Andy McCall ↶ 1488
            let mut m = self.closure.write().unwrap();
d45dab04 Andy McCall ↶ 1489
            m.sets.clear();
1490
            m.held = 0;
1491
        }
ff0af1ee unknown 1492
    }
1493
252e8cb2 Andy McCall ↶ 1494
    // ------------------------------------------------------------ checkpoints (spec §11)
1495
afaba5f1 Andy McCall ↶ 1496
    /// Serialize the whole state in payload version 1: change metadata,
1497
    /// tree, file graphs, replaces, all in one value (spec §11).
252e8cb2 Andy McCall ↶ 1498
    pub fn checkpoint_payload(&self) -> Vec<u8> {
e8d38e47 Andy McCall ↶ 1499
        self.require_full("a checkpoint");
afaba5f1 Andy McCall ↶ 1500
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
1501
        nodes.sort();
1502
        let files = Value::Array(
1503
            nodes
1504
                .into_iter()
1505
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
1506
                .collect(),
1507
        );
1508
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
1509
    }
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.
1513
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
1514
        use rayon::prelude::*;
e8d38e47 Andy McCall ↶ 1515
        self.require_full("a checkpoint");
dfb23a3a Andy McCall ↶ 1516
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
1517
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
afaba5f1 Andy McCall ↶ 1518
        nodes.sort_by_key(|(n, _)| **n);
1519
        nodes
1520
            .into_par_iter()
1521
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
1522
            .collect()
1523
    }
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).
1529
    pub fn checkpoint_index(
1530
        &self,
1531
        graphs: &[(NodeId, Vec<u8>)],
1532
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
1533
    ) -> Vec<u8> {
1534
        let files = Value::Array(
1535
            graphs
1536
                .iter()
1537
                .map(|(n, enc)| {
1538
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
1539
                        cbor::decode(enc).expect("an encoded graph decodes")
1540
                    } else {
1541
                        Value::Bytes(blob_of(enc).0.to_vec())
1542
                    };
1543
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
1544
                })
1545
                .collect(),
1546
        );
1547
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
1548
    }
1549
1550
    /// The payload map around `files`: changes, tree and replaces as in version 1.
1551
    fn payload_value(&self, version: u64, files: Value) -> Value {
252e8cb2 Andy McCall ↶ 1552
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
1553
        hashes.sort();
1554
        let changes = Value::Array(
1555
            hashes
1556
                .into_iter()
1557
                .map(|h| {
1558
                    let m = &self.changes[h];
1559
                    Value::Array(vec![
1560
                        Value::Bytes(h.0.to_vec()),
1561
                        Value::Bytes(m.change_id.0.to_vec()),
1562
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
1563
                        Value::Text(m.message.clone()),
1564
                        Value::Uint(m.hlc.wall_ms),
1565
                        Value::Uint(m.hlc.logical as u64),
1566
                        Value::Uint(m.kind.tag()),
1567
                        Value::Bytes(m.author.0.to_vec()),
1568
                    ])
1569
                })
75167672 Andy McCall 1570
                .collect(),
1571
        );
252e8cb2 Andy McCall ↶ 1572
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
1573
        rnodes.sort();
75167672 Andy McCall 1574
        let opt =
1575
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
252e8cb2 Andy McCall ↶ 1576
        let replaces = Value::Array(
1577
            rnodes
1578
                .into_iter()
1579
                .map(|n| {
1580
                    Value::Array(vec![
1581
                        Value::Bytes(n.0.to_vec()),
75167672 Andy McCall 1582
                        Value::Array(
1583
                            self.replaces[n]
1584
                                .iter()
1585
                                .map(|(c, o, nw)| {
1586
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
1587
                                })
1588
                                .collect(),
1589
                        ),
252e8cb2 Andy McCall ↶ 1590
                    ])
1591
                })
1592
                .collect(),
1593
        );
afaba5f1 Andy McCall ↶ 1594
        Value::map([
1595
            (0, Value::Uint(version)),
75167672 Andy McCall 1596
            (1, changes),
1597
            (2, self.tree.to_value()),
1598
            (3, files),
1599
            (4, replaces),
afaba5f1 Andy McCall ↶ 1600
        ])
252e8cb2 Andy McCall ↶ 1601
    }
1602
afaba5f1 Andy McCall ↶ 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`].
252e8cb2 Andy McCall ↶ 1605
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
afaba5f1 Andy McCall ↶ 1606
        State::from_checkpoint(bytes, |_| {
1607
            Err(ObjectError::Schema(
1608
                "a version 2 checkpoint needs its graph blobs".into(),
1609
            ))
1610
        })
1611
    }
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.
1616
    pub fn from_checkpoint(
1617
        bytes: &[u8],
1618
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
1619
    ) -> Result<State, ObjectError> {
1620
        use rayon::prelude::*;
252e8cb2 Andy McCall ↶ 1621
        let v = cbor::decode(bytes)?;
1622
        let m = o::map(&v, "checkpoint payload")?;
afaba5f1 Andy McCall ↶ 1623
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
1624
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
1625
            return Err(ObjectError::Schema(format!(
1626
                "checkpoint payload version {version} is not supported"
1627
            )));
1628
        }
1629
        let mut st = State::payload_common(m)?;
1630
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
1631
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
1632
        for f in entries {
1633
            let e = o::array(f, "file")?;
1634
            if e.len() != 2 {
1635
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1636
            }
1637
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1638
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1639
            parsed.push((node, &e[1]));
1640
        }
1641
        // Version 2 names large graphs by blob: fetch those in one batch.
1642
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
1643
        if version == CHECKPOINT_INDEX_VERSION {
1644
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
1645
                .iter()
1646
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
1647
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
1648
                .collect::<Result<_, ObjectError>>()?;
1649
            if !wanted.is_empty() {
1650
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
1651
                let contents = {
1652
                    let _t = crate::timing::phase("load:   graph blobs read");
1653
                    load(&refs)?
1654
                };
1655
                if contents.len() != refs.len() {
1656
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
1657
                }
1658
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
1659
            }
1660
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
1661
            return Err(ObjectError::Schema(
1662
                "a version 1 payload holds graphs inline".into(),
1663
            ));
1664
        }
1665
        // File graphs are independent; decode and build them in parallel.
1666
        let graphs = parsed
1667
            .par_iter()
1668
            .map(|(node, entry)| {
1669
                let graph = match fetched.get(node) {
1670
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
1671
                    None => FileGraph::from_value(entry)?,
1672
                };
1673
                Ok((*node, graph))
1674
            })
1675
            .collect::<Result<Vec<_>, ObjectError>>()?;
dfb23a3a Andy McCall ↶ 1676
        st.files
1677
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
afaba5f1 Andy McCall ↶ 1678
        Ok(st)
1679
    }
1680
1681
    /// The graph blobs a payload names: empty for version 1.
1682
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
1683
        let v = cbor::decode(bytes)?;
1684
        let m = o::map(&v, "checkpoint payload")?;
1685
        let mut out = Vec::new();
1686
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1687
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
1688
                out.push(o::oref(entry, "graph blob")?);
1689
            }
1690
        }
1691
        Ok(out)
e8d38e47 Andy McCall ↶ 1692
    }
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.
1698
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
1699
        let v = cbor::decode(bytes)?;
1700
        let m = o::map(&v, "checkpoint payload")?;
1701
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
1702
        if version != CHECKPOINT_INDEX_VERSION {
1703
            return State::from_checkpoint_payload(bytes);
1704
        }
1705
        let mut st = State::payload_common(m)?;
36e51aa8 Andy McCall ↶ 1706
        let mut deferred = crate::fasthash::FastMap::default();
e8d38e47 Andy McCall ↶ 1707
        for f in o::array(o::field(m, 3, "files")?, "files")? {
1708
            let e = o::array(f, "file")?;
1709
            if e.len() != 2 {
1710
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
1711
            }
1712
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1713
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
1714
            let base = match &e[1] {
1715
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
1716
                other => DeferredBase::Inline(other.clone()),
1717
            };
1718
            deferred.insert(
1719
                node,
3f1b8fe2 Andy McCall ↶ 1720
                Arc::new(Deferred::from_body(DeferredBody {
e8d38e47 Andy McCall ↶ 1721
                    base: Some(base),
3f1b8fe2 Andy McCall ↶ 1722
                    ..DeferredBody::default()
1723
                })),
e8d38e47 Andy McCall ↶ 1724
            );
1725
        }
1726
        st.deferred = Some(deferred);
1727
        Ok(st)
afaba5f1 Andy McCall ↶ 1728
    }
1729
1730
    /// Changes, tree and replaces of a payload of either version.
1731
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
252e8cb2 Andy McCall ↶ 1732
        let mut st = State::new();
1733
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
1734
            let e = o::array(c, "change meta")?;
1735
            if e.len() != 8 {
1736
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
1737
            }
1738
            let hash = o::oref(&e[0], "hash")?;
1739
            let meta = ChangeMeta {
75167672 Andy McCall 1740
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
1741
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
1742
                deps: o::array(&e[2], "deps")?
1743
                    .iter()
1744
                    .map(|d| o::oref(d, "dep"))
1745
                    .collect::<Result<Vec<_>, _>>()?,
252e8cb2 Andy McCall ↶ 1746
                message: o::text(&e[3], "message")?.to_owned(),
75167672 Andy McCall 1747
                hlc: Hlc {
1748
                    wall_ms: o::uint(&e[4], "wall")?,
1749
                    logical: o::u32_(&e[5], "logical")?,
1750
                },
252e8cb2 Andy McCall ↶ 1751
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
1752
                author: o::oref(&e[7], "author")?,
1753
            };
f6451fbb Andy McCall ↶ 1754
            st.changes.insert(hash, Arc::new(meta));
252e8cb2 Andy McCall ↶ 1755
        }
1756
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
75167672 Andy McCall 1757
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
1758
            if v.is_null() {
1759
                Ok(None)
1760
            } else {
1761
                o::oref(v, "blob").map(Some)
1762
            }
1763
        };
252e8cb2 Andy McCall ↶ 1764
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
1765
            let e = o::array(r, "replace")?;
1766
            if e.len() != 2 {
75167672 Andy McCall 1767
                return Err(ObjectError::Schema(
1768
                    "replace: expected [node, records]".into(),
1769
                ));
252e8cb2 Andy McCall ↶ 1770
            }
75167672 Andy McCall 1771
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
1772
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
252e8cb2 Andy McCall ↶ 1773
            let mut recs = Vec::new();
1774
            for rec in o::array(&e[1], "records")? {
1775
                let x = o::array(rec, "record")?;
1776
                if x.len() != 3 {
1777
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
1778
                }
1779
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
1780
            }
1781
            st.replaces.insert(node, recs);
1782
        }
1783
        Ok(st)
1784
    }
1785
ff0af1ee unknown 1786
    pub fn validate(&self) -> Result<(), StateError> {
1787
        for (h, c) in &self.changes {
1788
            for d in &c.deps {
1789
                if !self.changes.contains_key(d) {
1790
                    return Err(StateError::MissingDep(*d, *h));
1791
                }
1792
            }
1793
        }
1794
        Ok(())
1795
    }
1796
a4fad5b0 Andy McCall ↶ 1797
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<TextRef>) {
ff0af1ee unknown 1798
        for (i, op) in c.tree_ops.iter().enumerate() {
1799
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
1800
        }
e8d38e47 Andy McCall ↶ 1801
        if let Some(deferred) = self.deferred.as_mut() {
86e1824f Andy McCall ↶ 1802
            // History only: edits of files not built wait, grouped per file,
1803
            // with the texts of inserts read without their lines.
1804
            let mut texts = texts.into_iter();
1805
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
e8d38e47 Andy McCall ↶ 1806
            for e in c.edits {
1807
                match e {
1808
                    Edit::Replace { node, old, new } => {
1809
                        self.replaces.entry(node).or_default().push((h, old, new))
1810
                    }
86e1824f Andy McCall ↶ 1811
                    e => {
1812
                        let slot = per_node.entry(e.node()).or_default();
1813
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
1814
                            slot.1.extend(texts.next());
1815
                        }
1816
                        slot.0.push(e);
1817
                    }
e8d38e47 Andy McCall ↶ 1818
                }
1819
            }
86e1824f Andy McCall ↶ 1820
            for (node, (edits, node_texts)) in per_node {
e8d38e47 Andy McCall ↶ 1821
                match self.files.get_mut(&node) {
86e1824f Andy McCall ↶ 1822
                    Some(g) => {
1823
                        assert!(
1824
                            node_texts.is_empty(),
1825
                            "a change read without its text applied to a built graph"
1826
                        );
1827
                        apply_file_edits(Arc::make_mut(g), h, edits)
1828
                    }
1829
                    None => {
f6451fbb Andy McCall ↶ 1830
                        let d = Arc::make_mut(deferred.entry(node).or_default());
5552e69c Andy McCall ↶ 1831
                        d.add(h, edits, node_texts);
f9575918 Andy McCall ↶ 1832
                        d.key = Default::default();
86e1824f Andy McCall ↶ 1833
                    }
e8d38e47 Andy McCall ↶ 1834
                }
1835
            }
1836
            return;
1837
        }
86e1824f Andy McCall ↶ 1838
        assert!(
1839
            texts.is_empty(),
1840
            "a change read without its text applied to a full state"
1841
        );
ff0af1ee unknown 1842
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
0bdc3f91 Andy McCall ↶ 1843
        for e in c.edits {
ff0af1ee unknown 1844
            match e {
75167672 Andy McCall 1845
                Edit::Insert {
1846
                    node,
1847
                    after,
1848
                    before,
1849
                    lines,
1850
                } => {
0bdc3f91 Andy McCall ↶ 1851
                    let idx = counters.entry(node).or_default();
ff0af1ee unknown 1852
                    let first = *idx;
1853
                    *idx += lines.len() as u32;
dfb23a3a Andy McCall ↶ 1854
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
75167672 Andy McCall 1855
                        h,
1856
                        first,
1857
                        vertex(after.resolve(h)),
1858
                        vertex(before.resolve(h)),
1859
                        lines,
1860
                    );
ff0af1ee unknown 1861
                }
1862
                Edit::Delete { node, atoms } => {
dfb23a3a Andy McCall ↶ 1863
                    let g = Arc::make_mut(self.files.entry(node).or_default());
ff0af1ee unknown 1864
                    for r in atoms {
1865
                        g.delete(h, &r.resolve(h));
1866
                    }
1867
                }
1868
                Edit::Replace { node, old, new } => {
0bdc3f91 Andy McCall ↶ 1869
                    self.replaces.entry(node).or_default().push((h, old, new));
ff0af1ee unknown 1870
                }
1871
            }
1872
        }
1873
    }
1874
1875
    /// Transitive dependencies of `h`, excluding `h` itself.
119bbf50 Andy McCall ↶ 1876
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
aedfe465 Andy McCall ↶ 1877
        if let Some(c) = self.closure.read().unwrap().sets.get(h) {
ff0af1ee unknown 1878
            return c.clone();
1879
        }
1880
        let mut out = HashSet::new();
75167672 Andy McCall 1881
        let mut stack: Vec<ChangeHash> = self
1882
            .changes
1883
            .get(h)
1884
            .map(|c| c.deps.clone())
1885
            .unwrap_or_default();
ff0af1ee unknown 1886
        while let Some(d) = stack.pop() {
1887
            if out.insert(d) {
1888
                if let Some(c) = self.changes.get(&d) {
1889
                    stack.extend(c.deps.iter().copied());
1890
                }
1891
            }
1892
        }
119bbf50 Andy McCall ↶ 1893
        let rc = Arc::new(out);
aedfe465 Andy McCall ↶ 1894
        let mut memo = self.closure.write().unwrap();
d45dab04 Andy McCall ↶ 1895
        if memo.held + rc.len() > CLOSURE_MEMO_HASHES {
1896
            memo.sets.clear();
1897
            memo.held = 0;
1898
        }
1899
        memo.held += rc.len();
1900
        memo.sets.insert(*h, rc.clone());
ff0af1ee unknown 1901
        rc
1902
    }
1903
d45dab04 Andy McCall ↶ 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.
1907
    fn level(&self, h: &ChangeHash) -> u32 {
aedfe465 Andy McCall ↶ 1908
        // Nearly always known: read without excluding the other threads
1909
        // rendering beside this one (oxygen#96).
1910
        if let Some(l) = self.levels.read().unwrap().get(h) {
1911
            return *l;
1912
        }
1913
        let mut levels = self.levels.write().unwrap();
d45dab04 Andy McCall ↶ 1914
        if let Some(l) = levels.get(h) {
1915
            return *l;
1916
        }
1917
        let mut stack: Vec<(ChangeHash, bool)> = vec![(*h, false)];
1918
        while let Some((c, expanded)) = stack.pop() {
1919
            if levels.contains_key(&c) {
1920
                continue;
1921
            }
1922
            let deps: &[ChangeHash] = self
1923
                .changes
1924
                .get(&c)
1925
                .map(|m| m.deps.as_slice())
1926
                .unwrap_or(&[]);
1927
            if expanded {
1928
                let l = deps
1929
                    .iter()
1930
                    .map(|d| levels.get(d).map_or(0, |l| l + 1))
1931
                    .max()
1932
                    .unwrap_or(0);
1933
                levels.insert(c, l);
1934
            } else {
1935
                stack.push((c, true));
1936
                for d in deps {
1937
                    if !levels.contains_key(d) {
1938
                        stack.push((*d, false));
1939
                    }
1940
                }
1941
            }
1942
        }
1943
        levels[h]
1944
    }
1945
ff0af1ee unknown 1946
    /// Changes that no other change depends on directly, sorted.
1947
    pub fn heads(&self) -> Vec<ChangeHash> {
ac03130a Andy McCall ↶ 1948
        let depended: crate::fasthash::FastSet<&ChangeHash> =
75167672 Andy McCall 1949
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
1950
        let mut heads: Vec<ChangeHash> = self
1951
            .changes
1952
            .keys()
1953
            .filter(|h| !depended.contains(h))
1954
            .copied()
1955
            .collect();
ff0af1ee unknown 1956
        heads.sort();
1957
        heads
1958
    }
1959
07eb99be Andy McCall ↶ 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.
ff0af1ee unknown 1965
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
1966
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
ac03130a Andy McCall ↶ 1967
        let mut below: crate::fasthash::FastSet<ChangeHash> = Default::default();
07eb99be Andy McCall ↶ 1968
        let mut stack: Vec<ChangeHash> = set
1969
            .iter()
1970
            .filter_map(|h| self.changes.get(h))
1971
            .flat_map(|c| c.deps.iter().copied())
1972
            .collect();
1973
        while let Some(d) = stack.pop() {
1974
            if below.insert(d) {
1975
                if let Some(c) = self.changes.get(&d) {
1976
                    stack.extend(c.deps.iter().copied());
1977
                }
1978
            }
1979
        }
1980
        set.into_iter().filter(|h| !below.contains(h)).collect()
ff0af1ee unknown 1981
    }
1982
1983
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
e8d38e47 Andy McCall ↶ 1984
        self.graph(node)
75167672 Andy McCall 1985
            .map(|g| g.materialize(self))
1986
            .unwrap_or_default()
ff0af1ee unknown 1987
    }
1988
1989
    /// Live lines of a text node in materialized order.
1990
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
e8d38e47 Andy McCall ↶ 1991
        let Some(g) = self.graph(node) else {
75167672 Andy McCall 1992
            return vec![];
1993
        };
ff0af1ee unknown 1994
        let m = g.materialize(self);
75167672 Andy McCall 1995
        m.live_atoms()
1996
            .into_iter()
1997
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
1998
            .collect()
ff0af1ee unknown 1999
    }
2000
7bd805ff Andy McCall ↶ 2001
    /// The nodes with replace records: opaque files, as their blobs go.
2002
    pub fn opaque_nodes(&self) -> Vec<NodeId> {
2003
        let mut nodes: Vec<NodeId> = self.replaces.keys().copied().collect();
2004
        nodes.sort();
2005
        nodes
2006
    }
2007
ff0af1ee unknown 2008
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
2009
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
62794ecc Andy McCall ↶ 2010
        let mut live: Vec<ObjectRef> = self
2011
            .live_replaces(node)
2012
            .into_iter()
2013
            .map(|(_, n)| n)
75167672 Andy McCall 2014
            .collect();
ff0af1ee unknown 2015
        live.sort();
2016
        live.dedup();
2017
        live
2018
    }
2019
62794ecc Andy McCall ↶ 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.
2028
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
2029
        let Some(rs) = self.replaces.get(node) else {
2030
            return vec![];
2031
        };
7fc36536 Andy McCall ↶ 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).
2035
        let dep =
2036
            |a: &ChangeHash, b: &ChangeHash| a != b && <Self as DepOracle>::depends_on(self, a, b);
62794ecc Andy McCall ↶ 2037
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
2038
            rs.iter()
7fc36536 Andy McCall ↶ 2039
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && dep(s, q))
62794ecc Andy McCall ↶ 2040
        };
2041
        rs.iter()
2042
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
2043
            .filter(|(c, n)| {
2044
                !rs.iter().any(|(s, o, _)| {
7fc36536 Andy McCall ↶ 2045
                    s != c && *o == Some(*n) && (dep(s, c) || (!knows_its_old(s, n) && !dep(c, s)))
62794ecc Andy McCall ↶ 2046
                })
2047
            })
2048
            .collect()
2049
    }
2050
ff0af1ee unknown 2051
    /// Short label for conflict markers: `changeid-prefix "message"`.
2052
    pub fn label(&self, h: &ChangeHash) -> String {
2053
        match self.changes.get(h) {
75167672 Andy McCall 2054
            Some(c) => format!(
2055
                "{} \"{}\"",
2056
                c.change_id.short(8),
2057
                c.message.lines().next().unwrap_or("")
2058
            ),
ff0af1ee unknown 2059
            None => format!("#{}", h.short(12)),
2060
        }
2061
    }
2062
20247a03 Andy McCall ↶ 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.
50a046e4 Andy McCall ↶ 2066
    /// The changes that introduced the live blobs of an opaque node, for a
2067
    /// replace conflict (spec §9.3).
2068
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
2069
        let mut out: Vec<ChangeHash> = Vec::new();
2070
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
2071
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
2072
                out.push(*h);
2073
            }
2074
        }
2075
        out.sort();
2076
        out
2077
    }
2078
20247a03 Andy McCall ↶ 2079
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
2080
        let mut out = ConflictRegions::default();
e8d38e47 Andy McCall ↶ 2081
        let Some(g) = self.graph(node) else {
75167672 Andy McCall 2082
            return out;
2083
        };
20247a03 Andy McCall ↶ 2084
        let m = g.materialize(self);
2085
        let mut contributors = BTreeSet::new();
2086
        for seg in &m.segments {
2087
            match seg {
2088
                crate::graph::Segment::Lines(atoms) => {
2089
                    for a in atoms {
75167672 Andy McCall 2090
                        out.plain
2091
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
20247a03 Andy McCall ↶ 2092
                    }
2093
                }
2094
                crate::graph::Segment::Conflict(sides) => {
2095
                    for side in sides {
2096
                        for a in side {
2097
                            out.region_atoms.push(*a);
2098
                            contributors.insert(a.0);
2099
                        }
2100
                    }
2101
                }
2102
                crate::graph::Segment::Zombie { deleted, inserted } => {
2103
                    for a in deleted {
2104
                        contributors.insert(a.0);
2105
                        contributors.extend(g.deleters(a).copied());
2106
                    }
2107
                    for a in inserted {
2108
                        out.region_atoms.push(*a);
2109
                        contributors.insert(a.0);
2110
                    }
2111
                }
2112
            }
2113
        }
2114
        out.contributors = contributors.into_iter().collect();
2115
        out
2116
    }
2117
ff0af1ee unknown 2118
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
e8d38e47 Andy McCall ↶ 2119
        let Some(g) = self.graph(node) else {
75167672 Andy McCall 2120
            return (Vec::new(), Materialized::default());
2121
        };
ff0af1ee unknown 2122
        let m = g.materialize(self);
2123
        let bytes = g.render(&m, &|h| self.label(h));
2124
        (bytes, m)
2125
    }
2126
e7ddd552 Andy McCall ↶ 2127
    /// Every file rendered, in parallel: files are independent, and
2128
    /// rendering them is most of a snapshot's cost in a large tree.
ff0af1ee unknown 2129
    pub fn materialize(&self) -> Snapshot {
e7ddd552 Andy McCall ↶ 2130
        use rayon::prelude::*;
e8d38e47 Andy McCall ↶ 2131
        self.require_full("materializing a state");
c2e1d090 Andy McCall 2132
        let tree = self.view();
e7ddd552 Andy McCall ↶ 2133
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
2134
        let rendered: Vec<(String, FileState)> = entries
2135
            .par_iter()
2136
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
2137
            .collect();
2138
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
cc7a0056 Andy McCall ↶ 2139
        Snapshot {
2140
            tree,
2141
            files,
2142
            unrendered: BTreeSet::new(),
2143
        }
2144
    }
2145
2146
    /// Like [`State::materialize`], leaving the text files of nodes in
2147
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
2148
    /// file's graph must be loaded. For a caller that already knows those
c2e1d090 Andy McCall 2149
    /// files are unchanged and not conflicted. Its tree is the tree
2150
    /// graph's own view, as a Git import builds against it: same-path
2151
    /// additions are not unified ([`State::view`]), since the import's
2152
    /// merge records Git's tree for them itself.
cc7a0056 Andy McCall ↶ 2153
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
c2e1d090 Andy McCall 2154
        self.materialize_leaving(self.tree.view(), |_, e| skip.contains(&e.node))
d616faf5 Andy McCall ↶ 2155
    }
2156
2157
    /// As [`State::materialize_except`], rendering only the text files at
c2e1d090 Andy McCall 2158
    /// `render` (a few, where the caller knows the rest unchanged), with
2159
    /// the tree as [`State::view`] has it.
d616faf5 Andy McCall ↶ 2160
    pub fn materialize_only(&self, render: &std::collections::HashSet<&str>) -> Snapshot {
c2e1d090 Andy McCall 2161
        self.materialize_leaving(self.view(), |p, _| !render.contains(p))
d616faf5 Andy McCall ↶ 2162
    }
2163
c2e1d090 Andy McCall 2164
    /// As [`State::materialize_only`], rendering only the text files of
10b4fd43 Andy McCall ↶ 2165
    /// the nodes in `render` (a change's edited files), without a set of
2166
    /// every other file to leave out.
2167
    pub fn materialize_nodes(&self, render: &HashSet<NodeId>) -> Snapshot {
c2e1d090 Andy McCall 2168
        self.materialize_leaving(self.view(), |_, e| !render.contains(&e.node))
10b4fd43 Andy McCall ↶ 2169
    }
2170
d616faf5 Andy McCall ↶ 2171
    fn materialize_leaving(
2172
        &self,
c2e1d090 Andy McCall 2173
        tree: TreeView,
d616faf5 Andy McCall ↶ 2174
        leave: impl Fn(&str, &crate::tree::TreeEntry) -> bool + Sync,
2175
    ) -> Snapshot {
cc7a0056 Andy McCall ↶ 2176
        use rayon::prelude::*;
2177
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
2178
        let rendered: Vec<(String, FileState, bool)> = entries
2179
            .par_iter()
2180
            .map(|(path, e)| {
d616faf5 Andy McCall ↶ 2181
                if e.kind == NodeKind::File && !e.mode.opaque && leave(path, e) {
cc7a0056 Andy McCall ↶ 2182
                    let f = FileState {
2183
                        node: e.node,
2184
                        kind: e.kind,
2185
                        mode: e.mode,
2186
                        content: FileContent::Text {
2187
                            bytes: Vec::new(),
2188
                            materialized: Materialized::default(),
2189
                        },
2190
                    };
2191
                    (path.to_string(), f, true)
2192
                } else {
2193
                    (path.to_string(), self.file_state(e), false)
2194
                }
2195
            })
2196
            .collect();
36e51aa8 Andy McCall ↶ 2197
        // In the view's path order, so the maps are built without searching.
2198
        let unrendered: BTreeSet<String> = rendered
2199
            .iter()
2200
            .filter(|(_, _, skipped)| *skipped)
2201
            .map(|(p, _, _)| p.clone())
2202
            .collect();
2203
        let files: BTreeMap<String, FileState> =
2204
            rendered.into_iter().map(|(p, f, _)| (p, f)).collect();
cc7a0056 Andy McCall ↶ 2205
        Snapshot {
2206
            tree,
2207
            files,
2208
            unrendered,
2209
        }
e7ddd552 Andy McCall ↶ 2210
    }
2211
2306a4d2 Andy McCall ↶ 2212
    /// A snapshot of only `paths` (those `view` has), `view` being this
2213
    /// state's tree view: for a caller that works from what changed. The
2214
    /// graphs of those text files must be loaded.
2215
    pub fn materialize_paths<'p>(
2216
        &self,
2217
        view: crate::tree::TreeView,
2218
        paths: impl IntoIterator<Item = &'p str>,
2219
    ) -> Snapshot {
aedfe465 Andy McCall ↶ 2220
        use rayon::prelude::*;
2221
        // On every core: a merge may render thousands (oxygen#96).
2222
        let entries: Vec<(&str, &crate::tree::TreeEntry)> = paths
2223
            .into_iter()
2224
            .filter_map(|p| Some((p, view.entries.get(p)?)))
2225
            .collect();
2226
        let files = entries
2227
            .par_iter()
2228
            .map(|(p, e)| (p.to_string(), self.file_state(e)))
2229
            .collect::<Vec<_>>()
2306a4d2 Andy McCall ↶ 2230
            .into_iter()
2231
            .collect();
2232
        Snapshot {
2233
            tree: view,
2234
            files,
2235
            unrendered: BTreeSet::new(),
2236
        }
2237
    }
2238
c3d2ef61 Andy McCall ↶ 2239
    /// The state of one tree entry: a directory, an opaque file's live
2240
    /// blobs, or a text file rendered from its graph (which must be built).
2241
    pub fn entry_state(&self, e: &crate::tree::TreeEntry) -> FileState {
2242
        self.file_state(e)
2243
    }
2244
e7ddd552 Andy McCall ↶ 2245
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
2246
        {
ff0af1ee unknown 2247
            let content = match e.kind {
2248
                NodeKind::Dir => FileContent::Dir,
75167672 Andy McCall 2249
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
2250
                    blobs: self.live_blobs(&e.node),
2251
                },
2252
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
2253
                    blobs: self.live_blobs(&e.node),
2254
                },
ff0af1ee unknown 2255
                NodeKind::File => {
2256
                    let (bytes, materialized) = self.render_file(&e.node);
75167672 Andy McCall 2257
                    FileContent::Text {
2258
                        bytes,
2259
                        materialized,
2260
                    }
ff0af1ee unknown 2261
                }
2262
            };
e7ddd552 Andy McCall ↶ 2263
            FileState {
2264
                node: e.node,
2265
                kind: e.kind,
2266
                mode: e.mode,
2267
                content,
2268
            }
ff0af1ee unknown 2269
        }
2270
    }
2271
}
2272
2273
impl DepOracle for State {
d45dab04 Andy McCall ↶ 2274
    /// Whether `a` depends on `b`, by a walk down from `a` that stops at
2275
    /// changes no higher than `b`: they cannot have `b` below them. Nothing
2276
    /// of the walk is kept, so asking about many pairs costs no more memory
2277
    /// than one walk (#25); a closure already memoised answers at once.
ff0af1ee unknown 2278
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
d45dab04 Andy McCall ↶ 2279
        if a == b {
2280
            return true;
2281
        }
aedfe465 Andy McCall ↶ 2282
        if let Some(c) = self.closure.read().unwrap().sets.get(a) {
d45dab04 Andy McCall ↶ 2283
            return c.contains(b);
2284
        }
2285
        if !self.changes.contains_key(b) {
2286
            return false;
2287
        }
2288
        let lb = self.level(b);
2289
        if self.level(a) <= lb {
2290
            return false;
2291
        }
aedfe465 Andy McCall ↶ 2292
        let mut seen: crate::fasthash::FastSet<ChangeHash> = Default::default();
4476cdbb Andy McCall ↶ 2293
        // A dependency is looked for as it is found, before the walk goes
2294
        // below it: most questions are about a direct one (spec §8.1 makes
2295
        // a deletion depend on the inserter of the line after it, which is
2296
        // what a render asks about), and a depth-first walk that only
2297
        // looked when it came back up went through thousands of changes
2298
        // first (oxygen#137: 4.4 billion steps rendering the VS Code tree).
d45dab04 Andy McCall ↶ 2299
        let mut stack: Vec<ChangeHash> = self
2300
            .changes
2301
            .get(a)
2302
            .map(|m| m.deps.clone())
2303
            .unwrap_or_default();
4476cdbb Andy McCall ↶ 2304
        if stack.contains(b) {
2305
            return true;
2306
        }
d45dab04 Andy McCall ↶ 2307
        while let Some(c) = stack.pop() {
2308
            if c == *b {
2309
                return true;
2310
            }
2311
            if !seen.insert(c) || self.level(&c) <= lb {
2312
                continue;
2313
            }
2314
            if let Some(m) = self.changes.get(&c) {
4476cdbb Andy McCall ↶ 2315
                if m.deps.contains(b) {
2316
                    return true;
2317
                }
d45dab04 Andy McCall ↶ 2318
                stack.extend(m.deps.iter().copied());
2319
            }
2320
        }
2321
        false
ff0af1ee unknown 2322
    }
2323
}
2324
2325
#[cfg(test)]
2326
mod tests {
2327
    use super::*;
2cd6bf89 Andy McCall ↶ 2328
2329
    /// A changes block of thousands comes back whole and in order, and a
2330
    /// truncated one is refused (oxygen#94).
2331
    #[test]
2332
    fn a_long_changes_block_decodes_in_order() {
2333
        use crate::flat::Writer;
2334
        let metas: Vec<(ChangeHash, ChangeMeta)> = (0..5000u32)
2335
            .map(|i| {
2336
                let mut h = [0u8; 32];
2337
                h[..4].copy_from_slice(&i.to_le_bytes());
2338
                let meta = ChangeMeta {
2339
                    change_id: crate::ids::ChangeId([i as u8; 16]),
2340
                    deps: (0..i % 3).map(|d| ObjectRef([d as u8; 32])).collect(),
2341
                    author: ObjectRef([7; 32]),
2342
                    hlc: Hlc {
2343
                        wall_ms: 1_000_000 - i as u64,
2344
                        logical: i,
2345
                    },
2346
                    message: "x".repeat((i % 50) as usize),
2347
                    kind: ChangeKind::Normal,
2348
                };
2349
                (ObjectRef(h), meta)
2350
            })
2351
            .collect();
2352
        let mut w = Writer::default();
2353
        w.fixed(State::INDEX_MAGIC);
2354
        w.count(metas.len());
2355
        for (h, m) in &metas {
2356
            w.object(h);
2357
            m.write_flat(&mut w);
2358
        }
2359
        assert_eq!(State::read_index_changes_listed(&w.0).unwrap(), metas);
2360
        let mut cut = w.0.clone();
2361
        cut.pop();
2362
        assert!(
2363
            State::read_index_changes_listed(&cut).is_err(),
2364
            "a truncated block is refused"
2365
        );
2366
    }
ff0af1ee unknown 2367
    use crate::ids::ChangeId;
2368
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
2369
2370
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
2371
        let mut c = Change {
6f8aeb99 Andy McCall ↶ 2372
            version: crate::objects::CHANGE_VERSION,
ff0af1ee unknown 2373
            change_id: ChangeId::random(),
2374
            deps,
2375
            author: ObjectRef::ZERO,
75167672 Andy McCall 2376
            hlc: Hlc {
2377
                wall_ms: 1,
2378
                logical: 0,
2379
            },
ff0af1ee unknown 2380
            message: "m".into(),
2381
            tree_ops,
2382
            edits,
2383
            kind: ChangeKind::Normal,
2384
        };
2385
        c.normalize();
2386
        c
2387
    }
2388
2389
    #[test]
2390
    fn build_edit_and_materialize() {
2391
        let mut st = State::new();
2392
        let f = NodeId::random();
2393
        let c1 = change(
2394
            vec![],
75167672 Andy McCall 2395
            vec![TreeOp::AddNode {
2396
                node: f,
2397
                kind: NodeKind::File,
2398
                mode: Mode::TEXT,
2399
                parent: NodeId::ROOT,
2400
                name: "a.txt".into(),
2401
            }],
2402
            vec![Edit::Insert {
2403
                node: f,
2404
                after: AtomRef::Start,
2405
                before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2406
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()].into(),
75167672 Andy McCall 2407
            }],
ff0af1ee unknown 2408
        );
2409
        let h1 = st.add(c1).unwrap();
2410
        // Depends on h1: append a line and delete "one".
2411
        let c2 = change(
2412
            vec![h1],
2413
            vec![],
2414
            vec![
75167672 Andy McCall 2415
                Edit::Delete {
2416
                    node: f,
2417
                    atoms: vec![AtomRange {
2418
                        change: h1,
2419
                        from: 0,
2420
                        to: 1,
2421
                    }],
2422
                },
2423
                Edit::Insert {
2424
                    node: f,
2425
                    after: AtomRef::Atom {
2426
                        change: h1,
2427
                        index: 1,
2428
                    },
2429
                    before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2430
                    lines: vec![b"three\n".to_vec()].into(),
75167672 Andy McCall 2431
                },
ff0af1ee unknown 2432
            ],
2433
        );
2434
        let h2 = st.add(c2).unwrap();
2435
        assert_eq!(st.heads(), vec![h2]);
2436
        assert!(st.depends_on(&h2, &h1));
2437
        assert!(!st.depends_on(&h1, &h2));
2438
        let snap = st.materialize();
2439
        assert!(!snap.is_conflicted());
2440
        let a = &snap.files["a.txt"];
2441
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
2442
        assert_eq!(st.live_lines(&f).len(), 2);
2443
    }
2444
2445
    #[test]
2446
    fn missing_dependency_is_rejected() {
2447
        let mut st = State::new();
2448
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
2449
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
2450
    }
2451
2452
    #[test]
2453
    fn self_references_and_multi_insert_indexing() {
2454
        let mut st = State::new();
2455
        let f = NodeId::random();
75167672 Andy McCall 2456
        let me = OpRef {
2457
            change: ObjectRef::ZERO,
2458
            index: 0,
2459
        };
ff0af1ee unknown 2460
        let c1 = change(
2461
            vec![],
2462
            vec![
75167672 Andy McCall 2463
                TreeOp::AddNode {
2464
                    node: f,
2465
                    kind: NodeKind::File,
2466
                    mode: Mode::TEXT,
2467
                    parent: NodeId::ROOT,
2468
                    name: "x".into(),
2469
                },
2470
                TreeOp::SetMode {
2471
                    node: f,
2472
                    old: me,
2473
                    mode: Mode {
2474
                        exec: true,
2475
                        opaque: false,
2476
                    },
2477
                },
ff0af1ee unknown 2478
            ],
2479
            vec![
75167672 Andy McCall 2480
                Edit::Insert {
2481
                    node: f,
2482
                    after: AtomRef::Start,
2483
                    before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2484
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()].into(),
75167672 Andy McCall 2485
                },
ff0af1ee unknown 2486
                // Insert between the two lines just inserted, using self references.
2487
                Edit::Insert {
2488
                    node: f,
75167672 Andy McCall 2489
                    after: AtomRef::Atom {
2490
                        change: ObjectRef::ZERO,
2491
                        index: 0,
2492
                    },
2493
                    before: AtomRef::Atom {
2494
                        change: ObjectRef::ZERO,
2495
                        index: 1,
2496
                    },
01a47cd7 Andy McCall ↶ 2497
                    lines: vec![b"b\n".to_vec()].into(),
ff0af1ee unknown 2498
                },
2499
            ],
2500
        );
2501
        st.add(c1).unwrap();
2502
        let snap = st.materialize();
2503
        let x = &snap.files["x"];
75167672 Andy McCall 2504
        assert_eq!(
2505
            x.mode,
2506
            Mode {
2507
                exec: true,
2508
                opaque: false
2509
            }
2510
        );
ff0af1ee unknown 2511
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
2512
    }
2513
2514
    #[test]
2515
    fn opaque_replace_and_conflict() {
2516
        let mut st = State::new();
2517
        let f = NodeId::random();
2518
        let b1 = ObjectRef([1; 32]);
2519
        let b2 = ObjectRef([2; 32]);
2520
        let b3 = ObjectRef([3; 32]);
75167672 Andy McCall 2521
        let h1 = st
2522
            .add(change(
2523
                vec![],
2524
                vec![TreeOp::AddNode {
2525
                    node: f,
2526
                    kind: NodeKind::File,
2527
                    mode: Mode::OPAQUE,
2528
                    parent: NodeId::ROOT,
2529
                    name: "img".into(),
2530
                }],
2531
                vec![Edit::Replace {
2532
                    node: f,
2533
                    old: None,
2534
                    new: Some(b1),
2535
                }],
2536
            ))
2537
            .unwrap();
2538
        assert_eq!(st.live_blobs(&f), vec![b1]);
2539
        st.add(change(
2540
            vec![h1],
2541
            vec![],
2542
            vec![Edit::Replace {
2543
                node: f,
2544
                old: Some(b1),
2545
                new: Some(b2),
2546
            }],
2547
        ))
2548
        .unwrap();
2549
        st.add(change(
2550
            vec![h1],
ff0af1ee unknown 2551
            vec![],
75167672 Andy McCall 2552
            vec![Edit::Replace {
2553
                node: f,
2554
                old: Some(b1),
2555
                new: Some(b3),
2556
            }],
ff0af1ee unknown 2557
        ))
2558
        .unwrap();
2559
        let snap = st.materialize();
2560
        assert!(snap.is_conflicted());
75167672 Andy McCall 2561
        assert!(
2562
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
2563
        );
ff0af1ee unknown 2564
    }
2565
2566
    #[test]
252e8cb2 Andy McCall ↶ 2567
    fn checkpoint_payload_round_trip_and_replay() {
2568
        let mut st = State::new();
2569
        let f = NodeId::random();
75167672 Andy McCall 2570
        let h1 = st
2571
            .add(change(
2572
                vec![],
2573
                vec![TreeOp::AddNode {
2574
                    node: f,
2575
                    kind: NodeKind::File,
2576
                    mode: Mode::TEXT,
2577
                    parent: NodeId::ROOT,
2578
                    name: "a".into(),
2579
                }],
2580
                vec![Edit::Insert {
2581
                    node: f,
2582
                    after: AtomRef::Start,
2583
                    before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2584
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()].into(),
75167672 Andy McCall 2585
                }],
2586
            ))
2587
            .unwrap();
2588
        let h2 = st
2589
            .add(change(
2590
                vec![h1],
2591
                vec![],
2592
                vec![Edit::Delete {
2593
                    node: f,
2594
                    atoms: vec![AtomRange {
2595
                        change: h1,
2596
                        from: 0,
2597
                        to: 1,
2598
                    }],
2599
                }],
2600
            ))
2601
            .unwrap();
252e8cb2 Andy McCall ↶ 2602
        let payload = st.checkpoint_payload();
2603
        let back = State::from_checkpoint_payload(&payload).unwrap();
2604
        assert_eq!(back.len(), 2);
2605
        assert_eq!(back.heads(), vec![h2]);
2606
        assert_eq!(back.get(&h1).unwrap().message, "m");
2607
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
2608
        // Replaying a further change onto the restored state equals a full build.
75167672 Andy McCall 2609
        let c3 = change(
2610
            vec![h2],
2611
            vec![],
2612
            vec![Edit::Insert {
2613
                node: f,
2614
                after: AtomRef::Atom {
2615
                    change: h1,
2616
                    index: 1,
2617
                },
2618
                before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2619
                lines: vec![b"3\n".to_vec()].into(),
75167672 Andy McCall 2620
            }],
2621
        );
252e8cb2 Andy McCall ↶ 2622
        let mut full = st.clone();
2623
        full.add(c3.clone()).unwrap();
2624
        let mut restored = back;
2625
        restored.add(c3).unwrap();
2626
        let (a, b) = (full.materialize(), restored.materialize());
75167672 Andy McCall 2627
        assert_eq!(
2628
            a.files.keys().collect::<Vec<_>>(),
2629
            b.files.keys().collect::<Vec<_>>()
2630
        );
252e8cb2 Andy McCall ↶ 2631
        assert_eq!(a.files["a"].content, b.files["a"].content);
75167672 Andy McCall 2632
        assert!(
2633
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
2634
        );
252e8cb2 Andy McCall ↶ 2635
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
e8d38e47 Andy McCall ↶ 2636
    }
2637
2638
    /// History-only states (O10f): the same state as a full load once its
2639
    /// graphs are built, by replay and from a version 2 checkpoint with
2640
    /// later changes; unloaded graphs are never read as empty.
cc7a0056 Andy McCall ↶ 2641
    #[test]
2642
    fn graph_keys_change_exactly_when_a_graph_does() {
2643
        let (f, g) = (NodeId::random(), NodeId::random());
2644
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2645
            node,
2646
            kind: NodeKind::File,
2647
            mode: Mode::TEXT,
2648
            parent: NodeId::ROOT,
2649
            name: name.into(),
2650
        };
2651
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
2652
            node,
2653
            after: AtomRef::Start,
2654
            before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2655
            lines: vec![line.to_vec()].into(),
cc7a0056 Andy McCall ↶ 2656
        };
2657
        let c1 = change(
2658
            vec![],
2659
            vec![add(f, "f"), add(g, "g")],
2660
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
2661
        );
2662
        let h1 = c1.hash();
2663
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
2664
        let h2 = c2.hash();
2665
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
2666
        let load = |cs: &[&Change]| {
2667
            let mut st = State::new_history_only();
2668
            for c in cs {
2669
                st.add((*c).clone()).unwrap();
2670
            }
2671
            st
2672
        };
2673
        let s1 = load(&[&c1]);
2674
        let s2 = load(&[&c1, &c2]);
2675
        let s3 = load(&[&c1, &c2, &c3]);
2676
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
2677
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
2678
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
2679
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
2680
        assert_ne!(key(&s2, &f), key(&s3, &f));
2681
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
2682
        let mut built = load(&[&c1]);
a4fad5b0 Andy McCall ↶ 2683
        built
2684
            .load_graphs(&[f], |_| unreachable!(), |_| unreachable!())
2685
            .unwrap();
cc7a0056 Andy McCall ↶ 2686
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
2687
        let mut full = State::new();
2688
        full.add(c1.clone()).unwrap();
2689
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
2690
2691
        // Through a version 2 checkpoint of c1, keys name its graph blobs
2692
        // or inline values: stable across loads, changed by later edits.
2693
        let graphs = full.checkpoint_file_graphs();
2694
        let index = full.checkpoint_index(&graphs, |enc| {
2695
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
2696
        });
2697
        let cp = |extra: &[&Change]| {
2698
            let mut st = State::from_checkpoint_history(&index).unwrap();
2699
            for c in extra {
2700
                st.add((*c).clone()).unwrap();
2701
            }
2702
            st
2703
        };
2704
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
2705
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
2706
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
2707
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
2708
2709
        // Partial rendering: skipped files are listed and empty, the others
2710
        // render as in a full state.
2711
        let mut part = load(&[&c1, &c2]);
a4fad5b0 Andy McCall ↶ 2712
        part.load_graphs(&[g], |_| unreachable!(), |_| unreachable!())
2713
            .unwrap();
cc7a0056 Andy McCall ↶ 2714
        let snap = part.materialize_except(&[f].into_iter().collect());
2715
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
2716
        let mut whole = State::new();
2717
        whole.add(c1.clone()).unwrap();
2718
        whole.add(c2.clone()).unwrap();
2719
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
2720
        assert!(
2721
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
2722
        );
2723
    }
2724
e8d38e47 Andy McCall ↶ 2725
    #[test]
2726
    fn history_only_states_build_the_same_graphs_on_demand() {
2727
        let small = NodeId::random();
2728
        let big = NodeId::random();
2729
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2730
            node,
2731
            kind: NodeKind::File,
2732
            mode: Mode::TEXT,
2733
            parent: NodeId::ROOT,
2734
            name: name.into(),
2735
        };
01a47cd7 Andy McCall ↶ 2736
        let lines: crate::lines::Lines = (0..300)
e8d38e47 Andy McCall ↶ 2737
            .map(|i| format!("line {i}\n").into_bytes())
2738
            .collect();
2739
        let c1 = change(
2740
            vec![],
2741
            vec![add(small, "small"), add(big, "big")],
2742
            vec![
2743
                Edit::Insert {
2744
                    node: small,
2745
                    after: AtomRef::Start,
2746
                    before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2747
                    lines: vec![b"x\n".to_vec()].into(),
e8d38e47 Andy McCall ↶ 2748
                },
2749
                Edit::Insert {
2750
                    node: big,
2751
                    after: AtomRef::Start,
2752
                    before: AtomRef::End,
2753
                    lines,
2754
                },
2755
            ],
2756
        );
2757
        let h1 = c1.hash();
2758
        let c2 = change(
2759
            vec![h1],
2760
            vec![],
2761
            vec![
2762
                Edit::Delete {
2763
                    node: big,
2764
                    atoms: vec![AtomRange {
2765
                        change: h1,
2766
                        from: 2,
2767
                        to: 9,
2768
                    }],
2769
                },
2770
                Edit::Insert {
2771
                    node: big,
2772
                    after: AtomRef::Atom {
2773
                        change: h1,
2774
                        index: 20,
2775
                    },
2776
                    before: AtomRef::Atom {
2777
                        change: h1,
2778
                        index: 21,
2779
                    },
01a47cd7 Andy McCall ↶ 2780
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()].into(),
e8d38e47 Andy McCall ↶ 2781
                },
2782
                Edit::Insert {
2783
                    node: small,
2784
                    after: AtomRef::Atom {
2785
                        change: h1,
2786
                        index: 0,
2787
                    },
2788
                    before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2789
                    lines: vec![b"y\n".to_vec()].into(),
e8d38e47 Andy McCall ↶ 2790
                },
2791
            ],
2792
        );
2793
        let h2 = c2.hash();
2794
        let c3 = change(
2795
            vec![h2],
2796
            vec![],
2797
            vec![Edit::Delete {
2798
                node: small,
2799
                atoms: vec![AtomRange {
2800
                    change: h1,
2801
                    from: 0,
2802
                    to: 1,
2803
                }],
2804
            }],
2805
        );
2806
2807
        let mut full = State::new();
2808
        for c in [&c1, &c2, &c3] {
2809
            full.add(c.clone()).unwrap();
2810
        }
2811
        // By replay: nothing built until asked, then exactly the full graphs.
2812
        let mut hist = State::new_history_only();
2813
        for c in [&c1, &c2, &c3] {
2814
            hist.add(c.clone()).unwrap();
2815
        }
2816
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
2817
        assert_eq!(hist.len(), 3);
a4fad5b0 Andy McCall ↶ 2818
        hist.load_graphs(
2819
            &[big],
2820
            |_| unreachable!("no checkpoint"),
2821
            |_| unreachable!(),
2822
        )
2823
        .unwrap();
e8d38e47 Andy McCall ↶ 2824
        assert_eq!(
2825
            hist.render_file(&big).0,
2826
            full.render_file(&big).0,
2827
            "one file on its own"
2828
        );
2829
        assert!(!hist.is_full());
a4fad5b0 Andy McCall ↶ 2830
        hist.load_graphs(&[small, big], |_| unreachable!(), |_| unreachable!())
2831
            .unwrap();
e8d38e47 Andy McCall ↶ 2832
        assert!(hist.is_full());
2833
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
2834
2835
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
2836
        let mut base = State::new();
2837
        base.add(c1.clone()).unwrap();
2838
        base.add(c2.clone()).unwrap();
2839
        let graphs = base.checkpoint_file_graphs();
2840
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
2841
        let index = base.checkpoint_index(&graphs, |enc| {
2842
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
2843
            blobs.insert(r, enc.to_vec());
2844
            r
2845
        });
2846
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
2847
        from_cp.add(c3.clone()).unwrap();
2848
        assert!(!from_cp.is_full());
2849
        let mut fetched = 0;
2850
        from_cp
a4fad5b0 Andy McCall ↶ 2851
            .load_graphs(
2852
                &[small, big],
2853
                |refs| {
2854
                    fetched += refs.len();
2855
                    refs.iter()
2856
                        .map(|r| {
2857
                            blobs
2858
                                .get(r)
2859
                                .cloned()
2860
                                .ok_or_else(|| ObjectError::Schema("missing".into()))
2861
                        })
2862
                        .collect()
2863
                },
2864
                |_| unreachable!(),
2865
            )
e8d38e47 Andy McCall ↶ 2866
            .unwrap();
2867
        assert_eq!(
2868
            fetched, 1,
2869
            "the large graph's blob, in one batch; the small one was inline"
2870
        );
2871
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
2872
    }
2873
2874
    #[test]
2875
    #[should_panic(expected = "was not loaded")]
2876
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
2877
        let f = NodeId::random();
2878
        let mut st = State::new_history_only();
2879
        st.add(change(
2880
            vec![],
2881
            vec![TreeOp::AddNode {
2882
                node: f,
2883
                kind: NodeKind::File,
2884
                mode: Mode::TEXT,
2885
                parent: NodeId::ROOT,
2886
                name: "a".into(),
2887
            }],
2888
            vec![Edit::Insert {
2889
                node: f,
2890
                after: AtomRef::Start,
2891
                before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2892
                lines: vec![b"a\n".to_vec()].into(),
e8d38e47 Andy McCall ↶ 2893
            }],
2894
        ))
2895
        .unwrap();
2896
        st.render_file(&f);
2897
    }
2898
2899
    #[test]
2900
    #[should_panic(expected = "needs every file graph")]
2901
    fn materializing_a_history_only_state_is_refused() {
2902
        let f = NodeId::random();
2903
        let mut st = State::new_history_only();
2904
        st.add(change(
2905
            vec![],
2906
            vec![TreeOp::AddNode {
2907
                node: f,
2908
                kind: NodeKind::File,
2909
                mode: Mode::TEXT,
2910
                parent: NodeId::ROOT,
2911
                name: "a".into(),
2912
            }],
2913
            vec![Edit::Insert {
2914
                node: f,
2915
                after: AtomRef::Start,
2916
                before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2917
                lines: vec![b"a\n".to_vec()].into(),
e8d38e47 Andy McCall ↶ 2918
            }],
2919
        ))
2920
        .unwrap();
2921
        st.materialize();
afaba5f1 Andy McCall ↶ 2922
    }
2923
2924
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
2925
    /// blob; the state read back is the same as from version 1.
2926
    #[test]
2927
    fn checkpoint_index_round_trip_matches_version_1() {
2928
        let mut st = State::new();
2929
        let small = NodeId::random();
2930
        let big = NodeId::random();
2931
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
2932
            node,
2933
            kind: NodeKind::File,
2934
            mode: Mode::TEXT,
2935
            parent: NodeId::ROOT,
2936
            name: name.into(),
2937
        };
01a47cd7 Andy McCall ↶ 2938
        let big_lines: crate::lines::Lines = (0..400)
afaba5f1 Andy McCall ↶ 2939
            .map(|i| format!("line {i} of a long file\n").into_bytes())
2940
            .collect();
2941
        let h1 = st
2942
            .add(change(
2943
                vec![],
2944
                vec![add(small, "small"), add(big, "big")],
2945
                vec![
2946
                    Edit::Insert {
2947
                        node: small,
2948
                        after: AtomRef::Start,
2949
                        before: AtomRef::End,
01a47cd7 Andy McCall ↶ 2950
                        lines: vec![b"x\n".to_vec()].into(),
afaba5f1 Andy McCall ↶ 2951
                    },
2952
                    Edit::Insert {
2953
                        node: big,
2954
                        after: AtomRef::Start,
2955
                        before: AtomRef::End,
2956
                        lines: big_lines,
2957
                    },
2958
                ],
2959
            ))
2960
            .unwrap();
2961
        st.add(change(
2962
            vec![h1],
2963
            vec![],
2964
            vec![Edit::Delete {
2965
                node: big,
2966
                atoms: vec![AtomRange {
2967
                    change: h1,
2968
                    from: 3,
2969
                    to: 7,
2970
                }],
2971
            }],
2972
        ))
2973
        .unwrap();
2974
2975
        let graphs = st.checkpoint_file_graphs();
2976
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
2977
        let index = st.checkpoint_index(&graphs, |enc| {
2978
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
2979
            blobs.insert(r, enc.to_vec());
2980
            r
2981
        });
2982
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
2983
        assert_eq!(
2984
            State::checkpoint_graph_refs(&index).unwrap(),
2985
            blobs.keys().copied().collect::<Vec<_>>()
2986
        );
2987
        assert!(
2988
            State::checkpoint_graph_refs(&st.checkpoint_payload())
2989
                .unwrap()
2990
                .is_empty(),
2991
            "version 1 names none"
2992
        );
2993
        assert!(index.len() < st.checkpoint_payload().len());
2994
2995
        let back = State::from_checkpoint(&index, |refs| {
2996
            refs.iter()
2997
                .map(|r| {
2998
                    blobs
2999
                        .get(r)
3000
                        .cloned()
3001
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
3002
                })
3003
                .collect()
3004
        })
3005
        .unwrap();
3006
        assert_eq!(
3007
            back.checkpoint_payload(),
3008
            st.checkpoint_payload(),
3009
            "the same state as version 1"
3010
        );
3011
        assert_eq!(
3012
            back.materialize().files["big"].content,
3013
            st.materialize().files["big"].content
3014
        );
3015
        // Deterministic: the same state gives the same index.
3016
        assert_eq!(
3017
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
3018
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
3019
            }),
3020
            index
3021
        );
3022
        // A missing graph blob is an error, not an empty file.
3023
        assert!(
3024
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
3025
        );
3026
        assert!(
3027
            State::from_checkpoint_payload(&index).is_err(),
3028
            "version 2 needs its blobs"
3029
        );
3030
        // Version 1 payloads still read, and unknown versions do not.
3031
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
3032
        let mut v3 = cbor::decode(&index).unwrap();
3033
        if let Value::Map(m) = &mut v3 {
3034
            m.insert(0, Value::Uint(3));
3035
        }
3036
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
252e8cb2 Andy McCall ↶ 3037
    }
3038
3039
    #[test]
ff0af1ee unknown 3040
    fn maximal_elements() {
3041
        let mut st = State::new();
3042
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
3043
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
3044
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
3045
        let mut m = st.maximal(&[h1, h2, h3]);
3046
        m.sort();
3047
        let mut want = vec![h2, h3];
3048
        want.sort();
3049
        assert_eq!(m, want);
3050
        assert_eq!(st.heads(), want);
d45dab04 Andy McCall ↶ 3051
    }
3052
3053
    /// The bounded walk of `depends_on` agrees with the closure on random
3054
    /// graphs, and the memo stays within its bound.
3055
    #[test]
3056
    fn depends_on_matches_the_closure() {
3057
        use rand::{Rng, SeedableRng};
3058
        let mut rng = rand::rngs::StdRng::seed_from_u64(11);
3059
        for _ in 0..10 {
3060
            let mut st = State::new();
3061
            let mut all: Vec<ChangeHash> = Vec::new();
3062
            for _ in 0..80 {
3063
                let deps: Vec<ChangeHash> =
3064
                    all.iter().copied().filter(|_| rng.gen_bool(0.06)).collect();
3065
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
3066
            }
3067
            let unknown = ObjectRef([0xee; 32]);
3068
            for a in &all {
3069
                let want = st.closure(a).clone();
aedfe465 Andy McCall ↶ 3070
                st.closure.write().unwrap().sets.clear();
3071
                st.closure.write().unwrap().held = 0;
d45dab04 Andy McCall ↶ 3072
                for b in all.iter().chain([&unknown]) {
3073
                    assert_eq!(
3074
                        st.depends_on(a, b),
3075
                        a == b || want.contains(b),
3076
                        "{a:?} on {b:?}"
3077
                    );
3078
                }
3079
            }
aedfe465 Andy McCall ↶ 3080
            assert!(st.closure.write().unwrap().held <= CLOSURE_MEMO_HASHES);
d45dab04 Andy McCall ↶ 3081
        }
ff0af1ee unknown 3082
    }
07eb99be Andy McCall ↶ 3083
3084
    /// The one-walk `maximal` agrees with the definition (not in the
3085
    /// closure of another element) on random graphs, with repeated and
3086
    /// unknown hashes among the input.
3087
    #[test]
3088
    fn maximal_matches_its_definition() {
3089
        use rand::{Rng, SeedableRng};
3090
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
3091
        for _ in 0..20 {
3092
            let mut st = State::new();
3093
            let mut all: Vec<ChangeHash> = Vec::new();
3094
            for _ in 0..60 {
3095
                let deps: Vec<ChangeHash> =
3096
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
3097
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
3098
            }
3099
            let mut pick: Vec<ChangeHash> =
3100
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
3101
            pick.extend(pick.clone().into_iter().take(3));
3102
            pick.push(ObjectRef([0xee; 32]));
3103
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
3104
            let want: Vec<ChangeHash> = set
3105
                .iter()
3106
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
3107
                .copied()
3108
                .collect();
3109
            assert_eq!(st.maximal(&pick), want);
3110
            assert_eq!(st.maximal(&all), st.heads());
3111
        }
3112
    }
ff0af1ee unknown 3113
}