mirror of
https://github.com/openai/codex.git
synced 2026-12-05 01:00:54 +00:00
Add automation worker loop
This commit is contained in:
@@ -337,6 +337,7 @@ impl MessageProcessor {
|
||||
),
|
||||
);
|
||||
let goal_service = Arc::new(GoalService::new());
|
||||
let automation_worker_installation_id = installation_id.clone();
|
||||
let thread_manager = Arc::new_cyclic(|thread_manager| {
|
||||
ThreadManager::new(
|
||||
config.as_ref(),
|
||||
@@ -486,8 +487,10 @@ impl MessageProcessor {
|
||||
thread_goal_processor.clone(),
|
||||
state_db.clone(),
|
||||
log_db,
|
||||
automation_worker_installation_id,
|
||||
Arc::clone(&skills_watcher),
|
||||
);
|
||||
thread_processor.spawn_automation_worker();
|
||||
let turn_processor = TurnRequestProcessor::new(
|
||||
auth_manager.clone(),
|
||||
Arc::clone(&thread_manager),
|
||||
|
||||
@@ -479,6 +479,7 @@ mod account_processor;
|
||||
mod apps_processor;
|
||||
mod automation_dispatch;
|
||||
mod automation_processor;
|
||||
mod automation_worker;
|
||||
mod catalog_processor;
|
||||
mod command_exec_processor;
|
||||
mod config_processor;
|
||||
|
||||
@@ -90,7 +90,7 @@ impl ThreadRequestProcessor {
|
||||
AutomationDispatchOutcome::Claimed(claim) => claim,
|
||||
};
|
||||
|
||||
let dispatch_result = match self.dispatch_automation_run_now(state_db, &claim).await {
|
||||
let dispatch_result = match self.dispatch_claimed_automation(state_db, &claim).await {
|
||||
Ok(dispatch_result) => dispatch_result,
|
||||
Err(err) => {
|
||||
let _ = state_db
|
||||
@@ -142,7 +142,7 @@ impl ThreadRequestProcessor {
|
||||
.any(|thread_id| thread_id == automation.owner_thread_id))
|
||||
}
|
||||
|
||||
async fn dispatch_automation_run_now(
|
||||
pub(super) async fn dispatch_claimed_automation(
|
||||
&self,
|
||||
state_db: &StateDbHandle,
|
||||
claim: &AutomationDispatchClaim,
|
||||
@@ -161,27 +161,48 @@ impl ThreadRequestProcessor {
|
||||
}
|
||||
|
||||
match &claim.automation.target {
|
||||
AutomationTarget::Cron { cwds } => self.dispatch_cron_run_now(claim, cwds).await,
|
||||
AutomationTarget::Cron { cwds } => {
|
||||
self.dispatch_cron_automation(state_db, claim, cwds).await
|
||||
}
|
||||
AutomationTarget::Heartbeat { thread_id } => {
|
||||
self.dispatch_heartbeat_run_now(claim, *thread_id).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn dispatch_cron_run_now(
|
||||
async fn dispatch_cron_automation(
|
||||
&self,
|
||||
state_db: &StateDbHandle,
|
||||
claim: &AutomationDispatchClaim,
|
||||
cwds: &[PathBuf],
|
||||
) -> Result<RunNowDispatchResult, JSONRPCErrorError> {
|
||||
let mut started_count = 0_usize;
|
||||
let mut last_error = None;
|
||||
for cwd in cwds.iter().skip(claim.dispatch_cwd_index) {
|
||||
for (cwd_index, cwd) in cwds.iter().enumerate().skip(claim.dispatch_cwd_index) {
|
||||
match self
|
||||
.spawn_and_submit_automation_thread(&claim.automation, cwd)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
started_count += 1;
|
||||
let checkpointed = state_db
|
||||
.checkpoint_automation_dispatch_progress(
|
||||
claim.automation.id.as_str(),
|
||||
claim.ownership_token.as_str(),
|
||||
cwd_index + 1,
|
||||
last_error.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to checkpoint automation dispatch: {err}"
|
||||
))
|
||||
})?;
|
||||
if !checkpointed {
|
||||
return Err(internal_error(
|
||||
"automation run claim was lost before checkpoint",
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
last_error = Some(err.message);
|
||||
@@ -338,7 +359,7 @@ fn run_now_response(found: bool, started_count: u32) -> ClientResponsePayload {
|
||||
.into()
|
||||
}
|
||||
|
||||
struct RunNowDispatchResult {
|
||||
pub(super) struct RunNowDispatchResult {
|
||||
started_count: usize,
|
||||
last_error: Option<String>,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
use crate::error_code::INVALID_REQUEST_ERROR_CODE;
|
||||
use crate::request_processors::thread_processor::ThreadRequestProcessor;
|
||||
use codex_rollout::StateDbHandle;
|
||||
use codex_state::AUTOMATION_DISPATCH_BATCH_SIZE;
|
||||
use codex_state::AUTOMATION_POLL_INTERVAL;
|
||||
use codex_state::AutomationDispatchClaim;
|
||||
use tracing::warn;
|
||||
|
||||
impl ThreadRequestProcessor {
|
||||
pub(crate) fn spawn_automation_worker(&self) {
|
||||
let (Some(state_db), Some(worker_id), Some(shutdown)) = (
|
||||
self.state_db.clone(),
|
||||
self.automation_worker_id.clone(),
|
||||
self.automation_worker_shutdown.clone(),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let processor = self.clone();
|
||||
self.background_tasks.spawn(async move {
|
||||
processor
|
||||
.run_automation_worker(state_db, worker_id, shutdown)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
|
||||
async fn run_automation_worker(
|
||||
self,
|
||||
state_db: StateDbHandle,
|
||||
worker_id: String,
|
||||
shutdown: tokio_util::sync::CancellationToken,
|
||||
) {
|
||||
loop {
|
||||
if let Err(err) = self
|
||||
.automation_worker_tick(&state_db, worker_id.as_str())
|
||||
.await
|
||||
{
|
||||
warn!("automation worker tick failed: {err:#}");
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => break,
|
||||
_ = tokio::time::sleep(AUTOMATION_POLL_INTERVAL) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn automation_worker_tick(
|
||||
&self,
|
||||
state_db: &StateDbHandle,
|
||||
worker_id: &str,
|
||||
) -> anyhow::Result<usize> {
|
||||
let mut processed = 0_usize;
|
||||
while processed < AUTOMATION_DISPATCH_BATCH_SIZE {
|
||||
let Some(claim) = state_db.claim_due_automation_dispatch(worker_id).await? else {
|
||||
break;
|
||||
};
|
||||
self.handle_claimed_automation(state_db, &claim).await;
|
||||
processed += 1;
|
||||
}
|
||||
Ok(processed)
|
||||
}
|
||||
|
||||
async fn handle_claimed_automation(
|
||||
&self,
|
||||
state_db: &StateDbHandle,
|
||||
claim: &AutomationDispatchClaim,
|
||||
) {
|
||||
if let Err(err) = self.dispatch_claimed_automation(state_db, claim).await {
|
||||
let result = if err.code == INVALID_REQUEST_ERROR_CODE {
|
||||
state_db
|
||||
.mark_automation_dispatch_failed_terminal(
|
||||
claim.automation.id.as_str(),
|
||||
claim.ownership_token.as_str(),
|
||||
err.message.as_str(),
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
} else {
|
||||
state_db
|
||||
.release_automation_dispatch_after_retryable_failure(
|
||||
claim.automation.id.as_str(),
|
||||
claim.ownership_token.as_str(),
|
||||
err.message.as_str(),
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
};
|
||||
if let Err(state_err) = result {
|
||||
warn!(
|
||||
"failed to persist automation {} dispatch failure: {state_err:#}",
|
||||
claim.automation.id
|
||||
);
|
||||
}
|
||||
warn!(
|
||||
"automation {} dispatch failed: {}",
|
||||
claim.automation.id, err.message
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ use super::*;
|
||||
use crate::error_code::method_not_found;
|
||||
use codex_app_server_protocol::SelectedCapabilityRoot;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
|
||||
|
||||
@@ -357,6 +358,8 @@ pub(crate) struct ThreadRequestProcessor {
|
||||
pub(super) thread_goal_processor: ThreadGoalRequestProcessor,
|
||||
pub(super) state_db: Option<StateDbHandle>,
|
||||
pub(super) log_db: Option<LogDbLayer>,
|
||||
pub(super) automation_worker_id: Option<String>,
|
||||
pub(super) automation_worker_shutdown: Option<CancellationToken>,
|
||||
pub(super) background_tasks: TaskTracker,
|
||||
pub(super) skills_watcher: Arc<SkillsWatcher>,
|
||||
}
|
||||
@@ -389,8 +392,11 @@ impl ThreadRequestProcessor {
|
||||
thread_goal_processor: ThreadGoalRequestProcessor,
|
||||
state_db: Option<StateDbHandle>,
|
||||
log_db: Option<LogDbLayer>,
|
||||
automation_worker_installation_id: String,
|
||||
skills_watcher: Arc<SkillsWatcher>,
|
||||
) -> Self {
|
||||
let automation_worker_enabled =
|
||||
config.features.enabled(Feature::Automations) && state_db.is_some();
|
||||
Self {
|
||||
auth_manager,
|
||||
thread_manager,
|
||||
@@ -406,6 +412,13 @@ impl ThreadRequestProcessor {
|
||||
thread_goal_processor,
|
||||
state_db,
|
||||
log_db,
|
||||
automation_worker_id: automation_worker_enabled.then(|| {
|
||||
format!(
|
||||
"{automation_worker_installation_id}:{}",
|
||||
uuid::Uuid::now_v7()
|
||||
)
|
||||
}),
|
||||
automation_worker_shutdown: automation_worker_enabled.then(CancellationToken::new),
|
||||
background_tasks: TaskTracker::new(),
|
||||
skills_watcher,
|
||||
}
|
||||
@@ -967,6 +980,9 @@ impl ThreadRequestProcessor {
|
||||
}
|
||||
|
||||
pub(crate) async fn drain_background_tasks(&self) {
|
||||
if let Some(shutdown) = &self.automation_worker_shutdown {
|
||||
shutdown.cancel();
|
||||
}
|
||||
self.background_tasks.close();
|
||||
if tokio::time::timeout(Duration::from_secs(10), self.background_tasks.wait())
|
||||
.await
|
||||
|
||||
@@ -118,6 +118,8 @@ pub const AUTOMATIONS_DB_FILENAME: &str = "automations_1.sqlite";
|
||||
pub const STATE_DB_FILENAME: &str = "state_5.sqlite";
|
||||
pub const DEFAULT_AUTOMATION_RRULE: &str = "FREQ=HOURLY;INTERVAL=24;BYMINUTE=0";
|
||||
pub const AUTOMATION_CLAIM_LEASE_SECS: i64 = 120;
|
||||
pub const AUTOMATION_DISPATCH_BATCH_SIZE: usize = 8;
|
||||
pub const AUTOMATION_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
pub const AUTOMATION_RETRY_BACKOFF_SECS: i64 = 10;
|
||||
pub const AUTOMATION_RETRY_BUDGET: i64 = 3;
|
||||
pub const AUTOMATION_RUN_JITTER_WINDOW_SECS: i64 = 120;
|
||||
|
||||
Reference in New Issue
Block a user