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