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