From 1a20d58eec35e3ee695be9ef36a7653ec6406ceb Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Sat, 31 Oct 2026 15:11:51 -0700 Subject: [PATCH] test(backend): registering drops nothing; a replaced handle is dropped by the caller Pins the cost rule the macOS fix depends on: Registry::insert of a new id runs no handle's drop, a replaced handle is handed back and dropped only when the caller drops it, get drops nothing, and remove hands the handle back. A probe handle counts its drops. Verified: native cargo test -p komorebi-backend: 40 unit, 7 doc, 1 compile_fail passed, 0 failed. --- crates/komorebi-backend/src/registry.rs | 40 ++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/crates/komorebi-backend/src/registry.rs b/crates/komorebi-backend/src/registry.rs index aae9940c..402985f1 100644 --- a/crates/komorebi-backend/src/registry.rs +++ b/crates/komorebi-backend/src/registry.rs @@ -78,7 +78,9 @@ impl Registry { /// if the id was registered: the caller drops it, with no lock held. #[must_use = "drop the replaced handle yourself: it is not dropped under the lock"] pub fn insert(&self, id: WindowId, pid: i32, handle: H) -> Option { - self.lock().insert(id, Entry { pid, handle }).map(|e| e.handle) + self.lock() + .insert(id, Entry { pid, handle }) + .map(|e| e.handle) } /// Replaces the handle of a window that is registered, keeping its pid. Returns the old @@ -285,6 +287,42 @@ mod tests { assert!(registry.is_empty()); } + /// Registering must not run the drop of any handle: macOS handles do Accessibility calls when + /// they are dropped, and registration happens on the event thread under the window manager lock. + #[test] + fn registering_a_new_id_drops_nothing_and_a_replaced_handle_only_when_the_caller_drops_it() { + let registry = Arc::new(Registry::new()); + let drops = Arc::new(AtomicUsize::new(0)); + let probe = || { + Arc::new(Probe { + registry: registry.clone(), + drops: drops.clone(), + }) + }; + + let replaced = registry.insert(id(1), 10, probe()); + assert!(replaced.is_none()); + assert_eq!(drops.load(Ordering::SeqCst), 0); + + let replaced = registry.insert(id(1), 10, probe()); + assert_eq!( + drops.load(Ordering::SeqCst), + 0, + "the old handle is handed back, not dropped" + ); + + drop(replaced); + assert_eq!(drops.load(Ordering::SeqCst), 1); + + // a lookup clones the Arc and drops nothing + let found = registry.get(id(1)).unwrap(); + drop(found); + assert_eq!(drops.load(Ordering::SeqCst), 1); + + drop(registry.remove(id(1))); + assert_eq!(drops.load(Ordering::SeqCst), 2); + } + #[test] fn many_threads_can_register_look_up_and_remove() { let r = Arc::new(Registry::new());