A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[RSI, feature] python_repl per-cell watchdog teaches over-budget cells toward bash() (#3691)
Seth Kartenf07099812c4a
diff --git a/crates/pa-core/src/kernel/manager/execution.rs b/crates/pa-core/src/kernel/manager/execution.rsindex 71fcd12457..9edc237a67 100644--- a/crates/pa-core/src/kernel/manager/execution.rs+++ b/crates/pa-core/src/kernel/manager/execution.rs@@ -190,6 +190,21 @@ impl Inner {{status = ExecuteStatus::Aborted;}+ // The watchdog teaches instead of killing: a cell that outlived+ // its budget but still settled ok keeps its ok status and its own+ // result; only a stderr note teaches. A completed cell reported+ // as a timeout error invites a duplicate run of finished work and+ // corrupts error-based telemetry, so the overage must not lie. A+ // cell that failed or was aborted keeps its own outcome, no note.+ let mut stderr = stderr;+ if status == ExecuteStatus::Ok {+ if let Some(note) = cell_watchdog_note(execution) {+ if !stderr.is_empty() {+ stderr.push('\n');+ }+ stderr.push_str(¬e);+ }+ }let mut background_output = std::mem::take(&mut buffers.background_output);buffers.background_output_chars = 0;@@ -275,3 +290,52 @@ impl Inner {true}}++/// The watchdog's teaching note for a cell that outlived its budget, or `None`+/// when the watchdog is off or the cell stayed inside the budget. Measured from+/// the wire write to the settle: queue wait and kernel boot are excluded. The+/// note rides stderr (the kernel lane's degrade-hint precedent) and the cell+/// keeps its ok status: the teaching must not turn a completed cell into a+/// retried timeout.+fn cell_watchdog_note(execution: &ActiveExecution) -> Option<String> {+ let timeout_ms = execution.opts.cell_timeout_ms.filter(|ms| *ms > 0)?;+ let started = (*lock(&execution.cell_started))?;+ let elapsed_ms = started.elapsed().as_millis() as u64;+ if elapsed_ms <= timeout_ms {+ return None;+ }+ Some(format!(+ "[watchdog] Cell exceeded the {} python_repl budget (ran {}). Move long shell work to \+bash() (it auto-backgrounds past its yield window) and split long python work into smaller \+cells. Intentional long awaits (yield_after, rlm.collect timeouts) can ignore this note.",+ humanize_ms(timeout_ms),+ humanize_ms(elapsed_ms),+ ))+}++/// Milliseconds as one plain reading: whole seconds when the value divides,+/// a decimal otherwise, raw milliseconds under one second.+fn humanize_ms(ms: u64) -> String {+ if ms < 1000 {+ format!("{ms}ms")+ } else if ms.is_multiple_of(1000) {+ format!("{}s", ms / 1000)+ } else {+ format!("{}.{:03}s", ms / 1000, ms % 1000)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn humanize_ms_pads_the_millisecond_remainder() {+ assert_eq!(humanize_ms(500), "500ms");+ assert_eq!(humanize_ms(2000), "2s");+ assert_eq!(humanize_ms(60_000), "60s");+ assert_eq!(humanize_ms(1500), "1.500s");+ // A sub-100ms remainder must not read as tenths: 60.005s, not 60.5s.+ assert_eq!(humanize_ms(60_005), "60.005s");+ }+}diff --git a/crates/pa-core/src/kernel/manager/mod.rs b/crates/pa-core/src/kernel/manager/mod.rsindex 6c89a41209..6ee1c11e70 100644--- a/crates/pa-core/src/kernel/manager/mod.rs+++ b/crates/pa-core/src/kernel/manager/mod.rs@@ -113,6 +113,9 @@ pub(crate) struct ActiveExecution {restores_namespace: bool,buffers: Mutex<ExecBuffers>,result_tx: Mutex<Option<oneshot::Sender<anyhow::Result<InternalExecuteResult>>>>,+ /// When the request frame went on the wire: the cell's own wall-clock start,+ /// excluding queue wait and kernel boot. `None` until the write begins.+ cell_started: Mutex<Option<Instant>>,}/// `ExecuteResult` plus the raw fields of the request's `done` event (state ops).@@ -600,6 +603,9 @@ impl ReplKernelManager {let result = self.enqueue_execute(code, opts, execution_timeout_ms).await?;+ // A watchdog-noted cell stayed ok in the kernel and committed its+ // namespace changes: the auto-snapshot applies exactly as for any ok+ // cell, or a crash would revive a namespace missing the cell.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.rsindex e00f594bcc..912c984f92 100644--- a/crates/pa-core/src/kernel/manager/requests.rs+++ b/crates/pa-core/src/kernel/manager/requests.rs@@ -304,6 +304,7 @@ impl ReplKernelManager {restores_namespace,buffers: Mutex::new(buffers),result_tx: Mutex::new(Some(result_tx)),+ cell_started: Mutex::new(None),opts,});{@@ -375,6 +376,9 @@ impl ReplKernelManager {(send_task, stdin_retire)};+ // The cell's own window starts as its frame goes on the wire: boot and+ // queue wait are excluded so a cold kernel cannot trip the watchdog.+ *lock(&execution.cell_started) = Some(Instant::now());let mut settled_result: Option<anyhow::Result<InternalExecuteResult>> = None;let send_outcome: anyhow::Result<()> = {let send_promise = &mut send_task;diff --git a/crates/pa-core/src/kernel/provisioner.rs b/crates/pa-core/src/kernel/provisioner.rsindex 0081f706b0..e5b9919f9c 100644--- a/crates/pa-core/src/kernel/provisioner.rs+++ b/crates/pa-core/src/kernel/provisioner.rs@@ -104,6 +104,11 @@ pub type KernelBootstrapResultHandler = Arc<dyn Fn(KernelBootstrapStats) + Sendpub struct IpythonKernelProvisionerOptions {/// Python override. Must have prime-agent-runtime installed.pub python: Option<PathBuf>,+ /// Per-cell watchdog budget for user `python_repl` cells, in milliseconds+ /// (`None`: the watchdog never arms). The daemon engine resolves it from+ /// settings and disarms it for daemonless sessions; the runtime bootstrap+ /// and internal state ops never arm it.+ pub cell_timeout_ms: Option<u64>,pub env: HashMap<String, String>,/// Command prefix prepended to every kernel `bash()` invocation.pub command_prefix: Option<String>,@@ -278,6 +283,13 @@ impl IpythonKernelProvisioner {self.lock_state().manager.clone()}+ /// The per-cell watchdog budget the kernel executor arms for user cells+ /// (`None`: the watchdog never arms).+ #[must_use]+ pub fn cell_timeout_ms(&self) -> Option<u64> {+ self.inner.options.cell_timeout_ms+ }+/// The Python skills pre-imported at kernel bootstrap.#[cfg(test)]#[must_use]diff --git a/crates/pa-core/src/kernel/shared.rs b/crates/pa-core/src/kernel/shared.rsindex 7cc425f94b..40eb03f813 100644--- a/crates/pa-core/src/kernel/shared.rs+++ b/crates/pa-core/src/kernel/shared.rs@@ -228,6 +228,14 @@ pub struct ExecuteOptions {pub internal: bool,/// The protocol repair's own request; exempt from waiting on the repair it belongs to.pub protocol_repair: bool,+ /// Per-cell watchdog budget in milliseconds. When non-zero, a cell whose own+ /// run (request on the wire -> done event) outlives the budget still settles+ /// ok and keeps its own result; a teaching note is appended to its stderr+ /// instead of a quiet over-budget success. The kernel is never killed: the+ /// note lands only after the cell settles, so the serial execution queue and+ /// the namespace are untouched. `None` and zero disable the watchdog; the+ /// runtime bootstrap never arms it.+ pub cell_timeout_ms: Option<u64>,}/// The error raised when a new cell cannot start because the previouslydiff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex 684ba6e286..bdaf9ba6e8 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -270,6 +270,9 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S// factory host bridge's preflight facts (the daemon `allowedModels`// pin), like the request-timing snapshot above.let factory_allowed_models = settings.get_allowed_models();+ // Captured before `settings` moves into the resource loader: the+ // per-cell watchdog budget (default 60s, `0` disables).+ let python_cell_timeout_ms = settings.get_python_cell_timeout_ms();let (mcp_skill_overrides, mcp_generic_servers, built_manager) =mcp_gating(&settings, config.agent_dir.clone()).await?;let mcp_manager = config@@ -486,6 +489,11 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S.await.map_err(|join| anyhow::anyhow!("websearch key resolve join failed: {join}"))?};+ // The per-cell watchdog: daemon-backed sessions arm the settings budget+ // (default 60s, `0` disables); daemonless sessions keep `await bash()`+ // unbounded by design (#3523), so their cells are never annotated.+ let cell_timeout_ms =+ super::runtime_wiring::arm_cell_timeout_ms(config.daemonless, python_cell_timeout_ms);let provisioner = super::runtime_wiring::kernel_provisioner(session_id,handlers,@@ -496,6 +504,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Skernel_command_prefix,serper_api_key,session_artifact_dir,+ cell_timeout_ms,on_restore,config.on_background_work_settled.clone(),on_unavailable_skills,diff --git a/crates/pa-core/src/session_engine/runtime_wiring.rs b/crates/pa-core/src/session_engine/runtime_wiring.rsindex 25757a785b..880bf5bf60 100644--- a/crates/pa-core/src/session_engine/runtime_wiring.rs+++ b/crates/pa-core/src/session_engine/runtime_wiring.rs@@ -253,6 +253,7 @@ pub fn kernel_provisioner(command_prefix: Option<String>,serper_api_key: Option<String>,session_artifact_dir: Option<std::path::PathBuf>,+ cell_timeout_ms: Option<u64>,on_restore: Option<crate::kernel::provisioner::RestoreCallback>,on_background_work_settled: Option<crate::kernel::shared::BackgroundWorkSettledCallback>,on_unavailable_skills: Option<crate::kernel::provisioner::UnavailableSkillsCallback>,@@ -298,6 +299,9 @@ pub fn kernel_provisioner(// Only persistent sessions (which have an artifact dir) get// a revivable snapshot (TS `snapshotDir`).snapshot_dir: session_artifact_dir,+ // The engine-resolved watchdog budget (`None`: daemonless or+ // disabled; the runtime bootstrap and state ops never arm it).+ cell_timeout_ms,ready_gate: None,on_restore,on_background_work_settled,@@ -347,7 +351,11 @@ impl IpythonKernelProvisioner for KernelProvisioner {// wraps it in its own abort signal.let signal = signal.map(crate::kernel::cancellation::AbortSignal::from_token);let manager = this.ensure(on_progress, signal).await?;- Ok(Box::new(KernelManagerExecutor { manager }) as Box<dyn KernelExecutor>)+ let cell_timeout_ms = this.cell_timeout_ms();+ Ok(Box::new(KernelManagerExecutor {+ manager,+ cell_timeout_ms,+ }) as Box<dyn KernelExecutor>)})}@@ -362,6 +370,8 @@ impl IpythonKernelProvisioner for KernelProvisioner {/// Adapts the kernel manager to the ipython tool's executor contract.struct KernelManagerExecutor {manager: crate::kernel::manager::ReplKernelManager,+ /// The provisioner-resolved per-cell watchdog budget (`None`: never armed).+ cell_timeout_ms: Option<u64>,}impl KernelExecutor for KernelManagerExecutor {@@ -379,6 +389,7 @@ impl KernelExecutor for KernelManagerExecutor {let code = code.to_string();let signal = options.signal;let on_late_sent_agent_message = options.on_late_sent_agent_message;+ let cell_timeout_ms = self.cell_timeout_ms;Box::pin(async move {let result = manager.execute(@@ -386,6 +397,7 @@ impl KernelExecutor for KernelManagerExecutor {crate::kernel::shared::ExecuteOptions {signal: signal.map(crate::kernel::cancellation::AbortSignal::from_token),on_late_sent_agent_message,+ cell_timeout_ms,..Default::default()},)@@ -396,6 +408,18 @@ impl KernelExecutor for KernelManagerExecutor {}}+/// Whether the per-cell watchdog arms for this session. Daemonless sessions+/// keep `await bash()` unbounded by design (#3523): every over-budget cell+/// there would be a sanctioned long await with no background lane to move+/// to, so the watchdog arms only in daemon-backed sessions.+pub(crate) fn arm_cell_timeout_ms(daemonless: bool, settings_ms: u64) -> Option<u64> {+ if daemonless {+ None+ } else {+ Some(settings_ms)+ }+}+fn convert_status(status: crate::kernel::shared::ExecuteStatus,) -> crate::tools::ipython::ExecuteStatus {@@ -543,4 +567,16 @@ mod tests {);assert_eq!(visible.len(), 3);}++ #[test]+ fn cell_watchdog_arms_only_in_daemon_backed_sessions() {+ // Daemonless sessions keep `await bash()` unbounded by design+ // (#3523): their over-budget cells are sanctioned long awaits.+ assert_eq!(arm_cell_timeout_ms(true, 60_000), None);+ assert_eq!(arm_cell_timeout_ms(true, 0), None);+ assert_eq!(arm_cell_timeout_ms(false, 60_000), Some(60_000));+ // A zero setting is the explicit disable: it must reach the+ // executor as an armed zero budget, not fall back to a default.+ assert_eq!(arm_cell_timeout_ms(false, 0), Some(0));+ }}diff --git a/crates/pa-core/src/settings/load.rs b/crates/pa-core/src/settings/load.rsindex 1e68cc4d0a..571d666e96 100644--- a/crates/pa-core/src/settings/load.rs+++ b/crates/pa-core/src/settings/load.rs@@ -61,6 +61,7 @@ const KNOWN_FIELDS: &[&str] = &["warnings","sessionDir","requestTiming",+ "pythonCellTimeoutMs",];/// Extract each known field independently; ignore fields whose JSON type does not match the Rust@@ -126,6 +127,28 @@ mod tests {);}+ #[test]+ fn wrong_typed_python_cell_timeout_loads_as_unset() {+ // A known field: a wrong-typed value must behave as unset (the+ // getter's default), not survive raw in `extra` where a save+ // would persist the bad key.+ let value: Value = serde_json::json!({+ "pythonCellTimeoutMs": "sixty seconds",+ "pythonCellTimeoutValid": 30_000+ });+ let settings = from_value_lenient(&value);+ assert_eq!(settings.python_cell_timeout_ms, None);+ assert!(+ !settings.extra.contains_key("pythonCellTimeoutMs"),+ "a wrong-typed known field never rides extra into a save"+ );+ assert_eq!(+ settings.extra.get("pythonCellTimeoutValid"),+ Some(&serde_json::json!(30_000)),+ "genuine unknown keys keep flowing through extra"+ );+ }+#[test]fn clean_document_strict_parses() {let value: Value = serde_json::json!({ "theme": "prime", "rlmMaxDepth": 4 });diff --git a/crates/pa-core/src/settings/manager.rs b/crates/pa-core/src/settings/manager.rsindex 6e9af35b51..9d0b6a9009 100644--- a/crates/pa-core/src/settings/manager.rs+++ b/crates/pa-core/src/settings/manager.rs@@ -648,6 +648,16 @@ impl SettingsManager {self.merged.recent_models.clone().unwrap_or_default()}+ /// The per-cell watchdog budget for user `python_repl` cells, in+ /// milliseconds (`0` disables; the default is 60s). Daemonless+ /// sessions never arm the watchdog.+ #[must_use]+ pub fn get_python_cell_timeout_ms(&self) -> u64 {+ self.merged+ .python_cell_timeout_ms+ .unwrap_or(crate::settings::types::DEFAULT_PYTHON_CELL_TIMEOUT_MS)+ }+/// The steering queue's delivery mode: `all` co-delivers every queued message at/// the next turn boundary; `one-at-a-time` delivers one per turn.#[must_use]@@ -1013,7 +1023,7 @@ fn load_scope(#[cfg(test)]mod tests {use super::*;- use crate::settings::types::MarkdownSettings;+ use crate::settings::types::{MarkdownSettings, DEFAULT_PYTHON_CELL_TIMEOUT_MS};#[test]fn in_memory_loads_merges_and_saves() {@@ -1225,6 +1235,26 @@ mod tests {assert!(!manager.get_compaction_enabled());}+ #[test]+ fn python_cell_timeout_reads_setting_or_default() {+ let manager = SettingsManager::in_memory(&Settings::default());+ assert_eq!(+ manager.get_python_cell_timeout_ms(),+ DEFAULT_PYTHON_CELL_TIMEOUT_MS+ );+ let manager = SettingsManager::in_memory(&Settings {+ python_cell_timeout_ms: Some(90_000),+ ..Settings::default()+ });+ assert_eq!(manager.get_python_cell_timeout_ms(), 90_000);+ // Zero is the explicit disable, not the default.+ let manager = SettingsManager::in_memory(&Settings {+ python_cell_timeout_ms: Some(0),+ ..Settings::default()+ });+ assert_eq!(manager.get_python_cell_timeout_ms(), 0);+ }+#[test]fn image_model_reads_trimmed_or_unset() {let manager = SettingsManager::in_memory(&Settings {diff --git a/crates/pa-core/src/settings/types.rs b/crates/pa-core/src/settings/types.rsindex 0cd795ac6d..ff61907bb7 100644--- a/crates/pa-core/src/settings/types.rs+++ b/crates/pa-core/src/settings/types.rs@@ -298,6 +298,10 @@ pub enum McpServerConfig {},}+/// The default per-cell watchdog budget for user `python_repl` cells: 60+/// seconds.+pub const DEFAULT_PYTHON_CELL_TIMEOUT_MS: u64 = 60_000;+/// The settings document: every known field optional; unknown keys preserved.#[derive(Debug, Clone, Default, Serialize, Deserialize)]#[serde(rename_all = "camelCase", default)]@@ -333,6 +337,10 @@ pub struct Settings {/// session model does not accept image input. Default: none - image turns on a text-only model/// fail with a configuration hint instead of silently dropping the images.pub image_model: Option<String>,+ /// Per-cell watchdog budget for user `python_repl` cells, in milliseconds+ /// (default [`DEFAULT_PYTHON_CELL_TIMEOUT_MS`]; `0` disables). Daemonless+ /// sessions never arm it.+ pub python_cell_timeout_ms: Option<u64>,pub autonomous: Option<AutonomousSettings>,/// Custom shell that runs every kernel `bash()` and user-bash command as/// `<shell> -c <command>`: an absolute path to an existing executable,diff --git a/crates/pa-core/tests/kernel_cell_watchdog.rs b/crates/pa-core/tests/kernel_cell_watchdog.rsnew file mode 100644index 0000000000..c486d4379d--- /dev/null+++ b/crates/pa-core/tests/kernel_cell_watchdog.rs@@ -0,0 +1,292 @@+// Pedantic-gate dispositions as src/lib.rs (large_futures/too_many_lines/casts).+#![allow(+ clippy::large_futures,+ clippy::too_many_lines,+ clippy::cast_possible_truncation,+ clippy::cast_possible_wrap,+ clippy::cast_sign_loss,+ clippy::cast_precision_loss+)]++//! Per-cell watchdog integration tests: spawn a real `python -m rlm.repl`+//! kernel and verify the watchdog teaches instead of killing. A cell that+//! outlives its budget still settles ok and keeps its own result, with the+//! teaching note appended to stderr; sub-budget cells, disabled budgets,+//! failed cells, and the kernel itself (namespace intact, process alive) are+//! untouched.+#![cfg(unix)]++use std::collections::HashMap;+use std::path::PathBuf;+use std::time::Duration;++use pa_core::kernel::manager::{KernelStartOptions, ReplKernelManager};+use pa_core::kernel::shared::{+ ExecuteOptions, ExecuteStatus, HostRequestHandlers, KernelManagerOptions, KernelSnapshotConfig,+};+use pa_core::kernel::state_snapshot::{manifest_path_in, snapshot_path_in};++/// The kernel Python with prime-agent-runtime installed. Ambient product+/// state, not test input: skipped (with a note) when absent;+/// `PA_CORE_KERNEL_PYTHON` points at an explicit interpreter instead.+fn kernel_python() -> Option<PathBuf> {+ if let Some(explicit) = std::env::var_os("PA_CORE_KERNEL_PYTHON") {+ let explicit = PathBuf::from(explicit);+ assert!(+ explicit.exists(),+ "PA_CORE_KERNEL_PYTHON {} not found",+ explicit.display()+ );+ return Some(explicit);+ }+ let candidate = PathBuf::from(std::env::var("HOME").map_or_else(+ |_| "/home/ubuntu/.prime/agent/kernel-venv/bin/python".to_string(),+ |home| format!("{home}/.prime/agent/kernel-venv/bin/python"),+ ));+ if candidate.exists() {+ return Some(candidate);+ }+ eprintln!(+ "kernel python {} not found; skipping live kernel test",+ candidate.display()+ );+ None+}++/// A started kernel manager, or `None` when no kernel interpreter is+/// available on this machine; the caller skips the test then. The watchdog+/// needs no RLM bootstrap: a bare `rlm.repl` kernel serves sleep cells.+async fn started_manager() -> Option<ReplKernelManager> {+ let python = kernel_python()?;+ let options = KernelManagerOptions {+ python: Some(python),+ cwd: Some(std::env::temp_dir()),+ env: HashMap::new(),+ session_id: Some("cell-watchdog-test".to_string()),+ host_handlers: HostRequestHandlers::new(),+ python_skills: Vec::new(),+ on_background_work_settled: None,+ snapshot: None,+ bootstrap_code: None,+ stderr_log_path: None,+ };+ let manager = ReplKernelManager::new(options);+ manager+ .start(KernelStartOptions::default())+ .await+ .expect("kernel must start");+ Some(manager)+}++/// Execute one cell under the given watchdog budget (`None` or `0` disables).+async fn execute(+ manager: &ReplKernelManager,+ code: &str,+ cell_timeout_ms: Option<u64>,+) -> pa_core::kernel::shared::ExecuteResult {+ manager+ .execute(+ code,+ ExecuteOptions {+ cell_timeout_ms,+ ..ExecuteOptions::default()+ },+ )+ .await+ .expect("execute must not fail")+}++#[tokio::test]+async fn overage_cell_keeps_ok_with_the_watchdog_note_on_stderr() {+ let Some(manager) = started_manager().await else {+ return;+ };++ // Sub-budget cell: returns normally, result and stderr untouched.+ let quick = execute(+ &manager,+ "import time, sys\ntime.sleep(0.2)\n'quick'",+ Some(2000),+ )+ .await;+ assert_eq!(quick.status, ExecuteStatus::Ok);+ assert_eq!(quick.result.as_deref(), Some("'quick'"));+ assert!(quick.error.is_none());+ assert!(+ !quick.stderr.contains("[watchdog]"),+ "a sub-budget cell must carry no watchdog note"+ );++ // Staged ~5s cell under a 2s budget: the cell runs to completion and+ // keeps its ok status; the watchdog note is appended to stderr.+ let slow = execute(&manager, "time.sleep(5)\n'slow'", Some(2000)).await;+ assert_eq!(+ slow.status,+ ExecuteStatus::Ok,+ "a completed over-budget cell must not resolve as a failure: a \+ timeout-looking error invites a duplicate run of finished work"+ );+ assert!(slow.error.is_none());+ assert!(+ slow.stderr.contains("[watchdog]"),+ "the teaching note rides stderr: {}",+ slow.stderr+ );+ assert!(+ slow.stderr+ .contains("Cell exceeded the 2s python_repl budget"),+ "teaching text names the budget: {}",+ slow.stderr+ );+ assert!(+ slow.stderr.contains("Move long shell work to bash()"),+ "teaching text points at the real mechanism: {}",+ slow.stderr+ );+ // The cell's own outcome survives alongside the note.+ assert_eq!(slow.result.as_deref(), Some("'slow'"));+ assert!(+ slow.duration_ms >= 5000,+ "the cell itself ran to completion"+ );++ // A zero budget disables the watchdog: the same ~5s cell carries no note.+ let disabled = execute(&manager, "time.sleep(5)\n'disabled'", Some(0)).await;+ assert_eq!(disabled.status, ExecuteStatus::Ok);+ assert_eq!(disabled.result.as_deref(), Some("'disabled'"));+ assert!(!disabled.stderr.contains("[watchdog]"));++ // The kernel was never killed: the namespace from the first cells is intact.+ let alive = execute(&manager, "time is not None and sys.executable", None).await;+ assert_eq!(alive.status, ExecuteStatus::Ok);+ assert!(alive.result.is_some(), "kernel state survived the watchdog");++ manager+ .shutdown(pa_core::kernel::shared::KernelShutdownOptions::default())+ .await+ .expect("shutdown");+}++#[tokio::test]+async fn watchdog_noted_cell_still_schedules_the_snapshot() {+ let Some(python) = kernel_python() else {+ return;+ };+ let dir = tempfile::TempDir::new().expect("temp dir");+ let options = KernelManagerOptions {+ python: Some(python),+ cwd: Some(std::env::temp_dir()),+ env: HashMap::new(),+ session_id: Some("cell-watchdog-snapshot-test".to_string()),+ host_handlers: HostRequestHandlers::new(),+ python_skills: Vec::new(),+ on_background_work_settled: None,+ snapshot: Some(KernelSnapshotConfig {+ path: snapshot_path_in(dir.path()),+ manifest_path: manifest_path_in(dir.path()),+ max_bytes: None,+ max_variable_bytes: None,+ debounce_ms: Some(100),+ }),+ bootstrap_code: None,+ stderr_log_path: None,+ };+ let manager = ReplKernelManager::new(options);+ manager+ .start(KernelStartOptions::default())+ .await+ .expect("kernel must start");++ // The cell commits a variable but outruns a 500ms budget: the watchdog+ // appends its note, yet the cell completed ok in the kernel, so the+ // debounced namespace snapshot must still fire.+ let overage = execute(+ &manager,+ "import time\ntime.sleep(2)\nwatch_var = 'committed'",+ Some(500),+ )+ .await;+ assert_eq!(overage.status, ExecuteStatus::Ok);+ assert!(overage.stderr.contains("[watchdog]"));++ let snapshot = snapshot_path_in(dir.path());+ let mut flushed = false;+ for _ in 0..30 {+ let written =+ snapshot.exists() && std::fs::metadata(&snapshot).is_ok_and(|meta| meta.len() > 0);+ if written {+ flushed = true;+ break;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ assert!(+ flushed,+ "the watchdog-flipped cell must still schedule the namespace snapshot"+ );++ manager+ .shutdown(pa_core::kernel::shared::KernelShutdownOptions::default())+ .await+ .expect("shutdown");+}++#[tokio::test]+async fn overage_error_cell_keeps_its_own_error() {+ let Some(manager) = started_manager().await else {+ return;+ };++ // A cell that FAILS after outrunning the budget keeps its own error:+ // the watchdog never fabricates a timeout over a real traceback, and+ // the failed cell carries no teaching note.+ let failed = execute(&manager, "import time\ntime.sleep(2.5)\n1/0", Some(1000)).await;+ assert_eq!(failed.status, ExecuteStatus::Error);+ let error = failed.error.expect("the cell's own error survives");+ assert_eq!(+ error.ename, "ZeroDivisionError",+ "the cell's own error wins"+ );+ assert!(+ !failed.stderr.contains("[watchdog]"),+ "a failed cell gets no watchdog note: {}",+ failed.stderr+ );++ manager+ .shutdown(pa_core::kernel::shared::KernelShutdownOptions::default())+ .await+ .expect("shutdown");+}++#[tokio::test]+async fn queue_wait_is_excluded_from_the_cell_budget() {+ let Some(manager) = started_manager().await else {+ return;+ };++ // A ~3s cell holds the serial execution queue; a fast cell enqueued+ // behind it measures its budget from its own wire write, not from its+ // enqueue, so its queue wait must not trip the watchdog.+ let slow_manager = manager.clone();+ let slow = tokio::spawn(async move {+ execute(&slow_manager, "import time\ntime.sleep(3)\n'slow'", Some(0)).await+ });+ tokio::time::sleep(Duration::from_millis(200)).await;+ let queued = execute(&manager, "'fast'", Some(2000)).await;+ // The queue wait (~2.8s) exceeds the 2s budget; the fast cell's own+ // run is instant, so it must resolve clean with no note.+ assert_eq!(queued.status, ExecuteStatus::Ok);+ assert!(+ !queued.stderr.contains("[watchdog]"),+ "queue wait must not trip the watchdog: {}",+ queued.stderr+ );+ let slow = slow.await.expect("slow cell join");+ assert_eq!(slow.status, ExecuteStatus::Ok);++ manager+ .shutdown(pa_core::kernel::shared::KernelShutdownOptions::default())+ .await+ .expect("shutdown");+}