OXYGENHUB
# 598009a75f6c oxygen / crates / oxy-core / src / state.rs
67.5 KiB · Rust · last changed Encode a large change once, and store it on every core 1 month ago source blame history raw
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
4
use crate::cbor::{self, Value};
5
use crate::graph::{AtomKey, DepOracle, FileGraph, Materialized, Vertex};
6
use crate::hash::KeyId;
7
use crate::hash::{ChangeHash, ObjectRef};
8
use crate::ids::NodeId;
9
use crate::objects::{
10
    self as o, AtomRef, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, ObjectError, TreeOp,
11
};
12
use crate::tree::{TreeGraph, TreeView};
13
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
14
use std::sync::{Arc, Mutex};
15
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
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
28
/// One `Replace` edit: `(change, old blob, new blob)`.
29
type ReplaceRecord = (ChangeHash, Option<ObjectRef>, Option<ObjectRef>);
30
31
/// What a state remembers about a change: everything but its operations,
32
/// which live in the graphs once applied (and in the store).
33
#[derive(Clone, Debug, PartialEq, Eq)]
34
pub struct ChangeMeta {
35
    pub change_id: crate::ids::ChangeId,
36
    pub deps: Vec<ChangeHash>,
37
    pub author: KeyId,
38
    pub hlc: Hlc,
39
    pub message: String,
40
    pub kind: ChangeKind,
41
}
42
43
impl ChangeMeta {
44
    pub fn of(c: &Change) -> ChangeMeta {
45
        ChangeMeta {
46
            change_id: c.change_id,
47
            deps: c.deps.clone(),
48
            author: c.author,
49
            hlc: c.hlc,
50
            message: c.message.clone(),
51
            kind: c.kind,
52
        }
53
    }
54
}
55
56
#[derive(Default)]
57
pub struct State {
58
    changes: HashMap<ChangeHash, ChangeMeta>,
59
    tree: TreeGraph,
60
    /// Shared between clones: a clone copies a graph only when an edit
61
    /// changes it (`Arc::make_mut`), so keeping several states that differ
62
    /// by a few changes costs little more than one.
63
    files: HashMap<NodeId, Arc<FileGraph>>,
64
    replaces: HashMap<NodeId, Vec<ReplaceRecord>>,
65
    /// Memoised transitive dependencies. A mutex, not a `RefCell`, so a
66
    /// loaded state can be shared across threads by a host that caches it.
67
    closure: Mutex<HashMap<ChangeHash, Arc<HashSet<ChangeHash>>>>,
68
    /// `None` for a full state. For a history-only state (loaded for its
69
    /// changes and tree), the file graphs not built yet, by node: `files`
70
    /// holds only those loaded with [`State::load_graphs`].
71
    deferred: Option<HashMap<NodeId, Deferred>>,
72
}
73
74
/// A stored insert's text blob and line count.
75
type TextRef = (ObjectRef, u32);
76
77
/// A file graph a history-only state has not built: its base from a
78
/// version 2 checkpoint, if any, and the edits of later changes in the
79
/// order they were applied (spec §11). Building it later gives the same
80
/// graph, since graph construction does not depend on order (§8).
81
#[derive(Clone, Default)]
82
struct Deferred {
83
    base: Option<DeferredBase>,
84
    edits: Vec<(ChangeHash, Vec<Edit>)>,
85
    /// The text blob and line count of each insert in `edits` left without
86
    /// its lines, in order: read when the graph is built.
87
    texts: Vec<(ObjectRef, u32)>,
88
}
89
90
#[derive(Clone)]
91
enum DeferredBase {
92
    Inline(Value),
93
    Blob(ObjectRef),
94
}
95
96
impl Clone for State {
97
    fn clone(&self) -> State {
98
        State {
99
            changes: self.changes.clone(),
100
            tree: self.tree.clone(),
101
            files: self.files.clone(),
102
            replaces: self.replaces.clone(),
103
            closure: Mutex::new(self.closure.lock().unwrap().clone()),
104
            deferred: self.deferred.clone(),
105
        }
106
    }
107
}
108
109
#[derive(Clone, Debug, PartialEq, Eq)]
110
pub enum FileContent {
111
    Text {
112
        bytes: Vec<u8>,
113
        materialized: Materialized,
114
    },
115
    /// Live blobs; more than one is a replace conflict (spec §9.3).
116
    Opaque {
117
        blobs: Vec<ObjectRef>,
118
    },
119
    Dir,
120
}
121
122
#[derive(Clone, Debug, PartialEq, Eq)]
123
pub struct FileState {
124
    pub node: NodeId,
125
    pub kind: NodeKind,
126
    pub mode: Mode,
127
    pub content: FileContent,
128
}
129
130
impl FileState {
131
    pub fn is_conflicted(&self) -> bool {
132
        match &self.content {
133
            FileContent::Text { materialized, .. } => materialized.is_conflicted(),
134
            FileContent::Opaque { blobs } => blobs.len() > 1,
135
            FileContent::Dir => false,
136
        }
137
    }
138
}
139
140
/// See `State::conflict_regions`.
141
#[derive(Clone, Debug, Default, PartialEq, Eq)]
142
pub struct ConflictRegions {
143
    pub plain: Vec<(AtomKey, Vec<u8>)>,
144
    pub region_atoms: Vec<AtomKey>,
145
    pub contributors: Vec<ChangeHash>,
146
}
147
148
/// The whole tree of a state, materialized.
149
#[derive(Clone, Debug, Default)]
150
pub struct Snapshot {
151
    pub tree: TreeView,
152
    pub files: BTreeMap<String, FileState>,
153
    /// Text files left unrendered by [`State::materialize_except`]: their
154
    /// `bytes` are empty and they are known not to be conflicted.
155
    pub unrendered: BTreeSet<String>,
156
}
157
158
impl Snapshot {
159
    pub fn is_conflicted(&self) -> bool {
160
        self.tree.is_conflicted() || self.files.values().any(|f| f.is_conflicted())
161
    }
162
}
163
164
fn vertex(r: AtomRef) -> Vertex {
165
    match r {
166
        AtomRef::Start => Vertex::Start,
167
        AtomRef::End => Vertex::End,
168
        AtomRef::Atom { change, index } => Vertex::Atom((change, index)),
169
    }
170
}
171
172
/// Replace self references in a tree op with the concrete change hash.
173
pub fn resolve_tree_op(op: &TreeOp, me: ChangeHash) -> TreeOp {
174
    match op {
175
        TreeOp::RemoveNode { node, placement } => TreeOp::RemoveNode {
176
            node: *node,
177
            placement: placement.resolve(me),
178
        },
179
        TreeOp::Move {
180
            node,
181
            old,
182
            parent,
183
            name,
184
        } => TreeOp::Move {
185
            node: *node,
186
            old: old.resolve(me),
187
            parent: *parent,
188
            name: name.clone(),
189
        },
190
        TreeOp::SetMode { node, old, mode } => TreeOp::SetMode {
191
            node: *node,
192
            old: old.resolve(me),
193
            mode: *mode,
194
        },
195
        add @ TreeOp::AddNode { .. } => add.clone(),
196
    }
197
}
198
199
/// Apply one change's edits of one file (inserts and deletes; replaces
200
/// live beside the graphs) to that file's graph.
201
fn apply_file_edits(g: &mut FileGraph, h: ChangeHash, edits: Vec<Edit>) {
202
    let mut next = 0u32;
203
    for e in edits {
204
        match e {
205
            Edit::Insert {
206
                after,
207
                before,
208
                lines,
209
                ..
210
            } => {
211
                let first = next;
212
                next += lines.len() as u32;
213
                g.insert_owned(
214
                    h,
215
                    first,
216
                    vertex(after.resolve(h)),
217
                    vertex(before.resolve(h)),
218
                    lines,
219
                );
220
            }
221
            Edit::Delete { atoms, .. } => {
222
                for r in atoms {
223
                    g.delete(h, &r.resolve(h));
224
                }
225
            }
226
            Edit::Replace { .. } => {}
227
        }
228
    }
229
}
230
231
impl State {
232
    pub fn new() -> Self {
233
        Self::default()
234
    }
235
236
    /// An empty state for history only: changes and tree are kept, file
237
    /// edits are recorded but no file graph is built until
238
    /// [`State::load_graphs`] asks for it. For log and other commands that
239
    /// need no file contents, or only a few files.
240
    pub fn new_history_only() -> Self {
241
        State {
242
            deferred: Some(HashMap::new()),
243
            ..Self::default()
244
        }
245
    }
246
247
    /// Whether this state builds file graphs only when asked
248
    /// ([`State::new_history_only`]), even if it has none waiting.
249
    pub fn is_history_only(&self) -> bool {
250
        self.deferred.is_some()
251
    }
252
253
    /// Whether this state holds every file graph.
254
    pub fn is_full(&self) -> bool {
255
        self.deferred.as_ref().is_none_or(|d| d.is_empty())
256
    }
257
258
    /// The graph of `node`, which must be loaded: asking a history-only
259
    /// state for a graph it has not built is a bug, never an empty file.
260
    fn graph(&self, node: &NodeId) -> Option<&FileGraph> {
261
        if let Some(d) = &self.deferred {
262
            assert!(
263
                !d.contains_key(node),
264
                "file graph {} of a history-only state was not loaded (State::load_graphs)",
265
                node.short(12)
266
            );
267
        }
268
        self.files.get(node).map(|g| g.as_ref())
269
    }
270
271
    /// Operations over every file need every graph.
272
    fn require_full(&self, what: &str) {
273
        assert!(
274
            self.is_full(),
275
            "{what} needs every file graph; this state was loaded for history only"
276
        );
277
    }
278
279
    /// Build the graphs of `nodes` in a history-only state: from their
280
    /// checkpoint base (blobs read in one batch through `load`) and their
281
    /// deferred edits. Nodes already built, or with no graph, are skipped.
282
    pub fn load_graphs(
283
        &mut self,
284
        nodes: &[NodeId],
285
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
286
    ) -> Result<(), ObjectError> {
287
        let Some(deferred) = self.deferred.as_mut() else {
288
            return Ok(());
289
        };
290
        let mut taken: Vec<(NodeId, Deferred)> = nodes
291
            .iter()
292
            .filter_map(|n| deferred.remove(n).map(|d| (*n, d)))
293
            .collect();
294
        let mut refs: Vec<ObjectRef> = taken
295
            .iter()
296
            .filter_map(|(_, d)| match &d.base {
297
                Some(DeferredBase::Blob(r)) => Some(*r),
298
                _ => None,
299
            })
300
            .collect();
301
        // Text blobs of inserts read without their lines, after the bases.
302
        let bases = refs.len();
303
        refs.extend(
304
            taken
305
                .iter()
306
                .flat_map(|(_, d)| d.texts.iter().map(|(r, _)| *r)),
307
        );
308
        let mut blobs = if refs.is_empty() {
309
            Vec::new()
310
        } else {
311
            load(&refs)?
312
        };
313
        if blobs.len() != refs.len() {
314
            return Err(ObjectError::Schema("graph blobs: wrong count".into()));
315
        }
316
        let mut texts = blobs.split_off(bases).into_iter();
317
        let mut blobs = blobs.into_iter();
318
        // Pair each graph with its blob, then build them all in parallel:
319
        // graphs are independent.
320
        let mut work: Vec<(NodeId, Deferred, Option<Vec<u8>>)> = Vec::with_capacity(taken.len());
321
        for (node, mut d) in taken.drain(..) {
322
            // Fill in the lines of inserts read without them, in order.
323
            let mut want = std::mem::take(&mut d.texts).into_iter();
324
            for (_, edits) in d.edits.iter_mut() {
325
                for e in edits.iter_mut() {
326
                    if let Edit::Insert { lines, .. } = e {
327
                        if lines.is_empty() {
328
                            let (_, count) = want.next().ok_or_else(|| {
329
                                ObjectError::Schema("an insert's text is missing".into())
330
                            })?;
331
                            let content = texts.next().ok_or_else(|| {
332
                                ObjectError::Schema("text blobs: wrong count".into())
333
                            })?;
334
                            *lines = crate::objects::text_lines(&content, count)?;
335
                        }
336
                    }
337
                }
338
            }
339
            let bytes = match &d.base {
340
                Some(DeferredBase::Blob(_)) => Some(
341
                    blobs
342
                        .next()
343
                        .ok_or_else(|| ObjectError::Schema("graph blobs: wrong count".into()))?,
344
                ),
345
                _ => None,
346
            };
347
            work.push((node, d, bytes));
348
        }
349
        use rayon::prelude::*;
350
        let built: Vec<(NodeId, FileGraph)> = work
351
            .into_par_iter()
352
            .map(|(node, mut d, bytes)| {
353
                let mut graph = match (d.base.take(), bytes) {
354
                    (Some(DeferredBase::Inline(v)), _) => FileGraph::from_value(&v)?,
355
                    (Some(DeferredBase::Blob(_)), Some(bytes)) => {
356
                        FileGraph::from_value(&cbor::decode(&bytes)?)?
357
                    }
358
                    _ => FileGraph::default(),
359
                };
360
                for (h, edits) in std::mem::take(&mut d.edits) {
361
                    apply_file_edits(&mut graph, h, edits);
362
                }
363
                Ok((node, graph))
364
            })
365
            .collect::<Result<_, ObjectError>>()?;
366
        self.files
367
            .extend(built.into_iter().map(|(n, g)| (n, Arc::new(g))));
368
        Ok(())
369
    }
370
371
    /// Every file graph a history-only state has not built, deleted files'
372
    /// included.
373
    pub fn unbuilt_nodes(&self) -> Vec<NodeId> {
374
        self.deferred
375
            .as_ref()
376
            .map(|d| d.keys().copied().collect())
377
            .unwrap_or_default()
378
    }
379
380
    /// Drop the built graphs of `nodes`, for a caller rendering a large
381
    /// tree a batch at a time. The state can no longer render those files,
382
    /// so it must not be used for them again.
383
    pub fn drop_graphs(&mut self, nodes: &[NodeId]) {
384
        for n in nodes {
385
            self.files.remove(n);
386
        }
387
    }
388
389
    /// Build every graph a history-only state has not built, making it full.
390
    pub fn load_all_graphs(
391
        &mut self,
392
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
393
    ) -> Result<(), ObjectError> {
394
        let nodes: Vec<NodeId> = match &self.deferred {
395
            Some(d) => d.keys().copied().collect(),
396
            None => return Ok(()),
397
        };
398
        self.load_graphs(&nodes, load)?;
399
        self.deferred = None;
400
        Ok(())
401
    }
402
403
    /// A key for the graph of `node` in a history-only state that has not
404
    /// built it: equal keys mean equal graphs, so equal renderings (a
405
    /// rendering depends only on the graph and on the changes' own
406
    /// immutable metadata). It names the node, its checkpoint base (a blob,
407
    /// an inline value, or none) and the set of later changes that edited
408
    /// the file.
409
    /// `None` for a full state or a graph already built.
410
    pub fn graph_key(&self, node: &NodeId) -> Option<[u8; 32]> {
411
        let deferred = self.deferred.as_ref()?;
412
        if self.files.contains_key(node) {
413
            return None;
414
        }
415
        let mut h = blake3::Hasher::new();
416
        h.update(b"oxy graph key 1\0");
417
        // A change's edits are applied per node: the node is part of it.
418
        h.update(&node.0);
419
        let Some(d) = deferred.get(node) else {
420
            // Never edited: the empty graph.
421
            h.update(&[0]);
422
            return Some(*h.finalize().as_bytes());
423
        };
424
        match &d.base {
425
            None => h.update(&[0]),
426
            Some(DeferredBase::Blob(r)) => h.update(&[1]).update(&r.0),
427
            Some(DeferredBase::Inline(v)) => h.update(&[2]).update(&cbor::encode(v)),
428
        };
429
        let mut changes: Vec<&ChangeHash> = d.edits.iter().map(|(c, _)| c).collect();
430
        changes.sort();
431
        changes.dedup();
432
        h.update(&(changes.len() as u64).to_le_bytes());
433
        for c in changes {
434
            h.update(&c.0);
435
        }
436
        Some(*h.finalize().as_bytes())
437
    }
438
439
    pub fn len(&self) -> usize {
440
        self.changes.len()
441
    }
442
    pub fn is_empty(&self) -> bool {
443
        self.changes.is_empty()
444
    }
445
    pub fn contains(&self, h: &ChangeHash) -> bool {
446
        self.changes.contains_key(h)
447
    }
448
    pub fn get(&self, h: &ChangeHash) -> Option<&ChangeMeta> {
449
        self.changes.get(h)
450
    }
451
    pub fn changes(&self) -> impl Iterator<Item = (&ChangeHash, &ChangeMeta)> {
452
        self.changes.iter()
453
    }
454
    pub fn tree(&self) -> &TreeGraph {
455
        &self.tree
456
    }
457
    pub fn file(&self, node: &NodeId) -> Option<&FileGraph> {
458
        self.graph(node)
459
    }
460
461
    /// Add a change whose dependencies are already present.
462
    pub fn add(&mut self, change: Change) -> Result<ChangeHash, StateError> {
463
        let h = change.hash();
464
        self.add_hashed(h, change)
465
    }
466
467
    /// [`State::add`] for a change whose hash `h` is already known (it was
468
    /// just stored), so it is not encoded again.
469
    pub fn add_hashed(&mut self, h: ChangeHash, change: Change) -> Result<ChangeHash, StateError> {
470
        if self.changes.contains_key(&h) {
471
            return Ok(h);
472
        }
473
        for d in &change.deps {
474
            if !self.changes.contains_key(d) {
475
                return Err(StateError::MissingDep(*d, h));
476
            }
477
        }
478
        self.add_known(h, change, Vec::new());
479
        Ok(h)
480
    }
481
482
    /// Add a change in any order; call `validate` once all are in.
483
    pub fn add_unchecked(&mut self, change: Change) -> ChangeHash {
484
        let h = change.hash();
485
        self.add_known(h, change, Vec::new());
486
        h
487
    }
488
489
    /// Add a change read from the store under hash `h`, without hashing it
490
    /// again (for a version 2 change that means chunking all its text).
491
    /// `texts` names, in order, the inserts left without their lines (see
492
    /// [`crate::store::Store::get_change_lazy`]); only a history-only state
493
    /// takes them, and only for graphs it has not built.
494
    pub fn add_known(&mut self, h: ChangeHash, change: Change, texts: Vec<(ObjectRef, u32)>) {
495
        if self.changes.contains_key(&h) {
496
            return;
497
        }
498
        let meta = ChangeMeta::of(&change);
499
        self.apply_with(h, change, texts);
500
        self.changes.insert(h, meta);
501
        self.closure.lock().unwrap().clear();
502
    }
503
504
    // ------------------------------------------------------------ checkpoints (spec §11)
505
506
    /// Serialize the whole state in payload version 1: change metadata,
507
    /// tree, file graphs, replaces, all in one value (spec §11).
508
    pub fn checkpoint_payload(&self) -> Vec<u8> {
509
        self.require_full("a checkpoint");
510
        let mut nodes: Vec<&NodeId> = self.files.keys().collect();
511
        nodes.sort();
512
        let files = Value::Array(
513
            nodes
514
                .into_iter()
515
                .map(|n| Value::Array(vec![Value::Bytes(n.0.to_vec()), self.files[n].to_value()]))
516
                .collect(),
517
        );
518
        cbor::encode(&self.payload_value(o::FORMAT_VERSION, files))
519
    }
520
521
    /// Each file graph encoded on its own, by node, for a version 2 payload
522
    /// (spec §11): the graphs of large files become blobs of their own.
523
    pub fn checkpoint_file_graphs(&self) -> Vec<(NodeId, Vec<u8>)> {
524
        use rayon::prelude::*;
525
        self.require_full("a checkpoint");
526
        let mut nodes: Vec<(&NodeId, &FileGraph)> =
527
            self.files.iter().map(|(n, g)| (n, g.as_ref())).collect();
528
        nodes.sort_by_key(|(n, _)| **n);
529
        nodes
530
            .into_par_iter()
531
            .map(|(n, g)| (*n, cbor::encode(&g.to_value())))
532
            .collect()
533
    }
534
535
    /// The payload version 2 index for the graphs of
536
    /// [`State::checkpoint_file_graphs`]: a graph encoded in fewer than
537
    /// [`INLINE_GRAPH_LIMIT`] bytes is kept inline, a larger one is named by
538
    /// `blob_of` (the ObjectRef of the blob holding its encoding).
539
    pub fn checkpoint_index(
540
        &self,
541
        graphs: &[(NodeId, Vec<u8>)],
542
        mut blob_of: impl FnMut(&[u8]) -> ObjectRef,
543
    ) -> Vec<u8> {
544
        let files = Value::Array(
545
            graphs
546
                .iter()
547
                .map(|(n, enc)| {
548
                    let entry = if enc.len() < INLINE_GRAPH_LIMIT {
549
                        cbor::decode(enc).expect("an encoded graph decodes")
550
                    } else {
551
                        Value::Bytes(blob_of(enc).0.to_vec())
552
                    };
553
                    Value::Array(vec![Value::Bytes(n.0.to_vec()), entry])
554
                })
555
                .collect(),
556
        );
557
        cbor::encode(&self.payload_value(CHECKPOINT_INDEX_VERSION, files))
558
    }
559
560
    /// The payload map around `files`: changes, tree and replaces as in version 1.
561
    fn payload_value(&self, version: u64, files: Value) -> Value {
562
        let mut hashes: Vec<&ChangeHash> = self.changes.keys().collect();
563
        hashes.sort();
564
        let changes = Value::Array(
565
            hashes
566
                .into_iter()
567
                .map(|h| {
568
                    let m = &self.changes[h];
569
                    Value::Array(vec![
570
                        Value::Bytes(h.0.to_vec()),
571
                        Value::Bytes(m.change_id.0.to_vec()),
572
                        Value::Array(m.deps.iter().map(|d| Value::Bytes(d.0.to_vec())).collect()),
573
                        Value::Text(m.message.clone()),
574
                        Value::Uint(m.hlc.wall_ms),
575
                        Value::Uint(m.hlc.logical as u64),
576
                        Value::Uint(m.kind.tag()),
577
                        Value::Bytes(m.author.0.to_vec()),
578
                    ])
579
                })
580
                .collect(),
581
        );
582
        let mut rnodes: Vec<&NodeId> = self.replaces.keys().collect();
583
        rnodes.sort();
584
        let opt =
585
            |o: &Option<ObjectRef>| o.map(|r| Value::Bytes(r.0.to_vec())).unwrap_or(Value::Null);
586
        let replaces = Value::Array(
587
            rnodes
588
                .into_iter()
589
                .map(|n| {
590
                    Value::Array(vec![
591
                        Value::Bytes(n.0.to_vec()),
592
                        Value::Array(
593
                            self.replaces[n]
594
                                .iter()
595
                                .map(|(c, o, nw)| {
596
                                    Value::Array(vec![Value::Bytes(c.0.to_vec()), opt(o), opt(nw)])
597
                                })
598
                                .collect(),
599
                        ),
600
                    ])
601
                })
602
                .collect(),
603
        );
604
        Value::map([
605
            (0, Value::Uint(version)),
606
            (1, changes),
607
            (2, self.tree.to_value()),
608
            (3, files),
609
            (4, replaces),
610
        ])
611
    }
612
613
    /// Decode a version 1 payload (the whole state in one value). A
614
    /// version 2 payload needs its graph blobs: use [`State::from_checkpoint`].
615
    pub fn from_checkpoint_payload(bytes: &[u8]) -> Result<State, ObjectError> {
616
        State::from_checkpoint(bytes, |_| {
617
            Err(ObjectError::Schema(
618
                "a version 2 checkpoint needs its graph blobs".into(),
619
            ))
620
        })
621
    }
622
623
    /// Decode a checkpoint payload of either version (spec §11). For
624
    /// version 2, `load` returns the contents of the named graph blobs, in
625
    /// order; the graphs are then decoded in parallel.
626
    pub fn from_checkpoint(
627
        bytes: &[u8],
628
        load: impl FnOnce(&[ObjectRef]) -> Result<Vec<Vec<u8>>, ObjectError>,
629
    ) -> Result<State, ObjectError> {
630
        use rayon::prelude::*;
631
        let v = cbor::decode(bytes)?;
632
        let m = o::map(&v, "checkpoint payload")?;
633
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
634
        if version != o::FORMAT_VERSION && version != CHECKPOINT_INDEX_VERSION {
635
            return Err(ObjectError::Schema(format!(
636
                "checkpoint payload version {version} is not supported"
637
            )));
638
        }
639
        let mut st = State::payload_common(m)?;
640
        let entries = o::array(o::field(m, 3, "files")?, "files")?;
641
        let mut parsed: Vec<(NodeId, &Value)> = Vec::with_capacity(entries.len());
642
        for f in entries {
643
            let e = o::array(f, "file")?;
644
            if e.len() != 2 {
645
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
646
            }
647
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
648
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
649
            parsed.push((node, &e[1]));
650
        }
651
        // Version 2 names large graphs by blob: fetch those in one batch.
652
        let mut fetched: HashMap<NodeId, Vec<u8>> = HashMap::new();
653
        if version == CHECKPOINT_INDEX_VERSION {
654
            let wanted: Vec<(NodeId, ObjectRef)> = parsed
655
                .iter()
656
                .filter(|(_, e)| matches!(e, Value::Bytes(_)))
657
                .map(|(n, e)| Ok((*n, o::oref(e, "graph blob")?)))
658
                .collect::<Result<_, ObjectError>>()?;
659
            if !wanted.is_empty() {
660
                let refs: Vec<ObjectRef> = wanted.iter().map(|(_, r)| *r).collect();
661
                let contents = {
662
                    let _t = crate::timing::phase("load:   graph blobs read");
663
                    load(&refs)?
664
                };
665
                if contents.len() != refs.len() {
666
                    return Err(ObjectError::Schema("graph blobs: wrong count".into()));
667
                }
668
                fetched.extend(wanted.iter().map(|(n, _)| *n).zip(contents));
669
            }
670
        } else if parsed.iter().any(|(_, e)| matches!(e, Value::Bytes(_))) {
671
            return Err(ObjectError::Schema(
672
                "a version 1 payload holds graphs inline".into(),
673
            ));
674
        }
675
        // File graphs are independent; decode and build them in parallel.
676
        let graphs = parsed
677
            .par_iter()
678
            .map(|(node, entry)| {
679
                let graph = match fetched.get(node) {
680
                    Some(bytes) => FileGraph::from_value(&cbor::decode(bytes)?)?,
681
                    None => FileGraph::from_value(entry)?,
682
                };
683
                Ok((*node, graph))
684
            })
685
            .collect::<Result<Vec<_>, ObjectError>>()?;
686
        st.files
687
            .extend(graphs.into_iter().map(|(n, g)| (n, Arc::new(g))));
688
        Ok(st)
689
    }
690
691
    /// The graph blobs a payload names: empty for version 1.
692
    pub fn checkpoint_graph_refs(bytes: &[u8]) -> Result<Vec<ObjectRef>, ObjectError> {
693
        let v = cbor::decode(bytes)?;
694
        let m = o::map(&v, "checkpoint payload")?;
695
        let mut out = Vec::new();
696
        for f in o::array(o::field(m, 3, "files")?, "files")? {
697
            if let Some(entry @ Value::Bytes(_)) = o::array(f, "file")?.get(1) {
698
                out.push(o::oref(entry, "graph blob")?);
699
            }
700
        }
701
        Ok(out)
702
    }
703
704
    /// Decode a checkpoint payload for history only: a version 2 payload's
705
    /// graphs are noted, not read or built, and come later through
706
    /// [`State::load_graphs`]. A version 1 payload holds them inline and is
707
    /// decoded in full.
708
    pub fn from_checkpoint_history(bytes: &[u8]) -> Result<State, ObjectError> {
709
        let v = cbor::decode(bytes)?;
710
        let m = o::map(&v, "checkpoint payload")?;
711
        let version = o::uint(o::field(m, 0, "version")?, "version")?;
712
        if version != CHECKPOINT_INDEX_VERSION {
713
            return State::from_checkpoint_payload(bytes);
714
        }
715
        let mut st = State::payload_common(m)?;
716
        let mut deferred = HashMap::new();
717
        for f in o::array(o::field(m, 3, "files")?, "files")? {
718
            let e = o::array(f, "file")?;
719
            if e.len() != 2 {
720
                return Err(ObjectError::Schema("file: expected [node, graph]".into()));
721
            }
722
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
723
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
724
            let base = match &e[1] {
725
                Value::Bytes(_) => DeferredBase::Blob(o::oref(&e[1], "graph blob")?),
726
                other => DeferredBase::Inline(other.clone()),
727
            };
728
            deferred.insert(
729
                node,
730
                Deferred {
731
                    base: Some(base),
732
                    edits: Vec::new(),
733
                    texts: Vec::new(),
734
                },
735
            );
736
        }
737
        st.deferred = Some(deferred);
738
        Ok(st)
739
    }
740
741
    /// Changes, tree and replaces of a payload of either version.
742
    fn payload_common(m: &BTreeMap<u64, Value>) -> Result<State, ObjectError> {
743
        let mut st = State::new();
744
        for c in o::array(o::field(m, 1, "changes")?, "changes")? {
745
            let e = o::array(c, "change meta")?;
746
            if e.len() != 8 {
747
                return Err(ObjectError::Schema("change meta: expected 8 fields".into()));
748
            }
749
            let hash = o::oref(&e[0], "hash")?;
750
            let meta = ChangeMeta {
751
                change_id: crate::ids::ChangeId::from_slice(o::bytes(&e[1], "change id")?)
752
                    .ok_or_else(|| ObjectError::Schema("change id: expected 16 bytes".into()))?,
753
                deps: o::array(&e[2], "deps")?
754
                    .iter()
755
                    .map(|d| o::oref(d, "dep"))
756
                    .collect::<Result<Vec<_>, _>>()?,
757
                message: o::text(&e[3], "message")?.to_owned(),
758
                hlc: Hlc {
759
                    wall_ms: o::uint(&e[4], "wall")?,
760
                    logical: o::u32_(&e[5], "logical")?,
761
                },
762
                kind: ChangeKind::from_tag(o::uint(&e[6], "kind")?)?,
763
                author: o::oref(&e[7], "author")?,
764
            };
765
            st.changes.insert(hash, meta);
766
        }
767
        st.tree = TreeGraph::from_value(o::field(m, 2, "tree")?)?;
768
        let opt = |v: &Value| -> Result<Option<ObjectRef>, ObjectError> {
769
            if v.is_null() {
770
                Ok(None)
771
            } else {
772
                o::oref(v, "blob").map(Some)
773
            }
774
        };
775
        for r in o::array(o::field(m, 4, "replaces")?, "replaces")? {
776
            let e = o::array(r, "replace")?;
777
            if e.len() != 2 {
778
                return Err(ObjectError::Schema(
779
                    "replace: expected [node, records]".into(),
780
                ));
781
            }
782
            let node = NodeId::from_slice(o::bytes(&e[0], "node")?)
783
                .ok_or_else(|| ObjectError::Schema("node: expected 16 bytes".into()))?;
784
            let mut recs = Vec::new();
785
            for rec in o::array(&e[1], "records")? {
786
                let x = o::array(rec, "record")?;
787
                if x.len() != 3 {
788
                    return Err(ObjectError::Schema("record: expected 3 fields".into()));
789
                }
790
                recs.push((o::oref(&x[0], "change")?, opt(&x[1])?, opt(&x[2])?));
791
            }
792
            st.replaces.insert(node, recs);
793
        }
794
        Ok(st)
795
    }
796
797
    pub fn validate(&self) -> Result<(), StateError> {
798
        for (h, c) in &self.changes {
799
            for d in &c.deps {
800
                if !self.changes.contains_key(d) {
801
                    return Err(StateError::MissingDep(*d, *h));
802
                }
803
            }
804
        }
805
        Ok(())
806
    }
807
808
    fn apply_with(&mut self, h: ChangeHash, c: Change, texts: Vec<(ObjectRef, u32)>) {
809
        for (i, op) in c.tree_ops.iter().enumerate() {
810
            self.tree.apply(h, i as u32, &resolve_tree_op(op, h));
811
        }
812
        if let Some(deferred) = self.deferred.as_mut() {
813
            // History only: edits of files not built wait, grouped per file,
814
            // with the texts of inserts read without their lines.
815
            let mut texts = texts.into_iter();
816
            let mut per_node: HashMap<NodeId, (Vec<Edit>, Vec<TextRef>)> = HashMap::new();
817
            for e in c.edits {
818
                match e {
819
                    Edit::Replace { node, old, new } => {
820
                        self.replaces.entry(node).or_default().push((h, old, new))
821
                    }
822
                    e => {
823
                        let slot = per_node.entry(e.node()).or_default();
824
                        if matches!(&e, Edit::Insert { lines, .. } if lines.is_empty()) {
825
                            slot.1.extend(texts.next());
826
                        }
827
                        slot.0.push(e);
828
                    }
829
                }
830
            }
831
            for (node, (edits, node_texts)) in per_node {
832
                match self.files.get_mut(&node) {
833
                    Some(g) => {
834
                        assert!(
835
                            node_texts.is_empty(),
836
                            "a change read without its text applied to a built graph"
837
                        );
838
                        apply_file_edits(Arc::make_mut(g), h, edits)
839
                    }
840
                    None => {
841
                        let d = deferred.entry(node).or_default();
842
                        d.edits.push((h, edits));
843
                        d.texts.extend(node_texts);
844
                    }
845
                }
846
            }
847
            return;
848
        }
849
        assert!(
850
            texts.is_empty(),
851
            "a change read without its text applied to a full state"
852
        );
853
        let mut counters: HashMap<NodeId, u32> = HashMap::new();
854
        for e in c.edits {
855
            match e {
856
                Edit::Insert {
857
                    node,
858
                    after,
859
                    before,
860
                    lines,
861
                } => {
862
                    let idx = counters.entry(node).or_default();
863
                    let first = *idx;
864
                    *idx += lines.len() as u32;
865
                    Arc::make_mut(self.files.entry(node).or_default()).insert_owned(
866
                        h,
867
                        first,
868
                        vertex(after.resolve(h)),
869
                        vertex(before.resolve(h)),
870
                        lines,
871
                    );
872
                }
873
                Edit::Delete { node, atoms } => {
874
                    let g = Arc::make_mut(self.files.entry(node).or_default());
875
                    for r in atoms {
876
                        g.delete(h, &r.resolve(h));
877
                    }
878
                }
879
                Edit::Replace { node, old, new } => {
880
                    self.replaces.entry(node).or_default().push((h, old, new));
881
                }
882
            }
883
        }
884
    }
885
886
    /// Transitive dependencies of `h`, excluding `h` itself.
887
    pub fn closure(&self, h: &ChangeHash) -> Arc<HashSet<ChangeHash>> {
888
        if let Some(c) = self.closure.lock().unwrap().get(h) {
889
            return c.clone();
890
        }
891
        let mut out = HashSet::new();
892
        let mut stack: Vec<ChangeHash> = self
893
            .changes
894
            .get(h)
895
            .map(|c| c.deps.clone())
896
            .unwrap_or_default();
897
        while let Some(d) = stack.pop() {
898
            if out.insert(d) {
899
                if let Some(c) = self.changes.get(&d) {
900
                    stack.extend(c.deps.iter().copied());
901
                }
902
            }
903
        }
904
        let rc = Arc::new(out);
905
        self.closure.lock().unwrap().insert(*h, rc.clone());
906
        rc
907
    }
908
909
    /// Changes that no other change depends on directly, sorted.
910
    pub fn heads(&self) -> Vec<ChangeHash> {
911
        let depended: HashSet<&ChangeHash> =
912
            self.changes.values().flat_map(|c| c.deps.iter()).collect();
913
        let mut heads: Vec<ChangeHash> = self
914
            .changes
915
            .keys()
916
            .filter(|h| !depended.contains(h))
917
            .copied()
918
            .collect();
919
        heads.sort();
920
        heads
921
    }
922
923
    /// Maximal elements among `hashes` (those not in the closure of another),
924
    /// sorted. One walk down from all of them at once: whatever the walk
925
    /// reaches is below some other element. Linear in the changes reached,
926
    /// where comparing every pair's closures was quadratic in the number
927
    /// of heads, which a bookmark of independent changes has many of.
928
    pub fn maximal(&self, hashes: &[ChangeHash]) -> Vec<ChangeHash> {
929
        let set: BTreeSet<ChangeHash> = hashes.iter().copied().collect();
930
        let mut below: HashSet<ChangeHash> = HashSet::new();
931
        let mut stack: Vec<ChangeHash> = set
932
            .iter()
933
            .filter_map(|h| self.changes.get(h))
934
            .flat_map(|c| c.deps.iter().copied())
935
            .collect();
936
        while let Some(d) = stack.pop() {
937
            if below.insert(d) {
938
                if let Some(c) = self.changes.get(&d) {
939
                    stack.extend(c.deps.iter().copied());
940
                }
941
            }
942
        }
943
        set.into_iter().filter(|h| !below.contains(h)).collect()
944
    }
945
946
    pub fn materialize_file(&self, node: &NodeId) -> Materialized {
947
        self.graph(node)
948
            .map(|g| g.materialize(self))
949
            .unwrap_or_default()
950
    }
951
952
    /// Live lines of a text node in materialized order.
953
    pub fn live_lines(&self, node: &NodeId) -> Vec<(AtomKey, Vec<u8>)> {
954
        let Some(g) = self.graph(node) else {
955
            return vec![];
956
        };
957
        let m = g.materialize(self);
958
        m.live_atoms()
959
            .into_iter()
960
            .map(|a| (a, g.content(&a).unwrap_or_default().to_vec()))
961
            .collect()
962
    }
963
964
    /// Live blobs of an opaque node: every `new` that no later `Replace` retired.
965
    pub fn live_blobs(&self, node: &NodeId) -> Vec<ObjectRef> {
966
        let mut live: Vec<ObjectRef> = self
967
            .live_replaces(node)
968
            .into_iter()
969
            .map(|(_, n)| n)
970
            .collect();
971
        live.sort();
972
        live.dedup();
973
        live
974
    }
975
976
    /// The replace records whose blob is live, with the change that set it
977
    /// (spec §9.3). A record's blob is superseded by a later replacement of
978
    /// that blob: one whose change depends on the record's change, as every
979
    /// replacement depends on the change that made its old blob current
980
    /// (§8.1). Two replacements that do not know each other both stay live
981
    /// (a replace conflict), and a file reverted to an earlier blob keeps it.
982
    /// A replacement without that dependency, from before the rule, is read
983
    /// as before: it supersedes every record that did not come after it.
984
    pub fn live_replaces(&self, node: &NodeId) -> Vec<(ChangeHash, ObjectRef)> {
985
        let Some(rs) = self.replaces.get(node) else {
986
            return vec![];
987
        };
988
        let knows_its_old = |s: &ChangeHash, old: &ObjectRef| {
989
            rs.iter()
990
                .any(|(q, _, n)| n.as_ref() == Some(old) && q != s && self.closure(s).contains(q))
991
        };
992
        rs.iter()
993
            .filter_map(|(c, _, n)| n.map(|n| (*c, n)))
994
            .filter(|(c, n)| {
995
                !rs.iter().any(|(s, o, _)| {
996
                    s != c
997
                        && *o == Some(*n)
998
                        && (self.closure(s).contains(c)
999
                            || (!knows_its_old(s, n) && !self.closure(c).contains(s)))
1000
                })
1001
            })
1002
            .collect()
1003
    }
1004
1005
    /// Short label for conflict markers: `changeid-prefix "message"`.
1006
    pub fn label(&self, h: &ChangeHash) -> String {
1007
        match self.changes.get(h) {
1008
            Some(c) => format!(
1009
                "{} \"{}\"",
1010
                c.change_id.short(8),
1011
                c.message.lines().next().unwrap_or("")
1012
            ),
1013
            None => format!("#{}", h.short(12)),
1014
        }
1015
    }
1016
1017
    /// For resolving a conflicted text node (spec §9.6): the live atoms that
1018
    /// are not part of any conflict region in order, every live atom that is
1019
    /// part of a region, and every change that contributed to a region.
1020
    /// The changes that introduced the live blobs of an opaque node, for a
1021
    /// replace conflict (spec §9.3).
1022
    pub fn blob_contributors(&self, node: &NodeId, blobs: &[ObjectRef]) -> Vec<ChangeHash> {
1023
        let mut out: Vec<ChangeHash> = Vec::new();
1024
        for (h, _, new) in self.replaces.get(node).map(|v| v.as_slice()).unwrap_or(&[]) {
1025
            if new.is_some_and(|b| blobs.contains(&b)) && !out.contains(h) {
1026
                out.push(*h);
1027
            }
1028
        }
1029
        out.sort();
1030
        out
1031
    }
1032
1033
    pub fn conflict_regions(&self, node: &NodeId) -> ConflictRegions {
1034
        let mut out = ConflictRegions::default();
1035
        let Some(g) = self.graph(node) else {
1036
            return out;
1037
        };
1038
        let m = g.materialize(self);
1039
        let mut contributors = BTreeSet::new();
1040
        for seg in &m.segments {
1041
            match seg {
1042
                crate::graph::Segment::Lines(atoms) => {
1043
                    for a in atoms {
1044
                        out.plain
1045
                            .push((*a, g.content(a).unwrap_or_default().to_vec()));
1046
                    }
1047
                }
1048
                crate::graph::Segment::Conflict(sides) => {
1049
                    for side in sides {
1050
                        for a in side {
1051
                            out.region_atoms.push(*a);
1052
                            contributors.insert(a.0);
1053
                        }
1054
                    }
1055
                }
1056
                crate::graph::Segment::Zombie { deleted, inserted } => {
1057
                    for a in deleted {
1058
                        contributors.insert(a.0);
1059
                        contributors.extend(g.deleters(a).copied());
1060
                    }
1061
                    for a in inserted {
1062
                        out.region_atoms.push(*a);
1063
                        contributors.insert(a.0);
1064
                    }
1065
                }
1066
            }
1067
        }
1068
        out.contributors = contributors.into_iter().collect();
1069
        out
1070
    }
1071
1072
    pub fn render_file(&self, node: &NodeId) -> (Vec<u8>, Materialized) {
1073
        let Some(g) = self.graph(node) else {
1074
            return (Vec::new(), Materialized::default());
1075
        };
1076
        let m = g.materialize(self);
1077
        let bytes = g.render(&m, &|h| self.label(h));
1078
        (bytes, m)
1079
    }
1080
1081
    /// Every file rendered, in parallel: files are independent, and
1082
    /// rendering them is most of a snapshot's cost in a large tree.
1083
    pub fn materialize(&self) -> Snapshot {
1084
        use rayon::prelude::*;
1085
        self.require_full("materializing a state");
1086
        let tree = self.tree.view();
1087
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
1088
        let rendered: Vec<(String, FileState)> = entries
1089
            .par_iter()
1090
            .map(|(path, e)| (path.to_string(), self.file_state(e)))
1091
            .collect();
1092
        let files: BTreeMap<String, FileState> = rendered.into_iter().collect();
1093
        Snapshot {
1094
            tree,
1095
            files,
1096
            unrendered: BTreeSet::new(),
1097
        }
1098
    }
1099
1100
    /// Like [`State::materialize`], leaving the text files of nodes in
1101
    /// `skip` unrendered (listed in [`Snapshot::unrendered`]); every other
1102
    /// file's graph must be loaded. For a caller that already knows those
1103
    /// files are unchanged and not conflicted.
1104
    pub fn materialize_except(&self, skip: &HashSet<NodeId>) -> Snapshot {
1105
        use rayon::prelude::*;
1106
        let tree = self.tree.view();
1107
        let entries: Vec<(&String, &crate::tree::TreeEntry)> = tree.entries.iter().collect();
1108
        let rendered: Vec<(String, FileState, bool)> = entries
1109
            .par_iter()
1110
            .map(|(path, e)| {
1111
                if e.kind == NodeKind::File && !e.mode.opaque && skip.contains(&e.node) {
1112
                    let f = FileState {
1113
                        node: e.node,
1114
                        kind: e.kind,
1115
                        mode: e.mode,
1116
                        content: FileContent::Text {
1117
                            bytes: Vec::new(),
1118
                            materialized: Materialized::default(),
1119
                        },
1120
                    };
1121
                    (path.to_string(), f, true)
1122
                } else {
1123
                    (path.to_string(), self.file_state(e), false)
1124
                }
1125
            })
1126
            .collect();
1127
        let mut files = BTreeMap::new();
1128
        let mut unrendered = BTreeSet::new();
1129
        for (p, f, skipped) in rendered {
1130
            if skipped {
1131
                unrendered.insert(p.clone());
1132
            }
1133
            files.insert(p, f);
1134
        }
1135
        Snapshot {
1136
            tree,
1137
            files,
1138
            unrendered,
1139
        }
1140
    }
1141
1142
    fn file_state(&self, e: &crate::tree::TreeEntry) -> FileState {
1143
        {
1144
            let content = match e.kind {
1145
                NodeKind::Dir => FileContent::Dir,
1146
                NodeKind::Symlink | NodeKind::Subrepo => FileContent::Opaque {
1147
                    blobs: self.live_blobs(&e.node),
1148
                },
1149
                NodeKind::File if e.mode.opaque => FileContent::Opaque {
1150
                    blobs: self.live_blobs(&e.node),
1151
                },
1152
                NodeKind::File => {
1153
                    let (bytes, materialized) = self.render_file(&e.node);
1154
                    FileContent::Text {
1155
                        bytes,
1156
                        materialized,
1157
                    }
1158
                }
1159
            };
1160
            FileState {
1161
                node: e.node,
1162
                kind: e.kind,
1163
                mode: e.mode,
1164
                content,
1165
            }
1166
        }
1167
    }
1168
}
1169
1170
impl DepOracle for State {
1171
    fn depends_on(&self, a: &ChangeHash, b: &ChangeHash) -> bool {
1172
        a == b || self.closure(a).contains(b)
1173
    }
1174
}
1175
1176
#[cfg(test)]
1177
mod tests {
1178
    use super::*;
1179
    use crate::ids::ChangeId;
1180
    use crate::objects::{AtomRange, ChangeKind, Hlc, OpRef};
1181
1182
    fn change(deps: Vec<ChangeHash>, tree_ops: Vec<TreeOp>, edits: Vec<Edit>) -> Change {
1183
        let mut c = Change {
1184
            version: crate::objects::CHANGE_VERSION,
1185
            change_id: ChangeId::random(),
1186
            deps,
1187
            author: ObjectRef::ZERO,
1188
            hlc: Hlc {
1189
                wall_ms: 1,
1190
                logical: 0,
1191
            },
1192
            message: "m".into(),
1193
            tree_ops,
1194
            edits,
1195
            kind: ChangeKind::Normal,
1196
        };
1197
        c.normalize();
1198
        c
1199
    }
1200
1201
    #[test]
1202
    fn build_edit_and_materialize() {
1203
        let mut st = State::new();
1204
        let f = NodeId::random();
1205
        let c1 = change(
1206
            vec![],
1207
            vec![TreeOp::AddNode {
1208
                node: f,
1209
                kind: NodeKind::File,
1210
                mode: Mode::TEXT,
1211
                parent: NodeId::ROOT,
1212
                name: "a.txt".into(),
1213
            }],
1214
            vec![Edit::Insert {
1215
                node: f,
1216
                after: AtomRef::Start,
1217
                before: AtomRef::End,
1218
                lines: vec![b"one\n".to_vec(), b"two\n".to_vec()],
1219
            }],
1220
        );
1221
        let h1 = st.add(c1).unwrap();
1222
        // Depends on h1: append a line and delete "one".
1223
        let c2 = change(
1224
            vec![h1],
1225
            vec![],
1226
            vec![
1227
                Edit::Delete {
1228
                    node: f,
1229
                    atoms: vec![AtomRange {
1230
                        change: h1,
1231
                        from: 0,
1232
                        to: 1,
1233
                    }],
1234
                },
1235
                Edit::Insert {
1236
                    node: f,
1237
                    after: AtomRef::Atom {
1238
                        change: h1,
1239
                        index: 1,
1240
                    },
1241
                    before: AtomRef::End,
1242
                    lines: vec![b"three\n".to_vec()],
1243
                },
1244
            ],
1245
        );
1246
        let h2 = st.add(c2).unwrap();
1247
        assert_eq!(st.heads(), vec![h2]);
1248
        assert!(st.depends_on(&h2, &h1));
1249
        assert!(!st.depends_on(&h1, &h2));
1250
        let snap = st.materialize();
1251
        assert!(!snap.is_conflicted());
1252
        let a = &snap.files["a.txt"];
1253
        assert!(matches!(&a.content, FileContent::Text { bytes, .. } if bytes == b"two\nthree\n"));
1254
        assert_eq!(st.live_lines(&f).len(), 2);
1255
    }
1256
1257
    #[test]
1258
    fn missing_dependency_is_rejected() {
1259
        let mut st = State::new();
1260
        let c = change(vec![ObjectRef([1; 32])], vec![], vec![]);
1261
        assert!(matches!(st.add(c), Err(StateError::MissingDep(..))));
1262
    }
1263
1264
    #[test]
1265
    fn self_references_and_multi_insert_indexing() {
1266
        let mut st = State::new();
1267
        let f = NodeId::random();
1268
        let me = OpRef {
1269
            change: ObjectRef::ZERO,
1270
            index: 0,
1271
        };
1272
        let c1 = change(
1273
            vec![],
1274
            vec![
1275
                TreeOp::AddNode {
1276
                    node: f,
1277
                    kind: NodeKind::File,
1278
                    mode: Mode::TEXT,
1279
                    parent: NodeId::ROOT,
1280
                    name: "x".into(),
1281
                },
1282
                TreeOp::SetMode {
1283
                    node: f,
1284
                    old: me,
1285
                    mode: Mode {
1286
                        exec: true,
1287
                        opaque: false,
1288
                    },
1289
                },
1290
            ],
1291
            vec![
1292
                Edit::Insert {
1293
                    node: f,
1294
                    after: AtomRef::Start,
1295
                    before: AtomRef::End,
1296
                    lines: vec![b"a\n".to_vec(), b"c\n".to_vec()],
1297
                },
1298
                // Insert between the two lines just inserted, using self references.
1299
                Edit::Insert {
1300
                    node: f,
1301
                    after: AtomRef::Atom {
1302
                        change: ObjectRef::ZERO,
1303
                        index: 0,
1304
                    },
1305
                    before: AtomRef::Atom {
1306
                        change: ObjectRef::ZERO,
1307
                        index: 1,
1308
                    },
1309
                    lines: vec![b"b\n".to_vec()],
1310
                },
1311
            ],
1312
        );
1313
        st.add(c1).unwrap();
1314
        let snap = st.materialize();
1315
        let x = &snap.files["x"];
1316
        assert_eq!(
1317
            x.mode,
1318
            Mode {
1319
                exec: true,
1320
                opaque: false
1321
            }
1322
        );
1323
        assert!(matches!(&x.content, FileContent::Text { bytes, .. } if bytes == b"a\nb\nc\n"));
1324
    }
1325
1326
    #[test]
1327
    fn opaque_replace_and_conflict() {
1328
        let mut st = State::new();
1329
        let f = NodeId::random();
1330
        let b1 = ObjectRef([1; 32]);
1331
        let b2 = ObjectRef([2; 32]);
1332
        let b3 = ObjectRef([3; 32]);
1333
        let h1 = st
1334
            .add(change(
1335
                vec![],
1336
                vec![TreeOp::AddNode {
1337
                    node: f,
1338
                    kind: NodeKind::File,
1339
                    mode: Mode::OPAQUE,
1340
                    parent: NodeId::ROOT,
1341
                    name: "img".into(),
1342
                }],
1343
                vec![Edit::Replace {
1344
                    node: f,
1345
                    old: None,
1346
                    new: Some(b1),
1347
                }],
1348
            ))
1349
            .unwrap();
1350
        assert_eq!(st.live_blobs(&f), vec![b1]);
1351
        st.add(change(
1352
            vec![h1],
1353
            vec![],
1354
            vec![Edit::Replace {
1355
                node: f,
1356
                old: Some(b1),
1357
                new: Some(b2),
1358
            }],
1359
        ))
1360
        .unwrap();
1361
        st.add(change(
1362
            vec![h1],
1363
            vec![],
1364
            vec![Edit::Replace {
1365
                node: f,
1366
                old: Some(b1),
1367
                new: Some(b3),
1368
            }],
1369
        ))
1370
        .unwrap();
1371
        let snap = st.materialize();
1372
        assert!(snap.is_conflicted());
1373
        assert!(
1374
            matches!(&snap.files["img"].content, FileContent::Opaque { blobs } if blobs == &vec![b2, b3])
1375
        );
1376
    }
1377
1378
    #[test]
1379
    fn checkpoint_payload_round_trip_and_replay() {
1380
        let mut st = State::new();
1381
        let f = NodeId::random();
1382
        let h1 = st
1383
            .add(change(
1384
                vec![],
1385
                vec![TreeOp::AddNode {
1386
                    node: f,
1387
                    kind: NodeKind::File,
1388
                    mode: Mode::TEXT,
1389
                    parent: NodeId::ROOT,
1390
                    name: "a".into(),
1391
                }],
1392
                vec![Edit::Insert {
1393
                    node: f,
1394
                    after: AtomRef::Start,
1395
                    before: AtomRef::End,
1396
                    lines: vec![b"1\n".to_vec(), b"2\n".to_vec()],
1397
                }],
1398
            ))
1399
            .unwrap();
1400
        let h2 = st
1401
            .add(change(
1402
                vec![h1],
1403
                vec![],
1404
                vec![Edit::Delete {
1405
                    node: f,
1406
                    atoms: vec![AtomRange {
1407
                        change: h1,
1408
                        from: 0,
1409
                        to: 1,
1410
                    }],
1411
                }],
1412
            ))
1413
            .unwrap();
1414
        let payload = st.checkpoint_payload();
1415
        let back = State::from_checkpoint_payload(&payload).unwrap();
1416
        assert_eq!(back.len(), 2);
1417
        assert_eq!(back.heads(), vec![h2]);
1418
        assert_eq!(back.get(&h1).unwrap().message, "m");
1419
        assert_eq!(back.checkpoint_payload(), payload, "deterministic");
1420
        // Replaying a further change onto the restored state equals a full build.
1421
        let c3 = change(
1422
            vec![h2],
1423
            vec![],
1424
            vec![Edit::Insert {
1425
                node: f,
1426
                after: AtomRef::Atom {
1427
                    change: h1,
1428
                    index: 1,
1429
                },
1430
                before: AtomRef::End,
1431
                lines: vec![b"3\n".to_vec()],
1432
            }],
1433
        );
1434
        let mut full = st.clone();
1435
        full.add(c3.clone()).unwrap();
1436
        let mut restored = back;
1437
        restored.add(c3).unwrap();
1438
        let (a, b) = (full.materialize(), restored.materialize());
1439
        assert_eq!(
1440
            a.files.keys().collect::<Vec<_>>(),
1441
            b.files.keys().collect::<Vec<_>>()
1442
        );
1443
        assert_eq!(a.files["a"].content, b.files["a"].content);
1444
        assert!(
1445
            matches!(&b.files["a"].content, FileContent::Text { bytes, .. } if bytes == b"2\n3\n")
1446
        );
1447
        assert!(State::from_checkpoint_payload(b"nonsense").is_err());
1448
    }
1449
1450
    /// History-only states (O10f): the same state as a full load once its
1451
    /// graphs are built, by replay and from a version 2 checkpoint with
1452
    /// later changes; unloaded graphs are never read as empty.
1453
    #[test]
1454
    fn graph_keys_change_exactly_when_a_graph_does() {
1455
        let (f, g) = (NodeId::random(), NodeId::random());
1456
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1457
            node,
1458
            kind: NodeKind::File,
1459
            mode: Mode::TEXT,
1460
            parent: NodeId::ROOT,
1461
            name: name.into(),
1462
        };
1463
        let ins = |node: NodeId, line: &[u8]| Edit::Insert {
1464
            node,
1465
            after: AtomRef::Start,
1466
            before: AtomRef::End,
1467
            lines: vec![line.to_vec()],
1468
        };
1469
        let c1 = change(
1470
            vec![],
1471
            vec![add(f, "f"), add(g, "g")],
1472
            vec![ins(f, b"f\n"), ins(g, b"g\n")],
1473
        );
1474
        let h1 = c1.hash();
1475
        let c2 = change(vec![h1], vec![], vec![ins(g, b"g2\n")]);
1476
        let h2 = c2.hash();
1477
        let c3 = change(vec![h2], vec![], vec![ins(f, b"f2\n")]);
1478
        let load = |cs: &[&Change]| {
1479
            let mut st = State::new_history_only();
1480
            for c in cs {
1481
                st.add((*c).clone()).unwrap();
1482
            }
1483
            st
1484
        };
1485
        let s1 = load(&[&c1]);
1486
        let s2 = load(&[&c1, &c2]);
1487
        let s3 = load(&[&c1, &c2, &c3]);
1488
        let key = |s: &State, n: &NodeId| s.graph_key(n).unwrap();
1489
        assert_eq!(key(&s1, &f), key(&load(&[&c1]), &f), "same state, same key");
1490
        assert_eq!(key(&s1, &f), key(&s2, &f), "an edit elsewhere keeps it");
1491
        assert_ne!(key(&s1, &g), key(&s2, &g), "an edit of the file changes it");
1492
        assert_ne!(key(&s2, &f), key(&s3, &f));
1493
        assert_ne!(key(&s1, &f), key(&s1, &g), "different files differ");
1494
        let mut built = load(&[&c1]);
1495
        built.load_graphs(&[f], |_| unreachable!()).unwrap();
1496
        assert!(built.graph_key(&f).is_none(), "a built graph has no key");
1497
        let mut full = State::new();
1498
        full.add(c1.clone()).unwrap();
1499
        assert!(full.graph_key(&f).is_none(), "nor has a full state");
1500
1501
        // Through a version 2 checkpoint of c1, keys name its graph blobs
1502
        // or inline values: stable across loads, changed by later edits.
1503
        let graphs = full.checkpoint_file_graphs();
1504
        let index = full.checkpoint_index(&graphs, |enc| {
1505
            crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
1506
        });
1507
        let cp = |extra: &[&Change]| {
1508
            let mut st = State::from_checkpoint_history(&index).unwrap();
1509
            for c in extra {
1510
                st.add((*c).clone()).unwrap();
1511
            }
1512
            st
1513
        };
1514
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[]), &f));
1515
        assert_eq!(key(&cp(&[]), &f), key(&cp(&[&c2]), &f));
