1use std::path::{Path, PathBuf};
53use std::sync::Arc;
54
55use serde::{Deserialize, Serialize};
56use thiserror::Error;
57
58use super::atomic::write_atomic;
59
60pub const RENEW_INTERVAL_MS: u64 = 5_000;
65
66pub const LEASE_TTL_MS: u64 = RENEW_INTERVAL_MS * 3;
69
70#[derive(Debug, Error)]
71pub enum LeaseError {
72 #[error("session '{instance_id}' is already owned by another AgentMux process (boot {owner_boot_id}, renewed {age_ms}ms ago)")]
73 HeldByOther {
74 instance_id: String,
75 owner_boot_id: String,
76 age_ms: u64,
77 holder: Option<LeaseHolder>,
80 },
81 #[error("io: {0}")]
82 Io(#[from] std::io::Error),
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct LeaseHolder {
90 pub owner_boot_id: String,
91 pub block_id: String,
92 pub pid: u32,
93 pub channel: String,
94 pub version: String,
95 pub hostname: String,
96 pub epoch: u64,
97 pub acquired_at_ms: i64,
98 pub renewed_at_ms: i64,
99}
100
101#[derive(Debug, Clone, Default)]
105pub struct ClaimantInfo {
106 pub channel: String,
107 pub version: String,
108}
109
110#[derive(Debug, Serialize, Deserialize)]
111struct LeaseFile {
112 instance_id: String,
113 owner_boot_id: String,
114 block_id: String,
115 session_id: Option<String>,
120 pid: u32,
121 acquired_at_ms: i64,
122 renewed_at_ms: i64,
123 #[serde(default)]
128 epoch: u64,
129 #[serde(default)]
130 hostname: String,
131 #[serde(default)]
134 pid_start_s: u64,
135 #[serde(default)]
136 channel: String,
137 #[serde(default)]
138 version: String,
139 #[serde(default)]
146 claim_id: String,
147}
148
149impl LeaseFile {
150 fn holder(&self) -> LeaseHolder {
151 LeaseHolder {
152 owner_boot_id: self.owner_boot_id.clone(),
153 block_id: self.block_id.clone(),
154 pid: self.pid,
155 channel: self.channel.clone(),
156 version: self.version.clone(),
157 hostname: self.hostname.clone(),
158 epoch: self.epoch,
159 acquired_at_ms: self.acquired_at_ms,
160 renewed_at_ms: self.renewed_at_ms,
161 }
162 }
163}
164
165#[derive(Debug, Clone)]
169pub struct Lease {
170 instance_id: String,
171 owner_boot_id: Arc<str>,
172 block_id: String,
173 claim_id: String,
174 epoch: u64,
175 path: PathBuf,
176}
177
178impl Lease {
179 pub fn instance_id(&self) -> &str {
180 &self.instance_id
181 }
182
183 pub fn owner_boot_id(&self) -> &str {
185 &self.owner_boot_id
186 }
187
188 pub fn epoch(&self) -> u64 {
191 self.epoch
192 }
193}
194
195use agentmux_common::time::now_ms;
196
197enum OnDisk {
199 Missing,
200 Unreadable { age_ms: u64 },
202 Valid(LeaseFile),
203}
204
205pub struct LeaseStore {
206 root: PathBuf,
207 ttl_ms: u64,
208}
209
210impl LeaseStore {
211 pub fn open(registry_root: &Path) -> std::io::Result<Self> {
213 let root = registry_root.join("leases");
214 std::fs::create_dir_all(&root)?;
215 Ok(Self {
216 root,
217 ttl_ms: LEASE_TTL_MS,
218 })
219 }
220
221 #[cfg(test)]
224 pub(crate) fn open_with_ttl(registry_root: &Path, ttl_ms: u64) -> std::io::Result<Self> {
225 let mut s = Self::open(registry_root)?;
226 s.ttl_ms = ttl_ms;
227 Ok(s)
228 }
229
230 fn content_path(&self, instance_id: &str) -> PathBuf {
231 self.root.join(format!("{instance_id}.lease.json"))
232 }
233
234 fn lock_path(&self, instance_id: &str) -> PathBuf {
235 self.root.join(format!("{instance_id}.lock"))
236 }
237
238 fn epoch_path(&self, instance_id: &str) -> PathBuf {
239 self.root.join(format!("{instance_id}.epoch"))
240 }
241
242 fn read(path: &Path) -> std::io::Result<OnDisk> {
243 let bytes = match std::fs::read(path) {
244 Ok(b) => b,
245 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(OnDisk::Missing),
246 Err(e) => return Err(e),
247 };
248 match serde_json::from_slice::<LeaseFile>(&bytes) {
249 Ok(file) => Ok(OnDisk::Valid(file)),
250 Err(_) => {
251 let age_ms = std::fs::metadata(path)
252 .and_then(|m| m.modified())
253 .ok()
254 .and_then(|t| t.elapsed().ok())
255 .map(|d| d.as_millis() as u64)
256 .unwrap_or(0);
259 Ok(OnDisk::Unreadable { age_ms })
260 }
261 }
262 }
263
264 fn next_epoch(&self, instance_id: &str, floor: u64) -> std::io::Result<u64> {
269 let path = self.epoch_path(instance_id);
270 let stored = std::fs::read_to_string(&path)
271 .ok()
272 .and_then(|s| s.trim().parse::<u64>().ok())
273 .unwrap_or(0);
274 let next = stored.max(floor) + 1;
275 write_atomic(&path, format!("{next}\n").as_bytes())?;
276 Ok(next)
277 }
278
279 pub fn claim(
282 &self,
283 instance_id: &str,
284 boot_id: &Arc<str>,
285 block_id: &str,
286 session_id_hint: Option<&str>,
287 ) -> Result<Lease, LeaseError> {
288 self.claim_as(instance_id, boot_id, block_id, session_id_hint, &ClaimantInfo::default())
289 }
290
291 pub fn claim_as(
310 &self,
311 instance_id: &str,
312 boot_id: &Arc<str>,
313 block_id: &str,
314 session_id_hint: Option<&str>,
315 info: &ClaimantInfo,
316 ) -> Result<Lease, LeaseError> {
317 let _cs = CriticalSection::enter(&self.lock_path(instance_id))?;
318 let path = self.content_path(instance_id);
319
320 let (kept_epoch, floor) = match Self::read(&path)? {
321 OnDisk::Missing => (None, 0),
322 OnDisk::Unreadable { age_ms } => {
323 if age_ms <= self.ttl_ms {
324 return Err(LeaseError::HeldByOther {
325 instance_id: instance_id.to_string(),
326 owner_boot_id: "<unreadable lease file>".to_string(),
327 age_ms,
328 holder: None,
329 });
330 }
331 tracing::warn!(
332 instance_id,
333 age_ms,
334 "lease: unreadable lease file not rewritten for a full TTL — reclaiming"
335 );
336 (None, 0)
337 }
338 OnDisk::Valid(existing) => {
339 let age_ms = (now_ms() - existing.renewed_at_ms).max(0) as u64;
340 if existing.owner_boot_id == boot_id.as_ref() && same_block(&existing, block_id) {
341 (Some(existing.epoch), existing.epoch)
345 } else if existing.owner_boot_id == boot_id.as_ref() {
346 if age_ms <= self.ttl_ms {
348 return Err(LeaseError::HeldByOther {
349 instance_id: instance_id.to_string(),
350 owner_boot_id: existing.owner_boot_id.clone(),
351 age_ms,
352 holder: Some(existing.holder()),
353 });
354 }
355 (None, existing.epoch)
356 } else {
357 if age_ms <= self.ttl_ms && !holder_is_dead(&existing) {
358 return Err(LeaseError::HeldByOther {
359 instance_id: instance_id.to_string(),
360 owner_boot_id: existing.owner_boot_id.clone(),
361 age_ms,
362 holder: Some(existing.holder()),
363 });
364 }
365 (None, existing.epoch)
367 }
368 }
369 };
370
371 let epoch = match kept_epoch {
372 Some(e) if e > 0 => e,
373 _ => self.next_epoch(instance_id, floor)?,
374 };
375 let claim_id = uuid::Uuid::new_v4().to_string();
376 let bytes = lease_bytes(instance_id, boot_id, block_id, session_id_hint, epoch, &claim_id, info)?;
377 write_atomic(&path, &bytes)?;
378 Ok(Lease {
379 instance_id: instance_id.to_string(),
380 owner_boot_id: Arc::clone(boot_id),
381 block_id: block_id.to_string(),
382 claim_id,
383 epoch,
384 path,
385 })
386 }
387
388 pub fn renew(&self, lease: &Lease) -> Result<(), LeaseError> {
395 let _cs = CriticalSection::enter(&self.lock_path(&lease.instance_id))?;
396 let existing = self.owned_file(lease)?;
397 let renewed = LeaseFile {
398 renewed_at_ms: now_ms(),
399 ..existing
400 };
401 let mut bytes = serde_json::to_vec_pretty(&renewed).map_err(std::io::Error::from)?;
402 bytes.push(b'\n');
403 write_atomic(&lease.path, &bytes)?;
404 Ok(())
405 }
406
407 pub fn verify(&self, lease: &Lease) -> Result<(), LeaseError> {
411 let _cs = CriticalSection::enter(&self.lock_path(&lease.instance_id))?;
412 self.owned_file(lease).map(|_| ())
413 }
414
415 fn owned_file(&self, lease: &Lease) -> Result<LeaseFile, LeaseError> {
418 let existing = match Self::read(&lease.path)? {
419 OnDisk::Valid(f) => f,
420 OnDisk::Missing | OnDisk::Unreadable { .. } => {
423 return Err(LeaseError::HeldByOther {
424 instance_id: lease.instance_id.clone(),
425 owner_boot_id: "<unknown — lease file missing or unreadable>".to_string(),
426 age_ms: 0,
427 holder: None,
428 });
429 }
430 };
431 if !is_this_claim(&existing, lease) {
435 let age_ms = (now_ms() - existing.renewed_at_ms).max(0) as u64;
436 return Err(LeaseError::HeldByOther {
437 instance_id: lease.instance_id.clone(),
438 owner_boot_id: existing.owner_boot_id.clone(),
439 age_ms,
440 holder: Some(existing.holder()),
441 });
442 }
443 Ok(existing)
444 }
445
446 pub fn release(&self, lease: &Lease) -> Result<(), LeaseError> {
453 let _cs = CriticalSection::enter(&self.lock_path(&lease.instance_id))?;
454 let existing = match Self::read(&lease.path)? {
455 OnDisk::Valid(f) => f,
456 OnDisk::Missing | OnDisk::Unreadable { .. } => return Ok(()),
457 };
458 if !is_this_claim(&existing, lease) {
459 return Ok(());
460 }
461 match std::fs::remove_file(&lease.path) {
462 Ok(()) => Ok(()),
463 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
464 Err(e) => Err(e.into()),
465 }
466 }
467
468 pub fn live_holder_other_than(
475 &self,
476 instance_id: &str,
477 own_boot_id: &str,
478 ) -> std::io::Result<Option<LeaseHolder>> {
479 let _cs = CriticalSection::enter(&self.lock_path(instance_id))?;
480 Ok(match Self::read(&self.content_path(instance_id))? {
481 OnDisk::Missing => None,
482 OnDisk::Unreadable { age_ms } => (age_ms <= self.ttl_ms).then(|| LeaseHolder {
483 owner_boot_id: "<unreadable lease file>".to_string(),
484 block_id: String::new(),
485 pid: 0,
486 channel: String::new(),
487 version: String::new(),
488 hostname: String::new(),
489 epoch: 0,
490 acquired_at_ms: 0,
491 renewed_at_ms: 0,
492 }),
493 OnDisk::Valid(f) => {
494 let age_ms = (now_ms() - f.renewed_at_ms).max(0) as u64;
495 (f.owner_boot_id != own_boot_id && age_ms <= self.ttl_ms && !holder_is_dead(&f))
496 .then(|| f.holder())
497 }
498 })
499 }
500}
501
502impl LeaseStore {
503 pub fn live_holder_block(&self, instance_id: &str) -> std::io::Result<Option<String>> {
506 let _cs = CriticalSection::enter(&self.lock_path(instance_id))?;
507 Ok(match Self::read(&self.content_path(instance_id))? {
508 OnDisk::Valid(f) => {
509 let age_ms = (now_ms() - f.renewed_at_ms).max(0) as u64;
510 (age_ms <= self.ttl_ms && !holder_is_dead(&f) && !f.block_id.is_empty()).then_some(f.block_id)
511 }
512 OnDisk::Missing | OnDisk::Unreadable { .. } => None,
513 })
514 }
515}
516
517fn same_block(file: &LeaseFile, block_id: &str) -> bool {
520 file.block_id.is_empty() || file.block_id == block_id
521}
522
523fn is_this_claim(file: &LeaseFile, lease: &Lease) -> bool {
526 file.owner_boot_id == lease.owner_boot_id.as_ref()
527 && same_block(file, &lease.block_id)
528 && (file.claim_id.is_empty() || file.claim_id == lease.claim_id)
529}
530
531fn this_host() -> String {
534 whoami::fallible::hostname()
535 .unwrap_or_default()
536 .trim()
537 .to_lowercase()
538}
539
540fn process_start_s(pid: u32) -> Option<u64> {
543 let target = sysinfo::Pid::from(pid as usize);
544 let mut sys = sysinfo::System::new();
545 sys.refresh_processes_specifics(
546 sysinfo::ProcessesToUpdate::Some(&[target]),
547 true,
548 sysinfo::ProcessRefreshKind::nothing(),
549 );
550 sys.process(target).map(|p| p.start_time())
551}
552
553fn holder_is_dead(file: &LeaseFile) -> bool {
559 if file.hostname.is_empty() || file.pid == 0 || file.hostname != this_host() {
560 return false;
561 }
562 match process_start_s(file.pid) {
563 None => true,
564 Some(start) => file.pid_start_s != 0 && start != file.pid_start_s,
565 }
566}
567
568fn lease_bytes(
569 instance_id: &str,
570 boot_id: &Arc<str>,
571 block_id: &str,
572 session_id_hint: Option<&str>,
573 epoch: u64,
574 claim_id: &str,
575 info: &ClaimantInfo,
576) -> Result<Vec<u8>, std::io::Error> {
577 let now = now_ms();
578 let pid = std::process::id();
579 let file = LeaseFile {
580 instance_id: instance_id.to_string(),
581 owner_boot_id: boot_id.to_string(),
582 block_id: block_id.to_string(),
583 session_id: session_id_hint.map(str::to_string),
584 pid,
585 acquired_at_ms: now,
586 renewed_at_ms: now,
587 epoch,
588 hostname: this_host(),
589 pid_start_s: process_start_s(pid).unwrap_or(0),
590 channel: info.channel.clone(),
591 version: info.version.clone(),
592 claim_id: claim_id.to_string(),
593 };
594 let mut bytes = serde_json::to_vec_pretty(&file).map_err(std::io::Error::from)?;
595 bytes.push(b'\n');
596 Ok(bytes)
597}
598
599struct CriticalSection {
605 _file: std::fs::File,
606}
607
608impl CriticalSection {
609 fn enter(lock_path: &Path) -> std::io::Result<Self> {
623 let file = std::fs::OpenOptions::new()
624 .create(true)
625 .write(true)
626 .open(lock_path)?;
627 lock_exclusive(&file)?;
628 Ok(Self { _file: file })
629 }
630}
631
632#[cfg(unix)]
633pub(crate) fn lock_exclusive(file: &std::fs::File) -> std::io::Result<()> {
634 use std::os::unix::io::AsRawFd;
635 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {
637 return Err(std::io::Error::last_os_error());
638 }
639 Ok(())
640}
641
642#[cfg(windows)]
643pub(crate) fn lock_exclusive(file: &std::fs::File) -> std::io::Result<()> {
644 use std::os::windows::io::AsRawHandle;
645 use windows_sys::Win32::Storage::FileSystem::{LockFileEx, LOCKFILE_EXCLUSIVE_LOCK};
646 use windows_sys::Win32::System::IO::OVERLAPPED;
647
648 let handle = file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE;
649 let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
654 let ok = unsafe {
656 LockFileEx(handle, LOCKFILE_EXCLUSIVE_LOCK, 0, u32::MAX, u32::MAX, &mut overlapped)
657 };
658 if ok == 0 {
659 return Err(std::io::Error::last_os_error());
660 }
661 Ok(())
662}
663
664#[cfg(unix)]
668pub(crate) fn try_lock_exclusive(file: &std::fs::File) -> std::io::Result<bool> {
669 use std::os::unix::io::AsRawFd;
670 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
671 return Ok(true);
672 }
673 let err = std::io::Error::last_os_error();
674 if err.kind() == std::io::ErrorKind::WouldBlock {
675 Ok(false)
676 } else {
677 Err(err)
678 }
679}
680
681#[cfg(unix)]
687pub(crate) fn try_lock_exclusive_range(file: &std::fs::File, _offset: u64, _len: u32) -> std::io::Result<bool> {
688 try_lock_exclusive(file)
689}
690
691#[cfg(windows)]
692pub(crate) fn try_lock_exclusive_range(file: &std::fs::File, offset: u64, len: u32) -> std::io::Result<bool> {
693 use std::os::windows::io::AsRawHandle;
694 use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION;
695 use windows_sys::Win32::Storage::FileSystem::{LockFileEx, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY};
696 use windows_sys::Win32::System::IO::OVERLAPPED;
697
698 let handle = file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE;
699 let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
700 overlapped.Anonymous.Anonymous.Offset = (offset & 0xffff_ffff) as u32;
701 overlapped.Anonymous.Anonymous.OffsetHigh = (offset >> 32) as u32;
702 let ok = unsafe {
703 LockFileEx(
704 handle,
705 LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
706 0,
707 len,
708 0,
709 &mut overlapped,
710 )
711 };
712 if ok != 0 {
713 return Ok(true);
714 }
715 let err = std::io::Error::last_os_error();
716 if err.raw_os_error() == Some(ERROR_LOCK_VIOLATION as i32) {
717 Ok(false)
718 } else {
719 Err(err)
720 }
721}
722
723#[cfg(windows)]
724pub(crate) fn try_lock_exclusive(file: &std::fs::File) -> std::io::Result<bool> {
725 use std::os::windows::io::AsRawHandle;
726 use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION;
727 use windows_sys::Win32::Storage::FileSystem::{LockFileEx, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY};
728 use windows_sys::Win32::System::IO::OVERLAPPED;
729
730 let handle = file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE;
731 let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
732 let ok = unsafe {
733 LockFileEx(
734 handle,
735 LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
736 0,
737 u32::MAX,
738 u32::MAX,
739 &mut overlapped,
740 )
741 };
742 if ok != 0 {
743 return Ok(true);
744 }
745 let err = std::io::Error::last_os_error();
746 if err.raw_os_error() == Some(ERROR_LOCK_VIOLATION as i32) {
747 Ok(false)
748 } else {
749 Err(err)
750 }
751}
752
753#[cfg(test)]
754mod tests {
755 use super::*;
756
757 fn store(ttl_ms: u64) -> (tempfile::TempDir, LeaseStore) {
758 let tmp = tempfile::tempdir().unwrap();
759 let s = LeaseStore::open_with_ttl(tmp.path(), ttl_ms).unwrap();
760 (tmp, s)
761 }
762
763 fn boot(id: &str) -> Arc<str> {
764 Arc::from(id)
765 }
766
767 fn lease_path(tmp: &tempfile::TempDir, id: &str) -> PathBuf {
768 tmp.path().join("leases").join(format!("{id}.lease.json"))
769 }
770
771 fn on_disk(tmp: &tempfile::TempDir, id: &str) -> LeaseFile {
772 serde_json::from_slice(&std::fs::read(lease_path(tmp, id)).unwrap()).unwrap()
773 }
774
775 fn set_holder_process(tmp: &tempfile::TempDir, id: &str, pid: u32, start_s: u64) {
778 let mut f = on_disk(tmp, id);
779 f.pid = pid;
780 f.pid_start_s = start_s;
781 std::fs::write(lease_path(tmp, id), serde_json::to_vec(&f).unwrap()).unwrap();
782 }
783
784 fn exited_pid() -> u32 {
788 const NO_SUCH_PID: u32 = 4_000_000_000;
789 assert!(process_start_s(NO_SUCH_PID).is_none(), "pid {NO_SUCH_PID} unexpectedly running");
790 NO_SUCH_PID
791 }
792
793 #[test]
794 fn claim_succeeds_when_no_existing_lease() {
795 let (_tmp, s) = store(60_000);
796 let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
797 assert_eq!(lease.instance_id(), "agent-1");
798 }
799
800 #[test]
801 fn claim_fails_when_held_by_other_and_fresh() {
802 let (_tmp, s) = store(60_000);
803 s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
804 let err = s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap_err();
805 match err {
806 LeaseError::HeldByOther { owner_boot_id, holder, .. } => {
807 assert_eq!(owner_boot_id, "boot-a");
808 let holder = holder.expect("a readable lease names its holder");
809 assert_eq!(holder.block_id, "block-1");
810 assert_eq!(holder.pid, std::process::id());
811 }
812 other => panic!("expected HeldByOther, got {other:?}"),
813 }
814 }
815
816 #[test]
817 fn claim_is_idempotent_for_same_owner() {
818 let (_tmp, s) = store(60_000);
819 let first = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
820 let second = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
821 assert_eq!(first.epoch(), second.epoch(), "a same-owner re-claim is not an ownership change");
822 }
823
824 #[test]
825 fn claim_reclaims_after_ttl_expiry() {
826 let (_tmp, s) = store(50);
830 s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
831 std::thread::sleep(std::time::Duration::from_millis(1_000));
832 let reclaimed = s.claim("agent-1", &boot("boot-b"), "block-2", None);
833 assert!(reclaimed.is_ok(), "expected expired lease to be reclaimable, got {reclaimed:?}");
834 }
835
836 #[test]
838 fn a_fresh_unreadable_lease_is_held_not_evicted() {
839 let (tmp, s) = store(60_000);
840 let path = lease_path(&tmp, "agent-1");
841 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
842 std::fs::write(&path, b"not json").unwrap();
843 let err = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap_err();
844 assert!(matches!(err, LeaseError::HeldByOther { holder: None, .. }), "got {err:?}");
845 assert!(s.live_holder_other_than("agent-1", "boot-a").unwrap().is_some());
846 }
847
848 #[test]
849 fn an_unreadable_lease_nobody_rewrote_for_a_ttl_is_reclaimed() {
850 let (tmp, s) = store(50);
851 let path = lease_path(&tmp, "agent-1");
852 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
853 std::fs::write(&path, b"not json").unwrap();
854 std::thread::sleep(std::time::Duration::from_millis(1_000));
855 let claimed = s.claim("agent-1", &boot("boot-a"), "block-1", None);
856 assert!(claimed.is_ok(), "expected a stale unreadable lease to be reclaimable, got {claimed:?}");
857 }
858
859 #[test]
862 fn a_lease_in_the_old_format_is_still_honoured() {
863 let (tmp, s) = store(60_000);
864 let path = lease_path(&tmp, "agent-1");
865 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
866 let old = serde_json::json!({
867 "instance_id": "agent-1", "owner_boot_id": "boot-old", "block_id": "b",
868 "session_id": null, "pid": 1, "acquired_at_ms": now_ms(), "renewed_at_ms": now_ms(),
869 });
870 std::fs::write(&path, serde_json::to_vec(&old).unwrap()).unwrap();
871 let err = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap_err();
872 match err {
873 LeaseError::HeldByOther { owner_boot_id, .. } => assert_eq!(owner_boot_id, "boot-old"),
874 other => panic!("expected HeldByOther, got {other:?}"),
875 }
876 }
877
878 #[test]
881 fn epochs_strictly_increase_across_release_and_reclaim() {
882 let (_tmp, s) = store(60_000);
883 let a = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
884 s.release(&a).unwrap();
885 let b = s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap();
886 s.release(&b).unwrap();
887 let c = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
888 assert!(a.epoch() >= 1);
889 assert!(b.epoch() > a.epoch(), "{} !> {}", b.epoch(), a.epoch());
890 assert!(c.epoch() > b.epoch(), "{} !> {}", c.epoch(), b.epoch());
891 }
892
893 #[test]
894 fn epochs_increase_across_ttl_reclaim_too() {
895 let (_tmp, s) = store(50);
896 let a = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
897 std::thread::sleep(std::time::Duration::from_millis(1_000));
898 let b = s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap();
899 assert!(b.epoch() > a.epoch());
900 }
901
902 #[test]
903 fn a_holder_whose_process_is_gone_is_reclaimed_immediately() {
904 let (tmp, s) = store(60_000);
905 s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
906 set_holder_process(&tmp, "agent-1", exited_pid(), 0);
907 let reclaimed = s.claim("agent-1", &boot("boot-b"), "block-2", None);
908 assert!(reclaimed.is_ok(), "a dead holder must not wait out the TTL, got {reclaimed:?}");
909 assert!(s.live_holder_other_than("agent-1", "boot-c").unwrap().is_some());
910 }
911
912 #[test]
915 fn a_reused_pid_does_not_keep_a_lease_alive() {
916 let (tmp, s) = store(60_000);
917 s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
918 let me = std::process::id();
919 let my_start = process_start_s(me).expect("this test process is running");
920 set_holder_process(&tmp, "agent-1", me, my_start.saturating_sub(3_600));
921 assert!(s.claim("agent-1", &boot("boot-b"), "block-2", None).is_ok());
922 }
923
924 #[test]
925 fn a_holder_on_another_host_is_never_presumed_dead() {
926 let (tmp, s) = store(60_000);
927 s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
928 let mut f = on_disk(&tmp, "agent-1");
929 f.hostname = "some-other-host".to_string();
930 f.pid = exited_pid();
931 std::fs::write(lease_path(&tmp, "agent-1"), serde_json::to_vec(&f).unwrap()).unwrap();
932 assert!(s.claim("agent-1", &boot("boot-b"), "block-2", None).is_err());
933 }
934
935 #[test]
936 fn renew_extends_ttl_and_blocks_reclaim_by_other() {
937 let (_tmp, s) = store(5_000);
943 let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
944 std::thread::sleep(std::time::Duration::from_millis(20));
945 s.renew(&lease).unwrap();
946 std::thread::sleep(std::time::Duration::from_millis(20));
947 let err = s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap_err();
949 assert!(matches!(err, LeaseError::HeldByOther { .. }));
950 }
951
952 #[test]
953 fn renew_fails_when_already_reclaimed_by_other() {
954 let (tmp, s) = store(50);
955 let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
956 std::thread::sleep(std::time::Duration::from_millis(1_000));
957 s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap();
958
959 let err = s.renew(&lease).unwrap_err();
960 assert!(matches!(err, LeaseError::HeldByOther { .. }));
961
962 assert_eq!(on_disk(&tmp, "agent-1").owner_boot_id, "boot-b");
964 }
965
966 #[test]
968 fn verify_detects_a_lost_lease_without_writing() {
969 let (tmp, s) = store(50);
970 let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
971 assert!(s.verify(&lease).is_ok());
972 std::thread::sleep(std::time::Duration::from_millis(1_000));
973 assert!(s.verify(&lease).is_ok());
975 s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap();
976 assert!(matches!(s.verify(&lease), Err(LeaseError::HeldByOther { .. })));
977 assert_eq!(on_disk(&tmp, "agent-1").owner_boot_id, "boot-b");
978 }
979
980 #[test]
981 fn release_removes_the_lease_file() {
982 let (tmp, s) = store(60_000);
983 let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
984 s.release(&lease).unwrap();
985 assert!(!lease_path(&tmp, "agent-1").exists());
986 }
987
988 #[test]
989 fn release_is_a_noop_when_already_reclaimed_by_other() {
990 let (tmp, s) = store(50);
991 let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
992 std::thread::sleep(std::time::Duration::from_millis(1_000));
993 s.claim("agent-1", &boot("boot-b"), "block-2", None).unwrap();
994
995 s.release(&lease).unwrap();
996
997 assert!(lease_path(&tmp, "agent-1").exists(), "release must not delete another owner's lease");
998 assert_eq!(on_disk(&tmp, "agent-1").owner_boot_id, "boot-b");
999 }
1000
1001 #[test]
1005 fn a_second_block_of_the_same_process_is_refused_while_the_first_holds_it() {
1006 let (_tmp, s) = store(60_000);
1007 let first = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1008 let err = s.claim("agent-1", &boot("boot-a"), "block-2", None).unwrap_err();
1009 match err {
1010 LeaseError::HeldByOther { holder, .. } => assert_eq!(holder.unwrap().block_id, "block-1"),
1011 other => panic!("expected HeldByOther, got {other:?}"),
1012 }
1013 assert!(s.verify(&first).is_ok(), "the holder keeps the agent");
1014 s.release(&first).unwrap();
1015 assert!(s.claim("agent-1", &boot("boot-a"), "block-2", None).is_ok());
1016 }
1017
1018 #[test]
1023 fn a_same_block_reclaim_supersedes_the_older_handle() {
1024 let (tmp, s) = store(60_000);
1025 let old = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1026 let new = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1027 assert_eq!(old.epoch(), new.epoch(), "same owner and block: not an ownership change");
1028 s.release(&old).unwrap();
1029 assert!(lease_path(&tmp, "agent-1").exists(), "the old handle's release must not free the new claim");
1030 assert!(s.verify(&new).is_ok());
1031 assert!(s.renew(&new).is_ok());
1032 assert!(matches!(s.verify(&old), Err(LeaseError::HeldByOther { .. })));
1033 assert!(matches!(s.renew(&old), Err(LeaseError::HeldByOther { .. })));
1034 s.release(&new).unwrap();
1035 assert!(!lease_path(&tmp, "agent-1").exists());
1036 }
1037
1038 #[test]
1042 fn a_block_superseded_after_expiry_is_fenced_and_cannot_release() {
1043 let (tmp, s) = store(50);
1044 let first = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1045 std::thread::sleep(std::time::Duration::from_millis(1_000));
1046 let second = s.claim("agent-1", &boot("boot-a"), "block-2", None).unwrap();
1047 assert!(second.epoch() > first.epoch(), "a block change is an ownership change");
1048 assert!(matches!(s.verify(&first), Err(LeaseError::HeldByOther { .. })));
1049 assert!(matches!(s.renew(&first), Err(LeaseError::HeldByOther { .. })));
1050 s.release(&first).unwrap();
1051 assert_eq!(on_disk(&tmp, "agent-1").block_id, "block-2");
1052 }
1053
1054 #[test]
1055 fn release_is_idempotent_on_missing_file() {
1056 let (_tmp, s) = store(60_000);
1057 let lease = s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1058 s.release(&lease).unwrap();
1059 assert!(s.release(&lease).is_ok());
1060 }
1061
1062 #[test]
1063 fn live_holder_ignores_self_and_names_the_holder() {
1064 let (_tmp, s) = store(60_000);
1067 s.claim_as(
1068 "agent-1",
1069 &boot("boot-a"),
1070 "block-1",
1071 None,
1072 &ClaimantInfo { channel: "stable".into(), version: "0.57.4".into() },
1073 )
1074 .unwrap();
1075 assert!(s.live_holder_other_than("agent-1", "boot-a").unwrap().is_none());
1076 let other = s.live_holder_other_than("agent-1", "boot-b").unwrap().unwrap();
1077 assert_eq!((other.channel.as_str(), other.version.as_str()), ("stable", "0.57.4"));
1078 }
1079
1080 #[test]
1081 fn live_holder_ignores_an_expired_lease() {
1082 let (_tmp, s) = store(50);
1083 s.claim("agent-1", &boot("boot-a"), "block-1", None).unwrap();
1084 std::thread::sleep(std::time::Duration::from_millis(1_000));
1085 assert!(s.live_holder_other_than("agent-1", "boot-b").unwrap().is_none());
1086 }
1087
1088 #[test]
1089 fn concurrent_claim_race_has_exactly_one_winner() {
1090 let tmp = tempfile::tempdir().unwrap();
1091 let root = tmp.path().to_path_buf();
1092 let n = 8;
1093 let handles: Vec<_> = (0..n)
1094 .map(|i| {
1095 let root = root.clone();
1096 std::thread::spawn(move || {
1097 let s = LeaseStore::open(&root).unwrap();
1098 s.claim("agent-1", &boot(&format!("boot-{i}")), "block", None)
1099 .is_ok()
1100 })
1101 })
1102 .collect();
1103 let wins: usize = handles.into_iter().map(|h| h.join().unwrap()).filter(|ok| *ok).count();
1104 assert_eq!(wins, 1, "exactly one claimant should win the race");
1105 }
1106}