Skip to content

Commit 45e00ec

Browse files
loganjLarry
andcommitted
fix(acp): report fixed admission reasons for refused native steers
The stock admission owner (AgentPool::send_steer) returned conflated transport strings for mailbox refusals and the main loop's fallback log dumped the whole error via Debug. Give refusals a fixed structured vocabulary — task_absent, sender_absent, mailbox_full, mailbox_closed — carried in the existing Transport error and reported as the fallback log's reason field. Returns, fallback semantics, and ack-native post-admission errors stay untouched. Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Signed-off-by: Logan Johnson <[email protected]>
1 parent 277afba commit 45e00ec

2 files changed

Lines changed: 295 additions & 8 deletions

File tree

‎crates/buzz-acp/src/lib.rs‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4400,9 +4400,20 @@ fn try_native_steer(
44004400
true
44014401
}
44024402
Err(e) => {
4403+
// Structured fixed-reason label from the stock admission owner
4404+
// (`pool::send_steer`): task_absent / sender_absent /
4405+
// mailbox_full / mailbox_closed. Only admission refusals reach
4406+
// this arm — the ack watcher is spawned solely on `Ok(())`, so
4407+
// ack-native write failures are logged by the main loop's
4408+
// SteerAck arm instead and are never conflated with admission.
4409+
// The label never carries request content.
4410+
let reason = e
4411+
.admission_reason()
4412+
.map(|reason| reason.as_str())
4413+
.unwrap_or("unclassified");
44034414
tracing::info!(
44044415
channel = %channel_id,
4405-
error = ?e,
4416+
reason,
44064417
"non-cancelling steer not accepted — falling back to cancel+merge"
44074418
);
44084419
false

‎crates/buzz-acp/src/pool.rs‎

Lines changed: 283 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -536,7 +536,11 @@ pub enum SteerError {
536536
/// running or just ended.
537537
AgentError { code: i64, message: String },
538538
/// Transport-level failure: write error, read EOF, JSON-RPC framing
539-
/// violation, etc. The string carries the underlying `AcpError`'s display.
539+
/// violation, etc. For read-loop (post-admission) failures the string
540+
/// carries the underlying `AcpError`'s display. For admission refusals
541+
/// returned by [`AgentPool::send_steer`] it instead carries the fixed
542+
/// [`SteerAdmissionReason`] label so callers can log a structured
543+
/// reason without dumping request content.
540544
Transport(String),
541545
/// At steer-write time neither steer transport was available: no
542546
/// `expectedRunId` (`AcpClient::active_run_id` was `None`, so the
@@ -572,6 +576,80 @@ pub enum SteerError {
572576
PromptCompleted,
573577
}
574578

579+
/// Fixed-vocabulary reason the stock admission owner
580+
/// ([`AgentPool::send_steer`]) refused a native-steer request before any
581+
/// wire write was attempted.
582+
///
583+
/// These are structured diagnostic labels only — never request content,
584+
/// agent output, or tokens. They classify *admission* (getting the request
585+
/// into the in-flight read loop's capacity-1 steer mailbox) and are
586+
/// deliberately distinct from post-admission failures: a steer that was
587+
/// admitted and then failed at the wire keeps [`SteerError::Transport`]
588+
/// carrying the underlying `AcpError` display, and `AgentError` /
589+
/// `ExpectedRunIdMissing` / `OutcomeRejected` keep their own variants (see
590+
/// [`SteerError::admission_reason`]).
591+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
592+
pub enum SteerAdmissionReason {
593+
/// No in-flight task owns the scope. Returned as
594+
/// [`SteerError::PromptCompleted`], which keeps its distinct
595+
/// release-and-normal-dispatch semantics — a separate branch, not a
596+
/// transport refusal.
597+
TaskAbsent,
598+
/// The in-flight task has no `steer_tx` sender installed.
599+
SenderAbsent,
600+
/// The capacity-1 steer mailbox already holds one in-flight steer.
601+
MailboxFull,
602+
/// The read loop's steer receiver has been torn down.
603+
MailboxClosed,
604+
}
605+
606+
impl SteerAdmissionReason {
607+
/// Fixed, greppable label. Carried in the admission refusal's
608+
/// [`SteerError::Transport`] string and in the main loop's fallback
609+
/// log `reason` field; never contains request content.
610+
pub fn as_str(self) -> &'static str {
611+
match self {
612+
Self::TaskAbsent => "task_absent",
613+
Self::SenderAbsent => "sender_absent",
614+
Self::MailboxFull => "mailbox_full",
615+
Self::MailboxClosed => "mailbox_closed",
616+
}
617+
}
618+
619+
/// Wrap the reason as the transport-refusal error `send_steer` returns,
620+
/// preserving the historical `Err(SteerError::Transport(_))` return
621+
/// contract for these branches.
622+
fn transport_refusal(self) -> SteerError {
623+
SteerError::Transport(self.as_str().to_owned())
624+
}
625+
}
626+
627+
impl SteerError {
628+
/// Structured admission-refusal classification for errors produced by
629+
/// the stock admission owner, [`AgentPool::send_steer`]. Returns `None`
630+
/// for every post-admission error — ack-native steer write failures
631+
/// (`Transport` carrying an `AcpError` display), `AgentError`,
632+
/// `ExpectedRunIdMissing`, and `OutcomeRejected` — so admission
633+
/// refusals are never conflated with wire failures. The fixed labels
634+
/// mirror [`SteerAdmissionReason::as_str`] and are pinned together by
635+
/// unit tests.
636+
pub fn admission_reason(&self) -> Option<SteerAdmissionReason> {
637+
match self {
638+
Self::PromptCompleted => Some(SteerAdmissionReason::TaskAbsent),
639+
Self::Transport(msg) => match msg.as_str() {
640+
"sender_absent" => Some(SteerAdmissionReason::SenderAbsent),
641+
"mailbox_full" => Some(SteerAdmissionReason::MailboxFull),
642+
"mailbox_closed" => Some(SteerAdmissionReason::MailboxClosed),
643+
// Any other Transport string is a post-admission wire
644+
// failure (an AcpError display from the read loop), not an
645+
// admission refusal.
646+
_ => None,
647+
},
648+
_ => None,
649+
}
650+
}
651+
}
652+
575653
/// Outcome of a mid-turn steer, sent from the read loop back to the
576654
/// main loop's ack watcher.
577655
#[derive(Debug)]
@@ -1102,9 +1180,11 @@ impl AgentPool {
11021180
/// Returns `Ok(())` if the request was accepted by the read loop's
11031181
/// receiver (capacity-1 mpsc; one slot is the single in-flight steer
11041182
/// write). Returns `Err(SteerError::Transport(_))` on `Full`/`Closed`
1105-
/// (already-in-flight write, or read loop torn down). Callers must
1106-
/// fall back to the universal `ControlSignal::Steer` cancel+merge path
1107-
/// on `Err`.
1183+
/// (already-in-flight write, or read loop torn down); the `Transport`
1184+
/// string is the fixed [`SteerAdmissionReason`] label
1185+
/// (`sender_absent`/`mailbox_full`/`mailbox_closed`), never request
1186+
/// content. Callers must fall back to the universal
1187+
/// `ControlSignal::Steer` cancel+merge path on `Err`.
11081188
///
11091189
/// This does **not** spawn the ack watcher — the caller owns the
11101190
/// oneshot `ack_tx` inside `SteerRequest` and is responsible for
@@ -1131,9 +1211,20 @@ impl AgentPool {
11311211
let tx = meta
11321212
.steer_tx
11331213
.as_ref()
1134-
.ok_or_else(|| SteerError::Transport("steer_tx not installed".into()))?;
1135-
tx.try_send(request)
1136-
.map_err(|e| SteerError::Transport(e.to_string()))
1214+
.ok_or_else(|| SteerAdmissionReason::SenderAbsent.transport_refusal())?;
1215+
match tx.try_send(request) {
1216+
Ok(()) => Ok(()),
1217+
// Capacity-1 mailbox already holds one in-flight steer write.
1218+
// The refused request (including its oneshot ack) comes back
1219+
// inside the error and is dropped here, exactly as before.
1220+
Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
1221+
Err(SteerAdmissionReason::MailboxFull.transport_refusal())
1222+
}
1223+
// Read loop receiver torn down before this request arrived.
1224+
Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
1225+
Err(SteerAdmissionReason::MailboxClosed.transport_refusal())
1226+
}
1227+
}
11371228
}
11381229

