Skip to content

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

Rust

fix the abort and send idle race (#3159)

kt87c0391c2927
diff --git a/crates/pa-daemon/src/agent_engine/tests/abort.rs b/crates/pa-daemon/src/agent_engine/tests/abort.rs
index 891f0aa5a2..e8520eb7dc 100644
--- a/crates/pa-daemon/src/agent_engine/tests/abort.rs
+++ b/crates/pa-daemon/src/agent_engine/tests/abort.rs
@@ -159,6 +159,93 @@ fn abort_in_flight_turn_cancels_a_mid_provider_wait() {
);
}
+/// The abort-and-send idle race's engine seam (the gate-pool lane's solo
+/// finding, reproduced at rate): an abort landing after the delivery's
+/// pickup but before the agent run registers — the lazy session build and
+/// the policy reads widened TS's microscopic registration gap to the whole
+/// admission prefix — was entirely lost: `abort_in_flight_turn`'s
+/// `agent.abort()` found an empty run slot, the run registered fresh after
+/// it, and the turn ran its full provider hold (the session never went
+/// idle after the abort). The delivery's cancel flag (the worker's
+/// probe, armed by the abort after the pickup's clear) is consulted at
+/// the model-turn admission: the turn settles aborted BEFORE the provider
+/// call, no run registers, and the scripted response survives untouched —
+/// the next delivery serves it as its first reply (the served-path
+/// proof).
+#[test]
+fn abort_racing_the_admission_prefix_settles_the_turn_before_the_provider_call() {
+ let _faux = FAUX_TEST_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let (engine, _engine_dir) = faux_engine_with_settings(
+ &serde_json::json!({ "responses": ["raced reply", "next reply"] }),
+ 1,
+ );
+ // The racing abort, pinned exactly as the race arms it: the probe
+ // reads the delivery's cancel flag TRUE at the model-turn admission
+ // (cleared at the pickup, armed by the abort before the consult).
+ let mut events: Vec<EngineEvent> = Vec::new();
+ engine.run_prompt(
+ 0,
+ PromptRequest {
+ batch: Vec::new(),
+ images: Vec::new(),
+ message: "held turn for the racing abort".to_string(),
+ source: "user".to_string(),
+ agent_message_id: None,
+ custom_message: None,
+ },
+ &|| true,
+ &mut |event| {
+ events.push(event);
+ true
+ },
+ );
+ // The accepted row persists; the turn settles the structural aborted
+ // (never a failure the retry backoff would re-issue).
+ assert!(
+ matches!(&events[0], EngineEvent::UserMessage(_)),
+ "the accepted row leads: {events:?}"
+ );
+ assert!(
+ events
+ .iter()
+ .any(|event| matches!(event, EngineEvent::DoneAborted)),
+ "the raced turn settles aborted: {events:?}"
+ );
+ // No run registered, so no assistant row ever streamed and no
+ // turn/agent boundary frames fired (the worker's settle synthesizes
+ // its own trailing `agent_end` fallback for runs without a model
+ // turn).
+ assert!(
+ events.iter().all(|event| !matches!(
+ event,
+ EngineEvent::AssistantMessage(_) | EngineEvent::AssistantUpdate { .. }
+ )),
+ "no assistant row streamed (the provider call never started): {events:?}"
+ );
+ assert!(
+ events.iter().all(|event| !matches!(
+ event,
+ EngineEvent::TurnEnd { .. } | EngineEvent::AgentEnd { .. }
+ )),
+ "no run boundary frames (no run registered): {events:?}"
+ );
+ // The served-path proof: the scripted response was never consumed —
+ // the next delivery receives it as its first reply.
+ let mut next_events: Vec<EngineEvent> = Vec::new();
+ admit(&engine, "the next turn".to_string(), &mut next_events);
+ assert!(
+ next_events.iter().any(|event| matches!(
+ event,
+ EngineEvent::AssistantMessage(message)
+ if message["content"]
+ == serde_json::json!([{ "type": "text", "text": "raced reply" }])
+ )),
+ "the untouched first response served the next delivery: {next_events:?}"
+ );
+}
+
/// The settled turn's terminal frame (TS `turn_end`): the loop's boundary
/// event carries the final assistant message as its payload with the
/// turn's (empty) tool-result list, positioned between the final
diff --git a/crates/pa-daemon/src/agent_engine/turn/model.rs b/crates/pa-daemon/src/agent_engine/turn/model.rs
index a30fc9db55..71c80b06a1 100644
--- a/crates/pa-daemon/src/agent_engine/turn/model.rs
+++ b/crates/pa-daemon/src/agent_engine/turn/model.rs
@@ -95,6 +95,22 @@ impl AgentSessionEngine {
}
}
};
+ // The delivery's cancel flag is consulted at the admission, before
+ // the agent run registers: an abort that landed after this
+ // delivery's pickup but before the registration (the lazy session
+ // build and the policy reads widened TS's microscopic
+ // registration gap to the whole admission prefix) is otherwise
+ // lost — `abort_in_flight_turn`'s `agent.abort()` found an empty
+ // run slot, the run registers fresh after it, and the turn runs
+ // its full provider hold (the abort-and-send idle race: the
+ // session never went idle after the abort). The probe is
+ // delivery-scoped by construction (the pickup clears the flag,
+ // the next pickup re-arms it), so this consult aborts exactly the
+ // turn the abort raced. The remaining window (the run's own
+ // registration) is TS's own gap scale.
+ if aborted() {
+ return TurnResult::Aborted;
+ }
// A routed image-model episode applies its override BEFORE the
// first provider call: the serving target swaps to the image
// model and the run carries the route's model override (the
@@ -196,7 +212,14 @@ impl AgentSessionEngine {
drop_trailing_assistant(&agent).await;
}
match self
- .run_turn_once(&agent, &prompt, first, boundary_passed, &mut **emit)
+ .run_turn_once(
+ &agent,
+ &prompt,
+ first,
+ boundary_passed,
+ aborted,
+ &mut **emit,
+ )
.await
{
Ok(TurnOnce::Message { assistant }) => {
diff --git a/crates/pa-daemon/src/agent_engine/turn/run_once.rs b/crates/pa-daemon/src/agent_engine/turn/run_once.rs
index d13f08775d..44b4a5f0fb 100644
--- a/crates/pa-daemon/src/agent_engine/turn/run_once.rs
+++ b/crates/pa-daemon/src/agent_engine/turn/run_once.rs
@@ -68,13 +68,18 @@ impl AgentSessionEngine {
/// arrive. The first attempt prompts the session; retries continue the
/// parked turn. Returns the turn outcome: the final assistant message
/// (provider failures included), `None` when no assistant message was
- /// produced, or `Aborted` when the emit callback cancelled the run.
+ /// produced, or `Aborted` when the emit callback cancelled the run or
+ /// the delivery's cancel flag raced the admission (the abort-and-send
+ /// idle race: an abort landing between the runner's pickup and the
+ /// agent run's registration was lost to a run that registered fresh
+ /// after it — see [`Self::run_model_turn`]'s admission consult).
pub(super) async fn run_turn_once(
&self,
agent: &std::sync::Arc<pa_agent::agent::Agent>,
prompt: &TurnPrompt,
first_attempt: bool,
boundary_passed: &std::sync::Arc<std::sync::atomic::AtomicBool>,
+ aborted: &dyn Fn() -> bool,
emit: &mut dyn FnMut(EngineEvent) -> bool,
) -> anyhow::Result<TurnOnce> {
// Stream assistant events while the turn runs.
@@ -367,7 +372,18 @@ impl AgentSessionEngine {
// arrives. Buffering events until the future resolves is what made
// clients render a turn as one final batch.
let prompt = prompt.clone();
+ // The same admission consult as [`Self::run_model_turn`]'s, at the
+ // admission future's head — the last stop before the agent run
+ // registers: an abort landing in the driver's or the subscription's
+ // prefix (after the model-turn consult, before the registration)
+ // is honoured here the same way, so the whole [pickup,
+ // registration] window honours the delivery's cancel flag.
+ let abort_raced_admission = std::sync::atomic::AtomicBool::new(false);
let mut admitted = std::pin::pin!(async {
+ if aborted() {
+ abort_raced_admission.store(true, std::sync::atomic::Ordering::SeqCst);
+ return Ok(());
+ }
if first_attempt {
// The session lock covers the clone only: the turn below
// runs for the whole provider stream, and holding the
@@ -479,6 +495,13 @@ impl AgentSessionEngine {
if aborted {
return Ok(TurnOnce::Aborted);
}
+ // The admission consult fired: the turn never started (no run
+ // registered, no provider call) — the aborted outcome, never an
+ // admission error the retry driver would classify as a provider
+ // failure and re-issue.
+ if abort_raced_admission.load(std::sync::atomic::Ordering::SeqCst) {
+ return Ok(TurnOnce::Aborted);
+ }
if let Some(error) = admission_error {
return Err(anyhow::anyhow!("{error:#}"));
}
diff --git a/crates/pa-daemon/src/worker/turn.rs b/crates/pa-daemon/src/worker/turn.rs
index ee3c2185be..0778a34d72 100644
--- a/crates/pa-daemon/src/worker/turn.rs
+++ b/crates/pa-daemon/src/worker/turn.rs
@@ -512,6 +512,15 @@ impl TurnRunner {
// run).
let engine_agent_end = Arc::new(std::sync::atomic::AtomicBool::new(false));
let engine_agent_end_seen = Arc::clone(&engine_agent_end);
+ // Whether the abort gate ever observed the delivery's cancel flag
+ // DURING this turn (the per-event read below): the fallback
+ // `agent_end` keys its silence on THIS association — an abort
+ // landing after the turn's last emitted event (a late abort
+ // racing the settle) never armed the gate and must not suppress
+ // the completed run's fallback (the macroscope finding: the
+ // post-join flag read raced `handle_abort`).
+ let abort_gate_armed = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let abort_gate_armed_seen = Arc::clone(&abort_gate_armed);
let turn = tokio::task::spawn_blocking(move || {
// Whether the engine already emitted its own terminal
// `turn_end` frame this run (the loop emits one per turn —
@@ -610,10 +619,27 @@ impl TurnRunner {
| EngineEvent::DoneAborted
);
let mut core = core.lock().unwrap();
- if core.abort_requested
- && (core.suppress_aborted_row || !(abort_settle || aborted_row))
- {
- return false;
+ if core.abort_requested {
+ // The sighting arms the fallback's silence only when
+ // it is load-bearing for this run: the gate is
+ // dropping one of this run's frames (the suppressed-
+ // row class), or the event itself carries the aborted
+ // outcome (the admission consult's `DoneAborted`, the
+ // engine's aborted row). A flag sighting on the plain
+ // settle frames of a run that completed on its own -
+ // the trailing `Done` of a finished session command
+ // or pre-model failure - cancels nothing of it: the
+ // fallback closer must still pair the run's opening
+ // `agent_start` (TS: an abort of a finished run
+ // no-ops; the flag stays delivery-scoped and the next
+ // pickup clears it).
+ if core.suppress_aborted_row || !(abort_settle || aborted_row) {
+ abort_gate_armed_seen.store(true, std::sync::atomic::Ordering::SeqCst);
+ return false;
+ }
+ if aborted_row || matches!(&event, EngineEvent::DoneAborted) {
+ abort_gate_armed_seen.store(true, std::sync::atomic::Ordering::SeqCst);
+ }
}
// The engine cuts its in-memory entries; its
// `firstKeptEntryId` never matches this store's file ids,
@@ -1148,7 +1174,21 @@ impl TurnRunner {
// included — the TS `agent_end` `messages` payload) are the real
// frames, and a run whose `agent_end` the abort gate swallowed
// stays silent exactly like TS (the compact path's detached run).
- if !engine_agent_end.load(std::sync::atomic::Ordering::SeqCst) {
+ // An ABORTED settle keeps the same silence: the admission
+ // consult's pre-run abort ends the turn with NO engine
+ // `agent_end` at all (no run registered — the
+ // compact-interrupt probe's suppressed-run wire shape, which the
+ // fallback would otherwise break with a synthesized frame). The
+ // association is the abort GATE's own observation during the
+ // turn (the per-event flag read), never a post-join re-read of
+ // the flag: an abort landing after the turn's last emitted event
+ // cancels nothing of this run and must not suppress its fallback
+ // (the flag stays armed until the next pickup — a settle-time
+ // re-read would race `handle_abort` and silence a completed
+ // session-command or pre-model-failure run).
+ if !engine_agent_end.load(std::sync::atomic::Ordering::SeqCst)
+ && !abort_gate_armed.load(std::sync::atomic::Ordering::SeqCst)
+ {
self.emit_turn_event(json!({ "type": "agent_end" }));
}
let snapshot = {
diff --git a/crates/pa-daemon/src/worker/turn_stream_tests.rs b/crates/pa-daemon/src/worker/turn_stream_tests.rs
index 086cb7a9a3..95d6d5e6be 100644
--- a/crates/pa-daemon/src/worker/turn_stream_tests.rs
+++ b/crates/pa-daemon/src/worker/turn_stream_tests.rs
@@ -10,6 +10,7 @@ use crate::engine::{
// fixtures stay here (burst_runner, turn_session_events, positions_of)
// - every family drives them, and the children reach them + the worker
// namespace through `use super::*`.
+mod abort_idle_race;
mod broadcast;
mod burst;
mod feed;
@@ -119,3 +120,179 @@ fn positions_of(events: &[Value], frame_type: &str) -> Vec<usize> {
.map(|(index, _)| index)
.collect()
}
+
+// The abort gate's arm semantics (the fallback closer's silence
+// association), pinned on the wire: a scripted engine replays the
+// sighting frames through the worker's own gated emit with the flag
+// preset (`run_turn` driven directly - the pickup's delivery-scoped
+// clear never ran), so the final-emit race is deterministic.
+struct GateProbeEngine {
+ frames: Vec<EngineEvent>,
+}
+
+impl SessionEngine for GateProbeEngine {
+ fn run_prompt(
+ &self,
+ _prompt_index: usize,
+ _request: PromptRequest,
+ _aborted: &dyn Fn() -> bool,
+ emit: &mut dyn FnMut(EngineEvent) -> bool,
+ ) {
+ for frame in &self.frames {
+ if !emit(frame.clone()) {
+ return;
+ }
+ }
+ }
+
+ fn run_side_question(
+ &self,
+ _request: SideQuestionRequest,
+ _signal: &pa_agent::abort::AbortSignal,
+ _sink: &pa_core::session_engine::side_question::SideQuestionSink,
+ ) -> SideQuestionOutcome {
+ SideQuestionOutcome::Failed {
+ answer: String::new(),
+ error: "unsupported".to_string(),
+ }
+ }
+
+ fn run_compaction(
+ &self,
+ _request: CompactionRequest,
+ _signal: &pa_agent::abort::AbortSignal,
+ ) -> CompactionOutcome {
+ CompactionOutcome::Skipped {
+ message: "nothing to compact".to_string(),
+ }
+ }
+
+ fn run_branch_summary(
+ &self,
+ _request: crate::engine::BranchSummaryRequest,
+ _signal: &pa_agent::abort::AbortSignal,
+ ) -> crate::engine::BranchSummaryOutcome {
+ crate::engine::BranchSummaryOutcome::Failed {
+ error: "unsupported".to_string(),
+ }
+ }
+
+ fn rebuild_session_context(
+ &self,
+ _branch_entries: Vec<pa_types::session::FileEntry>,
+ _goal_reload: pa_core::session_engine::goal_driver::GoalBranchReload,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
+/// One gated sighting battery: the scripted frames through the worker's
+/// turn with the abort flag (and the suppressed-row class) preset.
+async fn gate_sighting_events(
+ frames: Vec<EngineEvent>,
+ abort_requested: bool,
+ suppress_aborted_row: bool,
+) -> Vec<Value> {
+ let engine: Arc<dyn SessionEngine> = Arc::new(GateProbeEngine { frames });
+ let runner = burst_runner(Arc::clone(&engine));
+ {
+ let mut core = runner.core.lock().unwrap();
+ core.abort_requested = abort_requested;
+ core.suppress_aborted_row = suppress_aborted_row;
+ }
+ let mut subscription = runner.events.subscribe();
+ runner
+ .run_turn(
+ engine,
+ vec![QueuedItem {
+ priority: QueuePriority::Human,
+ preview: None,
+ message: "gate".to_string(),
+ custom_message: None,
+ agent_message: None,
+ queue_key: None,
+ admission_id: None,
+ images: Vec::new(),
+ done: None,
+ queue_visible: true,
+ policy: TurnPolicy::Queued,
+ forced_batch: false,
+ }],
+ )
+ .await;
+ let mut events = Vec::new();
+ while let Ok(frame) = subscription.try_recv() {
+ if frame.outbound_type == "session_event" {
+ if let Ok(outbound) = serde_json::from_slice::<Value>(&frame.payload) {
+ events.push(outbound["event"].clone());
+ }
+ }
+ }
+ events
+}
+
+/// The finding's final-emit race, made deterministic: an abort flag
+/// sighting on the trailing `Done` of a run that completed on its own
+/// (the session-command / pre-model-failure shape - no aborted outcome,
+/// no suppressed row) must not arm the fallback's silence: the closer
+/// still pairs the run's opening `agent_start` (TS: an abort of a
+/// finished run no-ops).
+#[tokio::test]
+async fn a_late_abort_sighting_on_a_completed_runs_done_keeps_the_fallback_closer() {
+ let events = gate_sighting_events(vec![EngineEvent::Done(Ok(()))], true, false).await;
+ let starts = positions_of(&events, "agent_start");
+ let ends = positions_of(&events, "agent_end");
+ assert_eq!(starts.len(), 1, "the run opens one agent_start: {events:?}");
+ assert_eq!(
+ ends.len(),
+ 1,
+ "the fallback closer pairs the opening agent_start: {events:?}"
+ );
+ assert!(
+ ends[0] > starts[0],
+ "the closer lands after the open: {events:?}"
+ );
+}
+
+/// The admission consult's settle: `DoneAborted` with no engine
+/// `agent_end` - the aborted-outcome carrier arms the silence, the
+/// suppressed-run wire shape holds (no synthesized closer for the
+/// aborted turn).
+#[tokio::test]
+async fn done_aborted_arms_the_fallback_silence() {
+ let events = gate_sighting_events(vec![EngineEvent::DoneAborted], true, false).await;
+ assert!(
+ positions_of(&events, "agent_end").is_empty(),
+ "the aborted settle keeps the suppressed-run silence: {events:?}"
+ );
+}
+
+/// The suppressed-row class (the compact path's detached run): a settle
+/// frame that would forward on a plain flag sighting (the closer test's
+/// shape) drops when `suppress_aborted_row` is set - the arm is what the
+/// assertion discriminates on, not the flag: without the suppress term
+/// the same `ToolResultMessage` reaches the wire as its message pair.
+#[tokio::test]
+async fn the_suppressed_row_sighting_drops_and_arms_the_silence() {
+ let events = gate_sighting_events(
+ vec![
+ EngineEvent::ToolResultMessage(json!({
+ "role": "toolResult",
+ "text": "the aborted tool's error result",
+ })),
+ EngineEvent::Done(Ok(())),
+ ],
+ true,
+ true,
+ )
+ .await;
+ assert!(
+ positions_of(&events, "message_start").is_empty()
+ && positions_of(&events, "message_end").is_empty(),
+ "the suppressed settle frame never reaches the wire: {events:?}"
+ );
+ assert!(
+ positions_of(&events, "agent_end").is_empty(),
+ "the suppressed-row sighting arms the silence: {events:?}"
+ );
+}
diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/abort_idle_race.rs b/crates/pa-daemon/src/worker/turn_stream_tests/abort_idle_race.rs
new file mode 100644
index 0000000000..0752eb8fbd
--- /dev/null
+++ b/crates/pa-daemon/src/worker/turn_stream_tests/abort_idle_race.rs
@@ -0,0 +1,340 @@
+//! The abort-and-send idle-race rate harness (the gate-pool lane's honest
+//! disposition): `abort_and_send_queued`'s settle path left the session
+//! busy forever on an intermittent solo-reproducing interleaving
+//! (`abort_and_send_queued_delivers_the_steering_batch_then_the_follow_ups`
+//! hung to the harness wall and panicked at `queue.rs:545` — "the session
+//! never went idle after the abort" — on 1/3 quiet-VM solo runs). This
+//! harness reproduces that interleaving AT RATE: the held turn's delay
+//! and the idle window shrink so a miss costs a second instead of a
+//! hang, every miss dumps the settle-path state (the worker core, the
+//! engine's turn agent, the agent run's abort signal), and the run ends
+//! with a one-line verdict the rate driver classifies.
+//!
+//! Knobs (all default to the single-rep shape):
+//! - `PA_RACE_REPS`: repetitions in one process (default 50; a
+//! long battery should chunk processes — the workers accumulate
+//! engines and runtimes in-process past ~130 reps).
+//! - `PA_RACE_DELAY_MS`: the held turn's faux delay (default 3000; the
+//! product-family test uses `600_000` — the delay's magnitude does not
+//! change the abort-vs-admission interleaving, only the miss cost).
+//! - `PA_RACE_IDLE_WINDOW_MS`: the wait-for-idle window the settle
+//! latency report uses (default 300; an honored abort settles the
+//! held turn in single-digit ms).
+//! - `PA_RACE_EVENT_LOG`: path the per-rep event frames append to
+//! (forwarded to the worker's `PA_DAEMON_EVENT_LOG` seam).
+//!
+//! THE VERDICT CLASSES (the harness deliberately fires the abort without
+//! a positive-signal sync, so the abort can land anywhere in the
+//! delivery — the admission prefix included, exactly the product race):
+//! - `lost_aborts` — the PRODUCT race this harness exists for: the abort
+//! never reached the run, the held turn serves "held reply" as its OWN
+//! reply (the first assistant row behind ONE user row), the pre-fix
+//! dump shape (busy=true `abort_requested=true` `steering_len=2`
+//! `run_signal=live`). ANY occurrence fails the harness.
+//! - `fixture_leaks` — the expected post-fix artifact of the same
+//! interleaving: the consult aborts the turn BEFORE its provider call,
+//! so the faux step the held turn never consumed (the delayed one)
+//! leaks to the batch turn, whose co-delivered reply serves "held
+//! reply" behind the batch's user rows (the pop-at-call contract: no
+//! call, no consumption). With a real provider the batch turn serves
+//! promptly; the class is REPORTED, never asserted.
+//! - `green` — the abort landed on the registered run (the normal
+//! abort path) and the whole queue settled inside the window.
+//!
+//! `#[ignore]`d: the rate driver invokes it explicitly; it never runs in
+//! the normal test battery.
+use super::*;
+
+/// Read one numeric knob with a default.
+fn race_knob(name: &str, default: u64) -> u64 {
+ std::env::var(name)
+ .ok()
+ .and_then(|value| value.parse().ok())
+ .unwrap_or(default)
+}
+
+/// The state at the miss: everything the settle path owns, one dump line
+/// each, so the interleaving that left the session never-idle reads off
+/// the transcript directly.
+fn dump_hang_state(worker: &Worker) -> String {
+ use std::fmt::Write as _;
+ let core = worker.core.lock().unwrap();
+ let mut dump = format!(
+ "core: busy={} abort_requested={} retry_abort_requested={} \
+ queued_input_suspended={} compacting={} shutdown_requested={} \
+ forced_all_steering={} steering_len={} follow_up_len={} \
+ running_tool_calls={}",
+ core.busy,
+ core.abort_requested,
+ core.retry_abort_requested,
+ core.queued_input_suspended,
+ core.compacting,
+ core.shutdown_requested,
+ core.forced_all_steering,
+ core.steering.len(),
+ core.follow_up.len(),
+ core.running_tool_calls.len(),
+ );
+ drop(core);
+ // The engine's abort target: present? and does the agent's ACTIVE
+ // run carry an aborted signal? A miss with `run_signal=aborted`
+ // means the abort landed but the turn never settled; a miss with
+ // `run_signal=live` means the abort never reached the run (a lost
+ // abort at a registration boundary); `no-run` means no active run
+ // at all (the settle raced the next admission).
+ match worker.agent_engine.as_ref().map(|engine| {
+ engine
+ .turn_agent
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()
+ }) {
+ Some(Some(agent)) => {
+ let run_signal = match agent.signal() {
+ Some(signal) => {
+ if signal.is_aborted() {
+ "aborted"
+ } else {
+ "live"
+ }
+ }
+ None => "no-run",
+ };
+ let _ = write!(dump, " turn_agent=present run_signal={run_signal}");
+ }
+ Some(None) => dump.push_str(" turn_agent=absent"),
+ None => dump.push_str(" turn_agent=none-engine"),
+ }
+ dump
+}
+
+// The faux registry is process-global: the lock guard must span the
+// whole async flow (every rep registers into the same registry).
+#[allow(clippy::await_holding_lock)]
+#[tokio::test]
+#[ignore = "the rate harness: run with PA_RACE_* knobs (see the module docs)"]
+async fn abort_and_send_idle_race_rate_harness() {
+ let _faux = crate::agent_engine::tests::FAUX_TEST_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let reps = race_knob("PA_RACE_REPS", 50).clamp(1, 100_000);
+ let delay_ms = race_knob("PA_RACE_DELAY_MS", 3000).clamp(200, 600_000);
+ let window_ms = race_knob("PA_RACE_IDLE_WINDOW_MS", 300).clamp(50, 600_000);
+ // The worker's event-log seam: one file for the whole run, one
+ // rep-marker line per rep, the frames append behind each marker.
+ let event_log = std::env::var("PA_RACE_EVENT_LOG").ok();
+ if let Some(path) = &event_log {
+ std::env::set_var("PA_DAEMON_EVENT_LOG", path);
+ }
+ let mut lost_aborts = 0usize;
+ let mut fixture_leaks = 0usize;
+ let mut green_reps = 0usize;
+ for rep in 1..=reps {
+ if let Some(path) = &event_log {
+ if let Ok(mut file) = std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(path)
+ {
+ use std::io::Write;
+ let _ = writeln!(file, "=== RATE_HARNESS rep {rep} ===");
+ }
+ }
+ let dir = std::env::temp_dir().join(format!(
+ "pa-worker-abort-race-{rep}-{}",
+ uuid::Uuid::new_v4()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ let config = WorkerConfig {
+ socket_path: dir.join("worker.sock"),
+ supervisor_socket_path: PathBuf::new(),
+ token: "token".to_string(),
+ worker_instance_id: String::new(),
+ active_session_id: format!("abort-race-{rep}"),
+ agent_dir: dir.join("agent"),
+ recovery_journal_path: dir.join("recovery.jsonl"),
+ telemetry_disabled: None,
+ script: Some(json!({
+ "engine": "faux",
+ "responses": [
+ { "text": "held reply", "delayMs": delay_ms },
+ "batch reply",
+ "follow-up reply"
+ ],
+ })),
+ };
+ let worker = std::sync::Arc::new(Worker::new(config, None));
+ let created = worker
+ .dispatch(
+ "create",
+ &json!({ "noSession": true, "cwd": "/tmp", "name": format!("abort-race-{rep}") }),
+ )
+ .await;
+ assert!(created.success, "rep {rep}: create failed: {created:?}");
+ // The held turn parks the queue behind it (the delay hold).
+ let prompt = worker
+ .dispatch(
+ "prompt",
+ &json!({
+ "activeSessionId": format!("abort-race-{rep}"),
+ "message": "held turn for the batch abort",
+ }),
+ )
+ .await;
+ assert!(prompt.success, "rep {rep}: prompt failed: {prompt:?}");
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
+ loop {
+ if worker.core.lock().unwrap().busy {
+ break;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "rep {rep}: the held turn was never admitted"
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;
+ }
+ // The product-family test's exact pacing: the hold has the turn
+ // when this sleep ends, the steers queue behind it, and the abort
+ // fires against the in-flight run.
+ tokio::time::sleep(std::time::Duration::from_millis(400)).await;
+ for message in ["steering one", "steering two"] {
+ let steered = worker
+ .dispatch("steer", &json!({ "message": message }))
+ .await;
+ assert!(steered.success, "rep {rep}: steer failed: {steered:?}");
+ }
+ let follow = worker
+ .dispatch(
+ "follow_up",
+ &json!({ "message": "follow up after the batch" }),
+ )
+ .await;
+ assert!(follow.success, "rep {rep}: follow_up failed: {follow:?}");
+ let sent = worker.abort_and_send_queued();
+ assert!(
+ sent,
+ "rep {rep}: the armed steering batch sent with the abort"
+ );
+ // THE SETTLE-LATENCY WINDOW first (the original symptom's
+ // observable): an honored abort settles the whole queue in
+ // single-digit ms when the abort lands on the registered run; the
+ // consult's leaked-step class inherits the delay for the batch
+ // turn (the fixture artifact); a lost abort inherits it for the
+ // held turn (the product race).
+ let idle = tokio::time::timeout(
+ std::time::Duration::from_millis(window_ms),
+ worker.dispatch("wait_for_idle", &json!({})),
+ )
+ .await;
+ let idle_ok = matches!(&idle, Ok(response) if response.success);
+ // THE PRODUCT ASSERTION (the race this harness exists for): the
+ // abort is honored — the held turn NEVER serves its scripted
+ // reply. Classified by the settled transcript, never by wall
+ // latency: the first assistant row names the turn that won the
+ // race for the held step. The aborted row is the registered-run
+ // abort; "held reply" behind ONE user row is the held turn's own
+ // reply (the LOST abort — the run served its hold); "held reply"
+ // behind the batch's co-delivered user rows is the consult's
+ // honored abort leaking the unconsumed step to the batch turn
+ // (the fixture artifact).
+ let first_row =
+ tokio::time::timeout(std::time::Duration::from_millis(delay_ms + 10_000), async {
+ loop {
+ let messages = worker.dispatch("get_messages", &json!({})).await;
+ if !messages.success {
+ anyhow::bail!("rep {rep}: get_messages failed: {messages:?}");
+ }
+ let rows = messages
+ .data
+ .as_ref()
+ .and_then(|data| data.get("messages"))
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+ if let Some(index) = rows
+ .iter()
+ .position(|row| crate::types::message_role(row) == Some("assistant"))
+ {
+ let users_before = rows[..index]
+ .iter()
+ .filter(|row| crate::types::message_role(row) == Some("user"))
+ .count();
+ return Ok((rows[index].clone(), users_before));
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;
+ }
+ })
+ .await;
+ let mut honored = false;
+ match first_row {
+ Ok(Ok((row, users_before))) => {
+ let aborted = row.get("stopReason").and_then(Value::as_str) == Some("aborted");
+ let held_reply = crate::types::message_text(&row).contains("held reply");
+ if held_reply && users_before < 2 {
+ lost_aborts += 1;
+ eprintln!(
+ "RATE_HARNESS LOST_ABORT rep {rep} of {reps}: the held turn served \"held reply\" as its own reply (users_before={users_before}) - the abort never reached the run: {}",
+ dump_hang_state(&worker)
+ );
+ // Wait out the busy session (the batch and the
+ // follow-up lanes still hold work) so the next rep
+ // starts on an idle queue, exactly like the leak
+ // branch - the lost abort's worker otherwise keeps
+ // delivering behind the harness's back.
+ let _ = tokio::time::timeout(
+ std::time::Duration::from_millis(delay_ms + 10_000),
+ worker.dispatch("wait_for_idle", &json!({})),
+ )
+ .await;
+ } else {
+ honored = true;
+ if !idle_ok {
+ fixture_leaks += 1;
+ eprintln!(
+ "RATE_HARNESS FIXTURE_LEAK rep {rep} of {reps} (users_before={users_before}, aborted_row={aborted}): the consult honored the abort; the unconsumed held step leaked to the batch turn: {}",
+ dump_hang_state(&worker)
+ );
+ // Wait out the inherited hold so the next rep
+ // starts clean.
+ let settle = tokio::time::timeout(
+ std::time::Duration::from_millis(delay_ms + 10_000),
+ worker.dispatch("wait_for_idle", &json!({})),
+ )
+ .await;
+ let settle_ok = matches!(&settle, Ok(response) if response.success);
+ if !settle_ok {
+ // The inherited hold outlived its whole
+ // window: the session never settled - count
+ // it, never exit green on a busy session.
+ lost_aborts += 1;
+ }
+ eprintln!(
+ "RATE_HARNESS FIXTURE_LEAK rep {rep}: post-leak settle ok={settle_ok}"
+ );
+ }
+ }
+ }
+ Ok(Err(error)) => {
+ lost_aborts += 1;
+ eprintln!("RATE_HARNESS LOST_ABORT rep {rep}: {error:#}");
+ }
+ Err(_) => {
+ lost_aborts += 1;
+ eprintln!(
+ "RATE_HARNESS LOST_ABORT rep {rep} of {reps}: the first assistant row never settled past the delay: {}",
+ dump_hang_state(&worker)
+ );
+ }
+ }
+ if idle_ok && honored {
+ green_reps += 1;
+ }
+ }
+ println!(
+ "RATE_HARNESS reps={reps} green={green_reps} lost_aborts={lost_aborts} fixture_leaks={fixture_leaks}"
+ );
+ assert!(
+ lost_aborts == 0,
+ "the idle race reproduced at rate: {lost_aborts}/{reps} lost aborts"
+ );
+}
diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs b/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs
index a991be7ce2..67960f8d56 100644
--- a/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs
+++ b/crates/pa-daemon/src/worker/turn_stream_tests/queue.rs
@@ -514,6 +514,39 @@ async fn abort_and_send_queued_delivers_the_steering_batch_then_the_follow_ups()
);
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
}
+ // The TS acceptance case's positive-signal discipline (ENG-5991's
+ // `waitForToolStart`): the abort must land on the REGISTERED run —
+ // `core.busy` flips at the runner's pickup, before the engine's
+ // admission, so a busy-only sync races the first turn's session
+ // build and the abort lands in the admission prefix (the
+ // abort-and-send idle race: the consult aborts the turn before its
+ // provider call, the faux step the held turn never consumed leaks
+ // to the batch turn, and the batch inherits the 600s hold). The
+ // run slot is the registration signal: once it exists the abort
+ // lands on the run itself, the shape this family means to pin.
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
+ loop {
+ let registered = worker
+ .agent_engine
+ .as_ref()
+ .and_then(|engine| {
+ engine
+ .turn_agent
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()
+ })
+ .and_then(|agent| agent.signal())
+ .is_some();
+ if registered {
+ break;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "the held turn's run never registered"
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;
+ }
tokio::time::sleep(std::time::Duration::from_millis(400)).await;
// Two steering messages and one follow-up behind the streaming
// turn (the real wire admission path: queue-visible, policy-queued