1516
        assert_ne!(key(&cp(&[]), &g), key(&cp(&[&c2]), &g));
1517
        assert_ne!(key(&cp(&[&c2]), &f), key(&cp(&[&c2, &c3]), &f));
1518
1519
        // Partial rendering: skipped files are listed and empty, the others
1520
        // render as in a full state.
1521
        let mut part = load(&[&c1, &c2]);
1522
        part.load_graphs(&[g], |_| unreachable!()).unwrap();
1523
        let snap = part.materialize_except(&[f].into_iter().collect());
1524
        assert_eq!(snap.unrendered, ["f".to_string()].into_iter().collect());
1525
        let mut whole = State::new();
1526
        whole.add(c1.clone()).unwrap();
1527
        whole.add(c2.clone()).unwrap();
1528
        assert_eq!(snap.files["g"], whole.materialize().files["g"]);
1529
        assert!(
1530
            matches!(&snap.files["f"].content, FileContent::Text { bytes, .. } if bytes.is_empty())
1531
        );
1532
    }
1533
1534
    #[test]
1535
    fn history_only_states_build_the_same_graphs_on_demand() {
1536
        let small = NodeId::random();
1537
        let big = NodeId::random();
1538
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1539
            node,
1540
            kind: NodeKind::File,
1541
            mode: Mode::TEXT,
1542
            parent: NodeId::ROOT,
1543
            name: name.into(),
1544
        };
