diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index 4a562092f1..59068111aa 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -3,6 +3,8 @@ use crate::config::ConstraintResult; use crate::session::Codex; use crate::session::SessionSettingsUpdate; use crate::session::SteerInputError; +use crate::state::PersistedHistoryCursor; +use crate::state::PersistedHistoryCursorUncertainty; use codex_features::Feature; use codex_otel::SessionTelemetry; use codex_protocol::ThreadId; @@ -95,6 +97,33 @@ pub enum TryStartTurnIfIdleRejectionReason { Busy, } +/// Stable snapshot used to ensure persisted history is only installed over the +/// same idle in-memory history that preceded the storage read. +#[derive(Debug)] +pub struct ThreadHistoryReconciliationSnapshot { + pub(crate) history: Vec, + pub(crate) history_version: u64, + pub(crate) known_persisted_incomplete_tail: Option, + pub(crate) known_persisted_history_cursor: Option, + pub(crate) persisted_history_cursor_uncertainty: Option, + pub(crate) uncertain_expected_persisted_history_cursor: Option, +} + +/// Result of reconciling a loaded thread with its persisted rollout history. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ThreadHistoryReconciliationOutcome { + /// Persisted and in-memory model histories were already identical. + Unchanged, + /// The persisted rollout was canonically reconstructed and installed. + Refreshed, + /// A local turn is active, so its live state remains authoritative. + Busy, + /// The persisted rollout ends in a turn that has not reached a terminal event. + Incomplete, + /// The local idle history changed after the reconciliation snapshot was taken. + Conflict, +} + /// Rejection returned when an extension asks to start automatic idle work but /// the thread is not eligible to run it. #[derive(Debug)] @@ -243,6 +272,25 @@ impl CodexThread { self.codex.session.flush_rollout().await } + /// Captures the idle model history before a caller performs a persisted-history read. + pub async fn history_reconciliation_snapshot( + &self, + ) -> Option { + self.codex.session.history_reconciliation_snapshot().await + } + + /// Rebuilds and installs a completed persisted rollout without writing it again. + pub async fn reconcile_persisted_history( + &self, + snapshot: ThreadHistoryReconciliationSnapshot, + rollout_items: &[RolloutItem], + ) -> ThreadHistoryReconciliationOutcome { + self.codex + .session + .reconcile_persisted_history(snapshot, rollout_items) + .await + } + pub async fn submit_with_trace( &self, op: Op, @@ -413,6 +461,18 @@ impl CodexThread { self.codex.next_event().await } + /// Returns a queued event without waiting. Running-thread resume uses this while holding an + /// event-delivery cut so every event represented by its snapshot is consumed before attach. + pub fn try_next_event(&self) -> CodexResult> { + self.codex.try_next_event() + } + + /// Returns the queue depth at one instant. Running-thread resume uses this to bound its + /// pre-attach drain when a legacy exec producer can append output concurrently. + pub fn pending_event_count(&self) -> usize { + self.codex.pending_event_count() + } + pub async fn agent_status(&self) -> AgentStatus { self.codex.agent_status().await } @@ -443,6 +503,20 @@ impl CodexThread { self.codex.session.token_usage_info().await } + /// Serializes an idle persisted-history read/replacement with history-only mutations. + pub async fn acquire_history_reconciliation_event_cut( + &self, + ) -> ( + tokio::sync::OwnedMutexGuard<()>, + tokio::sync::OwnedMutexGuard<()>, + tokio::sync::OwnedMutexGuard<()>, + ) { + self.codex + .session + .acquire_history_reconciliation_event_cut() + .await + } + /// Records a user-role session-prefix message without creating a new user turn boundary. pub(crate) async fn inject_user_message_without_turn(&self, message: String) { let item = ResponseItem::Message { @@ -466,6 +540,7 @@ impl CodexThread { )); } + let _history_guard = self.codex.session.acquire_history_persistence_lock().await; let turn_context = self.codex.session.new_default_turn().await; if self.codex.session.reference_context_item().await.is_none() { // This history-only API runs without run_turn, so it owns its initial step. @@ -481,7 +556,7 @@ impl CodexThread { } self.codex .session - .inject_no_new_turn(items, Some(turn_context.as_ref())) + .inject_no_new_turn_locked(items, Some(turn_context.as_ref())) .await; self.codex.session.flush_rollout().await?; Ok(()) @@ -555,6 +630,7 @@ impl CodexThread { /// Appends rollout items through the live thread so derived metadata stays in sync. pub async fn append_rollout_items(&self, items: &[RolloutItem]) -> ThreadStoreResult<()> { + let rollout_guard = self.codex.session.acquire_rollout_persistence_lock().await; let live_thread = self .codex .session @@ -562,7 +638,24 @@ impl CodexThread { .map_err(|err| ThreadStoreError::Internal { message: err.to_string(), })?; - live_thread.append_items(items).await + match live_thread.append_items(items).await { + Ok(()) => { + self.codex + .session + .note_persisted_non_metadata_items(&rollout_guard, items) + .await; + Ok(()) + } + Err(err) => { + // A failed append can still have reached a buffered writer. Stop using the + // incremental cursor until the next full reconciliation establishes a prefix. + self.codex + .session + .invalidate_persisted_item_cursor(&rollout_guard, items) + .await; + Err(err) + } + } } pub fn state_db(&self) -> Option { diff --git a/codex-rs/core/src/context/token_budget_context.rs b/codex-rs/core/src/context/token_budget_context.rs index f3eef0b734..2defbeb850 100644 --- a/codex-rs/core/src/context/token_budget_context.rs +++ b/codex-rs/core/src/context/token_budget_context.rs @@ -4,6 +4,8 @@ use codex_protocol::protocol::CONTEXT_WINDOW_CLOSE_TAG; use codex_protocol::protocol::CONTEXT_WINDOW_GUIDANCE_CLOSE_TAG; use codex_protocol::protocol::CONTEXT_WINDOW_GUIDANCE_OPEN_TAG; use codex_protocol::protocol::CONTEXT_WINDOW_OPEN_TAG; +use codex_protocol::protocol::TOKEN_BUDGET_REMINDER_CLOSE_TAG; +use codex_protocol::protocol::TOKEN_BUDGET_REMINDER_OPEN_TAG; use uuid::Uuid; #[derive(Debug, Clone, PartialEq, Eq)] @@ -162,10 +164,13 @@ impl ContextualUserFragment for TokenBudgetReminder { } fn type_markers() -> (&'static str, &'static str) { - ("", "") + ( + TOKEN_BUDGET_REMINDER_OPEN_TAG, + TOKEN_BUDGET_REMINDER_CLOSE_TAG, + ) } fn body(&self) -> String { - self.message.clone() + format!("\n{}\n", self.message) } } diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index 318c5d4d2f..e198aec03e 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -108,6 +108,10 @@ impl ContextManager { self.world_state_baseline = Some(snapshot); } + pub(crate) fn replace_world_state_baseline(&mut self, snapshot: Option) { + self.world_state_baseline = snapshot; + } + pub(crate) fn set_token_usage_full(&mut self, context_window: i64) { match &mut self.token_info { Some(info) => info.fill_to_context_window(context_window), diff --git a/codex-rs/core/src/event_mapping.rs b/codex-rs/core/src/event_mapping.rs index 392203c079..e72d7eb275 100644 --- a/codex-rs/core/src/event_mapping.rs +++ b/codex-rs/core/src/event_mapping.rs @@ -20,6 +20,7 @@ use codex_protocol::protocol::CONTEXT_WINDOW_OPEN_TAG; use codex_protocol::protocol::MULTI_AGENT_MODE_OPEN_TAG; use codex_protocol::protocol::REALTIME_CONVERSATION_OPEN_TAG; use codex_protocol::protocol::SKILLS_INSTRUCTIONS_OPEN_TAG; +use codex_protocol::protocol::TOKEN_BUDGET_REMINDER_OPEN_TAG; use codex_protocol::user_input::UserInput; use tracing::warn; use uuid::Uuid; @@ -38,6 +39,7 @@ const CONTEXTUAL_DEVELOPER_PREFIXES: &[&str] = &[ "", // Keep recognizing token-budget wrappers persisted by older versions. "", + TOKEN_BUDGET_REMINDER_OPEN_TAG, CONTEXT_WINDOW_OPEN_TAG, CONTEXT_WINDOW_GUIDANCE_OPEN_TAG, "", diff --git a/codex-rs/core/src/event_mapping_tests.rs b/codex-rs/core/src/event_mapping_tests.rs index c91034d451..9e2ab80053 100644 --- a/codex-rs/core/src/event_mapping_tests.rs +++ b/codex-rs/core/src/event_mapping_tests.rs @@ -20,6 +20,8 @@ use codex_protocol::protocol::CONTEXT_WINDOW_GUIDANCE_CLOSE_TAG; use codex_protocol::protocol::CONTEXT_WINDOW_GUIDANCE_OPEN_TAG; use codex_protocol::protocol::CONTEXT_WINDOW_OPEN_TAG; use codex_protocol::protocol::SKILLS_INSTRUCTIONS_OPEN_TAG; +use codex_protocol::protocol::TOKEN_BUDGET_REMINDER_CLOSE_TAG; +use codex_protocol::protocol::TOKEN_BUDGET_REMINDER_OPEN_TAG; use codex_protocol::user_input::UserInput; use pretty_assertions::assert_eq; @@ -43,6 +45,18 @@ fn recognizes_legacy_token_budget_as_contextual_developer_content() { assert!(!has_non_contextual_dev_message_content(&content)); } +#[test] +fn recognizes_token_budget_reminder_as_contextual_developer_content() { + let content = vec![ContentItem::InputText { + text: format!( + "{TOKEN_BUDGET_REMINDER_OPEN_TAG}\nOnly 400 tokens remain.\n{TOKEN_BUDGET_REMINDER_CLOSE_TAG}" + ), + }]; + + assert!(is_contextual_dev_message_content(&content)); + assert!(!has_non_contextual_dev_message_content(&content)); +} + #[test] fn recognizes_context_window_as_contextual_developer_content() { let content = vec![ContentItem::InputText { diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index e9b749fea9..a1042e8011 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -27,6 +27,8 @@ pub use codex_thread::BackgroundTerminalInfo; pub use codex_thread::CodexThread; pub use codex_thread::CodexThreadSettingsOverrides; pub use codex_thread::ThreadConfigSnapshot; +pub use codex_thread::ThreadHistoryReconciliationOutcome; +pub use codex_thread::ThreadHistoryReconciliationSnapshot; pub use codex_thread::TryStartTurnIfIdleError; pub use codex_thread::TryStartTurnIfIdleRejectionReason; pub use session::turn_context::TurnContext; diff --git a/codex-rs/core/src/session/handlers.rs b/codex-rs/core/src/session/handlers.rs index a483ce5e0f..d8d347a2ab 100644 --- a/codex-rs/core/src/session/handlers.rs +++ b/codex-rs/core/src/session/handlers.rs @@ -461,6 +461,7 @@ pub async fn thread_rollback(sess: &Arc, sub_id: String, num_turns: u32 return; } + let _history_guard = sess.acquire_history_persistence_lock().await; let has_active_turn = { sess.active_turn.lock().await.is_some() }; if has_active_turn { sess.send_event_raw(Event { diff --git a/codex-rs/core/src/session/history_reconciliation.rs b/codex-rs/core/src/session/history_reconciliation.rs new file mode 100644 index 0000000000..7cae61650d --- /dev/null +++ b/codex-rs/core/src/session/history_reconciliation.rs @@ -0,0 +1,429 @@ +//! Reconciles a loaded running session with its authoritative persisted rollout. + +mod cursor; +mod install; + +pub(super) use self::install::AutoCompactWindowInstallMode; +pub(super) use self::install::RolloutHistoryInstallMode; +pub(super) use self::install::RolloutReconstructionInstallOptions; +pub(super) use self::install::history_contains_token_budget_reminder; + +use self::cursor::PersistedCursorComparison; +use self::cursor::advance_persisted_history_cursor; +pub(super) use self::cursor::empty_persisted_history_cursor; +use self::cursor::is_persisted_history_rewrite_item; +pub(super) use self::cursor::persisted_history_cursor; +use self::cursor::persisted_suffix_after_cursor; +use super::session::Session; +use crate::codex_thread::ThreadHistoryReconciliationOutcome; +use crate::codex_thread::ThreadHistoryReconciliationSnapshot; +use crate::context_manager::ContextManager; +use crate::image_preparation::prepare_response_items; +use crate::state::PersistedHistoryCursorUncertainty; +use codex_app_server_protocol::ThreadHistoryBuilder; +use codex_app_server_protocol::TurnStatus; +use codex_protocol::config_types::AutoCompactTokenLimitScope; +use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::TruncationPolicy; +use std::sync::Arc; + +pub(super) struct HistoryReconciliationConfig { + pub(super) truncation_policy: TruncationPolicy, + pub(super) auto_compact_token_limit_scope: AutoCompactTokenLimitScope, +} + +impl Session { + pub(crate) async fn acquire_history_persistence_lock( + &self, + ) -> tokio::sync::OwnedMutexGuard<()> { + Arc::clone(&self.history_persistence_lock) + .lock_owned() + .await + } + + pub(crate) async fn acquire_rollout_persistence_lock( + &self, + ) -> tokio::sync::OwnedMutexGuard<()> { + Arc::clone(&self.rollout_persistence_lock) + .lock_owned() + .await + } + + pub(super) async fn acquire_event_delivery_lock(&self) -> tokio::sync::OwnedMutexGuard<()> { + Arc::clone(&self.event_delivery_lock).lock_owned().await + } + + pub(crate) async fn acquire_history_reconciliation_event_cut( + &self, + ) -> ( + tokio::sync::OwnedMutexGuard<()>, + tokio::sync::OwnedMutexGuard<()>, + tokio::sync::OwnedMutexGuard<()>, + ) { + // History mutations can emit events while holding the history lock, so preserve the + // global history -> event delivery -> rollout lock order. + let history_guard = self.acquire_history_persistence_lock().await; + let event_delivery_guard = self.acquire_event_delivery_lock().await; + let rollout_guard = self.acquire_rollout_persistence_lock().await; + (history_guard, event_delivery_guard, rollout_guard) + } + + pub(crate) async fn note_persisted_non_metadata_items( + &self, + _rollout_guard: &tokio::sync::OwnedMutexGuard<()>, + items: &[RolloutItem], + ) { + let mut state = self.state.lock().await; + if let Some(cursor) = state.known_persisted_history_cursor() { + state.set_known_persisted_history_cursor(advance_persisted_history_cursor( + cursor, items, + )); + } else if state.persisted_history_cursor_uncertainty().is_some() { + let expected_cursor = state + .uncertain_expected_persisted_history_cursor() + .and_then(|cursor| advance_persisted_history_cursor(cursor, items)); + state.set_uncertain_expected_persisted_history_cursor(expected_cursor); + } + } + + pub(crate) async fn invalidate_persisted_item_cursor( + &self, + _rollout_guard: &tokio::sync::OwnedMutexGuard<()>, + items: &[RolloutItem], + ) { + let uncertainty = if items.iter().any(is_persisted_history_rewrite_item) { + PersistedHistoryCursorUncertainty::HistoryRewrite + } else { + PersistedHistoryCursorUncertainty::AppendOnly + }; + let mut state = self.state.lock().await; + let expected_cursor = state + .known_persisted_history_cursor() + .or_else(|| state.uncertain_expected_persisted_history_cursor()) + .and_then(|cursor| advance_persisted_history_cursor(cursor, items)); + state.invalidate_persisted_item_cursor(uncertainty, expected_cursor); + } + + #[expect( + clippy::await_holding_invalid_type, + reason = "history snapshots must stay atomic with the active-turn check" + )] + pub(crate) async fn history_reconciliation_snapshot( + &self, + ) -> Option { + let active_turn = self.active_turn.lock().await; + if active_turn.is_some() { + return None; + } + let state = self.state.lock().await; + Some(ThreadHistoryReconciliationSnapshot { + history: state.history.raw_items().to_vec(), + history_version: state.history.history_version(), + known_persisted_incomplete_tail: state.known_persisted_incomplete_tail(), + known_persisted_history_cursor: state.known_persisted_history_cursor(), + persisted_history_cursor_uncertainty: state.persisted_history_cursor_uncertainty(), + uncertain_expected_persisted_history_cursor: state + .uncertain_expected_persisted_history_cursor(), + }) + } + + #[expect( + clippy::await_holding_invalid_type, + reason = "history replacement must stay atomic with the final active-turn check" + )] + pub(crate) async fn reconcile_persisted_history( + &self, + snapshot: ThreadHistoryReconciliationSnapshot, + rollout_items: &[RolloutItem], + ) -> ThreadHistoryReconciliationOutcome { + let persisted_incomplete_tail = persisted_rollout_incomplete_turn_id(rollout_items); + { + let active_turn = self.active_turn.lock().await; + if active_turn.is_some() { + return ThreadHistoryReconciliationOutcome::Busy; + } + } + // Incremental replay is safe only when the loaded rollout still has the exact known + // non-metadata prefix. A mismatch means another writer interleaved before a local append, + // so fall back to canonical reconstruction instead of duplicating already-applied items. + let requires_uncertain_cursor_proof = snapshot.known_persisted_history_cursor.is_none() + && snapshot.persisted_history_cursor_uncertainty.is_some() + && snapshot + .uncertain_expected_persisted_history_cursor + .is_some(); + let reconciliation_cursor = match snapshot.known_persisted_history_cursor { + Some(cursor) => Some(cursor), + None if snapshot.persisted_history_cursor_uncertainty.is_some() => { + if let Some(expected_cursor) = snapshot.uncertain_expected_persisted_history_cursor + { + Some(expected_cursor) + } else if matches!( + snapshot.persisted_history_cursor_uncertainty, + Some(PersistedHistoryCursorUncertainty::HistoryRewrite) + ) { + // Without a pre-failure cursor, model-history equality cannot prove that an + // event-only rollback or compaction marker became durable. Restart is the + // recovery boundary for this deliberately fail-closed state. + return ThreadHistoryReconciliationOutcome::Conflict; + } else { + None + } + } + None => None, + }; + let persisted_suffix = match reconciliation_cursor { + Some(cursor) => match persisted_suffix_after_cursor(rollout_items, cursor) { + PersistedCursorComparison::Matched(suffix) => Some(suffix), + PersistedCursorComparison::Mismatched => { + if requires_uncertain_cursor_proof { + return ThreadHistoryReconciliationOutcome::Conflict; + } + None + } + PersistedCursorComparison::Shorter => { + return ThreadHistoryReconciliationOutcome::Conflict; + } + }, + None => None, + }; + let uncertainty_proven_by_cursor = + requires_uncertain_cursor_proof && persisted_suffix.is_some(); + let imports_compaction = persisted_suffix.is_some_and(|suffix| { + suffix + .iter() + .any(|item| matches!(item, RolloutItem::Compacted(_))) + }); + let imports_history_rewrite = persisted_suffix.is_some_and(|suffix| { + suffix.iter().any(|item| { + matches!( + item, + RolloutItem::Compacted(_) + | RolloutItem::EventMsg(EventMsg::ThreadRolledBack(_)) + ) + }) + }); + + let reconciliation_config = self.history_reconciliation_config().await; + let mut reconstruction = self + .reconstruct_history_from_rollout_with_policy( + reconciliation_config.truncation_policy, + rollout_items, + ) + .await; + prepare_response_items(&mut reconstruction.history); + if let Some(persisted_suffix) = persisted_suffix + && let Some(history) = reconcile_model_history_from_persisted_suffix( + &snapshot.history, + persisted_suffix, + reconciliation_config.truncation_policy, + ) + { + reconstruction.history = history; + } + let final_history_extends_snapshot = reconstruction.history.starts_with(&snapshot.history); + match snapshot.persisted_history_cursor_uncertainty { + Some(PersistedHistoryCursorUncertainty::AppendOnly) + if !uncertainty_proven_by_cursor && !final_history_extends_snapshot => + { + // An append error does not reveal whether storage accepted the item. Never let an + // older or divergent read replace authoritative in-memory history in that state. + // Exact cursor agreement proves that the ambiguous append landed; without it, + // only exact model-history matches and strict extensions provide that proof. + return ThreadHistoryReconciliationOutcome::Conflict; + } + _ => {} + } + let imports_effective_rollback = persisted_suffix.map_or_else( + || { + rollout_items.iter().any(|item| { + matches!(item, RolloutItem::EventMsg(EventMsg::ThreadRolledBack(_))) + }) && !reconstruction.history.starts_with(&snapshot.history) + }, + |suffix| { + suffix.iter().any(|item| { + matches!(item, RolloutItem::EventMsg(EventMsg::ThreadRolledBack(_))) + }) + }, + ); + let token_info = Self::last_token_info_from_rollout(rollout_items); + let token_budget_reminder_delivered = + history_contains_token_budget_reminder(&reconstruction.history); + + let active_turn = self.active_turn.lock().await; + if active_turn.is_some() { + return ThreadHistoryReconciliationOutcome::Busy; + } + let mut state = self.state.lock().await; + if state.history.history_version() != snapshot.history_version + || state.history.raw_items() != snapshot.history + || state.known_persisted_incomplete_tail().as_ref() + != snapshot.known_persisted_incomplete_tail.as_ref() + || state.known_persisted_history_cursor() != snapshot.known_persisted_history_cursor + || state.persisted_history_cursor_uncertainty() + != snapshot.persisted_history_cursor_uncertainty + || state.uncertain_expected_persisted_history_cursor() + != snapshot.uncertain_expected_persisted_history_cursor + { + return ThreadHistoryReconciliationOutcome::Conflict; + } + + if persisted_incomplete_tail.is_some() + && (persisted_incomplete_tail.as_ref() + != snapshot.known_persisted_incomplete_tail.as_ref() + || state.history.raw_items() != reconstruction.history) + { + return ThreadHistoryReconciliationOutcome::Incomplete; + } + + let outcome = if state.history.raw_items() == reconstruction.history { + ThreadHistoryReconciliationOutcome::Unchanged + } else { + ThreadHistoryReconciliationOutcome::Refreshed + }; + let fallback_window_ids = state.auto_compact_window_ids(); + let reconstructed_window_ids = Self::rollout_reconstruction_window_ids( + reconstruction.first_window_id, + reconstruction.previous_window_id, + reconstruction.window_id, + fallback_window_ids, + ); + let preserves_auto_compact_window = reconstruction.window_number + == state.auto_compact_window_number() + && reconstructed_window_ids == fallback_window_ids; + let imports_unconsumed_compaction = persisted_suffix.map_or_else( + || { + // A cursor mismatch forces canonical reconstruction, so there is no trustworthy + // suffix. A changed compaction-window identity still proves that the newest + // surviving compaction was imported. The newly installed full cursor makes this + // fallback one-shot on the next reconciliation. + !preserves_auto_compact_window && rollout_has_unconsumed_compaction(rollout_items) + }, + rollout_has_unconsumed_compaction, + ); + let preserves_append_only_prefill = final_history_extends_snapshot + && !imports_history_rewrite + && (persisted_suffix.is_some() + || snapshot.persisted_history_cursor_uncertainty.is_some()); + let preserves_rollback_prefill = + imports_effective_rollback && !imports_compaction && preserves_auto_compact_window; + let preserve_auto_compact_prefill = + matches!(outcome, ThreadHistoryReconciliationOutcome::Refreshed) + && (preserves_append_only_prefill || preserves_rollback_prefill); + let history_install = if matches!(outcome, ThreadHistoryReconciliationOutcome::Refreshed) { + if preserve_auto_compact_prefill { + RolloutHistoryInstallMode::ReplacePreservingAutoCompactPrefill + } else { + RolloutHistoryInstallMode::Replace + } + } else { + RolloutHistoryInstallMode::KeepExisting + }; + Self::install_rollout_reconstruction( + &mut state, + reconciliation_config.auto_compact_token_limit_scope, + reconstruction, + RolloutReconstructionInstallOptions { + token_info, + history: history_install, + auto_compact_window: AutoCompactWindowInstallMode::Reconcile, + token_budget_reminder_delivered, + }, + ); + if imports_unconsumed_compaction { + // Compaction queues this lifecycle source locally after replacing history. Mirror that + // transition only when no later turn has already consumed it in the other process. + state.queue_pending_session_start_source(codex_hooks::SessionStartSource::Compact); + } + state.set_known_persisted_incomplete_tail(persisted_incomplete_tail); + if imports_history_rewrite + || matches!(outcome, ThreadHistoryReconciliationOutcome::Refreshed) + { + state.reset_additional_context(); + } + if snapshot.known_persisted_history_cursor.is_some() + || snapshot.persisted_history_cursor_uncertainty.is_some() + || self.live_thread().is_some() + { + state.set_known_persisted_history_cursor(persisted_history_cursor(rollout_items)); + } + drop(state); + if let Some(live_thread) = self.live_thread() { + live_thread.seed_metadata_from_history(rollout_items).await; + } + if imports_effective_rollback { + self.services + .agent_control + .rollout_budget() + .rearm_reminder(self.thread_id()); + } + drop(active_turn); + outcome + } +} + +fn rollout_has_unconsumed_compaction(items: &[RolloutItem]) -> bool { + items + .iter() + .rposition(|item| matches!(item, RolloutItem::Compacted(_))) + .is_some_and(|compaction_index| { + !items[compaction_index + 1..] + .iter() + .any(|item| matches!(item, RolloutItem::EventMsg(EventMsg::TurnStarted(_)))) + }) +} + +pub(super) fn persisted_rollout_incomplete_turn_id( + rollout_items: &[RolloutItem], +) -> Option { + let mut history = ThreadHistoryBuilder::new(); + for item in rollout_items { + history.handle_rollout_item(item); + } + if !history.has_active_turn() { + return None; + } + let turn = history.active_turn_snapshot()?; + matches!(turn.status, TurnStatus::InProgress | TurnStatus::Failed).then_some(turn.id) +} + +fn reconcile_model_history_from_persisted_suffix( + snapshot_history: &[ResponseItem], + persisted_suffix: &[RolloutItem], + truncation_policy: TruncationPolicy, +) -> Option> { + if persisted_suffix + .iter() + .any(|item| matches!(item, RolloutItem::Compacted(_))) + { + return None; + } + + let mut history = ContextManager::new(); + history.replace(snapshot_history.to_vec()); + for item in persisted_suffix { + match item { + RolloutItem::ResponseItem(response_item) => { + let mut response_items = vec![response_item.clone()]; + prepare_response_items(&mut response_items); + history.record_items(response_items.iter(), truncation_policy); + } + RolloutItem::InterAgentCommunication(communication) => { + let mut response_items = vec![communication.to_model_input_item()]; + prepare_response_items(&mut response_items); + history.record_items(response_items.iter(), truncation_policy); + } + RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => { + history.drop_last_n_user_turns(rollback.num_turns); + } + RolloutItem::InterAgentCommunicationMetadata { .. } + | RolloutItem::EventMsg(_) + | RolloutItem::TurnContext(_) + | RolloutItem::WorldState(_) + | RolloutItem::SessionMeta(_) => {} + RolloutItem::Compacted(_) => unreachable!("compaction was rejected above"), + } + } + Some(history.raw_items().to_vec()) +} diff --git a/codex-rs/core/src/session/history_reconciliation/cursor.rs b/codex-rs/core/src/session/history_reconciliation/cursor.rs new file mode 100644 index 0000000000..b3e8246663 --- /dev/null +++ b/codex-rs/core/src/session/history_reconciliation/cursor.rs @@ -0,0 +1,117 @@ +//! Logical persisted-rollout cursors used to prove append and rewrite boundaries. + +use crate::state::PersistedHistoryCursor; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; +use codex_rollout::is_persisted_rollout_item; +use serde_json::Value; +use sha1::Digest; +use sha1::Sha1; + +fn is_persisted_non_metadata_item(item: &RolloutItem) -> bool { + is_persisted_rollout_item(item) && !matches!(item, RolloutItem::SessionMeta(_)) +} + +pub(super) fn is_persisted_history_rewrite_item(item: &RolloutItem) -> bool { + matches!( + item, + RolloutItem::Compacted(_) | RolloutItem::EventMsg(EventMsg::ThreadRolledBack(_)) + ) +} + +pub(in crate::session) fn empty_persisted_history_cursor() -> PersistedHistoryCursor { + PersistedHistoryCursor { + item_count: 0, + fingerprint: [0; 20], + } +} + +pub(in crate::session) fn persisted_history_cursor( + items: &[RolloutItem], +) -> Option { + advance_persisted_history_cursor(empty_persisted_history_cursor(), items) +} + +pub(super) fn advance_persisted_history_cursor( + mut cursor: PersistedHistoryCursor, + items: &[RolloutItem], +) -> Option { + for item in items + .iter() + .filter(|item| is_persisted_non_metadata_item(item)) + { + let encoded = canonical_rollout_item_bytes(item)?; + let encoded_len = u64::try_from(encoded.len()).ok()?; + let mut hasher = Sha1::new(); + hasher.update(cursor.fingerprint); + hasher.update(encoded_len.to_le_bytes()); + hasher.update(encoded); + cursor.fingerprint = hasher.finalize().into(); + cursor.item_count = cursor.item_count.saturating_add(1); + } + Some(cursor) +} + +fn canonical_rollout_item_bytes(item: &RolloutItem) -> Option> { + let value = serde_json::to_value(item).ok()?; + serde_json::to_vec(&canonicalize_json_value(value)).ok() +} + +fn canonicalize_json_value(value: Value) -> Value { + match value { + Value::Array(values) => { + Value::Array(values.into_iter().map(canonicalize_json_value).collect()) + } + Value::Object(values) => { + let mut entries = values.into_iter().collect::>(); + entries.sort_by(|(left, _), (right, _)| left.cmp(right)); + let mut sorted = serde_json::Map::new(); + for (key, value) in entries { + sorted.insert(key, canonicalize_json_value(value)); + } + Value::Object(sorted) + } + primitive => primitive, + } +} + +pub(super) enum PersistedCursorComparison<'a> { + Matched(&'a [RolloutItem]), + Mismatched, + Shorter, +} + +/// Validates the known logical prefix, deliberately ignoring metadata-only `SessionMeta` +/// appends, then maps it back to a raw rollout suffix. +pub(super) fn persisted_suffix_after_cursor( + items: &[RolloutItem], + known_cursor: PersistedHistoryCursor, +) -> PersistedCursorComparison<'_> { + let mut loaded_cursor = empty_persisted_history_cursor(); + if known_cursor.item_count == 0 { + return if loaded_cursor == known_cursor { + PersistedCursorComparison::Matched(items) + } else { + PersistedCursorComparison::Mismatched + }; + } + for (raw_index, item) in items.iter().enumerate() { + if !is_persisted_non_metadata_item(item) { + continue; + } + let Some(next_cursor) = + advance_persisted_history_cursor(loaded_cursor, std::slice::from_ref(item)) + else { + return PersistedCursorComparison::Mismatched; + }; + loaded_cursor = next_cursor; + if loaded_cursor.item_count == known_cursor.item_count { + return if loaded_cursor.fingerprint == known_cursor.fingerprint { + PersistedCursorComparison::Matched(&items[raw_index + 1..]) + } else { + PersistedCursorComparison::Mismatched + }; + } + } + PersistedCursorComparison::Shorter +} diff --git a/codex-rs/core/src/session/history_reconciliation/cursor_recovery_tests.rs b/codex-rs/core/src/session/history_reconciliation/cursor_recovery_tests.rs new file mode 100644 index 0000000000..d305871ba6 --- /dev/null +++ b/codex-rs/core/src/session/history_reconciliation/cursor_recovery_tests.rs @@ -0,0 +1,438 @@ +use super::*; +use pretty_assertions::assert_eq; + +#[tokio::test] +async fn reconcile_persisted_history_rejects_loaded_prefix_shorter_than_cursor() { + let (session, _turn_context) = make_session_and_context().await; + let mut local_history = model_history_for_turn("first user", "first assistant"); + local_history.extend(model_history_for_turn("second user", "second assistant")); + session.replace_history(local_history.clone(), None).await; + + let mut full_rollout = completed_turn("turn-1", "first user", "first assistant"); + full_rollout.extend(completed_turn("turn-2", "second user", "second assistant")); + session + .state + .lock() + .await + .set_known_persisted_history_cursor(persisted_history_cursor(&full_rollout)); + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let shorter_rollout = completed_turn("turn-1", "first user", "first assistant"); + + let outcome = session + .reconcile_persisted_history(snapshot, &shorter_rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Conflict); + assert_eq!(session.clone_history().await.raw_items(), local_history); +} + +#[test] +fn persisted_cursor_canonicalizes_nested_map_order_and_round_trip() { + let mut left_env = HashMap::new(); + left_env.insert("ALPHA".to_string(), "1".to_string()); + left_env.insert("BETA".to_string(), "2".to_string()); + let mut right_env = HashMap::new(); + right_env.insert("BETA".to_string(), "2".to_string()); + right_env.insert("ALPHA".to_string(), "1".to_string()); + let left = local_shell_call(left_env); + let right = local_shell_call(right_env); + let round_tripped: RolloutItem = + serde_json::from_slice(&serde_json::to_vec(&left).expect("serialize rollout item")) + .expect("deserialize rollout item"); + + assert_eq!( + persisted_history_cursor(std::slice::from_ref(&left)), + persisted_history_cursor(std::slice::from_ref(&right)) + ); + assert_eq!( + persisted_history_cursor(std::slice::from_ref(&left)), + persisted_history_cursor(std::slice::from_ref(&round_tripped)) + ); +} + +#[tokio::test] +async fn persisted_cursor_does_not_advance_for_session_metadata_append() { + let (session, _turn_context) = make_session_and_context().await; + let prefix = completed_turn("turn-1", "first user", "first assistant"); + let cursor = persisted_history_cursor(&prefix); + session + .state + .lock() + .await + .set_known_persisted_history_cursor(cursor); + let rollout_guard = session.acquire_rollout_persistence_lock().await; + + session + .note_persisted_non_metadata_items(&rollout_guard, &[session_meta(session.thread_id())]) + .await; + + assert_eq!( + session.state.lock().await.known_persisted_history_cursor(), + cursor + ); +} + +#[tokio::test] +async fn failed_persisted_append_invalidates_cursor() { + let (session, _turn_context) = make_session_and_context().await; + let prefix = completed_turn("turn-1", "first user", "first assistant"); + session + .state + .lock() + .await + .set_known_persisted_history_cursor(persisted_history_cursor(&prefix)); + let rollout_guard = session.acquire_rollout_persistence_lock().await; + + session + .invalidate_persisted_item_cursor( + &rollout_guard, + &[RolloutItem::ResponseItem(assistant_message( + "ambiguous append", + ))], + ) + .await; + + assert_eq!( + session.state.lock().await.known_persisted_history_cursor(), + None + ); + assert_eq!( + session + .state + .lock() + .await + .persisted_history_cursor_uncertainty(), + Some(PersistedHistoryCursorUncertainty::AppendOnly) + ); +} + +#[tokio::test] +async fn persisted_cursor_uncertainty_only_upgrades_to_history_rewrite() { + let (session, _turn_context) = make_session_and_context().await; + let mut expected_rollout = completed_turn("turn-1", "first user", "first assistant"); + session + .state + .lock() + .await + .set_known_persisted_history_cursor(persisted_history_cursor(&expected_rollout)); + let rollout_guard = session.acquire_rollout_persistence_lock().await; + let append = RolloutItem::ResponseItem(assistant_message("ambiguous append")); + let successful_append = RolloutItem::ResponseItem(assistant_message("successful append")); + let rollback = RolloutItem::EventMsg(EventMsg::ThreadRolledBack(ThreadRolledBackEvent { + num_turns: 1, + })); + + session + .invalidate_persisted_item_cursor(&rollout_guard, std::slice::from_ref(&append)) + .await; + session + .note_persisted_non_metadata_items(&rollout_guard, std::slice::from_ref(&successful_append)) + .await; + session + .invalidate_persisted_item_cursor(&rollout_guard, std::slice::from_ref(&rollback)) + .await; + session + .invalidate_persisted_item_cursor(&rollout_guard, std::slice::from_ref(&append)) + .await; + + assert_eq!( + session + .state + .lock() + .await + .persisted_history_cursor_uncertainty(), + Some(PersistedHistoryCursorUncertainty::HistoryRewrite) + ); + expected_rollout.extend([append.clone(), successful_append, rollback, append]); + assert_eq!( + session + .state + .lock() + .await + .uncertain_expected_persisted_history_cursor(), + persisted_history_cursor(&expected_rollout) + ); +} + +#[tokio::test] +async fn uncertain_persisted_cursor_never_replaces_valid_in_memory_tail() { + let (session, _turn_context) = make_session_and_context().await; + let mut persisted_prefix = completed_turn("turn-1", "first user", "first assistant"); + let local_tail = assistant_message("valid local tail after uncertain append"); + let mut local_history = model_history_for_turn("first user", "first assistant"); + local_history.push(local_tail.clone()); + session.replace_history(local_history.clone(), None).await; + session + .state + .lock() + .await + .set_known_persisted_history_cursor(persisted_history_cursor(&persisted_prefix)); + let rollout_guard = session.acquire_rollout_persistence_lock().await; + session + .invalidate_persisted_item_cursor( + &rollout_guard, + &[RolloutItem::ResponseItem(local_tail.clone())], + ) + .await; + drop(rollout_guard); + + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let outcome = session + .reconcile_persisted_history(snapshot, &persisted_prefix) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Conflict); + assert_eq!(session.clone_history().await.raw_items(), local_history); + assert_eq!( + session + .state + .lock() + .await + .persisted_history_cursor_uncertainty(), + Some(PersistedHistoryCursorUncertainty::AppendOnly) + ); + + // If a later read proves the exact ambiguous append reached storage, reconciliation can + // re-establish the cursor without rewriting authoritative in-memory history. + persisted_prefix.push(RolloutItem::ResponseItem(local_tail)); + let retry_snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle retry snapshot"); + let retry_outcome = session + .reconcile_persisted_history(retry_snapshot, &persisted_prefix) + .await; + assert_eq!(retry_outcome, ThreadHistoryReconciliationOutcome::Unchanged); + { + let state = session.state.lock().await; + assert_eq!( + state.known_persisted_history_cursor(), + persisted_history_cursor(&persisted_prefix) + ); + assert_eq!(state.persisted_history_cursor_uncertainty(), None); + } + + let second_ambiguous_append = assistant_message("second ambiguous append"); + let mut local_history_with_second_append = local_history.clone(); + local_history_with_second_append.push(second_ambiguous_append.clone()); + session + .replace_history(local_history_with_second_append.clone(), None) + .await; + let rollout_guard = session.acquire_rollout_persistence_lock().await; + session + .invalidate_persisted_item_cursor( + &rollout_guard, + &[RolloutItem::ResponseItem(second_ambiguous_append.clone())], + ) + .await; + drop(rollout_guard); + persisted_prefix.push(RolloutItem::ResponseItem(second_ambiguous_append)); + persisted_prefix.extend(completed_turn( + "turn-2", + "external user", + "external assistant", + )); + let extension_snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle extension snapshot"); + let extension_outcome = session + .reconcile_persisted_history(extension_snapshot, &persisted_prefix) + .await; + assert_eq!( + extension_outcome, + ThreadHistoryReconciliationOutcome::Refreshed + ); + let mut expected = local_history_with_second_append; + expected.extend(model_history_for_turn( + "external user", + "external assistant", + )); + assert_eq!(session.clone_history().await.raw_items(), expected); + let state = session.state.lock().await; + assert_eq!( + state.known_persisted_history_cursor(), + persisted_history_cursor(&persisted_prefix) + ); + assert_eq!(state.persisted_history_cursor_uncertainty(), None); +} + +#[tokio::test] +async fn uncertain_append_proven_by_cursor_allows_persisted_rollback_suffix() { + let (session, _turn_context) = make_session_and_context().await; + let first_turn = completed_turn("turn-1", "first user", "first assistant"); + let second_turn = completed_turn("turn-2", "second user", "second assistant"); + let first_history = model_history_for_turn("first user", "first assistant"); + let mut local_history = first_history.clone(); + local_history.extend(model_history_for_turn("second user", "second assistant")); + session.replace_history(local_history, None).await; + session + .state + .lock() + .await + .set_known_persisted_history_cursor(persisted_history_cursor(&first_turn)); + let rollout_guard = session.acquire_rollout_persistence_lock().await; + session + .invalidate_persisted_item_cursor(&rollout_guard, &second_turn) + .await; + drop(rollout_guard); + + let rollback = RolloutItem::EventMsg(EventMsg::ThreadRolledBack(ThreadRolledBackEvent { + num_turns: 1, + })); + let mut landed_rollout = first_turn; + landed_rollout.extend(second_turn); + landed_rollout.push(rollback); + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let outcome = session + .reconcile_persisted_history(snapshot, &landed_rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); + assert_eq!(session.clone_history().await.raw_items(), first_history); + let state = session.state.lock().await; + assert_eq!(state.persisted_history_cursor_uncertainty(), None); + assert_eq!( + state.known_persisted_history_cursor(), + persisted_history_cursor(&landed_rollout) + ); +} + +#[tokio::test] +async fn uncertain_history_rewrite_never_restores_pre_rollback_disk_history() { + let (session, _turn_context) = make_session_and_context().await; + let first_turn = completed_turn("turn-1", "first user", "first assistant"); + let second_turn = completed_turn("turn-2", "second user", "second assistant"); + let mut pre_rollback_rollout = first_turn.clone(); + pre_rollback_rollout.extend(second_turn); + let first_history = model_history_for_turn("first user", "first assistant"); + session.replace_history(first_history.clone(), None).await; + session + .state + .lock() + .await + .set_known_persisted_history_cursor(persisted_history_cursor(&pre_rollback_rollout)); + let rollback = RolloutItem::EventMsg(EventMsg::ThreadRolledBack(ThreadRolledBackEvent { + num_turns: 1, + })); + let rollout_guard = session.acquire_rollout_persistence_lock().await; + session + .invalidate_persisted_item_cursor(&rollout_guard, std::slice::from_ref(&rollback)) + .await; + drop(rollout_guard); + + let stale_snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let stale_outcome = session + .reconcile_persisted_history(stale_snapshot, &pre_rollback_rollout) + .await; + + assert_eq!(stale_outcome, ThreadHistoryReconciliationOutcome::Conflict); + assert_eq!(session.clone_history().await.raw_items(), first_history); + assert_eq!( + session + .state + .lock() + .await + .persisted_history_cursor_uncertainty(), + Some(PersistedHistoryCursorUncertainty::HistoryRewrite) + ); + + let mut landed_rollout = pre_rollback_rollout; + landed_rollout.push(rollback); + let landed_snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle retry snapshot"); + let landed_outcome = session + .reconcile_persisted_history(landed_snapshot, &landed_rollout) + .await; + + assert_eq!( + landed_outcome, + ThreadHistoryReconciliationOutcome::Unchanged + ); + assert_eq!(session.clone_history().await.raw_items(), first_history); + let state = session.state.lock().await; + assert_eq!(state.persisted_history_cursor_uncertainty(), None); + assert_eq!( + state.known_persisted_history_cursor(), + persisted_history_cursor(&landed_rollout) + ); +} + +#[tokio::test] +async fn uncertain_event_only_rollback_requires_the_durable_marker() { + let (session, _turn_context) = make_session_and_context().await; + let mut pre_rollback_rollout = vec![turn_started("event-only-turn")]; + pre_rollback_rollout.push(turn_complete("event-only-turn")); + session.replace_history(Vec::new(), None).await; + session + .state + .lock() + .await + .set_known_persisted_history_cursor(persisted_history_cursor(&pre_rollback_rollout)); + let rollback = RolloutItem::EventMsg(EventMsg::ThreadRolledBack(ThreadRolledBackEvent { + num_turns: 1, + })); + let rollout_guard = session.acquire_rollout_persistence_lock().await; + session + .invalidate_persisted_item_cursor(&rollout_guard, std::slice::from_ref(&rollback)) + .await; + drop(rollout_guard); + + let stale_snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let stale_outcome = session + .reconcile_persisted_history(stale_snapshot, &pre_rollback_rollout) + .await; + + assert_eq!(stale_outcome, ThreadHistoryReconciliationOutcome::Conflict); + assert!(session.clone_history().await.raw_items().is_empty()); + let mut expected_landed_rollout = pre_rollback_rollout.clone(); + expected_landed_rollout.push(rollback.clone()); + { + let state = session.state.lock().await; + assert_eq!( + state.persisted_history_cursor_uncertainty(), + Some(PersistedHistoryCursorUncertainty::HistoryRewrite) + ); + assert_eq!( + state.uncertain_expected_persisted_history_cursor(), + persisted_history_cursor(&expected_landed_rollout) + ); + } + + let landed_snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle retry snapshot"); + let landed_outcome = session + .reconcile_persisted_history(landed_snapshot, &expected_landed_rollout) + .await; + + assert_eq!( + landed_outcome, + ThreadHistoryReconciliationOutcome::Unchanged + ); + assert!(session.clone_history().await.raw_items().is_empty()); + let state = session.state.lock().await; + assert_eq!(state.persisted_history_cursor_uncertainty(), None); + assert_eq!( + state.known_persisted_history_cursor(), + persisted_history_cursor(&expected_landed_rollout) + ); +} diff --git a/codex-rs/core/src/session/history_reconciliation/install.rs b/codex-rs/core/src/session/history_reconciliation/install.rs new file mode 100644 index 0000000000..ded4f92171 --- /dev/null +++ b/codex-rs/core/src/session/history_reconciliation/install.rs @@ -0,0 +1,146 @@ +//! Installs reconstructed rollout history and compaction-window metadata. + +use crate::context::ContextualUserFragment; +use crate::context::TokenBudgetReminder; +use crate::session::PreviousTurnSettings; +use crate::session::rollout_reconstruction; +use crate::session::session::Session; +use crate::state::AutoCompactWindowIds; +use crate::state::SessionState; +use codex_protocol::config_types::AutoCompactTokenLimitScope; +use codex_protocol::models::BaseInstructions; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::TokenUsageInfo; +use uuid::Uuid; + +pub(in crate::session) enum RolloutHistoryInstallMode { + KeepExisting, + Replace, + ReplacePreservingAutoCompactPrefill, +} + +pub(in crate::session) enum AutoCompactWindowInstallMode { + Reconcile, + Restore, +} + +pub(in crate::session) struct RolloutReconstructionInstallOptions { + pub(in crate::session) token_info: Option, + pub(in crate::session) history: RolloutHistoryInstallMode, + pub(in crate::session) auto_compact_window: AutoCompactWindowInstallMode, + pub(in crate::session) token_budget_reminder_delivered: bool, +} + +pub(in crate::session) fn history_contains_token_budget_reminder(history: &[ResponseItem]) -> bool { + history.iter().any(|item| { + let ResponseItem::Message { role, content, .. } = item else { + return false; + }; + role == "developer" + && content.iter().any(|content| { + matches!( + content, + ContentItem::InputText { text } + if TokenBudgetReminder::matches_text(text) + ) + }) + }) +} + +impl Session { + pub(in crate::session) fn install_rollout_reconstruction( + state: &mut SessionState, + auto_compact_token_limit_scope: AutoCompactTokenLimitScope, + reconstruction: rollout_reconstruction::RolloutReconstruction, + options: RolloutReconstructionInstallOptions, + ) -> Option { + let RolloutReconstructionInstallOptions { + token_info, + history: history_install, + auto_compact_window, + token_budget_reminder_delivered, + } = options; + let rollout_reconstruction::RolloutReconstruction { + history, + previous_turn_settings, + reference_context_item, + world_state_baseline, + window_number, + first_window_id, + previous_window_id, + window_id, + } = reconstruction; + match history_install { + RolloutHistoryInstallMode::ReplacePreservingAutoCompactPrefill => { + state.replace_history_preserving_auto_compact_prefill( + history, + reference_context_item, + ); + state + .history + .replace_world_state_baseline(world_state_baseline); + } + RolloutHistoryInstallMode::Replace => { + state.replace_history(history, reference_context_item); + state + .history + .replace_world_state_baseline(world_state_baseline); + } + RolloutHistoryInstallMode::KeepExisting => { + state.set_reference_context_item(reference_context_item); + state + .history + .replace_world_state_baseline(world_state_baseline); + } + } + let ids = Self::rollout_reconstruction_window_ids( + first_window_id, + previous_window_id, + window_id, + state.auto_compact_window_ids(), + ); + match auto_compact_window { + AutoCompactWindowInstallMode::Reconcile => { + state.reconcile_auto_compact_window(window_number, ids); + } + AutoCompactWindowInstallMode::Restore => { + state.restore_auto_compact_window(window_number, ids); + } + } + state.set_token_budget_reminder_delivered(token_budget_reminder_delivered); + state.set_previous_turn_settings(previous_turn_settings.clone()); + if let Some(token_info) = token_info { + state.set_token_info(Some(token_info)); + } + if matches!( + auto_compact_token_limit_scope, + AutoCompactTokenLimitScope::BodyAfterPrefix + ) { + let base_instructions = BaseInstructions { + text: state.session_configuration.base_instructions.clone(), + }; + if let Some(prefix_tokens) = state + .history + .estimate_token_count_with_base_instructions(&base_instructions) + { + state.set_auto_compact_window_estimated_prefill(prefix_tokens); + } + } + previous_turn_settings + } + + pub(super) fn rollout_reconstruction_window_ids( + first_window_id: Option, + previous_window_id: Option, + window_id: Option, + fallback_ids: AutoCompactWindowIds, + ) -> AutoCompactWindowIds { + let window_id = window_id.unwrap_or(fallback_ids.window_id); + AutoCompactWindowIds { + first_window_id: first_window_id.unwrap_or(window_id), + previous_window_id, + window_id, + } + } +} diff --git a/codex-rs/core/src/session/history_reconciliation/reminder_state_tests.rs b/codex-rs/core/src/session/history_reconciliation/reminder_state_tests.rs new file mode 100644 index 0000000000..78a0a8fcf1 --- /dev/null +++ b/codex-rs/core/src/session/history_reconciliation/reminder_state_tests.rs @@ -0,0 +1,94 @@ +use super::*; +use codex_protocol::protocol::InitialHistory; +use codex_protocol::protocol::ResumedHistory; + +fn token_budget_reminder(turn_id: &str) -> ResponseItem { + let mut reminder = ContextualUserFragment::into(TokenBudgetReminder::new( + "reconciled reminder with {n_remaining} tokens", + /*n_remaining*/ 25, + )); + reminder.set_turn_id_if_missing(turn_id); + reminder +} + +#[tokio::test] +async fn reconcile_imported_same_window_reminder_restores_one_shot_latch() { + let (session, _turn_context) = make_session_and_context().await; + let first_history = model_history_for_turn("first user", "first assistant"); + session.replace_history(first_history.clone(), None).await; + let mut rollout = completed_turn("turn-1", "first user", "first assistant"); + { + let mut state = session.state.lock().await; + state.set_known_persisted_history_cursor(persisted_history_cursor(&rollout)); + } + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let reminder = token_budget_reminder("turn-2"); + let mut imported_turn = completed_turn("turn-2", "external user", "external assistant"); + imported_turn.insert( + imported_turn.len() - 1, + RolloutItem::ResponseItem(reminder.clone()), + ); + rollout.extend(imported_turn); + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); + let mut expected_history = first_history; + expected_history.extend(model_history_for_turn( + "external user", + "external assistant", + )); + expected_history.push(reminder); + let mut state = session.state.lock().await; + assert_eq!(state.history.raw_items(), expected_history); + assert!( + !state.claim_token_budget_reminder(), + "an imported current-window reminder must remain one-shot after reconciliation" + ); +} + +#[tokio::test] +async fn cold_restore_from_compacted_history_restores_reminder_latch() { + let (session, _turn_context) = make_session_and_context().await; + let reminder = token_budget_reminder("compact-turn"); + let first_window_id = Uuid::now_v7(); + let previous_window_id = Uuid::now_v7(); + let window_id = Uuid::now_v7(); + let rollout = vec![RolloutItem::Compacted(CompactedItem { + message: "summary".to_string(), + replacement_history: Some(vec![reminder.clone()]), + window_number: Some(7), + first_window_id: Some(first_window_id.to_string()), + previous_window_id: Some(previous_window_id.to_string()), + window_id: Some(window_id.to_string()), + })]; + + session + .record_initial_history(InitialHistory::Resumed(ResumedHistory { + conversation_id: session.thread_id(), + history: Arc::new(rollout), + rollout_path: None, + })) + .await; + + let mut state = session.state.lock().await; + assert_eq!(state.history.raw_items(), vec![reminder]); + assert_eq!(state.auto_compact_window_number(), 7); + assert_eq!( + state.auto_compact_window_ids(), + AutoCompactWindowIds { + first_window_id, + previous_window_id: Some(previous_window_id), + window_id, + } + ); + assert!( + !state.claim_token_budget_reminder(), + "a reminder surviving the compacted current window must remain one-shot after cold restore" + ); +} diff --git a/codex-rs/core/src/session/history_reconciliation/safety_and_locking_tests.rs b/codex-rs/core/src/session/history_reconciliation/safety_and_locking_tests.rs new file mode 100644 index 0000000000..5d54f048d9 --- /dev/null +++ b/codex-rs/core/src/session/history_reconciliation/safety_and_locking_tests.rs @@ -0,0 +1,591 @@ +use super::*; +use codex_protocol::items::HookPromptFragment; +use codex_protocol::items::build_hook_prompt_message; +use pretty_assertions::assert_eq; + +#[tokio::test] +async fn reconcile_persisted_history_hydrates_tokens_without_rewriting_equal_history() { + let (session, turn_context) = make_session_and_context().await; + let history = model_history_for_turn("user", "assistant"); + session.replace_history(history.clone(), None).await; + let old_info = token_usage_info(10); + let new_info = token_usage_info(25); + { + let mut state = session.state.lock().await; + state.set_token_info(Some(old_info)); + } + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let before_version = session.state.lock().await.history.history_version(); + let mut rollout = completed_turn("turn-1", "user", "assistant"); + let mut persisted_turn_context = turn_context.to_turn_context_item(); + persisted_turn_context.turn_id = Some("turn-1".to_string()); + rollout.insert(3, RolloutItem::TurnContext(persisted_turn_context.clone())); + rollout.push(RolloutItem::EventMsg(EventMsg::TokenCount( + TokenCountEvent { + info: Some(new_info.clone()), + rate_limits: None, + }, + ))); + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Unchanged); + let state = session.state.lock().await; + assert_eq!(state.history.raw_items(), history); + assert_eq!(state.history.history_version(), before_version); + assert_eq!(state.token_info(), Some(new_info)); + assert_eq!( + state.previous_turn_settings(), + Some(PreviousTurnSettings { + model: persisted_turn_context.model.clone(), + comp_hash: persisted_turn_context.comp_hash.clone(), + realtime_active: persisted_turn_context.realtime_active, + }) + ); + assert_eq!(state.reference_context_item(), Some(persisted_turn_context)); +} + +#[tokio::test] +async fn reconcile_persisted_history_prefers_busy_over_incomplete_tail() { + let (session, _turn_context) = make_session_and_context().await; + let history = model_history_for_turn("local user", "local assistant"); + session.replace_history(history.clone(), None).await; + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + *session.active_turn.lock().await = Some(ActiveTurn::default()); + + let outcome = session + .reconcile_persisted_history(snapshot, &[turn_started("running-turn")]) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Busy); + assert!(session.history_reconciliation_snapshot().await.is_none()); + assert_eq!(session.clone_history().await.raw_items(), history); + *session.active_turn.lock().await = None; +} + +#[tokio::test] +async fn reconcile_persisted_history_rejects_incomplete_idle_tail_without_mutation() { + let (session, _turn_context) = make_session_and_context().await; + let local_history = model_history_for_turn("local user", "local assistant"); + session.replace_history(local_history.clone(), None).await; + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let mut rollout = vec![ + turn_started("external-turn"), + RolloutItem::ResponseItem(user_message("external user")), + RolloutItem::ResponseItem(assistant_message("partial assistant")), + ]; + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Incomplete); + assert_eq!(session.clone_history().await.raw_items(), local_history); + + rollout.push(RolloutItem::EventMsg(EventMsg::TurnAborted( + TurnAbortedEvent { + turn_id: Some("external-turn".to_string()), + reason: TurnAbortReason::Interrupted, + completed_at: None, + duration_ms: None, + }, + ))); + let retry_snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle retry snapshot"); + let retry_outcome = session + .reconcile_persisted_history(retry_snapshot, &rollout) + .await; + assert_eq!(retry_outcome, ThreadHistoryReconciliationOutcome::Refreshed); + assert_eq!( + session.clone_history().await.raw_items(), + model_history_for_turn("external user", "partial assistant") + ); +} + +#[tokio::test] +async fn reconcile_persisted_history_requires_terminal_event_after_turn_error() { + let (session, _turn_context) = make_session_and_context().await; + let local_history = model_history_for_turn("local user", "local assistant"); + session.replace_history(local_history.clone(), None).await; + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let rollout = vec![ + turn_started("failed-turn"), + RolloutItem::ResponseItem(user_message("external user")), + RolloutItem::EventMsg(EventMsg::Error(ErrorEvent { + message: "external failure".to_string(), + codex_error_info: None, + })), + ]; + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Incomplete); + assert_eq!(session.clone_history().await.raw_items(), local_history); +} + +#[tokio::test] +async fn reconcile_persisted_history_allows_unchanged_known_crash_tail() { + let (session, _turn_context) = make_session_and_context().await; + let history = model_history_for_turn("crash user", "partial assistant"); + let rollout = vec![ + turn_started("crash-turn"), + RolloutItem::ResponseItem(user_message("crash user")), + RolloutItem::ResponseItem(assistant_message("partial assistant")), + ]; + session.replace_history(history.clone(), None).await; + session + .state + .lock() + .await + .set_known_persisted_incomplete_tail(Some("crash-turn".to_string())); + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Unchanged); + assert_eq!(session.clone_history().await.raw_items(), history); +} + +#[tokio::test] +async fn reconcile_persisted_history_allows_metadata_after_known_crash_tail() { + let (session, _turn_context) = make_session_and_context().await; + let history = model_history_for_turn("crash user", "partial assistant"); + let mut rollout = vec![ + turn_started("crash-turn"), + RolloutItem::ResponseItem(user_message("crash user")), + RolloutItem::ResponseItem(assistant_message("partial assistant")), + ]; + session.replace_history(history.clone(), None).await; + session + .state + .lock() + .await + .set_known_persisted_incomplete_tail(Some("crash-turn".to_string())); + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let thread_id = session.thread_id(); + rollout.push(RolloutItem::EventMsg(EventMsg::ThreadGoalUpdated( + ThreadGoalUpdatedEvent { + thread_id, + turn_id: None, + goal: ThreadGoal { + thread_id, + objective: "metadata only".to_string(), + status: ThreadGoalStatus::Active, + token_budget: None, + tokens_used: 0, + time_used_seconds: 0, + created_at: 1, + updated_at: 1, + }, + }, + ))); + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Unchanged); + assert_eq!(session.clone_history().await.raw_items(), history); +} + +#[tokio::test] +async fn reconcile_persisted_history_allows_rollback_after_known_crash_tail() { + let (session, _turn_context) = make_session_and_context().await; + let history = model_history_for_turn("crash user", "partial assistant"); + let mut rollout = vec![ + turn_started("crash-turn"), + RolloutItem::ResponseItem(user_message("crash user")), + RolloutItem::ResponseItem(assistant_message("partial assistant")), + ]; + session.replace_history(history, None).await; + session + .state + .lock() + .await + .set_known_persisted_incomplete_tail(Some("crash-turn".to_string())); + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + rollout.push(RolloutItem::EventMsg(EventMsg::ThreadRolledBack( + ThreadRolledBackEvent { num_turns: 1 }, + ))); + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); + assert_eq!(session.clone_history().await.raw_items(), Vec::new()); + assert_eq!( + session.state.lock().await.known_persisted_incomplete_tail(), + None + ); +} + +#[tokio::test] +async fn reconcile_persisted_history_detects_optimistic_conflicts() { + let (session, turn_context) = make_session_and_context().await; + session + .replace_history(vec![user_message("local baseline")], None) + .await; + let snapshot_before_append = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let local_append = assistant_message("local append"); + { + let mut state = session.state.lock().await; + state.history.record_items( + std::iter::once(&local_append), + turn_context.model_info.truncation_policy.into(), + ); + } + let persisted = completed_turn("external-turn", "external user", "external assistant"); + + let append_outcome = session + .reconcile_persisted_history(snapshot_before_append, &persisted) + .await; + + assert_eq!(append_outcome, ThreadHistoryReconciliationOutcome::Conflict); + let history_after_append = session.clone_history().await.raw_items().to_vec(); + assert!(history_after_append.contains(&local_append)); + + let snapshot_before_rewrite = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + session + .replace_history(history_after_append.clone(), None) + .await; + let rewrite_outcome = session + .reconcile_persisted_history(snapshot_before_rewrite, &persisted) + .await; + assert_eq!( + rewrite_outcome, + ThreadHistoryReconciliationOutcome::Conflict + ); + assert_eq!( + session.clone_history().await.raw_items(), + history_after_append + ); +} + +#[tokio::test] +async fn history_reconciliation_lock_serializes_idle_injection() { + let (session, _turn_context) = make_session_and_context().await; + let history_guard = session.acquire_history_persistence_lock().await; + let injection = session.inject_no_new_turn( + vec![assistant_message("injected while resume is pending")], + None, + ); + tokio::pin!(injection); + + assert!( + timeout(Duration::from_millis(10), injection.as_mut()) + .await + .is_err() + ); + drop(history_guard); + injection.await; + let history = session.clone_history().await; + assert!( + matches!( + history.raw_items(), + [ResponseItem::Message { content, .. }] + if matches!(content.as_slice(), [ContentItem::OutputText { text }] + if text == "injected while resume is pending") + ), + "unexpected injected history: {:?}", + history.raw_items() + ); +} + +#[tokio::test] +async fn history_reconciliation_event_cut_orders_pre_cut_during_and_post_cut_events() { + let (session, _turn_context, rx_event) = make_session_and_context_with_rx().await; + let pre_cut = Event { + id: "pre-cut".to_string(), + msg: EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "pre-cut".to_string(), + trace_id: None, + started_at: None, + model_context_window: None, + collaboration_mode_kind: Default::default(), + }), + }; + session.send_event_raw(pre_cut.clone()).await; + + let event_cut_guards = session.acquire_history_reconciliation_event_cut().await; + let received_pre_cut = rx_event.try_recv().expect("pre-cut event should be queued"); + assert_eq!(received_pre_cut.id, pre_cut.id); + assert!(matches!(received_pre_cut.msg, EventMsg::TurnStarted(_))); + + let during_cut = Event { + id: "during-cut".to_string(), + msg: EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: "during-cut".to_string(), + last_agent_message: None, + completed_at: None, + duration_ms: None, + time_to_first_token_ms: None, + }), + }; + let session_for_during_cut = Arc::clone(&session); + let during_cut_for_task = during_cut.clone(); + let mut during_cut_task = tokio::spawn(async move { + session_for_during_cut + .send_event_raw(during_cut_for_task) + .await; + }); + assert!( + timeout(Duration::from_millis(25), &mut during_cut_task) + .await + .is_err(), + "an event arriving during the cut must wait until after the snapshot" + ); + assert!(matches!( + rx_event.try_recv(), + Err(async_channel::TryRecvError::Empty) + )); + + drop(event_cut_guards); + timeout(Duration::from_secs(1), during_cut_task) + .await + .expect("during-cut event should unblock") + .expect("during-cut event task should not panic"); + let received_during_cut = rx_event + .try_recv() + .expect("during-cut event should be delivered after release"); + assert_eq!(received_during_cut.id, during_cut.id); + assert!(matches!(received_during_cut.msg, EventMsg::TurnComplete(_))); + + let post_cut = Event { + id: "post-cut".to_string(), + msg: EventMsg::TurnAborted(TurnAbortedEvent { + turn_id: Some("post-cut".to_string()), + reason: TurnAbortReason::Interrupted, + completed_at: None, + duration_ms: None, + }), + }; + session.send_event_raw(post_cut.clone()).await; + let received_post_cut = rx_event + .try_recv() + .expect("post-cut event should be delivered"); + assert_eq!(received_post_cut.id, post_cut.id); + assert!(matches!(received_post_cut.msg, EventMsg::TurnAborted(_))); + assert!(matches!( + rx_event.try_recv(), + Err(async_channel::TryRecvError::Empty) + )); +} + +#[tokio::test] +async fn history_reconciliation_event_cut_keeps_hook_prompt_persistence_with_raw_event() { + let (session, turn_context, rx_event) = make_session_and_context_with_rx().await; + let hook_prompt = build_hook_prompt_message(&[HookPromptFragment::from_single_hook( + "continue after the stop hook", + "hook-run-1", + )]) + .expect("hook prompt message"); + let rollout_guard = session.acquire_rollout_persistence_lock().await; + let session_for_record = Arc::clone(&session); + let turn_context_for_record = Arc::clone(&turn_context); + let mut record_task = tokio::spawn(async move { + session_for_record + .record_conversation_items( + turn_context_for_record.as_ref(), + std::slice::from_ref(&hook_prompt), + ) + .await; + }); + + timeout(Duration::from_secs(1), async { + loop { + if !session.clone_history().await.raw_items().is_empty() { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("hook prompt should reach in-memory history before persistence unblocks"); + + let session_for_cut = Arc::clone(&session); + let (cut_queued_tx, cut_queued_rx) = tokio::sync::oneshot::channel(); + let (cut_acquired_tx, mut cut_acquired_rx) = tokio::sync::oneshot::channel(); + let (release_cut_tx, release_cut_rx) = tokio::sync::oneshot::channel(); + let cut_task = tokio::spawn(async move { + let history_guard = session_for_cut.acquire_history_persistence_lock().await; + let _ = cut_queued_tx.send(()); + let event_guard = session_for_cut.acquire_event_delivery_lock().await; + let rollout_guard = session_for_cut.acquire_rollout_persistence_lock().await; + let _ = cut_acquired_tx.send(()); + let _ = release_cut_rx.await; + drop((history_guard, event_guard, rollout_guard)); + }); + timeout(Duration::from_secs(1), cut_queued_rx) + .await + .expect("the cut should queue behind the event transaction") + .expect("cut task should report that its history guard is held"); + assert!( + timeout(Duration::from_millis(25), &mut cut_acquired_rx) + .await + .is_err(), + "the cut must wait while the hook prompt batch is blocked on persistence" + ); + + drop(rollout_guard); + timeout(Duration::from_secs(1), &mut cut_acquired_rx) + .await + .expect("the cut should acquire after the hook prompt batch") + .expect("cut task should report acquisition"); + let raw_event_precedes_cut = std::iter::from_fn(|| rx_event.try_recv().ok()) + .any(|event| matches!(event.msg, EventMsg::RawResponseItem(_))); + let _ = release_cut_tx.send(()); + timeout(Duration::from_secs(1), cut_task) + .await + .expect("cut task should finish") + .expect("cut task should not panic"); + timeout(Duration::from_secs(1), &mut record_task) + .await + .expect("hook prompt record should finish") + .expect("hook prompt record task should not panic"); + + assert!( + raw_event_precedes_cut, + "the raw hook-prompt event must be delivered before a resume snapshot can include its persisted response item" + ); +} + +#[tokio::test] +async fn history_reconciliation_event_cut_keeps_record_and_item_lifecycle_in_one_batch() { + let (session, turn_context, rx_event) = make_session_and_context_with_rx().await; + let response_item = assistant_message("batched assistant item"); + let rollout_guard = session.acquire_rollout_persistence_lock().await; + let session_for_record = Arc::clone(&session); + let turn_context_for_record = Arc::clone(&turn_context); + let mut record_task = tokio::spawn(async move { + session_for_record + .record_response_item_and_emit_turn_item( + turn_context_for_record.as_ref(), + response_item, + ) + .await; + }); + + timeout(Duration::from_secs(1), async { + loop { + if !session.clone_history().await.raw_items().is_empty() { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("assistant item should reach in-memory history before persistence unblocks"); + + let session_for_cut = Arc::clone(&session); + let (cut_queued_tx, cut_queued_rx) = tokio::sync::oneshot::channel(); + let (cut_acquired_tx, mut cut_acquired_rx) = tokio::sync::oneshot::channel(); + let (release_cut_tx, release_cut_rx) = tokio::sync::oneshot::channel(); + let cut_task = tokio::spawn(async move { + let history_guard = session_for_cut.acquire_history_persistence_lock().await; + let _ = cut_queued_tx.send(()); + let event_guard = session_for_cut.acquire_event_delivery_lock().await; + let rollout_guard = session_for_cut.acquire_rollout_persistence_lock().await; + let _ = cut_acquired_tx.send(()); + let _ = release_cut_rx.await; + drop((history_guard, event_guard, rollout_guard)); + }); + timeout(Duration::from_secs(1), cut_queued_rx) + .await + .expect("the cut should queue behind the event transaction") + .expect("cut task should report that its history guard is held"); + assert!( + timeout(Duration::from_millis(25), &mut cut_acquired_rx) + .await + .is_err(), + "the cut must wait while the item batch is blocked on persistence" + ); + + drop(rollout_guard); + timeout(Duration::from_secs(1), &mut cut_acquired_rx) + .await + .expect("the cut should acquire after the item batch") + .expect("cut task should report acquisition"); + let events: Vec = std::iter::from_fn(|| rx_event.try_recv().ok()) + .map(|event| event.msg) + .collect(); + let raw_event_precedes_cut = events + .iter() + .any(|event| matches!(event, EventMsg::RawResponseItem(_))); + let item_started_precedes_cut = events + .iter() + .any(|event| matches!(event, EventMsg::ItemStarted(_))); + let item_completed_precedes_cut = events + .iter() + .any(|event| matches!(event, EventMsg::ItemCompleted(_))); + let _ = release_cut_tx.send(()); + timeout(Duration::from_secs(1), cut_task) + .await + .expect("cut task should finish") + .expect("cut task should not panic"); + timeout(Duration::from_secs(1), &mut record_task) + .await + .expect("assistant item record should finish") + .expect("assistant item record task should not panic"); + + assert!(raw_event_precedes_cut, "raw response item must precede cut"); + assert!(item_started_precedes_cut, "item/started must precede cut"); + assert!( + item_completed_precedes_cut, + "item/completed must precede cut" + ); +} + +#[tokio::test] +async fn history_reconciliation_locks_serialize_append_and_cursor_update() { + let (session, _turn_context) = make_session_and_context().await; + let reconciliation_guards = session.acquire_history_reconciliation_event_cut().await; + let rollout_items = [RolloutItem::ResponseItem(assistant_message( + "append waiting behind reconciliation", + ))]; + let append = session.persist_rollout_items(&rollout_items); + tokio::pin!(append); + + assert!( + timeout(Duration::from_millis(10), append.as_mut()) + .await + .is_err() + ); + drop(reconciliation_guards); + append.await; +} diff --git a/codex-rs/core/src/session/history_reconciliation/window_state_tests.rs b/codex-rs/core/src/session/history_reconciliation/window_state_tests.rs new file mode 100644 index 0000000000..3344edaab6 --- /dev/null +++ b/codex-rs/core/src/session/history_reconciliation/window_state_tests.rs @@ -0,0 +1,644 @@ +use super::*; +use pretty_assertions::assert_eq; + +#[tokio::test] +async fn reconcile_persisted_history_installs_compaction_checkpoint() { + let (session, _turn_context) = make_session_and_context().await; + session + .replace_history(model_history_for_turn("old user", "old assistant"), None) + .await; + { + let mut state = session.state.lock().await; + state.request_new_context_window(); + assert!(state.claim_token_budget_reminder()); + assert!(!state.claim_token_budget_reminder()); + } + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let compacted_history = model_history_for_turn("summary", "after summary"); + let first_window_id = Uuid::now_v7(); + let previous_window_id = Uuid::now_v7(); + let window_id = Uuid::now_v7(); + let rollout = vec![ + turn_started("compact-turn"), + RolloutItem::Compacted(CompactedItem { + message: "summary".to_string(), + replacement_history: Some(compacted_history.clone()), + window_number: Some(7), + first_window_id: Some(first_window_id.to_string()), + previous_window_id: Some(previous_window_id.to_string()), + window_id: Some(window_id.to_string()), + }), + turn_complete("compact-turn"), + ]; + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); + let mut state = session.state.lock().await; + assert_eq!(state.history.raw_items(), compacted_history); + assert_eq!(state.auto_compact_window_number(), 7); + assert_eq!( + state.auto_compact_window_ids(), + AutoCompactWindowIds { + first_window_id, + previous_window_id: Some(previous_window_id), + window_id, + } + ); + assert!(!state.take_new_context_window_request()); + assert!(state.claim_token_budget_reminder()); +} + +#[tokio::test] +async fn reconcile_persisted_history_resets_runtime_state_for_new_compaction_window() { + let (session, _turn_context) = make_session_and_context().await; + let history = model_history_for_turn("summary", "after summary"); + session.replace_history(history.clone(), None).await; + { + let mut state = session.state.lock().await; + state.ensure_auto_compact_window_server_prefill_from_usage(&TokenUsage { + input_tokens: 777, + total_tokens: 777, + ..Default::default() + }); + state.request_new_context_window(); + assert!(state.claim_token_budget_reminder()); + } + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let first_window_id = Uuid::now_v7(); + let previous_window_id = Uuid::now_v7(); + let window_id = Uuid::now_v7(); + let rollout = vec![ + turn_started("compact-turn"), + RolloutItem::Compacted(CompactedItem { + message: "summary".to_string(), + replacement_history: Some(history.clone()), + window_number: Some(7), + first_window_id: Some(first_window_id.to_string()), + previous_window_id: Some(previous_window_id.to_string()), + window_id: Some(window_id.to_string()), + }), + turn_complete("compact-turn"), + ]; + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Unchanged); + let mut state = session.state.lock().await; + assert_ne!( + state.auto_compact_window_snapshot().prefill_input_tokens, + Some(777) + ); + assert!(!state.take_new_context_window_request()); + assert!(state.claim_token_budget_reminder()); +} + +#[tokio::test] +async fn reconcile_persisted_history_queues_only_unconsumed_imported_compaction_hook() { + for followed_by_turn in [false, true] { + let (session, _turn_context) = make_session_and_context().await; + let first_history = model_history_for_turn("first user", "first assistant"); + session.replace_history(first_history, None).await; + let mut rollout = completed_turn("turn-1", "first user", "first assistant"); + { + let mut state = session.state.lock().await; + state.set_known_persisted_history_cursor(persisted_history_cursor(&rollout)); + while state.take_pending_session_start_source().is_some() {} + } + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + let first_window_id = Uuid::now_v7(); + let previous_window_id = Uuid::now_v7(); + let window_id = Uuid::now_v7(); + rollout.extend([ + turn_started("compact-turn"), + RolloutItem::Compacted(CompactedItem { + message: "summary".to_string(), + replacement_history: Some(model_history_for_turn("summary", "after summary")), + window_number: Some(7), + first_window_id: Some(first_window_id.to_string()), + previous_window_id: Some(previous_window_id.to_string()), + window_id: Some(window_id.to_string()), + }), + turn_complete("compact-turn"), + ]); + if followed_by_turn { + rollout.extend(completed_turn( + "turn-after-compact", + "later user", + "later assistant", + )); + } + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); + let pending_source = session + .state + .lock() + .await + .take_pending_session_start_source(); + if followed_by_turn { + assert!( + pending_source.is_none(), + "a later turn already consumed the imported compact lifecycle hook" + ); + } else { + assert!( + matches!( + pending_source, + Some(codex_hooks::SessionStartSource::Compact) + ), + "an imported compaction must queue its next-turn lifecycle hook" + ); + } + } +} + +#[tokio::test] +async fn cursor_mismatch_queues_imported_compaction_hook_exactly_once() { + let (session, _turn_context) = make_session_and_context().await; + let first_history = model_history_for_turn("first user", "first assistant"); + let local_item = assistant_message("locally known item after old prefix"); + let mut local_history = first_history.clone(); + local_history.push(local_item.clone()); + session.replace_history(local_history.clone(), None).await; + + let first_turn = completed_turn("turn-1", "first user", "first assistant"); + let mut locally_known_rollout = first_turn.clone(); + locally_known_rollout.push(RolloutItem::ResponseItem(local_item)); + { + let mut state = session.state.lock().await; + state.set_known_persisted_history_cursor(persisted_history_cursor(&locally_known_rollout)); + while state.take_pending_session_start_source().is_some() {} + } + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + + let first_window_id = Uuid::now_v7(); + let previous_window_id = Uuid::now_v7(); + let window_id = Uuid::now_v7(); + let mut actual_rollout = first_turn; + actual_rollout.extend([ + turn_started("compact-turn"), + RolloutItem::Compacted(CompactedItem { + message: "summary".to_string(), + replacement_history: Some(local_history), + window_number: Some(7), + first_window_id: Some(first_window_id.to_string()), + previous_window_id: Some(previous_window_id.to_string()), + window_id: Some(window_id.to_string()), + }), + turn_complete("compact-turn"), + ]); + + let outcome = session + .reconcile_persisted_history(snapshot, &actual_rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Unchanged); + assert!(matches!( + session + .state + .lock() + .await + .take_pending_session_start_source(), + Some(codex_hooks::SessionStartSource::Compact) + )); + + let second_snapshot = session + .history_reconciliation_snapshot() + .await + .expect("second idle history snapshot"); + let second_outcome = session + .reconcile_persisted_history(second_snapshot, &actual_rollout) + .await; + + assert_eq!( + second_outcome, + ThreadHistoryReconciliationOutcome::Unchanged + ); + assert!( + session + .state + .lock() + .await + .take_pending_session_start_source() + .is_none(), + "the installed full cursor must prevent duplicate Compact lifecycle hooks" + ); +} + +#[tokio::test] +async fn reconcile_persisted_history_applies_external_rollback() { + let (session, _turn_context) = make_session_and_context().await; + let first_history = model_history_for_turn("first user", "first assistant"); + let second_history = model_history_for_turn("second user", "second assistant"); + let mut local_history = first_history.clone(); + local_history.extend(second_history); + session.replace_history(local_history, None).await; + let window_id = session + .state + .lock() + .await + .auto_compact_window_ids() + .window_id + .to_string(); + let budget = session.services.agent_control.rollout_budget(); + budget.configure(RolloutBudgetConfig { + limit_tokens: 100, + reminder_at_remaining_tokens: vec![100], + sampling_token_weight: 1.0, + prefill_token_weight: 1.0, + }); + let reminder = budget + .pending_reminder(session.thread_id(), &window_id) + .expect("initial rollout budget reminder"); + budget.mark_reminder_delivered(session.thread_id(), &window_id, reminder); + assert!( + budget + .pending_reminder(session.thread_id(), &window_id) + .is_none() + ); + let mut additional_context = BTreeMap::new(); + additional_context.insert( + "project".to_string(), + AdditionalContextEntry { + value: "keep this available after rollback".to_string(), + kind: AdditionalContextKind::Application, + }, + ); + let mut rollout = completed_turn("turn-1", "first user", "first assistant"); + rollout.extend(completed_turn("turn-2", "second user", "second assistant")); + { + let mut state = session.state.lock().await; + let _ = state.additional_context.merge(additional_context.clone()); + state.set_known_persisted_history_cursor(persisted_history_cursor(&rollout)); + } + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + rollout.push(RolloutItem::EventMsg(EventMsg::ThreadRolledBack( + ThreadRolledBackEvent { num_turns: 1 }, + ))); + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); + assert_eq!(session.clone_history().await.raw_items(), first_history); + assert!( + budget + .pending_reminder(session.thread_id(), &window_id) + .is_some() + ); + assert_eq!( + session + .state + .lock() + .await + .additional_context + .merge(additional_context) + .len(), + 1, + "an imported rollback must rearm additional-context emission" + ); +} + +#[tokio::test] +async fn reconcile_persisted_history_rearms_token_budget_reminder_removed_by_rollback() { + for scope in [ + AutoCompactTokenLimitScope::Total, + AutoCompactTokenLimitScope::BodyAfterPrefix, + ] { + let (session, mut turn_context) = make_session_and_context().await; + let reminder_template = "reconciled budget reminder: {n_remaining}"; + let mut config = (*turn_context.config).clone(); + config.token_budget = Some(TokenBudgetConfig { + reminder_threshold_tokens: Some(50), + reminder_message_template: reminder_template.to_string(), + guidance_message: None, + }); + config.model_auto_compact_token_limit_scope = scope; + config + .features + .enable(Feature::TokenBudget) + .expect("test config should allow token budget"); + turn_context.config = Arc::new(config); + turn_context.sub_id = "turn-2".to_string(); + + let first_history = model_history_for_turn("first user", "first assistant"); + let second_history = model_history_for_turn("second user", "second assistant"); + let mut local_history = first_history.clone(); + local_history.extend(second_history.clone()); + session.replace_history(local_history, None).await; + + super::token_budget::maybe_record(&session, &turn_context, Some(25)).await; + + let mut delivered_reminder = ContextualUserFragment::into(TokenBudgetReminder::new( + reminder_template, + /*n_remaining*/ 25, + )); + delivered_reminder.set_turn_id_if_missing(&turn_context.sub_id); + let mut expected_delivered_history = first_history.clone(); + expected_delivered_history.extend(second_history); + expected_delivered_history.push(delivered_reminder.clone()); + assert_eq!( + session.clone_history().await.raw_items(), + expected_delivered_history + ); + + let mut rollout = completed_turn("turn-1", "first user", "first assistant"); + let mut second_turn = completed_turn("turn-2", "second user", "second assistant"); + second_turn.insert( + second_turn.len() - 1, + RolloutItem::ResponseItem(delivered_reminder.clone()), + ); + rollout.extend(second_turn); + let (window_number, window_ids) = { + let mut state = session.state.lock().await; + let mut config = (*state.session_configuration.original_config_do_not_use).clone(); + config.model_auto_compact_token_limit_scope = scope; + state.session_configuration.original_config_do_not_use = Arc::new(config); + state.set_known_persisted_history_cursor(persisted_history_cursor(&rollout)); + state.ensure_auto_compact_window_server_prefill_from_usage(&TokenUsage { + input_tokens: 777, + total_tokens: 777, + ..Default::default() + }); + assert!(!state.claim_token_budget_reminder()); + ( + state.auto_compact_window_number(), + state.auto_compact_window_ids(), + ) + }; + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + rollout.push(RolloutItem::EventMsg(EventMsg::ThreadRolledBack( + ThreadRolledBackEvent { num_turns: 1 }, + ))); + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); + assert_eq!(session.clone_history().await.raw_items(), first_history); + { + let state = session.state.lock().await; + assert_eq!(state.auto_compact_window_number(), window_number); + assert_eq!(state.auto_compact_window_ids(), window_ids); + assert_eq!( + state.auto_compact_window_snapshot().prefill_input_tokens, + Some(777), + "same-window rollback must preserve the server prefill for {scope:?}" + ); + } + + super::token_budget::maybe_record(&session, &turn_context, Some(25)).await; + + let mut expected_history = first_history; + expected_history.push(delivered_reminder); + assert_eq!(session.clone_history().await.raw_items(), expected_history); + + super::token_budget::maybe_record(&session, &turn_context, Some(25)).await; + assert_eq!( + session.clone_history().await.raw_items(), + expected_history, + "the re-emitted reminder remains one-shot within the reconciled window" + ); + } +} + +#[tokio::test] +async fn reconcile_persisted_history_preserves_loaded_prefix_truncation() { + let (session, _turn_context) = make_session_and_context().await; + let preserved_prefix = model_history_for_turn("truncated user", "truncated assistant"); + session + .replace_history(preserved_prefix.clone(), None) + .await; + let mut additional_context = BTreeMap::new(); + additional_context.insert( + "project".to_string(), + AdditionalContextEntry { + value: "primary context before external turn".to_string(), + kind: AdditionalContextKind::Application, + }, + ); + let _ = session + .state + .lock() + .await + .additional_context + .merge(additional_context.clone()); + let mut rollout = completed_turn("turn-1", "raw user", "raw assistant"); + { + let mut state = session.state.lock().await; + state.set_known_persisted_history_cursor(persisted_history_cursor(&rollout)); + state.ensure_auto_compact_window_server_prefill_from_usage(&TokenUsage { + input_tokens: 777, + total_tokens: 777, + ..Default::default() + }); + } + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + rollout.extend(completed_turn( + "turn-2", + "external user", + "external assistant", + )); + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); + let mut expected = preserved_prefix; + expected.extend(model_history_for_turn( + "external user", + "external assistant", + )); + assert_eq!(session.clone_history().await.raw_items(), expected); + assert_eq!( + session + .state + .lock() + .await + .auto_compact_window_snapshot() + .prefill_input_tokens, + Some(777), + "suffix reconciliation must preserve the prefill after restoring the loaded prefix" + ); + assert_eq!( + session.state.lock().await.known_persisted_history_cursor(), + persisted_history_cursor(&rollout) + ); + assert_eq!( + session + .state + .lock() + .await + .additional_context + .merge(additional_context) + .len(), + 1, + "an imported turn must rearm additional-context emission" + ); +} + +#[tokio::test] +async fn reconcile_persisted_history_preserves_same_window_prefill_for_append_only_suffix() { + let (session, _turn_context) = make_session_and_context().await; + let local_history = model_history_for_turn("first user", "first assistant"); + session.replace_history(local_history, None).await; + let mut rollout = completed_turn("turn-1", "first user", "first assistant"); + { + let mut state = session.state.lock().await; + state.set_known_persisted_history_cursor(persisted_history_cursor(&rollout)); + state.ensure_auto_compact_window_server_prefill_from_usage(&TokenUsage { + input_tokens: 777, + total_tokens: 777, + ..Default::default() + }); + } + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + rollout.extend(completed_turn( + "turn-2", + "external user", + "external assistant", + )); + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); + assert_eq!( + session + .state + .lock() + .await + .auto_compact_window_snapshot() + .prefill_input_tokens, + Some(777), + "append-only reconciliation in the same compaction window must retain the server baseline" + ); +} + +#[tokio::test] +async fn reconcile_persisted_history_ignores_interleaved_session_metadata_in_cursor() { + let (session, _turn_context) = make_session_and_context().await; + let mut preserved_prefix = model_history_for_turn("first user", "first assistant"); + let local_item = assistant_message("local item after metadata update"); + preserved_prefix.push(local_item.clone()); + session + .replace_history(preserved_prefix.clone(), None) + .await; + + let mut rollout = completed_turn("turn-1", "first user", "first assistant"); + rollout.push(session_meta(session.thread_id())); + rollout.push(RolloutItem::ResponseItem(local_item)); + session + .state + .lock() + .await + .set_known_persisted_history_cursor(persisted_history_cursor(&rollout)); + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + rollout.extend(completed_turn( + "turn-2", + "external user", + "external assistant", + )); + + let outcome = session + .reconcile_persisted_history(snapshot, &rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); + let mut expected = preserved_prefix; + expected.extend(model_history_for_turn( + "external user", + "external assistant", + )); + assert_eq!(session.clone_history().await.raw_items(), expected); + assert_eq!( + session.state.lock().await.known_persisted_history_cursor(), + persisted_history_cursor(&rollout) + ); +} + +#[tokio::test] +async fn reconcile_persisted_history_rebuilds_after_external_append_interleaves_prefix() { + let (session, _turn_context) = make_session_and_context().await; + let local_item = assistant_message("local item after unseen external turn"); + let mut local_history = model_history_for_turn("first user", "first assistant"); + local_history.push(local_item.clone()); + session.replace_history(local_history, None).await; + + let first_turn = completed_turn("turn-1", "first user", "first assistant"); + let mut locally_known_rollout = first_turn.clone(); + locally_known_rollout.push(RolloutItem::ResponseItem(local_item.clone())); + session + .state + .lock() + .await + .set_known_persisted_history_cursor(persisted_history_cursor(&locally_known_rollout)); + let snapshot = session + .history_reconciliation_snapshot() + .await + .expect("idle history snapshot"); + + let mut actual_rollout = first_turn; + actual_rollout.extend(completed_turn( + "turn-2", + "external user", + "external assistant", + )); + actual_rollout.push(RolloutItem::ResponseItem(local_item.clone())); + + let outcome = session + .reconcile_persisted_history(snapshot, &actual_rollout) + .await; + + assert_eq!(outcome, ThreadHistoryReconciliationOutcome::Refreshed); + let mut expected = model_history_for_turn("first user", "first assistant"); + expected.extend(model_history_for_turn( + "external user", + "external assistant", + )); + expected.push(local_item); + assert_eq!(session.clone_history().await.raw_items(), expected); + assert_eq!( + session.state.lock().await.known_persisted_history_cursor(), + persisted_history_cursor(&actual_rollout) + ); +} diff --git a/codex-rs/core/src/session/history_reconciliation_tests.rs b/codex-rs/core/src/session/history_reconciliation_tests.rs new file mode 100644 index 0000000000..82b0590648 --- /dev/null +++ b/codex-rs/core/src/session/history_reconciliation_tests.rs @@ -0,0 +1,157 @@ +use super::history_reconciliation::persisted_history_cursor; +use super::tests::make_session_and_context; +use super::tests::make_session_and_context_with_rx; +use super::*; +use crate::codex_thread::ThreadHistoryReconciliationOutcome; +use crate::config::RolloutBudgetConfig; +use crate::config::TokenBudgetConfig; +use crate::context::ContextualUserFragment; +use crate::context::TokenBudgetReminder; +use crate::state::ActiveTurn; +use crate::state::AutoCompactWindowIds; +use crate::state::PersistedHistoryCursorUncertainty; +use codex_features::Feature; +use codex_protocol::models::ContentItem; +use codex_protocol::models::LocalShellAction; +use codex_protocol::models::LocalShellExecAction; +use codex_protocol::models::LocalShellStatus; +use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::AdditionalContextEntry; +use codex_protocol::protocol::AdditionalContextKind; +use codex_protocol::protocol::CompactedItem; +use codex_protocol::protocol::ErrorEvent; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::SessionMeta; +use codex_protocol::protocol::SessionMetaLine; +use codex_protocol::protocol::ThreadGoal; +use codex_protocol::protocol::ThreadGoalStatus; +use codex_protocol::protocol::ThreadGoalUpdatedEvent; +use codex_protocol::protocol::ThreadRolledBackEvent; +use codex_protocol::protocol::TokenCountEvent; +use codex_protocol::protocol::TokenUsage; +use codex_protocol::protocol::TokenUsageInfo; +use codex_protocol::protocol::TurnAbortReason; +use codex_protocol::protocol::TurnAbortedEvent; +use codex_protocol::protocol::TurnCompleteEvent; +use codex_protocol::protocol::TurnStartedEvent; +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::sync::Arc; +use std::time::Duration; +use tokio::time::timeout; +use uuid::Uuid; + +fn user_message(text: &str) -> ResponseItem { + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: text.to_string(), + }], + phase: None, + internal_chat_message_metadata_passthrough: None, + } +} + +fn assistant_message(text: &str) -> ResponseItem { + ResponseItem::Message { + id: None, + role: "assistant".to_string(), + content: vec![ContentItem::OutputText { + text: text.to_string(), + }], + phase: None, + internal_chat_message_metadata_passthrough: None, + } +} + +fn turn_started(turn_id: &str) -> RolloutItem { + RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent { + turn_id: turn_id.to_string(), + trace_id: None, + started_at: None, + model_context_window: None, + collaboration_mode_kind: Default::default(), + })) +} + +fn turn_complete(turn_id: &str) -> RolloutItem { + RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: turn_id.to_string(), + last_agent_message: None, + completed_at: None, + duration_ms: None, + time_to_first_token_ms: None, + })) +} + +fn completed_turn(turn_id: &str, user: &str, assistant: &str) -> Vec { + vec![ + turn_started(turn_id), + RolloutItem::ResponseItem(user_message(user)), + RolloutItem::ResponseItem(assistant_message(assistant)), + turn_complete(turn_id), + ] +} + +fn model_history_for_turn(user: &str, assistant: &str) -> Vec { + vec![user_message(user), assistant_message(assistant)] +} + +fn session_meta(thread_id: ThreadId) -> RolloutItem { + RolloutItem::SessionMeta(SessionMetaLine { + meta: SessionMeta { + session_id: thread_id.into(), + id: thread_id, + ..SessionMeta::default() + }, + git: None, + }) +} + +fn local_shell_call(env: HashMap) -> RolloutItem { + RolloutItem::ResponseItem(ResponseItem::LocalShellCall { + id: None, + call_id: Some("shell-call".to_string()), + status: LocalShellStatus::Completed, + action: LocalShellAction::Exec(LocalShellExecAction { + command: vec!["printenv".to_string()], + timeout_ms: None, + working_directory: None, + env: Some(env), + user: None, + }), + internal_chat_message_metadata_passthrough: None, + }) +} + +fn token_usage_info(total_tokens: i64) -> TokenUsageInfo { + TokenUsageInfo { + total_token_usage: TokenUsage { + input_tokens: total_tokens, + cached_input_tokens: 0, + output_tokens: 0, + reasoning_output_tokens: 0, + total_tokens, + }, + last_token_usage: TokenUsage { + input_tokens: total_tokens, + cached_input_tokens: 0, + output_tokens: 0, + reasoning_output_tokens: 0, + total_tokens, + }, + model_context_window: Some(258_400), + } +} + +#[path = "history_reconciliation/cursor_recovery_tests.rs"] +mod cursor_recovery_tests; +#[path = "history_reconciliation/reminder_state_tests.rs"] +mod reminder_state_tests; +#[path = "history_reconciliation/safety_and_locking_tests.rs"] +mod safety_and_locking_tests; +#[path = "history_reconciliation/window_state_tests.rs"] +mod window_state_tests; diff --git a/codex-rs/core/src/session/inject.rs b/codex-rs/core/src/session/inject.rs index 5c5b7d1feb..6e4ecc40fc 100644 --- a/codex-rs/core/src/session/inject.rs +++ b/codex-rs/core/src/session/inject.rs @@ -144,6 +144,16 @@ impl Session { &self, items: Vec, current_turn_context: Option<&TurnContext>, + ) { + let _history_guard = self.acquire_history_persistence_lock().await; + self.inject_no_new_turn_locked(items, current_turn_context) + .await; + } + + pub(crate) async fn inject_no_new_turn_locked( + &self, + items: Vec, + current_turn_context: Option<&TurnContext>, ) { let Err(items) = self.inject_if_running(items).await else { return; diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index d43724e5db..576c5cf1ab 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -124,6 +124,7 @@ use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::ThreadHistoryMode; use codex_protocol::protocol::ThreadSource; +use codex_protocol::protocol::TruncationPolicy; use codex_protocol::protocol::TurnAbortReason; use codex_protocol::protocol::TurnContextItem; use codex_protocol::protocol::TurnContextNetworkItem; @@ -203,6 +204,7 @@ mod code_mode_warning; mod config_lock; pub(crate) mod context_window; mod handlers; +mod history_reconciliation; mod inject; mod input_queue; mod mcp; @@ -216,6 +218,7 @@ pub(crate) mod session; pub(crate) mod step_context; pub(crate) mod time_reminder; mod token_budget; + pub(crate) mod turn; pub(crate) mod turn_context; mod world_state; @@ -242,6 +245,9 @@ use self::turn::realtime_text_for_event; use self::turn_context::TurnContext; use self::turn_context::TurnSkillsContext; #[cfg(test)] +#[path = "history_reconciliation_tests.rs"] +mod history_reconciliation_tests; +#[cfg(test)] mod rollout_reconstruction_tests; #[derive(Debug, PartialEq)] @@ -811,6 +817,18 @@ impl Codex { Ok(event) } + pub(crate) fn try_next_event(&self) -> CodexResult> { + match self.rx_event.try_recv() { + Ok(event) => Ok(Some(event)), + Err(async_channel::TryRecvError::Empty) => Ok(None), + Err(async_channel::TryRecvError::Closed) => Err(CodexErr::InternalAgentDied), + } + } + + pub(crate) fn pending_event_count(&self) -> usize { + self.rx_event.len() + } + pub async fn steer_input( &self, input: Vec, @@ -1149,6 +1167,8 @@ impl Session { self.out_of_band_elicitation_paused.send_replace(paused); } + /// Sender for transient stream-only events (for example shell output and MCP startup). + /// Persisted events must use `send_event_raw` so resume's persistence/delivery cut orders them. pub(crate) fn get_tx_event(&self) -> Sender { self.tx_event.clone() } @@ -1301,9 +1321,20 @@ impl Session { .is_non_root_agent() }; let has_prior_user_turns = initial_history_has_prior_user_turns(&conversation_history); + let known_persisted_history_cursor = + self.live_thread() + .and_then(|_| match &conversation_history { + InitialHistory::Resumed(resumed) => { + history_reconciliation::persisted_history_cursor(resumed.history.as_slice()) + } + InitialHistory::New | InitialHistory::Cleared | InitialHistory::Forked(_) => { + Some(history_reconciliation::empty_persisted_history_cursor()) + } + }); { let mut state = self.state.lock().await; state.set_next_turn_is_first(!has_prior_user_turns); + state.set_known_persisted_history_cursor(known_persisted_history_cursor); } match conversation_history { InitialHistory::New | InitialHistory::Cleared => { @@ -1315,9 +1346,15 @@ impl Session { InitialHistory::Resumed(resumed_history) => { let turn_context = self.new_default_turn().await; let rollout_items = resumed_history.history; + let known_persisted_incomplete_tail = + history_reconciliation::persisted_rollout_incomplete_turn_id(&rollout_items); let previous_turn_settings = self .apply_rollout_reconstruction(&turn_context, &rollout_items) .await; + self.state + .lock() + .await + .set_known_persisted_incomplete_tail(known_persisted_incomplete_tail); // If resuming, warn when the last recorded model differs from the current one. let curr: &str = turn_context.model_info.slug.as_str(); @@ -1400,56 +1437,32 @@ impl Session { turn_context: &TurnContext, rollout_items: &[RolloutItem], ) -> Option { - let rollout_reconstruction::RolloutReconstruction { - mut history, - previous_turn_settings, - reference_context_item, - world_state_baseline, - window_number, - first_window_id, - previous_window_id, - window_id, - } = self + let mut reconstruction = self .reconstruct_history_from_rollout(turn_context, rollout_items) .await; // Keep the recorded rollout unchanged. Prepare its reconstructed history before // installing it, so legacy images are processed once for this resume or fork and // will be processed again if the rollout is reconstructed in a future session. // This meets image resizing requirements without modifying persisted rollouts. - prepare_response_items(&mut history); + prepare_response_items(&mut reconstruction.history); + let token_budget_reminder_delivered = + history_reconciliation::history_contains_token_budget_reminder(&reconstruction.history); + { let mut state = self.state.lock().await; - state.replace_history(history, reference_context_item); - if let Some(world_state) = world_state_baseline { - state.history.set_world_state_baseline(world_state); - } - let fallback_ids = state.auto_compact_window_ids(); - let window_id = window_id.unwrap_or(fallback_ids.window_id); - state.restore_auto_compact_window( - window_number, - AutoCompactWindowIds { - first_window_id: first_window_id.unwrap_or(window_id), - previous_window_id, - window_id, + Self::install_rollout_reconstruction( + &mut state, + turn_context.config.model_auto_compact_token_limit_scope, + reconstruction, + history_reconciliation::RolloutReconstructionInstallOptions { + token_info: None, + history: history_reconciliation::RolloutHistoryInstallMode::Replace, + auto_compact_window: + history_reconciliation::AutoCompactWindowInstallMode::Restore, + token_budget_reminder_delivered, }, - ); - state.set_previous_turn_settings(previous_turn_settings.clone()); + ) } - let prefix_tokens = if matches!( - turn_context.config.model_auto_compact_token_limit_scope, - AutoCompactTokenLimitScope::BodyAfterPrefix - ) { - let history = self.clone_history().await; - let base_instructions = self.get_base_instructions().await; - history.estimate_token_count_with_base_instructions(&base_instructions) - } else { - None - }; - if let Some(prefix_tokens) = prefix_tokens { - self.set_auto_compact_window_estimated_prefill_for_scope(turn_context, prefix_tokens) - .await; - } - previous_turn_settings } async fn set_auto_compact_window_estimated_prefill_for_scope( @@ -1740,6 +1753,20 @@ impl Session { /// Persist the event to rollout and send it to clients. pub(crate) async fn send_event(&self, turn_context: &TurnContext, msg: EventMsg) { + let event_delivery_guard = self.acquire_event_delivery_lock().await; + let delivered = self + .send_event_locked(turn_context, msg, &event_delivery_guard) + .await; + drop(event_delivery_guard); + self.run_event_side_effects(turn_context, &delivered).await; + } + + async fn send_event_locked( + &self, + turn_context: &TurnContext, + msg: EventMsg, + event_delivery_guard: &tokio::sync::OwnedMutexGuard<()>, + ) -> EventMsg { let legacy_source = msg.clone(); if let EventMsg::Error(error) = &legacy_source && error @@ -1763,12 +1790,7 @@ impl Session { id: turn_context.sub_id.clone(), msg, }; - self.send_event_raw(event).await; - self.maybe_notify_parent_of_terminal_turn(turn_context, &legacy_source) - .await; - self.maybe_mirror_event_text_to_realtime(&legacy_source) - .await; - self.maybe_clear_realtime_handoff_for_event(&legacy_source) + self.send_event_raw_locked(event, event_delivery_guard) .await; let show_raw_agent_reasoning = self.show_raw_agent_reasoning(); @@ -1777,8 +1799,17 @@ impl Session { id: turn_context.sub_id.clone(), msg: legacy, }; - self.send_event_raw(legacy_event).await; + self.send_event_raw_locked(legacy_event, event_delivery_guard) + .await; } + legacy_source + } + + async fn run_event_side_effects(&self, turn_context: &TurnContext, msg: &EventMsg) { + self.maybe_notify_parent_of_terminal_turn(turn_context, msg) + .await; + self.maybe_mirror_event_text_to_realtime(msg).await; + self.maybe_clear_realtime_handoff_for_event(msg).await; } /// Forwards terminal turn events from spawned MultiAgentV2 children to their direct parent. @@ -1914,16 +1945,31 @@ impl Session { } pub(crate) async fn send_event_raw(&self, event: Event) { + let event_delivery_guard = self.acquire_event_delivery_lock().await; + self.send_event_raw_locked(event, &event_delivery_guard) + .await; + } + + async fn send_event_raw_locked( + &self, + event: Event, + _event_delivery_guard: &tokio::sync::OwnedMutexGuard<()>, + ) { // Persist the event into rollout storage (the store filters as needed). let rollout_items = vec![RolloutItem::EventMsg(event.msg.clone())]; self.persist_rollout_items(&rollout_items).await; self.services .rollout_thread_trace .record_protocol_event(&event.msg); - self.deliver_event_raw(event).await; + self.deliver_event_raw_locked(event).await; } async fn deliver_event_raw(&self, event: Event) { + let _event_delivery_guard = self.acquire_event_delivery_lock().await; + self.deliver_event_raw_locked(event).await; + } + + async fn deliver_event_raw_locked(&self, event: Event) { // Record the last known agent status. if let Some(status) = agent_status_from_event(&event.msg) { self.agent_status.send_replace(status); @@ -1946,6 +1992,25 @@ impl Session { .await; } + async fn emit_turn_item_started_locked( + &self, + turn_context: &TurnContext, + item: &TurnItem, + event_delivery_guard: &tokio::sync::OwnedMutexGuard<()>, + ) -> EventMsg { + self.send_event_locked( + turn_context, + EventMsg::ItemStarted(ItemStartedEvent { + thread_id: self.thread_id, + turn_id: turn_context.sub_id.clone(), + item: item.clone(), + started_at_ms: now_unix_timestamp_ms(), + }), + event_delivery_guard, + ) + .await + } + pub(crate) async fn emit_turn_item_completed( &self, turn_context: &TurnContext, @@ -1964,6 +2029,26 @@ impl Session { .await; } + async fn emit_turn_item_completed_locked( + &self, + turn_context: &TurnContext, + item: TurnItem, + event_delivery_guard: &tokio::sync::OwnedMutexGuard<()>, + ) -> EventMsg { + record_turn_ttfm_metric(turn_context, &item).await; + self.send_event_locked( + turn_context, + EventMsg::ItemCompleted(ItemCompletedEvent { + thread_id: self.thread_id, + turn_id: turn_context.sub_id.clone(), + item, + completed_at_ms: now_unix_timestamp_ms(), + }), + event_delivery_guard, + ) + .await + } + /// Adds an execpolicy amendment to both the in-memory and on-disk policies so future /// commands can use the newly approved prefix. pub(crate) async fn persist_execpolicy_amendment( @@ -2776,6 +2861,17 @@ impl Session { &self, turn_context: &TurnContext, items: &[ResponseItem], + ) { + let event_delivery_guard = self.acquire_event_delivery_lock().await; + self.record_conversation_items_locked(turn_context, items, &event_delivery_guard) + .await; + } + + async fn record_conversation_items_locked( + &self, + turn_context: &TurnContext, + items: &[ResponseItem], + event_delivery_guard: &tokio::sync::OwnedMutexGuard<()>, ) { let items = self.prepare_conversation_items_for_history(turn_context, items); let items = items.as_ref(); @@ -2788,7 +2884,8 @@ impl Session { ); } self.persist_rollout_response_items(items).await; - self.send_raw_response_items(turn_context, items).await; + self.send_raw_response_items_locked(turn_context, items, event_delivery_guard) + .await; } pub(crate) async fn record_step_world_state_if_changed( @@ -2876,6 +2973,7 @@ impl Session { turn_context: &TurnContext, mut communication: InterAgentCommunication, ) { + let event_delivery_guard = self.acquire_event_delivery_lock().await; communication.set_turn_id_if_missing(&turn_context.sub_id); let response_item = communication.to_model_input_item(); let items = self.prepare_conversation_items_for_history( @@ -2899,7 +2997,8 @@ impl Session { RolloutItem::ResponseItem(response_item), ]) .await; - self.send_raw_response_items(turn_context, items).await; + self.send_raw_response_items_locked(turn_context, items, &event_delivery_guard) + .await; } async fn maybe_warn_on_server_model_mismatch( @@ -3068,11 +3167,17 @@ impl Session { } #[tracing::instrument(level = "trace", skip_all, fields(item_count = items.len()))] - async fn send_raw_response_items(&self, turn_context: &TurnContext, items: &[ResponseItem]) { + async fn send_raw_response_items_locked( + &self, + turn_context: &TurnContext, + items: &[ResponseItem], + event_delivery_guard: &tokio::sync::OwnedMutexGuard<()>, + ) { for item in items { - self.send_event( + self.send_event_locked( turn_context, EventMsg::RawResponseItem(RawResponseItemEvent { item: item.clone() }), + event_delivery_guard, ) .await; } @@ -3463,10 +3568,22 @@ impl Session { #[tracing::instrument(level = "trace", skip_all, fields(item_count = items.len()))] pub(crate) async fn persist_rollout_items(&self, items: &[RolloutItem]) { - if let Some(live_thread) = self.live_thread() - && let Err(e) = live_thread.append_items(items).await - { - error!("failed to record rollout items: {e:#}"); + let rollout_guard = self.acquire_rollout_persistence_lock().await; + let Some(live_thread) = self.live_thread() else { + return; + }; + match live_thread.append_items(items).await { + Ok(()) => { + self.note_persisted_non_metadata_items(&rollout_guard, items) + .await; + } + Err(e) => { + // A failed append may still become durable if a buffered writer flushes later. + // Invalidate the positional cursor so reconciliation uses a full rebuild. + self.invalidate_persisted_item_cursor(&rollout_guard, items) + .await; + error!("failed to record rollout items: {e:#}"); + } } } @@ -3777,14 +3894,30 @@ impl Session { turn_context: &TurnContext, response_item: ResponseItem, ) { + let event_delivery_guard = self.acquire_event_delivery_lock().await; // Add to conversation history and persist response item to rollout. - self.record_conversation_items(turn_context, std::slice::from_ref(&response_item)) - .await; + self.record_conversation_items_locked( + turn_context, + std::slice::from_ref(&response_item), + &event_delivery_guard, + ) + .await; // Derive a turn item and emit lifecycle events if applicable. - if let Some(item) = parse_turn_item(&response_item) { - self.emit_turn_item_started(turn_context, &item).await; - self.emit_turn_item_completed(turn_context, item).await; + let lifecycle_events = if let Some(item) = parse_turn_item(&response_item) { + let started = self + .emit_turn_item_started_locked(turn_context, &item, &event_delivery_guard) + .await; + let completed = self + .emit_turn_item_completed_locked(turn_context, item, &event_delivery_guard) + .await; + vec![started, completed] + } else { + Vec::new() + }; + drop(event_delivery_guard); + for event in lifecycle_events { + self.run_event_side_effects(turn_context, &event).await; } } @@ -3794,17 +3927,29 @@ impl Session { input: &[UserInput], client_id: Option, ) { + let event_delivery_guard = self.acquire_event_delivery_lock().await; // Persist the user message to history, but emit the turn item from `UserInput` so // UI-only `text_elements` are preserved. `ResponseItem::Message` does not carry // those spans, and `record_response_item_and_emit_turn_item` would drop them. let response_item = self.response_item_from_user_input(input.to_vec()); - self.record_conversation_items(turn_context, std::slice::from_ref(&response_item)) - .await; + self.record_conversation_items_locked( + turn_context, + std::slice::from_ref(&response_item), + &event_delivery_guard, + ) + .await; let mut user_message_item = UserMessageItem::new(input); user_message_item.client_id = client_id; let turn_item = TurnItem::UserMessage(user_message_item); - self.emit_turn_item_started(turn_context, &turn_item).await; - self.emit_turn_item_completed(turn_context, turn_item).await; + let started = self + .emit_turn_item_started_locked(turn_context, &turn_item, &event_delivery_guard) + .await; + let completed = self + .emit_turn_item_completed_locked(turn_context, turn_item, &event_delivery_guard) + .await; + drop(event_delivery_guard); + self.run_event_side_effects(turn_context, &started).await; + self.run_event_side_effects(turn_context, &completed).await; self.ensure_rollout_materialized().await; } diff --git a/codex-rs/core/src/session/rollout_reconstruction.rs b/codex-rs/core/src/session/rollout_reconstruction.rs index 0b89caaf05..f6a0b6b047 100644 --- a/codex-rs/core/src/session/rollout_reconstruction.rs +++ b/codex-rs/core/src/session/rollout_reconstruction.rs @@ -114,6 +114,18 @@ impl Session { &self, turn_context: &TurnContext, rollout_items: &[RolloutItem], + ) -> RolloutReconstruction { + self.reconstruct_history_from_rollout_with_policy( + turn_context.model_info.truncation_policy.into(), + rollout_items, + ) + .await + } + + pub(super) async fn reconstruct_history_from_rollout_with_policy( + &self, + truncation_policy: TruncationPolicy, + rollout_items: &[RolloutItem], ) -> RolloutReconstruction { // Replay metadata should already match the shape of the future lazy reverse loader, even // while history materialization still uses an eager bridge. Scan newest-to-oldest, @@ -325,17 +337,11 @@ impl Session { for item in rollout_suffix { match item { RolloutItem::ResponseItem(response_item) => { - history.record_items( - std::iter::once(response_item), - turn_context.model_info.truncation_policy.into(), - ); + history.record_items(std::iter::once(response_item), truncation_policy); } RolloutItem::InterAgentCommunication(communication) => { let response_item = communication.to_model_input_item(); - history.record_items( - std::iter::once(&response_item), - turn_context.model_info.truncation_policy.into(), - ); + history.record_items(std::iter::once(&response_item), truncation_policy); } RolloutItem::InterAgentCommunicationMetadata { .. } => {} RolloutItem::Compacted(compacted) => { diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 5e7046b148..daa9af800d 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -32,6 +32,13 @@ pub(crate) struct Session { pub(super) agent_status: watch::Sender, pub(super) out_of_band_elicitation_paused: watch::Sender, pub(super) state: Mutex, + /// Keeps idle history mutation and its rollout persistence atomic with reconciliation. + pub(super) history_persistence_lock: Arc>, + /// Keeps rollout append order identical to persisted-history cursor update order. + pub(super) rollout_persistence_lock: Arc>, + /// Keeps response-item persistence and its raw/canonical event batch on one side of a + /// running-thread resume snapshot cut. + pub(super) event_delivery_lock: Arc>, /// Serializes rebuild/apply cycles for the running proxy; each cycle /// rebuilds from the current SessionState while holding this lock. pub(super) managed_network_proxy_refresh_lock: Semaphore, @@ -1134,6 +1141,9 @@ impl Session { agent_status, out_of_band_elicitation_paused, state: Mutex::new(state), + history_persistence_lock: Arc::new(Mutex::new(())), + rollout_persistence_lock: Arc::new(Mutex::new(())), + event_delivery_lock: Arc::new(Mutex::new(())), managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1), features: config.features.clone(), multi_agent_version, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index ece9d446b5..caf501eb4e 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -5496,6 +5496,9 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { agent_status: agent_status_tx, out_of_band_elicitation_paused: watch::channel(false).0, state: Mutex::new(state), + history_persistence_lock: Arc::new(Mutex::new(())), + rollout_persistence_lock: Arc::new(Mutex::new(())), + event_delivery_lock: Arc::new(Mutex::new(())), managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1), features: config.features.clone(), multi_agent_version: OnceLock::from(config.multi_agent_version_from_features()), @@ -7622,6 +7625,9 @@ where agent_status: agent_status_tx, out_of_band_elicitation_paused: watch::channel(false).0, state: Mutex::new(state), + history_persistence_lock: Arc::new(Mutex::new(())), + rollout_persistence_lock: Arc::new(Mutex::new(())), + event_delivery_lock: Arc::new(Mutex::new(())), managed_network_proxy_refresh_lock: Semaphore::new(/*permits*/ 1), features: config.features.clone(), multi_agent_version: OnceLock::from(config.multi_agent_version_from_features()), diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index b9bf42073b..4677319f21 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -1,3 +1,4 @@ +use super::history_reconciliation::HistoryReconciliationConfig; use super::*; use crate::environment_selection::TurnEnvironmentSnapshot; use crate::shell_snapshot::ShellSnapshotFile; @@ -806,6 +807,26 @@ impl Session { .await } + pub(super) async fn history_reconciliation_config(&self) -> HistoryReconciliationConfig { + let session_configuration = self.default_turn_configuration().await; + let per_turn_config = Self::build_per_turn_config( + &session_configuration, + session_configuration.cwd().clone(), + ); + let model_info = self + .services + .models_manager + .get_model_info( + session_configuration.collaboration_mode.model(), + &per_turn_config.to_models_manager_config(), + ) + .await; + HistoryReconciliationConfig { + truncation_policy: model_info.truncation_policy.into(), + auto_compact_token_limit_scope: per_turn_config.model_auto_compact_token_limit_scope, + } + } + pub(crate) async fn new_default_turn_with_sub_id(&self, sub_id: String) -> Arc { let session_configuration = self.default_turn_configuration().await; self.new_turn_from_configuration( diff --git a/codex-rs/core/src/state/auto_compact_window.rs b/codex-rs/core/src/state/auto_compact_window.rs index 6301231df6..6cf2633253 100644 --- a/codex-rs/core/src/state/auto_compact_window.rs +++ b/codex-rs/core/src/state/auto_compact_window.rs @@ -72,6 +72,16 @@ impl AutoCompactWindow { self.ids = ids; } + pub(super) fn reconcile(&mut self, window_number: u64, ids: AutoCompactWindowIds) { + if self.window_number == window_number && self.ids == ids { + return; + } + self.restore(window_number, ids); + self.new_context_window_requested = false; + self.prefill_input_tokens = None; + self.token_budget_reminder_delivered = false; + } + pub(super) fn advance(&mut self) -> (u64, AutoCompactWindowIds) { self.window_number = self.window_number.saturating_add(1); self.ids.previous_window_id = Some(self.ids.window_id); @@ -85,6 +95,10 @@ impl AutoCompactWindow { !std::mem::replace(&mut self.token_budget_reminder_delivered, true) } + pub(super) fn set_token_budget_reminder_delivered(&mut self, delivered: bool) { + self.token_budget_reminder_delivered = delivered; + } + pub(super) fn request_new_context_window(&mut self) { self.new_context_window_requested = true; } diff --git a/codex-rs/core/src/state/mod.rs b/codex-rs/core/src/state/mod.rs index 20ff78b54f..dfa8748919 100644 --- a/codex-rs/core/src/state/mod.rs +++ b/codex-rs/core/src/state/mod.rs @@ -8,6 +8,8 @@ pub(crate) use additional_context::AdditionalContextStore; pub(crate) use auto_compact_window::AutoCompactWindowIds; pub(crate) use auto_compact_window::AutoCompactWindowSnapshot; pub(crate) use service::SessionServices; +pub(crate) use session::PersistedHistoryCursor; +pub(crate) use session::PersistedHistoryCursorUncertainty; pub(crate) use session::SessionState; pub(crate) use turn::ActiveTurn; pub(crate) use turn::MailboxDeliveryPhase; diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index d681c6fa87..fbbaf6fc63 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -22,6 +22,23 @@ use codex_protocol::protocol::TokenUsageInfo; use codex_protocol::protocol::TurnContextItem; use codex_utils_output_truncation::TruncationPolicy; +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct PersistedHistoryCursor { + pub(crate) item_count: usize, + pub(crate) fingerprint: [u8; 20], +} + +/// What kind of persistence operation may have reached storage after reporting an error. +/// +/// Append-only ambiguity can be resolved by observing the in-memory history as a prefix of a +/// later durable read. A history rewrite cannot use that proof: the pre-rewrite rollout is also a +/// strict extension of the rewritten in-memory history. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum PersistedHistoryCursorUncertainty { + AppendOnly, + HistoryRewrite, +} + /// Persistent, session-scoped state previously stored directly on `Session`. pub(crate) struct SessionState { pub(crate) session_configuration: SessionConfiguration, @@ -43,6 +60,10 @@ pub(crate) struct SessionState { pub(crate) pending_session_start_sources: VecDeque, granted_permissions_by_environment_id: HashMap, next_turn_is_first: bool, + known_persisted_incomplete_tail: Option, + known_persisted_history_cursor: Option, + persisted_history_cursor_uncertainty: Option, + uncertain_expected_persisted_history_cursor: Option, } impl SessionState { @@ -75,6 +96,10 @@ impl SessionState { pending_session_start_sources: VecDeque::new(), granted_permissions_by_environment_id: HashMap::new(), next_turn_is_first: true, + known_persisted_incomplete_tail: None, + known_persisted_history_cursor: None, + persisted_history_cursor_uncertainty: None, + uncertain_expected_persisted_history_cursor: None, } } @@ -107,6 +132,68 @@ impl SessionState { is_first_turn } + pub(crate) fn known_persisted_incomplete_tail(&self) -> Option { + self.known_persisted_incomplete_tail.clone() + } + + pub(crate) fn set_known_persisted_incomplete_tail(&mut self, tail: Option) { + self.known_persisted_incomplete_tail = tail; + } + + pub(crate) fn known_persisted_history_cursor(&self) -> Option { + self.known_persisted_history_cursor + } + + pub(crate) fn set_known_persisted_history_cursor( + &mut self, + cursor: Option, + ) { + self.known_persisted_history_cursor = cursor; + self.persisted_history_cursor_uncertainty = None; + self.uncertain_expected_persisted_history_cursor = None; + } + + pub(crate) fn persisted_history_cursor_uncertainty( + &self, + ) -> Option { + self.persisted_history_cursor_uncertainty + } + + pub(crate) fn uncertain_expected_persisted_history_cursor( + &self, + ) -> Option { + self.uncertain_expected_persisted_history_cursor + } + + pub(crate) fn set_uncertain_expected_persisted_history_cursor( + &mut self, + cursor: Option, + ) { + self.uncertain_expected_persisted_history_cursor = cursor; + } + + pub(crate) fn invalidate_persisted_item_cursor( + &mut self, + uncertainty: PersistedHistoryCursorUncertainty, + expected_cursor: Option, + ) { + self.known_persisted_history_cursor = None; + self.uncertain_expected_persisted_history_cursor = expected_cursor; + self.persisted_history_cursor_uncertainty = Some( + match (self.persisted_history_cursor_uncertainty, uncertainty) { + (Some(PersistedHistoryCursorUncertainty::HistoryRewrite), _) + | (_, PersistedHistoryCursorUncertainty::HistoryRewrite) => { + PersistedHistoryCursorUncertainty::HistoryRewrite + } + _ => PersistedHistoryCursorUncertainty::AppendOnly, + }, + ); + } + + pub(crate) fn reset_additional_context(&mut self) { + self.additional_context = AdditionalContextStore::default(); + } + pub(crate) fn clone_history(&self) -> ContextManager { self.history.clone() } @@ -116,10 +203,20 @@ impl SessionState { items: Vec, reference_context_item: Option, ) { + self.replace_history_preserving_auto_compact_prefill(items, reference_context_item); + self.auto_compact_window.clear_prefill(); + } + + pub(crate) fn replace_history_preserving_auto_compact_prefill( + &mut self, + items: Vec, + reference_context_item: Option, + ) { + // Append-only handoffs stay in the same compaction window, so their server-observed + // baseline remains authoritative even though the model history is replaced wholesale. self.history.replace(items); self.history .set_reference_context_item(reference_context_item); - self.auto_compact_window.clear_prefill(); } pub(crate) fn set_token_info(&mut self, info: Option) { @@ -163,6 +260,11 @@ impl SessionState { self.auto_compact_window.claim_token_budget_reminder() } + pub(crate) fn set_token_budget_reminder_delivered(&mut self, delivered: bool) { + self.auto_compact_window + .set_token_budget_reminder_delivered(delivered); + } + pub(crate) fn auto_compact_window_number(&self) -> u64 { self.auto_compact_window.window_number() } @@ -179,6 +281,14 @@ impl SessionState { self.auto_compact_window.restore(window_number, ids); } + pub(crate) fn reconcile_auto_compact_window( + &mut self, + window_number: u64, + ids: AutoCompactWindowIds, + ) { + self.auto_compact_window.reconcile(window_number, ids); + } + pub(crate) fn advance_auto_compact_window(&mut self) -> (u64, AutoCompactWindowIds) { self.auto_compact_window.advance() } diff --git a/codex-rs/core/tests/suite/token_budget.rs b/codex-rs/core/tests/suite/token_budget.rs index e536d6b888..b8e650b5a6 100644 --- a/codex-rs/core/tests/suite/token_budget.rs +++ b/codex-rs/core/tests/suite/token_budget.rs @@ -16,6 +16,8 @@ use codex_protocol::protocol::HookRunStatus; use codex_protocol::protocol::ItemCompletedEvent; use codex_protocol::protocol::ItemStartedEvent; use codex_protocol::protocol::Op; +use codex_protocol::protocol::TOKEN_BUDGET_REMINDER_CLOSE_TAG; +use codex_protocol::protocol::TOKEN_BUDGET_REMINDER_OPEN_TAG; use core_test_support::PathBufExt; use core_test_support::assert_regex_match; use core_test_support::context_snapshot; @@ -56,6 +58,10 @@ fn token_budget_contexts(request: &ResponsesRequest) -> Vec { .collect() } +fn wrapped_token_budget_reminder(message: &str) -> String { + format!("{TOKEN_BUDGET_REMINDER_OPEN_TAG}\n{message}\n{TOKEN_BUDGET_REMINDER_CLOSE_TAG}") +} + fn token_budget_window_ids( text: &str, thread_id: codex_protocol::ThreadId, @@ -381,12 +387,14 @@ async fn token_budget_reminder_emits_after_crossing_compaction_threshold() -> Re assert_eq!(requests.len(), 2); let initial_context = token_budget_contexts(&requests[0]); assert_eq!(initial_context.len(), 1); - let reminder = "Your context window is nearly exhausted (only 1000 tokens remaining) and will be automatically reset for you soon. Once reset, message items in current context window will be cleared in the new window, but notes and history items will be persistent across windows."; + let reminder = wrapped_token_budget_reminder( + "Your context window is nearly exhausted (only 1000 tokens remaining) and will be automatically reset for you soon. Once reset, message items in current context window will be cleared in the new window, but notes and history items will be persistent across windows.", + ); assert_eq!( requests[1] .message_input_texts("developer") .into_iter() - .filter(|text| text == reminder) + .filter(|text| text == &reminder) .count(), 1 ); @@ -439,7 +447,9 @@ async fn token_budget_reminder_uses_body_after_prefix_window() -> Result<()> { let requests = responses.requests(); assert_eq!(requests.len(), 3); - let reminder = "Your context window is nearly exhausted (only 400 tokens remaining) and will be automatically reset for you soon. Once reset, message items in current context window will be cleared in the new window, but notes and history items will be persistent across windows."; + let reminder = wrapped_token_budget_reminder( + "Your context window is nearly exhausted (only 400 tokens remaining) and will be automatically reset for you soon. Once reset, message items in current context window will be cleared in the new window, but notes and history items will be persistent across windows.", + ); assert!( requests[1] .message_input_texts("developer") @@ -451,7 +461,7 @@ async fn token_budget_reminder_uses_body_after_prefix_window() -> Result<()> { requests[2] .message_input_texts("developer") .into_iter() - .filter(|text| text == reminder) + .filter(|text| text == &reminder) .count(), 1 ); diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 96a793bcd3..7a2f974a6b 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -117,6 +117,8 @@ pub const CONTEXT_WINDOW_OPEN_TAG: &str = ""; pub const CONTEXT_WINDOW_CLOSE_TAG: &str = ""; pub const CONTEXT_WINDOW_GUIDANCE_OPEN_TAG: &str = ""; pub const CONTEXT_WINDOW_GUIDANCE_CLOSE_TAG: &str = ""; +pub const TOKEN_BUDGET_REMINDER_OPEN_TAG: &str = ""; +pub const TOKEN_BUDGET_REMINDER_CLOSE_TAG: &str = ""; pub const USER_MESSAGE_BEGIN: &str = "## My request for Codex:"; // TODO(anp): Replace `TurnEnvironmentSelection` with `PathUri` once path URIs carry environment diff --git a/codex-rs/thread-store/src/live_thread.rs b/codex-rs/thread-store/src/live_thread.rs index 793bbf9965..1a405a7848 100644 --- a/codex-rs/thread-store/src/live_thread.rs +++ b/codex-rs/thread-store/src/live_thread.rs @@ -220,6 +220,17 @@ impl LiveThread { .await } + /// Seeds append-derived metadata observation from an already persisted history. + /// + /// Callers that refresh a live session from storage must do this before accepting another + /// append, so metadata imported by the refresh is not mistaken for metadata from that append. + pub async fn seed_metadata_from_history(&self, history: &[RolloutItem]) { + self.metadata_sync + .lock() + .await + .record_resume_history(history); + } + pub async fn read_thread( &self, include_archived: bool, diff --git a/codex-rs/thread-store/src/local/mod.rs b/codex-rs/thread-store/src/local/mod.rs index 5939ea606e..50aee63db6 100644 --- a/codex-rs/thread-store/src/local/mod.rs +++ b/codex-rs/thread-store/src/local/mod.rs @@ -470,6 +470,49 @@ mod tests { assert_eq!(metadata.title, "observed append"); } + #[tokio::test] + async fn live_thread_seeded_history_preserves_imported_first_message_metadata() { + let home = TempDir::new().expect("temp dir"); + let config = test_config(home.path()); + let runtime = codex_state::StateRuntime::init( + config.sqlite_home.clone(), + config.default_model_provider_id.clone(), + ) + .await + .expect("state db should initialize"); + let store = Arc::new(LocalThreadStore::new(config, Some(runtime.clone()))); + let thread_id = ThreadId::default(); + let live_thread = LiveThread::create(store, create_thread_params(thread_id)) + .await + .expect("create live thread"); + + live_thread + .seed_metadata_from_history(&[user_message_item("imported first message")]) + .await; + live_thread + .append_items(&[user_message_item("later local message")]) + .await + .expect("append after history refresh"); + + let metadata = runtime + .get_thread(thread_id) + .await + .expect("sqlite metadata read") + .expect("sqlite metadata"); + assert_eq!( + ( + metadata.first_user_message.as_deref(), + metadata.preview.as_deref(), + metadata.title.as_str(), + ), + ( + Some("imported first message"), + Some("imported first message"), + "imported first message", + ) + ); + } + #[tokio::test] async fn live_thread_output_advances_updated_at_but_not_recency_at() { let home = TempDir::new().expect("temp dir");