Base: codex-main originale (prima del fork aKode)
This commit is contained in:
213
codex-rs/code-mode-host/tests/capacity.rs
Normal file
213
codex-rs/code-mode-host/tests/capacity.rs
Normal file
@@ -0,0 +1,213 @@
|
||||
//! Shared-host capacity, callback completion, and unrelated-session progress.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_code_mode::CellId;
|
||||
use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeSessionProvider;
|
||||
use codex_code_mode::CodeModeToolKind;
|
||||
use codex_code_mode::ExecuteRequest;
|
||||
use codex_code_mode::FunctionCallOutputContentItem;
|
||||
use codex_code_mode::GrpcCodeModeSessionProvider;
|
||||
use codex_code_mode::NotificationFuture;
|
||||
use codex_code_mode::ProcessOwnedCodeModeSessionProvider;
|
||||
use codex_code_mode::RuntimeResponse;
|
||||
use codex_code_mode::ToolDefinition;
|
||||
use codex_code_mode::ToolInvocationFuture;
|
||||
use codex_code_mode::WaitOutcome;
|
||||
use codex_code_mode::WaitRequest;
|
||||
use codex_protocol::ToolName;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[path = "support/host.rs"]
|
||||
mod host;
|
||||
|
||||
struct BlockingDelegate {
|
||||
started: Semaphore,
|
||||
release: Semaphore,
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for BlockingDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
_invocation: CodeModeNestedToolCall,
|
||||
cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
self.started.add_permits(1);
|
||||
tokio::select! {
|
||||
permit = self.release.acquire() => {
|
||||
permit.map_err(|error| error.to_string())?.forget();
|
||||
Ok(json!("done"))
|
||||
}
|
||||
_ = cancellation.cancelled() => Err("cancelled".to_string()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
_call_id: String,
|
||||
_cell_id: CellId,
|
||||
_text: String,
|
||||
_cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
fn cell_closed(&self, _cell_id: &CellId) {}
|
||||
}
|
||||
|
||||
#[allow(clippy::expect_used)]
|
||||
async fn assert_shared_capacity(
|
||||
provider: &dyn CodeModeSessionProvider,
|
||||
cells: usize,
|
||||
calls_per_cell: usize,
|
||||
) {
|
||||
let delegate = Arc::new(BlockingDelegate {
|
||||
started: Semaphore::new(/*permits*/ 0),
|
||||
release: Semaphore::new(/*permits*/ 0),
|
||||
});
|
||||
let mut sessions = Vec::new();
|
||||
for _ in 0..2 {
|
||||
sessions.push(
|
||||
provider
|
||||
.create_session()
|
||||
.await
|
||||
.expect("create shared session"),
|
||||
);
|
||||
}
|
||||
let mut pending = Vec::new();
|
||||
for index in 0..cells {
|
||||
let session = &sessions[index % sessions.len()];
|
||||
let request = ExecuteRequest {
|
||||
tool_call_id: format!("capacity-{index}"),
|
||||
enabled_tools: vec![ToolDefinition {
|
||||
name: "block".to_string(),
|
||||
tool_name: ToolName::plain("block"),
|
||||
description: String::new(),
|
||||
kind: CodeModeToolKind::Function,
|
||||
input_schema: None,
|
||||
input_schema_max_bytes: None,
|
||||
output_schema: None,
|
||||
}],
|
||||
source: format!(
|
||||
"const results = await Promise.all(Array.from({{length: {calls_per_cell}}}, () => tools.block({{}}))); text(results.length);"
|
||||
),
|
||||
yield_time_ms: Some(1),
|
||||
max_output_tokens: None,
|
||||
};
|
||||
let started = session
|
||||
.execute(request, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("admit cell {index}: {error}"));
|
||||
let cell_id = started.cell_id.clone();
|
||||
let response = started.initial_response().await.expect("initial response");
|
||||
assert!(
|
||||
matches!(response, RuntimeResponse::Yielded { .. }),
|
||||
"{response:?}"
|
||||
);
|
||||
pending.push((Arc::clone(session), cell_id));
|
||||
}
|
||||
let callbacks = cells * calls_per_cell;
|
||||
delegate
|
||||
.started
|
||||
.acquire_many(callbacks as u32)
|
||||
.await
|
||||
.expect("all callbacks started")
|
||||
.forget();
|
||||
|
||||
let probe = sessions[0]
|
||||
.execute(
|
||||
ExecuteRequest {
|
||||
tool_call_id: "unrelated-probe".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: "text('ready');".to_string(),
|
||||
yield_time_ms: Some(60_000),
|
||||
max_output_tokens: None,
|
||||
},
|
||||
delegate.clone(),
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("unrelated work admitted")
|
||||
.initial_response()
|
||||
.await
|
||||
.expect("unrelated work completed");
|
||||
assert!(
|
||||
matches!(
|
||||
probe,
|
||||
RuntimeResponse::Result {
|
||||
error_text: None,
|
||||
..
|
||||
}
|
||||
),
|
||||
"{probe:?}"
|
||||
);
|
||||
|
||||
delegate.release.add_permits(callbacks);
|
||||
for (session, cell_id) in pending {
|
||||
let result = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id,
|
||||
yield_time_ms: 60_000,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("collect callback results");
|
||||
let WaitOutcome::LiveCell(RuntimeResponse::Result {
|
||||
content_items,
|
||||
error_text,
|
||||
..
|
||||
}) = result
|
||||
else {
|
||||
panic!("expected completed cell: {result:?}");
|
||||
};
|
||||
assert_eq!(
|
||||
(content_items, error_text),
|
||||
(
|
||||
vec![FunctionCallOutputContentItem::InputText {
|
||||
text: calls_per_cell.to_string()
|
||||
}],
|
||||
None
|
||||
)
|
||||
);
|
||||
}
|
||||
for session in sessions {
|
||||
session.shutdown().await.expect("close shared session");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stdio_shared_sessions_complete_thousands_of_callbacks() {
|
||||
let provider = ProcessOwnedCodeModeSessionProvider::with_host_program(
|
||||
codex_utils_cargo_bin::cargo_bin("codex-code-mode-host").expect("host binary"),
|
||||
);
|
||||
assert_shared_capacity(&provider, /*cells*/ 256, /*calls_per_cell*/ 16).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grpc_shared_sessions_complete_thousands_of_callbacks() {
|
||||
let host = host::HostHarness::start("grpc://127.0.0.1:0")
|
||||
.await
|
||||
.expect("host");
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
assert_shared_capacity(&provider, /*cells*/ 256, /*calls_per_cell*/ 16).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires resources for 2,048 live V8 isolates and OS threads"]
|
||||
async fn grpc_full_host_capacity() {
|
||||
let host = host::HostHarness::start("grpc://127.0.0.1:0")
|
||||
.await
|
||||
.expect("host");
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
assert_shared_capacity(&provider, /*cells*/ 2_047, /*calls_per_cell*/ 2).await;
|
||||
}
|
||||
1527
codex-rs/code-mode-host/tests/grpc.rs
Normal file
1527
codex-rs/code-mode-host/tests/grpc.rs
Normal file
File diff suppressed because it is too large
Load Diff
320
codex-rs/code-mode-host/tests/grpc/admission_tests.rs
Normal file
320
codex-rs/code-mode-host/tests/grpc/admission_tests.rs
Normal file
@@ -0,0 +1,320 @@
|
||||
//! Initial admission may retry transient failures; established work must not replay.
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_admission_retries_only_transient_failures_and_is_bounded() -> Result<()> {
|
||||
for (code, failures, expected_attempts, succeeds) in [
|
||||
(Code::Unavailable, 1, 2, true),
|
||||
(Code::ResourceExhausted, 1, 2, true),
|
||||
(Code::Unavailable, usize::MAX, 5, false),
|
||||
(Code::InvalidArgument, 1, 1, false),
|
||||
(Code::Unknown, 1, 1, false),
|
||||
] {
|
||||
let attempts = Arc::new(AtomicUsize::new(0));
|
||||
let count = Arc::clone(&attempts);
|
||||
let app = axum::Router::new()
|
||||
.fallback_service(grpc::code_mode_host_server::CodeModeHostServer::new(
|
||||
codex_code_mode_host::GrpcCodeModeHost::new(),
|
||||
))
|
||||
.layer(axum::middleware::from_fn(
|
||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||
let count = Arc::clone(&count);
|
||||
async move {
|
||||
if request.uri().path().ends_with("/OpenSession")
|
||||
&& count.fetch_add(1, Ordering::SeqCst) < failures
|
||||
{
|
||||
return tonic::Status::new(code, "transient admission test")
|
||||
.into_http::<axum::body::Body>();
|
||||
}
|
||||
next.run(request).await
|
||||
}
|
||||
},
|
||||
));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.expect("admission test server");
|
||||
}));
|
||||
let provider = GrpcCodeModeSessionProvider::new(format!("http://{address}"));
|
||||
let result = timeout(TEST_TIMEOUT, provider.create_session()).await?;
|
||||
assert_eq!(
|
||||
result.is_ok(),
|
||||
succeeds,
|
||||
"status {code}: {}",
|
||||
result.as_ref().err().cloned().unwrap_or_default()
|
||||
);
|
||||
assert_eq!(attempts.load(Ordering::SeqCst), expected_attempts);
|
||||
if let Ok(session) = result {
|
||||
let response = execute(
|
||||
&session,
|
||||
request("text(42);"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
response,
|
||||
text_response("1", "42", response.code_mode_host_duration())
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
}
|
||||
drop(server);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_admission_recovers_after_connection_reset() -> Result<()> {
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
// Drop the first connection with unread HTTP/2 bytes to send TCP RST.
|
||||
// Serve the next connection normally; no timer or launcher mock is needed.
|
||||
let (mut stream, _) = listener.accept().await?;
|
||||
stream.read_exact(&mut [0]).await?;
|
||||
drop(stream);
|
||||
let app = axum::Router::new().fallback_service(
|
||||
grpc::code_mode_host_server::CodeModeHostServer::new(
|
||||
codex_code_mode_host::GrpcCodeModeHost::new(),
|
||||
),
|
||||
);
|
||||
axum::serve(listener, app).await
|
||||
}));
|
||||
let provider = GrpcCodeModeSessionProvider::new(format!("http://{address}"));
|
||||
let session = timeout(TEST_TIMEOUT, provider.create_session())
|
||||
.await?
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let response = execute(
|
||||
&session,
|
||||
request("text(42);"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
response,
|
||||
text_response("1", "42", response.code_mode_host_duration())
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
drop(server);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn routing_metadata_is_scoped_to_each_session_on_a_shared_provider() -> Result<()> {
|
||||
use axum::body::Body;
|
||||
use axum::extract::Request;
|
||||
use axum::response::Response;
|
||||
use tonic::codegen::Service;
|
||||
|
||||
let backends = Arc::new(["a", "b"].map(|_| {
|
||||
axum::Router::new().fallback_service(grpc::code_mode_host_server::CodeModeHostServer::new(
|
||||
codex_code_mode_host::GrpcCodeModeHost::new(),
|
||||
))
|
||||
}));
|
||||
let admissions = Arc::new(AtomicUsize::new(0));
|
||||
let rejection = Arc::new(std::sync::Mutex::new(/*t*/ None::<tonic::Status>));
|
||||
let rejected_executions = Arc::new(AtomicUsize::new(0));
|
||||
let next_rejection = Arc::clone(&rejection);
|
||||
let executions = Arc::clone(&rejected_executions);
|
||||
let opens = Arc::clone(&admissions);
|
||||
let app = axum::Router::new().fallback(move |request: Request| {
|
||||
let backends = Arc::clone(&backends);
|
||||
let admissions = Arc::clone(&admissions);
|
||||
let rejection = Arc::clone(&next_rejection);
|
||||
let executions = Arc::clone(&executions);
|
||||
async move {
|
||||
let opening = request.uri().path().ends_with("/OpenSession");
|
||||
let route = request.headers().get("x-code-mode-route");
|
||||
let token = if opening {
|
||||
assert_eq!(
|
||||
route, None,
|
||||
"a new admission must not inherit any session's route"
|
||||
);
|
||||
match admissions.fetch_add(1, Ordering::SeqCst) {
|
||||
0 => {
|
||||
// Even a rejected admission can carry response metadata. The
|
||||
// next attempt must still be free to select another backend.
|
||||
let mut response =
|
||||
tonic::Status::resource_exhausted("full").into_http::<Body>();
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("x-code-mode-route", "rejected".parse().unwrap());
|
||||
return response;
|
||||
}
|
||||
1 => "a",
|
||||
_ => "b",
|
||||
}
|
||||
} else {
|
||||
route
|
||||
.expect("every session RPC needs its routing token")
|
||||
.to_str()
|
||||
.unwrap()
|
||||
};
|
||||
let index = match token {
|
||||
"a" => 0,
|
||||
"b" => 1,
|
||||
_ => panic!("unexpected routing token"),
|
||||
};
|
||||
if token == "a"
|
||||
&& request.uri().path().ends_with("/Execute")
|
||||
&& let Some(error) = rejection.lock().unwrap().as_ref()
|
||||
{
|
||||
executions.fetch_add(1, Ordering::SeqCst);
|
||||
return error.clone().into_http::<Body>();
|
||||
}
|
||||
let mut response: Response = backends[index].clone().call(request).await.unwrap();
|
||||
if opening {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("x-code-mode-route", ["a", "b"][index].parse().unwrap());
|
||||
}
|
||||
response
|
||||
}
|
||||
});
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let _server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.expect("routing test server");
|
||||
}));
|
||||
let provider = GrpcCodeModeSessionProvider::new(format!("http://{address}"));
|
||||
let parent = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let child = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
for (session, value) in [(&parent, 11), (&child, 22), (&parent, 33)] {
|
||||
let mut req = request(&format!(
|
||||
"await tools.echo({{value: {value}}}); text({value});"
|
||||
));
|
||||
req.enabled_tools = vec![tool("echo")];
|
||||
let actual = execute(session, req, Arc::new(RecordingDelegate::default())).await?;
|
||||
let RuntimeResponse::Result { error_text, .. } = actual else {
|
||||
anyhow::bail!("session did not finish");
|
||||
};
|
||||
assert_eq!(error_text, None);
|
||||
let mut req = request("await new Promise(() => {});");
|
||||
req.yield_time_ms = Some(1);
|
||||
let started = session
|
||||
.execute(
|
||||
req,
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let id = started.cell_id.clone();
|
||||
assert!(matches!(
|
||||
started
|
||||
.initial_response()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?,
|
||||
RuntimeResponse::Yielded { .. }
|
||||
));
|
||||
let outcome = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: id.clone(),
|
||||
yield_time_ms: 1,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert!(matches!(
|
||||
outcome,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Yielded { .. })
|
||||
));
|
||||
session
|
||||
.terminate(id.into())
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
}
|
||||
for session in [&parent, &child] {
|
||||
execute(
|
||||
session,
|
||||
request(r#"store("preserved", "original");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
for retired in [false, true] {
|
||||
let mut error = tonic::Status::unavailable("no healthy upstream");
|
||||
if retired {
|
||||
error
|
||||
.metadata_mut()
|
||||
.insert("x-code-mode-route-lost", "true".parse()?);
|
||||
}
|
||||
*rejection.lock().unwrap() = Some(error);
|
||||
let opens_before = opens.load(Ordering::SeqCst);
|
||||
let failures_before = rejected_executions.load(Ordering::SeqCst);
|
||||
execute(
|
||||
&parent,
|
||||
request(r#"store("preserved", "replayed");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await
|
||||
.expect_err("the rejected execution must not be replayed");
|
||||
assert_eq!(opens.load(Ordering::SeqCst), opens_before);
|
||||
assert_eq!(
|
||||
rejected_executions.load(Ordering::SeqCst),
|
||||
failures_before + 1
|
||||
);
|
||||
if !retired {
|
||||
*rejection.lock().unwrap() = None;
|
||||
} else {
|
||||
let reset = execute(
|
||||
&parent,
|
||||
request(r#"store("preserved", "must not run");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await
|
||||
.expect_err("route loss must report the reset before executing new code");
|
||||
assert!(
|
||||
reset
|
||||
.to_string()
|
||||
.contains("Stored values and running cells were lost")
|
||||
);
|
||||
}
|
||||
// The old lease and callback streams are still open. Only the explicit
|
||||
// route-loss response may replace the parent; the child must keep its state.
|
||||
for (session, expected) in [
|
||||
(&parent, if retired { "undefined" } else { "original" }),
|
||||
(&child, "original"),
|
||||
] {
|
||||
let actual = execute(
|
||||
session,
|
||||
request(r#"text(String(load("preserved")));"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
let RuntimeResponse::Result { cell_id, .. } = &actual else {
|
||||
anyhow::bail!("execution did not finish");
|
||||
};
|
||||
assert_eq!(
|
||||
actual,
|
||||
text_response(cell_id.as_str(), expected, actual.code_mode_host_duration())
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
opens.load(Ordering::SeqCst),
|
||||
opens_before + usize::from(retired)
|
||||
);
|
||||
}
|
||||
parent.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
child.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Cancellation of reentrant image getters through the standalone host.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_stops_reentrant_image_getter() -> Result<()> {
|
||||
// Force reentry and JSON fallback at a shallow depth, independent of stack limits.
|
||||
let source = r#"
|
||||
let calls = 0;
|
||||
const deadline = Date.now() + 60000;
|
||||
const value = {
|
||||
get image_url() {
|
||||
switch (++calls) {
|
||||
case 1: image(value); return "";
|
||||
case 2: throw new Error("enter fallback");
|
||||
default:
|
||||
notify("started");
|
||||
while (Date.now() < deadline) {}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
};
|
||||
try { image(value); } catch { text(calls); }
|
||||
"#;
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let other_session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let other_response = execute(
|
||||
&other_session,
|
||||
request(r#"store("alive", "yes"); text("yes");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
other_response,
|
||||
text_response("g2:1", "yes", other_response.code_mode_host_duration())
|
||||
);
|
||||
|
||||
let delegate = Arc::new(RecordingDelegate::default());
|
||||
let mut pending = request(source);
|
||||
pending.yield_time_ms = Some(60_000);
|
||||
let started = session
|
||||
.execute(pending, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let id = started.cell_id.clone();
|
||||
// The second image call enters JSON fallback; wait until its getter is running.
|
||||
timeout(TEST_TIMEOUT, delegate.notification_delivered.notified())
|
||||
.await
|
||||
.context("getter did not signal startup")?;
|
||||
|
||||
let result = timeout(Duration::from_secs(1), session.terminate(id.clone().into()))
|
||||
.await
|
||||
.context("workload did not stop within the cancellation deadline")?
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
// The getter would otherwise run for 60 seconds and emit its counter.
|
||||
assert_eq!(
|
||||
result,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Terminated {
|
||||
code_mode_host_duration: result.code_mode_host_duration(),
|
||||
cell_id: id.clone(),
|
||||
content_items: Vec::new(),
|
||||
})
|
||||
);
|
||||
let initial = timeout(TEST_TIMEOUT, started.initial_response())
|
||||
.await
|
||||
.context("initial termination response did not arrive")?
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(
|
||||
initial,
|
||||
RuntimeResponse::Terminated {
|
||||
code_mode_host_duration: initial.code_mode_host_duration(),
|
||||
cell_id: id,
|
||||
content_items: Vec::new(),
|
||||
}
|
||||
);
|
||||
let other_response = execute(
|
||||
&other_session,
|
||||
request(r#"text(load("alive"));"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
other_response,
|
||||
text_response("g2:2", "yes", other_response.code_mode_host_duration())
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
other_session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
100
codex-rs/code-mode-host/tests/grpc/network_policy_tests.rs
Normal file
100
codex-rs/code-mode-host/tests/grpc/network_policy_tests.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
//! Destination admission and account revocation cover the gRPC request lifetime.
|
||||
|
||||
use codex_http_client::DestinationPolicy;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::NetworkPolicyController;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn restricted_destination_is_rejected_before_connecting_to_the_code_mode_host() -> Result<()>
|
||||
{
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let controller = NetworkPolicyController::default();
|
||||
assert!(controller.publish(
|
||||
controller.policy().revision(),
|
||||
DestinationPolicy::Restricted {
|
||||
allowed_hosts: ["allowed.example".into()].into()
|
||||
}
|
||||
));
|
||||
let provider = Arc::new(GrpcCodeModeSessionProvider::with_http_client_factory(
|
||||
format!("https://{}", listener.local_addr()?),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_network_policy(controller.policy()),
|
||||
));
|
||||
let Err(error) = provider.create_session().await else {
|
||||
anyhow::bail!("restricted endpoint created a session")
|
||||
};
|
||||
assert!(
|
||||
error.contains("destination denied by application network policy"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
timeout(Duration::from_millis(/*millis*/ 50), listener.accept())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_change_revokes_active_rpc_and_renews_the_cached_client() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let controller = NetworkPolicyController::default();
|
||||
assert!(controller.publish(
|
||||
controller.policy().revision(),
|
||||
DestinationPolicy::Unrestricted
|
||||
));
|
||||
let provider = GrpcCodeModeSessionProvider::with_http_client_factory(
|
||||
host.endpoint.clone(),
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault)
|
||||
.with_network_policy(controller.policy()),
|
||||
);
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let mut pending = request("await new Promise(() => {});");
|
||||
pending.yield_time_ms = Some(60_000);
|
||||
let started = session
|
||||
.execute(
|
||||
pending,
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
|
||||
controller.policy().invalidate();
|
||||
assert!(
|
||||
timeout(TEST_TIMEOUT, started.initial_response())
|
||||
.await
|
||||
.context("account revocation did not interrupt the active RPC")?
|
||||
.is_err()
|
||||
);
|
||||
assert!(controller.publish(
|
||||
controller.policy().revision(),
|
||||
DestinationPolicy::Unrestricted
|
||||
));
|
||||
|
||||
let replacement = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let response = execute(
|
||||
&replacement,
|
||||
request(r#"text("replacement")"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
response,
|
||||
text_response("g2:1", "replacement", response.code_mode_host_duration())
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
replacement.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
217
codex-rs/code-mode-host/tests/grpc/process_metrics_tests.rs
Normal file
217
codex-rs/code-mode-host/tests/grpc/process_metrics_tests.rs
Normal file
@@ -0,0 +1,217 @@
|
||||
//! Process observations are independent of session state and HTTP/2 keepalive.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_code_mode::CodeModeProcessMetrics;
|
||||
use codex_code_mode::CodeModeProcessMetricsSample;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio_stream::wrappers::TcpListenerStream;
|
||||
use tonic::transport::Endpoint;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn metrics_failures_and_deadlines_preserve_sessions_and_keepalive() -> Result<()> {
|
||||
let snapshot = CodeModeProcessMetrics {
|
||||
process_id: 42,
|
||||
process_start_time_seconds: 1_700_000_000.0,
|
||||
cpu_seconds_total: 1.5,
|
||||
resident_memory_bytes: 4096,
|
||||
};
|
||||
let expected = snapshot.clone();
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let collector_calls = calls.clone();
|
||||
let (release, blocked) = std::sync::mpsc::channel::<()>();
|
||||
let blocked = Mutex::new(blocked);
|
||||
let host = codex_code_mode_host::GrpcCodeModeHost::with_process_metrics(Arc::new(move || {
|
||||
match collector_calls.fetch_add(1, Ordering::SeqCst) {
|
||||
0 => Ok(snapshot.clone()),
|
||||
1 => Err("metrics unavailable".to_string()),
|
||||
2 => panic!("collector panic"),
|
||||
_ => {
|
||||
blocked
|
||||
.lock()
|
||||
.unwrap()
|
||||
.recv()
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(snapshot.clone())
|
||||
}
|
||||
}
|
||||
}));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let connections = Arc::new(AtomicUsize::new(0));
|
||||
let accepted = connections.clone();
|
||||
let incoming = TcpListenerStream::new(listener).inspect(move |connection| {
|
||||
if connection.is_ok() {
|
||||
accepted.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
});
|
||||
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
tonic::transport::Server::builder()
|
||||
.add_service(grpc::code_mode_host_server::CodeModeHostServer::new(host))
|
||||
.serve_with_incoming(incoming)
|
||||
.await
|
||||
}));
|
||||
// Multiple keepalive intervals elapse while the collector is blocked, even
|
||||
// on this single-threaded runtime. A stalled HTTP/2 driver would lose state.
|
||||
let channel = Endpoint::from_shared(format!("http://{address}"))?
|
||||
.http2_keep_alive_interval(Duration::from_millis(/*millis*/ 50))
|
||||
.keep_alive_timeout(Duration::from_millis(/*millis*/ 100))
|
||||
.keep_alive_while_idle(/*enabled*/ true)
|
||||
.connect()
|
||||
.await?;
|
||||
let provider = GrpcCodeModeSessionProvider::with_channel(channel);
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
execute(
|
||||
&session,
|
||||
request("store('survives', 42);"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
provider
|
||||
.sample_process_metrics()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?,
|
||||
CodeModeProcessMetricsSample::Snapshot(expected)
|
||||
);
|
||||
for cell in 2..=4 {
|
||||
assert!(provider.sample_process_metrics().await.is_err());
|
||||
let response = execute(
|
||||
&session,
|
||||
request("text(load('survives'));"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
response,
|
||||
text_response(&cell.to_string(), "42", response.code_mode_host_duration())
|
||||
);
|
||||
}
|
||||
// A canceled blocked RPC retains its collector quota: no unbounded worker
|
||||
// threads are added, and neither the sample nor overload opens another channel.
|
||||
assert!(provider.sample_process_metrics().await.is_err());
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 4);
|
||||
assert_eq!(connections.load(Ordering::SeqCst), 1);
|
||||
release.send(())?;
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
drop(server);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A running server's collection precondition failure is not local host absence.
|
||||
#[tokio::test]
|
||||
async fn remote_metrics_precondition_is_a_failure() -> Result<()> {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
tonic::transport::Server::builder()
|
||||
.add_service(
|
||||
grpc::code_mode_host_server::CodeModeHostServer::with_interceptor(
|
||||
codex_code_mode_host::GrpcCodeModeHost::new(),
|
||||
|_request| {
|
||||
Err(tonic::Status::failed_precondition(
|
||||
"collector is misconfigured",
|
||||
))
|
||||
},
|
||||
),
|
||||
)
|
||||
.serve_with_incoming(TcpListenerStream::new(listener))
|
||||
.await
|
||||
}));
|
||||
let channel = Endpoint::from_shared(format!("http://{address}"))?
|
||||
.connect()
|
||||
.await?;
|
||||
let provider = GrpcCodeModeSessionProvider::with_channel(channel);
|
||||
let error = provider.sample_process_metrics().await.unwrap_err();
|
||||
assert!(error.contains("collector is misconfigured"), "{error}");
|
||||
drop(server);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A permanently stuck collector is bounded and cannot hang normal runtime drop.
|
||||
#[test]
|
||||
fn stuck_collector_does_not_block_runtime_shutdown() -> Result<()> {
|
||||
const CHILD_ENV: &str = "CODE_MODE_METRICS_SHUTDOWN_TEST_CHILD";
|
||||
if let Some(shutdown_marker) = std::env::var_os(CHILD_ENV) {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()?;
|
||||
runtime.block_on(async {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let collector_calls = calls.clone();
|
||||
let host =
|
||||
codex_code_mode_host::GrpcCodeModeHost::with_process_metrics(Arc::new(move || {
|
||||
collector_calls.fetch_add(1, Ordering::SeqCst);
|
||||
loop {
|
||||
std::thread::park();
|
||||
}
|
||||
}));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let address = listener.local_addr()?;
|
||||
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
tonic::transport::Server::builder()
|
||||
.add_service(grpc::code_mode_host_server::CodeModeHostServer::new(host))
|
||||
.serve_with_incoming(TcpListenerStream::new(listener))
|
||||
.await
|
||||
}));
|
||||
let channel = Endpoint::from_shared(format!("http://{address}"))?
|
||||
.connect()
|
||||
.await?;
|
||||
let provider = GrpcCodeModeSessionProvider::with_channel(channel);
|
||||
assert!(provider.sample_process_metrics().await.is_err());
|
||||
let busy = provider.sample_process_metrics().await.unwrap_err();
|
||||
assert!(busy.contains("collector is busy"), "{busy}");
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
drop(server);
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})?;
|
||||
let shutdown_marker = std::path::PathBuf::from(shutdown_marker);
|
||||
std::fs::write(shutdown_marker.with_extension("started"), "")?;
|
||||
drop(runtime);
|
||||
std::fs::write(shutdown_marker, "runtime dropped")?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let directory = tempfile::tempdir()?;
|
||||
let shutdown_marker = directory.path().join("shutdown-completed");
|
||||
let mut child = std::process::Command::new(std::env::current_exe()?)
|
||||
.args([
|
||||
"--exact",
|
||||
"process_metrics_tests::stuck_collector_does_not_block_runtime_shutdown",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD_ENV, &shutdown_marker)
|
||||
.spawn()?;
|
||||
let shutdown_started = shutdown_marker.with_extension("started");
|
||||
let startup_deadline = std::time::Instant::now() + Duration::from_secs(60);
|
||||
let mut shutdown_deadline = None;
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
assert!(status.success(), "metrics subprocess failed: {status}");
|
||||
assert_eq!(std::fs::read_to_string(shutdown_marker)?, "runtime dropped");
|
||||
return Ok(());
|
||||
}
|
||||
let now = std::time::Instant::now();
|
||||
if shutdown_deadline.is_none() && shutdown_started.exists() {
|
||||
shutdown_deadline = Some(now + Duration::from_secs(10));
|
||||
}
|
||||
if now >= shutdown_deadline.unwrap_or(startup_deadline) {
|
||||
child.kill()?;
|
||||
child.wait()?;
|
||||
anyhow::ensure!(
|
||||
shutdown_deadline.is_some(),
|
||||
"metrics subprocess startup timed out"
|
||||
);
|
||||
anyhow::bail!("a stuck metrics collector blocked runtime shutdown");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(/*millis*/ 10));
|
||||
}
|
||||
}
|
||||
378
codex-rs/code-mode-host/tests/grpc/session_recovery_tests.rs
Normal file
378
codex-rs/code-mode-host/tests/grpc/session_recovery_tests.rs
Normal file
@@ -0,0 +1,378 @@
|
||||
//! Exercises missing-session recovery while the host's lease streams remain open.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_code_mode::CodeModeOutputTruncation;
|
||||
use codex_code_mode::CodeModeSessionOptions;
|
||||
use codex_code_mode::CodeModeSessionProvider;
|
||||
use codex_code_mode::FunctionCallOutputContentItem;
|
||||
use codex_code_mode::GrpcCodeModeSessionProvider;
|
||||
use codex_code_mode::NoopCodeModeSessionDelegate;
|
||||
use codex_code_mode::RuntimeResponse;
|
||||
use codex_code_mode_host::GrpcCodeModeHost;
|
||||
use codex_code_mode_protocol::grpc::code_mode_host_server::CodeModeHostServer;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_stream::wrappers::TcpListenerStream;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
use tonic::Code;
|
||||
use tonic::Status;
|
||||
use tonic::transport::Server;
|
||||
|
||||
use super::execute;
|
||||
use super::request;
|
||||
use super::text_response;
|
||||
|
||||
#[tokio::test]
|
||||
async fn quiet_session_reuses_its_worker_connection() -> Result<()> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = format!("http://{}", listener.local_addr()?);
|
||||
let connections = Arc::new(AtomicUsize::new(0));
|
||||
let accepted = Arc::clone(&connections);
|
||||
let incoming = TcpListenerStream::new(listener).inspect(move |_| {
|
||||
accepted.fetch_add(1, Ordering::SeqCst);
|
||||
});
|
||||
let _server = AbortOnDropHandle::new(tokio::spawn(
|
||||
Server::builder()
|
||||
.add_service(CodeModeHostServer::new(GrpcCodeModeHost::new()))
|
||||
.serve_with_incoming(incoming),
|
||||
));
|
||||
let session = GrpcCodeModeSessionProvider::new(endpoint)
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
execute(
|
||||
&session,
|
||||
request(r#"store("key", "persisted");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(std::time::Duration::from_secs(120)).await;
|
||||
tokio::time::resume();
|
||||
|
||||
let result = execute(
|
||||
&session,
|
||||
request(r#"text(load("key"));"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
result,
|
||||
text_response("2", "persisted", result.code_mode_host_duration())
|
||||
);
|
||||
assert_eq!(connections.load(Ordering::SeqCst), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn last_failed_session_releases_the_shared_connection() -> Result<()> {
|
||||
let reject = Arc::new(AtomicBool::new(false));
|
||||
let reject_next_rpc = Arc::clone(&reject);
|
||||
let service = CodeModeHostServer::with_interceptor(GrpcCodeModeHost::new(), move |req| {
|
||||
if reject_next_rpc.swap(false, Ordering::SeqCst) {
|
||||
Err(Status::not_found("session was lost"))
|
||||
} else {
|
||||
Ok(req)
|
||||
}
|
||||
});
|
||||
let host = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let host_addr = host.local_addr()?;
|
||||
let _server = AbortOnDropHandle::new(tokio::spawn(
|
||||
Server::builder()
|
||||
.add_service(service)
|
||||
.serve_with_incoming(TcpListenerStream::new(host)),
|
||||
));
|
||||
|
||||
// Forward exactly one TCP connection. Its EOF is the worker-release signal.
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(format!("http://{}", listener.local_addr()?));
|
||||
let connection = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let (mut client, _) = listener.accept().await?;
|
||||
drop(listener);
|
||||
let mut host = TcpStream::connect(host_addr).await?;
|
||||
tokio::io::copy_bidirectional(&mut client, &mut host).await
|
||||
}));
|
||||
let first = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let last = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
first.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
let result = execute(
|
||||
&last,
|
||||
request("text('still live')"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
result,
|
||||
text_response("g2:1", "still live", result.code_mode_host_duration())
|
||||
);
|
||||
|
||||
reject.store(true, Ordering::SeqCst);
|
||||
let error = execute(
|
||||
&last,
|
||||
request("text('must not run')"),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!(
|
||||
"gRPC code-mode execution failed: {}",
|
||||
Status::not_found("session was lost")
|
||||
)
|
||||
);
|
||||
tokio::time::timeout(super::TEST_TIMEOUT, connection)
|
||||
.await
|
||||
.expect("last failed session kept its worker connection open")??;
|
||||
drop((first, last, provider));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_missing_sessions_reopen_without_replaying_execution() -> Result<()> {
|
||||
for (code, route_lost, expected_cell, expected_value) in [
|
||||
(Code::NotFound, false, "g2:1", "undefined"),
|
||||
(Code::InvalidArgument, false, "2", "1"),
|
||||
(Code::Unavailable, false, "2", "1"),
|
||||
(Code::Unavailable, true, "2", "1"),
|
||||
] {
|
||||
let rejection = Arc::new(Mutex::new(/*t*/ None));
|
||||
let next_rejection = Arc::clone(&rejection);
|
||||
let request_count = Arc::new(AtomicUsize::new(/*v*/ 0));
|
||||
let count = Arc::clone(&request_count);
|
||||
let service = CodeModeHostServer::with_interceptor(
|
||||
GrpcCodeModeHost::new(),
|
||||
move |request: tonic::Request<()>| {
|
||||
count.fetch_add(/*val*/ 1, Ordering::SeqCst);
|
||||
match next_rejection.lock().unwrap().take() {
|
||||
Some(rejection) => Err(rejection),
|
||||
None => Ok(request),
|
||||
}
|
||||
},
|
||||
);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = format!("http://{}", listener.local_addr()?);
|
||||
let _server = AbortOnDropHandle::new(tokio::spawn(
|
||||
Server::builder()
|
||||
.add_service(service)
|
||||
.serve_with_incoming(TcpListenerStream::new(listener)),
|
||||
));
|
||||
let session = GrpcCodeModeSessionProvider::new(endpoint)
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(
|
||||
session.output_truncation(),
|
||||
CodeModeOutputTruncation::Client
|
||||
);
|
||||
execute(
|
||||
&session,
|
||||
request(r#"store("before", 1);"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Reject the next Execute without closing the lease or subscription streams.
|
||||
let mut failure = Status::new(code, "injected RPC rejection");
|
||||
if route_lost {
|
||||
// A direct host has no proxy route to retire.
|
||||
failure
|
||||
.metadata_mut()
|
||||
.insert("x-code-mode-route-lost", "true".parse()?);
|
||||
}
|
||||
*rejection.lock().unwrap() = Some(failure.clone());
|
||||
let requests_before_rejection = request_count.load(Ordering::SeqCst);
|
||||
let failed = execute(
|
||||
&session,
|
||||
request(r#"store("before", "replayed");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
failed.to_string(),
|
||||
format!("gRPC code-mode execution failed: {failure}")
|
||||
);
|
||||
assert_eq!(
|
||||
request_count.load(Ordering::SeqCst),
|
||||
requests_before_rejection + 1,
|
||||
"the failed call must return without opening a session or replaying Execute"
|
||||
);
|
||||
if code == Code::NotFound {
|
||||
let reset = execute(
|
||||
&session,
|
||||
request(r#"store("before", "must not run");"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
reset
|
||||
.to_string()
|
||||
.contains("Stored values and running cells were lost")
|
||||
);
|
||||
}
|
||||
let actual = execute(
|
||||
&session,
|
||||
request(r#"text(String(load("before")))"#),
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
text_response(
|
||||
expected_cell,
|
||||
expected_value,
|
||||
actual.code_mode_host_duration()
|
||||
)
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grpc_session_pins_output_mode_across_recovery_and_shutdown() -> Result<()> {
|
||||
use CodeModeOutputTruncation::Client;
|
||||
use CodeModeOutputTruncation::Server;
|
||||
use axum::body::Body;
|
||||
use axum::extract::Request;
|
||||
use axum::middleware::Next;
|
||||
|
||||
// A Server-capable host honors either choice. A Client-only host ignores the new field.
|
||||
for (initial_host, replacement_host) in [(Server, Server), (Server, Client), (Client, Server)] {
|
||||
let opens = Arc::new(AtomicUsize::new(0));
|
||||
let subscriptions = Arc::new(AtomicUsize::new(0));
|
||||
let subscription_count = Arc::clone(&subscriptions);
|
||||
let app = axum::Router::new()
|
||||
.fallback_service(CodeModeHostServer::new(GrpcCodeModeHost::new()))
|
||||
.layer(axum::middleware::from_fn(
|
||||
move |mut rpc: Request, next: Next| {
|
||||
let opens = Arc::clone(&opens);
|
||||
let subscriptions = Arc::clone(&subscription_count);
|
||||
async move {
|
||||
if rpc.uri().path().ends_with("/OpenSession") {
|
||||
let host = if opens.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
initial_host
|
||||
} else {
|
||||
replacement_host
|
||||
};
|
||||
if host == Client {
|
||||
// No resource limits were requested, so ignoring the output mode
|
||||
// leaves an empty OpenSessionRequest in one uncompressed gRPC frame.
|
||||
rpc.headers_mut().remove("content-length");
|
||||
*rpc.body_mut() = Body::from(&[0_u8; 5][..]);
|
||||
}
|
||||
} else if rpc.uri().path().ends_with("/Execute")
|
||||
&& opens.load(Ordering::SeqCst) == 1
|
||||
{
|
||||
return Status::not_found("session was lost").into_http::<Body>();
|
||||
} else if rpc.uri().path().ends_with("/SubscribeToToolCalls") {
|
||||
subscriptions.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
next.run(rpc).await
|
||||
}
|
||||
},
|
||||
));
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = format!("http://{}", listener.local_addr()?);
|
||||
let _server = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.expect("recovery test host");
|
||||
}));
|
||||
let session = GrpcCodeModeSessionProvider::new(endpoint)
|
||||
.create_session_with_options(CodeModeSessionOptions {
|
||||
output_truncation: Server,
|
||||
..CodeModeSessionOptions::default()
|
||||
})
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(session.output_truncation(), initial_host);
|
||||
|
||||
let delegate = Arc::new(NoopCodeModeSessionDelegate);
|
||||
let failed = execute(&session, request("text('must not run')"), delegate.clone())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(failed.to_string().contains("session was lost"));
|
||||
let reset = execute(
|
||||
&session,
|
||||
request("text('must not replay')"),
|
||||
delegate.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
if initial_host == Server && replacement_host == Client {
|
||||
assert_eq!(
|
||||
reset.to_string(),
|
||||
"gRPC code-mode host changed the session output truncation mode on reconnect"
|
||||
);
|
||||
assert_eq!(
|
||||
subscriptions.load(Ordering::SeqCst),
|
||||
1,
|
||||
"the downgraded binding must not subscribe"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
reset
|
||||
.to_string()
|
||||
.contains("Stored values and running cells were lost")
|
||||
);
|
||||
let source = match initial_host {
|
||||
Client => "text('x'.repeat(2 * 1024 * 1024))",
|
||||
Server => "throw 'begin:' + 'X'.repeat(65 * 1024 * 1024) + ':end'",
|
||||
};
|
||||
let mut observation = request(source);
|
||||
observation.max_output_tokens = Some(5);
|
||||
observation.yield_time_ms = Some(60_000);
|
||||
let response = execute(&session, observation, delegate).await?;
|
||||
match initial_host {
|
||||
Client => assert_eq!(
|
||||
response,
|
||||
text_response(
|
||||
"g2:1",
|
||||
&"x".repeat(2 * 1024 * 1024),
|
||||
response.code_mode_host_duration()
|
||||
)
|
||||
),
|
||||
Server => {
|
||||
let RuntimeResponse::Result {
|
||||
cell_id,
|
||||
content_items,
|
||||
error_text: Some(diagnostic),
|
||||
..
|
||||
} = response
|
||||
else {
|
||||
panic!("expected a script failure");
|
||||
};
|
||||
assert_eq!(cell_id.as_str(), "g2:1");
|
||||
assert_eq!(diagnostic.len(), 64 * 1024);
|
||||
assert!(diagnostic.starts_with("begin:") && diagnostic.ends_with(":end"));
|
||||
assert_eq!(content_items, [
|
||||
"Warning: truncated output (original token count: 262144)\nTotal output lines: 2\n\nScript err…262139 tokens truncated…",
|
||||
"[Code Mode session output limit reached: omitted 67108888 text bytes; discarded 0 text segments, 0 images, 0 audio items]",
|
||||
"XXXXXX:end",
|
||||
].map(|text| FunctionCallOutputContentItem::InputText { text: text.into() }));
|
||||
}
|
||||
}
|
||||
}
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(session.output_truncation(), initial_host);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
353
codex-rs/code-mode-host/tests/grpc_notifications.rs
Normal file
353
codex-rs/code-mode-host/tests/grpc_notifications.rs
Normal file
@@ -0,0 +1,353 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::PoisonError;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_code_mode::CellId;
|
||||
use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSession;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeSessionProvider;
|
||||
use codex_code_mode::ExecuteRequest;
|
||||
use codex_code_mode::FunctionCallOutputContentItem;
|
||||
use codex_code_mode::GrpcCodeModeSessionProvider;
|
||||
use codex_code_mode::NotificationFuture;
|
||||
use codex_code_mode::RuntimeResponse;
|
||||
use codex_code_mode::ToolInvocationFuture;
|
||||
use codex_code_mode::WaitOutcome;
|
||||
use codex_code_mode::WaitRequest;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[path = "support/host.rs"]
|
||||
mod host;
|
||||
#[path = "support/recording_delegate.rs"]
|
||||
mod recording_delegate;
|
||||
|
||||
use host::HostHarness;
|
||||
use recording_delegate::RecordingDelegate;
|
||||
use recording_delegate::cell_id;
|
||||
|
||||
const TEST_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
struct BlockingNotificationDelegate {
|
||||
started: Semaphore,
|
||||
release: Semaphore,
|
||||
delivered: Semaphore,
|
||||
cancelled: Semaphore,
|
||||
closed: Semaphore,
|
||||
}
|
||||
|
||||
impl BlockingNotificationDelegate {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
started: Semaphore::new(/*permits*/ 0),
|
||||
release: Semaphore::new(/*permits*/ 0),
|
||||
delivered: Semaphore::new(/*permits*/ 0),
|
||||
cancelled: Semaphore::new(/*permits*/ 0),
|
||||
closed: Semaphore::new(/*permits*/ 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for BlockingNotificationDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
_invocation: CodeModeNestedToolCall,
|
||||
_cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async { Err("unexpected tool invocation".to_string()) })
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
_call_id: String,
|
||||
_cell_id: CellId,
|
||||
_text: String,
|
||||
cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
self.started.add_permits(/*n*/ 1);
|
||||
tokio::select! {
|
||||
_ = cancellation.cancelled() => {
|
||||
self.cancelled.add_permits(/*n*/ 1);
|
||||
Err("notification cancelled".to_string())
|
||||
}
|
||||
permit = self.release.acquire() => {
|
||||
permit
|
||||
.map_err(|_| "notification release closed".to_string())?
|
||||
.forget();
|
||||
self.delivered.add_permits(/*n*/ 1);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn cell_closed(&self, _cell_id: &CellId) {
|
||||
self.closed.add_permits(/*n*/ 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn request(source: &str) -> ExecuteRequest {
|
||||
ExecuteRequest {
|
||||
tool_call_id: "call-1".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
source: source.to_string(),
|
||||
yield_time_ms: Some(/*value*/ 5_000),
|
||||
max_output_tokens: Some(/*value*/ 1_000),
|
||||
}
|
||||
}
|
||||
|
||||
fn text_response(
|
||||
cell: &str,
|
||||
value: &str,
|
||||
code_mode_host_duration: Option<Duration>,
|
||||
) -> RuntimeResponse {
|
||||
RuntimeResponse::Result {
|
||||
code_mode_host_duration,
|
||||
cell_id: cell_id(cell),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: value.to_string(),
|
||||
}],
|
||||
result_buffered_for: Duration::ZERO,
|
||||
error_text: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
session: &Arc<dyn CodeModeSession>,
|
||||
request: ExecuteRequest,
|
||||
delegate: Arc<dyn CodeModeSessionDelegate>,
|
||||
) -> Result<RuntimeResponse> {
|
||||
timeout(TEST_TIMEOUT, async {
|
||||
session
|
||||
.execute(request, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?
|
||||
.initial_response()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)
|
||||
})
|
||||
.await
|
||||
.context("timed out executing gRPC code-mode cell")?
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_cells_drain_pending_notifications_before_completion() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
let delegate = Arc::new(BlockingNotificationDelegate::new());
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
|
||||
let executing = Arc::clone(&session);
|
||||
let execution_delegate = delegate.clone();
|
||||
let completion = tokio::spawn(async move {
|
||||
execute(
|
||||
&executing,
|
||||
request(r#"notify("notice"); text("done");"#),
|
||||
execution_delegate,
|
||||
)
|
||||
.await
|
||||
});
|
||||
timeout(TEST_TIMEOUT, delegate.started.acquire())
|
||||
.await
|
||||
.context("notification did not start")??
|
||||
.forget();
|
||||
assert!(!completion.is_finished());
|
||||
delegate.release.add_permits(/*n*/ 1);
|
||||
let actual = timeout(TEST_TIMEOUT, completion)
|
||||
.await
|
||||
.context("completed cell did not finish after notification delivery")???;
|
||||
assert_eq!(
|
||||
actual,
|
||||
text_response("1", "done", actual.code_mode_host_duration())
|
||||
);
|
||||
timeout(TEST_TIMEOUT, delegate.delivered.acquire())
|
||||
.await
|
||||
.context("completed cell did not deliver its pending notification")??
|
||||
.forget();
|
||||
assert!(delegate.cancelled.try_acquire().is_err());
|
||||
timeout(TEST_TIMEOUT, delegate.closed.acquire())
|
||||
.await
|
||||
.context("completed cell was not retired")??
|
||||
.forget();
|
||||
|
||||
let actual = execute(
|
||||
&session,
|
||||
request(r#"text("still alive");"#),
|
||||
delegate.clone(),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
text_response("2", "still alive", actual.code_mode_host_duration())
|
||||
);
|
||||
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_waits_drain_pending_notifications_before_returning() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
let delegate = Arc::new(BlockingNotificationDelegate::new());
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let pending = request(r#"yield_control(); notify("notice"); text("done");"#);
|
||||
let cell = session
|
||||
.execute(pending, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let actual = cell.initial_response().await.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
RuntimeResponse::Yielded {
|
||||
code_mode_host_duration: actual.code_mode_host_duration(),
|
||||
cell_id: cell_id("1"),
|
||||
content_items: Vec::new(),
|
||||
}
|
||||
);
|
||||
|
||||
let waiting = Arc::clone(&session);
|
||||
let completion = tokio::spawn(async move {
|
||||
waiting
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: cell_id("1"),
|
||||
yield_time_ms: 5_000,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)
|
||||
});
|
||||
timeout(TEST_TIMEOUT, delegate.started.acquire())
|
||||
.await
|
||||
.context("wait notification did not start")??
|
||||
.forget();
|
||||
assert!(!completion.is_finished());
|
||||
delegate.release.add_permits(/*n*/ 1);
|
||||
let actual = timeout(TEST_TIMEOUT, completion)
|
||||
.await
|
||||
.context("wait did not finish after notification delivery")???;
|
||||
assert_eq!(
|
||||
actual,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Result {
|
||||
code_mode_host_duration: actual.code_mode_host_duration(),
|
||||
cell_id: cell_id("1"),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "done".to_string(),
|
||||
}],
|
||||
result_buffered_for: actual.result_buffered_for().unwrap(),
|
||||
error_text: None,
|
||||
})
|
||||
);
|
||||
timeout(TEST_TIMEOUT, delegate.delivered.acquire())
|
||||
.await
|
||||
.context("wait did not deliver its pending notification")??
|
||||
.forget();
|
||||
assert!(delegate.cancelled.try_acquire().is_err());
|
||||
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn termination_cancels_pending_notifications() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
let delegate = Arc::new(BlockingNotificationDelegate::new());
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let mut pending = request(r#"notify("notice"); await new Promise(() => {});"#);
|
||||
pending.yield_time_ms = Some(/*value*/ 1);
|
||||
let cell = session
|
||||
.execute(pending, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
|
||||
timeout(TEST_TIMEOUT, delegate.started.acquire())
|
||||
.await
|
||||
.context("notification did not start")??
|
||||
.forget();
|
||||
let actual = cell.initial_response().await.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
RuntimeResponse::Yielded {
|
||||
code_mode_host_duration: actual.code_mode_host_duration(),
|
||||
cell_id: cell_id("1"),
|
||||
content_items: Vec::new(),
|
||||
}
|
||||
);
|
||||
let actual = session
|
||||
.terminate(cell_id("1").into())
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Terminated {
|
||||
code_mode_host_duration: actual.code_mode_host_duration(),
|
||||
cell_id: cell_id("1"),
|
||||
content_items: Vec::new(),
|
||||
})
|
||||
);
|
||||
timeout(TEST_TIMEOUT, delegate.cancelled.acquire())
|
||||
.await
|
||||
.context("termination did not cancel notification delivery")??
|
||||
.forget();
|
||||
timeout(TEST_TIMEOUT, delegate.closed.acquire())
|
||||
.await
|
||||
.context("terminated cell was not retired")??
|
||||
.forget();
|
||||
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oversized_notification_text_is_delivered_unchanged() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
let delegate = Arc::new(RecordingDelegate::default());
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
|
||||
let actual = execute(
|
||||
&session,
|
||||
request(r#"notify("🦀".repeat(512)); text("done");"#),
|
||||
delegate.clone(),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
actual,
|
||||
text_response("1", "done", actual.code_mode_host_duration())
|
||||
);
|
||||
timeout(TEST_TIMEOUT, delegate.notification_delivered.notified())
|
||||
.await
|
||||
.context("oversized notification was not delivered")?;
|
||||
assert_eq!(
|
||||
*delegate
|
||||
.notifications
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner),
|
||||
vec![("call-1".to_string(), cell_id("1"), "🦀".repeat(512),)]
|
||||
);
|
||||
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
178
codex-rs/code-mode-host/tests/grpc_tcp.rs
Normal file
178
codex-rs/code-mode-host/tests/grpc_tcp.rs
Normal file
@@ -0,0 +1,178 @@
|
||||
use std::future::poll_fn;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use axum::http::Request;
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::Version;
|
||||
use codex_code_mode_protocol::grpc;
|
||||
use codex_code_mode_protocol::grpc::code_mode_host_client::CodeModeHostClient;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
use tonic::body::Body;
|
||||
use tonic::codegen::Service;
|
||||
use tonic::transport::Endpoint;
|
||||
|
||||
#[path = "support/host.rs"]
|
||||
mod host;
|
||||
|
||||
use host::HostHarness;
|
||||
|
||||
const TEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_listener_serves_http1_healthz() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let request = "GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
|
||||
let response = http1_response(&host.endpoint, request.as_bytes()).await?;
|
||||
|
||||
assert_eq!(response.lines().next(), Some("HTTP/1.1 200 OK"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_listener_rejects_http1_grpc_requests() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let mut request = concat!(
|
||||
"POST /codex.code_mode.v1.CodeModeHost/OpenSession HTTP/1.1\r\n",
|
||||
"Host: localhost\r\n",
|
||||
"Content-Type: application/grpc\r\n",
|
||||
"Content-Length: 5\r\n",
|
||||
"Connection: close\r\n\r\n"
|
||||
)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
request.extend_from_slice(&[0; 5]);
|
||||
let response = http1_response(&host.endpoint, &request).await?;
|
||||
|
||||
assert_eq!(
|
||||
response.lines().next(),
|
||||
Some("HTTP/1.1 505 HTTP Version Not Supported")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_listener_serves_http2_healthz() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let mut channel = Endpoint::from_shared(host.endpoint.clone())
|
||||
.context("gRPC code-mode host published an invalid endpoint")?
|
||||
.connect_timeout(TEST_TIMEOUT)
|
||||
.timeout(TEST_TIMEOUT)
|
||||
.connect()
|
||||
.await
|
||||
.context("failed to connect to gRPC code-mode host health endpoint")?;
|
||||
let request = Request::builder()
|
||||
.uri(format!("{}/healthz", host.endpoint))
|
||||
.body(Body::empty())
|
||||
.context("failed to build gRPC code-mode host health request")?;
|
||||
|
||||
let response = timeout(TEST_TIMEOUT, async {
|
||||
poll_fn(|context| channel.poll_ready(context))
|
||||
.await
|
||||
.context("gRPC code-mode host health channel is unavailable")?;
|
||||
channel
|
||||
.call(request)
|
||||
.await
|
||||
.context("failed to request gRPC code-mode host health")
|
||||
})
|
||||
.await
|
||||
.context("timed out requesting gRPC code-mode host health")??;
|
||||
|
||||
assert_eq!(response.version(), Version::HTTP_2);
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn http1_response(endpoint: &str, request: &[u8]) -> Result<String> {
|
||||
let address = endpoint
|
||||
.strip_prefix("http://")
|
||||
.context("gRPC code-mode host URL should use http://")?;
|
||||
|
||||
timeout(TEST_TIMEOUT, async {
|
||||
let mut stream = TcpStream::connect(address)
|
||||
.await
|
||||
.context("failed to connect to gRPC code-mode host")?;
|
||||
stream
|
||||
.write_all(request)
|
||||
.await
|
||||
.context("failed to send HTTP/1.1 request to gRPC code-mode host")?;
|
||||
|
||||
let mut response = String::new();
|
||||
stream
|
||||
.read_to_string(&mut response)
|
||||
.await
|
||||
.context("failed to read HTTP/1.1 response from gRPC code-mode host")?;
|
||||
Ok(response)
|
||||
})
|
||||
.await
|
||||
.context("timed out waiting for HTTP/1.1 response from gRPC code-mode host")?
|
||||
}
|
||||
|
||||
/// Negotiate zstd for capable clients while preserving identity-only clients.
|
||||
#[tokio::test]
|
||||
async fn tcp_listener_opens_a_grpc_session() -> Result<()> {
|
||||
let mut host = Command::new(codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?)
|
||||
.args(["--listen", "grpc://127.0.0.1:0"])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(/*kill_on_drop*/ true)
|
||||
.spawn()
|
||||
.context("failed to start gRPC code-mode host")?;
|
||||
let stdout = host
|
||||
.stdout
|
||||
.take()
|
||||
.context("gRPC code-mode host stdout is unavailable")?;
|
||||
let mut stdout = BufReader::new(stdout);
|
||||
let mut endpoint = String::new();
|
||||
timeout(TEST_TIMEOUT, stdout.read_line(&mut endpoint))
|
||||
.await
|
||||
.context("gRPC code-mode host did not publish its endpoint")??;
|
||||
let endpoint = Endpoint::from_shared(endpoint.trim().to_string())
|
||||
.context("gRPC code-mode host published an invalid endpoint")?
|
||||
.connect_timeout(TEST_TIMEOUT)
|
||||
.timeout(TEST_TIMEOUT);
|
||||
for encoding in [None, Some(tonic::codec::CompressionEncoding::Zstd)] {
|
||||
let mut client = CodeModeHostClient::connect(endpoint.clone())
|
||||
.await
|
||||
.context("failed to connect to gRPC code-mode host")?;
|
||||
if let Some(encoding) = encoding {
|
||||
client = client.accept_compressed(encoding);
|
||||
}
|
||||
let response = client
|
||||
.open_session(grpc::OpenSessionRequest {
|
||||
max_pending_delegate_calls: None,
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
})
|
||||
.await
|
||||
.context("failed to open gRPC code-mode session")?;
|
||||
assert_eq!(
|
||||
response
|
||||
.metadata()
|
||||
.get("grpc-encoding")
|
||||
.map(|value| value.to_str())
|
||||
.transpose()?,
|
||||
encoding.map(|_| "zstd"),
|
||||
);
|
||||
let mut events = response.into_inner();
|
||||
let event = timeout(TEST_TIMEOUT, events.message())
|
||||
.await
|
||||
.context("timed out waiting for gRPC code-mode session event")?
|
||||
.context("failed to read gRPC code-mode session event")?
|
||||
.context("gRPC code-mode session ended before opening")?;
|
||||
assert!(matches!(
|
||||
event.event,
|
||||
Some(grpc::session_event::Event::Opened(opened)) if !opened.session_id.is_empty()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
304
codex-rs/code-mode-host/tests/grpc_timing.rs
Normal file
304
codex-rs/code-mode-host/tests/grpc_timing.rs
Normal file
@@ -0,0 +1,304 @@
|
||||
//! Checks that remote timing measures each observation, not client delays or cell lifetime.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_code_mode::CodeModeSessionProvider;
|
||||
use codex_code_mode::ExecuteRequest;
|
||||
use codex_code_mode::GrpcCodeModeSessionProvider;
|
||||
use codex_code_mode::NoopCodeModeSessionDelegate;
|
||||
use codex_code_mode::ProcessOwnedCodeModeSessionProvider;
|
||||
use codex_code_mode::RuntimeResponse;
|
||||
use codex_code_mode::WaitOutcome;
|
||||
use codex_code_mode::WaitRequest;
|
||||
use codex_code_mode_protocol::grpc;
|
||||
use codex_code_mode_protocol::grpc::code_mode_host_client::CodeModeHostClient;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::time::sleep;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[path = "support/host.rs"]
|
||||
mod host;
|
||||
#[expect(dead_code, reason = "Other suites use the shared cell_id helper.")]
|
||||
#[path = "support/recording_delegate.rs"]
|
||||
mod recording_delegate;
|
||||
|
||||
use host::HostHarness;
|
||||
use recording_delegate::RecordingDelegate;
|
||||
|
||||
const TEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 20);
|
||||
|
||||
/// Successful and failed JavaScript include computation and timers in their host timing.
|
||||
/// Waiting to read a finished execution must not increase that measurement.
|
||||
#[tokio::test]
|
||||
async fn execution_timing_includes_javascript_but_excludes_delayed_reads() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let mut client = CodeModeHostClient::connect(host.endpoint).await?;
|
||||
let mut events = client
|
||||
.open_session(grpc::OpenSessionRequest {
|
||||
max_pending_delegate_calls: None,
|
||||
cell_execution_limits: None,
|
||||
output_truncation: None,
|
||||
})
|
||||
.await?
|
||||
.into_inner();
|
||||
let opened = timeout(TEST_TIMEOUT, events.message())
|
||||
.await??
|
||||
.context("session ended")?;
|
||||
let Some(grpc::session_event::Event::Opened(opened)) = opened.event else {
|
||||
anyhow::bail!("expected session opening event");
|
||||
};
|
||||
|
||||
let endings = ["", "throw new Error('timed failure');"];
|
||||
for (index, suffix) in endings.into_iter().enumerate() {
|
||||
let observed = Instant::now();
|
||||
let mut execution = client
|
||||
.execute(grpc::ExecuteRequest {
|
||||
session_id: opened.session_id.clone(),
|
||||
execution_id: format!("execution-{index}"),
|
||||
tool_call_id: format!("call-{index}"),
|
||||
source: format!(
|
||||
"const until = Date.now() + 150; while (Date.now() < until) {{}} \
|
||||
await new Promise(resolve => setTimeout(resolve, 150)); {suffix}"
|
||||
),
|
||||
enabled_tools: Vec::new(),
|
||||
yield_time_ms: Some(/*value*/ 5_000),
|
||||
max_output_tokens: Some(/*value*/ 1_000),
|
||||
})
|
||||
.await?
|
||||
.into_inner();
|
||||
let started = timeout(TEST_TIMEOUT, execution.message())
|
||||
.await??
|
||||
.context("execution ended")?;
|
||||
let Some(grpc::execute_event::Event::Started(started)) = started.event else {
|
||||
anyhow::bail!("expected execution admission");
|
||||
};
|
||||
let closed = timeout(TEST_TIMEOUT, events.message())
|
||||
.await??
|
||||
.context("session ended")?;
|
||||
assert!(
|
||||
matches!(closed.event, Some(grpc::session_event::Event::CellClosed(closed))
|
||||
if closed.cell_id == started.cell_id)
|
||||
);
|
||||
|
||||
// CellClosed confirms the JS finished before introducing a client-only delay.
|
||||
sleep(Duration::from_millis(/*millis*/ 600)).await;
|
||||
let result = timeout(TEST_TIMEOUT, execution.message())
|
||||
.await??
|
||||
.context("execution ended")?;
|
||||
let Some(grpc::execute_event::Event::Outcome(outcome)) = result.event else {
|
||||
anyhow::bail!("expected execution outcome");
|
||||
};
|
||||
let duration = Duration::from_nanos(outcome.code_mode_host_duration_ns);
|
||||
assert!(duration >= Duration::from_millis(/*millis*/ 250));
|
||||
assert!(duration + Duration::from_millis(/*millis*/ 300) <= observed.elapsed());
|
||||
let Some(grpc::execution_outcome::Outcome::Completed(completed)) = outcome.outcome else {
|
||||
anyhow::bail!("expected completed execution");
|
||||
};
|
||||
if suffix.is_empty() {
|
||||
assert_eq!(completed.error_text, None);
|
||||
} else {
|
||||
assert!(
|
||||
completed
|
||||
.error_text
|
||||
.context("expected JS failure")?
|
||||
.contains("timed failure")
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The process-owned host freezes successful and failed execution timing before
|
||||
/// the client reads its initial response, including JavaScript computation and timers.
|
||||
#[tokio::test]
|
||||
async fn stdio_execution_timing_includes_javascript_but_excludes_delayed_reads() -> Result<()> {
|
||||
let provider = ProcessOwnedCodeModeSessionProvider::with_host_program(
|
||||
codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?,
|
||||
);
|
||||
let delegate = Arc::new(RecordingDelegate::default());
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
|
||||
let endings = ["", "throw new Error('timed failure');"];
|
||||
for (index, suffix) in endings.into_iter().enumerate() {
|
||||
let observed = Instant::now();
|
||||
let started = session
|
||||
.execute(
|
||||
ExecuteRequest {
|
||||
tool_call_id: format!("call-{index}"),
|
||||
source: format!(
|
||||
"const until = Date.now() + 150; while (Date.now() < until) {{}} \
|
||||
await new Promise(resolve => setTimeout(resolve, 150)); \
|
||||
notify('finished'); {suffix}"
|
||||
),
|
||||
enabled_tools: Vec::new(),
|
||||
yield_time_ms: Some(/*value*/ 5_000),
|
||||
max_output_tokens: Some(/*value*/ 1_000),
|
||||
},
|
||||
delegate.clone(),
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
timeout(TEST_TIMEOUT, delegate.notification_delivered.notified())
|
||||
.await
|
||||
.context("JS did not report completion of its timed work")?;
|
||||
|
||||
// Delay only after the host has finished the computation and timer.
|
||||
sleep(Duration::from_millis(/*millis*/ 600)).await;
|
||||
let response = timeout(TEST_TIMEOUT, started.initial_response())
|
||||
.await?
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let duration = response
|
||||
.code_mode_host_duration()
|
||||
.context("missing stdio exec timing")?;
|
||||
assert!(duration >= Duration::from_millis(/*millis*/ 250));
|
||||
assert!(duration + Duration::from_millis(/*millis*/ 300) <= observed.elapsed());
|
||||
let RuntimeResponse::Result { error_text, .. } = response else {
|
||||
anyhow::bail!("expected completed execution");
|
||||
};
|
||||
if suffix.is_empty() {
|
||||
assert_eq!(error_text, None);
|
||||
} else {
|
||||
let Some(error_text) = error_text else {
|
||||
anyhow::bail!("expected JS failure");
|
||||
};
|
||||
assert!(error_text.contains("timed failure"));
|
||||
}
|
||||
}
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every wait and termination measures its own request, including missing-cell outcomes.
|
||||
/// Earlier execution and background time must not be charged again by later observations.
|
||||
#[tokio::test]
|
||||
async fn observation_timing_excludes_previous_requests_and_background_time() -> Result<()> {
|
||||
let host = HostHarness::start("grpc://127.0.0.1:0").await?;
|
||||
let providers: [Arc<dyn CodeModeSessionProvider>; 2] = [
|
||||
Arc::new(ProcessOwnedCodeModeSessionProvider::with_host_program(
|
||||
codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?,
|
||||
)),
|
||||
Arc::new(GrpcCodeModeSessionProvider::new(host.endpoint)),
|
||||
];
|
||||
for provider in providers {
|
||||
let session = provider
|
||||
.create_session()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let started = session
|
||||
.execute(
|
||||
ExecuteRequest {
|
||||
tool_call_id: "call-1".to_string(),
|
||||
source: "await new Promise(() => {});".to_string(),
|
||||
enabled_tools: Vec::new(),
|
||||
yield_time_ms: Some(/*value*/ 200),
|
||||
max_output_tokens: Some(/*value*/ 1_000),
|
||||
},
|
||||
Arc::new(NoopCodeModeSessionDelegate),
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let cell_id = started.cell_id.clone();
|
||||
let initial = started
|
||||
.initial_response()
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let duration = initial
|
||||
.code_mode_host_duration()
|
||||
.context("missing exec timing")?;
|
||||
assert!(duration >= Duration::from_millis(/*millis*/ 150));
|
||||
let yielded = RuntimeResponse::Yielded {
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: Vec::new(),
|
||||
code_mode_host_duration: Some(duration),
|
||||
};
|
||||
assert_eq!(initial, yielded);
|
||||
|
||||
for _ in 0..2 {
|
||||
sleep(Duration::from_millis(/*millis*/ 300)).await;
|
||||
let observed = Instant::now();
|
||||
let outcome = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: cell_id.clone(),
|
||||
yield_time_ms: 50,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let duration = outcome
|
||||
.code_mode_host_duration()
|
||||
.context("missing wait timing")?;
|
||||
assert!(duration >= Duration::from_millis(/*millis*/ 40));
|
||||
assert!(
|
||||
duration <= observed.elapsed(),
|
||||
"wait included time before its request: {duration:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
outcome,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Yielded {
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: Vec::new(),
|
||||
code_mode_host_duration: Some(duration),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
let observed = Instant::now();
|
||||
let terminated = session
|
||||
.terminate(cell_id.clone().into())
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let duration = terminated
|
||||
.code_mode_host_duration()
|
||||
.context("missing termination timing")?;
|
||||
assert!(duration <= observed.elapsed());
|
||||
assert_eq!(
|
||||
terminated,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Terminated {
|
||||
cell_id: cell_id.clone(),
|
||||
content_items: Vec::new(),
|
||||
code_mode_host_duration: Some(duration),
|
||||
})
|
||||
);
|
||||
|
||||
let observed = Instant::now();
|
||||
let missing = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: cell_id.clone(),
|
||||
yield_time_ms: 50,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let duration = missing
|
||||
.code_mode_host_duration()
|
||||
.context("missing absent-cell timing")?;
|
||||
assert!(duration <= observed.elapsed());
|
||||
assert_eq!(
|
||||
missing,
|
||||
WaitOutcome::MissingCell(RuntimeResponse::Result {
|
||||
result_buffered_for: Duration::ZERO,
|
||||
error_text: Some(format!("exec cell {cell_id} not found")),
|
||||
cell_id,
|
||||
content_items: Vec::new(),
|
||||
code_mode_host_duration: Some(duration),
|
||||
})
|
||||
);
|
||||
session.shutdown().await.map_err(anyhow::Error::msg)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
186
codex-rs/code-mode-host/tests/settled.rs
Normal file
186
codex-rs/code-mode-host/tests/settled.rs
Normal file
@@ -0,0 +1,186 @@
|
||||
//! Verifies partial settlement output survives waits on both host transports.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use codex_code_mode::CellId;
|
||||
use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::CodeModeSessionProvider;
|
||||
use codex_code_mode::CodeModeToolKind;
|
||||
use codex_code_mode::ExecuteRequest;
|
||||
use codex_code_mode::FunctionCallOutputContentItem;
|
||||
use codex_code_mode::GrpcCodeModeSessionProvider;
|
||||
use codex_code_mode::NotificationFuture;
|
||||
use codex_code_mode::ProcessOwnedCodeModeSessionProvider;
|
||||
use codex_code_mode::RuntimeResponse;
|
||||
use codex_code_mode::ToolDefinition;
|
||||
use codex_code_mode::ToolInvocationFuture;
|
||||
use codex_code_mode::WaitOutcome;
|
||||
use codex_code_mode::WaitRequest;
|
||||
use codex_protocol::ToolName;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Notify;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[path = "support/host.rs"]
|
||||
mod host;
|
||||
|
||||
#[derive(Default)]
|
||||
struct SlowDelegate {
|
||||
release: Notify,
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for SlowDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
_invocation: CodeModeNestedToolCall,
|
||||
cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
tokio::select! {
|
||||
_ = self.release.notified() => Ok(json!("slow")),
|
||||
_ = cancellation.cancelled() => Err("cancelled".to_string()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
_call_id: String,
|
||||
_cell_id: CellId,
|
||||
_text: String,
|
||||
_cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
fn cell_closed(&self, _cell_id: &CellId) {}
|
||||
}
|
||||
|
||||
#[allow(clippy::expect_used)]
|
||||
async fn assert_partial_results(provider: &dyn CodeModeSessionProvider) {
|
||||
for consumer in [
|
||||
"for await (const result of as_settled(promises)) text(result);",
|
||||
"await stream_settled(promises, text);",
|
||||
] {
|
||||
let delegate = Arc::new(SlowDelegate::default());
|
||||
let session = provider.create_session().await.expect("create session");
|
||||
let started = session
|
||||
.execute(ExecuteRequest {
|
||||
tool_call_id: "settled".to_string(),
|
||||
enabled_tools: vec![ToolDefinition {
|
||||
name: "slow".to_string(),
|
||||
tool_name: ToolName::plain("slow"),
|
||||
description: String::new(),
|
||||
kind: CodeModeToolKind::Function,
|
||||
input_schema: None,
|
||||
input_schema_max_bytes: None,
|
||||
output_schema: None,
|
||||
}],
|
||||
source: format!(
|
||||
r#"const promises = [tools.slow({{}}), Promise.resolve("fast"), Promise.reject("failed")];
|
||||
{consumer}"#
|
||||
),
|
||||
yield_time_ms: Some(/*value*/ 10),
|
||||
max_output_tokens: None,
|
||||
}, delegate.clone(), /*preempt*/ None)
|
||||
.await
|
||||
.expect("start cell");
|
||||
let cell_id = started.cell_id.clone();
|
||||
let mut response = started.initial_response().await.expect("initial response");
|
||||
let mut partial = Vec::new();
|
||||
loop {
|
||||
let RuntimeResponse::Yielded { content_items, .. } = response else {
|
||||
panic!("cell completed before the slow tool was released: {response:?}");
|
||||
};
|
||||
partial.extend(content_items.into_iter().map(|item| {
|
||||
let FunctionCallOutputContentItem::InputText { text } = item else {
|
||||
panic!("unexpected output: {item:?}");
|
||||
};
|
||||
serde_json::from_str::<serde_json::Value>(&text).expect("JSON output")
|
||||
}));
|
||||
if partial.len() >= 2 {
|
||||
break;
|
||||
}
|
||||
let WaitOutcome::LiveCell(next) = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: cell_id.clone(),
|
||||
yield_time_ms: 10,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("wait for partial results")
|
||||
else {
|
||||
panic!("cell disappeared while the slow tool was pending");
|
||||
};
|
||||
response = next;
|
||||
}
|
||||
assert_eq!(
|
||||
partial,
|
||||
[
|
||||
json!({"index": 1, "status": "fulfilled", "value": "fast"}),
|
||||
json!({"index": 2, "status": "rejected", "reason": "failed"}),
|
||||
]
|
||||
);
|
||||
|
||||
delegate.release.notify_one();
|
||||
let completed = session
|
||||
.wait(
|
||||
WaitRequest {
|
||||
cell_id: cell_id.clone(),
|
||||
yield_time_ms: 5_000,
|
||||
max_output_tokens: None,
|
||||
},
|
||||
/*preempt*/ None,
|
||||
)
|
||||
.await
|
||||
.expect("wait for completion");
|
||||
assert_eq!(
|
||||
completed,
|
||||
WaitOutcome::LiveCell(RuntimeResponse::Result {
|
||||
code_mode_host_duration: completed.code_mode_host_duration(),
|
||||
cell_id,
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: json!({"index": 0, "status": "fulfilled", "value": "slow"}).to_string(),
|
||||
}],
|
||||
result_buffered_for: completed
|
||||
.result_buffered_for()
|
||||
.expect("completed result includes buffering duration"),
|
||||
error_text: None,
|
||||
})
|
||||
);
|
||||
session.shutdown().await.expect("shutdown session");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settled_results_stream_over_stdio() {
|
||||
let provider = ProcessOwnedCodeModeSessionProvider::with_host_program(
|
||||
codex_utils_cargo_bin::cargo_bin("codex-code-mode-host").expect("host binary"),
|
||||
);
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 20),
|
||||
assert_partial_results(&provider),
|
||||
)
|
||||
.await
|
||||
.expect("settlement streaming timed out");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settled_results_stream_over_grpc() {
|
||||
let host = host::HostHarness::start("grpc://127.0.0.1:0")
|
||||
.await
|
||||
.expect("start gRPC host");
|
||||
let provider = GrpcCodeModeSessionProvider::new(host.endpoint);
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 20),
|
||||
assert_partial_results(&provider),
|
||||
)
|
||||
.await
|
||||
.expect("settlement streaming timed out");
|
||||
}
|
||||
1185
codex-rs/code-mode-host/tests/stdio.rs
Normal file
1185
codex-rs/code-mode-host/tests/stdio.rs
Normal file
File diff suppressed because it is too large
Load Diff
53
codex-rs/code-mode-host/tests/support/host.rs
Normal file
53
codex-rs/code-mode-host/tests/support/host.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::process::Child;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
pub(crate) struct HostHarness {
|
||||
pub(crate) _child: Child,
|
||||
pub(crate) endpoint: String,
|
||||
}
|
||||
|
||||
impl HostHarness {
|
||||
pub(crate) async fn start(listen_url: &str) -> Result<Self> {
|
||||
let host_program = codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?;
|
||||
let mut child = Command::new(host_program)
|
||||
.args(["--listen", listen_url])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(/*kill_on_drop*/ true)
|
||||
.spawn()
|
||||
.context("failed to start code-mode host")?;
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.context("code-mode host stdout was not captured")?;
|
||||
let endpoint = timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
BufReader::new(stdout).lines().next_line(),
|
||||
)
|
||||
.await
|
||||
.context("timed out waiting for code-mode host endpoint")??
|
||||
.context("code-mode host exited before publishing its endpoint")?;
|
||||
let expected_scheme = if listen_url.starts_with("grpc://") {
|
||||
"http"
|
||||
} else {
|
||||
"ws"
|
||||
};
|
||||
if !endpoint.starts_with(&format!("{expected_scheme}://127.0.0.1:")) {
|
||||
anyhow::bail!("unexpected code-mode host endpoint `{endpoint}`");
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
_child: child,
|
||||
endpoint,
|
||||
})
|
||||
}
|
||||
}
|
||||
49
codex-rs/code-mode-host/tests/support/large_tool_delegate.rs
Normal file
49
codex-rs/code-mode-host/tests/support/large_tool_delegate.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use codex_code_mode::CellId;
|
||||
use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::NotificationFuture;
|
||||
use codex_code_mode::ToolInvocationFuture;
|
||||
use codex_protocol::ToolName;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(crate) struct LargeToolResultDelegate {
|
||||
pub(crate) started: Semaphore,
|
||||
pub(crate) release: Semaphore,
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for LargeToolResultDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
invocation: CodeModeNestedToolCall,
|
||||
_cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
Box::pin(async move {
|
||||
if invocation.tool_name == ToolName::plain("fast") {
|
||||
return Ok(json!({ "value": "isolated" }));
|
||||
}
|
||||
assert_eq!(invocation.tool_name, ToolName::plain("large"));
|
||||
self.started.add_permits(/*n*/ 1);
|
||||
self.release
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|_| "large tool release closed".to_string())?
|
||||
.forget();
|
||||
Ok(json!({ "value": "x".repeat(8 * 1024 * 1024) }))
|
||||
})
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
_call_id: String,
|
||||
_cell_id: CellId,
|
||||
_text: String,
|
||||
_cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
fn cell_closed(&self, _cell_id: &CellId) {}
|
||||
}
|
||||
59
codex-rs/code-mode-host/tests/support/recording_delegate.rs
Normal file
59
codex-rs/code-mode-host/tests/support/recording_delegate.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use codex_code_mode::CellId;
|
||||
use codex_code_mode::CodeModeNestedToolCall;
|
||||
use codex_code_mode::CodeModeSessionDelegate;
|
||||
use codex_code_mode::NotificationFuture;
|
||||
use codex_code_mode::ToolInvocationFuture;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Notify;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RecordingDelegate {
|
||||
pub(crate) invocations: Mutex<Vec<CodeModeNestedToolCall>>,
|
||||
pub(crate) notifications: Mutex<Vec<(String, CellId, String)>>,
|
||||
pub(crate) notification_delivered: Notify,
|
||||
pub(crate) closed_cells: Mutex<Vec<CellId>>,
|
||||
}
|
||||
|
||||
impl CodeModeSessionDelegate for RecordingDelegate {
|
||||
fn invoke_tool<'a>(
|
||||
&'a self,
|
||||
invocation: CodeModeNestedToolCall,
|
||||
_cancellation: CancellationToken,
|
||||
) -> ToolInvocationFuture<'a> {
|
||||
self.invocations
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push(invocation);
|
||||
Box::pin(async { Ok(json!({ "value": "output" })) })
|
||||
}
|
||||
|
||||
fn notify<'a>(
|
||||
&'a self,
|
||||
call_id: String,
|
||||
cell_id: CellId,
|
||||
text: String,
|
||||
_cancellation: CancellationToken,
|
||||
) -> NotificationFuture<'a> {
|
||||
self.notifications
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push((call_id, cell_id, text));
|
||||
self.notification_delivered.notify_one();
|
||||
Box::pin(async { Ok(()) })
|
||||
}
|
||||
|
||||
fn cell_closed(&self, cell_id: &CellId) {
|
||||
self.closed_cells
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.push(cell_id.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cell_id(value: &str) -> CellId {
|
||||
CellId::new(value.to_string())
|
||||
}
|
||||
506
codex-rs/code-mode-host/tests/ui_plugin_wire.rs
Normal file
506
codex-rs/code-mode-host/tests/ui_plugin_wire.rs
Normal file
@@ -0,0 +1,506 @@
|
||||
//! Exercises the child protocol without the parent supervisor or session APIs.
|
||||
|
||||
use anyhow::Context;
|
||||
use codex_plugin_host::PluginProcess;
|
||||
use codex_plugin_host::protocol::MAX_PENDING_PROMISES;
|
||||
use codex_plugin_host::protocol::MAX_SCRIPT_ERROR_BYTES;
|
||||
use codex_plugin_host::protocol::Packet;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[tokio::test]
|
||||
async fn child_initializes_invokes_and_closes_an_isolate() -> anyhow::Result<()> {
|
||||
let program = codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let source = format!("/*{}*/ export default () => 'x'.repeat(5000);", "p".repeat(40 * 1024));
|
||||
for (message, expected) in [
|
||||
(json!({"type": "initialize", "source": source}), json!({"type": "initialized"})),
|
||||
(json!({"type": "dispatch", "id": 0, "export": "default", "returnMode": "maybeAsync"}), json!({"type": "reply", "id": 0, "value": "x".repeat(5000)})),
|
||||
(json!({"type": "close"}), json!({"type": "closed"})),
|
||||
] {
|
||||
send(&mut child, /*instance*/ 7, message).await?;
|
||||
assert_eq!(receive(&mut child).await?, (7, expected));
|
||||
}
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
async fn send(
|
||||
child: &mut PluginProcess,
|
||||
instance: u64,
|
||||
message: serde_json::Value,
|
||||
) -> anyhow::Result<()> {
|
||||
let (input, _) = child.pipes();
|
||||
input
|
||||
.send(serde_json::to_vec(&Packet { instance, message })?.into())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(child: &mut PluginProcess) -> anyhow::Result<(u64, serde_json::Value)> {
|
||||
let (_, output) = child.pipes();
|
||||
let packet: Packet<serde_json::Value> = serde_json::from_slice(
|
||||
&output
|
||||
.next()
|
||||
.await
|
||||
.context("plugin child closed stdout")??,
|
||||
)?;
|
||||
Ok((packet.instance, packet.message))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn promise_errors_close_the_isolate_in_both_return_modes() -> anyhow::Result<()> {
|
||||
let program = codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let source = r#"
|
||||
export function run() {
|
||||
const promise = Promise.reject(Error('tracked failure'));
|
||||
promise.catch(() => {});
|
||||
return promise;
|
||||
}
|
||||
"#;
|
||||
for (instance, return_mode, code) in [
|
||||
(1, "sync", "invalid_result"),
|
||||
(2, "maybeAsync", "execution_failed"),
|
||||
] {
|
||||
send(
|
||||
&mut child,
|
||||
instance,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(instance, json!({"type": "initialized"}))
|
||||
);
|
||||
send(
|
||||
&mut child,
|
||||
instance,
|
||||
json!({"type": "dispatch", "id": 0, "export": "run", "returnMode": return_mode}),
|
||||
)
|
||||
.await?;
|
||||
let (id, error) = receive(&mut child).await?;
|
||||
assert_eq!(
|
||||
(id, error["type"].as_str(), error["code"].as_str()),
|
||||
(instance, Some("error"), Some(code))
|
||||
);
|
||||
if return_mode == "maybeAsync" {
|
||||
assert!(
|
||||
error["scriptError"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|diagnostic| diagnostic.contains("tracked failure"))
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(instance, json!({"type": "closed"}))
|
||||
);
|
||||
}
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_closes_an_isolate_with_pending_work() -> anyhow::Result<()> {
|
||||
let program = codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let source = "export function run() { return new Promise(() => {}); }";
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(1, json!({"type": "initialized"}))
|
||||
);
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "dispatch", "id": 0, "export": "run", "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(1, json!({"type": "pending", "id": 0}))
|
||||
);
|
||||
send(&mut child, /*instance*/ 1, json!({"type": "close"})).await?;
|
||||
assert_eq!(receive(&mut child).await?, (1, json!({"type": "closed"})));
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sync_dispatch_settles_pending_invocations() -> anyhow::Result<()> {
|
||||
let program = codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let source = r#"
|
||||
const resolvers = [];
|
||||
export function wait() { return new Promise(resolve => resolvers.push(resolve)); }
|
||||
export function finish() {
|
||||
for (const resolve of resolvers) resolve('done');
|
||||
return 'finished';
|
||||
}
|
||||
"#;
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(1, json!({"type": "initialized"}))
|
||||
);
|
||||
let sync_id = MAX_PENDING_PROMISES as u64;
|
||||
for id in 0..sync_id {
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "dispatch", "id": id, "export": "wait", "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(1, json!({"type": "pending", "id": id}))
|
||||
);
|
||||
}
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "dispatch", "id": sync_id, "export": "finish", "returnMode": "sync"}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(
|
||||
1,
|
||||
json!({"type": "reply", "id": sync_id, "value": "finished"})
|
||||
)
|
||||
);
|
||||
let mut resolved = Vec::new();
|
||||
for _ in 0..sync_id {
|
||||
let (instance, reply) = receive(&mut child).await?;
|
||||
let id = reply["id"].as_u64().unwrap();
|
||||
assert_eq!(
|
||||
(instance, reply),
|
||||
(1, json!({"type": "reply", "id": id, "value": "done"}))
|
||||
);
|
||||
resolved.push(id);
|
||||
}
|
||||
resolved.sort_unstable();
|
||||
assert_eq!(resolved, (0..sync_id).collect::<Vec<_>>());
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn syntax_and_execution_failures_preserve_bounded_script_errors() -> anyhow::Result<()> {
|
||||
let program = codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 1,
|
||||
json!({"type": "initialize", "source": "export default => ;"}),
|
||||
)
|
||||
.await?;
|
||||
let (id, error) = receive(&mut child).await?;
|
||||
assert_eq!(id, 1);
|
||||
assert_eq!(error["code"], "invalid_program");
|
||||
assert_eq!(error["scriptError"]["line"], 1);
|
||||
assert!(error["scriptError"]["column"].is_number());
|
||||
assert_eq!(error["scriptError"]["truncated"], false);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(1, json!({"type": "closed"}))
|
||||
);
|
||||
|
||||
let source = format!(
|
||||
r#"export function fail() {{ throw Error('xxx\u001b[31m' + 'x'.repeat({MAX_SCRIPT_ERROR_BYTES})); }}"#
|
||||
);
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 2,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(2, json!({"type": "initialized"}))
|
||||
);
|
||||
send(
|
||||
&mut child,
|
||||
/*instance*/ 2,
|
||||
json!({"type": "dispatch", "id": 0, "export": "fail", "returnMode": "sync"}),
|
||||
)
|
||||
.await?;
|
||||
let (id, error) = receive(&mut child).await?;
|
||||
assert_eq!(id, 2);
|
||||
let message = error["scriptError"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("Error: xxx\u{001b}[31m"));
|
||||
assert!(message.len() <= MAX_SCRIPT_ERROR_BYTES);
|
||||
assert_eq!(error["scriptError"]["truncated"], true);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(2, json!({"type": "closed"}))
|
||||
);
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loading_restrictions_close_the_isolate() -> anyhow::Result<()> {
|
||||
let program = codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let cases = [
|
||||
(
|
||||
"import 'forbidden';",
|
||||
"invalid_program",
|
||||
"module imports are unavailable",
|
||||
),
|
||||
(
|
||||
"await import('forbidden');",
|
||||
"execution_failed",
|
||||
"Not supported",
|
||||
),
|
||||
("eval('1 + 1');", "execution_failed", "EvalError"),
|
||||
(
|
||||
"new Function('return 1')();",
|
||||
"execution_failed",
|
||||
"EvalError",
|
||||
),
|
||||
(
|
||||
"WebAssembly;",
|
||||
"execution_failed",
|
||||
"WebAssembly is not defined",
|
||||
),
|
||||
(
|
||||
"new ArrayBuffer(1);",
|
||||
"execution_failed",
|
||||
"ArrayBuffer is not defined",
|
||||
),
|
||||
(
|
||||
"new Uint8Array(1);",
|
||||
"execution_failed",
|
||||
"Uint8Array is not defined",
|
||||
),
|
||||
];
|
||||
for (instance, (source, code, diagnostic)) in (1_u64..).zip(cases) {
|
||||
send(
|
||||
&mut child,
|
||||
instance,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
let (id, error) = receive(&mut child)
|
||||
.await
|
||||
.with_context(|| format!("loading {source}"))?;
|
||||
assert_eq!(
|
||||
(id, error["type"].as_str(), error["code"].as_str()),
|
||||
(instance, Some("error"), Some(code)),
|
||||
"{source}"
|
||||
);
|
||||
assert!(
|
||||
error["scriptError"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|message| message.contains(diagnostic)),
|
||||
"{source}: {error}"
|
||||
);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(instance, json!({"type": "closed"})),
|
||||
"{source}"
|
||||
);
|
||||
}
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
let exit = child.close().await?;
|
||||
result.with_context(|| {
|
||||
format!(
|
||||
"plugin helper exited with {}; stderr: {:?}",
|
||||
exit.status,
|
||||
String::from_utf8_lossy(&exit.stderr_tail)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn isolate_failures_do_not_affect_healthy_peers() -> anyhow::Result<()> {
|
||||
const HEALTHY: u64 = 1;
|
||||
const REJECTING: u64 = 2;
|
||||
const LOOPING: u64 = 3;
|
||||
|
||||
let program = codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let source = r#"
|
||||
let n = 0;
|
||||
export function count() { return String(++n); }
|
||||
export function caught() {
|
||||
const p = Promise.reject('handled');
|
||||
p.catch(() => {});
|
||||
return 'ok';
|
||||
}
|
||||
export function detached() {
|
||||
Promise.resolve().then(() => { throw Error('detached failure'); });
|
||||
return 'ok';
|
||||
}
|
||||
"#;
|
||||
for instance in [HEALTHY, REJECTING] {
|
||||
send(
|
||||
&mut child,
|
||||
instance,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(instance, json!({"type": "initialized"}))
|
||||
);
|
||||
}
|
||||
for (instance, export, expected) in [
|
||||
(HEALTHY, "count", "1"),
|
||||
(HEALTHY, "count", "2"),
|
||||
(REJECTING, "caught", "ok"),
|
||||
(REJECTING, "count", "1"),
|
||||
] {
|
||||
send(
|
||||
&mut child,
|
||||
instance,
|
||||
json!({"type": "dispatch", "id": 0, "export": export, "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(
|
||||
instance,
|
||||
json!({"type": "reply", "id": 0, "value": expected})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
send(
|
||||
&mut child,
|
||||
REJECTING,
|
||||
json!({"type": "dispatch", "id": 0, "export": "detached", "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
let (id, error) = receive(&mut child).await?;
|
||||
assert_eq!(id, REJECTING);
|
||||
assert_eq!(error["code"], "execution_failed");
|
||||
assert!(
|
||||
error["scriptError"]["message"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("detached failure")
|
||||
);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(REJECTING, json!({"type": "closed"}))
|
||||
);
|
||||
|
||||
let source = "export function loop() { while (true) {} }";
|
||||
send(
|
||||
&mut child,
|
||||
LOOPING,
|
||||
json!({"type": "initialize", "source": source}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(LOOPING, json!({"type": "initialized"}))
|
||||
);
|
||||
send(
|
||||
&mut child,
|
||||
LOOPING,
|
||||
json!({"type": "dispatch", "id": 0, "export": "loop", "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
send(
|
||||
&mut child,
|
||||
HEALTHY,
|
||||
json!({"type": "dispatch", "id": 0, "export": "count", "returnMode": "maybeAsync"}),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(
|
||||
LOOPING,
|
||||
json!({"type": "error", "code": "execution_timed_out", "scriptError": null})
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(LOOPING, json!({"type": "closed"}))
|
||||
);
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(HEALTHY, json!({"type": "reply", "id": 0, "value": "3"}))
|
||||
);
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closed_instance_can_be_replaced_at_capacity() -> anyhow::Result<()> {
|
||||
let program = codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?;
|
||||
let mut child =
|
||||
PluginProcess::spawn(&program, &tokio_util::sync::CancellationToken::new()).await?;
|
||||
let result = async {
|
||||
let limit = codex_plugin_host::MAX_INSTANCES as u64;
|
||||
let initialize = json!({"type":"initialize", "source":"export default () => 'ok'"});
|
||||
for instance in 0..limit {
|
||||
send(&mut child, instance, initialize.clone()).await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(instance, json!({"type":"initialized"}))
|
||||
);
|
||||
}
|
||||
send(&mut child, /*instance*/ 0, json!({"type":"close"})).await?;
|
||||
assert_eq!(receive(&mut child).await?, (0, json!({"type":"closed"})));
|
||||
send(&mut child, limit, initialize).await?;
|
||||
assert_eq!(
|
||||
receive(&mut child).await?,
|
||||
(limit, json!({"type":"initialized"}))
|
||||
);
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
child.close().await?;
|
||||
result
|
||||
}
|
||||
28
codex-rs/code-mode-host/tests/ui_sandbox.rs
Normal file
28
codex-rs/code-mode-host/tests/ui_sandbox.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
#[test]
|
||||
fn plugin_arguments_are_parsed_before_startup() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let program = codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?;
|
||||
for arguments in [
|
||||
["--help", "--codex-ui-plugin-process"],
|
||||
["--codex-ui-plugin-process", "--help"],
|
||||
] {
|
||||
let output = codex_utils_process::background_command(&program)
|
||||
.args(arguments)
|
||||
.output()?;
|
||||
assert!(output.status.success());
|
||||
assert!(String::from_utf8(output.stdout)?.contains("Usage:"));
|
||||
}
|
||||
for arguments in [
|
||||
["--unknown", "--codex-ui-plugin-process"],
|
||||
["--codex-ui-plugin-process", "--unknown"],
|
||||
["--listen=stdio", "--codex-ui-plugin-process"],
|
||||
["--codex-ui-plugin-process", "--listen=stdio"],
|
||||
] {
|
||||
let output = codex_utils_process::background_command(&program)
|
||||
.args(arguments)
|
||||
.output()?;
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
assert!(String::from_utf8(output.stderr)?.contains("error:"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user