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