Skip to content

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

Rust

fix(kernel): close the provisioner's four residual mid-boot lifecycle gaps (#3303)

ktaa96ff158f6a
diff --git a/crates/pa-core/src/kernel/provisioner.rs b/crates/pa-core/src/kernel/provisioner.rs
index cdca1aea31..8da86d6452 100644
--- a/crates/pa-core/src/kernel/provisioner.rs
+++ b/crates/pa-core/src/kernel/provisioner.rs
@@ -157,6 +157,52 @@ struct StartupFailure {
type StartupResult = Result<ReplKernelManager, StartupFailure>;
+/// How one boot's settle publishes: the normal park, one of the two
+/// teardown rejects (a racing dispose; a memo generation invalidated by
+/// `kill()`), or the boot's own failure.
+enum Settle {
+ /// The boot's manager parked into the provisioner.
+ Published(ReplKernelManager),
+ /// A dispose raced the boot: tear the kernel down with the dispose's
+ /// snapshot policy and reject with its cause.
+ TearDownForDispose {
+ manager: ReplKernelManager,
+ snapshot: bool,
+ duration_ms: u64,
+ },
+ /// The memo this boot armed was cleared underneath it (`kill()`, or a
+ /// defunct clear superseding the generation): never publish a kernel
+ /// into a memo generation the boot no longer owns - kill it instead.
+ TearDownForKill {
+ manager: ReplKernelManager,
+ duration_ms: u64,
+ },
+ /// The boot failed on its own; its failure already carries the cause
+ /// and duration.
+ Failed(StartupFailure),
+}
+
+/// One `stop_kernel` call's starting point.
+enum StopArm {
+ /// Neither a live kernel nor an in-flight boot: nothing to stop.
+ Nothing,
+ /// This stop's own gate, installed atomically with the manager take
+ /// (direct) or the in-flight boot it joins.
+ Armed {
+ manager: Option<ReplKernelManager>,
+ startup: Option<tokio::sync::watch::Receiver<Option<StartupResult>>>,
+ stop_tx: tokio::sync::watch::Sender<bool>,
+ /// The gate this arm superseded. The stop task waits it before
+ /// opening its own, so a revival gated on this stop's gate can
+ /// never cross before the superseded stop's final snapshot flush
+ /// settles; and because every task waits only a gate OLDER than
+ /// its own arm, the waits cannot form a cycle (the
+ /// wait-the-installed-gate shape admitted both the missed
+ /// supersede window and a three-task deadlock).
+ previous_stop: Option<tokio::sync::watch::Receiver<bool>>,
+ },
+}
+
struct ProvisionerState {
manager: Option<ReplKernelManager>,
/// Shared result of the in-flight boot. Joined callers retain its manager
@@ -174,9 +220,24 @@ struct ProvisionerState {
/// before reading that snapshot back, so the two kernels never race
/// over the same on-disk file. The receiver yields `true` once the
/// recorded stop settles (a settled stop awaits instantly; a dead
- /// sender errs and unblocks the same way); each stop's gate also
- /// waits for the previous stop's gate.
+ /// sender errs and unblocks the same way); each stop supersedes the
+ /// previous.
pending_stop: Option<tokio::sync::watch::Receiver<bool>>,
+ /// The startup memo the installed pending-stop gate is armed against;
+ /// `None` when the gate was armed with a directly-taken manager. The
+ /// failed-boot teardown consults it to keep the gate of a stop
+ /// ACTIVELY armed for its own boot (that stop's task waits the boot's
+ /// memo, which settles only after the teardown): the teardown's flush
+ /// is already covered, so it installs no replacement gate.
+ pending_stop_for_startup: Option<tokio::sync::watch::Receiver<Option<StartupResult>>>,
+ /// Startup memos `kill()` invalidated but whose boots have not settled
+ /// yet. The memo's generation is dead (the boot tears down with `kill()`
+ /// semantics) yet the boot's kernel still exists, so a later
+ /// `dispose()` must wait its settle the same way it waits an armed
+ /// memo — without the park, a kill followed by a dispose skips the
+ /// doomed boot entirely and can orphan its kernel at worker exit.
+ /// Each parked memo is spent by its own boot's settle.
+ doomed_startups: Vec<tokio::sync::watch::Receiver<Option<StartupResult>>>,
}
/// Owns one kernel for one session: lazily starts it, memoizes the startup so
@@ -211,6 +272,8 @@ impl IpythonKernelProvisioner {
disposed: false,
dispose_snapshot: true,
pending_stop: None,
+ pending_stop_for_startup: None,
+ doomed_startups: Vec::new(),
}),
dispose_signal: AbortSignal::new(),
}),
@@ -307,44 +370,123 @@ impl IpythonKernelProvisioner {
let inner = Arc::clone(&self.inner);
let pending_stop = state.pending_stop.clone();
let startup_progress = on_progress.clone();
- let memo = done_rx.clone();
+ let startup_memo = done_rx.clone();
tokio::spawn(async move {
- let boot =
- tokio::spawn(run_startup(inner.clone(), startup_progress, pending_stop));
+ let boot = tokio::spawn(run_startup(
+ inner.clone(),
+ startup_progress,
+ pending_stop,
+ startup_memo.clone(),
+ ));
let result = match boot.await {
Ok(result) => result,
Err(error) => {
- // A panicked boot never reached run_startup's own
- // settle block, so clear the listener state here:
- // the next ensure() must boot fresh (self-heal).
- let mut state = inner
- .state
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- state.startup_listeners.clear();
- state.last_startup_message = None;
+ // A panicked boot never reached its own settle;
+ // the settle below still runs so the listener
+ // state clears and the next ensure() boots fresh.
Err(StartupFailure {
message: format!("kernel startup task failed: {error}"),
duration_ms: 0,
})
}
};
+ // Atomic settle/publish: the disposed check, the
+ // memo-generation check, the listener teardown, and the
+ // manager publication share ONE lock scope. Separate
+ // scopes let a dispose or a kill land between the check
+ // and the publish - the boot would park a live kernel
+ // into a provisioner that already reported itself torn
+ // down.
+ let settle = {
+ let mut state = inner
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let mine = state
+ .startup
+ .as_ref()
+ .is_some_and(|memo| memo.same_channel(&startup_memo));
+ // The listener state belongs to the ACTIVE memo
+ // generation: a doomed boot settling against a
+ // newer memo must not wipe the newer boot's
+ // progress listeners or its replayed stage. With
+ // no memo armed at all the entries are stale
+ // (their waiters already hold results) - clear.
+ if mine || state.startup.is_none() {
+ state.startup_listeners.clear();
+ state.last_startup_message = None;
+ }
+ match result {
+ Ok((manager, duration_ms)) => {
+ park_or_tear_down(&mut state, mine, manager, duration_ms)
+ }
+ Err(failure) => Settle::Failed(failure),
+ }
+ };
+ let settled = match settle {
+ Settle::Published(manager) => Ok(manager),
+ Settle::TearDownForDispose {
+ manager,
+ snapshot,
+ duration_ms,
+ } => {
+ // A dispose raced the boot: tear the kernel down
+ // with the dispose's snapshot policy and reject
+ // with its abort error instead of handing joined
+ // callers a manager that is already dead.
+ let _ = manager
+ .shutdown(KernelShutdownOptions {
+ snapshot,
+ drain_host_requests: true,
+ })
+ .await;
+ Err(StartupFailure {
+ message: "Kernel provisioner disposed during startup".to_string(),
+ duration_ms,
+ })
+ }
+ Settle::TearDownForKill {
+ manager,
+ duration_ms,
+ } => {
+ // TS kill() settles the pending startup and kills
+ // the manager it produced.
+ if !manager.is_defunct() {
+ manager.kill();
+ }
+ Err(StartupFailure {
+ message: "Kernel provisioner killed during startup".to_string(),
+ duration_ms,
+ })
+ }
+ Settle::Failed(failure) => Err(failure),
+ };
// Publish the completed result before clearing the memo:
// joined waiters keep the manager even if stop takes it.
- let _ = done_tx.send(Some(result));
+ let _ = done_tx.send(Some(settled));
+ // Clear only the memo this task installed (TS ensure()'s
+ // `managerPromise === startup` guard): a boot's manager
+ // can turn defunct inside the park->publish->clear window
+ // and another ensure() defunct-clears it and arms a NEWER
+ // memo already; an unconditional clear would wipe that
+ // memo mid-boot and arm a transient duplicate kernel.
let mut state = inner
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
- // A defunct manager may already have been replaced by a
- // newer boot; only clear the memo if it is still ours.
if state
.startup
.as_ref()
- .is_some_and(|current| current.same_channel(&memo))
+ .is_some_and(|memo| memo.same_channel(&startup_memo))
{
state.startup = None;
}
+ release_spent_stop_arm(&mut state, &startup_memo);
+ // A memo kill() parked for this boot is spent with the
+ // settle the dispose() parker waits on.
+ state
+ .doomed_startups
+ .retain(|parked| !parked.same_channel(&startup_memo));
});
state.startup = Some(done_rx.clone());
done_rx
@@ -396,8 +538,6 @@ impl IpythonKernelProvisioner {
manager.list_namespace_names(signal).await
}
- /// Dispose the kernel owned by this provisioner, including one still
- /// starting up. A still-queued boot drops out of the boot gate.
/// Stop the owned kernel without marking the provisioner disposed (TS
/// #2483's `stopKernel`): the shutdown flushes the final snapshot, and
/// the next `ensure()` boots a fresh kernel gated on this stop (the
@@ -408,70 +548,118 @@ impl IpythonKernelProvisioner {
/// resident); with neither a live kernel nor an in-flight boot there
/// is nothing to stop.
///
+ /// Concurrent stops of one in-flight boot chain instead of racing: each
+ /// stop arms its own gate superseding the previous, and every stop task
+ /// waits the strictly older gate it superseded before opening its own,
+ /// so a revival gated on any of them cannot cross before the final
+ /// snapshot flush settles.
+ ///
/// Best-effort by construction: a failed shutdown leaves no manager
/// and the next `ensure()` boots fresh.
pub async fn stop_kernel(&self, options: Option<KernelShutdownOptions>) {
let snapshot = options.is_none_or(|o| o.snapshot);
- let (manager, startup, stop_tx, previous_stop) = {
- let mut state = self.lock_state();
- state.dispose_snapshot = snapshot;
- let manager = state.manager.take();
- let startup = state.startup.clone();
- if manager.is_none() && startup.is_none() {
- return;
+ match self.arm_stop(snapshot) {
+ StopArm::Nothing => {}
+ StopArm::Armed {
+ manager,
+ startup,
+ stop_tx,
+ previous_stop,
+ ..
+ } => {
+ let inner = Arc::clone(&self.inner);
+ let stop = tokio::spawn(async move {
+ let manager = if let Some(manager) = manager {
+ Some(manager)
+ } else {
+ if let Some(mut startup) = startup {
+ let _ = startup.wait_for(Option::is_some).await;
+ }
+ inner
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .manager
+ .take()
+ };
+ if let Some(manager) = manager {
+ let _ = manager
+ .shutdown(KernelShutdownOptions {
+ snapshot,
+ drain_host_requests: true,
+ })
+ .await;
+ }
+ // Chained gate (the #3257 shape, kept under the join):
+ // open ours only after the gate THIS arm superseded
+ // settles - never the currently-installed one. A
+ // revival gated on ours then cannot cross before the
+ // superseded stop's final snapshot flush, whether this
+ // task shut its own kernel down or lost the manager
+ // take to the stop that gate belongs to; and because
+ // each task waits only a strictly older gate, the
+ // waits cannot form a cycle.
+ if let Some(mut previous) = previous_stop {
+ let _ = previous.wait_for(|done| *done).await;
+ }
+ let _ = stop_tx.send(true);
+ });
+ let _ = stop.await;
}
- // Publish the predecessor gate while holding the same lock used by
- // ensure() to select its startup; no revival can miss this stop.
- let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
- let previous_stop = state.pending_stop.replace(stop_rx);
- (manager, startup, stop_tx, previous_stop)
+ }
+ }
+
+ /// Claim one stop: take a live manager directly, or arm this stop's
+ /// own gate for the in-flight boot's parked kernel. The gate is
+ /// installed under the same lock `ensure()` uses to select its
+ /// startup, so no revival can miss this stop; a second stop of the
+ /// same boot simply supersedes the first's gate, and the stops chain
+ /// through their superseded gates.
+ fn arm_stop(&self, snapshot: bool) -> StopArm {
+ let mut state = self.lock_state();
+ state.dispose_snapshot = snapshot;
+ let manager = state.manager.take();
+ let startup = state.startup.clone();
+ if manager.is_none() && startup.is_none() {
+ return StopArm::Nothing;
+ }
+ let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
+ let previous_stop = state.pending_stop.replace(stop_rx);
+ // A gate armed with a directly-taken manager guards that manager's
+ // shutdown, not a boot; the failed-boot teardown consults this
+ // record to leave a stop ACTIVELY armed for the tearing-down boot
+ // alone (its own task already covers the flush).
+ state.pending_stop_for_startup = if manager.is_some() {
+ None
+ } else {
+ startup.clone()
};
- let inner = Arc::clone(&self.inner);
- let stop = tokio::spawn(async move {
- let manager = if let Some(manager) = manager {
- Some(manager)
- } else {
- if let Some(mut startup) = startup {
- let _ = startup.wait_for(Option::is_some).await;
- }
- inner
- .state
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .manager
- .take()
- };
- if let Some(manager) = manager {
- let _ = manager
- .shutdown(KernelShutdownOptions {
- snapshot,
- drain_host_requests: true,
- })
- .await;
- }
- // Concurrent stops can join the same boot and only one of them
- // takes its manager, so this gate also waits for the earlier
- // stop's shutdown before a revival may read the snapshot.
- if let Some(mut previous_stop) = previous_stop {
- let _ = previous_stop.wait_for(|done| *done).await;
- }
- let _ = stop_tx.send(true);
- });
- let _ = stop.await;
+ StopArm::Armed {
+ manager,
+ startup,
+ stop_tx,
+ previous_stop,
+ }
}
pub async fn dispose(&self, options: Option<KernelShutdownOptions>) {
let snapshot = options.is_none_or(|o| o.snapshot);
- let mut startup = {
+ let (mut startup, mut doomed) = {
let mut state = self.lock_state();
state.dispose_snapshot = snapshot;
state.disposed = true;
- state.startup.clone()
+ (state.startup.clone(), state.doomed_startups.clone())
};
self.inner.dispose_signal.abort();
+ // A boot `kill()` invalidated settles like an armed one: the
+ // dispose must not return while its kernel is still settling, or a
+ // worker exit could orphan it.
if let Some(startup) = &mut startup {
let _ = startup.wait_for(Option::is_some).await;
}
+ for memo in &mut doomed {
+ let _ = memo.wait_for(Option::is_some).await;
+ }
let manager = self.lock_state().manager.take();
if let Some(manager) = manager {
let _ = manager
@@ -484,26 +672,206 @@ impl IpythonKernelProvisioner {
}
/// Kill the owned kernel without a final snapshot (busy-kernel restart).
+ /// A kernel still starting up has not been published yet: like TS
+ /// `kill()`, the startup memo leaves the generation (invalidation), so
+ /// the doomed boot's own settle kills its kernel instead of parking
+ /// it, and the next `ensure()` boots fresh - a kill racing a boot
+ /// leaves no resident kernel behind. The invalidated memo is PARKED
+ /// for `dispose()`: the doomed boot's kernel still exists until its
+ /// settle, and a dispose racing the kill must wait it out.
pub fn kill(&self) {
- let manager = self.lock_state().manager.take();
+ let manager = {
+ let mut state = self.lock_state();
+ // The stop gate armed against the boot this kill invalidates
+ // is spent with it.
+ if let Some(armed_for) = state.startup.clone() {
+ release_spent_stop_arm(&mut state, &armed_for);
+ }
+ if let Some(doomed) = state.startup.take() {
+ state.doomed_startups.push(doomed);
+ }
+ // The shared progress state belongs to the memo generation
+ // kill() just invalidated: its own emits already skip shared
+ // writes, and the next ensure() must neither replay the
+ // killed boot's stale stage to a fresh handler nor fan the
+ // newer boot's stages out to the killed generation's
+ // listeners.
+ state.startup_listeners.clear();
+ state.last_startup_message = None;
+ state.manager.take()
+ };
if let Some(manager) = manager {
manager.kill();
}
}
}
+/// Release the stop gate armed for `memo`'s boot, if any. The arm's
+/// memo receiver is a strong handle to the settled result's manager, and
+/// a stale one keeps a parked-or-failed kernel alive past `stop_kernel()`,
+/// so a later failed shutdown's process would leak with it as the sole
+/// owner. Both spenders call this: the boot's settle and the `kill()` that
+/// invalidates the boot.
+fn release_spent_stop_arm(
+ state: &mut ProvisionerState,
+ memo: &tokio::sync::watch::Receiver<Option<StartupResult>>,
+) {
+ if state
+ .pending_stop_for_startup
+ .as_ref()
+ .is_some_and(|armed| armed.same_channel(memo))
+ {
+ state.pending_stop_for_startup = None;
+ }
+}
+
+/// The settled boot's disposition: apply the settle decision under the
+/// settle's own lock scope.
+fn park_or_tear_down(
+ state: &mut ProvisionerState,
+ mine: bool,
+ manager: ReplKernelManager,
+ duration_ms: u64,
+) -> Settle {
+ match settle_decision(state, mine) {
+ SettleDecision::Kill => Settle::TearDownForKill {
+ manager,
+ duration_ms,
+ },
+ SettleDecision::Dispose => Settle::TearDownForDispose {
+ manager,
+ snapshot: state.dispose_snapshot,
+ duration_ms,
+ },
+ SettleDecision::Publish => {
+ state.manager = Some(manager.clone());
+ Settle::Published(manager)
+ }
+ }
+}
+
+/// The settle's disposition order, isolated because the ORDER is the
+/// contract: the generation check comes FIRST — a boot `kill()` doomed
+/// tears down with `kill()` semantics (no flush) even when a dispose raced
+/// in behind the kill, because the dispose's own snapshot policy cannot
+/// resurrect a generation `kill()` invalidated (a killed+disposed boot
+/// reaching Ok must never flush, and kill→ensure→dispose must never
+/// overlap two flushes on one `snapshot_dir`). Only a live generation
+/// honors the dispose.
+fn settle_decision(state: &ProvisionerState, mine: bool) -> SettleDecision {
+ if !mine {
+ SettleDecision::Kill
+ } else if state.disposed {
+ SettleDecision::Dispose
+ } else {
+ SettleDecision::Publish
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+enum SettleDecision {
+ Kill,
+ Dispose,
+ Publish,
+}
+
+/// The snapshot policy for a failed boot's teardown: the provisioner's
+/// dispose policy while the boot's memo generation is still armed, but
+/// NEVER a flush for a boot `kill()` invalidated — the replacement
+/// generation is already restoring from the same on-disk payload, and a
+/// failed doomed boot's teardown flushing over it would rewrite a healthy
+/// snapshot (and the kernel stderr log) out from under the new kernel.
+/// `dispose()` does not clear the memo, so a disposed boot keeps the
+/// dispose's own policy.
+///
+/// When the policy still flushes, this ALSO installs a pending-stop gate
+/// for the teardown's own flush — the decision and the gate share ONE
+/// lock scope, so a `kill()` landing between the decision and the flush
+/// still leaves the replacement boot gated on this teardown: it restores
+/// only after the flush settles (the same revival gate `stop_kernel`
+/// arms against its own flush). A stop actively armed for this boot
+/// already covers the flush (its task waits this boot's memo, which
+/// settles only after the teardown), so the gate stays untouched in
+/// that one case; any older, merely installed gate - including one long
+/// settled and left in place - covers nothing and is replaced. Hold the
+/// returned sender across the shutdown — the gate opens when the
+/// teardown scope drops it (a dead sender unblocks the waiters the same
+/// way a settled one does).
+#[must_use]
+fn hold_snapshot_flush_gate(
+ inner: &Arc<ProvisionerInner>,
+ memo: &tokio::sync::watch::Receiver<Option<StartupResult>>,
+) -> (bool, Option<tokio::sync::watch::Sender<bool>>) {
+ let mut state = inner
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let flush = state
+ .startup
+ .as_ref()
+ .is_some_and(|armed| armed.same_channel(memo))
+ && state.dispose_snapshot;
+ // A stop actively armed for THIS boot covers the teardown's flush
+ // through its own memo wait (the stop's task waits this boot's
+ // settle, which happens only after the teardown); a merely
+ // installed older gate - including one long settled and left in
+ // place - covers nothing, so this teardown's gate replaces it.
+ let covered_by_active_stop = state
+ .pending_stop_for_startup
+ .as_ref()
+ .is_some_and(|armed_for| armed_for.same_channel(memo));
+ if !flush || covered_by_active_stop {
+ return (flush, None);
+ }
+ let (gate_tx, gate_rx) = tokio::sync::watch::channel(false);
+ state.pending_stop = Some(gate_rx);
+ (flush, Some(gate_tx))
+}
+
+/// The boot's memo is still the armed startup generation AND the
+/// provisioner is not disposed: a failed attempt may retry, and a
+/// restore may surface. `kill()` (or a newer boot's defunct-clear)
+/// invalidating the memo makes a further attempt stale work whose
+/// kernel the settle would only have to kill.
+fn boot_generation_is_live(
+ inner: &Arc<ProvisionerInner>,
+ memo: &tokio::sync::watch::Receiver<Option<StartupResult>>,
+) -> bool {
+ let state = inner
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ !state.disposed
+ && state
+ .startup
+ .as_ref()
+ .is_some_and(|armed| armed.same_channel(memo))
+}
+
fn emit_startup_progress(
inner: &Arc<ProvisionerInner>,
on_progress: Option<&KernelBootstrapProgressHandler>,
+ memo: &tokio::sync::watch::Receiver<Option<StartupResult>>,
message: &str,
) {
let mut state = inner
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
- state.last_startup_message = Some(message.to_string());
- for listener in &state.startup_listeners {
- listener(message);
+ // The shared stage belongs to the ACTIVE memo generation: a boot
+ // kill() invalidated must not overwrite the newer boot's replayed
+ // stage nor fire the newer generation's listeners with its own
+ // (the boot's own handler below is its caller's, not shared
+ // state, so it keeps firing).
+ if state
+ .startup
+ .as_ref()
+ .is_some_and(|armed| armed.same_channel(memo))
+ {
+ state.last_startup_message = Some(message.to_string());
+ for listener in &state.startup_listeners {
+ listener(message);
+ }
}
if let Some(on_progress) = on_progress {
on_progress(message);
@@ -545,8 +913,9 @@ fn resolve_startup_budget_ms() -> u64 {
/// bootstrap) never auto-retry — each needs either user action or a fresh
/// attempt initiated by the caller.
fn startup_failure_is_retryable(error: &anyhow::Error) -> bool {
- const FATAL_MARKERS: [&str; 8] = [
+ const FATAL_MARKERS: [&str; 9] = [
"provisioner disposed",
+ "provisioner killed",
"aborted",
"Failed to set up the Python kernel runtime",
"PRIME_AGENT_KERNEL_PYTHON points to a Python",
@@ -560,26 +929,30 @@ fn startup_failure_is_retryable(error: &anyhow::Error) -> bool {
}
/// Boot the kernel, retrying transient failures with backoff until the
-/// retry allowance or the hard startup budget runs out.
+/// retry allowance or the hard startup budget runs out. Returns the booted
+/// manager with the boot's duration, or the failure; the publisher task's
+/// atomic settle decides whether the manager may park.
async fn run_startup(
inner: Arc<ProvisionerInner>,
on_progress: Option<KernelBootstrapProgressHandler>,
pending_stop: Option<tokio::sync::watch::Receiver<bool>>,
-) -> StartupResult {
+ memo: tokio::sync::watch::Receiver<Option<StartupResult>>,
+) -> Result<(ReplKernelManager, u64), StartupFailure> {
let started = std::time::Instant::now();
let budget = std::time::Duration::from_millis(resolve_startup_budget_ms());
let mut remaining_retries = resolve_startup_retries();
let mut attempt: u32 = 0;
let outcome = loop {
attempt += 1;
- match start_kernel(&inner, on_progress.as_ref(), pending_stop.clone()).await {
+ match start_kernel(&inner, on_progress.as_ref(), pending_stop.clone(), &memo).await {
Ok(manager) => break Ok(manager),
Err(error) => {
- if inner
- .state
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .disposed
+ // A boot whose memo generation kill() (or a newer boot's
+ // defunct-clear) invalidated must not retry: each attempt
+ // spawns an interpreter and runs restore/bootstrap, and a
+ // stale attempt's restore would surface notifications and
+ // state a fresher generation never asked for.
+ if !boot_generation_is_live(&inner, &memo)
|| !startup_failure_is_retryable(&error)
|| remaining_retries == 0
|| started.elapsed() >= budget
@@ -592,50 +965,27 @@ async fn run_startup(
emit_startup_progress(
&inner,
on_progress.as_ref(),
+ &memo,
&format!("Kernel start failed; retrying in {backoff_ms}ms…"),
);
tokio::select! {
() = tokio::time::sleep(std::time::Duration::from_millis(backoff_ms)) => {}
() = inner.dispose_signal.cancelled() => break Err(error),
}
+ // Re-check after the backoff: kill() can invalidate the
+ // generation while this task sleeps it out.
+ if !boot_generation_is_live(&inner, &memo) {
+ break Err(error);
+ }
}
}
};
let duration_ms = started.elapsed().as_millis() as u64;
- let (raced_dispose, dispose_snapshot) = {
- let mut state = inner
- .state
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- state.startup_listeners.clear();
- state.last_startup_message = None;
- (outcome.is_ok() && state.disposed, state.dispose_snapshot)
- };
+ // The settle (disposed check, memo-generation check, park-or-reject)
+ // runs in the publisher task's atomic scope; this task only reports
+ // the boot's own outcome and duration.
match outcome {
- Ok(manager) => {
- if raced_dispose {
- // A dispose raced the boot: tear the kernel down with the
- // dispose's snapshot policy (TS startKernel's catch) and
- // reject with its abort error instead of handing joined
- // callers a manager that is already dead.
- let _ = manager
- .shutdown(KernelShutdownOptions {
- snapshot: dispose_snapshot,
- drain_host_requests: true,
- })
- .await;
- return Err(StartupFailure {
- message: "Kernel provisioner disposed during startup".to_string(),
- duration_ms,
- });
- }
- let mut state = inner
- .state
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- state.manager = Some(manager.clone());
- Ok(manager)
- }
+ Ok(manager) => Ok((manager, duration_ms)),
Err(error) => Err(StartupFailure {
message: format!("{error:#}"),
duration_ms,
@@ -651,6 +1001,7 @@ async fn start_kernel(
inner: &Arc<ProvisionerInner>,
on_progress: Option<&KernelBootstrapProgressHandler>,
pending_stop: Option<tokio::sync::watch::Receiver<bool>>,
+ memo: &tokio::sync::watch::Receiver<Option<StartupResult>>,
) -> anyhow::Result<ReplKernelManager> {
let started = std::time::Instant::now();
let cold = !inner
@@ -658,7 +1009,7 @@ async fn start_kernel(
.snapshot_dir
.as_ref()
.is_some_and(|dir| snapshot_path_in(dir).exists());
- let result = start_kernel_impl(inner, on_progress, pending_stop).await;
+ let result = start_kernel_impl(inner, on_progress, pending_stop, memo).await;
if let Some(report) = &inner.options.on_bootstrap_result {
report(KernelBootstrapStats {
cold,
@@ -677,6 +1028,7 @@ async fn start_kernel_impl(
inner: &Arc<ProvisionerInner>,
on_progress: Option<&KernelBootstrapProgressHandler>,
mut pending_stop: Option<tokio::sync::watch::Receiver<bool>>,
+ memo: &tokio::sync::watch::Receiver<Option<StartupResult>>,
) -> anyhow::Result<ReplKernelManager> {
let options = &inner.options;
let cwd = inner.cwd.clone();
@@ -686,14 +1038,15 @@ async fn start_kernel_impl(
let permit_dispose_signal = dispose_signal.clone();
// Wait for this provisioner's own in-flight stop_kernel() — and its
// final snapshot flush — before reading that snapshot back (TS #2483's
- // `pendingStop` gate; a completed stop awaits instantly and the latest
- // stop's gate also covers the earlier ones). `ready_gate` stays the cross-provisioner
+ // `pendingStop` gate; a completed stop awaits instantly and each stop
+ // supersedes the previous). `ready_gate` stays the cross-provisioner
// /reload arm.
if let Some(stop_gate) = &mut pending_stop {
if !*stop_gate.borrow() {
emit_startup_progress(
inner,
on_progress,
+ memo,
"Waiting for the previous kernel to stop...",
);
}
@@ -742,7 +1095,7 @@ async fn start_kernel_impl(
stderr_log_path,
});
- emit_startup_progress(inner, on_progress, "Starting Python kernel...");
+ emit_startup_progress(inner, on_progress, memo, "Starting Python kernel...");
// Only the process spawn + ready handshake contends for OS resources under
// a fan-out, and it is bounded by start()'s own timeout — so the permit
// covers only start(). Restore/bootstrap run per-kernel afterwards.
@@ -750,12 +1103,21 @@ async fn start_kernel_impl(
signal: None,
on_bootstrap_progress: on_progress.cloned(),
});
+ let permit_inner = Arc::clone(inner);
+ let permit_memo = memo.clone();
let boot = async {
with_kernel_boot_permit(move || async move {
- // Disposed while queued for the permit — don't spawn a kernel nobody wants.
+ // Disposed, or its memo generation kill() invalidated, while
+ // queued for the permit — don't spawn a kernel nobody wants.
+ // The permit frees after the stop/ready gates below, so a boot
+ // that waited those gates rechecks liveness here, the last
+ // point before the interpreter spawn.
if permit_dispose_signal.is_aborted() {
return Err(anyhow!("Kernel provisioner disposed before start"));
}
+ if !boot_generation_is_live(&permit_inner, &permit_memo) {
+ return Err(anyhow!("Kernel provisioner killed before start"));
+ }
start.await
})
.await
@@ -764,13 +1126,7 @@ async fn start_kernel_impl(
// Never leak the kernel process if startup fails after spawn — and
// never surface the failure before the teardown (final snapshot flush
// included) finished.
- let snapshot_policy = {
- inner
- .state
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .dispose_snapshot
- };
+ let (snapshot_policy, _teardown_gate) = hold_snapshot_flush_gate(inner, memo);
let _ = manager
.shutdown(KernelShutdownOptions {
snapshot: snapshot_policy,
@@ -804,13 +1160,13 @@ async fn start_kernel_impl(
let mut snapshot_existed = false;
if let Some(dir) = &snapshot_dir {
snapshot_existed = snapshot_path_in(dir).exists();
- emit_startup_progress(inner, on_progress, "Restoring Python state...");
+ emit_startup_progress(inner, on_progress, memo, "Restoring Python state...");
let restore = manager.restore_state().await;
if snapshot_existed {
pending_restore = Some(restore.unwrap_or_default());
}
}
- emit_startup_progress(inner, on_progress, "Preparing Python runtime...");
+ emit_startup_progress(inner, on_progress, memo, "Preparing Python runtime...");
// The bootstrap runs on the dispose signal (TS startKernel races every
// boot stage against the dispose-linked abort): a dispose mid-bootstrap
// settles the cell aborted, and the aborted-status arm below tears the
@@ -829,13 +1185,7 @@ async fn start_kernel_impl(
// The cell completed, but the provisioner was disposed under it:
// the same teardown as the aborted-status arm, with the honest
// disposed-startup cause (TS startKernel's abort error).
- let snapshot_policy = {
- inner
- .state
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .dispose_snapshot
- };
+ let (snapshot_policy, _teardown_gate) = hold_snapshot_flush_gate(inner, memo);
let _ = manager
.shutdown(KernelShutdownOptions {
snapshot: snapshot_policy,
@@ -854,12 +1204,29 @@ async fn start_kernel_impl(
}
// Broken skill imports stay importable-looking placeholders;
// report them so the model learns before its first call, not
- // from the placeholder's error (TS startKernel).
+ // from the placeholder's error (TS startKernel) - but only a
+ // LIVE generation may report: the callback shares the restore
+ // notice's mailbox, and a boot kill() invalidated must not
+ // append stale skills-unavailable rows the next turn shows the
+ // model. Same contract as the restore gate below: the
+ // generation check and the callback share ONE lock scope, and
+ // the callbacks must not re-enter the provisioner.
let unavailable = parse_unavailable_python_skills(&bootstrap.stdout);
- if let (Some(on_unavailable_skills), Some(errors)) =
- (&inner.options.on_unavailable_skills, unavailable)
- {
- on_unavailable_skills(&errors);
+ if let Some(errors) = unavailable {
+ let state = inner
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !state.disposed
+ && state
+ .startup
+ .as_ref()
+ .is_some_and(|armed| armed.same_channel(memo))
+ {
+ if let Some(on_unavailable_skills) = &inner.options.on_unavailable_skills {
+ on_unavailable_skills(&errors);
+ }
+ }
}
}
Ok(bootstrap) => {
@@ -875,13 +1242,7 @@ async fn start_kernel_impl(
.join("\n");
// TS startKernel's catch shuts the failed boot down with the
// dispose snapshot policy (default true), not `false`.
- let snapshot_policy = {
- inner
- .state
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .dispose_snapshot
- };
+ let (snapshot_policy, _teardown_gate) = hold_snapshot_flush_gate(inner, memo);
let _ = manager
.shutdown(KernelShutdownOptions {
snapshot: snapshot_policy,
@@ -893,13 +1254,7 @@ async fn start_kernel_impl(
));
}
Err(error) => {
- let snapshot_policy = {
- inner
- .state
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .dispose_snapshot
- };
+ let (snapshot_policy, _teardown_gate) = hold_snapshot_flush_gate(inner, memo);
let _ = manager
.shutdown(KernelShutdownOptions {
snapshot: snapshot_policy,
@@ -911,16 +1266,31 @@ async fn start_kernel_impl(
}
// Only tell the model what was revived once the kernel is actually usable —
- // a notice claiming restored state must never outlive a failed bootstrap.
+ // a notice claiming restored state must never outlive a failed bootstrap,
+ // and only a LIVE generation may surface it: a boot kill() invalidated
+ // restores its snapshot only for the settle to kill its kernel, so its
+ // restore must not fire the notification nor pollute last_restore for
+ // the fresher generation. The liveness check, the write, AND the
+ // callback share ONE lock scope (this provisioner invokes its
+ // callbacks under the state lock - the startup-progress listeners
+ // already do - and they must not re-enter the provisioner), so a
+ // kill() can no longer slip between the check and the notice.
if let Some(restore) = pending_restore {
- if let Some(on_restore) = &inner.options.on_restore {
- on_restore(&restore);
- }
- inner
+ let mut state = inner
.state
.lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .last_restore = Some(restore);
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !state.disposed
+ && state
+ .startup
+ .as_ref()
+ .is_some_and(|armed| armed.same_channel(memo))
+ {
+ state.last_restore = Some(restore.clone());
+ if let Some(on_restore) = &inner.options.on_restore {
+ on_restore(&restore);
+ }
+ }
}
Ok(manager)
}
@@ -938,6 +1308,200 @@ pub fn provisioner_for_path(
mod tests {
use super::*;
+ #[test]
+ fn a_spent_stop_arm_releases_only_its_own_boot() {
+ let provisioner = IpythonKernelProvisioner::new(
+ PathBuf::from("/tmp"),
+ IpythonKernelProvisionerOptions::default(),
+ );
+ let (armed_tx, armed_rx) = tokio::sync::watch::channel(None::<StartupResult>);
+ let (other_tx, other_rx) = tokio::sync::watch::channel(None::<StartupResult>);
+ drop((armed_tx, other_tx));
+ {
+ let mut state = provisioner.lock_state();
+ state.pending_stop_for_startup = Some(armed_rx.clone());
+ release_spent_stop_arm(&mut state, &other_rx);
+ assert!(
+ state.pending_stop_for_startup.is_some(),
+ "an arm armed for a different boot is not spent by this boot's settle"
+ );
+ release_spent_stop_arm(&mut state, &armed_rx);
+ assert!(
+ state.pending_stop_for_startup.is_none(),
+ "the arm armed for this boot is spent by its settle"
+ );
+ }
+ }
+
+ #[test]
+ fn kill_releases_the_stop_arm_armed_for_the_killed_boot() {
+ let provisioner = IpythonKernelProvisioner::new(
+ PathBuf::from("/tmp"),
+ IpythonKernelProvisionerOptions::default(),
+ );
+ let (memo_tx, memo_rx) = tokio::sync::watch::channel(None::<StartupResult>);
+ drop(memo_tx);
+ {
+ let mut state = provisioner.lock_state();
+ state.startup = Some(memo_rx.clone());
+ state.pending_stop_for_startup = Some(memo_rx);
+ }
+ provisioner.kill();
+ let state = provisioner.lock_state();
+ assert!(state.startup.is_none(), "kill() invalidates the memo");
+ assert!(
+ state.pending_stop_for_startup.is_none(),
+ "kill() releases the stop arm armed for the boot it invalidates"
+ );
+ assert_eq!(
+ state.doomed_startups.len(),
+ 1,
+ "kill() parks the invalidated memo for dispose() to wait"
+ );
+ }
+
+ #[test]
+ fn a_killed_boot_never_takes_the_dispose_teardown() {
+ let provisioner = IpythonKernelProvisioner::new(
+ PathBuf::from("/tmp"),
+ IpythonKernelProvisionerOptions::default(),
+ );
+ {
+ let mut state = provisioner.lock_state();
+ state.disposed = true;
+ state.dispose_snapshot = true;
+ }
+ // A killed generation tears down with kill() semantics even under a
+ // racing dispose: the dispose's own snapshot policy cannot resurrect
+ // it. The order is the contract — checking disposed first would
+ // flush a snapshot kill() forbade.
+ {
+ let state = provisioner.lock_state();
+ assert_eq!(settle_decision(&state, false), SettleDecision::Kill);
+ // A live generation honors the dispose; a live undisposed one
+ // parks.
+ assert_eq!(settle_decision(&state, true), SettleDecision::Dispose);
+ }
+ {
+ let mut state = provisioner.lock_state();
+ state.disposed = false;
+ }
+ let state = provisioner.lock_state();
+ assert_eq!(settle_decision(&state, true), SettleDecision::Publish);
+ }
+
+ #[test]
+ fn a_doomed_boot_teardown_never_flushes_a_snapshot() {
+ let provisioner = IpythonKernelProvisioner::new(
+ PathBuf::from("/tmp"),
+ IpythonKernelProvisionerOptions::default(),
+ );
+ let (memo_tx, memo_rx) = tokio::sync::watch::channel(None::<StartupResult>);
+ drop(memo_tx);
+ // A live boot's failed teardown keeps the dispose policy (true by
+ // default) and installs the revival gate for its own flush: a
+ // replacement boot that arms after this decision restores only
+ // after the flush settles.
+ {
+ let mut state = provisioner.lock_state();
+ state.startup = Some(memo_rx.clone());
+ }
+ let (flushes, gate) = hold_snapshot_flush_gate(&provisioner.inner, &memo_rx);
+ assert!(flushes);
+ assert!(
+ provisioner.lock_state().pending_stop.is_some(),
+ "a flushing teardown gates the revival on its own flush"
+ );
+ assert!(!provisioner
+ .lock_state()
+ .pending_stop
+ .as_ref()
+ .is_some_and(|g| *g.borrow()));
+ drop(gate);
+ // A boot kill() invalidated must never flush: the replacement
+ // generation is already restoring the same on-disk payload.
+ provisioner.kill();
+ {
+ let mut state = provisioner.lock_state();
+ state.pending_stop = None;
+ }
+ let (flushes, gate) = hold_snapshot_flush_gate(&provisioner.inner, &memo_rx);
+ assert!(!flushes);
+ assert!(gate.is_none());
+ assert!(
+ provisioner.lock_state().pending_stop.is_none(),
+ "a doomed teardown installs no gate"
+ );
+ // A disposed boot keeps the dispose's own policy (dispose does not
+ // clear the memo) and gates the same way.
+ let (disposed_tx, disposed_rx) = tokio::sync::watch::channel(None::<StartupResult>);
+ drop(disposed_tx);
+ {
+ let mut state = provisioner.lock_state();
+ state.startup = Some(disposed_rx.clone());
+ state.disposed = true;
+ }
+ let (flushes, gate) = hold_snapshot_flush_gate(&provisioner.inner, &disposed_rx);
+ assert!(flushes);
+ assert!(gate.is_some());
+ drop(gate);
+ {
+ let mut state = provisioner.lock_state();
+ state.dispose_snapshot = false;
+ }
+ let (flushes, gate) = hold_snapshot_flush_gate(&provisioner.inner, &disposed_rx);
+ assert!(!flushes);
+ assert!(gate.is_none());
+ // A stop actively armed for THIS boot covers the flush through its
+ // own memo wait (it settles only after this teardown): the
+ // teardown leaves that stop's gate untouched.
+ let (armed_tx, armed_rx) = tokio::sync::watch::channel(false);
+ {
+ let mut state = provisioner.lock_state();
+ state.dispose_snapshot = true;
+ state.pending_stop = Some(armed_rx.clone());
+ state.pending_stop_for_startup = Some(disposed_rx.clone());
+ }
+ let (flushes, gate) = hold_snapshot_flush_gate(&provisioner.inner, &disposed_rx);
+ assert!(flushes);
+ assert!(
+ gate.is_none(),
+ "an active stop armed for this boot covers the teardown flush"
+ );
+ assert!(
+ provisioner
+ .lock_state()
+ .pending_stop
+ .as_ref()
+ .is_some_and(|g| g.same_channel(&armed_rx)),
+ "the active stop's gate survives the teardown decision"
+ );
+ drop(armed_tx);
+ // A merely installed, long-settled older gate covers nothing:
+ // the teardown gate replaces it, or a kill() racing the teardown
+ // would leave the replacement boot restoring against this
+ // teardown's flush.
+ {
+ let mut state = provisioner.lock_state();
+ state.pending_stop_for_startup = None;
+ }
+ let (flushes, gate) = hold_snapshot_flush_gate(&provisioner.inner, &disposed_rx);
+ assert!(flushes);
+ assert!(
+ gate.is_some(),
+ "a stale settled gate must not suppress the teardown gate"
+ );
+ assert!(
+ !provisioner
+ .lock_state()
+ .pending_stop
+ .as_ref()
+ .is_some_and(|g| g.same_channel(&armed_rx)),
+ "the stale gate is replaced"
+ );
+ drop(gate);
+ }
+
#[test]
fn boot_concurrency_defaults_and_override() {
let default = default_kernel_boot_concurrency();
@@ -987,6 +1551,9 @@ mod tests {
assert!(!startup_failure_is_retryable(&anyhow!(
"Kernel provisioner disposed before start"
)));
+ assert!(!startup_failure_is_retryable(&anyhow!(
+ "Kernel provisioner killed before start"
+ )));
assert!(!startup_failure_is_retryable(&anyhow!(
"Python execution aborted"
)));
diff --git a/crates/pa-core/tests/kernel_startup_memo.rs b/crates/pa-core/tests/kernel_startup_memo.rs
new file mode 100644
index 0000000000..9c32434af5
--- /dev/null
+++ b/crates/pa-core/tests/kernel_startup_memo.rs
@@ -0,0 +1,1015 @@
+// The Tier-C/D ruling (fleet-uniform, 2026-09-28) - this target's own
+// crate root: the same bounded-boundary disposition as src/lib.rs
+// (large_futures/too_many_lines/the cast family; details there).
+#![allow(
+ clippy::large_futures,
+ clippy::too_many_lines,
+ clippy::cast_possible_truncation,
+ clippy::cast_possible_wrap,
+ clippy::cast_sign_loss,
+ clippy::cast_precision_loss
+)]
+// The whole target drives /bin/sh interpreter wrappers and unix-only
+// file permissions, so it stays off the windows cross-check (the same
+// gate the sibling kernel targets carry).
+#![cfg(unix)]
+
+//! Verifier integration tests for the startup memo's generation contract
+//! and the provisioner's mid-boot lifecycle edges (all on the
+//! single-threaded `#[tokio::test]` runtime, whose scheduler runs a whole
+//! wake chain - park, publish, clear, taker - in one drain; the fixtures
+//! therefore observe state at drain boundaries and never rely on sleeping):
+//!
+//! - a settled boot's publisher clears only the memo generation it
+//! installed (TS `ensure()`'s `managerPromise === startup` guard): a
+//! boot doomed by a mid-flight `kill()` settles against a NEWER memo
+//! armed underneath it and must leave that memo alone;
+//! - `kill()` before publication leaves no resident kernel (TS `kill()`
+//! clears `managerPromise`; the doomed boot's own settle kills its
+//! kernel instead of parking it);
+//! - `dispose()` during a boot owns that boot: it waits the in-flight
+//! startup, and the disposed boot settles without parking a kernel
+//! (the atomic settle/publish's invariant).
+//!
+//! The kernel Python is ambient product state (the auto-bootstrapped kernel
+//! venv); like `kernel_stop_revive.rs`, these tests skip (with a note) on
+//! machines without a live install so the suite stays hermetic elsewhere.
+
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use pa_core::kernel::provisioner::{IpythonKernelProvisioner, IpythonKernelProvisionerOptions};
+use pa_core::kernel::shared::{ExecuteOptions, ExecuteStatus};
+use pa_core::kernel::state_snapshot::snapshot_path_in;
+use std::os::unix::fs::PermissionsExt;
+
+/// The kernel Python with prime-agent-runtime installed (see
+/// `kernel_stop_revive.rs`); skipped with a note when absent.
+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 startup-memo test",
+ candidate.display()
+ );
+ None
+}
+
+/// A kernel interpreter wrapper that counts spawns into `count` AND holds
+/// the n-th interpreter (0-based, from the count file) until the fixture
+/// creates `gates/gate<n>`, so a test controls exactly when each boot's
+/// handshake may complete - a file barrier, never a timing assumption.
+fn counting_gated_kernel(
+ dir: &std::path::Path,
+ python: &std::path::Path,
+ count: &std::path::Path,
+ gates: &std::path::Path,
+) -> PathBuf {
+ let wrapper = dir.join("counting-gated-python");
+ std::fs::write(
+ &wrapper,
+ format!(
+ "#!/bin/sh\nn=$(wc -c < '{}')\nprintf x >> '{}'\nwhile [ ! -f '{}'/gate$n ] && [ -d '{}' ]; do sleep 0.05; done\nexec '{}' \"$@\"\n",
+ count.display(),
+ count.display(),
+ gates.display(),
+ gates.display(),
+ python.display()
+ ),
+ )
+ .unwrap();
+ std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o700)).unwrap();
+ wrapper
+}
+
+/// Number of interpreter spawns recorded so far.
+fn starts(count: &std::path::Path) -> u64 {
+ count.metadata().map_or(0, |m| m.len())
+}
+
+/// A settled boot's publisher clears only the memo generation it installed
+/// (TS `ensure()`'s `managerPromise === startup` guard). `kill()` removes
+/// the memo mid-boot (the generation invalidation), a NEWER memo is armed
+/// before the doomed boot settles, and the doomed settle's clear must
+/// leave that newer memo alone: the late joiner below must land on the
+/// newer boot, and exactly two interpreters may spawn.
+#[tokio::test]
+async fn stale_publisher_cannot_clear_a_newer_startup_memo() {
+ let Some(python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let count = dir.path().join("starts");
+ // The wrapper reads its ordinal from the count file BEFORE appending,
+ // so the file must exist (empty) before the first spawn.
+ std::fs::write(&count, "").unwrap();
+ let gates = dir.path().join("gates");
+ std::fs::create_dir_all(&gates).unwrap();
+ let wrapped = counting_gated_kernel(dir.path(), &python, &count, &gates);
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(wrapped),
+ ..Default::default()
+ },
+ );
+ // Boot one, doomed by a kill before publication. Its interpreter is
+ // held at gate0 (its handshake cannot complete until the fixture opens
+ // the gate), so the kill lands mid-boot by construction.
+ let doomed = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while starts(&count) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the fixture interpreter spawned");
+ provisioner.kill();
+ // Arm the NEWER generation while the doomed boot is still settling.
+ let newer = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ // Release the doomed boot: its settle (its memo clear) runs before
+ // this resolves, and it must leave the newer memo alone.
+ std::fs::write(gates.join("gate0"), "").unwrap();
+ let settled = tokio::time::timeout(Duration::from_secs(30), doomed)
+ .await
+ .expect("the doomed boot settled")
+ .unwrap();
+ assert!(
+ settled.is_err(),
+ "a kill before publication must not deliver a kernel"
+ );
+ // The newer boot survived the doomed settle; the late ask joins it
+ // while it is still in flight.
+ std::fs::write(gates.join("gate1"), "").unwrap();
+ let late = tokio::time::timeout(Duration::from_secs(30), provisioner.ensure(None, None))
+ .await
+ .expect("the late ask settled")
+ .unwrap();
+ let newer = tokio::time::timeout(Duration::from_secs(30), newer)
+ .await
+ .expect("the newer ask settled")
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ starts(&count),
+ 2,
+ "the doomed boot and the newer one; a stale clear must not arm a duplicate"
+ );
+ for manager in [&late, &newer] {
+ let result = manager
+ .execute("1 + 1", ExecuteOptions::default())
+ .await
+ .unwrap();
+ assert_eq!(result.status, ExecuteStatus::Ok);
+ }
+}
+
+/// `kill()` before publication must not leave a resident kernel: the kill
+/// removes the startup memo (TS `kill()` clears `managerPromise`), so the
+/// doomed boot's own settle kills its kernel instead of parking it, and
+/// the next `ensure()` boots fresh.
+#[tokio::test]
+async fn kill_during_boot_leaves_no_resident_kernel() {
+ let Some(python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let count = dir.path().join("starts");
+ // The wrapper reads its ordinal from the count file BEFORE appending,
+ // so the file must exist (empty) before the first spawn.
+ std::fs::write(&count, "").unwrap();
+ let gates = dir.path().join("gates");
+ std::fs::create_dir_all(&gates).unwrap();
+ let wrapped = counting_gated_kernel(dir.path(), &python, &count, &gates);
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(wrapped),
+ ..Default::default()
+ },
+ );
+ // The interpreter is held at gate0: the boot cannot publish before the
+ // kill lands, so the kill is mid-boot by construction.
+ let boot = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while starts(&count) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the fixture interpreter spawned");
+ provisioner.kill();
+ std::fs::write(gates.join("gate0"), "").unwrap();
+ let settled = tokio::time::timeout(Duration::from_secs(30), boot)
+ .await
+ .expect("the doomed boot settled")
+ .unwrap();
+ assert!(
+ settled.is_err(),
+ "a kill before publication must not deliver a kernel"
+ );
+ assert!(
+ provisioner.manager().is_none(),
+ "no kernel may park after a kill"
+ );
+ assert!(!provisioner.has_running_kernel());
+ // TS kill() clears the memo: the next ensure() starts a fresh boot.
+ // The fresh boot has nothing racing it, so its gate opens up front.
+ std::fs::write(gates.join("gate1"), "").unwrap();
+ let fresh = tokio::time::timeout(Duration::from_secs(30), provisioner.ensure(None, None))
+ .await
+ .expect("the next ensure booted fresh")
+ .unwrap();
+ let result = fresh
+ .execute("1 + 1", ExecuteOptions::default())
+ .await
+ .unwrap();
+ assert_eq!(result.status, ExecuteStatus::Ok);
+ assert_eq!(
+ starts(&count),
+ 2,
+ "the doomed boot and the fresh boot, nothing else"
+ );
+}
+
+/// `dispose()` during a boot owns that boot: it waits the in-flight
+/// startup, and the disposed boot settles as a failure without ever
+/// parking a kernel - the atomic settle/publish's invariant. A boot that
+/// published between separate check and publish scopes could park a live
+/// kernel into a provisioner that had already reported itself torn down.
+#[tokio::test]
+async fn dispose_during_boot_settles_it_without_parking() {
+ let Some(python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let count = dir.path().join("starts");
+ // The wrapper reads its ordinal from the count file BEFORE appending,
+ // so the file must exist (empty) before the first spawn.
+ std::fs::write(&count, "").unwrap();
+ let gates = dir.path().join("gates");
+ std::fs::create_dir_all(&gates).unwrap();
+ let wrapped = counting_gated_kernel(dir.path(), &python, &count, &gates);
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(wrapped),
+ ..Default::default()
+ },
+ );
+ // The interpreter is held at gate0, so the dispose below lands
+ // mid-boot by construction - the boot cannot settle before the
+ // fixture lets it.
+ let boot = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while starts(&count) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the fixture interpreter spawned");
+ // dispose() waits the held boot's settle, so it runs as its own task;
+ // the drain below lets it arm (disposed, abort signal) before the
+ // boot's handshake can complete.
+ let dispose = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.dispose(None).await }
+ });
+ for _ in 0..5 {
+ tokio::task::yield_now().await;
+ }
+ std::fs::write(gates.join("gate0"), "").unwrap();
+ let settled = tokio::time::timeout(Duration::from_secs(30), boot)
+ .await
+ .expect("the disposed boot settled")
+ .unwrap();
+ assert!(
+ settled.is_err(),
+ "the disposed provisioner must reject the boot"
+ );
+ tokio::time::timeout(Duration::from_secs(30), dispose)
+ .await
+ .expect("dispose waited the boot it owned")
+ .unwrap();
+ assert!(
+ provisioner.manager().is_none(),
+ "no kernel may park into a disposed provisioner"
+ );
+ assert!(!provisioner.has_running_kernel());
+ // And nothing may park afterwards either: the provisioner stays
+ // disposed, and no further interpreter spawns.
+ let error = provisioner
+ .ensure(None, None)
+ .await
+ .expect_err("a disposed provisioner rejects new boots");
+ assert!(error.to_string().contains("disposed"));
+ assert_eq!(
+ starts(&count),
+ 1,
+ "exactly one interpreter: the disposed boot, no duplicates"
+ );
+}
+
+/// The kill-vs-boot contract composes with #3257's panic-recovery: a
+/// panicking boot settles and clears its memo, the re-armed boot is a
+/// fresh generation, and `kill()` mid-re-armed-boot still leaves no
+/// resident kernel - the doomed re-armed boot is killed by its own settle.
+#[tokio::test]
+async fn kill_during_the_re_armed_boot_leaves_no_resident_kernel() {
+ let Some(python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let count = dir.path().join("starts");
+ // The wrapper reads its ordinal from the count file BEFORE appending,
+ // so the file must exist (empty) before the first spawn.
+ std::fs::write(&count, "").unwrap();
+ let gates = dir.path().join("gates");
+ std::fs::create_dir_all(&gates).unwrap();
+ let wrapped = counting_gated_kernel(dir.path(), &python, &count, &gates);
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(wrapped),
+ ..Default::default()
+ },
+ );
+ // F1's self-heal: a panicking progress callback kills the boot before
+ // the interpreter spawns; the memo settles and the next ensure boots
+ // fresh (the panic-cleanup ordering #3257 added).
+ let progress: pa_core::kernel::bootstrap::KernelBootstrapProgressHandler =
+ Arc::new(|_| panic!("progress callback panic"));
+ let error = tokio::time::timeout(
+ Duration::from_secs(5),
+ provisioner.ensure(Some(progress), None),
+ )
+ .await
+ .expect("panicked startup settled")
+ .expect_err("panicked callback must not report success");
+ assert!(format!("{error:#}").contains("kernel startup task failed"));
+ assert_eq!(
+ starts(&count),
+ 0,
+ "the panicked boot spawned no interpreter"
+ );
+ // The re-armed boot (a fresh generation) spawns interpreter #0,
+ // held at gate0: the kill lands mid-boot by construction.
+ let re_armed = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while starts(&count) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the re-armed interpreter spawned");
+ provisioner.kill();
+ std::fs::write(gates.join("gate0"), "").unwrap();
+ let settled = tokio::time::timeout(Duration::from_secs(30), re_armed)
+ .await
+ .expect("the doomed re-armed boot settled")
+ .unwrap();
+ assert!(
+ settled.is_err(),
+ "a kill before publication must not deliver a kernel"
+ );
+ assert!(provisioner.manager().is_none());
+ assert!(!provisioner.has_running_kernel());
+ // The provisioner stays consistent: the next ensure boots fresh.
+ // The fresh boot has nothing racing it, so its gate opens up front.
+ std::fs::write(gates.join("gate1"), "").unwrap();
+ let fresh = tokio::time::timeout(Duration::from_secs(30), provisioner.ensure(None, None))
+ .await
+ .expect("the next ensure booted fresh")
+ .unwrap();
+ let result = fresh
+ .execute("1 + 1", ExecuteOptions::default())
+ .await
+ .unwrap();
+ assert_eq!(result.status, ExecuteStatus::Ok);
+ assert_eq!(
+ starts(&count),
+ 2,
+ "the doomed re-armed boot and the fresh boot, nothing else"
+ );
+}
+
+/// A doomed boot settling against a NEWER memo generation must not wipe
+/// the newer boot's progress state: the settle's listener teardown and
+/// the replayed-stage reset belong to the ACTIVE generation only. The
+/// observable is the joiner replay - a late `ensure()` joiner of the
+/// newer boot replays that boot's last stage to its fresh progress
+/// handler; after the doomed settle the replay must still fire.
+#[tokio::test]
+async fn doomed_settle_keeps_the_newer_boot_listener_state() {
+ let Some(python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let count = dir.path().join("starts");
+ // The wrapper reads its ordinal from the count file BEFORE appending,
+ // so the file must exist (empty) before the first spawn.
+ std::fs::write(&count, "").unwrap();
+ let gates = dir.path().join("gates");
+ std::fs::create_dir_all(&gates).unwrap();
+ let wrapped = counting_gated_kernel(dir.path(), &python, &count, &gates);
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(wrapped),
+ ..Default::default()
+ },
+ );
+ // Boot A spawns its interpreter held at gate0 (its handshake cannot
+ // complete until the fixture opens the gate, so its settle timing is
+ // under the test's control, never a timing race).
+ let doomed = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while starts(&count) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the fixture interpreter spawned");
+ // A joiner of the doomed generation attaches its progress handler
+ // first (replaying A's current stage) and parks on A's memo.
+ let a_stages: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
+ let a_progress: pa_core::kernel::bootstrap::KernelBootstrapProgressHandler = {
+ let a_stages = a_stages.clone();
+ Arc::new(move |message| a_stages.lock().unwrap().push(message.to_string()))
+ };
+ let a_joiner = tokio::spawn({
+ let provisioner = provisioner.clone();
+ let a_progress = a_progress.clone();
+ async move { provisioner.ensure(Some(a_progress), None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while a_stages.lock().unwrap().is_empty() {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the doomed generation's joiner replayed A's stage");
+ // The kill invalidates A's memo generation while A is still settling.
+ provisioner.kill();
+ // Boot B (the newer generation) registers a live progress listener
+ // and reaches its first stage - which precedes its own interpreter
+ // spawn, so the stage is observable while B's handshake is held at
+ // gate1.
+ let (stage_tx, stage_rx) = tokio::sync::oneshot::channel();
+ let stage_tx = Arc::new(Mutex::new(Some(stage_tx)));
+ let b_stages: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
+ let progress_b: pa_core::kernel::bootstrap::KernelBootstrapProgressHandler = {
+ let b_stages = b_stages.clone();
+ Arc::new(move |message| {
+ b_stages.lock().unwrap().push(message.to_string());
+ if let Some(tx) = stage_tx.lock().unwrap().take() {
+ let _ = tx.send(message.to_string());
+ }
+ })
+ };
+ let newer = tokio::spawn({
+ let provisioner = provisioner.clone();
+ let progress_b = progress_b.clone();
+ async move { provisioner.ensure(Some(progress_b), None).await }
+ });
+ let first_stage = tokio::time::timeout(Duration::from_secs(30), stage_rx)
+ .await
+ .expect("the newer boot reached its first stage")
+ .expect("stage signal");
+ assert_eq!(first_stage, "Starting Python kernel...");
+ // NOW the doomed boot settles (gate0 opens its handshake): whatever
+ // it does to the shared progress state, the newer generation's
+ // listener and replay stage must survive it.
+ std::fs::write(gates.join("gate0"), "").unwrap();
+ let settled = tokio::time::timeout(Duration::from_secs(30), doomed)
+ .await
+ .expect("the doomed boot settled")
+ .unwrap();
+ assert!(
+ settled.is_err(),
+ "a boot doomed by kill() must settle as a failure"
+ );
+ // A late joiner of the NEWER boot replays its current stage to a
+ // fresh handler: the doomed settle must not have wiped it.
+ let (replay_tx, replay_rx) = tokio::sync::oneshot::channel();
+ let replay_tx = Arc::new(Mutex::new(Some(replay_tx)));
+ let progress_c: pa_core::kernel::bootstrap::KernelBootstrapProgressHandler =
+ Arc::new(move |message| {
+ if let Some(tx) = replay_tx.lock().unwrap().take() {
+ let _ = tx.send(message.to_string());
+ }
+ });
+ let joiner = tokio::spawn({
+ let provisioner = provisioner.clone();
+ let progress_c = progress_c.clone();
+ async move { provisioner.ensure(Some(progress_c), None).await }
+ });
+ let replayed = tokio::time::timeout(Duration::from_secs(5), replay_rx)
+ .await
+ .expect("a late joiner must replay the active boot's stage")
+ .expect("replay signal");
+ assert_eq!(replayed, "Starting Python kernel...");
+ // The killed generation's shared progress state died with the kill:
+ // its joiner heard nothing after the kill (its one entry is the
+ // pre-kill replay), and the newer boot's handler heard exactly its
+ // own first stage - no stale replay of the killed boot's stage in
+ // between.
+ assert_eq!(
+ *a_stages.lock().unwrap(),
+ vec!["Starting Python kernel...".to_string()],
+ "the killed generation's listener must not hear the newer boot"
+ );
+ assert_eq!(
+ *b_stages.lock().unwrap(),
+ vec![
+ "Starting Python kernel...".to_string(),
+ "Starting Python kernel...".to_string(),
+ ],
+ "the arming caller hears its own stage twice (fan-out + boot-local, the pre-existing main shape) and never the killed boot's stale replay first"
+ );
+ let a_settled = tokio::time::timeout(Duration::from_secs(30), a_joiner)
+ .await
+ .expect("the doomed generation's joiner settled")
+ .unwrap();
+ assert!(
+ a_settled.is_err(),
+ "a joiner of a killed boot must settle as a failure"
+ );
+ // Release the newer boot: it settles, serves, and the absolute spawn
+ // count stays pinned - the doomed boot and the newer one, nothing
+ // else.
+ std::fs::write(gates.join("gate1"), "").unwrap();
+ let manager = tokio::time::timeout(Duration::from_secs(30), newer)
+ .await
+ .expect("the newer boot settled")
+ .unwrap()
+ .unwrap();
+ tokio::time::timeout(Duration::from_secs(30), joiner)
+ .await
+ .expect("the joiner settled")
+ .unwrap()
+ .unwrap();
+ let result = manager
+ .execute("1 + 1", ExecuteOptions::default())
+ .await
+ .unwrap();
+ assert_eq!(result.status, ExecuteStatus::Ok);
+ assert_eq!(
+ starts(&count),
+ 2,
+ "the doomed boot and the newer boot, nothing else"
+ );
+}
+
+/// A kernel interpreter wrapper whose FIRST invocation records the spawn
+/// and then holds before failing (until the fixture writes the fail
+/// gate), while every later invocation records the spawn and execs the
+/// real kernel Python: a boot's first attempt fails retryably on the
+/// fixture's schedule, and only a live generation's retry may consume
+/// the second.
+fn flaky_first_kernel(
+ dir: &std::path::Path,
+ python: &std::path::Path,
+ count: &std::path::Path,
+ flip: &std::path::Path,
+ fail_gate: &std::path::Path,
+) -> PathBuf {
+ let wrapper = dir.join("flaky-first-python");
+ std::fs::write(
+ &wrapper,
+ format!(
+ "#!/bin/sh\nprintf x >> '{}'\nif [ -f '{}' ]; then exec '{}' \"$@\"; fi\nwhile [ ! -f '{}' ] && [ -d '{}' ]; do sleep 0.05; done\nexit 1\n",
+ count.display(),
+ flip.display(),
+ python.display(),
+ fail_gate.display(),
+ dir.display(),
+ ),
+ )
+ .unwrap();
+ std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o700)).unwrap();
+ wrapper
+}
+
+/// A boot `kill()` invalidated must not RETRY: each attempt spawns an
+/// interpreter and runs restore/bootstrap, and the doomed attempt's
+/// settle only kills its kernel - the absolute spawn count pins that the
+/// killed generation never consumed its retry after the backoff.
+#[tokio::test]
+async fn kill_during_the_retry_backoff_pins_the_spawn_count() {
+ let Some(python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let count = dir.path().join("starts");
+ std::fs::write(&count, "").unwrap();
+ let flip = dir.path().join("flipped");
+ let fail_gate = dir.path().join("fail-gate");
+ let wrapped = flaky_first_kernel(dir.path(), &python, &count, &flip, &fail_gate);
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(wrapped),
+ ..Default::default()
+ },
+ );
+ // Boot A's first attempt spawns and holds BEFORE its failure: the
+ // fixture owns the failure timing through the gate, never the
+ // backoff window.
+ let doomed = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while starts(&count) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the first attempt spawned");
+ // The kill invalidates A's generation while A's first attempt is
+ // still in flight; only then does the failure land.
+ provisioner.kill();
+ std::fs::write(&fail_gate, "").unwrap();
+ // Boot B (the newer generation) boots on the stable arm. The flip is
+ // the TEST's to write - A's own invocation must not race B's to it.
+ std::fs::write(&flip, "").unwrap();
+ let newer = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ let manager = tokio::time::timeout(Duration::from_secs(30), newer)
+ .await
+ .expect("the newer boot settled")
+ .unwrap()
+ .unwrap();
+ // The doomed boot settles as a failure WITHOUT consuming its retry.
+ let settled = tokio::time::timeout(Duration::from_secs(30), doomed)
+ .await
+ .expect("the doomed boot settled")
+ .unwrap();
+ assert!(settled.is_err(), "a killed boot settles as a failure");
+ let result = manager
+ .execute("1 + 1", ExecuteOptions::default())
+ .await
+ .unwrap();
+ assert_eq!(result.status, ExecuteStatus::Ok);
+ assert_eq!(
+ starts(&count),
+ 2,
+ "the failed attempt and the newer boot, nothing else"
+ );
+}
+
+/// A boot `kill()` invalidated must not report unavailable skills: the
+/// callback shares the restore notice's mailbox, so a discarded kernel's
+/// broken-import rows must not reach the next turn - while the LIVE
+/// boot's report still must (the same bootstrap's broken import, the
+/// same callback, exactly one report).
+#[tokio::test]
+async fn doomed_boot_does_not_report_unavailable_skills() {
+ let Some(python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let count = dir.path().join("starts");
+ std::fs::write(&count, "").unwrap();
+ let gates = dir.path().join("gates");
+ std::fs::create_dir_all(&gates).unwrap();
+ let wrapped = counting_gated_kernel(dir.path(), &python, &count, &gates);
+ let reported: Arc<Mutex<Vec<pa_core::kernel::bootstrap::UnavailablePythonSkills>>> =
+ Arc::new(Mutex::new(Vec::new()));
+ let on_unavailable_skills = {
+ let reported = Arc::clone(&reported);
+ Arc::new(
+ move |errors: &pa_core::kernel::bootstrap::UnavailablePythonSkills| {
+ reported.lock().unwrap().push(errors.clone());
+ },
+ ) as pa_core::kernel::provisioner::UnavailableSkillsCallback
+ };
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(wrapped),
+ python_skills: vec![pa_core::kernel::bootstrap::KernelPythonSkill {
+ name: "doomed-broken-skill".to_string(),
+ import_name: "doomed_broken_skill".to_string(),
+ package_path: PathBuf::from("/nonexistent/skill"),
+ pyproject_path: PathBuf::from("/nonexistent/skill/pyproject.toml"),
+ }],
+ on_unavailable_skills: Some(on_unavailable_skills),
+ ..Default::default()
+ },
+ );
+ // Boot A spawns its interpreter held at gate0.
+ let doomed = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while starts(&count) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the fixture interpreter spawned");
+ // The kill invalidates A's generation while A is still settling.
+ provisioner.kill();
+ // Boot B arms fresh and spawns its own interpreter held at gate1.
+ let newer = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while starts(&count) < 2 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the newer boot's interpreter spawned");
+ // Release A: its bootstrap still parses its broken skill for a DEAD
+ // generation - its report must not reach the mailbox.
+ std::fs::write(gates.join("gate0"), "").unwrap();
+ let settled = tokio::time::timeout(Duration::from_secs(30), doomed)
+ .await
+ .expect("the doomed boot settled")
+ .unwrap();
+ assert!(settled.is_err(), "a killed boot settles as a failure");
+ // Release B: the LIVE generation's report is the only one.
+ std::fs::write(gates.join("gate1"), "").unwrap();
+ let manager = tokio::time::timeout(Duration::from_secs(30), newer)
+ .await
+ .expect("the newer boot settled")
+ .unwrap()
+ .unwrap();
+ let result = manager
+ .execute("1 + 1", ExecuteOptions::default())
+ .await
+ .unwrap();
+ assert_eq!(result.status, ExecuteStatus::Ok);
+ let reported = reported.lock().unwrap().clone();
+ assert_eq!(
+ reported.len(),
+ 1,
+ "only the live generation reports unavailable skills: {reported:?}"
+ );
+ assert_eq!(
+ reported[0],
+ vec![(
+ "doomed_broken_skill".to_string(),
+ "No module named 'doomed_broken_skill'".to_string(),
+ )],
+ "the live boot's broken-import report"
+ );
+}
+
+/// A kill followed by a dispose must not let the doomed boot flush a
+/// snapshot: the settle checks the generation BEFORE the disposed flag, so
+/// a killed boot tears down with `kill()` semantics (no flush) even when a
+/// dispose raced in after the kill - the dispose's own policy cannot
+/// resurrect a generation `kill()` doomed. The sentinel snapshot stays
+/// byte-identical.
+#[tokio::test]
+async fn a_killed_then_disposed_boot_never_flushes_the_snapshot() {
+ let Some(python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let count = dir.path().join("starts");
+ std::fs::write(&count, "").unwrap();
+ let gates = dir.path().join("gates");
+ std::fs::create_dir_all(&gates).unwrap();
+ let wrapped = counting_gated_kernel(dir.path(), &python, &count, &gates);
+ let snapshot = snapshot_path_in(dir.path());
+ std::fs::write(&snapshot, "SENTINEL").unwrap();
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(wrapped),
+ snapshot_dir: Some(dir.path().to_path_buf()),
+ ..Default::default()
+ },
+ );
+ // Boot A spawns its interpreter held at gate0.
+ let doomed = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while starts(&count) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the fixture interpreter spawned");
+ // The kill dooms A; the dispose races in behind it and must wait A's
+ // settle (no worker-exit orphan).
+ provisioner.kill();
+ let dispose = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.dispose(None).await }
+ });
+ // Drain so the dispose has armed (disposed, abort signal, parked on
+ // the doomed memo) before the boot's failure can settle.
+ for _ in 0..5 {
+ tokio::task::yield_now().await;
+ }
+ // Release A: it fails its aborted bootstrap and settles against a
+ // dead generation - with kill() semantics, never a flush.
+ std::fs::write(gates.join("gate0"), "").unwrap();
+ let settled = tokio::time::timeout(Duration::from_secs(30), doomed)
+ .await
+ .expect("the doomed boot settled")
+ .unwrap();
+ assert!(settled.is_err(), "a killed boot settles as a failure");
+ tokio::time::timeout(Duration::from_secs(30), dispose)
+ .await
+ .expect("dispose waits the doomed boot's settle")
+ .unwrap();
+ let content = std::fs::read_to_string(&snapshot).unwrap_or_default();
+ assert_eq!(
+ content, "SENTINEL",
+ "a killed-then-disposed boot must not flush over the snapshot"
+ );
+}
+
+/// A dispose after a kill waits the doomed boot's settle: without the
+/// parked memo, `dispose()` would skip the doomed boot entirely and could
+/// orphan its kernel at worker exit. The observable is the dispose's own
+/// completion - it cannot return while the doomed boot's interpreter is
+/// still held.
+#[tokio::test]
+async fn dispose_after_a_kill_waits_the_doomed_boot() {
+ let Some(python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let count = dir.path().join("starts");
+ std::fs::write(&count, "").unwrap();
+ let gates = dir.path().join("gates");
+ std::fs::create_dir_all(&gates).unwrap();
+ let wrapped = counting_gated_kernel(dir.path(), &python, &count, &gates);
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(wrapped),
+ ..Default::default()
+ },
+ );
+ // Boot A spawns its interpreter held at gate0.
+ let doomed = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while starts(&count) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the fixture interpreter spawned");
+ provisioner.kill();
+ let mut dispose = std::pin::pin!(tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.dispose(None).await }
+ }));
+ // While the doomed boot is still held, the dispose cannot return.
+ let jumped = tokio::time::timeout(Duration::from_secs(2), dispose.as_mut()).await;
+ assert!(
+ jumped.is_err(),
+ "dispose must wait the killed boot's settle, not skip it"
+ );
+ // Release the boot: its settle unblocks the dispose.
+ std::fs::write(gates.join("gate0"), "").unwrap();
+ let settled = tokio::time::timeout(Duration::from_secs(30), doomed)
+ .await
+ .expect("the doomed boot settled")
+ .unwrap();
+ assert!(settled.is_err(), "a killed boot settles as a failure");
+ tokio::time::timeout(Duration::from_secs(30), dispose.as_mut())
+ .await
+ .expect("dispose completes after the doomed boot settles")
+ .unwrap();
+}
+
+/// A `kill()` landing while a fresh boot is still WAITING — here queued
+/// behind an in-flight stop's gate, before the boot permit and the spawn -
+/// must not let that doomed generation spawn an interpreter at all: the
+/// permit gate rechecks the memo generation is still live, not just the
+/// dispose signal. The observable is the spawn count: only the first
+/// boot's interpreter ever spawns.
+#[tokio::test]
+async fn a_kill_while_the_boot_waits_the_stop_gate_spawns_no_interpreter() {
+ let Some(python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let count = dir.path().join("starts");
+ std::fs::write(&count, "").unwrap();
+ let gates = dir.path().join("gates");
+ std::fs::create_dir_all(&gates).unwrap();
+ let wrapped = counting_gated_kernel(dir.path(), &python, &count, &gates);
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(wrapped),
+ ..Default::default()
+ },
+ );
+ // Boot A spawns its interpreter and holds mid-handshake at gate0.
+ let boot_a = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), async {
+ while starts(&count) == 0 {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the fixture interpreter spawned");
+ // The stop arms its gate in the synchronous prefix of its first poll,
+ // and every later boot waits that gate before the permit and the
+ // spawn. Poll it once on the test thread so the arm is guaranteed -
+ // no scheduling assumption - and assert the wait state instead of
+ // discarding it.
+ let mut stop = Box::pin(provisioner.stop_kernel(None));
+ assert!(
+ futures::future::poll_immediate(stop.as_mut())
+ .await
+ .is_none(),
+ "the stop armed and is waiting for the boot it targets"
+ );
+ // kill() invalidates A's generation; a fresh ensure arms a NEWER memo
+ // in the synchronous prefix of ITS first poll (guaranteed the same
+ // way), and a second kill() then invalidates that newer generation
+ // while its boot still waits.
+ provisioner.kill();
+ let mut boot_b = Box::pin(provisioner.ensure(None, None));
+ assert!(
+ futures::future::poll_immediate(boot_b.as_mut())
+ .await
+ .is_none(),
+ "the fresh boot armed its memo and is waiting"
+ );
+ provisioner.kill();
+ // Release A: its handshake completes, its settle tears it down, the
+ // stop's gate opens, and B's wait ends. The liveness check fails B
+ // before the interpreter spawn, so the count stays at one.
+ std::fs::write(gates.join("gate0"), "").unwrap();
+ std::fs::write(gates.join("gate1"), "").unwrap();
+ let settled_a = tokio::time::timeout(Duration::from_secs(30), boot_a)
+ .await
+ .expect("the first boot settled")
+ .unwrap();
+ assert!(settled_a.is_err(), "a killed boot settles as a failure");
+ tokio::time::timeout(Duration::from_secs(30), stop.as_mut())
+ .await
+ .expect("the stop settled");
+ let settled_b = tokio::time::timeout(Duration::from_secs(30), boot_b.as_mut())
+ .await
+ .expect("the queued boot settled");
+ let error = format!("{:#}", settled_b.unwrap_err());
+ assert!(
+ error.contains("killed before start"),
+ "the queued boot fails the liveness gate before spawning: {error}"
+ );
+ assert_eq!(
+ starts(&count),
+ 1,
+ "only the first boot's interpreter ever spawns"
+ );
+}
diff --git a/crates/pa-core/tests/kernel_stop_revive.rs b/crates/pa-core/tests/kernel_stop_revive.rs
index 814592d85d..b1aab91b4a 100644
--- a/crates/pa-core/tests/kernel_stop_revive.rs
+++ b/crates/pa-core/tests/kernel_stop_revive.rs
@@ -9,6 +9,10 @@
clippy::cast_sign_loss,
clippy::cast_precision_loss
)]
+// The whole target drives /bin/sh interpreter wrappers and unix-only
+// file permissions, so it stays off the windows cross-check (the same
+// gate the sibling kernel targets carry).
+#![cfg(unix)]
//! Verifier integration tests for the revivable kernel stop (TS #2483's
//! `stopKernel`): a snapshot-flushing stop that keeps the provisioner
@@ -22,6 +26,7 @@
//! hermetic elsewhere. `PA_CORE_KERNEL_PYTHON` points at an explicit
//! interpreter.
+use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -268,3 +273,157 @@ async fn revival_waits_for_in_flight_stop_before_booting() {
assert_eq!(result.status, ExecuteStatus::Ok);
let _ = first_cell.await;
}
+
+/// A stop armed for one boot, a `kill()`, a revival boot gated on that
+/// stop's gate, and a second stop of the REVIVED boot: the second stop
+/// supersedes the first stop's gate (the two arms are for different
+/// boots), and the first stop's task - which loses the manager take -
+/// must wait a strictly OLDER gate, never the currently-installed one.
+/// Waiting the installed gate deadlocks: the first stop waits the second
+/// stop's gate, which waits the revival's boot, which waits the FIRST
+/// stop's gate (a cycle with no drain boundary left to cross). The
+/// oracle is the settle itself, bounded: every task must settle within
+/// the timeouts on the chained-gate shape; the cycle shape wedges
+/// against the first bounded await. The absolute spawn count stays pinned
+/// at two: nothing in the chain may arm a third interpreter.
+#[tokio::test]
+async fn superseding_stop_after_kill_cannot_deadlock_the_revival_gate() {
+ let Some(python) = kernel_python() else {
+ return;
+ };
+ let dir = tempfile::TempDir::new().unwrap();
+ let count = dir.path().join("starts");
+ let wrapped = counting_kernel(dir.path(), &python, &count);
+ let artifacts = dir.path().join("artifacts");
+ std::fs::create_dir_all(&artifacts).unwrap();
+ let provisioner = IpythonKernelProvisioner::new(
+ dir.path(),
+ IpythonKernelProvisionerOptions {
+ python: Some(wrapped),
+ snapshot_dir: Some(artifacts),
+ ..Default::default()
+ },
+ );
+ // Boot one, and observe it mid-flight through its first progress
+ // stage (the memo is armed; the stage precedes the interpreter spawn,
+ // and the handshake runs for seconds after it).
+ let (stage_tx, stage_rx) = tokio::sync::oneshot::channel();
+ let stage_tx = Arc::new(Mutex::new(Some(stage_tx)));
+ let progress: pa_core::kernel::bootstrap::KernelBootstrapProgressHandler =
+ Arc::new(move |message| {
+ if !message.starts_with("Waiting for the previous kernel to stop") {
+ if let Some(tx) = stage_tx.lock().unwrap().take() {
+ let _ = tx.send(());
+ }
+ }
+ });
+ let doomed = tokio::spawn({
+ let provisioner = provisioner.clone();
+ let progress = progress.clone();
+ async move { provisioner.ensure(Some(progress), None).await }
+ });
+ tokio::time::timeout(Duration::from_secs(30), stage_rx)
+ .await
+ .expect("the first boot reached its first stage")
+ .expect("stage signal");
+ // The first stop arms its gate for that boot (nothing to join yet);
+ // one scheduler poll runs the stop task to its first await, past the
+ // arm.
+ let first_stop = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.stop_kernel(None).await }
+ });
+ tokio::task::yield_now().await;
+ // The kill invalidates the boot's memo generation (TS kill() clears
+ // managerPromise): the doomed boot still settles, but against no memo.
+ provisioner.kill();
+ // The revival boots fresh and parks on the first stop's gate.
+ let revival = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.ensure(None, None).await }
+ });
+ tokio::task::yield_now().await;
+ // A stop of the REVIVED boot supersedes the first stop's gate (its
+ // arm is for the newer memo, so the same-boot JOIN does not apply).
+ let second_stop = tokio::spawn({
+ let provisioner = provisioner.clone();
+ async move { provisioner.stop_kernel(None).await }
+ });
+ tokio::task::yield_now().await;
+ // The doomed boot settles (its failure publishes to its own memo's
+ // waiters); nothing here can wedge.
+ let settled = tokio::time::timeout(Duration::from_secs(30), doomed)
+ .await
+ .expect("the doomed boot settled")
+ .unwrap();
+ assert!(
+ settled.is_err(),
+ "a boot doomed by kill() must settle as a failure"
+ );
+ // THE ORACLE: the first stop must settle too. On the cycle shape its
+ // take-loser waits the currently-installed gate - the second stop's
+ // gate - which waits the revival's boot, which waits the FIRST
+ // stop's gate: the await below times out. On the chained-gate shape
+ // the loser waits only the gate its own arm replaced (none here), its
+ // gate opens, the revival parks, the second stop settles, all within
+ // the bound.
+ tokio::time::timeout(Duration::from_secs(30), first_stop)
+ .await
+ .expect("the first stop settled (no wait cycle)")
+ .unwrap();
+ tokio::time::timeout(Duration::from_secs(30), second_stop)
+ .await
+ .expect("the second stop settled")
+ .unwrap();
+ tokio::time::timeout(Duration::from_secs(30), revival)
+ .await
+ .expect("the revival settled")
+ .unwrap()
+ .unwrap();
+ // The second stop took and shut down the revived kernel (it stopped
+ // the NEW boot); the provisioner must be fully revivable after the
+ // cycle: a fresh ensure boots a third interpreter and serves.
+ assert!(provisioner.manager().is_none());
+ assert!(!provisioner.has_running_kernel());
+ let fresh = tokio::time::timeout(Duration::from_secs(30), provisioner.ensure(None, None))
+ .await
+ .expect("a fresh ensure booted after the cycle")
+ .unwrap();
+ let result = fresh
+ .execute("1 + 1", ExecuteOptions::default())
+ .await
+ .unwrap();
+ assert_eq!(result.status, ExecuteStatus::Ok);
+ assert_eq!(
+ starts(&count),
+ 3,
+ "the doomed boot, the revival, the fresh boot - nothing else"
+ );
+}
+
+/// A kernel interpreter wrapper that counts spawns into `count` before
+/// exec'ing the real kernel Python (see `kernel_startup_memo.rs`), so a
+/// test can pin exactly how many kernels were armed.
+fn counting_kernel(
+ dir: &std::path::Path,
+ python: &std::path::Path,
+ count: &std::path::Path,
+) -> PathBuf {
+ let wrapper = dir.join("counting-python");
+ std::fs::write(
+ &wrapper,
+ format!(
+ "#!/bin/sh\nprintf x >> '{}'\nexec '{}' \"$@\"\n",
+ count.display(),
+ python.display()
+ ),
+ )
+ .unwrap();
+ std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o700)).unwrap();
+ wrapper
+}
+
+/// Number of interpreter spawns recorded so far.
+fn starts(count: &std::path::Path) -> u64 {
+ count.metadata().map_or(0, |m| m.len())
+}