Skip to content

The agent that grows with you

fix(update): A7 marker mutex, one incarnation rule, delegate-aware release, checkout custody

Tekniuma66193a8c780
diff --git a/apps/bootstrap-installer/src-tauri/src/marker.rs b/apps/bootstrap-installer/src-tauri/src/marker.rs
index 1345f0e3b2c..df35c60732e 100644
--- a/apps/bootstrap-installer/src-tauri/src/marker.rs
+++ b/apps/bootstrap-installer/src-tauri/src/marker.rs
@@ -26,9 +26,15 @@ use crate::update::UPDATE_EXIT_CONCURRENT;
/// <pid>
/// <started_at unix seconds>
/// ct:<owner process creation time, unix seconds, 3 decimals>
-/// delegate:<pid> ct:<ct> (optional; written by `hermes update`)
+/// delegate:<pid> ct:<ct> (optional; written by `hermes update` / the hand-off scripts)
+/// run:<id> (optional; the Desktop update run, A7 rule 6)
/// ```
///
+/// Every decision-and-mutation (reclaim, adopt, release, rewrite) runs while holding the
+/// kernel lock on the never-deleted sidecar `<marker>.lock` (A7 rule 1); only the exclusive
+/// first publish is lock-free. `tests/fixtures/update_marker_corpus.json` pins parse, liveness
+/// and release byte-for-byte across every implementation.
+///
/// Line 3 is absent in legacy (v1) markers. The creation time makes the pid
/// a process IDENTITY, so liveness never has to fall back to an age ceiling
/// (a live v2 owner is live however long it runs) and a recycled pid is not
@@ -43,9 +49,8 @@ use crate::update::UPDATE_EXIT_CONCURRENT;
/// rewrote the tree underneath it.
pub(crate) struct UpdateMarkerGuard {
path: PathBuf,
- /// Identity lines (pid, started_at, optional ct) of the claim we hold,
- /// compared before release so we never delete someone else's claim.
- claim: Option<Vec<String>>,
+ /// We published or adopted a claim (released per A7 rule 5 on `complete`/`Drop`).
+ claimed: bool,
}
/// Why `UpdateMarkerGuard::acquire` did not produce a claim.
@@ -83,12 +88,32 @@ struct MarkerRecord {
pid: u32,
started_at: u64,
ct: Option<f64>,
+ /// The `ct:` value exactly as written (a rewrite keeps it byte-identical).
+ ct_text: Option<String>,
+ /// The first well-formed `delegate:<pid> ct:<ct>` line at line 4 or later.
delegate: Option<(u32, f64)>,
- /// Lines 1-2 plus the `ct:` line when present: what an owner compares
- /// before deleting (a delegate line may come and go underneath it).
+ delegate_ct_text: Option<String>,
+ /// Every well-formed `run:<id>` line at line 4 or later (the first is THE run id).
+ runs: Vec<String>,
+ /// Lines 1-2 plus the `ct:` line when present.
+ #[cfg_attr(not(test), allow(dead_code))]
identity: Vec<String>,
}
+impl MarkerRecord {
+ /// A7 rule 5 rewrite: `pid` owns the claim from the original `started_at`; run lines kept.
+ fn canonical(&self, pid: u32, ct_text: Option<&str>) -> Vec<u8> {
+ let mut body = format!("{pid}\n{}\n", self.started_at);
+ if let Some(ct) = ct_text {
+ body.push_str(&format!("ct:{ct}\n"));
+ }
+ for run in &self.runs {
+ body.push_str(&format!("run:{run}\n"));
+ }
+ body.into_bytes()
+ }
+}
+
fn is_ascii_digits(text: &str) -> bool {
!text.is_empty() && text.bytes().all(|b| b.is_ascii_digit())
}
@@ -105,19 +130,31 @@ fn parse_ct_value(text: &str) -> Option<f64> {
text.parse().ok()
}
-/// Line 4 only: `delegate:<pid> ct:<ct>` with exactly one space.
-fn parse_delegate(line: &str) -> Option<(u32, f64)> {
+/// `delegate:<pid> ct:<ct>` with exactly one space.
+fn parse_delegate(line: &str) -> Option<(u32, f64, &str)> {
let (pid, ct) = line.strip_prefix("delegate:")?.split_once(' ')?;
if !is_ascii_digits(pid) {
return None;
}
- Some((pid.parse().ok()?, parse_ct_value(ct.strip_prefix("ct:")?)?))
+ let ct = ct.strip_prefix("ct:")?;
+ Some((pid.parse().ok()?, parse_ct_value(ct)?, ct))
}
-/// Parse a marker body (A2). `None` = malformed (dead): line 1 and line 2
-/// must be ASCII digits only after dropping one BOM, one trailing `\r` per
-/// line and surrounding spaces/tabs. A line 3 that is not a well-formed
-/// `ct:` makes a v1 marker; only line 4 can name a delegate.
+/// `run:<[A-Za-z0-9._-]{1,128}>` (A7 rule 6).
+fn parse_run(line: &str) -> Option<&str> {
+ let id = line.strip_prefix("run:")?;
+ let ok = (1..=128).contains(&id.len())
+ && id
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
+ ok.then_some(id)
+}
+
+/// Parse a marker body (A2 + A7 rule 7; `tests/fixtures/update_marker_corpus.json`). `None` =
+/// malformed (dead): line 1 (a u32 pid) and line 2 must be ASCII digits only after dropping one
+/// BOM, one trailing `\r` per line and surrounding spaces/tabs. A line 3 that is not a
+/// well-formed `ct:` makes a v1 marker. Lines 4+ are tagged: the first well-formed delegate line
+/// and every well-formed run line count; anything else is ignored.
fn parse_marker(raw: &[u8]) -> Option<MarkerRecord> {
let text = String::from_utf8_lossy(raw);
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
@@ -136,16 +173,27 @@ fn parse_marker(raw: &[u8]) -> Option<MarkerRecord> {
let pid = pid_line.parse().ok()?;
let started_at = started_line.parse().ok()?;
let ct_line = lines.get(2).copied().unwrap_or("");
- let ct = ct_line.strip_prefix("ct:").and_then(parse_ct_value);
+ let ct_text = ct_line
+ .strip_prefix("ct:")
+ .filter(|ct| parse_ct_value(ct).is_some());
let mut identity = vec![pid_line.to_string(), started_line.to_string()];
- if ct.is_some() {
+ if ct_text.is_some() {
identity.push(ct_line.to_string());
}
+ let tagged = lines.get(3..).unwrap_or(&[]);
+ let delegate = tagged.iter().find_map(|line| parse_delegate(line));
Some(MarkerRecord {
pid,
started_at,
- ct,
- delegate: lines.get(3).and_then(|line| parse_delegate(line)),
+ ct: ct_text.and_then(parse_ct_value),
+ ct_text: ct_text.map(str::to_string),
+ delegate: delegate.map(|(pid, ct, _)| (pid, ct)),
+ delegate_ct_text: delegate.map(|(_, _, text)| text.to_string()),
+ runs: tagged
+ .iter()
+ .filter_map(|line| parse_run(line))
+ .map(str::to_string)
+ .collect(),
identity,
})
}
@@ -157,135 +205,211 @@ fn unix_now_secs() -> u64 {
.unwrap_or(0)
}
-/// The process `pid` is alive AND is the process that recorded
-/// `recorded_ct` (A1). Only a confirmed creation-time match is unbounded:
-/// a v1 record, or a live pid whose creation time `probe` cannot read, is
-/// live only while the marker is within the v1 age ceiling — unreadable
-/// evidence must not hold a possibly recycled pid's lock forever.
-fn identity_live(
+/// The process facts a marker verdict depends on: who we are, the clock, and how to probe a pid.
+/// Production uses `World::real`; the shared corpus injects its own process table.
+struct World<'a> {
pid: u32,
- recorded_ct: Option<f64>,
- age_secs: u64,
- probe: &impl Fn(u32) -> Option<f64>,
-) -> bool {
- if !pid_is_alive(pid) {
+ /// Our own creation time; `None` only when it cannot be probed.
+ ct: Option<f64>,
+ now: u64,
+ alive: &'a dyn Fn(u32) -> bool,
+ ct_of: &'a dyn Fn(u32) -> Option<f64>,
+}
+
+impl World<'static> {
+ fn real() -> Self {
+ let pid = std::process::id();
+ World {
+ pid,
+ ct: process_creation_time(pid),
+ now: unix_now_secs(),
+ alive: &pid_is_alive,
+ ct_of: &process_creation_time,
+ }
+ }
+}
+
+/// Our own pid is our incarnation only within this epsilon (A7 rule 4, R12): the `ct:` we
+/// wrote is our exact creation time to 3 decimals, so anything further is a previous process
+/// that had our pid — never "close enough".
+const OWN_CT_EPSILON_SECS: f64 = 0.005;
+
+/// The process `pid` is alive AND is the process that recorded `recorded_ct` (A1, A7 rule 4).
+/// Our own pid must match our creation time exactly; a no-`ct` claim naming our pid is a
+/// previous incarnation (dead). Any other pid: only a confirmed creation-time match is
+/// unbounded; a v1 record, or a live pid whose creation time cannot be read, is live only while
+/// the marker is within the v1 age ceiling.
+fn identity_live(pid: u32, recorded_ct: Option<f64>, age_secs: u64, world: &World) -> bool {
+ if pid == 0 || !(world.alive)(pid) {
return false;
}
+ if pid == world.pid {
+ return match (recorded_ct, world.ct) {
+ (Some(recorded), Some(own)) => (recorded - own).abs() <= OWN_CT_EPSILON_SECS,
+ // Degraded: we cannot read our own creation time, so we write v1 claims ourselves.
+ (None, None) => true,
+ _ => false,
+ };
+ }
let within_ceiling = age_secs <= UPDATE_MARKER_MAX_AGE_SECS;
let Some(recorded) = recorded_ct else {
return within_ceiling;
};
- match probe(pid) {
+ match (world.ct_of)(pid) {
Some(actual) => (recorded - actual).abs() <= MARKER_CT_TOLERANCE_SECS,
None => within_ceiling,
}
}
-/// The live holder of a parsed marker, if any: the owner (lines 1-3) or,
-/// failing that, the delegate (line 4), both aged by the marker's
-/// `started_at`.
-fn marker_live_holder(
- record: &MarkerRecord,
- now_secs: u64,
- probe: &impl Fn(u32) -> Option<f64>,
-) -> Option<MarkerOwner> {
- let age_secs = now_secs.saturating_sub(record.started_at);
- if identity_live(record.pid, record.ct, age_secs, probe) {
+/// The live holder of a parsed marker, if any: the owner (lines 1-3) or, failing that, the
+/// delegate, both aged by the marker's `started_at`.
+fn marker_live_holder(record: &MarkerRecord, world: &World) -> Option<MarkerOwner> {
+ let age_secs = world.now.saturating_sub(record.started_at);
+ if identity_live(record.pid, record.ct, age_secs, world) {
return Some(MarkerOwner {
pid: record.pid,
age_secs,
});
}
match record.delegate {
- Some((pid, ct)) if identity_live(pid, Some(ct), age_secs, probe) => {
+ Some((pid, ct)) if identity_live(pid, Some(ct), age_secs, world) => {
Some(MarkerOwner { pid, age_secs })
}
_ => None,
}
}
-/// Process creation time as unix seconds, comparable with the `ct:` values
-/// `hermes_cli/update_lock.py` records. `None` when it cannot be probed.
-#[cfg(target_os = "linux")]
-fn process_creation_time(pid: u32) -> Option<f64> {
- let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
- // Field 22 (starttime, clock ticks since boot). The comm field may hold
- // spaces, so count from the closing paren: the field after it is #3.
- let after_comm = &stat[stat.rfind(')')? + 1..];
- let ticks: f64 = after_comm.split_whitespace().nth(22 - 3)?.parse().ok()?;
- let btime: f64 = std::fs::read_to_string("/proc/stat")
- .ok()?
- .lines()
- .find_map(|line| line.strip_prefix("btime "))?
- .trim()
- .parse()
- .ok()?;
- let clk_tck = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
- if clk_tck <= 0 {
- return None;
- }
- Some(btime + ticks / clk_tck as f64)
+/// What releasing our claim does to the marker bytes (A7 rule 5).
+#[derive(Debug, PartialEq)]
+enum Release {
+ Keep,
+ Delete,
+ Rewrite(Vec<u8>),
}
-#[cfg(target_os = "macos")]
-fn process_creation_time(pid: u32) -> Option<f64> {
- // proc_pidinfo(PROC_PIDTBSDINFO) reads the same kernel start time as
- // sysctl kern.proc.pid's kp_proc.p_starttime.
- let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
- let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
- let written = unsafe {
- libc::proc_pidinfo(
- pid as libc::c_int,
- libc::PROC_PIDTBSDINFO,
- 0,
- &mut info as *mut _ as *mut libc::c_void,
- size,
- )
+/// A7 rule 5. The owner (lines 1-3 are our exact incarnation) deletes the marker regardless of
+/// delegate lines, unless a LIVE delegate other than us exists: that delegate then inherits the
+/// claim (rewritten with it as owner). A delegate (us) drops its line while the owner lives,
+/// else deletes. A marker not naming us is kept.
+fn release_decision(raw: &[u8], world: &World) -> Release {
+ let Some(record) = parse_marker(raw) else {
+ return Release::Keep;
};
- if written != size {
- return None;
+ let age_secs = world.now.saturating_sub(record.started_at);
+ let owner_live = identity_live(record.pid, record.ct, age_secs, world);
+ let delegate_live = record
+ .delegate
+ .is_some_and(|(pid, ct)| identity_live(pid, Some(ct), age_secs, world));
+ let delegate_pid = record.delegate.map(|(pid, _)| pid);
+ if record.pid == world.pid && owner_live {
+ return match delegate_pid {
+ Some(pid) if pid != world.pid && delegate_live => {
+ Release::Rewrite(record.canonical(pid, record.delegate_ct_text.as_deref()))
+ }
+ _ => Release::Delete,
+ };
}
- Some(info.pbi_start_tvsec as f64 + info.pbi_start_tvusec as f64 / 1_000_000.0)
+ if delegate_pid == Some(world.pid) && delegate_live {
+ return if owner_live {
+ Release::Rewrite(record.canonical(record.pid, record.ct_text.as_deref()))
+ } else {
+ Release::Delete
+ };
+ }
+ Release::Keep
}
-#[cfg(windows)]
-fn process_creation_time(pid: u32) -> Option<f64> {
- use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
- use windows_sys::Win32::System::Threading::{
- GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
- };
+/// How long a marker mutation waits for another process's hold on the marker mutex.
+const MUTEX_WAIT: Duration = Duration::from_secs(10);
- const UNIX_EPOCH_AS_FILETIME: u64 = 116_444_736_000_000_000;
- let empty = || FILETIME {
- dwLowDateTime: 0,
- dwHighDateTime: 0,
- };
- let (mut creation, mut exit, mut kernel, mut user) = (empty(), empty(), empty(), empty());
- let ok = unsafe {
- let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
- if handle.is_null() {
- return None;
+/// `<marker>.lock`: the A7 rule 1 sidecar. Never deleted; holding its kernel lock serializes
+/// every marker decision-and-mutation across Python, this updater and the hand-off scripts.
+fn marker_mutex_path(path: &Path) -> PathBuf {
+ let name = path.file_name().unwrap_or_default().to_string_lossy();
+ path.with_file_name(format!("{name}.lock"))
+}
+
+/// A held marker mutex; the kernel lock is released when the file closes (also on a crash).
+struct MarkerMutex {
+ _file: std::fs::File,
+}
+
+/// A7 rule 1: hold the sidecar's kernel lock (POSIX `flock`; Windows an exclusive, share-none
+/// open — the same lock the PowerShell hand-off takes) for at most `MUTEX_WAIT`.
+/// `ErrorKind::WouldBlock` = another process held it the whole time.
+fn lock_marker(path: &Path) -> std::io::Result<MarkerMutex> {
+ let sidecar = marker_mutex_path(path);
+ let deadline = std::time::Instant::now() + MUTEX_WAIT;
+ loop {
+ if let Some(file) = try_lock_sidecar(&sidecar)? {
+ return Ok(MarkerMutex { _file: file });
}
- let ok = GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user);
- CloseHandle(handle);
- ok
+ if std::time::Instant::now() >= deadline {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::WouldBlock,
+ "another process holds the update marker mutex",
+ ));
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+}
+
+#[cfg(unix)]
+fn try_lock_sidecar(sidecar: &Path) -> std::io::Result<Option<std::fs::File>> {
+ use std::os::unix::io::AsRawFd;
+
+ let file = match std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .open(sidecar)
+ {
+ Ok(file) => file,
+ // flock needs no write access: a sidecar another user created still serializes us.
+ Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => {
+ std::fs::OpenOptions::new().read(true).open(sidecar)?
+ }
+ Err(err) => return Err(err),
};
- if ok == 0 {
- return None;
+ if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
+ return Ok(Some(file));
+ }
+ let err = std::io::Error::last_os_error();
+ match err.raw_os_error() {
+ Some(code) if code == libc::EWOULDBLOCK || code == libc::EINTR => Ok(None),
+ _ => Err(err),
}
- let ticks = (u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime);
- Some(ticks.checked_sub(UNIX_EPOCH_AS_FILETIME)? as f64 / 10_000_000.0)
}
-#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
-fn process_creation_time(_pid: u32) -> Option<f64> {
- None
+#[cfg(windows)]
+fn try_lock_sidecar(sidecar: &Path) -> std::io::Result<Option<std::fs::File>> {
+ use std::os::windows::fs::OpenOptionsExt;
+ const ERROR_ACCESS_DENIED: i32 = 5;
+ const ERROR_SHARING_VIOLATION: i32 = 32;
+
+ let opened = std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .share_mode(0)
+ .open(sidecar);
+ let opened = match opened {
+ Err(err) if err.raw_os_error() == Some(ERROR_ACCESS_DENIED) => std::fs::OpenOptions::new()
+ .read(true)
+ .share_mode(0)
+ .open(sidecar),
+ other => other,
+ };
+ match opened {
+ Ok(file) => Ok(Some(file)),
+ Err(err) if err.raw_os_error() == Some(ERROR_SHARING_VIOLATION) => Ok(None),
+ Err(err) => Err(err),
+ }
}
-/// Delete the marker only if its bytes still equal `expected` — the bytes a
-/// verdict was reached on, or the bytes we wrote. A marker replaced since
-/// (a new claim, an added delegate line) belongs to someone else's verdict.
-/// `Ok(true)` when the file is gone afterwards because of us.
+/// Delete the marker only if its bytes still equal `expected` (the bytes a verdict was reached
+/// on). Callers hold the marker mutex; the compare additionally spares a claim a non-locking
+/// legacy writer published meanwhile. `Ok(true)` when the file is gone because of us.
fn remove_if_unchanged(path: &Path, expected: &[u8]) -> std::io::Result<bool> {
match std::fs::read(path) {
Ok(current) if current == expected => match std::fs::remove_file(path) {
@@ -304,24 +428,35 @@ fn compare_and_delete(path: &Path, expected: &[u8]) -> bool {
remove_if_unchanged(path, expected).unwrap_or(false)
}
+/// Replace the marker with `body` (tmp + rename) while its bytes are still `expected`.
+fn replace_if_unchanged(path: &Path, expected: &[u8], body: &[u8]) -> std::io::Result<bool> {
+ let tmp = tmp_sibling(path);
+ let swapped = write_new_file(&tmp, body).and_then(|()| {
+ if std::fs::read(path)? != expected {
+ return Ok(false);
+ }
+ std::fs::rename(&tmp, path).map(|()| true)
+ });
+ let _ = std::fs::remove_file(&tmp);
+ swapped
+}
+
/// What is on disk at the marker path.
enum MarkerState {
Absent,
- /// A live holder, with the exact bytes judged.
- Live(MarkerOwner, Vec<u8>),
+ /// A live holder.
+ Live(MarkerOwner),
/// Dead / malformed / recycled / past the ceiling, compare-and-deleted.
/// Carries the error when the marker could not be read or removed (it
/// is then still on disk).
Dead(Option<std::io::Error>),
}
-/// Read and judge the marker. A dead verdict REMOVES the marker by
-/// compare-and-delete (only the exact bytes judged), mirroring
-/// `read_live_update` in `hermes_cli/update_lock.py`: a crashed updater
-/// whose `Drop` never ran must not wedge every later acquire (#77259).
-/// A 0-byte marker younger than `EMPTY_MARKER_GRACE` is a claim being
-/// written: live as pid 0 and never deleted.
-fn inspect_marker(path: &Path, probe: &impl Fn(u32) -> Option<f64>) -> MarkerState {
+/// Read and judge the marker; a dead verdict REMOVES it. The CALLER HOLDS the marker mutex
+/// (A7 rule 1), so the verdict and the delete are one critical section: a claim published by a
+/// lock-respecting process after our read can no longer be deleted on a stale verdict (R3).
+/// A 0-byte marker younger than `EMPTY_MARKER_GRACE` is a claim being written: live as pid 0.
+fn inspect_marker_locked(path: &Path, world: &World) -> MarkerState {
let raw = match std::fs::read(path) {
Ok(raw) => raw,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return MarkerState::Absent,
@@ -336,10 +471,10 @@ fn inspect_marker(path: &Path, probe: &impl Fn(u32) -> Option<f64>) -> MarkerSta
age_secs: age.as_secs(),
})
} else {
- parse_marker(&raw).and_then(|record| marker_live_holder(&record, unix_now_secs(), probe))
+ parse_marker(&raw).and_then(|record| marker_live_holder(&record, world))
};
match live {
- Some(owner) => MarkerState::Live(owner, raw),
+ Some(owner) => MarkerState::Live(owner),
None => MarkerState::Dead(remove_if_unchanged(path, &raw).err()),
}
}
@@ -356,35 +491,29 @@ fn empty_marker_age(path: &Path) -> Option<Duration> {
)
}
-/// Read the marker and report a live holder, if any. `None` for every "no
-/// live update" case — absent, unreadable, malformed, dead owner and
-/// delegate, a recycled pid (creation-time mismatch), or an unconfirmed
-/// identity past the age ceiling — matching `readLiveUpdateMarker` in the
-/// Electron gate. A dead marker is removed (see `inspect_marker`).
-///
-/// Self-PID is returned so `acquire` can adopt the desktop's pre-written claim
-/// without refreshing its acquisition time (#74761). A foreign live pid (e.g.
-/// a dashboard-spawned `hermes update`) still blocks.
+/// Read the marker (under its mutex) and report a live holder, if any; a dead marker is
+/// removed. Test-only view of `inspect_marker_locked`.
#[cfg(test)]
fn live_marker_owner(path: &Path) -> Option<MarkerOwner> {
- match inspect_marker(path, &process_creation_time) {
- MarkerState::Live(owner, _) => Some(owner),
+ let _mutex = lock_marker(path).ok()?;
+ match inspect_marker_locked(path, &World::real()) {
+ MarkerState::Live(owner) => Some(owner),
_ => None,
}
}
-/// True when the on-disk marker names THIS process as its owner.
+/// True when the on-disk marker's owner identity is THIS incarnation (A7 rule 4): our pid AND
+/// our creation time, never just a pid a previous process also had.
///
-/// Liveness is deliberately NOT consulted: the exit-2 self-heal below needs
-/// exactly one fact — does the marker name our PID — because a `hermes
-/// update` child that refuses over OUR marker is a handoff-recognition
-/// failure in a stale checkout, not a real concurrent update.
+/// Liveness of anything else is deliberately NOT consulted: the exit-2 self-heal below needs
+/// exactly one fact — is this our claim — because a `hermes update` child that refuses over
+/// OUR claim is a handoff-recognition failure in a stale checkout, not a concurrent update.
fn marker_owned_by_self(path: &Path) -> bool {
- std::fs::read(path)
- .ok()
- .and_then(|raw| parse_marker(&raw))
- .map(|record| record.pid)
- == Some(std::process::id())
+ let Some(record) = std::fs::read(path).ok().and_then(|raw| parse_marker(&raw)) else {
+ return false;
+ };
+ let world = World::real();
+ record.pid == world.pid && identity_live(record.pid, record.ct, 0, &world)
}
/// The exit-2 heal decision (#75788), extracted so the contract is testable.
@@ -399,6 +528,84 @@ pub(crate) fn should_heal_self_marker_refusal(exit_code: Option<i32>, marker_pat
exit_code == Some(UPDATE_EXIT_CONCURRENT) && marker_owned_by_self(marker_path)
}
+/// Process creation time as unix seconds, comparable with the `ct:` values
+/// `hermes_cli/update_lock.py` records. `None` when it cannot be probed.
+#[cfg(target_os = "linux")]
+fn process_creation_time(pid: u32) -> Option<f64> {
+ let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
+ // Field 22 (starttime, clock ticks since boot). The comm field may hold
+ // spaces, so count from the closing paren: the field after it is #3.
+ let after_comm = &stat[stat.rfind(')')? + 1..];
+ let ticks: f64 = after_comm.split_whitespace().nth(22 - 3)?.parse().ok()?;
+ let btime: f64 = std::fs::read_to_string("/proc/stat")
+ .ok()?
+ .lines()
+ .find_map(|line| line.strip_prefix("btime "))?
+ .trim()
+ .parse()
+ .ok()?;
+ let clk_tck = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
+ if clk_tck <= 0 {
+ return None;
+ }
+ Some(btime + ticks / clk_tck as f64)
+}
+
+#[cfg(target_os = "macos")]
+fn process_creation_time(pid: u32) -> Option<f64> {
+ // proc_pidinfo(PROC_PIDTBSDINFO) reads the same kernel start time as
+ // sysctl kern.proc.pid's kp_proc.p_starttime.
+ let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
+ let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int;
+ let written = unsafe {
+ libc::proc_pidinfo(
+ pid as libc::c_int,
+ libc::PROC_PIDTBSDINFO,
+ 0,
+ &mut info as *mut _ as *mut libc::c_void,
+ size,
+ )
+ };
+ if written != size {
+ return None;
+ }
+ Some(info.pbi_start_tvsec as f64 + info.pbi_start_tvusec as f64 / 1_000_000.0)
+}
+
+#[cfg(windows)]
+fn process_creation_time(pid: u32) -> Option<f64> {
+ use windows_sys::Win32::Foundation::{CloseHandle, FILETIME};
+ use windows_sys::Win32::System::Threading::{
+ GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
+ };
+
+ const UNIX_EPOCH_AS_FILETIME: u64 = 116_444_736_000_000_000;
+ let empty = || FILETIME {
+ dwLowDateTime: 0,
+ dwHighDateTime: 0,
+ };
+ let (mut creation, mut exit, mut kernel, mut user) = (empty(), empty(), empty(), empty());
+ let ok = unsafe {
+ let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
+ if handle.is_null() {
+ return None;
+ }
+ let ok = GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user);
+ CloseHandle(handle);
+ ok
+ };
+ if ok == 0 {
+ return None;
+ }
+ let ticks = (u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime);
+ Some(ticks.checked_sub(UNIX_EPOCH_AS_FILETIME)? as f64 / 10_000_000.0)
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
+fn process_creation_time(_pid: u32) -> Option<f64> {
+ None
+}
+
/// True when a process with `pid` currently exists.
#[cfg(windows)]
fn pid_is_alive(pid: u32) -> bool {
@@ -567,34 +774,6 @@ fn publish_claim(path: &Path, body: &[u8]) -> std::io::Result<Publish> {
}
}
-/// M1: `raw` is a live v1 marker naming us (Electron pre-wrote our pid).
-/// Upgrade it in place to v2 — lines 1-2 byte-identical (so `started_at`,
-/// the age, is preserved) plus our `ct:` line — via tmp + rename after
-/// re-checking the bytes are unchanged. `Ok(Some(body))` = upgraded,
-/// `Ok(None)` = the bytes changed underneath us (re-evaluate).
-fn upgrade_own_v1(path: &Path, raw: &[u8], ct: f64) -> std::io::Result<Option<Vec<u8>>> {
- let line2_end = raw
- .iter()
- .enumerate()
- .filter(|(_, b)| **b == b'\n')
- .nth(1)
- .map(|(index, _)| index + 1);
- let mut body = match line2_end {
- Some(end) => raw[..end].to_vec(),
- None => [raw, b"\n"].concat(),
- };
- body.extend_from_slice(format!("ct:{ct:.3}\n").as_bytes());
- let tmp = tmp_sibling(path);
- let swapped = write_new_file(&tmp, &body).and_then(|()| {
- if std::fs::read(path)? != raw {
- return Ok(false);
- }
- std::fs::rename(&tmp, path).map(|()| true)
- });
- let _ = std::fs::remove_file(&tmp);
- Ok(swapped?.then_some(body))
-}
-
fn unwritable(path: &Path, err: &std::io::Error) -> AcquireError {
AcquireError::Unwritable(format!(
"Cannot lock this install for the update: {} is not writable ({err}). \
@@ -606,23 +785,19 @@ fn unwritable(path: &Path, err: &std::io::Error) -> AcquireError {
impl UpdateMarkerGuard {
/// Claim the marker, or report why not.
///
- /// The claim is an exclusive publish (`publish_claim`); an existing
- /// marker is never truncated and overwritten. If one exists and its
- /// holder is dead (or its bytes are unparseable) it is removed by
- /// compare-and-delete and the claim is retried ONCE; a live foreign
- /// holder is `Busy`. A marker naming our own live process (the desktop
- /// pre-writes our pid, #74761) is adopted without resetting its age; a
- /// v1 pre-write is upgraded to v2 with our creation time (M1) so a
- /// stale copy of it can never be mistaken for a later process that
- /// reuses our pid.
+ /// A7 rule 2: the claim is an exclusive publish (`publish_claim`) with no lock; an existing
+ /// marker is never truncated and overwritten. If one exists, the verdict and any mutation
+ /// happen under the marker mutex (rule 1): a dead holder (or unparseable bytes — including a
+ /// no-`ct` claim naming our own pid, a previous incarnation, rule 4) is removed and the
+ /// claim re-published inside the same hold; a live foreign holder is `Busy`; a claim that is
+ /// our exact incarnation is adopted.
///
/// A marker that cannot be written at all is `Unwritable`: the update
/// refuses rather than run unserialized against other updaters (m8).
pub(crate) fn acquire(path: PathBuf) -> Result<Self, AcquireError> {
- let pid = std::process::id();
- let own_ct = process_creation_time(pid);
- let mut body = format!("{pid}\n{}\n", unix_now_secs());
- if let Some(ct) = own_ct {
+ let world = World::real();
+ let mut body = format!("{}\n{}\n", world.pid, world.now);
+ if let Some(ct) = world.ct {
body.push_str(&format!("ct:{ct:.3}\n"));
}
if let Some(parent) = path.parent() {
@@ -631,62 +806,50 @@ impl UpdateMarkerGuard {
}
}
sweep_tmp_litter(&path);
- let mut retried = false;
- loop {
+ let claimed = |path: PathBuf| Self {
+ path,
+ claimed: true,
+ };
+ for _ in 0..3 {
match publish_claim(&path, body.as_bytes()) {
- Ok(Publish::Claimed) => {
- return Ok(Self {
- claim: parse_marker(body.as_bytes()).map(|record| record.identity),
- path,
- })
- }
+ Ok(Publish::Claimed) => return Ok(claimed(path)),
Ok(Publish::Exists) => {}
Err(err) => {
tracing::warn!(?path, %err, "could not create update-in-progress marker");
return Err(unwritable(&path, &err));
}
}
- match inspect_marker(&path, &process_creation_time) {
- MarkerState::Live(owner, raw) if owner.pid == pid => {
- let record = parse_marker(&raw).filter(|record| record.pid == pid);
- let upgraded = match (record.as_ref().and_then(|r| r.ct), own_ct) {
- (None, Some(ct)) => match upgrade_own_v1(&path, &raw, ct) {
- Ok(Some(upgraded)) => Some(upgraded),
- // Changed underneath us: judge the new bytes.
- Ok(None) => continue,
- Err(err) => {
- tracing::warn!(?path, %err, "could not upgrade own v1 marker");
- None
- }
- },
- _ => None,
- };
- let claim = match upgraded {
- Some(upgraded) => parse_marker(&upgraded),
- None => record,
- };
- return Ok(Self {
- path,
- claim: claim.map(|record| record.identity),
- });
- }
- MarkerState::Live(owner, _) => return Err(AcquireError::Busy(owner)),
- // One retry for everything else: a read or delete can fail
- // transiently while another process has the file open
- // (Windows sharing rules).
- MarkerState::Absent | MarkerState::Dead(_) if !retried => retried = true,
- MarkerState::Dead(Some(err)) => return Err(unwritable(&path, &err)),
- MarkerState::Absent | MarkerState::Dead(None) => {
- // Lost the race twice: something else is claiming this
- // path right now. Refuse rather than run unserialized.
- tracing::warn!(?path, "update marker changed under two claim attempts");
+ let _mutex = match lock_marker(&path) {
+ Ok(mutex) => mutex,
+ Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
return Err(AcquireError::Busy(MarkerOwner {
pid: 0,
age_secs: 0,
- }));
+ }))
+ }
+ Err(err) => return Err(unwritable(&marker_mutex_path(&path), &err)),
+ };
+ let world = World::real();
+ match inspect_marker_locked(&path, &world) {
+ MarkerState::Live(owner) if owner.pid == world.pid => return Ok(claimed(path)),
+ MarkerState::Live(owner) => return Err(AcquireError::Busy(owner)),
+ MarkerState::Dead(Some(err)) => return Err(unwritable(&path, &err)),
+ MarkerState::Absent | MarkerState::Dead(None) => {
+ match publish_claim(&path, body.as_bytes()) {
+ Ok(Publish::Claimed) => return Ok(claimed(path)),
+ // A non-locking exclusive creator won the path: judge it.
+ Ok(Publish::Exists) => {}
+ Err(err) => return Err(unwritable(&path, &err)),
+ }
}
}
}
+ // The path kept changing under three attempts: refuse rather than run unserialized.
+ tracing::warn!(?path, "update marker changed under three claim attempts");
+ Err(AcquireError::Busy(MarkerOwner {
+ pid: 0,
+ age_secs: 0,
+ }))
}
/// Release the marker as soon as every mutating stage has completed.
@@ -696,37 +859,36 @@ impl UpdateMarkerGuard {
/// alone therefore leaves a *successful* update looking active — a live
/// pid holding a fresh marker — which blocks desktop startup and every
/// other updater. Idempotent: `Drop` still runs and tolerates an
- /// already-removed marker.
+ /// already-removed (or handed-over) marker.
///
- /// Compare-and-delete only: the marker is removed only while its
- /// identity lines (1-3) are still ours. A `delegate:` line naming a LIVE
- /// `hermes update` leaves the marker to that delegate; a dead delegate's
- /// line does not stop us from releasing our own claim.
+ /// A7 rule 5 under the marker mutex (`release_decision`): our claim is removed regardless of
+ /// delegate lines, except that a LIVE `hermes update` delegate inherits it (the marker is
+ /// rewritten with that delegate as owner) instead of losing it.
pub(crate) fn complete(&self) {
- let Some(claim) = &self.claim else {
+ if !self.claimed {
return;
+ }
+ let _mutex = match lock_marker(&self.path) {
+ Ok(mutex) => mutex,
+ Err(err) => {
+ tracing::warn!(path = ?self.path, %err, "could not lock the update marker to release it");
+ return;
+ }
};
let Ok(raw) = std::fs::read(&self.path) else {
return;
};
- let Some(record) = parse_marker(&raw) else {
- return;
- };
- if &record.identity != claim {
- return;
- }
- if let Some((delegate_pid, delegate_ct)) = record.delegate {
- let age_secs = unix_now_secs().saturating_sub(record.started_at);
- if identity_live(
- delegate_pid,
- Some(delegate_ct),
- age_secs,
- &process_creation_time,
- ) {
- return;
+ match release_decision(&raw, &World::real()) {
+ Release::Keep => {}
+ Release::Delete => {
+ compare_and_delete(&self.path, &raw);
+ }
+ Release::Rewrite(body) => {
+ if let Err(err) = replace_if_unchanged(&self.path, &raw, &body) {
+ tracing::warn!(path = ?self.path, %err, "could not hand the update marker to its delegate");
+ }
}
}
- compare_and_delete(&self.path, &raw);
}
}
@@ -737,1062 +899,5 @@ impl Drop for UpdateMarkerGuard {
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn update_marker_guard_writes_then_removes_on_drop() {
- let dir = unique_tmp_dir("marker-guard");
- std::fs::create_dir_all(&dir).unwrap();
- let marker = dir.join(".hermes-update-in-progress");
-
- {
- let _g = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("no live owner => acquire must succeed"));
- assert!(marker.exists(), "marker must exist while the guard is held");
- let body = std::fs::read_to_string(&marker).unwrap();
- let pid_line = body.lines().next().unwrap();
- assert_eq!(
- pid_line.trim().parse::<u32>().unwrap(),
- std::process::id(),
- "marker records our pid so the desktop can probe liveness"
- );
- assert_eq!(
- body.lines().count(),
- 3,
- "marker is pid + started_at + ct lines"
- );
- assert!(
- body.ends_with('\n'),
- "contract C1 bodies end with a newline"
- );
- let ct = parse_marker(body.as_bytes()).and_then(|record| record.ct);
- assert!(ct.is_some(), "a v2 claim records the owner's creation time");
- }
-
- assert!(
- !marker.exists(),
- "Drop must remove the marker on every exit path (incl. early return / panic unwind)"
- );
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn update_marker_guard_drop_is_quiet_when_already_gone() {
- let dir = unique_tmp_dir("marker-guard-gone");
- std::fs::create_dir_all(&dir).unwrap();
- let marker = dir.join(".hermes-update-in-progress");
-
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("no live owner => acquire must succeed"));
- // Simulate an external cleanup (e.g. the desktop pruned a marker it
- // judged stale) before our guard drops — Drop must not panic.
- std::fs::remove_file(&marker).unwrap();
- drop(guard);
-
- assert!(!marker.exists());
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- /// Spawn a short-lived sibling process whose pid stands in for a foreign
- /// updater. Same-process double-acquire no longer models contention: since
- /// #74761 `acquire` treats our own pid as adoptable (desktop pre-writes it),
- /// so a second acquire in *this* process would succeed.
- fn spawn_foreign_holder() -> std::process::Child {
- #[cfg(windows)]
- {
- std::process::Command::new("timeout")
- .args(["/t", "30", "/nobreak"])
- .stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- .spawn()
- .expect("spawn foreign marker holder")
- }
- #[cfg(not(windows))]
- {
- std::process::Command::new("sleep")
- .arg("30")
- .stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- .spawn()
- .expect("spawn foreign marker holder")
- }
- }
-
- #[test]
- fn acquire_refuses_while_a_live_updater_owns_the_marker() {
- let dir = unique_tmp_dir("marker-contended");
- std::fs::create_dir_all(&dir).unwrap();
- let marker = dir.join(".hermes-update-in-progress");
-
- // A live *foreign* updater holds it. We must NOT clobber the marker and
- // run concurrently over the same checkout — that race is what let a
- // dashboard `hermes update` and install-mode bootstrap mutate one tree
- // at once. Own-pid markers are adoptable (#74761), so the foreign pid
- // must be a real sibling process.
- let mut foreign = spawn_foreign_holder();
- let foreign_pid = foreign.id();
- let started_at = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0);
- std::fs::write(&marker, format!("{foreign_pid}\n{started_at}")).unwrap();
-
- let owner = busy(UpdateMarkerGuard::acquire(marker.clone()));
- assert_eq!(owner.pid, foreign_pid);
-
- // The refused guard must not delete the live owner's marker.
- assert!(
- marker.exists(),
- "refused acquire must leave the marker intact"
- );
- let _ = foreign.kill();
- let _ = foreign.wait();
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn acquire_adopts_a_marker_prewritten_with_our_own_pid() {
- // #74761: desktop writeUpdateMarker(hermesHome, child.pid) races ahead
- // of UpdateMarkerGuard::acquire. The marker names US; refusing it made
- // every in-app desktop update loop forever. Adopt it without resetting
- // the holder age, so a wedged updater still reaches the stale ceiling.
- let dir = unique_tmp_dir("marker-own-pid");
- std::fs::create_dir_all(&dir).unwrap();
- let marker = dir.join(".hermes-update-in-progress");
-
- let started_at = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0)
- .saturating_sub(2);
- std::fs::write(&marker, format!("{}\n{started_at}", std::process::id())).unwrap();
-
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("own-pid pre-write must be adoptable"));
- assert!(marker.exists(), "adopted guard must own the marker");
- let body = std::fs::read_to_string(&marker).unwrap();
- assert_eq!(
- body.lines().next().unwrap().trim().parse::<u32>().unwrap(),
- std::process::id(),
- "acquire keeps the adopted marker owner"
- );
- assert_eq!(
- body.lines().nth(1).unwrap().trim().parse::<u64>().unwrap(),
- started_at,
- "adopting an own-pid marker must preserve its original holder age"
- );
- drop(guard);
- assert!(
- !marker.exists(),
- "Drop must still clear the marker we adopted"
- );
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- // ---- exit-2 self-marker heal (#75788) --------------------------------
- // The deadlock: the updater holds the marker with its own PID; a stale
- // checkout's `hermes update` reads it as a live foreign update and exits
- // 2; the generic retry deliberately skips exit 2 — so the refusal loops
- // forever. These tests pin the heal decision's full contract. On
- // merge-base product code (no heal) the decision function does not exist
- // and the refusal is terminal — the A/B run proves that.
-
- #[test]
- fn self_owned_marker_plus_exit_2_heals() {
- let dir = unique_tmp_dir("heal-self-owned");
- let marker = dir.join(".hermes-update-in-progress");
- std::fs::write(&marker, format!("{}\n123\n", std::process::id())).unwrap();
-
- assert!(
- should_heal_self_marker_refusal(Some(UPDATE_EXIT_CONCURRENT), &marker),
- "a child refusing over OUR marker is the #75788 deadlock — must heal"
- );
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn foreign_owned_marker_never_heals() {
- let dir = unique_tmp_dir("heal-foreign");
- let marker = dir.join(".hermes-update-in-progress");
- // A live sibling process stands in for a genuinely concurrent updater.
- let mut foreign = spawn_foreign_holder();
- std::fs::write(&marker, format!("{}\n123\n", foreign.id())).unwrap();
-
- assert!(
- !should_heal_self_marker_refusal(Some(UPDATE_EXIT_CONCURRENT), &marker),
- "a foreign owner is a REAL concurrent update — the refusal must stand"
- );
- let _ = foreign.kill();
- let _ = foreign.wait();
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn missing_or_garbage_marker_never_heals() {
- let dir = unique_tmp_dir("heal-garbage");
- let missing = dir.join("never-written");
- assert!(
- !should_heal_self_marker_refusal(Some(UPDATE_EXIT_CONCURRENT), &missing),
- "no marker on disk = the child refused over something else entirely"
- );
-
- let garbage = dir.join(".hermes-update-in-progress");
- std::fs::write(&garbage, "not-a-pid\n123\n").unwrap();
- assert!(
- !should_heal_self_marker_refusal(Some(UPDATE_EXIT_CONCURRENT), &garbage),
- "an unparseable marker must not be treated as ours"
- );
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn non_exit_2_outcomes_never_heal() {
- let dir = unique_tmp_dir("heal-wrong-exit");
- let marker = dir.join(".hermes-update-in-progress");
- std::fs::write(&marker, format!("{}\n123\n", std::process::id())).unwrap();
-
- for code in [Some(0), Some(1), Some(3), None] {
- assert!(
- !should_heal_self_marker_refusal(code, &marker),
- "heal is exit-2-only; exit {code:?} must keep its normal path"
- );
- }
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn heal_end_to_end_marker_lifecycle() {
- // The full deadlock-and-heal sequence with a REAL marker guard, as
- // run_update executes it: acquire (marker written with our pid) →
- // child exits 2 refusing our own claim → heal decision fires →
- // complete() drops the claim → the retry's precondition (no marker,
- // or a marker the child can now claim) holds.
- let dir = unique_tmp_dir("heal-e2e");
- let marker = dir.join(".hermes-update-in-progress");
-
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("no live owner => acquire must succeed"));
- assert!(
- marker.exists(),
- "updater holds the marker during the child run"
- );
-
- // Stale child refused over our claim:
- assert!(should_heal_self_marker_refusal(
- Some(UPDATE_EXIT_CONCURRENT),
- &marker
- ));
-
- // The heal drops the claim exactly as run_update does:
- guard.complete();
- assert!(
- !marker.exists(),
- "claim dropped — the one retry now runs with the marker absent"
- );
-
- // And with the marker gone the heal can never fire twice (the retry's
- // own exit 2, e.g. a genuinely still-running Hermes, stays terminal).
- assert!(!should_heal_self_marker_refusal(
- Some(UPDATE_EXIT_CONCURRENT),
- &marker
- ));
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn acquire_reclaims_a_marker_owned_by_a_dead_pid() {
- let dir = unique_tmp_dir("marker-dead-pid");
- std::fs::create_dir_all(&dir).unwrap();
- let marker = dir.join(".hermes-update-in-progress");
-
- // pid 1 exists everywhere, so fabricate a dead one: a very large pid
- // that no live process owns. A crashed updater must never wedge every
- // future update.
- let started_at = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0);
- std::fs::write(&marker, format!("4294967294\n{started_at}")).unwrap();
-
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("a dead owner must not block acquisition"));
- let body = std::fs::read_to_string(&marker).unwrap();
- assert_eq!(
- body.lines().next().unwrap().trim().parse::<u32>().unwrap(),
- std::process::id(),
- "reclaiming rewrites the marker with our pid"
- );
- drop(guard);
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn acquire_reclaims_a_marker_past_the_age_ceiling() {
- let dir = unique_tmp_dir("marker-stale-age");
- std::fs::create_dir_all(&dir).unwrap();
- let marker = dir.join(".hermes-update-in-progress");
-
- // LEGACY v1 marker (no ct line): our own live pid, but started past
- // the ceiling. Without a creation time the pid may be recycled, so
- // age still bounds a v1 claim. (v2 has no ceiling — see
- // v2_live_owner_is_never_aged_out.)
- let long_ago = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0)
- .saturating_sub(UPDATE_MARKER_MAX_AGE_SECS + 60);
- std::fs::write(&marker, format!("{}\n{long_ago}", std::process::id())).unwrap();
-
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("a marker past the ceiling must be reclaimable"));
- drop(guard);
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn live_marker_owner_removes_stale_marker_with_dead_pid() {
- // The core self-heal of #77259: a marker whose owner is gone must be
- // REMOVED on read (like read_live_update in update_lock.py), not just
- // ignored — otherwise the stale bytes keep failing every acquire
- // until the 20-minute age ceiling expires.
- let dir = unique_tmp_dir("marker-read-dead");
- let marker = dir.join(".hermes-update-in-progress");
- let started_at = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0);
- // i32::MAX: beyond every platform's pid_max, and positive even when
- // narrowed to a 32-bit pid_t — unlike 4294967294, which wraps to -2
- // on macOS and probes process group 2 instead of a pid.
- std::fs::write(&marker, format!("2147483647\n{started_at}")).unwrap();
-
- assert!(live_marker_owner(&marker).is_none());
- assert!(
- !marker.exists(),
- "a dead owner's marker must be self-healed (removed) on read"
- );
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn live_marker_owner_removes_marker_past_the_age_ceiling() {
- let dir = unique_tmp_dir("marker-read-stale-age");
- let marker = dir.join(".hermes-update-in-progress");
- // LEGACY v1 marker (no ct line): our own live pid, but started past
- // the ceiling: age alone must stale a v1 claim, and the stale file
- // must not survive to wedge the next run.
- let long_ago = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0)
- .saturating_sub(UPDATE_MARKER_MAX_AGE_SECS + 60);
- std::fs::write(&marker, format!("{}\n{long_ago}", std::process::id())).unwrap();
-
- assert!(live_marker_owner(&marker).is_none());
- assert!(
- !marker.exists(),
- "past-ceiling marker must be removed on read"
- );
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn live_marker_owner_removes_malformed_marker() {
- // A torn write (garbage pid line) is not a live update either; leaving
- // it would wedge every future acquire the same way a dead pid does.
- let dir = unique_tmp_dir("marker-read-malformed");
- let marker = dir.join(".hermes-update-in-progress");
- std::fs::write(&marker, "not-a-pid\n").unwrap();
-
- assert!(live_marker_owner(&marker).is_none());
- assert!(
- !marker.exists(),
- "an unparseable marker must not wedge future updates"
- );
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn live_marker_owner_keeps_live_foreign_marker() {
- // The self-heal must NOT delete a live updater's marker — that would
- // let two updaters mutate one checkout concurrently.
- let mut foreign = spawn_foreign_holder();
- let dir = unique_tmp_dir("marker-read-live-foreign");
- let marker = dir.join(".hermes-update-in-progress");
- let started_at = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0);
- std::fs::write(&marker, format!("{}\n{started_at}", foreign.id())).unwrap();
-
- let owner = live_marker_owner(&marker).expect("live foreign holder must be reported");
- assert_eq!(owner.pid, foreign.id());
- assert!(
- marker.exists(),
- "a live owner's marker must be left intact (no clobbering)"
- );
- let _ = foreign.kill();
- let _ = foreign.wait();
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn live_marker_owner_keeps_own_live_marker() {
- // #74761: the desktop pre-writes the marker with OUR pid. That claim
- // must be reported (so `acquire` can adopt it without refreshing its
- // age), never deleted as stale — deleting it would break the desktop
- // handoff that pre-claims the lock for us.
- let dir = unique_tmp_dir("marker-read-own-live");
- let marker = dir.join(".hermes-update-in-progress");
- let started_at = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0);
- std::fs::write(&marker, format!("{}\n{started_at}", std::process::id())).unwrap();
-
- let owner = live_marker_owner(&marker)
- .expect("our own live pid must be reported for acquire to adopt");
- assert_eq!(owner.pid, std::process::id());
- assert!(
- marker.exists(),
- "our own live marker must be kept for adoption"
- );
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn pid_is_alive_true_for_self() {
- assert!(pid_is_alive(std::process::id()));
- }
-
- #[test]
- fn pid_is_alive_false_for_unusable_pid() {
- // i32::MAX is beyond every platform's pid_max, and stays positive
- // when narrowed to a 32-bit pid_t (unlike 4294967294 -> -2 on macOS,
- // which would probe process group 2): it can never name a live pid.
- assert!(!pid_is_alive(2147483647));
- }
-
- #[test]
- fn pid_is_alive_false_for_pid_zero() {
- // pid 0 means the caller's process GROUP to kill(2), so kill(0, 0)
- // always succeeds. Without the guard, a marker corrupted to "0" would
- // read as a live owner forever.
- assert!(!pid_is_alive(0));
- }
-
- #[cfg(target_os = "linux")]
- #[test]
- fn pid_is_alive_false_for_zombie() {
- // The kill(pid, 0) false positive behind #77259: a process that has
- // exited but is still in the table as a zombie (parent hasn't reaped
- // it yet) reads as "alive" via signal 0. /proc shows state 'Z', which
- // must count as dead so a crashed updater can't hold the marker past
- // its death.
- unsafe {
- let pid = libc::fork();
- assert!(pid >= 0, "fork failed");
- if pid == 0 {
- // Child: exit immediately, staying unreaped (a zombie).
- libc::_exit(0);
- }
- // Parent: do NOT waitpid yet — the child must linger as a zombie.
- // Poll until it actually reaches state 'Z' so the assertion below
- // can't race the child's exit.
- let mut became_zombie = false;
- for _ in 0..20 {
- if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) {
- if let Some(comm_end) = stat.rfind(')') {
- if stat[comm_end + 1..].split_whitespace().next() == Some("Z") {
- became_zombie = true;
- break;
- }
- }
- }
- std::thread::sleep(std::time::Duration::from_millis(25));
- }
- assert!(became_zombie, "child never reached zombie state");
-
- assert!(
- !pid_is_alive(pid as u32),
- "a zombie must not count as a live marker owner"
- );
- // Reap the zombie so the test process doesn't leak children.
- let mut status: libc::c_int = 0;
- libc::waitpid(pid, &mut status, 0);
- }
- }
-
- #[cfg(target_os = "macos")]
- #[test]
- fn pid_is_alive_false_for_zombie() {
- // Same false positive as the Linux branch, probed the macOS way: the
- // child exits, the parent does not reap it, and `ps -o stat=` must
- // report state 'Z' (or 'Z+'), which counts as dead.
- unsafe {
- let pid = libc::fork();
- assert!(pid >= 0, "fork failed");
- if pid == 0 {
- libc::_exit(0);
- }
- let mut became_zombie = false;
- for _ in 0..20 {
- if let Ok(output) = std::process::Command::new("ps")
- .arg("-o")
- .arg("stat=")
- .arg("-p")
- .arg(pid.to_string())
- .output()
- {
- let state = String::from_utf8_lossy(&output.stdout);
- if state.trim_start().starts_with('Z') {
- became_zombie = true;
- break;
- }
- }
- std::thread::sleep(std::time::Duration::from_millis(25));
- }
- assert!(became_zombie, "child never reached zombie state");
-
- assert!(
- !pid_is_alive(pid as u32),
- "a zombie must not count as a live marker owner"
- );
- // Reap the zombie so the test process doesn't leak children.
- let mut status: libc::c_int = 0;
- libc::waitpid(pid, &mut status, 0);
- }
- }
-
- #[test]
- fn completed_update_releases_marker_before_guard_drop() {
- let dir = unique_tmp_dir("marker-complete");
- std::fs::create_dir_all(&dir).unwrap();
- let marker = dir.join(".hermes-update-in-progress");
-
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("no live owner => acquire must succeed"));
- guard.complete();
-
- assert!(
- !marker.exists(),
- "a successful update must unblock desktop startup before relaunch/exit"
- );
- drop(guard);
- assert!(!marker.exists(), "Drop stays idempotent after completion");
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- // ---- marker contract C1 (v2: ct identity, CAS claim/delete, delegate) ----
-
- fn now_secs() -> u64 {
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0)
- }
-
- fn v2_body(pid: u32, started_at: u64, ct: f64) -> String {
- format!("{pid}\n{started_at}\nct:{ct:.3}\n")
- }
-
- fn ct_of(pid: u32) -> f64 {
- process_creation_time(pid).expect("creation-time probe must work on the test host")
- }
-
- #[test]
- fn v2_live_owner_is_never_aged_out() {
- // V3: a v2 owner that is alive (pid AND creation time match) stays
- // live however long it has run. The old 20-minute ceiling stole the
- // lock from a slow but healthy update.
- let mut foreign = spawn_foreign_holder();
- let dir = unique_tmp_dir("marker-v2-old-live");
- let marker = dir.join(".hermes-update-in-progress");
- let body = v2_body(foreign.id(), now_secs() - 25 * 60, ct_of(foreign.id()));
- std::fs::write(&marker, &body).unwrap();
-
- // a live v2 owner must not be reclaimed by age
- let owner = busy(UpdateMarkerGuard::acquire(marker.clone()));
- assert_eq!(owner.pid, foreign.id());
- assert_eq!(std::fs::read_to_string(&marker).unwrap(), body);
- let _ = foreign.kill();
- let _ = foreign.wait();
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn v2_marker_with_mismatched_creation_time_is_reclaimed() {
- // V22: a live pid whose creation time differs from the recorded one is
- // a recycled pid, not the owner — the marker is dead.
- let dir = unique_tmp_dir("marker-v2-ct-mismatch");
- let marker = dir.join(".hermes-update-in-progress");
- let me = std::process::id();
- std::fs::write(&marker, v2_body(me, now_secs(), ct_of(me) + 100.0)).unwrap();
-
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("a recycled-pid marker must be reclaimable"));
- let body = std::fs::read_to_string(&marker).unwrap();
- let record = parse_marker(body.as_bytes()).expect("reclaimed marker must parse");
- assert_eq!(record.pid, me);
- let ct = record.ct.expect("our claim records a creation time");
- assert!((ct - ct_of(me)).abs() <= MARKER_CT_TOLERANCE_SECS);
- drop(guard);
- assert!(!marker.exists());
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- /// Child half of `second_claimant_process_is_refused_by_exclusive_publish`:
- /// claims the marker from a SEPARATE process and reports via exit code.
- #[test]
- #[ignore = "spawned by second_claimant_process_is_refused_by_exclusive_publish"]
- fn marker_claim_child_helper() {
- let Some(path) = std::env::var_os("HERMES_TEST_MARKER_CLAIM_PATH") else {
- return;
- };
- let code = match UpdateMarkerGuard::acquire(PathBuf::from(path)) {
- Ok(guard) if guard.claim.is_some() => {
- // Leave the claim on disk, as a still-running owner would.
- std::mem::forget(guard);
- 0
- }
- Ok(_) => 4,
- Err(_) => 3,
- };
- std::process::exit(code);
- }
-
- fn run_claim_child(marker: &Path) -> (i32, u32) {
- let module = module_path!();
- let test_name = format!(
- "{}::marker_claim_child_helper",
- module.split_once("::").map_or(module, |(_, rest)| rest)
- );
- let child = std::process::Command::new(std::env::current_exe().unwrap())
- .args([test_name.as_str(), "--exact", "--ignored", "--nocapture"])
- .env("HERMES_TEST_MARKER_CLAIM_PATH", marker)
- .stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- .spawn()
- .expect("spawn claim child");
- let pid = child.id();
- let status = child.wait_with_output().unwrap().status;
- (status.code().unwrap_or(-1), pid)
- }
-
- #[test]
- fn second_claimant_process_is_refused_by_exclusive_publish() {
- // V4: the claim is an exclusive publish, so a second updater process
- // racing a fresh claim is refused and never truncates our bytes.
- let dir = unique_tmp_dir("marker-exclusive");
- let marker = dir.join(".hermes-update-in-progress");
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("fresh acquire must succeed"));
- let ours = std::fs::read(&marker).unwrap();
-
- let (code, _) = run_claim_child(&marker);
- assert_eq!(
- code, 3,
- "second claimant must be refused while our claim is live"
- );
- assert_eq!(
- std::fs::read(&marker).unwrap(),
- ours,
- "refusal must not touch our bytes"
- );
-
- drop(guard);
- assert!(!marker.exists());
- let (code, child_pid) = run_claim_child(&marker);
- assert_eq!(code, 0, "after release the next claimant must succeed");
- assert!(std::fs::read_to_string(&marker)
- .unwrap()
- .starts_with(&format!("{child_pid}\n")));
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn compare_and_delete_spares_changed_bytes() {
- // V4: a delete decided on earlier bytes must not remove a marker that
- // was replaced since (a new claim, or our claim plus a delegate line).
- let dir = unique_tmp_dir("marker-cas");
- let marker = dir.join(".hermes-update-in-progress");
- std::fs::write(&marker, "2147483647\n1\n").unwrap();
- assert!(!compare_and_delete(&marker, b"2147483647\n0\n"));
- assert!(
- marker.exists(),
- "changed bytes must survive compare-and-delete"
- );
- assert!(compare_and_delete(&marker, b"2147483647\n1\n"));
- assert!(!marker.exists());
-
- // The guard's release is compare-and-delete too: a marker whose
- // identity lines are no longer ours is someone else's claim.
- let mut foreign = spawn_foreign_holder();
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("fresh acquire must succeed"));
- let theirs = v2_body(foreign.id(), now_secs(), ct_of(foreign.id()));
- std::fs::write(&marker, &theirs).unwrap();
- drop(guard);
- assert_eq!(std::fs::read_to_string(&marker).unwrap(), theirs);
- let _ = foreign.kill();
- let _ = foreign.wait();
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn live_delegate_keeps_a_dead_owner_marker_live() {
- // Rule 6: `hermes update` running under a claim appends line 4; the
- // marker is live while EITHER the owner or the delegate is.
- let mut foreign = spawn_foreign_holder();
- let dir = unique_tmp_dir("marker-delegate");
- let marker = dir.join(".hermes-update-in-progress");
- let delegate = format!("delegate:{} ct:{:.3}\n", foreign.id(), ct_of(foreign.id()));
- let body = format!("{}{delegate}", v2_body(2147483647, now_secs(), 1.0));
- std::fs::write(&marker, &body).unwrap();
-
- let owner = live_marker_owner(&marker).expect("live delegate keeps the marker live");
- assert_eq!(owner.pid, foreign.id());
- assert!(UpdateMarkerGuard::acquire(marker.clone()).is_err());
- assert_eq!(std::fs::read_to_string(&marker).unwrap(), body);
- std::fs::remove_file(&marker).unwrap();
-
- // Our own claim with a live delegate line: release leaves it to the
- // delegate; once the delegate is dead, release removes it.
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("fresh acquire must succeed"));
- let mut ours = std::fs::read_to_string(&marker).unwrap();
- ours.push_str(&delegate);
- std::fs::write(&marker, &ours).unwrap();
- guard.complete();
- assert!(
- marker.exists(),
- "a live delegate owns the marker after our release"
- );
- let _ = foreign.kill();
- let _ = foreign.wait();
- guard.complete();
- assert!(
- !marker.exists(),
- "a dead delegate's line must not strand our claim"
- );
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- // ---- LP-LOCK round 2: shared parse / liveness / claim / litter rules ----
-
- #[test]
- fn parse_matrix_follows_the_shared_contract() {
- let parse = |body: &str| parse_marker(body.as_bytes());
- for body in [
- "\u{feff}123\n456\nct:1.5\n",
- "123\r\n456\r\nct:1.5\r\n",
- " 123\t\n\t456 \n ct:1.5 \n",
- ] {
- let record = parse(body).unwrap_or_else(|| panic!("{body:?} must parse"));
- assert_eq!(
- (record.pid, record.started_at, record.ct),
- (123, 456, Some(1.5)),
- "{body:?}"
- );
- assert_eq!(record.identity, ["123", "456", "ct:1.5"], "{body:?}");
- }
- for malformed in [
- "123\n1700000000.5\n", // fractional started_at
- "123\nabc\n", // garbage line 2
- "123\n\n", // empty line 2
- "123\n", // missing line 2
- "123",
- "1_0\n456\n",
- "+5\n456\n",
- "\u{663}\n456\n", // non-ASCII digit
- "",
- ] {
- assert!(
- parse(malformed).is_none(),
- "{malformed:?} must be malformed"
- );
- }
- for v1 in [
- "123\n456\nct:abc\n",
- "123\n456\nct: 1.5\n",
- "123\n456\nct:1.\n",
- "123\n456\n",
- ] {
- let record = parse(v1).unwrap_or_else(|| panic!("{v1:?} must parse"));
- assert_eq!(record.ct, None, "{v1:?} is a v1 marker");
- assert_eq!(record.identity.len(), 2, "{v1:?}");
- }
- // A delegate is read from line 4 only, in its exact shape.
- let line3 = parse("123\n456\ndelegate:5 ct:1.0\n").unwrap();
- assert_eq!(
- (line3.ct, line3.delegate),
- (None, None),
- "line 3 is never a delegate"
- );
- assert_eq!(
- parse("123\n456\nct:1.5\ndelegate:5 ct:1.0\n")
- .unwrap()
- .delegate,
- Some((5, 1.0))
- );
- for bad in [
- "delegate:5 ct:1.0",
- "delegate:5 ct:abc",
- "delegate:5",
- "delegate:x ct:1.0",
- ] {
- let body = format!("123\n456\nct:1.5\n{bad}\n");
- assert_eq!(parse(&body).unwrap().delegate, None, "{bad:?}");
- }
- }
-
- #[test]
- fn malformed_started_at_marker_is_dead_and_deleted() {
- // Our own live pid, but a fractional line 2: malformed, so dead.
- let dir = unique_tmp_dir("marker-fractional");
- let marker = dir.join(".hermes-update-in-progress");
- std::fs::write(
- &marker,
- format!("{}\n{}.5\n", std::process::id(), now_secs()),
- )
- .unwrap();
- assert!(live_marker_owner(&marker).is_none());
- assert!(
- !marker.exists(),
- "a malformed marker is compare-and-deleted"
- );
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn unreadable_creation_time_gets_the_v1_age_ceiling() {
- // A1: a live pid whose creation time cannot be probed is live only
- // within the v1 ceiling; a confirmed match has no age limit.
- let me = std::process::id();
- let started = now_secs() - 30 * 60;
- let record =
- parse_marker(format!("{me}\n{started}\nct:{:.3}\n", ct_of(me)).as_bytes()).unwrap();
- let unreadable = |_: u32| None;
- let at = |mins: u64| started + mins * 60;
- assert!(
- marker_live_holder(&record, at(5), &unreadable).is_some(),
- "5 min, ct unreadable: live"
- );
- assert!(
- marker_live_holder(&record, at(25), &unreadable).is_none(),
- "25 min, ct unreadable: dead"
- );
- let matching = |pid: u32| process_creation_time(pid);
- assert!(
- marker_live_holder(&record, at(25), &matching).is_some(),
- "matching ct: live at any age"
- );
- let mismatched = |pid: u32| process_creation_time(pid).map(|ct| ct + 100.0);
- assert!(
- marker_live_holder(&record, at(5), &mismatched).is_none(),
- "ct mismatch: recycled pid"
- );
-
- // The delegate is aged by the same marker age.
- let delegated = format!(
- "2147483647\n{started}\nct:1.000\ndelegate:{me} ct:{:.3}\n",
- ct_of(me)
- );
- let record = parse_marker(delegated.as_bytes()).unwrap();
- let holder =
- marker_live_holder(&record, at(5), &unreadable).expect("delegate live at 5 min");
- assert_eq!(holder.pid, me);
- assert!(marker_live_holder(&record, at(25), &unreadable).is_none());
- }
-
- #[test]
- fn fresh_empty_marker_is_a_claim_in_flight() {
- // A3: a 0-byte marker younger than 5 s is a claimant between its
- // exclusive create and its write — live, and never deleted.
- let dir = unique_tmp_dir("marker-empty-fresh");
- let marker = dir.join(".hermes-update-in-progress");
- std::fs::write(&marker, "").unwrap();
- assert_eq!(busy(UpdateMarkerGuard::acquire(marker.clone())).pid, 0);
- assert_eq!(
- std::fs::read(&marker).unwrap(),
- b"",
- "a fresh empty marker is not deleted"
- );
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn old_empty_marker_is_reclaimed_and_claim_leaves_no_tmp() {
- let dir = unique_tmp_dir("marker-empty-old");
- let marker = dir.join(".hermes-update-in-progress");
- let file = std::fs::File::create(&marker).unwrap();
- file.set_modified(SystemTime::now() - Duration::from_secs(10))
- .unwrap();
- drop(file);
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("a 10 s old empty marker is dead"));
- let body = std::fs::read_to_string(&marker).unwrap();
- assert!(body.starts_with(&format!("{}\n", std::process::id())));
- let litter: Vec<_> = std::fs::read_dir(&dir)
- .unwrap()
- .flatten()
- .map(|entry| entry.file_name().to_string_lossy().into_owned())
- .filter(|name| name.ends_with(".tmp"))
- .collect();
- assert!(
- litter.is_empty(),
- "the publish tmp file must be removed: {litter:?}"
- );
- drop(guard);
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn own_v1_prewrite_is_upgraded_to_v2_and_released() {
- // M1: Electron pre-writes `<our pid>\n<ts>\n`; acquire upgrades it to
- // v2 with our creation time, keeping lines 1-2 byte-identical (the
- // age survives), and complete() releases the upgraded claim.
- let me = std::process::id();
- let ts = now_secs() - 2;
- let ct_line = format!("ct:{:.3}\n", ct_of(me));
- for (prewrite, lines12) in [
- (format!("{me}\n{ts}\n"), format!("{me}\n{ts}\n")),
- (format!("{me}\r\n{ts}\r\n"), format!("{me}\r\n{ts}\r\n")),
- (format!("{me}\n{ts}"), format!("{me}\n{ts}\n")),
- ] {
- let dir = unique_tmp_dir("marker-m1");
- let marker = dir.join(".hermes-update-in-progress");
- std::fs::write(&marker, &prewrite).unwrap();
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("own-pid pre-write {prewrite:?} must be adopted"));
- assert_eq!(
- std::fs::read_to_string(&marker).unwrap(),
- format!("{lines12}{ct_line}")
- );
- guard.complete();
- assert!(!marker.exists(), "the upgraded claim is ours to release");
- drop(guard);
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- // An own-pid marker that already carries ct is adopted verbatim.
- let dir = unique_tmp_dir("marker-m1-v2");
- let marker = dir.join(".hermes-update-in-progress");
- let body = v2_body(me, now_secs() - 25 * 60, ct_of(me));
- std::fs::write(&marker, &body).unwrap();
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("own v2 marker must be adopted"));
- assert_eq!(std::fs::read_to_string(&marker).unwrap(), body);
- drop(guard);
- assert!(!marker.exists());
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- fn unwritable_message(result: Result<UpdateMarkerGuard, AcquireError>) -> String {
- match result {
- Err(AcquireError::Unwritable(msg)) => msg,
- Err(AcquireError::Busy(owner)) => {
- panic!("expected Unwritable, got Busy pid {}", owner.pid)
- }
- Ok(_) => panic!("expected Unwritable, acquire succeeded"),
- }
- }
-
- #[test]
- fn marker_under_a_regular_file_is_unwritable() {
- // m8: never proceed unclaimed.
- let dir = unique_tmp_dir("marker-under-file");
- let not_a_dir = dir.join("home");
- std::fs::write(&not_a_dir, "x").unwrap();
- let marker = not_a_dir.join(".hermes-update-in-progress");
- let msg = unwritable_message(UpdateMarkerGuard::acquire(marker.clone()));
- assert!(msg.starts_with(&format!(
- "Cannot lock this install for the update: {} is not writable (",
- marker.display()
- )));
- assert!(msg.ends_with("). Run the update as the user that owns the install."));
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[cfg(unix)]
- #[test]
- fn marker_in_a_read_only_dir_is_unwritable() {
- use std::os::unix::fs::PermissionsExt;
- if unsafe { libc::geteuid() } == 0 {
- return; // root ignores directory permissions
- }
- // No marker yet, and a dead marker that cannot be removed: both refuse.
- for existing in [None, Some(format!("2147483647\n{}\n", now_secs()))] {
- let dir = unique_tmp_dir("marker-read-only");
- let marker = dir.join(".hermes-update-in-progress");
- if let Some(body) = &existing {
- std::fs::write(&marker, body).unwrap();
- }
- std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap();
- let result = UpdateMarkerGuard::acquire(marker.clone());
- std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
- assert!(
- unwritable_message(result).contains("is not writable"),
- "{existing:?}"
- );
- assert_eq!(std::fs::read_to_string(&marker).ok(), existing);
- let _ = std::fs::remove_dir_all(&dir);
- }
- }
-
- #[test]
- fn claim_sweeps_dead_claimants_tmp_litter() {
- // m10: a claimant that died mid-publish leaves its tmp sibling.
- let dir = unique_tmp_dir("marker-litter");
- let marker = dir.join(".hermes-update-in-progress");
- let me = std::process::id();
- let dead = [
- ".hermes-update-in-progress.2147483647.123.tmp",
- ".hermes-update-in-progress.2147483647.tmp",
- ];
- let kept = [
- format!(".hermes-update-in-progress.{me}.123.tmp"),
- "other.2147483647.123.tmp".to_string(),
- ];
- for name in dead
- .iter()
- .map(|n| n.to_string())
- .chain(kept.iter().cloned())
- {
- std::fs::write(dir.join(name), "").unwrap();
- }
- let guard = UpdateMarkerGuard::acquire(marker.clone())
- .unwrap_or_else(|_| panic!("fresh acquire must succeed"));
- for name in dead {
- assert!(!dir.join(name).exists(), "{name} belongs to a dead pid");
- }
- for name in &kept {
- assert!(dir.join(name).exists(), "{name} must be kept");
- }
- drop(guard);
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- /// The live owner a refused acquire reports; panics on any other outcome.
- fn busy(result: Result<UpdateMarkerGuard, AcquireError>) -> MarkerOwner {
- match result {
- Err(AcquireError::Busy(owner)) => owner,
- Err(AcquireError::Unwritable(msg)) => panic!("expected Busy, got Unwritable: {msg}"),
- Ok(_) => panic!("expected Busy, acquire succeeded"),
- }
- }
-
- fn unique_tmp_dir(tag: &str) -> PathBuf {
- let base = std::env::temp_dir().join(format!(
- "hermes-marker-test-{tag}-{}-{}",
- std::process::id(),
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap()
- .as_nanos()
- ));
- std::fs::create_dir_all(&base).unwrap();
- base
- }
-}
+#[path = "marker_tests.rs"]
+mod tests;
diff --git a/apps/bootstrap-installer/src-tauri/src/marker_tests.rs b/apps/bootstrap-installer/src-tauri/src/marker_tests.rs
new file mode 100644
index 00000000000..5001003a29a
--- /dev/null
+++ b/apps/bootstrap-installer/src-tauri/src/marker_tests.rs
@@ -0,0 +1,1277 @@
+//! `marker.rs` tests (split out to keep the module under the size gate).
+
+use super::*;
+
+#[test]
+fn update_marker_guard_writes_then_removes_on_drop() {
+ let dir = unique_tmp_dir("marker-guard");
+ std::fs::create_dir_all(&dir).unwrap();
+ let marker = dir.join(".hermes-update-in-progress");
+
+ {
+ let _g = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("no live owner => acquire must succeed"));
+ assert!(marker.exists(), "marker must exist while the guard is held");
+ let body = std::fs::read_to_string(&marker).unwrap();
+ let pid_line = body.lines().next().unwrap();
+ assert_eq!(
+ pid_line.trim().parse::<u32>().unwrap(),
+ std::process::id(),
+ "marker records our pid so the desktop can probe liveness"
+ );
+ assert_eq!(
+ body.lines().count(),
+ 3,
+ "marker is pid + started_at + ct lines"
+ );
+ assert!(
+ body.ends_with('\n'),
+ "contract C1 bodies end with a newline"
+ );
+ let ct = parse_marker(body.as_bytes()).and_then(|record| record.ct);
+ assert!(ct.is_some(), "a v2 claim records the owner's creation time");
+ }
+
+ assert!(
+ !marker.exists(),
+ "Drop must remove the marker on every exit path (incl. early return / panic unwind)"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn update_marker_guard_drop_is_quiet_when_already_gone() {
+ let dir = unique_tmp_dir("marker-guard-gone");
+ std::fs::create_dir_all(&dir).unwrap();
+ let marker = dir.join(".hermes-update-in-progress");
+
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("no live owner => acquire must succeed"));
+ // Simulate an external cleanup (e.g. the desktop pruned a marker it
+ // judged stale) before our guard drops — Drop must not panic.
+ std::fs::remove_file(&marker).unwrap();
+ drop(guard);
+
+ assert!(!marker.exists());
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// Spawn a short-lived sibling process whose pid stands in for a foreign
+/// updater. Same-process double-acquire no longer models contention: since
+/// #74761 `acquire` treats our own pid as adoptable (desktop pre-writes it),
+/// so a second acquire in *this* process would succeed.
+fn spawn_foreign_holder() -> std::process::Child {
+ #[cfg(windows)]
+ {
+ std::process::Command::new("timeout")
+ .args(["/t", "30", "/nobreak"])
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .expect("spawn foreign marker holder")
+ }
+ #[cfg(not(windows))]
+ {
+ std::process::Command::new("sleep")
+ .arg("30")
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .expect("spawn foreign marker holder")
+ }
+}
+
+#[test]
+fn acquire_refuses_while_a_live_updater_owns_the_marker() {
+ let dir = unique_tmp_dir("marker-contended");
+ std::fs::create_dir_all(&dir).unwrap();
+ let marker = dir.join(".hermes-update-in-progress");
+
+ // A live *foreign* updater holds it. We must NOT clobber the marker and
+ // run concurrently over the same checkout — that race is what let a
+ // dashboard `hermes update` and install-mode bootstrap mutate one tree
+ // at once. Own-pid markers are adoptable (#74761), so the foreign pid
+ // must be a real sibling process.
+ let mut foreign = spawn_foreign_holder();
+ let foreign_pid = foreign.id();
+ let started_at = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ std::fs::write(&marker, format!("{foreign_pid}\n{started_at}")).unwrap();
+
+ let owner = busy(UpdateMarkerGuard::acquire(marker.clone()));
+ assert_eq!(owner.pid, foreign_pid);
+
+ // The refused guard must not delete the live owner's marker.
+ assert!(
+ marker.exists(),
+ "refused acquire must leave the marker intact"
+ );
+ let _ = foreign.kill();
+ let _ = foreign.wait();
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn own_pid_v1_prewrite_is_a_previous_incarnation_and_reclaimed() {
+ // A7 rule 4 / R12: a no-ct claim naming our pid cannot prove it is THIS process (an old
+ // Desktop pre-writes `<our pid>\n<ts>`, but so did any earlier process that had our pid).
+ // It is dead: reclaimed under the mutex and replaced by our exact v2 claim.
+ let dir = unique_tmp_dir("marker-own-pid");
+ std::fs::create_dir_all(&dir).unwrap();
+ let marker = dir.join(".hermes-update-in-progress");
+ let me = std::process::id();
+ std::fs::write(&marker, format!("{me}\n{}", now_secs() - 2)).unwrap();
+
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("a previous incarnation's claim never blocks us"));
+ let record = parse_marker(&std::fs::read(&marker).unwrap()).unwrap();
+ assert_eq!(record.pid, me);
+ assert!((record.ct.expect("our claim is v2") - ct_of(me)).abs() <= OWN_CT_EPSILON_SECS);
+ drop(guard);
+ assert!(!marker.exists(), "Drop clears our claim");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn own_pid_with_a_creation_time_6ms_off_is_not_us() {
+ // R12: the 2 s foreign tolerance never applies to our own pid.
+ let dir = unique_tmp_dir("marker-own-pid-6ms");
+ let marker = dir.join(".hermes-update-in-progress");
+ let me = std::process::id();
+ std::fs::write(&marker, v2_body(me, now_secs(), ct_of(me) - 0.006)).unwrap();
+ assert!(live_marker_owner(&marker).is_none());
+ assert!(
+ !marker.exists(),
+ "a previous incarnation's claim is reclaimed"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+// ---- exit-2 self-marker heal (#75788) --------------------------------
+// The deadlock: the updater holds the marker with its own PID; a stale
+// checkout's `hermes update` reads it as a live foreign update and exits
+// 2; the generic retry deliberately skips exit 2 — so the refusal loops
+// forever. These tests pin the heal decision's full contract. On
+// merge-base product code (no heal) the decision function does not exist
+// and the refusal is terminal — the A/B run proves that.
+
+#[test]
+fn self_owned_marker_plus_exit_2_heals() {
+ let dir = unique_tmp_dir("heal-self-owned");
+ let marker = dir.join(".hermes-update-in-progress");
+ let me = std::process::id();
+ std::fs::write(&marker, v2_body(me, 123, ct_of(me))).unwrap();
+
+ assert!(
+ should_heal_self_marker_refusal(Some(UPDATE_EXIT_CONCURRENT), &marker),
+ "a child refusing over OUR marker is the #75788 deadlock — must heal"
+ );
+ // R12: our pid without our creation time is a previous incarnation's claim, not ours.
+ std::fs::write(&marker, format!("{me}\n123\n")).unwrap();
+ assert!(!should_heal_self_marker_refusal(
+ Some(UPDATE_EXIT_CONCURRENT),
+ &marker
+ ));
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn foreign_owned_marker_never_heals() {
+ let dir = unique_tmp_dir("heal-foreign");
+ let marker = dir.join(".hermes-update-in-progress");
+ // A live sibling process stands in for a genuinely concurrent updater.
+ let mut foreign = spawn_foreign_holder();
+ std::fs::write(&marker, format!("{}\n123\n", foreign.id())).unwrap();
+
+ assert!(
+ !should_heal_self_marker_refusal(Some(UPDATE_EXIT_CONCURRENT), &marker),
+ "a foreign owner is a REAL concurrent update — the refusal must stand"
+ );
+ let _ = foreign.kill();
+ let _ = foreign.wait();
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn missing_or_garbage_marker_never_heals() {
+ let dir = unique_tmp_dir("heal-garbage");
+ let missing = dir.join("never-written");
+ assert!(
+ !should_heal_self_marker_refusal(Some(UPDATE_EXIT_CONCURRENT), &missing),
+ "no marker on disk = the child refused over something else entirely"
+ );
+
+ let garbage = dir.join(".hermes-update-in-progress");
+ std::fs::write(&garbage, "not-a-pid\n123\n").unwrap();
+ assert!(
+ !should_heal_self_marker_refusal(Some(UPDATE_EXIT_CONCURRENT), &garbage),
+ "an unparseable marker must not be treated as ours"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn non_exit_2_outcomes_never_heal() {
+ let dir = unique_tmp_dir("heal-wrong-exit");
+ let marker = dir.join(".hermes-update-in-progress");
+ let me = std::process::id();
+ std::fs::write(&marker, v2_body(me, 123, ct_of(me))).unwrap();
+
+ for code in [Some(0), Some(1), Some(3), None] {
+ assert!(
+ !should_heal_self_marker_refusal(code, &marker),
+ "heal is exit-2-only; exit {code:?} must keep its normal path"
+ );
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn heal_end_to_end_marker_lifecycle() {
+ // The full deadlock-and-heal sequence with a REAL marker guard, as
+ // run_update executes it: acquire (marker written with our pid) →
+ // child exits 2 refusing our own claim → heal decision fires →
+ // complete() drops the claim → the retry's precondition (no marker,
+ // or a marker the child can now claim) holds.
+ let dir = unique_tmp_dir("heal-e2e");
+ let marker = dir.join(".hermes-update-in-progress");
+
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("no live owner => acquire must succeed"));
+ assert!(
+ marker.exists(),
+ "updater holds the marker during the child run"
+ );
+
+ // Stale child refused over our claim:
+ assert!(should_heal_self_marker_refusal(
+ Some(UPDATE_EXIT_CONCURRENT),
+ &marker
+ ));
+
+ // The heal drops the claim exactly as run_update does:
+ guard.complete();
+ assert!(
+ !marker.exists(),
+ "claim dropped — the one retry now runs with the marker absent"
+ );
+
+ // And with the marker gone the heal can never fire twice (the retry's
+ // own exit 2, e.g. a genuinely still-running Hermes, stays terminal).
+ assert!(!should_heal_self_marker_refusal(
+ Some(UPDATE_EXIT_CONCURRENT),
+ &marker
+ ));
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn acquire_reclaims_a_marker_owned_by_a_dead_pid() {
+ let dir = unique_tmp_dir("marker-dead-pid");
+ std::fs::create_dir_all(&dir).unwrap();
+ let marker = dir.join(".hermes-update-in-progress");
+
+ // pid 1 exists everywhere, so fabricate a dead one: a very large pid
+ // that no live process owns. A crashed updater must never wedge every
+ // future update.
+ let started_at = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ std::fs::write(&marker, format!("4294967294\n{started_at}")).unwrap();
+
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("a dead owner must not block acquisition"));
+ let body = std::fs::read_to_string(&marker).unwrap();
+ assert_eq!(
+ body.lines().next().unwrap().trim().parse::<u32>().unwrap(),
+ std::process::id(),
+ "reclaiming rewrites the marker with our pid"
+ );
+ drop(guard);
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn acquire_reclaims_a_marker_past_the_age_ceiling() {
+ let dir = unique_tmp_dir("marker-stale-age");
+ std::fs::create_dir_all(&dir).unwrap();
+ let marker = dir.join(".hermes-update-in-progress");
+
+ // LEGACY v1 marker (no ct line): our own live pid, but started past
+ // the ceiling. Without a creation time the pid may be recycled, so
+ // age still bounds a v1 claim. (v2 has no ceiling — see
+ // v2_live_owner_is_never_aged_out.)
+ let long_ago = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+ .saturating_sub(UPDATE_MARKER_MAX_AGE_SECS + 60);
+ std::fs::write(&marker, format!("{}\n{long_ago}", std::process::id())).unwrap();
+
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("a marker past the ceiling must be reclaimable"));
+ drop(guard);
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn live_marker_owner_removes_stale_marker_with_dead_pid() {
+ // The core self-heal of #77259: a marker whose owner is gone must be
+ // REMOVED on read (like read_live_update in update_lock.py), not just
+ // ignored — otherwise the stale bytes keep failing every acquire
+ // until the 20-minute age ceiling expires.
+ let dir = unique_tmp_dir("marker-read-dead");
+ let marker = dir.join(".hermes-update-in-progress");
+ let started_at = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ // i32::MAX: beyond every platform's pid_max, and positive even when
+ // narrowed to a 32-bit pid_t — unlike 4294967294, which wraps to -2
+ // on macOS and probes process group 2 instead of a pid.
+ std::fs::write(&marker, format!("2147483647\n{started_at}")).unwrap();
+
+ assert!(live_marker_owner(&marker).is_none());
+ assert!(
+ !marker.exists(),
+ "a dead owner's marker must be self-healed (removed) on read"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn live_marker_owner_removes_marker_past_the_age_ceiling() {
+ let dir = unique_tmp_dir("marker-read-stale-age");
+ let marker = dir.join(".hermes-update-in-progress");
+ // LEGACY v1 marker (no ct line): our own live pid, but started past
+ // the ceiling: age alone must stale a v1 claim, and the stale file
+ // must not survive to wedge the next run.
+ let long_ago = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+ .saturating_sub(UPDATE_MARKER_MAX_AGE_SECS + 60);
+ std::fs::write(&marker, format!("{}\n{long_ago}", std::process::id())).unwrap();
+
+ assert!(live_marker_owner(&marker).is_none());
+ assert!(
+ !marker.exists(),
+ "past-ceiling marker must be removed on read"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn live_marker_owner_removes_malformed_marker() {
+ // A torn write (garbage pid line) is not a live update either; leaving
+ // it would wedge every future acquire the same way a dead pid does.
+ let dir = unique_tmp_dir("marker-read-malformed");
+ let marker = dir.join(".hermes-update-in-progress");
+ std::fs::write(&marker, "not-a-pid\n").unwrap();
+
+ assert!(live_marker_owner(&marker).is_none());
+ assert!(
+ !marker.exists(),
+ "an unparseable marker must not wedge future updates"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn live_marker_owner_keeps_live_foreign_marker() {
+ // The self-heal must NOT delete a live updater's marker — that would
+ // let two updaters mutate one checkout concurrently.
+ let mut foreign = spawn_foreign_holder();
+ let dir = unique_tmp_dir("marker-read-live-foreign");
+ let marker = dir.join(".hermes-update-in-progress");
+ let started_at = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ std::fs::write(&marker, format!("{}\n{started_at}", foreign.id())).unwrap();
+
+ let owner = live_marker_owner(&marker).expect("live foreign holder must be reported");
+ assert_eq!(owner.pid, foreign.id());
+ assert!(
+ marker.exists(),
+ "a live owner's marker must be left intact (no clobbering)"
+ );
+ let _ = foreign.kill();
+ let _ = foreign.wait();
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn live_marker_owner_keeps_own_live_marker() {
+ // A claim that is our exact incarnation is reported (so `acquire` adopts it), never
+ // deleted as stale.
+ let dir = unique_tmp_dir("marker-read-own-live");
+ let marker = dir.join(".hermes-update-in-progress");
+ let me = std::process::id();
+ std::fs::write(&marker, v2_body(me, now_secs(), ct_of(me))).unwrap();
+
+ let owner =
+ live_marker_owner(&marker).expect("our own live pid must be reported for acquire to adopt");
+ assert_eq!(owner.pid, std::process::id());
+ assert!(
+ marker.exists(),
+ "our own live marker must be kept for adoption"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn pid_is_alive_true_for_self() {
+ assert!(pid_is_alive(std::process::id()));
+}
+
+#[test]
+fn pid_is_alive_false_for_unusable_pid() {
+ // i32::MAX is beyond every platform's pid_max, and stays positive
+ // when narrowed to a 32-bit pid_t (unlike 4294967294 -> -2 on macOS,
+ // which would probe process group 2): it can never name a live pid.
+ assert!(!pid_is_alive(2147483647));
+}
+
+#[test]
+fn pid_is_alive_false_for_pid_zero() {
+ // pid 0 means the caller's process GROUP to kill(2), so kill(0, 0)
+ // always succeeds. Without the guard, a marker corrupted to "0" would
+ // read as a live owner forever.
+ assert!(!pid_is_alive(0));
+}
+
+#[cfg(target_os = "linux")]
+#[test]
+fn pid_is_alive_false_for_zombie() {
+ // The kill(pid, 0) false positive behind #77259: a process that has
+ // exited but is still in the table as a zombie (parent hasn't reaped
+ // it yet) reads as "alive" via signal 0. /proc shows state 'Z', which
+ // must count as dead so a crashed updater can't hold the marker past
+ // its death.
+ unsafe {
+ let pid = libc::fork();
+ assert!(pid >= 0, "fork failed");
+ if pid == 0 {
+ // Child: exit immediately, staying unreaped (a zombie).
+ libc::_exit(0);
+ }
+ // Parent: do NOT waitpid yet — the child must linger as a zombie.
+ // Poll until it actually reaches state 'Z' so the assertion below
+ // can't race the child's exit.
+ let mut became_zombie = false;
+ for _ in 0..20 {
+ if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) {
+ if let Some(comm_end) = stat.rfind(')') {
+ if stat[comm_end + 1..].split_whitespace().next() == Some("Z") {
+ became_zombie = true;
+ break;
+ }
+ }
+ }
+ std::thread::sleep(std::time::Duration::from_millis(25));
+ }
+ assert!(became_zombie, "child never reached zombie state");
+
+ assert!(
+ !pid_is_alive(pid as u32),
+ "a zombie must not count as a live marker owner"
+ );
+ // Reap the zombie so the test process doesn't leak children.
+ let mut status: libc::c_int = 0;
+ libc::waitpid(pid, &mut status, 0);
+ }
+}
+
+#[cfg(target_os = "macos")]
+#[test]
+fn pid_is_alive_false_for_zombie() {
+ // Same false positive as the Linux branch, probed the macOS way: the
+ // child exits, the parent does not reap it, and `ps -o stat=` must
+ // report state 'Z' (or 'Z+'), which counts as dead.
+ unsafe {
+ let pid = libc::fork();
+ assert!(pid >= 0, "fork failed");
+ if pid == 0 {
+ libc::_exit(0);
+ }
+ let mut became_zombie = false;
+ for _ in 0..20 {
+ if let Ok(output) = std::process::Command::new("ps")
+ .arg("-o")
+ .arg("stat=")
+ .arg("-p")
+ .arg(pid.to_string())
+ .output()
+ {
+ let state = String::from_utf8_lossy(&output.stdout);
+ if state.trim_start().starts_with('Z') {
+ became_zombie = true;
+ break;
+ }
+ }
+ std::thread::sleep(std::time::Duration::from_millis(25));
+ }
+ assert!(became_zombie, "child never reached zombie state");
+
+ assert!(
+ !pid_is_alive(pid as u32),
+ "a zombie must not count as a live marker owner"
+ );
+ // Reap the zombie so the test process doesn't leak children.
+ let mut status: libc::c_int = 0;
+ libc::waitpid(pid, &mut status, 0);
+ }
+}
+
+#[test]
+fn completed_update_releases_marker_before_guard_drop() {
+ let dir = unique_tmp_dir("marker-complete");
+ std::fs::create_dir_all(&dir).unwrap();
+ let marker = dir.join(".hermes-update-in-progress");
+
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("no live owner => acquire must succeed"));
+ guard.complete();
+
+ assert!(
+ !marker.exists(),
+ "a successful update must unblock desktop startup before relaunch/exit"
+ );
+ drop(guard);
+ assert!(!marker.exists(), "Drop stays idempotent after completion");
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+// ---- marker contract C1 (v2: ct identity, CAS claim/delete, delegate) ----
+
+fn now_secs() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+}
+
+fn v2_body(pid: u32, started_at: u64, ct: f64) -> String {
+ format!("{pid}\n{started_at}\nct:{ct:.3}\n")
+}
+
+fn ct_of(pid: u32) -> f64 {
+ process_creation_time(pid).expect("creation-time probe must work on the test host")
+}
+
+#[test]
+fn v2_live_owner_is_never_aged_out() {
+ // V3: a v2 owner that is alive (pid AND creation time match) stays
+ // live however long it has run. The old 20-minute ceiling stole the
+ // lock from a slow but healthy update.
+ let mut foreign = spawn_foreign_holder();
+ let dir = unique_tmp_dir("marker-v2-old-live");
+ let marker = dir.join(".hermes-update-in-progress");
+ let body = v2_body(foreign.id(), now_secs() - 25 * 60, ct_of(foreign.id()));
+ std::fs::write(&marker, &body).unwrap();
+
+ // a live v2 owner must not be reclaimed by age
+ let owner = busy(UpdateMarkerGuard::acquire(marker.clone()));
+ assert_eq!(owner.pid, foreign.id());
+ assert_eq!(std::fs::read_to_string(&marker).unwrap(), body);
+ let _ = foreign.kill();
+ let _ = foreign.wait();
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn v2_marker_with_mismatched_creation_time_is_reclaimed() {
+ // V22: a live pid whose creation time differs from the recorded one is
+ // a recycled pid, not the owner — the marker is dead.
+ let dir = unique_tmp_dir("marker-v2-ct-mismatch");
+ let marker = dir.join(".hermes-update-in-progress");
+ let me = std::process::id();
+ std::fs::write(&marker, v2_body(me, now_secs(), ct_of(me) + 100.0)).unwrap();
+
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("a recycled-pid marker must be reclaimable"));
+ let body = std::fs::read_to_string(&marker).unwrap();
+ let record = parse_marker(body.as_bytes()).expect("reclaimed marker must parse");
+ assert_eq!(record.pid, me);
+ let ct = record.ct.expect("our claim records a creation time");
+ assert!((ct - ct_of(me)).abs() <= MARKER_CT_TOLERANCE_SECS);
+ drop(guard);
+ assert!(!marker.exists());
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// Child half of `second_claimant_process_is_refused_by_exclusive_publish`:
+/// claims the marker from a SEPARATE process and reports via exit code.
+#[test]
+#[ignore = "spawned by second_claimant_process_is_refused_by_exclusive_publish"]
+fn marker_claim_child_helper() {
+ let Some(path) = std::env::var_os("HERMES_TEST_MARKER_CLAIM_PATH") else {
+ return;
+ };
+ let code = match UpdateMarkerGuard::acquire(PathBuf::from(path)) {
+ Ok(guard) if guard.claimed => {
+ // Leave the claim on disk, as a still-running owner would.
+ std::mem::forget(guard);
+ 0
+ }
+ Ok(_) => 4,
+ Err(_) => 3,
+ };
+ std::process::exit(code);
+}
+
+fn run_claim_child(marker: &Path) -> (i32, u32) {
+ let module = module_path!();
+ let test_name = format!(
+ "{}::marker_claim_child_helper",
+ module.split_once("::").map_or(module, |(_, rest)| rest)
+ );
+ let child = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([test_name.as_str(), "--exact", "--ignored", "--nocapture"])
+ .env("HERMES_TEST_MARKER_CLAIM_PATH", marker)
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .expect("spawn claim child");
+ let pid = child.id();
+ let status = child.wait_with_output().unwrap().status;
+ (status.code().unwrap_or(-1), pid)
+}
+
+#[test]
+fn second_claimant_process_is_refused_by_exclusive_publish() {
+ // V4: the claim is an exclusive publish, so a second updater process
+ // racing a fresh claim is refused and never truncates our bytes.
+ let dir = unique_tmp_dir("marker-exclusive");
+ let marker = dir.join(".hermes-update-in-progress");
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("fresh acquire must succeed"));
+ let ours = std::fs::read(&marker).unwrap();
+
+ let (code, _) = run_claim_child(&marker);
+ assert_eq!(
+ code, 3,
+ "second claimant must be refused while our claim is live"
+ );
+ assert_eq!(
+ std::fs::read(&marker).unwrap(),
+ ours,
+ "refusal must not touch our bytes"
+ );
+
+ drop(guard);
+ assert!(!marker.exists());
+ let (code, child_pid) = run_claim_child(&marker);
+ assert_eq!(code, 0, "after release the next claimant must succeed");
+ assert!(std::fs::read_to_string(&marker)
+ .unwrap()
+ .starts_with(&format!("{child_pid}\n")));
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn compare_and_delete_spares_changed_bytes() {
+ // V4: a delete decided on earlier bytes must not remove a marker that
+ // was replaced since (a new claim, or our claim plus a delegate line).
+ let dir = unique_tmp_dir("marker-cas");
+ let marker = dir.join(".hermes-update-in-progress");
+ std::fs::write(&marker, "2147483647\n1\n").unwrap();
+ assert!(!compare_and_delete(&marker, b"2147483647\n0\n"));
+ assert!(
+ marker.exists(),
+ "changed bytes must survive compare-and-delete"
+ );
+ assert!(compare_and_delete(&marker, b"2147483647\n1\n"));
+ assert!(!marker.exists());
+
+ // The guard's release is compare-and-delete too: a marker whose
+ // identity lines are no longer ours is someone else's claim.
+ let mut foreign = spawn_foreign_holder();
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("fresh acquire must succeed"));
+ let theirs = v2_body(foreign.id(), now_secs(), ct_of(foreign.id()));
+ std::fs::write(&marker, &theirs).unwrap();
+ drop(guard);
+ assert_eq!(std::fs::read_to_string(&marker).unwrap(), theirs);
+ let _ = foreign.kill();
+ let _ = foreign.wait();
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn live_delegate_keeps_a_dead_owner_marker_live() {
+ // Rule 6: `hermes update` running under a claim appends line 4; the
+ // marker is live while EITHER the owner or the delegate is.
+ let mut foreign = spawn_foreign_holder();
+ let dir = unique_tmp_dir("marker-delegate");
+ let marker = dir.join(".hermes-update-in-progress");
+ let delegate = format!("delegate:{} ct:{:.3}\n", foreign.id(), ct_of(foreign.id()));
+ let body = format!("{}{delegate}", v2_body(2147483647, now_secs(), 1.0));
+ std::fs::write(&marker, &body).unwrap();
+
+ let owner = live_marker_owner(&marker).expect("live delegate keeps the marker live");
+ assert_eq!(owner.pid, foreign.id());
+ assert!(UpdateMarkerGuard::acquire(marker.clone()).is_err());
+ assert_eq!(std::fs::read_to_string(&marker).unwrap(), body);
+ std::fs::remove_file(&marker).unwrap();
+
+ // A7 rule 5: our release with a LIVE delegate hands the claim to it (rewritten with the
+ // delegate as owner, started_at and run line kept); a dead delegate's line never strands
+ // our claim.
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("fresh acquire must succeed"));
+ let mut ours = std::fs::read_to_string(&marker).unwrap();
+ let started = ours.lines().nth(1).unwrap().to_string();
+ ours.push_str(&delegate);
+ ours.push_str("run:desk-1\n");
+ std::fs::write(&marker, &ours).unwrap();
+ guard.complete();
+ assert_eq!(
+ std::fs::read_to_string(&marker).unwrap(),
+ format!(
+ "{}\n{started}\nct:{:.3}\nrun:desk-1\n",
+ foreign.id(),
+ ct_of(foreign.id())
+ ),
+ "the live delegate inherits the claim"
+ );
+ guard.complete();
+ assert!(
+ marker.exists(),
+ "a handed-over claim is no longer ours to release"
+ );
+ let _ = foreign.kill();
+ let _ = foreign.wait();
+ std::fs::remove_file(&marker).unwrap();
+
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("fresh acquire must succeed"));
+ let mut ours = std::fs::read_to_string(&marker).unwrap();
+ ours.push_str(&delegate); // the delegate is dead now
+ std::fs::write(&marker, &ours).unwrap();
+ guard.complete();
+ assert!(
+ !marker.exists(),
+ "a dead delegate's line must not strand our claim"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+// ---- LP-LOCK round 2: shared parse / liveness / claim / litter rules ----
+
+#[test]
+fn parse_matrix_follows_the_shared_contract() {
+ let parse = |body: &str| parse_marker(body.as_bytes());
+ for body in [
+ "\u{feff}123\n456\nct:1.5\n",
+ "123\r\n456\r\nct:1.5\r\n",
+ " 123\t\n\t456 \n ct:1.5 \n",
+ ] {
+ let record = parse(body).unwrap_or_else(|| panic!("{body:?} must parse"));
+ assert_eq!(
+ (record.pid, record.started_at, record.ct),
+ (123, 456, Some(1.5)),
+ "{body:?}"
+ );
+ assert_eq!(record.identity, ["123", "456", "ct:1.5"], "{body:?}");
+ }
+ for malformed in [
+ "123\n1700000000.5\n", // fractional started_at
+ "123\nabc\n", // garbage line 2
+ "123\n\n", // empty line 2
+ "123\n", // missing line 2
+ "123",
+ "1_0\n456\n",
+ "+5\n456\n",
+ "\u{663}\n456\n", // non-ASCII digit
+ "",
+ ] {
+ assert!(
+ parse(malformed).is_none(),
+ "{malformed:?} must be malformed"
+ );
+ }
+ for v1 in [
+ "123\n456\nct:abc\n",
+ "123\n456\nct: 1.5\n",
+ "123\n456\nct:1.\n",
+ "123\n456\n",
+ ] {
+ let record = parse(v1).unwrap_or_else(|| panic!("{v1:?} must parse"));
+ assert_eq!(record.ct, None, "{v1:?} is a v1 marker");
+ assert_eq!(record.identity.len(), 2, "{v1:?}");
+ }
+ // A delegate is read from line 4 only, in its exact shape.
+ let line3 = parse("123\n456\ndelegate:5 ct:1.0\n").unwrap();
+ assert_eq!(
+ (line3.ct, line3.delegate),
+ (None, None),
+ "line 3 is never a delegate"
+ );
+ assert_eq!(
+ parse("123\n456\nct:1.5\ndelegate:5 ct:1.0\n")
+ .unwrap()
+ .delegate,
+ Some((5, 1.0))
+ );
+ for bad in [
+ "delegate:5 ct:1.0",
+ "delegate:5 ct:abc",
+ "delegate:5",
+ "delegate:x ct:1.0",
+ ] {
+ let body = format!("123\n456\nct:1.5\n{bad}\n");
+ assert_eq!(parse(&body).unwrap().delegate, None, "{bad:?}");
+ }
+}
+
+#[test]
+fn malformed_started_at_marker_is_dead_and_deleted() {
+ // Our own live pid, but a fractional line 2: malformed, so dead.
+ let dir = unique_tmp_dir("marker-fractional");
+ let marker = dir.join(".hermes-update-in-progress");
+ std::fs::write(
+ &marker,
+ format!("{}\n{}.5\n", std::process::id(), now_secs()),
+ )
+ .unwrap();
+ assert!(live_marker_owner(&marker).is_none());
+ assert!(
+ !marker.exists(),
+ "a malformed marker is compare-and-deleted"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+fn world_with<'a>(
+ now: u64,
+ alive: &'a dyn Fn(u32) -> bool,
+ ct_of: &'a dyn Fn(u32) -> Option<f64>,
+) -> World<'a> {
+ let me = std::process::id();
+ World {
+ pid: me,
+ ct: process_creation_time(me),
+ now,
+ alive,
+ ct_of,
+ }
+}
+
+#[test]
+fn unreadable_creation_time_gets_the_v1_age_ceiling() {
+ // A1: a live foreign pid whose creation time cannot be probed is live only within the v1
+ // ceiling; a confirmed match has no age limit.
+ let mut foreign = spawn_foreign_holder();
+ let pid = foreign.id();
+ let started = now_secs() - 30 * 60;
+ let record = parse_marker(v2_body(pid, started, ct_of(pid)).as_bytes()).unwrap();
+ let alive = |pid: u32| pid_is_alive(pid);
+ let unreadable = |_: u32| None;
+ let at = |mins: u64| started + mins * 60;
+ let holder = |now, probe: &dyn Fn(u32) -> Option<f64>| {
+ marker_live_holder(&record, &world_with(now, &alive, probe)).map(|owner| owner.pid)
+ };
+ assert_eq!(
+ holder(at(5), &unreadable),
+ Some(pid),
+ "5 min, ct unreadable: live"
+ );
+ assert_eq!(
+ holder(at(25), &unreadable),
+ None,
+ "25 min, ct unreadable: dead"
+ );
+ let matching = |pid: u32| process_creation_time(pid);
+ assert_eq!(
+ holder(at(25), &matching),
+ Some(pid),
+ "matching ct: live at any age"
+ );
+ let mismatched = |pid: u32| process_creation_time(pid).map(|ct| ct + 100.0);
+ assert_eq!(
+ holder(at(5), &mismatched),
+ None,
+ "ct mismatch: recycled pid"
+ );
+
+ // The delegate is aged by the same marker age.
+ let delegated = format!(
+ "2147483647\n{started}\nct:1.000\ndelegate:{pid} ct:{:.3}\n",
+ ct_of(pid)
+ );
+ let record = parse_marker(delegated.as_bytes()).unwrap();
+ let delegate_holder = |now| {
+ marker_live_holder(&record, &world_with(now, &alive, &unreadable)).map(|owner| owner.pid)
+ };
+ assert_eq!(delegate_holder(at(5)), Some(pid));
+ assert_eq!(delegate_holder(at(25)), None);
+ let _ = foreign.kill();
+ let _ = foreign.wait();
+}
+
+#[test]
+fn fresh_empty_marker_is_a_claim_in_flight() {
+ // A3: a 0-byte marker younger than 5 s is a claimant between its
+ // exclusive create and its write — live, and never deleted.
+ let dir = unique_tmp_dir("marker-empty-fresh");
+ let marker = dir.join(".hermes-update-in-progress");
+ std::fs::write(&marker, "").unwrap();
+ assert_eq!(busy(UpdateMarkerGuard::acquire(marker.clone())).pid, 0);
+ assert_eq!(
+ std::fs::read(&marker).unwrap(),
+ b"",
+ "a fresh empty marker is not deleted"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn old_empty_marker_is_reclaimed_and_claim_leaves_no_tmp() {
+ let dir = unique_tmp_dir("marker-empty-old");
+ let marker = dir.join(".hermes-update-in-progress");
+ let file = std::fs::File::create(&marker).unwrap();
+ file.set_modified(SystemTime::now() - Duration::from_secs(10))
+ .unwrap();
+ drop(file);
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("a 10 s old empty marker is dead"));
+ let body = std::fs::read_to_string(&marker).unwrap();
+ assert!(body.starts_with(&format!("{}\n", std::process::id())));
+ let litter: Vec<_> = std::fs::read_dir(&dir)
+ .unwrap()
+ .flatten()
+ .map(|entry| entry.file_name().to_string_lossy().into_owned())
+ .filter(|name| name.ends_with(".tmp"))
+ .collect();
+ assert!(
+ litter.is_empty(),
+ "the publish tmp file must be removed: {litter:?}"
+ );
+ drop(guard);
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[test]
+fn own_exact_v2_claim_is_adopted_verbatim_and_released() {
+ // Our exact incarnation's claim (any age) is adopted byte-for-byte; complete() releases it.
+ let me = std::process::id();
+ let dir = unique_tmp_dir("marker-own-v2");
+ let marker = dir.join(".hermes-update-in-progress");
+ let body = v2_body(me, now_secs() - 25 * 60, ct_of(me));
+ std::fs::write(&marker, &body).unwrap();
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("own v2 marker must be adopted"));
+ assert_eq!(std::fs::read_to_string(&marker).unwrap(), body);
+ drop(guard);
+ assert!(!marker.exists());
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+fn unwritable_message(result: Result<UpdateMarkerGuard, AcquireError>) -> String {
+ match result {
+ Err(AcquireError::Unwritable(msg)) => msg,
+ Err(AcquireError::Busy(owner)) => {
+ panic!("expected Unwritable, got Busy pid {}", owner.pid)
+ }
+ Ok(_) => panic!("expected Unwritable, acquire succeeded"),
+ }
+}
+
+#[test]
+fn marker_under_a_regular_file_is_unwritable() {
+ // m8: never proceed unclaimed.
+ let dir = unique_tmp_dir("marker-under-file");
+ let not_a_dir = dir.join("home");
+ std::fs::write(&not_a_dir, "x").unwrap();
+ let marker = not_a_dir.join(".hermes-update-in-progress");
+ let msg = unwritable_message(UpdateMarkerGuard::acquire(marker.clone()));
+ assert!(msg.starts_with(&format!(
+ "Cannot lock this install for the update: {} is not writable (",
+ marker.display()
+ )));
+ assert!(msg.ends_with("). Run the update as the user that owns the install."));
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+#[cfg(unix)]
+#[test]
+fn marker_in_a_read_only_dir_is_unwritable() {
+ use std::os::unix::fs::PermissionsExt;
+ if unsafe { libc::geteuid() } == 0 {
+ return; // root ignores directory permissions
+ }
+ // No marker yet, and a dead marker that cannot be removed: both refuse.
+ for existing in [None, Some(format!("2147483647\n{}\n", now_secs()))] {
+ let dir = unique_tmp_dir("marker-read-only");
+ let marker = dir.join(".hermes-update-in-progress");
+ if let Some(body) = &existing {
+ std::fs::write(&marker, body).unwrap();
+ }
+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap();
+ let result = UpdateMarkerGuard::acquire(marker.clone());
+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
+ assert!(
+ unwritable_message(result).contains("is not writable"),
+ "{existing:?}"
+ );
+ assert_eq!(std::fs::read_to_string(&marker).ok(), existing);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+}
+
+#[test]
+fn claim_sweeps_dead_claimants_tmp_litter() {
+ // m10: a claimant that died mid-publish leaves its tmp sibling.
+ let dir = unique_tmp_dir("marker-litter");
+ let marker = dir.join(".hermes-update-in-progress");
+ let me = std::process::id();
+ let dead = [
+ ".hermes-update-in-progress.2147483647.123.tmp",
+ ".hermes-update-in-progress.2147483647.tmp",
+ ];
+ let kept = [
+ format!(".hermes-update-in-progress.{me}.123.tmp"),
+ "other.2147483647.123.tmp".to_string(),
+ ];
+ for name in dead
+ .iter()
+ .map(|n| n.to_string())
+ .chain(kept.iter().cloned())
+ {
+ std::fs::write(dir.join(name), "").unwrap();
+ }
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("fresh acquire must succeed"));
+ for name in dead {
+ assert!(!dir.join(name).exists(), "{name} belongs to a dead pid");
+ }
+ for name in &kept {
+ assert!(dir.join(name).exists(), "{name} must be kept");
+ }
+ drop(guard);
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+/// The live owner a refused acquire reports; panics on any other outcome.
+fn busy(result: Result<UpdateMarkerGuard, AcquireError>) -> MarkerOwner {
+ match result {
+ Err(AcquireError::Busy(owner)) => owner,
+ Err(AcquireError::Unwritable(msg)) => panic!("expected Busy, got Unwritable: {msg}"),
+ Ok(_) => panic!("expected Busy, acquire succeeded"),
+ }
+}
+
+fn unique_tmp_dir(tag: &str) -> PathBuf {
+ let base = std::env::temp_dir().join(format!(
+ "hermes-marker-test-{tag}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&base).unwrap();
+ base
+}
+
+// ---- A7: marker mutex (rule 1) and the shared corpus (rule 7) ----
+
+/// Child half of `marker_mutations_wait_for_the_mutex_another_process_holds`: holds the
+/// marker mutex from a SEPARATE process for 1.5 s.
+#[test]
+#[ignore = "spawned by marker_mutations_wait_for_the_mutex_another_process_holds"]
+fn marker_mutex_child_helper() {
+ let Some(path) = std::env::var_os("HERMES_TEST_MARKER_MUTEX_PATH") else {
+ return;
+ };
+ let path = PathBuf::from(path);
+ let _mutex = lock_marker(&path).expect("child takes the free mutex");
+ std::fs::write(path.with_extension("held"), b"").unwrap();
+ std::thread::sleep(Duration::from_millis(1500));
+}
+
+#[test]
+fn marker_mutations_wait_for_the_mutex_another_process_holds() {
+ // R3: a reclaim decided on stale bytes cannot delete a claim published after its read,
+ // because every decision-and-mutation runs under one kernel lock. Here another process
+ // holds that lock (as a paused reader would): our reclaim of a dead marker waits for it.
+ let dir = unique_tmp_dir("marker-mutex");
+ std::fs::create_dir_all(&dir).unwrap();
+ let marker = dir.join(".hermes-update-in-progress");
+ std::fs::write(&marker, "0\n0\n").unwrap();
+ let module = module_path!();
+ let test_name = format!(
+ "{}::marker_mutex_child_helper",
+ module.split_once("::").map_or(module, |(_, rest)| rest)
+ );
+ let mut child = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([test_name.as_str(), "--exact", "--ignored", "--nocapture"])
+ .env("HERMES_TEST_MARKER_MUTEX_PATH", &marker)
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .expect("spawn mutex child");
+ let held = marker.with_extension("held");
+ let deadline = std::time::Instant::now() + Duration::from_secs(30);
+ while !held.exists() {
+ assert!(
+ std::time::Instant::now() < deadline,
+ "mutex child never held the lock"
+ );
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ let started = std::time::Instant::now();
+ let guard = UpdateMarkerGuard::acquire(marker.clone())
+ .unwrap_or_else(|_| panic!("the dead marker is reclaimed once the mutex is free"));
+ assert!(
+ started.elapsed() >= Duration::from_millis(900),
+ "the reclaim ran while another process held the marker mutex"
+ );
+ assert_eq!(
+ parse_marker(&std::fs::read(&marker).unwrap()).unwrap().pid,
+ std::process::id()
+ );
+ assert!(
+ marker_mutex_path(&marker).exists(),
+ "the sidecar is never deleted"
+ );
+ drop(guard);
+ let _ = child.wait();
+ let _ = std::fs::remove_dir_all(&dir);
+}
+
+const CORPUS: &str = include_str!("../../../../tests/fixtures/update_marker_corpus.json");
+
+fn corpus_world<'a>(
+ corpus: &serde_json::Value,
+ case: &serde_json::Value,
+ pid_key: &str,
+ ct_key: &str,
+ table: &'a std::collections::HashMap<u32, Option<f64>>,
+ alive: &'a dyn Fn(u32) -> bool,
+ ct_of: &'a dyn Fn(u32) -> Option<f64>,
+) -> World<'a> {
+ let pid = case
+ .get(pid_key)
+ .unwrap_or(&corpus["our_pid"])
+ .as_u64()
+ .unwrap() as u32;
+ let ct = case.get(ct_key).unwrap_or(&corpus["our_ct"]).as_f64();
+ let _ = table;
+ World {
+ pid,
+ ct,
+ now: corpus["now"].as_u64().unwrap(),
+ alive,
+ ct_of,
+ }
+}
+
+fn corpus_table(
+ corpus: &serde_json::Value,
+ case: &serde_json::Value,
+ pid_key: &str,
+ ct_key: &str,
+) -> std::collections::HashMap<u32, Option<f64>> {
+ let mut table: std::collections::HashMap<u32, Option<f64>> = case["live"]
+ .as_object()
+ .unwrap()
+ .iter()
+ .filter_map(|(pid, ct)| Some((pid.parse::<u32>().ok()?, ct.as_f64())))
+ .collect();
+ let me = case
+ .get(pid_key)
+ .unwrap_or(&corpus["our_pid"])
+ .as_u64()
+ .unwrap() as u32;
+ table.insert(me, case.get(ct_key).unwrap_or(&corpus["our_ct"]).as_f64());
+ table
+}
+
+#[test]
+fn shared_marker_corpus_judge_cases() {
+ let corpus: serde_json::Value = serde_json::from_str(CORPUS).unwrap();
+ assert_eq!(corpus["own_ct_epsilon"].as_f64(), Some(OWN_CT_EPSILON_SECS));
+ assert_eq!(
+ corpus["ct_tolerance"].as_f64(),
+ Some(MARKER_CT_TOLERANCE_SECS)
+ );
+ assert_eq!(
+ corpus["v1_max_age"].as_u64(),
+ Some(UPDATE_MARKER_MAX_AGE_SECS)
+ );
+ let cases = corpus["judge"].as_array().unwrap();
+ assert!(cases.len() >= 30);
+ for case in cases {
+ let name = case["name"].as_str().unwrap();
+ let table = corpus_table(&corpus, case, "our_pid", "our_ct");
+ let alive = |pid: u32| pid != 0 && table.contains_key(&pid);
+ let ct_of = |pid: u32| table.get(&pid).copied().flatten();
+ let world = corpus_world(&corpus, case, "our_pid", "our_ct", &table, &alive, &ct_of);
+ let raw = case["text"].as_str().unwrap().as_bytes();
+ let (verdict, owner, run) = match parse_marker(raw) {
+ None => ("malformed", None, None),
+ Some(record) => {
+ let run = record.runs.first().cloned();
+ match marker_live_holder(&record, &world) {
+ None => ("dead", None, run),
+ Some(holder) => {
+ let age = world.now.saturating_sub(record.started_at);
+ let ours = (record.pid == world.pid
+ && identity_live(record.pid, record.ct, age, &world))
+ || record.delegate.is_some_and(|(pid, ct)| {
+ pid == world.pid && identity_live(pid, Some(ct), age, &world)
+ });
+ (if ours { "ours" } else { "live" }, Some(holder.pid), run)
+ }
+ }
+ }
+ };
+ let expect = &case["expect"];
+ assert_eq!(
+ verdict,
+ expect["verdict"].as_str().unwrap(),
+ "{name}: verdict"
+ );
+ assert_eq!(
+ owner.map(u64::from),
+ expect["owner"].as_u64(),
+ "{name}: owner"
+ );
+ assert_eq!(run.as_deref(), expect["run"].as_str(), "{name}: run");
+ }
+}
+
+#[test]
+fn shared_marker_corpus_release_cases() {
+ let corpus: serde_json::Value = serde_json::from_str(CORPUS).unwrap();
+ for case in corpus["release"].as_array().unwrap() {
+ let name = case["name"].as_str().unwrap();
+ let table = corpus_table(&corpus, case, "releaser_pid", "releaser_ct");
+ let alive = |pid: u32| pid != 0 && table.contains_key(&pid);
+ let ct_of = |pid: u32| table.get(&pid).copied().flatten();
+ let world = corpus_world(
+ &corpus,
+ case,
+ "releaser_pid",
+ "releaser_ct",
+ &table,
+ &alive,
+ &ct_of,
+ );
+ let expect = &case["expect"];
+ let got = release_decision(case["text"].as_str().unwrap().as_bytes(), &world);
+ let want = match expect["action"].as_str().unwrap() {
+ "keep" => Release::Keep,
+ "delete" => Release::Delete,
+ "rewrite" => Release::Rewrite(expect["text"].as_str().unwrap().as_bytes().to_vec()),
+ other => panic!("{name}: unknown action {other}"),
+ };
+ assert_eq!(got, want, "{name}");
+ }
+}
diff --git a/hermes_cli/_old_updater.py b/hermes_cli/_old_updater.py
index 4d53148bfc8..1077f3775a8 100644
--- a/hermes_cli/_old_updater.py
+++ b/hermes_cli/_old_updater.py
@@ -132,7 +132,7 @@ def _run_child(request: dict) -> tuple[int, dict]:
context.write_text(json.dumps(request), encoding="utf-8")
child = subprocess.run(
[sys.executable, "-I", "-S", "-B", "-X", "utf8", str(root / "hermes_cli/_update_takeover.py"),
- str(context), str(result)], cwd=root, env=env,
+ str(context), str(result)], cwd=root, env=env, **_checkout_custody(root),
)
completed = json.loads(result.read_text(encoding="utf-8-sig")) if result.is_file() else {}
if not isinstance(completed, dict):
@@ -140,6 +140,18 @@ def _run_child(request: dict) -> tuple[int, dict]:
return child.returncode if child.returncode >= 0 else 1, completed
+def _checkout_custody(root: Path) -> dict:
+ """The takeover child keeps the checkout lock this (old) updater holds: its fd, read from the
+ update_lock module ALREADY loaded in this process (nothing new is imported here). Releases
+ without a checkout lock hold none, and the takeover acquires it itself."""
+ held = getattr(sys.modules.get("hermes_cli.update_lock"), "checkout_lock_fds", None)
+ try:
+ fds = tuple(held(root)) if held is not None and os.name == "posix" else ()
+ except Exception: # noqa: BLE001 - an old module's surprise must not fail the update
+ fds = ()
+ return {"pass_fds": fds} if fds else {}
+
+
def stop_for_relaunch(*, incomplete: bool = False) -> NoReturn:
"""Finish in a fresh child, then exit rather than resume an old fallback.
diff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.py
index 72015741a66..248f69851be 100644
--- a/hermes_cli/_update_takeover.py
+++ b/hermes_cli/_update_takeover.py
@@ -86,7 +86,9 @@ def main() -> int:
from hermes_cli import update_receipt
from hermes_cli.update_lock import UpdateLock, describe_holder
- lock = UpdateLock()
+ # The takeover syncs dependencies and its update_finish child builds the checkout: hold
+ # (or join, inherited from the old updater) the checkout lock, not just the marker (R2).
+ lock = UpdateLock(install_root=Path(request["root"]))
if not lock.acquire():
print(describe_holder(lock.holder), file=sys.stderr)
return 2
@@ -101,7 +103,11 @@ def main() -> int:
# update liveness checks while the waiting parent still holds its lock.
command = [str(python), "-I", "-B", "-X", "utf8", str(Path(request["root"]) / "hermes_cli/update_finish.py"),
str(context), str(result)]
- code = subprocess.run(command, cwd=request["root"], env=env).returncode
+ from hermes_cli.update_lock import checkout_lock_fds
+
+ fds = checkout_lock_fds(request["root"])
+ code = subprocess.run(command, cwd=request["root"], env=env,
+ **({"pass_fds": fds} if fds else {})).returncode
if code != 0 and not result.is_file():
_record_failure(request, result, code, f"completion child exited {code} without acknowledgement")
return code
diff --git a/hermes_cli/source_build.py b/hermes_cli/source_build.py
index 240170e7d6b..f7846d38fe2 100644
--- a/hermes_cli/source_build.py
+++ b/hermes_cli/source_build.py
@@ -48,13 +48,17 @@ def source_build_env(base_env: dict | None = None, *, explicit: bool = False) ->
def run_source_script(project_root: Path, script: str, *args: str, env: dict, label: str) -> None:
from pm.progress import run_contained
+ from hermes_cli.update_lock import checkout_lock_fds
+ # The build writes the checkout: node (and npm/esbuild under it) inherits the update's
+ # checkout lock fd, so the checkout is never handed to a contender while it still writes.
+ fds = checkout_lock_fds(project_root)
# npm's deprecation warnings are the loudest lines and never actionable
# here; they still land in the failure tail.
run_contained(
[shutil.which("node", path=env["PATH"]), str(project_root / script), *args],
label, hide=lambda line: line.lower().startswith("npm warn"), indent=" ",
- cwd=project_root, env=env,
+ cwd=project_root, env=env, **({"pass_fds": fds} if fds else {}),
)
diff --git a/hermes_cli/source_completion.py b/hermes_cli/source_completion.py
index 40cdccfdd31..a0c417327b1 100644
--- a/hermes_cli/source_completion.py
+++ b/hermes_cli/source_completion.py
@@ -55,8 +55,10 @@ def complete_source_checkout(
# Claim the shared update lock so stacked completions serialize. A tail whose
# orchestrator already holds the lock (venv_sync's interrupted-update finish,
# the updater's completion child) runs under its parent's claim, exactly as
- # `hermes update` does under the desktop handoff pid.
- lock = UpdateLock()
+ # `hermes update` does under the desktop handoff pid. The CHECKOUT lock is acquired, not
+ # sampled (R2): a completion from another home must not build a checkout an update owns;
+ # one inside the update's tree joins the lock it inherited.
+ lock = UpdateLock(install_root=root)
if not lock.acquire():
raise RuntimeError(
f"an update is still running ({describe_holder(lock.holder)}); "
@@ -202,7 +204,13 @@ def main(argv: list[str] | None = None) -> int:
passthrough = (["--desktop"] if args.desktop else []) + \
(["--finish-update"] if args.finish_update else [])
command = _bootstrap_command(root, passthrough)
- return subprocess.call(command, cwd=root, env=activation_environment(root))
+ from hermes_cli.update_lock import checkout_lock_fds
+
+ # Called inside an update tree (venv_sync's interrupted-update finish), the prepared child
+ # keeps the checkout lock this bootstrap inherited.
+ fds = checkout_lock_fds(root)
+ return subprocess.call(command, cwd=root, env=activation_environment(root),
+ **({"pass_fds": fds} if fds else {}))
if __name__ == "__main__":
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index c45e99ffc96..4b45e5f3bef 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -260,6 +260,11 @@ def _git_run(git_cmd, args, cwd=None, *, check=False, network=False):
# calls, so layer them instead of passing the keyword twice.
spawn_kwargs = {"timeout": NETWORK_GIT_TIMEOUT_SECONDS, **_no_prompt_git_kwargs()} if network else {}
spawn_kwargs.setdefault("creationflags", windows_hide_flags())
+ from hermes_cli.update_lock import custody_spawn_kwargs
+
+ # Git (and the hooks it runs) mutates the checkout: it keeps the update's checkout lock fd,
+ # so a killed updater cannot hand the checkout to a contender while git still writes (R2).
+ spawn_kwargs.update(custody_spawn_kwargs())
try:
return subprocess.run(
git_cmd + args, cwd=_m().PROJECT_ROOT if cwd is None else cwd, capture_output=True,
diff --git a/hermes_cli/update_finish.py b/hermes_cli/update_finish.py
index 2014b0a1b6c..1d56faadc6b 100644
--- a/hermes_cli/update_finish.py
+++ b/hermes_cli/update_finish.py
@@ -122,7 +122,7 @@ def main(context: Path, result: Path) -> int:
cli.main()
else:
plan = _restore_plan(request.get("plan"))
- with UpdateLock() as lock:
+ with UpdateLock(install_root=root) as lock:
if not lock.acquired and lock.holder is not None:
print(describe_holder(lock.holder), file=sys.stderr)
code = 2
diff --git a/hermes_cli/update_lock.py b/hermes_cli/update_lock.py
index f31b3504b14..82ef4fc75d8 100644
--- a/hermes_cli/update_lock.py
+++ b/hermes_cli/update_lock.py
@@ -28,8 +28,9 @@ import re
import secrets
import subprocess
import sys
+import threading
import time
-from contextlib import suppress
+from contextlib import contextmanager, suppress
from dataclasses import dataclass
from pathlib import Path
@@ -223,23 +224,92 @@ def process_create_time(pid: int | None = None) -> float | None:
return _stdlib_create_time(target)
-def _identity_live(pid: int, create_time: float | None, age: float) -> bool:
- """C1 rule 3 + A1 for one (pid, ct) identity of a marker ``age`` seconds old.
+def _own_create_time() -> float | None:
+ """This process's creation time (cached per pid: a forked child is another process)."""
+ pid = os.getpid()
+ if _OWN_CT.get("pid") != pid:
+ _OWN_CT.update(pid=pid, ct=process_create_time(pid))
+ return _OWN_CT.get("ct")
+
+
+_OWN_CT: dict = {}
+
+
+def _as_ct(recorded) -> float | None:
+ """A recorded creation time as a float: a number, ``"ct:<s>"`` / ``"<s>"`` text, or None."""
+ if recorded is None or isinstance(recorded, (int, float)):
+ return None if recorded is None else float(recorded)
+ match = _CT_VALUE.fullmatch(str(recorded).strip().removeprefix("ct:"))
+ return float(match.group(0)) if match else None
+
+
+def incarnation_live(pid: int, recorded_ct=None) -> bool | None:
+ """THE one incarnation rule (A7 rule 4) for every Python identity reader (marker, pause record).
+
+ An identity is (pid, creation time). ``True``: that process is running. ``False``: no such
+ process, a different incarnation of the pid, or a claim naming OUR pid that is not us — our
+ own pid is ours only within :data:`_OWN_CREATE_TIME_EPSILON` of our creation time, and a
+ claim without a creation time naming our pid is a previous incarnation (a fresh pid
+ namespace hands a killed update's pid to the next launch). ``None``: alive but unprovable —
+ no creation time recorded, or the live one unreadable (Windows denies elevated/other-user
+ pids); each caller applies its own bound (the marker: the v1 age ceiling).
+
+ ``recorded_ct`` is a float or the marker spelling ``"ct:<seconds>"``.
+ """
+ try:
+ pid = int(pid)
+ except (TypeError, ValueError):
+ return False
+ if pid <= 0 or not _pid_alive(pid):
+ return False
+ recorded = _as_ct(recorded_ct)
+ if pid == os.getpid():
+ own = _own_create_time()
+ if own is None:
+ return None # degraded: we cannot tell our incarnations apart
+ return recorded is not None and abs(own - recorded) <= _OWN_CREATE_TIME_EPSILON
+ if recorded is None:
+ return None
+ actual = process_create_time(pid)
+ return None if actual is None else abs(actual - recorded) <= CREATE_TIME_TOLERANCE_SECONDS
+
+
+@dataclass(frozen=True)
+class _World:
+ """What a marker verdict depends on besides the bytes: us, the clock, the process table.
+ Production uses :func:`_real_world`; the shared corpus injects a table."""
+
+ pid: int
+ ct: float | None
+ now: float
+ alive: object # Callable[[int], bool]
+ ct_of: object # Callable[[int], float | None]
+
+
+def _real_world() -> _World:
+ return _World(os.getpid(), _own_create_time(), time.time(), _pid_alive, process_create_time)
+
+
+def _identity_live(pid: int, create_time: float | None, age: float, world: _World | None = None) -> bool:
+ """C1 rule 3 + A1 + A7 rule 4 for one (pid, ct) identity of a marker ``age`` seconds old.
Alive (not a zombie) and, when a creation time was recorded, the same process: a matching
creation time is live however old the marker is. Without that proof — a v1 marker, or a
- creation time we cannot read (Windows denies it for elevated/other-user pids) — the pid may
- be a reused one, so only the legacy age ceiling bounds it.
+ creation time we cannot read — the pid may be a reused one, so only the legacy age ceiling
+ bounds it. Our own pid follows :func:`incarnation_live` (exact creation time, no-ct = dead).
"""
- if not _pid_alive(pid):
+ w = world or _real_world()
+ if pid <= 0 or not w.alive(pid):
return False
- actual = None if create_time is None else process_create_time(pid)
+ if pid == w.pid:
+ if w.ct is None:
+ # Degraded: our own creation time is unreadable, so our claims are v1 too.
+ return create_time is None
+ return create_time is not None and abs(w.ct - create_time) <= _OWN_CREATE_TIME_EPSILON
+ actual = None if create_time is None else w.ct_of(pid)
if actual is None:
return age <= UPDATE_MARKER_MAX_AGE_SECONDS
- # Our own pid is us only at our exact creation time: a fresh pid namespace (container, bwrap)
- # hands a killed update's pid to the next launch well inside the cross-writer skew window.
- tolerance = _OWN_CREATE_TIME_EPSILON if pid == os.getpid() else CREATE_TIME_TOLERANCE_SECONDS
- return abs(actual - create_time) <= tolerance
+ return abs(actual - create_time) <= CREATE_TIME_TOLERANCE_SECONDS
def _identity_line(pid: int | None = None) -> str:
@@ -424,6 +494,14 @@ class UpdateHolder:
reason: str | None = None
+_U32_MAX = 0xFFFFFFFF
+_INT_LINE = re.compile(r"[0-9]+", re.ASCII)
+_CT_VALUE = re.compile(r"[0-9]+(?:\.[0-9]+)?", re.ASCII)
+_CT_LINE = re.compile(r"ct:([0-9]+(?:\.[0-9]+)?)", re.ASCII)
+_DELEGATE_LINE = re.compile(r"delegate:([0-9]+) ct:([0-9]+(?:\.[0-9]+)?)", re.ASCII)
+_RUN_LINE = re.compile(r"run:([A-Za-z0-9._-]{1,128})", re.ASCII)
+
+
@dataclass(frozen=True)
class _Marker:
raw: bytes
@@ -433,55 +511,112 @@ class _Marker:
delegate_pid: int | None
delegate_create_time: float | None
in_flight: bool = False # an empty marker younger than EMPTY_MARKER_GRACE_SECONDS
+ ct_text: str | None = None
+ delegate_ct_text: str | None = None
+ runs: tuple[str, ...] = ()
@property
def base(self) -> bytes:
"""Lines 1–3 exactly as written (what a delegate keeps byte-identical)."""
return b"".join(self.raw.splitlines(keepends=True)[:3])
- def age(self) -> float:
- return time.time() - self.started_at if self.started_at is not None else float("inf")
+ @property
+ def run(self) -> str | None:
+ return self.runs[0] if self.runs else None
+
+ def age(self, world: _World | None = None) -> float:
+ now = time.time() if world is None else world.now
+ return now - self.started_at if self.started_at is not None else float("inf")
- def owner_live(self) -> bool:
- return self.started_at is not None and _identity_live(self.pid, self.create_time, self.age())
+ def owner_live(self, world: _World | None = None) -> bool:
+ return self.started_at is not None \
+ and _identity_live(self.pid, self.create_time, self.age(world), world)
- def delegate_live(self) -> bool:
+ def delegate_live(self, world: _World | None = None) -> bool:
return self.delegate_pid is not None and self.started_at is not None \
- and _identity_live(self.delegate_pid, self.delegate_create_time, self.age())
+ and _identity_live(self.delegate_pid, self.delegate_create_time, self.age(world), world)
- def live_pid(self) -> int | None:
+ def live_pid(self, world: _World | None = None) -> int | None:
if self.in_flight:
return 0
- if self.owner_live():
+ if self.owner_live(world):
return self.pid
- return self.delegate_pid if self.delegate_live() else None
-
+ return self.delegate_pid if self.delegate_live(world) else None
-_INT_LINE = re.compile(r"[0-9]+", re.ASCII)
-_CT_LINE = re.compile(r"ct:([0-9]+(?:\.[0-9]+)?)", re.ASCII)
-_DELEGATE_LINE = re.compile(r"delegate:([0-9]+) ct:([0-9]+(?:\.[0-9]+)?)", re.ASCII)
+ def canonical(self, pid: int, ct_text: str | None) -> bytes:
+ """A rewritten claim (A7 rule 5): ``pid`` owns it from ``started_at`` on; run lines kept."""
+ body = f"{pid}\n{self.started_at}\n" + (f"ct:{ct_text}\n" if ct_text else "")
+ return (body + "".join(f"run:{run}\n" for run in self.runs)).encode()
def _parse_marker(raw: bytes, *, mtime: float | None = None) -> _Marker:
- """Contract A2, positional and identical in every reader (Rust ``marker.rs``, Electron,
- the hand-off scripts): BOM and CRLF tolerated; line 1 pid and line 2 started_at are
- integers or the marker is MALFORMED (dead: ``started_at`` None); a bad line 3 makes it v1;
- a bad line 4 is ignored."""
+ """Contract A2 + A7 rule 7, identical in every reader (Rust ``marker.rs``, Electron, the
+ hand-off scripts; ``tests/fixtures/update_marker_corpus.json``): BOM, CRLF and surrounding
+ spaces/tabs tolerated; line 1 pid (u32) and line 2 started_at are integers or the marker is
+ MALFORMED (dead: ``started_at`` None); a bad line 3 makes it v1; lines 4+ are tagged — the
+ first well-formed ``delegate:<pid> ct:<ct>`` and every ``run:<id>`` — anything else ignored."""
text = raw.decode("utf-8", errors="replace").removeprefix("\ufeff")
lines = [line.removesuffix("\r").strip(" \t") for line in text.split("\n")]
- lines += [""] * (4 - len(lines))
+ lines += [""] * (3 - len(lines))
pid = int(lines[0]) if _INT_LINE.fullmatch(lines[0]) else -1
+ if pid > _U32_MAX:
+ pid = -1
started_at = int(lines[1]) if pid >= 0 and _INT_LINE.fullmatch(lines[1]) else None
ct = _CT_LINE.fullmatch(lines[2])
- delegate = _DELEGATE_LINE.fullmatch(lines[3])
+ delegate = next((m for m in map(_DELEGATE_LINE.fullmatch, lines[3:])
+ if m and int(m.group(1)) <= _U32_MAX), None)
+ runs = tuple(m.group(1) for m in map(_RUN_LINE.fullmatch, lines[3:]) if m)
in_flight = not raw and mtime is not None and time.time() - mtime < EMPTY_MARKER_GRACE_SECONDS
return _Marker(
raw=raw, pid=pid, started_at=started_at, create_time=float(ct.group(1)) if ct else None,
delegate_pid=int(delegate.group(1)) if delegate else None,
delegate_create_time=float(delegate.group(2)) if delegate else None, in_flight=in_flight,
+ ct_text=ct.group(1) if ct else None, delegate_ct_text=delegate.group(2) if delegate else None,
+ runs=runs,
)
+def judge_marker(raw: bytes, world: _World | None = None) -> tuple[str, int | None, str | None]:
+ """``(verdict, owner, run)`` of marker bytes — the shared corpus' judge contract.
+
+ verdict: ``malformed`` | ``dead`` | ``ours`` (a live identity is this incarnation) | ``live``;
+ owner: the owner identity if live, else the delegate if live, else None.
+ """
+ w = world or _real_world()
+ marker = _parse_marker(raw)
+ if marker.started_at is None:
+ return "malformed", None, None
+ owner = marker.live_pid(w)
+ if owner is None:
+ return "dead", None, marker.run
+ ours = (marker.pid == w.pid and marker.owner_live(w)) \
+ or (marker.delegate_pid == w.pid and marker.delegate_live(w))
+ return ("ours" if ours else "live"), owner, marker.run
+
+
+def _release_decision(raw: bytes, world: _World | None = None) -> tuple[str, bytes | None]:
+ """A7 rule 5: what releasing ``world``'s claim does to marker bytes ``raw``.
+
+ ``("delete", None)`` | ``("rewrite", new bytes)`` | ``("keep", None)``. The owner (line 1–3
+ identity is our incarnation) deletes — regardless of delegate lines — unless a live delegate
+ other than us exists: then that delegate becomes the owner. A delegate (us) drops its line
+ while the owner lives, else deletes. Anything not naming us is kept.
+ """
+ w = world or _real_world()
+ marker = _parse_marker(raw)
+ if marker.started_at is None:
+ return "keep", None
+ if marker.pid == w.pid and marker.owner_live(w):
+ if marker.delegate_pid not in (None, w.pid) and marker.delegate_live(w):
+ return "rewrite", marker.canonical(marker.delegate_pid, marker.delegate_ct_text)
+ return "delete", None
+ if marker.delegate_pid == w.pid and marker.delegate_live(w):
+ if marker.owner_live(w):
+ return "rewrite", marker.canonical(marker.pid, marker.ct_text)
+ return "delete", None
+ return "keep", None
+
+
def _read_bytes(path: Path) -> bytes | None:
try:
return path.read_bytes()
@@ -519,49 +654,153 @@ def _sweep_dead_tmp_siblings(path: Path) -> None:
entry.unlink()
-def _compare_and_delete(path: Path, expected: bytes) -> bool:
- """Delete ``path`` only while it still holds exactly ``expected`` (C1 rule 5)."""
- if _read_bytes(path) != expected:
- return False
- with suppress(FileNotFoundError):
- path.unlink()
- return True
+# --- the marker mutex (A7 rule 1) -------------------------------------------------------------
+MUTEX_SUFFIX = ".lock"
+# Bounded wait for the sidecar: holders never run git/builds/network inside it.
+MUTEX_WAIT_SECONDS = 10.0
+
+
+class MarkerBusy(OSError):
+ """The marker mutex stayed held past :data:`MUTEX_WAIT_SECONDS`: report busy."""
+
+
+_MUTEX_HELD = threading.local()
+
+
+def marker_mutex_path(path: Path) -> Path:
+ """``<marker>.lock``: the sidecar every marker MUTATION holds a kernel lock on. Never deleted
+ (deleting it would split the lock across two inodes)."""
+ return path.with_name(path.name + MUTEX_SUFFIX)
+
+
+def _windows_open_exclusive(path: Path):
+ """The Windows sidecar mutex: the file opened with NO sharing (``FileShare.None`` in the
+ PowerShell scripts, ``share_mode(0)`` in marker.rs). ``None`` = someone else has it open."""
+ import ctypes
+ from ctypes import wintypes
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p,
+ wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
+ kernel32.CreateFileW.restype = wintypes.HANDLE
+ invalid = ctypes.c_void_p(-1).value
+ for access, disposition in ((0xC0000000, 4), (0x80000000, 3)): # RW OPEN_ALWAYS; R OPEN_EXISTING
+ handle = kernel32.CreateFileW(str(path), access, 0, None, disposition, 0x80, None)
+ if handle and handle != invalid:
+ return handle
+ error = ctypes.get_last_error()
+ if error == 32: # ERROR_SHARING_VIOLATION: held
+ return None
+ if error != 5: # anything but access denied: no read-only retry helps
+ break
+ raise ctypes.WinError(error)
+
+
+def _windows_close(handle) -> None:
+ import ctypes
+
+ ctypes.WinDLL("kernel32").CloseHandle(handle)
+
+
+def _mutex_acquire(path: Path, wait: float):
+ deadline = time.monotonic() + wait
+ if sys.platform == "win32":
+ while True:
+ handle = _windows_open_exclusive(path)
+ if handle is not None:
+ return handle
+ if time.monotonic() >= deadline:
+ raise MarkerBusy(f"{path} is held by another update")
+ time.sleep(0.02)
+ import fcntl
-def _compare_and_swap(path: Path, expected: bytes, new: bytes) -> bool:
- """Atomically replace ``path`` (tmp + ``os.replace``) only while it still holds ``expected``."""
- if _read_bytes(path) != expected:
- return False
- tmp = _tmp_sibling(path)
try:
- with open(tmp, "wb") as fh:
- fh.write(new)
- fh.flush()
- os.fsync(fh.fileno())
+ fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o644)
+ except PermissionError:
+ fd = os.open(path, os.O_RDONLY) # flock works on a read-only fd (root-owned sidecar)
+ try:
+ while True:
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ return fd
+ except BlockingIOError:
+ if time.monotonic() >= deadline:
+ raise MarkerBusy(f"{path} is held by another update") from None
+ time.sleep(0.02)
+ except BaseException:
+ os.close(fd)
+ raise
+
+
+@contextmanager
+def marker_mutex(path: Path, *, wait: float = MUTEX_WAIT_SECONDS):
+ """Hold the kernel lock on ``<marker>.lock`` (A7 rule 1): read → judge → mutate of the marker
+ at ``path`` happens entirely inside. Re-entrant per thread; the kernel releases it if we die.
+ Raises :class:`MarkerBusy` after ``wait`` seconds, ``OSError`` when it cannot be opened."""
+ key = str(marker_mutex_path(path))
+ held = getattr(_MUTEX_HELD, "keys", None)
+ if held is None:
+ held = _MUTEX_HELD.keys = {}
+ if held.get(key):
+ held[key] += 1
+ try:
+ yield
+ finally:
+ held[key] -= 1
+ return
+ handle = _mutex_acquire(Path(key), wait)
+ held[key] = 1
+ try:
+ yield
+ finally:
+ held.pop(key, None)
+ if sys.platform == "win32":
+ _windows_close(handle)
+ else:
+ os.close(handle) # closing the only fd of this open file description drops the flock
+
+
+def _compare_and_delete(path: Path, expected: bytes) -> bool:
+ """Delete ``path`` only while it still holds exactly ``expected`` — compared and unlinked under
+ the marker mutex, so no claim can be published in between (A7; C1 rule 5 was not CAS)."""
+ with marker_mutex(path):
if _read_bytes(path) != expected:
return False
- os.replace(tmp, path)
+ with suppress(FileNotFoundError):
+ path.unlink()
return True
- except OSError as exc:
- logger.debug("Could not rewrite update marker %s: %s", path, exc)
- return False
- finally:
- with suppress(OSError):
- tmp.unlink()
+
+
+def _compare_and_swap(path: Path, expected: bytes, new: bytes) -> bool:
+ """Atomically replace ``path`` (tmp + ``os.replace``) only while it still holds ``expected``,
+ under the marker mutex."""
+ with marker_mutex(path):
+ if _read_bytes(path) != expected:
+ return False
+ tmp = _tmp_sibling(path)
+ try:
+ with open(tmp, "wb") as fh:
+ fh.write(new)
+ fh.flush()
+ os.fsync(fh.fileno())
+ os.replace(tmp, path)
+ return True
+ except OSError as exc:
+ logger.debug("Could not rewrite update marker %s: %s", path, exc)
+ return False
+ finally:
+ with suppress(OSError):
+ tmp.unlink()
def _live_partners(marker: _Marker) -> list[int]:
"""Live identities behind a marker: the owner, then the delegate (``[0]`` for a claim
- still being written).
-
- A v1 marker naming our own pid is a killed update's claim whose pid this run inherited
- (containers restart pid numbering), not ours: without a creation time it cannot be told
- apart, and nothing pre-writes a v1 marker for this process.
- """
+ still being written). A claim naming our own pid counts only at our exact incarnation."""
if marker.in_flight:
return [0]
partners = []
- if marker.owner_live() and not (marker.pid == os.getpid() and marker.create_time is None):
+ if marker.owner_live():
partners.append(marker.pid)
if marker.delegate_live():
partners.append(marker.delegate_pid)
@@ -571,9 +810,9 @@ def _live_partners(marker: _Marker) -> list[int]:
def read_live_update(*, path: Path | None = None) -> UpdateHolder | None:
"""Return the live update holding the marker, or ``None``.
- Mirrors ``readLiveUpdateMarker`` in ``electron/update-marker.ts``: absent, unreadable,
- malformed and dead-owner all mean "no live update", and a dead marker is removed with
- compare-and-delete so it can't strand future runs. Never raises.
+ Absent, unreadable, malformed and dead-owner all mean "no live update". A dead marker is
+ reclaimed — judged again and removed inside the marker mutex, so a claim published after
+ our first read is never the one deleted. Never raises.
"""
marker = path or update_marker_path()
parsed = _read_marker(marker)
@@ -581,11 +820,43 @@ def read_live_update(*, path: Path | None = None) -> UpdateHolder | None:
return None
live = parsed.live_pid()
if live is None:
- _compare_and_delete(marker, parsed.raw)
+ _reclaim_dead(marker)
return None
return UpdateHolder(pid=live, age_seconds=parsed.age() if parsed.started_at is not None else 0.0)
+def _reclaim_dead(path: Path) -> None:
+ try:
+ with marker_mutex(path):
+ current = _read_marker(path)
+ if current is not None and current.live_pid() is None:
+ with suppress(FileNotFoundError):
+ path.unlink()
+ except OSError as exc: # MarkerBusy included: someone else is deciding right now
+ logger.debug("Left update marker %s for its current mutator: %s", path, exc)
+
+
+def legacy_profile_claims(root: Path | None = None) -> list[UpdateHolder]:
+ """Live claims in pre-root-marker ``<root>/profiles/<p>/.hermes-update-in-progress`` files (R11).
+
+ Before the marker moved to the profile-tree root, an update under a named profile claimed
+ its PROFILE home and never took the checkout lock. During the transition such an update can
+ still be running: honor it (v1 rules: pid alive, within the legacy age ceiling, never our own
+ previous incarnation). Read-only: an old updater reclaims its own dead markers.
+ """
+ root = update_marker_path().parent if root is None else root
+ claims = []
+ with suppress(OSError):
+ for profile in (root / "profiles").iterdir():
+ marker = _read_marker(profile / MARKER_NAME)
+ if marker is None or marker.in_flight:
+ continue
+ live = marker.live_pid()
+ if live:
+ claims.append(UpdateHolder(pid=live, age_seconds=marker.age()))
+ return claims
+
+
def describe_holder(holder: UpdateHolder | None) -> str:
"""One-line, user-facing explanation of who holds the update lock."""
if holder is not None and holder.reason:
@@ -710,6 +981,11 @@ def _acquire_checkout(install_root: Path) -> UpdateHolder | None:
try:
if not _try_lock(fd):
os.close(fd)
+ if _held_by_our_windows_ancestor(path):
+ # Windows has no fd inheritance: the update tree's children run in the lock
+ # owner's kill-on-close job (bind_child_to_update_tree) and die with it.
+ _HELD = {"path": str(path), "fd": None, "owned": False, "depth": 1}
+ return None
return _lock_holder(path)
if writable is True:
record = f"{os.getpid()}\n{int(time.time())}\n{_identity_line()}\n".encode()
@@ -724,6 +1000,17 @@ def _acquire_checkout(install_root: Path) -> UpdateHolder | None:
return None
+def _held_by_our_windows_ancestor(path: Path) -> bool:
+ """Windows: the checkout lock's holder record names a LIVE incarnation of one of our
+ ancestors (the ``hermes update`` whose completion/build children we are)."""
+ if sys.platform != "win32":
+ return False
+ record = _parse_marker(_read_bytes(path) or b"")
+ if record.started_at is None or record.pid == os.getpid():
+ return False
+ return incarnation_live(record.pid, record.create_time) is True and _is_ancestor_pid(record.pid)
+
+
def _release_checkout() -> None:
global _HELD
if _HELD is None:
@@ -746,11 +1033,21 @@ def checkout_lock_fds(install_root: Path | str | None = None) -> tuple[int, ...]
if sys.platform == "win32":
return ()
if _HELD is not None:
- return (_HELD["fd"],)
+ return () if _HELD["fd"] is None else (_HELD["fd"],)
fd = _inherited_lock_fd(checkout_lock_path(install_root))
return () if fd is None else (fd,)
+def custody_spawn_kwargs() -> dict:
+ """``subprocess`` kwargs that keep a checkout MUTATOR (git, the Node source build) in the
+ update tree's custody (R2): POSIX children inherit the held lock fd, so the checkout stays
+ locked until the last of them exits even if this process is killed. ``{}`` when this process
+ holds no checkout lock, and on Windows (bind the Popen with bind_child_to_update_tree)."""
+ if sys.platform == "win32" or _HELD is None or _HELD["fd"] is None:
+ return {}
+ return {"pass_fds": (_HELD["fd"],)}
+
+
def bind_child_to_update_tree(proc: subprocess.Popen) -> bool:
"""Windows: put an update-tree child in a kill-on-close job owned by this process, so the
child (and everything it spawns) dies when the lock owner dies and frees the lock.
@@ -867,6 +1164,11 @@ def _publish_exclusive(path: Path, body: bytes) -> bool:
return True
+# Per-process claim depth for each marker path: nested UpdateLocks (an update's completion run
+# in-process, venv_sync finishing a tail) share one claim, released by the outermost.
+_CLAIMS: dict[str, int] = {}
+
+
class UpdateLock:
"""Context manager owning the shared update marker (and, with ``install_root``, the
checkout lock) for this process.
@@ -882,17 +1184,12 @@ class UpdateLock:
self.install_root = None if install_root is None else Path(install_root)
self.acquired = False
self.holder: UpdateHolder | None = None
- self._written: bytes | None = None
- self._delegate_base: bytes | None = None
+ self._claimed = False
self._checkout = False
def acquire(self) -> bool:
- if self.install_root is not None:
- refused = _acquire_checkout(self.install_root)
- if refused is not None:
- self.holder = refused
- return False
- self._checkout = True
+ if self.install_root is not None and not self.acquire_checkout(self.install_root):
+ return False
try:
ok = self._claim_marker()
except BaseException:
@@ -900,7 +1197,23 @@ class UpdateLock:
raise
if not ok:
self._drop_checkout()
- return ok
+ return False
+ key = str(self.path)
+ _CLAIMS[key] = _CLAIMS.get(key, 0) + 1
+ self._claimed = True
+ return True
+
+ def acquire_checkout(self, install_root: Path | str) -> bool:
+ """Take (or join) the checkout lock — ACQUIRE custody, never sample it (R2): a caller
+ that will mutate the checkout under a marker it adopted or claimed calls this first."""
+ if self._checkout:
+ return True
+ refused = _acquire_checkout(Path(install_root))
+ if refused is not None:
+ self.holder = refused
+ return False
+ self._checkout = True
+ return True
def _claim_marker(self) -> bool:
try:
@@ -909,45 +1222,60 @@ class UpdateLock:
self.holder = UpdateHolder(pid=0, age_seconds=0.0, reason=f"{self.path.parent} is not writable ({exc})")
return False
_sweep_dead_tmp_siblings(self.path)
- body = f"{os.getpid()}\n{int(time.time())}\n{_identity_line()}\n".encode()
- for attempt in range(2):
- try:
- published = _publish_exclusive(self.path, body)
- except OSError as exc:
- self.holder = UpdateHolder(pid=0, age_seconds=0.0, reason=f"{self.path} is not writable ({exc})")
+ if _CLAIMS.get(str(self.path)) is None:
+ legacy = [claim for claim in legacy_profile_claims(self.path.parent)
+ if not self._is_partner(claim.pid)]
+ if legacy:
+ self.holder = legacy[0]
return False
- if published:
- self._written = body
- self.acquired = True
- return True
- existing = _read_marker(self.path)
- if existing is None:
- continue # vanished between publish and read: retry
- if _live_partners(existing):
- return self._adopt_or_refuse(existing)
- if attempt == 0 and _compare_and_delete(self.path, existing.raw):
- continue
- self.holder = UpdateHolder(pid=max(existing.pid, 0), age_seconds=0.0)
+ body = f"{os.getpid()}\n{int(time.time())}\n{_identity_line()}\n".encode()
+ try:
+ for _attempt in range(3):
+ # A7 rule 2: an exclusive create needs no mutex — it only succeeds on no marker.
+ if _publish_exclusive(self.path, body):
+ self.acquired = True
+ return True
+ with marker_mutex(self.path):
+ existing = _read_marker(self.path)
+ if existing is None:
+ continue # vanished between publish and read: retry
+ if _live_partners(existing):
+ return self._adopt_or_refuse(existing)
+ # Dead or malformed, judged under the mutex: reclaim and claim in one hold.
+ with suppress(FileNotFoundError):
+ self.path.unlink()
+ if _publish_exclusive(self.path, body):
+ self.acquired = True
+ return True
+ except MarkerBusy:
+ self.holder = UpdateHolder(pid=0, age_seconds=0.0)
+ return False
+ except OSError as exc:
+ self.holder = UpdateHolder(pid=0, age_seconds=0.0, reason=f"{self.path} is not writable ({exc})")
return False
self.holder = read_live_update(path=self.path) or UpdateHolder(pid=0, age_seconds=0.0)
return False
+ @staticmethod
+ def _is_partner(pid: int) -> bool:
+ return pid == os.getpid() or (pid and (pid == _handoff_pid() or _is_ancestor_pid(pid)))
+
def _adopt_or_refuse(self, existing: _Marker) -> bool:
- """C1 rule 4: a LIVE claim by us, an ancestor or the hand-off partner is run under."""
+ """C1 rule 4: a LIVE claim by us, an ancestor or the hand-off partner is run under.
+ Called inside the marker mutex."""
partners = _live_partners(existing)
- if os.getpid() not in partners and not any(
- p and (p == _handoff_pid() or _is_ancestor_pid(p)) for p in partners):
+ if not any(self._is_partner(p) for p in partners):
self.holder = UpdateHolder(pid=partners[0], age_seconds=existing.age() if existing.started_at else 0.0)
return False
own = _identity_line()
if os.getpid() not in partners and existing.delegate_pid not in partners \
and existing.create_time is not None and own:
- # Rule 6: name ourselves as the delegate so the claim stays visible if the partner
- # (a hand-off script, the Tauri updater) dies while this update still runs.
+ # Rule 6: name ourselves as the delegate (line 4) so the claim stays visible if the
+ # partner (a hand-off script, the Tauri updater) dies while this update still runs.
base = existing.base if existing.base.endswith(b"\n") else existing.base + b"\n"
- delegated = base + f"delegate:{os.getpid()} {own}\n".encode()
- if _compare_and_swap(self.path, existing.raw, delegated):
- self._written, self._delegate_base = delegated, existing.base
+ delegated = base + f"delegate:{os.getpid()} {own}\n".encode() \
+ + "".join(f"run:{run}\n" for run in existing.runs).encode()
+ _compare_and_swap(self.path, existing.raw, delegated)
return True
def _drop_checkout(self) -> None:
@@ -956,28 +1284,22 @@ class UpdateLock:
_release_checkout()
def release(self) -> None:
- """Give back what we wrote (compare-and-delete / compare-and-swap). Never raises."""
+ """Give back our part of the claim (A7 rule 5), decided under the marker mutex by
+ identity, not by the bytes we once wrote: whatever names this incarnation — as owner, or
+ as a delegate someone else wrote in (the hand-off script names its child) — is released;
+ a live delegate inherits an owner's claim. Only the outermost claim of a process
+ releases. Never raises."""
try:
- if self._written is not None:
- current = _read_bytes(self.path)
- if current is None:
- pass
- elif self.acquired:
- if current == self._written:
- _compare_and_delete(self.path, current)
- elif current.startswith(self._written) \
- and not _parse_marker(current).delegate_live():
- _compare_and_delete(self.path, current) # our claim + a dead delegate
- elif current == self._written and self._delegate_base is not None:
- if _parse_marker(self._delegate_base).owner_live():
- _compare_and_swap(self.path, current, self._delegate_base)
- else:
- _compare_and_delete(self.path, current)
+ if self._claimed:
+ key = str(self.path)
+ _CLAIMS[key] = _CLAIMS.get(key, 1) - 1
+ if _CLAIMS[key] <= 0:
+ _CLAIMS.pop(key, None)
+ _release_marker(self.path)
except OSError as exc:
logger.debug("Could not release update marker %s: %s", self.path, exc)
finally:
- self.acquired = False
- self._written = self._delegate_base = None
+ self.acquired = self._claimed = False
self._drop_checkout()
def __enter__(self) -> "UpdateLock":
@@ -986,3 +1308,16 @@ class UpdateLock:
def __exit__(self, *_exc) -> None:
self.release()
+
+
+def _release_marker(path: Path) -> None:
+ with marker_mutex(path):
+ raw = _read_bytes(path)
+ if raw is None:
+ return
+ action, new = _release_decision(raw)
+ if action == "delete":
+ with suppress(FileNotFoundError):
+ path.unlink()
+ elif action == "rewrite":
+ _compare_and_swap(path, raw, new)
diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.py
index a648a002c65..00a5ecceeab 100644
--- a/hermes_cli/venv_sync.py
+++ b/hermes_cli/venv_sync.py
@@ -376,7 +376,7 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:
import pm
from hermes_cli._launchers import resolve_store_python
- from hermes_cli.update_lock import UpdateLock, read_live_update, update_in_progress
+ from hermes_cli.update_lock import UpdateLock, read_live_update
current = pm.venv_is_current(project_root=root)
from pm.environments import owning_home_root
@@ -401,12 +401,8 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:
# noise (the record's age tracks the wait), leaving the marker armed.
pass
elif not owed_to_cli and (not current or pending.is_file()):
- # Read before claiming: our own claim would answer for us. A free marker over a held
- # checkout lock is a killed update whose tree (its completion child) still runs.
- busy = update_in_progress(root)
lock = UpdateLock()
- if not lock.acquire() or (lock.acquired and busy):
- lock.release()
+ if not lock.acquire():
raise RuntimeError("an update is still running; wait for it to exit, then relaunch Hermes")
try:
# Under the launching update's own claim (its pid is our ancestor) a process it
@@ -422,6 +418,11 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:
# Relaunching would land back here and sync again, forever.
raise RuntimeError("dependency sync left this install out of date")
else:
+ # The tail mutates the checkout: ACQUIRE its lock (R2), never sample it. A free
+ # marker over a held checkout lock is a killed update whose tree (its completion
+ # child) still runs.
+ if not lock.acquire_checkout(root):
+ raise RuntimeError("an update is still running; wait for it to exit, then relaunch Hermes")
_finish_source_update(root, current=current, pending=pending)
finally:
lock.release()
@@ -520,12 +521,18 @@ def _finish_source_update(root: Path, *, current: bool, pending: Path) -> None:
# The tail's progress lines go to stderr: this is an automatic repair in
# front of whatever command the user ran, and that command may be
# emitting machine-readable stdout (a JSON probe, a piped query).
+ from hermes_cli.update_lock import checkout_lock_fds
+
+ # The completion child stays in this launch's checkout custody (POSIX: it inherits the
+ # lock fd), so a contender never sees the checkout free while it builds.
+ fds = checkout_lock_fds(root)
code = subprocess.call(
[sys.executable, "-I", "-B", "-u",
str(root / "hermes_cli/source_completion.py"),
"--source", str(root), "--finish-update",
*(("--desktop",) if desktop else ())],
cwd=root, env=activation_environment(root), stdout=sys.__stderr__,
+ **({"pass_fds": fds} if fds else {}),
)
if code != 0:
_record_completion_attempt(root, failed=True)
diff --git a/tests/hermes_cli/test_update_lock_protocol.py b/tests/hermes_cli/test_update_lock_protocol.py
new file mode 100644
index 00000000000..fa6039abc73
--- /dev/null
+++ b/tests/hermes_cli/test_update_lock_protocol.py
@@ -0,0 +1,364 @@
+"""Marker mutation protocol (A7) and checkout custody (R2/R11) with real processes and files.
+
+Each test reproduces a review finding on the pre-A7 head: a stale reader deleting a claim
+published after its read (R3), a hand-off owner's killed claim surviving its orphaned delegate
+(A7 rule 5, the native Windows ``orphaned_update`` artifact), git / the Node build writing a
+checkout a contender already owns (R2), a completion from another home entering its build
+while the checkout is owned (R2), and a live pre-root-marker profile claim going unseen (R11).
+"""
+
+from __future__ import annotations
+
+import os
+import signal
+import subprocess
+import sys
+import textwrap
+import time
+from pathlib import Path
+
+import pytest
+
+from hermes_cli.update_lock import UpdateLock, marker_mutex_path, process_create_time
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+posix_only = pytest.mark.skipif(sys.platform == "win32", reason="POSIX signals / fd inheritance")
+
+
+def _script(tmp_path: Path, code: str) -> Path:
+ path = tmp_path / f"child_{abs(hash(code))}.py"
+ path.write_text(textwrap.dedent(code), encoding="utf-8")
+ return path
+
+
+def _python(tmp_path: Path, code: str, *args, **kwargs) -> subprocess.Popen:
+ return subprocess.Popen([sys.executable, str(_script(tmp_path, code)), str(REPO_ROOT), *map(str, args)],
+ stdin=subprocess.DEVNULL, **kwargs)
+
+
+def _wait_for(path: Path, proc: subprocess.Popen | None = None, timeout: float = 30.0) -> str:
+ end = time.monotonic() + timeout
+ while not path.exists():
+ assert proc is None or proc.poll() is None, f"child exited {proc.returncode} before {path.name}"
+ assert time.monotonic() < end, f"timed out waiting for {path}"
+ time.sleep(0.02)
+ return path.read_text(encoding="utf-8")
+
+
+def _alive(pid: int) -> bool:
+ from hermes_cli.update_lock import _pid_alive
+
+ return _pid_alive(pid)
+
+
+_STALE_READER = """
+import linecache, os, signal, sys
+from pathlib import Path
+sys.path.insert(0, sys.argv[1])
+from hermes_cli import update_lock
+src = update_lock.__file__
+def trace(frame, event, arg):
+ if event == "line" and frame.f_code.co_filename == src \\
+ and ".unlink()" in linecache.getline(src, frame.f_lineno):
+ sys.settrace(None)
+ os.kill(os.getpid(), signal.SIGSTOP) # a scheduling pause, nothing replaced
+ return trace
+sys.settrace(trace)
+update_lock.read_live_update(path=Path(sys.argv[2]))
+"""
+
+_CLAIMANT = """
+import sys, time
+from pathlib import Path
+sys.path.insert(0, sys.argv[1])
+from hermes_cli.update_lock import UpdateLock
+assert UpdateLock(path=Path(sys.argv[2])).acquire()
+Path(sys.argv[3]).touch()
+time.sleep(60)
+"""
+
+
+@posix_only
+def test_a_stale_reclaim_never_deletes_a_claim_published_after_its_read(tmp_path):
+ """R3: the reader judged a dead marker, then paused right at its unlink. A second real
+ process claims meanwhile. Pre-A7 the resumed reader deleted that live claim; now the
+ decision and the unlink share one hold of the marker mutex, so the claimant waits."""
+ marker = tmp_path / ".hermes-update-in-progress"
+ marker.write_bytes(b"0\n0\n") # malformed: dead
+ reader = _python(tmp_path, _STALE_READER, marker)
+ claimant = None
+ try:
+ _pid, status = os.waitpid(reader.pid, os.WUNTRACED)
+ assert os.WIFSTOPPED(status)
+ claimant = _python(tmp_path, _CLAIMANT, marker, tmp_path / "claimed")
+ time.sleep(1.0)
+ os.kill(reader.pid, signal.SIGCONT)
+ assert reader.wait(timeout=30) == 0
+ _wait_for(tmp_path / "claimed", claimant)
+ assert marker.read_text(encoding="utf-8").startswith(f"{claimant.pid}\n"), \
+ "a stale reader deleted a live claim published after its read"
+ assert marker_mutex_path(marker).exists(), "the sidecar is never deleted"
+ finally:
+ if reader.poll() is None:
+ os.kill(reader.pid, signal.SIGCONT)
+ reader.kill()
+ reader.wait()
+ if claimant is not None:
+ claimant.kill()
+ claimant.wait()
+
+
+_MUTEX_HOLDER = """
+import sys, time
+from pathlib import Path
+sys.path.insert(0, sys.argv[1])
+from hermes_cli.update_lock import marker_mutex
+with marker_mutex(Path(sys.argv[2])):
+ Path(sys.argv[3]).touch()
+ time.sleep(1.5)
+"""
+
+
+def test_marker_mutations_wait_for_the_mutex_another_process_holds(tmp_path):
+ """A7 rule 1 on every OS (POSIX flock / Windows share-none open of ``<marker>.lock``):
+ while another process holds the marker mutex, a reclaim of even a dead marker waits."""
+ marker = tmp_path / ".hermes-update-in-progress"
+ marker.write_bytes(b"0\n0\n")
+ holder = _python(tmp_path, _MUTEX_HOLDER, marker, tmp_path / "held")
+ try:
+ _wait_for(tmp_path / "held", holder)
+ started = time.monotonic()
+ lock = UpdateLock(path=marker)
+ assert lock.acquire() and lock.acquired
+ assert time.monotonic() - started >= 0.9, "the reclaim ran inside another process's hold"
+ lock.release()
+ assert marker_mutex_path(marker).exists(), "the sidecar is never deleted"
+ finally:
+ holder.wait(timeout=30)
+
+
+_ORPHAN_UPDATE = """
+import sys, time
+from pathlib import Path
+sys.path.insert(0, sys.argv[1])
+from hermes_cli.update_lock import UpdateLock
+base = Path(sys.argv[2])
+while not (base / "delegate-written").exists(): time.sleep(0.02)
+lock = UpdateLock(path=base / "marker")
+assert lock.acquire(), lock.holder
+(base / "ready").touch()
+while not (base / "go").exists(): time.sleep(0.02)
+lock.release()
+"""
+
+_HANDOFF_OWNER = """
+import os, subprocess, sys, time
+from pathlib import Path
+sys.path.insert(0, sys.argv[1])
+from hermes_cli.update_lock import process_create_time
+base = Path(sys.argv[2])
+marker = base / "marker"
+marker.write_text(f"{os.getpid()}\\n{int(time.time())}\\nct:{process_create_time():.3f}\\n")
+child = subprocess.Popen([sys.executable, sys.argv[3], sys.argv[1], str(base)], start_new_session=True)
+with open(marker, "a") as fh: # the hand-off scripts name their update child right after spawn
+ fh.write(f"delegate:{child.pid} ct:{process_create_time(child.pid):.3f}\\n")
+(base / "delegate-written").write_text(str(child.pid))
+child.wait()
+"""
+
+
+@posix_only
+def test_an_orphaned_delegate_removes_its_killed_owners_marker(tmp_path):
+ """A7 rule 5 / Windows ``orphaned_update``: the hand-off script claims, names its `hermes
+ update` child as delegate, and is killed alone. Pre-A7 the child adopted the claim without
+ writing it, so its exit released nothing: '<dead owner> … delegate:<exited child>' survived
+ (native artifact crash-12db). The delegate's release now removes a claim whose owner died."""
+ owner = _python(tmp_path, _HANDOFF_OWNER, tmp_path, _script(tmp_path, _ORPHAN_UPDATE))
+ try:
+ child = int(_wait_for(tmp_path / "delegate-written", owner))
+ _wait_for(tmp_path / "ready", owner)
+ owner.kill()
+ owner.wait()
+ (tmp_path / "go").touch()
+ end = time.monotonic() + 30
+ while _alive(child) and time.monotonic() < end:
+ time.sleep(0.05)
+ assert not _alive(child)
+ assert not (tmp_path / "marker").exists(), "the orphaned update's exit left its dead claim behind"
+ finally:
+ owner.kill()
+ owner.wait()
+
+
+@posix_only
+def test_owner_release_hands_the_claim_to_a_live_delegate(tmp_path):
+ """A7 rule 5, the other half: the owner's release never deletes the claim a live delegate
+ still runs under; it rewrites it with that delegate as owner (and keeps the run line)."""
+ marker = tmp_path / "marker"
+ delegate = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], stdin=subprocess.DEVNULL)
+ try:
+ lock = UpdateLock(path=marker)
+ assert lock.acquire() and lock.acquired
+ ct = f"{process_create_time(delegate.pid):.3f}"
+ marker.write_bytes(marker.read_bytes() + f"delegate:{delegate.pid} ct:{ct}\nrun:desk-1\n".encode())
+ started = marker.read_text(encoding="utf-8").splitlines()[1]
+ lock.release()
+ assert marker.read_text(encoding="utf-8") == f"{delegate.pid}\n{started}\nct:{ct}\nrun:desk-1\n"
+ finally:
+ delegate.kill()
+ delegate.wait()
+
+
+_GIT_OWNER = """
+import sys
+from pathlib import Path
+sys.path.insert(0, sys.argv[1])
+from hermes_cli.update_lock import UpdateLock
+from hermes_cli.update_cmd import _git_run
+root = Path(sys.argv[2])
+assert UpdateLock(path=root / "owner-marker", install_root=root).acquire()
+_git_run(["git"], ["commit", "-qm", "after"], cwd=root, check=True)
+"""
+
+
+def _git(root: Path, *args: str) -> str:
+ env = {**os.environ, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": os.devnull}
+ return subprocess.check_output(["git", "-C", str(root), *args], text=True, env=env).strip()
+
+
+@posix_only
+def test_git_keeps_checkout_custody_after_its_updater_is_killed(tmp_path):
+ """R2: `_git_run`'s git (and the hook it runs) inherits the checkout lock. Pre-fix the
+ killed updater's lock fell free while its git still committed, and a contender acquired."""
+ root = tmp_path / "checkout"
+ root.mkdir()
+ _git(root, "init", "-q")
+ _git(root, "config", "user.name", "probe")
+ _git(root, "config", "user.email", "[email protected]")
+ (root / "tracked").write_text("before\n")
+ _git(root, "add", "tracked")
+ _git(root, "commit", "-qm", "before")
+ (root / "tracked").write_text("after\n")
+ _git(root, "add", "tracked")
+ hook = root / ".git/hooks/pre-commit"
+ hook.write_text(f"#!{sys.executable}\nimport os, time\nfrom pathlib import Path\nr = Path({str(tmp_path)!r})\n"
+ "(r / 'hook').write_text(str(os.getpid()))\n"
+ "while not (r / 'go').exists(): time.sleep(0.02)\n")
+ hook.chmod(0o700)
+ owner = _python(tmp_path, _GIT_OWNER, root, env={**os.environ, "GIT_CONFIG_NOSYSTEM": "1",
+ "GIT_CONFIG_GLOBAL": os.devnull})
+ contender = UpdateLock(path=tmp_path / "contender-marker", install_root=root)
+ try:
+ hook_pid = int(_wait_for(tmp_path / "hook", owner))
+ owner.kill()
+ owner.wait()
+ assert _alive(hook_pid)
+ assert contender.acquire() is False, "a contender owns the checkout while git still commits"
+ (tmp_path / "go").touch()
+ end = time.monotonic() + 30
+ while not contender.acquire():
+ assert time.monotonic() < end, "the checkout stayed locked after git exited"
+ time.sleep(0.05)
+ finally:
+ (tmp_path / "go").touch()
+ contender.release()
+ owner.kill()
+ owner.wait()
+
+
+_BUILD_OWNER = """
+import os, sys
+from pathlib import Path
+sys.path.insert(0, sys.argv[1])
+from hermes_cli.update_lock import UpdateLock
+from hermes_cli.source_build import run_source_script
+root = Path(sys.argv[2])
+assert UpdateLock(path=root / "owner-marker", install_root=root).acquire()
+run_source_script(root, "build.mjs", env={**os.environ, "PATH": sys.argv[3]}, label="probe build")
+"""
+
+
+@posix_only
+def test_the_source_build_keeps_checkout_custody_after_its_updater_is_killed(tmp_path):
+ """R2: the Node build `run_source_script` starts keeps the lock fd. A real `node` stand-in
+ (an executable on the build's PATH) outlives the killed updater; the checkout stays locked."""
+ root = tmp_path / "checkout"
+ (root / ".git").mkdir(parents=True)
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ node = bin_dir / "node"
+ node.write_text(f"#!{sys.executable}\nimport os, time\nfrom pathlib import Path\nr = Path({str(tmp_path)!r})\n"
+ "(r / 'node').write_text(str(os.getpid()))\n"
+ "while not (r / 'go').exists(): time.sleep(0.02)\n")
+ node.chmod(0o700)
+ owner = _python(tmp_path, _BUILD_OWNER, root, bin_dir)
+ contender = UpdateLock(path=tmp_path / "contender-marker", install_root=root)
+ try:
+ node_pid = int(_wait_for(tmp_path / "node", owner))
+ owner.kill()
+ owner.wait()
+ assert _alive(node_pid)
+ assert contender.acquire() is False, "a contender owns the checkout while the build still writes"
+ finally:
+ (tmp_path / "go").touch()
+ contender.release()
+ owner.kill()
+ owner.wait()
+
+
+_HOLDER = """
+import sys, time
+from pathlib import Path
+sys.path.insert(0, sys.argv[1])
+from hermes_cli.update_lock import UpdateLock
+assert UpdateLock(path=Path(sys.argv[3]), install_root=sys.argv[2]).acquire()
+print("held", flush=True)
+time.sleep(120)
+"""
+
+
+def test_a_completion_from_another_home_never_builds_an_owned_checkout(tmp_path, monkeypatch):
+ """R2 admission: `complete_source_checkout` ACQUIRES the checkout lock. Pre-fix it claimed
+ only its own home's marker and entered the build body beside the owning update."""
+ from hermes_cli import source_completion
+
+ root = tmp_path / "checkout"
+ (root / ".git").mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "other-home"))
+ entered = []
+ monkeypatch.setattr(source_completion, "_complete_locked", lambda *a, **k: entered.append(a))
+ holder = subprocess.Popen([sys.executable, str(_script(tmp_path, _HOLDER)), str(REPO_ROOT), str(root),
+ str(tmp_path / "owner-marker")],
+ stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, text=True, encoding="utf-8")
+ try:
+ assert holder.stdout is not None and holder.stdout.readline().strip() == "held"
+ with pytest.raises(RuntimeError, match="an update is still running"):
+ source_completion.complete_source_checkout(root, desktop=False, assume_yes=True)
+ assert entered == [], "the completion body ran while another update owned the checkout"
+ finally:
+ holder.kill()
+ holder.wait()
+
+
+def test_a_live_legacy_profile_claim_is_honored(tmp_path, monkeypatch):
+ """R11: before the root marker, an update under a named profile claimed
+ ``<root>/profiles/<p>/.hermes-update-in-progress`` (v1) and never took the checkout lock.
+ While such a claim is live, a new update from that root refuses."""
+ root = tmp_path / "root"
+ profile = root / "profiles" / "work"
+ profile.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(profile))
+ legacy = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], stdin=subprocess.DEVNULL)
+ try:
+ (profile / ".hermes-update-in-progress").write_text(f"{legacy.pid}\n{int(time.time())}\n")
+ lock = UpdateLock(path=root / ".hermes-update-in-progress")
+ assert lock.acquire() is False
+ assert lock.holder is not None and lock.holder.pid == legacy.pid
+ assert not (root / ".hermes-update-in-progress").exists()
+ finally:
+ legacy.kill()
+ legacy.wait()
+ # Dead: no longer honored (and left for the old updater that wrote it).
+ lock = UpdateLock(path=root / ".hermes-update-in-progress")
+ assert lock.acquire() is True
+ lock.release()
diff --git a/tests/hermes_cli/test_update_marker_corpus.py b/tests/hermes_cli/test_update_marker_corpus.py
new file mode 100644
index 00000000000..7f4c36f0a85
--- /dev/null
+++ b/tests/hermes_cli/test_update_marker_corpus.py
@@ -0,0 +1,49 @@
+"""The shared update-marker corpus, run against the Python reader/releaser (A7 rule 7).
+
+``tests/fixtures/update_marker_corpus.json`` is the one table every marker implementation
+(Python, Rust ``marker.rs``, Electron, the Bash/PowerShell hand-off scripts) must agree with.
+The process table and clock are injected; the bytes, parser and verdict code are production.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import update_lock
+
+CORPUS = json.loads((Path(__file__).resolve().parents[1] / "fixtures/update_marker_corpus.json")
+ .read_text(encoding="utf-8"))
+
+
+def _world(case: dict, pid_key: str, ct_key: str) -> update_lock._World:
+ me = (case.get(pid_key, CORPUS["our_pid"]), case.get(ct_key, CORPUS["our_ct"]))
+ table = {int(pid): ct for pid, ct in case["live"].items()}
+ table[me[0]] = me[1]
+ return update_lock._World(pid=me[0], ct=me[1], now=CORPUS["now"], alive=lambda pid: pid in table,
+ ct_of=lambda pid: table.get(pid))
+
+
+def test_corpus_constants_are_the_production_ones():
+ assert CORPUS["own_ct_epsilon"] == update_lock._OWN_CREATE_TIME_EPSILON
+ assert CORPUS["ct_tolerance"] == update_lock.CREATE_TIME_TOLERANCE_SECONDS
+ assert CORPUS["v1_max_age"] == update_lock.UPDATE_MARKER_MAX_AGE_SECONDS
+
+
[email protected]("case", CORPUS["judge"], ids=[c["name"] for c in CORPUS["judge"]])
+def test_judge(case):
+ verdict, owner, run = update_lock.judge_marker(case["text"].encode("utf-8"), _world(case, "our_pid", "our_ct"))
+ assert {"verdict": verdict, "owner": owner, "run": run} == case["expect"]
+
+
[email protected]("case", CORPUS["release"], ids=[c["name"] for c in CORPUS["release"]])
+def test_release(case):
+ action, body = update_lock._release_decision(case["text"].encode("utf-8"),
+ _world(case, "releaser_pid", "releaser_ct"))
+ expected = case["expect"]
+ assert action == expected["action"]
+ if action == "rewrite":
+ assert body is not None
+ assert body.decode("utf-8") == expected["text"]