Skip to content

Commit 3bb82f0

Browse files
committed
PartialJoin trait abstracting fallible merge operations
PartialJoin<V>::try_join returns JoinResult<V>, either Ok(v), where v the least upper bound, or a Err(Conflict<V>) where the conflict contains values that could not be joined. Conflict<V> is a multiset with set-equality semantics (order-independent). It implements JoinMut to merge conflict sets (union of distinct values). JoinResult<V> itself implements Join: (Ok(a), Ok(b)) => a.try_join(b) (delegate to PartialJoin on V) (Ok(v), Err(c)) => Err(c ∪ {v}) (absorb into conflict) (Err(c), Ok(v)) => Err(c ∪ {v}) (absorb into conflict) (Err(a), Err(b)) => Err(a ∪ b) (join conflict sets) Containers or product types that wrap their fields in JoinResult<V> can implement Join recursively to compute the field-by-field merge without early exit. assert_partial_join_laws! is a crate-internal macro (gated behind prop-tests feature, scoped via #[macro_use]). Given clean-value and result strategies, it generates try_join law tests, JoinResult law tests (via assert_join_laws!), and a wrap roundtrip test. ## Rationale for Conflict as flat, order preserving & order insensitive Conflicts represent a formal completion of the partial semilattice `V : PartialJoin`. If `a` and `b` are conflicts, commutativity requires that `a.join(b) == b.join(a)`, and idempotence requires that `a.join(a) == a`. This is somewhat at odds with keeping track of where each conflicting value originated from. The main purpose of preserving the order is to allow provenance to be tracked. If `a` and `b` are both conflict free, and `let c = a.join(b)`, then `c.conflicted_field.len() == 2` and the first value is from `a` whereas the second is from `b`, which makes reporting this as an error with clear diagnostics easier, without requiring the provenance be tracked by some kind of surrogate ID. This does not generalize to n > 2, because if `a.join(b).join(c).some_conflicted_field.len() == 2`, the values could originate from `(a, b)`, `(b, c)`, or `(a, c)`. This compromise keeps the interface and implementation simple, allows provenance to be tracked as long as it's done one pair of values at a time in a straightforward way, but imposes no additional burdens on users that do not care about provenance (for instance if computing something like `vs.reduce(|a, b| a.join(b))`) ### Alternatives considered Several alternative approaches were tried, of which the compromise of making `Conflict` just a thin wrapper around Vec seemed the best. #### HashSet or BTreeSet based This alternative is very close to what is implemented. The differences are that with a Vec, the order is preserved, the implementation of equality and `join` has quadratic complexity. We expect `n` to be very small so this shouldn't make a difference in practice. Using a lookup based set requires `V : Hash` or `V : Ord` which the current `Conflict` does not require (unfortunately adding it later would be semver breaking, as would be changing the return value from `iter()` or the associated `IntoIter` type of the `IntoIterator` impl). #### Recursive data type The following definition could in principle shadow the `join` structure: ```rs enum Conflict<V> { Value(V), Pair([Box<Conflict>; 2]) } ``` In this case, if `a.join(b).join(c.join(d))` has 4 conflicting values, they would take the form `Pair([ Pair([ Value(x), Value(y) ]), Pair([ Value(z), Value(w) ]) ])`, which is arguably more informative. Unfortunately this is still imprecise because if `a.join(b).join(c)` has a binary conflict `Pair([ Value(x), Value(y) ])`, it's still ambiguous in the same way. In order for this approach to be workable it has to shadow the syntax tree of the join operation for the Ok branch too, in which case this entire abstraction kind of only computing the transpose, going from e.g. a list of structs with values, to a struct of lists of values, but not reducing any of the complexity unless there are no conflicts anywhere. The purpose of these abstractions is to take the problem of merging two or more compound values into the a series of simpler problems, merging two or more elements of a simpler type. Tracking provenance with perfect fidelity means that if there is any conflict the structure is not simplified at all. #### n-ary join The final option considered was defining join not as a binary operation but n-ary. This is no different than ### Associated error type or generics The above alternatives imply a "one size fits all" approach. However, PartialJoin could have an Error type, where `JoinResult<V> = Result<V, <V as PartialJoin>::Error>`. Ostensibly this would allow some choice, but with associated types the choice is fixed per implementation of the trait and so would not afford users the choice of whether to opt out of provenance tracking for simpler errors or opt in and deal with the added complexity. Making the error type fully generic would make that possible with even more complexity and syntactic overhead. However, no generality would be gained for this additional complexity. Thinking of Conflict<V> as just "deferred arguments for a join" (i.e. a formal product), any arbitrary merge operation can be expressed by just taking those arguments. More formally, Conflict<V> is the free semilattice (sets under union) over V. Since every semilattice is a quotient of the free semilattice, so there is no operation that can be expressed by setting Error to some type that merges V's according to some rules (e.g. taking the max of integers) that can't be expressed by simply processing the conflict after the fact. ### Conclusion For these reasons, making Conflict a thin wrapper around `Vec` seems like the best compromise: has the same expressive power but results in a simpler interface than all the alternatives, and makes provenance tracking possible and even relatively straightforward without forcing it on all users.
1 parent 7d43a52 commit 3bb82f0

3 files changed

Lines changed: 385 additions & 0 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
#[macro_use]
22
pub mod join;
3+
#[macro_use]
4+
pub mod partial;
Lines changed: 382 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,382 @@
1+
//! Some types have a natural merge operation but that isn't defined for all pairs of values.
2+
//! [`PartialJoin::try_join`] captures this.
3+
//!
4+
//! It returns [`JoinResult<V>`], an alias for `Result<V, Conflict<V>>`, where [`Conflict<V>`],
5+
//! collects all the distinct values that couldn't be merged.
6+
//!
7+
//! [`JoinResult<V>`] implements [`Join`], which is an infallible join operation (the free
8+
//! semilattice over `V`, more or less), in terms of [`Conflict<V>`]'s [`Join`] implementation.
9+
10+
use crate::lattice::join::{Join, JoinMut};
11+
12+
/// Fallible join for scalar value types where merge may produce a conflict.
13+
///
14+
/// Containers should not implement this, instead they should implement [`Join`] by wrapping
15+
/// contained values in [`JoinResult`].
16+
pub trait PartialJoin: Sized + PartialEq {
17+
/// Attempt to join two values.
18+
///
19+
/// Returns `Ok(lub)` where `lub` is the least upper bound if one exists, or `Err(Conflict)`
20+
/// containing both values.
21+
///
22+
/// Although `Conflict<V>` has set semantics (equality treats it as an unordered collection),
23+
/// insertion order is preserved during iteration: when two `Ok` values are joined and produce
24+
/// a binary conflict, the first value is the left operand and the second is the right.
25+
///
26+
/// Provenance is only reliable when both operands were `Ok` before the join. When an existing
27+
/// `Conflict` is joined with another value, new entries are appended, so a multi-way fold does
28+
/// not preserve per-operand attribution.
29+
fn try_join(self, other: Self) -> JoinResult<Self>;
30+
31+
/// Lift a value into the result domain as `Ok(self)`.
32+
fn wrap(self) -> JoinResult<Self> {
33+
Ok(self)
34+
}
35+
}
36+
37+
/// Result of a fallible join: `Ok(v)` where `v` is the least upper bound if one exists,
38+
/// `Err(Conflict)` otherwise.
39+
///
40+
/// `JoinResult<V>` implements [`Join`].
41+
pub type JoinResult<V> = Result<V, Conflict<V>>;
42+
43+
impl<V> Join for JoinResult<V>
44+
where
45+
V: PartialJoin,
46+
{
47+
fn join(self, other: Self) -> Self {
48+
match (self, other) {
49+
(Ok(a), Ok(b)) => a.try_join(b),
50+
(Err(a), Err(b)) => Err(a.join(b)),
51+
(Err(a), Ok(b)) => Err(a.join(Conflict::singleton(b))),
52+
(Ok(a), Err(b)) => Err(Conflict::singleton(a).join(b)),
53+
}
54+
}
55+
}
56+
57+
/// A set of conflicting values, produced when a join for those values does not exist.
58+
///
59+
/// When two participants set the same field to different values, neither can be chosen without
60+
/// losing information. `Conflict` preserves the set of distinct conflicting values allowing the
61+
/// caller to inspect or resolve the disagreement.
62+
///
63+
/// The inner values are [`PartialJoin`] with equality based on [`PartialEq`]. Duplicate values
64+
/// are omitted.
65+
#[derive(Debug, Clone)]
66+
pub struct Conflict<V: PartialJoin>(Vec<V>);
67+
68+
impl<V: PartialJoin> Conflict<V> {
69+
/// Wrap a single value into a conflict.
70+
fn singleton(v: V) -> Self {
71+
Self(vec![v])
72+
}
73+
74+
/// Build from an iterator, deduplicating values.
75+
#[allow(dead_code)] // production caller: tspwkqxz (values.rs IdempotentValue::try_join)
76+
pub(crate) fn from_values(iter: impl IntoIterator<Item = V>) -> Self {
77+
let mut vals = Vec::new();
78+
for v in iter {
79+
if !vals.contains(&v) {
80+
vals.push(v);
81+
}
82+
}
83+
Self(vals)
84+
}
85+
86+
/// Iterates over references to the conflicted values.
87+
fn iter(&self) -> std::slice::Iter<'_, V> {
88+
self.0.iter()
89+
}
90+
91+
/// Number of distinct conflicting values.
92+
pub fn len(&self) -> usize {
93+
self.0.len()
94+
}
95+
96+
pub fn is_empty(&self) -> bool {
97+
self.0.is_empty()
98+
}
99+
}
100+
101+
impl<V: PartialJoin> JoinMut for Conflict<V> {
102+
fn join_mut(&mut self, other: Self) {
103+
for value in other.0 {
104+
if !self.0.contains(&value) {
105+
self.0.push(value)
106+
}
107+
}
108+
}
109+
}
110+
111+
/// Set equality: same elements, regardless of order.
112+
///
113+
/// $O(n^2)$ but $n$ is tiny in practice (typically 2).
114+
impl<V: PartialJoin> PartialEq for Conflict<V> {
115+
fn eq(&self, other: &Self) -> bool {
116+
self.0.len() == other.0.len() && self.iter().all(|v| other.0.contains(v))
117+
}
118+
}
119+
120+
impl<V: PartialJoin + Eq> Eq for Conflict<V> {}
121+
122+
impl<V: PartialJoin> IntoIterator for Conflict<V> {
123+
type Item = V;
124+
type IntoIter = std::vec::IntoIter<V>;
125+
126+
fn into_iter(self) -> Self::IntoIter {
127+
self.0.into_iter()
128+
}
129+
}
130+
131+
impl<'a, V: PartialJoin> IntoIterator for &'a Conflict<V> {
132+
type Item = &'a V;
133+
type IntoIter = std::slice::Iter<'a, V>;
134+
135+
fn into_iter(self) -> Self::IntoIter {
136+
self.iter()
137+
}
138+
}
139+
140+
/// Proptest macros for verifying `PartialJoin` laws and the `JoinResult` completion. Available
141+
/// when `prop-tests` feature is enabled.
142+
///
143+
/// # `assert_partial_join_laws!($arb_clean, $arb_result)`
144+
///
145+
/// Generates:
146+
/// - `try_join` laws on clean values: idempotent, commutative, associative (via wrap/join)
147+
/// - `JoinResult` laws on pre-built Ok/Err values: idempotent, commutative, associative
148+
/// - `wrap_roundtrip`: wrapping a clean value always produces `Ok`
149+
///
150+
/// The `$arb_clean` strategy produces clean (pre-join) values.
151+
/// The `$arb_result` strategy produces `JoinResult` values (both Ok and Err).
152+
#[cfg(feature = "prop-tests")]
153+
#[allow(unused_macros)] // used by downstream commits (collection modules, domain types)
154+
macro_rules! assert_partial_join_laws {
155+
($arb_clean:expr, $arb_result:expr) => {
156+
proptest! {
157+
#[test]
158+
fn try_join_idempotent(a in $arb_clean) {
159+
prop_assert_eq!(a.clone().try_join(a.clone()), Ok(a));
160+
}
161+
162+
#[test]
163+
fn try_join_commutative(a in $arb_clean, b in $arb_clean) {
164+
prop_assert_eq!(a.clone().try_join(b.clone()), b.try_join(a));
165+
}
166+
167+
#[test]
168+
fn try_join_associative(a in $arb_clean, b in $arb_clean, c in $arb_clean) {
169+
prop_assert_eq!(
170+
a.clone().try_join(b.clone()).join(c.clone().wrap()),
171+
a.wrap().join(b.try_join(c)),
172+
);
173+
}
174+
175+
#[test]
176+
fn wrap_roundtrip(a in $arb_clean) {
177+
let wrapped = a.clone().wrap();
178+
prop_assert!(wrapped.is_ok());
179+
prop_assert_eq!(wrapped.expect("should be Ok"), a);
180+
}
181+
}
182+
183+
mod join_result {
184+
use super::*;
185+
assert_join_laws!($arb_result);
186+
}
187+
};
188+
}
189+
190+
#[cfg(all(test, any(feature = "unit-tests", feature = "prop-tests")))]
191+
#[cfg_attr(coverage_nightly, coverage(off))]
192+
mod tests {
193+
use super::*;
194+
195+
#[derive(Debug, Clone, Copy, PartialEq)]
196+
struct Foo(u8);
197+
198+
impl PartialJoin for Foo {
199+
fn try_join(self, other: Self) -> JoinResult<Self> {
200+
if self == other {
201+
Ok(self)
202+
} else {
203+
Err(Conflict::from_values([self, other]))
204+
}
205+
}
206+
}
207+
208+
#[cfg(feature = "unit-tests")]
209+
mod unit {
210+
use super::*;
211+
212+
#[test]
213+
fn result_ok_ok_different_produces_conflict() {
214+
assert_eq!(
215+
Foo(0).wrap().join(Foo(1).wrap()),
216+
Err(Conflict(vec![Foo(0), Foo(1)])),
217+
);
218+
}
219+
220+
#[test]
221+
fn result_err_ok_absorbs() {
222+
let err: JoinResult<Foo> = Err(Conflict(vec![Foo(0), Foo(1)]));
223+
assert_eq!(
224+
err.join(Ok(Foo(2))),
225+
Err(Conflict(vec![Foo(0), Foo(1), Foo(2)]))
226+
);
227+
}
228+
229+
#[test]
230+
fn result_ok_err_absorbs() {
231+
let err: JoinResult<Foo> = Err(Conflict(vec![Foo(0), Foo(1)]));
232+
assert_eq!(
233+
Ok(Foo(2)).join(err),
234+
Err(Conflict(vec![Foo(2), Foo(0), Foo(1)]))
235+
);
236+
}
237+
238+
#[test]
239+
fn result_err_err_merges_conflicts() {
240+
let a: JoinResult<Foo> = Err(Conflict(vec![Foo(0), Foo(1)]));
241+
let b: JoinResult<Foo> = Err(Conflict(vec![Foo(1), Foo(2)]));
242+
assert_eq!(a.join(b), Err(Conflict(vec![Foo(0), Foo(1), Foo(2)])));
243+
}
244+
245+
#[test]
246+
fn different_conflicts_are_not_equal() {
247+
let a = Conflict::from_values([Foo(0), Foo(1)]);
248+
let b = Conflict::from_values([Foo(0), Foo(2)]);
249+
assert_ne!(a, b);
250+
}
251+
252+
#[test]
253+
fn different_length_conflicts_are_not_equal() {
254+
let a = Conflict::from_values([Foo(0), Foo(1)]);
255+
let b = Conflict::from_values([Foo(0), Foo(1), Foo(2)]);
256+
assert_ne!(a, b);
257+
}
258+
259+
#[test]
260+
fn conflict_from_equal_pair_deduplicates() {
261+
let c = Conflict::from_values([Foo(0), Foo(0)]);
262+
assert_eq!(c.len(), 1);
263+
}
264+
265+
#[test]
266+
fn len_distinct_values() {
267+
let c = Conflict::from_values([Foo(0), Foo(1)]);
268+
assert_eq!(c.len(), 2);
269+
}
270+
271+
#[test]
272+
fn is_empty() {
273+
assert!(Conflict::<Foo>::from_values([]).is_empty());
274+
assert!(!Conflict::from_values([Foo(0)]).is_empty());
275+
}
276+
277+
#[test]
278+
fn into_iter_yields_elements() {
279+
let c = Conflict::from_values([Foo(0), Foo(1)]);
280+
let v: Vec<_> = c.into_iter().collect();
281+
assert_eq!(v, vec![Foo(0), Foo(1)]);
282+
}
283+
284+
#[test]
285+
fn borrowed_iteration() {
286+
let c = Conflict::from_values([Foo(0), Foo(1)]);
287+
let v: Vec<_> = (&c).into_iter().collect();
288+
assert_eq!(v, vec![&Foo(0), &Foo(1)]);
289+
}
290+
291+
#[test]
292+
fn conflict_preserves_order() {
293+
let x = Conflict::from_values([Foo(0)]);
294+
let y = Conflict::from_values([Foo(1)]);
295+
296+
let xy = x.clone().join(y.clone());
297+
let yx = y.clone().join(x.clone());
298+
299+
assert_eq!(xy, yx);
300+
assert_ne!(xy.iter().collect::<Vec<_>>(), yx.iter().collect::<Vec<_>>());
301+
assert_ne!(
302+
xy.into_iter().collect::<Vec<_>>(),
303+
yx.into_iter().collect::<Vec<_>>()
304+
);
305+
}
306+
}
307+
308+
// Small domain (4 values): high collision rate exercises the
309+
// equal-value (Ok) path while still covering the conflict (Err) path.
310+
#[cfg(feature = "prop-tests")]
311+
mod prop {
312+
use super::*;
313+
use proptest::prelude::*;
314+
315+
pub fn arb_foo() -> impl Strategy<Value = Foo> {
316+
(0u8..4).prop_map(Foo)
317+
}
318+
319+
/// Generate a JoinResult<Foo> which is either Ok(v) or Err(Conflict) with 1–5 values.
320+
/// Exercises all arms of JoinResult::join.
321+
pub fn arb_join_result() -> impl Strategy<Value = JoinResult<Foo>> {
322+
prop_oneof![
323+
arb_foo().prop_map(Ok),
324+
proptest::collection::vec(arb_foo(), 1..=5)
325+
.prop_map(|v| Err(Conflict::from_values(v))),
326+
]
327+
}
328+
329+
assert_partial_join_laws!(arb_foo(), arb_join_result());
330+
331+
proptest! {
332+
#[test]
333+
fn conflict_into_iter_roundtrips(a in arb_foo(), b in arb_foo()) {
334+
let c = Conflict::from_values([a, b]);
335+
let vals = c.clone().into_iter();
336+
let rebuilt = Conflict::from_values(vals);
337+
prop_assert_eq!(c, rebuilt);
338+
}
339+
340+
#[test]
341+
fn borrowed_iter_matches_owned(a in arb_foo(), b in arb_foo()) {
342+
let c = Conflict::from_values([a, b]);
343+
let owned: Vec<_> = c.clone().into_iter().collect();
344+
let borrowed: Vec<_> = (&c).into_iter().copied().collect();
345+
prop_assert_eq!(owned, borrowed);
346+
}
347+
348+
#[test]
349+
fn len_matches_iter_count(a in arb_foo(), b in arb_foo(), c in arb_foo()) {
350+
let conflict = Conflict::from_values([a, b, c]);
351+
prop_assert_eq!(conflict.len(), conflict.into_iter().count());
352+
}
353+
354+
#[test]
355+
fn non_empty_after_construction(a in arb_foo()) {
356+
let c = Conflict::from_values([a]);
357+
prop_assert!(!c.is_empty());
358+
}
359+
360+
#[test]
361+
fn empty_from_empty(a in arb_foo()) {
362+
let _ = a; // use the parameter to satisfy proptest
363+
let c = Conflict::<Foo>::from_values([]);
364+
prop_assert!(c.is_empty());
365+
prop_assert_eq!(c.len(), 0);
366+
}
367+
368+
#[test]
369+
fn conflict_different_lengths_not_equal(
370+
a in arb_foo(),
371+
b in arb_foo(),
372+
c in arb_foo(),
373+
) {
374+
let short = Conflict::from_values([a, b]);
375+
let long = Conflict::from_values([a, b, c]);
376+
if short.len() != long.len() {
377+
prop_assert_ne!(short, long);
378+
}
379+
}
380+
}
381+
}
382+
}

crates/concurrent-psbt/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@
66
mod lattice;
77

88
pub use lattice::join::{Join, JoinMut};
9+
pub use lattice::partial::{Conflict, JoinResult, PartialJoin};

0 commit comments

Comments
 (0)