use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use chrono::{DateTime, Utc};
use crate::agent::message_router::{AgentJob, MessageKind};
use crate::agent::registry::AGENT_REGISTRY;
use crate::session::SessionContext;
use crate::util::UnwrapPoison;
use crate::{ChatMessage, ChatRole, Role};
const POLL_INTERVAL: Duration = Duration::from_mins(10);
const STARTUP_POLL_INTERVAL: Duration = Duration::from_mins(1);
const STARTUP_WINDOW: Duration = Duration::from_mins(5);
const MAX_RETRIES: u8 = 10;
const BASE_BACKOFF_MINUTES: i64 = 10;
const MAX_BACKOFF_MINUTES: i64 = 40;
const STALE_GRACE_PERIOD: Duration = Duration::from_mins(2);
struct RetryState {
attempt_count: u8,
last_attempt_at: Option<DateTime<Utc>>,
backoff_minutes: i64,
deterministic_signature: Option<u64>,
}
impl RetryState {
fn fresh() -> Self {
Self {
attempt_count: 0,
last_attempt_at: None,
backoff_minutes: BASE_BACKOFF_MINUTES,
deterministic_signature: None,
}
}
}
struct DeadSessionTracker {
inner: Mutex<HashMap<String, RetryState>>,
}
impl DeadSessionTracker {
fn new() -> Self {
Self {
inner: Mutex::new(HashMap::new()),
}
}
fn should_retry(&self, agent_id: &str) -> bool {
let map = self.inner.lock().unwrap_poison();
match map.get(agent_id) {
Some(state) => {
if state.attempt_count >= MAX_RETRIES {
return false;
}
state
.last_attempt_at
.is_none_or(|at| (Utc::now() - at).num_minutes() >= state.backoff_minutes)
}
None => true,
}
}
fn record_attempt(&self, agent_id: &str) {
let mut map = self.inner.lock().unwrap_poison();
let state = map
.entry(agent_id.to_string())
.or_insert_with(RetryState::fresh);
state.attempt_count += 1;
state.last_attempt_at = Some(Utc::now());
state.backoff_minutes = (state.backoff_minutes * 2).min(MAX_BACKOFF_MINUTES);
}
fn cleanup(&self, agent_id: &str) {
self.inner.lock().unwrap_poison().remove(agent_id);
}
pub(crate) fn record_deterministic_failure(&self, agent_id: &str, last: Option<&ChatMessage>) {
let Some(last) = last else {
return;
};
if is_non_user_facing(agent_id) {
return;
}
self.inner
.lock()
.unwrap_poison()
.entry(agent_id.to_string())
.or_insert_with(RetryState::fresh)
.deterministic_signature = Some(history_signature(last.role, &last.content));
}
fn unchanged_since_deterministic_failure(
&self,
agent_id: &str,
last_role: ChatRole,
tail_content: &str,
) -> bool {
self.inner
.lock()
.unwrap_poison()
.get(agent_id)
.and_then(|state| state.deterministic_signature)
.is_some_and(|signature| signature == history_signature(last_role, tail_content))
}
fn forget_deterministic_failure(&self, agent_id: &str) {
let mut map = self.inner.lock().unwrap_poison();
if let Some(state) = map.get_mut(agent_id) {
state.deterministic_signature = None;
if state.attempt_count == 0 {
map.remove(agent_id);
}
}
}
fn prune_deterministic_failures(&self, live: &HashSet<&str>) {
self.inner.lock().unwrap_poison().retain(|agent_id, state| {
state.deterministic_signature.is_none() || live.contains(agent_id.as_str())
});
}
}
static DEAD_SESSION_TRACKER: std::sync::LazyLock<DeadSessionTracker> =
std::sync::LazyLock::new(DeadSessionTracker::new);
pub(crate) fn record_deterministic_failure(agent_id: &str, last: Option<&ChatMessage>) {
DEAD_SESSION_TRACKER.record_deterministic_failure(agent_id, last);
}
fn history_signature(role: ChatRole, content: &str) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
role.hash(&mut hasher);
content.hash(&mut hasher);
hasher.finish()
}
fn is_non_user_facing(agent_id: &str) -> bool {
crate::session::non_user_facing_agent_id_prefixes()
.any(|prefix| super::starts_with_ignore_ascii_case(agent_id, prefix))
}
pub async fn run_dead_session_recovery_loop() {
let started = Instant::now();
loop {
let interval = if started.elapsed() < STARTUP_WINDOW {
STARTUP_POLL_INTERVAL
} else {
POLL_INTERVAL
};
if !crate::shutdown::sleep_or_shutdown_or_drain(interval).await {
break;
}
if let Err(e) = recover_dead_sessions().await {
tracing::warn!(error = %e, "Dead session recovery poller failed");
}
}
}
fn is_recovery_candidate(last_role: ChatRole, last_content: &str) -> bool {
match last_role {
ChatRole::User | ChatRole::Tool => true,
ChatRole::Assistant => super::is_dangling_tool_call_frame(last_role, last_content),
ChatRole::System => false,
}
}
async fn recover_dead_sessions() -> anyhow::Result<()> {
let now = Utc::now();
let sessions = crate::session::store()
.list_sessions_with_metadata_excluding(
&crate::session::non_user_facing_agent_id_prefixes().collect::<Vec<&str>>(),
)
.await?;
for session in &sessions {
let agent_id = &session.agent_id;
let Some((last_role, tail_content)) = crate::session::store()
.get_last_message_tail(agent_id)
.await
else {
DEAD_SESSION_TRACKER.cleanup(agent_id);
continue; };
if !is_recovery_candidate(last_role, &tail_content) {
DEAD_SESSION_TRACKER.cleanup(agent_id);
continue;
}
if DEAD_SESSION_TRACKER.unchanged_since_deterministic_failure(
agent_id,
last_role,
&tail_content,
) {
tracing::debug!(
agent_id = %agent_id,
role = %last_role,
"Dead session recovery: unchanged history after a deterministic failure — \
skipping (the same request would be refused again)"
);
continue;
}
DEAD_SESSION_TRACKER.forget_deterministic_failure(agent_id);
let needs_pause_guard = last_role == ChatRole::Assistant;
if AGENT_REGISTRY.contains(agent_id) {
continue;
}
let age = now - session.last_activity;
let grace = chrono::Duration::from_std(STALE_GRACE_PERIOD)
.expect("STALE_GRACE_PERIOD fits in chrono::Duration");
if age < grace {
continue;
}
if crate::session::store().get_sleep_ended(agent_id).await {
DEAD_SESSION_TRACKER.cleanup(agent_id);
continue;
}
if session.launch_stopped {
DEAD_SESSION_TRACKER.cleanup(agent_id);
continue;
}
if !DEAD_SESSION_TRACKER.should_retry(agent_id) {
continue;
}
let Some(ctx) = crate::session::store().get_session_context(agent_id).await else {
DEAD_SESSION_TRACKER.cleanup(agent_id);
tracing::warn!(
agent_id = %agent_id,
"Dead session recovery: no context found \
(corrupted data) — skipping permanently"
);
continue;
};
let Ok(role) = ctx.role.parse::<Role>() else {
DEAD_SESSION_TRACKER.cleanup(agent_id);
tracing::warn!(
agent_id = %agent_id,
role = %ctx.role,
"Dead session recovery: invalid role in session context — \
skipping permanently"
);
continue;
};
if needs_pause_guard && paused_workspace_blocks(agent_id, &ctx, role).await {
continue;
}
if attempt_recovery(agent_id, &ctx, role).await {
DEAD_SESSION_TRACKER.record_attempt(agent_id);
} else {
DEAD_SESSION_TRACKER.cleanup(agent_id);
}
}
let live: HashSet<&str> = sessions
.iter()
.map(|session| session.agent_id.as_str())
.collect();
DEAD_SESSION_TRACKER.prune_deterministic_failures(&live);
Ok(())
}
async fn paused_workspace_blocks(agent_id: &str, ctx: &SessionContext, role: Role) -> bool {
if is_continuable_branch(role, agent_id) {
return false;
}
match crate::workspace::get_by_name(&ctx.workspace_name).await {
Ok(Some(ws)) if ws.paused => {
tracing::debug!(
agent_id = %agent_id,
workspace = %ctx.workspace_name,
"Dead session recovery: workspace paused — skipping"
);
true
}
Ok(_) => false,
Err(e) => {
tracing::warn!(
agent_id = %agent_id,
error = %e,
"Dead session recovery: workspace lookup failed — skipping this cycle"
);
true
}
}
}
async fn attempt_recovery(agent_id: &str, ctx: &SessionContext, role: Role) -> bool {
let Some(workspace_name) =
crate::users::enforce_personal_pinning(role, &ctx.workspace_name, &ctx.user_name)
else {
tracing::error!(
agent_id = %agent_id,
role = %role.as_str(),
workspace = %ctx.workspace_name,
"Dead session recovery: pinned role with empty user — refusing to route unpinned"
);
return false;
};
let chain = match recovered_chain(agent_id, ctx).await {
ChainStep::Resume(chain) => chain,
ChainStep::Retire => return false,
};
let launch = match recovered_launch(agent_id, ctx, role, chain.as_deref()).await {
RecoveredLaunch::Launch(launch) => launch,
RecoveredLaunch::Refuse => return false,
RecoveredLaunch::Retry => return true,
};
tracing::info!(
agent_id = %agent_id,
role = %role.as_str(),
workspace = %workspace_name,
user = %ctx.user_name,
channel = %ctx.channel,
"Dead session recovery: routing retry job"
);
let job = AgentJob {
content: String::new(),
workspace_name,
user_name: ctx.user_name.clone(),
channel: ctx.channel.clone(),
kind: MessageKind::RecoveryRetry,
role,
reply_target: None,
pending_job_id: None,
pause_notice_id: None,
originating_workspace: None,
custom_role: launch,
reply_to_custom: None,
urgent: false,
extract: ctx.extract.clone(),
};
crate::agent::message_router::route(agent_id, job);
true
}
enum RecoveredLaunch {
Launch(Option<crate::Launch>),
Refuse,
Retry,
}
async fn recovered_launch(
agent_id: &str,
ctx: &SessionContext,
role: Role,
chain: Option<&crate::launch::Chain>,
) -> RecoveredLaunch {
if role == Role::Custom {
let Some(name) = ctx.custom_role.as_deref() else {
tracing::warn!(
agent_id = %agent_id,
"Dead session recovery: custom-role session without a role name — skipping permanently"
);
if let Some(chain) = chain {
crate::tools::chain::fail(chain, "the step's conversation lost its role name")
.await;
}
return RecoveredLaunch::Refuse;
};
return match crate::custom_role::get(name).await {
Ok(Some(record)) => RecoveredLaunch::Launch(Some(crate::Launch {
role: Role::Custom,
name: name.to_string(),
identifier: ctx.custom_identifier.clone(),
prompt: record.prompt,
tools: record.tools,
agent_id: agent_id.to_string(),
reply_to: ctx.reply_to.clone().map(Box::new),
chain: chain.cloned().map(Box::new),
extract: ctx.extract.clone(),
})),
Ok(None) => {
tracing::warn!(
agent_id = %agent_id,
role = %name,
"Dead session recovery: custom role no longer exists — skipping permanently"
);
if let Some(chain) = chain {
crate::tools::chain::fail(chain, "the step's custom role no longer exists")
.await;
}
RecoveredLaunch::Refuse
}
Err(e) => {
tracing::warn!(
agent_id = %agent_id,
role = %name,
error = %e,
"Dead session recovery: custom role lookup failed — skipping this cycle"
);
RecoveredLaunch::Retry
}
};
}
if role == Role::Worker && crate::session::is_worker_branch_agent_id(agent_id) {
let branch = ctx
.custom_identifier
.clone()
.or_else(|| crate::session::worker_branch_name(agent_id).map(str::to_string));
return RecoveredLaunch::Launch(Some(crate::Launch {
role: Role::Worker,
name: String::new(),
identifier: branch,
prompt: String::new(),
tools: Vec::new(),
agent_id: agent_id.to_string(),
reply_to: ctx.reply_to.clone().map(Box::new),
chain: chain.cloned().map(Box::new),
extract: ctx.extract.clone(),
}));
}
RecoveredLaunch::Launch(None)
}
enum ChainStep {
Resume(Option<Box<crate::launch::Chain>>),
Retire,
}
async fn recovered_chain(agent_id: &str, ctx: &SessionContext) -> ChainStep {
match &ctx.chain {
crate::launch::Stored::Ordinary => ChainStep::Resume(None),
crate::launch::Stored::Step(chain) if !crate::tools::chain::stopped(chain) => {
ChainStep::Resume(Some(chain.clone()))
}
crate::launch::Stored::Step(_) => {
retire_chain_step(agent_id).await;
ChainStep::Retire
}
crate::launch::Stored::Unreadable(_) => {
let step = match ctx.custom_role.as_deref() {
Some(name) => crate::launch::Step {
addressee: crate::tools::send::Addressee::Role,
place: None,
branch: ctx.custom_identifier.clone(),
name: Some(name.to_string()),
extract: None,
},
None => crate::launch::Step {
branch: ctx.custom_identifier.clone(),
..crate::launch::Step::worker()
},
};
crate::tools::chain::abandon_unreadable(&ctx.chain, &step, &ctx.workspace_name, None)
.await;
retire_chain_step(agent_id).await;
ChainStep::Retire
}
}
}
async fn retire_chain_step(agent_id: &str) {
if let Err(e) = crate::jobs::retire_chain_session(agent_id).await {
tracing::warn!(
agent_id = %agent_id,
error = %e,
"Failed to retire a chain step's conversation"
);
}
}
fn is_continuable_branch(role: Role, agent_id: &str) -> bool {
match role {
Role::Custom => true,
Role::Worker => crate::session::is_worker_branch_agent_id(agent_id),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::super::BatchMetadata;
use super::*;
use crate::Tool;
#[tokio::test]
async fn attempt_recovery_abandons_a_custom_branch_without_a_role_record() {
crate::util::test::init_test_stores().await;
let ctx = SessionContext {
channel: "gui".to_string(),
user_name: crate::users::ADMIN_USER_NAME.to_string(),
workspace_name: crate::users::personal_workspace_name(crate::users::ADMIN_USER_NAME),
role: crate::Role::Custom.as_str().to_string(),
custom_role: None,
custom_identifier: None,
reply_to: None,
chain: crate::launch::Stored::Ordinary,
extract: None,
};
assert!(
!attempt_recovery("role_test_launchless", &ctx, Role::Custom).await,
"a custom session without a recorded role is permanently un-recoverable"
);
let deleted = SessionContext {
custom_role: Some("ghost_role".to_string()),
..ctx
};
assert!(
!attempt_recovery("role_test_ghost", &deleted, Role::Custom).await,
"a branch whose custom role was deleted is permanently un-recoverable"
);
}
#[tokio::test]
#[serial_test::serial(drain)]
async fn a_deleted_role_ends_its_chain_loudly() {
let _store = crate::util::test::STORE_LOCK.lock().await;
crate::util::test::init_management_test_stores().await;
let ws = crate::util::test::create_test_workspace(
&crate::util::test::test_root()
.join("dead_chain_role")
.to_string_lossy(),
"dead_chain_role_ws",
)
.await;
let chain = crate::launch::Chain {
id: "deadrole".to_string(),
task: "draft it".to_string(),
user: crate::users::ADMIN_USER_NAME.to_string(),
channel: "gui".to_string(),
workspace: ws.name.clone(),
inherited: None,
current: crate::launch::Step {
addressee: crate::tools::send::Addressee::Role,
place: None,
branch: None,
name: Some("ghost_role".to_string()),
extract: None,
},
step: 1,
next: Vec::new(),
};
let ctx = SessionContext {
channel: "gui".to_string(),
user_name: crate::users::ADMIN_USER_NAME.to_string(),
workspace_name: ws.name.clone(),
role: Role::Custom.as_str().to_string(),
custom_role: Some("ghost_role".to_string()),
custom_identifier: None,
reply_to: None,
chain: crate::launch::Stored::Step(Box::new(chain.clone())),
extract: None,
};
let admin = crate::session::assistant_agent_id(crate::users::ADMIN_USER_NAME);
let mut admin_rx = crate::agent::message_router::register_agent(&admin);
assert!(
!attempt_recovery("role_test_ghost_chain", &ctx, Role::Custom).await,
"the step cannot run"
);
let job = tokio::time::timeout(std::time::Duration::from_secs(2), admin_rx.recv())
.await
.expect("the chain's failure is delivered")
.expect("the failure envelope");
assert!(
job.content
.contains("Step 1 of 1 failed: the step's custom role no longer exists"),
"{}",
job.content
);
crate::agent::message_router::unregister_agent(&admin);
}
#[tokio::test]
async fn a_one_off_role_step_resumes_with_its_chain() {
crate::util::test::init_management_test_stores().await;
crate::custom_role::create(
"oneoff_editor",
"you edit",
&[],
crate::custom_role::CustomRoleBehavior::OneOff,
)
.await
.expect("create the step's role");
let workspace = crate::users::personal_workspace_name(crate::users::ADMIN_USER_NAME);
let chain = crate::launch::Chain {
id: "oneoff_step".to_string(),
task: "draft it".to_string(),
user: crate::users::ADMIN_USER_NAME.to_string(),
channel: "gui".to_string(),
workspace: workspace.clone(),
inherited: None,
current: crate::launch::Step {
addressee: crate::tools::send::Addressee::Role,
place: None,
branch: None,
name: Some("oneoff_editor".to_string()),
extract: None,
},
step: 1,
next: Vec::new(),
};
let conversation = crate::session::custom_role_run_agent_id("oneoff_editor");
let ctx = SessionContext {
channel: "gui".to_string(),
user_name: crate::users::ADMIN_USER_NAME.to_string(),
workspace_name: workspace,
role: Role::Custom.as_str().to_string(),
custom_role: Some("oneoff_editor".to_string()),
custom_identifier: None,
reply_to: None,
chain: crate::launch::Stored::Step(Box::new(chain.clone())),
extract: None,
};
let mut rx = crate::agent::message_router::register_agent(&conversation);
assert!(
attempt_recovery(&conversation, &ctx, Role::Custom).await,
"a one-off role's chain step is recoverable"
);
let job = rx.try_recv().expect("the retry job is routed");
assert_eq!(job.kind, MessageKind::RecoveryRetry);
let launch = job.custom_role.expect("the step's launch is rebuilt");
assert_eq!(
launch.chain.as_ref().map(|chain| chain.step),
Some(1),
"the resumed step carries its chain, so its answer is handed on"
);
assert_eq!(
launch.agent_id, conversation,
"and it continues in the conversation the step was mid-turn in"
);
crate::agent::message_router::unregister_agent(&conversation);
crate::jobs::delete_chain_rows(&chain.id)
.await
.expect("clean up this test's chain");
}
#[tokio::test]
async fn attempt_recovery_rebuilds_a_worker_branch_with_its_asker() {
crate::util::test::init_management_test_stores().await;
let branch = crate::session::worker_branch_agent_id("night");
let asker_folder = crate::users::personal_workspace_name(crate::users::ADMIN_USER_NAME);
let ctx = SessionContext {
channel: "gui".to_string(),
user_name: crate::users::ADMIN_USER_NAME.to_string(),
workspace_name: asker_folder.clone(),
role: Role::Worker.as_str().to_string(),
custom_role: None,
custom_identifier: Some("night".to_string()),
reply_to: Some(crate::agent::message_router::Asker {
launch: crate::Launch {
role: Role::Custom,
name: "briefer".to_string(),
identifier: Some("hourly".to_string()),
prompt: "you brief".to_string(),
tools: Vec::new(),
agent_id: crate::session::custom_role_agent_id("briefer", Some("hourly")),
reply_to: None,
chain: None,
extract: None,
},
workspace: asker_folder,
}),
chain: crate::launch::Stored::Ordinary,
extract: None,
};
let mut rx = crate::agent::message_router::register_agent(&branch);
assert!(
attempt_recovery(&branch, &ctx, Role::Worker).await,
"a worker branch is recoverable"
);
let job = rx.try_recv().expect("the retry job is routed");
assert_eq!(job.kind, MessageKind::RecoveryRetry);
assert_eq!(job.role, Role::Worker);
let launch = job
.custom_role
.expect("a worker branch's job carries its launch");
assert_eq!(launch.role, Role::Worker);
assert_eq!(launch.identifier.as_deref(), Some("night"));
assert_eq!(
launch
.reply_to
.as_ref()
.map(|reply| reply.launch.name.as_str()),
Some("briefer"),
"the asking conversation is restored, so the report returns there"
);
}
#[tokio::test]
async fn a_branch_step_survives_a_restart_on_its_conversation_alone() {
crate::util::test::init_management_test_stores().await;
let branch = crate::session::worker_branch_agent_id("editor");
let workspace = crate::users::personal_workspace_name(crate::users::ADMIN_USER_NAME);
let chain = crate::launch::Chain {
id: "recovered".to_string(),
task: "draft it".to_string(),
user: crate::users::ADMIN_USER_NAME.to_string(),
channel: "gui".to_string(),
workspace: workspace.clone(),
inherited: None,
current: crate::launch::Step {
addressee: crate::tools::send::Addressee::WorkerBranch,
place: None,
branch: Some("editor".to_string()),
name: None,
extract: None,
},
step: 1,
next: vec![crate::launch::Step {
addressee: crate::tools::send::Addressee::Worker,
place: None,
branch: None,
name: None,
extract: None,
}],
};
crate::session::store()
.set_branch(&branch, None, Some("editor"), None, Some(&chain), None)
.await
.expect("the conversation records the chain it is a step of");
let ctx = SessionContext {
channel: "gui".to_string(),
user_name: crate::users::ADMIN_USER_NAME.to_string(),
workspace_name: workspace,
role: Role::Worker.as_str().to_string(),
custom_role: None,
custom_identifier: Some("editor".to_string()),
reply_to: None,
chain: crate::launch::Stored::Step(Box::new(chain.clone())),
extract: None,
};
let mut rx = crate::agent::message_router::register_agent(&branch);
assert!(
attempt_recovery(&branch, &ctx, Role::Worker).await,
"a chain step is recoverable — it continues from where it was"
);
let job = rx.try_recv().expect("the retry job is routed");
let launch = job
.custom_role
.expect("a worker branch's job carries its launch");
assert_eq!(
launch.chain.as_ref().map(|chain| chain.step),
Some(1),
"the recovered turn carries its chain, so its answer is handed on"
);
crate::agent::message_router::unregister_agent(&branch);
crate::jobs::delete_chain_rows(&chain.id)
.await
.expect("clean up this test's chain");
}
#[tokio::test]
async fn an_ordinary_send_recovers_with_its_schema() {
crate::util::test::init_management_test_stores().await;
let branch = crate::session::worker_branch_agent_id("shaped");
let workspace = crate::users::personal_workspace_name(crate::users::ADMIN_USER_NAME);
let extract = crate::extract::Extract::from_text(
r#"{"type":"object","properties":{"summary":{"type":"string"}},"required":["summary"]}"#,
)
.expect("the schema is accepted");
crate::session::store()
.set_branch(&branch, None, Some("shaped"), None, None, Some(&extract))
.await
.expect("the conversation records the schema its answer must come back as");
let ctx = SessionContext {
channel: "gui".to_string(),
user_name: crate::users::ADMIN_USER_NAME.to_string(),
workspace_name: workspace,
role: Role::Worker.as_str().to_string(),
custom_role: None,
custom_identifier: Some("shaped".to_string()),
reply_to: None,
chain: crate::launch::Stored::Ordinary,
extract: Some(extract.clone()),
};
let mut rx = crate::agent::message_router::register_agent(&branch);
assert!(
attempt_recovery(&branch, &ctx, Role::Worker).await,
"an ordinary branch turn is recoverable"
);
let job = rx.try_recv().expect("the retry job is routed");
let launch = job
.custom_role
.expect("a worker branch's job carries its launch");
assert_eq!(
launch.extract.as_ref(),
Some(&extract),
"the recovered turn still knows the schema its answer must match"
);
crate::agent::message_router::unregister_agent(&branch);
}
#[tokio::test]
#[serial_test::serial(drain)]
async fn a_stopped_chain_step_is_never_resumed() {
crate::util::test::init_management_test_stores().await;
let branch = crate::session::worker_branch_agent_id("stopped");
let workspace = crate::users::personal_workspace_name(crate::users::ADMIN_USER_NAME);
let chain = crate::launch::Chain {
id: "stopped_step".to_string(),
task: "draft it".to_string(),
user: crate::users::ADMIN_USER_NAME.to_string(),
channel: "gui".to_string(),
workspace: workspace.clone(),
inherited: None,
current: crate::launch::Step {
addressee: crate::tools::send::Addressee::WorkerBranch,
place: None,
branch: Some("stopped".to_string()),
name: None,
extract: None,
},
step: 1,
next: Vec::new(),
};
crate::session::store()
.set_branch(&branch, None, Some("stopped"), None, Some(&chain), None)
.await
.expect("the conversation records the chain it is a step of");
let ctx = SessionContext {
channel: "gui".to_string(),
user_name: crate::users::ADMIN_USER_NAME.to_string(),
workspace_name: workspace,
role: Role::Worker.as_str().to_string(),
custom_role: None,
custom_identifier: Some("stopped".to_string()),
reply_to: None,
chain: crate::launch::Stored::Step(Box::new(chain.clone())),
extract: None,
};
crate::tools::chain::stop(&chain.id)
.await
.expect("stop the chain");
let mut rx = crate::agent::message_router::register_agent(&branch);
assert!(
!attempt_recovery(&branch, &ctx, Role::Worker).await,
"a stopped chain step is not resumed"
);
assert!(
rx.try_recv().is_err(),
"and nothing is routed into its conversation"
);
assert!(
crate::session::store().get_launch_stopped(&branch).await,
"the stopped conversation is never restarted by the poller"
);
crate::agent::message_router::unregister_agent(&branch);
}
#[tokio::test]
#[serial_test::serial(drain)]
async fn an_unreadable_chain_step_is_abandoned_loudly() {
crate::util::test::init_management_test_stores().await;
let branch = crate::session::worker_branch_agent_id("corrupt");
let workspace = crate::users::personal_workspace_name(crate::users::ADMIN_USER_NAME);
crate::session::store()
.set_branch(&branch, None, Some("corrupt"), None, None, None)
.await
.expect("the conversation exists");
let ctx = SessionContext {
channel: "gui".to_string(),
user_name: crate::users::ADMIN_USER_NAME.to_string(),
workspace_name: workspace,
role: Role::Worker.as_str().to_string(),
custom_role: None,
custom_identifier: Some("corrupt".to_string()),
reply_to: None,
chain: crate::launch::Stored::Unreadable(None),
extract: None,
};
let mut rx = crate::agent::message_router::register_agent(&branch);
let admin = crate::session::assistant_agent_id(crate::users::ADMIN_USER_NAME);
let mut admin_rx = crate::agent::message_router::register_agent(&admin);
assert!(
!attempt_recovery(&branch, &ctx, Role::Worker).await,
"an unreadable chain step is abandoned"
);
assert!(rx.try_recv().is_err(), "nothing is routed into it");
let job = admin_rx
.try_recv()
.expect("the caller is told the chain stopped");
assert!(job.content.contains("could not be read"), "{}", job.content);
assert!(
crate::session::store().get_launch_stopped(&branch).await,
"the abandoned conversation is never restarted"
);
crate::agent::message_router::unregister_agent(&branch);
crate::agent::message_router::unregister_agent(&admin);
}
#[test]
fn test_is_recovery_candidate_classification() {
assert!(is_recovery_candidate(ChatRole::User, ""));
assert!(is_recovery_candidate(ChatRole::Tool, ""));
assert!(!is_recovery_candidate(
ChatRole::Assistant,
"plain assistant reply"
));
assert!(!is_recovery_candidate(
ChatRole::Assistant,
r#"{"answer": 42}"#
));
let frame = crate::providers::reasoning::assistant_replay_payload(
Some(""),
&[crate::ToolCall {
id: "call_frame".into(),
name: "read".into(),
arguments: serde_json::json!({"path": "a.txt"}),
}],
None,
)
.to_string();
assert!(is_recovery_candidate(ChatRole::Assistant, &frame));
assert!(!is_recovery_candidate(
ChatRole::Assistant,
r#"{"content":"","tool_calls":[]}"#
));
assert!(!is_recovery_candidate(
ChatRole::Assistant,
"not json at all"
));
assert!(!is_recovery_candidate(ChatRole::System, ""));
}
#[test]
fn test_dead_session_tracker_exhaustion_is_permanent() {
let tracker = DeadSessionTracker::new();
let agent_id = "test_permanent_engineer";
assert!(tracker.should_retry(agent_id));
tracker.record_attempt(agent_id);
assert!(!tracker.should_retry(agent_id));
for _ in 2..=MAX_RETRIES {
tracker.record_attempt(agent_id);
}
assert!(
!tracker.should_retry(agent_id),
"should be blocked after {MAX_RETRIES} attempts"
);
if let Some(state) = tracker.inner.lock().unwrap_poison().get_mut(agent_id) {
state.last_attempt_at = Some(Utc::now() - chrono::Duration::hours(24));
}
assert!(
!tracker.should_retry(agent_id),
"cap must block even after the backoff has long elapsed"
);
assert_eq!(
tracker
.inner
.lock()
.unwrap_poison()
.get(agent_id)
.map(|s| s.attempt_count),
Some(MAX_RETRIES)
);
}
#[test]
fn dead_session_tracker_backoff_cleanup_and_restart_reset() {
let tracker = DeadSessionTracker::new();
let agent_id = "test_backoff_engineer";
assert!(tracker.should_retry(agent_id));
tracker.record_attempt(agent_id);
assert!(!tracker.should_retry(agent_id));
tracker.cleanup(agent_id);
assert!(tracker.should_retry(agent_id));
tracker.record_attempt(agent_id);
let tracker2 = DeadSessionTracker::new();
assert!(
tracker2.should_retry(agent_id),
"should be fresh after simulated restart"
);
}
#[test]
#[serial_test::serial(provider, drain)]
fn deterministic_failure_over_an_unchanged_tail_is_skipped() {
let agent_id = "test_deterministic_engineer";
let tail = ChatMessage::user("stuck question");
assert!(
!DEAD_SESSION_TRACKER.unchanged_since_deterministic_failure(
agent_id,
ChatRole::User,
&tail.content
),
"no record yet — the session is recoverable"
);
record_deterministic_failure(agent_id, Some(&tail));
assert!(
DEAD_SESSION_TRACKER.unchanged_since_deterministic_failure(
agent_id,
ChatRole::User,
&tail.content
),
"the same tail must be skipped"
);
assert!(DEAD_SESSION_TRACKER.should_retry(agent_id));
assert_eq!(
DEAD_SESSION_TRACKER
.inner
.lock()
.unwrap_poison()
.get(agent_id)
.map(|state| state.attempt_count),
Some(0),
"the skip must not record a recovery attempt"
);
assert!(
!DEAD_SESSION_TRACKER.unchanged_since_deterministic_failure(
agent_id,
ChatRole::User,
"a new question"
),
"a changed tail must be recovered"
);
assert!(
!DEAD_SESSION_TRACKER.unchanged_since_deterministic_failure(
agent_id,
ChatRole::Assistant,
&tail.content
),
"the role is part of the signature"
);
DEAD_SESSION_TRACKER.forget_deterministic_failure(agent_id);
assert!(!DEAD_SESSION_TRACKER.unchanged_since_deterministic_failure(
agent_id,
ChatRole::User,
&tail.content
));
for excluded in ["manager_test_det", "analyze_test_det", "ticket_test_det"] {
record_deterministic_failure(excluded, Some(&tail));
assert!(
!DEAD_SESSION_TRACKER.unchanged_since_deterministic_failure(
excluded,
ChatRole::User,
&tail.content
),
"{excluded} must not be recorded"
);
}
record_deterministic_failure("test_deterministic_no_tail", None);
assert!(!DEAD_SESSION_TRACKER.unchanged_since_deterministic_failure(
"test_deterministic_no_tail",
ChatRole::User,
""
));
}
#[expect(clippy::too_many_lines)] async fn seed_dangling_durable_session(agent_id: &str, ws: &crate::Workspace) -> String {
let conn = &crate::session::store().conn;
let frame = crate::providers::reasoning::assistant_replay_payload(
Some(""),
&[crate::ToolCall {
id: "call_analyze_e2e".to_string(),
name: "analyze".to_string(),
arguments: serde_json::json!({"message": "analyze this"}),
}],
None,
)
.to_string();
crate::session::store()
.append_messages(
agent_id,
&[
crate::ChatMessage::user("run the analysis"),
crate::ChatMessage::assistant(frame),
],
false,
BatchMetadata::context("gui", "e2e_user", ws.name.as_str(), "engineer"),
)
.await
.unwrap();
let past = (chrono::Utc::now() - chrono::Duration::minutes(10)).to_rfc3339();
conn.execute(
"UPDATE session_metadata SET last_activity = ?1 WHERE agent_id = ?2",
crate::db::params![past, agent_id],
)
.await
.unwrap();
crate::shutdown::drain_begin();
let tool = crate::tools::analyze::AnalyzeTool::new(
crate::tools::analyze::DispatchMode::Sync,
crate::Role::Engineer,
);
let res = crate::agent::CURRENT_TOOL_AGENT_ID
.scope(Some(agent_id.to_string()), async {
tool.execute(ws, serde_json::json!({"message": "analyze this"}))
.await
})
.await;
crate::shutdown::drain_clear();
let err = res.expect_err("drain must cut the sync analyze dispatch");
assert!(
err.downcast_ref::<crate::tools::CallSuspended>().is_some(),
"CallSuspended carrier expected: {err:#}"
);
let jobs = conn
.query(
"SELECT id, status, caller_agent_id FROM jobs WHERE caller_agent_id = ?1 AND kind = 'analyze'",
crate::db::params![agent_id],
)
.await
.unwrap();
assert_eq!(jobs.len(), 1, "one launched analyze job");
assert_eq!(jobs[0].get::<String>(1).unwrap(), "launched");
assert_eq!(
jobs[0].get::<String>(2).unwrap(),
agent_id,
"job is caller-owned by the session pin"
);
let job_id = jobs[0].get::<String>(0).unwrap();
let session_rows = conn
.query(
"SELECT role FROM sessions WHERE agent_id = ?1 ORDER BY id",
crate::db::params![agent_id],
)
.await
.unwrap();
let roles: Vec<String> = session_rows
.iter()
.map(|r| r.get::<String>(0).unwrap())
.collect();
assert_eq!(
roles,
vec!["user", "assistant"],
"frame persisted with NO tool-result row: {roles:?}"
);
let roster = crate::jobs::list_agents_for_job(conn, &job_id)
.await
.unwrap();
assert!(
roster.len() >= 2,
"analyze round spawns multiple analysts: {}",
roster.len()
);
for (i, row) in roster.iter().enumerate() {
let outcome = if i == 0 { "ANALYST_RAW" } else { "" };
crate::jobs::write_agent_outcome(
conn,
&job_id,
&row.agent_id,
crate::jobs::RowStatus::Done,
Some(outcome),
)
.await
.unwrap();
}
job_id
}
#[tokio::test]
#[serial_test::serial(provider, drain)] async fn recovery_resumes_dangling_durable_job_end_to_end() {
let fake = std::sync::Arc::new(
crate::util::test::FakeProvider::new()
.ok("Recovery round: analysis resumed and complete."),
);
let _seam = crate::util::test::install_retry_seam_dyn(fake.clone());
crate::util::test::init_management_test_stores().await;
let _ = crate::CHANNEL_REGISTRY.set(crate::ChannelRegistry::default());
let ws = crate::util::test::create_test_workspace(
"/tmp/dead_session_e2e_ws",
"dead_session_e2e_ws",
)
.await;
let agent_id = format!("e2e_user_{}_engineer", ws.name);
let conn = &crate::session::store().conn;
let job_id = seed_dangling_durable_session(&agent_id, &ws).await;
recover_dead_sessions().await.unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
loop {
let jobs = conn
.query(
"SELECT id FROM jobs WHERE id = ?1",
crate::db::params![job_id.clone()],
)
.await
.unwrap();
let tail = crate::session::store()
.get_last_message_tail(&agent_id)
.await;
let tail_role = tail.as_ref().map(|(role, _)| *role);
let tail_has_reply = tail
.as_ref()
.is_some_and(|(_, content)| content.contains("Recovery round"));
if jobs.is_empty() && tail_role == Some(crate::ChatRole::Assistant) && tail_has_reply {
break;
}
assert!(
std::time::Instant::now() < deadline,
"recovery did not complete within 60s: jobs={jobs:?} \
tail_role={tail_role:?} tail_has_reply={tail_has_reply}",
);
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
let last2 = conn
.query(
"SELECT role, content FROM sessions WHERE agent_id = ?1 ORDER BY id DESC LIMIT 2",
crate::db::params![agent_id.as_str()],
)
.await
.unwrap();
assert_eq!(last2.len(), 2, "tail has tool-result + reply: {last2:?}");
let reply_row = &last2[0];
let tool_row = &last2[1];
assert_eq!(tool_row.get::<String>(0).unwrap(), "tool");
let payload: crate::ToolResultPayload =
serde_json::from_str(&tool_row.get::<String>(1).unwrap()).unwrap();
assert_eq!(payload.tool_call_id, "call_analyze_e2e");
assert!(
payload.content.contains("ANALYST_RAW"),
"checkpointed outcome recorded: {}",
payload.content
);
assert!(
reply_row
.get::<String>(1)
.unwrap()
.contains("Recovery round"),
"recovery round reply persisted"
);
assert_eq!(
fake.request_fingerprints.lock().unwrap().len(),
1,
"durable resume sub-phase was LLM-free; the recovery round called the model once"
);
let pending_jobs = conn
.query(
"SELECT id FROM pending_jobs WHERE id = ?1",
crate::db::params![job_id.clone()],
)
.await
.unwrap();
assert!(pending_jobs.is_empty(), "no envelope pending after resume");
}
#[tokio::test]
#[serial_test::serial(provider, drain)] async fn live_running_session_is_not_recovered() {
crate::util::test::init_test_stores().await;
let ws = crate::util::test::create_test_workspace(
"/tmp/dead_session_live_ws",
"dead_session_live_ws",
)
.await;
let agent_id = format!("e2e_user_{}_engineer", ws.name);
let conn = &crate::session::store().conn;
let job_id = seed_dangling_durable_session(&agent_id, &ws).await;
let generation = AGENT_REGISTRY.register(
agent_id.clone(),
"engineer".into(),
None,
&ws,
tokio_util::sync::CancellationToken::new(),
tokio_util::sync::CancellationToken::new(),
None,
None,
std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
);
recover_dead_sessions().await.unwrap();
let jobs = conn
.query(
"SELECT status FROM jobs WHERE id = ?1",
crate::db::params![job_id.clone()],
)
.await
.unwrap();
assert_eq!(jobs.len(), 1, "job must not be terminalized");
assert_eq!(jobs[0].get::<String>(0).unwrap(), "launched");
assert!(
DEAD_SESSION_TRACKER.should_retry(&agent_id),
"no recovery attempt recorded for a live session"
);
AGENT_REGISTRY.deregister(&agent_id, generation);
conn.execute(
"DELETE FROM sessions WHERE agent_id = ?1",
crate::db::params![agent_id.clone()],
)
.await
.unwrap();
conn.execute(
"DELETE FROM session_metadata WHERE agent_id = ?1",
crate::db::params![agent_id.as_str()],
)
.await
.unwrap();
for row in conn
.query(
"SELECT agent_id FROM agents WHERE job_id = ?1",
crate::db::params![job_id.clone()],
)
.await
.unwrap()
{
let a_id: String = row.get(0).unwrap();
conn.execute(
"DELETE FROM agents WHERE job_id = ?1 AND agent_id = ?2",
crate::db::params![job_id.clone(), a_id],
)
.await
.unwrap();
}
conn.execute(
"DELETE FROM jobs WHERE id = ?1",
crate::db::params![job_id.clone()],
)
.await
.unwrap();
}
#[tokio::test]
#[serial_test::serial(provider, drain)] async fn paused_workspace_dangling_frame_is_not_recovered() {
crate::util::test::init_management_test_stores().await;
let ws = crate::util::test::create_test_workspace(
"/tmp/dead_session_paused_ws",
"dead_session_paused_ws",
)
.await;
let agent_id = format!("e2e_user_{}_engineer", ws.name);
let conn = &crate::session::store().conn;
let job_id = seed_dangling_durable_session(&agent_id, &ws).await;
conn.execute(
"UPDATE workspaces SET paused = 1 WHERE name = ?1",
crate::db::params![ws.name],
)
.await
.unwrap();
recover_dead_sessions().await.unwrap();
let jobs = conn
.query(
"SELECT status FROM jobs WHERE id = ?1",
crate::db::params![job_id.clone()],
)
.await
.unwrap();
assert_eq!(jobs.len(), 1, "job must not be terminalized");
assert_eq!(jobs[0].get::<String>(0).unwrap(), "launched");
assert!(
DEAD_SESSION_TRACKER.should_retry(&agent_id),
"no recovery attempt recorded for a paused workspace"
);
}
#[tokio::test]
#[serial_test::serial(provider)] async fn sleep_ended_session_is_not_recovered() {
crate::util::test::init_test_stores().await;
let ws = crate::util::test::create_test_workspace(
"/tmp/dead_session_sleep_ws",
"dead_session_sleep_ws",
)
.await;
let agent_id = format!("e2e_user_{}_engineer", ws.name);
let conn = &crate::session::store().conn;
crate::session::store()
.append_messages(
&agent_id,
&[
crate::ChatMessage::user("hello"),
crate::ChatMessage::tool_result("call_sleep", "Zzz..."),
],
false,
BatchMetadata::context("gui", "e2e_user", ws.name.as_str(), "assistant"),
)
.await
.unwrap();
let past = (chrono::Utc::now() - chrono::Duration::minutes(10)).to_rfc3339();
conn.execute(
"UPDATE session_metadata SET last_activity = ?1 WHERE agent_id = ?2",
crate::db::params![past, agent_id.as_str()],
)
.await
.unwrap();
crate::session::store()
.set_sleep_ended(&agent_id, true)
.await
.unwrap();
recover_dead_sessions().await.unwrap();
assert!(
DEAD_SESSION_TRACKER.should_retry(&agent_id),
"no recovery attempt recorded for a sleep-ended session"
);
assert!(
crate::session::store().get_sleep_ended(&agent_id).await,
"sleep-ended flag must survive the poll cycle"
);
conn.execute(
"DELETE FROM sessions WHERE agent_id = ?1",
crate::db::params![agent_id.as_str()],
)
.await
.unwrap();
conn.execute(
"DELETE FROM session_metadata WHERE agent_id = ?1",
crate::db::params![agent_id.as_str()],
)
.await
.unwrap();
}
}