Scope code mode callback delegates to individual executions (#44865)

## Why

A delegate bound at session creation cannot provide different callbacks for cells sharing that session. Each execution needs to retain its own delegate across yields and release it when the cell is cleaned up.

## What changed

- Pass `CodeModeSessionDelegate` to `execute` instead of session creation.
- Route tool calls, notifications, and cell closure callbacks through the execution's delegate in the in-process runtime and the gRPC and stdio transports.
- Retain delegates with pending executions and live cells, releasing them through closure and cancellation cleanup.

## Testing

Add coverage for distinct delegates across yielded cells, gRPC callbacks before cell admission, and delegate release after completion or abandoned execution cleanup. Update transport tests to verify callbacks reach the owning cell's delegate.

GitOrigin-RevId: 7469f52104b993e790a40c65fb800ad02b7fd606
This commit is contained in:
Abhinav authored and copyberry committed 2026-09-11 17:00:07 +00:00
1 parent bc5957eac9
commit 3305c4f31d
30 files changed
+1027 -637

No files matched your search

@@ -133,12 +133,12 @@ impl SessionInner {
}
let invocation_id = call.invocation_id.clone();
let cancellation = match admission {
CallbackAdmission::Active(cancellation) => Ok(cancellation),
CallbackAdmission::Active(cancellation, delegate) => Ok((cancellation, delegate)),
CallbackAdmission::Cancelled => return Ok(()),
CallbackAdmission::Closed => Err(format!("code-mode cell {} is closed", call.cell_id)),
CallbackAdmission::Rejected(error) => Err(error),
};
let cancellation = match cancellation {
let (cancellation, delegate) = match cancellation {
Ok(cancellation) => cancellation,
Err(error) => {
let inner = Arc::clone(self);
@@ -157,19 +157,18 @@ impl SessionInner {
let result = match invocation {
Ok(invocation) => {
let callback = AssertUnwindSafe(async {
inner
.delegate
delegate
.invoke_tool(invocation, cancellation.child_token())
.await
})
.catch_unwind();
tokio::select! {
biased;
_ = cancellation.cancelled() => return,
result = callback => match result {
Ok(result) => result,
Err(_) => Err("code-mode tool delegate panicked".to_string()),
},
biased;
_ = cancellation.cancelled() => return,
result = callback => match result {
Ok(result) => result,
Err(_) => Err("code-mode tool delegate panicked".to_string()),
},
}
}
Err(error) => Err(error),
@@ -223,8 +222,8 @@ impl SessionInner {
.lock()
.unwrap_or_else(PoisonError::into_inner)
.admit_notification(&notification)?;
let cancellation = match admission {
CallbackAdmission::Active(cancellation) => cancellation,
let (cancellation, delegate) = match admission {
CallbackAdmission::Active(cancellation, delegate) => (cancellation, delegate),
CallbackAdmission::Cancelled | CallbackAdmission::Closed => return Ok(()),
CallbackAdmission::Rejected(error) => {
warn!("code-mode notification was dropped: {error}");
@@ -237,8 +236,7 @@ impl SessionInner {
// them without waiting for arbitrary delegate work to complete.
tokio::spawn(async move {
let callback = AssertUnwindSafe(async {
inner
.delegate
delegate
.notify(
notification.call_id,
CellId::new(notification.cell_id),
+9 -18
View File
@@ -30,6 +30,7 @@ use tonic::transport::Channel;
use tracing::Instrument;
use self::operations::WaitSlot;
use self::state::ClosedCell;
use self::state::SessionState;
use self::transport::GrpcTransport;
use self::transport::SharedTransport;
@@ -96,7 +97,6 @@ impl GrpcCodeModeSessionProvider {
#[tracing::instrument(name = "code_mode.grpc.open_binding", level = "info", skip_all)]
async fn open_binding(
&self,
delegate: Arc<dyn CodeModeSessionDelegate>,
limits: CodeModeSessionCellExecutionLimits,
) -> Result<Arc<GrpcCodeModeSession>, String> {
let mut client = deadline::startup("transport connection", self.transport.client()).await?;
@@ -136,7 +136,6 @@ impl GrpcCodeModeSessionProvider {
let inner = Arc::new(SessionInner {
id: opened.session_id,
client,
delegate,
runtime: tokio::runtime::Handle::current(),
state: Mutex::new(SessionState::default()),
wait_slots: Mutex::new(HashMap::new()),
@@ -180,24 +179,16 @@ impl GrpcCodeModeSessionProvider {
}
impl CodeModeSessionProvider for GrpcCodeModeSessionProvider {
fn create_session<'a>(
&'a self,
delegate: Arc<dyn CodeModeSessionDelegate>,
) -> CodeModeSessionProviderFuture<'a> {
self.create_session_with_limits(delegate, CodeModeSessionCellExecutionLimits::default())
fn create_session(&self) -> CodeModeSessionProviderFuture<'_> {
self.create_session_with_limits(CodeModeSessionCellExecutionLimits::default())
}
fn create_session_with_limits<'a>(
&'a self,
delegate: Arc<dyn CodeModeSessionDelegate>,
limits: CodeModeSessionCellExecutionLimits,
) -> CodeModeSessionProviderFuture<'a> {
Box::pin(async move {
let session = Arc::new(reconnect::ReconnectableSession::new(
self.clone(),
delegate,
limits,
));
let session = Arc::new(reconnect::ReconnectableSession::new(self.clone(), limits));
session.initialize().await?;
Ok(session as _)
})
@@ -229,8 +220,9 @@ impl CodeModeSession for GrpcCodeModeSession {
fn execute<'a>(
&'a self,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
) -> CodeModeSessionResultFuture<'a, StartedCell> {
Box::pin(self.inner.execute(request))
Box::pin(self.inner.execute(request, delegate))
}
fn wait<'a>(&'a self, request: WaitRequest) -> CodeModeSessionResultFuture<'a, WaitOutcome> {
@@ -255,7 +247,6 @@ impl Drop for GrpcCodeModeSession {
pub(super) struct SessionInner {
pub(super) id: String,
pub(super) client: GrpcClient,
pub(super) delegate: Arc<dyn CodeModeSessionDelegate>,
runtime: tokio::runtime::Handle,
state: Mutex<SessionState>,
wait_slots: Mutex<HashMap<CellId, Weak<WaitSlot>>>,
@@ -282,14 +273,14 @@ impl SessionInner {
Ok(())
}
pub(super) fn report_closed_cell(&self, cell_id: Option<CellId>) {
if let Some(cell_id) = cell_id {
pub(super) fn report_closed_cell(&self, cell: Option<ClosedCell>) {
if let Some((cell_id, delegate)) = cell {
self.wait_slots
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&cell_id);
let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
self.delegate.cell_closed(&cell_id);
delegate.cell_closed(&cell_id);
}));
}
}
@@ -5,6 +5,7 @@ use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_code_mode_protocol::CellId;
use codex_code_mode_protocol::CodeModeSessionDelegate;
use codex_code_mode_protocol::DEFAULT_EXEC_YIELD_TIME_MS;
use codex_code_mode_protocol::ExecuteRequest;
use codex_code_mode_protocol::RuntimeResponse;
@@ -45,10 +46,11 @@ impl Drop for ExecutionOwnership {
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove_execution(&self.execution_id);
let Some(cell_id) = cell else {
let Some((cell_id, delegate)) = cell else {
return;
};
self.session.report_closed_cell(Some(cell_id.clone()));
self.session
.report_closed_cell(Some((cell_id.clone(), delegate)));
if self.session.stopped.is_cancelled() {
return;
}
@@ -67,6 +69,7 @@ impl SessionInner {
pub(super) async fn execute(
self: &Arc<Self>,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
) -> Result<StartedCell, String> {
self.require_open()?;
let execution_id = Uuid::new_v4().to_string();
@@ -81,7 +84,7 @@ impl SessionInner {
self.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.begin_execution(&request)?;
.begin_execution(&request, delegate)?;
let ownership = ExecutionOwnership {
session: Arc::clone(self),
execution_id,
@@ -31,7 +31,6 @@ pub(super) struct ReconnectableSession {
struct ReconnectInner {
provider: GrpcCodeModeSessionProvider,
delegate: Arc<dyn CodeModeSessionDelegate>,
limits: CodeModeSessionCellExecutionLimits,
binding: Mutex<Option<SessionBinding>>,
opening_permit: Semaphore,
@@ -49,13 +48,11 @@ struct SessionBinding {
impl ReconnectableSession {
pub(super) fn new(
provider: GrpcCodeModeSessionProvider,
delegate: Arc<dyn CodeModeSessionDelegate>,
limits: CodeModeSessionCellExecutionLimits,
) -> Self {
Self {
inner: Arc::new(ReconnectInner {
provider,
delegate,
limits,
binding: Mutex::new(None),
opening_permit: Semaphore::new(/*permits*/ 1),
@@ -75,10 +72,15 @@ impl CodeModeSession for ReconnectableSession {
fn execute<'a>(
&'a self,
request: ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
) -> CodeModeSessionResultFuture<'a, StartedCell> {
Box::pin(async move {
let binding = self.inner.get_or_open_binding().await?;
let started = binding.session.execute(request).await?;
let delegate = Arc::new(GenerationDelegate {
delegate,
generation: binding.generation,
});
let started = binding.session.execute(request, delegate).await?;
Ok(generation::public_started_cell(binding.generation, started))
})
}
@@ -151,16 +153,12 @@ impl ReconnectInner {
}
let generation = self.next_generation.fetch_add(1, Ordering::Relaxed);
let delegate = Arc::new(GenerationDelegate {
delegate: Arc::clone(&self.delegate),
generation,
});
let session = tokio::select! {
biased;
_ = self.shutdown_requested.cancelled() => {
return Err(SHUTDOWN_ERROR.to_string());
}
session = self.provider.open_binding(delegate, self.limits.clone()) => session?,
session = self.provider.open_binding(self.limits.clone()) => session?,
};
let binding = SessionBinding {
session,
+36 -13
View File
@@ -1,6 +1,9 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::sync::Arc;
use codex_code_mode_protocol::CodeModeSessionDelegate;
use codex_code_mode_protocol::CellId;
use codex_code_mode_protocol::grpc;
@@ -16,15 +19,17 @@ struct ActiveCallback {
cancellation: CancellationToken,
}
pub(super) type ClosedCell = (CellId, Arc<dyn CodeModeSessionDelegate>);
pub(super) enum CallbackAdmission {
Active(CancellationToken),
Active(CancellationToken, Arc<dyn CodeModeSessionDelegate>),
Cancelled,
Closed,
Rejected(String),
}
#[derive(Default)]
struct ExecutionRecord {
delegate: Arc<dyn CodeModeSessionDelegate>,
cell_id: Option<CellId>,
tool_call_id: String,
enabled_tools: HashMap<ToolName, i32>,
@@ -101,7 +106,11 @@ impl SessionState {
Ok(())
}
pub(super) fn begin_execution(&mut self, request: &grpc::ExecuteRequest) -> Result<(), String> {
pub(super) fn begin_execution(
&mut self,
request: &grpc::ExecuteRequest,
delegate: Arc<dyn CodeModeSessionDelegate>,
) -> Result<(), String> {
self.require_open()?;
if request.execution_id.is_empty() || self.executions.contains_key(&request.execution_id) {
return Err("code-mode execution ID was empty or reused".to_string());
@@ -127,7 +136,13 @@ impl SessionState {
ExecutionRecord {
tool_call_id: request.tool_call_id.clone(),
enabled_tools,
..ExecutionRecord::default()
delegate,
cell_id: None,
started: false,
ready: false,
closed: false,
notifications: 0,
cancellation: CancellationToken::new(),
},
);
Ok(())
@@ -155,7 +170,7 @@ impl SessionState {
pub(super) fn mark_execution_ready(
&mut self,
execution_id: &str,
) -> Result<Option<CellId>, String> {
) -> Result<Option<ClosedCell>, String> {
self.require_open()?;
let execution = self
.executions
@@ -224,7 +239,10 @@ impl SessionState {
cancellation: cancellation.clone(),
},
);
Ok(CallbackAdmission::Active(cancellation))
Ok(CallbackAdmission::Active(
cancellation,
Arc::clone(&execution.delegate),
))
}
pub(super) fn admit_notification(
@@ -255,10 +273,11 @@ impl SessionState {
self.notifications += 1;
Ok(CallbackAdmission::Active(
execution.cancellation.child_token(),
Arc::clone(&execution.delegate),
))
}
pub(super) fn finish_notification(&mut self, execution_id: &str) -> Option<CellId> {
pub(super) fn finish_notification(&mut self, execution_id: &str) -> Option<ClosedCell> {
let execution = self.executions.get_mut(execution_id)?;
execution.notifications = execution.notifications.checked_sub(1)?;
self.notifications -= 1;
@@ -296,7 +315,7 @@ impl SessionState {
pub(super) fn close_cell(
&mut self,
closed: grpc::CellClosed,
) -> Result<Option<CellId>, String> {
) -> Result<Option<ClosedCell>, String> {
self.require_open()?;
self.check_cell_ownership(&closed.execution_id, &closed.cell_id)?;
let Some(execution) = self.executions.get_mut(&closed.execution_id) else {
@@ -317,7 +336,7 @@ impl SessionState {
Ok(self.close_execution_if_ready(&closed.execution_id))
}
pub(super) fn close(&mut self, failure: Option<String>) -> Vec<CellId> {
pub(super) fn close(&mut self, failure: Option<String>) -> Vec<ClosedCell> {
if self.closed {
return Vec::new();
}
@@ -331,12 +350,14 @@ impl SessionState {
.drain()
.filter_map(|(_, execution)| {
execution.cancellation.cancel();
execution.cell_id
execution
.cell_id
.map(|cell_id| (cell_id, execution.delegate))
})
.collect()
}
fn close_execution_if_ready(&mut self, execution_id: &str) -> Option<CellId> {
fn close_execution_if_ready(&mut self, execution_id: &str) -> Option<ClosedCell> {
self.executions
.get(execution_id)
.is_some_and(|execution| {
@@ -349,12 +370,14 @@ impl SessionState {
.flatten()
}
pub(super) fn remove_execution(&mut self, execution_id: &str) -> Option<CellId> {
pub(super) fn remove_execution(&mut self, execution_id: &str) -> Option<ClosedCell> {
let execution = self.executions.remove(execution_id)?;
self.notifications -= execution.notifications;
execution.cancellation.cancel();
self.revoke_execution_callbacks(execution_id);
execution.cell_id
execution
.cell_id
.map(|cell_id| (cell_id, execution.delegate))
}
fn check_cell_ownership(&self, execution_id: &str, cell_id: &str) -> Result<(), String> {
@@ -1,7 +1,9 @@
use codex_code_mode_protocol::CellId;
use codex_code_mode_protocol::NoopCodeModeSessionDelegate;
use codex_code_mode_protocol::grpc;
use codex_code_mode_protocol::host::MAX_PENDING_DELEGATE_CALLS;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use uuid::Uuid;
use super::CallbackAdmission;
@@ -58,33 +60,66 @@ fn notification(execution_id: &str, notification_id: u128) -> grpc::Notification
}
}
#[test]
fn callbacks_use_their_execution_delegate_before_cell_admission() {
let mut state = SessionState::default();
let delegates: Vec<Arc<dyn codex_code_mode_protocol::CodeModeSessionDelegate>> = vec![
Arc::new(NoopCodeModeSessionDelegate),
Arc::new(NoopCodeModeSessionDelegate),
];
for (index, delegate) in delegates.iter().enumerate() {
state
.begin_execution(&request(&index.to_string()), delegate.clone())
.unwrap();
}
for (index, delegate) in delegates.iter().enumerate() {
let mut call = tool_call(&index.to_string(), index as u128 + 1);
call.cell_id = format!("cell-{index}");
let CallbackAdmission::Active(_, actual) = state.admit_invocation(&call).unwrap() else {
panic!("callback should be admitted before the execute response");
};
assert!(Arc::ptr_eq(&actual, delegate));
let mut notice = notification(&index.to_string(), index as u128 + 1);
notice.cell_id = call.cell_id;
let CallbackAdmission::Active(_, actual) = state.admit_notification(&notice).unwrap()
else {
panic!("notification should be admitted before the execute response");
};
assert!(Arc::ptr_eq(&actual, delegate));
}
drop(state.close(/*failure*/ None));
for delegate in delegates {
assert_eq!(Arc::strong_count(&delegate), 1);
}
}
#[test]
fn cell_closure_drains_notifications_and_cancels_tool_callbacks() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let first = state
.admit_invocation(&tool_call("execution", /*invocation_id*/ 1))
.expect("accept early invocation");
let CallbackAdmission::Active(first_cancellation) = first else {
let CallbackAdmission::Active(first_cancellation, _) = first else {
panic!("first callback was not admitted");
};
let CallbackAdmission::Active(notification_cancellation) = state
let CallbackAdmission::Active(notification_cancellation, _) = state
.admit_notification(&notification("execution", /*notification_id*/ 1))
.expect("admit notification")
else {
panic!("notification was not admitted");
};
assert_eq!(
assert!(
state
.close_cell(grpc::CellClosed {
execution_id: "execution".to_string(),
cell_id: "cell".to_string(),
final_tool_call_sequence: 3,
})
.expect("record cell closure"),
None
.expect("record cell closure")
.is_none()
);
assert!(first_cancellation.is_cancelled());
assert!(!notification_cancellation.is_cancelled());
@@ -97,14 +132,16 @@ fn cell_closure_drains_notifications_and_cancels_tool_callbacks() {
.expect("reject invocation for a closed cell"),
CallbackAdmission::Closed
));
assert_eq!(
assert!(
state
.mark_execution_ready("execution")
.expect("claim started cell"),
None
.expect("claim started cell")
.is_none()
);
assert_eq!(
state.finish_notification("execution"),
state
.finish_notification("execution")
.map(|(cell_id, _)| cell_id),
Some(CellId::new("cell".to_string()))
);
assert!(notification_cancellation.is_cancelled());
@@ -114,18 +151,18 @@ fn cell_closure_drains_notifications_and_cancels_tool_callbacks() {
fn cell_closure_waits_until_the_started_cell_is_claimed() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
assert_eq!(
assert!(
state
.close_cell(grpc::CellClosed {
execution_id: "execution".to_string(),
cell_id: "cell".to_string(),
final_tool_call_sequence: 0,
})
.expect("record early cell closure"),
None
.expect("record early cell closure")
.is_none()
);
state
.admit_execution("execution", "cell")
@@ -133,6 +170,7 @@ fn cell_closure_waits_until_the_started_cell_is_claimed() {
assert_eq!(
state
.mark_execution_ready("execution")
.map(|cell| cell.map(|(cell_id, _)| cell_id))
.expect("claim started cell"),
Some(CellId::new("cell".to_string()))
);
@@ -142,7 +180,7 @@ fn cell_closure_waits_until_the_started_cell_is_claimed() {
fn oversized_cell_ids_are_rejected_before_admission() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
assert_eq!(
@@ -152,17 +190,17 @@ fn oversized_cell_ids_are_rejected_before_admission() {
grpc::MAX_IDENTIFIER_BYTES
))
);
assert_eq!(state.remove_execution("execution"), None);
assert!(state.remove_execution("execution").is_none());
}
#[test]
fn callbacks_cannot_claim_another_executions_cell() {
let mut state = SessionState::default();
state
.begin_execution(&request("first"))
.begin_execution(&request("first"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register first execution");
state
.begin_execution(&request("second"))
.begin_execution(&request("second"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register second execution");
state
.admit_invocation(&tool_call("first", /*invocation_id*/ 1))
@@ -198,19 +236,19 @@ fn callbacks_cannot_claim_another_executions_cell() {
fn abandonment_before_start_ignores_later_cell_closure() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
assert_eq!(state.remove_execution("execution"), None);
assert_eq!(
assert!(state.remove_execution("execution").is_none());
assert!(
state
.close_cell(grpc::CellClosed {
execution_id: "execution".to_string(),
cell_id: "cell".to_string(),
final_tool_call_sequence: 0,
})
.expect("ignore closure for abandoned execution"),
None
.expect("ignore closure for abandoned execution")
.is_none()
);
assert!(state.close(/*failure*/ None).is_empty());
}
@@ -219,16 +257,18 @@ fn abandonment_before_start_ignores_later_cell_closure() {
fn abandonment_revokes_callbacks_and_ignores_late_events() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let CallbackAdmission::Active(invocation) = state
let CallbackAdmission::Active(invocation, _) = state
.admit_invocation(&tool_call("execution", /*invocation_id*/ 1))
.expect("admit callback before execution starts")
else {
panic!("invocation was not admitted");
};
assert_eq!(
state.remove_execution("execution"),
state
.remove_execution("execution")
.map(|(cell_id, _)| cell_id),
Some(CellId::new("cell".to_string()))
);
assert!(invocation.is_cancelled());
@@ -238,15 +278,15 @@ fn abandonment_revokes_callbacks_and_ignores_late_events() {
.expect("reject delayed tool invocation"),
CallbackAdmission::Closed
));
assert_eq!(
assert!(
state
.close_cell(grpc::CellClosed {
execution_id: "execution".to_string(),
cell_id: "cell".to_string(),
final_tool_call_sequence: 1,
})
.expect("ignore delayed cell closure"),
None
.expect("ignore delayed cell closure")
.is_none()
);
assert!(state.close(/*failure*/ None).is_empty());
}
@@ -255,7 +295,7 @@ fn abandonment_revokes_callbacks_and_ignores_late_events() {
fn invocation_cancellation_revokes_delegate_and_late_completion() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
state
.admit_execution("execution", "cell")
@@ -264,7 +304,7 @@ fn invocation_cancellation_revokes_delegate_and_late_completion() {
.mark_execution_ready("execution")
.expect("claim execution");
let invocation = tool_call("execution", /*invocation_id*/ 1);
let CallbackAdmission::Active(cancellation) = state
let CallbackAdmission::Active(cancellation, _) = state
.admit_invocation(&invocation)
.expect("accept invocation")
else {
@@ -284,6 +324,7 @@ fn invocation_cancellation_revokes_delegate_and_late_completion() {
cell_id: "cell".to_string(),
final_tool_call_sequence: 1,
})
.map(|cell| cell.map(|(cell_id, _)| cell_id))
.expect("close cell"),
Some(CellId::new("cell".to_string()))
);
@@ -293,7 +334,7 @@ fn invocation_cancellation_revokes_delegate_and_late_completion() {
fn duplicate_invocation_ids_are_rejected() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
state
.admit_execution("execution", "cell")
@@ -311,7 +352,7 @@ fn duplicate_invocation_ids_are_rejected() {
fn tool_callbacks_must_match_the_executions_enabled_tools() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let mut disabled = tool_call("execution", /*invocation_id*/ 1);
@@ -349,7 +390,7 @@ fn tool_callbacks_must_match_the_executions_enabled_tools() {
});
assert!(matches!(
state.admit_invocation(&explicit_default_namespace),
Ok(CallbackAdmission::Active(_))
Ok(CallbackAdmission::Active(_, _))
));
assert_eq!(state.require_open(), Ok(()));
}
@@ -361,20 +402,20 @@ fn execution_call_ids_must_be_bounded() {
oversized.tool_call_id = "x".repeat(grpc::MAX_IDENTIFIER_BYTES + 1);
assert_eq!(
state.begin_execution(&oversized),
state.begin_execution(&oversized, Arc::new(NoopCodeModeSessionDelegate)),
Err(format!(
"gRPC code-mode host returned tool call ID exceeding {} bytes",
grpc::MAX_IDENTIFIER_BYTES
))
);
assert_eq!(state.remove_execution("execution"), None);
assert!(state.remove_execution("execution").is_none());
}
#[test]
fn notification_call_ids_must_match_their_execution() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let mut oversized = notification("execution", /*notification_id*/ 1);
@@ -395,7 +436,7 @@ fn notification_call_ids_must_match_their_execution() {
);
assert!(matches!(
state.admit_notification(&notification("execution", /*notification_id*/ 3)),
Ok(CallbackAdmission::Active(_))
Ok(CallbackAdmission::Active(_, _))
));
}
@@ -403,7 +444,7 @@ fn notification_call_ids_must_match_their_execution() {
fn malformed_callback_ids_are_rejected_before_retention() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let mut invalid_invocation = tool_call("execution", /*invocation_id*/ 1);
invalid_invocation.invocation_id = "not-a-uuid".to_string();
@@ -442,13 +483,13 @@ fn malformed_callback_ids_are_rejected_before_retention() {
fn notifications_and_tools_share_the_pending_delegate_limit() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
for index in 0..MAX_PENDING_DELEGATE_CALLS {
assert!(matches!(
state.admit_notification(&notification("execution", index as u128 + 1)),
Ok(CallbackAdmission::Active(_))
Ok(CallbackAdmission::Active(_, _))
));
}
@@ -463,10 +504,10 @@ fn notifications_and_tools_share_the_pending_delegate_limit() {
if error == "code-mode host exceeded its pending delegate callback limit"
));
assert_eq!(state.require_open(), Ok(()));
assert_eq!(state.finish_notification("execution"), None);
assert!(state.finish_notification("execution").is_none());
assert!(matches!(
state.admit_invocation(&tool_call("execution", /*invocation_id*/ 2)),
Ok(CallbackAdmission::Active(_))
Ok(CallbackAdmission::Active(_, _))
));
}
@@ -474,9 +515,9 @@ fn notifications_and_tools_share_the_pending_delegate_limit() {
fn terminated_cells_cancel_pending_notifications() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
let CallbackAdmission::Active(cancellation) = state
let CallbackAdmission::Active(cancellation, _) = state
.admit_notification(&notification("execution", /*notification_id*/ 1))
.expect("admit notification")
else {
@@ -486,25 +527,25 @@ fn terminated_cells_cancel_pending_notifications() {
state.cancel_notifications(&CellId::new("cell".to_string()));
assert!(cancellation.is_cancelled());
assert_eq!(state.finish_notification("execution"), None);
assert!(state.finish_notification("execution").is_none());
}
#[test]
fn disconnect_revokes_callbacks_and_returns_each_live_cell_once() {
let mut state = SessionState::default();
state
.begin_execution(&request("execution"))
.begin_execution(&request("execution"), Arc::new(NoopCodeModeSessionDelegate))
.expect("register execution");
state
.admit_execution("execution", "cell")
.expect("admit execution");
let CallbackAdmission::Active(cancellation) = state
let CallbackAdmission::Active(cancellation, _) = state
.admit_invocation(&tool_call("execution", /*invocation_id*/ 1))
.expect("accept invocation")
else {
panic!("invocation was not admitted");
};
let CallbackAdmission::Active(notification_cancellation) = state
let CallbackAdmission::Active(notification_cancellation, _) = state
.admit_notification(&notification("execution", /*notification_id*/ 1))
.expect("admit notification")
else {
@@ -512,7 +553,11 @@ fn disconnect_revokes_callbacks_and_returns_each_live_cell_once() {
};
assert_eq!(
state.close(Some("lease closed".to_string())),
state
.close(Some("lease closed".to_string()))
.into_iter()
.map(|(cell_id, _)| cell_id)
.collect::<Vec<_>>(),
vec![CellId::new("cell".to_string())]
);
assert!(cancellation.is_cancelled());