返回 CodeWhale
workspace_lease.rs
根目录 / crates / runtime / src / workspace_lease.rs
1 //! Workspace drive lease: at most one driving engine per workspace, process-wide.
2 //!
3 //! The store process-owner lock serializes writers of one *store*, but a
4 //! workspace is shared across stores — a per-workspace store (the VS Code
5 //! extension), a per-session store (the interactive TUI) and the user-level
6 //! default store can all point at the same working tree, the same snapshot
7 //! side-repo (keyed by canonical workspace path) and the same git index, with
8 //! nothing serializing them across processes. The lease lifts the exclusivity
9 //! unit to the workspace itself.
10 //!
11 //! Drive vs watch: only a *driving* engine takes the lease. Watch-only
12 //! observers never do — their token intent already forbids mutation, and they
13 //! attach to the owner that holds the lease rather than admitting their own
14 //! workspace scope.
15 //!
16 //! The mechanism mirrors the store process-owner lock: an fd lock the kernel
17 //! releases when the holder dies, plus a small holder record a contender can
18 //! read to name the holder in a legible refusal. The kernel lock is the
19 //! authority; recorded holder facts never authorize replacing its file.
20 //!
21 //! Two capabilities are involved and they are asked about separately. The
22 //! directory admission needs ownership it can *prove*; HarmonyOS hmdfs — the
23 //! 2in1 user directory — synthesises the owner and mode of every object created
24 //! on it, so that proof can never hold there. Exclusivity itself is the kernel
25 //! lock, which is a different capability and does hold there. Admission
26 //! therefore relaxes only the proof, and the lease is still taken; refusing on
27 //! the proof turned a limit on evidence into a failed engine start.
28 //!
29 //! A mount that refuses the lock itself is the one case where exclusivity is
30 //! genuinely unavailable. It is reported to the caller — three outcomes, of
31 //! which only contention is a refusal — so that decision is named rather than
32 //! silently taken.
33
34 use std::fs::File;
35 use std::io::{Seek, SeekFrom, Write};
36 use std::path::{Path, PathBuf};
37 use std::time::{Duration, SystemTime};
38
39 use anyhow::{Context as _, Result};
40 use codewhale_config::private_directory::PrivateDirectory;
41
42 /// Upper bound on the bytes read back from a lease holder record. Also the
43 /// offset the Windows byte-range lock starts at, so a contender can still read
44 /// the record of the holder it is contending with.
45 const HOLDER_RECORD_MAX_BYTES: u64 = 512;
46
47 /// Facts about who holds a workspace drive lease.
48 #[derive(Debug, Clone, PartialEq, Eq)]
49 pub struct WorkspaceLeaseHolder {
50 pub pid: u32,
51 /// Liveness token of the holder process (`unix_process_start` shape), when
52 /// recorded. Absent on Windows and on records written before it existed.
53 pub process_start: Option<String>,
54 /// Human-readable client label, e.g. `vscode`, `desktop`, `tui`.
55 pub client: Option<String>,
56 /// Store root of the holding engine, for legible refusal messages.
57 pub store_root: Option<PathBuf>,
58 /// Wall-clock acquisition time (ms since UNIX_EPOCH).
59 pub since_ms: u64,
60 }
61
62 impl WorkspaceLeaseHolder {
63 fn to_record(&self) -> String {
64 let mut record = format!("version=1\npid={}\nsince_ms={}\n", self.pid, self.since_ms);
65 if let Some(process_start) = &self.process_start {
66 record.push_str(&format!("process_start={process_start}\n"));
67 }
68 if let Some(client) = &self.client {
69 record.push_str(&format!("client={}\n", client.replace(['\n', '='], " ")));
70 }
71 if let Some(store_root) = &self.store_root {
72 record.push_str(&format!(
73 "store_root={}\n",
74 store_root.to_string_lossy().replace(['\n', '='], " ")
75 ));
76 }
77 record
78 }
79
80 fn from_record(text: &str) -> Option<Self> {
81 let mut version = None;
82 let mut pid = None;
83 let mut process_start = None;
84 let mut client = None;
85 let mut store_root = None;
86 let mut since_ms = None;
87 for line in text.lines() {
88 match line.split_once('=') {
89 Some(("version", value)) => version = value.parse::<u32>().ok(),
90 Some(("pid", value)) => pid = value.parse::<u32>().ok(),
91 Some(("process_start", value)) => process_start = Some(value.to_string()),
92 Some(("client", value)) => client = Some(value.to_string()),
93 Some(("store_root", value)) => store_root = Some(PathBuf::from(value)),
94 Some(("since_ms", value)) => since_ms = value.parse::<u64>().ok(),
95 _ => {}
96 }
97 }
98 if version != Some(1) {
99 return None;
100 }
101 Some(Self {
102 pid: pid?,
103 process_start,
104 client,
105 store_root,
106 since_ms: since_ms?,
107 })
108 }
109
110 /// How long the lease has been held, best effort.
111 pub fn held_for(&self) -> Duration {
112 SystemTime::now()
113 .duration_since(SystemTime::UNIX_EPOCH + Duration::from_millis(self.since_ms))
114 .unwrap_or_default()
115 }
116 }
117
118 /// A shared process-wide drive lease handle.
119 ///
120 /// The first admission for a workspace acquires the OS lease; later admissions
121 /// in the *same process* (a successor manager, a second engine in one test
122 /// process) share it by counted acquisition instead of refusing each other.
123 /// The last admitted handle drop releases it.
124 pub struct SharedWorkspaceDriveLease {
125 inner: std::sync::Arc<LeaseInner>,
126 }
127
128 struct LeaseInner {
129 /// The OS lease plus the live shared-admission count, or nothing when a
130 /// foreign process held it at (first) acquire time.
131 state: std::sync::Mutex<Option<(WorkspaceDriveLease, usize)>>,
132 }
133
134 /// Why the lease could not be taken even though no other process holds it.
135 ///
136 /// This is a capability the filesystem lacks, not a refusal: the caller decides
137 /// whether to run without workspace exclusivity, and the reason is carried so
138 /// that decision can be explained to the user instead of looking like success.
139 #[derive(Debug, Clone, PartialEq, Eq)]
140 pub struct LeaseUnavailability {
141 /// The lease state root whose filesystem could not carry the lease.
142 pub directory: PathBuf,
143 /// What the mount did, in terms a user can act on.
144 pub reason: String,
145 }
146
147 impl LeaseUnavailability {
148 #[cfg(unix)]
149 fn new(directory: &Path, reason: impl Into<String>) -> Self {
150 Self {
151 directory: directory.to_path_buf(),
152 reason: reason.into(),
153 }
154 }
155 }
156
157 impl std::fmt::Display for LeaseUnavailability {
158 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159 write!(
160 f,
161 "{} cannot provide workspace exclusivity: {}",
162 self.directory.display(),
163 self.reason
164 )
165 }
166 }
167
168 /// One raw attempt to take a workspace's drive lease.
169 ///
170 /// Public because [`WorkspaceDriveLease::try_acquire`] is: it is how an
171 /// embedder that wants the lease without the shared-slot bookkeeping asks.
172 pub enum LeaseAttempt {
173 Acquired(WorkspaceDriveLease),
174 /// A foreign process holds the kernel lock.
175 Contended,
176 /// No lock can be taken here at all.
177 Unsupported(LeaseUnavailability),
178 }
179
180 /// The outcome of admitting one driving engine for a workspace.
181 pub enum LeaseAdmission {
182 /// This process holds (or shares) the workspace drive lease.
183 Held(SharedWorkspaceDriveLease),
184 /// Another process drives this workspace: refuse and name its holder.
185 Contended,
186 /// This filesystem cannot carry an exclusive lease. Running without one is
187 /// the caller's decision, and must be reported rather than assumed.
188 Unsupported(LeaseUnavailability),
189 }
190
191 /// The held handle is a guard, not a fact worth printing; the other two
192 /// outcomes are what a caller or a test needs to see.
193 impl std::fmt::Debug for LeaseAdmission {
194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195 match self {
196 Self::Held(_) => f.write_str("Held(..)"),
197 Self::Contended => f.write_str("Contended"),
198 Self::Unsupported(unavailable) => {
199 f.debug_tuple("Unsupported").field(unavailable).finish()
200 }
201 }
202 }
203 }
204
205 impl SharedWorkspaceDriveLease {
206 /// Acquire (or join) this process's drive lease for the workspace.
207 ///
208 /// [`LeaseAdmission::Contended`] means a *foreign process* holds it — the
209 /// caller refuses with the holder's facts from
210 /// [`WorkspaceDriveLease::read_holder`]. [`LeaseAdmission::Unsupported`]
211 /// means the filesystem cannot carry the lease at all, which is a different
212 /// answer and a different decision. Same-process joins never fail and never
213 /// re-lock.
214 pub fn acquire(
215 workspace: &Path,
216 client: Option<&str>,
217 store_root: Option<&Path>,
218 ) -> Result<LeaseAdmission> {
219 let lease_key = WorkspaceDriveLease::lease_path(workspace)?;
220 let slot = {
221 let mut registry = registry()
222 .lock()
223 .unwrap_or_else(|poisoned| poisoned.into_inner());
224 if let Some(slot) = registry.get(&lease_key) {
225 slot.clone()
226 } else {
227 let lease = match WorkspaceDriveLease::try_acquire(workspace, client, store_root)? {
228 LeaseAttempt::Acquired(lease) => lease,
229 LeaseAttempt::Contended => return Ok(LeaseAdmission::Contended),
230 LeaseAttempt::Unsupported(unavailable) => {
231 return Ok(LeaseAdmission::Unsupported(unavailable));
232 }
233 };
234 let inner = std::sync::Arc::new(LeaseInner {
235 state: std::sync::Mutex::new(Some((lease, 1))),
236 });
237 registry.insert(lease_key, inner.clone());
238 return Ok(LeaseAdmission::Held(Self { inner }));
239 }
240 };
241 // The returned handle is an owned clone, so moving it out never
242 // borrows the guard: the state guard stays held across `try_acquire`,
243 // which serializes two threads of one process racing for the same
244 // workspace and makes the slot — not the fd lock — the in-process
245 // authority.
246 let inner = slot.clone();
247 let mut state = slot
248 .state
249 .lock()
250 .unwrap_or_else(|poisoned| poisoned.into_inner());
251 if let Some((_lease, count)) = state.as_mut() {
252 *count += 1;
253 return Ok(LeaseAdmission::Held(Self { inner }));
254 }
255 let lease = match WorkspaceDriveLease::try_acquire(workspace, client, store_root)? {
256 LeaseAttempt::Acquired(lease) => lease,
257 LeaseAttempt::Contended => return Ok(LeaseAdmission::Contended),
258 LeaseAttempt::Unsupported(unavailable) => {
259 return Ok(LeaseAdmission::Unsupported(unavailable));
260 }
261 };
262 *state = Some((lease, 1));
263 Ok(LeaseAdmission::Held(Self { inner }))
264 }
265 }
266
267 impl Drop for SharedWorkspaceDriveLease {
268 fn drop(&mut self) {
269 // The decrement and the removal of the OS lease happen in *one*
270 // critical section. Deciding under the lock and taking afterwards
271 // leaves a window in which a concurrent `acquire` observes the zero
272 // count, joins the handle, and then loses the OS lease out from under
273 // itself — two engines driving one workspace, which is the whole
274 // failure this lease exists to prevent.
275 let Ok(mut state) = self.inner.state.lock() else {
276 return;
277 };
278 let Some((_lease, count)) = state.as_mut() else {
279 return;
280 };
281 *count -= 1;
282 if *count == 0 {
283 // Drop the OS lease *inside* this section. Deciding here and
284 // releasing after the guard is gone leaves a window in which a
285 // same-process `acquire` finds the slot empty while the OS lock is
286 // still held, and is refused — two engine scopes of one process
287 // refusing each other, which is precisely what the shared slot
288 // exists to prevent.
289 state.take();
290 }
291 }
292 }
293
294 /// One slot per workspace, kept for the life of the process.
295 ///
296 /// Removing a slot on release would race its owner: a contender that read the
297 /// map before the removal could populate the slot that is about to be deleted,
298 /// and the next contender would then create a second slot for the same
299 /// workspace. A free slot holds nothing but an empty `Option`, so keeping it
300 /// costs one map entry per workspace this process has successfully acquired.
301 /// Refused first acquisitions do not enter the registry.
302 type LeaseRegistry =
303 std::sync::Mutex<std::collections::HashMap<PathBuf, std::sync::Arc<LeaseInner>>>;
304
305 fn registry() -> &'static LeaseRegistry {
306 static REGISTRY: std::sync::OnceLock<LeaseRegistry> = std::sync::OnceLock::new();
307 REGISTRY.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
308 }
309
310 /// A held workspace drive lease. Dropping releases the kernel lock.
311 pub struct WorkspaceDriveLease {
312 file: File,
313 _base: PrivateDirectory,
314 _directory: PrivateDirectory,
315 }
316
317 impl WorkspaceDriveLease {
318 /// The lease path for a workspace: alongside the snapshot side-repo, using
319 /// the same canonical-path hashing (`snapshot::paths`), so worktrees of one
320 /// checkout share a project bucket and one worktree maps to exactly one
321 /// lease.
322 pub fn lease_path(workspace: &Path) -> Result<PathBuf> {
323 let base = lease_state_base()?;
324 let canonical = workspace
325 .canonicalize()
326 .unwrap_or_else(|_| workspace.to_path_buf());
327 let project = codewhale_paths::strip_worktree_suffix(&canonical);
328 Ok(base
329 .join(codewhale_paths::stable_hex(&project))
330 .join(codewhale_paths::stable_hex(&canonical))
331 .with_extension("lease"))
332 }
333
334 /// Try once to acquire the drive lease for this process.
335 ///
336 /// [`LeaseAttempt::Contended`] means the kernel lock is held: use
337 /// [`Self::read_holder`] to name the recorded holder. An unsupported mount
338 /// is reported, not refused.
339 pub fn try_acquire(
340 workspace: &Path,
341 client: Option<&str>,
342 store_root: Option<&Path>,
343 ) -> Result<LeaseAttempt> {
344 let path = Self::lease_path(workspace)?;
345 let parent = path.parent().context("Workspace lease has no parent")?;
346 let state_root = parent
347 .parent()
348 .context("Workspace lease has no state root")?;
349 let name = path
350 .file_name()
351 .and_then(|name| name.to_str())
352 .context("Workspace lease name is invalid")?;
353 // Admission relaxes *only* the proof that the directory is
354 // current-user-only, and only where the mount cannot express it. The
355 // exclusivity this function exists for is the kernel lock taken below,
356 // which is a different capability: on HarmonyOS hmdfs `flock` works
357 // and only the reported owner is unusable, so giving up the lease here
358 // would discard a guarantee that still holds. A mount that truly has
359 // no advisory locks is reported further down, after the lock says so.
360 let base = PrivateDirectory::admit_trusting_mount(state_root)?;
361 let directory = PrivateDirectory::admit_trusting_mount(parent)?;
362 let file = directory.open_internal_file(name)?;
363 #[cfg(unix)]
364 let contention = {
365 use std::os::fd::AsRawFd as _;
366 // SAFETY: `file` owns a valid descriptor retained by this guard.
367 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
368 Some(std::io::Error::last_os_error())
369 } else {
370 None
371 }
372 };
373 #[cfg(windows)]
374 let contention = {
375 use std::os::windows::io::AsRawHandle as _;
376 use windows_sys::Win32::Storage::FileSystem::LockFile;
377 let (offset_low, offset_high, length_low, length_high) =
378 (HOLDER_RECORD_MAX_BYTES as u32, 0, u32::MAX, 0x7FFF_FFFF);
379 // SAFETY: `file` owns a valid handle retained by this guard.
380 if unsafe {
381 LockFile(
382 file.as_raw_handle() as _,
383 offset_low,
384 offset_high,
385 length_low,
386 length_high,
387 )
388 } == 0
389 {
390 Some(std::io::Error::last_os_error())
391 } else {
392 None
393 }
394 };
395 #[cfg(not(any(unix, windows)))]
396 let contention: Option<std::io::Error> = None;
397 if let Some(error) = contention {
398 if codewhale_util::lock::is_contention(&error) {
399 return Ok(LeaseAttempt::Contended);
400 }
401 // No advisory locks on this mount at all: two drivers cannot be
402 // excluded here, but that is a property of the filesystem, not a
403 // holder. `EWOULDBLOCK` was handled above and stays contention.
404 #[cfg(unix)]
405 if codewhale_util::lock::advisory_locking_unavailable(&error) {
406 return Ok(LeaseAttempt::Unsupported(LeaseUnavailability::new(
407 state_root,
408 format!("this filesystem refuses advisory file locks ({error})"),
409 )));
410 }
411 return Err(error).context("Failed to lock workspace lease");
412 }
413 #[cfg(any(unix, windows))]
414 anyhow::ensure!(
415 base.is_at_selected_path()? && directory.is_at_selected_path()?,
416 "Workspace lease directory identity changed"
417 );
418 let selected = directory.open_internal_file(name)?;
419 anyhow::ensure!(
420 PrivateDirectory::same_file_identity(&file, &selected)?,
421 "Workspace lease file identity changed"
422 );
423 let holder = WorkspaceLeaseHolder {
424 pid: std::process::id(),
425 process_start: current_process_start(),
426 client: client.map(ToString::to_string),
427 store_root: store_root.map(Path::to_path_buf),
428 since_ms: SystemTime::now()
429 .duration_since(SystemTime::UNIX_EPOCH)
430 .map_or(0, |elapsed| elapsed.as_millis() as u64),
431 };
432 let mut lease = Self {
433 file,
434 _base: base,
435 _directory: directory,
436 };
437 // Best effort: holder diagnostics must never fail the lease holder.
438 let _ = lease
439 .file
440 .set_len(0)
441 .and_then(|()| lease.file.seek(SeekFrom::Start(0)).map(|_| ()))
442 .and_then(|()| lease.file.write_all(holder.to_record().as_bytes()));
443 Ok(LeaseAttempt::Acquired(lease))
444 }
445
446 /// Read the recorded holder, if any. Missing or malformed data is `None`;
447 /// filesystem errors remain explicit, and the record may be stale.
448 pub fn read_holder(workspace: &Path) -> Result<Option<WorkspaceLeaseHolder>> {
449 let path = Self::lease_path(workspace)?;
450 let parent = path.parent().context("Workspace lease has no parent")?;
451 let name = path
452 .file_name()
453 .and_then(|name| name.to_str())
454 .context("Workspace lease name is invalid")?;
455 // Naming a holder is a read. On a mount that cannot express ownership
456 // the strict proof fails for every directory, and refusing would hide
457 // the holder's pid behind "record unreadable" on exactly the platform
458 // where a user most needs to know who holds the workspace.
459 let directory = match PrivateDirectory::inspect_trusting_mount(parent) {
460 Ok(directory) => directory,
461 Err(error)
462 if error.chain().any(|cause| {
463 cause
464 .downcast_ref::<std::io::Error>()
465 .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound)
466 }) =>
467 {
468 return Ok(None);
469 }
470 Err(error) => return Err(error).context("Failed to inspect workspace lease directory"),
471 };
472 #[cfg(unix)]
473 let bytes =
474 match directory.read_private_receipt(name, HOLDER_RECORD_MAX_BYTES as usize - 1)? {
475 Some((bytes, _file)) => bytes,
476 None => return Ok(None),
477 };
478 #[cfg(windows)]
479 let bytes = {
480 use std::io::Read as _;
481 let Some(file) = directory.open_owned_file_for_read(name)? else {
482 return Ok(None);
483 };
484 let mut bytes = Vec::new();
485 file.take(HOLDER_RECORD_MAX_BYTES).read_to_end(&mut bytes)?;
486 bytes
487 };
488 #[cfg(not(any(unix, windows)))]
489 anyhow::bail!("Workspace drive lease is unsupported on this platform");
490 #[cfg(any(unix, windows))]
491 {
492 anyhow::ensure!(
493 directory.is_at_selected_path()?,
494 "Workspace lease directory identity changed"
495 );
496 let text = std::str::from_utf8(&bytes)?;
497 Ok(WorkspaceLeaseHolder::from_record(text))
498 }
499 }
500 }
501
502 impl Drop for WorkspaceDriveLease {
503 fn drop(&mut self) {
504 #[cfg(unix)]
505 {
506 use std::os::fd::AsRawFd as _;
507 // SAFETY: Drop runs only while `file` still owns this descriptor.
508 unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_UN) };
509 }
510 #[cfg(windows)]
511 {
512 use std::os::windows::io::AsRawHandle as _;
513 use windows_sys::Win32::Storage::FileSystem::UnlockFile;
514 let (offset_low, offset_high, length_low, length_high) =
515 (HOLDER_RECORD_MAX_BYTES as u32, 0, u32::MAX, 0x7FFF_FFFF);
516 // SAFETY: Drop runs only while `file` still owns this handle.
517 unsafe {
518 UnlockFile(
519 self.file.as_raw_handle() as _,
520 offset_low,
521 offset_high,
522 length_low,
523 length_high,
524 );
525 }
526 }
527 }
528 }
529
530 #[cfg(all(test, unix))]
531 fn holder_is_dead(path: &Path) -> bool {
532 use codewhale_config::private_directory::{UnixProcessStatus, unix_process_status};
533
534 let Some(holder) =
535 WorkspaceLeaseHolder::from_record(&std::fs::read_to_string(path).unwrap_or_default())
536 else {
537 return false;
538 };
539 let Some(recorded_start) = holder.process_start.as_deref() else {
540 return false;
541 };
542 if holder.pid == std::process::id() {
543 // Same-process contention: the record is either ours (a live sibling
544 // scope holds the lock — alive by definition) or a same-pid
545 // predecessor. Distinguish by creation token: a different one means
546 // the pid was recycled and the previous holder is gone.
547 return current_process_start().as_deref() != Some(recorded_start);
548 }
549 match unix_process_status(holder.pid) {
550 Ok(UnixProcessStatus::Present { start }) => start != recorded_start,
551 Ok(UnixProcessStatus::Absent) => true,
552 // Identity or liveness is uncertain (EPERM, a foreign principal, a
553 // pid we cannot probe). Never convert uncertainty into death.
554 Err(_) => false,
555 }
556 }
557
558 /// This process's liveness token, best effort.
559 #[cfg(unix)]
560 fn current_process_start() -> Option<String> {
561 use codewhale_config::private_directory::{UnixProcessStatus, unix_process_status};
562
563 match unix_process_status(std::process::id()) {
564 Ok(UnixProcessStatus::Present { start }) => Some(start),
565 _ => None,
566 }
567 }
568
569 /// Windows records no creation token; the byte-range lock itself is the
570 /// liveness mechanism.
571 #[cfg(not(unix))]
572 fn current_process_start() -> Option<String> {
573 None
574 }
575
576 fn lease_state_base() -> Result<PathBuf> {
577 #[cfg(test)]
578 {
579 if let Some(base) = crate::test_support::unsealed_state_dir("workspace-leases") {
580 PrivateDirectory::open(&base)?;
581 return Ok(base);
582 }
583 }
584 codewhale_config::resolve_state_dir("workspace-leases")
585 .context("Failed to resolve workspace lease state dir")
586 }
587
588 #[cfg(test)]
589 mod tests {
590 use super::*;
591
592 fn temp_workspace(tag: &str) -> PathBuf {
593 let dir = crate::test_support::test_scratch_dir(&format!("cw-ws-lease-{tag}"));
594 std::fs::create_dir_all(&dir).expect("create workspace");
595 dir
596 }
597
598 fn write_record(workspace: &Path, holder: &WorkspaceLeaseHolder) -> PathBuf {
599 let path = WorkspaceDriveLease::lease_path(workspace).expect("lease path");
600 let parent = path.parent().expect("lease dir");
601 let _base = PrivateDirectory::open(parent.parent().expect("lease state root"))
602 .expect("private lease state root");
603 let directory = PrivateDirectory::open(parent).expect("private lease dir");
604 let mut file = directory
605 .open_internal_file(path.file_name().unwrap().to_str().unwrap())
606 .expect("private lease file");
607 file.set_len(0).expect("truncate holder record");
608 file.write_all(holder.to_record().as_bytes())
609 .expect("write holder record");
610 path
611 }
612
613 fn expect_held(admission: LeaseAdmission) -> SharedWorkspaceDriveLease {
614 match admission {
615 LeaseAdmission::Held(lease) => lease,
616 LeaseAdmission::Contended => panic!("expected a held lease, got contention"),
617 LeaseAdmission::Unsupported(unavailable) => {
618 panic!("expected a held lease, got {unavailable}")
619 }
620 }
621 }
622
623 #[test]
624 fn acquire_then_contend_reports_holder() {
625 let workspace = temp_workspace("contend");
626 let first =
627 WorkspaceDriveLease::try_acquire(&workspace, Some("tui"), None).expect("first acquire");
628 assert!(
629 matches!(first, LeaseAttempt::Acquired(_)),
630 "first drive is admitted"
631 );
632 let second = WorkspaceDriveLease::try_acquire(&workspace, Some("vscode"), None)
633 .expect("contend probe");
634 assert!(
635 matches!(second, LeaseAttempt::Contended),
636 "second drive must be refused"
637 );
638 let holder = WorkspaceDriveLease::read_holder(&workspace)
639 .expect("read holder")
640 .expect("holder recorded");
641 assert_eq!(holder.pid, std::process::id());
642 assert_eq!(holder.client.as_deref(), Some("tui"));
643 assert_eq!(holder.process_start, current_process_start());
644 drop(first);
645 let third =
646 WorkspaceDriveLease::try_acquire(&workspace, Some("vscode"), None).expect("reacquire");
647 assert!(
648 matches!(third, LeaseAttempt::Acquired(_)),
649 "lease frees after drop"
650 );
651 }
652
653 #[test]
654 fn shared_lease_reenters_within_a_process() {
655 let workspace = temp_workspace("shared");
656 let first = expect_held(
657 SharedWorkspaceDriveLease::acquire(&workspace, Some("tui"), None)
658 .expect("first shared acquire"),
659 );
660 // A second engine in the same process joins by refcount instead of
661 // refusing — the lease's unit is the process.
662 let second = expect_held(
663 SharedWorkspaceDriveLease::acquire(&workspace, Some("vscode"), None)
664 .expect("second shared acquire"),
665 );
666 drop(first);
667 // Still held by the second handle: a raw probe must be refused.
668 let refused =
669 WorkspaceDriveLease::try_acquire(&workspace, Some("probe"), None).expect("probe");
670 assert!(
671 matches!(refused, LeaseAttempt::Contended),
672 "lease still held while shared"
673 );
674 drop(second);
675 let after = expect_held(
676 SharedWorkspaceDriveLease::acquire(&workspace, Some("next"), None)
677 .expect("reacquire after full release"),
678 );
679 drop(after);
680 }
681
682 #[test]
683 fn shared_handles_survive_concurrent_acquire_and_release() {
684 // The registry slot is shared by every handle for one workspace, so a
685 // wrong lock order here shows up as a deadlock or a lost OS lease. Both
686 // are matters of the slot being taken and cleared under the lock that
687 // guards the count.
688 let workspace = temp_workspace("churn");
689 let mut workers = Vec::new();
690 for _ in 0..8 {
691 let workspace = workspace.clone();
692 workers.push(std::thread::spawn(move || {
693 for _ in 0..25 {
694 let lease = expect_held(
695 SharedWorkspaceDriveLease::acquire(&workspace, Some("churn"), None)
696 .expect("acquire"),
697 );
698 drop(lease);
699 }
700 }));
701 }
702 for worker in workers {
703 worker.join().expect("churn worker");
704 }
705 // Every handle is gone: the lease is free and a fresh holder records
706 // itself rather than joining a slot nothing released.
707 let lease = expect_held(
708 SharedWorkspaceDriveLease::acquire(&workspace, Some("after"), None)
709 .expect("acquire after churn"),
710 );
711 let holder = WorkspaceDriveLease::read_holder(&workspace)
712 .expect("read holder")
713 .expect("holder recorded");
714 assert_eq!(holder.client.as_deref(), Some("after"));
715 drop(lease);
716 }
717
718 /// The one branch that decides fatal from degraded. A mount with no
719 /// advisory locks must never be reported as a second driver — that would
720 /// keep the engine from starting over a property of the filesystem — and a
721 /// second driver must never be downgraded to "run anyway", which would let
722 /// two engines write one tree. The two predicates are disjoint by
723 /// construction; this pins that.
724 #[cfg(unix)]
725 #[test]
726 fn only_a_held_lock_is_contention_and_only_a_lockless_mount_is_unsupported() {
727 use std::io::Error;
728
729 let held = Error::from_raw_os_error(libc::EWOULDBLOCK);
730 assert!(
731 codewhale_util::lock::is_contention(&held),
732 "a held lock is contention"
733 );
734 assert!(
735 !codewhale_util::lock::advisory_locking_unavailable(&held),
736 "a held lock is not a mount without locks"
737 );
738 for code in [
739 libc::EPERM,
740 libc::EACCES,
741 libc::ENOTSUP,
742 libc::EINVAL,
743 libc::ENOSYS,
744 ] {
745 let absent = Error::from_raw_os_error(code);
746 assert!(
747 !codewhale_util::lock::is_contention(&absent),
748 "{code} is the mount answering, not a holder"
749 );
750 assert!(
751 codewhale_util::lock::advisory_locking_unavailable(&absent),
752 "{code} means this mount has no advisory locks"
753 );
754 }
755 }
756
757 #[test]
758 fn lease_path_is_stable_and_worktree_aware() {
759 let workspace = temp_workspace("paths");
760 let one = WorkspaceDriveLease::lease_path(&workspace).expect("path");
761 let two = WorkspaceDriveLease::lease_path(&workspace).expect("path");
762 assert_eq!(one, two);
763 assert_eq!(one.extension().and_then(|ext| ext.to_str()), Some("lease"));
764 let worktree = workspace.join(".worktrees").join("feat");
765 std::fs::create_dir_all(&worktree).expect("create worktree");
766 let sibling = workspace.join(".worktrees").join("other");
767 std::fs::create_dir_all(&sibling).expect("create sibling");
768 let a = WorkspaceDriveLease::lease_path(&worktree).expect("path");
769 let b = WorkspaceDriveLease::lease_path(&sibling).expect("path");
770 assert_ne!(a, b, "distinct worktrees get distinct leases");
771 assert_eq!(
772 a.parent().unwrap(),
773 b.parent().unwrap(),
774 "worktrees of one project share a bucket"
775 );
776 }
777
778 #[test]
779 fn holder_record_round_trips_and_needs_a_version() {
780 let holder = WorkspaceLeaseHolder {
781 pid: 4242,
782 process_start: Some("macos:1:2".into()),
783 client: Some("vscode".into()),
784 store_root: Some(PathBuf::from("/tmp/store")),
785 since_ms: 1_700_000_000_000,
786 };
787 assert_eq!(
788 WorkspaceLeaseHolder::from_record(&holder.to_record()),
789 Some(holder)
790 );
791 // A record without a version is not a record we trust.
792 assert_eq!(
793 WorkspaceLeaseHolder::from_record("pid=1\nsince_ms=0\n"),
794 None
795 );
796 }
797
798 #[test]
799 fn absent_or_malformed_records_read_none() {
800 let workspace = temp_workspace("records");
801 assert_eq!(
802 WorkspaceDriveLease::read_holder(&workspace).expect("absent"),
803 None
804 );
805 let path = write_record(
806 &workspace,
807 &WorkspaceLeaseHolder {
808 pid: 7,
809 process_start: None,
810 client: None,
811 store_root: None,
812 since_ms: 5,
813 },
814 );
815 assert!(
816 WorkspaceDriveLease::read_holder(&workspace)
817 .expect("present")
818 .is_some()
819 );
820 std::fs::write(&path, "not a record\n").expect("write malformed");
821 assert_eq!(
822 WorkspaceDriveLease::read_holder(&workspace).expect("malformed"),
823 None
824 );
825 }
826
827 #[cfg(unix)]
828 #[test]
829 fn a_provably_dead_holder_record_does_not_replace_a_locked_lease() {
830 /// Spawn a child, report its pid and creation token while it is alive,
831 /// then reap it. Returns the recorded facts and the lease path.
832 fn holder_of_a_reaped_child(workspace: &Path) -> PathBuf {
833 use codewhale_config::private_directory::{UnixProcessStatus, unix_process_status};
834
835 let mut child = std::process::Command::new("/bin/sh")
836 .args(["-c", "exit 0"])
837 .spawn()
838 .expect("spawn child");
839 let pid = child.id();
840 let start = match unix_process_status(pid) {
841 Ok(UnixProcessStatus::Present { start }) => Some(start),
842 other => panic!("live child must be present: {other:?}"),
843 };
844 child.wait().expect("reap child");
845 let path = write_record(
846 workspace,
847 &WorkspaceLeaseHolder {
848 pid,
849 process_start: start,
850 client: Some("crashed".into()),
851 store_root: None,
852 since_ms: 0,
853 },
854 );
855 assert!(holder_is_dead(&path), "a reaped holder is provably dead");
856 path
857 }
858
859 let workspace = temp_workspace("dead");
860 holder_of_a_reaped_child(&workspace);
861 let first =
862 WorkspaceDriveLease::try_acquire(&workspace, Some("next"), None).expect("acquire");
863 assert!(
864 matches!(first, LeaseAttempt::Acquired(_)),
865 "an unlocked lease remains acquirable despite a stale record"
866 );
867 holder_of_a_reaped_child(&workspace);
868 assert!(
869 matches!(
870 WorkspaceDriveLease::try_acquire(&workspace, Some("contender"), None)
871 .expect("contend"),
872 LeaseAttempt::Contended
873 ),
874 "a stale holder record must not replace a held kernel lock"
875 );
876 drop(first);
877 assert!(
878 matches!(
879 WorkspaceDriveLease::try_acquire(&workspace, Some("after"), None)
880 .expect("reacquire"),
881 LeaseAttempt::Acquired(_)
882 ),
883 "the same lease is available after its holder releases it"
884 );
885 }
886
887 #[cfg(unix)]
888 #[test]
889 fn a_live_holder_with_a_matching_token_is_never_dead() {
890 use codewhale_config::private_directory::{UnixProcessStatus, unix_process_status};
891
892 let workspace = temp_workspace("live");
893 let mut child = std::process::Command::new("/bin/sh")
894 .args(["-c", "exec sleep 30"])
895 .spawn()
896 .expect("spawn child");
897 let pid = child.id();
898 let start = match unix_process_status(pid) {
899 Ok(UnixProcessStatus::Present { start }) => start,
900 other => panic!("live child must be present: {other:?}"),
901 };
902 let path = write_record(
903 &workspace,
904 &WorkspaceLeaseHolder {
905 pid,
906 process_start: Some(start),
907 client: Some("driving".into()),
908 store_root: None,
909 since_ms: 0,
910 },
911 );
912 assert!(
913 !holder_is_dead(&path),
914 "a live holder's recorded token must never read dead"
915 );
916 let _ = child.kill();
917 let _ = child.wait();
918 }
919
920 #[cfg(unix)]
921 #[test]
922 fn a_record_without_a_liveness_token_is_never_taken_over() {
923 let workspace = temp_workspace("no-token");
924 let path = write_record(
925 &workspace,
926 &WorkspaceLeaseHolder {
927 // A pid that cannot be probed at all.
928 pid: u32::MAX,
929 process_start: None,
930 client: None,
931 store_root: None,
932 since_ms: 0,
933 },
934 );
935 assert!(
936 !holder_is_dead(&path),
937 "without a liveness token, only a live-holder conclusion is safe"
938 );
939 }
940 }
941
941 lines RUST