1545
        let lines: Vec<Vec<u8>> = (0..300)
1546
            .map(|i| format!("line {i}\n").into_bytes())
1547
            .collect();
1548
        let c1 = change(
1549
            vec![],
1550
            vec![add(small, "small"), add(big, "big")],
1551
            vec![
1552
                Edit::Insert {
1553
                    node: small,
1554
                    after: AtomRef::Start,
1555
                    before: AtomRef::End,
1556
                    lines: vec![b"x\n".to_vec()],
1557
                },
1558
                Edit::Insert {
1559
                    node: big,
1560
                    after: AtomRef::Start,
1561
                    before: AtomRef::End,
1562
                    lines,
1563
                },
1564
            ],
1565
        );
1566
        let h1 = c1.hash();
1567
        let c2 = change(
1568
            vec![h1],
1569
            vec![],
1570
            vec![
1571
                Edit::Delete {
1572
                    node: big,
1573
                    atoms: vec![AtomRange {
1574
                        change: h1,
1575
                        from: 2,
1576
                        to: 9,
1577
                    }],
1578
                },
1579
                Edit::Insert {
1580
                    node: big,
1581
                    after: AtomRef::Atom {
1582
                        change: h1,
1583
                        index: 20,
1584
                    },
1585
                    before: AtomRef::Atom {
1586
                        change: h1,
1587
                        index: 21,
1588
                    },
1589
                    lines: vec![b"new a\n".to_vec(), b"new b\n".to_vec()],
1590
                },
1591
                Edit::Insert {
1592
                    node: small,
1593
                    after: AtomRef::Atom {
1594
                        change: h1,
1595
                        index: 0,
1596
                    },
1597
                    before: AtomRef::End,
1598
                    lines: vec![b"y\n".to_vec()],
1599
                },
1600
            ],
1601
        );