11391230
/// Durably associate a successful steer with the exact ACP session that
@@ -8807,6 +8898,191 @@ printf '%s\n' '{{"jsonrpc":"2.0","id":0,"result":{{"stopReason":"end_turn"}}}}'"
88078898
// Reaching here without a panic is the test.
88088899
}
88098900

8901+
// ── send_steer admission-reason tests ─────────────────────────────────
8902+
//
8903+
// These pin the fixed structured admission-refusal labels the stock
8904+
// admission owner (`send_steer`) reports, and that the fallback log's
8905+
// `reason` classification (via `SteerError::admission_reason`) matches
8906+
// them branch for branch without touching request content.
8907+
8908+
/// Insert an in-flight task_map entry for `scope` carrying `steer_tx`,
8909+
/// mirroring `mark_agent_busy` — the existing seam for simulating an
8910+
/// in-flight prompt task without spawning a real agent turn.
8911+
fn mark_agent_busy_with_steer_tx(
8912+
pool: &mut AgentPool,
8913+
scope: SessionScope,
8914+
steer_tx: Option<tokio::sync::mpsc::Sender<SteerRequest>>,
8915+
) {
8916+
let abort = pool.join_set.spawn(async {});
8917+
pool.task_map_mut().insert(
8918+
abort.id(),
8919+
TaskMeta {
8920+
agent_index: 0,
8921+
channel_id: Some(scope.channel_id()),
8922+
scope: Some(scope),
8923+
turn_id: "t".into(),
8924+
recoverable_batch: None,
8925+
control_tx: None,
8926+
steer_tx,
8927+
successful_steer_deliveries: HashSet::new(),
8928+
},
8929+
);
8930+
}
8931+
8932+
/// A minimal steer request; the ack oneshot is dropped with the request
8933+
/// when admission refuses it, exactly as in production.
8934+
fn steer_request() -> SteerRequest {
8935+
let (ack_tx, _ack_rx) = tokio::sync::oneshot::channel::<SteerAck>();
8936+
SteerRequest {
8937+
prompt_blocks: vec!["steer block".into()],
8938+
ack_tx,
8939+
}
8940+
}
8941+
8942+
#[test]
8943+
fn send_steer_reports_task_absent_when_no_task_in_flight() {
8944+
let mut pool = AgentPool::from_slots(vec![]);
8945+
let scope = conv(Uuid::nil());
8946+
let err = pool.send_steer(&scope, steer_request()).unwrap_err();
8947+
// Unchanged return shape: the separate task-absent branch keeps
8948+
// PromptCompleted's release-and-normal-dispatch semantics.
8949+
assert!(matches!(err, SteerError::PromptCompleted));
8950+
assert_eq!(
8951+
err.admission_reason(),
8952+
Some(SteerAdmissionReason::TaskAbsent)
8953+
);
8954+
}
8955+
8956+
#[tokio::test]
8957+
async fn send_steer_reports_sender_absent_when_no_steer_sender_installed() {
8958+
let mut pool = AgentPool::from_slots(vec![]);
8959+
let scope = conv(Uuid::nil());
8960+
// The existing seam inserts the in-flight task with steer_tx: None.
8961+
mark_agent_busy(&mut pool, 0, scope.clone());
8962+
let err = pool.send_steer(&scope, steer_request()).unwrap_err();
8963+
assert!(matches!(&err, SteerError::Transport(msg) if msg == "sender_absent"));
8964+
assert_eq!(
8965+
err.admission_reason(),
8966+
Some(SteerAdmissionReason::SenderAbsent)
8967+
);
8968+
}
8969+
8970+
#[tokio::test]
8971+
async fn send_steer_reports_mailbox_full_when_one_steer_already_in_flight() {
8972+
let mut pool = AgentPool::from_slots(vec![]);
8973+
let scope = conv(Uuid::nil());
8974+
let (tx, mut rx) = tokio::sync::mpsc::channel::<SteerRequest>(1);
8975+
mark_agent_busy_with_steer_tx(&mut pool, scope.clone(), Some(tx.clone()));
8976+
// Fill the capacity-1 mailbox: one steer write already in flight.
8977+
tx.try_send(steer_request())
8978+
.expect("capacity-1 mailbox accepts the first in-flight steer");
8979+
let err = pool.send_steer(&scope, steer_request()).unwrap_err();
8980+
assert!(matches!(&err, SteerError::Transport(msg) if msg == "mailbox_full"));
8981+
assert_eq!(
8982+
err.admission_reason(),
8983+
Some(SteerAdmissionReason::MailboxFull)
8984+
);
8985+
// The already-admitted request is untouched by the refused second
8986+
// attempt: send results are preserved.
8987+
let admitted = rx.try_recv().expect("first in-flight steer still queued");
8988+
assert_eq!(admitted.prompt_blocks, vec!["steer block".to_string()]);
8989+
}
8990+
8991+
#[tokio::test]
8992+
async fn send_steer_reports_mailbox_closed_after_receiver_dropped() {
8993+
let mut pool = AgentPool::from_slots(vec![]);
8994+
let scope = conv(Uuid::nil());
8995+
let (tx, rx) = tokio::sync::mpsc::channel::<SteerRequest>(1);
8996+
mark_agent_busy_with_steer_tx(&mut pool, scope.clone(), Some(tx));
8997+
drop(rx); // read loop torn down before this request arrived
8998+
let err = pool.send_steer(&scope, steer_request()).unwrap_err();
8999+
assert!(matches!(&err, SteerError::Transport(msg) if msg == "mailbox_closed"));
9000+
assert_eq!(
9001+
err.admission_reason(),
9002+
Some(SteerAdmissionReason::MailboxClosed)
9003+
);
9004+
}
9005+
9006+
#[tokio::test]
9007+
async fn send_steer_ok_hands_request_to_read_loop_receiver() {
9008+
let mut pool = AgentPool::from_slots(vec![]);
9009+
let scope = conv(Uuid::nil());
9010+
let (tx, mut rx) = tokio::sync::mpsc::channel::<SteerRequest>(1);
9011+
mark_agent_busy_with_steer_tx(&mut pool, scope.clone(), Some(tx));
9012+
let (ack_tx, mut ack_rx) = tokio::sync::oneshot::channel::<SteerAck>();
9013+
pool.send_steer(
9014+
&scope,
9015+
SteerRequest {
9016+
prompt_blocks: vec!["steer block".into()],
9017+
ack_tx,
9018+
},
9019+
)
9020+
.expect("admission succeeds with a live receiver");
9021+
let admitted = rx
9022+
.recv()
9023+
.await
9024+
.expect("request reaches the read loop mailbox");
9025+
assert_eq!(admitted.prompt_blocks, vec!["steer block".to_string()]);
9026+
admitted
9027+
.ack_tx
9028+
.send(SteerAck::PromptCompletedNeutral)
9029+
.expect("ack oneshot survives admission");
9030+
assert!(matches!(
9031+
ack_rx.try_recv(),
9032+
Ok(SteerAck::PromptCompletedNeutral)
9033+
));
9034+
}
9035+
9036+
#[test]
9037+
fn steer_admission_reason_labels_round_trip_with_send_steer_refusals() {
9038+
// send_steer writes exactly these labels via transport_refusal;
9039+
// admission_reason must classify them back without drift.
9040+
for reason in [
9041+
SteerAdmissionReason::SenderAbsent,
9042+
SteerAdmissionReason::MailboxFull,
9043+
SteerAdmissionReason::MailboxClosed,
9044+
] {
9045+
assert_eq!(reason.transport_refusal().admission_reason(), Some(reason));
9046+
}
9047+
assert_eq!(
9048+
SteerError::PromptCompleted.admission_reason(),
9049+
Some(SteerAdmissionReason::TaskAbsent)
9050+
);
9051+
// Fixed vocabulary the fallback log reports.
9052+
assert_eq!(SteerAdmissionReason::TaskAbsent.as_str(), "task_absent");
9053+
assert_eq!(SteerAdmissionReason::SenderAbsent.as_str(), "sender_absent");
9054+
assert_eq!(SteerAdmissionReason::MailboxFull.as_str(), "mailbox_full");
9055+
assert_eq!(
9056+
SteerAdmissionReason::MailboxClosed.as_str(),
9057+
"mailbox_closed"
9058+
);
9059+
}
9060+
9061+
#[test]
9062+
fn steer_admission_reason_excludes_post_admission_errors() {
9063+
// Ack-native write failures are built in the read loop AFTER
9064+
// admission (acp.rs carries the AcpError display); they and the
9065+
// other ack outcomes must never classify as admission refusals.
9066+
let post_admission = [
9067+
SteerError::Transport("I/O error: broken pipe mid-write".into()),
9068+
SteerError::AgentError {
9069+
code: -32601,
9070+
message: "method not found".into(),
9071+
},
9072+
SteerError::ExpectedRunIdMissing,
9073+
SteerError::OutcomeRejected {
9074+
outcome: "failed".into(),
9075+
},
9076+
];
9077+
for err in post_admission {
9078+
assert_eq!(
9079+
err.admission_reason(),
9080+
None,
9081+
"{err:?} is post-admission and must not classify as admission"
9082+
);
9083+
}
9084+
}
9085+
88109086
// ── NIP-AM emit-hook unit tests ────────────────────────────────────────
88119087

88129088
/// `acp_stop_to_core` maps all ACP stop reasons to the correct NIP-AM

0 commit comments

Comments
 (0)