Skip to content

Commit 9ff9ed8

Browse files
committed
fix(acp): widen silent-reply grace; generation-key watches
Default grace is 8s (override with BUZZ_SILENT_REPLY_GRACE_SECS) so post-reconnect echoes can clear the notice, and watches are keyed by generation so a stale timer cannot steal a later Ok turn's check. Signed-off-by: Taksh <takshkothari09@gmail.com> Signed-off-by: Taksh <takshkothari09@gmail.com>
1 parent 4b4ff13 commit 9ff9ed8

3 files changed

Lines changed: 110 additions & 37 deletions

File tree

‎.env.example‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,12 @@ RUST_LOG=buzz_relay=debug,buzz_datastore=info,buzz_db=debug,buzz_auth=debug,buzz
223223
# Set to true to process the agent's own messages (default: ignore self).
224224
# BUZZ_ACP_NO_IGNORE_SELF=false
225225

226+
# Seconds to wait after an Ok mention turn before posting a "couldn't publish"
227+
# notice, so a late ws echo (including post-reconnect replay) can clear it.
228+
# Default 8 covers ≈6s relay resubscribe bursts; set higher for many-channel
229+
# harnesses. (#2459)
230+
# BUZZ_SILENT_REPLY_GRACE_SECS=8
231+
226232
# ── Context ──────────────────────────────────────────────────────────────────
227233
# Max context messages fetched for thread replies and DMs (0–100). 0 = disabled.
228234
# BUZZ_ACP_CONTEXT_MESSAGE_LIMIT=12

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

Lines changed: 46 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,27 @@ mod setup_mode;
1313
mod silent_reply;
1414
mod usage;
1515

16-
/// Grace window before posting a silent-reply notice so a late ws echo can land (#2459).
17-
const SILENT_REPLY_GRACE: Duration = Duration::from_secs(3);
16+
/// Default grace before posting a silent-reply notice so a late ws echo can
17+
/// land (#2459). Relay resubscribe bursts can spread ≈6s under REQ pacing, so
18+
/// the default sits above that; override with `BUZZ_SILENT_REPLY_GRACE_SECS`.
19+
const DEFAULT_SILENT_REPLY_GRACE_SECS: u64 = 8;
20+
21+
fn silent_reply_grace() -> Duration {
22+
std::env::var("BUZZ_SILENT_REPLY_GRACE_SECS")
23+
.ok()
24+
.and_then(|raw| raw.parse::<u64>().ok())
25+
.filter(|&secs| secs > 0)
26+
.map(Duration::from_secs)
27+
.unwrap_or(Duration::from_secs(DEFAULT_SILENT_REPLY_GRACE_SECS))
28+
}
29+
30+
/// Deferred silent-reply check payload: batch plus the watch generation armed
31+
/// when the Ok turn completed.
32+
#[derive(Clone)]
33+
struct SilentReplyCheck {
34+
batch: FlushBatch,
35+
generation: u64,
36+
}
1837

1938
pub use usage::TurnUsage;
2039

