Skip to main content

gtars_refget/store/
lock.rs

1//! Exclusive writer lock for a store directory.
2//!
3//! # Why a lockfile and not `flock`
4//!
5//! These stores live on Lustre and NFS on a shared HPC filesystem. `flock(2)` on
6//! Lustre only works cluster-wide when the filesystem is mounted with the `flock`
7//! option; mounted with `localflock` it silently degrades to node-local locking,
8//! and mounted with neither it can fail with `ENOLCK`. Node-local locking that
9//! *looks* like it works is a worse failure mode than no lock at all, because it
10//! is invisible — two SLURM jobs on two nodes would both believe they hold it.
11//!
12//! `O_CREAT|O_EXCL` file creation is atomic on NFSv3 (guarded CREATE), NFSv4,
13//! Lustre, and Windows, needs no mount options, and matches the precedent already
14//! in this crate (`transcripts::builder::BuildLock`). So: a lockfile.
15//!
16//! # Scope
17//!
18//! WRITERS ONLY. Readers never acquire this — reads must never block on a shared
19//! filesystem, and after atomic publish (see [`super::atomic`]) a reader always
20//! observes a complete file. The lock guards a *commit*, not a handle: it is held
21//! for the seconds it takes to merge and publish the indexes, not for the hours a
22//! FASTA import takes.
23//!
24//! # Staleness
25//!
26//! A holder can die without releasing (SIGKILL, node failure, OOM). PID checks are
27//! meaningless across nodes, so liveness is decided in two tiers:
28//!
29//! - **Definitive:** the payload's `hostname` equals ours and `/proc/<pid>` does
30//!   not exist. That process is gone; break immediately.
31//! - **Presumed:** the payload's `heartbeat_at` AND the file's mtime are both
32//!   older than `stale_after` (default 120s = 8 missed heartbeats). Break, but
33//!   warn loudly naming host, pid, and age.
34//!
35//! Breaking is itself serialized. Contenders do NOT `remove_file` then re-create
36//! (two of them would both observe staleness, both unlink, both create, both
37//! proceed). Nor is a bare `rename(2)` of the lock enough: rename acts on the
38//! current pathname, not the inode a contender inspected, so if A steals and
39//! re-acquires before B's rename runs, B renames A's fresh lock away and both
40//! proceed. Instead a contender first claims `.rgstore.lock.break` with
41//! `O_EXCL`; only the claimant re-reads the lock, confirms it is still the very
42//! instance it judged stale (pid, host, `started_at`), and renames it to
43//! `.rgstore.lock.stale.<pid>.<nanos>`. Everyone else retries acquisition. A
44//! break marker whose claimant died is itself stolen once its mtime passes
45//! `BREAK_STALE_AFTER`.
46
47use std::fs::{self, OpenOptions};
48use std::io::Write;
49use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::thread::JoinHandle;
53use std::time::{Duration, SystemTime, UNIX_EPOCH};
54
55use anyhow::{Context, Result, anyhow};
56use serde::{Deserialize, Serialize};
57
58use super::atomic::atomic_write_bytes;
59
60/// Name of the lockfile inside a store directory.
61pub const LOCK_FILENAME: &str = ".rgstore.lock";
62
63/// Prefix of a stolen (stale) lockfile awaiting cleanup.
64pub const STALE_LOCK_PREFIX: &str = ".rgstore.lock.stale.";
65
66/// Marker claimed (`O_EXCL`) by the one contender allowed to break a stale lock.
67pub const BREAK_FILENAME: &str = ".rgstore.lock.break";
68
69/// A break marker older than this belongs to a claimant that died mid-break and
70/// may be taken over. Breaking is a handful of syscalls, so this is generous.
71const BREAK_STALE_AFTER: Duration = Duration::from_secs(60);
72
73/// How often the heartbeat thread refreshes the payload.
74const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(15);
75
76/// Granularity at which the heartbeat thread checks whether it should stop, so
77/// releasing the lock does not wait a full heartbeat interval.
78const HEARTBEAT_TICK: Duration = Duration::from_millis(100);
79
80const DEFAULT_TIMEOUT_SECS: u64 = 30 * 60;
81const DEFAULT_STALE_AFTER_SECS: u64 = 120;
82
83const BACKOFF_START: Duration = Duration::from_millis(50);
84const BACKOFF_MAX: Duration = Duration::from_secs(5);
85
86/// The JSON payload written into the lockfile.
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct LockInfo {
89    pub pid: u32,
90    pub hostname: String,
91    /// RFC 3339 timestamp of acquisition.
92    pub started_at: String,
93    /// RFC 3339 timestamp of the last heartbeat refresh.
94    pub heartbeat_at: String,
95    /// Unix epoch seconds of the last heartbeat, for age arithmetic that does
96    /// not depend on parsing RFC 3339.
97    pub heartbeat_epoch: u64,
98    /// What the holder is doing, e.g. `"write_index_files"`. Shown in errors.
99    pub operation: String,
100    pub gtars_version: String,
101}
102
103impl LockInfo {
104    fn new(operation: &str) -> Self {
105        let now = chrono::Utc::now().to_rfc3339();
106        LockInfo {
107            pid: std::process::id(),
108            hostname: hostname(),
109            started_at: now.clone(),
110            heartbeat_at: now,
111            heartbeat_epoch: epoch_secs(),
112            operation: operation.to_string(),
113            gtars_version: env!("CARGO_PKG_VERSION").to_string(),
114        }
115    }
116
117    /// Human-readable holder description for error messages.
118    pub fn describe(&self) -> String {
119        format!(
120            "pid {} on {} (operation={}, gtars {}, since {})",
121            self.pid, self.hostname, self.operation, self.gtars_version, self.started_at
122        )
123    }
124}
125
126/// Tunables for lock acquisition.
127///
128/// Defaults come from the environment when set:
129/// `GTARS_STORE_LOCK_TIMEOUT` and `GTARS_STORE_LOCK_STALE_AFTER`, both in
130/// seconds. A timeout of 0 means "wait forever".
131#[derive(Debug, Clone)]
132pub struct LockOptions {
133    /// How long to block waiting for the lock before erroring. `None` = forever.
134    pub timeout: Option<Duration>,
135    /// How old a heartbeat must be before the lock is presumed stale.
136    pub stale_after: Duration,
137    /// Break any existing lock immediately, without waiting. Operator escape
138    /// hatch (`--force-unlock`); do not set this by default.
139    pub force: bool,
140}
141
142impl Default for LockOptions {
143    fn default() -> Self {
144        LockOptions {
145            timeout: env_secs("GTARS_STORE_LOCK_TIMEOUT")
146                .unwrap_or(Some(Duration::from_secs(DEFAULT_TIMEOUT_SECS))),
147            stale_after: env_secs("GTARS_STORE_LOCK_STALE_AFTER")
148                .flatten()
149                .unwrap_or(Duration::from_secs(DEFAULT_STALE_AFTER_SECS)),
150            force: false,
151        }
152    }
153}
154
155impl LockOptions {
156    /// Never block: fail immediately if the lock is held by a live writer.
157    pub fn non_blocking() -> Self {
158        LockOptions {
159            timeout: Some(Duration::ZERO),
160            ..Default::default()
161        }
162    }
163
164    #[must_use]
165    pub fn timeout_secs(mut self, secs: u64) -> Self {
166        self.timeout = if secs == 0 {
167            None
168        } else {
169            Some(Duration::from_secs(secs))
170        };
171        self
172    }
173
174    #[must_use]
175    pub fn force(mut self, force: bool) -> Self {
176        self.force = force;
177        self
178    }
179}
180
181/// An acquired exclusive writer lock. Released on drop.
182pub struct StoreLock {
183    path: PathBuf,
184    info: LockInfo,
185    stop: Arc<AtomicBool>,
186    heartbeat: Option<JoinHandle<()>>,
187}
188
189impl std::fmt::Debug for StoreLock {
190    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191        f.debug_struct("StoreLock")
192            .field("path", &self.path)
193            .field("pid", &self.info.pid)
194            .field("operation", &self.info.operation)
195            .finish()
196    }
197}
198
199impl StoreLock {
200    /// Path of the lockfile for a store directory.
201    pub fn lock_path(store_dir: &Path) -> PathBuf {
202        store_dir.join(LOCK_FILENAME)
203    }
204
205    /// Acquire the exclusive writer lock, blocking with bounded exponential
206    /// backoff up to `opts.timeout`.
207    pub fn acquire(store_dir: &Path, operation: &str, opts: LockOptions) -> Result<Self> {
208        let path = Self::lock_path(store_dir);
209        fs::create_dir_all(store_dir)
210            .with_context(|| format!("creating store directory {:?} for locking", store_dir))?;
211
212        if opts.force {
213            steal(&path)?;
214        }
215
216        let deadline = opts.timeout.map(|t| SystemTime::now() + t);
217        let mut backoff = BACKOFF_START;
218
219        loop {
220            match try_create(&path, operation) {
221                Ok(Some(info)) => {
222                    let stop = Arc::new(AtomicBool::new(false));
223                    let heartbeat = spawn_heartbeat(path.clone(), info.clone(), stop.clone());
224                    return Ok(StoreLock {
225                        path,
226                        info,
227                        stop,
228                        heartbeat: Some(heartbeat),
229                    });
230                }
231                Ok(None) => {} // someone holds it; fall through to evaluate
232                Err(e) => return Err(e),
233            }
234
235            // Held. Decide whether the holder is alive.
236            match read_info(&path) {
237                Ok(Some(holder)) => {
238                    if let Some(reason) = staleness(&path, &holder, opts.stale_after) {
239                        eprintln!(
240                            "warning: breaking stale RefgetStore lock {:?}: {} ({})",
241                            path,
242                            holder.describe(),
243                            reason
244                        );
245                        // Serialized through the break marker; whoever does
246                        // not get it just retries and finds the lock gone.
247                        let _ = break_stale(&path, &holder);
248                        continue;
249                    }
250                    if deadline.is_some_and(|d| SystemTime::now() >= d) {
251                        return Err(anyhow!(
252                            "timed out waiting for the RefgetStore write lock at {:?}, \
253                             held by {}. If that writer is gone, clear it with \
254                             `gtars refget lock-status <store> --force-unlock`, or raise \
255                             GTARS_STORE_LOCK_TIMEOUT.",
256                            path,
257                            holder.describe()
258                        ));
259                    }
260                }
261                // Unreadable/corrupt payload, or the holder released between our
262                // create and our read. Treat an unparseable lock as stale only
263                // after `stale_after`, using mtime alone.
264                Ok(None) | Err(_) => {
265                    if mtime_age(&path).is_none_or(|age| age > opts.stale_after) {
266                        eprintln!(
267                            "warning: breaking unreadable RefgetStore lock {:?} (no valid payload)",
268                            path
269                        );
270                        let _ = break_unreadable(&path, opts.stale_after);
271                        continue;
272                    }
273                    if deadline.is_some_and(|d| SystemTime::now() >= d) {
274                        return Err(anyhow!(
275                            "timed out waiting for the RefgetStore write lock at {:?} \
276                             (lockfile payload unreadable)",
277                            path
278                        ));
279                    }
280                }
281            }
282
283            std::thread::sleep(backoff);
284            backoff = std::cmp::min(backoff * 2, BACKOFF_MAX);
285        }
286    }
287
288    /// Try to acquire without blocking. Returns `Ok(None)` if held by a live writer.
289    pub fn try_acquire(store_dir: &Path, operation: &str) -> Result<Option<Self>> {
290        match Self::acquire(store_dir, operation, LockOptions::non_blocking()) {
291            Ok(lock) => Ok(Some(lock)),
292            Err(_) => Ok(None),
293        }
294    }
295
296    /// The payload this process wrote.
297    pub fn info(&self) -> &LockInfo {
298        &self.info
299    }
300}
301
302impl Drop for StoreLock {
303    fn drop(&mut self) {
304        self.stop.store(true, Ordering::Relaxed);
305        if let Some(handle) = self.heartbeat.take() {
306            let _ = handle.join();
307        }
308        // Only remove the lockfile if it is still OURS. If another process broke
309        // it as stale and re-acquired, the file now belongs to them and unlinking
310        // it would hand the store to a third writer.
311        if let Ok(Some(current)) = read_info(&self.path) {
312            if current.pid != self.info.pid || current.hostname != self.info.hostname {
313                return;
314            }
315        }
316        let _ = fs::remove_file(&self.path);
317    }
318}
319
320// =========================================================================
321// Free functions (operator entry points)
322// =========================================================================
323
324/// Report the current holder of a store's write lock, if any.
325pub fn lock_status(store_dir: &Path) -> Result<Option<LockInfo>> {
326    read_info(&StoreLock::lock_path(store_dir))
327}
328
329/// Forcibly clear a store's write lock. Operator escape hatch: use only when the
330/// holder is known to be gone. Also sweeps `.rgstore.lock.stale.*` leftovers.
331pub fn force_unlock(store_dir: &Path) -> Result<bool> {
332    let path = StoreLock::lock_path(store_dir);
333    let existed = path.exists();
334    if existed {
335        steal(&path)?;
336    }
337    // Sweep any stolen-lock leftovers (and a dead break marker) from earlier breaks.
338    if let Ok(entries) = fs::read_dir(store_dir) {
339        for entry in entries.filter_map(|e| e.ok()) {
340            if entry
341                .file_name()
342                .to_str()
343                .is_some_and(|n| n.starts_with(STALE_LOCK_PREFIX) || n == BREAK_FILENAME)
344            {
345                let _ = fs::remove_file(entry.path());
346            }
347        }
348    }
349    Ok(existed)
350}
351
352// =========================================================================
353// Internals
354// =========================================================================
355
356/// Attempt an `O_CREAT|O_EXCL` create. `Ok(None)` means someone else holds it.
357fn try_create(path: &Path, operation: &str) -> Result<Option<LockInfo>> {
358    match OpenOptions::new().write(true).create_new(true).open(path) {
359        Ok(mut file) => {
360            let info = LockInfo::new(operation);
361            let json = serde_json::to_vec_pretty(&info)?;
362            // Write the payload directly into the exclusively-created file. It
363            // must NOT be published by rename here: the rename would clobber a
364            // lock another contender legitimately holds.
365            file.write_all(&json)?;
366            file.sync_all()?;
367            Ok(Some(info))
368        }
369        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(None),
370        Err(e) => Err(e).with_context(|| format!("creating lockfile {:?}", path)),
371    }
372}
373
374fn read_info(path: &Path) -> Result<Option<LockInfo>> {
375    match fs::read_to_string(path) {
376        Ok(s) => Ok(serde_json::from_str(&s).ok()),
377        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
378        Err(e) => Err(e).with_context(|| format!("reading lockfile {:?}", path)),
379    }
380}
381
382/// Take a held lock away by rename.
383///
384/// Callers breaking a STALE lock must hold the break claim (see
385/// [`break_stale`]); the rename alone is not race-safe, because it acts on
386/// whatever currently sits at `path`. Do NOT replace this with `remove_file` +
387/// `create_new` either: that lets two contenders both unlink, both create, and
388/// both proceed. The unguarded callers are the operator escape hatches
389/// (`--force-unlock`), which by definition assert no live holder exists.
390fn steal(path: &Path) -> Result<()> {
391    let dir = path.parent().unwrap_or_else(|| Path::new("."));
392    let stolen = dir.join(format!(
393        "{}{}.{}",
394        STALE_LOCK_PREFIX,
395        std::process::id(),
396        nanos()
397    ));
398    match fs::rename(path, &stolen) {
399        Ok(()) => {
400            let _ = fs::remove_file(&stolen);
401            Ok(())
402        }
403        // Lost the steal race, or the holder released first. Either way the lock
404        // is no longer the file we saw; the caller retries.
405        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
406        Err(e) => Err(e).with_context(|| format!("stealing stale lockfile {:?}", path)),
407    }
408}
409
410/// Exclusive right to break the lock at `path`. Removes the marker on drop.
411struct BreakClaim(PathBuf);
412
413impl Drop for BreakClaim {
414    fn drop(&mut self) {
415        let _ = fs::remove_file(&self.0);
416    }
417}
418
419/// Claim the break marker next to `path`. `Ok(None)` means another contender
420/// holds it (and is, or was, breaking the lock): back off and retry acquisition.
421///
422/// A marker left by a claimant that died is taken over by rename, which again
423/// succeeds for exactly one contender; that one then claims afresh.
424fn claim_break(path: &Path) -> Result<Option<BreakClaim>> {
425    let dir = path.parent().unwrap_or_else(|| Path::new("."));
426    let marker = dir.join(BREAK_FILENAME);
427    match OpenOptions::new().write(true).create_new(true).open(&marker) {
428        Ok(mut f) => {
429            let _ = write!(f, "{} {}", std::process::id(), hostname());
430            Ok(Some(BreakClaim(marker)))
431        }
432        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
433            if mtime_age(&marker).is_some_and(|age| age > BREAK_STALE_AFTER) {
434                let dead = dir.join(format!("{}break.{}.{}", STALE_LOCK_PREFIX, std::process::id(), nanos()));
435                if fs::rename(&marker, &dead).is_ok() {
436                    let _ = fs::remove_file(&dead);
437                }
438            }
439            Ok(None)
440        }
441        Err(e) => Err(e).with_context(|| format!("creating break marker {:?}", marker)),
442    }
443}
444
445/// Break the lock at `path`, but only if it is still the exact instance judged
446/// stale. Under the claim nobody else steals, so the only way the lock can be a
447/// different instance is that the stale holder released and a live writer
448/// acquired in between; in that case leave it alone.
449fn break_stale(path: &Path, judged: &LockInfo) -> Result<()> {
450    let Some(_claim) = claim_break(path)? else {
451        return Ok(());
452    };
453    match read_info(path)? {
454        Some(current)
455            if current.pid == judged.pid
456                && current.hostname == judged.hostname
457                && current.started_at == judged.started_at =>
458        {
459            steal(path)
460        }
461        // Gone, or already a different holder. Nothing to break.
462        _ => Ok(()),
463    }
464}
465
466/// Break a lock with no readable payload, re-checking its age under the claim so
467/// a marker holder never removes a lock that was rewritten in the meantime.
468fn break_unreadable(path: &Path, stale_after: Duration) -> Result<()> {
469    let Some(_claim) = claim_break(path)? else {
470        return Ok(());
471    };
472    match read_info(path)? {
473        Some(_) => Ok(()), // readable now: a live writer owns it
474        None => {
475            if mtime_age(path).is_none_or(|age| age > stale_after) {
476                steal(path)
477            } else {
478                Ok(())
479            }
480        }
481    }
482}
483
484/// Returns `Some(reason)` if the lock should be considered stale.
485fn staleness(path: &Path, holder: &LockInfo, stale_after: Duration) -> Option<String> {
486    // Tier 1 (definitive): same host, dead pid.
487    if holder.hostname == hostname() && !pid_alive(holder.pid) {
488        return Some(format!("pid {} is not running on this host", holder.pid));
489    }
490
491    // Tier 2 (presumed): heartbeat AND mtime both older than the threshold. Both
492    // are required — a clock skew between nodes could make one alone lie.
493    let now = epoch_secs();
494    let heartbeat_age = Duration::from_secs(now.saturating_sub(holder.heartbeat_epoch));
495    let file_age = mtime_age(path)?;
496    if heartbeat_age > stale_after && file_age > stale_after {
497        return Some(format!(
498            "no heartbeat for {}s (threshold {}s)",
499            heartbeat_age.as_secs(),
500            stale_after.as_secs()
501        ));
502    }
503    None
504}
505
506/// `None` if the file is gone or its mtime is unreadable.
507fn mtime_age(path: &Path) -> Option<Duration> {
508    let modified = fs::metadata(path).ok()?.modified().ok()?;
509    SystemTime::now().duration_since(modified).ok()
510}
511
512#[cfg(target_os = "linux")]
513fn pid_alive(pid: u32) -> bool {
514    Path::new(&format!("/proc/{}", pid)).exists()
515}
516
517/// Without `/proc` we cannot cheaply prove a pid is dead, so never claim tier-1
518/// staleness; the heartbeat path still handles genuinely dead holders.
519#[cfg(not(target_os = "linux"))]
520fn pid_alive(_pid: u32) -> bool {
521    true
522}
523
524fn hostname() -> String {
525    for path in ["/proc/sys/kernel/hostname", "/etc/hostname"] {
526        if let Ok(s) = fs::read_to_string(path) {
527            let s = s.trim();
528            if !s.is_empty() {
529                return s.to_string();
530            }
531        }
532    }
533    for var in ["HOSTNAME", "COMPUTERNAME"] {
534        if let Ok(s) = std::env::var(var) {
535            if !s.is_empty() {
536                return s;
537            }
538        }
539    }
540    "unknown-host".to_string()
541}
542
543fn epoch_secs() -> u64 {
544    SystemTime::now()
545        .duration_since(UNIX_EPOCH)
546        .map(|d| d.as_secs())
547        .unwrap_or(0)
548}
549
550fn nanos() -> u128 {
551    SystemTime::now()
552        .duration_since(UNIX_EPOCH)
553        .map(|d| d.as_nanos())
554        .unwrap_or(0)
555}
556
557/// Parse a duration (seconds) from an env var. Outer `None` = unset, inner
558/// `None` = explicitly "wait forever" (`0`).
559fn env_secs(var: &str) -> Option<Option<Duration>> {
560    let raw = std::env::var(var).ok()?;
561    let secs: u64 = raw.trim().parse().ok()?;
562    Some(if secs == 0 {
563        None
564    } else {
565        Some(Duration::from_secs(secs))
566    })
567}
568
569/// Refresh `heartbeat_at` every [`HEARTBEAT_INTERVAL`] so other writers can tell
570/// a live holder from a dead one. The refresh is an atomic publish, so a reader
571/// never sees a half-written payload — but it is skipped if the file has stopped
572/// being ours (another writer broke the lock), to avoid clobbering them.
573fn spawn_heartbeat(path: PathBuf, info: LockInfo, stop: Arc<AtomicBool>) -> JoinHandle<()> {
574    std::thread::spawn(move || {
575        let mut elapsed = Duration::ZERO;
576        while !stop.load(Ordering::Relaxed) {
577            std::thread::sleep(HEARTBEAT_TICK);
578            elapsed += HEARTBEAT_TICK;
579            if elapsed < HEARTBEAT_INTERVAL {
580                continue;
581            }
582            elapsed = Duration::ZERO;
583
584            match read_info(&path) {
585                Ok(Some(current))
586                    if current.pid == info.pid && current.hostname == info.hostname => {}
587                // Gone or taken over: stop refreshing rather than fight for it.
588                _ => return,
589            }
590
591            let mut refreshed = info.clone();
592            refreshed.heartbeat_at = chrono::Utc::now().to_rfc3339();
593            refreshed.heartbeat_epoch = epoch_secs();
594            if let Ok(json) = serde_json::to_vec_pretty(&refreshed) {
595                let _ = atomic_write_bytes(&path, &json);
596            }
597        }
598    })
599}
600
601#[cfg(test)]
602mod tests {
603    use super::*;
604
605    #[test]
606    fn acquire_and_release() {
607        let dir = tempfile::tempdir().unwrap();
608        let path = StoreLock::lock_path(dir.path());
609        {
610            let lock = StoreLock::acquire(dir.path(), "test", LockOptions::default()).unwrap();
611            assert!(path.exists());
612            assert_eq!(lock.info().operation, "test");
613            assert!(lock_status(dir.path()).unwrap().is_some());
614        }
615        assert!(!path.exists());
616        assert!(lock_status(dir.path()).unwrap().is_none());
617    }
618
619    #[test]
620    fn second_acquire_times_out_while_first_is_held() {
621        let dir = tempfile::tempdir().unwrap();
622        let _held = StoreLock::acquire(dir.path(), "first", LockOptions::default()).unwrap();
623
624        let err = StoreLock::acquire(
625            dir.path(),
626            "second",
627            LockOptions::default().timeout_secs(1),
628        );
629        assert!(err.is_err());
630        let msg = err.unwrap_err().to_string();
631        assert!(msg.contains("timed out"), "unexpected error: {}", msg);
632        assert!(msg.contains("first"), "error should name the holder: {}", msg);
633    }
634
635    #[test]
636    fn stale_lock_from_dead_pid_on_this_host_is_broken() {
637        let dir = tempfile::tempdir().unwrap();
638        let path = StoreLock::lock_path(dir.path());
639
640        // A pid that cannot be running: max_pid+1 is not allocatable.
641        let dead_pid = 4_194_305u32;
642        let mut info = LockInfo::new("abandoned");
643        info.pid = dead_pid;
644        info.hostname = hostname();
645        fs::write(&path, serde_json::to_vec_pretty(&info).unwrap()).unwrap();
646
647        // Even with a fresh heartbeat, tier-1 liveness breaks it immediately.
648        let lock = StoreLock::acquire(dir.path(), "recovering", LockOptions::default()).unwrap();
649        assert_eq!(lock.info().pid, std::process::id());
650    }
651
652    #[test]
653    fn old_heartbeat_from_another_host_is_presumed_stale() {
654        let dir = tempfile::tempdir().unwrap();
655        let path = StoreLock::lock_path(dir.path());
656
657        let mut info = LockInfo::new("remote");
658        info.hostname = "some-other-node".to_string();
659        info.heartbeat_epoch = epoch_secs().saturating_sub(10_000);
660        fs::write(&path, serde_json::to_vec_pretty(&info).unwrap()).unwrap();
661        // Backdate the file so the mtime half of the test also passes.
662        let backdated = SystemTime::now() - Duration::from_secs(10_000);
663        let f = fs::File::open(&path).unwrap();
664        f.set_modified(backdated).unwrap();
665        drop(f);
666
667        let opts = LockOptions {
668            stale_after: Duration::from_secs(120),
669            ..LockOptions::default()
670        };
671        let lock = StoreLock::acquire(dir.path(), "taking-over", opts).unwrap();
672        assert_eq!(lock.info().hostname, hostname());
673    }
674
675    #[test]
676    fn live_remote_holder_is_not_broken() {
677        let dir = tempfile::tempdir().unwrap();
678        let path = StoreLock::lock_path(dir.path());
679
680        let mut info = LockInfo::new("remote");
681        info.hostname = "some-other-node".to_string();
682        fs::write(&path, serde_json::to_vec_pretty(&info).unwrap()).unwrap();
683
684        let result = StoreLock::acquire(
685            dir.path(),
686            "contender",
687            LockOptions::default().timeout_secs(1),
688        );
689        assert!(result.is_err(), "a live remote holder must not be broken");
690    }
691
692    #[test]
693    fn force_unlock_clears_a_held_lock() {
694        let dir = tempfile::tempdir().unwrap();
695        let mut info = LockInfo::new("remote");
696        info.hostname = "some-other-node".to_string();
697        fs::write(
698            StoreLock::lock_path(dir.path()),
699            serde_json::to_vec_pretty(&info).unwrap(),
700        )
701        .unwrap();
702
703        assert!(force_unlock(dir.path()).unwrap());
704        assert!(lock_status(dir.path()).unwrap().is_none());
705        // Idempotent.
706        assert!(!force_unlock(dir.path()).unwrap());
707    }
708
709    #[test]
710    fn drop_does_not_remove_a_lock_another_writer_took_over() {
711        let dir = tempfile::tempdir().unwrap();
712        let path = StoreLock::lock_path(dir.path());
713        let lock = StoreLock::acquire(dir.path(), "original", LockOptions::default()).unwrap();
714
715        // Simulate a takeover: someone broke our lock and wrote their own.
716        let mut other = LockInfo::new("takeover");
717        other.pid = lock.info().pid + 1;
718        fs::write(&path, serde_json::to_vec_pretty(&other).unwrap()).unwrap();
719
720        drop(lock);
721        let remaining = lock_status(dir.path()).unwrap().expect("lock was clobbered");
722        assert_eq!(remaining.operation, "takeover");
723    }
724}