use std::collections::HashMap;
use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::{
atomic::{AtomicBool, AtomicU64, Ordering},
mpsc, Arc, Mutex, OnceLock, Weak,
};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use crate::{slog_debug, slog_error, slog_info, slog_warn};
#[derive(Debug)]
pub struct AdvisoryLockGuard(File);
impl AdvisoryLockGuard {
pub fn from_locked_file(file: File) -> Self {
Self(file)
}
}
impl Drop for AdvisoryLockGuard {
fn drop(&mut self) {
let _ = self.0.unlock();
}
}
pub const HEARTBEAT_INTERVAL_MS: u64 = 5_000;
pub const HEARTBEAT_REFRESH_INTERVAL_MS: u64 = 25_000;
pub const STALE_HEARTBEAT_MS: u64 = 15_000;
pub const LIVE_OWNER_WARN_MS: u64 = 600_000;
pub const POLL_INTERVAL_MS: u64 = 100;
const MAX_TRANSIENT_CREATE_RETRIES: u32 = 50;
const RECLAIM_TOKEN_MALFORMED_STALE_AGE: Duration = Duration::from_secs(60);
const RECLAIM_BLOCK_LOG_INTERVAL: Duration = Duration::from_secs(60);
const DEAD_RECLAIM_INITIAL_BACKOFF_MS: u64 = 250;
const DEAD_RECLAIM_MAX_BACKOFF_MS: u64 = 5_000;
static NEXT_LEASE_SLOT: AtomicU64 = AtomicU64::new(0);
static LEASE_FILES: OnceLock<Mutex<HashMap<usize, LeaseSlot>>> = OnceLock::new();
static LEASE_SLOT_BY_PATH: OnceLock<Mutex<HashMap<PathBuf, usize>>> = OnceLock::new();
#[derive(Clone)]
struct LeaseSlot {
handle: Weak<Mutex<Option<LeaseFile>>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReclaimTokenState {
Alive,
DeadForeignHost,
Malformed,
Dead,
}
impl ReclaimTokenState {
fn as_str(self) -> &'static str {
match self {
Self::Alive => "alive",
Self::DeadForeignHost => "dead-foreign-host",
Self::Malformed => "malformed",
Self::Dead => "dead",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct ReclaimTokenHeld {
pid: Option<u32>,
state: ReclaimTokenState,
}
#[derive(Debug)]
enum ReclaimResult {
Removed,
Blocked(ReclaimTokenHeld),
Unchanged,
}
#[derive(Clone, Debug)]
struct ReclaimBlockLogRecord {
last_emitted: Instant,
suppressed: u64,
}
#[derive(Clone, Debug, Default)]
struct LiveOwnerLogRecord {
stale_logged: bool,
long_held_logged: bool,
}
struct LiveOwnerLog {
record: LiveOwnerLogRecord,
}
impl LiveOwnerLog {
fn new() -> Self {
Self {
record: LiveOwnerLogRecord::default(),
}
}
fn first_stale(&mut self) -> bool {
!std::mem::replace(&mut self.record.stale_logged, true)
}
fn first_long_held(&mut self) -> bool {
!std::mem::replace(&mut self.record.long_held_logged, true)
}
}
static RECLAIM_BLOCK_LOGS: OnceLock<Mutex<HashMap<PathBuf, ReclaimBlockLogRecord>>> =
OnceLock::new();
fn is_transient_create_contention(error: &io::Error) -> bool {
if error.kind() == io::ErrorKind::PermissionDenied {
return true;
}
#[cfg(windows)]
{
if let Some(code) = error.raw_os_error() {
if code == 32 || code == 5 {
return true;
}
}
}
false
}
#[derive(Clone, Copy, Debug)]
struct LockConfig {
heartbeat_interval_ms: u64,
heartbeat_refresh_interval_ms: u64,
stale_heartbeat_ms: u64,
live_owner_warn_ms: u64,
poll_interval_ms: u64,
}
impl LockConfig {
fn cross_host_stale_heartbeat_ms(self) -> u64 {
self.stale_heartbeat_ms.saturating_mul(5)
}
fn live_owner_warning_age_ms(self) -> u64 {
self.stale_heartbeat_ms.max(
self.heartbeat_refresh_interval_ms
.saturating_add(self.heartbeat_interval_ms),
)
}
}
impl Default for LockConfig {
fn default() -> Self {
Self {
heartbeat_interval_ms: HEARTBEAT_INTERVAL_MS,
heartbeat_refresh_interval_ms: HEARTBEAT_REFRESH_INTERVAL_MS,
stale_heartbeat_ms: STALE_HEARTBEAT_MS,
live_owner_warn_ms: LIVE_OWNER_WARN_MS,
poll_interval_ms: POLL_INTERVAL_MS,
}
}
}
#[rustfmt::skip]
test_support_visibility! {
#[derive(Clone, Debug, PartialEq, Eq)]
struct ProcessIdentity {
#[cfg(any(test, feature = "test-support"))]
pub start_time: u64,
#[cfg(not(any(test, feature = "test-support")))]
start_time: u64,
boot_id: Option<String>,
#[cfg(any(test, feature = "test-support"))]
pub exited: bool,
#[cfg(not(any(test, feature = "test-support")))]
exited: bool,
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
struct LockMetadata {
pid: u32,
hostname: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
process_start_time: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
boot_id: Option<String>,
created_at_ms: u64,
heartbeat_at_ms: u64,
#[serde(default)]
writer_epoch: String,
}
pub fn acquire(path: &Path) -> Result<LockGuard, AcquireError> {
acquire_with_config(path, None, LockConfig::default())
}
pub fn try_acquire(path: &Path, timeout: Duration) -> Result<LockGuard, AcquireError> {
acquire_with_config(path, Some(timeout), LockConfig::default())
}
pub fn try_acquire_until(path: &Path, deadline: Instant) -> Result<LockGuard, AcquireError> {
crate::production_storage::refuse_write(path)?;
#[cfg(any(test, feature = "test-support"))]
retry_clock::before_acquire();
acquire_with_deadline(path, Some(deadline), false, true, LockConfig::default())
}
pub fn try_acquire_once(path: &Path) -> Result<LockGuard, AcquireError> {
try_acquire(path, Duration::ZERO)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LockAvailability {
Available,
LiveOwner,
Stale,
Malformed,
}
enum ObservedLock {
Available,
LiveOwner(LockMetadata),
Stale(LockMetadata),
Malformed(serde_json::Error),
}
impl ObservedLock {
fn availability(&self) -> LockAvailability {
match self {
Self::Available => LockAvailability::Available,
Self::LiveOwner(_) => LockAvailability::LiveOwner,
Self::Stale(_) => LockAvailability::Stale,
Self::Malformed(_) => LockAvailability::Malformed,
}
}
}
pub fn lock_availability(path: &Path) -> io::Result<LockAvailability> {
observe_lock(path, ¤t_hostname(), LockConfig::default())
.map(|observed| observed.availability())
}
fn observe_lock(path: &Path, hostname: &str, config: LockConfig) -> io::Result<ObservedLock> {
match read_lock_metadata(path) {
Ok(metadata) => {
if metadata_blocks_acquisition(&metadata, hostname, config, now_ms()) {
Ok(ObservedLock::LiveOwner(metadata))
} else {
Ok(ObservedLock::Stale(metadata))
}
}
Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
Ok(ObservedLock::Available)
}
Err(ReadLockError::Io(error)) => Err(error),
Err(ReadLockError::Malformed(error)) => Ok(ObservedLock::Malformed(error)),
}
}
fn metadata_blocks_acquisition(
metadata: &LockMetadata,
hostname: &str,
config: LockConfig,
now: u64,
) -> bool {
if metadata.hostname != hostname {
now.saturating_sub(metadata.heartbeat_at_ms) <= config.cross_host_stale_heartbeat_ms()
} else {
lock_owner_is_alive(metadata)
}
}
pub struct LockGuard {
path: PathBuf,
metadata: LockMetadata,
shutdown: Arc<AtomicBool>,
heartbeat_failed: Arc<AtomicBool>,
heartbeat_done: mpsc::Receiver<()>,
heartbeat: Option<JoinHandle<()>>,
pump: HeartbeatPump,
heartbeat_file: Arc<Mutex<Option<LeaseFile>>>,
}
impl LockGuard {
pub fn path(&self) -> &Path {
&self.path
}
pub fn writer_epoch(&self) -> &str {
&self.metadata.writer_epoch
}
pub(crate) fn heartbeat_is_visible(&self) -> bool {
self.pump.is_visible()
}
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code))]
fn heartbeat_once(&self) -> Result<(), HeartbeatError> {
heartbeat_once(&self.path, &self.metadata, &self.heartbeat_file)
}
pub fn verify_writer_epoch(&self) -> io::Result<bool> {
if self.heartbeat_failed.load(Ordering::Acquire) || !self.heartbeat_is_visible() {
return Ok(false);
}
match read_lock_metadata(&self.path) {
Ok(metadata) => Ok(lock_identity_matches(&metadata, &self.metadata)),
Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(ReadLockError::Io(error)) => Err(error),
Err(ReadLockError::Malformed(_)) => Ok(false),
}
}
#[rustfmt::skip]
test_support_visibility! {
pub(crate) fn stop_heartbeat_for_removal(&mut self) {
self.shutdown.store(true, Ordering::Release);
if let Some(handle) = self.heartbeat.take() {
handle.thread().unpark();
let _ = handle.join();
}
while self.heartbeat_done.try_recv().is_ok() {}
let mut handle = self
.heartbeat_file
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
*handle = None;
drop(handle);
unregister_lease_slot(self.pump.slot, &self.path);
self.pump.visible.store(false, Ordering::Release);
}
}
}
impl Drop for LockGuard {
fn drop(&mut self) {
self.stop_heartbeat_for_removal();
match remove_lock_if_owned(&self.path, &self.metadata) {
Ok(true) => slog_debug!("released filesystem lock at {}", self.path.display()),
Ok(false) => {}
Err(error) => slog_warn!(
"failed to release filesystem lock at {}: {}",
self.path.display(),
error
),
}
}
}
fn with_lease_handles_closed<T>(
path: &Path,
replace: impl FnOnce() -> io::Result<T>,
) -> io::Result<T> {
let slot = lease_slots_by_path()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(path)
.copied();
let handle = slot.and_then(|slot| {
lease_files()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(&slot)
.and_then(|entry| entry.handle.upgrade())
});
let mut released = Vec::new();
for handle in handle.iter() {
let Ok(mut slot) = handle.try_lock() else {
continue;
};
*slot = None;
released.push(slot);
}
let result = replace();
drop(released);
result
}
#[derive(Debug)]
pub enum AcquireError {
Io(io::Error),
Timeout,
}
impl fmt::Display for AcquireError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AcquireError::Io(error) => write!(f, "filesystem lock I/O error: {error}"),
AcquireError::Timeout => write!(f, "timed out acquiring filesystem lock"),
}
}
}
impl std::error::Error for AcquireError {}
impl From<io::Error> for AcquireError {
fn from(error: io::Error) -> Self {
AcquireError::Io(error)
}
}
fn acquire_with_config(
path: &Path,
timeout: Option<Duration>,
config: LockConfig,
) -> Result<LockGuard, AcquireError> {
crate::production_storage::refuse_write(path)?;
#[cfg(any(test, feature = "test-support"))]
retry_clock::before_acquire();
let deadline = timeout.map(|timeout| acquisition_now() + timeout);
acquire_with_deadline(
path,
deadline,
timeout == Some(Duration::ZERO),
false,
config,
)
}
fn acquire_with_deadline(
path: &Path,
deadline: Option<Instant>,
allow_malformed_grace: bool,
strict_deadline: bool,
config: LockConfig,
) -> Result<LockGuard, AcquireError> {
let hostname = current_hostname();
let mut live_owner_log = LiveOwnerLog::new();
let mut transient_create_failures: u32 = 0;
let mut attempted_once = false;
let mut dead_reclaim_blocked_attempts = 0_u32;
let mut immediate_retry_budget = 0_u8;
let mut malformed_grace_used = false;
loop {
if attempted_once {
if immediate_retry_budget > 0 && !strict_deadline {
immediate_retry_budget -= 1;
} else if let Some(deadline) = deadline {
if acquisition_now() >= deadline {
return Err(AcquireError::Timeout);
}
}
}
attempted_once = true;
#[cfg(any(test, feature = "test-support"))]
retry_clock::note_attempt();
match create_new_lock(path, &hostname, config) {
Ok(guard) => return Ok(guard),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
Err(error) if is_transient_create_contention(&error) => {
transient_create_failures += 1;
if transient_create_failures > MAX_TRANSIENT_CREATE_RETRIES {
return Err(error.into());
}
sleep_until_retry(deadline, config.poll_interval_ms)?;
continue;
}
Err(error) => return Err(error.into()),
}
transient_create_failures = 0;
let observed = match observe_lock(path, &hostname, config) {
Ok(observed) => observed,
Err(error) if is_transient_create_contention(&error) => {
transient_create_failures += 1;
if transient_create_failures > MAX_TRANSIENT_CREATE_RETRIES {
return Err(error.into());
}
sleep_until_retry(deadline, config.poll_interval_ms)?;
continue;
}
Err(error) => return Err(error.into()),
};
let availability = observed.availability();
let metadata = match observed {
ObservedLock::LiveOwner(metadata) | ObservedLock::Stale(metadata) => metadata,
ObservedLock::Available => {
immediate_retry_budget = 1;
continue;
}
ObservedLock::Malformed(error) => {
if allow_malformed_grace && !malformed_grace_used {
malformed_grace_used = true;
sleep_until_retry(None, config.poll_interval_ms)?;
} else {
sleep_until_retry(deadline, config.poll_interval_ms)?;
}
match read_lock_metadata(path) {
Ok(_) => continue,
Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
continue;
}
Err(ReadLockError::Io(error)) => return Err(error.into()),
Err(ReadLockError::Malformed(_)) => {}
}
slog_warn!(
"removing malformed filesystem lock at {}: {}",
path.display(),
error
);
let judged = fs::read(path)?;
if serde_json::from_slice::<LockMetadata>(&judged).is_ok() {
continue;
}
#[cfg(any(test, feature = "test-support"))]
run_acquisition_hook(&BEFORE_MALFORMED_RECLAIM);
if reclaim_malformed_lock(path, &judged)? {
immediate_retry_budget = 1;
}
continue;
}
};
let now = now_ms();
let since_heartbeat = now.saturating_sub(metadata.heartbeat_at_ms);
if metadata.hostname != hostname {
dead_reclaim_blocked_attempts = 0;
let cross_host_stale_ms = config.cross_host_stale_heartbeat_ms();
if availability == LockAvailability::Stale {
match reclaim_lock_file(path, &metadata)? {
ReclaimResult::Removed => {
slog_warn!(
"reclaimed cross-host filesystem lock at {} from host {} after stale heartbeat ({}ms > {}ms)",
path.display(),
metadata.hostname,
since_heartbeat,
cross_host_stale_ms
);
immediate_retry_budget = 1;
}
ReclaimResult::Blocked(holder) => {
log_reclaim_blocked(path, &holder);
sleep_until_retry(deadline, config.poll_interval_ms)?;
}
ReclaimResult::Unchanged => {
sleep_until_retry(deadline, config.poll_interval_ms)?;
}
}
continue;
}
sleep_until_retry(deadline, config.poll_interval_ms)?;
continue;
}
if availability == LockAvailability::Stale {
match reclaim_lock_file(path, &metadata)? {
ReclaimResult::Removed => {
slog_info!(
"removing filesystem lock at {} from dead or recycled PID {}",
path.display(),
metadata.pid
);
immediate_retry_budget = 1;
dead_reclaim_blocked_attempts = 0;
}
ReclaimResult::Blocked(holder) => {
log_reclaim_blocked(path, &holder);
let backoff_ms = dead_reclaim_backoff_ms(
dead_reclaim_blocked_attempts,
config.poll_interval_ms,
);
dead_reclaim_blocked_attempts = dead_reclaim_blocked_attempts.saturating_add(1);
sleep_until_retry(deadline, backoff_ms)?;
}
ReclaimResult::Unchanged => {
dead_reclaim_blocked_attempts = 0;
sleep_until_retry(deadline, config.poll_interval_ms)?;
}
}
continue;
}
dead_reclaim_blocked_attempts = 0;
if since_heartbeat > config.live_owner_warning_age_ms() && live_owner_log.first_stale() {
slog_warn!(
"filesystem lock at {} held by live PID {} has stale heartbeat ({}ms); NOT breaking",
path.display(),
metadata.pid,
since_heartbeat
);
}
let held_for = now.saturating_sub(metadata.created_at_ms);
if held_for > config.live_owner_warn_ms && live_owner_log.first_long_held() {
if metadata.pid == std::process::id() {
slog_debug!(
"filesystem lock at {} is held by a live lease of this process for >10min; \
waiting without breaking it",
path.display()
);
} else {
slog_warn!(
"filesystem lock at {} held >10min by live heartbeating PID {}; NOT breaking",
path.display(),
metadata.pid
);
}
}
sleep_until_retry(deadline, config.poll_interval_ms)?;
}
}
fn create_new_lock(path: &Path, hostname: &str, config: LockConfig) -> io::Result<LockGuard> {
let first_refresh =
Instant::now() + Duration::from_millis(config.heartbeat_refresh_interval_ms);
let now = now_ms();
let pid = std::process::id();
let process_identity = process_identity(pid);
let metadata = LockMetadata {
pid,
hostname: hostname.to_string(),
process_start_time: process_identity
.as_ref()
.map(|identity| identity.start_time),
boot_id: process_identity.and_then(|identity| identity.boot_id),
created_at_ms: now,
heartbeat_at_ms: now,
writer_epoch: format!("{pid}-{}", now_nanos()),
};
create_lock_file_atomically(path, &metadata)?;
let (heartbeat_pump, heartbeat_file) =
HeartbeatPump::attach(path, &metadata).inspect_err(|_| {
let _ = remove_lock_if_owned(path, &metadata);
})?;
let shutdown = Arc::new(AtomicBool::new(false));
let heartbeat_failed = Arc::new(AtomicBool::new(false));
let (done_tx, done_rx) = mpsc::channel();
let heartbeat_path = path.to_path_buf();
let heartbeat_shutdown = Arc::clone(&shutdown);
let heartbeat_failed_for_thread = Arc::clone(&heartbeat_failed);
let heartbeat_pump_for_thread = heartbeat_pump.clone();
let heartbeat = spawn_heartbeat(move || {
let heartbeat_shutdown_for_run = Arc::clone(&heartbeat_shutdown);
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
run_heartbeat(
heartbeat_path,
&heartbeat_pump_for_thread,
heartbeat_shutdown_for_run,
config,
first_refresh,
);
}));
if result.is_err() || !heartbeat_shutdown.load(Ordering::Acquire) {
heartbeat_failed_for_thread.store(true, Ordering::Release);
}
let _ = done_tx.send(());
})
.inspect_err(|_| {
let _ = remove_lock_if_owned(path, &metadata);
})?;
slog_debug!("acquired filesystem lock at {}", path.display());
#[cfg(any(test, feature = "test-support"))]
io_ledger::record(|ledger| ledger.acquisitions += 1);
Ok(LockGuard {
path: path.to_path_buf(),
metadata,
shutdown,
heartbeat_failed,
heartbeat_done: done_rx,
heartbeat: Some(heartbeat),
pump: heartbeat_pump,
heartbeat_file,
})
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
pub static BEFORE_MALFORMED_RECLAIM: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
pub static BEFORE_HEARTBEAT_SPAWN_FAILURE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
}
#[cfg(any(test, feature = "test-support"))]
fn run_acquisition_hook(
hook: &'static std::thread::LocalKey<std::cell::RefCell<Option<Box<dyn FnOnce()>>>>,
) -> bool {
let action = hook.with(|slot| slot.borrow_mut().take());
if let Some(action) = action {
action();
true
} else {
false
}
}
fn spawn_heartbeat(run: impl FnOnce() + Send + 'static) -> io::Result<thread::JoinHandle<()>> {
#[cfg(any(test, feature = "test-support"))]
if run_acquisition_hook(&BEFORE_HEARTBEAT_SPAWN_FAILURE) {
return Err(io::Error::other("injected heartbeat spawn failure"));
}
thread::Builder::new()
.name("aft-fs-lock-heartbeat".to_string())
.spawn(run)
}
fn run_heartbeat(
path: PathBuf,
pump: &HeartbeatPump,
shutdown: Arc<AtomicBool>,
config: LockConfig,
mut next_refresh: Instant,
) {
let stale_intervals = config
.stale_heartbeat_ms
.checked_div(config.heartbeat_interval_ms.max(1))
.unwrap_or(3)
.max(1);
let mut consecutive_transient_failures: u64 = 0;
let refresh_interval = Duration::from_millis(config.heartbeat_refresh_interval_ms);
loop {
if shutdown.load(Ordering::Acquire) {
return;
}
match refresh_heartbeat_if_due(pump, &mut next_refresh, refresh_interval, Instant::now()) {
Ok(false) => {}
Ok(true) => {
if consecutive_transient_failures > 0 {
slog_info!(
"filesystem lock at {} heartbeat recovered after {} transient failure(s)",
path.display(),
consecutive_transient_failures
);
consecutive_transient_failures = 0;
}
}
Err(error) if heartbeat_error_is_terminal(&error) => {
#[cfg(any(test, feature = "test-support"))]
pump.mark_stopped();
slog_error!(
"{}; stopping heartbeat",
terminal_heartbeat_message(&path, &error)
);
return;
}
Err(error) => {
consecutive_transient_failures += 1;
log_transient_heartbeat_failure(
&path,
&transient_heartbeat_reason(&error),
consecutive_transient_failures,
stale_intervals,
);
}
}
thread::park_timeout(Duration::from_millis(config.heartbeat_interval_ms));
}
}
fn refresh_heartbeat_if_due(
pump: &HeartbeatPump,
next_refresh: &mut Instant,
interval: Duration,
now: Instant,
) -> Result<bool, HeartbeatError> {
if now < *next_refresh {
return Ok(false);
}
pump.heartbeat_once()?;
*next_refresh = now + interval;
Ok(true)
}
fn heartbeat_error_is_terminal(error: &HeartbeatError) -> bool {
matches!(
error,
HeartbeatError::LockGone | HeartbeatError::NotOwner | HeartbeatError::NotPumped
)
}
fn terminal_heartbeat_message(path: &Path, error: &HeartbeatError) -> String {
match error {
HeartbeatError::LockGone => {
format!("filesystem lock at {} disappeared", path.display())
}
HeartbeatError::NotOwner => format!(
"filesystem lock at {} is no longer owned by this guard",
path.display()
),
HeartbeatError::NotPumped => format!(
"filesystem lock at {} heartbeat handle was released by this process",
path.display()
),
HeartbeatError::Io(error) => {
format!("filesystem lock at {} I/O error: {error}", path.display())
}
HeartbeatError::Malformed(error) => {
format!(
"filesystem lock at {} became malformed: {error}",
path.display()
)
}
}
}
fn transient_heartbeat_reason(error: &HeartbeatError) -> String {
match error {
HeartbeatError::Io(error) => format!("I/O error: {error}"),
HeartbeatError::Malformed(error) => format!("became malformed: {error}"),
HeartbeatError::LockGone => "lock disappeared".to_string(),
HeartbeatError::NotOwner => "lock no longer owned".to_string(),
HeartbeatError::NotPumped => "heartbeat handle released".to_string(),
}
}
fn log_transient_heartbeat_failure(
path: &Path,
reason: &str,
consecutive_failures: u64,
stale_intervals: u64,
) {
if consecutive_failures < stale_intervals {
slog_warn!(
"transient failure to heartbeat filesystem lock at {}: {}; retrying (attempt {})",
path.display(),
reason,
consecutive_failures
);
} else if consecutive_failures == stale_intervals {
slog_error!(
"filesystem lock at {} has failed {} consecutive heartbeats: {}; \
the lock may now be reclaimed by another owner — continuing to retry",
path.display(),
consecutive_failures,
reason
);
}
}
#[derive(Debug)]
struct HeartbeatPump {
path: PathBuf,
slot: usize,
owner: Mutex<LockMetadata>,
visible: AtomicBool,
#[cfg(any(test, feature = "test-support"))]
stopped: Arc<AtomicBool>,
}
fn lease_files() -> &'static Mutex<HashMap<usize, LeaseSlot>> {
LEASE_FILES.get_or_init(|| Mutex::new(HashMap::new()))
}
fn lease_slots_by_path() -> &'static Mutex<HashMap<PathBuf, usize>> {
LEASE_SLOT_BY_PATH.get_or_init(|| Mutex::new(HashMap::new()))
}
fn register_lease_slot(slot: usize, path: &Path, handle: &Arc<Mutex<Option<LeaseFile>>>) {
lease_files()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.insert(
slot,
LeaseSlot {
handle: Arc::downgrade(handle),
},
);
lease_slots_by_path()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.insert(path.to_path_buf(), slot);
}
fn unregister_lease_slot(slot: usize, path: &Path) {
lease_files()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.remove(&slot);
let mut by_path = lease_slots_by_path()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if by_path.get(path).copied() == Some(slot) {
by_path.remove(path);
}
}
impl Clone for HeartbeatPump {
fn clone(&self) -> Self {
Self {
path: self.path.clone(),
slot: self.slot,
owner: Mutex::new(
self.owner
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone(),
),
visible: AtomicBool::new(self.is_visible()),
#[cfg(any(test, feature = "test-support"))]
stopped: Arc::clone(&self.stopped),
}
}
}
impl HeartbeatPump {
fn attach(
path: &Path,
owner: &LockMetadata,
) -> io::Result<(Self, Arc<Mutex<Option<LeaseFile>>>)> {
let file = Arc::new(Mutex::new(Some(
open_lease_for_heartbeat(path).map_err(heartbeat_io_error)?,
)));
let slot = NEXT_LEASE_SLOT.fetch_add(1, Ordering::Relaxed) as usize;
{
let mut registry = lease_files()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if registry.len() > 4096 {
registry.retain(|_, known| known.handle.strong_count() > 0);
}
}
register_lease_slot(slot, path, &file);
Ok((
Self {
path: path.to_path_buf(),
slot,
owner: Mutex::new(owner.clone()),
visible: AtomicBool::new(true),
#[cfg(any(test, feature = "test-support"))]
stopped: Arc::new(AtomicBool::new(false)),
},
file,
))
}
fn is_visible(&self) -> bool {
self.visible.load(Ordering::Acquire)
}
#[cfg(any(test, feature = "test-support"))]
fn mark_stopped(&self) {
self.stopped.store(true, Ordering::Release);
}
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code))]
pub(super) fn heartbeat_stopped(&self) -> bool {
self.stopped.load(Ordering::Acquire)
}
fn heartbeat_once(&self) -> Result<(), HeartbeatError> {
if !self.is_visible() {
return Err(HeartbeatError::NotPumped);
}
let mut reopened = false;
loop {
let handle = {
let registry = lease_files()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
registry
.get(&self.slot)
.and_then(|entry| entry.handle.upgrade())
};
let Some(handle) = handle else {
return Err(HeartbeatError::NotPumped);
};
match self.beat(&handle) {
Ok(()) => return Ok(()),
Err(HeartbeatError::NotOwner) => {
self.retire_handle(&handle);
if self.release_if_reclaimed() {
return Err(HeartbeatError::NotOwner);
}
if reopened {
return Err(HeartbeatError::Io(io::Error::new(
io::ErrorKind::WouldBlock,
"lease replaced repeatedly during heartbeat",
)));
}
reopened = true;
}
Err(error @ HeartbeatError::Malformed(_)) => {
self.retire_handle(&handle);
return Err(error);
}
Err(error) => return Err(error),
}
}
}
fn beat(&self, handle: &Arc<Mutex<Option<LeaseFile>>>) -> Result<(), HeartbeatError> {
let owner = self
.owner
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone();
let needs_open = handle
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.is_none();
if needs_open {
let file = open_lease_for_heartbeat(&self.path)?;
let mut slot = handle
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if slot.is_none() {
*slot = Some(file);
}
}
heartbeat_once(&self.path, &owner, handle)
}
fn retire_handle(&self, handle: &Arc<Mutex<Option<LeaseFile>>>) {
let mut slot = handle
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
*slot = None;
}
fn release_if_reclaimed(&self) -> bool {
match read_lock_metadata(&self.path) {
Err(ReadLockError::Malformed(_)) => false,
Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => true,
Err(ReadLockError::Io(_)) => false,
Ok(on_disk) => {
let owner = self
.owner
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
!lock_identity_matches(&on_disk, &owner)
}
}
}
}
fn heartbeat_once(
path: &Path,
owner: &LockMetadata,
handle: &Mutex<Option<LeaseFile>>,
) -> Result<(), HeartbeatError> {
let mut slot = handle
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(kept) = slot.as_mut() {
let on_path = match LeaseFileIdentity::of_path(path) {
Ok(identity) => identity,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return Err(HeartbeatError::LockGone);
}
Err(error) => return Err(HeartbeatError::Io(error)),
};
match LeaseFileIdentity::of_file(kept.file()) {
Some(held) if held != on_path => return Err(HeartbeatError::NotOwner),
Some(_) => {}
None => *slot = None,
}
}
let mut opened = None;
let file = match slot.as_mut() {
Some(kept) => kept.file(),
None => opened.insert(open_lease_for_heartbeat(path)?).file(),
};
file.seek(SeekFrom::Start(0)).map_err(HeartbeatError::Io)?;
let mut current = Vec::new();
file.read_to_end(&mut current).map_err(HeartbeatError::Io)?;
let mut metadata: LockMetadata =
serde_json::from_slice(¤t).map_err(HeartbeatError::Malformed)?;
if !lock_identity_matches(&metadata, owner) {
return Err(HeartbeatError::NotOwner);
}
metadata.heartbeat_at_ms = now_ms();
let next = lock_metadata_bytes(&metadata).map_err(HeartbeatError::Io)?;
if next.len() == current.len() {
file.seek(SeekFrom::Start(0)).map_err(HeartbeatError::Io)?;
return write_lock_bytes(file, &next).map_err(HeartbeatError::Io);
}
*slot = None;
drop(opened);
replace_lock_bytes_unsynced(path, &next).map_err(HeartbeatError::Io)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct LeaseFileIdentity {
volume: u64,
file: u64,
}
impl LeaseFileIdentity {
#[cfg(unix)]
fn of_metadata(metadata: &fs::Metadata) -> Self {
use std::os::unix::fs::MetadataExt;
Self {
volume: metadata.dev(),
file: metadata.ino(),
}
}
#[cfg(windows)]
fn from_raw_handle(handle: windows_sys::Win32::Foundation::HANDLE) -> Option<Self> {
use windows_sys::Win32::Storage::FileSystem::{
GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
};
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
let ok = unsafe { GetFileInformationByHandle(handle, &mut info) } != 0;
ok.then(|| Self {
volume: u64::from(info.dwVolumeSerialNumber),
file: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
})
}
#[cfg(unix)]
fn of_file(file: &File) -> Option<Self> {
file.metadata()
.ok()
.map(|metadata| Self::of_metadata(&metadata))
}
#[cfg(windows)]
fn of_file(file: &File) -> Option<Self> {
use std::os::windows::io::AsRawHandle;
Self::from_raw_handle(file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE)
}
#[cfg(unix)]
fn of_path(path: &Path) -> io::Result<Self> {
fs::metadata(path).map(|metadata| Self::of_metadata(&metadata))
}
#[cfg(windows)]
fn of_path(path: &Path) -> io::Result<Self> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
use windows_sys::Win32::Storage::FileSystem::{
CreateFileW, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ,
FILE_SHARE_WRITE, OPEN_EXISTING,
};
struct Closed(windows_sys::Win32::Foundation::HANDLE);
impl Drop for Closed {
fn drop(&mut self) {
unsafe { CloseHandle(self.0) };
}
}
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let handle = unsafe {
CreateFileW(
wide.as_ptr(),
FILE_READ_ATTRIBUTES,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
std::ptr::null(),
OPEN_EXISTING,
0,
std::ptr::null_mut(),
)
};
if handle == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
let handle = Closed(handle);
Self::from_raw_handle(handle.0)
.ok_or_else(|| io::Error::other("lease path has no file identity"))
}
#[cfg(not(any(unix, windows)))]
fn of_file(_file: &File) -> Option<Self> {
None
}
#[cfg(not(any(unix, windows)))]
fn of_path(_path: &Path) -> io::Result<Self> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"no file identity on this platform",
))
}
}
fn open_lease_for_heartbeat(path: &Path) -> Result<LeaseFile, HeartbeatError> {
let file = match OpenOptions::new().read(true).write(true).open(path) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return Err(HeartbeatError::LockGone);
}
Err(error) => return Err(HeartbeatError::Io(error)),
};
io_ledger::record(|ledger| ledger.opens += 1);
Ok(LeaseFile(file))
}
#[derive(Debug)]
struct LeaseFile(File);
impl LeaseFile {
fn file(&mut self) -> &mut File {
&mut self.0
}
}
impl Drop for LeaseFile {
fn drop(&mut self) {
io_ledger::record(|ledger| ledger.closes += 1);
}
}
fn heartbeat_io_error(error: HeartbeatError) -> io::Error {
match error {
HeartbeatError::Io(error) => error,
other => io::Error::other(format!("{other:?}")),
}
}
#[derive(Debug)]
enum HeartbeatError {
Io(io::Error),
LockGone,
Malformed(serde_json::Error),
NotOwner,
NotPumped,
}
#[derive(Debug)]
enum ReadLockError {
Io(io::Error),
Malformed(serde_json::Error),
}
#[rustfmt::skip]
test_support_visibility! {
pub(crate) fn read_lease_settled(path: &Path) -> io::Result<Vec<u8>> {
let mut previous = fs::read(path)?;
for _ in 0..3 {
let next = fs::read(path)?;
if next == previous {
return Ok(next);
}
previous = next;
}
Ok(previous)
}
}
fn read_lock_metadata(path: &Path) -> Result<LockMetadata, ReadLockError> {
let bytes = read_lease_settled(path).map_err(ReadLockError::Io)?;
serde_json::from_slice(&bytes).map_err(ReadLockError::Malformed)
}
fn open_new_lock_file(path: &Path) -> io::Result<File> {
let file = crate::private_storage::options()
.write(true)
.create_new(true)
.open(path)?;
io_ledger::record(|ledger| ledger.new_files += 1);
Ok(file)
}
fn lock_metadata_bytes(metadata: &LockMetadata) -> io::Result<Vec<u8>> {
let mut bytes = serde_json::to_vec(metadata).map_err(io::Error::other)?;
bytes.push(b'\n');
Ok(bytes)
}
fn write_lock_bytes(file: &mut File, bytes: &[u8]) -> io::Result<()> {
file.write_all(bytes)?;
io_ledger::record(|ledger| ledger.bytes_written += bytes.len() as u64);
Ok(())
}
fn write_lock_metadata_to_file(file: &mut File, metadata: &LockMetadata) -> io::Result<()> {
write_lock_bytes(file, &lock_metadata_bytes(metadata)?)
}
fn create_lock_file_atomically(path: &Path, metadata: &LockMetadata) -> io::Result<()> {
let tmp_path = temp_path_for_lock(path);
let result = (|| {
let mut file = open_new_lock_file(&tmp_path)?;
write_lock_metadata_to_file(&mut file, metadata)?;
drop(file);
fs::hard_link(&tmp_path, path)?;
Ok(())
})();
let _ = fs::remove_file(&tmp_path);
result
}
fn replace_lock_bytes_unsynced(path: &Path, bytes: &[u8]) -> io::Result<()> {
let tmp_path = temp_path_for_lock(path);
let write_result = (|| {
let mut file = open_new_lock_file(&tmp_path)?;
write_lock_bytes(&mut file, bytes)?;
drop(file);
with_lease_handles_closed(path, || rename_over(&tmp_path, path))
})();
if write_result.is_err() {
let _ = fs::remove_file(&tmp_path);
}
write_result
}
#[cfg(any(windows, any(test, feature = "test-support")))]
#[cfg_attr(not(test), allow(dead_code))]
fn rename_over_with(
from: &Path,
to: &Path,
replace: impl FnOnce(&Path, &Path) -> io::Result<()>,
) -> io::Result<()> {
replace(from, to)
}
#[cfg(windows)]
pub fn rename_over(from: &Path, to: &Path) -> io::Result<()> {
rename_over_with(from, to, |from, to| fs::rename(from, to))
}
#[cfg(not(windows))]
pub fn rename_over(from: &Path, to: &Path) -> io::Result<()> {
fs::rename(from, to)
}
static TEMP_LOCK_COUNTER: AtomicU64 = AtomicU64::new(0);
fn temp_path_for_lock(path: &Path) -> PathBuf {
let file_name = path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("lock");
let seq = TEMP_LOCK_COUNTER.fetch_add(1, Ordering::Relaxed);
path.with_file_name(format!(
".{file_name}.tmp.{}.{}.{}",
std::process::id(),
now_nanos(),
seq
))
}
fn lock_identity_matches(left: &LockMetadata, right: &LockMetadata) -> bool {
left.pid == right.pid
&& left.hostname == right.hostname
&& left.process_start_time == right.process_start_time
&& left.boot_id == right.boot_id
&& left.created_at_ms == right.created_at_ms
&& left.writer_epoch == right.writer_epoch
}
fn remove_lock_if_owned(path: &Path, owner: &LockMetadata) -> io::Result<bool> {
let metadata = match read_lock_metadata(path) {
Ok(metadata) => metadata,
Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
return Ok(false);
}
Err(ReadLockError::Io(error)) => return Err(error),
Err(ReadLockError::Malformed(_)) => return Ok(false),
};
if lock_identity_matches(&metadata, owner) {
remove_lock_file(path)?;
Ok(true)
} else {
Ok(false)
}
}
fn remove_lock_file(path: &Path) -> io::Result<()> {
match with_lease_handles_closed(path, || fs::remove_file(path)) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error),
}
}
fn reclaim_lock_file(path: &Path, judged: &LockMetadata) -> io::Result<ReclaimResult> {
let token = match acquire_reclaim_token(path)? {
ReclaimTokenAcquire::Acquired(token) => token,
ReclaimTokenAcquire::Held(holder) => return Ok(ReclaimResult::Blocked(holder)),
};
let _token = token;
match read_lock_metadata(path) {
Ok(current) => {
if lock_identity_matches(¤t, judged) {
remove_lock_file(path)?;
Ok(ReclaimResult::Removed)
} else {
Ok(ReclaimResult::Unchanged)
}
}
Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
Ok(ReclaimResult::Unchanged)
}
Err(ReadLockError::Malformed(_)) => Ok(ReclaimResult::Unchanged),
Err(ReadLockError::Io(error)) => Err(error),
}
}
fn reclaim_malformed_lock(path: &Path, judged: &[u8]) -> io::Result<bool> {
let _token = match acquire_reclaim_token(path)? {
ReclaimTokenAcquire::Acquired(token) => token,
ReclaimTokenAcquire::Held(_) => return Ok(false),
};
match fs::read(path) {
Ok(current)
if current == judged && serde_json::from_slice::<LockMetadata>(¤t).is_err() =>
{
remove_lock_file(path)?;
Ok(true)
}
Ok(_) => Ok(false),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
struct ReclaimTokenGuard {
path: PathBuf,
}
impl Drop for ReclaimTokenGuard {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
}
}
fn acquire_reclaim_token(lock_path: &Path) -> io::Result<ReclaimTokenAcquire> {
let token_path = reclaim_token_path(lock_path);
let metadata = current_reclaim_token_metadata();
match create_reclaim_token(&token_path, &metadata) {
Ok(guard) => return Ok(ReclaimTokenAcquire::Acquired(guard)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(error),
}
let stale = match inspect_reclaim_token(&token_path)? {
ExistingReclaimToken::Held(holder) => return Ok(ReclaimTokenAcquire::Held(holder)),
ExistingReclaimToken::StaleValid(owner) => remove_lock_if_owned(&token_path, &owner)?,
ExistingReclaimToken::StaleMalformed => remove_malformed_reclaim_token(&token_path)?,
ExistingReclaimToken::Missing => true,
};
if !stale {
return inspect_reclaim_token_as_held(&token_path);
}
match create_reclaim_token(&token_path, &metadata) {
Ok(guard) => Ok(ReclaimTokenAcquire::Acquired(guard)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
inspect_reclaim_token_as_held(&token_path)
}
Err(error) => Err(error),
}
}
enum ReclaimTokenAcquire {
Acquired(ReclaimTokenGuard),
Held(ReclaimTokenHeld),
}
enum ExistingReclaimToken {
Held(ReclaimTokenHeld),
StaleValid(LockMetadata),
StaleMalformed,
Missing,
}
fn current_reclaim_token_metadata() -> LockMetadata {
let pid = std::process::id();
let process_identity = process_identity(pid);
let now = now_ms();
LockMetadata {
pid,
hostname: current_hostname(),
process_start_time: process_identity
.as_ref()
.map(|identity| identity.start_time),
boot_id: process_identity.and_then(|identity| identity.boot_id),
created_at_ms: now,
heartbeat_at_ms: now,
writer_epoch: format!("reclaim-{pid}-{}", now_nanos()),
}
}
fn create_reclaim_token(
token_path: &Path,
metadata: &LockMetadata,
) -> io::Result<ReclaimTokenGuard> {
let mut file = open_new_lock_file(token_path)?;
if let Err(error) = write_lock_metadata_to_file(&mut file, metadata) {
let _ = fs::remove_file(token_path);
return Err(error);
}
Ok(ReclaimTokenGuard {
path: token_path.to_path_buf(),
})
}
fn inspect_reclaim_token(token_path: &Path) -> io::Result<ExistingReclaimToken> {
match read_lock_metadata(token_path) {
Ok(metadata) if metadata.hostname != current_hostname() => {
Ok(ExistingReclaimToken::Held(ReclaimTokenHeld {
pid: Some(metadata.pid),
state: ReclaimTokenState::DeadForeignHost,
}))
}
Ok(metadata) if lock_owner_is_alive(&metadata) => {
Ok(ExistingReclaimToken::Held(ReclaimTokenHeld {
pid: Some(metadata.pid),
state: ReclaimTokenState::Alive,
}))
}
Ok(metadata) => Ok(ExistingReclaimToken::StaleValid(metadata)),
Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
Ok(ExistingReclaimToken::Missing)
}
Err(ReadLockError::Io(error)) => Err(error),
Err(ReadLockError::Malformed(_)) => {
let old_enough = fs::metadata(token_path)
.and_then(|metadata| metadata.modified())
.ok()
.and_then(|modified| SystemTime::now().duration_since(modified).ok())
.is_some_and(|age| age > RECLAIM_TOKEN_MALFORMED_STALE_AGE);
if old_enough {
Ok(ExistingReclaimToken::StaleMalformed)
} else {
Ok(ExistingReclaimToken::Held(ReclaimTokenHeld {
pid: malformed_token_pid(token_path),
state: ReclaimTokenState::Malformed,
}))
}
}
}
}
fn inspect_reclaim_token_as_held(token_path: &Path) -> io::Result<ReclaimTokenAcquire> {
let holder = match inspect_reclaim_token(token_path)? {
ExistingReclaimToken::Held(holder) => holder,
ExistingReclaimToken::StaleValid(metadata) => ReclaimTokenHeld {
pid: Some(metadata.pid),
state: ReclaimTokenState::Dead,
},
ExistingReclaimToken::StaleMalformed | ExistingReclaimToken::Missing => ReclaimTokenHeld {
pid: malformed_token_pid(token_path),
state: ReclaimTokenState::Malformed,
},
};
Ok(ReclaimTokenAcquire::Held(holder))
}
fn malformed_token_pid(token_path: &Path) -> Option<u32> {
let bytes = fs::read(token_path).ok()?;
serde_json::from_slice::<serde_json::Value>(&bytes)
.ok()?
.get("pid")?
.as_u64()
.and_then(|pid| u32::try_from(pid).ok())
}
fn remove_malformed_reclaim_token(token_path: &Path) -> io::Result<bool> {
match fs::remove_file(token_path) {
Ok(()) => Ok(true),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(true),
Err(error) => Err(error),
}
}
fn reclaim_token_path(lock_path: &Path) -> PathBuf {
let file_name = lock_path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("lock");
lock_path.with_file_name(format!(".{file_name}.reclaim"))
}
fn dead_reclaim_backoff_ms(blocked_attempt: u32, poll_interval_ms: u64) -> u64 {
let base = poll_interval_ms.max(DEAD_RECLAIM_INITIAL_BACKOFF_MS);
base.saturating_mul(
1_u64
.checked_shl(blocked_attempt.min(20))
.unwrap_or(u64::MAX),
)
.min(DEAD_RECLAIM_MAX_BACKOFF_MS)
}
fn log_reclaim_blocked(path: &Path, holder: &ReclaimTokenHeld) {
let now = Instant::now();
let logs = RECLAIM_BLOCK_LOGS.get_or_init(|| Mutex::new(HashMap::new()));
let Ok(mut logs) = logs.lock() else {
return;
};
let message = match logs.get_mut(path) {
Some(record)
if now.saturating_duration_since(record.last_emitted) < RECLAIM_BLOCK_LOG_INTERVAL =>
{
record.suppressed = record.suppressed.saturating_add(1);
return;
}
Some(record) => {
let suppressed = record.suppressed;
record.last_emitted = now;
record.suppressed = 0;
format_reclaim_blocked(path, holder, suppressed)
}
None => {
logs.insert(
path.to_path_buf(),
ReclaimBlockLogRecord {
last_emitted: now,
suppressed: 0,
},
);
format_reclaim_blocked(path, holder, 0)
}
};
drop(logs);
emit_reclaim_warning(message);
}
fn format_reclaim_blocked(path: &Path, holder: &ReclaimTokenHeld, suppressed: u64) -> String {
let pid = holder
.pid
.map(|pid| pid.to_string())
.unwrap_or_else(|| "unknown".to_string());
let mut message = format!(
"reclaim of {} blocked: reclaim token held by pid {} ({})",
path.display(),
pid,
holder.state.as_str()
);
if suppressed > 0 {
message.push_str(&format!(" (repeated {suppressed}x in 60s)"));
}
message
}
fn emit_reclaim_warning(message: String) {
#[cfg(any(test, feature = "test-support"))]
RECLAIM_TEST_LOGS.with(|logs| logs.borrow_mut().push(message.clone()));
slog_warn!("{}", message);
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
pub static RECLAIM_TEST_LOGS: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
static RETRY_SLEEP_OBSERVER: std::cell::RefCell<Option<Arc<std::sync::atomic::AtomicUsize>>> =
const { std::cell::RefCell::new(None) };
}
#[cfg(any(test, feature = "test-support"))]
pub struct RetrySleepObserverGuard {
previous: Option<Arc<std::sync::atomic::AtomicUsize>>,
}
#[cfg(any(test, feature = "test-support"))]
impl Drop for RetrySleepObserverGuard {
fn drop(&mut self) {
RETRY_SLEEP_OBSERVER.with(|observer| {
*observer.borrow_mut() = self.previous.take();
});
}
}
#[cfg(any(test, feature = "test-support"))]
pub fn observe_retry_sleeps_for_test(
observer: Arc<std::sync::atomic::AtomicUsize>,
) -> RetrySleepObserverGuard {
let previous = RETRY_SLEEP_OBSERVER.with(|slot| slot.replace(Some(observer)));
RetrySleepObserverGuard { previous }
}
#[cfg(any(test, feature = "test-support"))]
fn note_retry_sleep_for_test() {
RETRY_SLEEP_OBSERVER.with(|observer| {
if let Some(observer) = observer.borrow().as_ref() {
observer.fetch_add(1, Ordering::SeqCst);
}
});
}
pub fn acquisition_now() -> Instant {
#[cfg(any(test, feature = "test-support"))]
if let Some(now) = retry_clock::now() {
return now;
}
Instant::now()
}
pub fn sleep_until_retry(
deadline: Option<Instant>,
poll_interval_ms: u64,
) -> Result<(), AcquireError> {
let poll = Duration::from_millis(poll_interval_ms);
let sleep_for = match deadline {
Some(deadline) => {
let now = acquisition_now();
if now >= deadline {
return Err(AcquireError::Timeout);
}
poll.min(deadline.saturating_duration_since(now))
}
None => poll,
};
#[cfg(any(test, feature = "test-support"))]
note_retry_sleep_for_test();
#[cfg(any(test, feature = "test-support"))]
if retry_clock::sleep(sleep_for) {
return Ok(());
}
thread::sleep(sleep_for);
Ok(())
}
pub(crate) mod io_ledger {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
pub(crate) struct IoLedger {
pub(crate) acquisitions: u64,
pub(crate) opens: u64,
pub(crate) closes: u64,
pub(crate) file_syncs: u64,
pub(crate) dir_syncs: u64,
pub(crate) new_files: u64,
pub(crate) bytes_written: u64,
}
#[cfg(any(test, feature = "test-support"))]
thread_local! {
static LEDGER: std::cell::Cell<IoLedger> = std::cell::Cell::new(IoLedger::default());
}
#[cfg(any(test, feature = "test-support"))]
pub(crate) fn record(update: impl FnOnce(&mut IoLedger)) {
LEDGER.with(|cell| {
let mut ledger = cell.get();
update(&mut ledger);
cell.set(ledger);
});
}
#[cfg(not(any(test, feature = "test-support")))]
#[inline(always)]
pub(crate) fn record(_update: impl FnOnce(&mut IoLedger)) {}
#[cfg(any(test, feature = "test-support"))]
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn take() -> IoLedger {
LEDGER.with(|cell| cell.replace(IoLedger::default()))
}
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or(Duration::ZERO)
.as_millis() as u64
}
fn now_nanos() -> u128 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or(Duration::ZERO)
.as_nanos()
}
#[cfg(unix)]
pub(crate) fn current_hostname() -> String {
let mut buffer = [0u8; 256];
let result = unsafe { libc::gethostname(buffer.as_mut_ptr().cast(), buffer.len()) };
if result == 0 {
let len = buffer
.iter()
.position(|byte| *byte == 0)
.unwrap_or(buffer.len());
if len > 0 {
return String::from_utf8_lossy(&buffer[..len]).into_owned();
}
}
crate::environment::non_empty_var("HOSTNAME").unwrap_or_else(|| "unknown-host".to_string())
}
#[cfg(windows)]
pub(crate) fn current_hostname() -> String {
crate::environment::non_empty_var("COMPUTERNAME")
.or_else(|| crate::environment::non_empty_var("HOSTNAME"))
.unwrap_or_else(|| "unknown-host".to_string())
}
#[cfg(not(any(unix, windows)))]
pub(crate) fn current_hostname() -> String {
crate::environment::non_empty_var("HOSTNAME").unwrap_or_else(|| "unknown-host".to_string())
}
fn lock_owner_is_alive(metadata: &LockMetadata) -> bool {
if !process_alive(metadata.pid) {
return false;
}
let identity = process_identity(metadata.pid);
if identity.as_ref().is_some_and(|identity| identity.exited) {
return false;
}
let Some(recorded_start_time) = metadata.process_start_time else {
return true;
};
let Some(current_identity) = identity else {
return true;
};
if current_identity.start_time != recorded_start_time {
return false;
}
match &metadata.boot_id {
Some(recorded_boot_id) => current_identity
.boot_id
.as_deref()
.map_or(true, |current_boot_id| current_boot_id == recorded_boot_id),
None => true,
}
}
#[cfg(target_os = "linux")]
fn linux_process_stat_identity(stat: &str) -> Option<(u64, bool)> {
let fields = stat.rsplit_once(") ")?.1.split_ascii_whitespace();
let state = fields.clone().next()?;
if state.len() != 1 {
return None;
}
let num_threads = fields.clone().nth(17)?.parse::<u64>().ok()?;
let start_time = fields.clone().nth(19)?.parse::<u64>().ok()?;
Some((start_time, matches!(state, "Z" | "X") && num_threads == 1))
}
#[cfg(target_os = "linux")]
fn process_identity(pid: u32) -> Option<ProcessIdentity> {
let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let (start_time, exited) = linux_process_stat_identity(&stat)?;
let boot_id = fs::read_to_string("/proc/sys/kernel/random/boot_id")
.ok()?
.trim()
.to_owned();
if boot_id.is_empty() {
return None;
}
Some(ProcessIdentity {
start_time,
boot_id: Some(boot_id),
exited,
})
}
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
#[cfg_attr(not(test), allow(dead_code))]
const MACOS_KINFO_SIZE: usize = 648;
#[rustfmt::skip]
test_support_visibility! {
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
pub(crate) const SZOMB: u8 = 5;
}
#[rustfmt::skip]
test_support_visibility! {
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
pub(crate) const P_WEXIT: u32 = 0x0000_2000;
}
#[rustfmt::skip]
test_support_visibility! {
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum MacosExitState {
NotExiting,
Exiting,
Zombie,
}
}
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
#[derive(Clone, Debug)]
pub struct MacosKinfo {
pub comm: String,
pub ruid: u32,
pub pgid: i32,
#[cfg(any(test, feature = "test-support"))]
pub state: u8,
#[cfg(not(any(test, feature = "test-support")))]
pub(crate) state: u8,
#[cfg(any(test, feature = "test-support"))]
pub flags: u32,
#[cfg(not(any(test, feature = "test-support")))]
pub(crate) flags: u32,
#[cfg(any(test, feature = "test-support"))]
pub started_at_us: Option<u64>,
#[cfg(not(any(test, feature = "test-support")))]
pub(crate) started_at_us: Option<u64>,
}
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
impl MacosKinfo {
#[rustfmt::skip]
test_support_visibility! {
pub(crate) fn exit_state(&self) -> MacosExitState {
if self.state == SZOMB {
MacosExitState::Zombie
} else if self.flags & P_WEXIT != 0 {
MacosExitState::Exiting
} else {
MacosExitState::NotExiting
}
}
}
pub fn has_exited(&self) -> bool {
self.exit_state() != MacosExitState::NotExiting
}
}
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
#[cfg_attr(not(test), allow(dead_code))]
fn decode_macos_kinfo(bytes: &[u8]) -> Option<MacosKinfo> {
const P_FLAG_OFFSET: usize = 32;
const P_STAT_OFFSET: usize = 36;
const P_COMM_OFFSET: usize = 243;
const P_COMM_LEN: usize = 17;
const P_RUID_OFFSET: usize = 392;
const E_PGID_OFFSET: usize = 564;
if bytes.len() != MACOS_KINFO_SIZE {
return None;
}
let read_u32 = |offset: usize| {
u32::from_ne_bytes(bytes[offset..offset + 4].try_into().expect("four bytes"))
};
let seconds = i64::from_ne_bytes(bytes[0..8].try_into().ok()?);
let micros = i32::from_ne_bytes(bytes[8..12].try_into().ok()?);
let started_at_us = if seconds > 0 && (0..1_000_000).contains(µs) {
(seconds as u64)
.checked_mul(1_000_000)?
.checked_add(micros as u64)
} else {
None
};
let comm = &bytes[P_COMM_OFFSET..P_COMM_OFFSET + P_COMM_LEN];
let end = comm
.iter()
.position(|byte| *byte == 0)
.unwrap_or(comm.len());
Some(MacosKinfo {
comm: String::from_utf8_lossy(&comm[..end]).into_owned(),
ruid: read_u32(P_RUID_OFFSET),
pgid: read_u32(E_PGID_OFFSET) as i32,
state: bytes[P_STAT_OFFSET],
flags: read_u32(P_FLAG_OFFSET),
started_at_us,
})
}
#[cfg(target_os = "macos")]
pub fn macos_kinfo(pid: u32) -> Option<MacosKinfo> {
if pid == 0 || pid > i32::MAX as u32 {
return None;
}
let mut mib = [
libc::CTL_KERN,
libc::KERN_PROC,
libc::KERN_PROC_PID,
pid as i32,
];
let mut bytes = [0_u8; MACOS_KINFO_SIZE];
let mut size = bytes.len();
let status = unsafe {
libc::sysctl(
mib.as_mut_ptr(),
mib.len() as u32,
bytes.as_mut_ptr().cast(),
&mut size,
std::ptr::null_mut(),
0,
)
};
if status != 0 || size != bytes.len() {
return None;
}
decode_macos_kinfo(&bytes)
}
#[cfg(any(target_os = "macos", any(test, feature = "test-support")))]
#[cfg_attr(not(test), allow(dead_code))]
fn macos_process_identity(snapshot: Option<MacosKinfo>) -> Option<ProcessIdentity> {
let info = snapshot?;
Some(ProcessIdentity {
start_time: info.started_at_us?,
boot_id: None,
exited: info.has_exited(),
})
}
#[rustfmt::skip]
test_support_visibility! {
#[cfg(target_os = "macos")]
fn process_identity(pid: u32) -> Option<ProcessIdentity> {
macos_process_identity(macos_kinfo(pid))
}
}
#[cfg(windows)]
fn process_identity(pid: u32) -> Option<ProcessIdentity> {
windows_process_creation_time(pid)
.ok()
.flatten()
.map(|start_time| ProcessIdentity {
start_time,
boot_id: None,
exited: false,
})
}
pub fn speech_process_identity(pid: u32) -> Option<String> {
let identity = process_identity(pid)?;
if identity.exited {
return None;
}
#[cfg(target_os = "linux")]
let boot = identity.boot_id?;
#[cfg(target_os = "macos")]
let boot = crate::volume::boot_id()?;
#[cfg(windows)]
let boot = speech_windows_boot_id()?;
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
let boot = return None;
Some(format!(
"{}:{boot}:{}",
std::env::consts::OS,
identity.start_time
))
}
#[cfg(windows)]
fn speech_windows_boot_id() -> Option<String> {
#[repr(C)]
struct BootInfo {
id: [u8; 16],
firmware: u32,
flags: u64,
}
#[link(name = "ntdll")]
unsafe extern "system" {
#[link_name = "NtQuerySystemInformation"]
fn nt_query_system_information(
class: u32,
buffer: *mut std::ffi::c_void,
length: u32,
returned: *mut u32,
) -> i32;
}
let mut info = BootInfo {
id: [0; 16],
firmware: 0,
flags: 0,
};
let mut returned = 0;
let status = unsafe {
nt_query_system_information(
90,
(&mut info as *mut BootInfo).cast(),
std::mem::size_of::<BootInfo>() as u32,
&mut returned,
)
};
if status < 0 || returned < 16 || info.id == [0; 16] {
return None;
}
Some(info.id.iter().map(|byte| format!("{byte:02x}")).collect())
}
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
fn process_identity(_pid: u32) -> Option<ProcessIdentity> {
None
}
#[cfg(all(any(test, feature = "test-support"), target_os = "macos"))]
unsafe extern "C" {
pub fn proc_pidinfo(
pid: libc::c_int,
flavor: libc::c_int,
arg: u64,
buffer: *mut libc::c_void,
buffersize: libc::c_int,
) -> libc::c_int;
}
#[cfg(unix)]
pub fn process_alive(pid: u32) -> bool {
if pid == 0 || pid > i32::MAX as u32 {
return false;
}
let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
if result == 0 {
return true;
}
io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
}
#[cfg(windows)]
pub fn process_alive(pid: u32) -> bool {
windows_process_creation_time(pid).map_or(true, |created| created.is_some())
}
#[cfg(windows)]
fn windows_process_creation_time(pid: u32) -> io::Result<Option<u64>> {
use windows_sys::Win32::Foundation::{
CloseHandle, ERROR_INVALID_PARAMETER, FILETIME, WAIT_OBJECT_0, WAIT_TIMEOUT,
};
use windows_sys::Win32::System::Threading::{
GetProcessTimes, OpenProcess, WaitForSingleObject, PROCESS_QUERY_LIMITED_INFORMATION,
};
if pid == 0 {
return Ok(None);
}
const SYNCHRONIZE_RIGHT: u32 = 0x0010_0000;
let handle = unsafe {
OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE_RIGHT,
0,
pid,
)
};
if handle.is_null() {
let error = io::Error::last_os_error();
return if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
Ok(None)
} else {
Err(error)
};
}
struct ProcessHandle(windows_sys::Win32::Foundation::HANDLE);
impl Drop for ProcessHandle {
fn drop(&mut self) {
unsafe {
CloseHandle(self.0);
}
}
}
let handle = ProcessHandle(handle);
match unsafe { WaitForSingleObject(handle.0, 0) } {
WAIT_OBJECT_0 => return Ok(None),
WAIT_TIMEOUT => {}
_ => return Err(io::Error::last_os_error()),
}
let mut created = FILETIME {
dwLowDateTime: 0,
dwHighDateTime: 0,
};
let mut exited = created;
let mut kernel = created;
let mut user = created;
if unsafe { GetProcessTimes(handle.0, &mut created, &mut exited, &mut kernel, &mut user) } == 0
{
return Err(io::Error::last_os_error());
}
Ok(Some(
(u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime),
))
}
#[cfg(windows)]
pub(crate) fn windows_process_start_time_ms(pid: u32) -> Option<u64> {
windows_creation_ticks_to_unix_ms(windows_process_creation_time(pid).ok().flatten()?)
}
#[cfg(windows)]
fn windows_creation_ticks_to_unix_ms(ticks: u64) -> Option<u64> {
const UNIX_EPOCH_FILETIME: u64 = 116_444_736_000_000_000;
ticks
.checked_sub(UNIX_EPOCH_FILETIME)
.map(|ticks| ticks / 10_000)
}
#[cfg(not(any(unix, windows)))]
pub fn process_alive(_pid: u32) -> bool {
true
}
#[cfg(any(test, feature = "test-support"))]
pub mod retry_clock {
use super::*;
struct State {
started: Instant,
now: Instant,
preparation_delay: Duration,
sleeps: Vec<Duration>,
attempts: usize,
}
thread_local! {
static CLOCK: std::cell::RefCell<Option<State>> = const { std::cell::RefCell::new(None) };
}
pub struct Guard;
impl Guard {
pub fn install(preparation_delay: Duration) -> Self {
CLOCK.with(|clock| {
let mut clock = clock.borrow_mut();
assert!(clock.is_none(), "retry clock already installed");
let started = Instant::now();
*clock = Some(State {
started,
now: started,
preparation_delay,
sleeps: Vec::new(),
attempts: 0,
});
});
Self
}
pub fn observations(&self) -> (Duration, Vec<Duration>, usize) {
CLOCK.with(|clock| {
let clock = clock.borrow();
let state = clock.as_ref().unwrap();
(
state.now - state.started,
state.sleeps.clone(),
state.attempts,
)
})
}
}
impl Drop for Guard {
fn drop(&mut self) {
CLOCK.with(|clock| *clock.borrow_mut() = None);
}
}
pub fn now() -> Option<Instant> {
CLOCK.with(|clock| clock.borrow().as_ref().map(|state| state.now))
}
pub fn before_acquire() {
CLOCK.with(|clock| {
if let Some(state) = clock.borrow_mut().as_mut() {
state.now += std::mem::take(&mut state.preparation_delay);
}
});
}
pub fn note_attempt() {
CLOCK.with(|clock| {
if let Some(state) = clock.borrow_mut().as_mut() {
state.attempts += 1;
}
});
}
pub fn sleep(duration: Duration) -> bool {
CLOCK.with(|clock| {
let mut clock = clock.borrow_mut();
let Some(state) = clock.as_mut() else {
return false;
};
state.sleeps.push(duration);
state.now += duration;
assert!(
state.sleeps.len() <= 1_000,
"retry loop ignored its deadline"
);
true
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::BufRead as _;
use std::io::Write;
use std::process::Child;
use std::process::ChildStdin;
use std::process::Stdio;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use std::sync::Arc;
use std::sync::Barrier;
#[cfg(target_os = "linux")]
#[test]
#[ignore = "opt-in live-owner wait CPU measurement"]
fn measurement_live_owner_wait_cpu() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("held.lock");
let _owner = acquire(&path).unwrap();
let sleeps = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let _observer = observe_retry_sleeps_for_test(Arc::clone(&sleeps));
let cpu = || {
let mut time = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
assert_eq!(
unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut time) },
0
);
time.tv_sec as f64 + time.tv_nsec as f64 / 1e9
};
let cpu_started = cpu();
let started = Instant::now();
assert!(matches!(
try_acquire(&path, Duration::from_millis(1050)),
Err(AcquireError::Timeout)
));
eprintln!(
"LOCK_WAIT_MEASUREMENT poll_ms={} sleeps={} wall_ms={:.3} thread_cpu_ms={:.3}",
POLL_INTERVAL_MS,
sleeps.load(Ordering::SeqCst),
started.elapsed().as_secs_f64() * 1000.0,
(cpu() - cpu_started) * 1000.0
);
assert!(sleeps.load(Ordering::SeqCst) > 0);
}
#[test]
fn live_owner_poll_sleeps_to_the_original_deadline() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("held.lock");
let _owner = acquire(&path).unwrap();
let clock = retry_clock::Guard::install(Duration::ZERO);
assert!(matches!(
try_acquire(&path, Duration::from_millis(1050)),
Err(AcquireError::Timeout)
));
let (elapsed, sleeps, attempts) = clock.observations();
assert_eq!(elapsed, Duration::from_millis(1050));
assert_eq!(attempts, 11);
let mut expected = vec![Duration::from_millis(100); 10];
expected.push(Duration::from_millis(50));
assert_eq!(sleeps, expected);
}
fn macos_snapshot_bytes(state: u8, flags: u32) -> [u8; 648] {
let mut bytes = [0; 648];
bytes[0..8].copy_from_slice(&1_700_000_000_i64.to_ne_bytes());
bytes[8..12].copy_from_slice(&123_456_i32.to_ne_bytes());
bytes[32..36].copy_from_slice(&flags.to_ne_bytes());
bytes[36] = state;
bytes[243..248].copy_from_slice(b"owner");
bytes[392..396].copy_from_slice(&42_u32.to_ne_bytes());
bytes[564..568].copy_from_slice(&123_i32.to_ne_bytes());
bytes
}
#[test]
fn semantic_batch_lease_macos_snapshot_keeps_birth_and_exit_phase() {
let info = decode_macos_kinfo(&macos_snapshot_bytes(SZOMB, P_WEXIT)).unwrap();
assert_eq!(info.comm, "owner");
assert_eq!((info.ruid, info.pgid), (42, 123));
assert_eq!(info.exit_state(), MacosExitState::Zombie);
let identity = macos_process_identity(Some(info)).unwrap();
assert_eq!(identity.start_time, 1_700_000_000_123_456);
assert!(identity.exited);
assert!(identity.boot_id.is_none());
let exiting = decode_macos_kinfo(&macos_snapshot_bytes(2, P_WEXIT)).unwrap();
assert_eq!(exiting.exit_state(), MacosExitState::Exiting);
assert!(macos_process_identity(Some(exiting)).unwrap().exited);
let running = decode_macos_kinfo(&macos_snapshot_bytes(2, 0)).unwrap();
assert_eq!(running.exit_state(), MacosExitState::NotExiting);
assert!(!macos_process_identity(Some(running)).unwrap().exited);
}
#[test]
fn semantic_batch_lease_macos_missing_identity_stays_inconclusive() {
assert!(macos_process_identity(None).is_none());
let mut bytes = macos_snapshot_bytes(SZOMB, P_WEXIT);
assert!(decode_macos_kinfo(&bytes[..16]).is_none());
bytes[8..12].copy_from_slice(&1_000_000_i32.to_ne_bytes());
assert!(macos_process_identity(decode_macos_kinfo(&bytes)).is_none());
bytes[8..12].copy_from_slice(&0_i32.to_ne_bytes());
bytes[0..8].copy_from_slice(&0_i64.to_ne_bytes());
assert!(macos_process_identity(decode_macos_kinfo(&bytes)).is_none());
}
#[cfg(unix)]
#[test]
fn advisory_lock_guard_releases_lock_with_a_live_duplicate() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("advisory.lock");
for shared in [true, false] {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
.unwrap();
if shared {
file.lock_shared().unwrap();
} else {
file.lock().unwrap();
}
let duplicate = file.try_clone().unwrap();
let guard = AdvisoryLockGuard::from_locked_file(file);
let probe = OpenOptions::new()
.read(true)
.write(true)
.open(&path)
.unwrap();
assert!(matches!(
probe.try_lock(),
Err(fs::TryLockError::WouldBlock)
));
drop(guard);
probe
.try_lock()
.expect("the owner released exclusion even with a live duplicate");
assert!(duplicate.metadata().is_ok());
probe.unlock().unwrap();
}
}
#[cfg(windows)]
#[test]
fn windows_native_process_probe_records_creation_identity() {
let pid = std::process::id();
let identity = process_identity(pid).expect("current Windows process creation identity");
assert!(identity.start_time > 0);
assert!(windows_process_start_time_ms(pid).unwrap() > 0);
assert_eq!(
windows_creation_ticks_to_unix_ms(116_444_736_000_000_000),
Some(0)
);
assert_eq!(
windows_creation_ticks_to_unix_ms(116_444_736_010_000_000),
Some(1000)
);
assert_eq!(windows_creation_ticks_to_unix_ms(0), None);
assert!(process_alive(pid));
assert!(!process_alive(0));
assert!(!process_alive(u32::MAX));
let mut metadata = current_process_metadata();
metadata.process_start_time = Some(identity.start_time.saturating_add(1));
assert!(
!lock_owner_is_alive(&metadata),
"recycled PID must not keep an old lease alive"
);
}
#[cfg(windows)]
#[test]
fn windows_native_process_probe_recognizes_exited_status_259() {
let mut child = std::process::Command::new("cmd.exe")
.args(["/C", "exit 259"])
.spawn()
.unwrap();
let pid = child.id();
assert_eq!(child.wait().unwrap().code(), Some(259));
assert!(
!process_alive(pid),
"a signaled process object is exited even when its exit code is STILL_ACTIVE"
);
}
#[test]
fn malformed_reclaim_preserves_replacement_epoch() {
let (_dir, path) = test_lock_path();
fs::write(&path, b"malformed").unwrap();
let replacement = synthetic_metadata(std::process::id(), current_hostname(), now_ms());
let expected_epoch = replacement.writer_epoch.clone();
let replace_path = path.clone();
BEFORE_MALFORMED_RECLAIM.with(|slot| {
*slot.borrow_mut() = Some(Box::new(move || {
fs::remove_file(&replace_path).unwrap();
write_synthetic_lock(&replace_path, &replacement);
}))
});
let result = acquire_with_config(&path, Some(Duration::from_millis(100)), test_config());
assert!(
matches!(result, Err(AcquireError::Timeout)),
"replacement owner must block acquisition"
);
assert_eq!(
read_lock_metadata(&path).unwrap().writer_epoch,
expected_epoch
);
}
#[test]
fn heartbeat_spawn_failure_removes_own_lock() {
let (_dir, path) = test_lock_path();
BEFORE_HEARTBEAT_SPAWN_FAILURE.with(|slot| *slot.borrow_mut() = Some(Box::new(|| {})));
assert!(create_new_lock(&path, ¤t_hostname(), test_config()).is_err());
assert!(
!path.exists(),
"failed acquisition must not leave a live-PID lock"
);
drop(create_new_lock(&path, ¤t_hostname(), test_config()).unwrap());
}
#[test]
fn heartbeat_spawn_failure_preserves_replacement_lock() {
let (_dir, path) = test_lock_path();
let replacement = synthetic_metadata(std::process::id(), current_hostname(), now_ms());
let expected_epoch = replacement.writer_epoch.clone();
let replace_path = path.clone();
BEFORE_HEARTBEAT_SPAWN_FAILURE.with(|slot| {
*slot.borrow_mut() = Some(Box::new(move || {
fs::remove_file(&replace_path).unwrap();
write_synthetic_lock(&replace_path, &replacement);
}))
});
assert!(create_new_lock(&path, ¤t_hostname(), test_config()).is_err());
assert_eq!(
read_lock_metadata(&path).unwrap().writer_epoch,
expected_epoch
);
}
#[cfg(unix)]
#[test]
fn unreadable_lock_metadata_is_retried_as_contention_not_propagated() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("cache.lock");
std::fs::write(&path, b"{}\n").expect("seed lock file");
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000))
.expect("deny reads");
if std::fs::read(&path).is_ok() {
return;
}
let outcome = try_acquire(&path, Duration::from_millis(250));
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).ok();
match outcome {
Err(AcquireError::Timeout) => {}
Err(AcquireError::Io(error)) => {
panic!("contended metadata read propagated instead of retrying: {error:?}")
}
Ok(_) => panic!("acquired a lock whose metadata could not be read"),
}
}
const HARNESS_TEST: &str = "fs_lock::tests::fs_lock_separate_process_harness";
const HARNESS_MODE_INSPECT: &str = "inspect";
fn test_config() -> LockConfig {
LockConfig {
heartbeat_interval_ms: 25,
heartbeat_refresh_interval_ms: 25,
stale_heartbeat_ms: 2_000,
live_owner_warn_ms: LIVE_OWNER_WARN_MS,
poll_interval_ms: 10,
}
}
fn test_lock_path() -> (tempfile::TempDir, PathBuf) {
let dir = tempfile::tempdir().expect("create temp dir");
let path = dir.path().join("test.lock");
(dir, path)
}
fn write_synthetic_lock(path: &Path, metadata: &LockMetadata) {
let mut file = open_new_lock_file(path).expect("create synthetic lock");
write_lock_metadata_to_file(&mut file, metadata).expect("write synthetic lock");
}
#[derive(Serialize)]
struct LegacyLockMetadata<'a> {
pid: u32,
hostname: &'a str,
created_at_ms: u64,
heartbeat_at_ms: u64,
writer_epoch: &'a str,
}
fn write_legacy_lock(path: &Path, metadata: &LockMetadata) -> String {
let legacy = LegacyLockMetadata {
pid: metadata.pid,
hostname: &metadata.hostname,
created_at_ms: metadata.created_at_ms,
heartbeat_at_ms: metadata.heartbeat_at_ms,
writer_epoch: &metadata.writer_epoch,
};
let contents = format!(
"{}\n",
serde_json::to_string(&legacy).expect("serialize legacy lock")
);
fs::write(path, &contents).expect("write legacy synthetic lock");
contents
}
fn synthetic_metadata(pid: u32, hostname: String, created_at_ms: u64) -> LockMetadata {
LockMetadata {
pid,
hostname,
process_start_time: None,
boot_id: None,
created_at_ms,
heartbeat_at_ms: created_at_ms,
writer_epoch: format!("synthetic-{pid}-{created_at_ms}"),
}
}
fn current_process_metadata() -> LockMetadata {
let now = now_ms();
let pid = std::process::id();
let process_identity = process_identity(pid);
let mut metadata = synthetic_metadata(pid, current_hostname(), now);
metadata.process_start_time = process_identity
.as_ref()
.map(|identity| identity.start_time);
metadata.boot_id = process_identity.and_then(|identity| identity.boot_id);
metadata
}
fn different_start_time(start_time: u64) -> u64 {
start_time.checked_add(1).unwrap_or(start_time - 1)
}
fn write_reclaim_token(lock_path: &Path, metadata: &LockMetadata) -> PathBuf {
let token_path = reclaim_token_path(lock_path);
write_synthetic_lock(&token_path, metadata);
token_path
}
fn take_reclaim_test_logs() -> Vec<String> {
RECLAIM_TEST_LOGS.with(|logs| std::mem::take(&mut *logs.borrow_mut()))
}
#[test]
fn lock_operation_trace_lines_are_debug_not_info() {
let source = include_str!("fs_lock.rs");
assert!(source.contains("slog_debug!(\"acquired filesystem lock at {}\", path.display())"));
assert!(
source.contains("slog_debug!(\"released filesystem lock at {}\", self.path.display())")
);
assert!(!source.contains("slog_info!(\"acquired filesystem lock at {}\", path.display())"));
assert!(
!source.contains("slog_info!(\"released filesystem lock at {}\", self.path.display())")
);
}
#[test]
fn acquire_creates_lockfile_and_unlocks_on_drop() {
let (_dir, path) = test_lock_path();
let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
let metadata = read_lock_metadata(&path).expect("read lock metadata");
assert_eq!(metadata.pid, std::process::id());
assert_eq!(metadata.hostname, current_hostname());
assert_eq!(metadata.created_at_ms, guard.metadata.created_at_ms);
assert_eq!(metadata.writer_epoch, guard.metadata.writer_epoch);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
}
drop(guard);
assert!(!path.exists());
}
#[test]
fn permission_denied_is_treated_as_transient_create_contention() {
let err = io::Error::from(io::ErrorKind::PermissionDenied);
assert!(is_transient_create_contention(&err));
}
#[test]
fn unrelated_io_errors_are_not_treated_as_contention() {
let err = io::Error::from(io::ErrorKind::NotFound);
assert!(!is_transient_create_contention(&err));
}
#[cfg(windows)]
#[test]
fn windows_sharing_violation_is_treated_as_transient_create_contention() {
let err = io::Error::from_raw_os_error(32);
assert!(is_transient_create_contention(&err));
}
#[test]
fn reclaim_refuses_to_delete_a_different_owners_lock() {
let (_dir, path) = test_lock_path();
let owner_b = synthetic_metadata(4242, "host-b".to_string(), now_ms());
create_lock_file_atomically(&path, &owner_b).expect("write owner B lock");
let judged_a = synthetic_metadata(1111, "host-a".to_string(), now_ms() - 1_000_000);
let outcome = reclaim_lock_file(&path, &judged_a).expect("reclaim");
assert!(
matches!(outcome, ReclaimResult::Unchanged),
"must not remove a different owner's lock"
);
assert!(path.exists(), "owner B's lock must survive");
let still = read_lock_metadata(&path).expect("still readable");
assert_eq!(still.pid, 4242, "owner B's lock intact");
}
#[test]
fn reclaim_deletes_when_identity_still_matches() {
let (_dir, path) = test_lock_path();
let owner = synthetic_metadata(1111, "host-a".to_string(), 5_000);
create_lock_file_atomically(&path, &owner).expect("write lock");
let outcome = reclaim_lock_file(&path, &owner).expect("reclaim");
assert!(
matches!(outcome, ReclaimResult::Removed),
"matching-identity stale lock should be removed"
);
assert!(!path.exists());
assert!(matches!(
reclaim_lock_file(&path, &owner).expect("reclaim missing"),
ReclaimResult::Unchanged
));
}
#[test]
fn try_acquire_once_reclaims_malformed_after_one_grace_read() {
for contents in [
b"".as_slice(),
b"{\"pid\":999999999,\"hostname\":".as_slice(),
] {
let (_dir, path) = test_lock_path();
fs::write(&path, contents).unwrap();
let sleeper_entries = Arc::new(AtomicUsize::new(0));
let _observer = observe_retry_sleeps_for_test(Arc::clone(&sleeper_entries));
let guard = try_acquire_once(&path).expect("stable malformed lease must be reclaimed");
assert!(guard.verify_writer_epoch().unwrap());
assert_eq!(sleeper_entries.load(Ordering::SeqCst), 1);
}
}
#[test]
fn try_acquire_once_malformed_reclaim_stops_when_token_is_held() {
let (_dir, path) = test_lock_path();
fs::write(&path, b"malformed").unwrap();
write_reclaim_token(&path, ¤t_process_metadata());
let sleeper_entries = Arc::new(AtomicUsize::new(0));
let _observer = observe_retry_sleeps_for_test(Arc::clone(&sleeper_entries));
assert!(matches!(
try_acquire_once(&path),
Err(AcquireError::Timeout)
));
assert_eq!(sleeper_entries.load(Ordering::SeqCst), 1);
assert_eq!(fs::read(&path).unwrap(), b"malformed");
}
#[test]
fn try_acquire_once_malformed_reclaim_preserves_live_replacement() {
let (_dir, path) = test_lock_path();
fs::write(&path, b"malformed").unwrap();
let replacement = current_process_metadata();
let expected_epoch = replacement.writer_epoch.clone();
let replace_path = path.clone();
BEFORE_MALFORMED_RECLAIM.with(|slot| {
*slot.borrow_mut() = Some(Box::new(move || {
fs::remove_file(&replace_path).unwrap();
write_synthetic_lock(&replace_path, &replacement);
}))
});
assert!(matches!(
try_acquire_once(&path),
Err(AcquireError::Timeout)
));
assert_eq!(
read_lock_metadata(&path).unwrap().writer_epoch,
expected_epoch
);
}
#[test]
fn try_acquire_once_never_waits_behind_live_owner() {
const OUTER_THREAD_JOIN_TIMEOUT: Duration = Duration::from_secs(30);
let (_dir, path) = test_lock_path();
let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
let contender_path = path.clone();
let sleeper_entries = Arc::new(AtomicUsize::new(0));
let contender_sleeper_entries = Arc::clone(&sleeper_entries);
let (announced_tx, announced_rx) = mpsc::sync_channel(1);
let (enter_tx, enter_rx) = mpsc::sync_channel::<()>(1);
let (result_tx, result_rx) = mpsc::sync_channel(1);
let contender = std::thread::spawn(move || {
let _ = announced_tx.send(());
let _ = enter_rx.recv();
let _observer = observe_retry_sleeps_for_test(contender_sleeper_entries);
let _ = result_tx.send(try_acquire_once(&contender_path));
});
announced_rx
.recv_timeout(OUTER_THREAD_JOIN_TIMEOUT)
.expect("contender should announce before the controlled enter gate");
enter_tx
.send(())
.expect("contender should wait at the controlled enter gate");
let result = match result_rx.recv_timeout(OUTER_THREAD_JOIN_TIMEOUT) {
Ok(result) => result,
Err(error) => {
drop(guard);
let _ = result_rx.recv_timeout(OUTER_THREAD_JOIN_TIMEOUT);
let _ = contender.join();
panic!("contender did not finish before the outer join bound: {error}");
}
};
contender.join().expect("contender should exit");
assert!(matches!(result, Err(AcquireError::Timeout)));
assert_eq!(
sleeper_entries.load(Ordering::SeqCst),
0,
"zero-timeout acquisition must return Timeout without sleeping"
);
}
#[test]
fn acquire_serializes_concurrent_callers() {
let (_dir, path) = test_lock_path();
let path = Arc::new(path);
let barrier = Arc::new(Barrier::new(3));
let inside = Arc::new(AtomicUsize::new(0));
let entered = Arc::new(AtomicUsize::new(0));
let max_inside = Arc::new(AtomicUsize::new(0));
let mut handles = Vec::new();
for _ in 0..2 {
let path = Arc::clone(&path);
let barrier = Arc::clone(&barrier);
let inside = Arc::clone(&inside);
let entered = Arc::clone(&entered);
let max_inside = Arc::clone(&max_inside);
handles.push(thread::spawn(move || {
barrier.wait();
let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
.expect("thread acquire lock");
let previous = inside.fetch_add(1, Ordering::SeqCst);
assert_eq!(previous, 0, "two lock holders overlapped");
entered.fetch_add(1, Ordering::SeqCst);
max_inside.fetch_max(previous + 1, Ordering::SeqCst);
thread::sleep(Duration::from_millis(75));
inside.fetch_sub(1, Ordering::SeqCst);
drop(guard);
}));
}
barrier.wait();
for handle in handles {
handle.join().expect("join worker");
}
assert_eq!(entered.load(Ordering::SeqCst), 2);
assert_eq!(max_inside.load(Ordering::SeqCst), 1);
assert!(!path.exists());
}
#[test]
fn failed_atomic_replacement_preserves_existing_destination() {
let dir = tempfile::tempdir().expect("create temp dir");
let source = dir.path().join("source.tmp");
let destination = dir.path().join("artifact.bin");
fs::write(&source, b"new artifact").expect("write source");
fs::write(&destination, b"valid old artifact").expect("write destination");
let error = rename_over_with(&source, &destination, |_from, _to| {
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"injected replacement failure",
))
})
.expect_err("replacement must fail");
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
assert_eq!(
fs::read(&destination).expect("read preserved destination"),
b"valid old artifact"
);
assert_eq!(
fs::read(&source).expect("read retained source"),
b"new artifact"
);
}
const LEDGER_LEASES: usize = 8;
const LEDGER_BEATS_PER_LEASE: usize = (60_000 / HEARTBEAT_INTERVAL_MS) as usize;
fn create_owned_lock(path: &Path) -> LockMetadata {
let metadata = current_process_metadata();
create_lock_file_atomically(path, &metadata).expect("create lock");
metadata
}
#[cfg(unix)]
fn inode(path: &Path) -> u64 {
use std::os::unix::fs::MetadataExt;
fs::metadata(path).expect("lock metadata").ino()
}
#[test]
fn healthy_refresh_cadence_does_not_trigger_stale_warning() {
let config = LockConfig::default();
assert_eq!(config.live_owner_warning_age_ms(), 30_000);
assert_eq!(config.cross_host_stale_heartbeat_ms(), 75_000);
assert_eq!(test_config().live_owner_warning_age_ms(), 2_000);
}
#[test]
fn idle_writer_lease_writes_twice_in_sixty_seconds() {
let (_dir, path) = test_lock_path();
let owner = create_owned_lock(&path);
let (pump, _handle) = HeartbeatPump::attach(&path, &owner).unwrap();
let config = LockConfig::default();
let start = Instant::now();
let interval = Duration::from_millis(config.heartbeat_refresh_interval_ms);
let mut next = start + interval;
let bytes = fs::metadata(&path).unwrap().len();
let _ = io_ledger::take();
let mut writes = 0;
for seconds in (5..=60).step_by(5) {
writes += usize::from(
refresh_heartbeat_if_due(
&pump,
&mut next,
interval,
start + Duration::from_secs(seconds),
)
.unwrap(),
);
}
let ledger = io_ledger::take();
assert_eq!(writes, 2, "one idle lease must write at 25s and 50s only");
assert_eq!(ledger.bytes_written, bytes * 2);
assert_eq!(
(ledger.file_syncs, ledger.dir_syncs, ledger.new_files),
(0, 0, 0)
);
eprintln!("idle writer lease / virtual 60s: before=12 after={writes} {ledger:?}");
unregister_lease_slot(pump.slot, &path);
}
#[test]
fn delayed_refresh_preserves_live_owner_and_foreign_freshness() {
let (_dir, path) = test_lock_path();
let mut owner = create_owned_lock(&path);
let now = now_ms();
owner.heartbeat_at_ms = now - 65_000;
fs::write(&path, lock_metadata_bytes(&owner).unwrap()).unwrap();
let config = LockConfig::default();
assert_eq!(config.cross_host_stale_heartbeat_ms(), 75_000);
assert!(metadata_blocks_acquisition(
&owner,
"foreign-observer",
config,
now
));
assert!(metadata_blocks_acquisition(
&owner,
&owner.hostname,
config,
now + 3_600_000
));
let (pump, _handle) = HeartbeatPump::attach(&path, &owner).unwrap();
let wake = Instant::now();
let mut next = wake - Duration::from_secs(40);
assert!(refresh_heartbeat_if_due(&pump, &mut next, Duration::from_secs(25), wake).unwrap());
let refreshed = read_lock_metadata(&path).unwrap();
assert!(refreshed.heartbeat_at_ms >= now);
assert!(metadata_blocks_acquisition(
&refreshed,
"foreign-observer",
config,
now + 70_000
));
unregister_lease_slot(pump.slot, &path);
}
#[test]
fn failed_refresh_retries_on_next_short_wake() {
let (_dir, path) = test_lock_path();
let owner = create_owned_lock(&path);
let (pump, _handle) = HeartbeatPump::attach(&path, &owner).unwrap();
let wake = Instant::now();
let mut next = wake;
fs::write(&path, b"partial").unwrap();
assert!(refresh_heartbeat_if_due(&pump, &mut next, Duration::from_secs(25), wake).is_err());
assert_eq!(next, wake, "a failed write must not postpone the retry");
fs::write(&path, lock_metadata_bytes(&owner).unwrap()).unwrap();
assert!(refresh_heartbeat_if_due(
&pump,
&mut next,
Duration::from_secs(25),
wake + Duration::from_secs(5)
)
.unwrap());
unregister_lease_slot(pump.slot, &path);
}
#[test]
fn heartbeat_ledger_for_sixty_seconds_has_no_fsync_and_no_new_inodes() {
let dir = tempfile::tempdir().expect("create temp dir");
let leases = (0..LEDGER_LEASES)
.map(|index| {
let path = dir.path().join(format!("writer-{index}.lease"));
let owner = create_owned_lock(&path);
(path, owner)
})
.collect::<Vec<_>>();
#[cfg(unix)]
let inodes_before = leases
.iter()
.map(|(path, _)| inode(path))
.collect::<Vec<_>>();
let file_bytes: u64 = leases
.iter()
.map(|(path, _)| fs::metadata(path).expect("lock size").len())
.sum();
let _ = io_ledger::take();
for _ in 0..LEDGER_BEATS_PER_LEASE {
for (path, owner) in &leases {
heartbeat_once(path, owner, &Mutex::new(None)).expect("heartbeat");
}
}
let ledger = io_ledger::take();
eprintln!(
"fs_lock heartbeat ledger: leases={LEDGER_LEASES} beats_per_lease={LEDGER_BEATS_PER_LEASE} {ledger:?}"
);
assert_eq!(ledger.file_syncs, 0, "heartbeats must not fsync the lease");
assert_eq!(
ledger.dir_syncs, 0,
"heartbeats must not fsync the directory"
);
assert_eq!(ledger.new_files, 0, "heartbeats must rewrite in place");
assert_eq!(
ledger.bytes_written,
file_bytes * LEDGER_BEATS_PER_LEASE as u64,
"each beat rewrites exactly one lease's bytes"
);
#[cfg(unix)]
assert_eq!(
leases
.iter()
.map(|(path, _)| inode(path))
.collect::<Vec<_>>(),
inodes_before,
"heartbeats must keep the lease inode"
);
for (path, owner) in &leases {
let current = read_lock_metadata(path).expect("read lease");
assert!(lock_identity_matches(¤t, owner));
assert!(current.heartbeat_at_ms >= owner.heartbeat_at_ms);
}
}
#[test]
fn durability_lease_create_and_reclaim_unsynced() {
let (_dir, path) = test_lock_path();
let _ = io_ledger::take();
crate::durability::take();
let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
.expect("create lease");
let created = io_ledger::take();
drop(guard);
assert_eq!(
(created.file_syncs, created.dir_syncs, created.new_files),
(0, 0, 1),
"lease creation must not sync: {created:?}"
);
assert_eq!(crate::durability::sync_count(&crate::durability::take()), 0);
let dead = synthetic_metadata(999_999_999, current_hostname(), now_ms());
write_synthetic_lock(&path, &dead);
let _ = io_ledger::take();
crate::durability::take();
let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
.expect("reclaim dead lease");
let reclaimed = io_ledger::take();
drop(guard);
assert_eq!(
(
reclaimed.file_syncs,
reclaimed.dir_syncs,
reclaimed.new_files
),
(0, 0, 3),
"lease reclaim must not sync: {reclaimed:?}"
);
assert_eq!(crate::durability::sync_count(&crate::durability::take()), 0);
}
const DAEMON_SCALE_LEASES: usize = 200;
fn assert_beat_opens_no_descriptor(beat: &io_ledger::IoLedger) {
assert_eq!(
(beat.opens, beat.closes),
(0, 0),
"a beat must write through the kept handle, without opening or \
closing a descriptor: {beat:?}"
);
}
#[test]
fn daemon_scale_heartbeats_keep_descriptors_open_between_beats() {
let dir = tempfile::tempdir().expect("create temp dir");
let _ = io_ledger::take();
let guards = (0..DAEMON_SCALE_LEASES)
.map(|index| {
acquire_with_config(
&dir.path().join(format!("root-{index}.writer.lease")),
Some(Duration::from_secs(2)),
test_config(),
)
.expect("acquire live lease")
})
.collect::<Vec<_>>();
let setup = io_ledger::take();
assert_eq!(
setup.closes, 0,
"acquiring a fresh lease must not close a descriptor: {setup:?}"
);
let beats = 3;
let _ = io_ledger::take();
for _ in 0..beats {
for guard in &guards {
guard.heartbeat_once().expect("beat");
}
}
let beat_cost = io_ledger::take();
eprintln!(
"fs_lock heartbeat cost: leases={DAEMON_SCALE_LEASES} beats_per_lease={beats} \
opens={} closes={} bytes={} (open+close per beat would be opens={} closes={})",
beat_cost.opens,
beat_cost.closes,
beat_cost.bytes_written,
DAEMON_SCALE_LEASES * beats,
DAEMON_SCALE_LEASES * beats,
);
assert_beat_opens_no_descriptor(&beat_cost);
assert!(beat_cost.bytes_written > 0, "{beat_cost:?}");
for guard in &guards {
let current = read_lock_metadata(guard.path()).expect("read lease");
assert!(lock_identity_matches(¤t, &guard.metadata));
}
drop(guards);
let released = io_ledger::take();
assert!(
released.closes >= DAEMON_SCALE_LEASES as u64,
"each live lease closes its handle once, at release: {released:?}"
);
}
#[test]
fn zero_length_lease_is_treated_as_stale() {
let (_dir, path) = test_lock_path();
fs::write(&path, b"").expect("write empty lease");
let owner = current_process_metadata();
assert!(matches!(
heartbeat_once(&path, &owner, &Mutex::new(None)),
Err(HeartbeatError::Malformed(_))
));
assert!(!heartbeat_error_is_terminal(&HeartbeatError::Malformed(
serde_json::from_slice::<LockMetadata>(b"").unwrap_err()
)));
let guard = acquire_with_config(&path, Some(Duration::from_secs(2)), test_config())
.expect("empty lease must be reclaimed");
assert!(guard.verify_writer_epoch().expect("verify new owner"));
}
#[test]
fn heartbeat_length_change_falls_back_to_unsynced_rename() {
let (_dir, path) = test_lock_path();
let mut owner = current_process_metadata();
owner.heartbeat_at_ms = 7;
create_lock_file_atomically(&path, &owner).expect("create lock");
let _ = io_ledger::take();
heartbeat_once(&path, &owner, &Mutex::new(None)).expect("heartbeat");
let ledger = io_ledger::take();
assert_eq!((ledger.file_syncs, ledger.dir_syncs), (0, 0), "{ledger:?}");
assert_eq!(ledger.new_files, 1, "{ledger:?}");
let current = read_lock_metadata(&path).expect("read lease");
assert!(lock_identity_matches(¤t, &owner));
assert!(current.heartbeat_at_ms > 7);
let leftovers = fs::read_dir(path.parent().unwrap()).unwrap().count();
assert_eq!(leftovers, 1, "temp file must not be left behind");
}
#[test]
fn heartbeat_updates_lockfile_timestamp() {
let (_dir, path) = test_lock_path();
let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
let initial_metadata = read_lock_metadata(&path).expect("read initial metadata");
let initial = initial_metadata.heartbeat_at_ms;
let deadline = std::time::Instant::now() + Duration::from_millis(2_000);
let mut updated = initial;
while std::time::Instant::now() < deadline {
thread::sleep(Duration::from_millis(50));
match read_lock_metadata(&path) {
Ok(meta) => {
updated = meta.heartbeat_at_ms;
if updated > initial {
break;
}
}
Err(ReadLockError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
continue;
}
Err(other) => panic!("read updated metadata: {other:?}"),
}
}
assert!(
updated > initial,
"heartbeat timestamp did not advance within 2s"
);
let updated_metadata = read_lock_metadata(&path).expect("read final metadata");
assert_eq!(
updated_metadata.process_start_time, guard.metadata.process_start_time,
"heartbeat rewrite must preserve the owner's process start time"
);
assert_eq!(
updated_metadata.boot_id, guard.metadata.boot_id,
"heartbeat rewrite must preserve the owner's boot identity"
);
drop(guard);
}
#[test]
fn dead_pid_lock_is_reclaimed() {
let (_dir, path) = test_lock_path();
let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
write_synthetic_lock(&path, &metadata);
let (guard, lines) = crate::logging::capture_log_lines(|| {
acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
.expect("reclaim dead pid lock")
});
let reclaim_lines: Vec<_> = lines
.iter()
.filter(|line| line.contains("removing filesystem lock"))
.collect();
assert_eq!(
reclaim_lines,
vec![&format!(
"INFO removing filesystem lock at {} from dead or recycled PID {}",
path.display(),
metadata.pid
)]
);
let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
assert_eq!(metadata.pid, std::process::id());
drop(guard);
}
#[test]
fn zero_timeout_dead_pid_reclaim_acquires_after_removing_stale_file() {
let (_dir, path) = test_lock_path();
let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
write_synthetic_lock(&path, &metadata);
let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
.expect("zero-timeout acquire should claim the reaped stale lock");
let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
assert_eq!(metadata.pid, std::process::id());
drop(guard);
}
#[test]
fn dead_same_host_reclaim_token_is_reaped_with_stale_lock() {
let (_dir, path) = test_lock_path();
let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
write_synthetic_lock(&path, &stale);
let token_path = write_reclaim_token(&path, &stale);
let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
.expect("dead token must not wedge stale-lock reclamation");
assert!(!token_path.exists(), "stale reclaim token must be removed");
drop(guard);
assert!(!path.exists(), "acquired lock must be released normally");
}
#[test]
fn live_reclaim_token_blocks_and_is_untouched() {
let (_dir, path) = test_lock_path();
let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
write_synthetic_lock(&path, &stale);
let live = current_process_metadata();
let token_path = write_reclaim_token(&path, &live);
let result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
assert!(matches!(result, Err(AcquireError::Timeout)));
assert_eq!(read_lock_metadata(&token_path).expect("live token"), live);
}
#[test]
fn foreign_host_reclaim_token_is_authoritative() {
let (_dir, path) = test_lock_path();
let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
write_synthetic_lock(&path, &stale);
let mut foreign = stale.clone();
foreign.hostname = format!("{}-foreign", current_hostname());
let token_path = write_reclaim_token(&path, &foreign);
let result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
assert!(matches!(result, Err(AcquireError::Timeout)));
assert_eq!(
read_lock_metadata(&token_path).expect("foreign token"),
foreign
);
}
#[test]
fn malformed_reclaim_token_is_held_until_older_than_sixty_seconds() {
use filetime::{set_file_mtime, FileTime};
let (_dir, path) = test_lock_path();
let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
write_synthetic_lock(&path, &stale);
let token_path = reclaim_token_path(&path);
fs::write(&token_path, b"{ malformed").expect("write malformed token");
let young_result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
assert!(matches!(young_result, Err(AcquireError::Timeout)));
assert_eq!(fs::read(&token_path).expect("young token"), b"{ malformed");
let old = SystemTime::now()
.checked_sub(RECLAIM_TOKEN_MALFORMED_STALE_AGE + Duration::from_secs(1))
.expect("old timestamp");
set_file_mtime(&token_path, FileTime::from_system_time(old)).expect("age token");
let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
.expect("old malformed token should be reclaimed");
assert!(!token_path.exists());
drop(guard);
}
#[test]
fn held_reclaim_token_logs_blocked_without_claiming_lock_removal() {
let (_dir, path) = test_lock_path();
let stale = synthetic_metadata(999_999_999, current_hostname(), now_ms());
write_synthetic_lock(&path, &stale);
let live = current_process_metadata();
write_reclaim_token(&path, &live);
take_reclaim_test_logs();
let result = acquire_with_config(&path, Some(Duration::ZERO), test_config());
assert!(matches!(result, Err(AcquireError::Timeout)));
let logs = take_reclaim_test_logs();
assert!(logs.iter().any(|line| {
line.contains(&format!("reclaim of {} blocked", path.display()))
&& line.contains(&format!("pid {} (alive)", live.pid))
}));
assert!(!logs
.iter()
.any(|line| line.contains("removing filesystem lock")));
}
#[test]
fn dead_unreclaimable_lock_retry_backoff_stays_bounded() {
let mut elapsed_ms = 0_u64;
let mut attempts = 0_u32;
while elapsed_ms < 60_000 {
elapsed_ms = elapsed_ms.saturating_add(dead_reclaim_backoff_ms(attempts, 100));
attempts += 1;
}
assert!(
attempts <= 17,
"{attempts} retries exceed the one-minute bound"
);
assert_eq!(dead_reclaim_backoff_ms(0, 100), 250);
assert_eq!(dead_reclaim_backoff_ms(20, 100), 5_000);
}
#[test]
fn stale_heartbeat_from_live_pid_blocks() {
let (_dir, path) = test_lock_path();
let mut metadata = current_process_metadata();
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
let identity = process_identity(std::process::id())
.expect("current process should have a start-time identity");
assert_eq!(metadata.process_start_time, Some(identity.start_time));
assert_eq!(metadata.boot_id, identity.boot_id);
}
metadata.created_at_ms = now_ms().saturating_sub(60_000);
metadata.heartbeat_at_ms = now_ms().saturating_sub(60_000);
write_synthetic_lock(&path, &metadata);
let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
assert!(matches!(result, Err(AcquireError::Timeout)));
assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);
remove_lock_file(&path).expect("cleanup synthetic lock");
}
#[test]
fn availability_probe_preserves_a_live_owner_with_stale_heartbeat() {
let (_dir, path) = test_lock_path();
let mut metadata = current_process_metadata();
metadata.heartbeat_at_ms = 0;
write_synthetic_lock(&path, &metadata);
let original = fs::read(&path).unwrap();
assert_eq!(
lock_availability(&path).unwrap(),
LockAvailability::LiveOwner
);
assert_eq!(fs::read(&path).unwrap(), original);
}
#[test]
fn availability_probe_observes_dead_and_missing_owners_without_reclaiming() {
let (_dir, path) = test_lock_path();
assert_eq!(
lock_availability(&path).unwrap(),
LockAvailability::Available
);
assert!(!path.exists());
let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
write_synthetic_lock(&path, &metadata);
let original = fs::read(&path).unwrap();
assert_eq!(lock_availability(&path).unwrap(), LockAvailability::Stale);
assert_eq!(fs::read(&path).unwrap(), original);
}
#[test]
fn availability_probe_uses_extended_cross_host_heartbeat_policy() {
let (_dir, path) = test_lock_path();
let mut metadata = synthetic_metadata(
999_999_999,
format!("other-{}", current_hostname()),
now_ms(),
);
write_synthetic_lock(&path, &metadata);
assert!(
lock_availability(&path).unwrap() == LockAvailability::LiveOwner,
"a local PID probe cannot attest a remote owner"
);
metadata.heartbeat_at_ms = now_ms().saturating_sub(STALE_HEARTBEAT_MS * 2);
fs::write(&path, serde_json::to_vec(&metadata).unwrap()).unwrap();
assert!(
lock_availability(&path).unwrap() == LockAvailability::LiveOwner,
"cross-host reclamation needs the extended threshold"
);
metadata.heartbeat_at_ms = now_ms().saturating_sub(STALE_HEARTBEAT_MS * 5 + 1_000);
fs::write(&path, serde_json::to_vec(&metadata).unwrap()).unwrap();
assert_eq!(lock_availability(&path).unwrap(), LockAvailability::Stale);
assert_eq!(read_lock_metadata(&path).unwrap(), metadata);
}
#[test]
fn availability_probe_does_not_treat_malformed_metadata_as_available() {
let (_dir, path) = test_lock_path();
fs::write(&path, b"not-json").unwrap();
assert_eq!(
lock_availability(&path).unwrap(),
LockAvailability::Malformed
);
assert_eq!(fs::read(&path).unwrap(), b"not-json");
}
#[test]
fn availability_probe_keeps_io_errors_distinct_and_can_retry() {
let (_dir, path) = test_lock_path();
fs::create_dir(&path).unwrap();
assert!(lock_availability(&path).is_err());
assert!(path.is_dir());
fs::remove_dir(&path).unwrap();
assert_eq!(
lock_availability(&path).unwrap(),
LockAvailability::Available
);
}
#[cfg(any(target_os = "linux", target_os = "macos", windows))]
#[test]
fn live_pid_with_wrong_start_time_is_reclaimed() {
let (_dir, path) = test_lock_path();
let mut metadata = current_process_metadata();
let current_identity = process_identity(std::process::id())
.expect("current process should have a start-time identity");
metadata.process_start_time = Some(different_start_time(current_identity.start_time));
metadata.boot_id = current_identity.boot_id;
write_synthetic_lock(&path, &metadata);
let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
.expect("zero-timeout acquire should reclaim a reused PID");
assert_eq!(guard.metadata.pid, std::process::id());
assert_eq!(
guard.metadata.process_start_time,
Some(current_identity.start_time)
);
drop(guard);
}
#[cfg(target_os = "linux")]
#[test]
fn live_pid_with_wrong_boot_id_is_reclaimed() {
let (_dir, path) = test_lock_path();
let mut metadata = current_process_metadata();
let current_identity = process_identity(std::process::id())
.expect("current process should have a start-time identity");
metadata.boot_id = Some(format!("wrong-{}", current_identity.boot_id.unwrap()));
write_synthetic_lock(&path, &metadata);
let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
.expect("zero-timeout acquire should reclaim a rebooted PID identity");
assert_eq!(guard.metadata.pid, std::process::id());
drop(guard);
}
#[test]
fn legacy_live_pid_lock_keeps_pid_only_liveness() {
let (_dir, path) = test_lock_path();
let stale_at = now_ms().saturating_sub(60_000);
let mut metadata = synthetic_metadata(std::process::id(), current_hostname(), stale_at);
metadata.heartbeat_at_ms = stale_at;
let original = write_legacy_lock(&path, &metadata);
assert!(!original.contains("process_start_time"));
assert!(!original.contains("boot_id"));
let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
assert!(matches!(result, Err(AcquireError::Timeout)));
assert_eq!(
fs::read_to_string(&path).expect("read legacy lock"),
original
);
remove_lock_file(&path).expect("cleanup legacy lock");
}
#[test]
fn legacy_dead_pid_lock_is_reclaimed() {
let (_dir, path) = test_lock_path();
let metadata = synthetic_metadata(999_999_999, current_hostname(), now_ms());
let original = write_legacy_lock(&path, &metadata);
assert!(!original.contains("process_start_time"));
assert!(!original.contains("boot_id"));
let guard = acquire_with_config(&path, Some(Duration::ZERO), test_config())
.expect("zero-timeout acquire should reclaim a legacy dead PID lock");
assert_eq!(guard.metadata.pid, std::process::id());
drop(guard);
}
#[test]
fn healthy_live_owner_blocks() {
let (_dir, path) = test_lock_path();
let metadata = current_process_metadata();
write_synthetic_lock(&path, &metadata);
let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
assert!(matches!(result, Err(AcquireError::Timeout)));
remove_lock_file(&path).expect("cleanup synthetic lock");
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[test]
fn semantic_batch_lease_exited_unreaped_owner_is_dead() {
use std::io::Write;
use std::process::{Command, Stdio};
for legacy in [false, true] {
let (_root, path) = test_lock_path();
let mut child = Command::new("sh")
.args(["-c", "read gate; exit 0"])
.stdin(Stdio::piped())
.spawn()
.unwrap();
let identity = process_identity(child.id()).unwrap();
let mut metadata = synthetic_metadata(child.id(), current_hostname(), now_ms());
metadata.process_start_time = Some(identity.start_time);
metadata.boot_id = identity.boot_id;
if legacy {
write_legacy_lock(&path, &metadata);
} else {
write_synthetic_lock(&path, &metadata);
}
writeln!(child.stdin.take().unwrap(), "exit").unwrap();
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
let observed = unsafe {
libc::waitid(
libc::P_PID,
libc::id_t::try_from(child.id()).unwrap(),
info.as_mut_ptr(),
libc::WEXITED | libc::WNOWAIT,
)
};
let wait_error = io::Error::last_os_error();
let exited = process_identity(child.id()).is_some_and(|identity| identity.exited);
let recovered = try_acquire_once(&path);
child.wait().unwrap();
assert_eq!(observed, 0, "waitid failed: {wait_error}");
assert!(exited, "the native identity probe did not observe exit");
assert!(
recovered.is_ok(),
"an exited unreaped owner blocked recovery (legacy={legacy})"
);
}
}
#[cfg(target_os = "linux")]
#[test]
fn semantic_batch_lease_linux_stat_requires_quiescent_zombie() {
let one =
"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";
assert_eq!(linux_process_stat_identity(one), Some((1234, true)));
let live_threads = one.replace(" 1 0 1234 ", " 2 0 1234 ");
assert_eq!(
linux_process_stat_identity(&live_threads),
Some((1234, false)),
"a zombie leader does not prove its worker threads exited"
);
assert_eq!(
linux_process_stat_identity(&one.replace(" 1 0 1234 ", " 0 0 1234 ")),
Some((1234, false))
);
assert_eq!(
linux_process_stat_identity(&one.replace(") Z ", ") X ")),
Some((1234, true))
);
assert_eq!(
linux_process_stat_identity(&one.replace(") Z ", ") S ")),
Some((1234, false))
);
assert_eq!(
linux_process_stat_identity(&one.replace(" 1 0 1234 ", " bad 0 1234 ")),
None
);
assert_eq!(
linux_process_stat_identity(&one.replace("1234", "bad")),
None
);
assert_eq!(
linux_process_stat_identity(&one.replace(") Z ", ") bad ")),
None
);
}
#[test]
fn malformed_lockfile_is_reclaimed() {
let (_dir, path) = test_lock_path();
fs::write(&path, b"not valid json").expect("write malformed lock");
let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
.expect("reclaim malformed lock");
let metadata = read_lock_metadata(&path).expect("read reclaimed lock");
assert_eq!(metadata.pid, std::process::id());
drop(guard);
}
#[test]
fn cross_host_lock_is_not_stolen_before_extended_stale_threshold() {
let (_dir, path) = test_lock_path();
let now = now_ms();
let mut metadata = current_process_metadata();
metadata.hostname = format!("{}-other", current_hostname());
metadata.process_start_time = metadata.process_start_time.map(different_start_time);
metadata.created_at_ms = now;
metadata.heartbeat_at_ms = now;
metadata.writer_epoch = format!("cross-host-{now}");
#[cfg(any(target_os = "linux", target_os = "macos"))]
assert_ne!(
metadata.process_start_time,
process_identity(std::process::id()).map(|identity| identity.start_time)
);
write_synthetic_lock(&path, &metadata);
let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
assert!(matches!(result, Err(AcquireError::Timeout)));
assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);
remove_lock_file(&path).expect("cleanup synthetic lock");
}
#[test]
fn stale_cross_host_lock_is_reclaimed_after_extended_threshold() {
let (_dir, path) = test_lock_path();
let stale_at =
now_ms().saturating_sub(test_config().cross_host_stale_heartbeat_ms() + 1_000);
let mut metadata = current_process_metadata();
metadata.hostname = format!("{}-other", current_hostname());
metadata.process_start_time = metadata.process_start_time.map(different_start_time);
metadata.created_at_ms = stale_at;
metadata.heartbeat_at_ms = stale_at;
metadata.writer_epoch = format!("cross-host-{stale_at}");
write_synthetic_lock(&path, &metadata);
let guard = acquire_with_config(&path, Some(Duration::from_secs(1)), test_config())
.expect("reclaim stale cross-host lock");
let reclaimed = read_lock_metadata(&path).expect("read reclaimed lock");
assert_eq!(reclaimed.hostname, current_hostname());
assert_ne!(reclaimed.created_at_ms, metadata.created_at_ms);
drop(guard);
}
#[test]
fn live_owner_over_10min_warns_but_blocks() {
let (_dir, path) = test_lock_path();
let mut metadata = current_process_metadata();
metadata.created_at_ms = now_ms().saturating_sub(11 * 60 * 1_000);
metadata.heartbeat_at_ms = now_ms();
write_synthetic_lock(&path, &metadata);
let result = acquire_with_config(&path, Some(Duration::from_millis(80)), test_config());
assert!(matches!(result, Err(AcquireError::Timeout)));
assert_eq!(read_lock_metadata(&path).expect("read lock"), metadata);
remove_lock_file(&path).expect("cleanup synthetic lock");
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct HeartbeatObservation {
step: usize,
observed_at_ms: u64,
heartbeat_at_ms: Option<u64>,
volume: Option<u64>,
inode: Option<u64>,
modified_at_ms: Option<u64>,
error: Option<String>,
}
fn observe_heartbeat(path: &Path, step: usize) -> HeartbeatObservation {
let mut observation = HeartbeatObservation {
step,
observed_at_ms: now_ms(),
heartbeat_at_ms: None,
volume: None,
inode: None,
modified_at_ms: None,
error: None,
};
let mut file = match File::open(path) {
Ok(file) => file,
Err(error) => {
observation.error = Some(error.to_string());
return observation;
}
};
if let Some(identity) = LeaseFileIdentity::of_file(&file) {
observation.volume = Some(identity.volume);
observation.inode = Some(identity.file);
}
observation.modified_at_ms = file
.metadata()
.and_then(|metadata| metadata.modified())
.ok()
.and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
.map(|elapsed| elapsed.as_millis() as u64);
let mut bytes = Vec::new();
match file.read_to_end(&mut bytes) {
Ok(_) => match serde_json::from_slice::<LockMetadata>(&bytes) {
Ok(metadata) => observation.heartbeat_at_ms = Some(metadata.heartbeat_at_ms),
Err(error) => observation.error = Some(error.to_string()),
},
Err(error) => observation.error = Some(error.to_string()),
}
observation
}
struct HeartbeatHarness {
child: Child,
input: Option<ChildStdin>,
lines: mpsc::Receiver<String>,
reader: Option<JoinHandle<()>>,
transcript: Vec<String>,
}
impl HeartbeatHarness {
fn read_observation(
&mut self,
prefix: &str,
deadline: Instant,
) -> Result<HeartbeatObservation, String> {
loop {
let line = self
.lines
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
.map_err(|error| format!("observer response: {error}"))?;
self.transcript.push(line.clone());
if let Some(json) = line.strip_prefix(prefix) {
return serde_json::from_str(json)
.map_err(|error| format!("observer JSON: {error}"));
}
}
}
fn observe(
&mut self,
step: usize,
deadline: Instant,
) -> Result<HeartbeatObservation, String> {
let input = self.input.as_mut().expect("observer input is open");
writeln!(input, "{step}").map_err(|error| error.to_string())?;
input.flush().map_err(|error| error.to_string())?;
self.read_observation("sample:", deadline)
}
fn diagnostics(&self, path: &Path, guard: &LockGuard, step: usize) -> String {
let held_identity = guard.heartbeat_file.try_lock().ok().and_then(|mut slot| {
slot.as_mut()
.and_then(|lease| LeaseFileIdentity::of_file(lease.file()))
});
format!(
"parent={:?} held_identity={held_identity:?} stopped={} visible={}\nchild observations:\n{}",
observe_heartbeat(path, step),
guard.pump.heartbeat_stopped(),
guard.heartbeat_is_visible(),
self.transcript.join("\n")
)
}
fn finish(&mut self) -> std::process::ExitStatus {
self.input.take();
let status = self.child.wait().expect("observer exit");
self.reader.take().unwrap().join().expect("observer reader");
self.transcript.extend(self.lines.try_iter());
status
}
}
impl Drop for HeartbeatHarness {
fn drop(&mut self) {
self.input.take();
if !matches!(self.child.try_wait(), Ok(Some(_))) {
let _ = self.child.kill();
}
let _ = self.child.wait();
if let Some(reader) = self.reader.take() {
let _ = reader.join();
}
}
}
fn spawn_test_harness(mode: &str, path: &Path) -> HeartbeatHarness {
let mut command = std::process::Command::new(std::env::current_exe().expect("test exe"));
command
.args(["--exact", HARNESS_TEST, "--nocapture", "--test-threads=1"])
.env("FS_LOCK_HARNESS_MODE", mode)
.env("FS_LOCK_HARNESS_PATH", path)
.stdin(Stdio::piped())
.stdout(Stdio::piped());
for name in [
"AFT_TEST_REQUIRE_RUST_ANALYZER",
"AFT_TEST_STORAGE_ROOT",
"AFT_STORAGE_DIR",
] {
command.env_remove(name);
}
let mut child = command.spawn().expect("spawn test harness process");
let stdin = child.stdin.take().expect("harness stdin");
let stdout = child.stdout.take().expect("harness stdout");
let (sender, receiver) = mpsc::channel();
let reader = thread::spawn(move || {
for line in io::BufReader::new(stdout).lines() {
let Ok(line) = line else { break };
if sender.send(line).is_err() {
break;
}
}
});
HeartbeatHarness {
child,
input: Some(stdin),
lines: receiver,
reader: Some(reader),
transcript: Vec::new(),
}
}
#[test]
fn separate_process_sees_heartbeat_advance() {
if std::env::var_os(HARNESS_TEST).is_some() {
return;
}
assert_separate_process_heartbeat_advances(test_config());
}
#[test]
fn separate_process_waits_for_heartbeat_within_stale_bound() {
assert_separate_process_heartbeat_advances(LockConfig {
heartbeat_interval_ms: 400,
..test_config()
});
}
fn assert_separate_process_heartbeat_advances(config: LockConfig) {
let (_dir, path) = test_lock_path();
let guard = acquire_with_config(&path, None, config).expect("acquire lock");
guard.heartbeat_once().expect("initial beat");
let mut harness = spawn_test_harness(HARNESS_MODE_INSPECT, &path);
let ready = harness
.read_observation("ready:", Instant::now() + Duration::from_secs(10))
.unwrap_or_else(|error| {
panic!(
"observer startup failed: {error}\n{}",
harness.diagnostics(&path, &guard, 0)
)
});
let mut previous = ready.heartbeat_at_ms.unwrap_or_else(|| {
panic!(
"observer could not read initial lease\n{}",
harness.diagnostics(&path, &guard, 0)
)
});
for step in 1..=4 {
let deadline = Instant::now() + Duration::from_millis(config.stale_heartbeat_ms);
loop {
let observation = harness.observe(step, deadline).unwrap_or_else(|error| {
panic!(
"observer step {step} failed: {error}\n{}",
harness.diagnostics(&path, &guard, step)
)
});
if let Some(seen) = observation.heartbeat_at_ms.filter(|seen| *seen > previous) {
eprintln!("heartbeat observer advanced: {observation:?}");
previous = seen;
break;
}
assert!(
Instant::now() < deadline,
"observer heartbeat did not advance from {previous} within {}ms at step {step}\n{}",
config.stale_heartbeat_ms,
harness.diagnostics(&path, &guard, step)
);
thread::sleep(
Duration::from_millis(25)
.min(deadline.saturating_duration_since(Instant::now())),
);
}
}
let status = harness.finish();
assert!(
status.success(),
"observer failed: {status:?}\n{}",
harness.diagnostics(&path, &guard, 4)
);
}
#[cfg(unix)]
#[test]
fn separate_process_harness_drop_reaps_observer() {
let (_dir, path) = test_lock_path();
write_synthetic_lock(&path, ¤t_process_metadata());
let mut harness = spawn_test_harness(HARNESS_MODE_INSPECT, &path);
harness
.read_observation("ready:", Instant::now() + Duration::from_secs(10))
.expect("observer ready");
let pid = harness.child.id() as libc::pid_t;
drop(harness);
let mut status = 0;
let waited = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
let error = io::Error::last_os_error().raw_os_error();
if waited == 0 {
unsafe {
libc::kill(pid, libc::SIGKILL);
libc::waitpid(pid, &mut status, 0);
}
}
assert_eq!(waited, -1, "observer survived harness drop");
assert_eq!(error, Some(libc::ECHILD), "observer was not reaped");
}
#[test]
fn replacing_the_lease_keeps_the_next_beat_working_for_the_owner() {
let (_dir, path) = test_lock_path();
let guard = acquire_with_config(&path, None, test_config()).expect("acquire");
let mut restored = guard.metadata.clone();
restored.heartbeat_at_ms = now_ms().saturating_sub(1_000);
let fresh = {
let bytes = lock_metadata_bytes(&restored).expect("serialize");
with_lease_handles_closed(&path, || {
replace_lock_bytes_unsynced(&path, &bytes).map(|()| open_lease_for_heartbeat(&path))
})
.expect("replace the lease")
.expect("open the replacement lease")
};
let replacement = Arc::new(Mutex::new(Some(fresh)));
register_lease_slot(guard.pump.slot, &path, &replacement);
let stale_at = restored.heartbeat_at_ms;
let deadline = Instant::now() + Duration::from_secs(3);
let mut advanced = false;
while Instant::now() < deadline {
thread::sleep(Duration::from_millis(
test_config().heartbeat_interval_ms * 2,
));
if read_lock_metadata(&path)
.map(|meta| meta.heartbeat_at_ms > stale_at)
.unwrap_or(false)
{
advanced = true;
break;
}
}
assert!(
advanced,
"the heartbeat did not refresh the lease through the replacement \
handle: {:?}",
read_lock_metadata(&path)
);
assert!(
guard.verify_writer_epoch().expect("verify lease"),
"writers must still verify their epoch after a replacement"
);
}
#[test]
fn fs_lock_separate_process_harness() {
let Some(mode) = std::env::var_os("FS_LOCK_HARNESS_MODE") else {
return;
};
let path = PathBuf::from(std::env::var_os("FS_LOCK_HARNESS_PATH").expect("harness path"));
println!("mode:{mode:?} path={}", path.display());
match mode.to_string_lossy().as_ref() {
HARNESS_MODE_INSPECT => {
println!(
"ready:{}",
serde_json::to_string(&observe_heartbeat(&path, 0)).unwrap()
);
io::stdout().flush().unwrap();
for line in io::stdin().lock().lines() {
let step = line.unwrap().parse().expect("observation step");
println!(
"sample:{}",
serde_json::to_string(&observe_heartbeat(&path, step)).unwrap()
);
io::stdout().flush().unwrap();
}
}
other => panic!("unknown harness mode {other}"),
}
}
#[test]
fn beat_stops_when_another_owner_replaces_the_lease_file() {
let (_dir, path) = test_lock_path();
let guard = acquire_with_config(&path, None, test_config()).expect("acquire");
guard
.heartbeat_once()
.expect("beat through the kept descriptor");
let mut foreign = current_process_metadata();
foreign.pid = foreign.pid.wrapping_add(1);
foreign.created_at_ms = now_ms().saturating_add(1_000);
foreign.writer_epoch = format!("foreign-{}", now_ms());
assert!(!lock_identity_matches(&foreign, &guard.metadata));
let staging = path.with_extension("foreign");
fs::write(
&staging,
lock_metadata_bytes(&foreign).expect("serialize foreign lease"),
)
.expect("write the foreign owner's lease");
rename_over(&staging, &path).expect("foreign reclaim renames over the lease");
assert!(
matches!(guard.heartbeat_once(), Err(HeartbeatError::NotOwner)),
"a beat must not accept the orphaned descriptor it still holds"
);
assert_eq!(
read_lock_metadata(&path).expect("read foreign lease"),
foreign,
"a beat must never write over the foreign owner's lease"
);
}
#[test]
fn unrelated_lease_churn_keeps_the_kept_descriptor() {
let dir = tempfile::tempdir().expect("create temp dir");
let mut guards = (0..2)
.map(|index| {
acquire_with_config(
&dir.path().join(format!("tenant-{index}.lease")),
Some(Duration::from_secs(2)),
test_config(),
)
.expect("acquire")
})
.collect::<Vec<_>>();
let neighbour = dir.path().join("neighbour.lease");
for _ in 0..3 {
let churn = acquire_with_config(&neighbour, None, test_config()).expect("churn lease");
let mut restored = churn.metadata.clone();
restored.heartbeat_at_ms = now_ms().saturating_sub(1_000);
let bytes = lock_metadata_bytes(&restored).expect("serialize");
with_lease_handles_closed(&neighbour, || {
replace_lock_bytes_unsynced(&neighbour, &bytes)
})
.expect("replace the neighbour");
drop(churn);
let _ = io_ledger::take();
}
let _ = io_ledger::take();
for guard in &guards {
guard.heartbeat_once().expect("beat");
}
let cost = io_ledger::take();
assert_beat_opens_no_descriptor(&cost);
guards.clear();
}
#[test]
fn descriptor_identity_check_opens_no_descriptor() {
let (_dir, path) = test_lock_path();
let guard = acquire_with_config(&path, None, test_config()).expect("acquire");
let _ = io_ledger::take();
for _ in 0..3 {
guard.heartbeat_once().expect("beat");
}
let ledger = io_ledger::take();
assert_beat_opens_no_descriptor(&ledger);
}
#[test]
fn stopped_heartbeat_releases_handle_without_unlocking_or_touching_replacement() {
let dir = tempfile::tempdir().expect("temp dir");
let cache = dir.path().join("cache");
fs::create_dir(&cache).expect("cache dir");
let path = cache.join("writer.lease");
let mut guard = acquire_with_config(&path, None, test_config()).expect("acquire lease");
let _ = io_ledger::take();
guard.stop_heartbeat_for_removal();
assert_eq!(io_ledger::take().closes, 1, "close the kept handle now");
assert!(guard.heartbeat.is_none(), "join before closing the handle");
assert!(guard.heartbeat_file.lock().unwrap().is_none());
assert!(!guard
.verify_writer_epoch()
.expect("stopped guard is not writable"));
assert!(matches!(
guard.pump.heartbeat_once(),
Err(HeartbeatError::NotPumped)
));
assert!(matches!(
try_acquire_once(&path),
Err(AcquireError::Timeout)
));
assert!(lock_identity_matches(
&read_lock_metadata(&path).expect("lease remains until removal"),
&guard.metadata
));
let retired = dir.path().join("retired");
fs::rename(&cache, &retired).expect("retire with the lease guard still alive");
fs::create_dir(&cache).expect("replacement cache");
let replacement = acquire_with_config(&path, None, test_config()).expect("new owner");
let canary = cache.join("canary");
fs::write(&canary, b"replacement").expect("canary");
drop(guard);
assert!(replacement
.verify_writer_epoch()
.expect("replacement owns lease"));
assert_eq!(
fs::read(canary).expect("replacement preserved"),
b"replacement"
);
fs::remove_dir_all(retired).expect("reap without a lingering lease handle");
}
#[test]
fn drop_stops_heartbeat_thread() {
let (_dir, path) = test_lock_path();
let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
drop(guard);
thread::sleep(Duration::from_millis(
test_config().heartbeat_interval_ms * 3,
));
assert!(
!path.exists(),
"heartbeat recreated or kept updating lockfile"
);
}
#[test]
fn heartbeat_error_classification_terminal_vs_transient() {
assert!(heartbeat_error_is_terminal(&HeartbeatError::LockGone));
assert!(heartbeat_error_is_terminal(&HeartbeatError::NotOwner));
assert!(!heartbeat_error_is_terminal(&HeartbeatError::Io(
io::Error::other("disk blip")
)));
let malformed: serde_json::Error =
serde_json::from_str::<LockMetadata>("not json").unwrap_err();
assert!(!heartbeat_error_is_terminal(&HeartbeatError::Malformed(
malformed
)));
}
#[cfg(target_os = "linux")]
#[test]
fn released_lease_closes_all_descriptors_synchronously() {
let (dir, path) = test_lock_path();
let open_under_root = || {
fs::read_dir("/proc/self/fd")
.expect("descriptor census")
.filter_map(Result::ok)
.filter_map(|entry| fs::read_link(entry.path()).ok())
.filter(|target| target.starts_with(dir.path()))
.collect::<Vec<_>>()
};
let guard = acquire_with_config(&path, None, test_config()).expect("acquire lease");
let handle = Arc::downgrade(&guard.heartbeat_file);
assert!(!open_under_root().is_empty(), "live lease keeps its handle");
drop(guard);
assert!(
handle.upgrade().is_none(),
"heartbeat must release its handle"
);
assert!(open_under_root().is_empty(), "no descriptors after release");
}
#[test]
fn malformed_beat_reopens_atomic_replacement_on_next_beat() {
let (_dir, path) = test_lock_path();
let guard = acquire_with_config(
&path,
None,
LockConfig {
heartbeat_interval_ms: 60_000,
..test_config()
},
)
.expect("acquire lease");
let live = fs::read(&path).expect("read lease");
fs::write(&path, vec![b'x'; live.len()]).expect("corrupt lease");
assert!(matches!(
guard.pump.heartbeat_once(),
Err(HeartbeatError::Malformed(_))
));
assert!(guard.heartbeat_file.lock().unwrap().is_none());
assert!(guard.heartbeat_is_visible());
let mut restored = guard.metadata.clone();
restored.heartbeat_at_ms = now_ms().saturating_sub(1_000_000);
let replacement = path.with_extension("replacement");
fs::write(&replacement, lock_metadata_bytes(&restored).unwrap()).unwrap();
rename_over(&replacement, &path).expect("atomic recovery outside the lease registry");
let _ = io_ledger::take();
guard
.pump
.heartbeat_once()
.expect("retry through live inode");
let recovered = read_lock_metadata(&path).expect("independently read recovered lease");
assert!(lock_identity_matches(&recovered, &guard.metadata));
assert!(recovered.heartbeat_at_ms > restored.heartbeat_at_ms);
let recovery = io_ledger::take();
assert_eq!((recovery.opens, recovery.closes), (1, 0));
guard.pump.heartbeat_once().expect("healthy next beat");
assert_beat_opens_no_descriptor(&io_ledger::take());
}
#[test]
fn valid_same_owner_replacement_refreshes_within_stale_bound() {
let (_dir, path) = test_lock_path();
let config = test_config();
let guard = acquire_with_config(
&path,
None,
LockConfig {
heartbeat_interval_ms: 60_000,
..config
},
)
.expect("acquire lease");
let held_identity = LeaseFileIdentity::of_file(
guard
.heartbeat_file
.lock()
.unwrap()
.as_mut()
.unwrap()
.file(),
);
let mut restored = guard.metadata.clone();
restored.heartbeat_at_ms = now_ms().saturating_sub(1_000_000);
let replacement = path.with_extension("replacement");
fs::write(&replacement, lock_metadata_bytes(&restored).unwrap()).unwrap();
rename_over(&replacement, &path).expect("replace valid same-owner lease");
let live_identity = LeaseFileIdentity::of_path(&path).expect("replacement identity");
assert_ne!(held_identity, Some(live_identity));
let _ = io_ledger::take();
let started = Instant::now();
let result = guard.pump.heartbeat_once();
let elapsed = started.elapsed();
let on_disk = read_lock_metadata(&path).expect("independent path read");
let cost = io_ledger::take();
eprintln!(
"valid replacement beat: elapsed={elapsed:?} result={result:?} held={held_identity:?} live={live_identity:?} sentinel={} observed={} cost={cost:?}",
restored.heartbeat_at_ms, on_disk.heartbeat_at_ms
);
assert!(
elapsed < Duration::from_millis(config.stale_heartbeat_ms),
"same-owner replacement delayed a beat beyond its stale bound: {elapsed:?}"
);
result.expect("refresh replacement through reopened handle");
assert!(on_disk.heartbeat_at_ms > restored.heartbeat_at_ms);
assert!(lock_identity_matches(&on_disk, &guard.metadata));
assert_eq!((cost.opens, cost.closes), (1, 1));
let reopened_identity = LeaseFileIdentity::of_file(
guard
.heartbeat_file
.lock()
.unwrap()
.as_mut()
.unwrap()
.file(),
);
assert_eq!(reopened_identity, Some(live_identity));
guard.pump.heartbeat_once().expect("healthy next beat");
assert_beat_opens_no_descriptor(&io_ledger::take());
}
#[test]
fn heartbeat_survives_transient_malformed_and_recovers() {
let (_dir, path) = test_lock_path();
let guard = acquire_with_config(&path, None, test_config()).expect("acquire lock");
let owner = guard.metadata.clone();
let live = fs::read(&path).expect("read live lease");
fs::write(&path, vec![b'x'; live.len()]).expect("corrupt lockfile");
thread::sleep(Duration::from_millis(
test_config().heartbeat_interval_ms * 4,
));
let mut restored = owner.clone();
restored.heartbeat_at_ms = now_ms().saturating_sub(1_000_000);
let sentinel = restored.heartbeat_at_ms;
{
let bytes = lock_metadata_bytes(&restored).expect("serialize restored metadata");
with_lease_handles_closed(&path, || replace_lock_bytes_unsynced(&path, &bytes))
.expect("restore lock metadata");
}
let deadline = std::time::Instant::now() + Duration::from_secs(5);
let mut recovered = false;
while std::time::Instant::now() < deadline {
thread::sleep(Duration::from_millis(25));
match read_lock_metadata(&path) {
Ok(meta)
if meta.created_at_ms == owner.created_at_ms
&& meta.heartbeat_at_ms > sentinel =>
{
recovered = true;
break;
}
_ => continue,
}
}
assert!(
recovered,
"heartbeat did not recover after a transient malformed read — thread likely died: \
stopped={} visible={} on_disk={:?}",
guard.pump.heartbeat_stopped(),
guard.heartbeat_is_visible(),
read_lock_metadata(&path)
);
drop(guard);
}
}