Skip to content

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

Rust

fix(kernel): refuse raw-fd snapshot restore and bound the runtime bootstrap (#3346)

Sebastian Müller672085e883c2
diff --git a/.changes/fix-kernel-wedge-snapshot-fd.md b/.changes/fix-kernel-wedge-snapshot-fd.md
new file mode 100644
index 0000000000..33c47ed2d2
--- /dev/null
+++ b/.changes/fix-kernel-wedge-snapshot-fd.md
@@ -0,0 +1 @@
+- Session resume no longer wedges when the saved state held a `bash()` handle: snapshots skip live process handles, whose restore reopened a stale fd number and killed the restored kernel's event loop. Restoring also refuses to reopen any pickled raw fd number (legacy snapshots, user pipe objects), failing just that saved name instead of the whole kernel. A kernel that drops a protocol frame now logs it to kernel-stderr.log instead of failing silently. A timed-out request whose code was still being sent to a stalled kernel no longer leaves the kernel permanently busy; the kernel restarts instead.
diff --git a/crates/pa-core/src/kernel/manager/mod.rs b/crates/pa-core/src/kernel/manager/mod.rs
index 7884f1490c..e41dc122f8 100644
--- a/crates/pa-core/src/kernel/manager/mod.rs
+++ b/crates/pa-core/src/kernel/manager/mod.rs
@@ -645,8 +645,28 @@ impl ReplKernelManager {
/// Returns an error when the in-flight protocol repair fails, or when the
/// enqueued execution fails (kernel error, timeout, or aborted request).
pub async fn execute(&self, code: &str, opts: ExecuteOptions) -> anyhow::Result<ExecuteResult> {
+ self.execute_bounded(code, opts, /*execution_timeout_ms*/ None)
+ .await
+ }
+
+ /// The bounded entry onto the shared execute path: the provisioner's
+ /// runtime bootstrap passes its bound, so a lost bootstrap frame fails
+ /// the boot loudly instead of parking it forever.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error when the in-flight protocol repair fails, or when the
+ /// enqueued execution fails (kernel error, timeout, or aborted request).
+ pub(crate) async fn execute_bounded(
+ &self,
+ code: &str,
+ opts: ExecuteOptions,
+ execution_timeout_ms: Option<u64>,
+ ) -> anyhow::Result<ExecuteResult> {
self.wait_for_protocol_repair(opts.signal.as_ref()).await?;
- let result = self.enqueue_execute(code, opts, None).await?;
+ let result = self
+ .enqueue_execute(code, opts, execution_timeout_ms)
+ .await?;
if result.result.status == ExecuteStatus::Ok {
self.schedule_snapshot();
}
diff --git a/crates/pa-core/src/kernel/manager/requests.rs b/crates/pa-core/src/kernel/manager/requests.rs
index cad123544f..6d2b6cee0c 100644
--- a/crates/pa-core/src/kernel/manager/requests.rs
+++ b/crates/pa-core/src/kernel/manager/requests.rs
@@ -219,8 +219,18 @@ impl ReplKernelManager {
let Some(inner) = inner.upgrade() else {
return;
};
- let _ = inner.interrupt(Some(&execution.request_id)).await;
- tokio::time::sleep(Duration::from_millis(KERNEL_ABORT_GRACE_MS)).await;
+ // A blocked request write holds the stdin mutex. Do not let an
+ // interrupt queued behind it postpone the force-abort forever.
+ // Dropping the interrupt at this deadline cannot tear its
+ // frame: the ~60-byte frame is one write on a non-blocking
+ // pipe, all-or-nothing below PIPE_BUF.
+ let deadline =
+ tokio::time::Instant::now() + Duration::from_millis(KERNEL_ABORT_GRACE_MS);
+ tokio::select! {
+ _ = inner.interrupt(Some(&execution.request_id)) => {},
+ () = tokio::time::sleep_until(deadline) => {}
+ }
+ tokio::time::sleep_until(deadline).await;
// The execution stays active until its done event arrives;
// clearing it early would let a new cell race the interrupted
// one (see busy-after-interrupt).
@@ -235,7 +245,7 @@ impl ReplKernelManager {
let mut frame = request.to_json();
frame["id"] = json!(request_id);
- let mut send_task = {
+ let (mut send_task, stdin_retire) = {
let writer = lock(&self.inner.child).as_ref().map(|c| c.stdin.clone());
let Some(stdin) = writer else {
{
@@ -246,7 +256,11 @@ impl ReplKernelManager {
};
let mut line = frame.to_string();
line.push('\n');
- tokio::spawn(async move {
+ // The retire handle below must name this exact kernel's stream;
+ // re-deriving it from `child` later could reach a restarted
+ // kernel's stdin.
+ let stdin_retire = stdin.clone();
+ let send_task = tokio::spawn(async move {
let mut guard = stdin.lock().await;
let Some(stdin) = guard.as_mut() else {
return Err(anyhow!("Kernel stdin is not connected"));
@@ -254,7 +268,8 @@ impl ReplKernelManager {
stdin.write_all(line.as_bytes()).await?;
stdin.flush().await?;
Ok(())
- })
+ });
+ (send_task, stdin_retire)
};
let mut settled_result: Option<anyhow::Result<InternalExecuteResult>> = None;
@@ -272,6 +287,19 @@ impl ReplKernelManager {
};
let early_settle = matches!(&settled, Ok(result) if result.result.status == ExecuteStatus::Aborted);
if early_settle {
+ // A blocked request writer would otherwise retain stdin's
+ // mutex after the caller returned, wedging shutdown too.
+ send_task.abort();
+ // A cancelled write leaves the request unsent or
+ // torn: the runtime never sees it, its execution never
+ // settles, and every later request fails as busy.
+ // Retire stdin so the kernel is replaced.
+ if matches!(send_task.await, Err(e) if e.is_cancelled()) {
+ // Detached: a queued stdin writer must not park this request.
+ tokio::spawn(async move {
+ *stdin_retire.lock().await = None;
+ });
+ }
settled_result = Some(settled);
} else {
// Surfacing a failed write outranks the settled cell.
@@ -312,6 +340,128 @@ impl ReplKernelManager {
mod tests {
use super::append_truncated;
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn bounded_execute_settles_when_kernel_stops_reading_stdin() {
+ use super::*;
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let python = dir.path().join("ready-but-not-reading");
+ std::fs::write(
+ &python,
+ "#!/usr/bin/env python3\nimport json, time\nprint(json.dumps({'event': 'ready', 'protocol': 3, 'python': '3.13.0'}), flush=True)\ntime.sleep(30)\n",
+ )
+ .expect("write fake kernel");
+ std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755))
+ .expect("chmod fake kernel");
+ let manager = ReplKernelManager::new(crate::kernel::shared::KernelManagerOptions {
+ python: Some(python),
+ ..Default::default()
+ });
+ manager
+ .start(KernelStartOptions::default())
+ .await
+ .expect("ready handshake");
+ // Larger than the stdin pipe: the request writer holds its mutex while
+ // waiting for this non-reader, so the interrupt write cannot acquire it.
+ let code = "x".repeat(1024 * 1024);
+ let result = tokio::time::timeout(
+ Duration::from_secs(4),
+ manager.execute_bounded(&code, ExecuteOptions::default(), Some(100)),
+ )
+ .await;
+ let result = result
+ .expect("timeout must settle even when the interrupt cannot write")
+ .expect("bounded execute returns a result");
+ assert_eq!(result.status, ExecuteStatus::Aborted);
+ let stdin = manager
+ .inner
+ .child
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ .expect("child exists")
+ .stdin
+ .clone();
+ assert!(
+ stdin.try_lock().is_ok(),
+ "the aborted request must release the stdin writer lock"
+ );
+ manager.kill();
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn cancelled_request_write_retires_the_kernel() {
+ use super::*;
+ use std::os::unix::fs::PermissionsExt;
+
+ // Protocol v3: ready, then idles without reading stdin until the
+ // sibling "go" file appears, then answers execute frames, ignores
+ // glued garbage (a torn prefix makes any next line invalid), and
+ // never answers interrupts (that would settle the aborted execution).
+ const TORN_FRAME_RUNTIME: &str = r#"#!/usr/bin/env python3
+import json
+import os
+import sys
+import time
+
+print(json.dumps({"event": "ready", "protocol": 3, "python": "3.13.0"}), flush=True)
+go = os.path.join(os.path.dirname(os.path.abspath(__file__)), "go")
+while not os.path.exists(go):
+ time.sleep(0.01)
+for line in sys.stdin:
+ try:
+ req = json.loads(line)
+ except Exception:
+ continue
+ if req.get("type") == "execute":
+ print(json.dumps({"event": "done", "id": req.get("id"), "status": "ok"}), flush=True)
+"#;
+
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let python = dir.path().join("torn-frame-kernel");
+ std::fs::write(&python, TORN_FRAME_RUNTIME).expect("write fake kernel");
+ std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755))
+ .expect("chmod fake kernel");
+ let manager = ReplKernelManager::new(crate::kernel::shared::KernelManagerOptions {
+ python: Some(python),
+ ..Default::default()
+ });
+ manager
+ .start(KernelStartOptions::default())
+ .await
+ .expect("ready handshake");
+ // Larger than the stdin pipe, so the 100ms bound force-aborts while
+ // the request write is still mid-flight and tears the frame.
+ let code = "x".repeat(1024 * 1024);
+ let first = tokio::time::timeout(
+ Duration::from_secs(4),
+ manager.execute_bounded(&code, ExecuteOptions::default(), Some(100)),
+ )
+ .await
+ .expect("the bounded execute must settle")
+ .expect("bounded execute returns a result");
+ assert_eq!(first.status, ExecuteStatus::Aborted);
+ // Let the fake kernel read: EOF (retired stream) exits it, while
+ // glued garbage keeps the unfixed kernel Running. The request below
+ // observes the outcome: shutdown error or busy after the 5s window.
+ std::fs::write(dir.path().join("go"), b"").expect("write go file");
+ // Only the wait matters here; is_defunct() below discriminates.
+ let _ = tokio::time::timeout(
+ Duration::from_secs(10),
+ manager.execute_bounded("1+1", ExecuteOptions::default(), None),
+ )
+ .await
+ .expect("the next request must settle");
+ assert!(
+ manager.is_defunct(),
+ "a cancelled request write must retire the kernel"
+ );
+ manager.kill();
+ }
+
#[test]
fn capped_stream_matches_original_unicode_and_frame_semantics() {
let frames = ["", "a", "é", "🍁", "xy", "é🍁abc", "", "tail"];
diff --git a/crates/pa-core/src/kernel/manager/teardown.rs b/crates/pa-core/src/kernel/manager/teardown.rs
index 4e28721e67..4eaf61760f 100644
--- a/crates/pa-core/src/kernel/manager/teardown.rs
+++ b/crates/pa-core/src/kernel/manager/teardown.rs
@@ -98,31 +98,46 @@ impl Inner {
.insert(id.clone(), done_tx);
request_id = Some(id.clone());
let frame = json!({ "type": "shutdown", "id": id });
- let send_result = self.write_line(&frame).await;
- if let Err(error) = send_result {
- self.append_diagnostic(&format!("failed to send shutdown request: {error:#}"));
- }
- let graceful_reply = async {
- let _ = done_rx.await;
- };
- let deadline = tokio::time::sleep(Duration::from_millis(KERNEL_SHUTDOWN_TIMEOUT_MS));
- let mut failed = false;
- tokio::select! {
- () = graceful_reply => {}
- () = self.wait_for_kernel_exit() => {}
- () = deadline => {
- failed = true;
- self.append_diagnostic(&format!(
- "graceful shutdown failed (killing instead): Kernel did not shut down within {KERNEL_SHUTDOWN_TIMEOUT_MS}ms"
- ));
+ let send_result = tokio::time::timeout(
+ Duration::from_millis(KERNEL_SHUTDOWN_TIMEOUT_MS),
+ self.write_line(&frame),
+ )
+ .await;
+ let sent = match send_result {
+ Ok(Ok(())) => true,
+ Ok(Err(error)) => {
+ self.append_diagnostic(&format!("failed to send shutdown request: {error:#}"));
+ false
}
- }
- if !failed {
+ Err(_) => {
+ self.append_diagnostic("timed out sending shutdown request");
+ false
+ }
+ };
+ if sent {
+ let graceful_reply = async {
+ let _ = done_rx.await;
+ };
let deadline =
tokio::time::sleep(Duration::from_millis(KERNEL_SHUTDOWN_TIMEOUT_MS));
+ let mut failed = false;
tokio::select! {
+ () = graceful_reply => {}
() = self.wait_for_kernel_exit() => {}
- () = deadline => {}
+ () = deadline => {
+ failed = true;
+ self.append_diagnostic(&format!(
+ "graceful shutdown failed (killing instead): Kernel did not shut down within {KERNEL_SHUTDOWN_TIMEOUT_MS}ms"
+ ));
+ }
+ }
+ if !failed {
+ let deadline =
+ tokio::time::sleep(Duration::from_millis(KERNEL_SHUTDOWN_TIMEOUT_MS));
+ tokio::select! {
+ () = self.wait_for_kernel_exit() => {}
+ () = deadline => {}
+ }
}
}
}
diff --git a/crates/pa-core/src/kernel/provisioner.rs b/crates/pa-core/src/kernel/provisioner.rs
index 8da86d6452..7d2fcfe947 100644
--- a/crates/pa-core/src/kernel/provisioner.rs
+++ b/crates/pa-core/src/kernel/provisioner.rs
@@ -27,7 +27,7 @@ use crate::kernel::manager::{KernelStartOptions, ReplKernelManager};
use crate::kernel::shared::ExecuteStatus;
use crate::kernel::shared::{
ExecuteOptions, HostRequestHandlers, KernelManagerOptions, KernelShutdownOptions,
- KernelSnapshotConfig,
+ KernelSnapshotConfig, BOOTSTRAP_EXECUTION_TIMEOUT_MS,
};
use crate::kernel::state_snapshot::RestoreResult;
use crate::kernel::state_snapshot::{manifest_path_in, snapshot_path_in};
@@ -1172,12 +1172,13 @@ async fn start_kernel_impl(
// settles the cell aborted, and the aborted-status arm below tears the
// kernel down instead of leaking it into a disposed provisioner.
let bootstrap = manager
- .execute(
+ .execute_bounded(
&bootstrap_code,
ExecuteOptions {
signal: Some(dispose_signal.clone()),
..Default::default()
},
+ Some(BOOTSTRAP_EXECUTION_TIMEOUT_MS),
)
.await;
match bootstrap {
@@ -1249,9 +1250,20 @@ async fn start_kernel_impl(
drain_host_requests: true,
})
.await;
- return Err(anyhow!(
- "Failed to initialize rlm runtime in the Python kernel:\n{details}"
- ));
+ // An aborted bootstrap with a live dispose signal is the bound
+ // firing on a kernel that stopped answering: name the lost
+ // bootstrap instead of a bare runtime failure.
+ let error = if bootstrap.status == ExecuteStatus::Aborted
+ && !dispose_signal.is_aborted()
+ {
+ anyhow!(
+ "Failed to initialize rlm runtime in the Python kernel: \
+ the runtime bootstrap did not finish within {BOOTSTRAP_EXECUTION_TIMEOUT_MS}ms:\n{details}"
+ )
+ } else {
+ anyhow!("Failed to initialize rlm runtime in the Python kernel:\n{details}")
+ };
+ return Err(error);
}
Err(error) => {
let (snapshot_policy, _teardown_gate) = hold_snapshot_flush_gate(inner, memo);
@@ -1672,4 +1684,118 @@ mod tests {
"ensure must surface the spawn cause: {error:#}"
);
}
+
+ /// A ready kernel that stops reading stdin must not wedge its bootstrap
+ /// request or the failed boot's shutdown behind a full pipe.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn nonreading_kernel_fails_bootstrap_without_parking_shutdown() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let python = dir.path().join("ready-but-not-reading");
+ std::fs::write(
+ &python,
+ "#!/usr/bin/env python3\nimport json, time\nprint(json.dumps({'event': 'ready', 'protocol': 3, 'python': '3.13.0'}), flush=True)\ntime.sleep(30)\n",
+ )
+ .expect("write fake kernel");
+ std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755))
+ .expect("chmod fake kernel");
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(python),
+ python_skills: vec![KernelPythonSkill {
+ name: "oversized".into(),
+ import_name: "x".repeat(1024 * 1024),
+ package_path: dir.path().into(),
+ pyproject_path: dir.path().join("pyproject.toml"),
+ }],
+ ..Default::default()
+ },
+ );
+ let error = tokio::time::timeout(
+ std::time::Duration::from_secs(9),
+ provisioner.ensure(None, None),
+ )
+ .await
+ .expect("timed out bootstrap must not park during failed-boot cleanup")
+ .expect_err("kernel never reads bootstrap");
+ assert!(format!("{error:#}").contains("runtime bootstrap did not finish"));
+ assert!(!provisioner.has_running_kernel());
+ }
+
+ /// A kernel that answers the ready handshake but never answers the
+ /// bootstrap execute (the wedged-kernel shape: the frame is lost inside
+ /// the kernel) fails `ensure` with the bound's message instead of parking
+ /// forever, tears its kernel down, and does not auto-retry the fatal
+ /// failure.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn silent_bootstrap_fails_bounded_and_leaves_no_kernel() {
+ use std::os::unix::fs::PermissionsExt;
+
+ // Speaks protocol v3: answers the ready handshake, stays silent on
+ // every execute (the runtime bootstrap included), and answers the
+ // shutdown frame so a teardown does not wait out its kill deadline.
+ const SILENT_BOOTSTRAP_RUNTIME: &str = r#"#!/usr/bin/env python3
+import json
+import os
+import sys
+
+base = os.path.dirname(os.path.abspath(__file__))
+with open(os.path.join(base, "starts"), "a") as f:
+ f.write("x")
+print(json.dumps({"event": "ready", "protocol": 3, "python": "3.13.0"}), flush=True)
+for line in sys.stdin:
+ try:
+ req = json.loads(line)
+ except Exception:
+ continue
+ if req.get("type") == "shutdown":
+ print(json.dumps({"event": "done", "id": req.get("id"), "status": "ok"}), flush=True)
+ break
+"#;
+
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let python = dir.path().join("fake-kernel");
+ std::fs::write(&python, SILENT_BOOTSTRAP_RUNTIME).expect("write fake runtime");
+ std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755))
+ .expect("chmod fake runtime");
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(python),
+ ..Default::default()
+ },
+ );
+
+ let outcome = tokio::time::timeout(
+ std::time::Duration::from_secs(10),
+ provisioner.ensure(None, None),
+ )
+ .await
+ .expect("the bounded bootstrap must settle the boot")
+ .expect_err("a kernel that never answers the bootstrap must not report success");
+ let chain = format!("{outcome:#}");
+ assert!(
+ chain.contains("Failed to initialize rlm runtime"),
+ "{chain}"
+ );
+ assert!(
+ chain.contains(&format!(
+ "the runtime bootstrap did not finish within {BOOTSTRAP_EXECUTION_TIMEOUT_MS}ms"
+ )),
+ "{chain}"
+ );
+ assert!(
+ !provisioner.has_running_kernel(),
+ "the failed boot must tear its kernel down"
+ );
+ assert_eq!(
+ std::fs::metadata(dir.path().join("starts")).map_or(0, |m| m.len()),
+ 1,
+ "the fatal classification must not auto-retry the boot"
+ );
+ }
}
diff --git a/crates/pa-core/src/kernel/shared.rs b/crates/pa-core/src/kernel/shared.rs
index 3effdb648b..cbc9b1c2ac 100644
--- a/crates/pa-core/src/kernel/shared.rs
+++ b/crates/pa-core/src/kernel/shared.rs
@@ -18,6 +18,14 @@ pub const DEFAULT_SNAPSHOT_DEBOUNCE_MS: u64 = 1_500;
pub const SNAPSHOT_EXECUTION_TIMEOUT_MS: u64 = 5_000;
/// Restore deserializes everything a snapshot serializes: bounded like the repair step.
pub const RESTORE_EXECUTION_TIMEOUT_MS: u64 = 30_000;
+/// The provisioner's runtime bootstrap imports the runtime and skills in one
+/// cell: bounded like the restore step, so a lost bootstrap frame fails the
+/// boot loudly instead of parking it forever. Shrunk in test builds so the
+/// regression test does not wait out the production bound.
+#[cfg(not(test))]
+pub const BOOTSTRAP_EXECUTION_TIMEOUT_MS: u64 = 30_000;
+#[cfg(test)]
+pub const BOOTSTRAP_EXECUTION_TIMEOUT_MS: u64 = 500;
pub const KERNEL_ABORT_GRACE_MS: u64 = 1_000;
pub const KERNEL_BUSY_REUSE_WAIT_MS: u64 = 5_000;
pub const KERNEL_BUSY_INTERRUPT_INTERVAL_MS: u64 = 500;
diff --git a/prime-agent-runtime/src/rlm/bash.py b/prime-agent-runtime/src/rlm/bash.py
index 5e17b1ae32..79e285f572 100644
--- a/prime-agent-runtime/src/rlm/bash.py
+++ b/prime-agent-runtime/src/rlm/bash.py
@@ -22,7 +22,7 @@ from collections import deque
from collections.abc import Callable, Generator
from dataclasses import dataclass
from datetime import datetime, timezone
-from typing import Any, cast
+from typing import Any, NoReturn, cast
from . import _winjob
@@ -953,6 +953,12 @@ class BashHandle:
if completed:
self._note_result_consumed(current_task)
+ def __reduce__(self) -> NoReturn:
+ # Reviving a handle would resurrect a stale pid and raw fd numbers: dill
+ # restores the pickled pipe by reopening its fd number in the new kernel
+ # (and closing it), so a snapshot must never persist a live handle.
+ raise TypeError("cannot pickle 'BashHandle' object: live process handle")
+
def __repr__(self) -> str:
state = f"exit_code={self._result.exit_code}" if self._result else "running"
return f"<BashHandle pid={self._pid} {state} command={self.command!r}>"
diff --git a/prime-agent-runtime/src/rlm/repl.py b/prime-agent-runtime/src/rlm/repl.py
index 5293a30913..fd76e26d80 100644
--- a/prime-agent-runtime/src/rlm/repl.py
+++ b/prime-agent-runtime/src/rlm/repl.py
@@ -18,6 +18,7 @@ import io
import json
import linecache
import os
+import pickle
import platform
import select
import signal
@@ -66,6 +67,9 @@ _RESTORE_SKIP = {"In", "Out", "get_ipython"}
_last_snapshot_target: dict[str, Any] | None = None
_protocol_fd: int = -1
+# The host's stderr before _setup_fds captures fd 2: the only channel that can
+# report a dropped protocol frame without feeding it back into the protocol.
+_host_stderr_fd: int = -1
_write_lock = threading.Lock()
_loop: asyncio.AbstractEventLoop | None = None
_serve_task: asyncio.Task[Any] | None = None
@@ -114,8 +118,11 @@ def _send(event: dict[str, Any]) -> None:
try:
while view:
view = view[os.write(_protocol_fd, view) :]
- except OSError:
- pass
+ except OSError as err:
+ try:
+ os.write(_host_stderr_fd, f"rlm.repl: dropped protocol frame: {err}\n".encode())
+ except OSError:
+ pass
def _check_payload(event: str, data: dict[str, Any]) -> None:
@@ -1060,6 +1067,31 @@ def _revive_with_live_globals(
return rebound
+def _snapshot_unpickler(dill: Any) -> type:
+ """Unpickler that refuses to reopen a pickled raw fd number in this kernel.
+
+ dill serializes a pipe/socket-backed file as its fd NUMBER; restoring a
+ saved closed one reopens that number here and closes it again, killing
+ whatever owns the fd now (e.g. the event loop's self-pipe). The refusal
+ fails just that record; every other name still restores.
+ """
+ create_filehandle = dill._dill._create_filehandle
+
+ def refuse_raw_fd(name: Any, *args: Any) -> Any:
+ if isinstance(name, int):
+ raise pickle.UnpicklingError(
+ f"refusing to reopen raw file descriptor {name} from a snapshot"
+ )
+ return create_filehandle(name, *args)
+
+ class GuardedUnpickler(dill.Unpickler):
+ def find_class(self, module: str, name: str) -> Any:
+ target = super().find_class(module, name)
+ return refuse_raw_fd if target is create_filehandle else target
+
+ return GuardedUnpickler
+
+
def _restore_state(
ns: dict[str, Any],
path: str,
@@ -1073,6 +1105,7 @@ def _restore_state(
import dill
except Exception as err: # noqa: BLE001
return {"error": f"dill unavailable: {err}"}
+ unpickler = _snapshot_unpickler(dill)
try:
with open(path, "rb") as fh:
if fh.read(len(_SNAPSHOT_MAGIC)) == _SNAPSHOT_MAGIC:
@@ -1088,7 +1121,7 @@ def _restore_state(
else:
# Legacy: one dill-pickled dict; old snapshot files must keep restoring.
fh.seek(0)
- payload = dill.load(fh)
+ payload = unpickler(fh).load()
except Exception as err: # noqa: BLE001 - a corrupt snapshot yields an empty restore
return {"error": f"load failed: {_safe_str(err)}"}
if not isinstance(payload, dict):
@@ -1100,7 +1133,7 @@ def _restore_state(
if name in _RESTORE_SKIP:
continue
try:
- staged[name] = dill.loads(blob)
+ staged[name] = unpickler(io.BytesIO(blob)).load()
except Exception as err: # noqa: BLE001 - revive every other name regardless
failed.append({"name": name, "reason": f"{type(err).__name__}: {_safe_str(err)[:200]}"})
# Revive every staged name before parking: a failure must never abort the
@@ -1668,9 +1701,11 @@ _pump_err: _Pump
def _setup_fds() -> int:
"""Reserve stdout for the protocol; route fds 1/2 through captured pipes."""
- global _protocol_fd, _pump_out, _pump_err
+ global _protocol_fd, _pump_out, _pump_err, _host_stderr_fd
_protocol_fd = os.dup(1)
os.set_inheritable(_protocol_fd, False)
+ _host_stderr_fd = os.dup(2)
+ os.set_inheritable(_host_stderr_fd, False)
out_r, out_w = os.pipe()
err_r, err_w = os.pipe()
os.dup2(out_w, 1)
diff --git a/prime-agent-runtime/test/test_repl.py b/prime-agent-runtime/test/test_repl.py
index 117fccc973..cce4c88470 100644
--- a/prime-agent-runtime/test/test_repl.py
+++ b/prime-agent-runtime/test/test_repl.py
@@ -703,6 +703,101 @@ class ReplTest(unittest.TestCase):
self.assertEqual(one(events, "result")["text"], "42")
self.assertEqual(fresh.shutdown(), 0)
+ def test_snapshot_skips_off_cell_bash_handles(self):
+ # A handle created outside any cell (here: a plain thread) carries no
+ # unpicklable cell-task reference, so dill would happily persist its
+ # pipe fds; restoring a saved fd number reopens (and closes) it in the
+ # new kernel, killing whatever owns the fd there.
+ with tempfile.TemporaryDirectory() as tmp:
+ path = os.path.join(tmp, "kernel-state.dill")
+ manifest_path = os.path.join(tmp, "kernel-state.json")
+ setup = (
+ "import threading\n"
+ "from rlm import bash\n"
+ "hs = []\n"
+ "t = threading.Thread(target=lambda: hs.append(bash('echo done-h1')))\n"
+ "t.start()\n"
+ "t.join()\n"
+ "h1 = hs[0]\n"
+ "await h1\n"
+ "del t\n"
+ "keep = 1\n"
+ )
+ self.assertEqual(one(self.repl.execute("s1", setup), "done")["status"], "ok")
+ self.repl.send(
+ {"type": "snapshot", "id": "s2", "path": path, "manifest_path": manifest_path}
+ )
+ done = one(self.repl.until_done("s2"), "done")
+ self.assertEqual(done["status"], "ok")
+ skipped = {entry["name"]: entry["reason"] for entry in done["skipped"]}
+ self.assertEqual(sorted(skipped), ["h1", "hs"])
+ for reason in skipped.values():
+ self.assertIn("live process handle", reason)
+ self.assertIn("keep", done["saved"])
+
+ @unittest.skipIf(os.name == "nt", "pickled raw fd numbers are a POSIX landmine")
+ def test_restore_refuses_to_reopen_pickled_raw_fds(self):
+ # dill serializes a pipe-backed file as its raw fd NUMBER; restoring a
+ # saved closed one reopens that number in the new kernel and closes it
+ # again, killing whatever owns the fd now (the event loop's self-pipe).
+ import dill
+
+ sys.path.insert(0, SRC)
+ self.addCleanup(sys.path.remove, SRC)
+ from rlm import repl as repl_module
+
+ fresh = ReplProcess()
+ self.addCleanup(fresh.close)
+ fresh.ready()
+ # The loop's self-pipe READ end is the wakeup fd the selector waits on:
+ # reopening its number from a snapshot and closing it parks the kernel
+ # in select forever (nothing left can wake the loop).
+ events = fresh.execute(
+ "fd", "import asyncio\nasyncio.get_running_loop()._ssock.fileno()"
+ )
+ fd = int(one(events, "result")["text"])
+
+ class Landmine:
+ def __reduce__(self):
+ # The exact reconstructor dill saves for a closed pipe-backed
+ # file: name is the fd NUMBER.
+ return (dill._dill._create_filehandle, (fd, "rb", 0, True, open, False, 0, b""))
+
+ with tempfile.TemporaryDirectory() as tmp:
+ path = os.path.join(tmp, "kernel-state.dill")
+ manifest_path = os.path.join(tmp, "kernel-state.json")
+ result = repl_module._snapshot_state(
+ {"boom": Landmine(), "keep": 7},
+ path,
+ manifest_path,
+ repl_module.DEFAULT_SNAPSHOT_MAX_BYTES,
+ repl_module.DEFAULT_SNAPSHOT_MAX_VARIABLE_BYTES,
+ False,
+ )
+ self.assertEqual(result["saved"], ["boom", "keep"])
+
+ fresh.send({"type": "restore", "id": "r1", "path": path})
+ done = one(fresh.until_done("r1"), "done")
+ self.assertEqual(done["status"], "ok")
+ failed = {entry["name"]: entry["reason"] for entry in done["failed"]}
+ self.assertIn(f"refusing to reopen raw file descriptor {fd}", failed["boom"])
+ self.assertEqual(done["restored"], ["keep"])
+ # The bare await parks the loop with no timer of its own: only a
+ # live self-pipe wakeup can resolve it, and if the guard regressed
+ # the request would never be served at all (the harness's read
+ # timeout bounds that failure).
+ probe = (
+ "import asyncio, threading\n"
+ "loop = asyncio.get_running_loop()\n"
+ "fut = loop.create_future()\n"
+ "threading.Timer(0.3, lambda: loop.call_soon_threadsafe(\n"
+ " lambda: fut.done() or fut.set_result('woken'))).start()\n"
+ "await fut\n"
+ )
+ events = fresh.execute("wakeup-probe", probe)
+ self.assertEqual(one(events, "done")["status"], "ok")
+ self.assertEqual(one(events, "result")["text"], "'woken'")
+
def test_stdin_eof_flushes_final_snapshot(self):
# Host death (EOF, no shutdown request) must persist the namespace
# tail that postdates the last explicit snapshot.
@@ -2346,24 +2441,30 @@ class RestoreApplyShieldTest(unittest.TestCase):
signal.raise_signal(signal.SIGINT)
def test_sigint_during_staging_leaves_namespace_unchanged(self):
- import dill
-
+ from rlm import repl as repl_module
from rlm.repl import _restore_state
- real_loads = dill.loads
calls = {"n": 0}
- def loads_then_sigint(blob):
- calls["n"] += 1
- if calls["n"] == 2:
- # Synchronous SIGINT mid-deserialize: nothing may have touched ns yet.
- signal.raise_signal(signal.SIGINT)
- return real_loads(blob)
+ real_unpickler = repl_module._snapshot_unpickler
+
+ def unpickler_then_sigint(dill):
+ guarded = real_unpickler(dill)
+
+ class SigintOnSecondLoad(guarded):
+ def load(self):
+ calls["n"] += 1
+ if calls["n"] == 2:
+ # Synchronous SIGINT mid-deserialize: nothing may have touched ns yet.
+ signal.raise_signal(signal.SIGINT)
+ return super().load()
+
+ return SigintOnSecondLoad
with tempfile.TemporaryDirectory() as tmp:
path = self._write_snapshot(tmp, {"a": 1, "b": 2})
ns = {"a": "old", "unrelated": "keep"}
- with mock.patch.object(dill, "loads", loads_then_sigint):
+ with mock.patch.object(repl_module, "_snapshot_unpickler", unpickler_then_sigint):
with self.assertRaises(KeyboardInterrupt):
_restore_state(ns, path)
# The old namespace is byte-identical: no partial old/new mixture.