From 04c0231abb91503e55d9c8c7f715f5922928b261 Mon Sep 17 00:00:00 2001 From: adamv-symbolica Date: Tue, 17 Nov 2026 14:41:15 +0000 Subject: [PATCH] Check node uniqueness in make_unique by reading the refcount make_unique took the refcount from 1 to 0 with a compare-exchange and stored 1 back when the node turned out to be unique: a locked instruction and a store to the node's first cache line every time a node the trie already owns is taken mutably. Reading the count is enough. A count of 1 seen through `&mut self` means no other reference exists, and none can appear while the borrow lasts: a reference is only ever cloned from an existing one, and there are no weak references to upgrade, which is the reason `Arc::make_mut` needs the compare-exchange. `Arc::get_mut` checks its strong count the same way, and triomphe's `Arc::make_mut`, which has no weak references either, is written exactly like this. The load stays `Acquire`, as the compare-exchange was, so it still synchronizes with the `Release` decrement of the references that were dropped. On an EPYC 9B45 (one codegen unit, 5 rounds): prune -17%, write_zipper -9%, binary_keys -7.5% with set_val_at replacing a value 43-49% faster, superdense_insert 34-48% and sparse_insert 8-27% faster, creating a zipper from a ZipperHead 12-24% faster. Threads that each write to nodes of their own through a ZipperHead are about 30% faster at every thread count from 1 to 192: 38 ns to 27 ns per write on one thread, 45 ns to 32 ns on 192. Two tests take one shared node mutably from several threads at once, which no existing test did: one on the node references themselves, one through write zippers of a ZipperHead at paths that hold grafts of the same map. Co-Authored-By: Claude Fable 5.2 --- src/trie_node.rs | 64 +++++++++++++++++++++++++++++++++++++++++++--- src/zipper_head.rs | 55 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 4 deletions(-) diff --git a/src/trie_node.rs b/src/trie_node.rs index 19b7031b..d0d20331 100644 --- a/src/trie_node.rs +++ b/src/trie_node.rs @@ -3248,7 +3248,16 @@ mod opaque_dyn_rc_trie_node { let (ptr, _tag) = self.ptr.get_raw_parts(); - if unsafe{ &*ptr }.compare_exchange(1, 0, Acquire, Relaxed).is_err() { + // A count of 1 means `self` is the only reference to the node, and it stays the only one + // for as long as it is borrowed mutably: a reference can only be cloned from one that + // exists, and there are no weak references to upgrade. So reading the count is enough, + // as `Arc::get_mut` does with its strong count, where `Arc::make_mut` has to take the + // count with a compare-exchange to hold off `Weak::upgrade`. + // + // The load is `Acquire` to synchronize with the `Release` decrement in `drop` of the + // references that are gone. Whatever their owners read from the node then happens + // before what the caller goes on to write to it. + if unsafe{ &*ptr }.load(Acquire) != 1 { #[cfg(feature = "counters")] crate::counters::record_make_unique(true); @@ -3261,9 +3270,6 @@ mod opaque_dyn_rc_trie_node { } else { #[cfg(feature = "counters")] crate::counters::record_make_unique(false); - - // We were the sole reference so bump back up the ref count. - unsafe{ &*ptr }.store(1, Release); } } #[inline] @@ -3504,4 +3510,54 @@ mod tests { drop(cloned); } + /// Threads that each hold a reference to one node take it mutably at the same time. A thread + /// gets the node itself only when every other reference to it is gone, and a copy until then, + /// so what one thread writes must never show up for another + #[test] + fn make_unique_from_many_threads() { + #[cfg(miri)] + let (rounds, thread_cnt) = (4, 3); + #[cfg(not(miri))] + let (rounds, thread_cnt) = (500, 8); + + for _ in 0..rounds { + let node = LineListNode::::new_in(global_alloc()); + let mut original = TrieNodeODRc::new_in(node, global_alloc()); + original.make_mut().node_set_val(b"k", usize::MAX).unwrap(); + let barrier = std::sync::Barrier::new(thread_cnt + 1); + let barrier = &barrier; + + let nodes: Vec> = std::thread::scope(move |scope| { + let threads: Vec<_> = (0..thread_cnt).map(|n| { + let mut node = original.clone(); + scope.spawn(move || { + barrier.wait(); + //Half of the threads move the count around first + if n % 2 == 1 { + drop(node.clone()); + } + //Nobody may write to the node while this thread refers to it + assert_eq!(node.as_tagged().node_get_val(b"k"), Some(&usize::MAX)); + node.make_mut().node_set_val(b"k", n).unwrap(); + assert_eq!(node.as_tagged().node_get_val(b"k"), Some(&n)); + node + }) + }).collect(); + + //The original is still referenced here, so every thread that is done wrote to a copy. + // Dropping it lets the last thread to arrive have the node itself + barrier.wait(); + assert_eq!(original.as_tagged().node_get_val(b"k"), Some(&usize::MAX)); + drop(original); + threads.into_iter().map(|thread| thread.join().unwrap()).collect() + }); + + for (n, node) in nodes.iter().enumerate() { + assert_eq!(node.as_tagged().node_get_val(b"k"), Some(&n)); + assert_eq!(node.refcount(), 1); + assert!(nodes[..n].iter().all(|other| !other.ptr_eq(node))); + } + } + } + } diff --git a/src/zipper_head.rs b/src/zipper_head.rs index 16830ede..b5b59214 100644 --- a/src/zipper_head.rs +++ b/src/zipper_head.rs @@ -561,6 +561,61 @@ mod tests { } } + /// Every thread writes below a path of its own, but the subtries at those paths are grafts of + /// one map, so the threads meet at the nodes the grafts still have in common. A thread may + /// write to such a node in place only when it is the last one referring to it, and has to + /// copy it until then + #[test] + fn parallel_writes_to_shared_subtries_test() { + #[cfg(miri)] + let (rounds, elements) = (1, 24); + #[cfg(not(miri))] + let (rounds, elements) = (20, 1024); + + let thread_cnt = 8; + + for _ in 0..rounds { + let mut source = PathMap::::new(); + for i in 0..elements { + source.set_val_at(prefix_key(&(i as u64)), i); + } + let mut map = PathMap::::new(); + for n in 0..thread_cnt { + map.write_zipper_at_path(&[n as u8]).graft_map(source.clone()); + } + //With the source gone, the grafts are the only owners of the nodes they share + drop(source); + + let zipper_head = map.zipper_head(); + thread::scope(|scope| { + let zippers: Vec<_> = (0..thread_cnt).map(|n| { + zipper_head.write_zipper_at_exclusive_path(&[n as u8]).unwrap() + }).collect(); + + for (n, mut zipper) in zippers.into_iter().enumerate() { + scope.spawn(move || { + for i in 0..elements { + zipper.descend_to(prefix_key(&(i as u64))); + assert_eq!(zipper.set_val(n * elements + i), Some(i)); + zipper.reset(); + } + }); + } + }); + drop(zipper_head); + + //Each graft has the values its thread wrote, and nothing from another thread + assert_eq!(map.val_count(), thread_cnt * elements); + for n in 0..thread_cnt { + for i in 0..elements { + let mut path = vec![n as u8]; + path.extend(prefix_key(&(i as u64))); + assert_eq!(map.val_at(path), Some(&(n * elements + i))); + } + } + } + } + #[test] fn parallel_copy_values_test() { #[cfg(miri)]