1602
        let h2 = c2.hash();
1603
        let c3 = change(
1604
            vec![h2],
1605
            vec![],
1606
            vec![Edit::Delete {
1607
                node: small,
1608
                atoms: vec![AtomRange {
1609
                    change: h1,
1610
                    from: 0,
1611
                    to: 1,
1612
                }],
1613
            }],
1614
        );
1615
1616
        let mut full = State::new();
1617
        for c in [&c1, &c2, &c3] {
1618
            full.add(c.clone()).unwrap();
1619
        }
1620
        // By replay: nothing built until asked, then exactly the full graphs.
1621
        let mut hist = State::new_history_only();
1622
        for c in [&c1, &c2, &c3] {
1623
            hist.add(c.clone()).unwrap();
1624
        }
1625
        assert!(!hist.is_full() && hist.files.is_empty(), "no graph built");
1626
        assert_eq!(hist.len(), 3);
1627
        hist.load_graphs(&[big], |_| unreachable!("no checkpoint"))
1628
            .unwrap();
1629
        assert_eq!(
1630
            hist.render_file(&big).0,
1631
            full.render_file(&big).0,
1632
            "one file on its own"
1633
        );
1634
        assert!(!hist.is_full());
1635
        hist.load_graphs(&[small, big], |_| unreachable!()).unwrap();
