fix: make runtime session input admission atomic during shutdown

This commit is contained in:
coso committed 2026-11-11 17:24:39 +08:00
1 parent 0872471317
commit 84fe17268e
5 files changed
+161 -27

No files matched your search

+1
View File
@@ -22,6 +22,7 @@ Simplified Chinese release notes are the primary version.
- Explicitly release the Computer Use control lock so concurrently launched child processes cannot retain an ended control lease.
- Preserve model catalog instructions and multi-agent message configuration instead of replacing them with bundled defaults.
- Remove the Start menu shortcut created for Electron notifications during Windows uninstall, preventing a stale entry after the installation is removed.
- Fix a race between background input and session cleanup so rejected input cannot prematurely close a shared session.
### Improvements and Refactoring
+1
View File
@@ -20,6 +20,7 @@
- 显式释放 Computer Use 控制锁,避免并发启动的子进程短暂保留已结束的控制租约。
- 保留模型目录提供的基础指令与多 Agent 消息配置,避免被内置默认模板覆盖。
- Windows 卸载时清理 Electron 通知创建的自有开始菜单快捷方式,避免安装目录已删除但入口仍残留。
- 修复关闭会话时后台输入与清理流程的竞态,避免被拒绝的输入提前关闭共享会话。
### 优化与重构
@@ -29,12 +29,27 @@ impl RuntimeSessionRegistry {
session_id: &str,
thread_id: &str,
) -> Result<RuntimeSessionHandle, RuntimeSessionLoopError> {
self.get_or_create_if(session_id, thread_id, || true)
.await
.map(|handle| handle.expect("unconditional session admission"))
}
/// Evaluate admission while holding the same lock as actor lookup and creation.
pub async fn get_or_create_if(
&self,
session_id: &str,
thread_id: &str,
admit: impl FnOnce() -> bool,
) -> Result<Option<RuntimeSessionHandle>, RuntimeSessionLoopError> {
if session_id.trim().is_empty() || thread_id.trim().is_empty() {
return Err(RuntimeSessionLoopError::InvalidTask(
"runtime session actor requires canonical session_id and thread_id".to_string(),
));
}
let mut sessions = self.sessions.lock().await;
if !admit() {
return Ok(None);
}
if let Some(handle) = sessions.get(session_id) {
if handle.thread_id() != thread_id {
return Err(RuntimeSessionLoopError::InvalidTask(format!(
@@ -42,7 +57,7 @@ impl RuntimeSessionRegistry {
handle.thread_id()
)));
}
return Ok(handle.clone());
return Ok(Some(handle.clone()));
}
let handle = RuntimeSessionActor::spawn(
session_id.to_string(),
@@ -50,7 +65,7 @@ impl RuntimeSessionRegistry {
self.code_mode_factory.as_ref(),
);
sessions.insert(session_id.to_string(), handle.clone());
Ok(handle)
Ok(Some(handle))
}
pub async fn shutdown(&self, session_id: &str) -> Result<(), RuntimeSessionLoopError> {
@@ -116,3 +131,59 @@ impl RuntimeSessionRegistry {
handle.snapshot().await.map(Some)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
#[tokio::test]
async fn admission_is_checked_after_the_registry_lock_without_creating_a_rejected_actor() {
let registry = RuntimeSessionRegistry::default();
let admitted = Arc::new(AtomicBool::new(true));
let guard = registry.sessions.lock().await;
let (started, waiting) = tokio::sync::oneshot::channel();
let creation = tokio::spawn({
let registry = registry.clone();
let admitted = admitted.clone();
async move {
started.send(()).unwrap();
registry
.get_or_create_if("rejected-session", "rejected-thread", || {
admitted.load(Ordering::SeqCst)
})
.await
}
});
waiting.await.unwrap();
admitted.store(false, Ordering::SeqCst);
drop(guard);
assert!(creation.await.unwrap().unwrap().is_none());
assert!(registry.get_existing("rejected-session").await.is_none());
}
#[tokio::test]
async fn denied_admission_preserves_the_existing_actor_for_its_shutdown_owner() {
let registry = RuntimeSessionRegistry::default();
let actor = registry
.get_or_create_if("owned-session", "owned-thread", || true)
.await
.unwrap()
.unwrap();
assert!(registry
.get_or_create_if("owned-session", "owned-thread", || false)
.await
.unwrap()
.is_none());
actor
.snapshot()
.await
.expect("rejection must not close the actor");
registry.shutdown("owned-session").await.unwrap();
assert!(registry.get_existing("owned-session").await.is_none());
assert!(matches!(
actor.snapshot().await,
Err(RuntimeSessionLoopError::Closed)
));
}
}
@@ -223,34 +223,32 @@ impl RuntimeCore {
session_id: &str,
thread_id: &str,
) -> Result<RuntimeSessionHandle, RuntimeCoreError> {
let mut admission = Ok(());
let session = self
.session_loops
.get_or_create(session_id, thread_id)
.get_or_create_if(session_id, thread_id, || {
// Shutdown marks state before taking the registry lock. Admission
// must share that lock so rejected input cannot close its actor.
let state = self
.state
.lock()
.expect("runtime core state mutex poisoned");
admission = state
.ensure_session_accepts_input(session_id)
.and_then(|()| {
state
.sessions
.contains_key(session_id)
.then_some(())
.ok_or_else(|| {
RuntimeCoreError::SessionNotFound(session_id.to_string())
})
});
admission.is_ok()
})
.await
.map_err(|error| RuntimeCoreError::Backend(error.to_string()))?;
let admission = {
let state = self
.state
.lock()
.expect("runtime core state mutex poisoned");
state
.ensure_session_accepts_input(session_id)
.and_then(|()| {
state
.sessions
.contains_key(session_id)
.then_some(())
.ok_or_else(|| RuntimeCoreError::SessionNotFound(session_id.to_string()))
})
};
if let Err(error) = admission {
// A preparing request may have raced with shutdown while creating its actor.
self.session_loops
.shutdown(session_id)
.await
.map_err(|error| RuntimeCoreError::Backend(error.to_string()))?;
return Err(error);
}
Ok(session)
admission?;
Ok(session.expect("successful admission retains a runtime session actor"))
}
}
@@ -253,6 +253,69 @@ async fn closing_session_rejects_turn_admission_and_resume_without_creating_loop
.unwrap();
}
#[tokio::test]
async fn rejected_input_must_not_shutdown_the_actor_owned_by_session_cleanup() {
for shutting_down in [false, true] {
let (_temp, runtime, _backend) = prepared_runtime().await;
let actor = runtime
.session_loop_for_input("shutdown-session", "shutdown-thread")
.await
.unwrap();
let task = actor
.submit(
Arc::new(agent_runtime::session_loop::RuntimeSessionClosureTask::new(
"cleanup-owned-turn",
Vec::new(),
|_context, _input, cancellation| {
Box::pin(async move {
cancellation.cancelled().await;
Ok(())
})
},
)),
false,
)
.await
.unwrap();
{
let mut state = runtime.state.lock().unwrap();
state.shutting_down = shutting_down;
if !shutting_down {
state
.closing_sessions
.insert("shutdown-session".to_string());
}
}
let rejected = runtime
.session_loop_for_input("shutdown-session", "shutdown-thread")
.await;
assert!(
matches!(rejected, Err(RuntimeCoreError::InvalidRequest(ref message))
if message == "runtime session is shutting down: shutdown-session")
);
assert!(actor
.interrupt_for_turn(Some("cleanup-owned-turn"))
.await
.expect("rejected input must retain the cleanup owner's actor"));
assert_eq!(
task.completion.await.unwrap().unwrap(),
agent_runtime::session_loop::RuntimeSessionTaskOutcome::Interrupted
);
runtime
.state
.lock()
.unwrap()
.closing_sessions
.remove("shutdown-session");
runtime.shutdown().await.unwrap();
assert!(runtime
.session_loops
.get_existing("shutdown-session")
.await
.is_none());
}
}
#[tokio::test]
async fn transport_shutdown_waits_for_idle_cleanup_and_blocks_new_sessions() {
let (_temp, runtime, backend) = prepared_runtime().await;