Skip to main content

aft_base/
fs_lock.rs

1use std::collections::HashMap;
2use std::fmt;
3use std::fs::{self, File, OpenOptions};
4use std::io::{self, Read, Seek, SeekFrom, Write};
5use std::path::{Path, PathBuf};
6use std::sync::{
7    atomic::{AtomicBool, AtomicU64, Ordering},
8    mpsc, Arc, Mutex, OnceLock, Weak,
9};
10use std::thread::{self, JoinHandle};
11use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
12
13use serde::{Deserialize, Serialize};
14
15use crate::{slog_debug, slog_error, slog_info, slog_warn};
16
17/// Owns an already-acquired OS file lock, unlike the path/heartbeat lease below.
18/// Closing a file alone can leave its lock held by a forked child's descriptor
19/// until exec or exit. Explicitly unlock when the protected operation ends.
20/// Keep one guard per acquisition; share the guard, not cloned file handles.
21#[derive(Debug)]
22pub struct AdvisoryLockGuard(File);
23
24impl AdvisoryLockGuard {
25    pub fn from_locked_file(file: File) -> Self {
26        Self(file)
27    }
28}
29
30impl Drop for AdvisoryLockGuard {
31    fn drop(&mut self) {
32        let _ = self.0.unlock();
33    }
34}
35
36pub const HEARTBEAT_INTERVAL_MS: u64 = 5_000;
37/// Successful refreshes need not rewrite every wake. Foreign hosts allow 75s
38/// of silence, leaving 50s of scheduling/I/O headroom after a normal refresh.
39/// Same-host readers use process identity, never heartbeat age, for takeover.
40pub const HEARTBEAT_REFRESH_INTERVAL_MS: u64 = 25_000;
41pub const STALE_HEARTBEAT_MS: u64 = 15_000;
42pub const LIVE_OWNER_WARN_MS: u64 = 600_000;
43pub const POLL_INTERVAL_MS: u64 = 100;
44
45/// Max consecutive transient OS errors tolerated while creating the lock file
46/// before giving up. On Windows, two processes/threads racing to create (or one
47/// creating while another deletes) the same path can momentarily return
48/// ERROR_ACCESS_DENIED (5) or ERROR_SHARING_VIOLATION (32) instead of a clean
49/// "already exists". Those windows close in milliseconds, so a small bounded
50/// retry rides them out while a genuinely persistent permission/IO failure still
51/// surfaces promptly.
52const MAX_TRANSIENT_CREATE_RETRIES: u32 = 50;
53const RECLAIM_TOKEN_MALFORMED_STALE_AGE: Duration = Duration::from_secs(60);
54const RECLAIM_BLOCK_LOG_INTERVAL: Duration = Duration::from_secs(60);
55const DEAD_RECLAIM_INITIAL_BACKOFF_MS: u64 = 250;
56const DEAD_RECLAIM_MAX_BACKOFF_MS: u64 = 5_000;
57
58/// A heartbeat normally keeps one descriptor per lease open between beats
59/// instead of opening and closing the file on every beat. Closing a lease
60/// descriptor is expensive on the live daemon: it pulls the write-back of the
61/// lease page into the closing thread, and with hundreds of long-lived leases on
62/// macOS that was 10% of a core. The handle is released only when this process
63/// replaces the lease, or when a beat finds the lease no longer its own. These
64/// entries let those replacements find the open handles; acquisition, ownership
65/// checks and reclaim paths on other threads keep their own short-lived opens.
66static NEXT_LEASE_SLOT: AtomicU64 = AtomicU64::new(0);
67static LEASE_FILES: OnceLock<Mutex<HashMap<usize, LeaseSlot>>> = OnceLock::new();
68static LEASE_SLOT_BY_PATH: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();
69
70/// One heartbeat handle, filed under the slot that owns it and, in
71/// `LEASE_SLOT_BY_PATH`, under the lease path it was opened for. The path entry
72/// is what lets a replacement release the handle for *its* lease without
73/// touching any other lease's handle.
74#[derive(Clone)]
75struct LeaseSlot {
76    handle: Weak<Mutex<Option<LeaseFile>>>,
77}
78
79// Lock files in these storage domains have the fixed layout
80// `<storage>/<domain>/<key>/<lock>`. Add a domain here when a new persistent
81// artifact lock is introduced. BackupStore's deeper `.locks` shape is handled
82// separately so maintenance never walks backup entry histories.
83// compress::trust owns this one lock directly under the storage root.
84// BackupStore scopes locks below each harness and session. Prefixes cover the
85// client-specific MCP and fingerprint-specific federated harness directories.
86
87#[derive(Clone, Copy, Debug, PartialEq, Eq)]
88enum ReclaimTokenState {
89    Alive,
90    DeadForeignHost,
91    Malformed,
92    Dead,
93}
94
95impl ReclaimTokenState {
96    fn as_str(self) -> &'static str {
97        match self {
98            Self::Alive => "alive",
99            Self::DeadForeignHost => "dead-foreign-host",
100            Self::Malformed => "malformed",
101            Self::Dead => "dead",
102        }
103    }
104}
105
106#[derive(Clone, Debug, PartialEq, Eq)]
107struct ReclaimTokenHeld {
108    pid: Option<u32>,
109    state: ReclaimTokenState,
110}
111
112#[derive(Debug)]
113enum ReclaimResult {
114    Removed,
115    Blocked(ReclaimTokenHeld),
116    Unchanged,
117}
118
119#[derive(Clone, Debug)]
120struct ReclaimBlockLogRecord {
121    last_emitted: Instant,
122    suppressed: u64,
123}
124
125/// Which live-owner conditions one acquisition already reported, so a single
126/// attempt that polls many times (a daemon waiting on its own long-lived lease)
127/// logs each condition once instead of on every poll.
128#[derive(Clone, Debug, Default)]
129struct LiveOwnerLogRecord {
130    stale_logged: bool,
131    long_held_logged: bool,
132}
133
134/// Per-acquisition record of which live-owner conditions it already reported.
135struct LiveOwnerLog {
136    record: LiveOwnerLogRecord,
137}
138
139impl LiveOwnerLog {
140    fn new() -> Self {
141        Self {
142            record: LiveOwnerLogRecord::default(),
143        }
144    }
145
146    fn first_stale(&mut self) -> bool {
147        !std::mem::replace(&mut self.record.stale_logged, true)
148    }
149
150    fn first_long_held(&mut self) -> bool {
151        !std::mem::replace(&mut self.record.long_held_logged, true)
152    }
153}
154
155static RECLAIM_BLOCK_LOGS: OnceLock<Mutex<HashMap<PathBuf, ReclaimBlockLogRecord>>> =
156    OnceLock::new();
157
158/// True for OS errors that mean "another actor is touching this exact lock path
159/// right now", as opposed to a real, persistent failure. On Windows a contended
160/// create/delete on the same file surfaces as ERROR_ACCESS_DENIED (5) or
161/// ERROR_SHARING_VIOLATION (32); `PermissionDenied` covers the former across
162/// platforms. These are retried as contention, never treated as fatal.
163fn is_transient_create_contention(error: &io::Error) -> bool {
164    if error.kind() == io::ErrorKind::PermissionDenied {
165        return true;
166    }
167    #[cfg(windows)]
168    {
169        // ERROR_SHARING_VIOLATION = 32. ERROR_ACCESS_DENIED = 5 maps to
170        // PermissionDenied above, but match it explicitly too in case the OS
171        // surfaces it as an Other-kind raw error.
172        if let Some(code) = error.raw_os_error() {
173            if code == 32 || code == 5 {
174                return true;
175            }
176        }
177    }
178    false
179}
180
181#[derive(Clone, Copy, Debug)]
182struct LockConfig {
183    heartbeat_interval_ms: u64,
184    heartbeat_refresh_interval_ms: u64,
185    stale_heartbeat_ms: u64,
186    live_owner_warn_ms: u64,
187    poll_interval_ms: u64,
188}
189
190impl LockConfig {
191    fn cross_host_stale_heartbeat_ms(self) -> u64 {
192        self.stale_heartbeat_ms.saturating_mul(5)
193    }
194
195    fn live_owner_warning_age_ms(self) -> u64 {
196        // A healthy lease can now be older than the old warning window. Allow
197        // one wake of jitter without changing the foreign-host takeover bound.
198        self.stale_heartbeat_ms.max(
199            self.heartbeat_refresh_interval_ms
200                .saturating_add(self.heartbeat_interval_ms),
201        )
202    }
203}
204
205impl Default for LockConfig {
206    fn default() -> Self {
207        Self {
208            heartbeat_interval_ms: HEARTBEAT_INTERVAL_MS,
209            heartbeat_refresh_interval_ms: HEARTBEAT_REFRESH_INTERVAL_MS,
210            stale_heartbeat_ms: STALE_HEARTBEAT_MS,
211            live_owner_warn_ms: LIVE_OWNER_WARN_MS,
212            poll_interval_ms: POLL_INTERVAL_MS,
213        }
214    }
215}
216
217#[rustfmt::skip]
218test_support_visibility! {
219#[derive(Clone, Debug, PartialEq, Eq)]
220struct ProcessIdentity {
221    #[cfg(any(test, feature = "test-support"))]
222    pub start_time: u64,
223    #[cfg(not(any(test, feature = "test-support")))]
224    start_time: u64,
225    boot_id: Option<String>,
226    #[cfg(any(test, feature = "test-support"))]
227    pub exited: bool,
228    #[cfg(not(any(test, feature = "test-support")))]
229    exited: bool,
230}
231}
232
233#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
234struct LockMetadata {
235    pid: u32,
236    hostname: String,
237    /// Identifies this PID incarnation so a process in a restarted PID namespace
238    /// cannot be mistaken for an owner that was hard-killed in an earlier launch.
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    process_start_time: Option<u64>,
241    /// Linux start times are relative to boot. Keeping the boot ID alongside the
242    /// raw jiffies prevents a reboot from making a newly recycled PID look like
243    /// an earlier owner whose start time happened to match.
244    #[serde(default, skip_serializing_if = "Option::is_none")]
245    boot_id: Option<String>,
246    created_at_ms: u64,
247    heartbeat_at_ms: u64,
248    /// Fencing nonce for writer leases. The owner re-reads the lock immediately
249    /// before publishing/writing and aborts if a stale guard has been usurped.
250    #[serde(default)]
251    writer_epoch: String,
252}
253
254/// Acquire a filesystem lock at `path`. Blocks until the lock is held.
255///
256/// The returned guard owns a background heartbeat thread; dropping it releases
257/// the lock and removes the lock file.
258pub fn acquire(path: &Path) -> Result<LockGuard, AcquireError> {
259    acquire_with_config(path, None, LockConfig::default())
260}
261
262/// Try to acquire a filesystem lock at `path` within `timeout`.
263pub fn try_acquire(path: &Path, timeout: Duration) -> Result<LockGuard, AcquireError> {
264    acquire_with_config(path, Some(timeout), LockConfig::default())
265}
266
267/// Preserve a caller's deadline across filesystem preparation instead of
268/// starting a fresh timeout after that work has finished. Always allow the
269/// first attempt: slow preparation does not imply another writer owns the lock.
270pub fn try_acquire_until(path: &Path, deadline: Instant) -> Result<LockGuard, AcquireError> {
271    crate::production_storage::refuse_write(path)?;
272    #[cfg(any(test, feature = "test-support"))]
273    retry_clock::before_acquire();
274    acquire_with_deadline(path, Some(deadline), false, true, LockConfig::default())
275}
276
277/// Try one lock acquisition attempt, then check once whether an existing stale
278/// lock can be taken over.
279///
280/// Read-only cache openers use this to switch to writer mode without waiting
281/// behind another process that is still building the cache. Malformed leases
282/// receive one poll interval of grace so a creator can finish writing before
283/// the existing guarded reclaim path is tried.
284pub fn try_acquire_once(path: &Path) -> Result<LockGuard, AcquireError> {
285    try_acquire(path, Duration::ZERO)
286}
287
288#[derive(Clone, Copy, Debug, PartialEq, Eq)]
289pub enum LockAvailability {
290    Available,
291    LiveOwner,
292    Stale,
293    Malformed,
294}
295
296enum ObservedLock {
297    Available,
298    LiveOwner(LockMetadata),
299    Stale(LockMetadata),
300    Malformed(serde_json::Error),
301}
302
303impl ObservedLock {
304    fn availability(&self) -> LockAvailability {
305        match self {
306            Self::Available => LockAvailability::Available,
307            Self::LiveOwner(_) => LockAvailability::LiveOwner,
308            Self::Stale(_) => LockAvailability::Stale,
309            Self::Malformed(_) => LockAvailability::Malformed,
310        }
311    }
312}
313
314/// Observe the same lease states used by acquisition, without taking a lock.
315/// Malformed contents are not proof of a dead owner: acquisition must still
316/// perform its grace-period reread and guarded reclaim. I/O failures remain
317/// errors rather than evidence about ownership.
318pub fn lock_availability(path: &Path) -> io::Result<LockAvailability> {
319    observe_lock(path, &current_hostname(), LockConfig::default())
320        .map(|observed| observed.availability())
321}
322
323fn observe_lock(path: &Path, hostname: &str, config: LockConfig) -> io::Result<ObservedLock> {
324    match read_lock_metadata(path) {
325        Ok(metadata) => {
326            if metadata_blocks_acquisition(&metadata, hostname, config, now_ms()) {
327                Ok(ObservedLock::LiveOwner(metadata))
328            } else {
329                Ok(ObservedLock::Stale(metadata))
330            }
331        }
332        Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
333            Ok(ObservedLock::Available)
334        }
335        Err(ReadLockError::Io(error)) => Err(error),
336        Err(ReadLockError::Malformed(error)) => Ok(ObservedLock::Malformed(error)),
337    }
338}
339
340fn metadata_blocks_acquisition(
341    metadata: &LockMetadata,
342    hostname: &str,
343    config: LockConfig,
344    now: u64,
345) -> bool {
346    if metadata.hostname != hostname {
347        now.saturating_sub(metadata.heartbeat_at_ms) <= config.cross_host_stale_heartbeat_ms()
348    } else {
349        lock_owner_is_alive(metadata)
350    }
351}
352
353pub struct LockGuard {
354    path: PathBuf,
355    metadata: LockMetadata,
356    shutdown: Arc<AtomicBool>,
357    heartbeat_failed: Arc<AtomicBool>,
358    heartbeat_done: mpsc::Receiver<()>,
359    heartbeat: Option<JoinHandle<()>>,
360    pump: HeartbeatPump,
361    /// The heartbeat thread's handle on the lease, shared with it so the guard
362    /// can close it before any replacement of the lease and so this process's
363    /// lease index can tell other threads to wait for it.
364    heartbeat_file: Arc<Mutex<Option<LeaseFile>>>,
365}
366
367impl LockGuard {
368    pub fn path(&self) -> &Path {
369        &self.path
370    }
371
372    pub fn writer_epoch(&self) -> &str {
373        &self.metadata.writer_epoch
374    }
375
376    /// Whether this guard's heartbeat is still running. `verify_writer_epoch`
377    /// treats a guard whose heartbeat stopped as unverified, because nothing
378    /// else would keep the lease's heartbeat fresh for other processes.
379    pub(crate) fn heartbeat_is_visible(&self) -> bool {
380        self.pump.is_visible()
381    }
382
383    /// Refresh this lease once through the guard's own handle, so a same-length
384    /// beat costs one write and no descriptor open or close. Tests use this to
385    /// drive beats from a single thread; runtime beats go through the pump.
386    #[cfg(any(test, feature = "test-support"))]
387    #[cfg_attr(not(test), allow(dead_code))]
388    fn heartbeat_once(&self) -> Result<(), HeartbeatError> {
389        heartbeat_once(&self.path, &self.metadata, &self.heartbeat_file)
390    }
391
392    /// Re-read the lock file and confirm that this guard still owns the writer
393    /// token. Writers call this right before saving published data or starting
394    /// SQLite writes so they stop if another process has taken over the lock.
395    pub fn verify_writer_epoch(&self) -> io::Result<bool> {
396        if self.heartbeat_failed.load(Ordering::Acquire) || !self.heartbeat_is_visible() {
397            return Ok(false);
398        }
399        match read_lock_metadata(&self.path) {
400            Ok(metadata) => Ok(lock_identity_matches(&metadata, &self.metadata)),
401            Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => Ok(false),
402            Err(ReadLockError::Io(error)) => Err(error),
403            Err(ReadLockError::Malformed(_)) => Ok(false),
404        }
405    }
406    #[rustfmt::skip]
407    test_support_visibility! {
408    /// Stop and join the heartbeat, closing its kept descriptor without
409    /// unlinking the lease. Retention uses this immediately before moving or
410    /// removing a cache tree: Windows cannot rename a directory containing an
411    /// open lease file. The lease remains on disk and excludes other writers
412    /// during the move; the guard must be dropped after the operation, even on
413    /// error. Do not stop it early: remote hosts still rely on heartbeat age.
414    pub(crate) fn stop_heartbeat_for_removal(&mut self) {
415        // Signal shutdown then unconditionally join the heartbeat thread
416        // BEFORE removing the lockfile. The earlier `recv_timeout(100ms)`
417        // implementation could let `remove_lock_if_owned` race with a
418        // still-alive heartbeat:
419        //
420        //   1. Drop signals shutdown, ack times out under CI load.
421        //   2. Drop calls `remove_lock_if_owned` → file removed.
422        //   3. Another caller acquires the lock → writes its metadata.
423        //   4. Our heartbeat (still alive, mid-rewrite
424        //      from before shutdown was checked) overwrites the new
425        //      owner's file with our stale metadata. heartbeat_once's
426        //      ownership check happens BEFORE the write, so it can race
427        //      with a concurrent acquire that flips ownership in between.
428        //   5. The new owner's heartbeat sees foreign metadata, exits
429        //      `NotOwner`. The new owner's drop sees foreign metadata,
430        //      `remove_lock_if_owned` returns `Ok(false)`, file persists.
431        //
432        // Always-joining bounds drop latency to one `park_timeout`
433        // iteration (~25ms) plus the current `heartbeat_once` IO —
434        // typically <500ms under CI load. The unused `heartbeat_done`
435        // channel is kept for backward compatibility with any external
436        // code that may still construct LockGuard manually, but Drop no
437        // longer relies on it.
438        self.shutdown.store(true, Ordering::Release);
439        if let Some(handle) = self.heartbeat.take() {
440            handle.thread().unpark();
441            let _ = handle.join();
442        }
443        // Drain any pending ack so the receiver doesn't carry stale state
444        // if this LockGuard is somehow re-used (it isn't today, but be
445        // defensive).
446        while self.heartbeat_done.try_recv().is_ok() {}
447
448        // Release the heartbeat handle before the lease file: closing any other
449        // descriptor to it now would drop the advisory locks this process holds
450        // on it, so the unlink and any concurrent replacement wait for this.
451        let mut handle = self
452            .heartbeat_file
453            .lock()
454            .unwrap_or_else(|poisoned| poisoned.into_inner());
455        *handle = None;
456        drop(handle);
457        // Stop publishing the slot so a later replacement for this path never
458        // waits on this guard's closed handle.
459        unregister_lease_slot(self.pump.slot, &self.path);
460        self.pump.visible.store(false, Ordering::Release);
461    }
462
463    }
464}
465
466impl Drop for LockGuard {
467    fn drop(&mut self) {
468        self.stop_heartbeat_for_removal();
469        match remove_lock_if_owned(&self.path, &self.metadata) {
470            Ok(true) => slog_debug!("released filesystem lock at {}", self.path.display()),
471            Ok(false) => {}
472            Err(error) => slog_warn!(
473                "failed to release filesystem lock at {}: {}",
474                self.path.display(),
475                error
476            ),
477        }
478    }
479}
480
481/// Run `replace`, a replacement of a lease file, after releasing the heartbeat
482/// handles this process publishes for leases.
483///
484/// Closing one descriptor to a file drops *all* the POSIX advisory locks this
485/// process holds on it, including on a descriptor another thread still keeps.
486/// A heartbeat holds its lease open between beats, so the process must not leave
487/// that descriptor to be closed by a replacement: this takes each published
488/// handle, drops the descriptor, and holds the handle's lock across `replace`.
489/// Because the guards are taken before the lock is released, a beat cannot open
490/// a lease into a slot this call is holding; a beat waits for the replacement
491/// and then opens the live file.
492fn with_lease_handles_closed<T>(
493    path: &Path,
494    replace: impl FnOnce() -> io::Result<T>,
495) -> io::Result<T> {
496    // Only this path's handle. Releasing every published handle would empty
497    // another lease's slot, and its next beat would reopen the file, giving
498    // back the per-beat descriptor churn the kept handle exists to avoid.
499    let slot = lease_slots_by_path()
500        .lock()
501        .unwrap_or_else(|poisoned| poisoned.into_inner())
502        .get(path)
503        .copied();
504    let handle = slot.and_then(|slot| {
505        lease_files()
506            .lock()
507            .unwrap_or_else(|poisoned| poisoned.into_inner())
508            .get(&slot)
509            .and_then(|entry| entry.handle.upgrade())
510    });
511    // Take the handle without waiting. A held lock means the heartbeat is
512    // mid-beat on this lease (or the caller is the beat itself), and a beat that
513    // already holds the descriptor keeps its own safety: it re-checks the path's
514    // identity and the owner before every write. Waiting here would deadlock
515    // against the very thread that has to finish the beat.
516    let mut released = Vec::new();
517    for handle in handle.iter() {
518        let Ok(mut slot) = handle.try_lock() else {
519            continue;
520        };
521        *slot = None;
522        released.push(slot);
523    }
524    let result = replace();
525    drop(released);
526    result
527}
528
529#[derive(Debug)]
530pub enum AcquireError {
531    Io(io::Error),
532    Timeout,
533}
534
535impl fmt::Display for AcquireError {
536    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537        match self {
538            AcquireError::Io(error) => write!(f, "filesystem lock I/O error: {error}"),
539            AcquireError::Timeout => write!(f, "timed out acquiring filesystem lock"),
540        }
541    }
542}
543
544impl std::error::Error for AcquireError {}
545
546impl From<io::Error> for AcquireError {
547    fn from(error: io::Error) -> Self {
548        AcquireError::Io(error)
549    }
550}
551
552fn acquire_with_config(
553    path: &Path,
554    timeout: Option<Duration>,
555    config: LockConfig,
556) -> Result<LockGuard, AcquireError> {
557    crate::production_storage::refuse_write(path)?;
558    #[cfg(any(test, feature = "test-support"))]
559    retry_clock::before_acquire();
560    let deadline = timeout.map(|timeout| acquisition_now() + timeout);
561    acquire_with_deadline(
562        path,
563        deadline,
564        timeout == Some(Duration::ZERO),
565        false,
566        config,
567    )
568}
569
570fn acquire_with_deadline(
571    path: &Path,
572    deadline: Option<Instant>,
573    allow_malformed_grace: bool,
574    strict_deadline: bool,
575    config: LockConfig,
576) -> Result<LockGuard, AcquireError> {
577    let hostname = current_hostname();
578    // Report a live blocking owner once, not once per poll this acquisition
579    // makes: a daemon with many roots re-attempts its own long-lived leases
580    // constantly, and every attempt would otherwise repeat the same warning.
581    let mut live_owner_log = LiveOwnerLog::new();
582    let mut transient_create_failures: u32 = 0;
583    let mut attempted_once = false;
584    let mut dead_reclaim_blocked_attempts = 0_u32;
585    // A zero-timeout acquire still gets one immediate retry after it removes a
586    // stale lock; otherwise it would reap the dead owner and report Timeout.
587    let mut immediate_retry_budget = 0_u8;
588    let mut malformed_grace_used = false;
589
590    loop {
591        if attempted_once {
592            if immediate_retry_budget > 0 && !strict_deadline {
593                immediate_retry_budget -= 1;
594            } else if let Some(deadline) = deadline {
595                if acquisition_now() >= deadline {
596                    return Err(AcquireError::Timeout);
597                }
598            }
599        }
600        attempted_once = true;
601        #[cfg(any(test, feature = "test-support"))]
602        retry_clock::note_attempt();
603
604        match create_new_lock(path, &hostname, config) {
605            Ok(guard) => return Ok(guard),
606            // The lock file already exists — fall through to inspect its owner.
607            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
608            // Transient contention (chiefly Windows: a concurrent create/delete
609            // on this exact path surfaces as access-denied/sharing-violation
610            // rather than already-exists). Back off one poll interval and retry,
611            // bounded so a persistent failure still propagates instead of
612            // spinning forever.
613            Err(error) if is_transient_create_contention(&error) => {
614                transient_create_failures += 1;
615                if transient_create_failures > MAX_TRANSIENT_CREATE_RETRIES {
616                    return Err(error.into());
617                }
618                sleep_until_retry(deadline, config.poll_interval_ms)?;
619                continue;
620            }
621            Err(error) => return Err(error.into()),
622        }
623        transient_create_failures = 0;
624
625        let observed = match observe_lock(path, &hostname, config) {
626            Ok(observed) => observed,
627            // The same Windows contention the create arm above tolerates can
628            // land here instead: a lock file pending deletion is visible to
629            // the create attempt but denies the open that reads it. Only the
630            // create path recognised that spelling of "busy", so a race that
631            // was meant to be retried propagated as a hard failure and
632            // panicked a caller mid-write (Windows CI, 2026-09-22).
633            Err(error) if is_transient_create_contention(&error) => {
634                transient_create_failures += 1;
635                if transient_create_failures > MAX_TRANSIENT_CREATE_RETRIES {
636                    return Err(error.into());
637                }
638                sleep_until_retry(deadline, config.poll_interval_ms)?;
639                continue;
640            }
641            Err(error) => return Err(error.into()),
642        };
643        let availability = observed.availability();
644        let metadata = match observed {
645            ObservedLock::LiveOwner(metadata) | ObservedLock::Stale(metadata) => metadata,
646            ObservedLock::Available => {
647                immediate_retry_budget = 1;
648                continue;
649            }
650            ObservedLock::Malformed(error) => {
651                // A just-created O_EXCL file is visible before its owner has
652                // finished writing JSON. Give that transient creation window
653                // one poll interval before treating malformed contents as stale.
654                // Zero-timeout callers also need this one grace read to reach
655                // reclaim, but must not loop if another actor keeps corrupting
656                // the lease or prevents its removal.
657                if allow_malformed_grace && !malformed_grace_used {
658                    malformed_grace_used = true;
659                    sleep_until_retry(None, config.poll_interval_ms)?;
660                } else {
661                    sleep_until_retry(deadline, config.poll_interval_ms)?;
662                }
663                match read_lock_metadata(path) {
664                    Ok(_) => continue,
665                    Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
666                        continue;
667                    }
668                    Err(ReadLockError::Io(error)) => return Err(error.into()),
669                    Err(ReadLockError::Malformed(_)) => {}
670                }
671                slog_warn!(
672                    "removing malformed filesystem lock at {}: {}",
673                    path.display(),
674                    error
675                );
676                let judged = fs::read(path)?;
677                if serde_json::from_slice::<LockMetadata>(&judged).is_ok() {
678                    continue;
679                }
680                #[cfg(any(test, feature = "test-support"))]
681                run_acquisition_hook(&BEFORE_MALFORMED_RECLAIM);
682                if reclaim_malformed_lock(path, &judged)? {
683                    immediate_retry_budget = 1;
684                }
685                continue;
686            }
687        };
688
689        let now = now_ms();
690        let since_heartbeat = now.saturating_sub(metadata.heartbeat_at_ms);
691
692        if metadata.hostname != hostname {
693            dead_reclaim_blocked_attempts = 0;
694            let cross_host_stale_ms = config.cross_host_stale_heartbeat_ms();
695            if availability == LockAvailability::Stale {
696                match reclaim_lock_file(path, &metadata)? {
697                    ReclaimResult::Removed => {
698                        slog_warn!(
699                            "reclaimed cross-host filesystem lock at {} from host {} after stale heartbeat ({}ms > {}ms)",
700                            path.display(),
701                            metadata.hostname,
702                            since_heartbeat,
703                            cross_host_stale_ms
704                        );
705                        immediate_retry_budget = 1;
706                    }
707                    ReclaimResult::Blocked(holder) => {
708                        log_reclaim_blocked(path, &holder);
709                        sleep_until_retry(deadline, config.poll_interval_ms)?;
710                    }
711                    ReclaimResult::Unchanged => {
712                        sleep_until_retry(deadline, config.poll_interval_ms)?;
713                    }
714                }
715                continue;
716            }
717            sleep_until_retry(deadline, config.poll_interval_ms)?;
718            continue;
719        }
720
721        if availability == LockAvailability::Stale {
722            match reclaim_lock_file(path, &metadata)? {
723                ReclaimResult::Removed => {
724                    slog_info!(
725                        "removing filesystem lock at {} from dead or recycled PID {}",
726                        path.display(),
727                        metadata.pid
728                    );
729                    immediate_retry_budget = 1;
730                    dead_reclaim_blocked_attempts = 0;
731                }
732                ReclaimResult::Blocked(holder) => {
733                    log_reclaim_blocked(path, &holder);
734                    let backoff_ms = dead_reclaim_backoff_ms(
735                        dead_reclaim_blocked_attempts,
736                        config.poll_interval_ms,
737                    );
738                    dead_reclaim_blocked_attempts = dead_reclaim_blocked_attempts.saturating_add(1);
739                    sleep_until_retry(deadline, backoff_ms)?;
740                }
741                ReclaimResult::Unchanged => {
742                    dead_reclaim_blocked_attempts = 0;
743                    sleep_until_retry(deadline, config.poll_interval_ms)?;
744                }
745            }
746            continue;
747        }
748        dead_reclaim_blocked_attempts = 0;
749
750        if since_heartbeat > config.live_owner_warning_age_ms() && live_owner_log.first_stale() {
751            // Same-host PID plus start-time identity is authoritative. A
752            // SIGSTOP'd process, suspended VM, or sleeping laptop can miss
753            // heartbeats and later resume inside the critical section. Breaking
754            // that lock would allow split-brain writers, so a paused matching
755            // owner blocks acquirers until it resumes and releases the lock or
756            // dies. PID namespaces restart numbering after hard-killed owners,
757            // which turns this safety rule into a deadlock unless the start time
758            // distinguishes the unrelated process that reused the PID.
759            slog_warn!(
760                "filesystem lock at {} held by live PID {} has stale heartbeat ({}ms); NOT breaking",
761                path.display(),
762                metadata.pid,
763                since_heartbeat
764            );
765        }
766
767        let held_for = now.saturating_sub(metadata.created_at_ms);
768        if held_for > config.live_owner_warn_ms && live_owner_log.first_long_held() {
769            if metadata.pid == std::process::id() {
770                // A lease this process holds and keeps heartbeating is a
771                // long-lived writer (an inspect or callgraph writer lease lives
772                // as long as its cache), so nothing is wrong and nothing is at
773                // risk. Report it at debug level so the acquisition trace still
774                // shows why it is waiting.
775                slog_debug!(
776                    "filesystem lock at {} is held by a live lease of this process for >10min; \
777                     waiting without breaking it",
778                    path.display()
779                );
780            } else {
781                slog_warn!(
782                    "filesystem lock at {} held >10min by live heartbeating PID {}; NOT breaking",
783                    path.display(),
784                    metadata.pid
785                );
786            }
787        }
788
789        sleep_until_retry(deadline, config.poll_interval_ms)?;
790    }
791}
792
793fn create_new_lock(path: &Path, hostname: &str, config: LockConfig) -> io::Result<LockGuard> {
794    // Anchor the first deadline before publication, not when the new thread
795    // eventually gets CPU time. A late-starting thread must refresh immediately.
796    let first_refresh =
797        Instant::now() + Duration::from_millis(config.heartbeat_refresh_interval_ms);
798    let now = now_ms();
799    let pid = std::process::id();
800    let process_identity = process_identity(pid);
801    let metadata = LockMetadata {
802        pid,
803        hostname: hostname.to_string(),
804        process_start_time: process_identity
805            .as_ref()
806            .map(|identity| identity.start_time),
807        boot_id: process_identity.and_then(|identity| identity.boot_id),
808        created_at_ms: now,
809        heartbeat_at_ms: now,
810        writer_epoch: format!("{pid}-{}", now_nanos()),
811    };
812
813    create_lock_file_atomically(path, &metadata)?;
814
815    let (heartbeat_pump, heartbeat_file) =
816        HeartbeatPump::attach(path, &metadata).inspect_err(|_| {
817            let _ = remove_lock_if_owned(path, &metadata);
818        })?;
819
820    let shutdown = Arc::new(AtomicBool::new(false));
821    let heartbeat_failed = Arc::new(AtomicBool::new(false));
822    let (done_tx, done_rx) = mpsc::channel();
823    let heartbeat_path = path.to_path_buf();
824    let heartbeat_shutdown = Arc::clone(&shutdown);
825    let heartbeat_failed_for_thread = Arc::clone(&heartbeat_failed);
826    let heartbeat_pump_for_thread = heartbeat_pump.clone();
827    let heartbeat = spawn_heartbeat(move || {
828        let heartbeat_shutdown_for_run = Arc::clone(&heartbeat_shutdown);
829        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
830            run_heartbeat(
831                heartbeat_path,
832                &heartbeat_pump_for_thread,
833                heartbeat_shutdown_for_run,
834                config,
835                first_refresh,
836            );
837        }));
838        if result.is_err() || !heartbeat_shutdown.load(Ordering::Acquire) {
839            heartbeat_failed_for_thread.store(true, Ordering::Release);
840        }
841        let _ = done_tx.send(());
842    })
843    .inspect_err(|_| {
844        // Thread creation failed after publication; do not strand this PID's
845        // lease, or unlink a replacement that no longer has our epoch.
846        let _ = remove_lock_if_owned(path, &metadata);
847    })?;
848
849    slog_debug!("acquired filesystem lock at {}", path.display());
850    #[cfg(any(test, feature = "test-support"))]
851    io_ledger::record(|ledger| ledger.acquisitions += 1);
852
853    Ok(LockGuard {
854        path: path.to_path_buf(),
855        metadata,
856        shutdown,
857        heartbeat_failed,
858        heartbeat_done: done_rx,
859        heartbeat: Some(heartbeat),
860        pump: heartbeat_pump,
861        heartbeat_file,
862    })
863}
864
865#[cfg(any(test, feature = "test-support"))]
866thread_local! {
867    pub static BEFORE_MALFORMED_RECLAIM: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
868    pub static BEFORE_HEARTBEAT_SPAWN_FAILURE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
869}
870
871#[cfg(any(test, feature = "test-support"))]
872fn run_acquisition_hook(
873    hook: &'static std::thread::LocalKey<std::cell::RefCell<Option<Box<dyn FnOnce()>>>>,
874) -> bool {
875    let action = hook.with(|slot| slot.borrow_mut().take());
876    if let Some(action) = action {
877        action();
878        true
879    } else {
880        false
881    }
882}
883
884fn spawn_heartbeat(run: impl FnOnce() + Send + 'static) -> io::Result<thread::JoinHandle<()>> {
885    #[cfg(any(test, feature = "test-support"))]
886    if run_acquisition_hook(&BEFORE_HEARTBEAT_SPAWN_FAILURE) {
887        return Err(io::Error::other("injected heartbeat spawn failure"));
888    }
889    thread::Builder::new()
890        .name("aft-fs-lock-heartbeat".to_string())
891        .spawn(run)
892}
893
894fn run_heartbeat(
895    path: PathBuf,
896    pump: &HeartbeatPump,
897    shutdown: Arc<AtomicBool>,
898    config: LockConfig,
899    mut next_refresh: Instant,
900) {
901    // Number of consecutive retry intervals before the warning window elapses.
902    // Local takeover still requires proof of a dead or recycled process.
903    // Beyond this point a sustained failure is genuinely dangerous, so we
904    // escalate the log from warn to error — but we still keep retrying.
905    let stale_intervals = config
906        .stale_heartbeat_ms
907        .checked_div(config.heartbeat_interval_ms.max(1))
908        .unwrap_or(3)
909        .max(1);
910    let mut consecutive_transient_failures: u64 = 0;
911    let refresh_interval = Duration::from_millis(config.heartbeat_refresh_interval_ms);
912
913    loop {
914        if shutdown.load(Ordering::Acquire) {
915            return;
916        }
917
918        match refresh_heartbeat_if_due(pump, &mut next_refresh, refresh_interval, Instant::now()) {
919            Ok(false) => {}
920            Ok(true) => {
921                if consecutive_transient_failures > 0 {
922                    slog_info!(
923                        "filesystem lock at {} heartbeat recovered after {} transient failure(s)",
924                        path.display(),
925                        consecutive_transient_failures
926                    );
927                    consecutive_transient_failures = 0;
928                }
929            }
930            Err(error) if heartbeat_error_is_terminal(&error) => {
931                // Terminal states: the lock is provably gone or owned by
932                // someone else. Continuing to write would clobber a new owner's
933                // metadata (the exact race documented in LockGuard::drop), so
934                // stop heartbeating.
935                #[cfg(any(test, feature = "test-support"))]
936                pump.mark_stopped();
937                slog_error!(
938                    "{}; stopping heartbeat",
939                    terminal_heartbeat_message(&path, &error)
940                );
941                return;
942            }
943            Err(error) => {
944                // Transient states: a temporary I/O hiccup (disk/NFS blip,
945                // quota) or a read that raced a concurrent writer mid-write
946                // (momentarily unparseable file). A single such error must NOT
947                // permanently kill the heartbeat — that would silently stop
948                // refreshing heartbeat_at_ms while the guard holder keeps
949                // running its critical section, letting another process reclaim
950                // the lock after the stale window and produce concurrent
951                // writers. Log and retry on the next interval; a later success
952                // resumes heartbeating automatically.
953                consecutive_transient_failures += 1;
954                log_transient_heartbeat_failure(
955                    &path,
956                    &transient_heartbeat_reason(&error),
957                    consecutive_transient_failures,
958                    stale_intervals,
959                );
960            }
961        }
962        thread::park_timeout(Duration::from_millis(config.heartbeat_interval_ms));
963    }
964}
965
966fn refresh_heartbeat_if_due(
967    pump: &HeartbeatPump,
968    next_refresh: &mut Instant,
969    interval: Duration,
970    now: Instant,
971) -> Result<bool, HeartbeatError> {
972    if now < *next_refresh {
973        return Ok(false);
974    }
975    // A delayed wake refreshes immediately. Only success advances the deadline,
976    // so transient failures retry at the short wake cadence, not another 25s.
977    pump.heartbeat_once()?;
978    *next_refresh = now + interval;
979    Ok(true)
980}
981
982/// A heartbeat failure is terminal when the lock is provably no longer ours to
983/// refresh: it was removed (`LockGone`) or a different owner now holds it
984/// (`NotOwner`). I/O and malformed-read failures are treated as transient —
985/// they are typically temporary disk/NFS hiccups or a read that raced a
986/// concurrent writer — so the heartbeat retries rather than dying.
987fn heartbeat_error_is_terminal(error: &HeartbeatError) -> bool {
988    matches!(
989        error,
990        HeartbeatError::LockGone | HeartbeatError::NotOwner | HeartbeatError::NotPumped
991    )
992}
993
994fn terminal_heartbeat_message(path: &Path, error: &HeartbeatError) -> String {
995    match error {
996        HeartbeatError::LockGone => {
997            format!("filesystem lock at {} disappeared", path.display())
998        }
999        HeartbeatError::NotOwner => format!(
1000            "filesystem lock at {} is no longer owned by this guard",
1001            path.display()
1002        ),
1003        HeartbeatError::NotPumped => format!(
1004            "filesystem lock at {} heartbeat handle was released by this process",
1005            path.display()
1006        ),
1007        // Not reachable for non-terminal errors, but keep a sensible string.
1008        HeartbeatError::Io(error) => {
1009            format!("filesystem lock at {} I/O error: {error}", path.display())
1010        }
1011        HeartbeatError::Malformed(error) => {
1012            format!(
1013                "filesystem lock at {} became malformed: {error}",
1014                path.display()
1015            )
1016        }
1017    }
1018}
1019
1020fn transient_heartbeat_reason(error: &HeartbeatError) -> String {
1021    match error {
1022        HeartbeatError::Io(error) => format!("I/O error: {error}"),
1023        HeartbeatError::Malformed(error) => format!("became malformed: {error}"),
1024        HeartbeatError::LockGone => "lock disappeared".to_string(),
1025        HeartbeatError::NotOwner => "lock no longer owned".to_string(),
1026        HeartbeatError::NotPumped => "heartbeat handle released".to_string(),
1027    }
1028}
1029
1030/// Log a transient heartbeat failure, escalating to error exactly once when the
1031/// failures have lasted long enough that the lock is now reclaimable by another
1032/// owner. Beyond that point we stay quiet to avoid log spam while still
1033/// retrying — the holder has already been warned the lock is at risk.
1034fn log_transient_heartbeat_failure(
1035    path: &Path,
1036    reason: &str,
1037    consecutive_failures: u64,
1038    stale_intervals: u64,
1039) {
1040    if consecutive_failures < stale_intervals {
1041        slog_warn!(
1042            "transient failure to heartbeat filesystem lock at {}: {}; retrying (attempt {})",
1043            path.display(),
1044            reason,
1045            consecutive_failures
1046        );
1047    } else if consecutive_failures == stale_intervals {
1048        slog_error!(
1049            "filesystem lock at {} has failed {} consecutive heartbeats: {}; \
1050             the lock may now be reclaimed by another owner — continuing to retry",
1051            path.display(),
1052            consecutive_failures,
1053            reason
1054        );
1055    }
1056}
1057
1058/// The heartbeat thread's handle on one lease.
1059///
1060/// The thread keeps the lease open between beats so a beat costs one write
1061/// instead of an open, a read and a close. A `File` released on its own thread
1062/// closes there, and on macOS the close is where the lease's write-back runs,
1063/// so per-beat close/open churn put the write-back cost on the heartbeat
1064/// thread. Three rules bound how long the handle lives:
1065///
1066/// * Another thread of this process that has to replace the lease needs every
1067///   handle to it released first (`LEASE_FILES`), because closing any
1068///   descriptor to a file drops the advisory locks this process holds on it.
1069///   That is why the replacement paths close before they rename.
1070/// * A beat never trusts the handle blindly. Before reading it compares the
1071///   file the handle refers to with the file the path now names (device and
1072///   inode, or on Windows volume serial number and file index). Unix reads both
1073///   with a stat; Windows reads the descriptor's identity from its own handle
1074///   and opens the path for attributes only, so that arm does take one
1075///   short-lived handle per beat. A different file retires the old handle. If
1076///   the path still carries this guard's owner identity, the beat reopens it
1077///   immediately; a different owner stops the heartbeat instead of refreshing
1078///   the orphan the handle still holds.
1079///   When the handle was released by a replacement, the next beat opens the path
1080///   again. Releases happen on the heartbeat thread, or on the thread running a
1081///   replacement through `with_lease_handles_closed`.
1082/// * Failing that check, the bytes read through the handle must still carry this
1083///   guard's identity, and a path that is gone is reported as `LockGone`. A
1084///   guard whose heartbeat stopped reports the lease as unverified; see
1085///   `heartbeat_is_visible`.
1086#[derive(Debug)]
1087struct HeartbeatPump {
1088    path: PathBuf,
1089    slot: usize,
1090    /// Full owner identity, recorded at attach. The path can later hold a
1091    /// different owner: a reclaim by any process mints a new epoch, so a path
1092    /// whose identity no longer matches was released and re-indexed for its new
1093    /// owner. A reclaim happens when the owner is judged dead, or when another
1094    /// host's heartbeat went stale beyond its extended window.
1095    owner: Mutex<LockMetadata>,
1096    visible: AtomicBool,
1097    /// Set when the heartbeat ends for a reason other than the guard closing.
1098    /// Tests read it to tell "a later beat failed" from "the beat was still
1099    /// retrying", which a file timestamp cannot show.
1100    #[cfg(any(test, feature = "test-support"))]
1101    stopped: Arc<AtomicBool>,
1102}
1103
1104fn lease_files() -> &'static Mutex<HashMap<usize, LeaseSlot>> {
1105    LEASE_FILES.get_or_init(|| Mutex::new(HashMap::new()))
1106}
1107
1108fn lease_slots_by_path() -> &'static Mutex<HashMap<PathBuf, usize>> {
1109    LEASE_SLOT_BY_PATH.get_or_init(|| Mutex::new(HashMap::new()))
1110}
1111
1112/// Record a handle under its slot and its path. A path holds one heartbeat's
1113/// handle, so a later registration for the same path supersedes the earlier
1114/// entry; the old handle belongs to a guard that has released or lost the lease.
1115fn register_lease_slot(slot: usize, path: &Path, handle: &Arc<Mutex<Option<LeaseFile>>>) {
1116    lease_files()
1117        .lock()
1118        .unwrap_or_else(|poisoned| poisoned.into_inner())
1119        .insert(
1120            slot,
1121            LeaseSlot {
1122                handle: Arc::downgrade(handle),
1123            },
1124        );
1125    lease_slots_by_path()
1126        .lock()
1127        .unwrap_or_else(|poisoned| poisoned.into_inner())
1128        .insert(path.to_path_buf(), slot);
1129}
1130
1131/// Forget a slot and, if it still owns the path entry, that entry too.
1132fn unregister_lease_slot(slot: usize, path: &Path) {
1133    lease_files()
1134        .lock()
1135        .unwrap_or_else(|poisoned| poisoned.into_inner())
1136        .remove(&slot);
1137    let mut by_path = lease_slots_by_path()
1138        .lock()
1139        .unwrap_or_else(|poisoned| poisoned.into_inner());
1140    if by_path.get(path).copied() == Some(slot) {
1141        by_path.remove(path);
1142    }
1143}
1144
1145impl Clone for HeartbeatPump {
1146    fn clone(&self) -> Self {
1147        Self {
1148            path: self.path.clone(),
1149            slot: self.slot,
1150            owner: Mutex::new(
1151                self.owner
1152                    .lock()
1153                    .unwrap_or_else(|poisoned| poisoned.into_inner())
1154                    .clone(),
1155            ),
1156            visible: AtomicBool::new(self.is_visible()),
1157            #[cfg(any(test, feature = "test-support"))]
1158            stopped: Arc::clone(&self.stopped),
1159        }
1160    }
1161}
1162
1163impl HeartbeatPump {
1164    /// Register a heartbeat handle for a newly created lease and publish it in
1165    /// this process's lease index.
1166    fn attach(
1167        path: &Path,
1168        owner: &LockMetadata,
1169    ) -> io::Result<(Self, Arc<Mutex<Option<LeaseFile>>>)> {
1170        let file = Arc::new(Mutex::new(Some(
1171            open_lease_for_heartbeat(path).map_err(heartbeat_io_error)?,
1172        )));
1173        let slot = NEXT_LEASE_SLOT.fetch_add(1, Ordering::Relaxed) as usize;
1174        {
1175            let mut registry = lease_files()
1176                .lock()
1177                .unwrap_or_else(|poisoned| poisoned.into_inner());
1178            if registry.len() > 4096 {
1179                registry.retain(|_, known| known.handle.strong_count() > 0);
1180            }
1181        }
1182        register_lease_slot(slot, path, &file);
1183        Ok((
1184            Self {
1185                path: path.to_path_buf(),
1186                slot,
1187                owner: Mutex::new(owner.clone()),
1188                visible: AtomicBool::new(true),
1189                #[cfg(any(test, feature = "test-support"))]
1190                stopped: Arc::new(AtomicBool::new(false)),
1191            },
1192            file,
1193        ))
1194    }
1195
1196    fn is_visible(&self) -> bool {
1197        self.visible.load(Ordering::Acquire)
1198    }
1199
1200    #[cfg(any(test, feature = "test-support"))]
1201    fn mark_stopped(&self) {
1202        self.stopped.store(true, Ordering::Release);
1203    }
1204
1205    /// Whether the heartbeat thread ended by itself instead of at guard drop.
1206    #[cfg(any(test, feature = "test-support"))]
1207    #[cfg_attr(not(test), allow(dead_code))]
1208    pub(super) fn heartbeat_stopped(&self) -> bool {
1209        self.stopped.load(Ordering::Acquire)
1210    }
1211
1212    /// One beat: read the lease through the kept handle, refresh the timestamp,
1213    /// and write it back through the same handle, opening the lease only when
1214    /// no handle is kept.
1215    fn heartbeat_once(&self) -> Result<(), HeartbeatError> {
1216        if !self.is_visible() {
1217            return Err(HeartbeatError::NotPumped);
1218        }
1219        let mut reopened = false;
1220        loop {
1221            let handle = {
1222                let registry = lease_files()
1223                    .lock()
1224                    .unwrap_or_else(|poisoned| poisoned.into_inner());
1225                registry
1226                    .get(&self.slot)
1227                    .and_then(|entry| entry.handle.upgrade())
1228            };
1229            let Some(handle) = handle else {
1230                return Err(HeartbeatError::NotPumped);
1231            };
1232            match self.beat(&handle) {
1233                Ok(()) => return Ok(()),
1234                // The lease on disk is not the one this handle was opened for.
1235                // If it is no longer this process's lease, stop instead of
1236                // writing over another owner's heartbeat; otherwise the path
1237                // was replaced under the handle (a plain rewrite, or a stale
1238                // rename), so the next attempt reads the live file.
1239                Err(HeartbeatError::NotOwner) => {
1240                    self.retire_handle(&handle);
1241                    if self.release_if_reclaimed() {
1242                        return Err(HeartbeatError::NotOwner);
1243                    }
1244                    // A same-owner replacement is already safe to reopen. An
1245                    // extra heartbeat-interval sleep here leaves the live path
1246                    // stale even though the inode change was detected. Retry
1247                    // once now; repeated replacements remain transient and are
1248                    // retried by the normal heartbeat loop without spinning.
1249                    if reopened {
1250                        return Err(HeartbeatError::Io(io::Error::new(
1251                            io::ErrorKind::WouldBlock,
1252                            "lease replaced repeatedly during heartbeat",
1253                        )));
1254                    }
1255                    reopened = true;
1256                }
1257                // A partial rewrite does not prove ownership was lost. Retire
1258                // the descriptor so the next scheduled beat opens the live
1259                // path, including when recovery replaces the inode atomically.
1260                // Let the heartbeat loop schedule that retry: waiting here can
1261                // turn a transient read into a terminal NotOwner timeout.
1262                Err(error @ HeartbeatError::Malformed(_)) => {
1263                    self.retire_handle(&handle);
1264                    return Err(error);
1265                }
1266                Err(error) => return Err(error),
1267            }
1268        }
1269    }
1270
1271    fn beat(&self, handle: &Arc<Mutex<Option<LeaseFile>>>) -> Result<(), HeartbeatError> {
1272        let owner = self
1273            .owner
1274            .lock()
1275            .unwrap_or_else(|poisoned| poisoned.into_inner())
1276            .clone();
1277        let needs_open = handle
1278            .lock()
1279            .unwrap_or_else(|poisoned| poisoned.into_inner())
1280            .is_none();
1281        if needs_open {
1282            // Publish the reopened descriptor under the slot before the beat:
1283            // the handle another thread's replacement waits for must always be
1284            // the one this process holds. Opening inside the beat would leave a
1285            // window where a replacement renames the lease the beat is not
1286            // looking at.
1287            let file = open_lease_for_heartbeat(&self.path)?;
1288            let mut slot = handle
1289                .lock()
1290                .unwrap_or_else(|poisoned| poisoned.into_inner());
1291            if slot.is_none() {
1292                *slot = Some(file);
1293            }
1294        }
1295        heartbeat_once(&self.path, &owner, handle)
1296    }
1297
1298    /// Release the lease descriptor but keep the slot registered, so the next
1299    /// beat reopens the lease into it. Dropping the slot instead would leave the
1300    /// heartbeat with no handle to find, and it would stop.
1301    fn retire_handle(&self, handle: &Arc<Mutex<Option<LeaseFile>>>) {
1302        let mut slot = handle
1303            .lock()
1304            .unwrap_or_else(|poisoned| poisoned.into_inner());
1305        *slot = None;
1306    }
1307
1308    fn release_if_reclaimed(&self) -> bool {
1309        match read_lock_metadata(&self.path) {
1310            Err(ReadLockError::Malformed(_)) => false,
1311            Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => true,
1312            Err(ReadLockError::Io(_)) => false,
1313            Ok(on_disk) => {
1314                let owner = self
1315                    .owner
1316                    .lock()
1317                    .unwrap_or_else(|poisoned| poisoned.into_inner());
1318                !lock_identity_matches(&on_disk, &owner)
1319            }
1320        }
1321    }
1322}
1323
1324/// Refresh `heartbeat_at_ms` in a lease this guard owns.
1325///
1326/// Durability: a heartbeat only has to be visible to other processes, so this
1327/// path never fsyncs the file or its directory. If the machine crashes before
1328/// the page cache is written back, the lease on disk just carries an older
1329/// heartbeat and looks stale sooner, which the stale-lease rules already
1330/// handle. Creation and reclaim tokens also need only visibility: ownership
1331/// depends on a live process identity, which cannot survive a machine crash.
1332///
1333/// The rewrite happens in place on `handle`, whose contents were just checked
1334/// for ownership: no new inode per beat, and no window in which the path is
1335/// missing (which other code reads as `LockGone`). Serialization is
1336/// deterministic, so only the digits of `heartbeat_at_ms` differ and the file
1337/// keeps its length; overwriting the same length from offset zero never leaves
1338/// a truncated or zero-length file. If the length would change (the timestamp
1339/// gained a digit), fall back to an unsynced temp-file rename, which still
1340/// replaces the path atomically.
1341///
1342/// `handle` is empty for a beat that has no kept descriptor; that beat opens
1343/// the lease for itself and releases it when it returns. A heartbeat thread
1344/// passes the handle it keeps, so a same-length beat opens and closes nothing;
1345/// a length change still writes a temp file and renames it.
1346fn heartbeat_once(
1347    path: &Path,
1348    owner: &LockMetadata,
1349    handle: &Mutex<Option<LeaseFile>>,
1350) -> Result<(), HeartbeatError> {
1351    let mut slot = handle
1352        .lock()
1353        .unwrap_or_else(|poisoned| poisoned.into_inner());
1354    // A kept descriptor only speaks for the lease while it is still the file
1355    // the path names. Another process's reclaim renames its own lease over the
1356    // path, which leaves our descriptor holding the old, unlinked file: reading
1357    // it would show our own identity, the beat would refresh the orphan and
1358    // report success, and the live lease would silently go stale. On Unix both
1359    // identities come from a stat, so this costs no descriptor there.
1360    if let Some(kept) = slot.as_mut() {
1361        let on_path = match LeaseFileIdentity::of_path(path) {
1362            Ok(identity) => identity,
1363            Err(error) if error.kind() == io::ErrorKind::NotFound => {
1364                return Err(HeartbeatError::LockGone);
1365            }
1366            Err(error) => return Err(HeartbeatError::Io(error)),
1367        };
1368        // A stat that cannot read the descriptor's identity is the only reason
1369        // this comparison is unavailable, and it may be the same failure that
1370        // hides a replacement. Retire the handle instead of trusting it: the
1371        // read below then opens the live file and compares the bytes, which is
1372        // the behaviour before the descriptor was kept between beats.
1373        match LeaseFileIdentity::of_file(kept.file()) {
1374            Some(held) if held != on_path => return Err(HeartbeatError::NotOwner),
1375            Some(_) => {}
1376            None => *slot = None,
1377        }
1378    }
1379    let mut opened = None;
1380    let file = match slot.as_mut() {
1381        Some(kept) => kept.file(),
1382        None => opened.insert(open_lease_for_heartbeat(path)?).file(),
1383    };
1384    file.seek(SeekFrom::Start(0)).map_err(HeartbeatError::Io)?;
1385    let mut current = Vec::new();
1386    file.read_to_end(&mut current).map_err(HeartbeatError::Io)?;
1387    let mut metadata: LockMetadata =
1388        serde_json::from_slice(&current).map_err(HeartbeatError::Malformed)?;
1389
1390    if !lock_identity_matches(&metadata, owner) {
1391        return Err(HeartbeatError::NotOwner);
1392    }
1393
1394    metadata.heartbeat_at_ms = now_ms();
1395    let next = lock_metadata_bytes(&metadata).map_err(HeartbeatError::Io)?;
1396    if next.len() == current.len() {
1397        file.seek(SeekFrom::Start(0)).map_err(HeartbeatError::Io)?;
1398        return write_lock_bytes(file, &next).map_err(HeartbeatError::Io);
1399    }
1400    // Close before replacing the path: a handle stays usable for later beats
1401    // only while it refers to the lease at this path. The replacement itself
1402    // also releases any handle this process publishes for the path.
1403    *slot = None;
1404    drop(opened);
1405    replace_lock_bytes_unsynced(path, &next).map_err(HeartbeatError::Io)
1406}
1407
1408/// What identifies one lease file on disk, independent of the name pointing at
1409/// it: device and inode on Unix, volume serial number and file index on
1410/// Windows. A rename gives the path a different file, so comparing the file a
1411/// heartbeat holds with the file the path now names tells whether the lease was
1412/// replaced under the kept descriptor.
1413#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1414struct LeaseFileIdentity {
1415    volume: u64,
1416    file: u64,
1417}
1418
1419impl LeaseFileIdentity {
1420    #[cfg(unix)]
1421    fn of_metadata(metadata: &fs::Metadata) -> Self {
1422        use std::os::unix::fs::MetadataExt;
1423        Self {
1424            volume: metadata.dev(),
1425            file: metadata.ino(),
1426        }
1427    }
1428
1429    /// Volume serial number and 64-bit file index from a handle. On Windows
1430    /// that pair is what an inode is on Unix. Creation time would not do: NTFS
1431    /// file-name tunneling gives a name reused within about 15 s the creation
1432    /// time of the entry that last had it, so a replaced lease could look
1433    /// unchanged.
1434    #[cfg(windows)]
1435    fn from_raw_handle(handle: windows_sys::Win32::Foundation::HANDLE) -> Option<Self> {
1436        use windows_sys::Win32::Storage::FileSystem::{
1437            GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
1438        };
1439        // SAFETY: an all-zero BY_HANDLE_FILE_INFORMATION is a valid value (plain
1440        // integers and FILETIME structs); the call only writes into it.
1441        let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
1442        // SAFETY: the caller owns `handle` and keeps it alive across this call,
1443        // and `info` is a valid out pointer.
1444        let ok = unsafe { GetFileInformationByHandle(handle, &mut info) } != 0;
1445        ok.then(|| Self {
1446            volume: u64::from(info.dwVolumeSerialNumber),
1447            file: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
1448        })
1449    }
1450
1451    /// The identity of the file behind an open descriptor, read from the
1452    /// descriptor's own handle: nothing is opened.
1453    #[cfg(unix)]
1454    fn of_file(file: &File) -> Option<Self> {
1455        file.metadata()
1456            .ok()
1457            .map(|metadata| Self::of_metadata(&metadata))
1458    }
1459
1460    #[cfg(windows)]
1461    fn of_file(file: &File) -> Option<Self> {
1462        use std::os::windows::io::AsRawHandle;
1463        Self::from_raw_handle(file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE)
1464    }
1465
1466    /// The identity of the file the path names now. On Unix this is a stat and
1467    /// opens nothing. Windows has no handle-free file index, so that arm opens
1468    /// the path for attributes only, sharing every access a heartbeat holds, and
1469    /// closes it before returning.
1470    #[cfg(unix)]
1471    fn of_path(path: &Path) -> io::Result<Self> {
1472        fs::metadata(path).map(|metadata| Self::of_metadata(&metadata))
1473    }
1474
1475    #[cfg(windows)]
1476    fn of_path(path: &Path) -> io::Result<Self> {
1477        use std::os::windows::ffi::OsStrExt;
1478        use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
1479        use windows_sys::Win32::Storage::FileSystem::{
1480            CreateFileW, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ,
1481            FILE_SHARE_WRITE, OPEN_EXISTING,
1482        };
1483
1484        /// Closes the attribute handle on every path out of this function.
1485        struct Closed(windows_sys::Win32::Foundation::HANDLE);
1486        impl Drop for Closed {
1487            fn drop(&mut self) {
1488                // SAFETY: this wrapper is only ever built from the handle
1489                // `CreateFileW` returned after it was checked against
1490                // `INVALID_HANDLE_VALUE`, and it is dropped exactly once.
1491                unsafe { CloseHandle(self.0) };
1492            }
1493        }
1494
1495        let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
1496        // SAFETY: `wide` is a NUL-terminated UTF-16 path that outlives the call;
1497        // the remaining arguments are plain flags and null pointers.
1498        let handle = unsafe {
1499            CreateFileW(
1500                wide.as_ptr(),
1501                FILE_READ_ATTRIBUTES,
1502                FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1503                std::ptr::null(),
1504                OPEN_EXISTING,
1505                0,
1506                std::ptr::null_mut(),
1507            )
1508        };
1509        if handle == INVALID_HANDLE_VALUE {
1510            return Err(io::Error::last_os_error());
1511        }
1512        let handle = Closed(handle);
1513        Self::from_raw_handle(handle.0)
1514            .ok_or_else(|| io::Error::other("lease path has no file identity"))
1515    }
1516
1517    #[cfg(not(any(unix, windows)))]
1518    fn of_file(_file: &File) -> Option<Self> {
1519        None
1520    }
1521
1522    #[cfg(not(any(unix, windows)))]
1523    fn of_path(_path: &Path) -> io::Result<Self> {
1524        Err(io::Error::new(
1525            io::ErrorKind::Unsupported,
1526            "no file identity on this platform",
1527        ))
1528    }
1529}
1530
1531fn open_lease_for_heartbeat(path: &Path) -> Result<LeaseFile, HeartbeatError> {
1532    let file = match OpenOptions::new().read(true).write(true).open(path) {
1533        Ok(file) => file,
1534        Err(error) if error.kind() == io::ErrorKind::NotFound => {
1535            return Err(HeartbeatError::LockGone);
1536        }
1537        Err(error) => return Err(HeartbeatError::Io(error)),
1538    };
1539    io_ledger::record(|ledger| ledger.opens += 1);
1540    Ok(LeaseFile(file))
1541}
1542
1543/// A descriptor the heartbeat opened, so its release is counted wherever it
1544/// happens: a beat that drops it, `LockGuard::drop`, or a lease replacement
1545/// that releases the published handle.
1546#[derive(Debug)]
1547struct LeaseFile(File);
1548
1549impl LeaseFile {
1550    fn file(&mut self) -> &mut File {
1551        &mut self.0
1552    }
1553}
1554
1555impl Drop for LeaseFile {
1556    fn drop(&mut self) {
1557        io_ledger::record(|ledger| ledger.closes += 1);
1558    }
1559}
1560
1561fn heartbeat_io_error(error: HeartbeatError) -> io::Error {
1562    match error {
1563        HeartbeatError::Io(error) => error,
1564        other => io::Error::other(format!("{other:?}")),
1565    }
1566}
1567
1568#[derive(Debug)]
1569enum HeartbeatError {
1570    Io(io::Error),
1571    LockGone,
1572    Malformed(serde_json::Error),
1573    NotOwner,
1574    NotPumped,
1575}
1576
1577#[derive(Debug)]
1578enum ReadLockError {
1579    Io(io::Error),
1580    Malformed(serde_json::Error),
1581}
1582
1583#[rustfmt::skip]
1584test_support_visibility! {
1585
1586/// Read a lease file, re-reading until two consecutive reads agree.
1587///
1588/// Heartbeats overwrite lease files in place, and a read that overlaps such a
1589/// write is not guaranteed to be atomic on every filesystem: it could mix old
1590/// and new digits of the timestamp. The contents are otherwise identical, so a
1591/// mixed read still parses, but the timestamp could look older than either
1592/// write. Two identical reads in a row rule that out. The retry is bounded;
1593/// after it the last read is returned as-is.
1594pub(crate) fn read_lease_settled(path: &Path) -> io::Result<Vec<u8>> {
1595    let mut previous = fs::read(path)?;
1596    for _ in 0..3 {
1597        let next = fs::read(path)?;
1598        if next == previous {
1599            return Ok(next);
1600        }
1601        previous = next;
1602    }
1603    Ok(previous)
1604}
1605}
1606
1607/// Parse a lease. An empty or partial file (for example one left by a crash
1608/// after an unsynced rename) is `Malformed`, which acquirers treat as a stale
1609/// lease to remove, never as a live owner.
1610fn read_lock_metadata(path: &Path) -> Result<LockMetadata, ReadLockError> {
1611    let bytes = read_lease_settled(path).map_err(ReadLockError::Io)?;
1612    serde_json::from_slice(&bytes).map_err(ReadLockError::Malformed)
1613}
1614
1615fn open_new_lock_file(path: &Path) -> io::Result<File> {
1616    let file = crate::private_storage::options()
1617        .write(true)
1618        .create_new(true)
1619        .open(path)?;
1620    io_ledger::record(|ledger| ledger.new_files += 1);
1621    Ok(file)
1622}
1623
1624fn lock_metadata_bytes(metadata: &LockMetadata) -> io::Result<Vec<u8>> {
1625    let mut bytes = serde_json::to_vec(metadata).map_err(io::Error::other)?;
1626    bytes.push(b'\n');
1627    Ok(bytes)
1628}
1629
1630fn write_lock_bytes(file: &mut File, bytes: &[u8]) -> io::Result<()> {
1631    file.write_all(bytes)?;
1632    io_ledger::record(|ledger| ledger.bytes_written += bytes.len() as u64);
1633    Ok(())
1634}
1635
1636fn write_lock_metadata_to_file(file: &mut File, metadata: &LockMetadata) -> io::Result<()> {
1637    write_lock_bytes(file, &lock_metadata_bytes(metadata)?)
1638}
1639
1640fn create_lock_file_atomically(path: &Path, metadata: &LockMetadata) -> io::Result<()> {
1641    let tmp_path = temp_path_for_lock(path);
1642    let result = (|| {
1643        let mut file = open_new_lock_file(&tmp_path)?;
1644        write_lock_metadata_to_file(&mut file, metadata)?;
1645        drop(file);
1646
1647        fs::hard_link(&tmp_path, path)?;
1648        Ok(())
1649    })();
1650
1651    let _ = fs::remove_file(&tmp_path);
1652    result
1653}
1654
1655/// Replace a lease's contents through a temp file and an atomic rename,
1656/// without fsync. Only the heartbeat uses this, and only when the in-place
1657/// rewrite cannot keep the file length; see `heartbeat_once` for why a
1658/// heartbeat needs no durability.
1659fn replace_lock_bytes_unsynced(path: &Path, bytes: &[u8]) -> io::Result<()> {
1660    let tmp_path = temp_path_for_lock(path);
1661    let write_result = (|| {
1662        let mut file = open_new_lock_file(&tmp_path)?;
1663        write_lock_bytes(&mut file, bytes)?;
1664        drop(file);
1665        with_lease_handles_closed(path, || rename_over(&tmp_path, path))
1666    })();
1667
1668    if write_result.is_err() {
1669        let _ = fs::remove_file(&tmp_path);
1670    }
1671
1672    write_result
1673}
1674
1675#[cfg(any(windows, any(test, feature = "test-support")))]
1676#[cfg_attr(not(test), allow(dead_code))]
1677fn rename_over_with(
1678    from: &Path,
1679    to: &Path,
1680    replace: impl FnOnce(&Path, &Path) -> io::Result<()>,
1681) -> io::Result<()> {
1682    replace(from, to)
1683}
1684
1685#[cfg(windows)]
1686pub fn rename_over(from: &Path, to: &Path) -> io::Result<()> {
1687    // MoveFileExW with MOVEFILE_REPLACE_EXISTING is the only replacement path
1688    // here that preserves the old destination on failure. A copy fallback
1689    // truncates the destination before copying and can expose partial bytes or
1690    // destroy the last valid artifact if the copy fails midway. Callers retain
1691    // their temp file cleanup and retry policy when an open handle prevents the
1692    // atomic replacement.
1693    // Closure instead of the bare `fs::rename` fn item: the generic fn item
1694    // instantiates with concrete reference lifetimes and fails the
1695    // higher-ranked `FnOnce(&Path, &Path)` bound on some targets.
1696    rename_over_with(from, to, |from, to| fs::rename(from, to))
1697}
1698
1699#[cfg(not(windows))]
1700pub fn rename_over(from: &Path, to: &Path) -> io::Result<()> {
1701    fs::rename(from, to)
1702}
1703
1704// Per-thread counter that disambiguates temp lockfile paths for callers
1705// inside the same process. `now_nanos()` alone is not unique enough on
1706// Windows when two threads race to acquire the same lock (caught by the
1707// `acquire_serializes_concurrent_callers` test): two threads sampling the
1708// nanosecond clock within the same scheduler quantum produce identical
1709// timestamps, both write to the same `.lock.tmp.<pid>.<nanos>` file, one
1710// thread's `fs::remove_file(&tmp_path)` cleanup deletes the file before
1711// the other thread's `fs::hard_link(&tmp_path, ...)` runs, and the loser
1712// panics with `Io(Os { code: 2, NotFound })`.
1713//
1714// `AtomicU64` shared across threads makes every temp path unique within
1715// the process regardless of clock resolution or scheduling races.
1716static TEMP_LOCK_COUNTER: AtomicU64 = AtomicU64::new(0);
1717
1718fn temp_path_for_lock(path: &Path) -> PathBuf {
1719    let file_name = path
1720        .file_name()
1721        .and_then(|name| name.to_str())
1722        .unwrap_or("lock");
1723    let seq = TEMP_LOCK_COUNTER.fetch_add(1, Ordering::Relaxed);
1724    path.with_file_name(format!(
1725        ".{file_name}.tmp.{}.{}.{}",
1726        std::process::id(),
1727        now_nanos(),
1728        seq
1729    ))
1730}
1731
1732fn lock_identity_matches(left: &LockMetadata, right: &LockMetadata) -> bool {
1733    left.pid == right.pid
1734        && left.hostname == right.hostname
1735        && left.process_start_time == right.process_start_time
1736        && left.boot_id == right.boot_id
1737        && left.created_at_ms == right.created_at_ms
1738        && left.writer_epoch == right.writer_epoch
1739}
1740
1741fn remove_lock_if_owned(path: &Path, owner: &LockMetadata) -> io::Result<bool> {
1742    let metadata = match read_lock_metadata(path) {
1743        Ok(metadata) => metadata,
1744        Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
1745            return Ok(false);
1746        }
1747        Err(ReadLockError::Io(error)) => return Err(error),
1748        Err(ReadLockError::Malformed(_)) => return Ok(false),
1749    };
1750
1751    if lock_identity_matches(&metadata, owner) {
1752        remove_lock_file(path)?;
1753        Ok(true)
1754    } else {
1755        Ok(false)
1756    }
1757}
1758
1759fn remove_lock_file(path: &Path) -> io::Result<()> {
1760    match with_lease_handles_closed(path, || fs::remove_file(path)) {
1761        Ok(()) => Ok(()),
1762        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
1763        Err(error) => Err(error),
1764    }
1765}
1766
1767/// Reclaim (delete) a lock file we judged stale/dead, but ONLY if it still holds
1768/// the SAME owner identity we evaluated. Between reading the metadata and
1769/// deleting, the stale owner could release and a FRESH owner acquire — blindly
1770/// `remove_file` would then delete the fresh owner's lock, allowing split-brain
1771/// writers. Re-read immediately before the unlink and bail if the full owner
1772/// identity changed or the file vanished. POSIX has no atomic compare-and-unlink,
1773/// so a microscopic residual race remains, but this shrinks the window from the
1774/// whole judgment/poll duration to a couple of syscalls — the standard mitigation.
1775fn reclaim_lock_file(path: &Path, judged: &LockMetadata) -> io::Result<ReclaimResult> {
1776    let token = match acquire_reclaim_token(path)? {
1777        ReclaimTokenAcquire::Acquired(token) => token,
1778        ReclaimTokenAcquire::Held(holder) => return Ok(ReclaimResult::Blocked(holder)),
1779    };
1780    let _token = token;
1781    match read_lock_metadata(path) {
1782        Ok(current) => {
1783            if lock_identity_matches(&current, judged) {
1784                remove_lock_file(path)?;
1785                Ok(ReclaimResult::Removed)
1786            } else {
1787                // A different owner acquired it in the gap — do NOT delete.
1788                Ok(ReclaimResult::Unchanged)
1789            }
1790        }
1791        // Already gone (released/reclaimed by someone else) — nothing to do.
1792        Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
1793            Ok(ReclaimResult::Unchanged)
1794        }
1795        // Malformed now (mid-write by a new owner) — don't delete; retry next poll.
1796        Err(ReadLockError::Malformed(_)) => Ok(ReclaimResult::Unchanged),
1797        Err(ReadLockError::Io(error)) => Err(error),
1798    }
1799}
1800
1801fn reclaim_malformed_lock(path: &Path, judged: &[u8]) -> io::Result<bool> {
1802    let _token = match acquire_reclaim_token(path)? {
1803        ReclaimTokenAcquire::Acquired(token) => token,
1804        ReclaimTokenAcquire::Held(_) => return Ok(false),
1805    };
1806    match fs::read(path) {
1807        Ok(current)
1808            if current == judged && serde_json::from_slice::<LockMetadata>(&current).is_err() =>
1809        {
1810            remove_lock_file(path)?;
1811            Ok(true)
1812        }
1813        Ok(_) => Ok(false),
1814        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
1815        Err(error) => Err(error),
1816    }
1817}
1818
1819struct ReclaimTokenGuard {
1820    path: PathBuf,
1821}
1822
1823impl Drop for ReclaimTokenGuard {
1824    fn drop(&mut self) {
1825        let _ = fs::remove_file(&self.path);
1826    }
1827}
1828
1829fn acquire_reclaim_token(lock_path: &Path) -> io::Result<ReclaimTokenAcquire> {
1830    let token_path = reclaim_token_path(lock_path);
1831    let metadata = current_reclaim_token_metadata();
1832
1833    match create_reclaim_token(&token_path, &metadata) {
1834        Ok(guard) => return Ok(ReclaimTokenAcquire::Acquired(guard)),
1835        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
1836        Err(error) => return Err(error),
1837    }
1838
1839    let stale = match inspect_reclaim_token(&token_path)? {
1840        ExistingReclaimToken::Held(holder) => return Ok(ReclaimTokenAcquire::Held(holder)),
1841        ExistingReclaimToken::StaleValid(owner) => remove_lock_if_owned(&token_path, &owner)?,
1842        ExistingReclaimToken::StaleMalformed => remove_malformed_reclaim_token(&token_path)?,
1843        ExistingReclaimToken::Missing => true,
1844    };
1845    if !stale {
1846        return inspect_reclaim_token_as_held(&token_path);
1847    }
1848
1849    // A stale-token takeover gets exactly one O_EXCL retry. Another contender may
1850    // win after the unlink; never loop and accidentally turn reclamation into a
1851    // second lock-acquisition spin.
1852    match create_reclaim_token(&token_path, &metadata) {
1853        Ok(guard) => Ok(ReclaimTokenAcquire::Acquired(guard)),
1854        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
1855            inspect_reclaim_token_as_held(&token_path)
1856        }
1857        Err(error) => Err(error),
1858    }
1859}
1860
1861enum ReclaimTokenAcquire {
1862    Acquired(ReclaimTokenGuard),
1863    Held(ReclaimTokenHeld),
1864}
1865
1866enum ExistingReclaimToken {
1867    Held(ReclaimTokenHeld),
1868    StaleValid(LockMetadata),
1869    StaleMalformed,
1870    Missing,
1871}
1872
1873fn current_reclaim_token_metadata() -> LockMetadata {
1874    let pid = std::process::id();
1875    let process_identity = process_identity(pid);
1876    let now = now_ms();
1877    LockMetadata {
1878        pid,
1879        hostname: current_hostname(),
1880        process_start_time: process_identity
1881            .as_ref()
1882            .map(|identity| identity.start_time),
1883        boot_id: process_identity.and_then(|identity| identity.boot_id),
1884        created_at_ms: now,
1885        heartbeat_at_ms: now,
1886        writer_epoch: format!("reclaim-{pid}-{}", now_nanos()),
1887    }
1888}
1889
1890fn create_reclaim_token(
1891    token_path: &Path,
1892    metadata: &LockMetadata,
1893) -> io::Result<ReclaimTokenGuard> {
1894    let mut file = open_new_lock_file(token_path)?;
1895    if let Err(error) = write_lock_metadata_to_file(&mut file, metadata) {
1896        let _ = fs::remove_file(token_path);
1897        return Err(error);
1898    }
1899    Ok(ReclaimTokenGuard {
1900        path: token_path.to_path_buf(),
1901    })
1902}
1903
1904fn inspect_reclaim_token(token_path: &Path) -> io::Result<ExistingReclaimToken> {
1905    match read_lock_metadata(token_path) {
1906        Ok(metadata) if metadata.hostname != current_hostname() => {
1907            Ok(ExistingReclaimToken::Held(ReclaimTokenHeld {
1908                pid: Some(metadata.pid),
1909                state: ReclaimTokenState::DeadForeignHost,
1910            }))
1911        }
1912        Ok(metadata) if lock_owner_is_alive(&metadata) => {
1913            Ok(ExistingReclaimToken::Held(ReclaimTokenHeld {
1914                pid: Some(metadata.pid),
1915                state: ReclaimTokenState::Alive,
1916            }))
1917        }
1918        Ok(metadata) => Ok(ExistingReclaimToken::StaleValid(metadata)),
1919        Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
1920            Ok(ExistingReclaimToken::Missing)
1921        }
1922        Err(ReadLockError::Io(error)) => Err(error),
1923        Err(ReadLockError::Malformed(_)) => {
1924            let old_enough = fs::metadata(token_path)
1925                .and_then(|metadata| metadata.modified())
1926                .ok()
1927                .and_then(|modified| SystemTime::now().duration_since(modified).ok())
1928                .is_some_and(|age| age > RECLAIM_TOKEN_MALFORMED_STALE_AGE);
1929            if old_enough {
1930                Ok(ExistingReclaimToken::StaleMalformed)
1931            } else {
1932                Ok(ExistingReclaimToken::Held(ReclaimTokenHeld {
1933                    pid: malformed_token_pid(token_path),
1934                    state: ReclaimTokenState::Malformed,
1935                }))
1936            }
1937        }
1938    }
1939}
1940
1941fn inspect_reclaim_token_as_held(token_path: &Path) -> io::Result<ReclaimTokenAcquire> {
1942    let holder = match inspect_reclaim_token(token_path)? {
1943        ExistingReclaimToken::Held(holder) => holder,
1944        ExistingReclaimToken::StaleValid(metadata) => ReclaimTokenHeld {
1945            pid: Some(metadata.pid),
1946            state: ReclaimTokenState::Dead,
1947        },
1948        ExistingReclaimToken::StaleMalformed | ExistingReclaimToken::Missing => ReclaimTokenHeld {
1949            pid: malformed_token_pid(token_path),
1950            state: ReclaimTokenState::Malformed,
1951        },
1952    };
1953    Ok(ReclaimTokenAcquire::Held(holder))
1954}
1955
1956fn malformed_token_pid(token_path: &Path) -> Option<u32> {
1957    let bytes = fs::read(token_path).ok()?;
1958    serde_json::from_slice::<serde_json::Value>(&bytes)
1959        .ok()?
1960        .get("pid")?
1961        .as_u64()
1962        .and_then(|pid| u32::try_from(pid).ok())
1963}
1964
1965fn remove_malformed_reclaim_token(token_path: &Path) -> io::Result<bool> {
1966    match fs::remove_file(token_path) {
1967        Ok(()) => Ok(true),
1968        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(true),
1969        Err(error) => Err(error),
1970    }
1971}
1972
1973fn reclaim_token_path(lock_path: &Path) -> PathBuf {
1974    let file_name = lock_path
1975        .file_name()
1976        .and_then(|name| name.to_str())
1977        .unwrap_or("lock");
1978    lock_path.with_file_name(format!(".{file_name}.reclaim"))
1979}
1980
1981fn dead_reclaim_backoff_ms(blocked_attempt: u32, poll_interval_ms: u64) -> u64 {
1982    let base = poll_interval_ms.max(DEAD_RECLAIM_INITIAL_BACKOFF_MS);
1983    base.saturating_mul(
1984        1_u64
1985            .checked_shl(blocked_attempt.min(20))
1986            .unwrap_or(u64::MAX),
1987    )
1988    .min(DEAD_RECLAIM_MAX_BACKOFF_MS)
1989}
1990
1991fn log_reclaim_blocked(path: &Path, holder: &ReclaimTokenHeld) {
1992    let now = Instant::now();
1993    let logs = RECLAIM_BLOCK_LOGS.get_or_init(|| Mutex::new(HashMap::new()));
1994    let Ok(mut logs) = logs.lock() else {
1995        return;
1996    };
1997    let message = match logs.get_mut(path) {
1998        Some(record)
1999            if now.saturating_duration_since(record.last_emitted) < RECLAIM_BLOCK_LOG_INTERVAL =>
2000        {
2001            record.suppressed = record.suppressed.saturating_add(1);
2002            return;
2003        }
2004        Some(record) => {
2005            let suppressed = record.suppressed;
2006            record.last_emitted = now;
2007            record.suppressed = 0;
2008            format_reclaim_blocked(path, holder, suppressed)
2009        }
2010        None => {
2011            logs.insert(
2012                path.to_path_buf(),
2013                ReclaimBlockLogRecord {
2014                    last_emitted: now,
2015                    suppressed: 0,
2016                },
2017            );
2018            format_reclaim_blocked(path, holder, 0)
2019        }
2020    };
2021    drop(logs);
2022    emit_reclaim_warning(message);
2023}
2024
2025fn format_reclaim_blocked(path: &Path, holder: &ReclaimTokenHeld, suppressed: u64) -> String {
2026    let pid = holder
2027        .pid
2028        .map(|pid| pid.to_string())
2029        .unwrap_or_else(|| "unknown".to_string());
2030    let mut message = format!(
2031        "reclaim of {} blocked: reclaim token held by pid {} ({})",
2032        path.display(),
2033        pid,
2034        holder.state.as_str()
2035    );
2036    if suppressed > 0 {
2037        message.push_str(&format!(" (repeated {suppressed}x in 60s)"));
2038    }
2039    message
2040}
2041
2042fn emit_reclaim_warning(message: String) {
2043    #[cfg(any(test, feature = "test-support"))]
2044    RECLAIM_TEST_LOGS.with(|logs| logs.borrow_mut().push(message.clone()));
2045    slog_warn!("{}", message);
2046}
2047
2048#[cfg(any(test, feature = "test-support"))]
2049thread_local! {
2050    pub static RECLAIM_TEST_LOGS: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
2051
2052    // The observer is thread-local so concurrent lock tests cannot record one
2053    // another's retry decisions.
2054    static RETRY_SLEEP_OBSERVER: std::cell::RefCell<Option<Arc<std::sync::atomic::AtomicUsize>>> =
2055        const { std::cell::RefCell::new(None) };
2056}
2057
2058#[cfg(any(test, feature = "test-support"))]
2059pub struct RetrySleepObserverGuard {
2060    previous: Option<Arc<std::sync::atomic::AtomicUsize>>,
2061}
2062
2063#[cfg(any(test, feature = "test-support"))]
2064impl Drop for RetrySleepObserverGuard {
2065    fn drop(&mut self) {
2066        RETRY_SLEEP_OBSERVER.with(|observer| {
2067            *observer.borrow_mut() = self.previous.take();
2068        });
2069    }
2070}
2071
2072#[cfg(any(test, feature = "test-support"))]
2073pub fn observe_retry_sleeps_for_test(
2074    observer: Arc<std::sync::atomic::AtomicUsize>,
2075) -> RetrySleepObserverGuard {
2076    let previous = RETRY_SLEEP_OBSERVER.with(|slot| slot.replace(Some(observer)));
2077    RetrySleepObserverGuard { previous }
2078}
2079
2080#[cfg(any(test, feature = "test-support"))]
2081fn note_retry_sleep_for_test() {
2082    RETRY_SLEEP_OBSERVER.with(|observer| {
2083        if let Some(observer) = observer.borrow().as_ref() {
2084            observer.fetch_add(1, Ordering::SeqCst);
2085        }
2086    });
2087}
2088
2089pub fn acquisition_now() -> Instant {
2090    #[cfg(any(test, feature = "test-support"))]
2091    if let Some(now) = retry_clock::now() {
2092        return now;
2093    }
2094    Instant::now()
2095}
2096
2097pub fn sleep_until_retry(
2098    deadline: Option<Instant>,
2099    poll_interval_ms: u64,
2100) -> Result<(), AcquireError> {
2101    let poll = Duration::from_millis(poll_interval_ms);
2102    let sleep_for = match deadline {
2103        Some(deadline) => {
2104            let now = acquisition_now();
2105            if now >= deadline {
2106                return Err(AcquireError::Timeout);
2107            }
2108            poll.min(deadline.saturating_duration_since(now))
2109        }
2110        None => poll,
2111    };
2112    #[cfg(any(test, feature = "test-support"))]
2113    note_retry_sleep_for_test();
2114    #[cfg(any(test, feature = "test-support"))]
2115    if retry_clock::sleep(sleep_for) {
2116        return Ok(());
2117    }
2118    thread::sleep(sleep_for);
2119    Ok(())
2120}
2121
2122/// Per-thread counters of successful acquisitions and lease I/O: file fsyncs,
2123/// directory fsyncs, newly created files (new inodes) and payload bytes.
2124/// Tests read them to prove which paths sync and how much a heartbeat
2125/// writes; outside tests every call compiles to nothing. The counters are
2126/// thread-local so tests running in parallel do not see each other's I/O.
2127pub(crate) mod io_ledger {
2128    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2129    #[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
2130    pub(crate) struct IoLedger {
2131        pub(crate) acquisitions: u64,
2132        /// Descriptors opened for a heartbeat read or write (`fopen`/`open`).
2133        pub(crate) opens: u64,
2134        /// Descriptors released by a heartbeat (`fclose`/`close`), at the
2135        /// `fclose` that `close()` spends its time in on the performance sweep.
2136        pub(crate) closes: u64,
2137        pub(crate) file_syncs: u64,
2138        pub(crate) dir_syncs: u64,
2139        pub(crate) new_files: u64,
2140        pub(crate) bytes_written: u64,
2141    }
2142
2143    #[cfg(any(test, feature = "test-support"))]
2144    thread_local! {
2145        static LEDGER: std::cell::Cell<IoLedger> = std::cell::Cell::new(IoLedger::default());
2146    }
2147
2148    #[cfg(any(test, feature = "test-support"))]
2149    pub(crate) fn record(update: impl FnOnce(&mut IoLedger)) {
2150        LEDGER.with(|cell| {
2151            let mut ledger = cell.get();
2152            update(&mut ledger);
2153            cell.set(ledger);
2154        });
2155    }
2156
2157    #[cfg(not(any(test, feature = "test-support")))]
2158    #[inline(always)]
2159    pub(crate) fn record(_update: impl FnOnce(&mut IoLedger)) {}
2160
2161    /// Return this thread's counters and reset them to zero.
2162    #[cfg(any(test, feature = "test-support"))]
2163    #[cfg_attr(not(test), allow(dead_code))]
2164    pub(crate) fn take() -> IoLedger {
2165        LEDGER.with(|cell| cell.replace(IoLedger::default()))
2166    }
2167}
2168
2169fn now_ms() -> u64 {
2170    SystemTime::now()
2171        .duration_since(UNIX_EPOCH)
2172        .unwrap_or(Duration::ZERO)
2173        .as_millis() as u64
2174}
2175
2176fn now_nanos() -> u128 {
2177    SystemTime::now()
2178        .duration_since(UNIX_EPOCH)
2179        .unwrap_or(Duration::ZERO)
2180        .as_nanos()
2181}
2182
2183#[cfg(unix)]
2184pub(crate) fn current_hostname() -> String {
2185    let mut buffer = [0u8; 256];
2186    let result = unsafe { libc::gethostname(buffer.as_mut_ptr().cast(), buffer.len()) };
2187    if result == 0 {
2188        let len = buffer
2189            .iter()
2190            .position(|byte| *byte == 0)
2191            .unwrap_or(buffer.len());
2192        if len > 0 {
2193            return String::from_utf8_lossy(&buffer[..len]).into_owned();
2194        }
2195    }
2196
2197    crate::environment::non_empty_var("HOSTNAME").unwrap_or_else(|| "unknown-host".to_string())
2198}
2199
2200#[cfg(windows)]
2201pub(crate) fn current_hostname() -> String {
2202    crate::environment::non_empty_var("COMPUTERNAME")
2203        .or_else(|| crate::environment::non_empty_var("HOSTNAME"))
2204        .unwrap_or_else(|| "unknown-host".to_string())
2205}
2206
2207#[cfg(not(any(unix, windows)))]
2208pub(crate) fn current_hostname() -> String {
2209    crate::environment::non_empty_var("HOSTNAME").unwrap_or_else(|| "unknown-host".to_string())
2210}
2211
2212/// Returns whether a same-host lock owner is still the same process instance.
2213///
2214/// Old leases have no start time, so they deliberately retain PID-only liveness
2215/// for backward compatibility. If an OS lookup cannot attest a recorded start
2216/// time, keep the PID alive: incorrectly reclaiming a paused owner is worse than
2217/// waiting for a process that may release the lock later.
2218fn lock_owner_is_alive(metadata: &LockMetadata) -> bool {
2219    if !process_alive(metadata.pid) {
2220        return false;
2221    }
2222
2223    let identity = process_identity(metadata.pid);
2224    // An exited process cannot execute protected work, even while its parent
2225    // leaves it waitable. Missing or inconclusive identity still fails closed.
2226    if identity.as_ref().is_some_and(|identity| identity.exited) {
2227        return false;
2228    }
2229    let Some(recorded_start_time) = metadata.process_start_time else {
2230        return true;
2231    };
2232    let Some(current_identity) = identity else {
2233        return true;
2234    };
2235
2236    if current_identity.start_time != recorded_start_time {
2237        return false;
2238    }
2239
2240    match &metadata.boot_id {
2241        Some(recorded_boot_id) => current_identity
2242            .boot_id
2243            .as_deref()
2244            .map_or(true, |current_boot_id| current_boot_id == recorded_boot_id),
2245        None => true,
2246    }
2247}
2248
2249#[cfg(target_os = "linux")]
2250fn linux_process_stat_identity(stat: &str) -> Option<(u64, bool)> {
2251    // Fields 20 and 22 are num_threads and starttime. Split after the final ')'
2252    // because the command can contain spaces and parentheses. pthread_exit can
2253    // leave a zombie leader while other threads still execute protected work.
2254    // Z (zombie) or X (dead) proves exit only with one reported thread. Malformed
2255    // fields give no identity, so owner liveness remains conservative.
2256    let fields = stat.rsplit_once(") ")?.1.split_ascii_whitespace();
2257    let state = fields.clone().next()?;
2258    if state.len() != 1 {
2259        return None;
2260    }
2261    let num_threads = fields.clone().nth(17)?.parse::<u64>().ok()?;
2262    let start_time = fields.clone().nth(19)?.parse::<u64>().ok()?;
2263    Some((start_time, matches!(state, "Z" | "X") && num_threads == 1))
2264}
2265
2266#[cfg(target_os = "linux")]
2267fn process_identity(pid: u32) -> Option<ProcessIdentity> {
2268    let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
2269    let (start_time, exited) = linux_process_stat_identity(&stat)?;
2270    let boot_id = fs::read_to_string("/proc/sys/kernel/random/boot_id")
2271        .ok()?
2272        .trim()
2273        .to_owned();
2274    if boot_id.is_empty() {
2275        return None;
2276    }
2277
2278    Some(ProcessIdentity {
2279        start_time,
2280        boot_id: Some(boot_id),
2281        exited,
2282    })
2283}
2284
2285#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
2286#[cfg_attr(not(test), allow(dead_code))]
2287const MACOS_KINFO_SIZE: usize = 648;
2288#[rustfmt::skip]
2289test_support_visibility! {
2290#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
2291pub(crate) const SZOMB: u8 = 5;
2292}
2293#[rustfmt::skip]
2294test_support_visibility! {
2295#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
2296pub(crate) const P_WEXIT: u32 = 0x0000_2000;
2297}
2298
2299#[rustfmt::skip]
2300test_support_visibility! {
2301#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
2302#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2303pub(crate) enum MacosExitState {
2304    NotExiting,
2305    Exiting,
2306    Zombie,
2307}
2308}
2309
2310/// One kernel snapshot supplies both incarnation and exit evidence. libproc's
2311/// PROC_PIDTBSDINFO can fail for a zombie, which is not evidence of liveness.
2312#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
2313#[derive(Clone, Debug)]
2314pub struct MacosKinfo {
2315    pub comm: String,
2316    pub ruid: u32,
2317    pub pgid: i32,
2318    #[cfg(any(test, feature = "test-support"))]
2319    pub state: u8,
2320    #[cfg(not(any(test, feature = "test-support")))]
2321    pub(crate) state: u8,
2322    #[cfg(any(test, feature = "test-support"))]
2323    pub flags: u32,
2324    #[cfg(not(any(test, feature = "test-support")))]
2325    pub(crate) flags: u32,
2326    #[cfg(any(test, feature = "test-support"))]
2327    pub started_at_us: Option<u64>,
2328    #[cfg(not(any(test, feature = "test-support")))]
2329    pub(crate) started_at_us: Option<u64>,
2330}
2331
2332#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
2333impl MacosKinfo {
2334    #[rustfmt::skip]
2335    test_support_visibility! {
2336    pub(crate) fn exit_state(&self) -> MacosExitState {
2337        if self.state == SZOMB {
2338            MacosExitState::Zombie
2339        } else if self.flags & P_WEXIT != 0 {
2340            MacosExitState::Exiting
2341        } else {
2342            MacosExitState::NotExiting
2343        }
2344    }
2345    }
2346
2347    /// The kernel exposes exit-started (P_WEXIT) before the process reaches the
2348    /// zombie state (SZOMB). Both count as exited for lease ownership and for
2349    /// deciding when a killed background task has finished.
2350    pub fn has_exited(&self) -> bool {
2351        self.exit_state() != MacosExitState::NotExiting
2352    }
2353}
2354
2355#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
2356#[cfg_attr(not(test), allow(dead_code))]
2357fn decode_macos_kinfo(bytes: &[u8]) -> Option<MacosKinfo> {
2358    // Darwin's kinfo_proc ABI is 648 bytes on arm64 and x86_64. libc does not
2359    // declare it for Apple targets; reject any other layout rather than guess.
2360    const P_FLAG_OFFSET: usize = 32;
2361    const P_STAT_OFFSET: usize = 36;
2362    const P_COMM_OFFSET: usize = 243;
2363    const P_COMM_LEN: usize = 17;
2364    const P_RUID_OFFSET: usize = 392;
2365    const E_PGID_OFFSET: usize = 564;
2366    if bytes.len() != MACOS_KINFO_SIZE {
2367        return None;
2368    }
2369    let read_u32 = |offset: usize| {
2370        u32::from_ne_bytes(bytes[offset..offset + 4].try_into().expect("four bytes"))
2371    };
2372    // extern_proc begins with p_un.p_starttime (timeval): 64-bit seconds and
2373    // 32-bit microseconds. Keep microsecond identity distinct from ms callers.
2374    let seconds = i64::from_ne_bytes(bytes[0..8].try_into().ok()?);
2375    let micros = i32::from_ne_bytes(bytes[8..12].try_into().ok()?);
2376    let started_at_us = if seconds > 0 && (0..1_000_000).contains(&micros) {
2377        (seconds as u64)
2378            .checked_mul(1_000_000)?
2379            .checked_add(micros as u64)
2380    } else {
2381        None
2382    };
2383    let comm = &bytes[P_COMM_OFFSET..P_COMM_OFFSET + P_COMM_LEN];
2384    let end = comm
2385        .iter()
2386        .position(|byte| *byte == 0)
2387        .unwrap_or(comm.len());
2388    Some(MacosKinfo {
2389        comm: String::from_utf8_lossy(&comm[..end]).into_owned(),
2390        ruid: read_u32(P_RUID_OFFSET),
2391        pgid: read_u32(E_PGID_OFFSET) as i32,
2392        state: bytes[P_STAT_OFFSET],
2393        flags: read_u32(P_FLAG_OFFSET),
2394        started_at_us,
2395    })
2396}
2397
2398/// kern.proc.pid also answers for other users and unreaped processes. A failed
2399/// or partial read is inconclusive, never a fabricated live/dead identity.
2400#[cfg(target_os = "macos")]
2401pub fn macos_kinfo(pid: u32) -> Option<MacosKinfo> {
2402    if pid == 0 || pid > i32::MAX as u32 {
2403        return None;
2404    }
2405    let mut mib = [
2406        libc::CTL_KERN,
2407        libc::KERN_PROC,
2408        libc::KERN_PROC_PID,
2409        pid as i32,
2410    ];
2411    let mut bytes = [0_u8; MACOS_KINFO_SIZE];
2412    let mut size = bytes.len();
2413    // SAFETY: sysctl receives the real buffer size and may write at most it.
2414    let status = unsafe {
2415        libc::sysctl(
2416            mib.as_mut_ptr(),
2417            mib.len() as u32,
2418            bytes.as_mut_ptr().cast(),
2419            &mut size,
2420            std::ptr::null_mut(),
2421            0,
2422        )
2423    };
2424    if status != 0 || size != bytes.len() {
2425        return None;
2426    }
2427    decode_macos_kinfo(&bytes)
2428}
2429
2430#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
2431#[cfg_attr(not(test), allow(dead_code))]
2432fn macos_process_identity(snapshot: Option<MacosKinfo>) -> Option<ProcessIdentity> {
2433    let info = snapshot?;
2434    Some(ProcessIdentity {
2435        start_time: info.started_at_us?,
2436        boot_id: None,
2437        exited: info.has_exited(),
2438    })
2439}
2440
2441#[rustfmt::skip]
2442test_support_visibility! {
2443
2444#[cfg(target_os = "macos")]
2445fn process_identity(pid: u32) -> Option<ProcessIdentity> {
2446    macos_process_identity(macos_kinfo(pid))
2447}
2448}
2449
2450#[cfg(windows)]
2451fn process_identity(pid: u32) -> Option<ProcessIdentity> {
2452    windows_process_creation_time(pid)
2453        .ok()
2454        .flatten()
2455        .map(|start_time| ProcessIdentity {
2456            start_time,
2457            boot_id: None,
2458            exited: false,
2459        })
2460}
2461
2462/// Exact birth and boot identity for speech redemption. Missing evidence is denial,
2463/// unlike the deliberately conservative "still alive" policy used by lock cleanup.
2464pub fn speech_process_identity(pid: u32) -> Option<String> {
2465    let identity = process_identity(pid)?;
2466    if identity.exited {
2467        return None;
2468    }
2469    #[cfg(target_os = "linux")]
2470    let boot = identity.boot_id?;
2471    #[cfg(target_os = "macos")]
2472    let boot = crate::volume::boot_id()?;
2473    #[cfg(windows)]
2474    let boot = speech_windows_boot_id()?;
2475    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
2476    let boot = return None;
2477    Some(format!(
2478        "{}:{boot}:{}",
2479        std::env::consts::OS,
2480        identity.start_time
2481    ))
2482}
2483
2484#[cfg(windows)]
2485fn speech_windows_boot_id() -> Option<String> {
2486    #[repr(C)]
2487    struct BootInfo {
2488        id: [u8; 16],
2489        firmware: u32,
2490        flags: u64,
2491    }
2492    #[link(name = "ntdll")]
2493    unsafe extern "system" {
2494        #[link_name = "NtQuerySystemInformation"]
2495        fn nt_query_system_information(
2496            class: u32,
2497            buffer: *mut std::ffi::c_void,
2498            length: u32,
2499            returned: *mut u32,
2500        ) -> i32;
2501    }
2502    let mut info = BootInfo {
2503        id: [0; 16],
2504        firmware: 0,
2505        flags: 0,
2506    };
2507    let mut returned = 0;
2508    // SystemBootEnvironmentInformation (90) supplies the kernel's per-boot GUID.
2509    let status = unsafe {
2510        nt_query_system_information(
2511            90,
2512            (&mut info as *mut BootInfo).cast(),
2513            std::mem::size_of::<BootInfo>() as u32,
2514            &mut returned,
2515        )
2516    };
2517    if status < 0 || returned < 16 || info.id == [0; 16] {
2518        return None;
2519    }
2520    Some(info.id.iter().map(|byte| format!("{byte:02x}")).collect())
2521}
2522
2523#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
2524fn process_identity(_pid: u32) -> Option<ProcessIdentity> {
2525    None
2526}
2527
2528#[cfg(all(any(test, feature = "test-support"), target_os = "macos"))]
2529unsafe extern "C" {
2530    pub fn proc_pidinfo(
2531        pid: libc::c_int,
2532        flavor: libc::c_int,
2533        arg: u64,
2534        buffer: *mut libc::c_void,
2535        buffersize: libc::c_int,
2536    ) -> libc::c_int;
2537}
2538
2539#[cfg(unix)]
2540pub fn process_alive(pid: u32) -> bool {
2541    if pid == 0 || pid > i32::MAX as u32 {
2542        return false;
2543    }
2544
2545    let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
2546    if result == 0 {
2547        return true;
2548    }
2549
2550    io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
2551}
2552
2553#[cfg(windows)]
2554pub fn process_alive(pid: u32) -> bool {
2555    // A denied or inconclusive probe must not permit reclaiming a live owner.
2556    windows_process_creation_time(pid).map_or(true, |created| created.is_some())
2557}
2558
2559#[cfg(windows)]
2560fn windows_process_creation_time(pid: u32) -> io::Result<Option<u64>> {
2561    use windows_sys::Win32::Foundation::{
2562        CloseHandle, ERROR_INVALID_PARAMETER, FILETIME, WAIT_OBJECT_0, WAIT_TIMEOUT,
2563    };
2564    use windows_sys::Win32::System::Threading::{
2565        GetProcessTimes, OpenProcess, WaitForSingleObject, PROCESS_QUERY_LIMITED_INFORMATION,
2566    };
2567    if pid == 0 {
2568        return Ok(None);
2569    }
2570    const SYNCHRONIZE_RIGHT: u32 = 0x0010_0000;
2571    let handle = unsafe {
2572        OpenProcess(
2573            PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE_RIGHT,
2574            0,
2575            pid,
2576        )
2577    };
2578    if handle.is_null() {
2579        let error = io::Error::last_os_error();
2580        return if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
2581            Ok(None)
2582        } else {
2583            Err(error)
2584        };
2585    }
2586    struct ProcessHandle(windows_sys::Win32::Foundation::HANDLE);
2587    impl Drop for ProcessHandle {
2588        fn drop(&mut self) {
2589            unsafe {
2590                CloseHandle(self.0);
2591            }
2592        }
2593    }
2594    let handle = ProcessHandle(handle);
2595    // Waiting on the process object distinguishes exit from liveness even when
2596    // an application exits with 259, the ambiguous STILL_ACTIVE exit-code value.
2597    match unsafe { WaitForSingleObject(handle.0, 0) } {
2598        WAIT_OBJECT_0 => return Ok(None),
2599        WAIT_TIMEOUT => {}
2600        _ => return Err(io::Error::last_os_error()),
2601    }
2602    let mut created = FILETIME {
2603        dwLowDateTime: 0,
2604        dwHighDateTime: 0,
2605    };
2606    let mut exited = created;
2607    let mut kernel = created;
2608    let mut user = created;
2609    if unsafe { GetProcessTimes(handle.0, &mut created, &mut exited, &mut kernel, &mut user) } == 0
2610    {
2611        return Err(io::Error::last_os_error());
2612    }
2613    Ok(Some(
2614        (u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime),
2615    ))
2616}
2617
2618#[cfg(windows)]
2619pub(crate) fn windows_process_start_time_ms(pid: u32) -> Option<u64> {
2620    windows_creation_ticks_to_unix_ms(windows_process_creation_time(pid).ok().flatten()?)
2621}
2622
2623#[cfg(windows)]
2624fn windows_creation_ticks_to_unix_ms(ticks: u64) -> Option<u64> {
2625    // FILETIME counts 100-nanosecond intervals since 1601; manifests use Unix ms.
2626    const UNIX_EPOCH_FILETIME: u64 = 116_444_736_000_000_000;
2627    ticks
2628        .checked_sub(UNIX_EPOCH_FILETIME)
2629        .map(|ticks| ticks / 10_000)
2630}
2631
2632#[cfg(not(any(unix, windows)))]
2633pub fn process_alive(_pid: u32) -> bool {
2634    true
2635}
2636
2637#[cfg(any(test, feature = "test-support"))]
2638pub mod retry_clock {
2639    use super::*;
2640
2641    struct State {
2642        started: Instant,
2643        now: Instant,
2644        preparation_delay: Duration,
2645        sleeps: Vec<Duration>,
2646        attempts: usize,
2647    }
2648
2649    thread_local! {
2650        static CLOCK: std::cell::RefCell<Option<State>> = const { std::cell::RefCell::new(None) };
2651    }
2652
2653    pub struct Guard;
2654
2655    impl Guard {
2656        pub fn install(preparation_delay: Duration) -> Self {
2657            CLOCK.with(|clock| {
2658                let mut clock = clock.borrow_mut();
2659                assert!(clock.is_none(), "retry clock already installed");
2660                let started = Instant::now();
2661                *clock = Some(State {
2662                    started,
2663                    now: started,
2664                    preparation_delay,
2665                    sleeps: Vec::new(),
2666                    attempts: 0,
2667                });
2668            });
2669            Self
2670        }
2671
2672        pub fn observations(&self) -> (Duration, Vec<Duration>, usize) {
2673            CLOCK.with(|clock| {
2674                let clock = clock.borrow();
2675                let state = clock.as_ref().unwrap();
2676                (
2677                    state.now - state.started,
2678                    state.sleeps.clone(),
2679                    state.attempts,
2680                )
2681            })
2682        }
2683    }
2684
2685    impl Drop for Guard {
2686        fn drop(&mut self) {
2687            CLOCK.with(|clock| *clock.borrow_mut() = None);
2688        }
2689    }
2690
2691    pub fn now() -> Option<Instant> {
2692        CLOCK.with(|clock| clock.borrow().as_ref().map(|state| state.now))
2693    }
2694
2695    pub fn before_acquire() {
2696        CLOCK.with(|clock| {
2697            if let Some(state) = clock.borrow_mut().as_mut() {
2698                // Model filesystem preparation after the caller chose its deadline.
2699                state.now += std::mem::take(&mut state.preparation_delay);
2700            }
2701        });
2702    }
2703
2704    pub fn note_attempt() {
2705        CLOCK.with(|clock| {
2706            if let Some(state) = clock.borrow_mut().as_mut() {
2707                state.attempts += 1;
2708            }
2709        });
2710    }
2711
2712    pub fn sleep(duration: Duration) -> bool {
2713        CLOCK.with(|clock| {
2714            let mut clock = clock.borrow_mut();
2715            let Some(state) = clock.as_mut() else {
2716                return false;
2717            };
2718            state.sleeps.push(duration);
2719            state.now += duration;
2720            assert!(
2721                state.sleeps.len() <= 1_000,
2722                "retry loop ignored its deadline"
2723            );
2724            true
2725        })
2726    }
2727}
2728
2729#[cfg(test)]
2730mod tests {
2731    use super::*;
2732    use std::io::BufRead as _;
2733    use std::io::Write;
2734    use std::process::Child;
2735    use std::process::ChildStdin;
2736    use std::process::Stdio;
2737    use std::sync::atomic::AtomicUsize;
2738    use std::sync::atomic::Ordering;
2739    use std::sync::mpsc;
2740    use std::sync::Arc;
2741    use std::sync::Barrier;
2742
2743    #[cfg(target_os = "linux")]
2744    #[test]
2745    #[ignore = "opt-in live-owner wait CPU measurement"]
2746    fn measurement_live_owner_wait_cpu() {
2747        let root = tempfile::tempdir().unwrap();
2748        let path = root.path().join("held.lock");
2749        let _owner = acquire(&path).unwrap();
2750        let sleeps = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2751        let _observer = observe_retry_sleeps_for_test(Arc::clone(&sleeps));
2752        let cpu = || {
2753            let mut time = libc::timespec {
2754                tv_sec: 0,
2755                tv_nsec: 0,
2756            };
2757            assert_eq!(
2758                unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut time) },
2759                0
2760            );
2761            time.tv_sec as f64 + time.tv_nsec as f64 / 1e9
2762        };
2763        let cpu_started = cpu();
2764        let started = Instant::now();
2765        assert!(matches!(
2766            try_acquire(&path, Duration::from_millis(1050)),
2767            Err(AcquireError::Timeout)
2768        ));
2769        eprintln!(
2770            "LOCK_WAIT_MEASUREMENT poll_ms={} sleeps={} wall_ms={:.3} thread_cpu_ms={:.3}",
2771            POLL_INTERVAL_MS,
2772            sleeps.load(Ordering::SeqCst),
2773            started.elapsed().as_secs_f64() * 1000.0,
2774            (cpu() - cpu_started) * 1000.0
2775        );
2776        assert!(sleeps.load(Ordering::SeqCst) > 0);
2777    }
2778
2779    #[test]
2780    fn live_owner_poll_sleeps_to_the_original_deadline() {
2781        let root = tempfile::tempdir().unwrap();
2782        let path = root.path().join("held.lock");
2783        let _owner = acquire(&path).unwrap();
2784        let clock = retry_clock::Guard::install(Duration::ZERO);
2785        assert!(matches!(
2786            try_acquire(&path, Duration::from_millis(1050)),
2787            Err(AcquireError::Timeout)
2788        ));
2789        let (elapsed, sleeps, attempts) = clock.observations();
2790        assert_eq!(elapsed, Duration::from_millis(1050));
2791        assert_eq!(attempts, 11);
2792        let mut expected = vec![Duration::from_millis(100); 10];
2793        expected.push(Duration::from_millis(50));
2794        assert_eq!(sleeps, expected);
2795    }
2796
2797    fn macos_snapshot_bytes(state: u8, flags: u32) -> [u8; 648] {
2798        let mut bytes = [0; 648];
2799        bytes[0..8].copy_from_slice(&1_700_000_000_i64.to_ne_bytes());
2800        bytes[8..12].copy_from_slice(&123_456_i32.to_ne_bytes());
2801        bytes[32..36].copy_from_slice(&flags.to_ne_bytes());
2802        bytes[36] = state;
2803        bytes[243..248].copy_from_slice(b"owner");
2804        bytes[392..396].copy_from_slice(&42_u32.to_ne_bytes());
2805        bytes[564..568].copy_from_slice(&123_i32.to_ne_bytes());
2806        bytes
2807    }
2808
2809    #[test]
2810    fn semantic_batch_lease_macos_snapshot_keeps_birth_and_exit_phase() {
2811        let info = decode_macos_kinfo(&macos_snapshot_bytes(SZOMB, P_WEXIT)).unwrap();
2812        assert_eq!(info.comm, "owner");
2813        assert_eq!((info.ruid, info.pgid), (42, 123));
2814        assert_eq!(info.exit_state(), MacosExitState::Zombie);
2815        let identity = macos_process_identity(Some(info)).unwrap();
2816        assert_eq!(identity.start_time, 1_700_000_000_123_456);
2817        assert!(identity.exited);
2818        assert!(identity.boot_id.is_none());
2819
2820        let exiting = decode_macos_kinfo(&macos_snapshot_bytes(2, P_WEXIT)).unwrap();
2821        assert_eq!(exiting.exit_state(), MacosExitState::Exiting);
2822        assert!(macos_process_identity(Some(exiting)).unwrap().exited);
2823        let running = decode_macos_kinfo(&macos_snapshot_bytes(2, 0)).unwrap();
2824        assert_eq!(running.exit_state(), MacosExitState::NotExiting);
2825        assert!(!macos_process_identity(Some(running)).unwrap().exited);
2826    }
2827
2828    #[test]
2829    fn semantic_batch_lease_macos_missing_identity_stays_inconclusive() {
2830        assert!(macos_process_identity(None).is_none());
2831        let mut bytes = macos_snapshot_bytes(SZOMB, P_WEXIT);
2832        assert!(decode_macos_kinfo(&bytes[..16]).is_none());
2833        bytes[8..12].copy_from_slice(&1_000_000_i32.to_ne_bytes());
2834        assert!(macos_process_identity(decode_macos_kinfo(&bytes)).is_none());
2835        bytes[8..12].copy_from_slice(&0_i32.to_ne_bytes());
2836        bytes[0..8].copy_from_slice(&0_i64.to_ne_bytes());
2837        assert!(macos_process_identity(decode_macos_kinfo(&bytes)).is_none());
2838    }
2839
2840    #[cfg(unix)]
2841    #[test]
2842    fn advisory_lock_guard_releases_lock_with_a_live_duplicate() {
2843        let dir = tempfile::tempdir().unwrap();
2844        let path = dir.path().join("advisory.lock");
2845        for shared in [true, false] {
2846            let file = OpenOptions::new()
2847                .read(true)
2848                .write(true)
2849                .create(true)
2850                .truncate(false)
2851                .open(&path)
2852                .unwrap();
2853            if shared {
2854                file.lock_shared().unwrap();
2855            } else {
2856                file.lock().unwrap();
2857            }
2858            // A duplicate shares the open file description, just like fork's copy.
2859            let duplicate = file.try_clone().unwrap();
2860            let guard = AdvisoryLockGuard::from_locked_file(file);
2861            let probe = OpenOptions::new()
2862                .read(true)
2863                .write(true)
2864                .open(&path)
2865                .unwrap();
2866            assert!(matches!(
2867                probe.try_lock(),
2868                Err(fs::TryLockError::WouldBlock)
2869            ));
2870            drop(guard);
2871            probe
2872                .try_lock()
2873                .expect("the owner released exclusion even with a live duplicate");
2874            assert!(duplicate.metadata().is_ok());
2875            probe.unlock().unwrap();
2876        }
2877    }
2878
2879    #[cfg(windows)]
2880    #[test]
2881    fn windows_native_process_probe_records_creation_identity() {
2882        let pid = std::process::id();
2883        let identity = process_identity(pid).expect("current Windows process creation identity");
2884        assert!(identity.start_time > 0);
2885        assert!(windows_process_start_time_ms(pid).unwrap() > 0);
2886        assert_eq!(
2887            windows_creation_ticks_to_unix_ms(116_444_736_000_000_000),
2888            Some(0)
2889        );
2890        assert_eq!(
2891            windows_creation_ticks_to_unix_ms(116_444_736_010_000_000),
2892            Some(1000)
2893        );
2894        assert_eq!(windows_creation_ticks_to_unix_ms(0), None);
2895        assert!(process_alive(pid));
2896        assert!(!process_alive(0));
2897        assert!(!process_alive(u32::MAX));
2898        let mut metadata = current_process_metadata();
2899        metadata.process_start_time = Some(identity.start_time.saturating_add(1));
2900        assert!(
2901            !lock_owner_is_alive(&metadata),
2902            "recycled PID must not keep an old lease alive"
2903        );
2904    }
2905
2906    #[cfg(windows)]
2907    #[test]
2908    fn windows_native_process_probe_recognizes_exited_status_259() {
2909        let mut child = std::process::Command::new("cmd.exe")
2910            .args(["/C", "exit 259"])
2911            .spawn()
2912            .unwrap();
2913        let pid = child.id();
2914        assert_eq!(child.wait().unwrap().code(), Some(259));
2915        assert!(
2916            !process_alive(pid),
2917            "a signaled process object is exited even when its exit code is STILL_ACTIVE"
2918        );
2919    }
2920
2921    #[test]
2922    fn malformed_reclaim_preserves_replacement_epoch() {
2923        let (_dir, path) = test_lock_path();
2924        fs::write(&path, b"malformed").unwrap();
2925        let replacement = synthetic_metadata(std::process::id(), current_hostname(), now_ms());
2926        let expected_epoch = replacement.writer_epoch.clone();
2927        let replace_path = path.clone();
2928        BEFORE_MALFORMED_RECLAIM.with(|slot| {
2929            *slot.borrow_mut() = Some(Box::new(move || {
2930                fs::remove_file(&replace_path).unwrap();
2931                write_synthetic_lock(&replace_path, &replacement);
2932            }))
2933        });
2934        let result = acquire_with_config(&path, Some(Duration::from_millis(100)), test_config());
2935        assert!(
2936            matches!(result, Err(AcquireError::Timeout)),
2937            "replacement owner must block acquisition"
2938        );
2939        assert_eq!(
2940            read_lock_metadata(&path).unwrap().writer_epoch,
2941            expected_epoch
2942        );
2943    }
2944
2945    #[test]
2946    fn heartbeat_spawn_failure_removes_own_lock() {
2947        let (_dir, path) = test_lock_path();
2948        BEFORE_HEARTBEAT_SPAWN_FAILURE.with(|slot| *slot.borrow_mut() = Some(Box::new(|| {})));
2949        assert!(create_new_lock(&path, &current_hostname(), test_config()).is_err());
2950        assert!(
2951            !path.exists(),
2952            "failed acquisition must not leave a live-PID lock"
2953        );
2954        drop(create_new_lock(&path, &current_hostname(), test_config()).unwrap());
2955    }
2956
2957    #[test]
2958    fn heartbeat_spawn_failure_preserves_replacement_lock() {
2959        let (_dir, path) = test_lock_path();
2960        let replacement = synthetic_metadata(std::process::id(), current_hostname(), now_ms());
2961        let expected_epoch = replacement.writer_epoch.clone();
2962        let replace_path = path.clone();
2963        BEFORE_HEARTBEAT_SPAWN_FAILURE.with(|slot| {
2964            *slot.borrow_mut() = Some(Box::new(move || {
2965                fs::remove_file(&replace_path).unwrap();
2966                write_synthetic_lock(&replace_path, &replacement);
2967            }))
2968        });
2969        assert!(create_new_lock(&path, &current_hostname(), test_config()).is_err());
2970        assert_eq!(
2971            read_lock_metadata(&path).unwrap().writer_epoch,
2972            expected_epoch
2973        );
2974    }
2975
2976    /// A lock file whose metadata cannot be read because another actor is
2977    /// mid-create/delete is contention, not a failure. The create arm already
2978    /// treated it that way; the metadata read beside it did not, so on Windows
2979    /// a pending-deletion lock denied the read and propagated a hard error to a
2980    /// caller that then panicked mid-write. Permission-denied is classified as
2981    /// contention on every platform, so this reproduces without Windows: with
2982    /// the retry the acquisition spends its budget and times out; without it
2983    /// the raw permission error escapes immediately.
2984    #[cfg(unix)]
2985    #[test]
2986    fn unreadable_lock_metadata_is_retried_as_contention_not_propagated() {
2987        use std::os::unix::fs::PermissionsExt;
2988
2989        let dir = tempfile::tempdir().expect("tempdir");
2990        let path = dir.path().join("cache.lock");
2991        std::fs::write(&path, b"{}\n").expect("seed lock file");
2992        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000))
2993            .expect("deny reads");
2994        if std::fs::read(&path).is_ok() {
2995            // Running as a user that bypasses the mode bits (root in some CI
2996            // images); the premise cannot hold, so assert nothing.
2997            return;
2998        }
2999
3000        let outcome = try_acquire(&path, Duration::from_millis(250));
3001
3002        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).ok();
3003        match outcome {
3004            Err(AcquireError::Timeout) => {}
3005            Err(AcquireError::Io(error)) => {
3006                panic!("contended metadata read propagated instead of retrying: {error:?}")
3007            }
3008            Ok(_) => panic!("acquired a lock whose metadata could not be read"),
3009        }
3010    }
3011
3012    const HARNESS_TEST: &str = "fs_lock::tests::fs_lock_separate_process_harness";
3013    const HARNESS_MODE_INSPECT: &str = "inspect";
3014
3015    fn test_config() -> LockConfig {
3016        LockConfig {
3017            heartbeat_interval_ms: 25,
3018            heartbeat_refresh_interval_ms: 25,
3019            stale_heartbeat_ms: 2_000,
3020            live_owner_warn_ms: LIVE_OWNER_WARN_MS,
3021            poll_interval_ms: 10,
3022        }
3023    }
3024
3025    fn test_lock_path() -> (tempfile::TempDir, PathBuf) {
3026        let dir = tempfile::tempdir().expect("create temp dir");
3027        let path = dir.path().join("test.lock");
3028        (dir, path)
3029    }
3030
3031    fn write_synthetic_lock(path: &Path, metadata: &LockMetadata) {
3032        let mut file = open_new_lock_file(path).expect("create synthetic lock");
3033        write_lock_metadata_to_file(&mut file, metadata).expect("write synthetic lock");
3034    }
3035
3036    #[derive(Serialize)]
3037    struct LegacyLockMetadata<'a> {
3038        pid: u32,
3039        hostname: &'a str,
3040        created_at_ms: u64,
3041        heartbeat_at_ms: u64,
3042        writer_epoch: &'a str,
3043    }
3044
3045    fn write_legacy_lock(path: &Path, metadata: &LockMetadata) -> String {
3046        let legacy = LegacyLockMetadata {
3047            pid: metadata.pid,
3048            hostname: &metadata.hostname,
3049            created_at_ms: metadata.created_at_ms,
3050            heartbeat_at_ms: metadata.heartbeat_at_ms,
3051            writer_epoch: &metadata.writer_epoch,
3052        };
3053        let contents = format!(
3054            "{}\n",
3055            serde_json::to_string(&legacy).expect("serialize legacy lock")
3056        );
3057        fs::write(path, &contents).expect("write legacy synthetic lock");
3058        contents
3059    }
3060
3061    fn synthetic_metadata(pid: u32, hostname: String, created_at_ms: u64) -> LockMetadata {
3062        LockMetadata {
3063            pid,
3064            hostname,
3065            // Synthetic metadata defaults to the legacy shape so tests must opt
3066            // in when they need to exercise process-instance identity.
3067            process_start_time: None,
3068            boot_id: None,
3069            created_at_ms,
3070            heartbeat_at_ms: created_at_ms,
3071            writer_epoch: format!("synthetic-{pid}-{created_at_ms}"),
3072        }
3073    }
3074
3075    fn current_process_metadata() -> LockMetadata {
3076        let now = now_ms();
3077        let pid = std::process::id();
3078        let process_identity = process_identity(pid);
3079        let mut metadata = synthetic_metadata(pid, current_hostname(), now);
3080        metadata.process_start_time = process_identity
3081            .as_ref()
3082            .map(|identity| identity.start_time);
3083        metadata.boot_id = process_identity.and_then(|identity| identity.boot_id);
3084        metadata
3085    }
3086
3087    fn different_start_time(start_time: u64) -> u64 {
3088        start_time.checked_add(1).unwrap_or(start_time - 1)
3089    }
3090
3091    fn write_reclaim_token(lock_path: &Path, metadata: &LockMetadata) -> PathBuf {
3092        let token_path = reclaim_token_path(lock_path);
3093        write_synthetic_lock(&token_path, metadata);
3094        token_path
3095    }
3096
3097    fn take_reclaim_test_logs() -> Vec<String> {
3098        RECLAIM_TEST_LOGS.with(|logs| std::mem::take(&mut *logs.borrow_mut()))
3099    }
3100
3101    #[test]
3102    fn lock_operation_trace_lines_are_debug_not_info() {
3103        let source = include_str!("fs_lock.rs");
3104        assert!(source.contains("slog_debug!(\"acquired filesystem lock at {}\", path.display())"));
3105        assert!(
3106            source.contains("slog_debug!(\"released filesystem lock at {}\", self.path.display())")
3107        );
3108        assert!(!source.contains("slog_info!(\"acquired filesystem lock at {}\", path.display())"));
3109        assert!(
3110            !source.contains("slog_info!(\"released filesystem lock at {}\", self.path.display())")
3111        );
3112    }
3113
3114    #[test]
3115    fn acquire_creates_lockfile_and_unlocks_on_drop() {
3116        let (_dir, path) = test_lock_path();
3117
3118        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
3119        let metadata = read_lock_metadata(&path).expect("read lock metadata");
3120        assert_eq!(metadata.pid, std::process::id());
3121        assert_eq!(metadata.hostname, current_hostname());
3122        assert_eq!(metadata.created_at_ms, guard.metadata.created_at_ms);
3123        assert_eq!(metadata.writer_epoch, guard.metadata.writer_epoch);
3124        #[cfg(unix)]
3125        {
3126            use std::os::unix::fs::PermissionsExt;
3127            assert_eq!(
3128                fs::metadata(&path).unwrap().permissions().mode() & 0o777,
3129                0o600
3130            );
3131        }
3132
3133        drop(guard);
3134        assert!(!path.exists());
3135    }
3136
3137    #[test]
3138    fn permission_denied_is_treated_as_transient_create_contention() {
3139        // Windows surfaces a contended create/delete on the same lock path as
3140        // access-denied; acquire must retry these rather than fail the caller.
3141        let err = io::Error::from(io::ErrorKind::PermissionDenied);
3142        assert!(is_transient_create_contention(&err));
3143    }
3144
3145    #[test]
3146    fn unrelated_io_errors_are_not_treated_as_contention() {
3147        // A genuinely fatal error (e.g. the parent dir is missing) must still
3148        // propagate, not spin in the transient-retry arm.
3149        let err = io::Error::from(io::ErrorKind::NotFound);
3150        assert!(!is_transient_create_contention(&err));
3151    }
3152
3153    #[cfg(windows)]
3154    #[test]
3155    fn windows_sharing_violation_is_treated_as_transient_create_contention() {
3156        // ERROR_SHARING_VIOLATION (32) is the other contention code Windows
3157        // returns when a concurrent actor holds the path open mid-create.
3158        let err = io::Error::from_raw_os_error(32);
3159        assert!(is_transient_create_contention(&err));
3160    }
3161
3162    #[test]
3163    fn reclaim_refuses_to_delete_a_different_owners_lock() {
3164        let (_dir, path) = test_lock_path();
3165
3166        // A lock currently owned by "owner B".
3167        let owner_b = synthetic_metadata(4242, "host-b".to_string(), now_ms());
3168        create_lock_file_atomically(&path, &owner_b).expect("write owner B lock");
3169
3170        // We judged a DIFFERENT (older) owner A as stale. Reclaiming must NOT
3171        // delete B's lock (the TOCTOU split-brain guard).
3172        let judged_a = synthetic_metadata(1111, "host-a".to_string(), now_ms() - 1_000_000);
3173        let outcome = reclaim_lock_file(&path, &judged_a).expect("reclaim");
3174        assert!(
3175            matches!(outcome, ReclaimResult::Unchanged),
3176            "must not remove a different owner's lock"
3177        );
3178        assert!(path.exists(), "owner B's lock must survive");
3179        let still = read_lock_metadata(&path).expect("still readable");
3180        assert_eq!(still.pid, 4242, "owner B's lock intact");
3181    }
3182
3183    #[test]
3184    fn reclaim_deletes_when_identity_still_matches() {
3185        let (_dir, path) = test_lock_path();
3186        let owner = synthetic_metadata(1111, "host-a".to_string(), 5_000);
3187        create_lock_file_atomically(&path, &owner).expect("write lock");
3188
3189        // Same identity we judged → safe to remove.
3190        let outcome = reclaim_lock_file(&path, &owner).expect("reclaim");
3191        assert!(
3192            matches!(outcome, ReclaimResult::Removed),
3193            "matching-identity stale lock should be removed"
3194        );
3195        assert!(!path.exists());
3196
3197        // Reclaiming a now-absent lock is a no-op, not an error.
3198        assert!(matches!(
3199            reclaim_lock_file(&path, &owner).expect("reclaim missing"),
3200            ReclaimResult::Unchanged
3201        ));
3202    }
3203
3204    #[test]
3205    fn try_acquire_once_reclaims_malformed_after_one_grace_read() {
3206        for contents in [
3207            b"".as_slice(),
3208            b"{\"pid\":999999999,\"hostname\":".as_slice(),
3209        ] {
3210            let (_dir, path) = test_lock_path();
3211            fs::write(&path, contents).unwrap();
3212            let sleeper_entries = Arc::new(AtomicUsize::new(0));
3213            let _observer = observe_retry_sleeps_for_test(Arc::clone(&sleeper_entries));
3214            let guard = try_acquire_once(&path).expect("stable malformed lease must be reclaimed");
3215            assert!(guard.verify_writer_epoch().unwrap());
3216            assert_eq!(sleeper_entries.load(Ordering::SeqCst), 1);
3217        }
3218    }
3219
3220    #[test]
3221    fn try_acquire_once_malformed_reclaim_stops_when_token_is_held() {
3222        let (_dir, path) = test_lock_path();
3223        fs::write(&path, b"malformed").unwrap();
3224        write_reclaim_token(&path, &current_process_metadata());
3225        let sleeper_entries = Arc::new(AtomicUsize::new(0));
3226        let _observer = observe_retry_sleeps_for_test(Arc::clone(&sleeper_entries));
3227        assert!(matches!(
3228            try_acquire_once(&path),
3229            Err(AcquireError::Timeout)
3230        ));
3231        assert_eq!(sleeper_entries.load(Ordering::SeqCst), 1);
3232        assert_eq!(fs::read(&path).unwrap(), b"malformed");
3233    }
3234
3235    #[test]
3236    fn try_acquire_once_malformed_reclaim_preserves_live_replacement() {
3237        let (_dir, path) = test_lock_path();
3238        fs::write(&path, b"malformed").unwrap();
3239        let replacement = current_process_metadata();
3240        let expected_epoch = replacement.writer_epoch.clone();
3241        let replace_path = path.clone();
3242        BEFORE_MALFORMED_RECLAIM.with(|slot| {
3243            *slot.borrow_mut() = Some(Box::new(move || {
3244                fs::remove_file(&replace_path).unwrap();
3245                write_synthetic_lock(&replace_path, &replacement);
3246            }))
3247        });
3248        assert!(matches!(
3249            try_acquire_once(&path),
3250            Err(AcquireError::Timeout)
3251        ));
3252        assert_eq!(
3253            read_lock_metadata(&path).unwrap().writer_epoch,
3254            expected_epoch
3255        );
3256    }
3257
3258    #[test]
3259    fn try_acquire_once_never_waits_behind_live_owner() {
3260        const OUTER_THREAD_JOIN_TIMEOUT: Duration = Duration::from_secs(30);
3261
3262        let (_dir, path) = test_lock_path();
3263        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
3264        let contender_path = path.clone();
3265        let sleeper_entries = Arc::new(AtomicUsize::new(0));
3266        let contender_sleeper_entries = Arc::clone(&sleeper_entries);
3267        let (announced_tx, announced_rx) = mpsc::sync_channel(1);
3268        let (enter_tx, enter_rx) = mpsc::sync_channel::<()>(1);
3269        let (result_tx, result_rx) = mpsc::sync_channel(1);
3270        let contender = std::thread::spawn(move || {
3271            let _ = announced_tx.send(());
3272            let _ = enter_rx.recv();
3273            let _observer = observe_retry_sleeps_for_test(contender_sleeper_entries);
3274            let _ = result_tx.send(try_acquire_once(&contender_path));
3275        });
3276
3277        announced_rx
3278            .recv_timeout(OUTER_THREAD_JOIN_TIMEOUT)
3279            .expect("contender should announce before the controlled enter gate");
3280        // Keep the announce-to-enter gap under channel control rather than
3281        // charging an arbitrary scheduler pause to the acquisition decision.
3282        enter_tx
3283            .send(())
3284            .expect("contender should wait at the controlled enter gate");
3285
3286        let result = match result_rx.recv_timeout(OUTER_THREAD_JOIN_TIMEOUT) {
3287            Ok(result) => result,
3288            Err(error) => {
3289                drop(guard);
3290                let _ = result_rx.recv_timeout(OUTER_THREAD_JOIN_TIMEOUT);
3291                let _ = contender.join();
3292                panic!("contender did not finish before the outer join bound: {error}");
3293            }
3294        };
3295
3296        contender.join().expect("contender should exit");
3297        assert!(matches!(result, Err(AcquireError::Timeout)));
3298        assert_eq!(
3299            sleeper_entries.load(Ordering::SeqCst),
3300            0,
3301            "zero-timeout acquisition must return Timeout without sleeping"
3302        );
3303    }
3304
3305    #[test]
3306    fn acquire_serializes_concurrent_callers() {
3307        let (_dir, path) = test_lock_path();
3308        let path = Arc::new(path);
3309        let barrier = Arc::new(Barrier::new(3));
3310        let inside = Arc::new(AtomicUsize::new(0));
3311        let entered = Arc::new(AtomicUsize::new(0));
3312        let max_inside = Arc::new(AtomicUsize::new(0));
3313
3314        let mut handles = Vec::new();
3315        for _ in 0..2 {
3316            let path = Arc::clone(&path);
3317            let barrier = Arc::clone(&barrier);
3318            let inside = Arc::clone(&inside);
3319            let entered = Arc::clone(&entered);
3320            let max_inside = Arc::clone(&max_inside);
3321            handles.push(thread::spawn(move || {
3322                barrier.wait();
3323                let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
3324                    .expect("thread acquire lock");
3325                let previous = inside.fetch_add(1, Ordering::SeqCst);
3326                assert_eq!(previous, 0, "two lock holders overlapped");
3327                entered.fetch_add(1, Ordering::SeqCst);
3328                max_inside.fetch_max(previous + 1, Ordering::SeqCst);
3329                thread::sleep(Duration::from_millis(75));
3330                inside.fetch_sub(1, Ordering::SeqCst);
3331                drop(guard);
3332            }));
3333        }
3334
3335        barrier.wait();
3336        for handle in handles {
3337            handle.join().expect("join worker");
3338        }
3339
3340        assert_eq!(entered.load(Ordering::SeqCst), 2);
3341        assert_eq!(max_inside.load(Ordering::SeqCst), 1);
3342        assert!(!path.exists());
3343    }
3344
3345    #[test]
3346    fn failed_atomic_replacement_preserves_existing_destination() {
3347        let dir = tempfile::tempdir().expect("create temp dir");
3348        let source = dir.path().join("source.tmp");
3349        let destination = dir.path().join("artifact.bin");
3350        fs::write(&source, b"new artifact").expect("write source");
3351        fs::write(&destination, b"valid old artifact").expect("write destination");
3352
3353        let error = rename_over_with(&source, &destination, |_from, _to| {
3354            Err(io::Error::new(
3355                io::ErrorKind::PermissionDenied,
3356                "injected replacement failure",
3357            ))
3358        })
3359        .expect_err("replacement must fail");
3360
3361        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
3362        assert_eq!(
3363            fs::read(&destination).expect("read preserved destination"),
3364            b"valid old artifact"
3365        );
3366        assert_eq!(
3367            fs::read(&source).expect("read retained source"),
3368            b"new artifact"
3369        );
3370    }
3371
3372    /// Number of lease files and beats per lease that model sixty seconds of
3373    /// heartbeats at the production interval.
3374    const LEDGER_LEASES: usize = 8;
3375    const LEDGER_BEATS_PER_LEASE: usize = (60_000 / HEARTBEAT_INTERVAL_MS) as usize;
3376
3377    fn create_owned_lock(path: &Path) -> LockMetadata {
3378        let metadata = current_process_metadata();
3379        create_lock_file_atomically(path, &metadata).expect("create lock");
3380        metadata
3381    }
3382
3383    #[cfg(unix)]
3384    fn inode(path: &Path) -> u64 {
3385        use std::os::unix::fs::MetadataExt;
3386        fs::metadata(path).expect("lock metadata").ino()
3387    }
3388
3389    #[test]
3390    fn healthy_refresh_cadence_does_not_trigger_stale_warning() {
3391        let config = LockConfig::default();
3392        assert_eq!(config.live_owner_warning_age_ms(), 30_000);
3393        assert_eq!(config.cross_host_stale_heartbeat_ms(), 75_000);
3394        assert_eq!(test_config().live_owner_warning_age_ms(), 2_000);
3395    }
3396
3397    #[test]
3398    fn idle_writer_lease_writes_twice_in_sixty_seconds() {
3399        let (_dir, path) = test_lock_path();
3400        let owner = create_owned_lock(&path);
3401        let (pump, _handle) = HeartbeatPump::attach(&path, &owner).unwrap();
3402        let config = LockConfig::default();
3403        let start = Instant::now();
3404        let interval = Duration::from_millis(config.heartbeat_refresh_interval_ms);
3405        let mut next = start + interval;
3406        let bytes = fs::metadata(&path).unwrap().len();
3407        let _ = io_ledger::take();
3408        let mut writes = 0;
3409        // Drive the production scheduler with a virtual minute; actual lease
3410        // writes still go through the kept descriptor and I/O ledger.
3411        for seconds in (5..=60).step_by(5) {
3412            writes += usize::from(
3413                refresh_heartbeat_if_due(
3414                    &pump,
3415                    &mut next,
3416                    interval,
3417                    start + Duration::from_secs(seconds),
3418                )
3419                .unwrap(),
3420            );
3421        }
3422        let ledger = io_ledger::take();
3423        assert_eq!(writes, 2, "one idle lease must write at 25s and 50s only");
3424        assert_eq!(ledger.bytes_written, bytes * 2);
3425        assert_eq!(
3426            (ledger.file_syncs, ledger.dir_syncs, ledger.new_files),
3427            (0, 0, 0)
3428        );
3429        eprintln!("idle writer lease / virtual 60s: before=12 after={writes} {ledger:?}");
3430        unregister_lease_slot(pump.slot, &path);
3431    }
3432
3433    #[test]
3434    fn delayed_refresh_preserves_live_owner_and_foreign_freshness() {
3435        let (_dir, path) = test_lock_path();
3436        let mut owner = create_owned_lock(&path);
3437        let now = now_ms();
3438        // A wake delayed 40s beyond the 25s target is still inside the unchanged
3439        // 75s foreign-host window. Local identity remains protected even later.
3440        owner.heartbeat_at_ms = now - 65_000;
3441        fs::write(&path, lock_metadata_bytes(&owner).unwrap()).unwrap();
3442        let config = LockConfig::default();
3443        assert_eq!(config.cross_host_stale_heartbeat_ms(), 75_000);
3444        assert!(metadata_blocks_acquisition(
3445            &owner,
3446            "foreign-observer",
3447            config,
3448            now
3449        ));
3450        assert!(metadata_blocks_acquisition(
3451            &owner,
3452            &owner.hostname,
3453            config,
3454            now + 3_600_000
3455        ));
3456        let (pump, _handle) = HeartbeatPump::attach(&path, &owner).unwrap();
3457        let wake = Instant::now();
3458        let mut next = wake - Duration::from_secs(40);
3459        assert!(refresh_heartbeat_if_due(&pump, &mut next, Duration::from_secs(25), wake).unwrap());
3460        let refreshed = read_lock_metadata(&path).unwrap();
3461        assert!(refreshed.heartbeat_at_ms >= now);
3462        assert!(metadata_blocks_acquisition(
3463            &refreshed,
3464            "foreign-observer",
3465            config,
3466            now + 70_000
3467        ));
3468        unregister_lease_slot(pump.slot, &path);
3469    }
3470
3471    #[test]
3472    fn failed_refresh_retries_on_next_short_wake() {
3473        let (_dir, path) = test_lock_path();
3474        let owner = create_owned_lock(&path);
3475        let (pump, _handle) = HeartbeatPump::attach(&path, &owner).unwrap();
3476        let wake = Instant::now();
3477        let mut next = wake;
3478        fs::write(&path, b"partial").unwrap();
3479        assert!(refresh_heartbeat_if_due(&pump, &mut next, Duration::from_secs(25), wake).is_err());
3480        assert_eq!(next, wake, "a failed write must not postpone the retry");
3481        fs::write(&path, lock_metadata_bytes(&owner).unwrap()).unwrap();
3482        assert!(refresh_heartbeat_if_due(
3483            &pump,
3484            &mut next,
3485            Duration::from_secs(25),
3486            wake + Duration::from_secs(5)
3487        )
3488        .unwrap());
3489        unregister_lease_slot(pump.slot, &path);
3490    }
3491
3492    /// Sixty seconds of forced heartbeats on several leases must not fsync anything
3493    /// and must not create a new file per beat. The ledger totals are printed
3494    /// so the cost can be compared across changes.
3495    #[test]
3496    fn heartbeat_ledger_for_sixty_seconds_has_no_fsync_and_no_new_inodes() {
3497        let dir = tempfile::tempdir().expect("create temp dir");
3498        let leases = (0..LEDGER_LEASES)
3499            .map(|index| {
3500                let path = dir.path().join(format!("writer-{index}.lease"));
3501                let owner = create_owned_lock(&path);
3502                (path, owner)
3503            })
3504            .collect::<Vec<_>>();
3505        #[cfg(unix)]
3506        let inodes_before = leases
3507            .iter()
3508            .map(|(path, _)| inode(path))
3509            .collect::<Vec<_>>();
3510        let file_bytes: u64 = leases
3511            .iter()
3512            .map(|(path, _)| fs::metadata(path).expect("lock size").len())
3513            .sum();
3514
3515        let _ = io_ledger::take();
3516        for _ in 0..LEDGER_BEATS_PER_LEASE {
3517            for (path, owner) in &leases {
3518                heartbeat_once(path, owner, &Mutex::new(None)).expect("heartbeat");
3519            }
3520        }
3521        let ledger = io_ledger::take();
3522        eprintln!(
3523            "fs_lock heartbeat ledger: leases={LEDGER_LEASES} beats_per_lease={LEDGER_BEATS_PER_LEASE} {ledger:?}"
3524        );
3525
3526        assert_eq!(ledger.file_syncs, 0, "heartbeats must not fsync the lease");
3527        assert_eq!(
3528            ledger.dir_syncs, 0,
3529            "heartbeats must not fsync the directory"
3530        );
3531        assert_eq!(ledger.new_files, 0, "heartbeats must rewrite in place");
3532        assert_eq!(
3533            ledger.bytes_written,
3534            file_bytes * LEDGER_BEATS_PER_LEASE as u64,
3535            "each beat rewrites exactly one lease's bytes"
3536        );
3537        #[cfg(unix)]
3538        assert_eq!(
3539            leases
3540                .iter()
3541                .map(|(path, _)| inode(path))
3542                .collect::<Vec<_>>(),
3543            inodes_before,
3544            "heartbeats must keep the lease inode"
3545        );
3546        for (path, owner) in &leases {
3547            let current = read_lock_metadata(path).expect("read lease");
3548            assert!(lock_identity_matches(&current, owner));
3549            assert!(current.heartbeat_at_ms >= owner.heartbeat_at_ms);
3550        }
3551    }
3552
3553    /// The old contract asserted file + directory syncs at creation and during
3554    /// reclaim. Ownership instead depends on the live process identity: after
3555    /// power loss the owner is dead, and torn leases are stale. The atomic hard
3556    /// link and reclaim token still serialize live contenders without making
3557    /// those process-lifetime records power-loss durable.
3558    #[test]
3559    fn durability_lease_create_and_reclaim_unsynced() {
3560        let (_dir, path) = test_lock_path();
3561        let _ = io_ledger::take();
3562        crate::durability::take();
3563        let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
3564            .expect("create lease");
3565        let created = io_ledger::take();
3566        drop(guard);
3567        assert_eq!(
3568            (created.file_syncs, created.dir_syncs, created.new_files),
3569            (0, 0, 1),
3570            "lease creation must not sync: {created:?}"
3571        );
3572        assert_eq!(crate::durability::sync_count(&crate::durability::take()), 0);
3573
3574        let dead = synthetic_metadata(999_999_999, current_hostname(), now_ms());
3575        write_synthetic_lock(&path, &dead);
3576        let _ = io_ledger::take();
3577        crate::durability::take();
3578        let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
3579            .expect("reclaim dead lease");
3580        let reclaimed = io_ledger::take();
3581        drop(guard);
3582        // The failed create's temp file, reclaim token and new lease still
3583        // require three inodes, but none need to survive their owner's death.
3584        assert_eq!(
3585            (
3586                reclaimed.file_syncs,
3587                reclaimed.dir_syncs,
3588                reclaimed.new_files
3589            ),
3590            (0, 0, 3),
3591            "lease reclaim must not sync: {reclaimed:?}"
3592        );
3593        assert_eq!(crate::durability::sync_count(&crate::durability::take()), 0);
3594    }
3595
3596    /// Leases a live daemon of this size holds at once: one root-keyed inspect
3597    /// writer lease and one root-keyed callgraph writer lease per bound project,
3598    /// for about a hundred projects with both caches open.
3599    const DAEMON_SCALE_LEASES: usize = 200;
3600
3601    /// Fails if a beat opened or closed a descriptor instead of writing through
3602    /// the handle the guard keeps, which is what a regression to open-per-beat
3603    /// would show up as in the ledger.
3604    fn assert_beat_opens_no_descriptor(beat: &io_ledger::IoLedger) {
3605        assert_eq!(
3606            (beat.opens, beat.closes),
3607            (0, 0),
3608            "a beat must write through the kept handle, without opening or \
3609             closing a descriptor: {beat:?}"
3610        );
3611    }
3612
3613    /// What the heartbeat costs for a daemon-shaped set of long-lived leases.
3614    ///
3615    /// Before the kept handle, every beat of every lease opened the file,
3616    /// read it, wrote it and closed it: 200 opens and 200 closes per beat, 40
3617    /// per second at the five-second interval, and the macOS `close()` that
3618    /// pulls the page write-back ran on the heartbeat thread. A beat now writes
3619    /// through the handle the heartbeat already holds. `kept_descriptors` counts
3620    /// how many descriptor opens occur across all the beats, so a regression to
3621    /// open-per-beat moves it from zero to the number of beats.
3622    #[test]
3623    fn daemon_scale_heartbeats_keep_descriptors_open_between_beats() {
3624        let dir = tempfile::tempdir().expect("create temp dir");
3625        let _ = io_ledger::take();
3626        let guards = (0..DAEMON_SCALE_LEASES)
3627            .map(|index| {
3628                acquire_with_config(
3629                    &dir.path().join(format!("root-{index}.writer.lease")),
3630                    Some(Duration::from_secs(2)),
3631                    test_config(),
3632                )
3633                .expect("acquire live lease")
3634            })
3635            .collect::<Vec<_>>();
3636        // Open-only: every lease created here had no prior contents, so its
3637        // heartbeat started from the handle acquisition opened. A kept
3638        // descriptor released since would have taken the close path below.
3639        let setup = io_ledger::take();
3640        assert_eq!(
3641            setup.closes, 0,
3642            "acquiring a fresh lease must not close a descriptor: {setup:?}"
3643        );
3644
3645        let beats = 3;
3646        let _ = io_ledger::take();
3647        for _ in 0..beats {
3648            for guard in &guards {
3649                guard.heartbeat_once().expect("beat");
3650            }
3651        }
3652        let beat_cost = io_ledger::take();
3653        eprintln!(
3654            "fs_lock heartbeat cost: leases={DAEMON_SCALE_LEASES} beats_per_lease={beats} \
3655             opens={} closes={} bytes={} (open+close per beat would be opens={} closes={})",
3656            beat_cost.opens,
3657            beat_cost.closes,
3658            beat_cost.bytes_written,
3659            DAEMON_SCALE_LEASES * beats,
3660            DAEMON_SCALE_LEASES * beats,
3661        );
3662        assert_beat_opens_no_descriptor(&beat_cost);
3663        assert!(beat_cost.bytes_written > 0, "{beat_cost:?}");
3664
3665        for guard in &guards {
3666            let current = read_lock_metadata(guard.path()).expect("read lease");
3667            assert!(lock_identity_matches(&current, &guard.metadata));
3668        }
3669
3670        drop(guards);
3671        let released = io_ledger::take();
3672        // Release closes each handle once. Other tests in this process run
3673        // their own leases on their own threads, so this asks only that the
3674        // releases are accounted for, never for exactly this test's count.
3675        assert!(
3676            released.closes >= DAEMON_SCALE_LEASES as u64,
3677            "each live lease closes its handle once, at release: {released:?}"
3678        );
3679    }
3680
3681    /// A crash after an unsynced rename can leave a zero-length lease. Readers
3682    /// must treat it as stale: acquisition removes it and takes the lock, the
3683    /// owner's heartbeat reports a transient malformed read, and nothing panics.
3684    #[test]
3685    fn zero_length_lease_is_treated_as_stale() {
3686        let (_dir, path) = test_lock_path();
3687        fs::write(&path, b"").expect("write empty lease");
3688        let owner = current_process_metadata();
3689        assert!(matches!(
3690            heartbeat_once(&path, &owner, &Mutex::new(None)),
3691            Err(HeartbeatError::Malformed(_))
3692        ));
3693        assert!(!heartbeat_error_is_terminal(&HeartbeatError::Malformed(
3694            serde_json::from_slice::<LockMetadata>(b"").unwrap_err()
3695        )));
3696
3697        let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
3698            .expect("empty lease must be reclaimed");
3699        assert!(guard.verify_writer_epoch().expect("verify new owner"));
3700    }
3701
3702    /// When the new timestamp would change the file length, the heartbeat
3703    /// falls back to an atomic rename, still without fsync.
3704    #[test]
3705    fn heartbeat_length_change_falls_back_to_unsynced_rename() {
3706        let (_dir, path) = test_lock_path();
3707        let mut owner = current_process_metadata();
3708        owner.heartbeat_at_ms = 7;
3709        create_lock_file_atomically(&path, &owner).expect("create lock");
3710
3711        let _ = io_ledger::take();
3712        heartbeat_once(&path, &owner, &Mutex::new(None)).expect("heartbeat");
3713        let ledger = io_ledger::take();
3714        assert_eq!((ledger.file_syncs, ledger.dir_syncs), (0, 0), "{ledger:?}");
3715        assert_eq!(ledger.new_files, 1, "{ledger:?}");
3716        let current = read_lock_metadata(&path).expect("read lease");
3717        assert!(lock_identity_matches(&current, &owner));
3718        assert!(current.heartbeat_at_ms > 7);
3719        let leftovers = fs::read_dir(path.parent().unwrap()).unwrap().count();
3720        assert_eq!(leftovers, 1, "temp file must not be left behind");
3721    }
3722
3723    #[test]
3724    fn heartbeat_updates_lockfile_timestamp() {
3725        let (_dir, path) = test_lock_path();
3726        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
3727        let initial_metadata = read_lock_metadata(&path).expect("read initial metadata");
3728        let initial = initial_metadata.heartbeat_at_ms;
3729
3730        // Poll for up to 2s rather than sleeping a fixed multiple of the
3731        // heartbeat interval. `park_timeout` is a *maximum* wait, not a
3732        // guaranteed periodic timer — under load (shared macOS CI runners
3733        // running other cargo-test threads concurrently) the heartbeat
3734        // thread may not fire 3 times within 75ms even though
3735        // heartbeat_interval_ms=25. The contract being asserted is "the
3736        // heartbeat advances eventually", not "it advances within N
3737        // heartbeat intervals".
3738        //
3739        let deadline = std::time::Instant::now() + Duration::from_millis(2_000);
3740        let mut updated = initial;
3741        while std::time::Instant::now() < deadline {
3742            thread::sleep(Duration::from_millis(50));
3743            match read_lock_metadata(&path) {
3744                Ok(meta) => {
3745                    updated = meta.heartbeat_at_ms;
3746                    if updated > initial {
3747                        break;
3748                    }
3749                }
3750                Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
3751                    // Heartbeat thread is mid-rewrite (Windows
3752                    // remove-then-rename window). Retry next iteration.
3753                    continue;
3754                }
3755                Err(other) => panic!("read updated metadata: {other:?}"),
3756            }
3757        }
3758        assert!(
3759            updated > initial,
3760            "heartbeat timestamp did not advance within 2s"
3761        );
3762        let updated_metadata = read_lock_metadata(&path).expect("read final metadata");
3763        assert_eq!(
3764            updated_metadata.process_start_time, guard.metadata.process_start_time,
3765            "heartbeat rewrite must preserve the owner's process start time"
3766        );
3767        assert_eq!(
3768            updated_metadata.boot_id, guard.metadata.boot_id,
3769            "heartbeat rewrite must preserve the owner's boot identity"
3770        );
3771        drop(guard);
3772    }
3773
3774    #[test]
3775    fn dead_pid_lock_is_reclaimed() {
3776        let (_dir, path) = test_lock_path();
3777        let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
3778        write_synthetic_lock(&path, &metadata);
3779
3780        let (guard, lines) = crate::logging::capture_log_lines(|| {
3781            acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
3782                .expect("reclaim dead pid lock")
3783        });
3784        let reclaim_lines: Vec<_> = lines
3785            .iter()
3786            .filter(|line| line.contains("removing filesystem lock"))
3787            .collect();
3788        assert_eq!(
3789            reclaim_lines,
3790            vec![&format!(
3791                "INFO removing filesystem lock at {} from dead or recycled PID {}",
3792                path.display(),
3793                metadata.pid
3794            )]
3795        );
3796        let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
3797        assert_eq!(metadata.pid, std::process::id());
3798        drop(guard);
3799    }
3800
3801    #[test]
3802    fn zero_timeout_dead_pid_reclaim_acquires_after_removing_stale_file() {
3803        let (_dir, path) = test_lock_path();
3804        let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
3805        write_synthetic_lock(&path, &metadata);
3806
3807        let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
3808            .expect("zero-timeout acquire should claim the reaped stale lock");
3809        let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
3810        assert_eq!(metadata.pid, std::process::id());
3811        drop(guard);
3812    }
3813
3814    #[test]
3815    fn dead_same_host_reclaim_token_is_reaped_with_stale_lock() {
3816        let (_dir, path) = test_lock_path();
3817        let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
3818        write_synthetic_lock(&path, &stale);
3819        let token_path = write_reclaim_token(&path, &stale);
3820
3821        let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
3822            .expect("dead token must not wedge stale-lock reclamation");
3823        assert!(!token_path.exists(), "stale reclaim token must be removed");
3824        drop(guard);
3825        assert!(!path.exists(), "acquired lock must be released normally");
3826    }
3827
3828    #[test]
3829    fn live_reclaim_token_blocks_and_is_untouched() {
3830        let (_dir, path) = test_lock_path();
3831        let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
3832        write_synthetic_lock(&path, &stale);
3833        let live = current_process_metadata();
3834        let token_path = write_reclaim_token(&path, &live);
3835
3836        let result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
3837        assert!(matches!(result, Err(AcquireError::Timeout)));
3838        assert_eq!(read_lock_metadata(&token_path).expect("live token"), live);
3839    }
3840
3841    #[test]
3842    fn foreign_host_reclaim_token_is_authoritative() {
3843        let (_dir, path) = test_lock_path();
3844        let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
3845        write_synthetic_lock(&path, &stale);
3846        let mut foreign = stale.clone();
3847        foreign.hostname = format!("{}-foreign", current_hostname());
3848        let token_path = write_reclaim_token(&path, &foreign);
3849
3850        let result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
3851        assert!(matches!(result, Err(AcquireError::Timeout)));
3852        assert_eq!(
3853            read_lock_metadata(&token_path).expect("foreign token"),
3854            foreign
3855        );
3856    }
3857
3858    #[test]
3859    fn malformed_reclaim_token_is_held_until_older_than_sixty_seconds() {
3860        use filetime::{set_file_mtime, FileTime};
3861
3862        let (_dir, path) = test_lock_path();
3863        let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
3864        write_synthetic_lock(&path, &stale);
3865        let token_path = reclaim_token_path(&path);
3866        fs::write(&token_path, b"{ malformed").expect("write malformed token");
3867
3868        let young_result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
3869        assert!(matches!(young_result, Err(AcquireError::Timeout)));
3870        assert_eq!(fs::read(&token_path).expect("young token"), b"{ malformed");
3871
3872        let old = SystemTime::now()
3873            .checked_sub(RECLAIM_TOKEN_MALFORMED_STALE_AGE + Duration::from_secs(1))
3874            .expect("old timestamp");
3875        set_file_mtime(&token_path, FileTime::from_system_time(old)).expect("age token");
3876        let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
3877            .expect("old malformed token should be reclaimed");
3878        assert!(!token_path.exists());
3879        drop(guard);
3880    }
3881
3882    #[test]
3883    fn held_reclaim_token_logs_blocked_without_claiming_lock_removal() {
3884        let (_dir, path) = test_lock_path();
3885        let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
3886        write_synthetic_lock(&path, &stale);
3887        let live = current_process_metadata();
3888        write_reclaim_token(&path, &live);
3889        take_reclaim_test_logs();
3890
3891        let result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
3892        assert!(matches!(result, Err(AcquireError::Timeout)));
3893        let logs = take_reclaim_test_logs();
3894        assert!(logs.iter().any(|line| {
3895            line.contains(&format!("reclaim of {} blocked", path.display()))
3896                && line.contains(&format!("pid {} (alive)", live.pid))
3897        }));
3898        assert!(!logs
3899            .iter()
3900            .any(|line| line.contains("removing filesystem lock")));
3901    }
3902
3903    #[test]
3904    fn dead_unreclaimable_lock_retry_backoff_stays_bounded() {
3905        let mut elapsed_ms = 0_u64;
3906        let mut attempts = 0_u32;
3907        while elapsed_ms < 60_000 {
3908            elapsed_ms = elapsed_ms.saturating_add(dead_reclaim_backoff_ms(attempts, 100));
3909            attempts += 1;
3910        }
3911
3912        assert!(
3913            attempts <= 17,
3914            "{attempts} retries exceed the one-minute bound"
3915        );
3916        assert_eq!(dead_reclaim_backoff_ms(0, 100), 250);
3917        assert_eq!(dead_reclaim_backoff_ms(20, 100), 5_000);
3918    }
3919
3920    #[test]
3921    fn stale_heartbeat_from_live_pid_blocks() {
3922        let (_dir, path) = test_lock_path();
3923        let mut metadata = current_process_metadata();
3924        #[cfg(any(target_os = "linux", target_os = "macos"))]
3925        {
3926            let identity = process_identity(std::process::id())
3927                .expect("current process should have a start-time identity");
3928            assert_eq!(metadata.process_start_time, Some(identity.start_time));
3929            assert_eq!(metadata.boot_id, identity.boot_id);
3930        }
3931        metadata.created_at_ms = now_ms().saturating_sub(60_000);
3932        metadata.heartbeat_at_ms = now_ms().saturating_sub(60_000);
3933        write_synthetic_lock(&path, &metadata);
3934
3935        let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
3936        assert!(matches!(result, Err(AcquireError::Timeout)));
3937        assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);
3938
3939        remove_lock_file(&path).expect("cleanup synthetic lock");
3940    }
3941
3942    #[test]
3943    fn availability_probe_preserves_a_live_owner_with_stale_heartbeat() {
3944        let (_dir, path) = test_lock_path();
3945        let mut metadata = current_process_metadata();
3946        metadata.heartbeat_at_ms = 0;
3947        write_synthetic_lock(&path, &metadata);
3948        let original = fs::read(&path).unwrap();
3949        assert_eq!(
3950            lock_availability(&path).unwrap(),
3951            LockAvailability::LiveOwner
3952        );
3953        assert_eq!(fs::read(&path).unwrap(), original);
3954    }
3955
3956    #[test]
3957    fn availability_probe_observes_dead_and_missing_owners_without_reclaiming() {
3958        let (_dir, path) = test_lock_path();
3959        assert_eq!(
3960            lock_availability(&path).unwrap(),
3961            LockAvailability::Available
3962        );
3963        assert!(!path.exists());
3964        let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
3965        write_synthetic_lock(&path, &metadata);
3966        let original = fs::read(&path).unwrap();
3967        assert_eq!(lock_availability(&path).unwrap(), LockAvailability::Stale);
3968        assert_eq!(fs::read(&path).unwrap(), original);
3969    }
3970
3971    #[test]
3972    fn availability_probe_uses_extended_cross_host_heartbeat_policy() {
3973        let (_dir, path) = test_lock_path();
3974        let mut metadata = synthetic_metadata(
3975            999_999_999,
3976            format!("other-{}", current_hostname()),
3977            now_ms(),
3978        );
3979        write_synthetic_lock(&path, &metadata);
3980        assert!(
3981            lock_availability(&path).unwrap() == LockAvailability::LiveOwner,
3982            "a local PID probe cannot attest a remote owner"
3983        );
3984        metadata.heartbeat_at_ms = now_ms().saturating_sub(STALE_HEARTBEAT_MS * 2);
3985        fs::write(&path, serde_json::to_vec(&metadata).unwrap()).unwrap();
3986        assert!(
3987            lock_availability(&path).unwrap() == LockAvailability::LiveOwner,
3988            "cross-host reclamation needs the extended threshold"
3989        );
3990        metadata.heartbeat_at_ms = now_ms().saturating_sub(STALE_HEARTBEAT_MS * 5 + 1_000);
3991        fs::write(&path, serde_json::to_vec(&metadata).unwrap()).unwrap();
3992        assert_eq!(lock_availability(&path).unwrap(), LockAvailability::Stale);
3993        assert_eq!(read_lock_metadata(&path).unwrap(), metadata);
3994    }
3995
3996    #[test]
3997    fn availability_probe_does_not_treat_malformed_metadata_as_available() {
3998        let (_dir, path) = test_lock_path();
3999        fs::write(&path, b"not-json").unwrap();
4000        assert_eq!(
4001            lock_availability(&path).unwrap(),
4002            LockAvailability::Malformed
4003        );
4004        assert_eq!(fs::read(&path).unwrap(), b"not-json");
4005    }
4006
4007    #[test]
4008    fn availability_probe_keeps_io_errors_distinct_and_can_retry() {
4009        let (_dir, path) = test_lock_path();
4010        fs::create_dir(&path).unwrap();
4011        assert!(lock_availability(&path).is_err());
4012        assert!(path.is_dir());
4013        fs::remove_dir(&path).unwrap();
4014        assert_eq!(
4015            lock_availability(&path).unwrap(),
4016            LockAvailability::Available
4017        );
4018    }
4019
4020    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
4021    #[test]
4022    fn live_pid_with_wrong_start_time_is_reclaimed() {
4023        let (_dir, path) = test_lock_path();
4024        let mut metadata = current_process_metadata();
4025        let current_identity = process_identity(std::process::id())
4026            .expect("current process should have a start-time identity");
4027        metadata.process_start_time = Some(different_start_time(current_identity.start_time));
4028        metadata.boot_id = current_identity.boot_id;
4029        write_synthetic_lock(&path, &metadata);
4030
4031        let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
4032            .expect("zero-timeout acquire should reclaim a reused PID");
4033        assert_eq!(guard.metadata.pid, std::process::id());
4034        assert_eq!(
4035            guard.metadata.process_start_time,
4036            Some(current_identity.start_time)
4037        );
4038        drop(guard);
4039    }
4040
4041    #[cfg(target_os = "linux")]
4042    #[test]
4043    fn live_pid_with_wrong_boot_id_is_reclaimed() {
4044        let (_dir, path) = test_lock_path();
4045        let mut metadata = current_process_metadata();
4046        let current_identity = process_identity(std::process::id())
4047            .expect("current process should have a start-time identity");
4048        metadata.boot_id = Some(format!("wrong-{}", current_identity.boot_id.unwrap()));
4049        write_synthetic_lock(&path, &metadata);
4050
4051        let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
4052            .expect("zero-timeout acquire should reclaim a rebooted PID identity");
4053        assert_eq!(guard.metadata.pid, std::process::id());
4054        drop(guard);
4055    }
4056
4057    #[test]
4058    fn legacy_live_pid_lock_keeps_pid_only_liveness() {
4059        let (_dir, path) = test_lock_path();
4060        let stale_at = now_ms().saturating_sub(60_000);
4061        let mut metadata = synthetic_metadata(std::process::id(), current_hostname(), stale_at);
4062        metadata.heartbeat_at_ms = stale_at;
4063        let original = write_legacy_lock(&path, &metadata);
4064        assert!(!original.contains("process_start_time"));
4065        assert!(!original.contains("boot_id"));
4066
4067        let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
4068        assert!(matches!(result, Err(AcquireError::Timeout)));
4069        assert_eq!(
4070            fs::read_to_string(&path).expect("read legacy lock"),
4071            original
4072        );
4073
4074        remove_lock_file(&path).expect("cleanup legacy lock");
4075    }
4076
4077    #[test]
4078    fn legacy_dead_pid_lock_is_reclaimed() {
4079        let (_dir, path) = test_lock_path();
4080        let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
4081        let original = write_legacy_lock(&path, &metadata);
4082        assert!(!original.contains("process_start_time"));
4083        assert!(!original.contains("boot_id"));
4084
4085        let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
4086            .expect("zero-timeout acquire should reclaim a legacy dead PID lock");
4087        assert_eq!(guard.metadata.pid, std::process::id());
4088        drop(guard);
4089    }
4090
4091    #[test]
4092    fn healthy_live_owner_blocks() {
4093        let (_dir, path) = test_lock_path();
4094        let metadata = current_process_metadata();
4095        write_synthetic_lock(&path, &metadata);
4096
4097        let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
4098        assert!(matches!(result, Err(AcquireError::Timeout)));
4099
4100        remove_lock_file(&path).expect("cleanup synthetic lock");
4101    }
4102
4103    #[cfg(any(target_os = "linux", target_os = "macos"))]
4104    #[test]
4105    fn semantic_batch_lease_exited_unreaped_owner_is_dead() {
4106        use std::io::Write;
4107        use std::process::{Command, Stdio};
4108        for legacy in [false, true] {
4109            let (_root, path) = test_lock_path();
4110            let mut child = Command::new("sh")
4111                .args(["-c", "read gate; exit 0"])
4112                .stdin(Stdio::piped())
4113                .spawn()
4114                .unwrap();
4115            let identity = process_identity(child.id()).unwrap();
4116            let mut metadata = synthetic_metadata(child.id(), current_hostname(), now_ms());
4117            metadata.process_start_time = Some(identity.start_time);
4118            metadata.boot_id = identity.boot_id;
4119            if legacy {
4120                write_legacy_lock(&path, &metadata);
4121            } else {
4122                write_synthetic_lock(&path, &metadata);
4123            }
4124            writeln!(child.stdin.take().unwrap(), "exit").unwrap();
4125            // WNOWAIT proves exit without reaping: kill(pid, 0) can still see
4126            // this PID, but the process can no longer execute protected work.
4127            let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
4128            let observed = unsafe {
4129                libc::waitid(
4130                    libc::P_PID,
4131                    libc::id_t::try_from(child.id()).unwrap(),
4132                    info.as_mut_ptr(),
4133                    libc::WEXITED | libc::WNOWAIT,
4134                )
4135            };
4136            let wait_error = io::Error::last_os_error();
4137            let exited = process_identity(child.id()).is_some_and(|identity| identity.exited);
4138            let recovered = try_acquire_once(&path);
4139            child.wait().unwrap();
4140            assert_eq!(observed, 0, "waitid failed: {wait_error}");
4141            assert!(exited, "the native identity probe did not observe exit");
4142            assert!(
4143                recovered.is_ok(),
4144                "an exited unreaped owner blocked recovery (legacy={legacy})"
4145            );
4146        }
4147    }
4148
4149    #[cfg(target_os = "linux")]
4150    #[test]
4151    fn semantic_batch_lease_linux_stat_requires_quiescent_zombie() {
4152        let one =
4153            "4242 (worker (lease owner)) Z 1 1 1 0 -1 4194304 10 0 0 0 0 0 0 0 20 0 1 0 1234 0";
4154        assert_eq!(linux_process_stat_identity(one), Some((1234, true)));
4155        let live_threads = one.replace(" 1 0 1234 ", " 2 0 1234 ");
4156        assert_eq!(
4157            linux_process_stat_identity(&live_threads),
4158            Some((1234, false)),
4159            "a zombie leader does not prove its worker threads exited"
4160        );
4161        assert_eq!(
4162            linux_process_stat_identity(&one.replace(" 1 0 1234 ", " 0 0 1234 ")),
4163            Some((1234, false))
4164        );
4165        assert_eq!(
4166            linux_process_stat_identity(&one.replace(") Z ", ") X ")),
4167            Some((1234, true))
4168        );
4169        assert_eq!(
4170            linux_process_stat_identity(&one.replace(") Z ", ") S ")),
4171            Some((1234, false))
4172        );
4173        assert_eq!(
4174            linux_process_stat_identity(&one.replace(" 1 0 1234 ", " bad 0 1234 ")),
4175            None
4176        );
4177        assert_eq!(
4178            linux_process_stat_identity(&one.replace("1234", "bad")),
4179            None
4180        );
4181        assert_eq!(
4182            linux_process_stat_identity(&one.replace(") Z ", ") bad ")),
4183            None
4184        );
4185    }
4186
4187    #[test]
4188    fn malformed_lockfile_is_reclaimed() {
4189        let (_dir, path) = test_lock_path();
4190        fs::write(&path, b"not valid json").expect("write malformed lock");
4191
4192        let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
4193            .expect("reclaim malformed lock");
4194        let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
4195        assert_eq!(metadata.pid, std::process::id());
4196        drop(guard);
4197    }
4198
4199    #[test]
4200    fn cross_host_lock_is_not_stolen_before_extended_stale_threshold() {
4201        let (_dir, path) = test_lock_path();
4202        let now = now_ms();
4203        let mut metadata = current_process_metadata();
4204        metadata.hostname = format!("{}-other", current_hostname());
4205        metadata.process_start_time = metadata.process_start_time.map(different_start_time);
4206        metadata.created_at_ms = now;
4207        metadata.heartbeat_at_ms = now;
4208        metadata.writer_epoch = format!("cross-host-{now}");
4209        #[cfg(any(target_os = "linux", target_os = "macos"))]
4210        assert_ne!(
4211            metadata.process_start_time,
4212            process_identity(std::process::id()).map(|identity| identity.start_time)
4213        );
4214        write_synthetic_lock(&path, &metadata);
4215
4216        let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
4217        assert!(matches!(result, Err(AcquireError::Timeout)));
4218        assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);
4219
4220        remove_lock_file(&path).expect("cleanup synthetic lock");
4221    }
4222
4223    #[test]
4224    fn stale_cross_host_lock_is_reclaimed_after_extended_threshold() {
4225        let (_dir, path) = test_lock_path();
4226        let stale_at =
4227            now_ms().saturating_sub(test_config().cross_host_stale_heartbeat_ms() + 1_000);
4228        let mut metadata = current_process_metadata();
4229        metadata.hostname = format!("{}-other", current_hostname());
4230        metadata.process_start_time = metadata.process_start_time.map(different_start_time);
4231        metadata.created_at_ms = stale_at;
4232        metadata.heartbeat_at_ms = stale_at;
4233        metadata.writer_epoch = format!("cross-host-{stale_at}");
4234        write_synthetic_lock(&path, &metadata);
4235
4236        let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
4237            .expect("reclaim stale cross-host lock");
4238        let reclaimed = read_lock_metadata(&path).expect("read reclaimed lock");
4239        assert_eq!(reclaimed.hostname, current_hostname());
4240        assert_ne!(reclaimed.created_at_ms, metadata.created_at_ms);
4241        drop(guard);
4242    }
4243
4244    #[test]
4245    fn live_owner_over_10min_warns_but_blocks() {
4246        let (_dir, path) = test_lock_path();
4247        let mut metadata = current_process_metadata();
4248        metadata.created_at_ms = now_ms().saturating_sub(11 * 60 * 1_000);
4249        metadata.heartbeat_at_ms = now_ms();
4250        write_synthetic_lock(&path, &metadata);
4251
4252        let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
4253        assert!(matches!(result, Err(AcquireError::Timeout)));
4254        assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);
4255
4256        remove_lock_file(&path).expect("cleanup synthetic lock");
4257    }
4258
4259    #[derive(Debug, serde::Serialize, serde::Deserialize)]
4260    struct HeartbeatObservation {
4261        step: usize,
4262        observed_at_ms: u64,
4263        heartbeat_at_ms: Option<u64>,
4264        volume: Option<u64>,
4265        inode: Option<u64>,
4266        modified_at_ms: Option<u64>,
4267        error: Option<String>,
4268    }
4269
4270    fn observe_heartbeat(path: &Path, step: usize) -> HeartbeatObservation {
4271        let mut observation = HeartbeatObservation {
4272            step,
4273            observed_at_ms: now_ms(),
4274            heartbeat_at_ms: None,
4275            volume: None,
4276            inode: None,
4277            modified_at_ms: None,
4278            error: None,
4279        };
4280        let mut file = match File::open(path) {
4281            Ok(file) => file,
4282            Err(error) => {
4283                observation.error = Some(error.to_string());
4284                return observation;
4285            }
4286        };
4287        // Identity and contents come from the same open, including if the path
4288        // is atomically replaced while the observer is reading it.
4289        if let Some(identity) = LeaseFileIdentity::of_file(&file) {
4290            observation.volume = Some(identity.volume);
4291            observation.inode = Some(identity.file);
4292        }
4293        observation.modified_at_ms = file
4294            .metadata()
4295            .and_then(|metadata| metadata.modified())
4296            .ok()
4297            .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
4298            .map(|elapsed| elapsed.as_millis() as u64);
4299        let mut bytes = Vec::new();
4300        match file.read_to_end(&mut bytes) {
4301            Ok(_) => match serde_json::from_slice::<LockMetadata>(&bytes) {
4302                Ok(metadata) => observation.heartbeat_at_ms = Some(metadata.heartbeat_at_ms),
4303                Err(error) => observation.error = Some(error.to_string()),
4304            },
4305            Err(error) => observation.error = Some(error.to_string()),
4306        }
4307        observation
4308    }
4309
4310    struct HeartbeatHarness {
4311        child: Child,
4312        input: Option<ChildStdin>,
4313        lines: mpsc::Receiver<String>,
4314        reader: Option<JoinHandle<()>>,
4315        transcript: Vec<String>,
4316    }
4317
4318    impl HeartbeatHarness {
4319        fn read_observation(
4320            &mut self,
4321            prefix: &str,
4322            deadline: Instant,
4323        ) -> Result<HeartbeatObservation, String> {
4324            loop {
4325                let line = self
4326                    .lines
4327                    .recv_timeout(deadline.saturating_duration_since(Instant::now()))
4328                    .map_err(|error| format!("observer response: {error}"))?;
4329                self.transcript.push(line.clone());
4330                if let Some(json) = line.strip_prefix(prefix) {
4331                    return serde_json::from_str(json)
4332                        .map_err(|error| format!("observer JSON: {error}"));
4333                }
4334            }
4335        }
4336
4337        fn observe(
4338            &mut self,
4339            step: usize,
4340            deadline: Instant,
4341        ) -> Result<HeartbeatObservation, String> {
4342            let input = self.input.as_mut().expect("observer input is open");
4343            writeln!(input, "{step}").map_err(|error| error.to_string())?;
4344            input.flush().map_err(|error| error.to_string())?;
4345            self.read_observation("sample:", deadline)
4346        }
4347
4348        fn diagnostics(&self, path: &Path, guard: &LockGuard, step: usize) -> String {
4349            let held_identity = guard.heartbeat_file.try_lock().ok().and_then(|mut slot| {
4350                slot.as_mut()
4351                    .and_then(|lease| LeaseFileIdentity::of_file(lease.file()))
4352            });
4353            format!(
4354                "parent={:?} held_identity={held_identity:?} stopped={} visible={}\nchild observations:\n{}",
4355                observe_heartbeat(path, step),
4356                guard.pump.heartbeat_stopped(),
4357                guard.heartbeat_is_visible(),
4358                self.transcript.join("\n")
4359            )
4360        }
4361
4362        fn finish(&mut self) -> std::process::ExitStatus {
4363            self.input.take();
4364            let status = self.child.wait().expect("observer exit");
4365            self.reader.take().unwrap().join().expect("observer reader");
4366            self.transcript.extend(self.lines.try_iter());
4367            status
4368        }
4369    }
4370
4371    impl Drop for HeartbeatHarness {
4372        fn drop(&mut self) {
4373            // An assertion can unwind before normal EOF/wait cleanup. Reap the
4374            // observer and join its stdout reader before the owner releases the
4375            // lease, so no child retains the test runner's inherited stderr.
4376            self.input.take();
4377            if !matches!(self.child.try_wait(), Ok(Some(_))) {
4378                let _ = self.child.kill();
4379            }
4380            let _ = self.child.wait();
4381            if let Some(reader) = self.reader.take() {
4382                let _ = reader.join();
4383            }
4384        }
4385    }
4386
4387    /// Run the Rust test binary as an independent lease observer. Each request
4388    /// opens the lease afresh and returns its content timestamp and file identity.
4389    fn spawn_test_harness(mode: &str, path: &Path) -> HeartbeatHarness {
4390        let mut command = std::process::Command::new(std::env::current_exe().expect("test exe"));
4391        command
4392            .args(["--exact", HARNESS_TEST, "--nocapture", "--test-threads=1"])
4393            .env("FS_LOCK_HARNESS_MODE", mode)
4394            .env("FS_LOCK_HARNESS_PATH", path)
4395            .stdin(Stdio::piped())
4396            .stdout(Stdio::piped());
4397        for name in [
4398            "AFT_TEST_REQUIRE_RUST_ANALYZER",
4399            "AFT_TEST_STORAGE_ROOT",
4400            "AFT_STORAGE_DIR",
4401        ] {
4402            command.env_remove(name);
4403        }
4404        let mut child = command.spawn().expect("spawn test harness process");
4405        let stdin = child.stdin.take().expect("harness stdin");
4406        let stdout = child.stdout.take().expect("harness stdout");
4407        let (sender, receiver) = mpsc::channel();
4408        let reader = thread::spawn(move || {
4409            for line in io::BufReader::new(stdout).lines() {
4410                let Ok(line) = line else { break };
4411                if sender.send(line).is_err() {
4412                    break;
4413                }
4414            }
4415        });
4416        HeartbeatHarness {
4417            child,
4418            input: Some(stdin),
4419            lines: receiver,
4420            reader: Some(reader),
4421            transcript: Vec::new(),
4422        }
4423    }
4424
4425    /// Another process must see background heartbeats through the kept handle.
4426    /// A beat interval is not a scheduling guarantee: allow progress within the
4427    /// configured stale bound, and never substitute a parent-side read for the
4428    /// observer's actual timestamp and inode.
4429    #[test]
4430    fn separate_process_sees_heartbeat_advance() {
4431        if std::env::var_os(HARNESS_TEST).is_some() {
4432            return;
4433        }
4434        assert_separate_process_heartbeat_advances(test_config());
4435    }
4436
4437    #[test]
4438    fn separate_process_waits_for_heartbeat_within_stale_bound() {
4439        assert_separate_process_heartbeat_advances(LockConfig {
4440            heartbeat_interval_ms: 400,
4441            ..test_config()
4442        });
4443    }
4444
4445    fn assert_separate_process_heartbeat_advances(config: LockConfig) {
4446        let (_dir, path) = test_lock_path();
4447        let guard = acquire_with_config(&path, None, config).expect("acquire lock");
4448        guard.heartbeat_once().expect("initial beat");
4449        let mut harness = spawn_test_harness(HARNESS_MODE_INSPECT, &path);
4450        let ready = harness
4451            .read_observation("ready:", Instant::now() + Duration::from_secs(10))
4452            .unwrap_or_else(|error| {
4453                panic!(
4454                    "observer startup failed: {error}\n{}",
4455                    harness.diagnostics(&path, &guard, 0)
4456                )
4457            });
4458        let mut previous = ready.heartbeat_at_ms.unwrap_or_else(|| {
4459            panic!(
4460                "observer could not read initial lease\n{}",
4461                harness.diagnostics(&path, &guard, 0)
4462            )
4463        });
4464        for step in 1..=4 {
4465            let deadline = Instant::now() + Duration::from_millis(config.stale_heartbeat_ms);
4466            loop {
4467                let observation = harness.observe(step, deadline).unwrap_or_else(|error| {
4468                    panic!(
4469                        "observer step {step} failed: {error}\n{}",
4470                        harness.diagnostics(&path, &guard, step)
4471                    )
4472                });
4473                if let Some(seen) = observation.heartbeat_at_ms.filter(|seen| *seen > previous) {
4474                    eprintln!("heartbeat observer advanced: {observation:?}");
4475                    previous = seen;
4476                    break;
4477                }
4478                assert!(
4479                    Instant::now() < deadline,
4480                    "observer heartbeat did not advance from {previous} within {}ms at step {step}\n{}",
4481                    config.stale_heartbeat_ms,
4482                    harness.diagnostics(&path, &guard, step)
4483                );
4484                thread::sleep(
4485                    Duration::from_millis(25)
4486                        .min(deadline.saturating_duration_since(Instant::now())),
4487                );
4488            }
4489        }
4490        let status = harness.finish();
4491        assert!(
4492            status.success(),
4493            "observer failed: {status:?}\n{}",
4494            harness.diagnostics(&path, &guard, 4)
4495        );
4496    }
4497
4498    #[cfg(unix)]
4499    #[test]
4500    fn separate_process_harness_drop_reaps_observer() {
4501        let (_dir, path) = test_lock_path();
4502        write_synthetic_lock(&path, &current_process_metadata());
4503        let mut harness = spawn_test_harness(HARNESS_MODE_INSPECT, &path);
4504        harness
4505            .read_observation("ready:", Instant::now() + Duration::from_secs(10))
4506            .expect("observer ready");
4507        let pid = harness.child.id() as libc::pid_t;
4508        drop(harness);
4509        let mut status = 0;
4510        // SAFETY: pid names the child this test just spawned; status is a valid
4511        // out pointer. A completed Drop must already have waited for this child.
4512        let waited = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
4513        let error = io::Error::last_os_error().raw_os_error();
4514        if waited == 0 {
4515            // SAFETY: only our still-running child can be waitable under pid.
4516            unsafe {
4517                libc::kill(pid, libc::SIGKILL);
4518                libc::waitpid(pid, &mut status, 0);
4519            }
4520        }
4521        assert_eq!(waited, -1, "observer survived harness drop");
4522        assert_eq!(error, Some(libc::ECHILD), "observer was not reaped");
4523    }
4524
4525    /// A replacement by another part of this process must leave the owner's
4526    /// heartbeat working: writers keep publishing through the same guard, and a
4527    /// heartbeat that stopped would let another process reclaim the lease after
4528    /// the stale window while the writer is still running. The test replaces the
4529    /// lease (which releases the published handle), then opens a fresh handle
4530    /// and publishes it, and requires the next beat to refresh through it.
4531    #[test]
4532    fn replacing_the_lease_keeps_the_next_beat_working_for_the_owner() {
4533        let (_dir, path) = test_lock_path();
4534        let guard = acquire_with_config(&path, None, test_config()).expect("acquire");
4535        let mut restored = guard.metadata.clone();
4536        // Same digit count as the live heartbeat, so the serialized lease keeps
4537        // its byte length; the replacement itself is still an atomic rename.
4538        restored.heartbeat_at_ms = now_ms().saturating_sub(1_000);
4539        let fresh = {
4540            let bytes = lock_metadata_bytes(&restored).expect("serialize");
4541            with_lease_handles_closed(&path, || {
4542                replace_lock_bytes_unsynced(&path, &bytes).map(|()| open_lease_for_heartbeat(&path))
4543            })
4544            .expect("replace the lease")
4545            .expect("open the replacement lease")
4546        };
4547        // The owner keeps a reference, as `LockGuard` does, so the handle
4548        // survives until the guard is released.
4549        let replacement = Arc::new(Mutex::new(Some(fresh)));
4550        register_lease_slot(guard.pump.slot, &path, &replacement);
4551
4552        let stale_at = restored.heartbeat_at_ms;
4553        let deadline = Instant::now() + Duration::from_secs(3);
4554        let mut advanced = false;
4555        while Instant::now() < deadline {
4556            thread::sleep(Duration::from_millis(
4557                test_config().heartbeat_interval_ms * 2,
4558            ));
4559            if read_lock_metadata(&path)
4560                .map(|meta| meta.heartbeat_at_ms > stale_at)
4561                .unwrap_or(false)
4562            {
4563                advanced = true;
4564                break;
4565            }
4566        }
4567        assert!(
4568            advanced,
4569            "the heartbeat did not refresh the lease through the replacement \
4570             handle: {:?}",
4571            read_lock_metadata(&path)
4572        );
4573        assert!(
4574            guard.verify_writer_epoch().expect("verify lease"),
4575            "writers must still verify their epoch after a replacement"
4576        );
4577    }
4578
4579    /// Body of the separate-process harness this module's tests spawn.
4580    #[test]
4581    fn fs_lock_separate_process_harness() {
4582        let Some(mode) = std::env::var_os("FS_LOCK_HARNESS_MODE") else {
4583            return;
4584        };
4585        let path = PathBuf::from(std::env::var_os("FS_LOCK_HARNESS_PATH").expect("harness path"));
4586        println!("mode:{mode:?} path={}", path.display());
4587        match mode.to_string_lossy().as_ref() {
4588            HARNESS_MODE_INSPECT => {
4589                println!(
4590                    "ready:{}",
4591                    serde_json::to_string(&observe_heartbeat(&path, 0)).unwrap()
4592                );
4593                io::stdout().flush().unwrap();
4594                for line in io::stdin().lock().lines() {
4595                    let step = line.unwrap().parse().expect("observation step");
4596                    println!(
4597                        "sample:{}",
4598                        serde_json::to_string(&observe_heartbeat(&path, step)).unwrap()
4599                    );
4600                    io::stdout().flush().unwrap();
4601                }
4602            }
4603            other => panic!("unknown harness mode {other}"),
4604        }
4605    }
4606
4607    /// A beat reads ownership through the descriptor the heartbeat keeps, not
4608    /// through the path. When another process reclaims the lease, the rename
4609    /// gives the path a new file while the kept descriptor still refers to the
4610    /// old, unlinked one. Reading through it would still see this owner's
4611    /// identity, so the beat would refresh the orphan and report success while
4612    /// the live lease went stale. The beat must instead see that the path is no
4613    /// longer the file it holds and stop.
4614    #[test]
4615    fn beat_stops_when_another_owner_replaces_the_lease_file() {
4616        let (_dir, path) = test_lock_path();
4617        let guard = acquire_with_config(&path, None, test_config()).expect("acquire");
4618        guard
4619            .heartbeat_once()
4620            .expect("beat through the kept descriptor");
4621
4622        // Another process's reclaim: it writes its own lease beside the file and
4623        // renames it over the path. It cannot see this process's open
4624        // descriptors, so the heartbeat keeps the old, now unlinked file.
4625        let mut foreign = current_process_metadata();
4626        foreign.pid = foreign.pid.wrapping_add(1);
4627        foreign.created_at_ms = now_ms().saturating_add(1_000);
4628        foreign.writer_epoch = format!("foreign-{}", now_ms());
4629        assert!(!lock_identity_matches(&foreign, &guard.metadata));
4630        let staging = path.with_extension("foreign");
4631        fs::write(
4632            &staging,
4633            lock_metadata_bytes(&foreign).expect("serialize foreign lease"),
4634        )
4635        .expect("write the foreign owner's lease");
4636        rename_over(&staging, &path).expect("foreign reclaim renames over the lease");
4637
4638        assert!(
4639            matches!(guard.heartbeat_once(), Err(HeartbeatError::NotOwner)),
4640            "a beat must not accept the orphaned descriptor it still holds"
4641        );
4642        assert_eq!(
4643            read_lock_metadata(&path).expect("read foreign lease"),
4644            foreign,
4645            "a beat must never write over the foreign owner's lease"
4646        );
4647    }
4648
4649    /// Replacing or removing another lease must not cost this lease its kept
4650    /// descriptor. Every replacement releases the handle it publishes for its
4651    /// own path; releasing every published handle instead would drop this one
4652    /// and the next beat would reopen the file, restoring the per-beat
4653    /// descriptor churn the kept handle exists to remove.
4654    #[test]
4655    fn unrelated_lease_churn_keeps_the_kept_descriptor() {
4656        let dir = tempfile::tempdir().expect("create temp dir");
4657        let mut guards = (0..2)
4658            .map(|index| {
4659                acquire_with_config(
4660                    &dir.path().join(format!("tenant-{index}.lease")),
4661                    Some(Duration::from_secs(2)),
4662                    test_config(),
4663                )
4664                .expect("acquire")
4665            })
4666            .collect::<Vec<_>>();
4667        let neighbour = dir.path().join("neighbour.lease");
4668
4669        for _ in 0..3 {
4670            // Another tenant is acquired, replaced and released while this
4671            // lease keeps its own descriptor.
4672            let churn = acquire_with_config(&neighbour, None, test_config()).expect("churn lease");
4673            let mut restored = churn.metadata.clone();
4674            restored.heartbeat_at_ms = now_ms().saturating_sub(1_000);
4675            let bytes = lock_metadata_bytes(&restored).expect("serialize");
4676            with_lease_handles_closed(&neighbour, || {
4677                replace_lock_bytes_unsynced(&neighbour, &bytes)
4678            })
4679            .expect("replace the neighbour");
4680            drop(churn);
4681            let _ = io_ledger::take();
4682        }
4683
4684        let _ = io_ledger::take();
4685        for guard in &guards {
4686            guard.heartbeat_once().expect("beat");
4687        }
4688        let cost = io_ledger::take();
4689        assert_beat_opens_no_descriptor(&cost);
4690        guards.clear();
4691    }
4692
4693    /// The identity check runs on every beat, so it must not open or close the
4694    /// lease a second time. Unix needs a stat for it; on Windows the path lookup
4695    /// takes one short-lived attribute handle, which this ledger only counts if
4696    /// it went through the heartbeat's own open. What it pins is that the beat
4697    /// neither reopens the lease for reading nor closes the descriptor it
4698    /// keeps.
4699    #[test]
4700    fn descriptor_identity_check_opens_no_descriptor() {
4701        let (_dir, path) = test_lock_path();
4702        let guard = acquire_with_config(&path, None, test_config()).expect("acquire");
4703        let _ = io_ledger::take();
4704        for _ in 0..3 {
4705            guard.heartbeat_once().expect("beat");
4706        }
4707        let ledger = io_ledger::take();
4708        assert_beat_opens_no_descriptor(&ledger);
4709    }
4710
4711    #[test]
4712    fn stopped_heartbeat_releases_handle_without_unlocking_or_touching_replacement() {
4713        let dir = tempfile::tempdir().expect("temp dir");
4714        let cache = dir.path().join("cache");
4715        fs::create_dir(&cache).expect("cache dir");
4716        let path = cache.join("writer.lease");
4717        let mut guard = acquire_with_config(&path, None, test_config()).expect("acquire lease");
4718        let _ = io_ledger::take();
4719
4720        guard.stop_heartbeat_for_removal();
4721        assert_eq!(io_ledger::take().closes, 1, "close the kept handle now");
4722        assert!(guard.heartbeat.is_none(), "join before closing the handle");
4723        assert!(guard.heartbeat_file.lock().unwrap().is_none());
4724        assert!(!guard
4725            .verify_writer_epoch()
4726            .expect("stopped guard is not writable"));
4727        assert!(matches!(
4728            guard.pump.heartbeat_once(),
4729            Err(HeartbeatError::NotPumped)
4730        ));
4731        assert!(matches!(
4732            try_acquire_once(&path),
4733            Err(AcquireError::Timeout)
4734        ));
4735        assert!(lock_identity_matches(
4736            &read_lock_metadata(&path).expect("lease remains until removal"),
4737            &guard.metadata
4738        ));
4739
4740        // Windows refuses this directory rename while the heartbeat handle is
4741        // open. Keep the lease on disk until the directory has moved so another
4742        // writer cannot enter the old cache during retirement.
4743        let retired = dir.path().join("retired");
4744        fs::rename(&cache, &retired).expect("retire with the lease guard still alive");
4745        fs::create_dir(&cache).expect("replacement cache");
4746        let replacement = acquire_with_config(&path, None, test_config()).expect("new owner");
4747        let canary = cache.join("canary");
4748        fs::write(&canary, b"replacement").expect("canary");
4749        drop(guard);
4750        assert!(replacement
4751            .verify_writer_epoch()
4752            .expect("replacement owns lease"));
4753        assert_eq!(
4754            fs::read(canary).expect("replacement preserved"),
4755            b"replacement"
4756        );
4757        fs::remove_dir_all(retired).expect("reap without a lingering lease handle");
4758    }
4759
4760    #[test]
4761    fn drop_stops_heartbeat_thread() {
4762        let (_dir, path) = test_lock_path();
4763        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
4764        drop(guard);
4765
4766        thread::sleep(Duration::from_millis(
4767            test_config().heartbeat_interval_ms * 3,
4768        ));
4769        assert!(
4770            !path.exists(),
4771            "heartbeat recreated or kept updating lockfile"
4772        );
4773    }
4774
4775    #[test]
4776    fn heartbeat_error_classification_terminal_vs_transient() {
4777        // Terminal: the lock is provably no longer ours to refresh.
4778        assert!(heartbeat_error_is_terminal(&HeartbeatError::LockGone));
4779        assert!(heartbeat_error_is_terminal(&HeartbeatError::NotOwner));
4780        // Transient: a temporary I/O hiccup or a read that raced a concurrent
4781        // writer. These must NOT kill the heartbeat — it retries instead.
4782        assert!(!heartbeat_error_is_terminal(&HeartbeatError::Io(
4783            io::Error::other("disk blip")
4784        )));
4785        let malformed: serde_json::Error =
4786            serde_json::from_str::<LockMetadata>("not json").unwrap_err();
4787        assert!(!heartbeat_error_is_terminal(&HeartbeatError::Malformed(
4788            malformed
4789        )));
4790    }
4791
4792    #[cfg(target_os = "linux")]
4793    #[test]
4794    fn released_lease_closes_all_descriptors_synchronously() {
4795        let (dir, path) = test_lock_path();
4796        let open_under_root = || {
4797            fs::read_dir("/proc/self/fd")
4798                .expect("descriptor census")
4799                .filter_map(Result::ok)
4800                .filter_map(|entry| fs::read_link(entry.path()).ok())
4801                .filter(|target| target.starts_with(dir.path()))
4802                .collect::<Vec<_>>()
4803        };
4804        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lease");
4805        let handle = Arc::downgrade(&guard.heartbeat_file);
4806        assert!(!open_under_root().is_empty(), "live lease keeps its handle");
4807        drop(guard);
4808        assert!(
4809            handle.upgrade().is_none(),
4810            "heartbeat must release its handle"
4811        );
4812        assert!(open_under_root().is_empty(), "no descriptors after release");
4813    }
4814
4815    #[test]
4816    fn malformed_beat_reopens_atomic_replacement_on_next_beat() {
4817        let (_dir, path) = test_lock_path();
4818        let guard = acquire_with_config(
4819            &path,
4820            None,
4821            LockConfig {
4822                heartbeat_interval_ms: 60_000,
4823                ..test_config()
4824            },
4825        )
4826        .expect("acquire lease");
4827        let live = fs::read(&path).expect("read lease");
4828        fs::write(&path, vec![b'x'; live.len()]).expect("corrupt lease");
4829
4830        assert!(matches!(
4831            guard.pump.heartbeat_once(),
4832            Err(HeartbeatError::Malformed(_))
4833        ));
4834        assert!(guard.heartbeat_file.lock().unwrap().is_none());
4835        assert!(guard.heartbeat_is_visible());
4836
4837        let mut restored = guard.metadata.clone();
4838        restored.heartbeat_at_ms = now_ms().saturating_sub(1_000_000);
4839        let replacement = path.with_extension("replacement");
4840        fs::write(&replacement, lock_metadata_bytes(&restored).unwrap()).unwrap();
4841        rename_over(&replacement, &path).expect("atomic recovery outside the lease registry");
4842        let _ = io_ledger::take();
4843        guard
4844            .pump
4845            .heartbeat_once()
4846            .expect("retry through live inode");
4847        let recovered = read_lock_metadata(&path).expect("independently read recovered lease");
4848        assert!(lock_identity_matches(&recovered, &guard.metadata));
4849        assert!(recovered.heartbeat_at_ms > restored.heartbeat_at_ms);
4850        let recovery = io_ledger::take();
4851        assert_eq!((recovery.opens, recovery.closes), (1, 0));
4852
4853        guard.pump.heartbeat_once().expect("healthy next beat");
4854        assert_beat_opens_no_descriptor(&io_ledger::take());
4855    }
4856
4857    #[test]
4858    fn valid_same_owner_replacement_refreshes_within_stale_bound() {
4859        let (_dir, path) = test_lock_path();
4860        let config = test_config();
4861        let guard = acquire_with_config(
4862            &path,
4863            None,
4864            LockConfig {
4865                heartbeat_interval_ms: 60_000,
4866                ..config
4867            },
4868        )
4869        .expect("acquire lease");
4870        let held_identity = LeaseFileIdentity::of_file(
4871            guard
4872                .heartbeat_file
4873                .lock()
4874                .unwrap()
4875                .as_mut()
4876                .unwrap()
4877                .file(),
4878        );
4879        let mut restored = guard.metadata.clone();
4880        restored.heartbeat_at_ms = now_ms().saturating_sub(1_000_000);
4881        let replacement = path.with_extension("replacement");
4882        fs::write(&replacement, lock_metadata_bytes(&restored).unwrap()).unwrap();
4883        // Do not release or re-index the kept handle: an atomic replacement by
4884        // another process cannot notify this process's lease registry either.
4885        rename_over(&replacement, &path).expect("replace valid same-owner lease");
4886        let live_identity = LeaseFileIdentity::of_path(&path).expect("replacement identity");
4887        assert_ne!(held_identity, Some(live_identity));
4888
4889        let _ = io_ledger::take();
4890        let started = Instant::now();
4891        let result = guard.pump.heartbeat_once();
4892        let elapsed = started.elapsed();
4893        let on_disk = read_lock_metadata(&path).expect("independent path read");
4894        let cost = io_ledger::take();
4895        eprintln!(
4896            "valid replacement beat: elapsed={elapsed:?} result={result:?} held={held_identity:?} live={live_identity:?} sentinel={} observed={} cost={cost:?}",
4897            restored.heartbeat_at_ms, on_disk.heartbeat_at_ms
4898        );
4899        assert!(
4900            elapsed < Duration::from_millis(config.stale_heartbeat_ms),
4901            "same-owner replacement delayed a beat beyond its stale bound: {elapsed:?}"
4902        );
4903        result.expect("refresh replacement through reopened handle");
4904        assert!(on_disk.heartbeat_at_ms > restored.heartbeat_at_ms);
4905        assert!(lock_identity_matches(&on_disk, &guard.metadata));
4906        assert_eq!((cost.opens, cost.closes), (1, 1));
4907        let reopened_identity = LeaseFileIdentity::of_file(
4908            guard
4909                .heartbeat_file
4910                .lock()
4911                .unwrap()
4912                .as_mut()
4913                .unwrap()
4914                .file(),
4915        );
4916        assert_eq!(reopened_identity, Some(live_identity));
4917        guard.pump.heartbeat_once().expect("healthy next beat");
4918        assert_beat_opens_no_descriptor(&io_ledger::take());
4919    }
4920
4921    #[test]
4922    fn heartbeat_survives_transient_malformed_and_recovers() {
4923        // Regression: a single transient failure (e.g. a read that races a
4924        // concurrent writer and sees a momentarily-unparseable file) used to
4925        // permanently kill the heartbeat thread. The guard holder would then
4926        // run its critical section with a stale heartbeat_at_ms, letting
4927        // another process reclaim the lock after the stale window — concurrent
4928        // writers / split-brain. The heartbeat must instead retry and resume
4929        // refreshing once the file is readable again.
4930        let (_dir, path) = test_lock_path();
4931        let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
4932        let owner = guard.metadata.clone();
4933
4934        // Corrupt the lockfile out from under the heartbeat (simulates a
4935        // concurrent-writer race producing a momentarily-unparseable read).
4936        // The heartbeat reads-then-writes, so it observes Malformed and, with
4937        // the fix, retries instead of dying. The corruption keeps the lease's
4938        // byte length: a length change takes the process-wide replacement path,
4939        // which releases the beat's kept handle and leaves the ownership check
4940        // to the next open, and this test is about retrying a read that failed.
4941        let live = fs::read(&path).expect("read live lease");
4942        fs::write(&path, vec![b'x'; live.len()]).expect("corrupt lockfile");
4943
4944        // Give the heartbeat several intervals to observe the malformed file.
4945        // Pre-fix, the thread is dead by now.
4946        thread::sleep(Duration::from_millis(
4947            test_config().heartbeat_interval_ms * 4,
4948        ));
4949
4950        // Restore the owner's own lease bytes with a clearly-stale heartbeat
4951        // timestamp. The replacement bytes keep the lease's byte length, so the
4952        // next beat takes its in-place path. The restore's timestamp only has to
4953        // be older than the beat that follows, so a value from before the
4954        // corruption is enough.
4955        let mut restored = owner.clone();
4956        restored.heartbeat_at_ms = now_ms().saturating_sub(1_000_000);
4957        let sentinel = restored.heartbeat_at_ms;
4958        // Use an atomic replacement to exercise reopening the lease, rather
4959        // than only rewriting the inode that the heartbeat previously held.
4960        {
4961            let bytes = lock_metadata_bytes(&restored).expect("serialize restored metadata");
4962            with_lease_handles_closed(&path, || replace_lock_bytes_unsynced(&path, &bytes))
4963                .expect("restore lock metadata");
4964        }
4965
4966        // If the heartbeat thread is still alive (the fix), it will overwrite
4967        // heartbeat_at_ms with a current value. Poll for that recovery. The
4968        // window covers the beat that finds the restored lease but is still
4969        // failing on the earlier corrupt state, plus several retries after it.
4970        let deadline = std::time::Instant::now() + Duration::from_secs(5);
4971        let mut recovered = false;
4972        while std::time::Instant::now() < deadline {
4973            thread::sleep(Duration::from_millis(25));
4974            match read_lock_metadata(&path) {
4975                Ok(meta)
4976                    if meta.created_at_ms == owner.created_at_ms
4977                        && meta.heartbeat_at_ms > sentinel =>
4978                {
4979                    recovered = true;
4980                    break;
4981                }
4982                _ => continue,
4983            }
4984        }
4985        assert!(
4986            recovered,
4987            "heartbeat did not recover after a transient malformed read — thread likely died: \
4988             stopped={} visible={} on_disk={:?}",
4989            guard.pump.heartbeat_stopped(),
4990            guard.heartbeat_is_visible(),
4991            read_lock_metadata(&path)
4992        );
4993        drop(guard);
4994    }
4995}