Skip to content

Commit 2dec46e

Browse files
[codex] Record exec-server lifecycle metrics (#27467)
## Summary - Record bounded connection, request, and process lifecycle metrics. - Report active gauges from callbacks on every collection, including delta exports. - Serialize active-count updates so concurrent starts and finishes cannot publish stale values. - Serialize process exit, explicit termination, and shutdown through the process registry so exactly one completion result wins. - Keep the implementation small with single-owner RAII guards and one real OTLP/HTTP integration test using the existing `wiremock` dependency. ## Root cause Process exit and session shutdown previously used cloned completion state. That avoided duplicate emission, but it duplicated lifecycle ownership and made the ordering harder to reason about. The process registry mutex already defines the lifecycle ordering, so the final implementation stores the metric guard and termination flag directly on the process entry. Whichever path claims the entry first owns the completion result. Production metric export uses delta temporality. Event-only synchronous gauge recordings disappear after the next collection when no count changes, so active counts now use observable callbacks that report current state on every collection. The cleanup also removes the constant `result="accepted"` connection tag, redundant route and response assertions, a custom HTTP collector, and fallback initialization machinery that did not add behavior. ## Stack Review and land this stack in order: 1. #27466 — trace exec-server JSON-RPC requests 2. #27467 — record bounded connection, request, and process lifecycle metrics **(this PR)** 3. #27470 — observe remote registration and Noise rendezvous lifecycle ## Validation - `just test -p codex-exec-server --lib` (158 passed) - `just test -p codex-cli --test exec_server` (3 passed) - `just test -p codex-otel observable_gauge_is_collected_on_every_delta_snapshot` (1 passed) - `CARGO_BUILD_JOBS=1 just fix -p codex-otel -p codex-exec-server` - `just fmt` - `git diff --check`
1 parent 8f02973 commit 2dec46e

18 files changed

Lines changed: 924 additions & 57 deletions

File tree

codex-rs/cli/src/exec_server_telemetry.rs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ const OTEL_SERVICE_NAME: &str = "codex-exec-server";
77

88
pub(crate) fn init(
99
config: Option<&codex_core::config::Config>,
10-
) -> Result<impl Send + Sync, Box<dyn std::error::Error>> {
10+
) -> (impl Send + Sync, codex_exec_server::ExecServerTelemetry) {
1111
let fmt_layer = tracing_subscriber::fmt::layer()
1212
.with_writer(std::io::stderr)
1313
.with_filter(stderr_env_filter());
@@ -17,21 +17,30 @@ pub(crate) fn init(
1717
env!("CARGO_PKG_VERSION"),
1818
Some(OTEL_SERVICE_NAME),
1919
DEFAULT_ANALYTICS_ENABLED,
20-
),
21-
None => Ok(None),
20+
)
21+
.unwrap_or_else(|error| {
22+
eprintln!("Could not create otel exporter: {error}");
23+
None
24+
}),
25+
None => None,
2226
};
23-
let provider = otel.as_ref().ok().and_then(Option::as_ref);
27+
let provider = otel.as_ref();
2428
codex_core::otel_init::record_process_start(provider, OTEL_SERVICE_NAME);
2529

2630
let otel_logger_layer = provider.and_then(|otel| otel.logger_layer());
2731
let otel_tracing_layer = provider.and_then(|otel| otel.tracing_layer());
32+
let telemetry = provider
33+
.and_then(|otel| otel.metrics())
34+
.cloned()
35+
.map(codex_exec_server::ExecServerTelemetry::new)
36+
.unwrap_or_default();
2837
let _ = tracing_subscriber::registry()
2938
.with(fmt_layer)
3039
.with(otel_tracing_layer)
3140
.with(otel_logger_layer)
3241
.try_init();
3342
tracing::callsite::rebuild_interest_cache();
34-
otel
43+
(otel, telemetry)
3544
}
3645

