aKode fase 2c: eliminato il codice di invio dati (crate analytics, otel-trace-websocket, sentry, esportatori OTLP); /feedback salva solo in locale; chiavi legacy [analytics]/[otel] accettate e ignorate; test di analytics/OTLP/upload rimossi
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled

This commit is contained in:
Andrea
2026-11-09 18:45:41 +01:00
parent 981745ccc8
commit 60532b6337
509 changed files with 2043 additions and 46606 deletions

View File

@@ -1,4 +1,3 @@
use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;
use std::sync::Arc;
@@ -67,9 +66,6 @@ use tokio::net::TcpListener;
use tokio::sync::Notify;
use tokio::time::timeout;
use super::analytics::captured_analytics_events;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_matching_analytics_event;
use super::mcp_tool::TEST_SERVER_NAME;
use super::mcp_tool::TEST_TOOL_NAME;
use super::mcp_tool::start_mcp_server;
@@ -190,10 +186,6 @@ struct MockResponsesState {
gate_each_guardian_review: bool,
gate_second_tool_on_classification: bool,
allow_second_tool: Notify,
classification_completed: Notify,
truncation_recorded: Notify,
context_metric_bounds: Mutex<BTreeMap<(String, String), Option<f64>>>,
context_metrics_recorded: Notify,
luna_score: f64,
invalid_classification: bool,
fail_after_classification: bool,
@@ -326,6 +318,52 @@ fn sync_review_fragments(request: &Value) -> Vec<&str> {
.collect()
}
async fn wait_for_luna_completions(state: &MockResponsesState, expected: usize) -> Result<()> {
timeout(TIMEOUT, async {
while state.luna_completions.load(Ordering::Relaxed) < expected {
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await?;
Ok(())
}
/// Waits until `expected` Guardian V2 classifications of `thread_id` have finished, using the
/// result or failure line each classification writes to the local feedback logs.
async fn wait_for_classification_logs(
codex_home: &TempDir,
thread_id: &str,
expected: usize,
) -> Result<()> {
let state_db = StateRuntime::init(
load_default_config_for_test(codex_home).await.sqlite,
"mock_provider".to_owned(),
)
.await?;
timeout(TIMEOUT, async {
loop {
let logs = String::from_utf8(
state_db
.query_feedback_logs_for_threads(&[thread_id])
.await?,
)?;
let finished = logs
.lines()
.filter(|line| {
line.contains("Guardian V2 classification result")
|| line.contains("Guardian V2 background scoring failed")
})
.count();
if finished >= expected {
return anyhow::Ok(());
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await??;
Ok(())
}
async fn wait_for_luna_request(state: &MockResponsesState, index: usize) -> Result<Value> {
Ok(timeout(TIMEOUT, async {
loop {
@@ -779,73 +817,6 @@ async fn guardian_v2_routes_scoped_tool_approvals(
let responses_url = format!("http://{}", listener.local_addr()?);
let router = Router::new()
.route("/v1/responses", get(luna_websocket).post(parent_response))
.route(
"/metrics",
post(
|State(state): State<Arc<MockResponsesState>>, body: String| async move {
if matches!(state.transcript_content, TranscriptContent::MixedEvidence) {
let payload: Value = serde_json::from_str(&body).expect("OTLP JSON");
for metric in payload["resourceMetrics"]
.as_array()
.into_iter()
.flatten()
.flat_map(|resource| {
resource["scopeMetrics"].as_array().into_iter().flatten()
})
.flat_map(|scope| scope["metrics"].as_array().into_iter().flatten())
.filter(|metric| {
matches!(
metric["name"].as_str(),
Some(
"codex.guardian.context.request_tokens"
| "codex.guardian.context.section_cost"
)
)
})
{
let name = metric["name"].as_str().expect("context metric name");
for point in metric["histogram"]["dataPoints"]
.as_array()
.into_iter()
.flatten()
{
let attributes =
point["attributes"].as_array().expect("metric attributes");
for target in ["sync", "async"] {
if attributes.iter().any(|attr| {
attr["key"] == "target"
&& attr["value"]["stringValue"] == target
}) {
let mut bounds = state
.context_metric_bounds
.lock()
.expect("context metric bounds");
bounds.insert(
(name.to_owned(), target.to_owned()),
point["explicitBounds"]
.as_array()
.and_then(|bounds| bounds.last())
.and_then(Value::as_f64),
);
if bounds.len() == 4 {
state.context_metrics_recorded.notify_one();
}
}
}
}
}
}
if body.contains("\"codex.guardian_v2.classification\"") {
state.classification_completed.notify_one();
}
if body.contains("codex.guardian_v2.classification.truncation")
&& body.contains("sync_review_action")
{
state.truncation_recorded.notify_one();
}
},
),
)
.with_state(Arc::clone(&responses_state));
let responses_server = tokio::spawn(async move {
let _ = axum::serve(listener, router).await;
@@ -853,8 +824,6 @@ async fn guardian_v2_routes_scoped_tool_approvals(
let (mcp_server_url, mcp_server_handle) = start_mcp_server(sensitive_action).await?;
let codex_home = TempDir::new()?;
let analytics_server = responses::start_mock_server().await;
mount_analytics_capture(&analytics_server, codex_home.path()).await?;
let mixed_evidence = matches!(transcript_content, TranscriptContent::MixedEvidence);
let root_skill = if matches!(lifecycle, ThreadLifecycle::RootTrustedSkill) || mixed_evidence {
let path = codex_home.path().join("skills/root-trusted/SKILL.md");
@@ -930,12 +899,9 @@ async fn guardian_v2_routes_scoped_tool_approvals(
.with_model(MODEL)
.with_provider_config("supports_websockets = false")
.with_approval_policy("on-request")
.with_root_config(&format!(
"{reviewer_config}\nchatgpt_base_url = \"{}\"",
analytics_server.uri(),
))
.with_root_config(reviewer_config)
.with_extra_config(&format!(
"[mcp_servers.{server_name}]\nurl = \"{mcp_server_url}/mcp\"\ndefault_tools_approval_mode = \"{tool_approval_mode}\"\n\n[analytics]\nenabled = true\n\n[otel]\nmetrics_exporter = {{ otlp-http = {{ endpoint = \"{responses_url}/metrics\", protocol = \"json\" }} }}\n\n[features.guardianv2]\nenabled = true{classifier_config}{guardian_scope_config}"
"[mcp_servers.{server_name}]\nurl = \"{mcp_server_url}/mcp\"\ndefault_tools_approval_mode = \"{tool_approval_mode}\"\n\n[features.guardianv2]\nenabled = true{classifier_config}{guardian_scope_config}"
))
.enable_feature(Feature::GuardianApproval);
if lifecycle.has_user_input() || lifecycle.has_root_user_input() {
@@ -1008,10 +974,7 @@ async fn guardian_v2_routes_scoped_tool_approvals(
.then(|| traces.path().to_str().expect("trace root path"));
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.with_env_overrides(&[
("OTEL_METRIC_EXPORT_INTERVAL", Some("25")),
("CODEX_ROLLOUT_TRACE_ROOT", trace_root),
])
.with_env_overrides(&[("CODEX_ROLLOUT_TRACE_ROOT", trace_root)])
.build_initialized_with_timeout(TIMEOUT)
.await?;
let thread = match lifecycle {
@@ -1244,7 +1207,13 @@ async fn guardian_v2_routes_scoped_tool_approvals(
.await??;
}
responses_state.allow_luna.notify_one();
timeout(TIMEOUT, responses_state.classification_completed.notified()).await?;
if late_root_restriction {
// A superseded classification leaves no observable trace, so only wait
// until the classifier response has been served.
wait_for_luna_completions(&responses_state, /*expected*/ 1).await?;
} else {
wait_for_classification_logs(&codex_home, &reviewed_thread_id, /*expected*/ 1).await?;
}
if late_root_restriction {
responses_state.allow_guardian_review.notify_one();
} else {
@@ -1700,26 +1669,6 @@ async fn guardian_v2_routes_scoped_tool_approvals(
assert!(text.contains("Planned action JSON:"));
}
}
if mixed_evidence {
timeout(TIMEOUT, responses_state.context_metrics_recorded.notified())
.await
.expect("sync and async request/section metrics should all be exported");
let bounds = responses_state
.context_metric_bounds
.lock()
.expect("context metric bounds");
for ((metric, target), bound) in bounds.iter() {
assert_eq!(
*bound,
Some(if metric == "codex.guardian.context.request_tokens" {
2_000_000.0
} else {
16_777_216.0
}),
"{metric} ({target}) must export its context metric buckets"
);
}
}
if lifecycle.has_user_answer() {
let reviews = responses_state
.guardian_requests
@@ -1793,7 +1742,7 @@ async fn guardian_v2_routes_scoped_tool_approvals(
"mock_provider".to_owned(),
)
.await?;
// Exercise the same log export used by feedback/upload, including async
// Exercise the same log export used by feedback/save, including async
// classifier events that cannot rely on inheriting a thread tracing span.
let logs = timeout(TIMEOUT, async {
loop {
@@ -1826,7 +1775,7 @@ async fn guardian_v2_routes_scoped_tool_approvals(
if matches!(lifecycle, ThreadLifecycle::RequiredModelSwitch) {
// Both MCP actions have low scores; the sandboxed exec must still receive full review.
timeout(TIMEOUT, responses_state.classification_completed.notified()).await?;
wait_for_classification_logs(&codex_home, &reviewed_thread_id, /*expected*/ 2).await?;
// Continue without new user input so authorization changes cannot invalidate the score.
// Only the required-model check should prevent cached approval of the sandboxed command.
let request_id = app_server
@@ -2051,26 +2000,10 @@ async fn guardian_v2_routes_scoped_tool_approvals(
responses_state.allow_luna.notify_one();
}
if matches!(review_outcome, ReviewOutcome::Deny) && !lifecycle.has_user_answer() {
timeout(TIMEOUT, responses_state.truncation_recorded.notified()).await?;
}
if matches!(lifecycle, ThreadLifecycle::New)
&& matches!(scope, GuardianToolScope::AllTools)
&& sensitive_action.is_none()
{
if classifier_in_scope {
wait_for_matching_analytics_event(&analytics_server, TIMEOUT, |event| {
event["event_type"] == "codex_guardian_v2_classification"
&& event["event_params"]["item_id"] == "guardian-action-0"
})
.await?;
}
let turn = wait_for_matching_analytics_event(&analytics_server, TIMEOUT, |event| {
event["event_type"] == "codex_turn_event"
&& event["event_params"]["thread_id"] == reviewed_thread_id
})
.await?;
timeout(TIMEOUT, app_server.shutdown_gracefully()).await??;
if matches!(review_outcome, ReviewOutcome::Deny) {
// Denied calls have no backend response, but their runtime result must
@@ -2135,58 +2068,6 @@ async fn guardian_v2_routes_scoped_tool_approvals(
None
),
);
let events = captured_analytics_events(&analytics_server).await;
let turn = &turn["event_params"];
assert_eq!(turn["guardian_v2_enabled"], classifier_in_scope);
let classification = events.iter().find(|event| {
event["event_type"] == "codex_guardian_v2_classification"
&& event["event_params"]["item_id"] == "guardian-action-0"
});
assert_eq!(classification.is_some(), classifier_in_scope);
if let Some(event) = classification {
assert_eq!(
json!([
event["event_params"]["outcome"],
event["event_params"]["risk_level"]
]),
match risk {
GuardianRisk::Low | GuardianRisk::LowWithStreamFailure =>
json!(["success", "low"]),
GuardianRisk::Threshold | GuardianRisk::High => json!(["success", "high"]),
GuardianRisk::InvalidResponse => json!(["failure", null]),
}
);
}
let approvals = events
.iter()
.filter(|event| event["event_type"] == "codex_guardian_v2_fast_decision")
.collect::<Vec<_>>();
assert_eq!(
approvals.len(),
usize::from(classifier_in_scope && matches!(risk, GuardianRisk::Low))
);
for event in classification.into_iter().chain(approvals) {
let params = &event["event_params"];
for key in [
"session_id",
"thread_id",
"turn_id",
"model",
"app_server_client",
"runtime",
"thread_source",
"subagent_source",
"parent_thread_id",
] {
assert_eq!(params[key], turn[key], "{key}");
}
if event["event_type"] == "codex_guardian_v2_fast_decision" {
assert_eq!(
json!([params["item_id"], params["decision"]]),
json!(["guardian-action-1", "approved"])
);
}
}
}
mcp_server_handle.abort();