1636
        assert!(hist.is_full());
1637
        assert_eq!(hist.checkpoint_payload(), full.checkpoint_payload());
1638
1639
        // From a version 2 checkpoint of c1+c2, then c3 applied later.
1640
        let mut base = State::new();
1641
        base.add(c1.clone()).unwrap();
1642
        base.add(c2.clone()).unwrap();
1643
        let graphs = base.checkpoint_file_graphs();
1644
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
1645
        let index = base.checkpoint_index(&graphs, |enc| {
1646
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
1647
            blobs.insert(r, enc.to_vec());
1648
            r
1649
        });
1650
        let mut from_cp = State::from_checkpoint_history(&index).unwrap();
1651
        from_cp.add(c3.clone()).unwrap();
1652
        assert!(!from_cp.is_full());
1653
        let mut fetched = 0;
1654
        from_cp
1655
            .load_graphs(&[small, big], |refs| {
1656
                fetched += refs.len();
1657
                refs.iter()
1658
                    .map(|r| {
1659
                        blobs
1660
                            .get(r)
1661
                            .cloned()
1662
                            .ok_or_else(|| ObjectError::Schema("missing".into()))
1663
                    })
1664
                    .collect()
1665
            })
1666
            .unwrap();
1667
        assert_eq!(
1668
            fetched, 1,
1669
            "the large graph's blob, in one batch; the small one was inline"
1670
        );
