Skip to main content

agentmux_srv_core/backend/blockcontroller/
resync_lock.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One resync of a block at a time. `resync_controller` looks the block's controller up, decides, and
5//! then creates and starts one; two of them for the same block at once both saw "no controller, or one
6//! still in `init`" and both started it. Seen on a fresh Muse install: a forced resync and an ordinary
7//! one 74 ms apart spawned `muse serve` twice, 28 ms apart, and the first process was thrown away.
8
9use std::collections::HashSet;
10use std::sync::{Condvar, Mutex};
11
12static BUSY: Mutex<Option<HashSet<String>>> = Mutex::new(None);
13static FREED: Condvar = Condvar::new();
14
15/// Held for the length of one resync of a block; the next resync of that block waits for it.
16pub(super) struct ResyncGuard(String);
17
18impl ResyncGuard {
19    pub(super) fn acquire(block_id: &str) -> Self {
20        let mut busy = BUSY.lock().unwrap_or_else(|e| e.into_inner());
21        while busy.get_or_insert_with(HashSet::new).contains(block_id) {
22            busy = FREED.wait(busy).unwrap_or_else(|e| e.into_inner());
23        }
24        busy.get_or_insert_with(HashSet::new).insert(block_id.to_string());
25        Self(block_id.to_string())
26    }
27}
28
29impl Drop for ResyncGuard {
30    fn drop(&mut self) {
31        let mut busy = BUSY.lock().unwrap_or_else(|e| e.into_inner());
32        if let Some(set) = busy.as_mut() {
33            set.remove(&self.0);
34        }
35        FREED.notify_all();
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42    use std::sync::atomic::{AtomicUsize, Ordering};
43    use std::sync::Arc;
44
45    #[test]
46    fn two_resyncs_of_one_block_never_overlap_and_two_blocks_do() {
47        let (inside, worst) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
48        let threads: Vec<_> = (0..8)
49            .map(|_| {
50                let (inside, worst) = (inside.clone(), worst.clone());
51                std::thread::spawn(move || {
52                    let _g = ResyncGuard::acquire("resync-lock-same");
53                    let now = inside.fetch_add(1, Ordering::SeqCst) + 1;
54                    worst.fetch_max(now, Ordering::SeqCst);
55                    std::thread::sleep(std::time::Duration::from_millis(5));
56                    inside.fetch_sub(1, Ordering::SeqCst);
57                })
58            })
59            .collect();
60        threads.into_iter().for_each(|t| t.join().unwrap());
61        assert_eq!(worst.load(Ordering::SeqCst), 1, "one block, one resync at a time");
62
63        // A different block is not held up by the first one.
64        let held = ResyncGuard::acquire("resync-lock-a");
65        let other = std::thread::spawn(|| drop(ResyncGuard::acquire("resync-lock-b")));
66        other.join().unwrap();
67        drop(held);
68        drop(ResyncGuard::acquire("resync-lock-a")); // free again once released
69    }
70}