Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

bound kernel bootstrap lock waits (#3539)

kt1a9d3e88da6c
diff --git a/crates/pa-core/src/kernel/bootstrap/dir_lock.rs b/crates/pa-core/src/kernel/bootstrap/dir_lock.rs
index 92ff4709df..38b13da783 100644
--- a/crates/pa-core/src/kernel/bootstrap/dir_lock.rs
+++ b/crates/pa-core/src/kernel/bootstrap/dir_lock.rs
@@ -4,11 +4,17 @@
use std::io::Write;
use std::path::{Path, PathBuf};
+use std::time::Duration;
use super::venv::{
BOOTSTRAP_LOCK_NAME, BOOTSTRAP_LOCK_RETRY_MS, BOOTSTRAP_LOCK_STALE_WITHOUT_PID_MS,
};
+// A PID-only lock cannot distinguish its original owner from an unrelated
+// process that later receives the same PID. Never evict a possibly live
+// bootstrap: bound the caller's wait instead, including for legacy locks.
+const BOOTSTRAP_LOCK_WAIT: Duration = Duration::from_secs(120);
+
fn is_process_alive(pid: u32) -> bool {
crate::platform::process::pid_exists(pid)
}
@@ -115,6 +121,7 @@ pub(crate) async fn acquire_bootstrap_lock(venv: &Path) -> anyhow::Result<impl D
BOOTSTRAP_LOCK_NAME
));
std::fs::create_dir_all(lock_dir.parent().unwrap_or(Path::new("/")))?;
+ let deadline = tokio::time::Instant::now() + BOOTSTRAP_LOCK_WAIT;
loop {
match try_acquire_dir_lock(&lock_dir)? {
DirLockAttempt::Acquired => {
@@ -127,8 +134,105 @@ pub(crate) async fn acquire_bootstrap_lock(venv: &Path) -> anyhow::Result<impl D
return Ok(Guard(lock_dir));
}
DirLockAttempt::Held | DirLockAttempt::Reclaimed => {
- tokio::time::sleep(std::time::Duration::from_millis(BOOTSTRAP_LOCK_RETRY_MS)).await;
+ if tokio::time::Instant::now() >= deadline {
+ anyhow::bail!(
+ "Timed out after {} seconds waiting for the Python kernel bootstrap lock at {}. \
+ Another Prime Agent process may still be setting up this runtime. \
+ Retry after it finishes. If setup was interrupted, verify that no process \
+ is setting up this runtime before removing this lock and retrying.",
+ BOOTSTRAP_LOCK_WAIT.as_secs(),
+ lock_dir.display()
+ );
+ }
+ tokio::time::sleep_until(deadline.min(
+ tokio::time::Instant::now() + Duration::from_millis(BOOTSTRAP_LOCK_RETRY_MS),
+ ))
+ .await;
}
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test(start_paused = true)]
+ async fn live_pid_file_has_a_bounded_wait_without_removing_the_owner() {
+ let root = tempfile::tempdir().unwrap();
+ let venv = root.path().join("kernel-venv");
+ let lock = root.path().join("kernel-venv.bootstrap.lock");
+ // An unrelated live PID is indistinguishable from a recycled owner.
+ let owner = format!("{}\n", std::process::id());
+ std::fs::write(&lock, &owner).unwrap();
+
+ let result = tokio::time::timeout(
+ BOOTSTRAP_LOCK_WAIT + Duration::from_secs(1),
+ acquire_bootstrap_lock(&venv),
+ )
+ .await
+ .expect("lock acquisition must return an error rather than wait forever");
+ let error = match result {
+ Ok(_) => panic!("must not acquire a live owner's lock"),
+ Err(error) => error.to_string(),
+ };
+ assert!(error.contains("Timed out"), "{error}");
+ assert!(error.contains(&lock.display().to_string()), "{error}");
+ assert_eq!(std::fs::read_to_string(&lock).unwrap(), owner);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn legacy_directory_has_a_bounded_wait_without_removing_the_owner() {
+ let root = tempfile::tempdir().unwrap();
+ let venv = root.path().join("kernel-venv");
+ let lock = root.path().join("kernel-venv.bootstrap.lock");
+ std::fs::create_dir(&lock).unwrap();
+ let owner = format!("{}\n", std::process::id());
+ std::fs::write(lock.join("pid"), &owner).unwrap();
+
+ let result = tokio::time::timeout(
+ BOOTSTRAP_LOCK_WAIT + Duration::from_secs(1),
+ acquire_bootstrap_lock(&venv),
+ )
+ .await
+ .expect("legacy lock acquisition must also have a deadline");
+ assert!(result.is_err());
+ assert_eq!(std::fs::read_to_string(lock.join("pid")).unwrap(), owner);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn an_owner_releasing_before_the_deadline_allows_acquisition() {
+ let root = tempfile::tempdir().unwrap();
+ let venv = root.path().join("kernel-venv");
+ let lock = root.path().join("kernel-venv.bootstrap.lock");
+ let owner = acquire_bootstrap_lock(&venv).await.unwrap();
+ let mut waiter = Box::pin(acquire_bootstrap_lock(&venv));
+ assert!(matches!(
+ futures::poll!(&mut waiter),
+ std::task::Poll::Pending
+ ));
+ drop(owner);
+ let successor = waiter.await.unwrap();
+ assert!(lock.exists());
+ drop(successor);
+ assert!(!lock.exists());
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn cancelling_a_waiter_preserves_the_owner_and_cleans_candidates() {
+ let root = tempfile::tempdir().unwrap();
+ let venv = root.path().join("kernel-venv");
+ let lock = root.path().join("kernel-venv.bootstrap.lock");
+ let owner = acquire_bootstrap_lock(&venv).await.unwrap();
+ let mut waiter = Box::pin(acquire_bootstrap_lock(&venv));
+ assert!(matches!(
+ futures::poll!(&mut waiter),
+ std::task::Poll::Pending
+ ));
+ drop(waiter);
+ assert!(lock.exists());
+ assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 1);
+ drop(owner);
+ assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0);
+ }
+}
diff --git a/crates/pa-core/src/kernel/bootstrap/mod.rs b/crates/pa-core/src/kernel/bootstrap/mod.rs
index f3b598b35d..184087633e 100644
--- a/crates/pa-core/src/kernel/bootstrap/mod.rs
+++ b/crates/pa-core/src/kernel/bootstrap/mod.rs
@@ -220,6 +220,14 @@ async fn ensure_kernel_python_uncached(
}
let venv = resolve_writable_kernel_venv_dir()?;
+ ensure_kernel_venv(options, python_skills, venv).await
+}
+
+async fn ensure_kernel_venv(
+ options: &EnsureKernelPythonOptions,
+ python_skills: &[BootstrapPythonSkill],
+ venv: PathBuf,
+) -> anyhow::Result<PathBuf> {
let python = kernel_venv_python(&venv);
let python_str = python.to_string_lossy().to_string();
let runtime_identity = resolve_runtime_identity();
@@ -227,7 +235,7 @@ async fn ensure_kernel_python_uncached(
return Ok(python);
}
- let release_lock = acquire_bootstrap_lock(&venv).await;
+ let release_lock = acquire_bootstrap_lock(&venv).await?;
let result = async {
if kernel_ready(&python_str, &venv, &runtime_identity, python_skills) {
return Ok(python);
@@ -260,3 +268,42 @@ async fn ensure_kernel_python_uncached(
options.report("✓ ready");
result.map_err(|error| format_bootstrap_failure(&error))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test(start_paused = true)]
+ async fn lock_timeout_prevents_venv_rebuild() {
+ let root = tempfile::tempdir().unwrap();
+ let venv = root.path().join("kernel-venv");
+ std::fs::create_dir(&venv).unwrap();
+ let sentinel = venv.join("owner-state");
+ std::fs::write(&sentinel, "another bootstrap owns this venv").unwrap();
+ let owner = acquire_bootstrap_lock(&venv).await.unwrap();
+ let options = EnsureKernelPythonOptions {
+ // Fail before any destructive operation or network access if the
+ // caller regresses and enters setup without acquiring the lock.
+ on_progress: Some(Arc::new(|message| {
+ panic!("bootstrap must stop at the lock error, got progress: {message}");
+ })),
+ ..Default::default()
+ };
+
+ let error = tokio::time::timeout(
+ std::time::Duration::from_secs(121),
+ ensure_kernel_venv(&options, &[], venv),
+ )
+ .await
+ .expect("lock acquisition must have a bounded wait")
+ .expect_err("a lock timeout must propagate to the caller");
+
+ assert!(error.to_string().contains("Timed out"), "{error}");
+ assert_eq!(
+ std::fs::read_to_string(sentinel).unwrap(),
+ "another bootstrap owns this venv"
+ );
+ assert!(root.path().join("kernel-venv.bootstrap.lock").exists());
+ drop(owner);
+ }
+}