1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! Abstractions for working with commits.
use crate::collections::{Map, Set};
use alloc::vec::Vec;
use core::error::Error;
use thiserror::Error;
use crate::{
blob::BlobMeta, depth::DepthMetric, fragment::Fragment, id::SedimentreeId,
loose_commit::id::CommitId,
};
/// An error indicating that a commit is missing from the store.
#[derive(Debug, Clone, Copy, Error, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[error("missing commit: {0}")]
pub struct MissingCommitError(CommitId);
/// A trait for types that have parent hashes.
pub trait Parents {
/// The parent identifiers of this node.
fn parents(&self) -> Set<CommitId>;
}
#[allow(clippy::implicit_hasher)]
impl Parents for Set<CommitId> {
fn parents(&self) -> Set<CommitId> {
self.clone()
}
}
#[derive(Debug, Error)]
/// An error for the [`fragment`] function.
pub enum FragmentError<'a, S: CommitStore<'a> + ?Sized> {
/// An error occurred during lookup.
#[error(transparent)]
LookupError(S::LookupError),
/// A commit was missing from the store.
#[error(transparent)]
MissingCommit(#[from] MissingCommitError),
/// The head identifier has depth 0 and cannot be a fragment head.
///
/// Depth-0 commits are loose commits, not fragment heads. The caller
/// should filter them out before calling [`CommitStore::fragment`].
#[error("depth-0 commit cannot be a fragment head: {0}")]
DepthZeroHead(CommitId),
}
/// An abstraction over stores of commits that can be looked up by their identifier.
pub trait CommitStore<'a> {
/// The type of node stored in the commit store.
type Node: Parents;
/// The error type returned when a lookup fails.
type LookupError: Error;
/// Looks up a commit by its identifier.
///
/// # Errors
///
/// Returns a [`Self::LookupError`] if the lookup fails.
fn lookup(&self, id: CommitId) -> Result<Option<Self::Node>, Self::LookupError>;
/// Constructs a single fragment starting from `head_id`.
///
/// Walks from the head through parents, collecting all commits
/// whose depth is _less than or equal to_ the head's depth. Commits
/// with depth _strictly greater_ than the head become the boundary —
/// they delimit the fragment and will head deeper (larger) strata.
///
/// Same-depth commits encountered during the walk are absorbed as
/// members but are _not_ recorded as checkpoints. Only commits whose
/// depth is strictly between 0 and the head's depth (`0 < depth <
/// head_depth`) are recorded as checkpoints. This means a depth-N
/// fragment spans all the way back to the next depth-(N+1)+ commit,
/// rather than stopping at each depth-N peer.
///
/// `head_id` must have depth > 0; depth-0 commits are loose
/// commits, not fragment heads.
///
/// # Errors
///
/// Returns [`FragmentError::MissingCommit`] if any commit in the walk
/// is absent from the store.
fn fragment<D: DepthMetric>(
&self,
head_id: CommitId,
known_fragment_states: &Map<CommitId, FragmentState<Self::Node>>,
strategy: &D,
) -> Result<FragmentState<Self::Node>, FragmentError<'a, Self>> {
let head_depth = strategy.to_depth(head_id);
if !head_depth.is_boundary() {
return Err(FragmentError::DepthZeroHead(head_id));
}
let mut visited: Set<CommitId> = Set::from([head_id]);
let mut members: Set<CommitId> = Set::from([head_id]);
let mut boundary: Map<CommitId, Self::Node> = Map::new();
let mut checkpoints: Set<CommitId> = Set::new();
let head_node = self
.lookup(head_id)
.map_err(FragmentError::LookupError)?
.ok_or(FragmentError::MissingCommit(MissingCommitError(head_id)))?;
let mut queue: Vec<CommitId> = head_node.parents().into_iter().collect();
while let Some(id) = queue.pop() {
if !visited.insert(id) {
continue;
}
let node = self
.lookup(id)
.map_err(FragmentError::LookupError)?
.ok_or(FragmentError::MissingCommit(MissingCommitError(id)))?;
let depth = strategy.to_depth(id);
if depth >= head_depth {
// Same or deeper: this commit heads a sibling or larger stratum.
// It becomes our boundary — don't expand its parents.
boundary.insert(id, node);
} else {
// Shallower depth: absorbed into this fragment.
members.insert(id);
if depth.is_boundary() && depth < head_depth {
// Shallower stratum boundary within this fragment.
// Retained so we can determine the "supports"
// relationship between strata.
checkpoints.insert(id);
}
for p in node.parents() {
if !visited.contains(&p) {
queue.push(p);
}
}
}
}
// Strip overlap with already-known deeper fragments whose heads
// coincide with our boundary.
for boundary_hash in boundary.keys() {
if let Some(known) = known_fragment_states.get(boundary_hash) {
for m in known.members() {
members.remove(m);
checkpoints.remove(m);
}
}
}
Ok(FragmentState::new(head_id, members, checkpoints, boundary))
}
/// Builds a complete fragment store by walking from heads to roots.
///
/// Fragments are built level-by-level: the document heads yield the
/// shallowest fragments, whose boundaries become the heads for the
/// next (deeper) level. Depth-0 commits are skipped — they are loose
/// commits, not fragment heads — but their parents are still walked
/// so that deeper fragment boundaries are discovered.
///
/// Previously computed fragments in `known_fragment_states` are reused;
/// newly built ones are inserted into the map and also returned.
///
/// # Errors
///
/// Returns a [`FragmentError`] if any lookup fails.
fn build_fragment_store<'b, D: DepthMetric>(
&self,
head_ids: &[CommitId],
known_fragment_states: &'b mut Map<CommitId, FragmentState<Self::Node>>,
strategy: &D,
) -> Result<Vec<&'b FragmentState<Self::Node>>, FragmentError<'a, Self>> {
let mut fresh_heads: Vec<CommitId> = Vec::new();
let mut queue = head_ids.to_vec();
let mut visited: Set<CommitId> = Set::new();
while let Some(head) = queue.pop() {
if !visited.insert(head) {
continue;
}
// Already computed — just walk past to discover deeper levels.
if let Some(state) = known_fragment_states.get(&head) {
queue.extend(state.boundary().keys().copied());
continue;
}
// Depth-0 commits are loose commits, not fragment heads.
// Walk their parents so we still discover deeper boundaries.
if !strategy.to_depth(head).is_boundary() {
if let Some(node) = self.lookup(head).map_err(FragmentError::LookupError)? {
queue.extend(node.parents());
}
continue;
}
match self.fragment(head, known_fragment_states, strategy) {
Ok(state) => {
queue.extend(state.boundary().keys().copied());
known_fragment_states.insert(head, state);
fresh_heads.push(head);
}
Err(FragmentError::MissingCommit(missing)) => {
tracing::debug!(%head, %missing, "skipping head with incomplete history");
}
Err(e) => return Err(e),
}
}
// Post-pass: dedupe members against transitive ancestor fragments.
//
// The BFS in `fragment()` walks parents of any shallower-depth commit,
// which in a concurrent DAG can re-enter territory that is already
// covered by a deeper ancestor fragment reached through a different
// boundary path. The inline strip at the bottom of `fragment()` only
// handles direct boundary fragments — it can't see deeper ancestors
// because they aren't in `known_fragment_states` yet (the loop above
// discovers them later). Now that every fresh fragment is built and
// the boundary chain is fully populated, strip any member that also
// appears in an ancestor's members.
//
// Regression test: `tests/build_fragment_store.rs`'s
// `members_disjoint_from_transitive_ancestor_members`.
for head in &fresh_heads {
let ancestor_members = known_fragment_states
.get(head)
.map(|state| state.transitive_ancestor_members(known_fragment_states))
.unwrap_or_default();
if ancestor_members.is_empty() {
continue;
}
if let Some(state) = known_fragment_states.get_mut(head) {
state.retain_members(|c| !ancestor_members.contains(c));
}
}
let mut fresh = Vec::with_capacity(fresh_heads.len());
for h in fresh_heads {
#[allow(clippy::expect_used)]
fresh.push(known_fragment_states.get(&h).expect("just inserted"));
}
Ok(fresh)
}
/// Parallel variant of [`build_fragment_store`](Self::build_fragment_store).
///
/// Processes each depth level of the fragment tree in parallel using
/// [rayon](https://docs.rs/rayon). Starting from the given heads, all
/// fragments at the same level are built concurrently, then their
/// boundaries become the next level's heads.
///
/// Each parallel task receives a read-only snapshot of
/// `known_fragment_states` for deduplication; newly computed states
/// are merged sequentially after each level completes.
///
/// Depth-0 commits are skipped (they are loose commits, not fragment
/// heads), but their parents are walked so deeper boundaries are found.
///
/// # Performance
///
/// For a document with _n_ changes and _k_ fragment boundaries at the
/// first level, this gives ~k-way parallelism. With
/// [`CountLeadingZeroBytes`], k ≈ n/256, so a 200k-change document
/// gets ~800-way parallelism.
///
/// # Errors
///
/// Returns a [`FragmentError`] if any lookup fails.
#[cfg(feature = "rayon")]
#[cfg_attr(docsrs, doc(cfg(feature = "rayon")))]
fn build_fragment_store_par<'b, D: DepthMetric + Sync>(
&self,
head_ids: &[CommitId],
known_fragment_states: &'b mut Map<CommitId, FragmentState<Self::Node>>,
strategy: &D,
) -> Result<Vec<&'b FragmentState<Self::Node>>, FragmentError<'a, Self>>
where
Self: Sync,
Self::Node: Send + Sync + Clone,
Self::LookupError: Send,
{
use rayon::prelude::*;
let mut all_heads: Vec<CommitId> = Vec::new();
let mut horizon = head_ids.to_vec();
while !horizon.is_empty() {
// Dedup against already-known fragments.
horizon.retain(|h| !known_fragment_states.contains_key(h));
if horizon.is_empty() {
break;
}
// Walk past depth-0 commits (loose commits, not fragment heads)
// to discover their deeper-depth parents.
{
let mut visited_d0: Set<CommitId> = Set::new();
let mut pending: Vec<CommitId> = Vec::new();
horizon.retain(|&h| {
if strategy.to_depth(h).is_boundary() {
true
} else {
if visited_d0.insert(h) {
pending.push(h);
}
false
}
});
while let Some(d) = pending.pop() {
let Some(node) = self.lookup(d).map_err(FragmentError::LookupError)? else {
continue;
};
for p in node.parents() {
if known_fragment_states.contains_key(&p) {
continue;
}
if strategy.to_depth(p).is_boundary() {
horizon.push(p);
} else if visited_d0.insert(p) {
pending.push(p);
}
}
}
}
horizon.retain(|h| !known_fragment_states.contains_key(h));
if horizon.is_empty() {
break;
}
// Parallel phase: snapshot the known states so each task can
// deduplicate members against previously computed fragments.
let snapshot: Map<CommitId, FragmentState<Self::Node>> = known_fragment_states.clone();
let level_results: Vec<Result<_, FragmentError<'a, Self>>> = horizon
.par_iter()
.filter_map(|&head| match self.fragment(head, &snapshot, strategy) {
Ok(state) => Some(Ok((head, state))),
Err(FragmentError::MissingCommit(missing)) => {
tracing::debug!(%head, %missing, "skipping head with incomplete history");
None
}
Err(e) => Some(Err(e)),
})
.collect();
// Sequential phase: merge results into known_fragment_states.
let mut successes = Vec::with_capacity(level_results.len());
for result in level_results {
successes.push(result?);
}
let mut next_horizon = Vec::new();
for (head, state) in successes {
next_horizon.extend(state.boundary().keys().copied());
all_heads.push(head);
known_fragment_states.insert(head, state);
}
horizon = next_horizon;
}
// Post-pass: dedupe members against transitive ancestor fragments.
// See the comment in `build_fragment_store` for rationale — the
// parallel variant has the same overlap pattern in concurrent DAGs.
for head in &all_heads {
let ancestor_members = known_fragment_states
.get(head)
.map(|state| state.transitive_ancestor_members(known_fragment_states))
.unwrap_or_default();
if ancestor_members.is_empty() {
continue;
}
if let Some(state) = known_fragment_states.get_mut(head) {
state.retain_members(|c| !ancestor_members.contains(c));
}
}
let mut fresh = Vec::with_capacity(all_heads.len());
for head in all_heads {
#[allow(clippy::expect_used)]
let r = known_fragment_states.get(&head).expect("just inserted");
fresh.push(r);
}
Ok(fresh)
}
}
/// `Fragment`s are a consistent unit of document history,
/// which may end before the complete history is covered.
/// In this way, a document can be broken up into a series
/// of `Fragment`s that are consistent across replicas.
///
/// This is an experimental API, the fragment API is subject to change
/// and so should not be used in production just yet.
#[derive(Debug, Clone)]
pub struct FragmentState<T> {
head_id: CommitId,
members: Set<CommitId>,
checkpoints: Set<CommitId>,
boundary: Map<CommitId, T>,
}
impl<T> FragmentState<T> {
/// Create a new `FragmentState`.
#[must_use]
pub const fn new(
head_id: CommitId,
members: Set<CommitId>,
checkpoints: Set<CommitId>,
boundary: Map<CommitId, T>,
) -> Self {
Self {
head_id,
members,
checkpoints,
boundary,
}
}
/// The "newest" element of the fragment.
///
/// This identifier provides a stable point from which
/// the rest of the fragment is built.
#[must_use]
pub const fn head_id(&self) -> CommitId {
self.head_id
}
/// All members of the fragment.
///
/// This includes all history between the `head_id`
/// and the `boundary` (not including the boundary elements).
#[must_use]
pub const fn members(&self) -> &Set<CommitId> {
&self.members
}
/// The checkpoints of the fragment.
///
/// These are all of the [`CommitId`]s that match a valid level
/// below the target, so that it is possible to know which other fragments
/// this one covers.
#[must_use]
pub const fn checkpoints(&self) -> &Set<CommitId> {
&self.checkpoints
}
/// The boundary from which the next set of fragments would be built.
#[must_use]
pub const fn boundary(&self) -> &Map<CommitId, T> {
&self.boundary
}
/// Converts into a [`Fragment`] with the given [`BlobMeta`].
///
/// # Errors
///
/// Returns an error if normalized boundary or checkpoint counts exceed wire limits.
pub fn to_fragment(
self,
sedimentree_id: SedimentreeId,
blob_meta: BlobMeta,
) -> Result<Fragment, crate::fragment::InvalidFragment> {
let checkpoints: Vec<_> = self.checkpoints.iter().copied().collect();
Fragment::new(
sedimentree_id,
self.head_id,
self.boundary.keys().copied().collect(),
&checkpoints,
blob_meta,
)
}
/// Drop any member (and checkpoint) for which `predicate` returns false.
///
/// Used by [`CommitStore::build_fragment_store`] to dedupe members
/// against transitive ancestor fragments after the full tree is built.
pub fn retain_members<F>(&mut self, mut predicate: F)
where
F: FnMut(&CommitId) -> bool,
{
self.members.retain(|c| predicate(c));
self.checkpoints.retain(|c| predicate(c));
}
/// Walk this fragment's boundary chain transitively through `known`
/// and return the union of all reachable ancestor fragments' members.
///
/// "Ancestor" here means: a fragment whose head is reachable from this
/// fragment by following `boundary` keys through fragments present in
/// `known`. Boundary keys that don't resolve to a fragment in `known`
/// (e.g. depth-0 commits beyond the deepest level) are ignored.
///
/// Used by [`CommitStore::build_fragment_store`]'s post-pass to dedupe
/// members against transitive ancestor fragments. Also intended as the
/// regression-test reference for the same invariant.
#[must_use]
pub fn transitive_ancestor_members(
&self,
known: &Map<CommitId, FragmentState<T>>,
) -> Set<CommitId> {
let mut acc: Set<CommitId> = Set::new();
let mut seen: Set<CommitId> = Set::new();
let mut to_visit: Vec<CommitId> = self.boundary.keys().copied().collect();
while let Some(b) = to_visit.pop() {
if !seen.insert(b) {
continue;
}
if let Some(anc) = known.get(&b) {
acc.extend(anc.members().iter().copied());
to_visit.extend(anc.boundary().keys().copied());
}
}
acc
}
}