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