mirror of
https://github.com/openai/codex.git
synced 2026-12-05 01:00:54 +00:00
Harden code mode host I/O
This commit is contained in:
@@ -15,6 +15,59 @@ use codex_code_mode_protocol::host::SessionId;
|
||||
use codex_code_mode_protocol::host::SupportedProtocolVersions;
|
||||
use codex_code_mode_protocol::host::WireResult;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncWrite;
|
||||
|
||||
struct FailWritesAfterFirstFlush<W> {
|
||||
inner: W,
|
||||
fail_writes: bool,
|
||||
}
|
||||
|
||||
impl<W> FailWritesAfterFirstFlush<W> {
|
||||
fn new(inner: W) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
fail_writes: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W> AsyncWrite for FailWritesAfterFirstFlush<W>
|
||||
where
|
||||
W: AsyncWrite + Unpin,
|
||||
{
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
context: &mut Context<'_>,
|
||||
buffer: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
if self.fail_writes {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
"injected writer failure",
|
||||
)));
|
||||
}
|
||||
Pin::new(&mut self.inner).poll_write(context, buffer)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
match Pin::new(&mut self.inner).poll_flush(context) {
|
||||
Poll::Ready(Ok(())) => {
|
||||
self.fail_writes = true;
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_shutdown(context)
|
||||
}
|
||||
}
|
||||
|
||||
use super::run;
|
||||
|
||||
@@ -261,3 +314,45 @@ async fn session_id_cannot_be_reused_after_shutdown() {
|
||||
drop(reader);
|
||||
host.await.expect("host task").expect("host connection");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn writer_failure_terminates_the_connection() {
|
||||
let (host_stream, client_stream) = tokio::io::duplex(/*max_buf_size*/ 1024);
|
||||
let (host_reader, host_writer) = tokio::io::split(host_stream);
|
||||
let (client_reader, client_writer) = tokio::io::split(client_stream);
|
||||
let host = tokio::spawn(run(
|
||||
host_reader,
|
||||
FailWritesAfterFirstFlush::new(host_writer),
|
||||
));
|
||||
let mut reader = FramedReader::new(client_reader);
|
||||
let mut writer = FramedWriter::new(client_writer);
|
||||
|
||||
writer
|
||||
.write(&client_hello([ProtocolVersion::V1], CapabilitySet::empty()))
|
||||
.await
|
||||
.expect("write hello");
|
||||
reader
|
||||
.read::<HostToClient>()
|
||||
.await
|
||||
.expect("read hello")
|
||||
.expect("host hello");
|
||||
|
||||
writer
|
||||
.write(&ClientToHost::Request {
|
||||
id: 1,
|
||||
request: HostRequest::OpenSession {
|
||||
session_id: session_id("session-1"),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("open session");
|
||||
let error = tokio::time::timeout(Duration::from_secs(5), host)
|
||||
.await
|
||||
.expect("host exit timeout")
|
||||
.expect("host task")
|
||||
.expect_err("writer failure should fail the connection");
|
||||
assert!(
|
||||
format!("{error:#}").contains("failed to write code-mode host message"),
|
||||
"unexpected error: {error:#}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
@@ -18,6 +19,7 @@ use codex_code_mode_protocol::host::HostHello;
|
||||
use codex_code_mode_protocol::host::HostRequest;
|
||||
use codex_code_mode_protocol::host::HostResponse;
|
||||
use codex_code_mode_protocol::host::HostToClient;
|
||||
use codex_code_mode_protocol::host::MAX_FRAME_BYTES;
|
||||
use codex_code_mode_protocol::host::ProtocolVersion;
|
||||
use codex_code_mode_protocol::host::RequestId;
|
||||
use codex_code_mode_protocol::host::SessionId;
|
||||
@@ -26,6 +28,7 @@ use codex_code_mode_protocol::host::WireResult;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::AsyncWrite;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::task::TaskTracker;
|
||||
|
||||
use self::delegate::RemoteDelegate;
|
||||
@@ -60,22 +63,75 @@ where
|
||||
closing: AtomicBool::new(false),
|
||||
peer: Arc::clone(&peer),
|
||||
});
|
||||
let (writer_finished_tx, mut writer_finished_rx) = oneshot::channel();
|
||||
let writer_task = tokio::spawn(async move {
|
||||
while let Some(message) = outgoing_rx.recv().await {
|
||||
writer
|
||||
.write(&message)
|
||||
.await
|
||||
.context("failed to write code-mode host message")?;
|
||||
let result = async {
|
||||
while let Some(message) = outgoing_rx.recv().await {
|
||||
let write_result = match writer.write(&message).await {
|
||||
Err(error) if error.kind() == io::ErrorKind::InvalidInput => {
|
||||
let error_message = format!(
|
||||
"code-mode host response exceeded the {MAX_FRAME_BYTES}-byte IPC frame limit: {error}"
|
||||
);
|
||||
let fallback = match &message {
|
||||
HostToClient::Response { id, .. } => Some(HostToClient::Response {
|
||||
id: *id,
|
||||
result: WireResult::Err {
|
||||
message: error_message,
|
||||
},
|
||||
}),
|
||||
HostToClient::InitialResponse { id, .. } => {
|
||||
Some(HostToClient::InitialResponse {
|
||||
id: *id,
|
||||
result: WireResult::Err {
|
||||
message: error_message,
|
||||
},
|
||||
})
|
||||
}
|
||||
HostToClient::HostHello(_)
|
||||
| HostToClient::HandshakeRejected { .. }
|
||||
| HostToClient::DelegateRequest { .. }
|
||||
| HostToClient::CancelDelegateRequest { .. }
|
||||
| HostToClient::CellClosed { .. } => None,
|
||||
};
|
||||
match fallback {
|
||||
Some(fallback) => writer.write(&fallback).await,
|
||||
None => Err(error),
|
||||
}
|
||||
}
|
||||
result => result,
|
||||
};
|
||||
write_result.context("failed to write code-mode host message")?;
|
||||
}
|
||||
Ok::<(), anyhow::Error>(())
|
||||
}
|
||||
Ok::<(), anyhow::Error>(())
|
||||
.await;
|
||||
let status = match &result {
|
||||
Ok(()) => "code-mode host writer stopped unexpectedly".to_string(),
|
||||
Err(error) => format!("{error:#}"),
|
||||
};
|
||||
let _ = writer_finished_tx.send(status);
|
||||
result
|
||||
});
|
||||
|
||||
let input_result = async {
|
||||
while let Some(message) = reader
|
||||
.read::<ClientToHost>()
|
||||
.await
|
||||
.context("failed to read code-mode client message")?
|
||||
{
|
||||
loop {
|
||||
let message = tokio::select! {
|
||||
biased;
|
||||
writer_status = &mut writer_finished_rx => {
|
||||
let message = writer_status.unwrap_or_else(|_| {
|
||||
"code-mode host writer task stopped without reporting status".to_string()
|
||||
});
|
||||
anyhow::bail!(message);
|
||||
}
|
||||
message = reader.read::<ClientToHost>() => {
|
||||
let Some(message) = message
|
||||
.context("failed to read code-mode client message")?
|
||||
else {
|
||||
break;
|
||||
};
|
||||
message
|
||||
}
|
||||
};
|
||||
match message {
|
||||
ClientToHost::ClientHello(_) => {
|
||||
anyhow::bail!("received a second code-mode client hello");
|
||||
|
||||
@@ -31,6 +31,7 @@ use codex_code_mode::host::HostHello;
|
||||
use codex_code_mode::host::HostRequest;
|
||||
use codex_code_mode::host::HostResponse;
|
||||
use codex_code_mode::host::HostToClient;
|
||||
use codex_code_mode::host::MAX_FRAME_BYTES;
|
||||
use codex_code_mode::host::ProtocolVersion;
|
||||
use codex_code_mode::host::RequestId;
|
||||
use codex_code_mode::host::SessionId;
|
||||
@@ -214,6 +215,66 @@ text(result.value);
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oversized_output_errors_the_cell_without_wedging_the_host() {
|
||||
let provider = ProcessOwnedCodeModeSessionProvider::with_host_program(
|
||||
codex_utils_cargo_bin::cargo_bin("codex-code-mode-host").expect("host binary"),
|
||||
);
|
||||
let session = provider
|
||||
.create_session(Arc::new(RecordingDelegate::default()))
|
||||
.await
|
||||
.expect("create remote session");
|
||||
|
||||
let accepted_output_bytes = 9 * 1024 * 1024;
|
||||
let accepted = execute(
|
||||
&session,
|
||||
execute_request(&format!(r#"text("x".repeat({accepted_output_bytes}));"#)),
|
||||
)
|
||||
.await;
|
||||
let RuntimeResponse::Result {
|
||||
cell_id: accepted_cell_id,
|
||||
content_items,
|
||||
error_text,
|
||||
} = accepted
|
||||
else {
|
||||
panic!("expected accepted output to complete");
|
||||
};
|
||||
assert_eq!(accepted_cell_id, cell_id("1"));
|
||||
assert_eq!(error_text, None);
|
||||
let [FunctionCallOutputContentItem::InputText { text }] = content_items.as_slice() else {
|
||||
panic!("expected one text output item");
|
||||
};
|
||||
assert_eq!(text.len(), accepted_output_bytes);
|
||||
|
||||
let oversized_output_bytes = MAX_FRAME_BYTES + 1024;
|
||||
let started = session
|
||||
.execute(execute_request(&format!(
|
||||
r#"text("x".repeat({oversized_output_bytes}));"#
|
||||
)))
|
||||
.await
|
||||
.expect("start oversized output");
|
||||
let error = tokio::time::timeout(Duration::from_secs(15), started.initial_response())
|
||||
.await
|
||||
.expect("oversized response timeout")
|
||||
.expect_err("oversized response should error the cell");
|
||||
assert!(
|
||||
error.contains(&format!("{MAX_FRAME_BYTES}-byte IPC frame limit")),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
execute(&session, execute_request(r#"text("recovered");"#)).await,
|
||||
RuntimeResponse::Result {
|
||||
cell_id: cell_id("3"),
|
||||
content_items: vec![FunctionCallOutputContentItem::InputText {
|
||||
text: "recovered".to_string(),
|
||||
}],
|
||||
error_text: None,
|
||||
}
|
||||
);
|
||||
session.shutdown().await.expect("shutdown remote session");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cpu_bound_output_loop_can_be_terminated() {
|
||||
let provider = ProcessOwnedCodeModeSessionProvider::with_host_program(
|
||||
@@ -530,6 +591,80 @@ setTimeout(() => { text("should never emit"); }, 60000);
|
||||
assert!(status.success(), "host exited with {status}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn closed_host_stdout_terminates_the_spawned_process() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let temp_dir = tempfile::tempdir().expect("temp dir");
|
||||
let pid_log = temp_dir.path().join("host-pids");
|
||||
let wrapper = temp_dir.path().join("stdout-closing-host");
|
||||
let payload = serde_json::to_vec(&HostToClient::HostHello(HostHello::new(
|
||||
ProtocolVersion::V1,
|
||||
CapabilitySet::empty(),
|
||||
)))
|
||||
.expect("serialize host hello");
|
||||
let mut frame = (payload.len() as u32).to_le_bytes().to_vec();
|
||||
frame.extend(payload);
|
||||
let escaped_frame = frame
|
||||
.iter()
|
||||
.map(|byte| format!("\\{byte:03o}"))
|
||||
.collect::<String>();
|
||||
let script = format!(
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$$\" >> {}\nprintf '%b' '{escaped_frame}'\nexec 1>&-\nwhile :; do :; done\n",
|
||||
shell_quote(&pid_log),
|
||||
);
|
||||
std::fs::write(&wrapper, script).expect("write host wrapper");
|
||||
let mut permissions = std::fs::metadata(&wrapper)
|
||||
.expect("host wrapper metadata")
|
||||
.permissions();
|
||||
permissions.set_mode(/*mode*/ 0o755);
|
||||
std::fs::set_permissions(&wrapper, permissions).expect("make host wrapper executable");
|
||||
|
||||
let provider = ProcessOwnedCodeModeSessionProvider::with_host_program(wrapper);
|
||||
let session_result = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
provider.create_session(Arc::new(RecordingDelegate::default())),
|
||||
)
|
||||
.await;
|
||||
let pid = recorded_pids(&pid_log)[0];
|
||||
let error = match session_result {
|
||||
Ok(result) => result
|
||||
.err()
|
||||
.expect("closed stdout should fail session creation"),
|
||||
Err(error) => {
|
||||
// SAFETY: `pid` was written by the wrapper process owned by this test.
|
||||
let _ = unsafe { libc::kill(pid, libc::SIGKILL) };
|
||||
panic!("session creation timeout: {error}");
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
error.contains("closed its stdout"),
|
||||
"unexpected error: {error}"
|
||||
);
|
||||
|
||||
let exited = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
// SAFETY: signal zero only checks whether the process recorded by
|
||||
// this test still exists.
|
||||
if unsafe {
|
||||
libc::kill(pid, /*sig*/ 0)
|
||||
} == -1
|
||||
&& std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if let Err(error) = exited {
|
||||
// SAFETY: `pid` was written by the wrapper process owned by this test.
|
||||
let _ = unsafe { libc::kill(pid, libc::SIGKILL) };
|
||||
panic!("host process was not terminated: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn crashed_host_fails_in_flight_exec_and_next_exec_respawns() {
|
||||
|
||||
@@ -80,7 +80,7 @@ where
|
||||
})?;
|
||||
if payload.len() > MAX_FRAME_BYTES {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"code-mode IPC frame length {} exceeds {MAX_FRAME_BYTES} bytes",
|
||||
payload.len()
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use self::reader::drive_reader;
|
||||
use codex_code_mode_protocol::CellId;
|
||||
use codex_code_mode_protocol::CodeModeSessionDelegate;
|
||||
use codex_code_mode_protocol::ExecuteRequest;
|
||||
@@ -26,19 +27,14 @@ use codex_code_mode_protocol::host::ProtocolVersion;
|
||||
use codex_code_mode_protocol::host::RequestId;
|
||||
use codex_code_mode_protocol::host::SessionId;
|
||||
use codex_code_mode_protocol::host::SupportedProtocolVersions;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::BufReader;
|
||||
use tokio::process::Command;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::debug;
|
||||
use tracing::warn;
|
||||
|
||||
use self::reader::drive_reader;
|
||||
|
||||
mod reader;
|
||||
mod stderr;
|
||||
|
||||
const IPC_CHANNEL_CAPACITY: usize = 128;
|
||||
|
||||
@@ -138,19 +134,9 @@ impl Connection {
|
||||
drive_reader(reader, reader_state, reader_cancellation).await;
|
||||
});
|
||||
|
||||
if let Some(stderr) = stderr {
|
||||
if let Some(stderr_pipe) = stderr {
|
||||
tokio::spawn(async move {
|
||||
let mut lines = BufReader::new(stderr).lines();
|
||||
loop {
|
||||
match lines.next_line().await {
|
||||
Ok(Some(line)) => debug!("code-mode host stderr: {line}"),
|
||||
Ok(None) => break,
|
||||
Err(err) => {
|
||||
warn!("failed to read code-mode host stderr: {err}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
stderr::drain(stderr_pipe).await;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
use std::io;
|
||||
|
||||
use tokio::io::AsyncBufRead;
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::io::AsyncRead;
|
||||
use tokio::io::BufReader;
|
||||
use tracing::debug;
|
||||
use tracing::warn;
|
||||
|
||||
const MAX_STDERR_LINE_BYTES: usize = 4 * 1024 * 1024;
|
||||
|
||||
pub(super) async fn drain<R>(stderr: R)
|
||||
where
|
||||
R: AsyncRead + Unpin,
|
||||
{
|
||||
let mut reader = BufReader::new(stderr);
|
||||
let mut line = Vec::new();
|
||||
loop {
|
||||
match read_capped_line(&mut reader, &mut line).await {
|
||||
Ok(Some(true)) => {
|
||||
let line = String::from_utf8_lossy(&line);
|
||||
debug!(
|
||||
"code-mode host stderr: {line} [truncated after {MAX_STDERR_LINE_BYTES} bytes]"
|
||||
);
|
||||
}
|
||||
Ok(Some(false)) => {
|
||||
let line = String::from_utf8_lossy(&line);
|
||||
debug!("code-mode host stderr: {line}");
|
||||
}
|
||||
Ok(None) => break,
|
||||
Err(error) => {
|
||||
warn!("failed to read code-mode host stderr: {error}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_capped_line<R>(reader: &mut R, line: &mut Vec<u8>) -> io::Result<Option<bool>>
|
||||
where
|
||||
R: AsyncBufRead + Unpin,
|
||||
{
|
||||
line.clear();
|
||||
let mut truncated = false;
|
||||
loop {
|
||||
let buffer = reader.fill_buf().await?;
|
||||
if buffer.is_empty() {
|
||||
if line.is_empty() && !truncated {
|
||||
return Ok(None);
|
||||
}
|
||||
trim_carriage_return(line, truncated);
|
||||
return Ok(Some(truncated));
|
||||
}
|
||||
|
||||
let newline = buffer.iter().position(|byte| *byte == b'\n');
|
||||
let chunk_len = newline.unwrap_or(buffer.len());
|
||||
let remaining = MAX_STDERR_LINE_BYTES.saturating_sub(line.len());
|
||||
let copy_len = remaining.min(chunk_len);
|
||||
line.extend_from_slice(&buffer[..copy_len]);
|
||||
truncated |= copy_len < chunk_len;
|
||||
let consumed = newline.map_or(chunk_len, |index| index + 1);
|
||||
reader.consume(consumed);
|
||||
|
||||
if newline.is_some() {
|
||||
trim_carriage_return(line, truncated);
|
||||
return Ok(Some(truncated));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn trim_carriage_return(line: &mut Vec<u8>, truncated: bool) {
|
||||
if !truncated && line.last() == Some(&b'\r') {
|
||||
line.pop();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "stderr_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,43 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::io::BufReader;
|
||||
|
||||
use super::MAX_STDERR_LINE_BYTES;
|
||||
use super::read_capped_line;
|
||||
|
||||
#[tokio::test]
|
||||
async fn oversized_lines_are_truncated_without_consuming_the_next_line() {
|
||||
let mut input = vec![b'a'; MAX_STDERR_LINE_BYTES + 1024];
|
||||
input.extend_from_slice(b"\nnext\r\nunterminated");
|
||||
let mut reader = BufReader::new(input.as_slice());
|
||||
let mut line = Vec::new();
|
||||
|
||||
assert_eq!(
|
||||
read_capped_line(&mut reader, &mut line)
|
||||
.await
|
||||
.expect("read oversized line"),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(line, vec![b'a'; MAX_STDERR_LINE_BYTES]);
|
||||
|
||||
assert_eq!(
|
||||
read_capped_line(&mut reader, &mut line)
|
||||
.await
|
||||
.expect("read next line"),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(line, b"next");
|
||||
|
||||
assert_eq!(
|
||||
read_capped_line(&mut reader, &mut line)
|
||||
.await
|
||||
.expect("read unterminated line"),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(line, b"unterminated");
|
||||
assert_eq!(
|
||||
read_capped_line(&mut reader, &mut line)
|
||||
.await
|
||||
.expect("read eof"),
|
||||
None
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user