From d78cf67e210be0be9165dfb1405dc3325798cbc3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 17:53:23 -0800 Subject: [PATCH 1/2] suite-account: the accounts lock timeout applies to one hold, not the whole wait `with_lock` gave up after waiting 5 s in total, however many times the lock changed hands meanwhile. A process signing in many accounts takes the lock in a quick run of short holds, and a waiter polling every 20 ms can miss every gap. Under load, `concurrent_sign_ins_from_two_processes_lose_no_rows` failed with "timed out waiting for the accounts lock". Each hold now sets the lock file's length to the next value in 1 to 64. A waiter that sees the length change starts its 5 s over, so it still gives up on one hold that lasts past 5 s. Unit tests drive the wait with their own times instead of sleeping. --- crates/suite-account/src/lock.rs | 81 ++++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 5 deletions(-) diff --git a/crates/suite-account/src/lock.rs b/crates/suite-account/src/lock.rs index 6a95e6bd2a..a76238a14a 100644 --- a/crates/suite-account/src/lock.rs +++ b/crates/suite-account/src/lock.rs @@ -21,11 +21,42 @@ use std::time::{Duration, Instant}; use crate::error::Error; -/// How long to wait for another process holding the lock before giving up. Long enough that a -/// normal read-change-write of a few-hundred-byte file never times out under load; short enough -/// that a process holding the lock across a crash does not wedge every other app indefinitely. +/// How long one hold of the lock by another process may last before a waiter gives up. Long enough +/// that a normal read-change-write of a few-hundred-byte file never times out under load; short +/// enough that a process stuck holding the lock does not wedge every other app indefinitely. The +/// wait starts again whenever another hold begins, so a waiter behind a long run of short holds +/// (another app signing in many accounts) keeps waiting. const LOCK_TIMEOUT: Duration = Duration::from_secs(5); const POLL_INTERVAL: Duration = Duration::from_millis(20); +/// Every hold sets the lock file's length to the next value in `1..=HOLDS`, so a waiter can see +/// that the lock changed hands between two polls. +const HOLDS: u64 = 64; + +/// A waiter's view of the holds it has waited through. +struct Wait { + since: Instant, + hold: Option, +} + +impl Wait { + fn new(now: Instant, hold: Option) -> Self { + Wait { since: now, hold } + } + + /// Whether to give up, seeing `hold` (the lock file's length, when it could be read) at `now`. + fn expired(&mut self, now: Instant, hold: Option) -> bool { + if hold.is_some() && hold != self.hold { + self.hold = hold; + self.since = now; + return false; + } + now.saturating_duration_since(self.since) > LOCK_TIMEOUT + } +} + +fn hold_mark(lock: &File) -> Option { + lock.metadata().ok().map(|m| m.len()) +} fn lock_path(path: &Path) -> PathBuf { let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts.json"); @@ -51,12 +82,12 @@ pub(crate) fn with_lock(path: &Path, f: impl FnOnce() -> Result) -> let lock = open_lock_file(path).map_err(|e| Error::Io(format!("couldn't open the lock beside {} ({e})", path.display())))?; #[cfg(windows)] let _prepared = crate::accounts::prepare(path); - let start = Instant::now(); + let mut wait = Wait::new(Instant::now(), hold_mark(&lock)); loop { match lock.try_lock() { Ok(()) => break, Err(fs::TryLockError::WouldBlock) => { - if start.elapsed() > LOCK_TIMEOUT { + if wait.expired(Instant::now(), hold_mark(&lock)) { return Err(Error::Io(format!("timed out waiting for the accounts lock on {}", path.display()))); } std::thread::sleep(POLL_INTERVAL); @@ -66,6 +97,10 @@ pub(crate) fn with_lock(path: &Path, f: impl FnOnce() -> Result) -> } } } + // A failure here only costs waiters the restart of their timeout for this hold. + if let Some(n) = hold_mark(&lock) { + let _ = lock.set_len(n % HOLDS + 1); + } let result = f(); let _ = lock.unlock(); result @@ -88,6 +123,42 @@ mod tests { assert!(with_lock(&path, || Ok(true)).unwrap(), "the lock is free again once `with_lock` returns"); } + #[test] + fn a_waiter_behind_many_short_holds_keeps_waiting() { + let t0 = Instant::now(); + let step = Duration::from_secs(1); + let mut wait = Wait::new(t0, Some(1)); + // Sixty seconds of holds that each last one second: far past `LOCK_TIMEOUT` in all. + for i in 1..=60u32 { + let hold = Some(u64::from(i) % HOLDS + 1); + assert!(!wait.expired(t0 + step * i, hold), "gave up after {i} s behind holds that kept changing"); + } + } + + #[test] + fn a_waiter_gives_up_on_one_hold_that_lasts_past_the_timeout() { + let t0 = Instant::now(); + let mut wait = Wait::new(t0, Some(3)); + assert!(!wait.expired(t0 + LOCK_TIMEOUT, Some(3))); + assert!(wait.expired(t0 + LOCK_TIMEOUT + Duration::from_millis(1), Some(3))); + // Without a readable length the timeout counts from the start of the wait. + let mut blind = Wait::new(t0, None); + assert!(!blind.expired(t0 + LOCK_TIMEOUT, None)); + assert!(blind.expired(t0 + LOCK_TIMEOUT + Duration::from_millis(1), None)); + } + + #[test] + fn each_hold_marks_the_lock_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("accounts.json"); + let mut seen = Vec::new(); + for _ in 0..3 { + with_lock(&path, || Ok(())).unwrap(); + seen.push(fs::metadata(lock_path(&path)).unwrap().len()); + } + assert_eq!(seen, [1, 2, 3]); + } + #[test] fn an_error_from_the_closure_still_releases_the_lock() { let dir = tempfile::tempdir().unwrap(); From 31d9c5cd3deb0f7ac84c9c172ef39c6ffb987bde Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 18:12:12 -0800 Subject: [PATCH 2/2] suite-account: a full cycle of lock-file lengths no longer reads as one long hold The lock file's length repeats every 64 holds, so a waiter that missed a whole cycle between two polls saw the same mark and could time out behind holds that each lasted far less than the timeout. The mark now also carries the lock file's modification time, which each hold moves when it sets the new length. --- crates/suite-account/src/lock.rs | 60 ++++++++++++++++++++++++-------- 1 file changed, 45 insertions(+), 15 deletions(-) diff --git a/crates/suite-account/src/lock.rs b/crates/suite-account/src/lock.rs index a76238a14a..74906014b6 100644 --- a/crates/suite-account/src/lock.rs +++ b/crates/suite-account/src/lock.rs @@ -17,7 +17,7 @@ use std::fs::{self, File, OpenOptions}; use std::io; use std::path::{Path, PathBuf}; -use std::time::{Duration, Instant}; +use std::time::{Duration, Instant, SystemTime}; use crate::error::Error; @@ -28,23 +28,28 @@ use crate::error::Error; /// (another app signing in many accounts) keeps waiting. const LOCK_TIMEOUT: Duration = Duration::from_secs(5); const POLL_INTERVAL: Duration = Duration::from_millis(20); -/// Every hold sets the lock file's length to the next value in `1..=HOLDS`, so a waiter can see -/// that the lock changed hands between two polls. +/// Every hold sets the lock file's length to the next value in `1..=HOLDS`, which also moves its +/// modification time, so a waiter can see that the lock changed hands between two polls. The length +/// repeats every `HOLDS` holds; the modification time tells apart two holds that left the same length. const HOLDS: u64 = 64; +/// What a waiter reads from the lock file: its length and, when the file system reports one, its +/// modification time. +type HoldMark = (u64, Option); + /// A waiter's view of the holds it has waited through. struct Wait { since: Instant, - hold: Option, + hold: Option, } impl Wait { - fn new(now: Instant, hold: Option) -> Self { + fn new(now: Instant, hold: Option) -> Self { Wait { since: now, hold } } - /// Whether to give up, seeing `hold` (the lock file's length, when it could be read) at `now`. - fn expired(&mut self, now: Instant, hold: Option) -> bool { + /// Whether to give up, seeing `hold` (the lock file's mark, when it could be read) at `now`. + fn expired(&mut self, now: Instant, hold: Option) -> bool { if hold.is_some() && hold != self.hold { self.hold = hold; self.since = now; @@ -54,8 +59,8 @@ impl Wait { } } -fn hold_mark(lock: &File) -> Option { - lock.metadata().ok().map(|m| m.len()) +fn hold_mark(lock: &File) -> Option { + lock.metadata().ok().map(|m| (m.len(), m.modified().ok())) } fn lock_path(path: &Path) -> PathBuf { @@ -98,7 +103,7 @@ pub(crate) fn with_lock(path: &Path, f: impl FnOnce() -> Result) -> } } // A failure here only costs waiters the restart of their timeout for this hold. - if let Some(n) = hold_mark(&lock) { + if let Some((n, _)) = hold_mark(&lock) { let _ = lock.set_len(n % HOLDS + 1); } let result = f(); @@ -127,20 +132,45 @@ mod tests { fn a_waiter_behind_many_short_holds_keeps_waiting() { let t0 = Instant::now(); let step = Duration::from_secs(1); - let mut wait = Wait::new(t0, Some(1)); + let mut wait = Wait::new(t0, Some((1, None))); // Sixty seconds of holds that each last one second: far past `LOCK_TIMEOUT` in all. for i in 1..=60u32 { - let hold = Some(u64::from(i) % HOLDS + 1); + let hold = Some((u64::from(i) % HOLDS + 1, None)); assert!(!wait.expired(t0 + step * i, hold), "gave up after {i} s behind holds that kept changing"); } } + #[test] + fn a_waiter_that_misses_a_whole_cycle_of_lengths_keeps_waiting() { + let t0 = Instant::now(); + let first = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000); + let mut wait = Wait::new(t0, Some((1, Some(first)))); + // `HOLDS` holds of 80 ms each went by between two polls and the last one left the length at + // 1 again; only the modification time shows that the lock changed hands. + let later = first + Duration::from_millis(80) * 64; + assert!(!wait.expired(t0 + Duration::from_millis(5_070), Some((1, Some(later))))); + } + + #[test] + fn the_mark_tells_apart_two_holds_that_leave_the_same_length() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("accounts.json"); + with_lock(&path, || Ok(())).unwrap(); + let lock = open_lock_file(&path).unwrap(); + let before = hold_mark(&lock).unwrap(); + let Some(modified) = before.1 else { return }; + lock.set_modified(modified + Duration::from_secs(1)).unwrap(); + let after = hold_mark(&lock).unwrap(); + assert_eq!(before.0, after.0); + assert_ne!(before, after, "a new hold that leaves the same length must still change the mark"); + } + #[test] fn a_waiter_gives_up_on_one_hold_that_lasts_past_the_timeout() { let t0 = Instant::now(); - let mut wait = Wait::new(t0, Some(3)); - assert!(!wait.expired(t0 + LOCK_TIMEOUT, Some(3))); - assert!(wait.expired(t0 + LOCK_TIMEOUT + Duration::from_millis(1), Some(3))); + let mut wait = Wait::new(t0, Some((3, None))); + assert!(!wait.expired(t0 + LOCK_TIMEOUT, Some((3, None)))); + assert!(wait.expired(t0 + LOCK_TIMEOUT + Duration::from_millis(1), Some((3, None)))); // Without a readable length the timeout counts from the start of the wait. let mut blind = Wait::new(t0, None); assert!(!blind.expired(t0 + LOCK_TIMEOUT, None));