Skip to main content

agentmux_srv_core/registry/
leases.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Cross-process session-ownership leases — at most one live process
5//! may drive turns for a given agent `instance_id` at a time.
6//!
7//! Sibling of [`super::store::Registry`] but deliberately a separate
8//! file tree (`<registry_root>/leases/<instance_id>.{lease.json,lock,epoch}`),
9//! not new fields on [`super::schema::NamedAgentRecordV1`]:
10//! `Registry::upsert` is a blind read-modify-write (cross-process
11//! safety comes only from atomic rename, no compare-and-swap — see
12//! that module's doc comment), which is fine for the registry's own
13//! last-writer-wins semantics but wrong for a lock, where "I thought
14//! nobody held it" must be an atomic check.
15//!
16//! `claim`/`renew`/`release`/`verify` each hold a real, blocking,
17//! per-`instance_id` OS advisory lock (`flock` on Unix, `LockFileEx` on
18//! Windows — same primitive family already used for single-instance
19//! enforcement in `backend::base::MuxLock` and
20//! `agentmux-launcher::second_instance`, just scoped per-lease instead of
21//! globally) for the short duration of the call, not across calls. An
22//! earlier draft tried to get away with pure atomic-rename/create-if-not-
23//! exists tricks and no real lock; it had two real, independently-
24//! discovered races (a create-then-write window a concurrent claimer could
25//! observe as "corrupt" and evict, and a check-then-write TOCTOU in renew
26//! that could clobber a new owner) — a real critical section is simpler
27//! AND correct, where the lock-free version was neither.
28//!
29//! Since `SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24.md` Phase 1 the key is
30//! the agent UID and interactive (persistent) panes hold a lease for as long
31//! as their CLI process lives, not just the subprocess controller per turn.
32//! That spec's review added three rules this module enforces:
33//!
34//! - **Fail closed on an unreadable lease.** A lease file that doesn't parse
35//!   proves nothing about its holder. It stays held until nobody has
36//!   rewritten it for a full TTL (a live holder renews — rewrites — it every
37//!   [`RENEW_INTERVAL_MS`]), rather than being evicted on sight.
38//! - **Epochs survive release.** Every change of owner takes the next value
39//!   of a per-key counter (`<instance_id>.epoch`) that, like the lock file,
40//!   is never deleted — so a release followed by a new claim can never
41//!   reuse an older holder's epoch.
42//! - **A dead holder is reclaimed at once.** A lease records its holder's
43//!   host, pid and process start time; on the same host a pid that is gone,
44//!   or now belongs to a different process, frees the lease immediately
45//!   instead of after the TTL.
46//!
47//! Root cause + design context:
48//! `docs/retro/RETRO_DEV_BUILD_SHARED_AGENT_SESSION_COLLISION_2026_07_29.md`,
49//! `docs/analysis/ANALYSIS_MULTI_AGENT_SESSION_AND_WORKDIR_ISOLATION_2026-07-29.md`,
50//! `docs/specs/SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24.md`.
51
52use std::path::{Path, PathBuf};
53use std::sync::Arc;
54
55use serde::{Deserialize, Serialize};
56use thiserror::Error;
57
58use super::atomic::write_atomic;
59
60/// How often a held lease must be renewed. Drives its own dedicated renewal
61/// task (`subprocess/host_spawn.rs` per turn; `backend::agent_admission` for
62/// a persistent pane's process) on this interval — not piggybacked on
63/// anything else.
64pub const RENEW_INTERVAL_MS: u64 = 5_000;
65
66/// 3x the renew interval — tolerates two missed ticks (disk hiccup, GC
67/// pause) before a lease is considered abandoned and reclaimable.
68pub const LEASE_TTL_MS: u64 = RENEW_INTERVAL_MS * 3;
69
70#[derive(Debug, Error)]
71pub enum LeaseError {
72    #[error("session '{instance_id}' is already owned by another AgentMux process (boot {owner_boot_id}, renewed {age_ms}ms ago)")]
73    HeldByOther {
74        instance_id: String,
75        owner_boot_id: String,
76        age_ms: u64,
77        /// Who holds it, when the lease file could be read — what a
78        /// refusal message names. `None` for an unreadable or vanished file.
79        holder: Option<LeaseHolder>,
80    },
81    #[error("io: {0}")]
82    Io(#[from] std::io::Error),
83}
84
85/// Who holds a lease, as recorded in its file. Fields added by the
86/// single-live-instance spec are empty/zero on a lease written by an older
87/// build; readers must treat those as "unknown", never as a value.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct LeaseHolder {
90    pub owner_boot_id: String,
91    pub block_id: String,
92    pub pid: u32,
93    pub channel: String,
94    pub version: String,
95    pub hostname: String,
96    pub epoch: u64,
97    pub acquired_at_ms: i64,
98    pub renewed_at_ms: i64,
99}
100
101/// What a claimant records about itself beyond its boot id and block —
102/// shown to whoever it later refuses. Empty strings are allowed (tests,
103/// callers that don't know); they render as "unknown".
104#[derive(Debug, Clone, Default)]
105pub struct ClaimantInfo {
106    pub channel: String,
107    pub version: String,
108}
109
110#[derive(Debug, Serialize, Deserialize)]
111struct LeaseFile {
112    instance_id: String,
113    owner_boot_id: String,
114    block_id: String,
115    /// Informational only — NOT the lease key (see module doc comment
116    /// and the analysis doc's Open Question this resolves: a
117    /// session_id can be `None` on an agent's first-ever turn, which
118    /// would leave that exact case unprotected if it were the key).
119    session_id: Option<String>,
120    pid: u32,
121    acquired_at_ms: i64,
122    renewed_at_ms: i64,
123    // ── Added by SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 Phase 1. ──
124    // `serde(default)` both ways: an older build's lease file still parses
125    // here (so version skew never looks "corrupt"), and an older build
126    // reading one of ours ignores unknown fields.
127    #[serde(default)]
128    epoch: u64,
129    #[serde(default)]
130    hostname: String,
131    /// Holder process start time, seconds since the Unix epoch (sysinfo).
132    /// 0 = unknown. Distinguishes a reused pid from the original holder.
133    #[serde(default)]
134    pid_start_s: u64,
135    #[serde(default)]
136    channel: String,
137    #[serde(default)]
138    version: String,
139    /// Fresh for every successful `claim`, including a same-block re-claim.
140    /// Only the handle carrying the current value may renew, verify or
141    /// release: a controller replaced for the same block (a forced restart)
142    /// re-claims before the old process's exit runs, and that exit must not
143    /// delete — or be fenced by — the lease the new process now holds.
144    /// Empty on a lease written by an older build (matches any handle).
145    #[serde(default)]
146    claim_id: String,
147}
148
149impl LeaseFile {
150    fn holder(&self) -> LeaseHolder {
151        LeaseHolder {
152            owner_boot_id: self.owner_boot_id.clone(),
153            block_id: self.block_id.clone(),
154            pid: self.pid,
155            channel: self.channel.clone(),
156            version: self.version.clone(),
157            hostname: self.hostname.clone(),
158            epoch: self.epoch,
159            acquired_at_ms: self.acquired_at_ms,
160            renewed_at_ms: self.renewed_at_ms,
161        }
162    }
163}
164
165/// A held lease. Cheap to `Clone` (a few `String`s + a `PathBuf`) — the
166/// renew task, the pre-turn fence check and the eventual release each need
167/// their own owned copy.
168#[derive(Debug, Clone)]
169pub struct Lease {
170    instance_id: String,
171    owner_boot_id: Arc<str>,
172    block_id: String,
173    claim_id: String,
174    epoch: u64,
175    path: PathBuf,
176}
177
178impl Lease {
179    pub fn instance_id(&self) -> &str {
180        &self.instance_id
181    }
182
183    /// The boot id of the process that holds this lease.
184    pub fn owner_boot_id(&self) -> &str {
185        &self.owner_boot_id
186    }
187
188    /// The ownership generation this lease was granted under. Strictly
189    /// greater than every earlier holder's for the same key.
190    pub fn epoch(&self) -> u64 {
191        self.epoch
192    }
193}
194
195use agentmux_common::time::now_ms;
196
197/// The lease file as found on disk.
198enum OnDisk {
199    Missing,
200    /// Present but unparseable; `age_ms` since it was last written.
201    Unreadable { age_ms: u64 },
202    Valid(LeaseFile),
203}
204
205pub struct LeaseStore {
206    root: PathBuf,
207    ttl_ms: u64,
208}
209
210impl LeaseStore {
211    /// `<registry_root>/leases/`. Creates the directory if missing.
212    pub fn open(registry_root: &Path) -> std::io::Result<Self> {
213        let root = registry_root.join("leases");
214        std::fs::create_dir_all(&root)?;
215        Ok(Self {
216            root,
217            ttl_ms: LEASE_TTL_MS,
218        })
219    }
220
221    /// Test-only constructor with a small TTL so expiry tests don't
222    /// need real multi-second sleeps.
223    #[cfg(test)]
224    pub(crate) fn open_with_ttl(registry_root: &Path, ttl_ms: u64) -> std::io::Result<Self> {
225        let mut s = Self::open(registry_root)?;
226        s.ttl_ms = ttl_ms;
227        Ok(s)
228    }
229
230    fn content_path(&self, instance_id: &str) -> PathBuf {
231        self.root.join(format!("{instance_id}.lease.json"))
232    }
233
234    fn lock_path(&self, instance_id: &str) -> PathBuf {
235        self.root.join(format!("{instance_id}.lock"))
236    }
237
238    fn epoch_path(&self, instance_id: &str) -> PathBuf {
239        self.root.join(format!("{instance_id}.epoch"))
240    }
241
242    fn read(path: &Path) -> std::io::Result<OnDisk> {
243        let bytes = match std::fs::read(path) {
244            Ok(b) => b,
245            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(OnDisk::Missing),
246            Err(e) => return Err(e),
247        };
248        match serde_json::from_slice::<LeaseFile>(&bytes) {
249            Ok(file) => Ok(OnDisk::Valid(file)),
250            Err(_) => {
251                let age_ms = std::fs::metadata(path)
252                    .and_then(|m| m.modified())
253                    .ok()
254                    .and_then(|t| t.elapsed().ok())
255                    .map(|d| d.as_millis() as u64)
256                    // An mtime we can't read proves nothing either way;
257                    // treat the file as fresh (held) — fail closed.
258                    .unwrap_or(0);
259                Ok(OnDisk::Unreadable { age_ms })
260            }
261        }
262    }
263
264    /// Next ownership epoch for `instance_id`: one past the larger of the
265    /// persisted counter and `floor` (the current file's epoch, which a lease
266    /// written before the counter existed may carry alone). Must be called
267    /// inside the key's critical section.
268    fn next_epoch(&self, instance_id: &str, floor: u64) -> std::io::Result<u64> {
269        let path = self.epoch_path(instance_id);
270        let stored = std::fs::read_to_string(&path)
271            .ok()
272            .and_then(|s| s.trim().parse::<u64>().ok())
273            .unwrap_or(0);
274        let next = stored.max(floor) + 1;
275        write_atomic(&path, format!("{next}\n").as_bytes())?;
276        Ok(next)
277    }
278
279    /// Attempt to claim the lease for `instance_id`. Kept for the
280    /// subprocess controller's per-turn claim; see [`Self::claim_as`].
281    pub fn claim(
282        &self,
283        instance_id: &str,
284        boot_id: &Arc<str>,
285        block_id: &str,
286        session_id_hint: Option<&str>,
287    ) -> Result<Lease, LeaseError> {
288        self.claim_as(instance_id, boot_id, block_id, session_id_hint, &ClaimantInfo::default())
289    }
290
291    /// Attempt to claim the lease for `instance_id`.
292    ///
293    /// - Already held by `boot_id` (this process) for the same block →
294    ///   idempotent re-claim, timestamp refreshed, epoch kept.
295    /// - Held, not yet expired, by **another block of this same process**
296    ///   → `Err(HeldByOther)`: one driver per agent holds inside a process
297    ///   too (ReAgent P1 on #3738), and the newcomer is the one refused.
298    /// - Held by another owner, not yet expired, holder not provably
299    ///   dead → `Err(HeldByOther)`.
300    /// - Unreadable and rewritten within the TTL → `Err(HeldByOther)`
301    ///   (fail closed — see module doc).
302    /// - Free, expired, unreadable-and-stale, or held by a dead process
303    ///   → claimed under a new epoch.
304    ///
305    /// The whole read-decide-write sequence runs inside a per-
306    /// `instance_id` exclusive lock (see module doc comment), so
307    /// there's no window for a concurrent claimer to observe an
308    /// inconsistent state.
309    pub fn claim_as(
310        &self,
311        instance_id: &str,
312        boot_id: &Arc<str>,
313        block_id: &str,
314        session_id_hint: Option<&str>,
315        info: &ClaimantInfo,
316    ) -> Result<Lease, LeaseError> {
317        let _cs = CriticalSection::enter(&self.lock_path(instance_id))?;
318        let path = self.content_path(instance_id);
319
320        let (kept_epoch, floor) = match Self::read(&path)? {
321            OnDisk::Missing => (None, 0),
322            OnDisk::Unreadable { age_ms } => {
323                if age_ms <= self.ttl_ms {
324                    return Err(LeaseError::HeldByOther {
325                        instance_id: instance_id.to_string(),
326                        owner_boot_id: "<unreadable lease file>".to_string(),
327                        age_ms,
328                        holder: None,
329                    });
330                }
331                tracing::warn!(
332                    instance_id,
333                    age_ms,
334                    "lease: unreadable lease file not rewritten for a full TTL — reclaiming"
335                );
336                (None, 0)
337            }
338            OnDisk::Valid(existing) => {
339                let age_ms = (now_ms() - existing.renewed_at_ms).max(0) as u64;
340                if existing.owner_boot_id == boot_id.as_ref() && same_block(&existing, block_id) {
341                    // Same owner re-claiming (e.g. controller recreated
342                    // on a resync with no process restart): ownership
343                    // didn't change, so neither does the epoch.
344                    (Some(existing.epoch), existing.epoch)
345                } else if existing.owner_boot_id == boot_id.as_ref() {
346                    // Another block of this process holds it.
347                    if age_ms <= self.ttl_ms {
348                        return Err(LeaseError::HeldByOther {
349                            instance_id: instance_id.to_string(),
350                            owner_boot_id: existing.owner_boot_id.clone(),
351                            age_ms,
352                            holder: Some(existing.holder()),
353                        });
354                    }
355                    (None, existing.epoch)
356                } else {
357                    if age_ms <= self.ttl_ms && !holder_is_dead(&existing) {
358                        return Err(LeaseError::HeldByOther {
359                            instance_id: instance_id.to_string(),
360                            owner_boot_id: existing.owner_boot_id.clone(),
361                            age_ms,
362                            holder: Some(existing.holder()),
363                        });
364                    }
365                    // Expired, or its process is gone — take it over.
366                    (None, existing.epoch)
367                }
368            }
369        };
370
371        let epoch = match kept_epoch {
372            Some(e) if e > 0 => e,
373            _ => self.next_epoch(instance_id, floor)?,
374        };
375        let claim_id = uuid::Uuid::new_v4().to_string();
376        let bytes = lease_bytes(instance_id, boot_id, block_id, session_id_hint, epoch, &claim_id, info)?;
377        write_atomic(&path, &bytes)?;
378        Ok(Lease {
379            instance_id: instance_id.to_string(),
380            owner_boot_id: Arc::clone(boot_id),
381            block_id: block_id.to_string(),
382            claim_id,
383            epoch,
384            path,
385        })
386    }
387
388    /// Extend a held lease's TTL. Runs inside the same per-`instance_id`
389    /// critical section as `claim`, so the ownership check and the
390    /// write are atomic with respect to any concurrent `claim`/`renew`/
391    /// `release` for this instance — a caller that lost the lease to a
392    /// TTL reclaim between its last renew and this one gets a real
393    /// `HeldByOther`, never a silent clobber of the new owner's file.
394    pub fn renew(&self, lease: &Lease) -> Result<(), LeaseError> {
395        let _cs = CriticalSection::enter(&self.lock_path(&lease.instance_id))?;
396        let existing = self.owned_file(lease)?;
397        let renewed = LeaseFile {
398            renewed_at_ms: now_ms(),
399            ..existing
400        };
401        let mut bytes = serde_json::to_vec_pretty(&renewed).map_err(std::io::Error::from)?;
402        bytes.push(b'\n');
403        write_atomic(&lease.path, &bytes)?;
404        Ok(())
405    }
406
407    /// Is `lease` still ours? The pre-turn fence check: a holder that was
408    /// suspended past the TTL and reclaimed must find out before it starts
409    /// another turn, not only at its next renew tick. Does not write.
410    pub fn verify(&self, lease: &Lease) -> Result<(), LeaseError> {
411        let _cs = CriticalSection::enter(&self.lock_path(&lease.instance_id))?;
412        self.owned_file(lease).map(|_| ())
413    }
414
415    /// Read the lease file and confirm `lease`'s owner still holds it.
416    /// Caller holds the critical section.
417    fn owned_file(&self, lease: &Lease) -> Result<LeaseFile, LeaseError> {
418        let existing = match Self::read(&lease.path)? {
419            OnDisk::Valid(f) => f,
420            // Gone entirely (reclaimed and later released, or evicted), or
421            // unreadable — either way not provably ours.
422            OnDisk::Missing | OnDisk::Unreadable { .. } => {
423                return Err(LeaseError::HeldByOther {
424                    instance_id: lease.instance_id.clone(),
425                    owner_boot_id: "<unknown — lease file missing or unreadable>".to_string(),
426                    age_ms: 0,
427                    holder: None,
428                });
429            }
430        };
431        // Owner, block AND claim: a lease another block of this process took
432        // over (after this one's expired), or this block re-claimed through a
433        // newer handle (a replaced controller), is not this handle's any more.
434        if !is_this_claim(&existing, lease) {
435            let age_ms = (now_ms() - existing.renewed_at_ms).max(0) as u64;
436            return Err(LeaseError::HeldByOther {
437                instance_id: lease.instance_id.clone(),
438                owner_boot_id: existing.owner_boot_id.clone(),
439                age_ms,
440                holder: Some(existing.holder()),
441            });
442        }
443        Ok(existing)
444    }
445
446    /// Release a held lease. If it's no longer ours — already
447    /// TTL-reclaimed by another process, or re-claimed by another block of
448    /// this same process — this is a safe no-op: deleting would destroy the
449    /// current holder's lease, not ours. Idempotent: releasing an
450    /// already-missing lease is `Ok(())`. The epoch counter is never
451    /// removed (see module doc).
452    pub fn release(&self, lease: &Lease) -> Result<(), LeaseError> {
453        let _cs = CriticalSection::enter(&self.lock_path(&lease.instance_id))?;
454        let existing = match Self::read(&lease.path)? {
455            OnDisk::Valid(f) => f,
456            OnDisk::Missing | OnDisk::Unreadable { .. } => return Ok(()),
457        };
458        if !is_this_claim(&existing, lease) {
459            return Ok(());
460        }
461        match std::fs::remove_file(&lease.path) {
462            Ok(()) => Ok(()),
463            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
464            Err(e) => Err(e.into()),
465        }
466    }
467
468    /// The current holder of `instance_id`'s lease if it is **live** —
469    /// unexpired and not provably dead — and is not `own_boot_id`. The
470    /// read-only early check callers run before doing anything shared on
471    /// the agent's behalf (spec I9); the binding decision is still `claim`.
472    /// An unreadable, still-fresh file is reported as held with an empty
473    /// holder (fail closed).
474    pub fn live_holder_other_than(
475        &self,
476        instance_id: &str,
477        own_boot_id: &str,
478    ) -> std::io::Result<Option<LeaseHolder>> {
479        let _cs = CriticalSection::enter(&self.lock_path(instance_id))?;
480        Ok(match Self::read(&self.content_path(instance_id))? {
481            OnDisk::Missing => None,
482            OnDisk::Unreadable { age_ms } => (age_ms <= self.ttl_ms).then(|| LeaseHolder {
483                owner_boot_id: "<unreadable lease file>".to_string(),
484                block_id: String::new(),
485                pid: 0,
486                channel: String::new(),
487                version: String::new(),
488                hostname: String::new(),
489                epoch: 0,
490                acquired_at_ms: 0,
491                renewed_at_ms: 0,
492            }),
493            OnDisk::Valid(f) => {
494                let age_ms = (now_ms() - f.renewed_at_ms).max(0) as u64;
495                (f.owner_boot_id != own_boot_id && age_ms <= self.ttl_ms && !holder_is_dead(&f))
496                    .then(|| f.holder())
497            }
498        })
499    }
500}
501
502impl LeaseStore {
503    /// The pane that holds `instance_id`'s lease right now, whichever AgentMux process it belongs to: none
504    /// when nobody holds it, or the lease is expired, dead or has no block recorded. Read-only.
505    pub fn live_holder_block(&self, instance_id: &str) -> std::io::Result<Option<String>> {
506        let _cs = CriticalSection::enter(&self.lock_path(instance_id))?;
507        Ok(match Self::read(&self.content_path(instance_id))? {
508            OnDisk::Valid(f) => {
509                let age_ms = (now_ms() - f.renewed_at_ms).max(0) as u64;
510                (age_ms <= self.ttl_ms && !holder_is_dead(&f) && !f.block_id.is_empty()).then_some(f.block_id)
511            }
512            OnDisk::Missing | OnDisk::Unreadable { .. } => None,
513        })
514    }
515}
516
517/// Does `file` belong to `block_id`? A lease written before block ids were
518/// compared (empty) matches any block of its owner.
519fn same_block(file: &LeaseFile, block_id: &str) -> bool {
520    file.block_id.is_empty() || file.block_id == block_id
521}
522
523/// Is `file` the lease `lease` was granted — same owner, same block, same
524/// claim? An empty `claim_id` (older build) matches.
525fn is_this_claim(file: &LeaseFile, lease: &Lease) -> bool {
526    file.owner_boot_id == lease.owner_boot_id.as_ref()
527        && same_block(file, &lease.block_id)
528        && (file.claim_id.is_empty() || file.claim_id == lease.claim_id)
529}
530
531/// This host's name as recorded in a lease — lowercased and trimmed so two
532/// processes on one host always agree.
533fn this_host() -> String {
534    whoami::fallible::hostname()
535        .unwrap_or_default()
536        .trim()
537        .to_lowercase()
538}
539
540/// Start time (seconds since the Unix epoch) of process `pid` on this host,
541/// `None` if no such process is running.
542fn process_start_s(pid: u32) -> Option<u64> {
543    let target = sysinfo::Pid::from(pid as usize);
544    let mut sys = sysinfo::System::new();
545    sys.refresh_processes_specifics(
546        sysinfo::ProcessesToUpdate::Some(&[target]),
547        true,
548        sysinfo::ProcessRefreshKind::nothing(),
549    );
550    sys.process(target).map(|p| p.start_time())
551}
552
553/// True only when the holder is **provably** gone: it recorded this host,
554/// and its pid is not running or now belongs to a process that started at a
555/// different time. Anything we can't prove (a lease from another host — the
556/// shared root on a network drive — or one written before hosts were
557/// recorded) is treated as alive.
558fn holder_is_dead(file: &LeaseFile) -> bool {
559    if file.hostname.is_empty() || file.pid == 0 || file.hostname != this_host() {
560        return false;
561    }
562    match process_start_s(file.pid) {
563        None => true,
564        Some(start) => file.pid_start_s != 0 && start != file.pid_start_s,
565    }
566}
567
568fn lease_bytes(
569    instance_id: &str,
570    boot_id: &Arc<str>,
571    block_id: &str,
572    session_id_hint: Option<&str>,
573    epoch: u64,
574    claim_id: &str,
575    info: &ClaimantInfo,
576) -> Result<Vec<u8>, std::io::Error> {
577    let now = now_ms();
578    let pid = std::process::id();
579    let file = LeaseFile {
580        instance_id: instance_id.to_string(),
581        owner_boot_id: boot_id.to_string(),
582        block_id: block_id.to_string(),
583        session_id: session_id_hint.map(str::to_string),
584        pid,
585        acquired_at_ms: now,
586        renewed_at_ms: now,
587        epoch,
588        hostname: this_host(),
589        pid_start_s: process_start_s(pid).unwrap_or(0),
590        channel: info.channel.clone(),
591        version: info.version.clone(),
592        claim_id: claim_id.to_string(),
593    };
594    let mut bytes = serde_json::to_vec_pretty(&file).map_err(std::io::Error::from)?;
595    bytes.push(b'\n');
596    Ok(bytes)
597}
598
599/// A held per-`instance_id` OS advisory lock. Blocking (waits rather
600/// than failing immediately) — critical sections here are a handful of
601/// small file ops, so worst-case wait time is negligible. Released
602/// automatically on drop: closing the underlying handle releases both
603/// `flock` (Unix) and `LockFileEx` (Windows) advisory locks.
604struct CriticalSection {
605    _file: std::fs::File,
606}
607
608impl CriticalSection {
609    /// Deliberately never removes `lock_path` — one empty lock file
610    /// persists per `instance_id` that has ever called `claim`, same
611    /// bounded/accepted cost as `backend::base::MuxLock`'s single
612    /// global lock file. This is NOT an oversight: deleting a flock/
613    /// LockFileEx-locked file out from under a waiter is the classic
614    /// "unlink race" footgun — a process blocked in `open()` (before
615    /// it gets to actually lock) can end up holding a handle to a
616    /// *different* underlying file than a fresh claimant that
617    /// recreated the path after deletion, so both would believe they
618    /// hold "the" lock while actually holding two distinct advisory
619    /// locks on two distinct inodes. Leaving the lock file in place
620    /// forever avoids that hazard entirely at the cost of a handful of
621    /// permanently-empty files.
622    fn enter(lock_path: &Path) -> std::io::Result<Self> {
623        let file = std::fs::OpenOptions::new()
624            .create(true)
625            .write(true)
626            .open(lock_path)?;
627        lock_exclusive(&file)?;
628        Ok(Self { _file: file })
629    }
630}
631
632#[cfg(unix)]
633pub(crate) fn lock_exclusive(file: &std::fs::File) -> std::io::Result<()> {
634    use std::os::unix::io::AsRawFd;
635    // Blocking (no LOCK_NB) — we want to wait for the holder, not fail.
636    if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {
637        return Err(std::io::Error::last_os_error());
638    }
639    Ok(())
640}
641
642#[cfg(windows)]
643pub(crate) fn lock_exclusive(file: &std::fs::File) -> std::io::Result<()> {
644    use std::os::windows::io::AsRawHandle;
645    use windows_sys::Win32::Storage::FileSystem::{LockFileEx, LOCKFILE_EXCLUSIVE_LOCK};
646    use windows_sys::Win32::System::IO::OVERLAPPED;
647
648    let handle = file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE;
649    // Zeroed OVERLAPPED with offset 0 + max length locks the whole
650    // file. LockFileEx requires an OVERLAPPED struct even for a
651    // synchronous, blocking call (offset fields only matter for
652    // partial-file locks, which we don't use).
653    let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
654    // No LOCKFILE_FAIL_IMMEDIATELY — blocks until the lock is free.
655    let ok = unsafe {
656        LockFileEx(handle, LOCKFILE_EXCLUSIVE_LOCK, 0, u32::MAX, u32::MAX, &mut overlapped)
657    };
658    if ok == 0 {
659        return Err(std::io::Error::last_os_error());
660    }
661    Ok(())
662}
663
664/// Non-blocking [`lock_exclusive`]: `Ok(true)` when the lock was taken,
665/// `Ok(false)` when another holder has it. For waiters that must stay
666/// cancellable (poll this instead of blocking in `lock_exclusive`).
667#[cfg(unix)]
668pub(crate) fn try_lock_exclusive(file: &std::fs::File) -> std::io::Result<bool> {
669    use std::os::unix::io::AsRawFd;
670    if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
671        return Ok(true);
672    }
673    let err = std::io::Error::last_os_error();
674    if err.kind() == std::io::ErrorKind::WouldBlock {
675        Ok(false)
676    } else {
677        Err(err)
678    }
679}
680
681/// Non-blocking exclusive lock on `len` bytes of `file` at `offset`: for a file other processes read
682/// while it is held. A Windows byte-range lock is mandatory, so locking the bytes that hold data would
683/// hide them from those readers; a range far past the data leaves them readable. Unix `flock` has no
684/// ranges and is advisory (a read is never blocked), so there it takes the whole-file lock.
685/// `Ok(false)` when another holder has the range.
686#[cfg(unix)]
687pub(crate) fn try_lock_exclusive_range(file: &std::fs::File, _offset: u64, _len: u32) -> std::io::Result<bool> {
688    try_lock_exclusive(file)
689}
690
691#[cfg(windows)]
692pub(crate) fn try_lock_exclusive_range(file: &std::fs::File, offset: u64, len: u32) -> std::io::Result<bool> {
693    use std::os::windows::io::AsRawHandle;
694    use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION;
695    use windows_sys::Win32::Storage::FileSystem::{LockFileEx, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY};
696    use windows_sys::Win32::System::IO::OVERLAPPED;
697
698    let handle = file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE;
699    let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
700    overlapped.Anonymous.Anonymous.Offset = (offset & 0xffff_ffff) as u32;
701    overlapped.Anonymous.Anonymous.OffsetHigh = (offset >> 32) as u32;
702    let ok = unsafe {
703        LockFileEx(
704            handle,
705            LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
706            0,
707            len,
708            0,
709            &mut overlapped,
710        )
711    };
712    if ok != 0 {
713        return Ok(true);
714    }
715    let err = std::io::Error::last_os_error();
716    if err.raw_os_error() == Some(ERROR_LOCK_VIOLATION as i32) {
717        Ok(false)
718    } else {
719        Err(err)
720    }
721}
722
723#[cfg(windows)]
724pub(crate) fn try_lock_exclusive(file: &std::fs::File) -> std::io::Result<bool> {
725    use std::os::windows::io::AsRawHandle;
726    use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION;
727    use windows_sys::Win32::Storage::FileSystem::{LockFileEx, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY};
728    use windows_sys::Win32::System::IO::OVERLAPPED;
729
730    let handle = file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE;
731    let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
732    let ok = unsafe {
733        LockFileEx(
734            handle,
735            LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
736            0,
737            u32::MAX,
738            u32::MAX,
739            &mut overlapped,
740        )
741    };
742    if ok != 0 {
743        return Ok(true);
744    }
745    let err = std::io::Error::last_os_error();
746    if err.raw_os_error() == Some(ERROR_LOCK_VIOLATION as i32) {
747        Ok(false)
748    } else {
749        Err(err)
750    }
751}
752
753#[cfg(test)]
754mod tests {
755    use super::*;
756
757    fn store(ttl_ms: u64) -> (tempfile::TempDir, LeaseStore) {
758        let tmp = tempfile::tempdir().unwrap();
759        let s = LeaseStore::open_with_ttl(tmp.path(), ttl_ms).unwrap();
760        (tmp, s)
761    }
762
763    fn boot(id: &str) -> Arc<str> {
764        Arc::from(id)
765    }
766
767    fn lease_path(tmp: &tempfile::TempDir, id: &str) -> PathBuf {
768        tmp.path().join("leases").join(format!("{id}.lease.json"))
769    }
770
771    fn on_disk(tmp: &tempfile::TempDir, id: &str) -> LeaseFile {
772        serde_json::from_slice(&std::fs::read(lease_path(tmp, id)).unwrap()).unwrap()
773    }
774
775    /// Rewrite the lease file so it names `pid` (and `start_s`) on this
776    /// host — simulates a holder that is some other process.
777    fn set_holder_process(tmp: &tempfile::TempDir, id: &str, pid: u32, start_s: u64) {
778        let mut f = on_disk(tmp, id);
779        f.pid = pid;
780        f.pid_start_s = start_s;
781        std::fs::write(lease_path(tmp, id), serde_json::to_vec(&f).unwrap()).unwrap();
782    }
783
784    /// A pid no process has: above Linux's `pid_max` ceiling (2^22) and far
785    /// above any pid Windows hands out. (Not a spawned-and-reaped child —
786    /// the srv's spawn surface is pinned by `pane_env`'s inventory test.)
787    fn exited_pid() -> u32 {
788        const NO_SUCH_PID: u32 = 4_000_000_000;
789        assert!(process_start_s(NO_SUCH_PID).is_none(), "pid {NO_SUCH_PID} unexpectedly running");
790        NO_SUCH_PID
791    }
792
793    #[test]
794    fn claim_succeeds_when_no_existing_lease() {
795        let (_tmp, s) = store(60_000);
796        let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
797        assert_eq!(lease.instance_id(), "agent-1");
798    }
799
800    #[test]
801    fn claim_fails_when_held_by_other_and_fresh() {
802        let (_tmp, s) = store(60_000);
803        s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
804        let err = s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap_err();
805        match err {
806            LeaseError::HeldByOther { owner_boot_id, holder, .. } => {
807                assert_eq!(owner_boot_id, "boot-a");
808                let holder = holder.expect("a readable lease names its holder");
809                assert_eq!(holder.block_id, "block-1");
810                assert_eq!(holder.pid, std::process::id());
811            }
812            other => panic!("expected HeldByOther, got {other:?}"),
813        }
814    }
815
816    #[test]
817    fn claim_is_idempotent_for_same_owner() {
818        let (_tmp, s) = store(60_000);
819        let first = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
820        let second = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
821        assert_eq!(first.epoch(), second.epoch(), "a same-owner re-claim is not an ownership change");
822    }
823
824    #[test]
825    fn claim_reclaims_after_ttl_expiry() {
826        // Wide margin (20x) — under a full parallel `cargo test` run,
827        // thread::sleep can overshoot by tens of ms under scheduler
828        // contention; a tight TTL/sleep ratio here was observed flaky.
829        let (_tmp, s) = store(50);
830        s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
831        std::thread::sleep(std::time::Duration::from_millis(1_000));
832        let reclaimed = s.claim("agent-1", &boot("boot-b"), "block-2", None);
833        assert!(reclaimed.is_ok(), "expected expired lease to be reclaimable, got {reclaimed:?}");
834    }
835
836    /// Codex P1 on #3730: a parse failure does not prove the holder dead.
837    #[test]
838    fn a_fresh_unreadable_lease_is_held_not_evicted() {
839        let (tmp, s) = store(60_000);
840        let path = lease_path(&tmp, "agent-1");
841        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
842        std::fs::write(&path, b"not json").unwrap();
843        let err = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap_err();
844        assert!(matches!(err, LeaseError::HeldByOther { holder: None, .. }), "got {err:?}");
845        assert!(s.live_holder_other_than("agent-1", "boot-a").unwrap().is_some());
846    }
847
848    #[test]
849    fn an_unreadable_lease_nobody_rewrote_for_a_ttl_is_reclaimed() {
850        let (tmp, s) = store(50);
851        let path = lease_path(&tmp, "agent-1");
852        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
853        std::fs::write(&path, b"not json").unwrap();
854        std::thread::sleep(std::time::Duration::from_millis(1_000));
855        let claimed = s.claim("agent-1", &boot("boot-a"), "block-1", None);
856        assert!(claimed.is_ok(), "expected a stale unreadable lease to be reclaimable, got {claimed:?}");
857    }
858
859    /// Version skew: a lease written by a build that predates the added
860    /// fields must parse (and so be honoured), not read as corrupt.
861    #[test]
862    fn a_lease_in_the_old_format_is_still_honoured() {
863        let (tmp, s) = store(60_000);
864        let path = lease_path(&tmp, "agent-1");
865        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
866        let old = serde_json::json!({
867            "instance_id": "agent-1", "owner_boot_id": "boot-old", "block_id": "b",
868            "session_id": null, "pid": 1, "acquired_at_ms": now_ms(), "renewed_at_ms": now_ms(),
869        });
870        std::fs::write(&path, serde_json::to_vec(&old).unwrap()).unwrap();
871        let err = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap_err();
872        match err {
873            LeaseError::HeldByOther { owner_boot_id, .. } => assert_eq!(owner_boot_id, "boot-old"),
874            other => panic!("expected HeldByOther, got {other:?}"),
875        }
876    }
877
878    /// Codex P2 on #3730: release deletes the lease file, so the epoch
879    /// must live somewhere that survives it.
880    #[test]
881    fn epochs_strictly_increase_across_release_and_reclaim() {
882        let (_tmp, s) = store(60_000);
883        let a = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
884        s.release(&a).unwrap();
885        let b = s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap();
886        s.release(&b).unwrap();
887        let c = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
888        assert!(a.epoch() >= 1);
889        assert!(b.epoch() > a.epoch(), "{} !> {}", b.epoch(), a.epoch());
890        assert!(c.epoch() > b.epoch(), "{} !> {}", c.epoch(), b.epoch());
891    }
892
893    #[test]
894    fn epochs_increase_across_ttl_reclaim_too() {
895        let (_tmp, s) = store(50);
896        let a = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
897        std::thread::sleep(std::time::Duration::from_millis(1_000));
898        let b = s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap();
899        assert!(b.epoch() > a.epoch());
900    }
901
902    #[test]
903    fn a_holder_whose_process_is_gone_is_reclaimed_immediately() {
904        let (tmp, s) = store(60_000);
905        s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
906        set_holder_process(&tmp, "agent-1", exited_pid(), 0);
907        let reclaimed = s.claim("agent-1", &boot("boot-b"), "block-2", None);
908        assert!(reclaimed.is_ok(), "a dead holder must not wait out the TTL, got {reclaimed:?}");
909        assert!(s.live_holder_other_than("agent-1", "boot-c").unwrap().is_some());
910    }
911
912    /// PID reuse: the pid is running, but it is not the process that
913    /// took the lease (different start time).
914    #[test]
915    fn a_reused_pid_does_not_keep_a_lease_alive() {
916        let (tmp, s) = store(60_000);
917        s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
918        let me = std::process::id();
919        let my_start = process_start_s(me).expect("this test process is running");
920        set_holder_process(&tmp, "agent-1", me, my_start.saturating_sub(3_600));
921        assert!(s.claim("agent-1", &boot("boot-b"), "block-2", None).is_ok());
922    }
923
924    #[test]
925    fn a_holder_on_another_host_is_never_presumed_dead() {
926        let (tmp, s) = store(60_000);
927        s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
928        let mut f = on_disk(&tmp, "agent-1");
929        f.hostname = "some-other-host".to_string();
930        f.pid = exited_pid();
931        std::fs::write(lease_path(&tmp, "agent-1"), serde_json::to_vec(&f).unwrap()).unwrap();
932        assert!(s.claim("agent-1", &boot("boot-b"), "block-2", None).is_err());
933    }
934
935    #[test]
936    fn renew_extends_ttl_and_blocks_reclaim_by_other() {
937        // Large TTL relative to the sleeps (100x+ margin) — this test
938        // asserts the lease is still considered FRESH, so it needs the
939        // opposite safety direction from the expiry tests: elapsed
940        // time must stay comfortably under the TTL even with generous
941        // scheduler jitter on a busy `cargo test` run.
942        let (_tmp, s) = store(5_000);
943        let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
944        std::thread::sleep(std::time::Duration::from_millis(20));
945        s.renew(&lease).unwrap();
946        std::thread::sleep(std::time::Duration::from_millis(20));
947        // ~40ms elapsed since claim, ~20ms since the renew — still fresh.
948        let err = s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap_err();
949        assert!(matches!(err, LeaseError::HeldByOther { .. }));
950    }
951
952    #[test]
953    fn renew_fails_when_already_reclaimed_by_other() {
954        let (tmp, s) = store(50);
955        let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
956        std::thread::sleep(std::time::Duration::from_millis(1_000));
957        s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap();
958
959        let err = s.renew(&lease).unwrap_err();
960        assert!(matches!(err, LeaseError::HeldByOther { .. }));
961
962        // Must NOT have clobbered boot-b's lease.
963        assert_eq!(on_disk(&tmp, "agent-1").owner_boot_id, "boot-b");
964    }
965
966    /// The fence check a holder runs before each turn.
967    #[test]
968    fn verify_detects_a_lost_lease_without_writing() {
969        let (tmp, s) = store(50);
970        let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
971        assert!(s.verify(&lease).is_ok());
972        std::thread::sleep(std::time::Duration::from_millis(1_000));
973        // Expired but not reclaimed: still ours.
974        assert!(s.verify(&lease).is_ok());
975        s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap();
976        assert!(matches!(s.verify(&lease), Err(LeaseError::HeldByOther { .. })));
977        assert_eq!(on_disk(&tmp, "agent-1").owner_boot_id, "boot-b");
978    }
979
980    #[test]
981    fn release_removes_the_lease_file() {
982        let (tmp, s) = store(60_000);
983        let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
984        s.release(&lease).unwrap();
985        assert!(!lease_path(&tmp, "agent-1").exists());
986    }
987
988    #[test]
989    fn release_is_a_noop_when_already_reclaimed_by_other() {
990        let (tmp, s) = store(50);
991        let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
992        std::thread::sleep(std::time::Duration::from_millis(1_000));
993        s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap();
994
995        s.release(&lease).unwrap();
996
997        assert!(lease_path(&tmp, "agent-1").exists(), "release must not delete another owner's lease");
998        assert_eq!(on_disk(&tmp, "agent-1").owner_boot_id, "boot-b");
999    }
1000
1001    /// ReAgent P1 on #3738: one process, two blocks of the same agent (two
1002    /// panes, or a subprocess turn beside a persistent pane) — one driver
1003    /// holds inside a process too, and the newcomer is the one refused.
1004    #[test]
1005    fn a_second_block_of_the_same_process_is_refused_while_the_first_holds_it() {
1006        let (_tmp, s) = store(60_000);
1007        let first = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1008        let err = s.claim("agent-1", &boot("boot-a"), "block-2", None).unwrap_err();
1009        match err {
1010            LeaseError::HeldByOther { holder, .. } => assert_eq!(holder.unwrap().block_id, "block-1"),
1011            other => panic!("expected HeldByOther, got {other:?}"),
1012        }
1013        assert!(s.verify(&first).is_ok(), "the holder keeps the agent");
1014        s.release(&first).unwrap();
1015        assert!(s.claim("agent-1", &boot("boot-a"), "block-2", None).is_ok());
1016    }
1017
1018    /// A controller replaced for the same block (a forced restart) re-claims
1019    /// before the old process's exit runs. That exit's release must not
1020    /// delete the new claim, and the old handle is the one fenced — not the
1021    /// new process.
1022    #[test]
1023    fn a_same_block_reclaim_supersedes_the_older_handle() {
1024        let (tmp, s) = store(60_000);
1025        let old = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1026        let new = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1027        assert_eq!(old.epoch(), new.epoch(), "same owner and block: not an ownership change");
1028        s.release(&old).unwrap();
1029        assert!(lease_path(&tmp, "agent-1").exists(), "the old handle's release must not free the new claim");
1030        assert!(s.verify(&new).is_ok());
1031        assert!(s.renew(&new).is_ok());
1032        assert!(matches!(s.verify(&old), Err(LeaseError::HeldByOther { .. })));
1033        assert!(matches!(s.renew(&old), Err(LeaseError::HeldByOther { .. })));
1034        s.release(&new).unwrap();
1035        assert!(!lease_path(&tmp, "agent-1").exists());
1036    }
1037
1038    /// If a same-process block does take over — after the first block's
1039    /// lease expired — the first block's `verify`/`renew` fail and its
1040    /// release leaves the new holder alone.
1041    #[test]
1042    fn a_block_superseded_after_expiry_is_fenced_and_cannot_release() {
1043        let (tmp, s) = store(50);
1044        let first = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1045        std::thread::sleep(std::time::Duration::from_millis(1_000));
1046        let second = s.claim("agent-1", &boot("boot-a"), "block-2", None).unwrap();
1047        assert!(second.epoch() > first.epoch(), "a block change is an ownership change");
1048        assert!(matches!(s.verify(&first), Err(LeaseError::HeldByOther { .. })));
1049        assert!(matches!(s.renew(&first), Err(LeaseError::HeldByOther { .. })));
1050        s.release(&first).unwrap();
1051        assert_eq!(on_disk(&tmp, "agent-1").block_id, "block-2");
1052    }
1053
1054    #[test]
1055    fn release_is_idempotent_on_missing_file() {
1056        let (_tmp, s) = store(60_000);
1057        let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1058        s.release(&lease).unwrap();
1059        assert!(s.release(&lease).is_ok());
1060    }
1061
1062    #[test]
1063    fn live_holder_ignores_self_and_names_the_holder() {
1064        // A TTL well above the sysinfo process lookup a liveness read does
1065        // (tens of ms on Windows) — this test asserts the lease is FRESH.
1066        let (_tmp, s) = store(60_000);
1067        s.claim_as(
1068            "agent-1",
1069            &boot("boot-a"),
1070            "block-1",
1071            None,
1072            &ClaimantInfo { channel: "stable".into(), version: "0.57.4".into() },
1073        )
1074        .unwrap();
1075        assert!(s.live_holder_other_than("agent-1", "boot-a").unwrap().is_none());
1076        let other = s.live_holder_other_than("agent-1", "boot-b").unwrap().unwrap();
1077        assert_eq!((other.channel.as_str(), other.version.as_str()), ("stable", "0.57.4"));
1078    }
1079
1080    #[test]
1081    fn live_holder_ignores_an_expired_lease() {
1082        let (_tmp, s) = store(50);
1083        s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1084        std::thread::sleep(std::time::Duration::from_millis(1_000));
1085        assert!(s.live_holder_other_than("agent-1", "boot-b").unwrap().is_none());
1086    }
1087
1088    #[test]
1089    fn concurrent_claim_race_has_exactly_one_winner() {
1090        let tmp = tempfile::tempdir().unwrap();
1091        let root = tmp.path().to_path_buf();
1092        let n = 8;
1093        let handles: Vec<_> = (0..n)
1094            .map(|i| {
1095                let root = root.clone();
1096                std::thread::spawn(move || {
1097                    let s = LeaseStore::open(&root).unwrap();
1098                    s.claim("agent-1", &boot(&format!("boot-{i}")), "block", None)
1099                        .is_ok()
1100                })
1101            })
1102            .collect();
1103        let wins: usize = handles.into_iter().map(|h| h.join().unwrap()).filter(|ok| *ok).count();
1104        assert_eq!(wins, 1, "exactly one claimant should win the race");
1105    }
1106}