1671
        assert_eq!(from_cp.checkpoint_payload(), full.checkpoint_payload());
1672
    }
1673
1674
    #[test]
1675
    #[should_panic(expected = "was not loaded")]
1676
    fn a_history_only_state_never_reads_an_unloaded_graph_as_empty() {
1677
        let f = NodeId::random();
1678
        let mut st = State::new_history_only();
1679
        st.add(change(
1680
            vec![],
1681
            vec![TreeOp::AddNode {
1682
                node: f,
1683
                kind: NodeKind::File,
1684
                mode: Mode::TEXT,
1685
                parent: NodeId::ROOT,
1686
                name: "a".into(),
1687
            }],
1688
            vec![Edit::Insert {
1689
                node: f,
1690
                after: AtomRef::Start,
1691
                before: AtomRef::End,
1692
                lines: vec![b"a\n".to_vec()],
1693
            }],
1694
        ))
1695
        .unwrap();
1696
        st.render_file(&f);
1697
    }
1698
1699
    #[test]
1700
    #[should_panic(expected = "needs every file graph")]
1701
    fn materializing_a_history_only_state_is_refused() {
1702
        let f = NodeId::random();
1703
        let mut st = State::new_history_only();
1704
        st.add(change(
1705
            vec![],
1706
            vec![TreeOp::AddNode {
1707
                node: f,
1708
                kind: NodeKind::File,
1709
                mode: Mode::TEXT,
1710
                parent: NodeId::ROOT,
1711
                name: "a".into(),
1712
            }],
1713
            vec![Edit::Insert {
1714
                node: f,
1715
                after: AtomRef::Start,
1716
                before: AtomRef::End,
1717
                lines: vec![b"a\n".to_vec()],
1718
            }],
1719
        ))
1720
        .unwrap();
1721
        st.materialize();
1722
    }