3746
fn stderr_env_filter() -> EnvFilter {

codex-rs/cli/src/main.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1693,9 +1693,7 @@ async fn run_exec_server_command(
16931693
.environment_id
16941694
.ok_or_else(|| anyhow::anyhow!("--environment-id is required when --remote is set"))?;
16951695
let config = load_exec_server_config(root_config_overrides, strict_config).await?;
1696-
let _otel = exec_server_telemetry::init(Some(&config))
1697-
.inspect_err(|err| eprintln!("Could not create otel exporter: {err}"))
1698-
.ok();
1696+
let (_otel, telemetry) = exec_server_telemetry::init(Some(&config));
16991697
let auth_provider =
17001698
load_exec_server_remote_auth_provider(&config, &base_url, cmd.use_agent_identity_auth)
17011699
.await?;
@@ -1707,6 +1705,7 @@ async fn run_exec_server_command(
17071705
if let Some(name) = cmd.name {
17081706
remote_config.name = name;
17091707
}
1708+
let remote_config = remote_config.with_telemetry(telemetry);
17101709
codex_exec_server::run_remote_environment(remote_config, runtime_paths).await?;
17111710
Ok(())
17121711
} else {
@@ -1716,14 +1715,12 @@ async fn run_exec_server_command(
17161715
} else {
17171716
config_result.ok()
17181717
};
1719-
let _otel = exec_server_telemetry::init(config.as_ref())
1720-
.inspect_err(|err| eprintln!("Could not create otel exporter: {err}"))
1721-
.ok();
1718+
let (_otel, telemetry) = exec_server_telemetry::init(config.as_ref());
17221719
let listen_url = cmd
17231720
.listen
17241721
.as_deref()
17251722
.unwrap_or(codex_exec_server::DEFAULT_LISTEN_URL);
1726-
codex_exec_server::run_main(listen_url, runtime_paths)
1723+
codex_exec_server::run_main_with_telemetry(listen_url, runtime_paths, telemetry)
17271724
.await
17281725
.map_err(anyhow::Error::from_boxed)
17291726
}

codex-rs/cli/tests/exec_server.rs

Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,20 @@
11
use std::path::Path;
2+
use std::process::Stdio;
3+
use std::time::Duration;
24

35
use anyhow::Result;
46
use predicates::prelude::PredicateBooleanExt;
57
use predicates::str::contains;
68
use tempfile::TempDir;
9+
use tokio::io::AsyncBufReadExt;
10+
use tokio::io::AsyncReadExt;
11+
use tokio::io::AsyncWriteExt;
12+
use tokio::io::BufReader;
13+
use wiremock::Mock;
14+
use wiremock::MockServer;
15+
use wiremock::ResponseTemplate;
16+
use wiremock::matchers::method;
17+
use wiremock::matchers::path;
718

819
fn codex_command(codex_home: &Path) -> Result<assert_cmd::Command> {
920
let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?);
@@ -48,3 +59,225 @@ fn local_exec_server_ignores_invalid_config_without_strict_config() -> Result<()
4859

4960
Ok(())
5061
}
62+
63+
#[tokio::test]
64+
async fn local_exec_server_flushes_telemetry_on_stdio_disconnect() -> Result<()> {
65+
let collector = MockServer::start().await;
66+
Mock::given(method("POST"))
67+
.and(path("/v1/metrics"))
68+
.respond_with(ResponseTemplate::new(202))
69+
.mount(&collector)
70+
.await;
71+
let codex_home = TempDir::new()?;
72+
let base_url = collector.uri();
73+
std::fs::write(
74+
codex_home.path().join("config.toml"),
75+
format!(
76+
r#"
77+
[analytics]
78+
enabled = true
79+
80+
[otel]
81+
environment = "test"
82+
metrics_exporter = {{ otlp-http = {{ endpoint = "{base_url}/v1/metrics", protocol = "json" }} }}
83+
"#
84+
),
85+
)?;
86+
87+
let cwd = url::Url::from_directory_path(std::env::current_dir()?)
88+
.map_err(|()| anyhow::anyhow!("could not convert cwd to file URL"))?;
89+
#[cfg(windows)]
90+
let argv = vec!["ping.exe", "-n", "61", "127.0.0.1"];
91+
#[cfg(not(windows))]
92+
let argv = vec!["/bin/sleep", "60"];
93+
let codex_bin = codex_utils_cargo_bin::cargo_bin("codex")?;
94+
let codex_home = codex_home.path().to_path_buf();
95+
let subprocess = async move {
96+
let mut command = tokio::process::Command::new(codex_bin);
97+
command
98+
.env("CODEX_HOME", codex_home)
99+
.env("NO_PROXY", "127.0.0.1,localhost")
100+
.env("no_proxy", "127.0.0.1,localhost")
101+
.args(["exec-server", "--listen", "stdio"])
102+
.stdin(Stdio::piped())
103+
.stdout(Stdio::piped())
104+
.kill_on_drop(true);
105+
let mut child = command.spawn()?;
106+
let mut stdin = child
107+
.stdin
108+
.take()
109+
.ok_or_else(|| anyhow::anyhow!("exec-server stdin was not piped"))?;
110+
let stdout = child
111+
.stdout
112+
.take()
113+
.ok_or_else(|| anyhow::anyhow!("exec-server stdout was not piped"))?;
114+
let mut stdout = BufReader::new(stdout);
115+
send_json_line(
116+
&mut stdin,
117+
&serde_json::json!({
118+
"id": 1,
119+
"method": "initialize",
120+
"params": {"clientName": "otel-test", "resumeSessionId": null}
121+
}),
122+
)
123+
.await?;
124+
wait_for_response(&mut stdout, /*expected_id*/ 1).await?;
125+
send_json_line(
126+
&mut stdin,
127+
&serde_json::json!({"method": "initialized", "params": {}}),
128+
)
129+
.await?;
130+
send_json_line(
131+
&mut stdin,
132+
&serde_json::json!({
133+
"id": 2,
134+
"method": "process/start",
135+
"params": {
136+
"processId": "otel-process",
137+
"argv": argv,
138+
"cwd": cwd,
139+
"env": {},
140+
"tty": false,
141+
"pipeStdin": false,
142+
"arg0": null
143+
}
144+
}),
145+
)
146+
.await?;
147+
wait_for_response(&mut stdout, /*expected_id*/ 2).await?;
148+
drop(stdin);
149+
let mut remaining_stdout = String::new();
150+
stdout.read_to_string(&mut remaining_stdout).await?;
151+
let status = child.wait().await?;
152+
anyhow::ensure!(
153+
status.success(),
154+
"exec-server exited with {status}; remaining stdout: {remaining_stdout}"
155+
);
156+
Ok::<(), anyhow::Error>(())
157+
};
158+
let subprocess_result = tokio::time::timeout(Duration::from_secs(30), subprocess)
159+
.await
160+
.map_err(|_| anyhow::anyhow!("exec-server subprocess timed out"))?;
161+
subprocess_result?;
162+
163+
let requests = collector
164+
.received_requests()
165+
.await
166+
.ok_or_else(|| anyhow::anyhow!("failed to read OTLP collector requests"))?;
167+
let metrics = requests
168+
.iter()
169+
.filter(|request| request.url.path() == "/v1/metrics")
170+
.map(|request| serde_json::from_slice::<serde_json::Value>(&request.body))
171+
.collect::<serde_json::Result<Vec<_>>>()?;
172+
assert_metric_point(
173+
&metrics,
174+
"exec_server_connections_active",
175+
&[("transport", "stdio")],
176+
Some(0),
177+
);
178+
assert_metric_point(
179+
&metrics,
180+
"exec_server_connections_total",
181+
&[("transport", "stdio")],
182+
Some(1),
183+
);
184+
assert_metric_point(
185+
&metrics,
186+
"exec_server_requests_total",
187+
&[("method", "process/start"), ("result", "success")],
188+
Some(1),
189+
);
190+
assert_metric_point(&metrics, "exec_server_processes_active", &[], Some(0));
191+
assert_metric_point(
192+
&metrics,
193+
"exec_server_processes_finished_total",
194+
&[("result", "terminated")],
195+
Some(1),
196+
);
197+
assert_metric_point(
198+
&metrics,
199+
"exec_server_request_duration_seconds",
200+
&[("method", "process/start"), ("result", "success")],
201+
/*value*/ None,
202+
);
203+
assert_metric_point(
204+
&metrics,
205+
"exec_server_process_duration_seconds",
206+
&[("result", "terminated")],
207+
/*value*/ None,
208+
);
209+
Ok(())
210+
}
211+
212+
async fn send_json_line(
213+
stdin: &mut (impl tokio::io::AsyncWrite + Unpin),
214+
message: &serde_json::Value,
215+
) -> Result<()> {
216+
let mut encoded = serde_json::to_vec(message)?;
217+
encoded.push(b'\n');
218+
stdin.write_all(&encoded).await?;
219+
stdin.flush().await?;
220+
Ok(())
221+
}
222+
223+
async fn wait_for_response(
224+
stdout: &mut (impl tokio::io::AsyncBufRead + Unpin),
225+
expected_id: i64,
226+
) -> Result<()> {
227+
loop {
228+
let mut line = String::new();
229+
if stdout.read_line(&mut line).await? == 0 {
230+
anyhow::bail!("exec-server stdout closed before response {expected_id}");
231+
}
232+
let message: serde_json::Value = serde_json::from_str(&line)?;
233+
if message["id"].as_i64() == Some(expected_id) {
234+
anyhow::ensure!(
235+
message.get("error").is_none(),
236+
"exec-server request {expected_id} failed: {message}"
237+
);
238+
return Ok(());
239+
}
240+
}
241+
}
242+
243+
fn assert_metric_point(
244+
payloads: &[serde_json::Value],
245+
name: &str,
246+
attributes: &[(&str, &str)],
247+
value: Option<i64>,
248+
) {
249+
let found = payloads
250+
.iter()
251+
.flat_map(|payload| payload["resourceMetrics"].as_array().into_iter().flatten())
252+
.flat_map(|resource| resource["scopeMetrics"].as_array().into_iter().flatten())
253+
.flat_map(|scope| scope["metrics"].as_array().into_iter().flatten())
254+
.filter(|metric| metric["name"].as_str() == Some(name))
255+
.flat_map(|metric| {
256+
["gauge", "sum", "histogram"]
257+
.into_iter()
258+
.find_map(|kind| metric[kind]["dataPoints"].as_array())
259+
.into_iter()
260+
.flatten()
261+
})
262+
.any(|point| {
263+
let actual_attributes = point["attributes"]
264+
.as_array()
265+
.map(Vec::as_slice)
266+
.unwrap_or_default();
267+
let attributes_match = actual_attributes.len() == attributes.len()
268+
&& attributes.iter().all(|(expected_key, expected_value)| {
269+
actual_attributes.iter().any(|actual| {
270+
actual["key"].as_str() == Some(*expected_key)
271+
&& actual["value"]["stringValue"].as_str() == Some(*expected_value)
272+
})
273+
});
274+
let actual_value = point["asInt"]
275+
.as_i64()
276+
.or_else(|| point["asInt"].as_str()?.parse().ok());
277+
attributes_match && value.is_none_or(|expected| actual_value == Some(expected))
278+
});
279+
assert!(
280+
found,
281+
"metric {name} with attributes {attributes:?} and value {value:?} missing"
282+
);
283+
}

codex-rs/exec-server/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ mod rpc;
2727
mod runtime_paths;
2828
mod sandboxed_file_system;
2929
mod server;
30+
mod telemetry;
3031

3132
use codex_exec_server_protocol as protocol;
3233

@@ -149,3 +150,5 @@ pub use runtime_paths::ExecServerRuntimePaths;
149150
pub use server::DEFAULT_LISTEN_URL;
150151
pub use server::ExecServerListenUrlParseError;
151152
pub use server::run_main;
153+
pub use server::run_main_with_telemetry;
154+
pub use telemetry::ExecServerTelemetry;

0 commit comments

Comments
 (0)