mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Address agent job timeout review
This commit is contained in:
@@ -615,6 +615,7 @@ fn started_at_from_item(item: &codex_state::AgentJobItem) -> Instant {
|
||||
let now = chrono::Utc::now();
|
||||
let age = now.signed_duration_since(item.updated_at);
|
||||
if let Ok(age) = age.to_std() {
|
||||
let age = age.saturating_sub(Duration::from_secs(1));
|
||||
Instant::now().checked_sub(age).unwrap_or_else(Instant::now)
|
||||
} else {
|
||||
Instant::now()
|
||||
@@ -624,7 +625,7 @@ fn started_at_from_item(item: &codex_state::AgentJobItem) -> Instant {
|
||||
fn is_item_stale(item: &codex_state::AgentJobItem, runtime_timeout: Duration) -> bool {
|
||||
let now = chrono::Utc::now();
|
||||
if let Ok(age) = now.signed_duration_since(item.updated_at).to_std() {
|
||||
age >= runtime_timeout
|
||||
age > runtime_timeout
|
||||
} else {
|
||||
false
|
||||
}
|
||||
|
||||
@@ -60,198 +60,3 @@ fn ensure_unique_headers_rejects_duplicates() {
|
||||
FunctionCallError::RespondToModel("csv header path is duplicated".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn assigning_thread_before_prompt_delivery_does_not_mark_item_running() -> anyhow::Result<()>
|
||||
{
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let runtime =
|
||||
codex_state::StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".into())
|
||||
.await?;
|
||||
let job_id = "job-before-prompt";
|
||||
let item_id = "row-1";
|
||||
|
||||
runtime
|
||||
.create_agent_job(
|
||||
&codex_state::AgentJobCreateParams {
|
||||
id: job_id.to_string(),
|
||||
name: "test-job".to_string(),
|
||||
instruction: "Return {path}".to_string(),
|
||||
auto_export: true,
|
||||
max_runtime_seconds: Some(1),
|
||||
output_schema_json: None,
|
||||
input_headers: vec!["path".to_string()],
|
||||
input_csv_path: "/tmp/input.csv".to_string(),
|
||||
output_csv_path: "/tmp/output.csv".to_string(),
|
||||
},
|
||||
&[codex_state::AgentJobItemCreateParams {
|
||||
item_id: item_id.to_string(),
|
||||
row_index: 0,
|
||||
source_id: None,
|
||||
row_json: json!({"path": "file-1"}),
|
||||
}],
|
||||
)
|
||||
.await?;
|
||||
runtime.mark_agent_job_running(job_id).await?;
|
||||
|
||||
let marked_running = runtime
|
||||
.mark_agent_job_item_running_with_thread(job_id, item_id, "child-thread-without-prompt")
|
||||
.await?;
|
||||
assert!(
|
||||
!marked_running,
|
||||
"assigning a child thread is not enough to mark an item running; \
|
||||
the worker prompt must be delivered first"
|
||||
);
|
||||
|
||||
let item = runtime
|
||||
.get_agent_job_item(job_id, item_id)
|
||||
.await?
|
||||
.expect("job item should exist");
|
||||
assert_eq!(item.status, codex_state::AgentJobItemStatus::Pending);
|
||||
assert_eq!(item.assigned_thread_id, None);
|
||||
assert_eq!(
|
||||
runtime.get_agent_job_progress(job_id).await?,
|
||||
codex_state::AgentJobProgress {
|
||||
total_items: 1,
|
||||
pending_items: 1,
|
||||
running_items: 0,
|
||||
completed_items: 0,
|
||||
failed_items: 0,
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn running_item_past_max_runtime_fails_even_if_worker_never_returns() -> anyhow::Result<()> {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let runtime =
|
||||
codex_state::StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".into())
|
||||
.await?;
|
||||
let job_id = "job-timeout";
|
||||
let item_id = "row-1";
|
||||
|
||||
runtime
|
||||
.create_agent_job(
|
||||
&codex_state::AgentJobCreateParams {
|
||||
id: job_id.to_string(),
|
||||
name: "test-job".to_string(),
|
||||
instruction: "Return {path}".to_string(),
|
||||
auto_export: true,
|
||||
max_runtime_seconds: Some(1),
|
||||
output_schema_json: None,
|
||||
input_headers: vec!["path".to_string()],
|
||||
input_csv_path: "/tmp/input.csv".to_string(),
|
||||
output_csv_path: "/tmp/output.csv".to_string(),
|
||||
},
|
||||
&[codex_state::AgentJobItemCreateParams {
|
||||
item_id: item_id.to_string(),
|
||||
row_index: 0,
|
||||
source_id: None,
|
||||
row_json: json!({"path": "file-1"}),
|
||||
}],
|
||||
)
|
||||
.await?;
|
||||
runtime.mark_agent_job_running(job_id).await?;
|
||||
let marked_running = runtime
|
||||
.mark_agent_job_item_running_with_thread(
|
||||
job_id,
|
||||
item_id,
|
||||
"00000000-0000-0000-0000-000000000001",
|
||||
)
|
||||
.await?;
|
||||
assert!(marked_running);
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1_100)).await;
|
||||
|
||||
let item = runtime
|
||||
.get_agent_job_item(job_id, item_id)
|
||||
.await?
|
||||
.expect("job item should exist");
|
||||
assert_eq!(item.status, codex_state::AgentJobItemStatus::Failed);
|
||||
assert_eq!(item.assigned_thread_id, None);
|
||||
assert!(
|
||||
item.last_error
|
||||
.as_deref()
|
||||
.is_some_and(|error| error.contains("worker exceeded max runtime")),
|
||||
"timed out running item should record a max-runtime failure"
|
||||
);
|
||||
assert_eq!(
|
||||
runtime.get_agent_job_progress(job_id).await?,
|
||||
codex_state::AgentJobProgress {
|
||||
total_items: 1,
|
||||
pending_items: 0,
|
||||
running_items: 0,
|
||||
completed_items: 0,
|
||||
failed_items: 1,
|
||||
}
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn late_report_after_timeout_failure_is_rejected() -> anyhow::Result<()> {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let runtime =
|
||||
codex_state::StateRuntime::init(codex_home.path().to_path_buf(), "test-provider".into())
|
||||
.await?;
|
||||
let job_id = "job-late-report";
|
||||
let item_id = "row-1";
|
||||
let thread_id = "00000000-0000-0000-0000-000000000001";
|
||||
|
||||
runtime
|
||||
.create_agent_job(
|
||||
&codex_state::AgentJobCreateParams {
|
||||
id: job_id.to_string(),
|
||||
name: "test-job".to_string(),
|
||||
instruction: "Return {path}".to_string(),
|
||||
auto_export: true,
|
||||
max_runtime_seconds: Some(1),
|
||||
output_schema_json: None,
|
||||
input_headers: vec!["path".to_string()],
|
||||
input_csv_path: "/tmp/input.csv".to_string(),
|
||||
output_csv_path: "/tmp/output.csv".to_string(),
|
||||
},
|
||||
&[codex_state::AgentJobItemCreateParams {
|
||||
item_id: item_id.to_string(),
|
||||
row_index: 0,
|
||||
source_id: None,
|
||||
row_json: json!({"path": "file-1"}),
|
||||
}],
|
||||
)
|
||||
.await?;
|
||||
runtime.mark_agent_job_running(job_id).await?;
|
||||
assert!(
|
||||
runtime
|
||||
.mark_agent_job_item_running_with_thread(job_id, item_id, thread_id)
|
||||
.await?
|
||||
);
|
||||
assert!(
|
||||
runtime
|
||||
.mark_agent_job_item_failed(job_id, item_id, "worker exceeded max runtime of 1s")
|
||||
.await?
|
||||
);
|
||||
|
||||
let accepted = runtime
|
||||
.report_agent_job_item_result(job_id, item_id, thread_id, &json!({"late": true}))
|
||||
.await?;
|
||||
assert!(
|
||||
!accepted,
|
||||
"late report from a timed-out worker must not convert the item back to completed"
|
||||
);
|
||||
|
||||
let item = runtime
|
||||
.get_agent_job_item(job_id, item_id)
|
||||
.await?
|
||||
.expect("job item should exist");
|
||||
assert_eq!(item.status, codex_state::AgentJobItemStatus::Failed);
|
||||
assert_eq!(item.result_json, None);
|
||||
assert_eq!(
|
||||
item.last_error,
|
||||
Some("worker exceeded max runtime of 1s".to_string())
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use wiremock::Mock;
|
||||
use wiremock::Respond;
|
||||
use wiremock::ResponseTemplate;
|
||||
@@ -53,6 +54,20 @@ impl StopAfterFirstResponder {
|
||||
}
|
||||
}
|
||||
|
||||
struct NeverReportingWorkerResponder {
|
||||
spawn_args_json: String,
|
||||
seen_main: AtomicBool,
|
||||
}
|
||||
|
||||
impl NeverReportingWorkerResponder {
|
||||
fn new(spawn_args_json: String) -> Self {
|
||||
Self {
|
||||
spawn_args_json,
|
||||
seen_main: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Respond for StopAfterFirstResponder {
|
||||
fn respond(&self, request: &wiremock::Request) -> ResponseTemplate {
|
||||
let body_bytes = decode_body_bytes(request);
|
||||
@@ -98,6 +113,38 @@ impl Respond for StopAfterFirstResponder {
|
||||
}
|
||||
}
|
||||
|
||||
impl Respond for NeverReportingWorkerResponder {
|
||||
fn respond(&self, request: &wiremock::Request) -> ResponseTemplate {
|
||||
let body_bytes = decode_body_bytes(request);
|
||||
let body: Value = serde_json::from_slice(&body_bytes).unwrap_or(Value::Null);
|
||||
|
||||
if has_function_call_output(&body) {
|
||||
return sse_response(sse(vec![
|
||||
ev_response_created("resp-tool"),
|
||||
ev_completed("resp-tool"),
|
||||
]));
|
||||
}
|
||||
|
||||
if extract_job_and_item(&body).is_some() {
|
||||
return sse_response(sse(vec![ev_response_created("resp-worker")]))
|
||||
.set_delay(Duration::from_secs(30));
|
||||
}
|
||||
|
||||
if !self.seen_main.swap(true, Ordering::SeqCst) {
|
||||
return sse_response(sse(vec![
|
||||
ev_response_created("resp-main"),
|
||||
ev_function_call("call-spawn", "spawn_agents_on_csv", &self.spawn_args_json),
|
||||
ev_completed("resp-main"),
|
||||
]));
|
||||
}
|
||||
|
||||
sse_response(sse(vec![
|
||||
ev_response_created("resp-default"),
|
||||
ev_completed("resp-default"),
|
||||
]))
|
||||
}
|
||||
}
|
||||
|
||||
impl Respond for AgentJobsResponder {
|
||||
fn respond(&self, request: &wiremock::Request) -> ResponseTemplate {
|
||||
let body_bytes = decode_body_bytes(request);
|
||||
@@ -214,6 +261,70 @@ fn parse_simple_csv_line(line: &str) -> Vec<String> {
|
||||
line.split(',').map(str::to_string).collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn spawn_agents_on_csv_times_out_never_reporting_worker_and_exports() -> Result<()> {
|
||||
let server = start_mock_server().await;
|
||||
let mut builder = test_codex().with_config(|config| {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::SpawnCsv)
|
||||
.expect("test config should allow feature update");
|
||||
config
|
||||
.features
|
||||
.enable(Feature::Sqlite)
|
||||
.expect("test config should allow feature update");
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
|
||||
let input_path = test.cwd_path().join("agent_jobs_timeout.csv");
|
||||
let output_path = test.cwd_path().join("agent_jobs_timeout_out.csv");
|
||||
fs::write(&input_path, "path\nfile-1\n")?;
|
||||
|
||||
let args = json!({
|
||||
"csv_path": input_path.display().to_string(),
|
||||
"instruction": "Return {path}",
|
||||
"output_csv_path": output_path.display().to_string(),
|
||||
"max_runtime_seconds": 1,
|
||||
});
|
||||
let args_json = serde_json::to_string(&args)?;
|
||||
|
||||
let responder = NeverReportingWorkerResponder::new(args_json);
|
||||
Mock::given(method("POST"))
|
||||
.and(path_regex(".*/responses$"))
|
||||
.respond_with(responder)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let completed = tokio::time::timeout(Duration::from_secs(6), test.submit_turn("run job")).await;
|
||||
assert!(
|
||||
completed.is_ok(),
|
||||
"parent spawn_agents_on_csv call should return after a worker exceeds max_runtime_seconds"
|
||||
);
|
||||
completed??;
|
||||
|
||||
let output = fs::read_to_string(&output_path)?;
|
||||
let mut lines = output.lines();
|
||||
let headers = lines.next().expect("csv headers");
|
||||
let header_cols = parse_simple_csv_line(headers);
|
||||
let status_index = header_cols
|
||||
.iter()
|
||||
.position(|header| header == "status")
|
||||
.expect("status column");
|
||||
let last_error_index = header_cols
|
||||
.iter()
|
||||
.position(|header| header == "last_error")
|
||||
.expect("last_error column");
|
||||
let row = lines.next().expect("output row");
|
||||
let cols = parse_simple_csv_line(row);
|
||||
assert_eq!(cols[status_index], "failed");
|
||||
assert!(
|
||||
cols[last_error_index].contains("worker exceeded max runtime"),
|
||||
"timed out worker should export a max-runtime failure"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn report_agent_job_result_rejects_wrong_thread() -> Result<()> {
|
||||
let server = start_mock_server().await;
|
||||
|
||||
@@ -135,7 +135,6 @@ WHERE id = ?
|
||||
status: Option<AgentJobItemStatus>,
|
||||
limit: Option<usize>,
|
||||
) -> anyhow::Result<Vec<AgentJobItem>> {
|
||||
self.fail_stale_agent_job_items(job_id).await?;
|
||||
let mut builder = QueryBuilder::<Sqlite>::new(
|
||||
r#"
|
||||
SELECT
|
||||
@@ -179,7 +178,6 @@ WHERE job_id =
|
||||
job_id: &str,
|
||||
item_id: &str,
|
||||
) -> anyhow::Result<Option<AgentJobItem>> {
|
||||
self.fail_stale_agent_job_items(job_id).await?;
|
||||
let row: Option<AgentJobItemRow> = sqlx::query_as::<_, AgentJobItemRow>(
|
||||
r#"
|
||||
SELECT
|
||||
@@ -315,6 +313,12 @@ WHERE id = ?
|
||||
Ok(AgentJobStatus::parse(status.as_str())? == AgentJobStatus::Cancelled)
|
||||
}
|
||||
|
||||
/// Fail any running items whose last state update is older than the job's runtime limit.
|
||||
///
|
||||
/// This is an external watchdog for workers that never emit a terminal event. It deliberately
|
||||
/// uses a strict second-based cutoff so workers are not failed before `max_runtime_seconds`
|
||||
/// has fully elapsed, and it preserves `assigned_thread_id` for observability and later
|
||||
/// cleanup by thread-deletion/recovery paths.
|
||||
pub async fn fail_stale_agent_job_items(&self, job_id: &str) -> anyhow::Result<u64> {
|
||||
let row = sqlx::query(
|
||||
r#"
|
||||
@@ -346,12 +350,11 @@ SET
|
||||
status = ?,
|
||||
completed_at = ?,
|
||||
updated_at = ?,
|
||||
last_error = ?,
|
||||
assigned_thread_id = NULL
|
||||
last_error = ?
|
||||
WHERE
|
||||
job_id = ?
|
||||
AND status = ?
|
||||
AND updated_at <= ?
|
||||
AND updated_at < ?
|
||||
"#,
|
||||
)
|
||||
.bind(AgentJobItemStatus::Failed.as_str())
|
||||
@@ -588,7 +591,6 @@ WHERE
|
||||
}
|
||||
|
||||
pub async fn get_agent_job_progress(&self, job_id: &str) -> anyhow::Result<AgentJobProgress> {
|
||||
self.fail_stale_agent_job_items(job_id).await?;
|
||||
let row = sqlx::query(
|
||||
r#"
|
||||
SELECT
|
||||
@@ -740,4 +742,87 @@ mod tests {
|
||||
assert_eq!(item.last_error, Some("missing report".to_string()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fail_stale_agent_job_items_preserves_thread_id_and_rejects_late_report()
|
||||
-> anyhow::Result<()> {
|
||||
let codex_home = unique_temp_dir();
|
||||
let runtime = StateRuntime::init(codex_home, "test-provider".to_string()).await?;
|
||||
let job_id = "job-stale".to_string();
|
||||
let item_id = "item-1".to_string();
|
||||
let thread_id = "00000000-0000-0000-0000-000000000001".to_string();
|
||||
runtime
|
||||
.create_agent_job(
|
||||
&AgentJobCreateParams {
|
||||
id: job_id.clone(),
|
||||
name: "test-job".to_string(),
|
||||
instruction: "Return a result".to_string(),
|
||||
auto_export: true,
|
||||
max_runtime_seconds: Some(60),
|
||||
output_schema_json: None,
|
||||
input_headers: vec!["path".to_string()],
|
||||
input_csv_path: "/tmp/in.csv".to_string(),
|
||||
output_csv_path: "/tmp/out.csv".to_string(),
|
||||
},
|
||||
&[AgentJobItemCreateParams {
|
||||
item_id: item_id.clone(),
|
||||
row_index: 0,
|
||||
source_id: None,
|
||||
row_json: json!({"path":"file-1"}),
|
||||
}],
|
||||
)
|
||||
.await?;
|
||||
runtime.mark_agent_job_running(job_id.as_str()).await?;
|
||||
assert!(
|
||||
runtime
|
||||
.mark_agent_job_item_running_with_thread(
|
||||
job_id.as_str(),
|
||||
item_id.as_str(),
|
||||
thread_id.as_str(),
|
||||
)
|
||||
.await?
|
||||
);
|
||||
|
||||
let stale_updated_at = Utc::now().timestamp().saturating_sub(120);
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE agent_job_items
|
||||
SET updated_at = ?
|
||||
WHERE job_id = ? AND item_id = ?
|
||||
"#,
|
||||
)
|
||||
.bind(stale_updated_at)
|
||||
.bind(job_id.as_str())
|
||||
.bind(item_id.as_str())
|
||||
.execute(runtime.pool.as_ref())
|
||||
.await?;
|
||||
|
||||
assert_eq!(
|
||||
runtime.fail_stale_agent_job_items(job_id.as_str()).await?,
|
||||
1
|
||||
);
|
||||
|
||||
let accepted = runtime
|
||||
.report_agent_job_item_result(
|
||||
job_id.as_str(),
|
||||
item_id.as_str(),
|
||||
thread_id.as_str(),
|
||||
&json!({"late": true}),
|
||||
)
|
||||
.await?;
|
||||
assert!(!accepted);
|
||||
|
||||
let item = runtime
|
||||
.get_agent_job_item(job_id.as_str(), item_id.as_str())
|
||||
.await?
|
||||
.expect("job item should exist");
|
||||
assert_eq!(item.status, AgentJobItemStatus::Failed);
|
||||
assert_eq!(item.assigned_thread_id, Some(thread_id));
|
||||
assert_eq!(
|
||||
item.last_error,
|
||||
Some("worker exceeded max runtime of 60s".to_string())
|
||||
);
|
||||
assert_eq!(item.result_json, None);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user