code-mode: add deterministic transport harness

This commit is contained in:
Channing Conger
2026-06-23 04:21:41 +00:00
parent 3750bce25c
commit a257556d88
6 changed files with 611 additions and 0 deletions
+11
View File
@@ -2525,6 +2525,17 @@ dependencies = [
"tokio-util",
]
[[package]]
name = "codex-code-mode-protocol-test-support"
version = "0.0.0"
dependencies = [
"codex-code-mode-protocol",
"pretty_assertions",
"serde",
"serde_json",
"tokio",
]
[[package]]
name = "codex-collaboration-mode-templates"
version = "0.0.0"
+2
View File
@@ -23,6 +23,7 @@ members = [
"code-mode",
"code-mode-host",
"code-mode-protocol",
"code-mode-protocol/tests/common",
"codex-home",
"cloud-config",
"cloud-tasks",
@@ -161,6 +162,7 @@ codex-cloud-tasks-client = { path = "cloud-tasks-client" }
codex-cloud-tasks-mock-client = { path = "cloud-tasks-mock-client" }
codex-code-mode = { path = "code-mode" }
codex-code-mode-protocol = { path = "code-mode-protocol" }
codex-code-mode-protocol-test-support = { path = "code-mode-protocol/tests/common" }
codex-home = { path = "codex-home" }
codex-config = { path = "config" }
codex-connectors = { path = "connectors" }
@@ -0,0 +1,7 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "common",
crate_name = "codex_code_mode_protocol_test_support",
crate_srcs = glob(["*.rs"]),
)
@@ -0,0 +1,22 @@
[package]
name = "codex-code-mode-protocol-test-support"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
doctest = false
path = "lib.rs"
[lints]
workspace = true
[dependencies]
codex-code-mode-protocol = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["sync"] }
[dev-dependencies]
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
@@ -0,0 +1,264 @@
use std::error::Error;
use std::fmt;
use std::marker::PhantomData;
use codex_code_mode_protocol::host::ClientToHost;
use codex_code_mode_protocol::host::HostToClient;
use serde::Serialize;
use serde::de::DeserializeOwned;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
/// The client side of a deterministic in-memory host connection.
pub type ClientEndpoint = Endpoint<ClientToHost, HostToClient>;
/// The host side of a deterministic in-memory host connection.
pub type HostEndpoint = Endpoint<HostToClient, ClientToHost>;
/// A typed endpoint whose outbound and inbound frames are controlled separately.
pub struct Endpoint<Outbound, Inbound> {
outbound: mpsc::UnboundedSender<Vec<u8>>,
inbound: mpsc::UnboundedReceiver<Delivery>,
received: mpsc::UnboundedSender<ReceivedFrameData>,
message_types: PhantomData<fn(Outbound) -> Inbound>,
}
impl<Outbound, Inbound> Endpoint<Outbound, Inbound>
where
Outbound: Serialize,
Inbound: DeserializeOwned,
{
/// Queues one encoded frame for the controller to inspect and deliver.
pub fn send(&self, message: &Outbound) -> Result<(), TransportError> {
let frame = serde_json::to_vec(message).map_err(TransportError::Encode)?;
self.outbound
.send(frame)
.map_err(|_| TransportError::WriteClosed)
}
/// Receives one controller-released frame, or `None` after orderly closure.
pub async fn receive(&mut self) -> Result<Option<Inbound>, TransportError> {
let Some(delivery) = self.inbound.recv().await else {
return Ok(None);
};
let frame = match delivery {
Delivery::Frame(frame) => frame,
Delivery::ReadFailure(message) => {
return Err(TransportError::ReadFailed(message));
}
};
let (release, released) = oneshot::channel();
self.received
.send(ReceivedFrameData {
bytes: frame.clone(),
release,
})
.map_err(|_| TransportError::ControllerClosed)?;
released
.await
.map_err(|_| TransportError::ControllerClosed)?;
serde_json::from_slice(&frame)
.map(Some)
.map_err(TransportError::Decode)
}
}
/// Controls delivery and fault injection for both directions of a connection.
pub struct ConnectionController {
pub client_to_host: DirectionController,
pub host_to_client: DirectionController,
}
/// Controls one ordered direction of an in-memory connection.
pub struct DirectionController {
pending: mpsc::UnboundedReceiver<Vec<u8>>,
delivery: Option<mpsc::UnboundedSender<Delivery>>,
received: mpsc::UnboundedReceiver<ReceivedFrameData>,
}
impl DirectionController {
/// Waits until the sender has queued its next frame.
pub async fn next_pending_frame(&mut self) -> Option<PendingFrame> {
self.pending.recv().await.map(PendingFrame)
}
/// Delivers a previously observed frame to the receiving endpoint.
pub fn deliver(&self, frame: PendingFrame) -> Result<(), ControlError> {
self.deliver_bytes(frame.0)
}
/// Injects arbitrary bytes as one complete in-memory frame.
pub fn deliver_bytes(&self, bytes: Vec<u8>) -> Result<(), ControlError> {
self.delivery
.as_ref()
.ok_or(ControlError::DirectionClosed)?
.send(Delivery::Frame(bytes))
.map_err(|_| ControlError::DirectionClosed)
}
/// Waits until the receiver has dequeued a frame, then holds its decode step.
pub async fn next_received_frame(&mut self) -> Option<ReceivedFrame> {
self.received.recv().await.map(|frame| ReceivedFrame {
bytes: frame.bytes,
release: frame.release,
})
}
/// Makes the receiving endpoint's next read fail with the supplied message.
pub fn inject_read_failure(&self, message: impl Into<String>) -> Result<(), ControlError> {
self.delivery
.as_ref()
.ok_or(ControlError::DirectionClosed)?
.send(Delivery::ReadFailure(message.into()))
.map_err(|_| ControlError::DirectionClosed)
}
/// Rejects new sends while preserving frames that were already queued.
pub fn fail_writes(&mut self) {
self.pending.close();
}
/// Closes this direction so new sends fail and the receiver observes EOF.
pub fn close(&mut self) {
self.pending.close();
self.delivery = None;
}
}
/// A frame queued by an endpoint but not yet delivered by the controller.
pub struct PendingFrame(Vec<u8>);
impl PendingFrame {
/// Returns the encoded bytes without consuming the pending frame.
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
/// Consumes the pending frame and returns its encoded bytes.
pub fn into_bytes(self) -> Vec<u8> {
self.0
}
}
/// A delivered frame paused after receiver dequeue and before JSON decoding.
pub struct ReceivedFrame {
bytes: Vec<u8>,
release: oneshot::Sender<()>,
}
impl ReceivedFrame {
/// Returns the delivered bytes without releasing the receiver.
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
/// Allows the receiving endpoint to decode and return the frame.
pub fn release(self) -> Result<(), ControlError> {
self.release
.send(())
.map_err(|_| ControlError::ReceiverClosed)
}
}
struct ReceivedFrameData {
bytes: Vec<u8>,
release: oneshot::Sender<()>,
}
enum Delivery {
Frame(Vec<u8>),
ReadFailure(String),
}
/// Endpoint failures surfaced by the deterministic transport.
#[derive(Debug)]
pub enum TransportError {
Encode(serde_json::Error),
Decode(serde_json::Error),
WriteClosed,
ReadFailed(String),
ControllerClosed,
}
impl fmt::Display for TransportError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Encode(error) => write!(formatter, "failed to encode frame: {error}"),
Self::Decode(error) => write!(formatter, "failed to decode frame: {error}"),
Self::WriteClosed => formatter.write_str("transport write direction is closed"),
Self::ReadFailed(message) => write!(formatter, "transport read failed: {message}"),
Self::ControllerClosed => formatter.write_str("transport controller is closed"),
}
}
}
impl Error for TransportError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Encode(error) | Self::Decode(error) => Some(error),
Self::WriteClosed | Self::ReadFailed(_) | Self::ControllerClosed => None,
}
}
}
/// Controller failures caused by a closed direction or receiver.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ControlError {
DirectionClosed,
ReceiverClosed,
}
impl fmt::Display for ControlError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::DirectionClosed => formatter.write_str("transport direction is closed"),
Self::ReceiverClosed => formatter.write_str("transport receiver is closed"),
}
}
}
impl Error for ControlError {}
/// Creates a typed connection and a controller that gates every frame.
pub fn in_memory_connection() -> (ClientEndpoint, HostEndpoint, ConnectionController) {
let (client_outbound, client_pending) = mpsc::unbounded_channel();
let (host_delivery, host_inbound) = mpsc::unbounded_channel();
let (host_received, client_to_host_received) = mpsc::unbounded_channel();
let (host_outbound, host_pending) = mpsc::unbounded_channel();
let (client_delivery, client_inbound) = mpsc::unbounded_channel();
let (client_received, host_to_client_received) = mpsc::unbounded_channel();
let client = Endpoint {
outbound: client_outbound,
inbound: client_inbound,
received: client_received,
message_types: PhantomData,
};
let host = Endpoint {
outbound: host_outbound,
inbound: host_inbound,
received: host_received,
message_types: PhantomData,
};
let controller = ConnectionController {
client_to_host: DirectionController {
pending: client_pending,
delivery: Some(host_delivery),
received: client_to_host_received,
},
host_to_client: DirectionController {
pending: host_pending,
delivery: Some(client_delivery),
received: host_to_client_received,
},
};
(client, host, controller)
}
#[cfg(test)]
#[path = "transport_tests.rs"]
mod tests;
@@ -0,0 +1,305 @@
use codex_code_mode_protocol::host::CapabilitySet;
use codex_code_mode_protocol::host::ClientHello;
use codex_code_mode_protocol::host::ClientToHost;
use codex_code_mode_protocol::host::HostHello;
use codex_code_mode_protocol::host::HostToClient;
use codex_code_mode_protocol::host::ProtocolVersion;
use codex_code_mode_protocol::host::SessionId;
use codex_code_mode_protocol::host::SupportedProtocolVersions;
use pretty_assertions::assert_eq;
use serde_json::json;
use super::DirectionController;
use super::TransportError;
use super::in_memory_connection;
fn session_id() -> SessionId {
SessionId::new("session-1").expect("valid session ID")
}
fn supported_versions() -> SupportedProtocolVersions {
SupportedProtocolVersions::try_new([ProtocolVersion::V1]).expect("supported version")
}
async fn deliver_next_frame(direction: &mut DirectionController) {
let pending = direction.next_pending_frame().await.expect("pending frame");
direction.deliver(pending).expect("deliver frame");
direction
.next_received_frame()
.await
.expect("receiver progress")
.release()
.expect("release receiver");
}
#[tokio::test]
async fn handshake_and_session_lifecycle_run_end_to_end() {
let (mut client, mut host, mut controller) = in_memory_connection();
let client_hello = ClientToHost::ClientHello(
ClientHello::new(
supported_versions(),
CapabilitySet::empty(),
CapabilitySet::empty(),
)
.expect("valid client hello"),
);
client.send(&client_hello).expect("queue client hello");
let (received, ()) = tokio::join!(
host.receive(),
deliver_next_frame(&mut controller.client_to_host)
);
assert_eq!(received.expect("receive client hello"), Some(client_hello));
let host_hello =
HostToClient::HostHello(HostHello::new(ProtocolVersion::V1, CapabilitySet::empty()));
host.send(&host_hello).expect("queue host hello");
let (received, ()) = tokio::join!(
client.receive(),
deliver_next_frame(&mut controller.host_to_client)
);
assert_eq!(received.expect("receive host hello"), Some(host_hello));
let open = ClientToHost::OpenSession {
session_id: session_id(),
};
client.send(&open).expect("queue session open");
let (received, ()) = tokio::join!(
host.receive(),
deliver_next_frame(&mut controller.client_to_host)
);
assert_eq!(received.expect("receive session open"), Some(open));
let ready = HostToClient::SessionReady {
session_id: session_id(),
};
host.send(&ready).expect("queue session ready");
let (received, ()) = tokio::join!(
client.receive(),
deliver_next_frame(&mut controller.host_to_client)
);
assert_eq!(received.expect("receive session ready"), Some(ready));
let close = ClientToHost::CloseSession {
session_id: session_id(),
};
client.send(&close).expect("queue session close");
let (received, ()) = tokio::join!(
host.receive(),
deliver_next_frame(&mut controller.client_to_host)
);
assert_eq!(received.expect("receive session close"), Some(close));
let closed = HostToClient::SessionClosed {
session_id: session_id(),
};
host.send(&closed).expect("queue session closed");
let (received, ()) = tokio::join!(
client.receive(),
deliver_next_frame(&mut controller.host_to_client)
);
assert_eq!(received.expect("receive session closed"), Some(closed));
}
#[tokio::test]
async fn controller_gates_frames_before_delivery_and_after_receive() {
let (client, mut host, mut controller) = in_memory_connection();
let message = ClientToHost::OpenSession {
session_id: session_id(),
};
client.send(&message).expect("queue client frame");
let pending = controller
.client_to_host
.next_pending_frame()
.await
.expect("pending client frame");
assert_eq!(
serde_json::from_slice::<serde_json::Value>(pending.as_bytes()).expect("valid JSON"),
json!({ "type": "session/open", "sessionId": "session-1" })
);
let receive = tokio::spawn(async move { host.receive().await });
assert!(!receive.is_finished());
controller
.client_to_host
.deliver(pending)
.expect("deliver client frame");
let received = controller
.client_to_host
.next_received_frame()
.await
.expect("receiver progress");
assert_eq!(
serde_json::from_slice::<serde_json::Value>(received.as_bytes()).expect("valid JSON"),
json!({ "type": "session/open", "sessionId": "session-1" })
);
assert!(!receive.is_finished());
received.release().expect("release receiver");
assert_eq!(
receive.await.expect("receive task").expect("receive frame"),
Some(message)
);
}
#[tokio::test]
async fn directions_preserve_order_independently() {
let (mut client, mut host, mut controller) = in_memory_connection();
let open = ClientToHost::OpenSession {
session_id: session_id(),
};
let close = ClientToHost::CloseSession {
session_id: session_id(),
};
let ready = HostToClient::SessionReady {
session_id: session_id(),
};
let closed = HostToClient::SessionClosed {
session_id: session_id(),
};
client.send(&open).expect("queue open");
client.send(&close).expect("queue close");
host.send(&ready).expect("queue ready");
host.send(&closed).expect("queue closed");
let host_receive = tokio::spawn(async move {
[
host.receive().await.expect("receive open"),
host.receive().await.expect("receive close"),
]
});
let client_receive = tokio::spawn(async move {
[
client.receive().await.expect("receive ready"),
client.receive().await.expect("receive closed"),
]
});
for direction in [
&mut controller.client_to_host,
&mut controller.host_to_client,
] {
for _ in 0..2 {
let pending = direction.next_pending_frame().await.expect("pending frame");
direction.deliver(pending).expect("deliver frame");
direction
.next_received_frame()
.await
.expect("receiver progress")
.release()
.expect("release receiver");
}
}
assert_eq!(
host_receive.await.expect("host receive task"),
[Some(open), Some(close)]
);
assert_eq!(
client_receive.await.expect("client receive task"),
[Some(ready), Some(closed)]
);
}
#[tokio::test]
async fn malformed_complete_frame_fails_decode_after_receive_barrier() {
let (_client, mut host, mut controller) = in_memory_connection();
let receive = tokio::spawn(async move { host.receive().await });
controller
.client_to_host
.deliver_bytes(br#"{"type":"session/open","sessionId":"#.to_vec())
.expect("inject malformed frame");
let received = controller
.client_to_host
.next_received_frame()
.await
.expect("receiver progress");
assert!(!receive.is_finished());
received.release().expect("release receiver");
assert!(matches!(
receive.await.expect("receive task"),
Err(TransportError::Decode(_))
));
}
#[tokio::test]
async fn read_and_write_failures_are_injected_per_direction() {
let (client, mut host, mut controller) = in_memory_connection();
controller.client_to_host.fail_writes();
assert!(matches!(
client.send(&ClientToHost::OpenSession {
session_id: session_id(),
}),
Err(TransportError::WriteClosed)
));
controller
.client_to_host
.inject_read_failure("injected read failure")
.expect("inject read failure");
assert!(matches!(
host.receive().await,
Err(TransportError::ReadFailed(message)) if message == "injected read failure"
));
let response = HostToClient::SessionClosed {
session_id: session_id(),
};
host.send(&response)
.expect("opposite direction remains open");
assert!(
controller
.host_to_client
.next_pending_frame()
.await
.is_some()
);
}
#[tokio::test]
async fn closing_one_direction_produces_eof_without_closing_the_other() {
let (mut client, mut host, mut controller) = in_memory_connection();
controller.client_to_host.close();
assert_eq!(host.receive().await.expect("orderly EOF"), None);
assert!(matches!(
client.send(&ClientToHost::CloseSession {
session_id: session_id(),
}),
Err(TransportError::WriteClosed)
));
let response = HostToClient::SessionClosed {
session_id: session_id(),
};
host.send(&response).expect("queue reverse frame");
let pending = controller
.host_to_client
.next_pending_frame()
.await
.expect("pending reverse frame");
controller
.host_to_client
.deliver(pending)
.expect("deliver reverse frame");
let receive = tokio::spawn(async move { client.receive().await });
controller
.host_to_client
.next_received_frame()
.await
.expect("reverse receiver progress")
.release()
.expect("release reverse receiver");
assert_eq!(
receive
.await
.expect("client receive task")
.expect("receive reverse frame"),
Some(response)
);
}