mod work_gate; use crate::config::RolloutBudgetConfig; use crate::config::rollout_budget_threshold_reached; use codex_protocol::BudgetUnitsSum; use codex_protocol::ThreadId; use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; use codex_protocol::protocol::TokenUsage; use std::collections::HashMap; use std::sync::Arc; use std::sync::Mutex; use std::sync::MutexGuard; use std::sync::OnceLock; pub(crate) use work_gate::ResponseWork; pub use work_gate::RolloutWorkGate; pub(crate) use work_gate::TurnWork; /// Budget reminder returned by a controller and acknowledged after history insertion. pub struct RolloutBudgetReminder { pub remaining_units: f64, /// Backend-defined reminder position, returned unchanged on acknowledgement. pub reminder_index: i64, } /// Native spending and reminders, plus the stop published by the tree's selected /// accounting owner (native or host). In-flight work can still report its bill. #[derive(Default)] pub struct RolloutBudget { state: OnceLock>, gate: Arc, } /// A native account owns this thread's bills. A host-owned thread only shares its work gate. pub(crate) enum ThreadBudgetAccount { Native(Arc), Shared(Arc), } /// Every thread consults the shared work gate before starting new work. #[derive(Clone, Debug, Default)] pub(crate) struct ThreadBudgetPolicy { rollout: Arc, } impl ThreadBudgetPolicy { pub(crate) fn new(account: ThreadBudgetAccount) -> CodexResult { let (ThreadBudgetAccount::Native(rollout) | ThreadBudgetAccount::Shared(rollout)) = account; Ok(Self { rollout }) } pub(crate) fn check_start(&self) -> CodexResult<()> { self.rollout.gate.check_start() } pub(crate) fn defer_compaction_start( &self, source: &codex_protocol::protocol::SessionSource, phase: codex_analytics::CompactionPhase, ) -> bool { work_gate::defer_compaction_start(self, source, phase) } } impl std::fmt::Debug for RolloutBudget { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("RolloutBudget") .field("state", &self.state) .field("stopped", &self.is_exhausted()) .finish_non_exhaustive() } } #[derive(Debug)] struct RolloutBudgetState { config: RolloutBudgetConfig, posted: BudgetUnitsSum, /// Last reminder delivered to each thread, so every thread observes crossed thresholds. deliveries: HashMap, } #[derive(Debug)] struct ThreadBudgetDelivery { window_id: String, reminder_index: i64, } impl RolloutBudget { pub(crate) fn configure(&self, config: RolloutBudgetConfig) { self.state.get_or_init(|| { Mutex::new(RolloutBudgetState { config, posted: BudgetUnitsSum::default(), deliveries: HashMap::new(), }) }); } pub(crate) fn config(&self) -> Option { self.lock().map(|state| state.config.clone()) } /// Post the response cost and enforce the allowance under the same lock. pub(crate) fn record_usage( &self, usage: Option<&TokenUsage>, hook_units: f64, ) -> CodexResult<()> { let Some(mut state) = self.lock() else { return Ok(()); }; if !hook_units.is_finite() || hook_units < 0.0 { return Err(CodexErr::Fatal("invalid additional sampling charge".into())); } let provider_units = if let Some(units) = usage.and_then(|usage| usage.codex_rollout_budget_units.as_ref()) { let units = units.as_f64().unwrap_or(f64::NAN); if !units.is_finite() || units < 0.0 { return Err(CodexErr::Fatal( "response.completed usage.codex_rollout_budget_units must be finite and non-negative" .to_string(), )); } units } else if let Some(usage) = usage { usage.output_tokens.max(0) as f64 * state.config.sampling_token_weight + usage.non_cached_input() as f64 * state.config.prefill_token_weight } else { 0.0 }; let response_charge_amount = provider_units + hook_units; if !response_charge_amount.is_finite() { return self.reject_overflow(&state, "responseChargeAmount"); } // Stage the bill so a failed check cannot change the previously posted balance. let Some(posted) = state .posted .checked_add(provider_units) .and_then(|sum| sum.checked_add(hook_units)) else { return self.reject_overflow(&state, "totalBudgetUsed"); }; state.posted = posted; let enforcement = self.enforce_posted_limit(&state); enforcement } fn reject_overflow(&self, state: &RolloutBudgetState, field: &str) -> CodexResult<()> { if state.config.enforce_limit { self.stop_on_overflow(); } Err(CodexErr::Fatal(format!("{field} must be finite"))) } pub(crate) fn stop_on_overflow(&self) { // Decline new work immediately and interrupt active turns on clocks that support it. self.stop_new_work(); } fn enforce_posted_limit(&self, state: &RolloutBudgetState) -> CodexResult<()> { let posted = state.posted.total(); if state.config.enforce_limit && posted > state.config.limit_budget.next_up() { self.stop_new_work(); } Ok(()) } pub(crate) fn pending_reminder( &self, thread_id: ThreadId, window_id: &str, ) -> Option { let state = self.lock()?; let remaining_units = self.remaining_units(&state).ok()?; let reminder_index = state .config .reminder_at_remaining_tokens .iter() .filter(|&&threshold| rollout_budget_threshold_reached(remaining_units, threshold)) .count() as i64; let previous = state.deliveries.get(&thread_id); let crossed_threshold = reminder_index > previous.map_or(0, |d| d.reminder_index); let new_window = state.config.reminder_at_context_start && previous.is_none_or(|d| d.window_id != window_id); if !crossed_threshold && !new_window { return None; } Some(RolloutBudgetReminder { remaining_units, reminder_index, }) } pub(crate) fn mark_reminder_delivered( &self, thread_id: ThreadId, window_id: &str, reminder: RolloutBudgetReminder, ) { // Mark delivery only after history insertion; cancellation before then should retry it. let Some(mut state) = self.lock() else { return; }; state.deliveries.insert( thread_id, ThreadBudgetDelivery { window_id: window_id.to_string(), reminder_index: reminder.reminder_index, }, ); } fn lock(&self) -> Option> { self.state.get().map(|state| { state .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) }) } pub(crate) fn stop_new_work(&self) { self.gate.stop_budget(); } pub(crate) fn can_receive_turn_input(&self, thread: ThreadId, turn: &str) -> bool { self.gate.can_receive_turn_input(thread, turn) } pub(crate) fn is_exhausted(&self) -> bool { self.gate.is_stopped() } fn remaining_units(&self, state: &RolloutBudgetState) -> CodexResult { let used = state.posted.total(); Ok((state.config.limit_budget - used).max(0.0)) } }