Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 159 additions & 1 deletion pkgs/id/src/tag_claims.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@
//!
//! Two folds give the live claims. [`live_claims`] walks the causal past of each clear. It is the
//! reference. [`compacted_claims`] makes one pass over the parent links and keeps, for each event,
//! only the live claims in its past. Both give the same result (P5.3, #184). An applied list
//! only the live claims in its past. Both give the same result (P5.3, #184) — including on a
//! cyclic `parents` graph, where the one-pass fold cannot order events after their parents:
//! [`compacted_claims`] detects a cycle and falls back to the reference computation for the
//! whole input rather than answer by iteration order (#6709). A cycle cannot arise from the
//! store — an event's ID is a hash of bytes that name its parents — so the fallback is a
//! contract guarantee for out-of-contract inputs, not a production path. An applied list
//! may repeat an event ID — a verbatim duplicate, or two entries with the same ID and
//! different contents; both folds keep only the last entry for an ID, so the agreement
//! holds on those inputs too (#4359).
Expand Down Expand Up @@ -232,6 +237,50 @@ pub fn live_claims(applied: &[Applied], parents: &HashMap<Hash, Vec<Hash>>) -> V
.collect()
}

/// Whether the `parents` graph contains a directed cycle (a self-loop counts).
/// Iterative three-color depth-first search over every node the graph names —
/// keys and the events they name alike. Deterministic: the answer is a property
/// of the graph, never of iteration order.
fn parents_have_cycle(parents: &HashMap<Hash, Vec<Hash>>) -> bool {
const UNVISITED: u8 = 0;
const OPEN: u8 = 1;
const DONE: u8 = 2;
let mut color: HashMap<Hash, u8> = HashMap::new();
let mut nodes: Vec<Hash> = parents.keys().copied().collect();
for named in parents.values() {
nodes.extend(named.iter().copied());
}
for start in nodes {
if color.get(&start).copied().unwrap_or(UNVISITED) != UNVISITED {
continue;
}
let mut stack = vec![(start, false)];
while let Some((id, closing)) = stack.pop() {
if closing {
color.insert(id, DONE);
continue;
}
match color.get(&id).copied().unwrap_or(UNVISITED) {
DONE => continue,
OPEN => return true,
_ => {}
}
color.insert(id, OPEN);
stack.push((id, true));
if let Some(named) = parents.get(&id) {
for parent in named {
match color.get(parent).copied().unwrap_or(UNVISITED) {
OPEN => return true,
DONE => {}
_ => stack.push((*parent, false)),
}
}
}
}
}
false
}

