mirror of
https://github.com/openai/codex.git
synced 2026-12-01 00:20:48 +00:00
Reuse unchanged history snapshots when resuming threads (#49600)
## Why Resuming a thread rereads persisted history even when a preloaded snapshot is unchanged. Reusing that snapshot must still account for writes committed before writer ownership is acquired. ## What changed - Carry optional, non-serialized revisions from stored history and model context through thread and agent resume paths. - Validate the revision under writer ownership and reuse the shared snapshot when it matches. Reload stored history when the revision is missing or changed, while preserving explicit history overrides. - Resolve the selected rollout before loading context, validate compressed snapshots before materialization, and enforce archived-thread restrictions on canonical paths. ## Testing Extend coverage for snapshot reuse and late-write refresh in legacy and paginated histories, compressed rollout reuse, archived rollout symlinks, and cold child restoration that includes edits made after preloading history. GitOrigin-RevId: e1fd7aee6ef2b30f41951e6b7e6b01c3e1420cab
This commit is contained in:
@@ -4598,6 +4598,7 @@ impl ThreadRequestProcessor {
|
||||
.await
|
||||
.map_err(thread_store_resume_read_error)?;
|
||||
let history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: model_context.revision,
|
||||
conversation_id: model_context.thread_id,
|
||||
history: Arc::new(model_context.items),
|
||||
rollout_path: stored_thread.rollout_path.clone(),
|
||||
@@ -4692,18 +4693,15 @@ impl ThreadRequestProcessor {
|
||||
stored_thread: &mut StoredThread,
|
||||
) -> Result<InitialHistory, JSONRPCErrorError> {
|
||||
let thread_id = stored_thread.thread_id;
|
||||
let history = stored_thread
|
||||
.history
|
||||
.take()
|
||||
.map(|history| history.items)
|
||||
.ok_or_else(|| {
|
||||
internal_error(format!(
|
||||
"thread {thread_id} did not include persisted history"
|
||||
))
|
||||
})?;
|
||||
let history = stored_thread.history.take().ok_or_else(|| {
|
||||
internal_error(format!(
|
||||
"thread {thread_id} did not include persisted history"
|
||||
))
|
||||
})?;
|
||||
Ok(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: history.revision,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(history),
|
||||
history: Arc::new(history.items),
|
||||
rollout_path: stored_thread.rollout_path.clone(),
|
||||
}))
|
||||
}
|
||||
@@ -5076,6 +5074,7 @@ impl ThreadRequestProcessor {
|
||||
// The fork cutoff can remove the only TurnContext that records the selected version.
|
||||
// Recover it from the untrimmed source or live parent, independently of permission overrides.
|
||||
let source_multi_agent_version = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: source_thread_id,
|
||||
history: Arc::clone(latest_context.as_ref().unwrap_or(&source_history_items)),
|
||||
rollout_path: source_thread.rollout_path.clone(),
|
||||
@@ -5203,6 +5202,7 @@ impl ThreadRequestProcessor {
|
||||
ForkSnapshot::Interrupted,
|
||||
fork_options,
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: source_thread_id,
|
||||
history: history_items,
|
||||
rollout_path: source_thread.rollout_path.clone(),
|
||||
|
||||
@@ -160,7 +160,7 @@ async fn load_agent_model_context(
|
||||
state: &ThreadManagerState,
|
||||
thread_id: ThreadId,
|
||||
history_mode: ThreadHistoryMode,
|
||||
) -> CodexResult<Option<Vec<RolloutItem>>> {
|
||||
) -> CodexResult<Option<codex_thread_store::StoredModelContext>> {
|
||||
match history_mode {
|
||||
ThreadHistoryMode::Legacy => Ok(state
|
||||
.read_stored_thread(ReadThreadParams {
|
||||
@@ -170,15 +170,18 @@ async fn load_agent_model_context(
|
||||
})
|
||||
.await?
|
||||
.history
|
||||
.map(|history| history.items)),
|
||||
.map(|history| codex_thread_store::StoredModelContext {
|
||||
thread_id,
|
||||
revision: history.revision,
|
||||
items: history.items,
|
||||
})),
|
||||
ThreadHistoryMode::Paginated => Ok(Some(
|
||||
state
|
||||
.load_latest_model_context(LoadThreadHistoryParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
})
|
||||
.await?
|
||||
.items,
|
||||
.await?,
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -365,8 +368,9 @@ impl LocalAgentControl {
|
||||
.await?
|
||||
.ok_or(CodexErr::ThreadNotFound(thread_id))?;
|
||||
let initial_history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: history.revision,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(history),
|
||||
history: Arc::new(history.items),
|
||||
rollout_path: stored_thread.rollout_path,
|
||||
});
|
||||
if initial_history.get_multi_agent_version() != Some(MultiAgentVersion::V2) {
|
||||
@@ -992,7 +996,8 @@ impl LocalAgentControl {
|
||||
CodexErr::Fatal(format!(
|
||||
"parent thread history unavailable for fork: {parent_thread_id}"
|
||||
))
|
||||
})?;
|
||||
})?
|
||||
.items;
|
||||
|
||||
let selected_capability_roots = forked_rollout_items
|
||||
.iter()
|
||||
@@ -1351,8 +1356,9 @@ impl LocalAgentControl {
|
||||
.await?
|
||||
.ok_or(CodexErr::ThreadNotFound(thread_id))?;
|
||||
let initial_history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: history.revision,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(history),
|
||||
history: Arc::new(history.items),
|
||||
rollout_path: stored_thread.rollout_path,
|
||||
});
|
||||
let parent_thread_id = stored_thread.parent_thread_id;
|
||||
|
||||
@@ -1347,6 +1347,7 @@ async fn cold_resume_with_thread_instructions_preserves_lazy_v2_child_inheritanc
|
||||
.await
|
||||
.expect("read parent history");
|
||||
let initial_history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: parent_thread_id,
|
||||
history: Arc::new(stored_parent.history.expect("parent history").items),
|
||||
rollout_path: stored_parent.rollout_path,
|
||||
|
||||
@@ -15,6 +15,7 @@ use test_case::test_case;
|
||||
|
||||
#[test_case(InitialHistory::Forked(Vec::new()); "fork")]
|
||||
#[test_case(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(Vec::new()),
|
||||
rollout_path: None,
|
||||
|
||||
@@ -98,6 +98,7 @@ async fn recorded_questions_share_queued_input_order_across_resume() {
|
||||
let saved = serde_json::from_value(serde_json::to_value(saved).unwrap()).unwrap();
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: session.thread_id,
|
||||
history: Arc::new(saved),
|
||||
rollout_path: None,
|
||||
@@ -307,6 +308,7 @@ async fn record_initial_history_reconstructs_typed_inter_agent_message() {
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(vec![RolloutItem::InterAgentCommunication(
|
||||
communication.clone(),
|
||||
@@ -334,6 +336,7 @@ async fn record_initial_history_ignores_security_risk_scores() {
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(vec![
|
||||
RolloutItem::ResponseItem(ResponseItemEnvelope::new(user_item.clone())),
|
||||
@@ -394,6 +397,7 @@ async fn record_initial_history_restores_world_state_baseline(input: BaselineTur
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -467,6 +471,7 @@ async fn record_initial_history_resumed_bare_turn_context_does_not_hydrate_previ
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -552,6 +557,7 @@ async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lif
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -1180,6 +1186,7 @@ async fn record_initial_history_resumed_rollback_skips_only_user_turns() {
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -1274,6 +1281,7 @@ async fn record_initial_history_resumed_rollback_drops_incomplete_user_turn_comp
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -1341,6 +1349,7 @@ async fn record_initial_history_requires_surviving_full_snapshot_without_user_tu
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -1374,6 +1383,7 @@ async fn record_initial_history_resumed_does_not_seed_reference_context_item_aft
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -1986,6 +1996,7 @@ async fn record_initial_history_resumed_turn_context_after_compaction_reestablis
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -2154,6 +2165,7 @@ async fn record_initial_history_resumed_aborted_turn_without_id_clears_active_tu
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -2291,6 +2303,7 @@ async fn record_initial_history_resumed_unmatched_abort_preserves_active_turn_fo
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -2423,6 +2436,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_compaction_clea
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -2476,6 +2490,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_preserves_turn_
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -2621,6 +2636,7 @@ async fn record_initial_history_resumed_replaced_incomplete_compacted_turn_clear
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
|
||||
@@ -1083,6 +1083,7 @@ impl Session {
|
||||
}
|
||||
InitialHistory::Resumed(resumed_history) => {
|
||||
let params = ResumeThreadParams {
|
||||
history_revision: resumed_history.history_revision.clone(),
|
||||
thread_id: resumed_history.conversation_id,
|
||||
rollout_path: resumed_history.rollout_path.clone(),
|
||||
history: Some(resumed_history.history.clone()),
|
||||
@@ -1205,6 +1206,7 @@ impl Session {
|
||||
&& let Some(history) = resume_context
|
||||
{
|
||||
resumed.history = history;
|
||||
resumed.history_revision = None;
|
||||
}
|
||||
let rollout_path = if let Some(live_thread) = live_thread.as_ref() {
|
||||
live_thread.local_rollout_path().await?
|
||||
|
||||
@@ -2484,6 +2484,7 @@ async fn record_initial_history_reconstructs_resumed_transcript() {
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -3101,6 +3102,7 @@ async fn prepares_resumed_history_before_installing_it() {
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(vec![RolloutItem::ResponseItem(ResponseItemEnvelope {
|
||||
item: resumed_item,
|
||||
@@ -3161,6 +3163,7 @@ fn resolve_multi_agent_version_handles_unset_and_legacy_history() {
|
||||
assert_eq!(
|
||||
resolve_multi_agent_version(
|
||||
&InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(Vec::new()),
|
||||
rollout_path: None,
|
||||
@@ -3172,6 +3175,7 @@ fn resolve_multi_agent_version_handles_unset_and_legacy_history() {
|
||||
assert_eq!(
|
||||
resolve_multi_agent_version(
|
||||
&InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(Vec::new()),
|
||||
rollout_path: None,
|
||||
@@ -3183,6 +3187,7 @@ fn resolve_multi_agent_version_handles_unset_and_legacy_history() {
|
||||
assert_eq!(
|
||||
resolve_multi_agent_version(
|
||||
&InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(vec![session_meta_item(
|
||||
thread_id,
|
||||
@@ -3248,6 +3253,7 @@ async fn resumed_history_injects_initial_context_on_first_context_update_only()
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -3358,6 +3364,7 @@ async fn record_initial_history_seeds_token_info_from_rollout() {
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(rollout_items),
|
||||
rollout_path: Some(PathBuf::from("/tmp/resume.jsonl")),
|
||||
@@ -7296,6 +7303,7 @@ async fn resumed_root_session_uses_thread_id_as_session_id() {
|
||||
let thread_id = ThreadId::new();
|
||||
let (session, rx_event) = make_session_with_history_source_and_agent_control_and_rx(
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(Vec::new()),
|
||||
rollout_path: None,
|
||||
@@ -7331,6 +7339,7 @@ async fn resumed_subagent_session_restores_persisted_session_id() {
|
||||
});
|
||||
let (session, rx_event) = make_session_with_history_source_and_agent_control_and_rx(
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(vec![RolloutItem::SessionMeta(SessionMetaLine {
|
||||
meta: SessionMeta {
|
||||
@@ -7392,6 +7401,7 @@ async fn resumed_copied_fork_ignores_source_history_base() {
|
||||
];
|
||||
let (session, _rx_event) = make_session_with_history_source_and_agent_control_and_rx(
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(history),
|
||||
rollout_path: None,
|
||||
|
||||
@@ -1492,6 +1492,7 @@ impl ThreadManager {
|
||||
prepared: PreparedFork,
|
||||
) -> CodexResult<NewThread> {
|
||||
let history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: prepared.source_thread_id,
|
||||
history: Arc::clone(&prepared.model_context),
|
||||
rollout_path: None,
|
||||
@@ -2466,6 +2467,7 @@ fn stored_thread_to_initial_history(
|
||||
))
|
||||
})?;
|
||||
Ok(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: history.revision,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(history.items),
|
||||
rollout_path: rollout_path.or(stored_thread.rollout_path),
|
||||
|
||||
@@ -109,6 +109,7 @@ async fn live_fork_keeps_instructions_when_source_is_unloaded_during_setup() {
|
||||
.await
|
||||
.expect("start source");
|
||||
let history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: source.thread_id,
|
||||
history: Arc::new(Vec::new()),
|
||||
rollout_path: None,
|
||||
@@ -323,6 +324,7 @@ async fn reserved_thread_id_is_used_without_changing_normal_id_generation() {
|
||||
.expect("start reserved thread");
|
||||
let mut resumed_options = StartThreadOptions::new(config.clone());
|
||||
resumed_options.initial_history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: reserved.thread_id,
|
||||
history: Arc::new(Vec::new()),
|
||||
rollout_path: None,
|
||||
@@ -2459,6 +2461,7 @@ async fn rollout_path_resume_and_fork_read_history_through_thread_store() {
|
||||
.resume_thread_with_history(
|
||||
config.clone(),
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: source.thread_id,
|
||||
history: Arc::new(vec![RolloutItem::ResponseItem(user_msg("hello").into())]),
|
||||
rollout_path: Some(rollout_path.clone()),
|
||||
|
||||
@@ -405,6 +405,7 @@ async fn host_factory_follows_thread_lifecycle() -> anyhow::Result<()> {
|
||||
test.codex.flush_rollout().await?;
|
||||
let saved = test.codex.load_history(/*include_archived*/ false).await?;
|
||||
let history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: root_id,
|
||||
history: Arc::new(saved.items),
|
||||
rollout_path: test.codex.rollout_path(),
|
||||
|
||||
@@ -279,6 +279,7 @@ pub(super) async fn persisted_resume_history(
|
||||
Ok((
|
||||
thread_id,
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(
|
||||
store
|
||||
@@ -1588,6 +1589,7 @@ async fn fork_preserves_thread_instructions(
|
||||
})
|
||||
.await?;
|
||||
let history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: parent_id,
|
||||
history: Arc::new(stored.items),
|
||||
rollout_path: None,
|
||||
|
||||
@@ -4690,6 +4690,7 @@ async fn paginated_compaction_cold_resume_from_bounded_suffix() -> Result<()> {
|
||||
.resume_thread_with_history(
|
||||
test.config.clone(),
|
||||
codex_history::InitialHistory::Resumed(codex_history::ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: context.thread_id,
|
||||
history: Arc::new(context.items),
|
||||
rollout_path: Some(path),
|
||||
|
||||
@@ -50,6 +50,7 @@ async fn ephemeral_fork_skips_stored_title_lookup() -> anyhow::Result<()> {
|
||||
ForkSnapshot::Interrupted,
|
||||
codex_core::StartThreadOptions::new(config),
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: test.session_configured.thread_id,
|
||||
history: Arc::new(Vec::new()),
|
||||
rollout_path: None,
|
||||
@@ -218,6 +219,7 @@ async fn fork_thread_restores_history_selection_and_preserves_explicit_clear() -
|
||||
)
|
||||
.await?;
|
||||
let history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: test.session_configured.thread_id,
|
||||
history: Arc::new(vec![thread_settings_applied_item(
|
||||
test.session_configured.thread_id,
|
||||
@@ -332,6 +334,7 @@ async fn assert_copied_fork_persists_inherited_history(history_mode: ThreadHisto
|
||||
ForkSnapshot::Interrupted,
|
||||
codex_core::StartThreadOptions::new(test.config.clone()),
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: test.session_configured.thread_id,
|
||||
history: Arc::new(supplied_history),
|
||||
rollout_path: None,
|
||||
|
||||
@@ -75,6 +75,7 @@ pub(super) async fn resume(
|
||||
.start_thread(StartThreadOptions {
|
||||
environments: Some(environments),
|
||||
initial_history: InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(history),
|
||||
rollout_path: None,
|
||||
|
||||
@@ -110,6 +110,7 @@ async fn guardian_history_survives_restart_and_user_fork(
|
||||
let items: Vec<RolloutItem> =
|
||||
serde_json::from_value(serde_json::to_value(model_context.items)?)?;
|
||||
let history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(items),
|
||||
rollout_path: None,
|
||||
|
||||
@@ -226,6 +226,7 @@ async fn resume(test: &TestCodex, thread: &CodexThread) -> Result<Arc<CodexThrea
|
||||
.resume_thread_with_history(
|
||||
test.config.clone(),
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(items),
|
||||
rollout_path: None,
|
||||
@@ -923,6 +924,7 @@ async fn standalone_fork_retains_inherited_user_instructions(
|
||||
ForkSnapshot::Interrupted,
|
||||
codex_core::StartThreadOptions::new(test.config.clone()),
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: worker.startup_metadata().thread_id,
|
||||
history: Arc::new(load_context(&test, &worker).await?),
|
||||
rollout_path: None,
|
||||
|
||||
@@ -1686,6 +1686,7 @@ async fn run_guardian_subagent_review(
|
||||
.resume_thread_with_history(
|
||||
test.config.clone(),
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: root_thread_id,
|
||||
history: Arc::new(saved.items),
|
||||
rollout_path: None,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Exercises read overlap and ordered identity registration when a V2 root resumes cold.
|
||||
//! Exercises read overlap, ordered identities, and revision-aware history on cold V2 resumes.
|
||||
|
||||
use super::ROLE_MODEL;
|
||||
use super::ROLE_NAME;
|
||||
@@ -13,6 +13,7 @@ use codex_features::Feature;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::error::CodexErrorDetails;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_thread_store::AppendThreadItemsParams;
|
||||
@@ -50,10 +51,13 @@ use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::timeout;
|
||||
|
||||
const LATE_EDIT: &str = "Durable edit after the child history snapshot";
|
||||
|
||||
struct GatedChildMetadataStore {
|
||||
inner: Arc<dyn ThreadStore>,
|
||||
gates: Mutex<HashMap<ThreadId, oneshot::Receiver<()>>>,
|
||||
failed_child: ThreadId,
|
||||
edited_child: ThreadId,
|
||||
started: mpsc::UnboundedSender<ThreadId>,
|
||||
completed: mpsc::UnboundedSender<ThreadId>,
|
||||
}
|
||||
@@ -77,7 +81,6 @@ impl ThreadStore for GatedChildMetadataStore {
|
||||
|
||||
delegate_store_methods! {
|
||||
fn create_thread(params: CreateThreadParams) -> ();
|
||||
fn resume_thread(params: ResumeThreadParams) -> Arc<Vec<RolloutItem>>;
|
||||
fn append_items(params: AppendThreadItemsParams) -> ();
|
||||
fn flush_thread(thread_id: ThreadId) -> ();
|
||||
fn shutdown_thread(thread_id: ThreadId) -> ();
|
||||
@@ -92,6 +95,41 @@ impl ThreadStore for GatedChildMetadataStore {
|
||||
fn delete_thread(params: DeleteThreadParams) -> ();
|
||||
}
|
||||
|
||||
fn resume_thread(
|
||||
&self,
|
||||
params: ResumeThreadParams,
|
||||
) -> ThreadStoreFuture<'_, Arc<Vec<RolloutItem>>> {
|
||||
Box::pin(async move {
|
||||
assert!(
|
||||
params.history_revision.is_some(),
|
||||
"core must forward the revision"
|
||||
);
|
||||
let supplied = params.history.as_ref().expect("preloaded history");
|
||||
let unchanged = self.inner.resume_thread(params.clone()).await?;
|
||||
assert!(Arc::ptr_eq(supplied, &unchanged));
|
||||
if params.thread_id != self.edited_child {
|
||||
return Ok(unchanged);
|
||||
}
|
||||
|
||||
// Commit an edit after core preloads history, before its writer acquisition finishes.
|
||||
let edit: ResponseItem = serde_json::from_value(json!({
|
||||
"type": "message", "role": "user",
|
||||
"content": [{"type": "input_text", "text": LATE_EDIT}],
|
||||
}))
|
||||
.expect("late user message");
|
||||
self.inner
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id: params.thread_id,
|
||||
items: vec![RolloutItem::ResponseItem(edit.into())],
|
||||
})
|
||||
.await?;
|
||||
self.inner.shutdown_thread(params.thread_id).await?;
|
||||
let refreshed = self.inner.resume_thread(params).await?;
|
||||
assert!(!Arc::ptr_eq(&unchanged, &refreshed));
|
||||
Ok(refreshed)
|
||||
})
|
||||
}
|
||||
|
||||
fn persist_thread(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
@@ -215,6 +253,7 @@ async fn cold_root_resume_overlaps_child_reads_and_applies_identities_in_graph_o
|
||||
(last, last_gate),
|
||||
])),
|
||||
failed_child: failed,
|
||||
edited_child: first,
|
||||
started: started_tx,
|
||||
completed: completed_tx,
|
||||
});
|
||||
@@ -266,5 +305,27 @@ async fn cold_root_resume_overlaps_child_reads_and_applies_identities_in_graph_o
|
||||
assert!(resumed.thread_manager.get_thread(first).await.is_ok());
|
||||
assert!(resumed.thread_manager.get_thread(last).await.is_err());
|
||||
assert!(resumed.thread_manager.get_thread(failed).await.is_err());
|
||||
|
||||
mount_root_collaboration_call(
|
||||
&server,
|
||||
"continue restored child",
|
||||
"resume-child",
|
||||
"followup_task",
|
||||
&json!({ "target": first.to_string(), "message": "continue after resume" }).to_string(),
|
||||
)
|
||||
.await;
|
||||
let followup = mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| request_has_model(request, ROLE_MODEL),
|
||||
sse(vec![ev_completed("restored-child-followup")]),
|
||||
)
|
||||
.await;
|
||||
resumed.submit_turn("continue restored child").await?;
|
||||
let child = resumed.thread_manager.get_thread(first).await?;
|
||||
wait_for_event(child.as_ref(), |event| {
|
||||
matches!(event, EventMsg::TurnComplete(_))
|
||||
})
|
||||
.await;
|
||||
assert!(followup.single_request().body_contains_text(LATE_EDIT));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -509,6 +509,7 @@ async fn local_preparation_is_durable_before_first_input_and_survives_restart(
|
||||
.resume_thread_with_history(
|
||||
initial.config.clone(),
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: context.thread_id,
|
||||
history: Arc::new(context.items),
|
||||
rollout_path: Some(rollout_path),
|
||||
|
||||
@@ -61,6 +61,7 @@ async fn local_thread_history_mode_survives_restart(
|
||||
.resume_thread_with_history(
|
||||
initial.config.clone(),
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: history.thread_id,
|
||||
history: Arc::new(history.items),
|
||||
rollout_path: initial.session_configured.rollout_path.clone(),
|
||||
|
||||
@@ -58,6 +58,7 @@ fn resume_history(
|
||||
};
|
||||
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: ThreadId::default(),
|
||||
history: Arc::new(vec![
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
|
||||
|
||||
@@ -169,6 +169,7 @@ async fn compressed_shared_fork_resume_preserves_checkpoint_and_frozen_history()
|
||||
.resume_thread_with_history(
|
||||
config,
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: context.thread_id,
|
||||
history: Arc::new(context.items),
|
||||
rollout_path: Some(child_path),
|
||||
|
||||
@@ -3089,6 +3089,7 @@ async fn production_turn_keeps_rebalanced_catalogs_stable_after_compaction_and_r
|
||||
.thread_manager
|
||||
.start_thread(StartThreadOptions {
|
||||
initial_history: InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: history.revision,
|
||||
conversation_id: history.thread_id,
|
||||
history: Arc::new(history.items),
|
||||
rollout_path: cloud_thread.session_configured.rollout_path.clone(),
|
||||
|
||||
@@ -71,6 +71,7 @@ pub async fn append_existing_session(
|
||||
}
|
||||
if thread_store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
|
||||
@@ -359,6 +359,9 @@ pub struct RolloutLine {
|
||||
pub struct ResumedHistory {
|
||||
pub conversation_id: ThreadId,
|
||||
pub history: Arc<Vec<RolloutItem>>,
|
||||
/// Store-issued revision for this exact snapshot; clear it when modifying the history.
|
||||
#[serde(skip)]
|
||||
pub history_revision: Option<String>,
|
||||
pub rollout_path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
|
||||
@@ -959,6 +959,7 @@ fn copied_history_uses_persisted_history_mode() -> Result<()> {
|
||||
git: None,
|
||||
});
|
||||
let history = InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(vec![session_meta.clone()]),
|
||||
rollout_path: None,
|
||||
@@ -978,6 +979,7 @@ fn copied_history_uses_persisted_history_mode() -> Result<()> {
|
||||
);
|
||||
assert_eq!(
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: thread_id,
|
||||
history: Arc::new(Vec::new()),
|
||||
rollout_path: None,
|
||||
|
||||
@@ -1164,6 +1164,7 @@ impl RolloutRecorder {
|
||||
|
||||
info!("Resumed rollout successfully from {path:?}");
|
||||
Ok(InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id,
|
||||
history: Arc::new(items),
|
||||
rollout_path: Some(compression::plain_rollout_path(path)),
|
||||
|
||||
@@ -335,6 +335,7 @@ mod tests {
|
||||
.expect("create paginated thread");
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path.clone()),
|
||||
history: None,
|
||||
@@ -397,6 +398,7 @@ mod tests {
|
||||
);
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: None,
|
||||
history: None,
|
||||
@@ -680,6 +682,7 @@ impl InMemoryThreadStore {
|
||||
let history_mode = history_mode_from_state(&state, params.thread_id);
|
||||
reject_paginated_history_mode(history_mode)?;
|
||||
Ok(StoredThreadHistory {
|
||||
revision: None,
|
||||
thread_id: params.thread_id,
|
||||
items: items.clone(),
|
||||
})
|
||||
@@ -699,6 +702,7 @@ impl InMemoryThreadStore {
|
||||
thread_id: params.thread_id,
|
||||
})?;
|
||||
Ok(StoredModelContext {
|
||||
revision: None,
|
||||
thread_id: params.thread_id,
|
||||
items: items.clone(),
|
||||
})
|
||||
@@ -1082,6 +1086,7 @@ fn stored_thread_from_state(
|
||||
.ok_or(ThreadStoreError::ThreadNotFound { thread_id })?;
|
||||
let history_items = state.histories.get(&thread_id).cloned().unwrap_or_default();
|
||||
let history = include_history.then(|| StoredThreadHistory {
|
||||
revision: None,
|
||||
thread_id,
|
||||
items: history_items.clone(),
|
||||
});
|
||||
|
||||
@@ -22,6 +22,7 @@ use uuid::Uuid;
|
||||
use super::LocalThreadStore;
|
||||
use super::test_support::test_config;
|
||||
use super::test_support::write_session_file;
|
||||
use crate::LoadThreadHistoryParams;
|
||||
use crate::ResumeThreadParams;
|
||||
use crate::ThreadMetadataPatch;
|
||||
use crate::ThreadPersistenceMetadata;
|
||||
@@ -46,6 +47,7 @@ fn age(path: &Path) -> TestResult<()> {
|
||||
|
||||
fn resume(thread_id: ThreadId, path: &Path, home: &Path) -> ResumeThreadParams {
|
||||
ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(path.to_path_buf()),
|
||||
history: None,
|
||||
@@ -186,6 +188,24 @@ async fn metadata_updates_share_ownership_and_resume_compressed_rollouts() -> Te
|
||||
json!(Some(RolloutItem::SessionMeta(expected.clone())))
|
||||
);
|
||||
|
||||
age(&path)?;
|
||||
compress(home.path()).await?;
|
||||
let snapshot = competitor
|
||||
.load_history(LoadThreadHistoryParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
})
|
||||
.await?;
|
||||
let history = Arc::new(snapshot.items);
|
||||
let resumed = competitor
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history: Some(Arc::clone(&history)),
|
||||
history_revision: snapshot.revision,
|
||||
..resume(thread_id, &path, home.path())
|
||||
})
|
||||
.await?;
|
||||
assert!(Arc::ptr_eq(&history, &resumed));
|
||||
competitor.shutdown_thread(thread_id).await?;
|
||||
age(&path)?;
|
||||
compress(home.path()).await?;
|
||||
patch.patch.memory_mode = Some(ThreadMemoryMode::Enabled);
|
||||
|
||||
@@ -794,6 +794,7 @@ SELECT
|
||||
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//! Validates snapshots of append-only local rollouts before reusing them for resume.
|
||||
//!
|
||||
//! Capture before and after reading; any change or unavailable metadata disables reuse. The
|
||||
//! selected path prevents reuse for a different rollout. Validate under writer ownership,
|
||||
//! before opening the recorder can materialize a compressed file.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
pub(super) async fn read(path: &Path) -> Option<String> {
|
||||
let path = codex_rollout::existing_rollout_path(path).await?;
|
||||
let path = tokio::fs::canonicalize(path).await.ok()?;
|
||||
let metadata = tokio::fs::metadata(&path).await.ok()?;
|
||||
let modified = metadata.modified().ok()?;
|
||||
let created = metadata.created().ok();
|
||||
#[cfg(unix)]
|
||||
let identity = {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
Some((
|
||||
metadata.dev(),
|
||||
metadata.ino(),
|
||||
metadata.ctime(),
|
||||
metadata.ctime_nsec(),
|
||||
))
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let identity: Option<(u64, u64, i64, i64)> = None;
|
||||
serde_json::to_string(&("local", path, metadata.len(), modified, created, identity)).ok()
|
||||
}
|
||||
@@ -15,7 +15,6 @@ use super::LocalThreadStore;
|
||||
use super::create_thread;
|
||||
use crate::AppendThreadItemsParams;
|
||||
use crate::CreateThreadParams;
|
||||
use crate::LoadThreadHistoryParams;
|
||||
use crate::ResumeThreadParams;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
@@ -45,16 +44,6 @@ pub(super) async fn resume_thread(
|
||||
let _live_writer_guard = store.live_writer_locks.lock(params.thread_id).await;
|
||||
store.ensure_live_recorder_absent(params.thread_id).await?;
|
||||
let writer_lock = store.acquire_writer_lock(params.thread_id)?;
|
||||
let supplied_history = params
|
||||
.history
|
||||
.as_ref()
|
||||
.filter(|history| {
|
||||
!matches!(
|
||||
history.first(),
|
||||
Some(RolloutItem::SessionMeta(meta)) if meta.meta.id == params.thread_id
|
||||
)
|
||||
})
|
||||
.cloned();
|
||||
let rollout_path = match params.rollout_path {
|
||||
Some(rollout_path) => rollout_path,
|
||||
None => {
|
||||
@@ -74,18 +63,38 @@ pub(super) async fn resume_thread(
|
||||
.path
|
||||
}
|
||||
};
|
||||
let history_mode = if let Some(history) = params.history.as_deref() {
|
||||
canonical_history_mode_from_rollout_items(history)
|
||||
} else {
|
||||
super::read_thread::read_thread_by_rollout_path(
|
||||
store,
|
||||
rollout_path.clone(),
|
||||
params.include_archived,
|
||||
/*include_history*/ false,
|
||||
)
|
||||
.await?
|
||||
.history_mode
|
||||
let rollout_path =
|
||||
super::read_thread::resolve_requested_rollout_path(store, rollout_path).await?;
|
||||
if !params.include_archived
|
||||
&& super::helpers::rollout_path_is_archived(&store.config.codex_home, &rollout_path)
|
||||
{
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("thread {} is archived", params.thread_id),
|
||||
});
|
||||
}
|
||||
let history = match params.history {
|
||||
Some(history)
|
||||
if !matches!(
|
||||
history.first(),
|
||||
Some(RolloutItem::SessionMeta(meta)) if meta.meta.id == params.thread_id
|
||||
) =>
|
||||
{
|
||||
history
|
||||
}
|
||||
Some(history)
|
||||
if params.history_revision.is_some()
|
||||
&& params.history_revision
|
||||
== super::history_revision::read(&rollout_path).await =>
|
||||
{
|
||||
history
|
||||
}
|
||||
_ => Arc::new(
|
||||
super::model_context::load_from_rollout_path(store, params.thread_id, &rollout_path)
|
||||
.await?
|
||||
.items,
|
||||
),
|
||||
};
|
||||
let history_mode = canonical_history_mode_from_rollout_items(&history);
|
||||
let cwd = params
|
||||
.metadata
|
||||
.cwd
|
||||
@@ -123,28 +132,7 @@ pub(super) async fn resume_thread(
|
||||
writer_lock,
|
||||
)
|
||||
.await?;
|
||||
if let Some(history) = supplied_history {
|
||||
return Ok(history);
|
||||
}
|
||||
// Resolve through the installed writer so explicit paths and materialized compressed rollouts
|
||||
// take precedence over SQLite. Both ownership guards remain held throughout this read.
|
||||
let history = super::model_context::load_latest_model_context(
|
||||
store,
|
||||
LoadThreadHistoryParams {
|
||||
thread_id: params.thread_id,
|
||||
include_archived: params.include_archived,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
if history.is_err() {
|
||||
let entry = store.live_recorders.lock().await.remove(¶ms.thread_id);
|
||||
if let Some(entry) = entry
|
||||
&& let Err(err) = entry.recorder.discard().await
|
||||
{
|
||||
warn!("failed to discard writer after resume history load failed: {err}");
|
||||
}
|
||||
}
|
||||
history.map(|history| Arc::new(history.items))
|
||||
Ok(history)
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
|
||||
@@ -2,6 +2,7 @@ mod archive_thread;
|
||||
mod create_thread;
|
||||
mod delete_thread;
|
||||
mod helpers;
|
||||
mod history_revision;
|
||||
mod list_threads;
|
||||
mod live_writer;
|
||||
mod model_context;
|
||||
@@ -1002,6 +1003,7 @@ mod tests {
|
||||
store,
|
||||
ThreadHistoryMode::Paginated,
|
||||
ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path.clone()),
|
||||
history: Some(Arc::clone(&history)),
|
||||
@@ -1018,7 +1020,7 @@ mod tests {
|
||||
assert!(Arc::ptr_eq(&supplied_history, &history));
|
||||
assert_eq!(
|
||||
resumed.local_rollout_path().await.expect("live rollout"),
|
||||
Some(rollout_path)
|
||||
Some(std::fs::canonicalize(rollout_path).expect("canonical rollout path"))
|
||||
);
|
||||
resumed.shutdown().await.expect("shutdown resumed writer");
|
||||
|
||||
@@ -1355,6 +1357,7 @@ mod tests {
|
||||
store,
|
||||
ThreadHistoryMode::Legacy,
|
||||
ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
@@ -1410,6 +1413,7 @@ mod tests {
|
||||
store,
|
||||
ThreadHistoryMode::Legacy,
|
||||
ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
@@ -1593,6 +1597,7 @@ mod tests {
|
||||
let resumed_store = LocalThreadStore::new(config, Some(runtime));
|
||||
resumed_store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: None,
|
||||
history: None,
|
||||
@@ -1641,15 +1646,16 @@ mod tests {
|
||||
.live_rollout_path(thread_id)
|
||||
.await
|
||||
.expect("load rollout path");
|
||||
let mut expected = primary
|
||||
let snapshot = primary
|
||||
.load_latest_model_context(LoadThreadHistoryParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
})
|
||||
.await
|
||||
.expect("load initial snapshot")
|
||||
.items;
|
||||
.expect("load initial snapshot");
|
||||
let mut expected = snapshot.items;
|
||||
let resume_params = ResumeThreadParams {
|
||||
history_revision: snapshot.revision,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: Some(Arc::new(expected.clone())),
|
||||
@@ -1669,6 +1675,19 @@ mod tests {
|
||||
.expect_err("competing resume should fail");
|
||||
assert!(matches!(error, ThreadStoreError::Conflict { .. }));
|
||||
|
||||
primary
|
||||
.shutdown_thread(thread_id)
|
||||
.await
|
||||
.expect("release writer");
|
||||
let unchanged = secondary
|
||||
.resume_thread(resume_params.clone())
|
||||
.await
|
||||
.expect("resume unchanged snapshot");
|
||||
assert!(Arc::ptr_eq(
|
||||
&unchanged,
|
||||
resume_params.history.as_ref().unwrap()
|
||||
));
|
||||
|
||||
let late_edit = RolloutItem::ResponseItem(
|
||||
ResponseItem::Message {
|
||||
id: None,
|
||||
@@ -1681,7 +1700,7 @@ mod tests {
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
primary
|
||||
secondary
|
||||
.append_items(AppendThreadItemsParams {
|
||||
thread_id,
|
||||
items: vec![late_edit.clone()],
|
||||
@@ -1689,11 +1708,11 @@ mod tests {
|
||||
.await
|
||||
.expect("append before handing off writer ownership");
|
||||
expected.push(late_edit);
|
||||
primary
|
||||
secondary
|
||||
.shutdown_thread(thread_id)
|
||||
.await
|
||||
.expect("shutdown should release writer ownership");
|
||||
let resumed = secondary
|
||||
let resumed = primary
|
||||
.resume_thread(resume_params)
|
||||
.await
|
||||
.expect("resume after shutdown should acquire writer ownership");
|
||||
@@ -1737,6 +1756,7 @@ mod tests {
|
||||
.expect("live rollout path");
|
||||
let err = store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
@@ -1766,6 +1786,7 @@ mod tests {
|
||||
.expect("session file");
|
||||
let err = store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path.clone()),
|
||||
history: None,
|
||||
@@ -1784,6 +1805,7 @@ mod tests {
|
||||
|
||||
competing_store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
@@ -1806,6 +1828,7 @@ mod tests {
|
||||
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
@@ -1854,6 +1877,7 @@ mod tests {
|
||||
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path.clone()),
|
||||
history: None,
|
||||
@@ -1872,7 +1896,10 @@ mod tests {
|
||||
.await
|
||||
.expect("read external live thread");
|
||||
|
||||
assert_eq!(thread.rollout_path, Some(rollout_path));
|
||||
assert_eq!(
|
||||
thread.rollout_path,
|
||||
Some(std::fs::canonicalize(rollout_path).expect("canonical rollout path"))
|
||||
);
|
||||
assert!(thread.history.expect("history").items.iter().any(|item| {
|
||||
matches!(
|
||||
item,
|
||||
@@ -1898,15 +1925,30 @@ mod tests {
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let rollout_path = write_archived_session_file(home.path(), "2025-01-04T10-30-00", uuid)
|
||||
.expect("archived session file");
|
||||
#[cfg(unix)]
|
||||
let rollout_path = {
|
||||
let alias = home.path().join("active-alias.jsonl");
|
||||
std::os::unix::fs::symlink(&rollout_path, &alias).expect("symlink archived rollout");
|
||||
alias
|
||||
};
|
||||
|
||||
let mut resume_params = ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
include_archived: false,
|
||||
metadata: thread_metadata(),
|
||||
};
|
||||
let err = store
|
||||
.resume_thread(resume_params.clone())
|
||||
.await
|
||||
.expect_err("active-only resume should reject archived rollout targets");
|
||||
assert!(matches!(err, ThreadStoreError::InvalidRequest { .. }));
|
||||
assert!(err.to_string().contains("archived"));
|
||||
resume_params.include_archived = true;
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
include_archived: true,
|
||||
metadata: thread_metadata(),
|
||||
})
|
||||
.resume_thread(resume_params)
|
||||
.await
|
||||
.expect("resume live archived thread");
|
||||
store
|
||||
@@ -2071,6 +2113,7 @@ mod tests {
|
||||
);
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Reconstructs model context and preserves source runtime metadata across fork cutoffs.
|
||||
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
use codex_protocol::protocol::HistoryPosition;
|
||||
use codex_protocol::protocol::SessionMetaLine;
|
||||
@@ -48,31 +49,44 @@ pub(super) async fn load_latest_model_context(
|
||||
message: format!("no rollout found for thread id {}", params.thread_id),
|
||||
})?;
|
||||
|
||||
let session_meta = codex_rollout::read_session_meta_line(path.as_path())
|
||||
load_from_rollout_path(store, params.thread_id, &path).await
|
||||
}
|
||||
|
||||
pub(super) async fn load_from_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: codex_protocol::ThreadId,
|
||||
path: &Path,
|
||||
) -> ThreadStoreResult<StoredModelContext> {
|
||||
let before = super::history_revision::read(path).await;
|
||||
let session_meta = codex_rollout::read_session_meta_line(path)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to read session metadata {}: {err}", path.display()),
|
||||
})?;
|
||||
if session_meta.meta.id != params.thread_id {
|
||||
if session_meta.meta.id != thread_id {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout at {} belongs to thread {}, not {}",
|
||||
path.display(),
|
||||
session_meta.meta.id,
|
||||
params.thread_id
|
||||
thread_id
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
let items = if matches!(session_meta.meta.history_mode, ThreadHistoryMode::Paginated) {
|
||||
let lineage = store.resolve_rollout_lineage(params.thread_id).await?;
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(thread_id, Some(path.to_path_buf()))
|
||||
.await?;
|
||||
scan_model_context_from_lineage(lineage, session_meta).await?
|
||||
} else {
|
||||
read_thread::load_history_items(path.as_path()).await?
|
||||
read_thread::load_history_items(path).await?
|
||||
};
|
||||
|
||||
let after = super::history_revision::read(path).await;
|
||||
Ok(StoredModelContext {
|
||||
thread_id: params.thread_id,
|
||||
revision: before.filter(|revision| Some(revision) == after.as_ref()),
|
||||
thread_id,
|
||||
items,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -153,7 +153,7 @@ async fn fork_context_excludes_items_after_frozen_cutoff() {
|
||||
append_items(path.as_path(), [user_message("later message")]);
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(thread_id)
|
||||
.resolve_rollout_lineage(thread_id, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve source lineage");
|
||||
let session_meta = codex_rollout::read_session_meta_line(path.as_path())
|
||||
@@ -230,7 +230,7 @@ async fn fork_version_stops_before_older_segments_once_resolved() {
|
||||
);
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(child_id)
|
||||
.resolve_rollout_lineage(child_id, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve source lineage");
|
||||
// The usable compaction should stop the scan before it reaches this missing segment.
|
||||
@@ -282,7 +282,7 @@ async fn fork_version_respects_inherited_segment_cutoffs() {
|
||||
);
|
||||
let store = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(child_id)
|
||||
.resolve_rollout_lineage(child_id, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve source lineage");
|
||||
let mut source_meta = codex_rollout::read_session_meta_line(&child_path)
|
||||
|
||||
@@ -199,7 +199,7 @@ fn reject_paginated_history(thread: &StoredThread, include_history: bool) -> Thr
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn resolve_requested_rollout_path(
|
||||
pub(super) async fn resolve_requested_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
rollout_path: std::path::PathBuf,
|
||||
) -> ThreadStoreResult<std::path::PathBuf> {
|
||||
@@ -253,8 +253,14 @@ async fn attach_history_if_requested(
|
||||
message: format!("failed to load thread history for thread {thread_id}"),
|
||||
});
|
||||
};
|
||||
let before = super::history_revision::read(&path).await;
|
||||
let items = load_history_items(&path).await?;
|
||||
thread.history = Some(StoredThreadHistory { thread_id, items });
|
||||
let after = super::history_revision::read(&path).await;
|
||||
thread.history = Some(StoredThreadHistory {
|
||||
revision: before.filter(|revision| Some(revision) == after.as_ref()),
|
||||
thread_id,
|
||||
items,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -79,7 +79,9 @@ pub(super) async fn revert(
|
||||
|
||||
// Preserve old-reader compatibility when introducing the first reference to a standalone
|
||||
// source. Already-shared ancestors stay read-only; their offsets address decoded JSONL bytes.
|
||||
let mut lineage = store.resolve_rollout_lineage(thread_id).await?;
|
||||
let mut lineage = store
|
||||
.resolve_rollout_lineage(thread_id, /*initial_path*/ None)
|
||||
.await?;
|
||||
for segment in &mut lineage.segments {
|
||||
if segment.rollout_id() == current_rollout.rollout_id && source_meta.history_base.is_none()
|
||||
{
|
||||
|
||||
@@ -33,10 +33,12 @@ impl LocalThreadStore {
|
||||
pub(super) async fn resolve_rollout_lineage(
|
||||
&self,
|
||||
requested_thread_id: ThreadId,
|
||||
initial_path: Option<PathBuf>,
|
||||
) -> ThreadStoreResult<RolloutLineage> {
|
||||
self.resolve_rollout_lineage_with_representation(
|
||||
requested_thread_id,
|
||||
LineageRepresentation::Existing,
|
||||
initial_path,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -48,6 +50,7 @@ impl LocalThreadStore {
|
||||
self.resolve_rollout_lineage_with_representation(
|
||||
requested_thread_id,
|
||||
LineageRepresentation::PlainForReference,
|
||||
/*initial_path*/ None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -56,6 +59,7 @@ impl LocalThreadStore {
|
||||
&self,
|
||||
requested_thread_id: ThreadId,
|
||||
representation: LineageRepresentation,
|
||||
mut initial_path: Option<PathBuf>,
|
||||
) -> ThreadStoreResult<RolloutLineage> {
|
||||
let mut segments = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
@@ -70,14 +74,23 @@ impl LocalThreadStore {
|
||||
Some(self.live_writer_locks.lock(coordination_id).await)
|
||||
}
|
||||
};
|
||||
let (rollout_id, rollout_path) = match next_rollout_id {
|
||||
Some(rollout_id) => {
|
||||
let (rollout_id, rollout_path) = match (next_rollout_id, initial_path.take()) {
|
||||
(Some(rollout_id), _) => {
|
||||
let rollout_path = resolve_rollout_path_by_id(self, rollout_id)
|
||||
.await?
|
||||
.ok_or_else(|| malformed_lineage(rollout_id, "missing source rollout"))?;
|
||||
(rollout_id, rollout_path)
|
||||
}
|
||||
None => {
|
||||
(None, Some(path)) => {
|
||||
let rollout_id =
|
||||
thread_rollout_resolver::rollout_id_from_path_or_legacy_thread_id(
|
||||
&path,
|
||||
requested_thread_id,
|
||||
ThreadHistoryMode::Paginated,
|
||||
)?;
|
||||
(rollout_id, path)
|
||||
}
|
||||
(None, None) => {
|
||||
let resolved = thread_rollout_resolver::resolve_current_including_archived(
|
||||
self,
|
||||
requested_thread_id,
|
||||
|
||||
@@ -74,7 +74,7 @@ async fn resolves_nested_lineage_with_empty_intermediate_segments() {
|
||||
);
|
||||
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(child)
|
||||
.resolve_rollout_lineage(child, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve nested lineage");
|
||||
|
||||
@@ -127,7 +127,7 @@ async fn resolves_archived_ancestors() {
|
||||
);
|
||||
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(child)
|
||||
.resolve_rollout_lineage(child, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve archived ancestor");
|
||||
|
||||
@@ -155,7 +155,7 @@ async fn resolves_lineage_at_explicit_history_position() {
|
||||
);
|
||||
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(child)
|
||||
.resolve_rollout_lineage(child, /*initial_path*/ None)
|
||||
.await
|
||||
.expect("resolve child lineage")
|
||||
.truncate_at(end)
|
||||
@@ -246,7 +246,7 @@ async fn rejects_missing_cycles_and_out_of_bounds_offsets() {
|
||||
|
||||
async fn assert_invalid_lineage(store: &LocalThreadStore, thread_id: ThreadId, detail: &str) {
|
||||
let err = store
|
||||
.resolve_rollout_lineage(thread_id)
|
||||
.resolve_rollout_lineage(thread_id, /*initial_path*/ None)
|
||||
.await
|
||||
.expect_err("lineage should be invalid");
|
||||
assert!(err.to_string().contains(detail), "{err}");
|
||||
|
||||
@@ -110,7 +110,9 @@ pub(in crate::local) async fn list_turns(
|
||||
)
|
||||
.await?;
|
||||
validate_page_size(params.page_size)?;
|
||||
let lineage = store.resolve_rollout_lineage(params.thread_id).await?;
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(params.thread_id, /*initial_path*/ None)
|
||||
.await?;
|
||||
let pool = store.thread_history_db().await?;
|
||||
let page = page_turn_rows(
|
||||
pool,
|
||||
@@ -168,7 +170,9 @@ pub(in crate::local) async fn list_items(
|
||||
)
|
||||
.await?;
|
||||
validate_page_size(params.page_size)?;
|
||||
let lineage = store.resolve_rollout_lineage(params.thread_id).await?;
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(params.thread_id, /*initial_path*/ None)
|
||||
.await?;
|
||||
let pool = store.thread_history_db().await?;
|
||||
let page = page_item_rows(pool, &lineage, ¶ms).await?;
|
||||
|
||||
|
||||
@@ -52,7 +52,9 @@ pub(in crate::local) async fn list_timeline(
|
||||
.await?;
|
||||
validate_page_size(params.page_size)?;
|
||||
|
||||
let lineage = store.resolve_rollout_lineage(params.thread_id).await?;
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(params.thread_id, /*initial_path*/ None)
|
||||
.await?;
|
||||
let pool = store.thread_history_db().await?;
|
||||
let cursor = params
|
||||
.cursor
|
||||
|
||||
@@ -74,7 +74,9 @@ pub(in crate::local) async fn search_thread_occurrences(
|
||||
¶ms.search_term,
|
||||
)?;
|
||||
let matcher = LiteralMatcher::new(params.search_term.as_str());
|
||||
let lineage = store.resolve_rollout_lineage(params.thread_id).await?;
|
||||
let lineage = store
|
||||
.resolve_rollout_lineage(params.thread_id, /*initial_path*/ None)
|
||||
.await?;
|
||||
let cursor_segment = cursor
|
||||
.as_ref()
|
||||
.map(|cursor| {
|
||||
|
||||
@@ -195,6 +195,7 @@ async fn split_homes_support_backfill_listing_and_paginated_history() {
|
||||
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(rollout_path),
|
||||
history: None,
|
||||
@@ -1091,6 +1092,7 @@ async fn paginated_fork_reads_compressed_shared_lineage_without_materializing()
|
||||
fs::rename(&source_compressed_path, &external_path).expect("move shared source outside home");
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id: source_thread_id,
|
||||
rollout_path: Some(external_path),
|
||||
history: None,
|
||||
|
||||
@@ -1287,6 +1287,7 @@ mod tests {
|
||||
let path = write_session_file(home.path(), "2025-01-03T12-00-00", uuid)?;
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(path.clone()),
|
||||
history: None,
|
||||
@@ -1506,6 +1507,7 @@ mod tests {
|
||||
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(path.clone()),
|
||||
history: None,
|
||||
@@ -2393,6 +2395,7 @@ mod tests {
|
||||
.await;
|
||||
store
|
||||
.resume_thread(ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: Some(archived_path.clone()),
|
||||
history: None,
|
||||
|
||||
@@ -145,7 +145,8 @@ pub trait ThreadStore: Any + Send + Sync {
|
||||
/// Stored snapshots supplied by callers may predate writer acquisition. Implementations must
|
||||
/// include writes committed before acquisition in the returned context. Explicitly supplied
|
||||
/// histories without a canonical session header retain their import/override semantics.
|
||||
/// Returned histories can share the caller's allocation when no refresh is needed.
|
||||
/// A supplied revision may enable reuse of the shared snapshot after validation; missing or
|
||||
/// unrecognized revisions must not be treated as proof that stored history is unchanged.
|
||||
/// On failure, implementations must release any writer acquired by this operation.
|
||||
fn resume_thread(
|
||||
&self,
|
||||
|
||||
@@ -872,6 +872,7 @@ mod tests {
|
||||
|
||||
fn resume_params(thread_id: ThreadId, history: Vec<RolloutItem>) -> ResumeThreadParams {
|
||||
ResumeThreadParams {
|
||||
history_revision: None,
|
||||
thread_id,
|
||||
rollout_path: None,
|
||||
history: Some(Arc::new(history)),
|
||||
|
||||
@@ -128,6 +128,9 @@ pub struct ResumeThreadParams {
|
||||
/// Previously loaded replay history. A canonical session header identifies a stored snapshot
|
||||
/// that may need refreshing under writer ownership; other histories are explicit overrides.
|
||||
pub history: Option<Arc<Vec<RolloutItem>>>,
|
||||
/// Opaque revision paired with `history`, validated by the store under writer ownership.
|
||||
#[serde(skip)]
|
||||
pub history_revision: Option<String>,
|
||||
/// Whether archived threads may be reopened.
|
||||
pub include_archived: bool,
|
||||
/// Metadata for future writes appended to the resumed live thread.
|
||||
@@ -176,6 +179,9 @@ pub struct StoredThreadHistory {
|
||||
pub thread_id: ThreadId,
|
||||
/// Persisted rollout items in replay order.
|
||||
pub items: Vec<RolloutItem>,
|
||||
/// Optional revision for reusing this exact snapshot within the current process.
|
||||
#[serde(skip)]
|
||||
pub revision: Option<String>,
|
||||
}
|
||||
|
||||
/// Persisted rollout items needed to reconstruct the latest model-visible context.
|
||||
@@ -189,6 +195,9 @@ pub struct StoredModelContext {
|
||||
pub thread_id: ThreadId,
|
||||
/// Persisted rollout items in replay order.
|
||||
pub items: Vec<RolloutItem>,
|
||||
/// Optional revision for reusing this exact snapshot within the current process.
|
||||
#[serde(skip)]
|
||||
pub revision: Option<String>,
|
||||
}
|
||||
|
||||
/// Requested boundary for inheriting a paginated thread's history.
|
||||
|
||||
Reference in New Issue
Block a user