Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Preserve model and access program pairs during compaction (#48224)

jamy-OAI5f3180c79374
diff --git a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst
index da8cafb91d..fa3fe4ce3a 100644
Binary files a/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst and b/codex-rs/app-server-protocol/schema/precomputed/app-server-exports-stable.json.zst differ
diff --git a/codex-rs/core/src/agent/control_tests.rs b/codex-rs/core/src/agent/control_tests.rs
index ceaeaa3213..27deef7dc3 100644
--- a/codex-rs/core/src/agent/control_tests.rs
+++ b/codex-rs/core/src/agent/control_tests.rs
@@ -1925,6 +1925,7 @@ async fn spawn_agent_fork_sanitizes_inherited_compaction_metadata() {
previous_turn_settings: Some(codex_history::PreviousTurnSettings {
model: "parent-model".into(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: None,
}),
};
@@ -3011,6 +3012,7 @@ async fn spawn_agent_full_fork_legacy_compaction_rebuilds_child_instructions_onc
previous_turn_settings: Some(codex_history::PreviousTurnSettings {
model: "parent-model".into(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: None,
}),
}),
diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs
index af14e64eb0..a937b39db0 100644
--- a/codex-rs/core/src/compact.rs
+++ b/codex-rs/core/src/compact.rs
@@ -277,6 +277,7 @@ async fn run_compact_task_inner_impl(
let prompt = Prompt {
input: turn_input,
base_instructions: sess.get_prompt_base_instructions().await,
+ cyber_access_program: turn_context.cyber_access_program,
..Default::default()
};
let responses_metadata = sess
diff --git a/codex-rs/core/src/session/rollout_reconstruction.rs b/codex-rs/core/src/session/rollout_reconstruction.rs
index bc195d7d34..29b1f1f483 100644
--- a/codex-rs/core/src/session/rollout_reconstruction.rs
+++ b/codex-rs/core/src/session/rollout_reconstruction.rs
@@ -303,6 +303,7 @@ impl Session {
) {
active_segment.previous_turn_settings = Some(PreviousTurnSettings {
model: ctx.model.clone(),
+ cyber_access_program: ctx.cyber_access_program,
comp_hash: ctx.comp_hash.clone(),
realtime_active: ctx.realtime_active,
});
diff --git a/codex-rs/core/src/session/rollout_reconstruction_tests.rs b/codex-rs/core/src/session/rollout_reconstruction_tests.rs
index 120912b804..3f9f81fc6b 100644
--- a/codex-rs/core/src/session/rollout_reconstruction_tests.rs
+++ b/codex-rs/core/src/session/rollout_reconstruction_tests.rs
@@ -20,6 +20,7 @@ use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::ThreadRolledBackEvent;
use codex_protocol::protocol::WorldStateItem;
use codex_protocol::security_risk::SecurityRiskScore;
+use codex_protocol::turn_input::CyberAccessProgram;
use codex_rollout::ModelContextScan;
use codex_rollout::ModelContextScanProgress;
use core_test_support::responses::strip_metadata_from_items;
@@ -404,6 +405,7 @@ async fn record_initial_history_restores_world_state_baseline(input: BaselineTur
Some(PreviousTurnSettings {
model: context_item.model.clone(),
comp_hash: context_item.comp_hash.clone(),
+ cyber_access_program: None,
realtime_active: context_item.realtime_active,
}),
serde_json::to_value(Some(context_item)).unwrap(),
@@ -558,6 +560,7 @@ async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lif
Some(PreviousTurnSettings {
model: previous_model.to_string(),
comp_hash: Some("comp-hash-a".to_string()),
+ cyber_access_program: None,
realtime_active: Some(turn_context.realtime_active),
})
);
@@ -566,7 +569,8 @@ async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lif
#[tokio::test]
async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_completed_turns() {
let (session, turn_context) = make_session_and_context().await;
- let first_context_item = turn_context.to_turn_context_item();
+ let mut first_context_item = turn_context.to_turn_context_item();
+ first_context_item.cyber_access_program = Some(CyberAccessProgram::DaybreakBlue);
let first_turn_id = first_context_item
.turn_id
.clone()
@@ -574,6 +578,7 @@ async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_com
let mut rolled_back_context_item = first_context_item.clone();
rolled_back_context_item.turn_id = Some("rolled-back-turn".to_string());
rolled_back_context_item.model = "rolled-back-model".to_string();
+ rolled_back_context_item.cyber_access_program = Some(CyberAccessProgram::DaybreakRed);
let rolled_back_turn_id = rolled_back_context_item
.turn_id
.clone()
@@ -672,11 +677,13 @@ async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_com
annotated(vec![turn_one_user, turn_one_assistant])
);
assert_eq!(
- reconstructed.previous_turn_settings,
- Some(PreviousTurnSettings {
- model: turn_context.model_info().slug.clone(),
- comp_hash: None,
- realtime_active: Some(turn_context.realtime_active),
+ serde_json::to_value(reconstructed.previous_turn_settings)
+ .expect("serialize previous settings"),
+ json!({
+ "model": turn_context.model_info().slug,
+ "comp_hash": null,
+ "realtime_active": turn_context.realtime_active,
+ "cyber_access_program": "daybreak_blue",
})
);
assert_eq!(
@@ -695,7 +702,8 @@ async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_com
#[tokio::test]
async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_incomplete_turn() {
let (session, turn_context) = make_session_and_context().await;
- let first_context_item = turn_context.to_turn_context_item();
+ let mut first_context_item = turn_context.to_turn_context_item();
+ first_context_item.cyber_access_program = Some(CyberAccessProgram::DaybreakBlue);
let first_turn_id = first_context_item
.turn_id
.clone()
@@ -775,11 +783,13 @@ async fn reconstruct_history_rollback_keeps_history_and_metadata_in_sync_for_inc
annotated(vec![turn_one_user, turn_one_assistant])
);
assert_eq!(
- reconstructed.previous_turn_settings,
- Some(PreviousTurnSettings {
- model: turn_context.model_info().slug.clone(),
- comp_hash: None,
- realtime_active: Some(turn_context.realtime_active),
+ serde_json::to_value(reconstructed.previous_turn_settings)
+ .expect("serialize previous settings"),
+ json!({
+ "model": turn_context.model_info().slug,
+ "comp_hash": null,
+ "realtime_active": turn_context.realtime_active,
+ "cyber_access_program": "daybreak_blue",
})
);
assert_eq!(
@@ -919,6 +929,7 @@ async fn reconstruct_history_rollback_skips_non_user_turns_for_history_and_metad
Some(PreviousTurnSettings {
model: turn_context.model_info().slug.clone(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(turn_context.realtime_active),
})
);
@@ -1026,6 +1037,7 @@ async fn reconstruct_history_rollback_counts_inter_agent_assistant_turns() {
Some(PreviousTurnSettings {
model: turn_context.model_info().slug.clone(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(turn_context.realtime_active),
})
);
@@ -1270,6 +1282,7 @@ async fn record_initial_history_resumed_rollback_drops_incomplete_user_turn_comp
Some(PreviousTurnSettings {
model: turn_context.model_info().slug.clone(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(turn_context.realtime_active),
})
);
@@ -1557,6 +1570,7 @@ async fn bounded_replay_matches_full_replay_after_empty_turn_compactions(
previous_turn_settings: Some(PreviousTurnSettings {
model: format!("metadata-model-{window_number}"),
comp_hash: Some(format!("metadata-hash-{window_number}")),
+ cyber_access_program: None,
realtime_active: Some(false),
}),
}),
@@ -1672,6 +1686,7 @@ async fn completed_turn_suffix_after_compaction_overrides_resume_metadata() {
let expected_settings = PreviousTurnSettings {
model: newer_context.model.clone(),
comp_hash: newer_context.comp_hash.clone(),
+ cyber_access_program: None,
realtime_active: newer_context.realtime_active,
};
let mut rollout_items = vec![
@@ -1978,6 +1993,7 @@ async fn record_initial_history_resumed_turn_context_after_compaction_reestablis
Some(PreviousTurnSettings {
model: previous_model.to_string(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(turn_context.realtime_active),
})
);
@@ -2144,6 +2160,7 @@ async fn record_initial_history_resumed_aborted_turn_without_id_clears_active_tu
Some(PreviousTurnSettings {
model: previous_model.to_string(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(turn_context.realtime_active),
})
);
@@ -2279,6 +2296,7 @@ async fn record_initial_history_resumed_unmatched_abort_preserves_active_turn_fo
Some(PreviousTurnSettings {
model: current_model.to_string(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(turn_context.realtime_active),
})
);
@@ -2410,6 +2428,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_compaction_clea
Some(PreviousTurnSettings {
model: previous_model.to_string(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(turn_context.realtime_active),
})
);
@@ -2462,6 +2481,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_preserves_turn_
Some(PreviousTurnSettings {
model: turn_context.model_info().slug.clone(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(turn_context.realtime_active),
})
);
@@ -2606,6 +2626,7 @@ async fn record_initial_history_resumed_replaced_incomplete_compacted_turn_clear
Some(PreviousTurnSettings {
model: previous_model.to_string(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(turn_context.realtime_active),
})
);
diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs
index ad0167f65b..92332bd9a9 100644
--- a/codex-rs/core/src/session/tests.rs
+++ b/codex-rs/core/src/session/tests.rs
@@ -4044,6 +4044,7 @@ async fn record_initial_history_forked_hydrates_previous_turn_settings() {
Some(PreviousTurnSettings {
model: previous_model.to_string(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(turn_context.realtime_active),
})
);
@@ -5791,6 +5792,7 @@ async fn compaction_persists_resume_metadata_and_companion_records() {
let previous_turn_settings = PreviousTurnSettings {
model: "previous-model".to_string(),
comp_hash: Some("comp-hash".to_string()),
+ cyber_access_program: None,
realtime_active: Some(true),
};
session
@@ -10515,6 +10517,7 @@ async fn build_initial_context_restates_realtime_start_when_reference_context_is
let previous_turn_settings = PreviousTurnSettings {
model: turn_context.model_info().slug.clone(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(true),
};
@@ -10878,6 +10881,7 @@ async fn build_initial_context_uses_retained_step_after_model_change() {
.set_previous_turn_settings(Some(PreviousTurnSettings {
model: "base-model".to_string(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: None,
}))
.await;
@@ -10959,6 +10963,7 @@ async fn build_initial_context_prepends_model_switch_message() {
let previous_turn_settings = PreviousTurnSettings {
model: "previous-regular-model".to_string(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: None,
};
@@ -11013,6 +11018,7 @@ async fn record_context_updates_and_set_reference_context_item_persists_full_rei
.set_previous_turn_settings(Some(PreviousTurnSettings {
model: previous_context.model_info().slug.clone(),
comp_hash: None,
+ cyber_access_program: None,
realtime_active: Some(previous_context.realtime_active),
}))
.await;
@@ -11582,6 +11588,7 @@ async fn interrupting_compaction_fallback_retains_last_known_step_context() {
.set_previous_turn_settings(Some(PreviousTurnSettings {
model: "gpt-5.4".to_string(),
comp_hash: Some("old".to_string()),
+ cyber_access_program: None,
realtime_active: Some(turn.realtime_active),
}))
.await;
diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs
index 1a0807b1c7..ce389bd303 100644
--- a/codex-rs/core/src/session/turn.rs
+++ b/codex-rs/core/src/session/turn.rs
@@ -388,6 +388,7 @@ pub(crate) async fn run_turn(
.await;
sess.set_previous_turn_settings(Some(PreviousTurnSettings {
model: turn_context.model_info().slug.clone(),
+ cyber_access_program: turn_context.cyber_access_program,
comp_hash: turn_context.model_info().comp_hash.clone(),
realtime_active: Some(turn_context.realtime_active),
}))
@@ -1359,11 +1360,15 @@ async fn maybe_run_previous_model_inline_compact(
if !should_compact_for_comp_hash_change && previous_model == turn_context.model_info().slug {
return Ok(());
}
- let previous_model_turn_context = Arc::new(
- turn_context
- .with_model(previous_model.clone(), &sess.services.models_manager)
- .await,
- );
+ let mut previous_model_turn_context = turn_context
+ .with_model(previous_model.clone(), &sess.services.models_manager)
+ .await;
+ // `with_model` preserves the current turn's access program. Restore the previous
+ // turn's program so compaction uses the same model/cyber_access_program pair as that turn.
+ // Combining the previous model with the current turn's program can produce a pair
+ // that the server rejects.
+ previous_model_turn_context.cyber_access_program = previous_turn_settings.cyber_access_program;
+ let previous_model_turn_context = Arc::new(previous_model_turn_context);
if should_compact_for_comp_hash_change {
let step_context = sess
diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs
index 0a4494ad62..7455ff786f 100644
--- a/codex-rs/core/tests/suite/compact.rs
+++ b/codex-rs/core/tests/suite/compact.rs
@@ -5684,3 +5684,6 @@ async fn remote_v2_compaction_refreshes_instructions_and_preserves_them_on_cold_
Ok(())
}
+
+#[path = "compact_program_tests.rs"]
+mod program_tests;
diff --git a/codex-rs/core/tests/suite/compact_program_tests.rs b/codex-rs/core/tests/suite/compact_program_tests.rs
new file mode 100644
index 0000000000..d65c36660d
--- /dev/null
+++ b/codex-rs/core/tests/suite/compact_program_tests.rs
@@ -0,0 +1,310 @@
+//! Model-switch compaction must retain the historical model/program pair across replay.
+
+use super::*;
+use codex_core::CodexThread;
+use codex_core::ForkSnapshot;
+use codex_core::StartThreadOptions;
+use codex_core::TurnStartOptions;
+use codex_protocol::turn_input::CyberAccessProgram;
+use pretty_assertions::assert_eq;
+use test_case::test_case;
+
+#[derive(Clone, Copy, Debug)]
+enum History {
+ Live,
+ Resume,
+ Fork,
+ Rollback,
+ IncompleteRollback,
+ Checkpoint,
+ ApiKeyResume,
+}
+
+#[derive(Clone, Copy, Debug)]
+enum Compaction {
+ RemoteHash,
+ RemoteDownshift,
+ LocalHash,
+ LocalDownshift,
+ Fallback,
+}
+
+async fn submit_pair(
+ thread: &CodexThread,
+ model: &str,
+ program: Option<CyberAccessProgram>,
+) -> Result<()> {
+ thread
+ .start_or_steer_turn(
+ TurnInputRequest::user_input(vec![UserInput::Text {
+ text: format!("turn with {model}"),
+ text_elements: Vec::new(),
+ }])
+ .with_thread_settings(ThreadSettingsOverrides {
+ model: Some(model.to_owned()),
+ ..Default::default()
+ })
+ .on_start(TurnStartOptions {
+ cyber_access_program: program,
+ ..Default::default()
+ }),
+ )
+ .await?;
+ let event = wait_for_event(thread, |event| {
+ matches!(event, EventMsg::TurnComplete(_) | EventMsg::Error(_))
+ })
+ .await;
+ if let EventMsg::Error(error) = event {
+ anyhow::bail!("turn failed: {error:?}");
+ }
+ Ok(())
+}
+
+#[test_case(Compaction::RemoteHash, History::Live, Some(CyberAccessProgram::DaybreakBlue); "remote hash")]
+#[test_case(Compaction::RemoteDownshift, History::Live, Some(CyberAccessProgram::DaybreakBlue); "remote downshift")]
+#[test_case(Compaction::LocalHash, History::Live, Some(CyberAccessProgram::DaybreakBlue); "local hash")]
+#[test_case(Compaction::LocalDownshift, History::Live, Some(CyberAccessProgram::DaybreakBlue); "local downshift")]
+#[test_case(Compaction::RemoteHash, History::Resume, Some(CyberAccessProgram::DaybreakBlue); "resume")]
+#[test_case(Compaction::RemoteHash, History::Fork, Some(CyberAccessProgram::DaybreakBlue); "fork")]
+#[test_case(Compaction::RemoteHash, History::Rollback, Some(CyberAccessProgram::DaybreakBlue); "rollback")]
+#[test_case(Compaction::RemoteHash, History::IncompleteRollback, Some(CyberAccessProgram::DaybreakBlue); "incomplete rollback")]
+#[test_case(Compaction::RemoteHash, History::Checkpoint, Some(CyberAccessProgram::DaybreakBlue); "checkpoint")]
+#[test_case(Compaction::RemoteHash, History::Resume, None; "missing program")]
+#[test_case(Compaction::RemoteHash, History::Resume, Some(CyberAccessProgram::Standard); "standard")]
+#[test_case(Compaction::LocalHash, History::Live, None; "local missing program")]
+#[test_case(Compaction::Fallback, History::Live, Some(CyberAccessProgram::DaybreakBlue); "fallback")]
+#[test_case(Compaction::LocalHash, History::ApiKeyResume, Some(CyberAccessProgram::DaybreakBlue); "api key cannot inherit authorization")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn model_switch_program_pair(
+ compaction: Compaction,
+ history: History,
+ previous_program: Option<CyberAccessProgram>,
+) -> Result<()> {
+ skip_if_no_network!(Ok(()));
+ let server = start_mock_server().await;
+ let previous_model = "gpt-5.5";
+ let next_model = "gpt-5.6-cyber";
+ let discarded_model = "discarded-model";
+ let downshift = matches!(
+ compaction,
+ Compaction::RemoteDownshift | Compaction::LocalDownshift
+ );
+ let local = matches!(
+ compaction,
+ Compaction::LocalHash | Compaction::LocalDownshift
+ );
+ let mut old = model_info_with_context_window(previous_model, /*context_window*/ 273_000);
+ let mut new = model_info_with_context_window(next_model, /*context_window*/ 125_000);
+ if !downshift {
+ old.comp_hash = Some("blue-hash".to_owned());
+ new.comp_hash = Some("red-hash".to_owned());
+ }
+ let mut discarded = old.clone();
+ discarded.slug = discarded_model.to_owned();
+ let models = ModelsResponse {
+ models: vec![old, new, discarded],
+ };
+ let provider = if local {
+ local_compaction_provider(&server)
+ } else {
+ openai_model_provider(&server)
+ };
+ let mut builder = test_codex()
+ .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
+ .with_model(previous_model)
+ .with_config(move |config| {
+ config.model_catalog = Some(models.clone());
+ config.model_provider = provider;
+ set_test_compact_prompt(config);
+ });
+ let initial = builder.build_with_auto_env(&server).await?;
+ let first = mount_sse_once(
+ &server,
+ sse(vec![
+ ev_assistant_message("first-message", "surviving history"),
+ ev_completed_with_tokens("first", if downshift { 120_000 } else { 100 }),
+ ]),
+ )
+ .await;
+ submit_pair(&initial.codex, previous_model, previous_program).await?;
+ let expected_program = previous_program
+ .map(|program| json!({"cyber": program}))
+ .unwrap_or(Value::Null);
+ assert_eq!(
+ first.single_request().body_json()["access_programs"],
+ expected_program
+ );
+
+ if matches!(
+ history,
+ History::Fork | History::Rollback | History::IncompleteRollback
+ ) {
+ let discarded = mount_sse_once(
+ &server,
+ sse(vec![
+ ev_assistant_message("discarded-message", "discarded history"),
+ ev_completed("discarded"),
+ ]),
+ )
+ .await;
+ submit_pair(
+ &initial.codex,
+ discarded_model,
+ Some(CyberAccessProgram::Standard),
+ )
+ .await?;
+ assert_eq!(
+ discarded.single_request().body_json()["model"],
+ discarded_model
+ );
+ }
+ if matches!(history, History::Checkpoint) {
+ let compact = mount_sse_once(
+ &server,
+ sse(vec![
+ json!({"type": "response.output_item.done", "item": {
+ "type": "compaction", "encrypted_content": "CHECKPOINT"
+ }}),
+ ev_completed("checkpoint"),
+ ]),
+ )
+ .await;
+ initial.codex.submit(Op::Compact).await?;
+ wait_for_event(&initial.codex, |event| {
+ matches!(event, EventMsg::TurnComplete(_))
+ })
+ .await;
+ assert_eq!(
+ compact
+ .single_request()
+ .inputs_of_type("compaction_trigger")
+ .len(),
+ 1
+ );
+ }
+
+ let resumed;
+ let thread = match history {
+ History::Live => Arc::clone(&initial.codex),
+ History::Fork => {
+ initial.codex.flush_rollout().await?;
+ let mut config = initial.config.clone();
+ config.model = Some(next_model.to_owned());
+ initial
+ .thread_manager
+ .fork_legacy_thread(
+ ForkSnapshot::TruncateBeforeNthUserMessage(1),
+ StartThreadOptions::new(config),
+ initial.codex.rollout_path().expect("rollout"),
+ )
+ .await?
+ .thread
+ }
+ History::Resume
+ | History::Rollback
+ | History::IncompleteRollback
+ | History::Checkpoint
+ | History::ApiKeyResume => {
+ initial.codex.shutdown_and_wait().await?;
+ let rollout_path = initial.codex.rollout_path().expect("rollout");
+ if matches!(history, History::Rollback | History::IncompleteRollback) {
+ // Live rollback is unsupported; replay its persisted marker, as older rollouts do.
+ let text = fs::read_to_string(&rollout_path)?;
+ let mut lines = text
+ .lines()
+ .map(serde_json::from_str::<Value>)
+ .collect::<std::result::Result<Vec<_>, _>>()?;
+ if matches!(history, History::IncompleteRollback) {
+ let completion = lines
+ .iter()
+ .rposition(|line| {
+ line["type"] == "event_msg"
+ && line["payload"]["type"] == "task_complete"
+ })
+ .expect("last completion");
+ lines.truncate(completion);
+ }
+ lines.push(
+ json!({"timestamp": "2026-01-01T00:00:00Z", "type": "event_msg", "payload": {
+ "type": "thread_rolled_back", "num_turns": 1
+ }}),
+ );
+ fs::write(
+ &rollout_path,
+ lines
+ .iter()
+ .map(Value::to_string)
+ .collect::<Vec<_>>()
+ .join("\n")
+ + "\n",
+ )?;
+ }
+ if matches!(history, History::ApiKeyResume) {
+ builder = builder.with_auth(CodexAuth::from_api_key("test-key"));
+ }
+ let resume_config = initial.config.clone();
+ builder = builder.with_config(move |config| {
+ config.model_catalog = resume_config.model_catalog;
+ config.model_provider = resume_config.model_provider;
+ set_test_compact_prompt(config);
+ });
+ resumed = builder
+ .resume(&server, Arc::clone(&initial.home), rollout_path)
+ .await?;
+ Arc::clone(&resumed.codex)
+ }
+ };
+ let summary = if local {
+ ev_assistant_message("summary", "summary of surviving history")
+ } else {
+ json!({"type": "response.output_item.done", "item": {
+ "type": "compaction", "encrypted_content": "SWITCH_SUMMARY"
+ }})
+ };
+ let mut replies = Vec::new();
+ if matches!(compaction, Compaction::Fallback) {
+ replies.push(invalid_request_response("previous model rejected"));
+ }
+ replies.push(sse_response(sse(vec![
+ summary,
+ ev_completed_with_tokens("compact", /*total_tokens*/ 10),
+ ])));
+ replies.push(sse_response(sse(vec![
+ ev_assistant_message("next-message", "next answer"),
+ ev_completed("next"),
+ ])));
+ let requests = mount_response_sequence(&server, replies).await;
+ submit_pair(&thread, next_model, Some(CyberAccessProgram::DaybreakRed)).await?;
+ thread.shutdown_and_wait().await?;
+ let requests = requests.requests();
+ let authorized = !matches!(history, History::ApiKeyResume);
+ let old_program = if authorized {
+ expected_program
+ } else {
+ Value::Null
+ };
+ let new_program = if authorized {
+ json!({"cyber": "daybreak_red"})
+ } else {
+ Value::Null
+ };
+ let actual = requests
+ .iter()
+ .map(|request| {
+ let body = request.body_json();
+ json!([body["model"], body["access_programs"]])
+ })
+ .collect::<Vec<_>>();
+ // Check fallback and subsequent sampling even when the historical request is wrong.
+ let mut following = Vec::new();
+ if matches!(compaction, Compaction::Fallback) {
+ following.push(json!([next_model, new_program]));
+ }
+ following.push(json!([next_model, new_program]));
+ assert_eq!(&actual[1..], following.as_slice());
+ assert_eq!(actual[0], json!([previous_model, old_program]));
+ if !local {
+ assert_eq!(requests[0].inputs_of_type("compaction_trigger").len(), 1);
+ }
+ Ok(())
+}
diff --git a/codex-rs/history/src/compaction_resume_metadata.rs b/codex-rs/history/src/compaction_resume_metadata.rs
index 1a70f8108d..4886fcd52b 100644
--- a/codex-rs/history/src/compaction_resume_metadata.rs
+++ b/codex-rs/history/src/compaction_resume_metadata.rs
@@ -2,6 +2,7 @@
use crate::RolloutItem;
use codex_protocol::protocol::MultiAgentVersion;
+use codex_protocol::turn_input::CyberAccessProgram;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
@@ -23,6 +24,9 @@ pub struct CompactionResumeMetadata {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
pub struct PreviousTurnSettings {
pub model: String,
+ /// Historical program for this model; absence must not inherit the next turn's selection.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cyber_access_program: Option<CyberAccessProgram>,
pub comp_hash: Option<String>,
pub realtime_active: Option<bool>,
}