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

@@ -182,7 +182,7 @@ async fn daemon_startup(command: &str) -> Result<()> {
format!(
"model = \"gpt-5.6-terra\"\n\
cli_auth_credentials_store = \"file\"\n\
suppress_unstable_features_warning = true\nanalytics.enabled = false\n\
suppress_unstable_features_warning = true\n\
windows.sandbox = \"unelevated\"\n\
tui.disable_paste_burst = true\n\
{}\n\

View File

@@ -1,77 +0,0 @@
//! Foreground updates honor explicit metrics exporters and never claim unconfirmed installation.
use anyhow::Context as _;
use pretty_assertions::assert_eq;
use serde_json::Value;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
#[tokio::test]
async fn foreground_update_honors_metrics_exporter_and_reports_unconfirmed() -> anyhow::Result<()> {
for (analytics_config, analytics_default_enabled, metrics_enabled) in [
("", false, true),
("", true, true),
("analytics.enabled = true\n", false, true),
("analytics.enabled = false\n", true, true),
("analytics.enabled = true\n", true, false),
] {
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
let server = MockServer::start().await;
Mock::given(wiremock::matchers::path("/metrics"))
.respond_with(ResponseTemplate::new(200))
.mount(&server)
.await;
let home = tempfile::tempdir()?;
std::fs::write(
home.path().join("config.toml"),
format!(
"cli_auth_credentials_store = \"file\"\n{analytics_config}[otel]\nmetrics_exporter = {{ otlp-http = {{ endpoint = \"{}/metrics\", protocol = \"json\" }} }}\n",
server.uri(),
),
)?;
// No managed installation exists, so the command cannot confirm an applied update.
let mut command = tokio::process::Command::new(&codex);
command
.current_dir(home.path())
.env("CODEX_HOME", home.path())
.env_remove(codex_app_server_daemon::telemetry::HANDOFF_ENV)
.arg("app-server");
if analytics_default_enabled {
command.arg("--analytics-default-enabled");
}
if !metrics_enabled {
command.args(["-c", "otel.metrics_exporter=\"none\""]);
}
let output = command
.args(["daemon", "update", "--from-cli", "--yes"])
.output()
.await?;
assert!(!output.status.success());
let requests = server
.received_requests()
.await
.context("metric requests")?;
assert_eq!(requests.len(), usize::from(metrics_enabled));
if !metrics_enabled {
continue;
}
let body: Value = serde_json::from_slice(&requests[0].body)?;
let metric = body["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())
.find(|metric| metric["name"] == "codex.daemon.update")
.context("daemon update metric")?;
assert!(
metric["sum"]["dataPoints"][0]["attributes"]
.as_array()
.context("metric attributes")?
.iter()
.any(|tag| tag["key"] == "outcome" && tag["value"]["stringValue"] == "unconfirmed")
);
}
Ok(())
}

View File

@@ -73,8 +73,6 @@ impl Fixture {
cli_auth_credentials_store = "file"
check_for_update_on_startup = false
model_provider = "local"
[analytics]
enabled = false
[model_providers.local]
name = "local test"
base_url = "http://127.0.0.1:9/v1"
@@ -621,7 +619,7 @@ async fn feedback_with_logs_does_not_execute_path_helpers() -> Result<()> {
let fixture = Fixture::new()?;
let proxy = TcpListener::bind("127.0.0.1:0").await?;
let proxy_uri = format!("http://{}", proxy.local_addr()?);
// Reject all outbound traffic locally, including the final feedback upload.
// Reject all outbound traffic locally; feedback collection must not need the network.
let proxy_task = tokio::spawn(async move {
while let Ok((stream, _)) = proxy.accept().await {
let mut stream = BufReader::new(stream);
@@ -664,20 +662,24 @@ async fn feedback_with_logs_does_not_execute_path_helpers() -> Result<()> {
])
.build_initialized_with_timeout(Duration::from_secs(/*secs*/ 30))
.await?;
// Feedback is only ever saved locally; collecting its diagnostics must not run PATH helpers.
let save_path = fixture.root.path().join("feedback.zip");
let request_id = app_server
.send_raw_request(
"feedback/upload",
"feedback/save",
Some(json!({
"classification": "bug", "includeLogs": true
"classification": "bug",
"includeLogs": true,
"savePath": save_path.to_string_lossy(),
})),
)
.await?;
let error = timeout(
timeout(
Duration::from_secs(/*secs*/ 45),
app_server.read_stream_until_error_message(RequestId::Integer(request_id)),
app_server.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
assert!(error.error.message.contains("failed to upload feedback"));
assert!(save_path.exists(), "feedback must be saved locally");
assert!(!fixture.marker.exists(), "feedback executed a PATH helper");
timeout(
Duration::from_secs(/*secs*/ 10),

View File

@@ -45,7 +45,6 @@ use predicates::str::contains;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::net::TcpListener;
@@ -457,12 +456,6 @@ async fn remote_exec_server_gracefully_stops_when_parent_stdin_closes() -> Resul
const EXECUTOR_REGISTRATION_ID: &str = "registration-parent-lifetime";
const TEST_TIMEOUT: Duration = Duration::from_secs(30);
let collector = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/metrics"))
.respond_with(ResponseTemplate::new(202))
.mount(&collector)
.await;
let listener = TcpListener::bind("127.0.0.1:0").await?;
let rendezvous_url = format!("ws://{}", listener.local_addr()?);
let registry = MockServer::start().await;
@@ -489,21 +482,9 @@ async fn remote_exec_server_gracefully_stops_when_parent_stdin_closes() -> Resul
.await;
let codex_home = TempDir::new()?;
let collector_url = collector.uri();
std::fs::write(
codex_home.path().join("config.toml"),
format!(
r#"
cli_auth_credentials_store = "file"
[analytics]
enabled = true
[otel]
environment = "test"
metrics_exporter = {{ otlp-http = {{ endpoint = "{collector_url}/v1/metrics", protocol = "json" }} }}
"#
),
"cli_auth_credentials_store = \"file\"\n",
)?;
let package = TempDir::new()?;
let bin_dir = package.path().join("bin");
@@ -685,29 +666,6 @@ metrics_exporter = {{ otlp-http = {{ endpoint = "{collector_url}/v1/metrics", pr
relay_task.abort();
let _ = relay_task.await;
let requests = collector
.received_requests()
.await
.ok_or_else(|| anyhow::anyhow!("failed to read OTLP collector requests"))?;
let metrics = requests
.iter()
.filter(|request| request.url.path() == "/v1/metrics")
.map(|request| serde_json::from_slice::<serde_json::Value>(&request.body))
.collect::<serde_json::Result<Vec<_>>>()?;
assert_metric_point(&metrics, "exec_server_processes_active", &[], Some(0));
assert_metric_point(
&metrics,
"exec_server_processes_finished_total",
&[("result", "terminated")],
Some(1),
);
assert_metric_point(
&metrics,
"exec_server_requests_total",
&[("method", "process/start"), ("result", "success")],
Some(1),
);
Ok(())
}
@@ -804,8 +762,6 @@ async fn remote_exec_server_scoped_credentials_authenticate_only_register_and_va
home.path().join("config.toml"),
format!(
r#"
[analytics]
enabled = true
[otel]
metrics_exporter = {{ otlp-http = {{ endpoint = "{}/v1/metrics", protocol = "json", headers = {{ Authorization = "general-telemetry-token" }} }} }}
"#,
@@ -1087,155 +1043,6 @@ async fn proxy_parent_lifetime_relay(
Ok(())
}
#[tokio::test]
async fn local_exec_server_flushes_telemetry_on_stdio_disconnect() -> Result<()> {
let collector = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/metrics"))
.respond_with(ResponseTemplate::new(202))
.mount(&collector)
.await;
let codex_home = TempDir::new()?;
let base_url = collector.uri();
std::fs::write(
codex_home.path().join("config.toml"),
format!(
r#"
[analytics]
enabled = true
[otel]
environment = "test"
metrics_exporter = {{ otlp-http = {{ endpoint = "{base_url}/v1/metrics", protocol = "json" }} }}
"#
),
)?;
let cwd = url::Url::from_directory_path(std::env::current_dir()?)
.map_err(|()| anyhow::anyhow!("could not convert cwd to file URL"))?;
#[cfg(windows)]
let argv = vec!["ping.exe", "-n", "61", "127.0.0.1"];
#[cfg(not(windows))]
let argv = vec!["/bin/sleep", "60"];
let codex_bin = codex_utils_cargo_bin::cargo_bin("codex")?;
let codex_home = codex_home.path().to_path_buf();
let subprocess = async move {
let mut command = tokio::process::Command::new(codex_bin);
command
.env("CODEX_HOME", codex_home)
.env("NO_PROXY", "127.0.0.1,localhost")
.env("no_proxy", "127.0.0.1,localhost")
.args(["exec-server", "--listen", "stdio"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.kill_on_drop(true);
let mut child = command.spawn()?;
let mut stdin = child
.stdin
.take()
.ok_or_else(|| anyhow::anyhow!("exec-server stdin was not piped"))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| anyhow::anyhow!("exec-server stdout was not piped"))?;
let mut stdout = BufReader::new(stdout);
send_json_line(
&mut stdin,
&serde_json::json!({
"id": 1,
"method": "initialize",
"params": {"clientName": "otel-test", "resumeSessionId": null}
}),
)
.await?;
wait_for_response(&mut stdout, /*expected_id*/ 1).await?;
send_json_line(
&mut stdin,
&serde_json::json!({"method": "initialized", "params": {}}),
)
.await?;
send_json_line(
&mut stdin,
&serde_json::json!({
"id": 2,
"method": "process/start",
"params": {
"processId": "otel-process",
"argv": argv,
"cwd": cwd,
"env": {},
"tty": false,
"pipeStdin": false,
"arg0": null
}
}),
)
.await?;
wait_for_response(&mut stdout, /*expected_id*/ 2).await?;
drop(stdin);
let mut remaining_stdout = String::new();
stdout.read_to_string(&mut remaining_stdout).await?;
let status = child.wait().await?;
anyhow::ensure!(
status.success(),
"exec-server exited with {status}; remaining stdout: {remaining_stdout}"
);
Ok::<(), anyhow::Error>(())
};
let subprocess_result = tokio::time::timeout(Duration::from_secs(30), subprocess)
.await
.map_err(|_| anyhow::anyhow!("exec-server subprocess timed out"))?;
subprocess_result?;
let requests = collector
.received_requests()
.await
.ok_or_else(|| anyhow::anyhow!("failed to read OTLP collector requests"))?;
let metrics = requests
.iter()
.filter(|request| request.url.path() == "/v1/metrics")
.map(|request| serde_json::from_slice::<serde_json::Value>(&request.body))
.collect::<serde_json::Result<Vec<_>>>()?;
assert_metric_point(
&metrics,
"exec_server_connections_active",
&[("transport", "stdio")],
Some(0),
);
assert_metric_point(
&metrics,
"exec_server_connections_total",
&[("transport", "stdio")],
Some(1),
);
assert_metric_point(
&metrics,
"exec_server_requests_total",
&[("method", "process/start"), ("result", "success")],
Some(1),
);
assert_metric_point(&metrics, "exec_server_processes_active", &[], Some(0));
assert_metric_point(
&metrics,
"exec_server_processes_finished_total",
&[("result", "terminated")],
Some(1),
);
assert_metric_point(
&metrics,
"exec_server_request_duration_seconds",
&[("method", "process/start"), ("result", "success")],
/*value*/ None,
);
assert_metric_point(
&metrics,
"exec_server_process_duration_seconds",
&[("result", "terminated")],
/*value*/ None,
);
Ok(())
}
async fn send_json_line(
stdin: &mut (impl tokio::io::AsyncWrite + Unpin),
message: &serde_json::Value,
@@ -1314,45 +1121,3 @@ async fn wait_for_response(
}
}
}
fn assert_metric_point(
payloads: &[serde_json::Value],
name: &str,
attributes: &[(&str, &str)],
value: Option<i64>,
) {
let found = payloads
.iter()
.flat_map(|payload| 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| metric["name"].as_str() == Some(name))
.flat_map(|metric| {
["gauge", "sum", "histogram"]
.into_iter()
.find_map(|kind| metric[kind]["dataPoints"].as_array())
.into_iter()
.flatten()
})
.any(|point| {
let actual_attributes = point["attributes"]
.as_array()
.map(Vec::as_slice)
.unwrap_or_default();
let attributes_match = actual_attributes.len() == attributes.len()
&& attributes.iter().all(|(expected_key, expected_value)| {
actual_attributes.iter().any(|actual| {
actual["key"].as_str() == Some(*expected_key)
&& actual["value"]["stringValue"].as_str() == Some(*expected_value)
})
});
let actual_value = point["asInt"]
.as_i64()
.or_else(|| point["asInt"].as_str()?.parse().ok());
attributes_match && value.is_none_or(|expected| actual_value == Some(expected))
});
assert!(
found,
"metric {name} with attributes {attributes:?} and value {value:?} missing"
);
}

View File

@@ -194,7 +194,7 @@ fn queue_rejects_unsupported_options() -> Result<()> {
"`--dangerously-bypass-hook-trust`",
),
(
"-c model=other queue -c analytics.enabled=false",
"-c model=other queue -c check_for_update_on_startup=false",
"`model` config override",
),
("queue -s read-only", "`--sandbox`"),
@@ -307,7 +307,7 @@ async fn remote_session_commands_with_workload_identity_use_server_auth() -> Res
.mount_as_scoped(&model)
.await;
MockResponsesConfig::new(&model.uri())
.with_root_config("features.plugins = false\nanalytics.enabled = false")
.with_root_config("features.plugins = false")
.with_provider_config("env_key = \"CODEX_QUEUE_SERVER_API_KEY\"")
.write(codex_home.path())?;
let _server = TestAppServer::builder()
@@ -685,7 +685,7 @@ async fn queue_rejects_overrides_that_bypass_local_daemon() -> Result<()> {
"-C",
".",
"-c",
"analytics.enabled=false",
"check_for_update_on_startup=false",
"--thread",
THREAD_ID,
"--message",

View File

@@ -9,7 +9,6 @@ use std::io::Write as _;
use std::path::Path;
use std::process::Command;
use std::time::Duration;
use std::time::Instant;
#[cfg(not(unix))]
use tempfile::TempDir;
use wiremock::Mock;
@@ -176,7 +175,7 @@ async fn worktree_start_and_fork(backend: &str) -> anyhow::Result<()> {
fs::create_dir(source.join(".codex"))?;
fs::write(
source.join(".codex/config.toml"),
"model = \"destination-model\"\nanalytics.enabled = false\ncli_auth_credentials_store = \"file\"\n",
"model = \"destination-model\"\ncli_auth_credentials_store = \"file\"\n",
)?;
git(&source, &["init", "--quiet"])?;
git(&source, &["add", "."])?;
@@ -190,7 +189,6 @@ async fn worktree_start_and_fork(backend: &str) -> anyhow::Result<()> {
r#"
cli_auth_credentials_store = "file"
chatgpt_base_url = "{}/source/backend-api"
analytics.enabled = false
check_for_update_on_startup = false
features.daemon_auto_start = {}
features.mcp_oauth_refresh_coordination = true
@@ -223,7 +221,7 @@ trust_level = "trusted"
)?;
fs::write(
source.join(".codex/config.toml"),
"model = \"source-model\"\nanalytics.enabled = true\n",
"model = \"source-model\"\n",
)?;
app_test_support::write_chatgpt_auth(
&home,
@@ -253,11 +251,6 @@ trust_level = "trusted"
env.insert("no_proxy".into(), "127.0.0.1,localhost".into());
env.insert("TERM".into(), "xterm-256color".into());
env.insert("TERM_PROGRAM".into(), "unrecognized-terminal".into());
env.insert("OTEL_METRIC_EXPORT_INTERVAL".into(), "100".into());
env.insert(
"OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE".into(),
"delta".into(),
);
for key in [
"CODEX_EXEC_SERVER_URL",
"CODEX_ACCESS_TOKEN",
@@ -313,12 +306,11 @@ trust_level = "trusted"
let mut owner = None;
let mut previous: Vec<String> = Vec::new();
let prompt = "describe checkout";
for (fork, explicit_cd, analytics, auth_failure) in [
(false, false, false, false),
(true, false, false, false),
(true, true, false, false),
(false, false, true, false),
(false, false, false, true),
for (fork, explicit_cd, auth_failure) in [
(false, false, false),
(true, false, false),
(true, true, false),
(false, false, true),
] {
if auth_failure {
fs::write(
@@ -337,12 +329,8 @@ trust_level = "trusted"
)?;
fs::write(source.join(".codex/config.toml"), "")?;
}
let (metric_tx, mut metric_rx) = tokio::sync::mpsc::unbounded_channel();
Mock::given(wiremock::matchers::path("/metrics"))
.respond_with(move |request: &wiremock::Request| {
let _ = metric_tx.send(request.body.clone());
ResponseTemplate::new(200).set_body_json(serde_json::json!({}))
})
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
.mount(&server)
.await;
Mock::given(wiremock::matchers::method("GET"))
@@ -410,18 +398,6 @@ trust_level = "trusted"
if explicit_cd {
args.extend(["--cd".into(), source.join(".codex").display().to_string()]);
}
if analytics {
args.extend([
"-c".into(),
// An explicit collector is independent of built-in analytics consent.
"analytics.enabled=false".into(),
"-c".into(),
format!(
"otel.metrics_exporter={{otlp-http={{endpoint=\"{}/metrics\",protocol=\"json\"}}}}",
server.uri()
),
]);
}
args.push(prompt.into());
if previous.is_empty() {
let mut untrusted_args = args.clone();
@@ -536,7 +512,7 @@ trust_level = "trusted"
} else {
Ok(())
};
if backend == "daemon" && !analytics && matches!(observed, Ok(Ok(_))) {
if backend == "daemon" && matches!(observed, Ok(Ok(_))) {
session.writer_sender().send(b"/status\r".to_vec()).await?;
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), async {
while !output.contains("Local background server") {
@@ -555,46 +531,6 @@ trust_level = "trusted"
.await
.with_context(|| format!("daemon status timed out: {output}"))??;
}
if analytics {
for reason in ["turn_start", "resize"] {
let started = Instant::now();
let wait = if reason == "resize" {
session.resize(codex_utils_pty::TerminalSize {
rows: 80,
cols: 240,
})?;
Duration::from_secs(/*secs*/ 30)
} else {
Duration::from_secs(/*secs*/ 10)
};
tokio::time::timeout(wait, async {
loop {
tokio::select! {
body = metric_rx.recv() => {
let payload: Value = serde_json::from_slice(&body.context("metric body")?)?;
let found = 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| metric["name"] == "codex.tui.terminal_size")
.flat_map(|metric| metric["sum"]["dataPoints"].as_array().into_iter().flatten())
.any(|point| point["attributes"].as_array().into_iter().flatten().any(|attribute|
attribute["key"] == "observation_reason" && attribute["value"]["stringValue"] == reason));
if found { return Ok::<_, anyhow::Error>(()); }
}
bytes = stdout.recv() => {
let bytes = bytes.context("TUI exited before size observation")?;
output.push_str(&String::from_utf8_lossy(&bytes));
let replies = queries.feed(&bytes);
if !replies.is_empty() { session.writer_sender().send(replies).await?; }
}
}
}
}).await.with_context(|| format!("waiting for {reason} observation"))??;
if reason == "resize" {
assert!(started.elapsed() >= Duration::from_secs(/*secs*/ 15));
}
}
}
let startup_result = observed.as_ref().map(|result| result.as_ref().map(|_| ()));
assert!(
!output.contains("Under-development features enabled:"),
@@ -656,110 +592,7 @@ trust_level = "trusted"
.filter(|request| request.url.path() == "/metrics")
.map(|request| serde_json::from_slice::<Value>(&request.body))
.collect::<serde_json::Result<Vec<_>>>()?;
if analytics {
let exported = metrics
.iter()
.flat_map(|payload| 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())
.collect::<Vec<_>>();
if backend == "embedded" {
let update = exported
.iter()
.find(|metric| metric["name"] == "codex.daemon.update")
.context("handoff metric")?;
let update_point = &update["sum"]["dataPoints"][0];
assert_eq!(update_point["asInt"], 1);
}
let point = exported
.iter()
.filter(|metric| metric["name"] == "codex.tui.start")
.flat_map(|metric| metric["sum"]["dataPoints"].as_array().into_iter().flatten())
.next()
.context("codex.tui.start data point")?;
assert_eq!(point["asInt"], 1);
let tags = point["attributes"]
.as_array()
.context("codex.tui.start attributes")?
.iter()
.map(|attribute| {
Ok((
attribute["key"].as_str().context("metric tag key")?,
attribute["value"]["stringValue"]
.as_str()
.context("metric tag value")?,
))
})
.collect::<anyhow::Result<HashMap<_, _>>>()?;
let mut expected_tags = HashMap::from([
("app_server_mode", "in_process"),
("terminal_name", "unknown"),
("terminal_columns", "120-239"),
("terminal_rows", "40-79"),
("multiplexer", "none"),
("daemon_selection_reason", "incompatible_option"),
(
"daemon_auto_start",
if backend == "daemon" {
"enabled"
} else {
"disabled"
},
),
("auto_update", "enabled"),
("auto_update_setting", "default"),
("update_interval_setting", "default"),
("shutdown_grace_setting", "default"),
]);
#[cfg(windows)]
if codex_app_server_daemon::is_elevated()? {
expected_tags.insert("daemon_selection_reason", "elevated_windows");
}
if backend == "daemon" {
expected_tags.extend([
("auto_update", "disabled"),
("auto_update_setting", "configured"),
("shutdown_grace_setting", "configured"),
]);
}
assert_eq!(tags, expected_tags);
let observations = exported
.iter()
.filter(|metric| metric["name"] == "codex.tui.terminal_size")
.flat_map(|metric| metric["sum"]["dataPoints"].as_array().into_iter().flatten())
.collect::<Vec<_>>();
assert_eq!(observations.len(), 2);
for observation in observations {
assert_eq!(observation["asInt"], 1);
let observation_tags = observation["attributes"]
.as_array()
.context("observation attributes")?
.iter()
.map(|attribute| {
Ok((
attribute["key"].as_str().context("observation key")?,
attribute["value"]["stringValue"]
.as_str()
.context("observation value")?,
))
})
.collect::<anyhow::Result<HashMap<_, _>>>()?;
let reason = observation_tags["observation_reason"];
let mut expected = expected_tags.clone();
expected.insert("observation_reason", reason);
match reason {
"turn_start" => {}
"resize" => {
expected.insert("terminal_columns", "240-479");
expected.insert("terminal_rows", "80-119");
}
other => anyhow::bail!("unexpected observation: {other}"),
}
assert_eq!(observation_tags, expected);
}
} else {
assert!(metrics.is_empty(), "metrics exporter disabled");
}
assert!(metrics.is_empty(), "no telemetry may be exported");
let (body, checkout, metadata) = observed
.with_context(|| {
format!(