diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index d9adbd1c54..336bec38b5 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -2572,9 +2572,43 @@ }, "type": "object" }, + "GuardianV3HousekeeperBatchLimit": { + "oneOf": [ + { + "additionalProperties": false, + "description": "Estimated tokens in the serialized channel catalog and new evidence.", + "properties": { + "limit": { + "format": "uint32", + "minimum": 1.0, + "type": "integer" + }, + "mode": { + "enum": [ + "tokens" + ], + "type": "string" + } + }, + "required": [ + "limit", + "mode" + ], + "type": "object" + } + ] + }, "GuardianV3HousekeeperConfigToml": { "additionalProperties": false, "properties": { + "batch_limit": { + "allOf": [ + { + "$ref": "#/definitions/GuardianV3HousekeeperBatchLimit" + } + ], + "description": "Size limit for one routing batch. Defaults to 100,000 estimated tokens." + }, "batch_timeout_ms": { "description": "Time budget for routing one batch, in milliseconds. Defaults to 90,000.", "format": "uint32", diff --git a/codex-rs/ext/guardian-v3/src/host_tests.rs b/codex-rs/ext/guardian-v3/src/host_tests.rs index 5b8a6784f3..7b83f8f425 100644 --- a/codex-rs/ext/guardian-v3/src/host_tests.rs +++ b/codex-rs/ext/guardian-v3/src/host_tests.rs @@ -587,15 +587,10 @@ async fn shadow_intake_enrolls_only_new_opted_in_roots( }) .with_history_mode(ThreadHistoryMode::Paginated); if overflow.is_some() { - builder = builder - .with_config(|config| { - Arc::make_mut(config.guardian_v3.get_or_insert_with(Arc::default)) - .shadow_board_limit_mib = std::num::NonZeroU32::new(1); - }) - .with_model_info_override("gpt-5.6-luna", |model| { - model.truncation_policy = - codex_protocol::openai_models::TruncationPolicyConfig::bytes(64 * 1024); - }); + builder = builder.with_config(|config| { + Arc::make_mut(config.guardian_v3.get_or_insert_with(Arc::default)) + .shadow_board_limit_mib = std::num::NonZeroU32::new(1); + }); } let test = builder.build_with_auto_env(&server).await?; let root = test.session_configured.thread_id; diff --git a/codex-rs/ext/guardian-v3/src/housekeeper.rs b/codex-rs/ext/guardian-v3/src/housekeeper.rs index 74244ff6d1..4beb141ce2 100644 --- a/codex-rs/ext/guardian-v3/src/housekeeper.rs +++ b/codex-rs/ext/guardian-v3/src/housekeeper.rs @@ -1,5 +1,5 @@ //! Serial routing and description updates over the existing board operations. -//! Batches keep whole originals within the model's tool-output and context budgets. +//! Batches keep whole originals within the configured batch limit and model context window. //! Progress is process-local. Any error stops the pass; partial writes are not repaired. use crate::EvidenceCursor; @@ -10,6 +10,7 @@ use crate::inbox::LiveDelivery; use crate::sampling::context_input; use anyhow::ensure; use codex_core::CodexThread; +use codex_features::GuardianV3HousekeeperBatchLimit; use codex_features::GuardianV3HousekeeperConfigToml; use codex_guardian_reviewer::ReviewDeadline; use codex_guardian_reviewer::run_before_review_deadline; @@ -23,6 +24,7 @@ use codex_message_board::SortDirection; use codex_message_board::UpsertChannelRequest; use codex_protocol::SessionId; use codex_protocol::ThreadId; +use codex_protocol::protocol::TruncationPolicy; use codex_utils_string::to_json_string_bounded; use serde::Deserialize; use serde::Serialize; @@ -61,6 +63,7 @@ pub struct Housekeeper { board: Arc, owner: ThreadId, sampler: HousekeeperSampler, + batch_limit: Option, batch_timeout: Duration, stopped: bool, pub(super) shadow_size: Option, @@ -91,6 +94,7 @@ impl Housekeeper { settings.routing_instructions.as_deref(), ) .await?, + batch_limit: settings.batch_limit, batch_timeout: settings .batch_timeout_ms .map_or(Duration::from_secs(90), |ms| { @@ -163,7 +167,11 @@ impl Housekeeper { break; } } - let policy = self.sampler.input_policy(); + let token_limit = match self.batch_limit { + None => 100_000, + Some(GuardianV3HousekeeperBatchLimit::Tokens(limit)) => limit.get() as usize, + }; + let policy = TruncationPolicy::Tokens(token_limit.min(self.sampler.input_limit)); let input_budget = policy.byte_budget(); let empty_input = RoutingInput { catalog: &catalog, @@ -191,7 +199,7 @@ impl Housekeeper { } ensure!( !texts.is_empty(), - "housekeeper catalog and original exceed the model's tool-output budget" + "housekeeper catalog and original exceed the routing input budget of {input_budget} bytes" ); let (source_count, output, batch) = run_before_review_deadline( deadline, diff --git a/codex-rs/ext/guardian-v3/src/housekeeper_sampler.rs b/codex-rs/ext/guardian-v3/src/housekeeper_sampler.rs index 481b17e64d..bcb06fc0fb 100644 --- a/codex-rs/ext/guardian-v3/src/housekeeper_sampler.rs +++ b/codex-rs/ext/guardian-v3/src/housekeeper_sampler.rs @@ -42,7 +42,7 @@ pub(super) struct HousekeeperSampler { instructions: ResponseItem, instruction_bytes: usize, history: Vec, - input_limit: usize, + pub(super) input_limit: usize, batches: VecDeque, retained_tokens: usize, } @@ -133,10 +133,6 @@ impl HousekeeperSampler { } } - pub(super) fn input_policy(&self) -> TruncationPolicy { - self.model.truncation_policy.into() - } - pub(super) async fn sample( &mut self, max_sources: usize, diff --git a/codex-rs/ext/guardian-v3/tests/housekeeping.rs b/codex-rs/ext/guardian-v3/tests/housekeeping.rs index 2fbd5d6f1b..58faf1b5a2 100644 --- a/codex-rs/ext/guardian-v3/tests/housekeeping.rs +++ b/codex-rs/ext/guardian-v3/tests/housekeeping.rs @@ -21,6 +21,7 @@ use codex_extension_api::ThreadStopInput; use codex_extension_api::TurnLifecycleContributor; use codex_extension_api::TurnStopInput; use codex_features::Feature; +use codex_features::GuardianV3HousekeeperBatchLimit; use codex_features::GuardianV3HousekeeperConfigToml; use codex_guardian_reviewer::GUARDIAN_FOLLOWUP_REVIEW_REMINDER; use codex_guardian_reviewer::SessionDisposition; @@ -47,7 +48,6 @@ use codex_protocol::ThreadId; use codex_protocol::approvals::GuardianAssessmentStatus; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::models::ResponseItem; -use codex_protocol::openai_models::TruncationPolicyConfig; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::SessionSource; @@ -92,6 +92,7 @@ use board_host::board_host; enum RoutingCase { Success, + DefaultBatchLimit, RetryExhausted, WindowPressure, InstructionsExceedWindow, @@ -106,6 +107,7 @@ enum RoutingCase { } #[test_case::test_case(RoutingCase::Success; "transient_failures_route_each_original_once")] +#[test_case::test_case(RoutingCase::DefaultBatchLimit; "default_token_limit_groups_large_originals")] #[test_case::test_case(RoutingCase::RetryExhausted; "exhausted_retries_leave_the_batch_pending")] #[test_case::test_case(RoutingCase::WindowPressure; "splits_batches_to_fit_routing_instructions_and_evicts_completed_batches")] #[test_case::test_case(RoutingCase::InstructionsExceedWindow; "budgets_configured_routing_instructions")] @@ -124,13 +126,10 @@ async fn routes_captured_originals_and_updates_descriptions( core_test_support::skip_if_no_network!(Ok(())); let server = start_mock_server().await; let window_pressure = matches!(case, RoutingCase::WindowPressure); - let input_policy = - TruncationPolicyConfig::bytes(if window_pressure { 16 * 1024 } else { 1024 }); let small_window = window_pressure || matches!(case, RoutingCase::InstructionsExceedWindow); let test = test_codex() .with_history_mode(ThreadHistoryMode::Paginated) .with_model_info_override("gpt-5.6-luna", move |model| { - model.truncation_policy = input_policy; if small_window { model.context_window = Some(4096); } @@ -169,10 +168,23 @@ async fn routes_captured_originals_and_updates_descriptions( test.thread_store.flush_thread(owner).await?; let snapshot = cursor.capture(test.thread_store.as_ref()).await?; assert_eq!(snapshot.records().len(), 1); - let first_batch_size = if window_pressure { 2 } else { 1 }; + let (first_batch_size, later_text, batch_limit) = match case { + // Eight 44 KiB originals fit the default 400,000-byte batch. The ninth starts another. + RoutingCase::DefaultBatchLimit => (8, "x".repeat(44 * 1024), None), + RoutingCase::WindowPressure => ( + 2, + "The later message is outside this capture.".repeat(50), + None, + ), + _ => ( + 1, + "The later message is outside this capture.".repeat(8), + Some(GuardianV3HousekeeperBatchLimit::Tokens( + NonZeroU32::new(256).expect("positive limit"), + )), + ), + }; let later_count = first_batch_size + 1; - let later_text = - "The later message is outside this capture.".repeat(if window_pressure { 50 } else { 8 }); for user_input_order in (2..).take(later_count) { let later = ResponseItemEnvelope { item: serde_json::from_value( @@ -220,7 +232,10 @@ async fn routes_captured_originals_and_updates_descriptions( .await?; let board_handle: Arc = board.clone(); let custom_strategy = "Route approvals and revocations to the same topic."; - let mut settings = GuardianV3HousekeeperConfigToml::default(); + let mut settings = GuardianV3HousekeeperConfigToml { + batch_limit, + ..Default::default() + }; if window_pressure { // Leave room for two of the three later originals in the model window. settings.routing_instructions = Some(custom_strategy.repeat(160)); @@ -254,6 +269,7 @@ async fn routes_captured_originals_and_updates_descriptions( RoutingCase::EmptyRoute => r#"{"routes":[[]],"descriptions":[]}"#, RoutingCase::InvalidResponse => r#"{"private-evidence-canary":true}"#, RoutingCase::Success + | RoutingCase::DefaultBatchLimit | RoutingCase::RetryExhausted | RoutingCase::WindowPressure | RoutingCase::InstructionsExceedWindow @@ -367,7 +383,10 @@ async fn routes_captured_originals_and_updates_descriptions( ); if !matches!( case, - RoutingCase::Success | RoutingCase::WindowPressure | RoutingCase::DuplicateDestination + RoutingCase::Success + | RoutingCase::DefaultBatchLimit + | RoutingCase::WindowPressure + | RoutingCase::DuplicateDestination ) { let error = routed.expect_err("routing should fail"); if matches!(case, RoutingCase::InvalidResponse) { @@ -499,15 +518,7 @@ async fn routes_captured_originals_and_updates_descriptions( serde_json::to_value(&snapshot.records()[0])? ); } - // Under window pressure all three originals fit the tool budget, but the prompt - // leaves room for only two. The other cases keep the smaller tool budget. let catalog = json!({"release":"Release policy","_audit":""}); - let combined_input = - serde_json::to_string(&json!({"catalog":catalog,"sources":next.records()}))?; - assert_eq!( - combined_input.len() <= input_policy.limit as usize, - window_pressure - ); let (first, last) = next.records().split_at(first_batch_size); // Omission preserves the description. A redundant echo is harmless too. let first_reply = @@ -561,7 +572,6 @@ async fn routes_captured_originals_and_updates_descriptions( let input = input.last().expect("latest operation input")["output"] .as_str() .expect("operation input"); - assert!(input.len() <= input_policy.limit as usize); assert_eq!( serde_json::from_str::(input)?, json!({"catalog":catalog,"sources":sources}) diff --git a/codex-rs/features/src/feature_configs.rs b/codex-rs/features/src/feature_configs.rs index ca84746aed..fd4a4dfbb2 100644 --- a/codex-rs/features/src/feature_configs.rs +++ b/codex-rs/features/src/feature_configs.rs @@ -364,11 +364,26 @@ pub struct GuardianV3HousekeeperConfigToml { /// Guidance for grouping originals into channels and describing their topics. Ignored in project config. #[serde(skip_serializing_if = "Option::is_none")] pub routing_instructions: Option, + /// Size limit for one routing batch. Defaults to 100,000 estimated tokens. + #[serde(skip_serializing_if = "Option::is_none")] + pub batch_limit: Option, /// Time budget for routing one batch, in milliseconds. Defaults to 90,000. #[serde(skip_serializing_if = "Option::is_none")] pub batch_timeout_ms: Option, } +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema)] +#[serde( + tag = "mode", + content = "limit", + rename_all = "snake_case", + deny_unknown_fields +)] +pub enum GuardianV3HousekeeperBatchLimit { + /// Estimated tokens in the serialized channel catalog and new evidence. + Tokens(NonZeroU32), +} + #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] #[serde(deny_unknown_fields)] pub struct GuardianV3ReviewerConfigToml { diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index ce1aaa78dd..69554bf7c6 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -30,6 +30,7 @@ pub use feature_configs::GuardianV2ReviewScopeConfigToml; pub use feature_configs::GuardianV2TranscriptConfigToml; pub use feature_configs::GuardianV2TranscriptSource; pub use feature_configs::GuardianV3ConfigToml; +pub use feature_configs::GuardianV3HousekeeperBatchLimit; pub use feature_configs::GuardianV3HousekeeperConfigToml; pub use feature_configs::GuardianV3ReviewerConfigToml; pub use feature_configs::MultiAgentV2ConfigToml; diff --git a/codex-rs/features/src/tests.rs b/codex-rs/features/src/tests.rs index 334cba5134..0612e72894 100644 --- a/codex-rs/features/src/tests.rs +++ b/codex-rs/features/src/tests.rs @@ -270,6 +270,7 @@ message_board_in_memory = true shadow_board_limit_mib = 32 [guardianv3.housekeeper] routing_instructions = "Group related deployment evidence." +batch_limit = { mode = "tokens", limit = 50000 } batch_timeout_ms = 15000 [guardianv3.reviewer] retrieval_instructions = "Search before assessing deployments." @@ -287,6 +288,9 @@ retrieval_instructions = "Search before assessing deployments." message_board_in_memory: Some(true), housekeeper: Some(crate::GuardianV3HousekeeperConfigToml { routing_instructions: Some("Group related deployment evidence.".to_owned()), + batch_limit: Some(crate::GuardianV3HousekeeperBatchLimit::Tokens( + std::num::NonZeroU32::new(50_000).unwrap(), + )), batch_timeout_ms: std::num::NonZeroU32::new(15_000), }), reviewer: Some(crate::GuardianV3ReviewerConfigToml { @@ -299,6 +303,12 @@ retrieval_instructions = "Search before assessing deployments." #[test] fn guardian_v3_rejects_zero_limits() { + assert!( + toml::from_str::( + "[guardianv3.housekeeper]\nbatch_limit = { mode = 'tokens', limit = 0 }" + ) + .is_err() + ); assert!(toml::from_str::("[guardianv3]\nshadow_board_limit_mib = 0").is_err()); assert!( toml::from_str::("[guardianv3.housekeeper]\nbatch_timeout_ms = 0").is_err()