@@ -1931,7 +1950,7 @@ async fn tokio_main() -> Result<()> {
19311950
let (steer_ack_tx, mut steer_ack_rx) = mpsc::unbounded_channel::<SteerAckEvent>();
19321951
// Deferred silent-reply checks: Ok mention turns wait a grace window so a
19331952
// late ws echo can clear the "couldn't publish" notice (#2459).
1934-
let (silent_reply_tx, mut silent_reply_rx) = mpsc::unbounded_channel::<FlushBatch>();
1953+
let (silent_reply_tx, mut silent_reply_rx) = mpsc::unbounded_channel::<SilentReplyCheck>();
19351954

19361955
// ── Step 7: Shutdown signal ───────────────────────────────────────────────
19371956
let (shutdown_tx, mut shutdown_rx) = watch::channel(());
@@ -2006,7 +2025,7 @@ async fn tokio_main() -> Result<()> {
20062025
Result(Box<PromptResult>),
20072026
Panic(tokio::task::JoinError),
20082027
SteerAck(SteerAckEvent),
2009-
SilentReplyDue(FlushBatch),
2028+
SilentReplyDue(SilentReplyCheck),
20102029
Wake(u32, Result<AgentPool, String>),
20112030
}
20122031

@@ -2154,8 +2173,8 @@ async fn tokio_main() -> Result<()> {
21542173
Some(ack_event) = steer_ack_rx.recv() => {
21552174
Some(PoolEvent::SteerAck(ack_event))
21562175
}
2157-
Some(batch) = silent_reply_rx.recv() => {
2158-
Some(PoolEvent::SilentReplyDue(batch))
2176+
Some(check) = silent_reply_rx.recv() => {
2177+
Some(PoolEvent::SilentReplyDue(check))
21592178
}
21602179
Some((attempt, result)) = wake_rx.recv(), if config.lazy_pool && !pool_ready => {
21612180
Some(PoolEvent::Wake(attempt, result))
@@ -2904,22 +2923,24 @@ async fn tokio_main() -> Result<()> {
29042923
typing_channels.insert(channel_id, thread_tags);
29052924
}
29062925
}
2907-
Some(PoolEvent::SilentReplyDue(batch)) => {
2908-
let Some(publishes) = queue.take_silent_reply_watch(batch.channel_id) else {
2909-
// Already consumed (e.g. a later Ok on the same channel
2910-
// re-armed / raced); nothing to do.
2926+
Some(PoolEvent::SilentReplyDue(check)) => {
2927+
let Some(publishes) =
2928+
queue.take_silent_reply_watch(check.batch.channel_id, check.generation)
2929+
else {
2930+
// Already consumed or superseded by a later Ok on the same
2931+
// channel; nothing to do.
29112932
continue;
29122933
};
29132934
if let Some(content) = silent_reply::silent_reply_loss_notice(
29142935
&PromptOutcome::Ok(StopReason::EndTurn),
2915-
Some(&batch),
2936+
Some(&check.batch),
29162937
publishes,
29172938
) {
29182939
tracing::warn!(
2919-
channel_id = %batch.channel_id,
2940+
channel_id = %check.batch.channel_id,
29202941
"mention turn completed Ok with no agent channel publish — posting failure notice"
29212942
);
2922-
spawn_failure_notice(Some(&ctx.rest_client), &batch, content);
2943+
spawn_failure_notice(Some(&ctx.rest_client), &check.batch, content);
29232944
}
29242945
}
29252946
Some(PoolEvent::Wake(attempt, result)) => {
@@ -3434,7 +3455,7 @@ fn handle_prompt_result(
34343455
respawn_tasks: &mut tokio::task::JoinSet<()>,
34353456
observer: Option<observer::ObserverHandle>,
34363457
rest_client: Option<&relay::RestClient>,
3437-
silent_reply_tx: Option<&mpsc::UnboundedSender<FlushBatch>>,
3458+
silent_reply_tx: Option<&mpsc::UnboundedSender<SilentReplyCheck>>,
34383459
) -> LoopAction {
34393460
let before = pool.task_map().len();
34403461
let agent_index = result.agent.index;
@@ -3468,18 +3489,23 @@ fn handle_prompt_result(
34683489
// and is not ordered vs pool completion. Arm a watch so
34693490
// counts survive mark_complete, then re-check after a
34703491
// short grace window.
3471-
queue.arm_silent_reply_watch(batch.channel_id);
3492+
let generation = queue.arm_silent_reply_watch(batch.channel_id);
34723493
if let Some(tx) = silent_reply_tx {
34733494
let tx = tx.clone();
3474-
let batch_for_check = batch.clone();
3495+
let check = SilentReplyCheck {
3496+
batch: batch.clone(),
3497+
generation,
3498+
};
3499+
let grace = silent_reply_grace();
34753500
tokio::spawn(async move {
3476-
tokio::time::sleep(SILENT_REPLY_GRACE).await;
3477-
let _ = tx.send(batch_for_check);
3501+
tokio::time::sleep(grace).await;
3502+
let _ = tx.send(check);
34783503
});
34793504
} else {
34803505
// Tests / callers without a deferred channel: decide now.
3481-
let publishes =
3482-
queue.take_silent_reply_watch(batch.channel_id).unwrap_or(0);
3506+
let publishes = queue
3507+
.take_silent_reply_watch(batch.channel_id, generation)
3508+
.unwrap_or(0);
34833509
if let Some(content) = silent_reply::silent_reply_loss_notice(
34843510
&result.outcome,
34853511
Some(&batch),

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

Lines changed: 58 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -146,10 +146,13 @@ pub struct EventQueue {
146146
/// Used to detect silent reply loss when ACP reports Ok but
147147
/// `buzz messages send` never landed (#2459).
148148
in_flight_self_publishes: HashMap<Uuid, u64>,
149-
/// Channels whose Ok turn is waiting on a deferred silent-reply check.
150-
/// Counts in [`in_flight_self_publishes`] survive [`mark_complete`] while
151-
/// a watch is armed so a late ws echo can still clear the notice.
152-
silent_reply_watches: HashSet<Uuid>,
149+
/// Channels whose Ok turn is waiting on a deferred silent-reply check,
150+
/// keyed by a per-channel generation. Counts in
151+
/// [`in_flight_self_publishes`] survive [`mark_complete`] while a watch is
152+
/// armed so a late ws echo can still clear the notice. Generation IDs stop
153+
/// a stale grace timer from consuming a newer turn's watch on the same
154+
/// channel (#2459).
155+
silent_reply_watches: HashMap<Uuid, u64>,
153156
retry_after: HashMap<Uuid, Instant>,
154157
/// Per-channel retry attempt counter for exponential backoff / dead-lettering.
155158
retry_counts: HashMap<Uuid, u32>,
@@ -192,7 +195,7 @@ impl EventQueue {
192195
in_flight_deadlines: HashMap::new(),
193196
in_flight_batch_sizes: HashMap::new(),
194197
in_flight_self_publishes: HashMap::new(),
195-
silent_reply_watches: HashSet::new(),
198+
silent_reply_watches: HashMap::new(),
196199
retry_after: HashMap::new(),
197200
retry_counts: HashMap::new(),
198201
dedup_mode,
@@ -407,7 +410,7 @@ impl EventQueue {
407410
self.in_flight_batch_sizes.remove(&channel_id);
408411
// Keep publish counts while a silent-reply grace watch is armed so a
409412
// late echo can still arrive after turn completion (#2459).
410-
if !self.silent_reply_watches.contains(&channel_id) {
413+
if !self.silent_reply_watches.contains_key(&channel_id) {
411414
self.in_flight_self_publishes.remove(&channel_id);
412415
}
413416
let now = Instant::now();
@@ -673,7 +676,7 @@ impl EventQueue {
673676
/// channel turn, or during a deferred silent-reply grace watch.
674677
pub fn note_self_publish(&mut self, channel_id: Uuid) {
675678
if self.in_flight_channels.contains(&channel_id)
676-
|| self.silent_reply_watches.contains(&channel_id)
679+
|| self.silent_reply_watches.contains_key(&channel_id)
677680
{
678681
*self.in_flight_self_publishes.entry(channel_id).or_insert(0) += 1;
679682
}
@@ -688,17 +691,33 @@ impl EventQueue {
688691

689692
/// Arm a post-Ok silent-reply watch so publish counts survive
690693
/// [`mark_complete`] until [`take_silent_reply_watch`].
691-
pub fn arm_silent_reply_watch(&mut self, channel_id: Uuid) {
692-
self.silent_reply_watches.insert(channel_id);
694+
///
695+
/// Returns the watch generation. Callers must pass that generation back to
696+
/// [`take_silent_reply_watch`] so a stale grace timer cannot consume a
697+
/// newer turn's watch on the same channel.
698+
pub fn arm_silent_reply_watch(&mut self, channel_id: Uuid) -> u64 {
699+
let next = self
700+
.silent_reply_watches
701+
.get(&channel_id)
702+
.copied()
703+
.unwrap_or(0)
704+
.wrapping_add(1);
705+
self.silent_reply_watches.insert(channel_id, next);
706+
next
693707
}
694708

695709
/// End a silent-reply watch and take the accumulated publish count.
696-
/// Returns `None` if no watch was armed (already consumed / never armed).
697-
pub fn take_silent_reply_watch(&mut self, channel_id: Uuid) -> Option<u64> {
698-
if !self.silent_reply_watches.remove(&channel_id) {
699-
return None;
710+
///
711+
/// Returns `None` if no matching generation is armed (already consumed,
712+
/// never armed, or superseded by a later Ok on the same channel).
713+
pub fn take_silent_reply_watch(&mut self, channel_id: Uuid, generation: u64) -> Option<u64> {
714+
match self.silent_reply_watches.get(&channel_id).copied() {
715+
Some(current) if current == generation => {
716+
self.silent_reply_watches.remove(&channel_id);
717+
Some(self.take_self_publishes(channel_id))
718+
}
719+
_ => None,
700720
}
701-
Some(self.take_self_publishes(channel_id))
702721
}
703722

704723
// ── Goose-native steer withhold (side table) ──────────────────────────
@@ -4823,19 +4842,41 @@ mod tests {
48234842
// Re-note during in-flight, arm watch, then complete — count must survive.
48244843
q.in_flight_channels.insert(ch);
48254844
q.note_self_publish(ch);
4826-
q.arm_silent_reply_watch(ch);
4845+
let gen = q.arm_silent_reply_watch(ch);
48274846
q.mark_complete(ch);
48284847
assert!(!q.is_channel_in_flight(ch));
48294848
// Late echo after completion still counts.
48304849
q.note_self_publish(ch);
4831-
assert_eq!(q.take_silent_reply_watch(ch), Some(2));
4850+
assert_eq!(q.take_silent_reply_watch(ch, gen), Some(2));
48324851
// Second take is a no-op.
4833-
assert_eq!(q.take_silent_reply_watch(ch), None);
4852+
assert_eq!(q.take_silent_reply_watch(ch, gen), None);
48344853
// Without a watch, post-complete echoes are ignored.
48354854
q.note_self_publish(ch);
48364855
assert_eq!(q.take_self_publishes(ch), 0);
48374856
}
48384857

4858+
#[test]
4859+
fn silent_reply_watch_generation_ignores_stale_timer() {
4860+
let mut q = EventQueue::new(DedupMode::Queue);
4861+
let ch = Uuid::new_v4();
4862+
q.in_flight_channels.insert(ch);
4863+
q.note_self_publish(ch);
4864+
let first = q.arm_silent_reply_watch(ch);
4865+
q.mark_complete(ch);
4866+
4867+
// A second Ok on the same channel re-arms with a new generation.
4868+
q.in_flight_channels.insert(ch);
4869+
let second = q.arm_silent_reply_watch(ch);
4870+
assert_ne!(first, second);
4871+
q.mark_complete(ch);
4872+
q.note_self_publish(ch);
4873+
4874+
// Stale first timer must not consume the newer watch (count still
4875+
// includes the earlier turn's publish — generations only gate take).
4876+
assert_eq!(q.take_silent_reply_watch(ch, first), None);
4877+
assert_eq!(q.take_silent_reply_watch(ch, second), Some(2));
4878+
}
4879+
48394880
#[test]
48404881
fn mark_complete_clears_publishes_without_silent_reply_watch() {
48414882
let mut q = EventQueue::new(DedupMode::Queue);

0 commit comments

Comments
 (0)