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