1723
1724
    /// Version 2 payloads (spec §11): small graphs inline, large ones by
1725
    /// blob; the state read back is the same as from version 1.
1726
    #[test]
1727
    fn checkpoint_index_round_trip_matches_version_1() {
1728
        let mut st = State::new();
1729
        let small = NodeId::random();
1730
        let big = NodeId::random();
1731
        let add = |node: NodeId, name: &str| TreeOp::AddNode {
1732
            node,
1733
            kind: NodeKind::File,
1734
            mode: Mode::TEXT,
1735
            parent: NodeId::ROOT,
1736
            name: name.into(),
1737
        };
1738
        let big_lines: Vec<Vec<u8>> = (0..400)
1739
            .map(|i| format!("line {i} of a long file\n").into_bytes())
1740
            .collect();
1741
        let h1 = st
1742
            .add(change(
1743
                vec![],
1744
                vec![add(small, "small"), add(big, "big")],
1745
                vec![
1746
                    Edit::Insert {
1747
                        node: small,
1748
                        after: AtomRef::Start,
1749
                        before: AtomRef::End,
1750
                        lines: vec![b"x\n".to_vec()],
1751
                    },
1752
                    Edit::Insert {
1753
                        node: big,
1754
                        after: AtomRef::Start,
1755
                        before: AtomRef::End,
1756
                        lines: big_lines,
1757
                    },
1758
                ],
1759
            ))
1760
            .unwrap();
1761
        st.add(change(
1762
            vec![h1],
1763
            vec![],
1764
            vec![Edit::Delete {
1765
                node: big,
1766
                atoms: vec![AtomRange {
1767
                    change: h1,
1768
                    from: 3,
1769
                    to: 7,
1770
                }],
1771
            }],
1772
        ))
1773
        .unwrap();
1774
1775
        let graphs = st.checkpoint_file_graphs();
1776
        let mut blobs: HashMap<ObjectRef, Vec<u8>> = HashMap::new();
1777
        let index = st.checkpoint_index(&graphs, |enc| {
1778
            let r = crate::hash::hash_object(crate::hash::ObjectType::Blob, enc);
1779
            blobs.insert(r, enc.to_vec());
1780
            r
1781
        });
1782
        assert_eq!(blobs.len(), 1, "only the large graph is a blob of its own");
1783
        assert_eq!(
1784
            State::checkpoint_graph_refs(&index).unwrap(),
1785
            blobs.keys().copied().collect::<Vec<_>>()
1786
        );
1787
        assert!(
1788
            State::checkpoint_graph_refs(&st.checkpoint_payload())
1789
                .unwrap()
1790
                .is_empty(),
1791
            "version 1 names none"
1792
        );
1793
        assert!(index.len() < st.checkpoint_payload().len());
1794
1795
        let back = State::from_checkpoint(&index, |refs| {
1796
            refs.iter()
1797
                .map(|r| {
1798
                    blobs
1799
                        .get(r)
1800
                        .cloned()
1801
                        .ok_or_else(|| ObjectError::Schema("missing".into()))
1802
                })
1803
                .collect()
1804
        })
1805
        .unwrap();
1806
        assert_eq!(
1807
            back.checkpoint_payload(),
1808
            st.checkpoint_payload(),
1809
            "the same state as version 1"
1810
        );
1811
        assert_eq!(
1812
            back.materialize().files["big"].content,
1813
            st.materialize().files["big"].content
1814
        );
1815
        // Deterministic: the same state gives the same index.
1816
        assert_eq!(
1817
            back.checkpoint_index(&back.checkpoint_file_graphs(), |enc| {
1818
                crate::hash::hash_object(crate::hash::ObjectType::Blob, enc)
1819
            }),
1820
            index
1821
        );
1822
        // A missing graph blob is an error, not an empty file.
1823
        assert!(
1824
            State::from_checkpoint(&index, |_| Err(ObjectError::Schema("gone".into()))).is_err()
1825
        );
1826
        assert!(
1827
            State::from_checkpoint_payload(&index).is_err(),
1828
            "version 2 needs its blobs"
1829
        );
1830
        // Version 1 payloads still read, and unknown versions do not.
1831
        assert!(State::from_checkpoint(&st.checkpoint_payload(), |_| unreachable!()).is_ok());
1832
        let mut v3 = cbor::decode(&index).unwrap();
1833
        if let Value::Map(m) = &mut v3 {
1834
            m.insert(0, Value::Uint(3));
1835
        }
1836
        assert!(State::from_checkpoint(&cbor::encode(&v3), |_| unreachable!()).is_err());
1837
    }
