mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Record root turn IDs in Guardian review analytics (#63837)
## Why The review's `turn_id` alone can't identify the root turn of the action being reviewed. For example, a background terminal can request network access during a later turn. ## What changed Add an optional `root_turn_id` to `codex_guardian_review` events. When a verified execution tag ties a network request to a registered tool call, use the root turn ID captured when the call started. Leave the field unset when the reviewed action's root turn is unknown. ## Testing Extend the MCP approval test to check the reported root turn ID. Cover untagged network requests and verify that a cross-turn network review reports the active turn's `turn_id` alongside the issuing turn's `root_turn_id`. GitOrigin-RevId: f0ae40ec4fc441891b4d843912f823a2385fa36f
This commit is contained in:
@@ -108,6 +108,8 @@ pub(crate) struct GuardianReviewContext {
|
||||
/// A host-verified, still-running tool invocation that requested this nested review.
|
||||
pub(crate) enclosing_invocation_id: Option<String>,
|
||||
turn: Arc<TurnContext>,
|
||||
/// Analytics lineage of the action, which can come from an earlier turn.
|
||||
reviewed_action_root_turn_id: Option<String>,
|
||||
review_execution: Option<codex_direct_tool_timing::ReviewExecution>,
|
||||
environments: TurnEnvironmentSnapshot,
|
||||
project_instructions: Option<Arc<LoadedAgentsMd>>,
|
||||
@@ -147,8 +149,10 @@ impl GuardianReviewContext {
|
||||
turn: Arc<TurnContext>,
|
||||
settings: &ResolvedStepSettings,
|
||||
environments: &TurnEnvironmentSnapshot,
|
||||
reviewed_action_root_turn_id: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
reviewed_action_root_turn_id,
|
||||
request_country: settings.request_country().clone(),
|
||||
serving_assessment: None,
|
||||
guardian_probe: None,
|
||||
@@ -188,6 +192,7 @@ impl From<&Arc<StepContext>> for GuardianReviewContext {
|
||||
enclosing_invocation_id: None,
|
||||
parent_response: step.turn.extension_data.get::<ParentResponse>(),
|
||||
turn: Arc::clone(&step.turn),
|
||||
reviewed_action_root_turn_id: step.turn.turn_metadata_state.root_turn_id(),
|
||||
environments: step.environments.clone(),
|
||||
project_instructions: Some(step.loaded_agents_md.clone().unwrap_or_default()),
|
||||
model_info: Arc::clone(&step.settings.model_info),
|
||||
@@ -218,6 +223,7 @@ impl From<Arc<TurnContext>> for GuardianReviewContext {
|
||||
personality: turn.personality(),
|
||||
approval_policy: turn.approval_policy(),
|
||||
approvals_reviewer: turn.config.approvals_reviewer,
|
||||
reviewed_action_root_turn_id: turn.turn_metadata_state.root_turn_id(),
|
||||
turn,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,6 +177,12 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
||||
} = options;
|
||||
let target_item_id = guardian_request_target_item_id(&request).map(str::to_string);
|
||||
let assessment_turn_id = guardian_request_turn_id(&request, &turn.sub_id).to_string();
|
||||
// An explicit action turn outside this context has unknown lineage.
|
||||
let root_turn_id = if assessment_turn_id == turn.sub_id {
|
||||
context.reviewed_action_root_turn_id.clone()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let plugin_attribution = match plugin_attribution_override {
|
||||
Some(attribution) => Some(attribution),
|
||||
None if matches!(&request, GuardianApprovalRequest::ExecCommand { .. }) => {
|
||||
@@ -210,6 +216,7 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
||||
let metadata = codex_guardian_reviewer::ReviewMetadata {
|
||||
thread_id: session.thread_id.to_string(),
|
||||
turn_id: assessment_turn_id,
|
||||
root_turn_id,
|
||||
turn_trigger: turn.turn_metadata_state.current_turn_trigger(),
|
||||
review_id: review_id.to_owned(),
|
||||
target_item_id,
|
||||
|
||||
@@ -791,6 +791,7 @@ async fn guardian_mcp_uses_thread_permissions_for_an_unavailable_captured_enviro
|
||||
Arc::clone(&turn),
|
||||
&turn.initial_settings,
|
||||
&captured,
|
||||
/*reviewed_action_root_turn_id*/ None,
|
||||
);
|
||||
let collected = collect_guardian_prompt_items_with_parent_turn(
|
||||
&session,
|
||||
|
||||
@@ -1150,6 +1150,7 @@ async fn review_guardian_mcp_elicitation(
|
||||
Arc::clone(&turn_context),
|
||||
&step_settings,
|
||||
&turn_context.initial_environments,
|
||||
/*reviewed_action_root_turn_id*/ None,
|
||||
)
|
||||
});
|
||||
let review_config = &review_context.turn().config;
|
||||
|
||||
@@ -289,6 +289,7 @@ impl PendingHostApproval {
|
||||
struct ActiveNetworkApprovalCall {
|
||||
registration_id: String,
|
||||
turn_id: String,
|
||||
root_turn_id: Option<String>,
|
||||
trigger: GuardianNetworkAccessTrigger,
|
||||
tool_name: ToolName,
|
||||
command: String,
|
||||
@@ -307,6 +308,8 @@ enum ActiveNetworkApprovalAttribution {
|
||||
struct NetworkRequestAttribution {
|
||||
owner_call: Option<Arc<ActiveNetworkApprovalCall>>,
|
||||
environment_id: Option<String>,
|
||||
/// Only a verified execution tag establishes the action's root.
|
||||
reviewed_action_root_turn_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -600,6 +603,7 @@ impl NetworkApprovalService {
|
||||
.clone()
|
||||
.unwrap_or_else(|| call.environment_id.clone());
|
||||
return (call.environment_id == environment_id).then_some(NetworkRequestAttribution {
|
||||
reviewed_action_root_turn_id: call.root_turn_id.clone(),
|
||||
owner_call: Some(call),
|
||||
environment_id: Some(environment_id),
|
||||
});
|
||||
@@ -616,6 +620,7 @@ impl NetworkApprovalService {
|
||||
return Some(NetworkRequestAttribution {
|
||||
owner_call,
|
||||
environment_id: Some(environment_id),
|
||||
reviewed_action_root_turn_id: None,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -623,12 +628,14 @@ impl NetworkApprovalService {
|
||||
ActiveNetworkApprovalAttribution::None => Some(NetworkRequestAttribution {
|
||||
owner_call: None,
|
||||
environment_id: None,
|
||||
reviewed_action_root_turn_id: None,
|
||||
}),
|
||||
ActiveNetworkApprovalAttribution::Single(call) => {
|
||||
let environment_id = call.environment_id.clone();
|
||||
Some(NetworkRequestAttribution {
|
||||
owner_call: Some(call),
|
||||
environment_id: Some(environment_id),
|
||||
reviewed_action_root_turn_id: None,
|
||||
})
|
||||
}
|
||||
ActiveNetworkApprovalAttribution::Ambiguous => None,
|
||||
@@ -762,6 +769,7 @@ impl NetworkApprovalService {
|
||||
let Some(NetworkRequestAttribution {
|
||||
owner_call,
|
||||
environment_id: active_environment_id,
|
||||
reviewed_action_root_turn_id,
|
||||
}) = self.resolve_request_attribution(&request).await
|
||||
else {
|
||||
return NetworkDecision::deny(REASON_NOT_ALLOWED);
|
||||
@@ -847,6 +855,7 @@ impl NetworkApprovalService {
|
||||
Arc::clone(&turn_context),
|
||||
&settings,
|
||||
review_environments,
|
||||
reviewed_action_root_turn_id,
|
||||
);
|
||||
if !allows_network_approval_flow(review_context.approval_policy) {
|
||||
if let Some(owner_call) = owner_call.as_ref() {
|
||||
@@ -1277,6 +1286,7 @@ pub(crate) async fn begin_network_approval(
|
||||
.register_call(ActiveNetworkApprovalCall {
|
||||
registration_id: registration_id.clone(),
|
||||
turn_id: turn.sub_id.clone(),
|
||||
root_turn_id: turn.turn_metadata_state.root_turn_id(),
|
||||
trigger,
|
||||
tool_name,
|
||||
command,
|
||||
|
||||
@@ -800,6 +800,7 @@ async fn register_call_with_default_shell_trigger(
|
||||
let registration = service.register_call(ActiveNetworkApprovalCall {
|
||||
registration_id: registration_id.to_string(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
tool_name: ToolName::plain("exec_command"),
|
||||
trigger: GuardianNetworkAccessTrigger {
|
||||
call_id: registration_id.to_string(),
|
||||
@@ -838,6 +839,7 @@ async fn active_call_preserves_triggering_command_context() {
|
||||
let _registration = service.register_call(ActiveNetworkApprovalCall {
|
||||
registration_id: "registration-1".to_string(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
root_turn_id: Some("issuing-root".to_string()),
|
||||
trigger: expected.clone(),
|
||||
tool_name: tool_name.clone(),
|
||||
command: "curl https://example.com".to_string(),
|
||||
@@ -847,15 +849,48 @@ async fn active_call_preserves_triggering_command_context() {
|
||||
cancellation_token: CancellationToken::new(),
|
||||
});
|
||||
|
||||
let call = service
|
||||
.resolve_single_active_call()
|
||||
let request = NetworkPolicyRequest {
|
||||
protocol: NetworkProtocol::Http,
|
||||
host: "example.com".to_string(),
|
||||
port: 80,
|
||||
execution_id: Some("registration-1".to_string()),
|
||||
environment_id: Some("remote".to_string()),
|
||||
client_addr: None,
|
||||
method: None,
|
||||
command: None,
|
||||
exec_policy_hint: None,
|
||||
disconnect: None,
|
||||
cancellation: None,
|
||||
};
|
||||
let attributed = service
|
||||
.resolve_request_attribution(&request)
|
||||
.await
|
||||
.expect("single active call should resolve");
|
||||
.expect("tagged request should resolve");
|
||||
assert_eq!(
|
||||
attributed.reviewed_action_root_turn_id.as_deref(),
|
||||
Some("issuing-root")
|
||||
);
|
||||
let call = attributed.owner_call.expect("registered execution");
|
||||
|
||||
assert_eq!(&call.trigger, &expected);
|
||||
assert_eq!(call.tool_name, tool_name);
|
||||
assert_eq!(call.command, "curl https://example.com");
|
||||
assert_eq!(call.environment_id, "remote");
|
||||
|
||||
let untagged = service
|
||||
.resolve_request_attribution(&NetworkPolicyRequest {
|
||||
execution_id: None,
|
||||
..request
|
||||
})
|
||||
.await
|
||||
.expect("untagged request can use current settings");
|
||||
assert_eq!(
|
||||
(
|
||||
untagged.owner_call.is_some(),
|
||||
untagged.reviewed_action_root_turn_id
|
||||
),
|
||||
(true, None)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::AppServerRpcTransport;
|
||||
use codex_app_server_protocol as app;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_config::types::ApprovalsReviewer;
|
||||
use codex_core::EnvironmentConfig;
|
||||
@@ -19,6 +22,7 @@ use codex_extension_api::ToolLifecycleContributor;
|
||||
use codex_extension_api::ToolLifecycleFuture;
|
||||
use codex_features::Feature;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_login::CodexAuth;
|
||||
#[cfg(unix)]
|
||||
use codex_network_proxy::CredentialProviderConfig;
|
||||
#[cfg(unix)]
|
||||
@@ -66,6 +70,7 @@ use codex_protocol::protocol::TurnEnvironmentSelections;
|
||||
use codex_protocol::request_permissions::PermissionGrantScope;
|
||||
use codex_protocol::request_permissions::RequestPermissionProfile;
|
||||
use codex_protocol::request_permissions::RequestPermissionsResponse;
|
||||
use codex_protocol::turn_input::TurnStartOptions;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use codex_thread_store::LoadThreadHistoryParams;
|
||||
use core_test_support::PathBufExt;
|
||||
@@ -80,6 +85,7 @@ use core_test_support::responses::mount_response_once_match;
|
||||
use core_test_support::responses::mount_sse_once;
|
||||
use core_test_support::responses::mount_sse_once_match;
|
||||
use core_test_support::responses::mount_sse_sequence;
|
||||
use core_test_support::responses::received_analytics_events;
|
||||
use core_test_support::responses::sse;
|
||||
use core_test_support::responses::sse_response;
|
||||
use core_test_support::responses::start_mock_server;
|
||||
@@ -111,6 +117,10 @@ use tempfile::TempDir;
|
||||
use test_case::test_case;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use wiremock::Mock;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const NETWORK_TEST_HOST: &str = "codex-network-test.invalid";
|
||||
const NETWORK_TEST_TARGET: &str = "http://codex-network-test.invalid:80";
|
||||
@@ -847,16 +857,55 @@ async fn background_network_approval_uses_current_review_settings_and_original_e
|
||||
skip_if_sandbox!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/codex/analytics-events/events"))
|
||||
.respond_with(ResponseTemplate::new(/*status*/ 200))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let analytics = AnalyticsEventsClient::new(
|
||||
codex_core::test_support::auth_manager_from_auth(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
),
|
||||
server.uri(),
|
||||
/*analytics_enabled*/ Some(true),
|
||||
);
|
||||
let test = managed_network_unified_exec_builder(&[
|
||||
Feature::RequestPermissionsTool,
|
||||
Feature::StepModelSwitching,
|
||||
])?
|
||||
.with_analytics_events_client(analytics.clone())
|
||||
.with_model("guardian-parent-a")
|
||||
.with_config(|config| {
|
||||
config.model_catalog = Some(guardian_parent_catalog());
|
||||
})
|
||||
.build_with_remote_and_local_env(&server)
|
||||
.await?;
|
||||
let session = &test.session_configured;
|
||||
analytics.track_initialize(
|
||||
/*connection_id*/ 1,
|
||||
app::InitializeParams::default(),
|
||||
"test-client".to_string(),
|
||||
AppServerRpcTransport::Stdio,
|
||||
);
|
||||
let sandbox = test.codex.config_snapshot().await.sandbox_policy();
|
||||
let thread_response = serde_json::from_value(json!({
|
||||
"thread": {
|
||||
"id": session.thread_id, "sessionId": session.session_id, "preview": "",
|
||||
"ephemeral": false, "modelProvider": session.model_provider_id,
|
||||
"createdAt": 1, "updatedAt": 1, "status": {"type": "idle"},
|
||||
"cwd": session.cwd, "cliVersion": "0.0.0", "source": "exec", "turns": [],
|
||||
},
|
||||
"model": session.model, "modelProvider": session.model_provider_id, "cwd": session.cwd,
|
||||
"approvalPolicy": app::AskForApproval::from(session.approval_policy),
|
||||
"approvalsReviewer": app::ApprovalsReviewer::from(session.approvals_reviewer),
|
||||
"sandbox": app::SandboxPolicy::from(sandbox),
|
||||
}))?;
|
||||
analytics.track_response(
|
||||
/*connection_id*/ 1,
|
||||
app::RequestId::Integer(1),
|
||||
&app::ClientResponsePayload::ThreadStart(thread_response),
|
||||
);
|
||||
|
||||
let start_call_id = "cross-turn-network-start";
|
||||
let permission_call_id = "cross-turn-network-permissions";
|
||||
let stdin_call_id = "cross-turn-network-stdin";
|
||||
@@ -955,14 +1004,22 @@ async fn background_network_approval_uses_current_review_settings_and_original_e
|
||||
}
|
||||
let responses = mount_sse_sequence(&server, events).await;
|
||||
|
||||
submit_managed_network_turn(
|
||||
&test,
|
||||
"start a background terminal that waits before requesting network access",
|
||||
vec![local(test.config.cwd.clone())],
|
||||
ApprovalsReviewer::User,
|
||||
AskForApproval::OnRequest,
|
||||
)
|
||||
.await?;
|
||||
let issuing_root_turn_id = "issuing-root";
|
||||
test.codex
|
||||
.start_or_steer_turn(
|
||||
managed_network_turn_input(
|
||||
&test,
|
||||
"start a background terminal that waits before requesting network access",
|
||||
vec![local(test.config.cwd.clone())],
|
||||
ApprovalsReviewer::User,
|
||||
AskForApproval::OnRequest,
|
||||
)
|
||||
.on_start(TurnStartOptions {
|
||||
root_turn_id: Some(issuing_root_turn_id.to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let EventMsg::TurnStarted(first_turn) = wait_for_event(&test.codex, |event| {
|
||||
matches!(event, EventMsg::TurnStarted(_))
|
||||
})
|
||||
@@ -999,6 +1056,10 @@ async fn background_network_approval_uses_current_review_settings_and_original_e
|
||||
},
|
||||
}),
|
||||
..Default::default()
|
||||
})
|
||||
.on_start(TurnStartOptions {
|
||||
root_turn_id: Some("servicing-root".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
@@ -1065,6 +1126,17 @@ async fn background_network_approval_uses_current_review_settings_and_original_e
|
||||
};
|
||||
assert_eq!(assessment.turn_id, active_turn_id);
|
||||
wait_for_turn_complete(&test).await;
|
||||
tokio::time::timeout(Duration::from_secs(10), analytics.flush()).await?;
|
||||
let reviews = received_analytics_events(&server, "codex_guardian_review").await;
|
||||
let review = reviews
|
||||
.iter()
|
||||
.map(|event| &event["event_params"])
|
||||
.find(|params| params["review_id"] == assessment.id)
|
||||
.context("expected analytics for the terminal's network review")?;
|
||||
assert_eq!(
|
||||
(review["turn_id"].as_str(), review["root_turn_id"].as_str()),
|
||||
(Some(active_turn_id.as_str()), Some(issuing_root_turn_id)),
|
||||
);
|
||||
|
||||
let actions = guardian_network_actions(&responses)?;
|
||||
assert_eq!(actions.len(), 2);
|
||||
@@ -3572,6 +3644,25 @@ async fn submit_managed_network_turn(
|
||||
approvals_reviewer: ApprovalsReviewer,
|
||||
approval_policy: AskForApproval,
|
||||
) -> Result<()> {
|
||||
test.codex
|
||||
.start_or_steer_turn(managed_network_turn_input(
|
||||
test,
|
||||
prompt,
|
||||
environments,
|
||||
approvals_reviewer,
|
||||
approval_policy,
|
||||
))
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn managed_network_turn_input(
|
||||
test: &TestCodex,
|
||||
prompt: &str,
|
||||
environments: Vec<TurnEnvironmentSelection>,
|
||||
approvals_reviewer: ApprovalsReviewer,
|
||||
approval_policy: AskForApproval,
|
||||
) -> TurnInputRequest {
|
||||
let permission_profile = PermissionProfile::workspace_write_with(
|
||||
&[],
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
@@ -3583,32 +3674,26 @@ async fn submit_managed_network_turn(
|
||||
let turn_environment_selections =
|
||||
TurnEnvironmentSelections::new(test.config.cwd.clone(), environments);
|
||||
|
||||
test.codex
|
||||
.start_or_steer_turn(
|
||||
TurnInputRequest::user_input(vec![UserInput::Text {
|
||||
text: prompt.into(),
|
||||
text_elements: Vec::new(),
|
||||
}])
|
||||
.with_thread_settings(ThreadSettingsOverrides {
|
||||
environments: Some(turn_environment_selections.into_requests()),
|
||||
approval_policy: Some(approval_policy),
|
||||
approvals_reviewer: Some(approvals_reviewer),
|
||||
sandbox_policy: Some(sandbox_policy),
|
||||
permission_profile,
|
||||
collaboration_mode: Some(CollaborationMode {
|
||||
mode: ModeKind::Default,
|
||||
settings: Settings {
|
||||
model: test.session_configured.model.clone(),
|
||||
reasoning_effort: None,
|
||||
developer_instructions: None,
|
||||
},
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
TurnInputRequest::user_input(vec![UserInput::Text {
|
||||
text: prompt.into(),
|
||||
text_elements: Vec::new(),
|
||||
}])
|
||||
.with_thread_settings(ThreadSettingsOverrides {
|
||||
environments: Some(turn_environment_selections.into_requests()),
|
||||
approval_policy: Some(approval_policy),
|
||||
approvals_reviewer: Some(approvals_reviewer),
|
||||
sandbox_policy: Some(sandbox_policy),
|
||||
permission_profile,
|
||||
collaboration_mode: Some(CollaborationMode {
|
||||
mode: ModeKind::Default,
|
||||
settings: Settings {
|
||||
model: test.session_configured.model.clone(),
|
||||
reasoning_effort: None,
|
||||
developer_instructions: None,
|
||||
},
|
||||
}),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn decoded_request_body(request: &wiremock::Request) -> Option<Vec<u8>> {
|
||||
|
||||
Reference in New Issue
Block a user