mirror of
https://github.com/openai/codex.git
synced 2026-11-23 07:17:11 +00:00
Preserve complete actions in Guardian approval reviews (#44569)
## Why Truncating action arguments can leave approval reviewers evaluating incomplete actions. Large actions need complete review input and explicit handling when they exceed the review budget. ## What changed - Remove action truncation and the fixed synchronous action byte limit. Admit complete actions against the whole-request budget, splitting long text losslessly into bounded transport parts and accounting for their framing. - Route actions exceeding the asynchronous action budget to synchronous review. Prevent cached scores from covering oversized calls, including expanded approval arguments, while allowing later small actions to recover score reuse. - Request user approval when optional review exhausts its local input budget. Keep required review and compaction service failures closed to approval, and retire exhausted review sessions. ## Testing Add coverage for complete large-action delivery, optional user fallback, required-review denial, subsequent review recovery, async overflow through MCP approval routing, and lossless text splitting with budget accounting. GitOrigin-RevId: 08f06e68a94b2f779480dd6b6cf5bc30b241f6dd
This commit is contained in:
1 parent
3319d9b296
commit
9c4879f3a5
33 files changed
+841
-547
No files matched your search
@@ -1,25 +1,26 @@
|
||||
//! Renders bounded planned-action JSON while preserving tool and call identity.
|
||||
//! String truncation precedes omission of optional fields.
|
||||
//! Renders complete planned-action JSON or rejects it for synchronous review.
|
||||
//! Action arguments cannot be shortened to fit the asynchronous classifier budget.
|
||||
|
||||
use codex_extension_api::ToolName;
|
||||
use codex_extension_api::ToolPayload;
|
||||
use codex_protocol::protocol::TruncationPolicy;
|
||||
use serde_json::json;
|
||||
|
||||
use super::transcript::truncate_entry;
|
||||
|
||||
pub(super) struct GuardianAction {
|
||||
pub(super) tool_name: ToolName,
|
||||
pub(super) payload: ToolPayload,
|
||||
}
|
||||
|
||||
pub(super) struct RenderedAction {
|
||||
pub(super) text: String,
|
||||
pub(super) original_bytes: usize,
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(super) enum ActionRenderError {
|
||||
#[error("Guardian action exceeds the {max_tokens}-token review limit")]
|
||||
TooLarge { max_tokens: usize },
|
||||
#[error(transparent)]
|
||||
Serialization(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
impl GuardianAction {
|
||||
pub(super) fn render(self, max_action_tokens: usize) -> serde_json::Result<RenderedAction> {
|
||||
pub(super) fn render(self, max_action_tokens: usize) -> Result<String, ActionRenderError> {
|
||||
let arguments = match self.payload {
|
||||
ToolPayload::Function { arguments } => {
|
||||
serde_json::from_str(&arguments).unwrap_or(serde_json::Value::String(arguments))
|
||||
@@ -42,129 +43,16 @@ impl GuardianAction {
|
||||
.for_each(serde_json::Value::sort_all_objects);
|
||||
let max_action_bytes = TruncationPolicy::Tokens(max_action_tokens).byte_budget();
|
||||
let rendered = serde_json::to_string_pretty(&action)?;
|
||||
let original_bytes = rendered.len();
|
||||
if rendered.len().saturating_add(1) <= max_action_bytes {
|
||||
return Ok(RenderedAction {
|
||||
text: rendered,
|
||||
original_bytes,
|
||||
});
|
||||
return Ok(rendered);
|
||||
}
|
||||
|
||||
if let Some(rendered) = fit_action_to_budget(&action, max_action_bytes, max_action_tokens)?
|
||||
{
|
||||
return Ok(RenderedAction {
|
||||
text: rendered,
|
||||
original_bytes,
|
||||
});
|
||||
}
|
||||
|
||||
let mut omission_key = "_guardian_omitted_fields".to_owned();
|
||||
while action.contains_key(&omission_key) {
|
||||
omission_key.push('_');
|
||||
}
|
||||
let mut retained = serde_json::Map::new();
|
||||
for key in ["tool", "call_id"] {
|
||||
if let Some(value) = action.get(key) {
|
||||
retained.insert(key.to_owned(), value.clone());
|
||||
}
|
||||
}
|
||||
let mut omitted = action.len().saturating_sub(retained.len());
|
||||
retained.insert(omission_key.clone(), json!(omitted));
|
||||
|
||||
let mut optional_fields = action
|
||||
.iter()
|
||||
.filter(|(key, _)| !matches!(key.as_str(), "tool" | "call_id"))
|
||||
.collect::<Vec<_>>();
|
||||
optional_fields.sort_by_key(|(key, _)| {
|
||||
!matches!(
|
||||
key.as_str(),
|
||||
"arguments" | "cmd" | "command" | "input" | "patch" | "path" | "url"
|
||||
)
|
||||
});
|
||||
for (key, value) in optional_fields {
|
||||
let mut candidate = retained.clone();
|
||||
candidate.insert(key.clone(), value.clone());
|
||||
candidate.insert(omission_key.clone(), json!(omitted.saturating_sub(1)));
|
||||
candidate.sort_keys();
|
||||
let minimized = render_action_with_limit(&candidate, /*max_tokens*/ 0)?;
|
||||
if minimized.len().saturating_add(1) <= max_action_bytes {
|
||||
retained = candidate;
|
||||
omitted = omitted.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
|
||||
retained.sort_keys();
|
||||
let rendered = fit_action_to_budget(&retained, max_action_bytes, max_action_tokens)?
|
||||
.ok_or_else(|| {
|
||||
serde_json::Error::io(std::io::Error::other(format!(
|
||||
"Guardian action identity exceeds the {max_action_tokens}-token limit"
|
||||
)))
|
||||
})?;
|
||||
Ok(RenderedAction {
|
||||
text: rendered,
|
||||
original_bytes,
|
||||
Err(ActionRenderError::TooLarge {
|
||||
max_tokens: max_action_tokens,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn fit_action_to_budget(
|
||||
action: &serde_json::Map<String, serde_json::Value>,
|
||||
max_action_bytes: usize,
|
||||
max_action_tokens: usize,
|
||||
) -> serde_json::Result<Option<String>> {
|
||||
let mut low = 0usize;
|
||||
let mut high = max_action_tokens.saturating_add(1);
|
||||
let mut best = None;
|
||||
|
||||
while low < high {
|
||||
let max_tokens = low + (high - low) / 2;
|
||||
let rendered = render_action_with_limit(action, max_tokens)?;
|
||||
if rendered.len().saturating_add(1) <= max_action_bytes {
|
||||
best = Some(rendered);
|
||||
low = max_tokens.saturating_add(1);
|
||||
} else {
|
||||
high = max_tokens;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(best)
|
||||
}
|
||||
|
||||
fn render_action_with_limit(
|
||||
action: &serde_json::Map<String, serde_json::Value>,
|
||||
max_tokens: usize,
|
||||
) -> serde_json::Result<String> {
|
||||
let mut truncated = action.clone();
|
||||
for (key, value) in &mut truncated {
|
||||
if !matches!(key.as_str(), "tool" | "call_id") {
|
||||
truncate_action_value(value, max_tokens);
|
||||
}
|
||||
}
|
||||
serde_json::to_string_pretty(&truncated)
|
||||
}
|
||||
|
||||
fn truncate_action_value(value: &mut serde_json::Value, max_tokens: usize) {
|
||||
match value {
|
||||
serde_json::Value::String(text) => {
|
||||
let truncated = truncate_entry(text, max_tokens);
|
||||
if truncated.len() < text.len() {
|
||||
*text = truncated;
|
||||
}
|
||||
}
|
||||
serde_json::Value::Array(values) => {
|
||||
for value in values {
|
||||
truncate_action_value(value, max_tokens);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Object(values) => {
|
||||
for value in values.values_mut() {
|
||||
truncate_action_value(value, max_tokens);
|
||||
}
|
||||
}
|
||||
serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "action_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,96 +1,37 @@
|
||||
//! Tests for bounded action rendering and field retention.
|
||||
//! Complete action rendering preserves nested arguments and rejects overflow.
|
||||
|
||||
use super::*;
|
||||
use anyhow::Result;
|
||||
use codex_extension_api::ToolName;
|
||||
use codex_extension_api::ToolPayload;
|
||||
use codex_protocol::protocol::TruncationPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
use super::GuardianAction;
|
||||
use crate::async_scorer::config::DEFAULT_MODEL_CONTEXT_ITEM_TOKENS;
|
||||
use serde_json::Value;
|
||||
|
||||
#[test]
|
||||
fn guardian_action_bounds_structurally_oversized_arrays() -> Result<()> {
|
||||
let action = GuardianAction {
|
||||
tool_name: ToolName::plain("inspect_values"),
|
||||
payload: ToolPayload::Function {
|
||||
arguments: json!({
|
||||
"call_id": "genuine-call",
|
||||
"tool": "spoofed-tool",
|
||||
"values": (0..6_000).collect::<Vec<_>>(),
|
||||
})
|
||||
.to_string(),
|
||||
},
|
||||
fn guardian_action_preserves_complete_arguments_at_budget_boundary() -> Result<()> {
|
||||
let arguments = json!({
|
||||
"call_id": "genuine-call",
|
||||
"tool": "untrusted-tool",
|
||||
"attachments": [{"content": "🦀\"\\\n".repeat(/*n*/ 40) + "required suffix"}],
|
||||
"metadata": {"description": "required argument", "values": [1, false, null]},
|
||||
});
|
||||
let render = |max_action_tokens| {
|
||||
GuardianAction {
|
||||
tool_name: ToolName::plain("inspect_values"),
|
||||
payload: ToolPayload::Function {
|
||||
arguments: arguments.to_string(),
|
||||
},
|
||||
}
|
||||
.render(max_action_tokens)
|
||||
};
|
||||
|
||||
let rendered = action.render(DEFAULT_MODEL_CONTEXT_ITEM_TOKENS)?.text;
|
||||
assert!(
|
||||
rendered.len().saturating_add(1)
|
||||
<= TruncationPolicy::Tokens(DEFAULT_MODEL_CONTEXT_ITEM_TOKENS).byte_budget()
|
||||
);
|
||||
let action = serde_json::from_str::<serde_json::Value>(&rendered)?;
|
||||
assert_eq!(
|
||||
action,
|
||||
json!({
|
||||
"_guardian_omitted_fields": 1,
|
||||
"call_id": "genuine-call",
|
||||
"tool": "inspect_values",
|
||||
})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guardian_action_bounds_structurally_oversized_object_keys() -> Result<()> {
|
||||
let oversized_key = "oversized_key_".to_owned()
|
||||
+ &"k".repeat(TruncationPolicy::Tokens(DEFAULT_MODEL_CONTEXT_ITEM_TOKENS).byte_budget());
|
||||
let mut arguments = serde_json::Map::from_iter([
|
||||
(
|
||||
"_guardian_omitted_fields".to_owned(),
|
||||
json!("actual-tool-argument"),
|
||||
),
|
||||
("call_id".to_owned(), json!("genuine-call")),
|
||||
("cmd".to_owned(), json!("remove-important-file")),
|
||||
("tool".to_owned(), json!("spoofed-tool")),
|
||||
(oversized_key.clone(), json!(true)),
|
||||
]);
|
||||
for index in 0..600 {
|
||||
arguments.insert(format!("a_{index:04}_{}", "k".repeat(64)), json!(index));
|
||||
}
|
||||
let original_field_count = arguments.len();
|
||||
let action = GuardianAction {
|
||||
tool_name: ToolName::plain("inspect_fields"),
|
||||
payload: ToolPayload::Function {
|
||||
arguments: serde_json::Value::Object(arguments).to_string(),
|
||||
},
|
||||
};
|
||||
|
||||
let rendered = action.render(DEFAULT_MODEL_CONTEXT_ITEM_TOKENS)?.text;
|
||||
assert!(
|
||||
rendered.len().saturating_add(1)
|
||||
<= TruncationPolicy::Tokens(DEFAULT_MODEL_CONTEXT_ITEM_TOKENS).byte_budget()
|
||||
);
|
||||
let action = serde_json::from_str::<serde_json::Value>(&rendered)?;
|
||||
let fields = action
|
||||
.as_object()
|
||||
.expect("the bounded action must remain a JSON object");
|
||||
assert_eq!(fields.get("tool"), Some(&json!("inspect_fields")));
|
||||
assert_eq!(fields.get("call_id"), Some(&json!("genuine-call")));
|
||||
assert_eq!(fields.get("cmd"), Some(&json!("remove-important-file")));
|
||||
assert_eq!(
|
||||
fields.get("_guardian_omitted_fields"),
|
||||
Some(&json!("actual-tool-argument"))
|
||||
);
|
||||
assert!(fields.len() < original_field_count);
|
||||
assert!(!fields.contains_key(&oversized_key));
|
||||
assert!(
|
||||
fields
|
||||
.get("_guardian_omitted_fields_")
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.is_some_and(|omitted| omitted > 0)
|
||||
);
|
||||
|
||||
let mut expected = arguments.clone();
|
||||
expected["tool"] = json!("inspect_values");
|
||||
let bytes = serde_json::to_string_pretty(&expected)?.len();
|
||||
let budget = TruncationPolicy::Bytes(bytes.saturating_add(1)).token_budget();
|
||||
let rendered = render(budget)?;
|
||||
assert_eq!(serde_json::from_str::<Value>(&rendered)?, expected);
|
||||
assert_eq!(rendered.len(), bytes);
|
||||
assert!(matches!(
|
||||
render(budget - 1),
|
||||
Err(ActionRenderError::TooLarge { .. })
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
@@ -22,6 +22,7 @@ use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::openai_models::GuardianReviewMode;
|
||||
use codex_protocol::openai_models::GuardianScope;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::TruncationPolicy;
|
||||
use codex_protocol::security_risk::SecurityRiskScore;
|
||||
use std::sync::Weak;
|
||||
use std::sync::atomic::Ordering;
|
||||
@@ -116,7 +117,10 @@ impl GuardianApprovalReviewer {
|
||||
?reason,
|
||||
"reviewing approval"
|
||||
);
|
||||
ApprovalDecision::Reviewed(input.synchronous_reviewer.review(reason).await)
|
||||
match input.synchronous_reviewer.review(reason).await {
|
||||
Some(decision) => ApprovalDecision::Reviewed(decision),
|
||||
None => ApprovalDecision::AskUser,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,6 +136,30 @@ async fn cached_evidence(
|
||||
record_fast_decision(metrics, "deferred", "missing_score");
|
||||
return Err(GuardianReviewReason::MissingScore);
|
||||
};
|
||||
// Elicitations and intercepted execs can expand beyond the original scored action.
|
||||
let mut action = input.action.clone();
|
||||
if action.get("tool").and_then(serde_json::Value::as_str) == Some("mcp_tool_call")
|
||||
&& let Some(fields) = action.as_object_mut()
|
||||
{
|
||||
// Match the action renderer: host descriptions are optional, arguments are not.
|
||||
fields.remove("tool_description");
|
||||
fields.remove("connector_description");
|
||||
}
|
||||
let max_action_bytes = TruncationPolicy::Tokens(config.max_action_tokens).byte_budget();
|
||||
let action_fits = serde_json::to_string_pretty(&action)
|
||||
.is_ok_and(|action| action.len().saturating_add(1) <= max_action_bytes);
|
||||
if !action_fits
|
||||
|| input.tool_call_id.is_some_and(|call_id| {
|
||||
progress
|
||||
.oversized_tool_calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.contains(call_id)
|
||||
})
|
||||
{
|
||||
record_fast_decision(metrics, "deferred", "scoring_failure");
|
||||
return Err(GuardianReviewReason::ScoringFailure);
|
||||
}
|
||||
let context_mode = store
|
||||
.get_or_init(GuardianReviewEvidence::default)
|
||||
.context_mode();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::transcript::ContextInput;
|
||||
use codex_core::context::ContextualUserFragment;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::Weak;
|
||||
@@ -28,6 +29,7 @@ use codex_extension_api::SkillInvocationContributor;
|
||||
use codex_extension_api::SkillInvocationInput;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_extension_api::ToolFinishInput;
|
||||
use codex_extension_api::ToolLifecycleContributor;
|
||||
use codex_extension_api::ToolLifecycleFuture;
|
||||
use codex_extension_api::ToolStartInput;
|
||||
@@ -46,8 +48,8 @@ use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::protocol::has_full_access;
|
||||
use codex_protocol::security_risk::SecurityRiskScore;
|
||||
|
||||
use super::action::ActionRenderError;
|
||||
use super::action::GuardianAction;
|
||||
use super::action::RenderedAction;
|
||||
use super::authorization::ScoreAuthorization;
|
||||
use super::config::GuardianV2Config;
|
||||
use super::coverage::UnscoredAction;
|
||||
@@ -82,6 +84,9 @@ pub(super) struct GuardianV2ScoreProgress {
|
||||
pub(super) js_executions: AtomicUsize,
|
||||
pub(super) latest_scored_tool_call: AtomicUsize,
|
||||
pub(super) latest_failed_tool_call: AtomicUsize,
|
||||
// Keep overflow attached to each active call even after a newer score succeeds.
|
||||
// The host's finish callback removes entries on completion, failure, or cancellation.
|
||||
pub(super) oversized_tool_calls: Mutex<BTreeSet<String>>,
|
||||
// Serialize successful score publication with its authorization metadata.
|
||||
pub(super) authorization: Mutex<Option<ScoreAuthorization>>,
|
||||
metrics: Option<Arc<dyn ExtensionMetrics>>,
|
||||
@@ -210,6 +215,18 @@ impl ToolLifecycleContributor for GuardianV2Extension {
|
||||
fn on_tool_start<'a>(&'a self, input: ToolStartInput<'a>) -> ToolLifecycleFuture<'a> {
|
||||
Box::pin(self.score_tool(input))
|
||||
}
|
||||
|
||||
fn on_tool_finish<'a>(&'a self, input: ToolFinishInput<'a>) -> ToolLifecycleFuture<'a> {
|
||||
Box::pin(async move {
|
||||
if let Some(progress) = input.thread_store.get::<GuardianV2ScoreProgress>() {
|
||||
progress
|
||||
.oversized_tool_calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.remove(input.call_id);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl GuardianV2Extension {
|
||||
@@ -427,6 +444,45 @@ impl GuardianV2Extension {
|
||||
tool_name: input.tool_name.clone(),
|
||||
payload: input.payload.clone(),
|
||||
};
|
||||
let planned_action = match action.render(guardian_config.max_action_tokens) {
|
||||
Ok(text) => text,
|
||||
Err(ActionRenderError::TooLarge { .. }) => {
|
||||
score_progress
|
||||
.oversized_tool_calls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.insert(input.call_id.to_owned());
|
||||
score_progress
|
||||
.latest_failed_tool_call
|
||||
.fetch_max(tool_call_index, Ordering::Release);
|
||||
Self::record_fail_closed_score(input.thread_store, sampled_at);
|
||||
record_classification(
|
||||
metrics.as_deref(),
|
||||
classification_started_at.elapsed(),
|
||||
"failure",
|
||||
Some("input_too_large"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
Err(error) => {
|
||||
score_progress
|
||||
.latest_failed_tool_call
|
||||
.fetch_max(tool_call_index, Ordering::Release);
|
||||
Self::record_fail_closed_score(input.thread_store, sampled_at);
|
||||
record_classification(
|
||||
metrics.as_deref(),
|
||||
classification_started_at.elapsed(),
|
||||
"failure",
|
||||
Some("action_serialization_error"),
|
||||
);
|
||||
event_sink.emit_warning(ExtensionWarning {
|
||||
thread_id,
|
||||
turn_id: Some(turn_id),
|
||||
message: format!("Guardian V2 action serialization failed: {error}"),
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
let review_model_override = parent_model
|
||||
.as_ref()
|
||||
.and_then(|model| model.auto_review_model_override.clone());
|
||||
@@ -489,30 +545,6 @@ impl GuardianV2Extension {
|
||||
model: parent_model.clone(),
|
||||
..score_authorization
|
||||
};
|
||||
let planned_action = match action.render(guardian_config.max_action_tokens) {
|
||||
Ok(RenderedAction {
|
||||
text,
|
||||
original_bytes,
|
||||
}) => {
|
||||
truncations.record("action", original_bytes, text.len());
|
||||
text
|
||||
}
|
||||
Err(error) => {
|
||||
Self::record_fail_closed_score(thread.thread_extension_data(), sampled_at);
|
||||
record_classification(
|
||||
metrics.as_deref(),
|
||||
classification_started_at.elapsed(),
|
||||
"failure",
|
||||
Some("action_serialization_error"),
|
||||
);
|
||||
event_sink.emit_warning(ExtensionWarning {
|
||||
thread_id,
|
||||
turn_id: Some(turn_id),
|
||||
message: format!("Guardian V2 action serialization failed: {error}"),
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
let action_section = PlannedAction {
|
||||
json: planned_action.clone(),
|
||||
tool_descriptions: None,
|
||||
|
||||
@@ -71,7 +71,6 @@ use super::GuardianV2Extension;
|
||||
use super::GuardianV2ScoreProgress;
|
||||
|
||||
use crate::async_scorer::config::CLASSIFICATION_OUTPUT_INSTRUCTIONS;
|
||||
use crate::async_scorer::config::DEFAULT_MODEL_CONTEXT_ITEM_TOKENS;
|
||||
use crate::async_scorer::config::DEFAULT_PARENT_COMPACTION_TOKENS;
|
||||
use crate::async_scorer::config::GuardianV2Config;
|
||||
use crate::async_scorer::coverage::GuardianPolicy;
|
||||
@@ -90,8 +89,6 @@ use crate::async_scorer::sampler::tests::proxy_websocket_servers_with_http;
|
||||
use crate::async_scorer::transcript::MAX_MESSAGE_ENTRY_TOKENS;
|
||||
use crate::async_scorer::transcript::MAX_TOOL_ENTRY_TOKENS;
|
||||
use crate::async_scorer::transcript::truncate_entry;
|
||||
use crate::async_scorer::truncation::CLASSIFICATION_TRUNCATION_BYTES_METRIC;
|
||||
use crate::async_scorer::truncation::CLASSIFICATION_TRUNCATION_METRIC;
|
||||
use codex_features::GuardianV2ReviewScopeConfigToml;
|
||||
|
||||
const TEST_GUARDIAN_POLICY: &str =
|
||||
@@ -1204,19 +1201,6 @@ async fn contributor_fails_closed_when_model_configuration_is_invalid() -> Resul
|
||||
fixture.assert_fails_closed("elevated_risk").await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn contributor_fails_closed_when_action_serialization_fails() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let fixture = GuardianFailureFixture::new().await?;
|
||||
let oversized_tool_name = ToolName::plain(
|
||||
"x".repeat(TruncationPolicy::Tokens(DEFAULT_MODEL_CONTEXT_ITEM_TOKENS).byte_budget()),
|
||||
);
|
||||
|
||||
fixture.score_tool(oversized_tool_name).await;
|
||||
fixture.assert_fails_closed("elevated_risk").await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn contributor_fails_closed_when_luna_classification_fails() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
@@ -1388,7 +1372,7 @@ max_recent_non_user_entries = 8
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
];
|
||||
let arguments = json!({"body": "x".repeat(4_000)}).to_string();
|
||||
let arguments = json!({"body": "x".repeat(/*n*/ 128)}).to_string();
|
||||
let (request, test, registry) = sample_configured_conversation_history(
|
||||
conversation_history,
|
||||
&arguments,
|
||||
@@ -1433,16 +1417,11 @@ max_recent_non_user_entries = 8
|
||||
.as_str()
|
||||
.expect("planned action should be a text item");
|
||||
assert!(action.len() <= TruncationPolicy::Tokens(/*limit*/ 128).byte_budget());
|
||||
let original_action_bytes = i64::try_from(
|
||||
serde_json::to_string_pretty(&json!({
|
||||
"body": "x".repeat(4_000),
|
||||
"tool": "read_file",
|
||||
}))?
|
||||
.len(),
|
||||
)?;
|
||||
let action: serde_json::Value = serde_json::from_str(action)?;
|
||||
let retained_action_bytes = i64::try_from(serde_json::to_string_pretty(&action)?.len())?;
|
||||
assert_eq!(action["tool"], "read_file");
|
||||
assert_eq!(
|
||||
action,
|
||||
json!({"body": "x".repeat(/*n*/ 128), "tool": "read_file"})
|
||||
);
|
||||
|
||||
let thread_store = test.codex.thread_extension_data();
|
||||
let score_progress = thread_store
|
||||
@@ -1454,7 +1433,7 @@ max_recent_non_user_entries = 8
|
||||
.latest_scored_tool_call
|
||||
.load(Ordering::Acquire)
|
||||
== 0
|
||||
|| metrics.classification_samples().len() < 14
|
||||
|| metrics.classification_samples().len() < 10
|
||||
{
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
@@ -1507,6 +1486,33 @@ max_recent_non_user_entries = 8
|
||||
Some(ReviewDecision::Approved)
|
||||
);
|
||||
|
||||
// A small scored call does not cover expanded elicitation arguments or an
|
||||
// intercepted exec with no tool-call ID. Both must still fit the action budget.
|
||||
for (argument, expected) in [
|
||||
("small".to_owned(), Some(ReviewDecision::Approved)),
|
||||
("expanded argument ".repeat(/*n*/ 128), None),
|
||||
] {
|
||||
for action in [
|
||||
json!({
|
||||
"tool": "mcp_tool_call", "server": "example", "id": "call-1",
|
||||
"arguments": {"body": argument},
|
||||
"tool_description": "optional metadata ".repeat(/*n*/ 128),
|
||||
}),
|
||||
json!({"tool": "exec_command", "program": "example", "argv": [argument]}),
|
||||
] {
|
||||
assert_eq!(
|
||||
cached_approval(
|
||||
®istry,
|
||||
thread_store,
|
||||
&action.to_string(),
|
||||
/*metrics*/ None
|
||||
)
|
||||
.await,
|
||||
expected
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
score_progress
|
||||
.latest_scored_tool_call
|
||||
@@ -1607,34 +1613,7 @@ max_recent_non_user_entries = 8
|
||||
classification_duration_ms,
|
||||
vec![("outcome".to_owned(), "success".to_owned())],
|
||||
),
|
||||
RecordedMetric::Counter(
|
||||
CLASSIFICATION_TRUNCATION_METRIC.to_owned(),
|
||||
1,
|
||||
vec![
|
||||
("component".to_owned(), "action".to_owned()),
|
||||
("disposition".to_owned(), "truncated".to_owned()),
|
||||
],
|
||||
),
|
||||
])
|
||||
.chain(
|
||||
[
|
||||
("original", original_action_bytes),
|
||||
("retained", retained_action_bytes),
|
||||
("omitted", original_action_bytes - retained_action_bytes),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(measurement, bytes)| {
|
||||
RecordedMetric::Histogram(
|
||||
CLASSIFICATION_TRUNCATION_BYTES_METRIC.to_owned(),
|
||||
bytes,
|
||||
vec![
|
||||
("component".to_owned(), "action".to_owned()),
|
||||
("disposition".to_owned(), "truncated".to_owned()),
|
||||
("measurement".to_owned(), measurement.to_owned()),
|
||||
],
|
||||
)
|
||||
}),
|
||||
)
|
||||
.chain([
|
||||
RecordedMetric::Histogram(TOOL_CALL_LAG_METRIC.to_owned(), 0, vec![]),
|
||||
fast_decision_metric("deferred", "elevated_risk"),
|
||||
@@ -1787,7 +1766,7 @@ async fn contributor_uses_model_defaults_and_preserves_local_overrides() -> Resu
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
},
|
||||
];
|
||||
let arguments = json!({"body": "x".repeat(4_000)}).to_string();
|
||||
let arguments = json!({"body": "x".repeat(/*n*/ 128)}).to_string();
|
||||
let local_config = "[features.guardianv2]\nenabled = true\nreview_threshold = 0.70\n";
|
||||
let (request, test, registry) = sample_configured_conversation_history(
|
||||
conversation_history,
|
||||
@@ -3212,78 +3191,13 @@ async fn legacy_contributor_can_disable_parent_compaction_reuse() -> Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn contributor_bounds_oversized_actions_and_fairly_truncates_nested_fields() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let arguments = json!({
|
||||
"attachments": [{
|
||||
"content": "🦀\"\\\n".repeat(20_000),
|
||||
"name": "financials.csv",
|
||||
}],
|
||||
"call_id": "untrusted-call",
|
||||
"metadata": { "reason": "b".repeat(100_000) },
|
||||
"path": "a".repeat(100_000),
|
||||
"recipient": "finance@example.com",
|
||||
"tool": "untrusted-tool",
|
||||
})
|
||||
.to_string();
|
||||
let (request, _test, _registry) =
|
||||
sample_conversation_history(Vec::new(), &arguments, Some(TEST_GUARDIAN_POLICY)).await?;
|
||||
let content = request["input"][2]["content"]
|
||||
.as_array()
|
||||
.expect("Luna user content should contain separate text items");
|
||||
let action_text = content[content.len() - 2]["text"]
|
||||
.as_str()
|
||||
.expect("the current action should be an input text item");
|
||||
let action = serde_json::from_str::<serde_json::Value>(action_text)?;
|
||||
let max_action_bytes =
|
||||
TruncationPolicy::Tokens(DEFAULT_MODEL_CONTEXT_ITEM_TOKENS).byte_budget();
|
||||
assert!(action_text.ends_with('\n'));
|
||||
assert!(
|
||||
action_text.len() <= max_action_bytes,
|
||||
"the complete model-visible action must remain bounded"
|
||||
);
|
||||
assert!(
|
||||
action_text.len() >= max_action_bytes * 9 / 10,
|
||||
"water-filling should use the available action budget"
|
||||
);
|
||||
assert_eq!(action["tool"], "read_file");
|
||||
assert_eq!(action["call_id"], "untrusted-call");
|
||||
assert_eq!(action["recipient"], "finance@example.com");
|
||||
assert_eq!(action["attachments"][0]["name"], "financials.csv");
|
||||
assert!(action.get("arguments_preview").is_none());
|
||||
assert!(action.get("truncated").is_none());
|
||||
let retained_values = [
|
||||
&action["path"],
|
||||
&action["metadata"]["reason"],
|
||||
&action["attachments"][0]["content"],
|
||||
]
|
||||
.map(|value| {
|
||||
value
|
||||
.as_str()
|
||||
.expect("action string field should remain present")
|
||||
});
|
||||
for text in retained_values {
|
||||
assert!(text.contains("<truncated omitted_approx_tokens=\""));
|
||||
}
|
||||
let smallest_retained = retained_values.iter().map(|text| text.len()).min().unwrap();
|
||||
let largest_retained = retained_values.iter().map(|text| text.len()).max().unwrap();
|
||||
assert!(
|
||||
largest_retained.saturating_sub(smallest_retained) <= 16,
|
||||
"long nested strings should receive comparable shares of the action budget"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct CacheMiss;
|
||||
impl codex_extension_api::SynchronousApprovalReviewer for CacheMiss {
|
||||
fn review(
|
||||
&self,
|
||||
_reason: codex_protocol::approvals::GuardianReviewReason,
|
||||
) -> codex_extension_api::ExtensionFuture<'_, ReviewDecision> {
|
||||
Box::pin(async { ReviewDecision::denied("cache miss") })
|
||||
) -> codex_extension_api::ExtensionFuture<'_, Option<ReviewDecision>> {
|
||||
Box::pin(async { Some(ReviewDecision::denied("cache miss")) })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user