mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Preserve remote session identity across recovery
This commit is contained in:
@@ -339,7 +339,7 @@ async fn writer_failure_terminates_the_connection() {
|
||||
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: 1,
|
||||
id: request_id(1),
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: session_id("session-1"),
|
||||
},
|
||||
|
||||
@@ -255,6 +255,7 @@ impl HostState {
|
||||
}
|
||||
HostRequest::Execute {
|
||||
session_id,
|
||||
cell_id,
|
||||
request,
|
||||
} => {
|
||||
let request = match request.try_into() {
|
||||
@@ -268,7 +269,7 @@ impl HostState {
|
||||
}
|
||||
};
|
||||
let result = match self.session(&session_id) {
|
||||
Ok(session) => session.execute(request).await,
|
||||
Ok(session) => session.execute_with_cell_id(cell_id.into(), request).await,
|
||||
Err(err) => {
|
||||
self.respond(request_id, Err(err));
|
||||
return;
|
||||
|
||||
@@ -423,6 +423,7 @@ async fn explicit_yield_frame_precedes_notification_and_terminal_output_drops_ti
|
||||
id: request_id(/*value*/ 2),
|
||||
request: HostRequest::Execute {
|
||||
session_id: session_id.clone(),
|
||||
cell_id: cell_id("client-cell").into(),
|
||||
request: execute_request(
|
||||
r#"
|
||||
text("hello");
|
||||
@@ -447,7 +448,7 @@ setTimeout(() => { text("should never emit"); }, 60000);
|
||||
id: request_id(/*value*/ 2),
|
||||
result: WireResult::Ok {
|
||||
value: HostResponse::ExecutionStarted {
|
||||
cell_id: cell_id("1").into(),
|
||||
cell_id: cell_id("client-cell").into(),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -461,7 +462,7 @@ setTimeout(() => { text("should never emit"); }, 60000);
|
||||
id: request_id(/*value*/ 2),
|
||||
result: WireResult::Ok {
|
||||
value: RuntimeResponse::Yielded {
|
||||
cell_id: cell_id("1"),
|
||||
cell_id: cell_id("client-cell"),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "hello".to_string(),
|
||||
}],
|
||||
@@ -488,7 +489,7 @@ setTimeout(() => { text("should never emit"); }, 60000);
|
||||
}) => {
|
||||
assert_eq!(callback_session_id, session_id);
|
||||
assert_eq!(call_id, "call-1");
|
||||
assert_eq!(callback_cell_id, cell_id("1").into());
|
||||
assert_eq!(callback_cell_id, cell_id("client-cell").into());
|
||||
assert_eq!(text, "this is important");
|
||||
id
|
||||
}
|
||||
@@ -509,7 +510,7 @@ setTimeout(() => { text("should never emit"); }, 60000);
|
||||
request: HostRequest::Wait {
|
||||
session_id: session_id.clone(),
|
||||
request: WaitRequest {
|
||||
cell_id: cell_id("1"),
|
||||
cell_id: cell_id("client-cell"),
|
||||
yield_time_ms: 60_000,
|
||||
}
|
||||
.into(),
|
||||
@@ -532,7 +533,7 @@ setTimeout(() => { text("should never emit"); }, 60000);
|
||||
cell_id: closed_cell_id,
|
||||
}) => {
|
||||
assert_eq!(closed_session_id, session_id);
|
||||
assert_eq!(closed_cell_id, cell_id("1").into());
|
||||
assert_eq!(closed_cell_id, cell_id("client-cell").into());
|
||||
}
|
||||
message => panic!("unexpected terminal frame: {message:?}"),
|
||||
}
|
||||
@@ -542,7 +543,7 @@ setTimeout(() => { text("should never emit"); }, 60000);
|
||||
WireResult::Ok {
|
||||
value: HostResponse::WaitCompleted {
|
||||
outcome: WaitOutcome::LiveCell(RuntimeResponse::Result {
|
||||
cell_id: cell_id("1"),
|
||||
cell_id: cell_id("client-cell"),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "world".to_string(),
|
||||
}],
|
||||
@@ -591,6 +592,79 @@ setTimeout(() => { text("should never emit"); }, 60000);
|
||||
assert!(status.success(), "host exited with {status}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn concurrent_sessions_from_one_provider_share_one_host_process() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let host_binary =
|
||||
codex_utils_cargo_bin::cargo_bin("codex-code-mode-host").expect("host binary");
|
||||
let temp_dir = tempfile::tempdir().expect("temp dir");
|
||||
let pid_log = temp_dir.path().join("host-pids");
|
||||
let wrapper = temp_dir.path().join("code-mode-host-wrapper");
|
||||
let script = format!(
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$$\" >> {}\nexec {}\n",
|
||||
shell_quote(&pid_log),
|
||||
shell_quote(&host_binary),
|
||||
);
|
||||
std::fs::write(&wrapper, script).expect("write host wrapper");
|
||||
let mut permissions = std::fs::metadata(&wrapper)
|
||||
.expect("host wrapper metadata")
|
||||
.permissions();
|
||||
permissions.set_mode(/*mode*/ 0o755);
|
||||
std::fs::set_permissions(&wrapper, permissions).expect("make host wrapper executable");
|
||||
|
||||
let provider = ProcessOwnedCodeModeSessionProvider::with_host_program(wrapper);
|
||||
let (first, second, third) = tokio::join!(
|
||||
provider.create_session(Arc::new(RecordingDelegate::default())),
|
||||
provider.create_session(Arc::new(RecordingDelegate::default())),
|
||||
provider.create_session(Arc::new(RecordingDelegate::default())),
|
||||
);
|
||||
let first = first.expect("create first session");
|
||||
let second = second.expect("create second session");
|
||||
let third = third.expect("create third session");
|
||||
|
||||
let (first_response, second_response, third_response) = tokio::join!(
|
||||
execute(&first, execute_request(r#"text("first");"#)),
|
||||
execute(&second, execute_request(r#"text("second");"#)),
|
||||
execute(&third, execute_request(r#"text("third");"#)),
|
||||
);
|
||||
assert_eq!(
|
||||
(first_response, second_response, third_response),
|
||||
(
|
||||
RuntimeResponse::Result {
|
||||
cell_id: cell_id("1"),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "first".to_string(),
|
||||
}],
|
||||
error_text: None,
|
||||
},
|
||||
RuntimeResponse::Result {
|
||||
cell_id: cell_id("1"),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "second".to_string(),
|
||||
}],
|
||||
error_text: None,
|
||||
},
|
||||
RuntimeResponse::Result {
|
||||
cell_id: cell_id("1"),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "third".to_string(),
|
||||
}],
|
||||
error_text: None,
|
||||
},
|
||||
)
|
||||
);
|
||||
assert_eq!(recorded_pids(&pid_log).len(), 1);
|
||||
|
||||
let (first_shutdown, second_shutdown, third_shutdown) =
|
||||
tokio::join!(first.shutdown(), second.shutdown(), third.shutdown(),);
|
||||
assert_eq!(
|
||||
(first_shutdown, second_shutdown, third_shutdown),
|
||||
(Ok(()), Ok(()), Ok(()))
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn closed_host_stdout_terminates_the_spawned_process() {
|
||||
@@ -667,7 +741,7 @@ async fn closed_host_stdout_terminates_the_spawned_process() {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn crashed_host_fails_in_flight_exec_and_next_exec_respawns() {
|
||||
async fn crashed_host_recovery_does_not_reuse_cell_ids() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let host_binary =
|
||||
@@ -709,15 +783,40 @@ async fn crashed_host_fails_in_flight_exec_and_next_exec_respawns() {
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
|
||||
let mut recovered_request = execute_request("await new Promise(() => {});");
|
||||
recovered_request.yield_time_ms = Some(1);
|
||||
let recovered = session
|
||||
.execute(recovered_request)
|
||||
.await
|
||||
.expect("start recovered execution");
|
||||
assert_eq!(recovered.cell_id, cell_id("2"));
|
||||
assert_eq!(
|
||||
execute(&session, execute_request(r#"text("recovered");"#)).await,
|
||||
RuntimeResponse::Result {
|
||||
recovered.initial_response().await,
|
||||
Ok(RuntimeResponse::Yielded {
|
||||
cell_id: cell_id("2"),
|
||||
content_items: Vec::new(),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.terminate(cell_id("1"))
|
||||
.await
|
||||
.expect("terminate stale cell"),
|
||||
WaitOutcome::MissingCell(RuntimeResponse::Result {
|
||||
cell_id: cell_id("1"),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "recovered".to_string(),
|
||||
}],
|
||||
error_text: None,
|
||||
}
|
||||
content_items: Vec::new(),
|
||||
error_text: Some("exec cell 1 not found".to_string()),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.terminate(cell_id("2"))
|
||||
.await
|
||||
.expect("terminate recovered cell"),
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Terminated {
|
||||
cell_id: cell_id("2"),
|
||||
content_items: Vec::new(),
|
||||
})
|
||||
);
|
||||
let pids = recorded_pids(&pid_log);
|
||||
assert_eq!(pids.len(), 2);
|
||||
|
||||
@@ -246,11 +246,13 @@ fn client_to_host_v1_variants_are_pinned() {
|
||||
request_id(/*value*/ 2),
|
||||
HostRequest::Execute {
|
||||
session_id: session_id(),
|
||||
cell_id: cell_id("cell-1"),
|
||||
request: execute_request,
|
||||
},
|
||||
json!({
|
||||
"method": "session/execute",
|
||||
"sessionId": "session-1",
|
||||
"cellId": "cell-1",
|
||||
"request": {
|
||||
"tool_call_id": "call-1",
|
||||
"enabled_tools": [
|
||||
|
||||
@@ -180,6 +180,7 @@ pub enum HostRequest {
|
||||
#[serde(rename = "session/execute")]
|
||||
Execute {
|
||||
session_id: SessionId,
|
||||
cell_id: WireCellId,
|
||||
request: WireExecuteRequest,
|
||||
},
|
||||
#[serde(rename = "session/wait")]
|
||||
|
||||
@@ -25,6 +25,9 @@ mod connection;
|
||||
const CODE_MODE_HOST_PATH_ENV: &str = "CODEX_CODE_MODE_HOST_PATH";
|
||||
|
||||
/// Creates code-mode sessions backed by one lazily spawned process host.
|
||||
///
|
||||
/// All sessions created by one provider share that host. Callers that want one
|
||||
/// sidecar across multiple Codex threads must share the provider instance.
|
||||
pub struct ProcessOwnedCodeModeSessionProvider {
|
||||
host_program: PathBuf,
|
||||
process_host: StdMutex<Option<Arc<OwnedProcessHost>>>,
|
||||
@@ -139,6 +142,7 @@ enum SessionState {
|
||||
pub struct ProcessOwnedCodeModeSession {
|
||||
process_host: Arc<OwnedProcessHost>,
|
||||
session_id: SessionId,
|
||||
next_cell_id: AtomicU64,
|
||||
delegate: Arc<dyn CodeModeSessionDelegate>,
|
||||
state: StdMutex<SessionState>,
|
||||
transition_permit: Semaphore,
|
||||
@@ -146,12 +150,8 @@ pub struct ProcessOwnedCodeModeSession {
|
||||
|
||||
impl ProcessOwnedCodeModeSession {
|
||||
pub fn new() -> Self {
|
||||
Self::with_delegate(Arc::new(NoopCodeModeSessionDelegate))
|
||||
}
|
||||
|
||||
pub fn with_delegate(delegate: Arc<dyn CodeModeSessionDelegate>) -> Self {
|
||||
Self::with_process_host(
|
||||
delegate,
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
Arc::new(OwnedProcessHost::new(default_host_program())),
|
||||
)
|
||||
}
|
||||
@@ -164,6 +164,7 @@ impl ProcessOwnedCodeModeSession {
|
||||
Self {
|
||||
process_host,
|
||||
session_id,
|
||||
next_cell_id: AtomicU64::new(1),
|
||||
delegate,
|
||||
state: StdMutex::new(SessionState::New),
|
||||
transition_permit: Semaphore::new(/*permits*/ 1),
|
||||
@@ -214,12 +215,21 @@ impl ProcessOwnedCodeModeSession {
|
||||
}
|
||||
|
||||
pub async fn execute(&self, request: ExecuteRequest) -> Result<StartedCell, String> {
|
||||
let cell_id = self.allocate_cell_id();
|
||||
self.connection()
|
||||
.await?
|
||||
.execute(self.session_id.clone(), request)
|
||||
.execute(self.session_id.clone(), cell_id, request)
|
||||
.await
|
||||
}
|
||||
|
||||
fn allocate_cell_id(&self) -> CellId {
|
||||
CellId::new(
|
||||
self.next_cell_id
|
||||
.fetch_add(1, Ordering::Relaxed)
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn wait(&self, request: WaitRequest) -> Result<WaitOutcome, String> {
|
||||
self.connection()
|
||||
.await?
|
||||
|
||||
@@ -203,6 +203,7 @@ impl Connection {
|
||||
pub(super) async fn execute(
|
||||
&self,
|
||||
session_id: SessionId,
|
||||
cell_id: CellId,
|
||||
request: ExecuteRequest,
|
||||
) -> Result<StartedCell, String> {
|
||||
let request = request
|
||||
@@ -223,6 +224,7 @@ impl Connection {
|
||||
id,
|
||||
request: HostRequest::Execute {
|
||||
session_id,
|
||||
cell_id: (&cell_id).into(),
|
||||
request,
|
||||
},
|
||||
})
|
||||
@@ -244,10 +246,11 @@ impl Connection {
|
||||
}
|
||||
};
|
||||
match response {
|
||||
HostResponse::ExecutionStarted { cell_id } => Ok(StartedCell::from_result_receiver(
|
||||
cell_id.into(),
|
||||
initial_rx,
|
||||
)),
|
||||
HostResponse::ExecutionStarted {
|
||||
cell_id: started_cell_id,
|
||||
} if started_cell_id.as_str() == cell_id.as_str() => {
|
||||
Ok(StartedCell::from_result_receiver(cell_id, initial_rx))
|
||||
}
|
||||
_ => {
|
||||
self.state.initial_responses.lock().await.remove(&id);
|
||||
Err("code-mode host returned an invalid execute response".to_string())
|
||||
|
||||
@@ -97,18 +97,26 @@ impl InProcessCodeModeSession {
|
||||
)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
let cell_id = protocol_cell_id(&started.cell_id);
|
||||
let response_cell_id = cell_id.clone();
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
tokio::spawn(async move {
|
||||
let response = started
|
||||
.initial_event()
|
||||
.await
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|event| runtime_response(&response_cell_id, event));
|
||||
let _ = response_tx.send(response);
|
||||
});
|
||||
Ok(StartedCell::from_result_receiver(cell_id, response_rx))
|
||||
Ok(protocol_started_cell(started))
|
||||
}
|
||||
|
||||
/// Executes a cell using an ID assigned by a remote-session client.
|
||||
pub async fn execute_with_cell_id(
|
||||
&self,
|
||||
cell_id: CellId,
|
||||
request: ExecuteRequest,
|
||||
) -> Result<StartedCell, String> {
|
||||
let yield_time_ms = request.yield_time_ms.unwrap_or(DEFAULT_EXEC_YIELD_TIME_MS);
|
||||
let started = self
|
||||
.runtime
|
||||
.execute_with_cell_id(
|
||||
runtime_cell_id(&cell_id),
|
||||
runtime_request(request),
|
||||
runtime::ObserveMode::YieldAfter(Duration::from_millis(yield_time_ms)),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(protocol_started_cell(started))
|
||||
}
|
||||
|
||||
pub async fn execute_to_pending(
|
||||
@@ -319,6 +327,21 @@ fn protocol_cell_id(cell_id: &runtime::CellId) -> CellId {
|
||||
CellId::new(cell_id.as_str().to_string())
|
||||
}
|
||||
|
||||
fn protocol_started_cell(started: runtime::StartedCell) -> StartedCell {
|
||||
let cell_id = protocol_cell_id(&started.cell_id);
|
||||
let response_cell_id = cell_id.clone();
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
tokio::spawn(async move {
|
||||
let response = started
|
||||
.initial_event()
|
||||
.await
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|event| runtime_response(&response_cell_id, event));
|
||||
let _ = response_tx.send(response);
|
||||
});
|
||||
StartedCell::from_result_receiver(cell_id, response_rx)
|
||||
}
|
||||
|
||||
fn pending_outcome(
|
||||
cell_id: &CellId,
|
||||
event: runtime::CellEvent,
|
||||
|
||||
@@ -67,11 +67,20 @@ impl<D: SessionRuntimeDelegate> SessionRuntime<D> {
|
||||
&self,
|
||||
request: CreateCellRequest,
|
||||
initial_observe_mode: ObserveMode,
|
||||
) -> Result<StartedCell, Error> {
|
||||
self.execute_with_cell_id(self.allocate_cell_id(), request, initial_observe_mode)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_with_cell_id(
|
||||
&self,
|
||||
cell_id: CellId,
|
||||
request: CreateCellRequest,
|
||||
initial_observe_mode: ObserveMode,
|
||||
) -> Result<StartedCell, Error> {
|
||||
if self.inner.shutdown_token.is_cancelled() {
|
||||
return Err(Error::ShuttingDown);
|
||||
}
|
||||
let cell_id = self.allocate_cell_id();
|
||||
let initial_event = self
|
||||
.start_cell(cell_id.clone(), request, initial_observe_mode)
|
||||
.await?;
|
||||
|
||||
Reference in New Issue
Block a user