Skip to main content

runner_manager_platform/
lock.rs

1// owner: d1-platform-core
2
3//! The host locks: one keeps a second agent from reconciling the same policies,
4//! one serialises runtime creation, and one serialises rotating credentials
5//! across a background service and foreground tools.
6//!
7//! `03-control-flows.md`, flow 3.1: *"A single-instance lock prevents two
8//! agents on one host from reconciling the same policy."* Flow 2.4: the agent
9//! *"takes the host-wide allocation lock before creating each local runtime"*.
10//! `07-security.md`'s threat table names the single-instance lock as one of the
11//! four controls on *"API replay or a duplicate agent creates too many
12//! runners"*.
13//!
14//! # Why an operating-system file lock, and not a PID file
15//!
16//! The requirement that decides the mechanism is *"released on crash rather
17//! than leaking"*. A PID file cannot do that: a process that is `SIGKILL`ed, or
18//! whose machine loses power, leaves the file behind, and every recovery
19//! strategy built on top — is that PID still alive? was it reused? — is
20//! guesswork that fails exactly when it matters. An operating-system file lock
21//! is released by the kernel when the holding process ends, for *any* reason,
22//! with no cooperation from the process and nothing left to clean up.
23//!
24//! Two mechanisms, one behaviour:
25//!
26//! - **Windows** opens the file for read and write while sharing only read
27//!   access. A second acquirer asks for write access as well, which the
28//!   holder's share mode denies, and gets `ERROR_SHARING_VIOLATION`. A
29//!   *reader* asks only for read access, which the share mode permits — which
30//!   is what lets the loser find out who beat it.
31//! - **Unix** takes `flock(LOCK_EX | LOCK_NB)`. `flock` is advisory and does
32//!   not stand in the way of an ordinary `open` for reading, so the loser can
33//!   read the holder record there too. Locks are held per open file
34//!   description, so a second acquisition from the *same* process is refused as
35//!   firmly as one from another process.
36//!
37//! # The lock file is never deleted
38//!
39//! Not on release, not on a clean shutdown, not by `Drop`. On Unix a lock is a
40//! property of the inode, so a holder that unlinks the file lets the next
41//! acquirer create and lock a *different* inode — after which two processes
42//! each hold "the lock" and neither can see the other. Leaving a zero-cost
43//! empty file behind is the whole price of not having that bug.
44//!
45//! # What "host-wide" means, precisely
46//!
47//! The lock is a file under [`crate::paths::AppPaths::state_dir`], as
48//! `05-infrastructure.md` specifies (*"state/ agent lock"*). Two agents
49//! contend if and only if they resolve the same state directory — which is what
50//! makes the lock host-wide for every configuration this product supports, and
51//! is worth stating rather than assuming: the platform-standard state directory
52//! is per-account on all three operating systems, so a daemon running as a
53//! service account and an interactive `daemon run` by a logged-in operator
54//! resolve *different* paths and would not contend. That is why
55//! `05-infrastructure.md` requires `service install` to record its resolved
56//! configuration and why `service status` reports it. A future host-wide
57//! machine lock (`%ProgramData%`, `/var/lock`) would need the installer to
58//! create it with the right ownership, which is `d3`'s territory, not this
59//! module's.
60
61use std::fmt;
62use std::fs::{File, OpenOptions};
63use std::io::{Read, Seek, SeekFrom, Write};
64use std::path::{Path, PathBuf};
65use std::time::{Duration, Instant};
66
67use chrono::{DateTime, Utc};
68use serde::{Deserialize, Serialize};
69
70use crate::paths::AppPaths;
71use crate::process::{Adoption, ProcessIdentity};
72
73/// Which host-wide operation is being excluded.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(rename_all = "snake_case")]
76pub enum LockKind {
77    /// Held for the whole life of the agent process. One holder per host means
78    /// one reconciler per host.
79    SingleInstance,
80    /// Held only while one runtime is being created, so that two concurrent
81    /// allocations cannot both read the same headroom and both use it.
82    Allocation,
83    /// Held while one process rotates the credential shared by a service and
84    /// foreground tools.
85    CredentialRenewal,
86    /// Held while a launch leases a dependency-cache namespace, or while a
87    /// prune moves an idle one aside, so a prune never takes a namespace a
88    /// runner is about to use. It lives in the cache root, not in `state/`.
89    DependencyCache,
90}
91
92impl LockKind {
93    /// The file this lock lives in, inside `state/`.
94    #[must_use]
95    pub const fn file_name(self) -> &'static str {
96        match self {
97            Self::SingleInstance => "agent.lock",
98            Self::Allocation => "allocation.lock",
99            Self::CredentialRenewal => "credential-renewal.lock",
100            Self::DependencyCache => ".lock",
101        }
102    }
103
104    /// How to name this lock to an operator.
105    #[must_use]
106    pub const fn description(self) -> &'static str {
107        match self {
108            Self::SingleInstance => "the single-instance agent lock",
109            Self::Allocation => "the runtime allocation lock",
110            Self::CredentialRenewal => "the credential-renewal lock",
111            Self::DependencyCache => "the dependency-cache lock",
112        }
113    }
114
115    /// What an operator who lost the race should do about it. Present because
116    /// "the lock is held" is a statement and not yet an instruction.
117    #[must_use]
118    pub const fn advice(self) -> &'static str {
119        match self {
120            Self::SingleInstance => {
121                "Only one agent may reconcile policies on a host. Stop the other agent, or wait \
122                 for it to exit; the operating system releases this lock when that process ends, \
123                 including after a crash, so there is never anything to clean up by hand."
124            }
125            Self::Allocation => {
126                "This lock is held only for as long as it takes to create one runtime. Retry \
127                 shortly."
128            }
129            Self::CredentialRenewal => {
130                "This lock is held only while one process rotates the shared credential. Retry \
131                 shortly."
132            }
133            Self::DependencyCache => {
134                "This lock is held only while a runner leases its cache or a prune moves an idle \
135                 cache aside. Retry shortly."
136            }
137        }
138    }
139}
140
141impl fmt::Display for LockKind {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.write_str(self.description())
144    }
145}
146
147/// Who holds a lock, as recorded by the holder itself.
148///
149/// Written into the lock file after the lock is taken, so that the process
150/// that loses the race can say something useful instead of "somebody else".
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152pub struct LockHolder {
153    /// The holder's process identity — a PID alone would not survive being
154    /// read back by a process that started after a reboot.
155    pub identity: ProcessIdentity,
156    /// The holder's executable, when it could be resolved. `05-infrastructure.md`
157    /// requires `service status` to report a stale or moved binary path, and
158    /// an operator looking at a contended lock has the same question.
159    pub executable: Option<PathBuf>,
160    /// When the lock was taken.
161    pub acquired_at: DateTime<Utc>,
162    /// Which lock the record belongs to. Recorded so that a file opened by
163    /// mistake is recognised rather than misreported.
164    pub lock: LockKind,
165}
166
167impl fmt::Display for LockHolder {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        write!(f, "process {}", self.identity.pid())?;
170        if let Some(executable) = &self.executable {
171            write!(f, " ({})", executable.display())?;
172        }
173        write!(f, ", holding since {}", self.acquired_at.to_rfc3339())
174    }
175}
176
177/// Something went wrong taking or inspecting a lock.
178#[derive(Debug, thiserror::Error)]
179pub enum LockError {
180    /// Somebody else has it.
181    #[error(
182        "{kind} ({}) is already held on this host by {}. {} [refused with {}]",
183        path.display(),
184        describe(holder.as_deref()),
185        kind.advice(),
186        describe_refusal(*refused_with)
187    )]
188    Held {
189        /// Which lock.
190        kind: LockKind,
191        /// Where the lock file is, so the message is actionable on a host with
192        /// a non-default layout.
193        path: PathBuf,
194        /// Who holds it, when the record could be read. `None` is not the same
195        /// as "nobody": it means the holder had not finished identifying
196        /// itself, which is a race of microseconds and not a reason to proceed.
197        ///
198        /// Boxed because this variant travels inside a `Result` that `e1`
199        /// carries across a `spawn_blocking` boundary, and an inline
200        /// `LockHolder` makes that `Err` large enough for clippy's
201        /// `result_large_err` to refuse the build. The indirection costs one
202        /// allocation on a path that has already lost a lock race.
203        holder: Option<Box<LockHolder>>,
204        /// The operating system code the refusal actually carried.
205        ///
206        /// # Why an errno is in a user-facing message
207        ///
208        /// This variant has two causes that look identical once it is
209        /// constructed: the lock is genuinely somebody else's, or the operating
210        /// system said "would block" for a reason this code does not model. The
211        /// second is not hypothetical — a refusal that no reading of this
212        /// module explains has been seen in CI on both Unix platforms, for a
213        /// lock the same process had just released, and there was nothing in
214        /// the message to tell the two apart.
215        ///
216        /// Carrying the raw code costs a few characters and turns the next
217        /// occurrence from a mystery into a report. `None` where the platform
218        /// excluded at the open rather than at the lock call.
219        refused_with: Option<i32>,
220    },
221
222    /// The lock file could not be opened, read, or written.
223    #[error("cannot use the lock file {}: {source}", path.display())]
224    Io {
225        /// The lock file.
226        path: PathBuf,
227        /// The underlying error.
228        #[source]
229        source: std::io::Error,
230    },
231
232    /// The holder's own identity could not be read, so it could not record who
233    /// it is.
234    #[error("cannot record this process as the holder of {kind}: {source}")]
235    Identity {
236        /// Which lock.
237        kind: LockKind,
238        /// The underlying error.
239        #[source]
240        source: crate::process::ProcessError,
241    },
242}
243
244/// Renders the holder half of a [`LockError::Held`] message.
245fn describe(holder: Option<&LockHolder>) -> String {
246    match holder {
247        Some(holder) => holder.to_string(),
248        None => "a process that has not finished identifying itself".to_string(),
249    }
250}
251
252/// A held lock. Releasing it is dropping it.
253///
254/// There is no `release()` returning a `Result`, deliberately: releasing is
255/// closing a file descriptor, the kernel does it whether this program asks or
256/// not, and an API that suggested release could fail would invite a caller to
257/// handle a failure that does not exist.
258#[derive(Debug)]
259pub struct HostLock {
260    /// Held open for the lock's whole life. Closing it *is* the release, which
261    /// is why this field exists even though nothing reads it after
262    /// acquisition.
263    file: File,
264    path: PathBuf,
265    kind: LockKind,
266}
267
268impl HostLock {
269    /// Takes the lock, or reports who has it, without waiting.
270    ///
271    /// # Errors
272    ///
273    /// [`LockError::Held`] when another process has it, [`LockError::Io`] when
274    /// the lock file cannot be opened, and [`LockError::Identity`] when this
275    /// process cannot describe itself.
276    pub fn try_acquire(paths: &AppPaths, kind: LockKind) -> Result<Self, LockError> {
277        Self::try_acquire_at(&paths.state_dir().join(kind.file_name()), kind)
278    }
279
280    /// Takes the lock, retrying until `wait` elapses.
281    ///
282    /// `e1` takes the allocation lock before each runtime it creates, and brief
283    /// contention there is expected rather than exceptional, so waiting a
284    /// little is the right default for that caller. The single-instance lock
285    /// should normally use [`HostLock::try_acquire`]: a second agent is a
286    /// configuration problem, and waiting for it makes the problem quieter
287    /// rather than fixing it.
288    ///
289    /// # This blocks the calling thread
290    ///
291    /// The retry loop is `std::thread::sleep`, not a timer an executor can
292    /// park. `e1` takes the allocation lock from inside async reconciliation,
293    /// and calling this directly from a `tokio` task blocks a worker thread for
294    /// up to `wait` — starving every other task scheduled on it, and with a
295    /// current-thread runtime deadlocking against the very task that would
296    /// release the lock. **Async callers must wrap it in
297    /// [`tokio::task::spawn_blocking`]**, which is also where the returned
298    /// [`HostLock`] should then live, since dropping it is the release.
299    ///
300    /// [`HostLock::try_acquire`] does not block and is safe to call inline.
301    ///
302    /// # Errors
303    ///
304    /// As [`HostLock::try_acquire`], reporting the last holder seen.
305    pub fn acquire(paths: &AppPaths, kind: LockKind, wait: Duration) -> Result<Self, LockError> {
306        Self::acquire_at(&paths.state_dir().join(kind.file_name()), kind, wait)
307    }
308
309    /// [`HostLock::try_acquire`] against an explicit path.
310    ///
311    /// # Errors
312    ///
313    /// As [`HostLock::try_acquire`].
314    pub fn try_acquire_at(path: &Path, kind: LockKind) -> Result<Self, LockError> {
315        if let Some(parent) = path.parent() {
316            std::fs::create_dir_all(parent).map_err(|source| LockError::Io {
317                path: path.to_path_buf(),
318                source,
319            })?;
320        }
321
322        // Best effort in both contention branches below: an unreadable or
323        // half-written record makes the message vaguer, and is never a reason
324        // to behave as if the lock were free.
325        let held = |path: &Path, refused_with: Option<i32>| LockError::Held {
326            kind,
327            path: path.to_path_buf(),
328            holder: read_holder(path).ok().flatten().map(Box::new),
329            refused_with,
330        };
331
332        let file = match open_for_locking(path) {
333            Ok(file) => file,
334            // Windows excludes at the open itself, through the share mode, so
335            // this is where contention surfaces there. On Unix nothing fails
336            // the open for contention and this arm never fires.
337            Err(source) if sys::is_contention(&source) => {
338                return Err(held(path, source.raw_os_error()));
339            }
340            Err(source) => return Err(io_error(path, source)),
341        };
342
343        match sys::try_lock(&file).map_err(|source| io_error(path, source))? {
344            Acquired::Yes => {}
345            Acquired::No { refused_with } => return Err(held(path, refused_with)),
346        }
347
348        let lock = Self {
349            file,
350            path: path.to_path_buf(),
351            kind,
352        };
353        lock.record_holder()?;
354        Ok(lock)
355    }
356
357    /// [`HostLock::acquire`] against an explicit path.
358    ///
359    /// # Errors
360    ///
361    /// As [`HostLock::try_acquire`].
362    pub fn acquire_at(path: &Path, kind: LockKind, wait: Duration) -> Result<Self, LockError> {
363        let deadline = Instant::now() + wait;
364        loop {
365            match Self::try_acquire_at(path, kind) {
366                Ok(lock) => return Ok(lock),
367                Err(error @ LockError::Held { .. }) => {
368                    if Instant::now() >= deadline {
369                        return Err(error);
370                    }
371                    std::thread::sleep(RETRY_INTERVAL);
372                }
373                Err(other) => return Err(other),
374            }
375        }
376    }
377
378    /// Reads the holder record of a lock without trying to take it.
379    ///
380    /// Answers `Ok(None)` when the file does not exist or carries no readable
381    /// record. It deliberately says nothing about whether the lock is *held*:
382    /// the record outlives its writer by design, and the only authority on
383    /// whether a lock is free is trying to take it.
384    ///
385    /// # Errors
386    ///
387    /// [`LockError::Io`] when the file exists but cannot be read.
388    pub fn holder_of(path: &Path) -> Result<Option<LockHolder>, LockError> {
389        read_holder(path)
390    }
391
392    /// Where the lock file is.
393    #[must_use]
394    pub fn path(&self) -> &Path {
395        &self.path
396    }
397
398    /// Which lock this is.
399    #[must_use]
400    pub const fn kind(&self) -> LockKind {
401        self.kind
402    }
403
404    /// Whether the recorded holder of `path` is still running.
405    ///
406    /// For diagnostics — `host show` reporting a lock whose record names a
407    /// process that no longer exists tells an operator something a bare
408    /// "locked/unlocked" does not.
409    ///
410    /// # Errors
411    ///
412    /// [`LockError::Io`] when the record cannot be read.
413    pub fn recorded_holder_is_live(path: &Path) -> Result<bool, LockError> {
414        let Some(holder) = read_holder(path)? else {
415            return Ok(false);
416        };
417        Ok(matches!(holder.identity.recheck(), Ok(Adoption::Live)))
418    }
419
420    /// Writes this process's identity into the lock file.
421    ///
422    /// Runs *after* the lock is taken, which leaves a window of a few
423    /// microseconds in which a loser sees the previous holder's record or none
424    /// at all. That is why [`LockError::Held`] carries an `Option` and why the
425    /// message for `None` says the holder has not identified itself yet, rather
426    /// than implying the lock might be free.
427    fn record_holder(&self) -> Result<(), LockError> {
428        let holder = LockHolder {
429            identity: ProcessIdentity::of_current_process().map_err(|source| {
430                LockError::Identity {
431                    kind: self.kind,
432                    source,
433                }
434            })?,
435            executable: std::env::current_exe().ok(),
436            acquired_at: Utc::now(),
437            lock: self.kind,
438        };
439
440        let encoded = serde_json::to_vec_pretty(&holder).map_err(|source| {
441            io_error(
442                &self.path,
443                std::io::Error::new(std::io::ErrorKind::InvalidData, source),
444            )
445        })?;
446
447        let mut file = &self.file;
448        file.seek(SeekFrom::Start(0))
449            .map_err(|source| io_error(&self.path, source))?;
450        // The previous holder's record is longer or shorter than this one; a
451        // write without a truncate would leave its tail behind and produce
452        // unparseable JSON for the next reader.
453        file.set_len(0)
454            .map_err(|source| io_error(&self.path, source))?;
455        file.write_all(&encoded)
456            .map_err(|source| io_error(&self.path, source))?;
457        file.flush()
458            .map_err(|source| io_error(&self.path, source))?;
459        // Durable before the caller does anything with the lock: a record that
460        // is only in the page cache is not there for the operator diagnosing
461        // the machine that just stopped responding.
462        file.sync_all()
463            .map_err(|source| io_error(&self.path, source))
464    }
465}
466
467fn io_error(path: &Path, source: std::io::Error) -> LockError {
468    LockError::Io {
469        path: path.to_path_buf(),
470        source,
471    }
472}
473
474/// How often [`HostLock::acquire_at`] retries. Short enough that an allocation
475/// waiting on the lock is not noticeably delayed.
476const RETRY_INTERVAL: Duration = Duration::from_millis(25);
477
478/// What a non-blocking lock attempt answered, and — when it refused — why.
479///
480/// A bare `bool` threw away the one fact that would explain a refusal nobody
481/// can account for. See [`LockError::Held::refused_with`].
482#[derive(Debug, Clone, Copy, PartialEq, Eq)]
483// Windows excludes at the open, so its `try_lock` can only ever answer `Yes`
484// and the refusal arm is genuinely unreachable there. It is not dead code — it
485// is the whole answer on the two platforms that lock after opening.
486#[cfg_attr(windows, allow(dead_code))]
487pub(crate) enum Acquired {
488    Yes,
489    No { refused_with: Option<i32> },
490}
491
492/// Renders the refusal code for an operator, without pretending to interpret it.
493fn describe_refusal(code: Option<i32>) -> String {
494    match code {
495        Some(code) => format!("os error {code}"),
496        None => "the open itself, which is how this platform excludes".to_string(),
497    }
498}
499
500fn open_for_locking(path: &Path) -> std::io::Result<File> {
501    let mut options = OpenOptions::new();
502    // `truncate(false)` is explicit rather than implied: the previous holder's
503    // record must survive the open, because it is what a *loser* reads, and the
504    // loser's open is this same call.
505    options.read(true).write(true).create(true).truncate(false);
506    sys::prepare_for_locking(&mut options);
507    options.open(path)
508}
509
510fn read_holder(path: &Path) -> Result<Option<LockHolder>, LockError> {
511    let mut options = OpenOptions::new();
512    options.read(true);
513    sys::prepare_for_reading(&mut options);
514
515    let mut file = match options.open(path) {
516        Ok(file) => file,
517        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
518        Err(source) => return Err(io_error(path, source)),
519    };
520
521    let mut contents = String::new();
522    file.read_to_string(&mut contents)
523        .map_err(|source| io_error(path, source))?;
524
525    // An empty or half-written file is the acquisition race described on
526    // `HostLock::record_holder`, not a corrupt installation. Say "no record"
527    // and let the caller's message be vaguer.
528    Ok(serde_json::from_str(&contents).ok())
529}
530
531// ---------------------------------------------------------------------------
532// Platform implementations
533// ---------------------------------------------------------------------------
534
535#[cfg(windows)]
536mod sys {
537    use std::fs::{File, OpenOptions};
538    use std::io;
539    use std::os::windows::fs::OpenOptionsExt;
540
541    use windows::Win32::Storage::FileSystem::{
542        FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
543    };
544
545    /// The acquisition open. Sharing *read* only: a second acquirer also asks
546    /// for write access, which this share mode denies, so `CreateFile` fails
547    /// with `ERROR_SHARING_VIOLATION` before any lock call is needed. The
548    /// exclusion is the open itself, which is why `try_lock` below has nothing
549    /// left to do.
550    pub(super) fn prepare_for_locking(options: &mut OpenOptions) {
551        options.share_mode(FILE_SHARE_READ.0);
552    }
553
554    /// The diagnostic open. Read access only, and permissive sharing, so that
555    /// it is compatible with the holder's open in both directions: the holder
556    /// permits readers, and this permits the holder's read/write access.
557    pub(super) fn prepare_for_reading(options: &mut OpenOptions) {
558        options.share_mode(FILE_SHARE_READ.0 | FILE_SHARE_WRITE.0 | FILE_SHARE_DELETE.0);
559    }
560
561    /// Always `true` on Windows: if the open in `open_for_locking` succeeded,
562    /// this process is the exclusive writer, and when the process ends — for
563    /// any reason, including a crash — the kernel closes the handle and the
564    /// next acquirer's open succeeds.
565    pub(super) fn try_lock(_file: &File) -> io::Result<super::Acquired> {
566        Ok(super::Acquired::Yes)
567    }
568
569    /// Windows reports a share-mode conflict as `ERROR_SHARING_VIOLATION`, and
570    /// `std` maps it to a generic error, so the raw code is what identifies it.
571    pub(super) const SHARING_VIOLATION: i32 =
572        windows::Win32::Foundation::ERROR_SHARING_VIOLATION.0 as i32;
573
574    /// Whether an open failure means "somebody else holds it" rather than
575    /// something an operator should investigate.
576    pub(super) fn is_contention(error: &io::Error) -> bool {
577        error.raw_os_error() == Some(SHARING_VIOLATION)
578    }
579}
580
581#[cfg(unix)]
582mod sys {
583    use std::fs::{File, OpenOptions};
584    use std::io;
585    use std::os::unix::io::AsRawFd;
586
587    /// Nothing to prepare: on Unix the open is ordinary and the exclusion comes
588    /// from `flock` below.
589    pub(super) fn prepare_for_locking(_options: &mut OpenOptions) {}
590
591    pub(super) fn prepare_for_reading(_options: &mut OpenOptions) {}
592
593    /// `flock(LOCK_EX | LOCK_NB)`.
594    ///
595    /// Chosen over `fcntl` record locks for one reason that matters here:
596    /// `fcntl` locks are dropped when *any* file descriptor for the file is
597    /// closed by the process, so an unrelated `read_holder` in the same process
598    /// would silently release the agent's lock. `flock` locks belong to the
599    /// open file description and are immune to that.
600    pub(super) fn try_lock(file: &File) -> io::Result<super::Acquired> {
601        // SAFETY: `flock` takes a file descriptor and a flag word and touches
602        // no memory this program owns. The descriptor is valid for the life of
603        // `file`, which outlives the call.
604        let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
605        if result == 0 {
606            return Ok(super::Acquired::Yes);
607        }
608        let error = io::Error::last_os_error();
609        if is_contention(&error) {
610            return Ok(super::Acquired::No {
611                refused_with: error.raw_os_error(),
612            });
613        }
614        Err(error)
615    }
616
617    /// `EWOULDBLOCK` — and `EAGAIN`, which is the same number on Linux and
618    /// macOS but is written both ways in the documentation.
619    pub(super) fn is_contention(error: &io::Error) -> bool {
620        matches!(
621            error.raw_os_error(),
622            Some(code) if code == libc::EWOULDBLOCK || code == libc::EAGAIN
623        )
624    }
625}
626
627#[cfg(test)]
628mod tests {
629    use super::*;
630
631    use crate::process::{OutputMode, SpawnSpec};
632
633    /// The environment variable that turns `lock_holder_helper` below from a
634    /// no-op into a process that takes a lock and holds it until it is killed.
635    const HELPER_PATH: &str = "RUNNER_MANAGER_LOCK_HELPER_PATH";
636    /// What the helper prints once it holds the lock.
637    ///
638    /// Searched for *within* a line rather than at the start of one, because
639    /// libtest writes `test <name> ... ` with no trailing newline before the
640    /// test body runs — so the helper's first line of output is that prefix
641    /// followed by this marker, not the marker alone.
642    const HELPER_READY: &str = "@@LOCK-HELD@@";
643
644    fn lock_path(directory: &tempfile::TempDir, kind: LockKind) -> PathBuf {
645        directory.path().join(kind.file_name())
646    }
647
648    /// Takes the lock twice with `acquire` and reports whether exactly one
649    /// acquisition won.
650    ///
651    /// A helper returning `Result` rather than inline assertions, so that
652    /// `the_contention_check_catches_a_lock_that_never_excludes` can point it
653    /// at a lock that excludes nothing. A mutual-exclusion test that has only
654    /// ever been run against a working lock cannot distinguish "the lock works"
655    /// from "the test asserts nothing".
656    fn check_mutual_exclusion<G>(acquire: impl Fn() -> Result<G, LockError>) -> Result<(), String> {
657        let first = acquire().map_err(|error| format!("the first acquisition failed: {error}"))?;
658
659        let outcome = match acquire() {
660            Ok(_) => Err("both acquisitions succeeded; nothing is being excluded".to_string()),
661            Err(LockError::Held { .. }) => Ok(()),
662            Err(other) => Err(format!(
663                "the second acquisition failed, but not because the lock was held: {other}"
664            )),
665        };
666
667        drop(first);
668        outcome
669    }
670
671    #[test]
672    fn two_contenders_produce_exactly_one_holder() {
673        let directory = tempfile::tempdir().expect("a temporary directory");
674        let path = lock_path(&directory, LockKind::SingleInstance);
675
676        check_mutual_exclusion(|| HostLock::try_acquire_at(&path, LockKind::SingleInstance))
677            .expect("the single-instance lock must admit exactly one holder");
678    }
679
680    #[test]
681    fn the_contention_check_catches_a_lock_that_never_excludes() {
682        let complaint = check_mutual_exclusion(|| Ok::<(), LockError>(()))
683            .expect_err("a lock that excludes nothing must be caught");
684        assert!(
685            complaint.contains("nothing is being excluded"),
686            "the complaint must name the failure mode, got: {complaint}"
687        );
688    }
689
690    #[test]
691    fn releasing_the_lock_lets_the_next_contender_take_it() {
692        let directory = tempfile::tempdir().expect("a temporary directory");
693        let path = lock_path(&directory, LockKind::SingleInstance);
694
695        let first = HostLock::try_acquire_at(&path, LockKind::SingleInstance).expect("acquired");
696        assert!(HostLock::try_acquire_at(&path, LockKind::SingleInstance).is_err());
697        drop(first);
698
699        let second = HostLock::try_acquire_at(&path, LockKind::SingleInstance)
700            .expect("the lock must be free once the holder drops it");
701        assert_eq!(second.path(), path);
702        assert_eq!(second.kind(), LockKind::SingleInstance);
703    }
704
705    #[test]
706    fn independent_host_locks_do_not_contend_with_each_other() {
707        // `e1` takes the allocation lock while the agent already holds the
708        // single-instance lock. If those two shared a file, the agent would
709        // deadlock against itself on the first runtime it tried to create.
710        let directory = tempfile::tempdir().expect("a temporary directory");
711
712        let instance = HostLock::try_acquire_at(
713            &lock_path(&directory, LockKind::SingleInstance),
714            LockKind::SingleInstance,
715        )
716        .expect("the instance lock is free");
717
718        let allocation = HostLock::try_acquire_at(
719            &lock_path(&directory, LockKind::Allocation),
720            LockKind::Allocation,
721        )
722        .expect("the allocation lock is a different lock and must be free");
723
724        let renewal = HostLock::try_acquire_at(
725            &lock_path(&directory, LockKind::CredentialRenewal),
726            LockKind::CredentialRenewal,
727        )
728        .expect("the credential-renewal lock is a different lock and must be free");
729
730        assert_ne!(instance.path(), allocation.path());
731        assert_ne!(instance.path(), renewal.path());
732        assert_ne!(allocation.path(), renewal.path());
733        assert_ne!(
734            LockKind::SingleInstance.file_name(),
735            LockKind::Allocation.file_name()
736        );
737        assert_ne!(
738            LockKind::Allocation.file_name(),
739            LockKind::CredentialRenewal.file_name()
740        );
741    }
742
743    #[test]
744    fn the_loser_gets_a_message_naming_the_holder_and_saying_what_to_do() {
745        let directory = tempfile::tempdir().expect("a temporary directory");
746        let path = lock_path(&directory, LockKind::SingleInstance);
747
748        let _held = HostLock::try_acquire_at(&path, LockKind::SingleInstance).expect("acquired");
749        let error = HostLock::try_acquire_at(&path, LockKind::SingleInstance)
750            .expect_err("the second acquisition must fail");
751
752        let LockError::Held { holder, kind, .. } = &error else {
753            panic!("expected a contention error, got {error}");
754        };
755        assert_eq!(*kind, LockKind::SingleInstance);
756
757        let holder = holder.as_ref().expect("the holder recorded itself");
758        assert_eq!(holder.identity.pid(), std::process::id());
759        assert_eq!(holder.lock, LockKind::SingleInstance);
760        assert_eq!(
761            holder.executable.as_deref(),
762            std::env::current_exe().ok().as_deref()
763        );
764
765        let message = error.to_string();
766        assert!(
767            message.contains(&std::process::id().to_string()),
768            "the message must name the holding process: {message}"
769        );
770        assert!(
771            message.contains("Stop the other agent"),
772            "the message must say what to do, not only what happened: {message}"
773        );
774    }
775
776    #[test]
777    fn the_recorded_holder_survives_a_read_by_a_second_process_shape() {
778        // Reading the record must work while the lock is held — on Windows that
779        // is a share-mode question and it is easy to get wrong in a way that
780        // only shows up when it matters, because the only caller is the loser.
781        let directory = tempfile::tempdir().expect("a temporary directory");
782        let path = lock_path(&directory, LockKind::SingleInstance);
783
784        let _held = HostLock::try_acquire_at(&path, LockKind::SingleInstance).expect("acquired");
785
786        let holder = HostLock::holder_of(&path)
787            .expect("the record must be readable while the lock is held")
788            .expect("a record must be there");
789        assert_eq!(holder.identity.pid(), std::process::id());
790        assert!(HostLock::recorded_holder_is_live(&path).expect("readable"));
791    }
792
793    #[test]
794    fn a_stale_record_is_reported_as_not_live() {
795        let directory = tempfile::tempdir().expect("a temporary directory");
796        let path = lock_path(&directory, LockKind::SingleInstance);
797
798        // A record naming a process that has come and gone: exactly what a
799        // crashed holder leaves behind.
800        //
801        // THE CHILD HAS TO OUTLIVE ITS OWN IDENTITY LOOKUP.
802        //
803        // `SpawnSpec::spawn` reads `ProcessIdentity::of_child` immediately after
804        // starting the process, because the start token is what stops a reused
805        // pid from being mistaken for the original. A child that exits INSTANTLY
806        // -- `true` did -- can be gone before that read, and the spawn then
807        // fails with `NoSuchProcess` rather than yielding the identity this test
808        // needs. It blocked release 0.1.5 on the macOS leg, where a loaded
809        // runner made the race easy to lose.
810        //
811        // So the child sleeps briefly: long enough to be observed, short enough
812        // that waiting for it costs nothing. What is being tested is unchanged
813        // -- the record is stale by the time it is read, because `wait` below
814        // returns only after the process is gone.
815        let mut child = SpawnSpec::new(if cfg!(windows) { "cmd" } else { "sh" })
816            .args(if cfg!(windows) {
817                vec!["/C", "exit", "0"]
818            } else {
819                vec!["-c", "sleep 0.3"]
820            })
821            .spawn()
822            .expect("the child starts");
823        let identity = child.identity().clone();
824        child.wait().expect("the child exits");
825
826        let stale = LockHolder {
827            identity,
828            executable: None,
829            acquired_at: Utc::now(),
830            lock: LockKind::SingleInstance,
831        };
832        std::fs::write(&path, serde_json::to_vec(&stale).expect("serialisable")).expect("writable");
833
834        assert!(
835            !HostLock::recorded_holder_is_live(&path).expect("readable"),
836            "a record naming a dead process must not be reported as live"
837        );
838        // And the lock itself is free, because nothing holds the file.
839        HostLock::try_acquire_at(&path, LockKind::SingleInstance)
840            .expect("a stale record must not keep the lock held");
841    }
842
843    #[test]
844    fn an_unidentified_holder_still_reads_as_a_holder() {
845        // The microsecond between taking the lock and writing the record. The
846        // message gets vaguer; the exclusion does not, and the wording must not
847        // leave a reader thinking the lock might be free.
848        let no_record = describe(None);
849        assert!(
850            no_record.contains("not finished identifying itself"),
851            "an unidentified holder must still read as a holder: {no_record}"
852        );
853
854        let error = LockError::Held {
855            kind: LockKind::SingleInstance,
856            path: PathBuf::from("/var/lib/runner-manager/state/agent.lock"),
857            holder: None,
858            refused_with: Some(35),
859        };
860        let message = error.to_string();
861        assert!(message.contains("already held"), "{message}");
862        assert!(message.contains("agent.lock"), "{message}");
863        assert!(message.contains("Stop the other agent"), "{message}");
864        // The refusal code is in the message because this variant has two
865        // causes that are otherwise indistinguishable once constructed: a lock
866        // that really is somebody else's, and a refusal this module does not
867        // model. Without it, the second reads exactly like the first.
868        assert!(message.contains("os error 35"), "{message}");
869
870        let at_open = LockError::Held {
871            kind: LockKind::SingleInstance,
872            path: PathBuf::from("/var/lib/runner-manager/state/agent.lock"),
873            holder: None,
874            refused_with: None,
875        };
876        assert!(
877            at_open.to_string().contains("the open itself"),
878            "a platform that excludes at the open says so rather than showing a bare `None`: {at_open}"
879        );
880    }
881
882    #[test]
883    fn acquire_waits_and_then_reports_the_holder() {
884        let directory = tempfile::tempdir().expect("a temporary directory");
885        let path = lock_path(&directory, LockKind::Allocation);
886
887        let _held = HostLock::try_acquire_at(&path, LockKind::Allocation).expect("acquired");
888
889        let wait = Duration::from_millis(200);
890        let started = Instant::now();
891        let error = HostLock::acquire_at(&path, LockKind::Allocation, wait)
892            .expect_err("the lock is held for the whole window");
893        let elapsed = started.elapsed();
894
895        assert!(matches!(error, LockError::Held { .. }), "{error}");
896        assert!(
897            elapsed >= wait,
898            "acquire must actually wait; it returned after {elapsed:?} of a {wait:?} window"
899        );
900    }
901
902    #[test]
903    fn acquire_returns_immediately_when_the_lock_is_free() {
904        let directory = tempfile::tempdir().expect("a temporary directory");
905        let path = lock_path(&directory, LockKind::Allocation);
906
907        let started = Instant::now();
908        let lock = HostLock::acquire_at(&path, LockKind::Allocation, Duration::from_secs(30))
909            .expect("the lock is free");
910        assert!(
911            started.elapsed() < Duration::from_secs(5),
912            "a free lock must not be waited for"
913        );
914        drop(lock);
915    }
916
917    #[test]
918    fn try_acquire_uses_the_state_directory() {
919        let root = tempfile::tempdir().expect("a temporary directory");
920        let paths = AppPaths::rooted_at(root.path());
921
922        let lock = HostLock::try_acquire(&paths, LockKind::SingleInstance).expect("acquired");
923        assert_eq!(lock.path(), paths.state_dir().join("agent.lock"));
924        assert!(
925            lock.path().exists(),
926            "the lock file must have been created under state/, as 05-infrastructure.md says"
927        );
928    }
929
930    // -----------------------------------------------------------------------
931    // The cross-process half of the Definition of Done
932    // -----------------------------------------------------------------------
933
934    /// Runs as an ordinary no-op test, unless `RUNNER_MANAGER_LOCK_HELPER_PATH`
935    /// is set — in which case this process *is* the second contender: it takes
936    /// the lock named by that variable, announces that it has it, and then
937    /// waits to be killed.
938    ///
939    /// Re-executing the test binary is what makes a genuinely separate process
940    /// available without shipping a second binary. The two tests below drive
941    /// it.
942    #[test]
943    fn lock_holder_helper() {
944        let Some(path) = std::env::var_os(HELPER_PATH) else {
945            return;
946        };
947
948        let _lock = HostLock::try_acquire_at(Path::new(&path), LockKind::SingleInstance)
949            .expect("the helper must be able to take the lock");
950
951        println!("{HELPER_READY} {}", std::process::id());
952        let _ = std::io::stdout().flush();
953
954        // Long enough that the parent always kills it first, short enough that
955        // a parent which somehow died leaves nothing behind for long.
956        std::thread::sleep(Duration::from_secs(120));
957    }
958
959    /// Starts the helper and waits until it reports that it holds the lock.
960    fn start_helper(path: &Path) -> (crate::process::ChildProcess, u32) {
961        let executable = std::env::current_exe().expect("the test binary's own path");
962
963        let mut child = SpawnSpec::new(executable)
964            .args([
965                "--exact",
966                "lock::tests::lock_holder_helper",
967                // Without this, libtest swallows the helper's announcement and
968                // the parent waits forever for a line that was captured.
969                "--nocapture",
970                "--test-threads=1",
971            ])
972            .env(HELPER_PATH, path)
973            .output(OutputMode::Capture)
974            .spawn()
975            .expect("the helper process starts");
976
977        let stdout = child.take_stdout().expect("captured");
978        let (sender, receiver) = std::sync::mpsc::channel();
979        std::thread::spawn(move || {
980            use std::io::BufRead as _;
981            for line in std::io::BufReader::new(stdout).lines() {
982                let Ok(line) = line else { break };
983                if let Some((_, rest)) = line.split_once(HELPER_READY) {
984                    let _ = sender.send(rest.trim().to_string());
985                    return;
986                }
987            }
988            let _ = sender.send(String::new());
989        });
990
991        let announced = receiver
992            .recv_timeout(Duration::from_secs(60))
993            .expect("the helper must announce that it holds the lock");
994        let pid: u32 = announced
995            .parse()
996            .unwrap_or_else(|_| panic!("the helper announced {announced:?} instead of a PID"));
997
998        (child, pid)
999    }
1000
1001    #[test]
1002    fn two_processes_contending_produce_exactly_one_holder() {
1003        let directory = tempfile::tempdir().expect("a temporary directory");
1004        let path = lock_path(&directory, LockKind::SingleInstance);
1005
1006        let (mut helper, helper_pid) = start_helper(&path);
1007        assert_ne!(helper_pid, std::process::id());
1008
1009        let error = HostLock::try_acquire_at(&path, LockKind::SingleInstance)
1010            .expect_err("a second agent must not get the lock");
1011
1012        let LockError::Held { holder, .. } = &error else {
1013            panic!("expected a contention error, got {error}");
1014        };
1015        let holder = holder.as_ref().expect("the helper recorded itself");
1016        assert_eq!(
1017            holder.identity.pid(),
1018            helper_pid,
1019            "the record must name the process that actually holds it"
1020        );
1021        assert!(
1022            error.to_string().contains(&helper_pid.to_string()),
1023            "the loser's message must name the holder: {error}"
1024        );
1025
1026        helper.stop(Duration::ZERO).expect("cleanup");
1027    }
1028
1029    #[test]
1030    fn killing_the_holder_releases_the_lock_with_no_manual_cleanup() {
1031        let directory = tempfile::tempdir().expect("a temporary directory");
1032        let path = lock_path(&directory, LockKind::SingleInstance);
1033
1034        let (mut helper, helper_pid) = start_helper(&path);
1035        assert!(
1036            HostLock::try_acquire_at(&path, LockKind::SingleInstance).is_err(),
1037            "the helper holds it"
1038        );
1039
1040        // `Duration::ZERO` leaves the helper no grace period. On Windows that
1041        // is literally straight to `TerminateProcess`, because there is no
1042        // signal to send; on Unix a SIGTERM is still sent first, but the grace
1043        // period it is given is zero, so SIGKILL follows before the helper can
1044        // act on it. Either way no destructor and no cleanup code runs, which
1045        // is the point: this is a crash, not a shutdown.
1046        helper.stop(Duration::ZERO).expect("the helper is killed");
1047        assert!(!helper.is_running().expect("observable"));
1048
1049        // Nothing is deleted, nothing is reset, no PID file is reaped: the next
1050        // acquisition simply succeeds.
1051        let recovered = HostLock::try_acquire_at(&path, LockKind::SingleInstance)
1052            .unwrap_or_else(|error| panic!("the lock leaked after its holder was killed: {error}"));
1053
1054        assert!(
1055            path.exists(),
1056            "the lock file itself must survive; deleting it is how two processes end up \
1057             locking different inodes"
1058        );
1059
1060        let holder = HostLock::holder_of(&path)
1061            .expect("readable")
1062            .expect("the new holder recorded itself");
1063        assert_eq!(holder.identity.pid(), std::process::id());
1064        assert_ne!(
1065            holder.identity.pid(),
1066            helper_pid,
1067            "the record must have been replaced, not inherited"
1068        );
1069        drop(recovered);
1070    }
1071}