Skip to content

Commit c11e582

Browse files
committed
fix(acp): drop bindings on idle model switch and retire sibling keys
Address Fable r2 PAN3-R1/R2: idle SwitchModel now removes channel bindings, and a fresh session/new retires every worker key for that channel before save_binding. Signed-off-by: Kelcee Lari <[email protected]>
1 parent a18e48d commit c11e582

3 files changed

Lines changed: 150 additions & 12 deletions

File tree

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

Lines changed: 121 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,13 +1084,14 @@ async fn publish_relay_observer_event(
10841084
/// Maximum age (seconds) for an observer control frame to be considered fresh.
10851085
const OBSERVER_CONTROL_FRESHNESS_SECS: i64 = 300;
10861086

1087-
fn handle_relay_observer_control_event(
1087+
async fn handle_relay_observer_control_event(
10881088
keys: &nostr::Keys,
10891089
event: nostr::Event,
10901090
pool: &mut AgentPool,
10911091
observer: Option<&observer::ObserverHandle>,
10921092
owner_pubkey_hex: &str,
10931093
event_publisher: RelayEventPublisher,
1094+
session_store: Option<&dyn session_store::SessionStore>,
10941095
) {
10951096
// Defense-in-depth: verify signature even though the relay already checked.
10961097
if let Err(e) = buzz_core::verify_event(&event) {
@@ -1134,7 +1135,7 @@ fn handle_relay_observer_control_event(
11341135
handle_cancel_turn_control(&payload, pool, observer);
11351136
}
11361137
Some("switch_model") => {
1137-
handle_switch_model_control(&payload, pool, observer);
1138+
handle_switch_model_control(&payload, pool, observer, session_store).await;
11381139
}
11391140
Some("publish_project_owner_announcements") => {
11401141
handle_publish_project_owner_announcements_control(
@@ -1337,11 +1338,14 @@ fn handle_cancel_turn_control(
13371338
///
13381339
/// Idle path: validate against the cached catalog *before* invalidating
13391340
/// (pre-cancel guard), then set `desired_model` + invalidate. The override
1340-
/// takes visible effect on the agent's next turn.
1341-
fn handle_switch_model_control(
1341+
/// takes visible effect on the agent's next turn. A successful idle switch
1342+
/// also retires durable bindings so the next prompt cannot `session/load`
1343+
/// the deliberately retired session.
1344+
async fn handle_switch_model_control(
13421345
payload: &serde_json::Value,
13431346
pool: &mut AgentPool,
13441347
observer: Option<&observer::ObserverHandle>,
1348+
session_store: Option<&dyn session_store::SessionStore>,
13451349
) {
13461350
let Some(channel_id) = payload
13471351
.get("channelId")
@@ -1390,7 +1394,18 @@ fn handle_switch_model_control(
13901394
} else {
13911395
// Idle path: validate against the cached catalog before invalidating.
13921396
match pool.switch_idle_agent_model(channel_id, model_id, request_id.clone()) {
1393-
IdleSwitchResult::Switched => "switched",
1397+
IdleSwitchResult::Switched => {
1398+
if let Some(store) = session_store {
1399+
if let Err(error) = store.remove_bindings_for_channel(channel_id).await {
1400+
tracing::warn!(
1401+
%error,
1402+
%channel_id,
1403+
"session store remove_binding failed on idle switch_model"
1404+
);
1405+
}
1406+
}
1407+
"switched"
1408+
}
13941409
IdleSwitchResult::UnsupportedModel => "unsupported_model",
13951410
IdleSwitchResult::NoIdleAgent => "no_active_turn",
13961411
}
@@ -2639,7 +2654,9 @@ async fn tokio_main() -> Result<()> {
26392654
observer.as_ref(),
26402655
owner_hex,
26412656
relay.event_publisher(),
2642-
);
2657+
session_store.as_deref(),
2658+
)
2659+
.await;
26432660
} else {
26442661
tracing::warn!("observer control frame received but no owner resolved — dropping");
26452662
}
@@ -8791,3 +8808,101 @@ mod session_store_dedupe_tests {
87918808
assert!(!skip_if_already_processed(Some(&store), "evt-2").await);
87928809
}
87938810
}
8811+
8812+
#[cfg(test)]
8813+
mod session_store_idle_switch_tests {
8814+
use super::*;
8815+
use session_store::{ContextKey, InMemorySessionStore, SessionStore};
8816+
8817+
async fn dummy_agent(channel_id: uuid::Uuid) -> OwnedAgent {
8818+
// Inert `cat` subprocess — the idle switch path never talks to ACP.
8819+
let mut agent = OwnedAgent {
8820+
index: 0,
8821+
acp: AcpClient::spawn("cat", &[], &[], false)
8822+
.await
8823+
.expect("spawn cat as inert agent"),
8824+
state: SessionState::default(),
8825+
model_capabilities: None,
8826+
desired_model: None,
8827+
model_overridden: false,
8828+
desired_model_request_id: None,
8829+
desired_model_pending_ack: false,
8830+
startup_effort: None,
8831+
agent_name: "unknown".into(),
8832+
goose_system_prompt_supported: None,
8833+
protocol_version: 1,
8834+
};
8835+
agent
8836+
.state
8837+
.sessions
8838+
.insert(channel_id, "retired-sid".into());
8839+
agent
8840+
}
8841+
8842+
#[tokio::test]
8843+
async fn session_store_idle_switch_model_removes_channel_bindings() {
8844+
let store = InMemorySessionStore::new();
8845+
let channel_id = uuid::Uuid::new_v4();
8846+
let key = ContextKey::Channel(channel_id).for_worker(0);
8847+
store.save_binding(&key, "retired-sid").await.unwrap();
8848+
8849+
let mut pool = AgentPool::from_slots(vec![Some(dummy_agent(channel_id).await)]);
8850+
handle_switch_model_control(
8851+
&serde_json::json!({
8852+
"channelId": channel_id.to_string(),
8853+
"modelId": "new-model",
8854+
}),
8855+
&mut pool,
8856+
None,
8857+
Some(&store),
8858+
)
8859+
.await;
8860+
8861+
assert!(
8862+
store.load_binding(&key).await.unwrap().is_none(),
8863+
"idle switch must retire durable bindings so restore cannot resurrect them"
8864+
);
8865+
if let Some(mut agent) = pool.try_claim(Some(channel_id)) {
8866+
agent.acp.shutdown().await;
8867+
}
8868+
}
8869+
8870+
#[tokio::test]
8871+
async fn session_store_unsupported_idle_switch_keeps_channel_bindings() {
8872+
let store = InMemorySessionStore::new();
8873+
let channel_id = uuid::Uuid::new_v4();
8874+
let key = ContextKey::Channel(channel_id).for_worker(0);
8875+
store.save_binding(&key, "keep-sid").await.unwrap();
8876+
8877+
let mut agent = dummy_agent(channel_id).await;
8878+
agent.model_capabilities = Some(crate::pool::AgentModelCapabilities {
8879+
config_options_raw: vec![],
8880+
available_models_raw: Some(serde_json::json!([])),
8881+
thought_level_config_id: None,
8882+
});
8883+
let mut pool = AgentPool::from_slots(vec![Some(agent)]);
8884+
handle_switch_model_control(
8885+
&serde_json::json!({
8886+
"channelId": channel_id.to_string(),
8887+
"modelId": "missing-model",
8888+
}),
8889+
&mut pool,
8890+
None,
8891+
Some(&store),
8892+
)
8893+
.await;
8894+
8895+
assert_eq!(
8896+
store
8897+
.load_binding(&key)
8898+
.await
8899+
.unwrap()
8900+
.expect("rejected switch must not delete the binding")
8901+
.session_id,
8902+
"keep-sid"
8903+
);
8904+
if let Some(mut agent) = pool.try_claim(Some(channel_id)) {
8905+
agent.acp.shutdown().await;
8906+
}
8907+
}
8908+
}

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

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1789,6 +1789,19 @@ async fn store_save_binding(
17891789
}
17901790
}
17911791

1792+
async fn store_retire_channel_bindings(ctx: &PromptContext, channel_id: uuid::Uuid) {
1793+
let Some(store) = ctx.session_store.as_ref() else {
1794+
return;
1795+
};
1796+
if let Err(error) = store.remove_bindings_for_channel(channel_id).await {
1797+
tracing::warn!(
1798+
%error,
1799+
%channel_id,
1800+
"session store remove_bindings_for_channel failed"
1801+
);
1802+
}
1803+
}
1804+
17921805
async fn store_mark_events_processed(
17931806
ctx: &PromptContext,
17941807
channel_id: uuid::Uuid,
@@ -2159,6 +2172,7 @@ pub async fn run_prompt_task(
21592172
// Seed a zero usage baseline: buzz-acp spawned this session
21602173
// so prior usage is zero by definition — first turn is reliable.
21612174
agent.acp.notify_session_spawned(&sid);
2175+
store_retire_channel_bindings(&ctx, *cid).await;
21622176
store_save_binding(
21632177
&ctx,
21642178
&crate::session_store::ContextKey::Channel(*cid)
@@ -8587,14 +8601,21 @@ done"#,
85878601
"worker 1 must not load worker 0 or unscoped bindings: {methods:?}"
85888602
);
85898603
assert!(methods.contains(&"session/new".to_string()));
8590-
assert_eq!(
8604+
assert!(
85918605
store
85928606
.load_binding(&worker_channel_key(channel_id, 0))
85938607
.await
85948608
.unwrap()
8609+
.is_none(),
8610+
"fresh create must retire superseded sibling-worker bindings"
8611+
);
8612+
assert!(
8613+
store
8614+
.load_binding(&crate::session_store::ContextKey::Channel(channel_id))
8615+
.await
85958616
.unwrap()
8596-
.session_id,
8597-
"worker0-sid"
8617+
.is_none(),
8618+
"fresh create must retire unscoped channel bindings"
85988619
);
85998620
assert_eq!(
86008621
store

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,11 @@
2424
//!
2525
//! The store is process-global. In-memory session maps are per-worker.
2626
//! Bindings are keyed by worker slot (`{index}:{context}`) so two adapter
27-
//! subprocesses never attach the same session id. `EventQueue`'s
28-
//! `in_flight_channels` gate still ensures one channel is processed by one
29-
//! worker at a time.
27+
//! subprocesses never attach the same session id. A fresh channel-session
28+
//! create retires every binding for that channel (including sibling-worker
29+
//! keys) before saving, so a later restart cannot restore a superseded
30+
//! history. `EventQueue`'s `in_flight_channels` gate still ensures one
31+
//! channel is processed by one worker at a time.
3032
//!
3133
//! # Adapters
3234
//!

0 commit comments

Comments
 (0)