Persist Guardian retention limits in thread settings (#62827)

## What changed

At session startup, derive `assistant_record_bytes` from the Sync Elastic
per-entry token limit for retained user instructions. Use the default
section limit when the configuration omits that section.

Store the resolved byte limit in the optional `guardian_retention` field
of `ThreadSettingsSnapshot` and update the app-server schema. Fixed-mode
snapshots omit the field, and older snapshots can still be read.

GitOrigin-RevId: a8de88c5bd0e35c4a114577e70fb0c858acb13c9
This commit is contained in:
ioanbudea-OAI
2026-11-20 20:08:33 +00:00
committed by copyberry
parent 60fc55bb69
commit 7fcb825b46
11 changed files with 46 additions and 125 deletions
@@ -34,6 +34,7 @@ fn settings_item(
thread_id,
thread_settings: ThreadSettingsSnapshot {
disabled_plugin_ids: Vec::new(),
guardian_retention: None,
model: "gpt-5".to_string(),
model_provider_id: "openai".to_string(),
service_tier: None,
+1
View File
@@ -2444,6 +2444,7 @@ async fn spawn_agent_fork_from_paginated_parent_uses_model_context_prefix(
thread_id: Some(parent_thread_id),
thread_settings: ThreadSettingsSnapshot {
disabled_plugin_ids: Vec::new(),
guardian_retention: None,
model: "parent-only-model".to_string(),
model_provider_id: "parent-only-provider".to_string(),
service_tier: None,
+16
View File
@@ -1758,6 +1758,22 @@ impl Config {
}
}
/// Resolves recorder limits from the Sync Elastic retained-instruction entry budget.
pub(crate) fn guardian_retention_policy(
&self,
) -> Option<codex_protocol::protocol::GuardianRetentionPolicy> {
let entry_tokens = self
.guardian_sync_elastic_budget
.as_ref()?
.section_limits(codex_guardian_context::ElasticSection::RetainedUserInstructions)
.max_section_entry_tokens();
Some(codex_protocol::protocol::GuardianRetentionPolicy {
assistant_record_bytes: Some(codex_utils_output_truncation::approx_bytes_for_tokens(
entry_tokens,
)),
})
}
pub fn sqlite_config(&self) -> &codex_state::SqliteConfig {
&self.sqlite
}
+1
View File
@@ -1088,6 +1088,7 @@ impl Session {
codex_home: config.codex_home.clone(),
thread_name: None,
disabled_plugin_ids,
guardian_retention: config.guardian_retention_policy(),
original_config_do_not_use: Arc::clone(&config),
metrics_service_name,
app_server_client_name: None,
+4
View File
@@ -42,6 +42,7 @@ use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::models::ProfileWorkspaceRoot;
use codex_protocol::openai_models::CatalogModel;
use codex_protocol::protocol::EnvironmentConfig;
use codex_protocol::protocol::GuardianRetentionPolicy;
use codex_protocol::protocol::HookCompletedEvent;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::ThreadHistoryMode;
@@ -165,6 +166,8 @@ pub(crate) struct SessionConfiguration {
pub(super) thread_name: Option<String>,
/// Thread-owned plugin selection inherited by future turns.
pub(super) disabled_plugin_ids: Vec<String>,
/// Recorder policy resolved at startup and shared with persisted settings.
pub(super) guardian_retention: Option<GuardianRetentionPolicy>,
// TODO(pakrym): Remove config from here
pub(super) original_config_do_not_use: Arc<Config>,
@@ -347,6 +350,7 @@ impl SessionConfiguration {
personality: self.step_settings.personality,
collaboration_mode: self.step_settings.collaboration_mode.clone(),
disabled_plugin_ids: self.disabled_plugin_ids.clone(),
guardian_retention: self.guardian_retention,
}
}
+7 -124
View File
@@ -4343,68 +4343,7 @@ async fn record_initial_history_forked_hydrates_previous_turn_settings() {
#[tokio::test]
async fn set_rate_limits_retains_previous_credits() {
let codex_home = tempfile::tempdir().expect("create temp dir");
let config = build_test_config(codex_home.path()).await;
let config = Arc::new(config);
let model = get_model_offline_for_tests(config.model.as_deref());
let model_info =
construct_model_info_offline_for_tests(model.as_str(), &config.to_models_manager_config());
let reasoning_effort = config.model_reasoning_effort.clone();
let collaboration_mode = CollaborationMode {
mode: ModeKind::Default,
settings: Settings {
model,
reasoning_effort,
developer_instructions: None,
},
};
let session_configuration = SessionConfiguration {
turn_extension_init: Default::default(),
provider: create_model_provider(config.model_provider.clone(), /*auth_manager*/ None),
environments: Vec::new(),
step_settings: Arc::new(StepSettings {
request_country: RequestCountry::default(),
collaboration_mode,
reasoning_summary: config.model_reasoning_summary,
service_tier: None,
personality: config.personality,
approval_policy: config.permissions.approval_policy.clone(),
approvals_reviewer: config.approvals_reviewer,
}),
model_info_overrides: config.to_models_manager_config().into(),
developer_instructions: config.developer_instructions.clone(),
base_instructions: config
.base_instructions
.clone()
.unwrap_or_else(|| render_model_instructions(&model_info)),
permission_profile_state: config.permissions.permission_profile_state().clone(),
allow_login_shell: config.permissions.allow_login_shell,
shell_environment_policy: config.permissions.shell_environment_policy.clone(),
windows_sandbox_level: WindowsSandboxLevel::from_config(&config),
windows_sandbox_type: config.permissions.windows_sandbox_type,
use_legacy_landlock: config.features.use_legacy_landlock(),
legacy_fallback_cwd: config.cwd.clone(),
runtime_workspace_roots: config.workspace_roots.clone(),
codex_home: config.codex_home.clone(),
thread_name: None,
disabled_plugin_ids: Vec::new(),
original_config_do_not_use: Arc::clone(&config),
metrics_service_name: None,
app_server_client_name: None,
app_server_client_version: None,
trusted_guardian_reviewer: false,
session_source: SessionSource::Exec,
root_capabilities_restricted: false,
history_mode: Default::default(),
forked_from_thread_id: None,
parent_thread_id: None,
thread_source: None,
originator: "test_originator".to_string(),
dynamic_tools: Arc::default(),
user_shell_override: None,
};
let mut state = SessionState::new(session_configuration);
let mut state = SessionState::new(make_session_configuration_for_tests().await);
let initial = RateLimitSnapshot {
limit_id: None,
limit_name: None,
@@ -4468,68 +4407,7 @@ async fn set_rate_limits_retains_previous_credits() {
#[tokio::test]
async fn set_rate_limits_updates_plan_type_when_present() {
let codex_home = tempfile::tempdir().expect("create temp dir");
let config = build_test_config(codex_home.path()).await;
let config = Arc::new(config);
let model = get_model_offline_for_tests(config.model.as_deref());
let model_info =
construct_model_info_offline_for_tests(model.as_str(), &config.to_models_manager_config());
let reasoning_effort = config.model_reasoning_effort.clone();
let collaboration_mode = CollaborationMode {
mode: ModeKind::Default,
settings: Settings {
model,
reasoning_effort,
developer_instructions: None,
},
};
let session_configuration = SessionConfiguration {
turn_extension_init: Default::default(),
provider: create_model_provider(config.model_provider.clone(), /*auth_manager*/ None),
environments: Vec::new(),
step_settings: Arc::new(StepSettings {
request_country: RequestCountry::default(),
collaboration_mode,
reasoning_summary: config.model_reasoning_summary,
service_tier: None,
personality: config.personality,
approval_policy: config.permissions.approval_policy.clone(),
approvals_reviewer: config.approvals_reviewer,
}),
model_info_overrides: config.to_models_manager_config().into(),
developer_instructions: config.developer_instructions.clone(),
base_instructions: config
.base_instructions
.clone()
.unwrap_or_else(|| render_model_instructions(&model_info)),
permission_profile_state: config.permissions.permission_profile_state().clone(),
allow_login_shell: config.permissions.allow_login_shell,
shell_environment_policy: config.permissions.shell_environment_policy.clone(),
windows_sandbox_level: WindowsSandboxLevel::from_config(&config),
windows_sandbox_type: config.permissions.windows_sandbox_type,
use_legacy_landlock: config.features.use_legacy_landlock(),
legacy_fallback_cwd: config.cwd.clone(),
runtime_workspace_roots: config.workspace_roots.clone(),
codex_home: config.codex_home.clone(),
thread_name: None,
disabled_plugin_ids: Vec::new(),
original_config_do_not_use: Arc::clone(&config),
metrics_service_name: None,
app_server_client_name: None,
app_server_client_version: None,
trusted_guardian_reviewer: false,
session_source: SessionSource::Exec,
root_capabilities_restricted: false,
history_mode: Default::default(),
forked_from_thread_id: None,
parent_thread_id: None,
thread_source: None,
originator: "test_originator".to_string(),
dynamic_tools: Arc::default(),
user_shell_override: None,
};
let mut state = SessionState::new(session_configuration);
let mut state = SessionState::new(make_session_configuration_for_tests().await);
let initial = RateLimitSnapshot {
limit_id: None,
limit_name: None,
@@ -5141,6 +5019,7 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati
codex_home: config.codex_home.clone(),
thread_name: None,
disabled_plugin_ids: Vec::new(),
guardian_retention: config.guardian_retention_policy(),
original_config_do_not_use: Arc::clone(&config),
metrics_service_name: None,
app_server_client_name: None,
@@ -6727,6 +6606,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
codex_home: config.codex_home.clone(),
thread_name: None,
disabled_plugin_ids: Vec::new(),
guardian_retention: config.guardian_retention_policy(),
original_config_do_not_use: Arc::clone(&config),
metrics_service_name: None,
app_server_client_name: None,
@@ -7076,6 +6956,7 @@ async fn make_session_with_config_and_rx(
codex_home: config.codex_home.clone(),
thread_name: None,
disabled_plugin_ids: Vec::new(),
guardian_retention: config.guardian_retention_policy(),
original_config_do_not_use: Arc::clone(&config),
metrics_service_name: None,
app_server_client_name: None,
@@ -7216,6 +7097,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx(
codex_home: config.codex_home.clone(),
thread_name: None,
disabled_plugin_ids: Vec::new(),
guardian_retention: config.guardian_retention_policy(),
original_config_do_not_use: Arc::clone(&config),
metrics_service_name: None,
app_server_client_name: None,
@@ -9089,6 +8971,7 @@ where
codex_home: config.codex_home.clone(),
thread_name: None,
disabled_plugin_ids: Vec::new(),
guardian_retention: config.guardian_retention_policy(),
original_config_do_not_use: Arc::clone(&config),
metrics_service_name: None,
app_server_client_name: None,
+2 -1
View File
@@ -199,7 +199,8 @@ impl ElasticBudgetConfig {
Ok(())
}
pub(crate) fn section_limits(&self, section: ElasticSection) -> ElasticSectionLimits {
/// Returns the configured limits or the default for an omitted section.
pub fn section_limits(&self, section: ElasticSection) -> ElasticSectionLimits {
self.sections.get(&section).copied().unwrap_or_else(|| {
let entries = crate::ContextProfile::synchronous().transcript.entry_limits;
let tokens = match section {
+12
View File
@@ -2598,6 +2598,18 @@ pub struct ThreadSettingsSnapshot {
/// Thread-owned plugin selection, retained even when a plugin is unavailable.
#[serde(default)]
pub disabled_plugin_ids: Vec<String>,
/// Effective Guardian recorder policy. Absent for Fixed and old snapshots.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub guardian_retention: Option<GuardianRetentionPolicy>,
}
/// Resolved limits for Guardian's retained evidence, in storage bytes.
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)]
pub struct GuardianRetentionPolicy {
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub assistant_record_bytes: Option<usize>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq, Eq, JsonSchema, TS)]
+1
View File
@@ -735,6 +735,7 @@ mod tests {
thread_id: None,
thread_settings: ThreadSettingsSnapshot {
disabled_plugin_ids: Vec::new(),
guardian_retention: None,
model: "gpt-5.2-codex".to_string(),
model_provider_id: "updated-provider".to_string(),
service_tier: None,
@@ -750,6 +750,7 @@ mod tests {
thread_id: None,
thread_settings: ThreadSettingsSnapshot {
disabled_plugin_ids: Vec::new(),
guardian_retention: None,
model: "gpt-5.2-codex".to_string(),
model_provider_id: "updated-provider".to_string(),
service_tier: None,