/// The live claims, folded in one pass over the parent links (P5.3, #184).
///
/// Each event gets the set of live claims in its causal past, including itself. The set of an
Expand All @@ -245,8 +294,19 @@ pub fn live_claims(applied: &[Applied], parents: &HashMap<Hash, Vec<Hash>>) -> V
/// ID — exactly as [`live_claims`] collapses repeats when it inserts into its map.
/// The walk for a clear is over the live claims in its parents' sets, not over its whole past. A clear from an author who
/// had not seen a claim leaves that claim live, as [`live_claims`] does.
///
/// Cyclic `parents` graphs are the one input the one-pass fold cannot order: whichever of a
/// set/clear pair a depth-first walk folds second would decide the result, so the answer
/// would depend on `HashMap` iteration order. A cycle is detected up front and the whole
/// input is folded by [`live_claims`] instead (#6709) — the equivalence is then by
/// construction, and deterministic. Cycles cannot arise from the store (an event ID is a
/// hash of the bytes naming its parents), so this costs one O(V + E) scan per call and the
/// fallback itself never runs on store inputs.
#[must_use]
pub fn compacted_claims(applied: &[Applied], parents: &HashMap<Hash, Vec<Hash>>) -> Vec<Claim> {
if parents_have_cycle(parents) {
return live_claims(applied, parents);
}
let by_id: HashMap<Hash, &Applied> = applied.iter().map(|event| (event.id, event)).collect();
// The live claims in each event's causal past, including the event if it is a live claim.
let mut live_past: HashMap<Hash, HashSet<Hash>> = HashMap::new();
Expand Down Expand Up @@ -479,6 +539,104 @@ mod tests {
assert_eq!(live, live_claims(&applied, &parents));
}

#[test]
fn test_the_compacted_fold_agrees_on_the_two_cycle_repro() {
// #6709: set 1, clear 2 naming 1, parents 1 -> [2], 2 -> [1].
// The reference removes the claim: 1 is in 2's causal past through
// the cycle. The compacted fold must agree, deterministically —
// before the fix its answer flipped with HashMap iteration order.
let applied = [set(1, 9, "city"), clear(2, &[1])];
let parents: HashMap<Hash, Vec<Hash>> =
HashMap::from([(hash(1), vec![hash(2)]), (hash(2), vec![hash(1)])]);
for _ in 0..16 {
assert!(compacted_claims(&applied, &parents).is_empty());
assert_eq!(
compacted_claims(&applied, &parents),
live_claims(&applied, &parents)
);
}
}

#[test]
fn test_the_compacted_fold_agrees_on_self_loops() {
// A self-loop on the set, and one on the clear: both are cycles,
// both folds must agree on each.
let applied = [set(1, 9, "city"), clear(2, &[1])];
let set_loop: HashMap<Hash, Vec<Hash>> =
HashMap::from([(hash(1), vec![hash(1)]), (hash(2), vec![hash(1)])]);
assert_eq!(
compacted_claims(&applied, &set_loop),
live_claims(&applied, &set_loop)
);
assert!(compacted_claims(&applied, &set_loop).is_empty());
let clear_loop: HashMap<Hash, Vec<Hash>> =
HashMap::from([(hash(1), vec![]), (hash(2), vec![hash(2), hash(1)])]);
assert_eq!(
compacted_claims(&applied, &clear_loop),
live_claims(&applied, &clear_loop)
);
assert!(compacted_claims(&applied, &clear_loop).is_empty());
}

#[test]
fn test_the_folds_agree_over_generated_graphs() {
// Property test with `live_claims` as the oracle (the repo's
// testing doctrine: every automated test names its oracle).
// The signed-history proptest in tests/tag_claims.rs can only
// generate DAGs; this generator builds raw parents graphs —
// cycles, self-loops, duplicate parent entries, nodes named but
// never applied — plus applied lists with duplicate IDs, the
// shapes #4359 and #6709 are about. A fixed seed keeps the run
// deterministic; 2000 graphs of up to 8 nodes.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
self.0 = x;
x
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
}
let mut rng = Rng(0x6709_184_4359);
for case in 0..2000 {
let n = 1 + rng.below(8) as u8;
let mut parents: HashMap<Hash, Vec<Hash>> = HashMap::new();
for id in 1..=n {
let edges = (0..rng.below(4))
.map(|_| hash(1 + rng.below(u64::from(n)) as u8))
.collect::<Vec<_>>();
parents.insert(hash(id), edges);
}
let mut applied: Vec<Applied> = Vec::new();
for id in 1..=n {
match rng.below(3) {
0 => applied.push(set(id, 9, "city")),
1 => {
let claims: Vec<u8> = (0..rng.below(3))
.map(|_| 1 + rng.below(u64::from(n)) as u8)
.collect();
applied.push(clear(id, &claims));
}
_ => {}
}
// Occasional verbatim duplicate / same-ID second entry.
if rng.below(4) == 0 {
applied.push(set(id, 9, "city"));
}
}
assert_eq!(
compacted_claims(&applied, &parents),
live_claims(&applied, &parents),
"folds diverged on generated graph case {case} (seed 0x6709_184_4359, n={n})"
);
}
}

#[test]
fn test_same_id_entries_with_different_operations_fold_as_the_last() {
// #4359: a repeated ID carrying a different operation is still one event:
Expand Down
Loading