1838
1839
    #[test]
1840
    fn maximal_elements() {
1841
        let mut st = State::new();
1842
        let h1 = st.add(change(vec![], vec![], vec![])).unwrap();
1843
        let h2 = st.add(change(vec![h1], vec![], vec![])).unwrap();
1844
        let h3 = st.add(change(vec![], vec![], vec![])).unwrap();
1845
        let mut m = st.maximal(&[h1, h2, h3]);
1846
        m.sort();
1847
        let mut want = vec![h2, h3];
1848
        want.sort();
1849
        assert_eq!(m, want);
1850
        assert_eq!(st.heads(), want);
1851
    }
1852
1853
    /// The one-walk `maximal` agrees with the definition (not in the
1854
    /// closure of another element) on random graphs, with repeated and
1855
    /// unknown hashes among the input.
1856
    #[test]
1857
    fn maximal_matches_its_definition() {
1858
        use rand::{Rng, SeedableRng};
1859
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
1860
        for _ in 0..20 {
1861
            let mut st = State::new();
1862
            let mut all: Vec<ChangeHash> = Vec::new();
1863
            for _ in 0..60 {
1864
                let deps: Vec<ChangeHash> =
1865
                    all.iter().copied().filter(|_| rng.gen_bool(0.05)).collect();
1866
                all.push(st.add(change(deps, vec![], vec![])).unwrap());
1867
            }
1868
            let mut pick: Vec<ChangeHash> =
1869
                all.iter().copied().filter(|_| rng.gen_bool(0.4)).collect();
1870
            pick.extend(pick.clone().into_iter().take(3));
1871
            pick.push(ObjectRef([0xee; 32]));
1872
            let set: BTreeSet<ChangeHash> = pick.iter().copied().collect();
1873
            let want: Vec<ChangeHash> = set
1874
                .iter()
1875
                .filter(|h| !set.iter().any(|o| o != *h && st.closure(o).contains(h)))
1876
                .copied()
1877
                .collect();
1878
            assert_eq!(st.maximal(&pick), want);
1879
            assert_eq!(st.maximal(&all), st.heads());
1880
        }
1881
    }
1882
}